From 83a88c033c64b276ffa73bddd281c35600da0a38 Mon Sep 17 00:00:00 2001 From: "kyle.huang" <324400663+KyleHuangFromHZ@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:38:30 +0800 Subject: [PATCH] =?UTF-8?q?feat(hardware):=20=E4=BC=98=E5=8C=96=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E5=88=97=E8=A1=A8=E3=80=81=E5=8D=8F=E8=AE=AE=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=92=8C=E5=9B=BA=E4=BB=B6=E5=8D=87=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CONTEXT.md | 11 + .../model/dto/DeviceProtocolVersionDto.java | 3 + .../model/dto/OfflineDeviceClearDto.java | 11 + .../model/dto/OfflineDeviceClearResult.java | 5 + .../com/opentest/core/jni/AudioJNIBridge.java | 2 + .../controller/CppHttpController.java | 8 + .../opentest/controller/DeviceController.java | 17 ++ .../opentest/service/CppHttpProxyService.java | 17 ++ .../service/DeviceProtocolVersionService.java | 58 ++++ .../com/opentest/service/DeviceService.java | 35 +++ .../deviceplugin/DevicePluginManagement.java | 10 + .../service/jni/AudioJNIBridgeService.java | 35 ++- .../service/jni/CaptureInputResources.java | 4 + .../service/jni/ContinueCaptureManager.java | 10 + .../PlaybackStreamSessionManager.java | 7 + .../DeviceProtocolVersionServiceTest.java | 63 ++++ .../service/OfflineDeviceClearTest.java | 47 +++ .../AudioJNIBridgeFinitePlaybackV1Test.java | 31 ++ .../components/ui/dc-dynamic-table/index.tsx | 6 +- apps/frontend/src/locales/en.ts | 184 +++++++----- apps/frontend/src/locales/zh-CN.ts | 259 ++++++++--------- .../__tests__/hardware-render.test.ts | 78 +++++ .../__tests__/protocol-versions.test.ts | 85 ++++++ .../information/__tests__/device-info.test.ts | 2 + .../information/__tests__/upgrade.test.ts | 81 +++++- .../detail/information/device-info.vue | 14 +- .../hardware/detail/information/index.vue | 9 +- .../hardware/detail/information/upgrade.vue | 269 +++++++++++------- .../src/modules/device/hardware/index.vue | 67 ++++- .../device/hardware/protocol-versions.vue | 98 +++++++ .../src/stores/__tests__/ota-upgrade.test.ts | 38 ++- apps/frontend/src/stores/ota-upgrade.ts | 152 +++++----- docs/specs/hardware-device-actions.md | 97 +++++++ docs/specs/hardware-device-actions.zh-CN.md | 97 +++++++ docs/verification/hardware-device-actions.md | 67 +++++ .../hardware-device-actions.zh-CN.md | 67 +++++ 36 files changed, 1659 insertions(+), 385 deletions(-) create mode 100644 apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/DeviceProtocolVersionDto.java create mode 100644 apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/OfflineDeviceClearDto.java create mode 100644 apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/OfflineDeviceClearResult.java create mode 100644 apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceProtocolVersionService.java create mode 100644 apps/backend/crydaq-service/src/test/java/com/opentest/service/DeviceProtocolVersionServiceTest.java create mode 100644 apps/backend/crydaq-service/src/test/java/com/opentest/service/OfflineDeviceClearTest.java create mode 100644 apps/frontend/src/modules/device/hardware/__tests__/hardware-render.test.ts create mode 100644 apps/frontend/src/modules/device/hardware/__tests__/protocol-versions.test.ts create mode 100644 apps/frontend/src/modules/device/hardware/protocol-versions.vue create mode 100644 docs/specs/hardware-device-actions.md create mode 100644 docs/specs/hardware-device-actions.zh-CN.md create mode 100644 docs/verification/hardware-device-actions.md create mode 100644 docs/verification/hardware-device-actions.zh-CN.md diff --git a/CONTEXT.md b/CONTEXT.md index 00eb3a56..1e5b272e 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -16,6 +16,17 @@ _Avoid_:运行实例、单个仓库 **版本运行实例(Version Runtime Instance)**:由版本与 HTTP/gRPC 端口对共同标识的独立运行环境,拥有自己的业务数据、插件安装状态与运行配置,其启停不影响其他版本或端口对的运行实例。 _Avoid_:版本源码目录、共享运行状态的分支切换 +## 硬件配置术语 + +**离线设备清空(Clear Offline Devices)**:对一组离线设备记录执行设备移除的操作,其删除含义与单条设备移除相同。 +_Avoid_:仅隐藏列表、清理临时缓存 + +**设备 SDK/驱动版本(Device SDK/Driver Version)**:用于设备接入的 SDK 或驱动运行库的版本标识,与设备驱动插件包版本及设备固件版本分别表达。 +_Avoid_:设备驱动插件包版本、设备固件版本 + +**设备固件版本(Device Firmware Version)**:设备自身运行的固件的版本标识。 +_Avoid_:设备 SDK/驱动版本、设备驱动插件包版本 + ## 结果名称术语 **结果名称键(Result Name Key)**:所属业务为结果名称指定的稳定文案标识,同一标识可以对应不同语言的显示名称。 diff --git a/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/DeviceProtocolVersionDto.java b/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/DeviceProtocolVersionDto.java new file mode 100644 index 00000000..15fc4f07 --- /dev/null +++ b/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/DeviceProtocolVersionDto.java @@ -0,0 +1,3 @@ +package com.opentest.common.model.dto; + +public record DeviceProtocolVersionDto(String name, String version, String status) { } diff --git a/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/OfflineDeviceClearDto.java b/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/OfflineDeviceClearDto.java new file mode 100644 index 00000000..67d3e58d --- /dev/null +++ b/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/OfflineDeviceClearDto.java @@ -0,0 +1,11 @@ +package com.opentest.common.model.dto; + +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.util.List; + +public record OfflineDeviceClearDto( + @NotNull Long projectId, + @NotEmpty @Size(max = 100000) List<@NotNull Long> ids, + Boolean deleteVirtualChannel) { } diff --git a/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/OfflineDeviceClearResult.java b/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/OfflineDeviceClearResult.java new file mode 100644 index 00000000..c17fd843 --- /dev/null +++ b/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/OfflineDeviceClearResult.java @@ -0,0 +1,5 @@ +package com.opentest.common.model.dto; + +import java.util.List; + +public record OfflineDeviceClearResult(List deletedIds, List skippedIds, List failedIds) { } diff --git a/apps/backend/crydaq-core/src/main/java/com/opentest/core/jni/AudioJNIBridge.java b/apps/backend/crydaq-core/src/main/java/com/opentest/core/jni/AudioJNIBridge.java index 2de4f1fd..faa71e79 100644 --- a/apps/backend/crydaq-core/src/main/java/com/opentest/core/jni/AudioJNIBridge.java +++ b/apps/backend/crydaq-core/src/main/java/com/opentest/core/jni/AudioJNIBridge.java @@ -10,6 +10,8 @@ /** Raw JNI declarations for audio devices, playback, capture, and calibration. */ @Service public class AudioJNIBridge { + /** Queries the SDK version exported by the specified active plugin library. */ + public native String getDeviceSdkVersion(String pluginLibraryPath); /** Optional localized plugin error lookup; older native libraries retain the original error handling. */ public native String getPluginErrorMessage(String protocol, String deviceId, int errorCode, String language); diff --git a/apps/backend/crydaq-server/src/main/java/com/opentest/controller/CppHttpController.java b/apps/backend/crydaq-server/src/main/java/com/opentest/controller/CppHttpController.java index af8458ea..fd30606f 100644 --- a/apps/backend/crydaq-server/src/main/java/com/opentest/controller/CppHttpController.java +++ b/apps/backend/crydaq-server/src/main/java/com/opentest/controller/CppHttpController.java @@ -17,6 +17,7 @@ import jakarta.annotation.Resource; import jakarta.servlet.http.HttpServletRequest; import java.util.Enumeration; +import java.nio.charset.StandardCharsets; /** * C++层HTTP接口调用控制层 @@ -63,6 +64,11 @@ public Object proxyRequest( try { // 获取实际请求路径 String path = request.getRequestURI().substring(request.getContextPath().length() + "/v1/cpp".length()); + if (HttpMethod.POST.matches(request.getMethod()) && ("/api/system/upgrade/upload".equals(path) + || ("/api/system/upgrade/action".equals(path) && body != null + && "confirm".equals(JSONUtil.parseObj(new String(body, StandardCharsets.UTF_8)).getStr("action"))))) { + cppHttpProxyService.assertUpgradeIdle(serverIp); + } String targetUrl = buildUrl(serverIp, path); log.info("调用C++接口,URL: {}, Method: {}", targetUrl, request.getMethod()); // 构建 HTTP 请求对象 @@ -88,6 +94,8 @@ public Object proxyRequest( response = httpRequest.execute(); } return buildProxyResponse(response); + } catch (CryBusinessException e) { + throw e; } catch (Exception e) { log.error("调用C++接口失败", e); throw new CryBusinessException(ErrorCode.FAILED, "调用C++接口失败"); diff --git a/apps/backend/crydaq-server/src/main/java/com/opentest/controller/DeviceController.java b/apps/backend/crydaq-server/src/main/java/com/opentest/controller/DeviceController.java index c8e9f5c2..8f139957 100644 --- a/apps/backend/crydaq-server/src/main/java/com/opentest/controller/DeviceController.java +++ b/apps/backend/crydaq-server/src/main/java/com/opentest/controller/DeviceController.java @@ -3,6 +3,9 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.opentest.common.model.DeleteDto; import com.opentest.common.model.dto.DeviceDto; +import com.opentest.common.model.dto.DeviceProtocolVersionDto; +import com.opentest.common.model.dto.OfflineDeviceClearDto; +import com.opentest.common.model.dto.OfflineDeviceClearResult; import com.opentest.common.model.dto.ptp.PtpDeviceStatusDto; import com.opentest.common.model.dto.ptp.PtpSyncConfigDto; import com.opentest.common.model.dto.ptp.PtpSyncRequestDto; @@ -10,6 +13,7 @@ import com.opentest.common.result.CommonResult; import com.opentest.core.jni.model.SonoDAQBoardInfo; import com.opentest.service.DeviceService; +import com.opentest.service.DeviceProtocolVersionService; import com.opentest.service.jni.DeviceDiscoveryRefreshCoordinator; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @@ -34,6 +38,19 @@ public class DeviceController extends BaseController { @Resource private DeviceService deviceService; + @Resource + private DeviceProtocolVersionService protocolVersions; + + @GetMapping("protocol/versions") + public CommonResult> protocolVersions() { + return success(protocolVersions.versions()); + } + + @PostMapping("offline/clear") + public CommonResult clearOffline(@Validated @RequestBody OfflineDeviceClearDto dto) { + return success(deviceService.clearOfflineDevices(dto)); + } + @Resource private DeviceDiscoveryRefreshCoordinator deviceDiscoveryRefreshCoordinator; diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/CppHttpProxyService.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/CppHttpProxyService.java index f32b5b9a..590514e3 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/CppHttpProxyService.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/CppHttpProxyService.java @@ -27,6 +27,23 @@ public class CppHttpProxyService { @Resource private AudioJNIBridgeService audioJNIBridgeService; + public void assertUpgradeIdle(String serverIp) { + List drivers = audioJNIBridgeService.getDrivers(true); + if (drivers != null) { + for (JNIDriver driver : drivers) { + if (driver != null && OPENDAQ_PROTOCOL.equalsIgnoreCase(driver.getProtocol()) && serverIp.equals(driver.getIp())) { + Device device = new Device(); + device.setProtocol(OPENDAQ_PROTOCOL); + device.setDeviceName(driver.getDevId()); + device.setIpAddress(serverIp); + audioJNIBridgeService.assertFirmwareUpgradeIdle(device); + return; + } + } + } + throw new CryBusinessException(ErrorCode.JNI_DEVICE_NOT_FOUND); + } + public String buildTargetUrl(String serverIp, String path) { if (StrUtil.isBlank(serverIp)) { throw new CryBusinessException(ErrorCode.PARAMETER, "服务器IP不能为空"); diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceProtocolVersionService.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceProtocolVersionService.java new file mode 100644 index 00000000..ca5abcf2 --- /dev/null +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceProtocolVersionService.java @@ -0,0 +1,58 @@ +package com.opentest.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.opentest.common.model.dto.DeviceProtocolVersionDto; +import com.opentest.core.jni.AudioJNIBridge; +import com.opentest.service.deviceplugin.DevicePluginManagement; +import java.util.List; +import java.util.Locale; +import java.nio.file.Path; +import org.springframework.stereotype.Service; + +/** Versions belong to the active device integration, not its package manifest. */ +@Service +public class DeviceProtocolVersionService { + private final DevicePluginManagement devices; + private final AudioJNIBridge bridge; + private final ObjectMapper json; + + public DeviceProtocolVersionService(DevicePluginManagement devices, AudioJNIBridge bridge, ObjectMapper json) { + this.devices = devices; + this.bridge = bridge; + this.json = json; + } + + public List versions() { + JsonNode packages = devices.snapshot(false).path("packages"); + return List.of(version(packages, "opentest.sonodaq.device", "SonoDAQ SDK", false), + version(packages, "opentest.nidaq.device", "NI-DAQmx", !System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows"))); + } + + private DeviceProtocolVersionDto version(JsonNode packages, String id, String name, boolean unsupported) { + JsonNode installed = null; + for (JsonNode item : packages) { + if (id.equals(item.path("packageId").asText()) && item.path("installed").asBoolean()) { + installed = item; + break; + } + } + if (installed == null) return new DeviceProtocolVersionDto(name, null, "notInstalled"); + if (unsupported) return new DeviceProtocolVersionDto(name, null, "unsupported"); + if (!"active".equals(installed.path("status").asText())) { + return new DeviceProtocolVersionDto(name, null, installed.path("enabled").asBoolean() ? "unavailable" : "disabled"); + } + try { + Path activeLibrary = devices.activeLibrary(id); + if (activeLibrary == null) return new DeviceProtocolVersionDto(name, null, "unavailable"); + JsonNode response = json.readTree(bridge.getDeviceSdkVersion(activeLibrary.toString())); + if (response != null && response.path("code").isIntegralNumber() && response.path("code").asInt() == 0 + && response.path("data").isTextual() && !response.path("data").asText().isBlank()) { + return new DeviceProtocolVersionDto(name, response.path("data").asText(), "ready"); + } + } catch (Exception | LinkageError error) { + // A missing native entry or one unavailable SDK must not hide the other row. + } + return new DeviceProtocolVersionDto(name, null, "failed"); + } +} diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceService.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceService.java index b2874997..598bc231 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceService.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceService.java @@ -15,6 +15,8 @@ import com.opentest.common.enums.ChannelSourceEnum; import com.opentest.common.enums.DeviceAddTypEnum; import com.opentest.common.enums.DeviceStateEnum; +import com.opentest.common.model.dto.OfflineDeviceClearDto; +import com.opentest.common.model.dto.OfflineDeviceClearResult; import com.opentest.common.enums.FieldColumnEnum; import com.opentest.common.exception.CryBusinessException; import com.opentest.common.exception.ErrorCode; @@ -1073,6 +1075,39 @@ public Boolean deleteFromCurrentProject(DeleteDto dto) { return deleted; } + /** Each item shares individual Remove semantics and commits independently. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED) + public OfflineDeviceClearResult clearOfflineDevices(OfflineDeviceClearDto request) { + if (request == null || request.projectId() == null || request.ids() == null || request.ids().isEmpty()) { + throw new CryBusinessException(ErrorCode.CHECK_PARAMETER_REQUIRED, "projectId/ids"); + } + List deleted = new ArrayList<>(); + List skipped = new ArrayList<>(); + List failed = new ArrayList<>(); + for (Long id : request.ids().stream().distinct().toList()) { + try { + Boolean removed = executeInShortTransaction(() -> { + Device current = (Device) getById(id); + if (current == null || !Objects.equals(current.getActiveState(), DeviceStateEnum.OFFLINE.getActiveState())) { + return null; + } + DeleteDto dto = new DeleteDto(); + dto.setId(id); + dto.setProjectId(request.projectId()); + dto.setDeleteVirtualChannel(Boolean.TRUE.equals(request.deleteVirtualChannel())); + return deleteFromCurrentProject(dto); + }); + if (removed == null) skipped.add(String.valueOf(id)); + else if (Boolean.TRUE.equals(removed)) deleted.add(String.valueOf(id)); + else failed.add(String.valueOf(id)); + } catch (RuntimeException error) { + log.warn("Offline device removal failed, deviceId={}", id, error); + failed.add(String.valueOf(id)); + } + } + return new OfflineDeviceClearResult(deleted, skipped, failed); + } + private void deleteDeviceAndPhysicalChannels(Device device) { log.info("设备删除,设备名称:" + device.getDeviceName() + ",设备id:" + device.getId()); if (ObjectUtil.equal(device.getProtocol(), "OTHER")) { diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/deviceplugin/DevicePluginManagement.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/deviceplugin/DevicePluginManagement.java index 48cdb7dc..58723289 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/deviceplugin/DevicePluginManagement.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/deviceplugin/DevicePluginManagement.java @@ -586,6 +586,16 @@ public synchronized ObjectNode snapshot(boolean permitted) { } return result; } + + /** Resolve the admitted runtime content, never a pending replacement's candidate. */ + public synchronized Path activeLibrary(String id) { + Installed installed = state.installed().get(id); + RuntimeView observed = runtime.get(id); + if (!started || closed || infrastructureError != null || installed == null || !installed.enabled() + || !admitted.contains(id) || !Boolean.TRUE.equals(decisions.get(id)) + || observed == null || !"ready".equals(observed.state())) return null; + return packages.entry(installed.content()); + } private static ObjectNode receipt(Receipt value) { ObjectNode result = DevicePluginJson.JSON.valueToTree(value); if (value.packageId() == null) result.remove("packageId"); diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/AudioJNIBridgeService.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/AudioJNIBridgeService.java index 4f4607e6..d98beb44 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/AudioJNIBridgeService.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/AudioJNIBridgeService.java @@ -259,6 +259,31 @@ static String bluetoothInputName(String name) { private final ConcurrentMap activeGeneratorSessionLocks = new ConcurrentHashMap<>(); private final AtomicLong activeGeneratorSessionSequence = new AtomicLong(); private volatile PlaybackStreamSessionManager playbackStreams; + private final ConcurrentMap finitePlaybackDevices = new ConcurrentHashMap<>(); + + public void assertFirmwareUpgradeIdle(Device device) { + String nativeId = getJniDeviceId(device); + if (continueCaptureManager.hasActiveDevice(device) + || playbackStreams().hasActiveDevice(device.getProtocol(), nativeId) + || finitePlaybackDevices.containsKey(device.getProtocol() + "\u0000" + nativeId)) { + throw new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY); + } + } + + private int withFinitePlaybackActivity(String protocol, String requestJson, Supplier operation) { + JSONObject request = JSONUtil.parseObj(requestJson); + Set devices = new HashSet<>(); + for (String direction : List.of("outputs", "inputs")) { + var channels = request.getJSONArray(direction); + if (channels != null) channels.forEach(value -> { + String id = JSONUtil.parseObj(value).getStr("deviceId"); + if (id != null) devices.add(protocol + "\u0000" + id); + }); + } + devices.forEach(key -> finitePlaybackDevices.merge(key, 1, Integer::sum)); + try { return operation.get(); } + finally { devices.forEach(key -> finitePlaybackDevices.computeIfPresent(key, (ignored, count) -> count > 1 ? count - 1 : null)); } + } // 保存实际运行配置;独立于页面选择,供差异修改、补偿和暂停恢复使用。 private final ConcurrentMap> generatorRuntimeConfigs = new ConcurrentHashMap<>(); private final ConcurrentMap generatorTargetConfigs = new ConcurrentHashMap<>(); @@ -2082,7 +2107,8 @@ public void playAudioData(Device device, List channelList, Map audioJNIBridge.playAudioDataBatchV1(protocol, request.json(), request.data())), "仅播放"); } /** @@ -2123,8 +2149,8 @@ public void playPreparedFinitePlaybackBatchV1(PreparedFinitePlaybackBatchV1 prep throw new CryBusinessException(ErrorCode.CHECK_PARAMETER, "有限播放请求未准备"); } requireSelectedBatch(prepared.protocol, prepared.request.json()); - JNIUtils.checkJniReturn(audioJNIBridge.playAudioDataBatchV1( - prepared.protocol, prepared.request.json(), prepared.request.data()), "有限批次播放"); + JNIUtils.checkJniReturn(withFinitePlaybackActivity(prepared.protocol, prepared.request.json(), + () -> audioJNIBridge.playAudioDataBatchV1(prepared.protocol, prepared.request.json(), prepared.request.data())), "有限批次播放"); } /** 仅由本服务创建和执行,调用方不能改写已经校验的 JNI 请求。 */ @@ -3072,7 +3098,8 @@ public Map playAndCaptureData(Device device, List ch JniNamedDoubleResultCollector collector = new JniNamedDoubleResultCollector(); try (var reservation = reserveExclusiveInputs(Map.of(device, inputChannels))) { requireSelectedBatch(protocol, request.json()); - int code = audioJNIBridge.playAndCaptureDataBatchV1(protocol, request.json(), request.data(), collector); + int code = withFinitePlaybackActivity(protocol, request.json(), + () -> audioJNIBridge.playAndCaptureDataBatchV1(protocol, request.json(), request.data(), collector)); JNIUtils.checkJniReturn(code, "播放并采集音频数据"); Map captured = collector.finish(); for (Map.Entry entry : resultChannels.entrySet()) { diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/CaptureInputResources.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/CaptureInputResources.java index fc0e3535..6da57a26 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/CaptureInputResources.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/CaptureInputResources.java @@ -14,6 +14,10 @@ public final class CaptureInputResources { private final Map activeChannels = new HashMap<>(); private final Map resources = new HashMap<>(); + synchronized boolean hasActiveDevice(String identity) { + return resources.keySet().stream().anyMatch(key -> key.equals(identity) || key.startsWith(identity + "\u0000")); + } + private static final class Occupancy { private int shared; private boolean exclusive; diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/ContinueCaptureManager.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/ContinueCaptureManager.java index a5928023..a37b8b77 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/ContinueCaptureManager.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/ContinueCaptureManager.java @@ -189,6 +189,16 @@ public CaptureLease reserveCapture(Device device) { return new CaptureLease(devices.computeIfAbsent(identity, key -> new DeviceCapture()), device); } + public boolean hasActiveDevice(Device device) { + String identity = AudioJNIBridgeService.inputCaptureIdentity(device, List.of()); + if (inputResources.hasActiveDevice(identity)) return true; + DeviceCapture state = devices.get(identity); + if (state == null) return false; + synchronized (state) { + return state.current != null || !state.carryForward.isEmpty() || !state.legacyLeases.isEmpty(); + } + } + private CaptureLease reserveLegacyCapture(Device device) { synchronized (nativeStartMonitor) { ensureNativeStartsOpen(); diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/playback/PlaybackStreamSessionManager.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/playback/PlaybackStreamSessionManager.java index b5445314..c2d206fa 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/playback/PlaybackStreamSessionManager.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/playback/PlaybackStreamSessionManager.java @@ -271,6 +271,13 @@ public boolean hasActive(List
addresses) { } } + public boolean hasActiveDevice(String protocol, String deviceId) { + synchronized (active) { + return active.keySet().stream().anyMatch(address -> + Objects.equals(protocol, address.protocol()) && Objects.equals(deviceId, address.deviceId())); + } + } + public boolean isRunning(List
addresses) { Set candidates; synchronized (active) { diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/DeviceProtocolVersionServiceTest.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/DeviceProtocolVersionServiceTest.java new file mode 100644 index 00000000..29797a44 --- /dev/null +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/DeviceProtocolVersionServiceTest.java @@ -0,0 +1,63 @@ +package com.opentest.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.opentest.core.jni.AudioJNIBridge; +import com.opentest.service.deviceplugin.DevicePluginManagement; +import java.nio.file.Path; +import java.util.function.Function; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +class DeviceProtocolVersionServiceTest { + private final ObjectMapper json = new ObjectMapper(); + private final DevicePluginManagement devices = mock(DevicePluginManagement.class); + @SuppressWarnings("unchecked") + private final Function versionQuery = mock(Function.class); + private final AudioJNIBridge bridge = new AudioJNIBridge() { + @Override public String getDeviceSdkVersion(String path) { return versionQuery.apply(path); } + }; + private final DeviceProtocolVersionService service = new DeviceProtocolVersionService(devices, bridge, json); + + @Test void readsSdkFromActiveContentRatherThanPackageVersionOrPendingCandidate() throws Exception { + when(devices.snapshot(false)).thenReturn(json.readTree(""" + {"packages":[{"packageId":"opentest.sonodaq.device","installed":true,"enabled":true, + "status":"active","version":"99.0.0","entryPath":"/pending/plugin.dylib"}]} + """).deepCopy()); + when(devices.activeLibrary("opentest.sonodaq.device")).thenReturn(Path.of("/active/plugin.dylib")); + when(versionQuery.apply("/active/plugin.dylib")).thenReturn("{\"code\":0,\"data\":\"1.4.0\"}"); + var rows = service.versions(); + assertEquals(2, rows.size()); + assertEquals("1.4.0", rows.getFirst().version()); + assertEquals("ready", rows.getFirst().status()); + verify(versionQuery).apply("/active/plugin.dylib"); + } + + @Test void missingAndDisabledPluginsNeverGetLoadedForVersionQueries() throws Exception { + when(devices.snapshot(false)).thenReturn(json.readTree(""" + {"packages":[{"packageId":"opentest.sonodaq.device","installed":true,"enabled":false,"status":"disabled"}]} + """).deepCopy()); + assertEquals("disabled", service.versions().getFirst().status()); + verifyNoInteractions(versionQuery); + var empty = json.createObjectNode(); + empty.putArray("packages"); + when(devices.snapshot(false)).thenReturn(empty); + assertEquals("notInstalled", service.versions().getFirst().status()); + assertEquals("notInstalled", service.versions().get(1).status()); + verifyNoInteractions(versionQuery); + } + + @Test void missingNativeSymbolIsAnIndependentRowFailure() throws Exception { + when(devices.snapshot(false)).thenReturn(json.readTree(""" + {"packages":[{"packageId":"opentest.sonodaq.device","installed":true,"enabled":true,"status":"active"}]} + """).deepCopy()); + when(devices.activeLibrary("opentest.sonodaq.device")).thenReturn(Path.of("/active/plugin.dylib")); + when(versionQuery.apply("/active/plugin.dylib")).thenThrow(new UnsatisfiedLinkError("old native library")); + var rows = service.versions(); + assertEquals("failed", rows.getFirst().status()); + assertEquals("NI-DAQmx", rows.get(1).name()); + } +} diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/OfflineDeviceClearTest.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/OfflineDeviceClearTest.java new file mode 100644 index 00000000..e0705374 --- /dev/null +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/OfflineDeviceClearTest.java @@ -0,0 +1,47 @@ +package com.opentest.service; + +import com.opentest.common.model.DeleteDto; +import com.opentest.common.model.dto.OfflineDeviceClearDto; +import com.opentest.common.model.entity.Device; +import java.util.List; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +class OfflineDeviceClearTest { + @Test void rechecksEachSnapshotItemAndContinuesAfterAnIndividualFailure() { + DeviceService service = spy(new DeviceService()); + for (long id : List.of(1L, 2L, 3L, 4L)) { + Device device = new Device(); + device.setId(id); + device.setActiveState(id == 2L ? 1 : 0); + doReturn(device).when(service).getById(id); + } + doAnswer(invocation -> { + DeleteDto dto = invocation.getArgument(0); + assertEquals(42L, dto.getProjectId()); + assertEquals(true, dto.getDeleteVirtualChannel()); + if (dto.getId() == 3L) throw new IllegalStateException("one device failed"); + return true; + }).when(service).deleteFromCurrentProject(any()); + var result = service.clearOfflineDevices(new OfflineDeviceClearDto(42L, List.of(1L, 2L, 3L, 4L, 1L), true)); + assertEquals(List.of("1", "4"), result.deletedIds()); + assertEquals(List.of("2"), result.skippedIds()); + assertEquals(List.of("3"), result.failedIds()); + verify(service, never()).deleteFromCurrentProject(argThat(dto -> dto.getId() == 2L)); + } + + @Test void aDeviceAlreadyRemovedByAnotherRequestIsSkipped() { + DeviceService service = spy(new DeviceService()); + doReturn(null).when(service).getById(1L); + var result = service.clearOfflineDevices(new OfflineDeviceClearDto(42L, List.of(1L), false)); + assertEquals(List.of("1"), result.skippedIds()); + verify(service, never()).deleteFromCurrentProject(any()); + } +} diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/AudioJNIBridgeFinitePlaybackV1Test.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/AudioJNIBridgeFinitePlaybackV1Test.java index ceeb5cd1..509b1206 100644 --- a/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/AudioJNIBridgeFinitePlaybackV1Test.java +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/AudioJNIBridgeFinitePlaybackV1Test.java @@ -18,6 +18,37 @@ import static org.junit.jupiter.api.Assertions.*; class AudioJNIBridgeFinitePlaybackV1Test { + @Test + void firmwareUpgradeRejectsTheDeviceDuringFinitePlaybackAndReleasesAfterNativeFailure() { + AudioJNIBridgeService service = new AudioJNIBridgeService(); + Device playing = device("Sono-A"); + playing.setProtocol("OPENDAQ"); + Device idle = device("Sono-B"); + idle.setProtocol("OPENDAQ"); + AudioJNIBridge bridge = new AudioJNIBridge() { + @Override public int playAudioDataBatchV1(String protocol, String request, float[][] data) { + assertThrows(CryBusinessException.class, () -> service.assertFirmwareUpgradeIdle(playing)); + assertDoesNotThrow(() -> service.assertFirmwareUpgradeIdle(idle)); + throw new IllegalStateException("native playback failed"); + } + }; + ReflectionTestUtils.setField(service, "audioJNIBridge", bridge); + assertThrows(IllegalStateException.class, () -> service.playAudioDataBatchV1( + List.of(output("Sono-A", "OPENDAQ", 4001, new float[]{0F})), "NORMAL")); + assertDoesNotThrow(() -> service.assertFirmwareUpgradeIdle(playing)); + } + + @Test + void firmwareUpgradeRejectsReservedCaptureInputsUntilTheyAreReleased() { + AudioJNIBridgeService service = new AudioJNIBridgeService(); + Device device = device("Sono-A"); + device.setProtocol("OPENDAQ"); + try (var reservation = service.reserveExclusiveInputs(Map.of(device, List.of(input("Sono-A", "OPENDAQ", 1001, 1L))))) { + assertThrows(CryBusinessException.class, () -> service.assertFirmwareUpgradeIdle(device)); + } + assertDoesNotThrow(() -> service.assertFirmwareUpgradeIdle(device)); + } + @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(ints = {1002, 2001}) void independentInputsReachNativeWhileFirstPlaybackCaptureIsRunning(int secondInput) throws Exception { diff --git a/apps/frontend/src/components/ui/dc-dynamic-table/index.tsx b/apps/frontend/src/components/ui/dc-dynamic-table/index.tsx index d34b8322..52edf649 100644 --- a/apps/frontend/src/components/ui/dc-dynamic-table/index.tsx +++ b/apps/frontend/src/components/ui/dc-dynamic-table/index.tsx @@ -28,6 +28,7 @@ interface ColumnFormat { interface DynamicColumn extends Record { prop?: string label?: string | VNodeChild + renderHeader?: () => VNodeChild show?: boolean | ((_data: TableRow[]) => boolean) children?: DynamicColumn[] sortable?: boolean @@ -191,6 +192,7 @@ export default defineComponent({ } const renderHeaderSlot = (columnSetting: DynamicColumn) => { return () => { + if (columnSetting.renderHeader) return columnSetting.renderHeader() let label = columnSetting.label const { sortable, tooltip } = columnSetting || {} if (sortable) { @@ -249,6 +251,8 @@ export default defineComponent({ } const renderColumn = (columnSetting: DynamicColumn, columnKey: string, columnIndex: number): VNodeChild => { + const nativeColumn = { ...columnSetting } + delete nativeColumn.renderHeader return ( ({ + NOOP: () => {}, + translate: (key: string) => key, + handleConfirmAction: vi.fn(), + isUndefined: (value: unknown) => value === undefined, + isNumber: (value: unknown) => typeof value === 'number', + isString: (value: unknown) => typeof value === 'string', + isFunction: (value: unknown) => typeof value === 'function', + thousandFormatter: (value: unknown) => value +})) +vi.mock('@/services/api', () => ({ + default: { + base: () => ({ post: async () => ({ data: {} }) }), + baseSilent: () => ({ get: async () => ({ data: [] }) }) + } +})) +vi.mock('../sync/sync-service', async () => { + const { ref } = await import('vue') + return { + ptpSyncService: { + syncStatusMap: ref({}), + syncData: ref({ isSyncing: false }), + bootstrap() {}, + stopPollingSyncStatusRequest() {} + } + } +}) +vi.mock('@/stores/device', async () => { + const { defineStore } = await import('pinia') + const { ref } = await import('vue') + return { + useDeviceStore: defineStore('hardware-render-devices', () => { + const deviceList = ref([{ id: 'one', deviceName: 'Device A', connected: true, protocol: 'OPENDAQ' }]) + return { + deviceList, + startDevicePolling() {}, + stopDevicePolling() {}, + async refreshDeviceList() { + deviceList.value = deviceList.value.map(device => ({ ...device })) + return deviceList.value + } + } + }) + } +}) + +describe('hardware table rendering', () => { + beforeEach(() => vi.clearAllMocks()) + it('retains device rows, protocol heading and offline structure after repeated refreshes', async () => { + const wrapper = mount(Hardware, { + props: { projectId: '42' }, + global: { + plugins: [createPinia(), ElementPlus], + components: { DcDynamicTable: DynamicTable }, + mocks: { $t: (key: string) => key }, + stubs: { SimpleCard: { template: '
' } } + } + }) + await flushPromises() + for (let index = 0; index < 3; index++) { + expect(wrapper.get('.is-online').text()).toContain('Device A') + expect(wrapper.get('.is-online').text()).toContain('device.protocol') + expect(wrapper.get('.dc-device-hardware__offline-bar .dc-device-hardware__offline-title').text()).toBe( + 'device.offline' + ) + await wrapper.get('button[title="device.refresh"]').trigger('click') + await flushPromises() + } + wrapper.unmount() + }) +}) diff --git a/apps/frontend/src/modules/device/hardware/__tests__/protocol-versions.test.ts b/apps/frontend/src/modules/device/hardware/__tests__/protocol-versions.test.ts new file mode 100644 index 00000000..dd5d859b --- /dev/null +++ b/apps/frontend/src/modules/device/hardware/__tests__/protocol-versions.test.ts @@ -0,0 +1,85 @@ +import { flushPromises, mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import ProtocolVersions from '../protocol-versions.vue' + +const api = vi.hoisted(() => ({ get: vi.fn() })) +vi.mock('@/services/api', () => ({ default: { baseSilent: () => api } })) + +function mountVersions() { + return mount(ProtocolVersions, { + global: { + mocks: { $t: (key: string) => key }, + directives: { loading: {} }, + stubs: { + DcIconButton: true, + 'el-popover': { emits: ['show'], template: '
' } + } + } + }) +} + +describe('protocol versions', () => { + it('loads only when opened and omits NI when its plugin is not installed', async () => { + api.get.mockResolvedValue({ + data: [ + { name: 'SonoDAQ SDK', status: 'ready', version: '1.4.0' }, + { name: 'NI-DAQmx', status: 'notInstalled' } + ] + }) + const wrapper = mountVersions() + expect(api.get).not.toHaveBeenCalled() + await wrapper.get('button').trigger('click') + await flushPromises() + expect(wrapper.text()).toContain('1.4.0') + expect(wrapper.findAll('tbody tr')).toHaveLength(1) + expect(wrapper.text()).not.toContain('NI-DAQmx') + }) + + it.each(['failed', 'disabled', 'unavailable', 'unsupported'])( + 'shows -- for an installed NI plugin with status %s', + async status => { + api.get.mockResolvedValue({ data: [{ name: 'NI-DAQmx', status, version: null }] }) + const wrapper = mountVersions() + await wrapper.get('button').trigger('click') + await flushPromises() + expect( + wrapper + .findAll('tbody tr')[1] + .findAll('td') + .map(cell => cell.text()) + ).toEqual(['NI-DAQmx', '--']) + } + ) + + it('shows the NI version when readable and omits it after uninstall', async () => { + api.get + .mockResolvedValueOnce({ data: [{ name: 'NI-DAQmx', status: 'ready', version: '25.3.1' }] }) + .mockResolvedValueOnce({ data: [{ name: 'NI-DAQmx', status: 'notInstalled' }] }) + const wrapper = mountVersions() + await wrapper.get('button').trigger('click') + await flushPromises() + expect( + wrapper + .findAll('tbody tr')[1] + .findAll('td') + .map(cell => cell.text()) + ).toEqual(['NI-DAQmx', '25.3.1']) + await wrapper.get('button').trigger('click') + await flushPromises() + expect(wrapper.text()).not.toContain('NI-DAQmx') + }) + + it('keeps an unknown NI installation hidden on request failure and retries when reopened', async () => { + api.get + .mockRejectedValueOnce(new Error('failed')) + .mockResolvedValueOnce({ data: [{ name: 'SonoDAQ SDK', status: 'ready', version: '1.4.1' }] }) + const wrapper = mountVersions() + await wrapper.get('button').trigger('click') + await flushPromises() + expect(wrapper.findAll('tbody tr')).toHaveLength(1) + expect(wrapper.text()).toContain('device.sdkStatus.failed') + await wrapper.get('button').trigger('click') + await flushPromises() + expect(wrapper.text()).toContain('1.4.1') + }) +}) diff --git a/apps/frontend/src/modules/device/hardware/detail/information/__tests__/device-info.test.ts b/apps/frontend/src/modules/device/hardware/detail/information/__tests__/device-info.test.ts index 583fb838..da509cad 100644 --- a/apps/frontend/src/modules/device/hardware/detail/information/__tests__/device-info.test.ts +++ b/apps/frontend/src/modules/device/hardware/detail/information/__tests__/device-info.test.ts @@ -2,6 +2,8 @@ import { computed, ref, watch } from 'vue' import { mount } from '@vue/test-utils' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +vi.mock('@/modules/device/hardware/detail/information/upgrade.vue', () => ({ default: { template: '' } })) + const apiMocks = vi.hoisted(() => ({ baseGet: vi.fn(), basePost: vi.fn() diff --git a/apps/frontend/src/modules/device/hardware/detail/information/__tests__/upgrade.test.ts b/apps/frontend/src/modules/device/hardware/detail/information/__tests__/upgrade.test.ts index 5ad22b6a..c59963e0 100644 --- a/apps/frontend/src/modules/device/hardware/detail/information/__tests__/upgrade.test.ts +++ b/apps/frontend/src/modules/device/hardware/detail/information/__tests__/upgrade.test.ts @@ -64,7 +64,8 @@ function mountUpgrade() { $t: (key: string) => key }, stubs: { - 'dc-file-select': true, + DcFileSelect: true, + DcIconButton: true, 'el-button': { template: '' }, @@ -83,7 +84,7 @@ describe('device firmware upgrade', () => { vi.stubGlobal('onBeforeUnmount', onBeforeUnmount) mocks.loadBinaryFile.mockResolvedValue({ data: new Uint8Array([1, 2, 3]), - fileSize: 1024 + size: 1024 }) mocks.handleConfirmAction.mockImplementation((...args: unknown[]) => { const options = args[2] as { cancelCallback?: () => void } @@ -91,6 +92,14 @@ describe('device firmware upgrade', () => { }) }) + it('starts collapsed and expands inline from the Firmware Version action', async () => { + const wrapper = mountUpgrade() + expect(wrapper.find('.dc-device-hardware-upgrade__editor').exists()).toBe(false) + await wrapper.get('.dc-device-hardware-upgrade__entry').trigger('click') + expect(wrapper.find('.dc-device-hardware-upgrade__editor').exists()).toBe(true) + expect(mocks.post).not.toHaveBeenCalled() + }) + it('shows replacement only when the device has a pending package', async () => { const wrapper = mountUpgrade() const store = useOtaUpgradeStore() @@ -98,6 +107,7 @@ describe('device firmware upgrade', () => { expect(wrapper.text()).not.toContain('device.replacePendingUpgrade') store.setUpgradeState(device, { + editorOpen: true, pendingConfirmation: true, uploadError: 'A validated upgrade package is awaiting confirm or cancel' }) @@ -111,6 +121,7 @@ describe('device firmware upgrade', () => { const store = useOtaUpgradeStore() store.initUpgradeState(device, { filePath: 'firmware.bin' }) store.setUpgradeState(device, { + editorOpen: true, pendingConfirmation: true, uploadError: 'A validated upgrade package is awaiting confirm or cancel' }) @@ -156,6 +167,7 @@ describe('device firmware upgrade', () => { const store = useOtaUpgradeStore() store.initUpgradeState(device, { filePath: 'firmware.bin' }) store.setUpgradeState(device, { + editorOpen: true, pendingConfirmation: true, uploadError: 'A validated upgrade package is awaiting confirm or cancel' }) @@ -170,4 +182,69 @@ describe('device firmware upgrade', () => { expect(mocks.post).not.toHaveBeenCalled() expect(store.getUpgradeState(device).pendingConfirmation).toBe(true) }) + + it('waits for explicit inline confirmation after validation and retains the original success criterion', async () => { + const wrapper = mountUpgrade() + const store = useOtaUpgradeStore() + store.setUpgradeState(device, { editorOpen: true, filePath: 'firmware.bin' }) + mocks.post.mockResolvedValue({ data: { success: true } }) + await store.upload(device, { filePath: 'firmware.bin' }) + await nextTick() + expect(mocks.post).toHaveBeenCalledTimes(1) + expect(store.getUpgradeState(device).fileValidated).toBe(true) + expect(wrapper.text()).toContain('device.upgradeAndRestart') + const confirm = wrapper.findAll('button').find(button => button.text() === 'device.upgradeAndRestart')! + await confirm.trigger('click') + await flushPromises() + expect(mocks.post).toHaveBeenLastCalledWith( + '/v1/cpp/api/system/upgrade/action', + { action: 'confirm' }, + expect.any(Object) + ) + expect(mocks.messageSuccess).toHaveBeenCalledOnce() + expect(store.getUpgradeState(device).editorOpen).toBe(false) + expect(mocks.handleConfirmAction).not.toHaveBeenCalled() + }) + + it('preserves active state when details unmount and prevents repeated confirmation', async () => { + const wrapper = mountUpgrade() + const store = useOtaUpgradeStore() + store.setUpgradeState(device, { editorOpen: true, filePath: 'firmware.bin', fileValidated: true }) + let finish!: (_value: unknown) => void + mocks.post.mockImplementation( + () => + new Promise(resolve => { + finish = resolve + }) + ) + const first = store.upgrade(device) + expect(await store.upgrade(device)).toBe(false) + wrapper.unmount() + expect(store.getUpgradeState(device).isConfirming).toBe(true) + expect(store.getUpgradeState(device).editorOpen).toBe(true) + expect(mocks.post).toHaveBeenCalledOnce() + finish({ data: { success: true } }) + expect(await first).toBe(true) + expect(store.getUpgradeState(device).isConfirming).toBe(false) + }) + + it('ignores a cancelled upload response that arrives after cancellation', async () => { + mountUpgrade() + const store = useOtaUpgradeStore() + let finish!: (_value: unknown) => void + mocks.post.mockImplementation( + () => + new Promise(resolve => { + finish = resolve + }) + ) + const upload = store.upload(device, { filePath: 'firmware.bin' }) + await flushPromises() + await store.cancelUpload(device) + finish({ data: { success: true } }) + await upload + expect(store.getUpgradeState(device).fileValidated).toBe(false) + expect(store.getUpgradeState(device).uploadStatus).toBe('cancelled') + expect(store.getUpgradeState(device).uploadError).toBe('') + }) }) diff --git a/apps/frontend/src/modules/device/hardware/detail/information/device-info.vue b/apps/frontend/src/modules/device/hardware/detail/information/device-info.vue index 5a0186ba..cb60180a 100644 --- a/apps/frontend/src/modules/device/hardware/detail/information/device-info.vue +++ b/apps/frontend/src/modules/device/hardware/detail/information/device-info.vue @@ -35,7 +35,10 @@ - {{ firmwareVersion || '-' }} +
+ {{ firmwareVersion || '-' }} + +
@@ -45,6 +48,7 @@ import { nextTick } from 'vue' import { ElMessage } from 'element-plus' import { CircleAlert } from 'lucide-vue-next' import api from '@/services/api' +import DcDeviceHardwareUpgrade from './upgrade.vue' import { translate } from '@/utils' import type { ApiResult } from '@/services/api.types' @@ -184,6 +188,14 @@ function submitDeviceName() { diff --git a/apps/frontend/src/modules/device/hardware/index.vue b/apps/frontend/src/modules/device/hardware/index.vue index 7523ba3a..7ccd4f3f 100644 --- a/apps/frontend/src/modules/device/hardware/index.vue +++ b/apps/frontend/src/modules/device/hardware/index.vue @@ -7,7 +7,8 @@ :key="index" :icon="action.icon" :tooltip="$t(action.text)" - :disabled="loading" + :disabled="loading || clearingOffline || (action.text === 'device.refresh' && isForceRefresPending)" + :class="{ 'is-pending': action.text === 'device.refresh' && isForceRefresPending }" @click="action.onClick" /> @@ -31,12 +32,11 @@ {{ $t('device.offline') }}
() const emit = defineEmits(['device-deleted', 'device-add-success', 'sonodaq-status-changed']) const loading = ref(false) +const clearingOffline = ref(false) const deviceDetailVisible = ref(false) const DcDeviceDetail = shallowRef(null) const selectedDevice = ref({}) @@ -148,6 +150,7 @@ interface DeviceRow { interface DeviceTableColumn extends Record { label: string + renderHeader?: () => VNodeChild prop: string width?: number minWidth?: number @@ -179,6 +182,11 @@ const deviceActions = computed(() => { text: 'device.add', onClick: addDevice }, + { + icon: RefreshCw, + text: 'device.refresh', + onClick: forceRefreshDeviceList + }, { icon: syncIcon, text: 'device.synchronization', @@ -244,6 +252,7 @@ const offlineDeviceColumns = computed(() => { return ( removeDevice(device)} > {translate('actions.remove')} @@ -268,6 +277,49 @@ onBeforeUnmount(() => { }) /** @description 删除设备 */ +async function clearOfflineDevices() { + if (clearingOffline.value || !offlineDeviceList.value.length) return + const ids = offlineDeviceList.value.map(device => device.id) + const projectId = props.projectId + const deleteVirtualChannel = ref(false) + clearingOffline.value = true + try { + await ElMessageBox.confirm( + () => ( +
+

{translate('device.clearOfflineConfirm', { count: ids.length })}

+

{translate('device.clearOfflineProjectNotice')}

+ (deleteVirtualChannel.value = value)} + > + {translate('device.deleteVirtualChannels')} + +
+ ), + translate('device.clearOffline'), + { type: 'warning', confirmButtonText: translate('common.confirm'), cancelButtonText: translate('common.cancel') } + ) + const response = await api.baseSilent().post<{ + data: { deletedIds: string[]; skippedIds: string[]; failedIds: string[] } + }>('/v1/device/offline/clear', { ids, projectId, deleteVirtualChannel: deleteVirtualChannel.value }) + const result = response.data + const message = translate('device.clearOfflineResult', { + deleted: result.deletedIds.length, + skipped: result.skippedIds.length, + failed: result.failedIds.length + }) + if (result.failedIds.length) ElMessage.warning(message) + else ElMessage.success(message) + if (result.deletedIds.length) emit('device-deleted') + await refreshDeviceList() + } catch (error) { + if (error !== 'cancel' && error !== 'close') ElMessage.error(translate('api.serviceException')) + } finally { + clearingOffline.value = false + } +} + function removeDevice(deviceData: DeviceRow) { const allowDeleteVirtualChannels = ref(false) const message = defineComponent({ @@ -428,6 +480,7 @@ function getBasicColumns(isOnline = true): DeviceTableColumn[] { }, { label: translate('device.protocol'), + renderHeader: () => , prop: 'protocol', formatter: (_row, value) => { const protocol = String(value ?? '') diff --git a/apps/frontend/src/modules/device/hardware/protocol-versions.vue b/apps/frontend/src/modules/device/hardware/protocol-versions.vue new file mode 100644 index 00000000..07a1fdf4 --- /dev/null +++ b/apps/frontend/src/modules/device/hardware/protocol-versions.vue @@ -0,0 +1,98 @@ + + + + + diff --git a/apps/frontend/src/stores/__tests__/ota-upgrade.test.ts b/apps/frontend/src/stores/__tests__/ota-upgrade.test.ts index d2e7ed24..fa776b31 100644 --- a/apps/frontend/src/stores/__tests__/ota-upgrade.test.ts +++ b/apps/frontend/src/stores/__tests__/ota-upgrade.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { createPinia, setActivePinia } from 'pinia' +import { flushPromises } from '@vue/test-utils' import { ref, nextTick } from 'vue' const mocks = vi.hoisted(() => ({ @@ -50,7 +51,7 @@ describe('ota upgrade store', () => { vi.clearAllMocks() mocks.loadBinaryFile.mockResolvedValue({ data: new Uint8Array([1, 2, 3]), - fileSize: 1024 + size: 1024 }) mocks.post.mockResolvedValue({ data: { @@ -59,6 +60,20 @@ describe('ota upgrade store', () => { }) }) + it('reads the file-loader size and reuses the selected binary for upload', async () => { + const store = await createOtaUpgradeStore() + const device = { id: 'selected-device', ipAddress: '192.168.5.157' } + await store.selectFile(device, 'firmware.bin') + expect(store.getUpgradeState(device).fileSize).toBe(1024) + await store.upload(device, { filePath: 'firmware.bin' }) + expect(mocks.loadBinaryFile).toHaveBeenCalledOnce() + expect(mocks.post).toHaveBeenCalledWith( + '/v1/cpp/api/system/upgrade/upload', + expect.any(Uint8Array), + expect.objectContaining({ timeout: 30000 }) + ) + }) + it('uploads scoped IPv6 firmware through the C++ proxy', async () => { const store = await createOtaUpgradeStore() const device = { @@ -186,8 +201,18 @@ describe('ota upgrade store', () => { deviceName: 'DAQ' } - await store.upload(device, { filePath: 'firmware.bin' }) + let finish!: (_value: unknown) => void + mocks.post.mockImplementationOnce( + () => + new Promise(resolve => { + finish = resolve + }) + ) + const upload = store.upload(device, { filePath: 'firmware.bin' }) + await flushPromises() await store.cancelUpload(device) + finish({ data: { success: true } }) + await upload const state = store.getUpgradeState(device) expect(mocks.cancel).toHaveBeenCalledWith('') @@ -196,14 +221,17 @@ describe('ota upgrade store', () => { expect(state.isCancelled).toBe(true) }) it('keeps an upstream device error code and formats uncoded caught failures through the update owner', async () => { - const store = await createOtaUpgradeStore(); const device = { id: 'failed-device' } + const store = await createOtaUpgradeStore() + const device = { id: 'failed-device' } mocks.post.mockResolvedValueOnce({ code: 6123, data: { success: false, message: 'Device refused package' } }) - await expect(store.upload(device, { filePath: 'firmware.bin' })).rejects.toMatchObject({ code: 6123, message: 'Device refused package (6123)' }) + await expect(store.upload(device, { filePath: 'firmware.bin' })).rejects.toMatchObject({ + code: 6123, + message: 'Device refused package (6123)' + }) expect(store.getUpgradeState(device).uploadError).toBe('Device refused package (6123)') mocks.loadBinaryFile.mockRejectedValueOnce(new Error('/private/technical/path')) await expect(store.upload(device, { filePath: 'firmware.bin' })).rejects.toThrow('/private/technical/path') expect(store.getUpgradeState(device).uploadError).toMatch(/\(11010005\)$/) expect(store.getUpgradeState(device).uploadError).not.toContain('/private/') }) - }) diff --git a/apps/frontend/src/stores/ota-upgrade.ts b/apps/frontend/src/stores/ota-upgrade.ts index 9592ec63..7852539d 100644 --- a/apps/frontend/src/stores/ota-upgrade.ts +++ b/apps/frontend/src/stores/ota-upgrade.ts @@ -3,8 +3,7 @@ import { FrontendErrorCode as FE } from '@/constants/error-codes' import type { CancelToken } from 'axios' import { defineStore } from 'pinia' import api from '@services/api' -import { loadBinaryFile } from '@/libs/file-loader' -import { handleConfirmAction, translate } from '@/utils' +import { loadBinaryFile, type BinaryFileResult } from '@/libs/file-loader' const UPGRADE_STATUS = { PENDING: 'pending', @@ -28,6 +27,10 @@ interface UpgradeCancelToken { } interface UpgradeState { + editorOpen: boolean + isConfirming: boolean + fileSize: number + attempt: number deviceId: UpgradeDevice['id'] deviceName: string | number | undefined filePath: string @@ -43,11 +46,6 @@ interface UpgradeState { isCancelled: boolean } -interface BinaryFileResponse { - data: unknown - fileSize: number -} - interface UploadProgressEvent { loaded: number total?: number | null @@ -69,10 +67,16 @@ function upgradeError(response: UpgradeResponse) { } export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { + let attempt = 0 + const selectedFiles = new Map() const upgradeMapping = ref(new Map()) function initUpgradeState(device: UpgradeDevice, { filePath = '' }: { filePath?: string } = {}) { const initialState: UpgradeState = { + editorOpen: false, + isConfirming: false, + fileSize: 0, + attempt: ++attempt, deviceId: device.id, deviceName: device.deviceNameAndIp || device.deviceName || device.ipAddress, @@ -90,6 +94,7 @@ export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { cancelToken: null, isCancelled: false } + selectedFiles.delete(device.id) upgradeMapping.value.set(device.id, initialState) return initialState } @@ -113,6 +118,12 @@ export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { function upload(device: UpgradeDevice, { filePath = '' }: { filePath?: string } = {}) { setUpgradeState(device, { filePath, + attempt: ++attempt, + isCancelled: false, + uploadError: '', + fileValidated: false, + isUploaded: false, + uploadProgress: 0, isUpgrading: true, isUploading: true, uploadStatus: UPGRADE_STATUS.UPLOADING @@ -121,8 +132,14 @@ export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { } async function uploadFile(device: UpgradeDevice, { filePath = '' }: { filePath?: string } = {}) { + const currentAttempt = getUpgradeState(device).attempt + const isCurrent = () => getUpgradeState(device).attempt === currentAttempt try { - const res = (await loadBinaryFile(filePath)) as unknown as BinaryFileResponse + const selected = selectedFiles.get(device.id) + const res = selected?.path === filePath ? selected.file : await loadBinaryFile(filePath) + if (!isCurrent()) return + const fileSize = res.size ?? res.data?.byteLength ?? 0 + setUpgradeState(device, { fileSize }) const cancelToken = api.CancelToken.source() as unknown as UpgradeCancelToken setUpgradeState(device, { @@ -135,12 +152,15 @@ export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { 'Content-Type': 'application/octet-stream' }, transformRequest: [data => data], - timeout: calculateTimeout(res.fileSize), + timeout: calculateTimeout(fileSize), cancelToken: cancelToken.token, - onUploadProgress: (event: UploadProgressEvent) => calcUploadProgress(event, device) + onUploadProgress: (event: UploadProgressEvent) => { + if (isCurrent()) calcUploadProgress(event, device) + } })) as UpgradeResponse - processUploadResponse(device, response) + if (isCurrent()) processUploadResponse(device, response) } catch (error) { + if (!isCurrent()) return setUpgradeState(device, { isUpgrading: false, isUploading: false, @@ -153,6 +173,8 @@ export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { async function cancelUpload(device: UpgradeDevice) { const upgradeState = getUpgradeState(device) + if (!upgradeState.isUploading) return + upgradeState.attempt = ++attempt upgradeState.cancelToken?.cancel('') await nextTick() @@ -193,59 +215,54 @@ export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { }) } - function upgrade(device: UpgradeDevice) { - const deviceName = device.deviceNameAndIp || device.deviceName || device.ipAddress - return new Promise((resolve, reject) => { - handleConfirmAction(translate('device.otaUpgradeConfirm'), deviceName, { - type: 'warning', - url: '/v1/cpp/api/system/upgrade/action', - method: 'post', - data: { action: 'confirm' }, - http: api.baseSilent() as unknown as Record< - string, - (_url?: string, _data?: unknown, _config?: unknown) => Promise - >, - config: { - headers: { - 'Cpp-Server-IP': device?.ipAddress - } - }, - cancelCallback: () => { - setUpgradeState(device, { - isUpgrading: false, - isCancelled: true - }) - reject() - }, - callback: (res: UpgradeResponse) => { - const isSuccess = res?.data?.success - if (isSuccess) { - initUpgradeState(device) - resolve() - } else { - const failure = upgradeError(res) - const errorMsg = failure.message - setUpgradeState(device, { - isUpgrading: false, - isUploading: false, - uploadStatus: UPGRADE_STATUS.FAILED, - uploadError: errorMsg || '' - }) - reject(failure) - } - resolve() - }, - errorCallback: error => { - setUpgradeState(device, { - isUpgrading: false, - isUploading: false, - uploadStatus: UPGRADE_STATUS.FAILED, - uploadError: getCaughtErrorMessage(error, FE.UPDATE) - }) - reject(error) - } - }) + async function selectFile(device: UpgradeDevice, filePath: string) { + const state = getUpgradeState(device) + if (state.isUploading || state.isConfirming) return + selectedFiles.delete(device.id) + setUpgradeState(device, { + filePath, + fileSize: 0, + uploadError: '', + pendingConfirmation: state.pendingConfirmation || state.fileValidated, + fileValidated: false, + isUploaded: false, + isUpgrading: false }) + const selectionAttempt = ++attempt + state.attempt = selectionAttempt + try { + const file = await loadBinaryFile(filePath) + if (getUpgradeState(device).attempt !== selectionAttempt) return + selectedFiles.set(device.id, { path: filePath, file }) + setUpgradeState(device, { fileSize: file.size ?? file.data?.byteLength ?? 0 }) + } catch (error) { + if (getUpgradeState(device).attempt === selectionAttempt) { + setUpgradeState(device, { uploadError: getCaughtErrorMessage(error, FE.UPDATE) }) + } + } + } + + async function upgrade(device: UpgradeDevice) { + const state = getUpgradeState(device) + if (state.isConfirming || state.isUploading || !state.fileValidated) return false + setUpgradeState(device, { isConfirming: true, isUpgrading: true, uploadError: '' }) + try { + const response = (await api.baseSilent().post( + '/v1/cpp/api/system/upgrade/action', + { action: 'confirm' }, + { + headers: { 'Cpp-Server-IP': device.ipAddress } + } + )) as UpgradeResponse + if (!response.data?.success) throw upgradeError(response) + initUpgradeState(device) + return true + } catch (error) { + setUpgradeState(device, { isUpgrading: false, uploadError: getCaughtErrorMessage(error, FE.UPDATE) }) + throw error + } finally { + setUpgradeState(device, { isConfirming: false }) + } } function processUploadResponse(device: UpgradeDevice, response: UpgradeResponse) { @@ -253,6 +270,10 @@ export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { if (isSuccess) { setUpgradeState(device, { isUploading: false, + isUpgrading: false, + isUploaded: true, + pendingConfirmation: false, + uploadProgress: 100, uploadStatus: UPGRADE_STATUS.COMPLETED, fileValidated: true }) @@ -269,8 +290,8 @@ export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { } function calcUploadProgress(event: UploadProgressEvent, device: UpgradeDevice) { - const total = event.total || event.loaded || 1 - const progress = (event.loaded / total) * 100 + const total = event.total + const progress = total ? Math.min(100, (event.loaded / total) * 100) : 0 setUpgradeState(device, { uploadProgress: progress, isUploaded: !!event.total && event.loaded === event.total, @@ -290,6 +311,7 @@ export const useOtaUpgradeStore = defineStore('ota-upgrade', () => { setUpgradeState, initUpgradeState, upload, + selectFile, cancelUpload, cancelPendingUpgrade, upgrade diff --git a/docs/specs/hardware-device-actions.md b/docs/specs/hardware-device-actions.md new file mode 100644 index 00000000..21604fca --- /dev/null +++ b/docs/specs/hardware-device-actions.md @@ -0,0 +1,97 @@ +# Hardware Configuration: Device Actions and Firmware Upgrade + +[简体中文](hardware-device-actions.zh-CN.md) + +Status: implemented; verification recorded + +This specification records the six product decisions confirmed in the grill-with-docs interview. The user subsequently authorized implementation in a new worktree and branch, with physical-device testing. See the [verification record](../verification/hardware-device-actions.md) for results and limits. + +## Explicit requirements + +| Item | Requirement | Interface boundary | +| --- | --- | --- | +| a | Move refresh from the Offline bar to the right side of the Devices title bar. | Follow image 1: place it between add and synchronization, retaining refresh behavior. | +| b | Add a clear-all entry to the right side of the Offline heading. | Use a broom icon for clear-all. Preserve the list, folding behavior, and page layout. Do not add selection columns. Removal semantics match individual Remove. | +| d | Add a details icon to the Protocol heading. Hovering over it shows protocol/SDK names and versions in a popover. | Prioritize SonoDAQ SDK and NI-DAQmx. The version numbers in image 2 are examples. | +| e | Remove the separate Firmware OTA section from SonoDAQ details and place Upgrade beside Firmware Version. | Follow image 3 and the supplied video for inline interaction. | + +No item c was requested. Other highlighted areas in the images do not automatically expand scope. Demo labels in the reference material are not product requirements. + +## Interaction shown in the video + +Reference: supplied interaction video, approximately 17 seconds long. + +1. Initially show Firmware Version and the Upgrade button. +2. Upgrade expands a file selection row below, containing file selection, filename, an upgrade action, and a close action. +3. After selection, show filename and size and allow replacement. +4. Starting the upgrade reveals an inline restart confirmation and a power reminder, with Upgrade & Restart and Cancel actions. +5. Lock relevant actions during execution and display progress and the power reminder. +6. Collapse the editor when finished and show the outcome beside the version. + +The reference shows an Installing percentage and a demo completion state. The user accepted its inline interaction structure, with actual upload progress and existing device-processing and success behavior. Device flashing percentages and completion verification after reconnection are not introduced. + +## Verified existing behavior + +- Refresh actively updates device state and reloads the list. It can also trigger module-change confirmation and project-channel updates. +- Offline currently supports individual Remove actions. Removal deletes shared device records and physical channels and can affect other projects. By default, project channel slots remain but their bindings are cleared. The existing delete-virtual-channels option actually also removes associated physical channel slots; it must not be interpreted as deleting mathematical channels. +- Individual removal does not recheck Offline state at execution time. Bulk removal needs an explicit rule for devices that come online concurrently. +- SonoDAQ already has firmware upload, validation, confirmation, and pending-package cancellation, forwarded to the device through OpenTest's HTTP proxy. The percentage only measures upload from frontend to backend. The backend receives the entire file before forwarding it, so 100% does not establish device receipt or completed flashing. No device flashing-progress query was found. +- The current interface reports success immediately after the device confirmation command returns success. It neither establishes that this response means completed flashing nor waits for restart or reconnection. A firmware-version query already exists but is not refreshed after an upgrade. State belongs to each device; closing details does not automatically cancel an upload. +- The native dependency already exposes a generic device SDK version entry, but the application still needs a connection to it. SonoDAQ reports the SDK version used to build the plugin; NI-DAQmx reports a version queried from the runtime library. Neither is the plugin package version. +- These observations describe the baseline before implementation. Current verification is recorded separately. + +## Confirmed behavior + +### Clear all Offline devices + +1. Use one confirmation for the batch. Removal meaning, defaults, associated-channel options, and handling of other projects match individual Remove. The confirmation explains effects on associated projects. The individual removal policy is not redesigned. +2. By default, retain project channel slots and clear their physical bindings. When the user selects the existing associated-slot deletion option, use individual Remove rules. Do not reinterpret this as mathematical-channel deletion. +3. Capture the Offline list when clear-all is clicked. Do not add devices that become offline while confirmation is open. Recheck each device before execution and skip devices that have returned online. +4. Continue after individual failures and summarize successes, skips, and failures. Do not roll back successful items because another item failed. Refresh device and affected-channel displays afterward. +5. Prevent duplicate submissions during execution and disable the button when no offline devices exist. Clicking the action must not toggle the Offline section. + +### Protocol details + +1. Hovering over the details icon beside the Protocol heading opens a temporary popover. Moving away closes it. Show the SonoDAQ SDK row. Include NI-DAQmx when its device plugin is installed. +2. Use the SDK version used to build the SonoDAQ plugin and the version queried from the NI-DAQmx runtime library. Query actual values; do not substitute plugin package versions or reference-image values. +3. For an installed NI-DAQmx plugin whose version cannot be read, show `--`. SonoDAQ SDK keeps its own status when no version is available. Opening details does not enable disabled or unloaded plugins. +4. This information describes device integration software and does not require an online device. Follow existing interface styles and localization. + +### SonoDAQ firmware upgrade + +1. Remove the standalone Firmware OTA section. Place Upgrade beside Firmware Version and expand the inline editor beneath it. Retain module information and the existing SonoDAQ Pro/Lite coverage. +2. Show filename and size, allowing replacement or closing before upgrade execution. Reuse existing firmware upload, device validation, confirmation, and pending-package cancellation APIs and business rules. +3. Show actual upload progress and allow upload cancellation. Retain existing behavior while the device processes the upload. Do not label HTTP upload percentage as installation or flashing progress. +4. Present confirmation in the inline area shown in the video. After confirmation, prevent repeated submission, file replacement, and cancellation. Retain the power reminder. +5. **Keep the existing success criterion: a successful response from the device upgrade confirmation API resets state and reports success through the existing flow.** Do not add restart, reconnection, firmware reread, or target-version comparison as completion conditions, or change the device protocol as part of this interface adjustment. +6. Closing details within the current application session preserves active task state; reopening restores its display. Retain existing upload/API error handling and pending-package replacement rules. Retries require an explicit user action; do not automatically repeat upgrade confirmation. +7. Prevent starting firmware upgrade on a device that is acquiring or playing. Lock relevant upgrade actions during its upgrade flow. Closing details does not itself cancel the upgrade. + +### First-round decisions + +| Question | User decision | +| --- | --- | +| Q1 Removal semantics | Clear-all matches individual Remove. | +| Q2 Concurrency and feedback | Accept the recommendation: snapshot the list, recheck before execution, skip devices returning online, continue and summarize partial failures, and disable on an empty list. | +| Q3 Version meaning and unavailable states | Accept actual SDK/runtime versions, two fixed rows, and corresponding unavailable states. | +| Q4 Upgrade progress | Accept actual upload progress; keep existing device-processing behavior. | +| Q5 Upgrade completion | Keep the original success criterion rather than adding reconnection verification. | +| Q6 Cancellation, closing, and device use | Accept upload cancellation, locking after confirmation, preserved state on close, and preventing startup during acquisition or playback. | + +## Implementation acceptance scope + +- Refresh appears on the right side of Devices and retains existing behavior. Offline receives the clear-all entry without reordered lists or selection columns. +- Cover retained slots by default, selected slot deletion, references from other projects, devices returning online during confirmation, partial failures, empty lists, and repeated clicks. Preserve individual Remove behavior. +- Cover an available NI version, an installed NI plugin with no readable version, and an absent NI plugin. Verify actual version provenance and reject accidental use of plugin package versions. +- Cover collapsed firmware editing, file selection and replacement, cancelled upload, validation failure, pending packages, inline confirmation, confirmation failure and success, repeated clicks, closing and reopening, and acquisition/playback restrictions. +- Verify that successful confirmation follows the existing success flow. Do not interpret completed HTTP upload as completed device flashing or add simulated installation progress. +- During implementation, run relevant frontend/backend incremental checks. When the environment permits, perform physical SonoDAQ integration and record the runtime instance, native materials, and plugin versions. Report simulated and physical-device verification separately. + +Implementation and targeted automated checks are complete. Windows interface and physical SonoDAQ testing have been performed; the verification record distinguishes observed hardware results from automated coverage and checks not performed. + +## Repository and workspace + +- Only OpenTest is modified. Implementation branch: `feature/hardware-device-actions-implementation`, based on `origin/main` at `17f7574f9764a5a18c1f04adf85eaa932f7edae9` when created. +- NativeDriver `origin/release/v2.5.0` has been updated to `a529bc7`. It is currently an inspected dependency without a new modification branch. +- The public SonoDAQ plugin and internal NI plugin supply version information. The internal NI capability is not yet in that repository's `origin/main`. Before changing it, resolve prerequisite interfaces and repository scope, then create its development worktree. +- Routine layout and interaction changes do not require an ADR. Settled domain definitions are recorded according to the repository's CONTEXT.md convention; operational rules remain in this specification. diff --git a/docs/specs/hardware-device-actions.zh-CN.md b/docs/specs/hardware-device-actions.zh-CN.md new file mode 100644 index 00000000..34e38c2a --- /dev/null +++ b/docs/specs/hardware-device-actions.zh-CN.md @@ -0,0 +1,97 @@ +# 硬件配置:设备操作与固件升级 + +[English](hardware-device-actions.md) + +Status: implemented; verification recorded + +本规格记录 grill-with-docs 访谈已确认的六项产品决策。用户随后授权在新 worktree、新分支实施并实测。结果与验证边界见[验证记录](../verification/hardware-device-actions.zh-CN.md)。 + +## 已明确的需求 + +| 编号 | 要求 | 界面边界 | +| --- | --- | --- | +| a | 将刷新按钮从 Offline 栏移动到 Devices 标题栏右侧。 | 按图 1 放在添加与同步入口之间,复用现有刷新行为。 | +| b | 在 Offline 标题栏右侧增加整批清空入口。 | 清空入口采用扫把图标,保持现有列表、折叠和页面布局,不增加选择列。删除语义与单条 Remove 一致。 | +| d | 在 Protocol 表头增加详情图标,鼠标悬停时浮层展示协议/SDK 名称与版本。 | 首要覆盖 SonoDAQ SDK 和 NI-DAQmx;图 2 中的版本数值为展示示例。 | +| e | SonoDAQ 详情中移除独立 Firmware OTA 栏,将 Upgrade 入口放到 Firmware Version 同行。 | 按图 3 和补充视频提供行内交互。 | + +用户未提出 c 项。截图中其他强调区域不自动扩展为本次改动要求;视频和图片中的 Demo 字样属于参考内容。 + +## 视频中的交互 + +参考用户提供的约 17 秒交互视频。 + +1. 默认仅显示 Firmware Version 与 Upgrade 按钮。 +2. 点击 Upgrade 后,在下方展开文件选择条,包含文件选择、文件名、升级按钮和关闭入口。 +3. 选定文件后显示文件名与大小,并允许替换。 +4. 点击升级后显示行内重启确认及保持供电提示,提供 Upgrade & Restart 与 Cancel。 +5. 执行期间锁定相关操作,显示进度及供电提示。 +6. 完成后收起编辑区,在版本行显示结果。 + +视频展示了 Installing 百分比和演示完成状态。用户已确认采用其行内交互结构;上传展示真实进度,设备处理和成功判据沿用既有逻辑,不引入设备刷写百分比或重连后的完成验证。 + +## 已核实的现有行为 + +- 刷新会主动更新设备状态并重新读取列表,还可能触发模块变化确认与项目通道刷新。 +- Offline 当前只有逐项 Remove。删除的是共享设备记录及物理通道,可能影响其他工程;默认保留工程通道槽位并解除绑定。现有“删除虚拟通道”选项实际还会删除关联的物理通道槽位,不能将其解释为删除数学通道。 +- 单项删除服务未在执行时重新校验 Offline 状态;整批操作需要明确并发恢复在线时的处理规则。 +- SonoDAQ 已有固件上传、校验、确认及取消待确认包的流程,OpenTest 通过 HTTP 代理转发到设备。当前百分比只代表前端向后端上传;后端完整收件后才转发设备,因此 100% 不表示设备已收件或刷写完成。未找到设备刷写进度查询链路。 +- 现有界面在设备确认命令返回成功后立即提示成功,没有核实该响应是否代表刷写完成,也没有等待重启或重连。已有固件版本查询接口,升级后尚未主动刷新。状态以设备身份保存,关闭详情不会自动取消上传。 +- 原生依赖已有通用设备 SDK 版本查询入口,上层尚需接通。SonoDAQ 插件返回编译时 SDK 版本;NI-DAQmx 返回运行库查询的版本,均不同于插件包版本。 +- 本节描述实施前基线;当前运行时和真机验证结果单独记录。 + +## 已确认的行为 + +### Offline 整批清空 + +1. 一次确认处理整批设备;删除含义、默认值、关联通道选项和跨工程处理均与现有单条 Remove 一致。确认框说明关联工程可能受影响;本次不另行改造单条 Remove 的删除策略。 +2. 默认保留项目通道槽位并解除物理绑定。用户选择现有删除关联槽位选项时,沿用单条 Remove 的处理规则;不将该选项重新解释为数学通道删除。 +3. 以点击清空时的 Offline 名单为范围,不自动纳入确认期间新增的离线设备。执行前重新检查各设备的当前状态,已恢复在线的跳过。 +4. 单项失败继续处理其他设备,最后汇总成功、跳过与失败;成功项不因其他项失败而回滚。完成后刷新设备和受影响的通道显示。 +5. 执行期间防止重复提交;没有离线设备时清空按钮置灰。按钮操作不触发 Offline 栏的折叠切换。 + +### Protocol 详情 + +1. 鼠标悬停在 Protocol 表头旁的详情图标上时显示浮层,移开后关闭。展示 SonoDAQ SDK,安装 NI 设备插件时才展示 NI-DAQmx。 +2. SonoDAQ SDK 采用插件编译时使用的 SDK 版本;NI-DAQmx 采用其运行库查询到的版本。展示值来自实际查询,不使用插件包版本或截图中的示例数值代替。 +3. NI 插件已安装但无法读取版本时,版本列显示 `--`。SonoDAQ SDK 无法提供版本时显示自身状态。打开浮层不会自动启用已禁用或未加载的插件。 +4. 信息属于设备接入软件,不要求存在在线设备;浮层沿用当前界面样式与语言机制。 + +### SonoDAQ 固件升级 + +1. 移除独立 Firmware OTA 折叠栏;在 Firmware Version 同行提供 Upgrade,点击后展开下方行内操作区,模块信息区保留。既有 SonoDAQ Pro/Lite 适用范围不变。 +2. 文件选择区显示文件名和大小,并允许在未执行升级时替换或关闭。复用现有文件上传、设备校验、确认与取消待确认包的接口及业务规则。 +3. 上传阶段展示真实上传进度并允许取消。上传后设备处理阶段保留现有逻辑,不把 HTTP 上传百分比标成设备安装或刷写百分比。 +4. 将确认操作放入视频所示的行内确认区。确认升级后禁止重复提交、替换文件和取消;保留供电提示。 +5. **成功判据保持原逻辑:设备升级确认接口返回成功后,即按现有流程重置状态并提示成功。** 本次不增加等待重启、重连、读回版本或比对目标版本的成功条件,也不借此次界面调整改变设备端协议。 +6. 当前运行会话内关闭详情不丢弃正在进行的任务状态,再次打开恢复展示。上传或接口失败沿用现有错误处理和待确认包替换规则,由用户明确重试,不自动重复确认升级。 +7. 设备正在采集或播放时禁止启动该设备的固件升级;设备进入升级流程后锁定相关升级操作。关闭详情本身不表示取消升级。 + +### 第一轮确认记录 + +| 问题 | 用户决定 | +| --- | --- | +| Q1 删除语义 | 清空与单条 Remove 保持一致。 | +| Q2 并发与反馈 | 按推荐:名单快照、执行前检查、恢复在线跳过、部分失败继续并汇总、空列表置灰。 | +| Q3 版本口径与缺失状态 | 按推荐:真实 SDK/运行库版本、固定两行及对应不可用状态。 | +| Q4 升级进度 | 接受真实上传进度;设备处理阶段保持现有逻辑。 | +| Q5 升级完成 | 保持原有成功判据,不采用新增的重连验证流程。 | +| Q6 取消、关闭和占用限制 | 按推荐:上传可取消、确认后锁定、关闭保留状态、采集或播放期间禁止启动。 | + +## 实施验收范围 + +- 刷新入口在 Devices 标题右侧,行为与旧入口一致;Offline 仅新增清空入口,无列表重排或选择列。 +- 批量清空覆盖默认保留槽位、选择删除槽位、跨工程引用、确认期间恢复在线、部分失败、空列表及重复点击;单条 Remove 的既有行为保持一致。 +- 版本浮层覆盖能读取 NI 版本、NI 插件已安装但读不到版本、NI 插件未安装这三种情况;核对实际版本来源,避免误用插件包版本。 +- 固件界面覆盖初始收起、文件选择与替换、上传取消、校验失败、待确认包、行内确认、确认失败及成功、重复点击、关闭后重开,以及采集或播放占用限制。 +- 回归断言确认接口成功后沿用旧成功流程;上传完成不得被误认为设备刷写完成,不增加模拟安装进度。 +- 实施时按仓库规范运行相关前后端增量检查;条件具备时补充真实 SonoDAQ 联调,记录实例、原生材料及插件版本。模拟验证与真机验证分别报告。 + +实现及相关自动化检查已完成,并进行了 Windows 界面与物理 SonoDAQ 实测。验证记录分别列出真机观察、自动化覆盖及未执行项目。 + +## 仓库与工作区 + +- 实际修改仓库仅为 OpenTest。实现分支 `feature/hardware-device-actions-implementation`,创建时基于 `origin/main` 的 `17f7574f9764a5a18c1f04adf85eaa932f7edae9`。 +- NativeDriver 的 `origin/release/v2.5.0` 已更新至 `a529bc7`,当前作为能力核对依赖,未创建修改分支。 +- 公共 SonoDAQ 插件及内部 NI 插件是版本信息来源。内部 NI 能力尚不在该仓 `origin/main`;若需要修改对应实现,须先明确前置接口与仓库范围,再创建其开发 worktree。 +- 普通布局与交互调整不单独建立 ADR。已确认术语按仓库 CONTEXT.md 的约定记录,操作规则保留在本规格。 diff --git a/docs/verification/hardware-device-actions.md b/docs/verification/hardware-device-actions.md new file mode 100644 index 00000000..9afa0c94 --- /dev/null +++ b/docs/verification/hardware-device-actions.md @@ -0,0 +1,67 @@ +# Hardware device actions verification + +[简体中文](hardware-device-actions.zh-CN.md) · [Specification](../specs/hardware-device-actions.md) + +Verified on 2026-11-17. Follow-up testing completed on 2026-11-18. + +## Runtime and provenance + +- Isolated OpenTest source runtime on Windows x64 with a physical SonoDAQ Pro and matching native runtime materials. +- SonoDAQ plugin: public OpenTest-Plugins commit `82cffc3`, built in a detached dependency worktree using VS 2022, SDK `1.4.0`, and the feature worktree's native framework headers. DLL, SDK dependencies, and package manifest were staged together through `OPENTEST_NATIVE_PLUGIN_BIN_ROOT`. +- NI plugin: existing Windows internal-plugin binary, not modified. Its SDK version export exists; its bundled `nicaiu.dll` file version is `25.3.1f0`, but the runtime version APIs return `-200090`. Neither standard NI-DAQmx installation registry key was present. File version is not substituted for a successful runtime query. + +The initial test environment could not open a project because the native certificate import returned `13300004`. With matching native materials, the project opened successfully. Detailed licensing diagnostics remain in the local test record. + +## Observed Windows and physical-device results + +| Check | Result | +| --- | --- | +| Refresh placement and repeated refresh | Pass: header action is between add and synchronization; device rows and Offline structure remain after three refreshes. | +| Protocol popover | Pass: SonoDAQ SDK `1.4.0`; NI-DAQmx independently shows Read failed for the actual failed native query. No reference-image values are used. | +| Offline confirmation and cancellation | Pass: confirmation lists one offline device and the shared-channel impact/legacy deletion option; cancel retains it. | +| Offline clear | Pass: default option removes the single offline monitor record; summary is removed 1, skipped 0, failed 0. Online devices remain. Empty-list clear is disabled. | +| Firmware placement | Pass: Upgrade is beside Firmware Version, with no separate Firmware OTA section; module information remains. | +| File selection | Pass: actual Windows file dialog selects the supplied file and the editor shows filename and `61.2 MB`. | +| Upload and pending cancellation | Pass: actual requests reach the physical SonoDAQ; upload validation reveals inline confirmation. Pending-package cancellation was sent before the later upload. | +| Close and reopen | Pass: the validated package, size, and inline confirmation remain after closing and reopening device details within the same application session. | +| Confirmation lock and success | Pass: while the confirm request runs, entry, file/editor close, confirm, and cancel are disabled and the power reminder remains. Successful confirmation collapses the editor and shows Operation successful. | +| Subsequent device query | Pass: firmware query returns HTTP 200/code 0, `V1.2.8`, the same physical serial, and an updated firmware build timestamp. | + +Firmware package version V1.2.8, 64,200,304 bytes. + +Success retains the approved existing meaning: the device confirmation API returns success. Device flashing percentage, restart/reconnection completion, and target-version comparison are not new application completion conditions. The package and original device both report V1.2.8; the later query is supplementary evidence, not a changed success rule. + +## Automated checks + +- Backend: 30 passing tests across `DeviceProtocolVersionServiceTest` (3), `OfflineDeviceClearTest` (2), `DeviceServiceOpenDaqUpdateTest` (13), and `AudioJNIBridgeFinitePlaybackV1Test` (12). Covers per-item recheck, duplicate/missing IDs, failure continuation, legacy deletion delegation, version availability, and activity guards. +- Frontend: 22 passing tests across hardware rendering, protocol versions, device information, upgrade component, and upgrade store. Covers actual Element Plus table rendering through repeated array replacement, inline confirmation, duplicate confirmation, preserved store state, cancellation races, and selected binary reuse/size. +- Incremental backend package, frontend SDK build, and frontend production build pass. Targeted ESLint passes. Frontend build requires a 6 GB Node heap in this environment. +- Full frontend typecheck completes with two existing errors at `src/composables/dashboard/use-grpc-exec.ts:677` (`length` on `unknown`); that file is unchanged. No new feature type errors remain. +- Real testing caught and fixed a cached-VNode table patch failure, misplaced locale keys, and the mismatch between file-loader `size` and the store's former `fileSize` assumption. The table and size regressions were observed failing before their fixes and passing afterward. + +Relevant backend command: + +```sh +cd apps/backend +mvn -pl crydaq-server -am -Dskip.crowdin.download=true -Dtest=DeviceProtocolVersionServiceTest,OfflineDeviceClearTest,DeviceServiceOpenDaqUpdateTest,AudioJNIBridgeFinitePlaybackV1Test -Dsurefire.failIfNoSpecifiedTests=false package +``` + +The final two activity-guard tests were added afterward and verified with the same Maven test selection on `crydaq-service -am`; the packaged production backend source was unchanged. + +## Limits and local evidence + +NI successful version reporting needs a machine with a working NI-DAQmx installation. Actual hardware acquisition/playback exclusion, mid-transfer network cancellation, disconnect/error injection, multi-project channel-slot cleanup, and batch partial failures were not exercised on physical hardware; relevant delegation/concurrency guards have automated coverage, not a claim of full hardware acceptance. + +Local test scripts and evidence remain under `.runtime/tasks/2026-11-17-hardware-device-actions` in both worktrees, outside Git. Key screenshots: `hardware-three-refreshes.png`, `protocol-sdk-real.png`, `ota-inline-confirm-ready.png`, `ota-confirm-outcome.png`, `offline-clear-confirm.png`, and `offline-cleared.png`. CDP screenshots show the actual renderer; native-dialog selection used Windows controls in the interactive session. No simulated device or mocked response is counted as real testing. + +## Manual testing follow-up + +On 2026-11-18 the user requested a broom-shaped clear-all icon and hover activation for protocol details. Offline clear now uses `BrushCleaning`; Protocol opens on pointer hover and closes after the pointer leaves. Targeted ESLint, formatting, three existing hardware/protocol tests, and the incremental production build passed. The Windows test client was updated; its rendered SVG uses the broom icon, and actual mouse movement showed the SDK popover without a click. Moving away hid it. Evidence: `protocol-hover-broom.png`. + +Virtual/math-channel Vp configuration was already present in baseline `17f7574f`; the input, persistence/validation, and tests predate this feature. No math-channel frontend or virtual-channel backend source was changed in this task. + +A second pass on the updated Windows client completed three device refreshes and verified the broom icon, disabled clear action for an empty list, and hover display and dismissal of the Protocol popover. A single batch confirmation used three temporary records in the isolated database. Cancelling kept all three. On a second confirmation, one record was set online before submission. The result was two removed, one skipped, and zero failed. The temporary records were cleaned up afterward. + +The physical SonoDAQ validated the supplied `61.2 MB` package. Closing and reopening details restored inline confirmation. Cancelling the pending package reset the editor. This pass ended at cancellation. The earlier physical confirmation remains the upgrade completion evidence. All 22 relevant frontend tests passed again. Screenshots: `retest-protocol-hover.png`, `retest-offline-three-result.png`, `retest-firmware-confirm.png`, and `retest-firmware-cancelled.png`. + +The latest Protocol display uses the NI plugin installation state. Automated checks verify that an absent plugin has no row and a readable version is displayed. Windows testing with the installed NI plugin verified `--` when its driver query failed, alongside SonoDAQ SDK `1.4.0`. The popover closed on pointer exit. The updated frontend and backend builds passed, with 27 frontend tests and 30 backend tests passing. Screenshot: `retest-ni-version-placeholder.png`. diff --git a/docs/verification/hardware-device-actions.zh-CN.md b/docs/verification/hardware-device-actions.zh-CN.md new file mode 100644 index 00000000..6d1c676f --- /dev/null +++ b/docs/verification/hardware-device-actions.zh-CN.md @@ -0,0 +1,67 @@ +# 硬件设备操作验证记录 + +[English](hardware-device-actions.md) · [需求规格](../specs/hardware-device-actions.zh-CN.md) + +验证日期为 2026-11-17。 2026-11-18 完成后续复测。 + +## 运行实例和材料来源 + +- Windows x64 上的独立 OpenTest 源码实例,使用物理 SonoDAQ Pro 和配套的原生运行材料。 +- SonoDAQ 插件来自公开插件仓 `82cffc3`,在 detached 依赖 worktree 使用 VS 2022、SDK `1.4.0` 和本需求宿主原生框架头文件构建。插件 DLL、SDK 依赖和清单通过 `OPENTEST_NATIVE_PLUGIN_BIN_ROOT` 成套投递。 +- NI 使用现有 Windows 内部插件二进制,未修改。版本查询导出存在,随包 `nicaiu.dll` 文件版本为 `25.3.1f0`,但驱动版本查询返回 `-200090`,两个常规 NI-DAQmx 安装注册表项均不存在。界面不使用文件版本冒充查询成功。 + +测试环境最初因原生证书解析失败(`13300004`)而无法创建工程。使用配套原生材料后,工程正常打开。许可证相关诊断记录保留在本地。 + +## Windows 和物理设备观察结果 + +| 检查 | 结果 | +| --- | --- | +| 刷新入口与连续刷新 | 通过:位于 Devices 的添加与同步之间,连续刷新三次后设备行和 Offline 结构正常。 | +| Protocol 浮层 | 通过:SonoDAQ SDK 显示实际 `1.4.0`;NI 查询失败单独显示“读取失败”,不影响另一行。 | +| Offline 确认与取消 | 通过:确认范围为 1 个离线设备,包含跨工程影响说明和既有关联通道选项;取消后保留设备。 | +| Offline 清空 | 通过:默认选项删除该离线显示器记录,汇总删除 1、跳过 0、失败 0;在线设备保留,空列表按钮置灰。 | +| 固件入口位置 | 通过:Upgrade 与 Firmware Version 同行,无独立 Firmware OTA 折叠栏,模块信息保留。 | +| 固件选择 | 通过:实际 Windows 文件对话框选择用户给定文件,界面显示文件名及 `61.2 MB`。 | +| 上传与待确认取消 | 通过:实际请求转发到物理 SonoDAQ,设备校验后出现行内确认;后续再次上传前执行过待确认包取消请求。 | +| 关闭重开 | 通过:同一应用会话内关闭并重开设备详情后,已校验文件、大小和行内确认仍保留。 | +| 确认锁定和成功 | 通过:确认执行中升级入口、文件/编辑区关闭、确认和取消均锁定,并显示供电提示;成功后编辑区收起,显示 Operation successful。 | +| 随后查询设备 | 通过:固件查询 HTTP 200/code 0,仍为 `V1.2.8` 和同一物理序列号,固件构建时间戳已更新。 | + +验证使用 V1.2.8 固件包,大小为 64,200,304 字节。 + +成功含义保持用户确认的既有规则:设备升级确认接口返回成功。未把刷写百分比、重启/重连结束或目标版本比对新增为应用完成条件。设备原版本与给定包均为 V1.2.8;随后查询只作为补充证据,不改变成功规则。 + +## 自动化检查 + +- 后端 30 项通过:`DeviceProtocolVersionServiceTest` 3 项、`OfflineDeviceClearTest` 2 项、`DeviceServiceOpenDaqUpdateTest` 13 项、`AudioJNIBridgeFinitePlaybackV1Test` 12 项。覆盖逐项重查、重复/已删除 ID、失败继续、委托既有删除逻辑、版本可用性和设备占用守卫。 +- 前端 22 项通过,覆盖硬件表格、协议版本、设备信息、升级组件和升级状态库。包含实际 Element Plus 表格在连续替换数组后的渲染、行内确认、重复确认、状态保留、取消竞态、选中文件复用和大小读取。 +- 后端增量打包、前端 SDK 构建、前端生产构建通过,改动文件 ESLint 通过。前端构建在本机需要 6 GB Node 堆。 +- 全量前端类型检查仍有原文件 `src/composables/dashboard/use-grpc-exec.ts:677` 的两处 `unknown.length` 错误,该文件未改动;没有遗留本需求新增类型错误。 +- 实测发现并修复了缓存 VNode 导致表格补丁失败、翻译键层级错误,以及文件读取器 `size` 与状态库原先读取 `fileSize` 不一致的问题。表格和文件大小回归均先观察到失败,再验证修复通过。 + +后端相关命令: + +```sh +cd apps/backend +mvn -pl crydaq-server -am -Dskip.crowdin.download=true -Dtest=DeviceProtocolVersionServiceTest,OfflineDeviceClearTest,DeviceServiceOpenDaqUpdateTest,AudioJNIBridgeFinitePlaybackV1Test -Dsurefire.failIfNoSpecifiedTests=false package +``` + +最后两项占用守卫测试在打包后添加,以同类 Maven 测试选择在 `crydaq-service -am` 执行通过;打包的后端生产源码未再变化。 + +## 验证边界与本地证据 + +NI 版本成功展示仍需在 NI-DAQmx 可正常工作的环境验证。真机采集/播放期间的升级拦截、传输中断网取消、设备断连/故障注入、多工程槽位清理和批量部分失败未在物理环境逐项执行;相关委托和并发守卫有自动化覆盖,不等同于完整真机验收。 + +脚本和证据保留在两端 worktree 的 `.runtime/tasks/2026-11-17-hardware-device-actions`,不进入 Git。主要截图为 `hardware-three-refreshes.png`、`protocol-sdk-real.png`、`ota-inline-confirm-ready.png`、`ota-confirm-outcome.png`、`offline-clear-confirm.png`、`offline-cleared.png`。CDP 截图来自实际渲染器;原生文件选择通过 Windows 交互会话中的真实控件完成。未将模拟设备或伪造响应计为实测。 + +## 手工测试反馈调整 + +2026-11-18 用户要求清空入口使用扫把图标,Protocol 详情改为悬停显示。Offline 清空现采用 `BrushCleaning`;鼠标悬停时打开版本浮层,移开后关闭。相关 ESLint、格式检查、3 项现有硬件/协议测试和前端增量生产构建通过。Windows 测试客户端已更新,实际 SVG 为扫把图标,实际鼠标移动验证了无需点击即可显示版本浮层,移开后隐藏。证据:`protocol-hover-broom.png`。 + +虚拟/数学通道 Vp 配置已存在于基线 `17f7574f`,包含输入框、保存/校验和测试。本任务未修改数学通道前端或虚拟通道后端源码。 + +更新后的 Windows 客户端复测了连续三次刷新、扫把图标、空列表禁用,以及 Protocol 悬停显示和移开关闭。批量清空使用隔离数据库中的三条临时记录。取消确认后全部保留。再次确认期间将一条设为在线,结果为删除 2 条、跳过 1 条、失败 0 条。测试结束后已清理临时记录。 + +物理 SonoDAQ 校验了指定的 `61.2 MB` 固件。关闭重开详情后恢复行内确认,取消待确认包后编辑区重置。本轮实测到取消为止,前一次真机确认结果仍作为升级完成证据。相关前端测试复跑 22 项通过。截图包括 `retest-protocol-hover.png`、`retest-offline-three-result.png`、`retest-firmware-confirm.png` 和 `retest-firmware-cancelled.png`。 + +Protocol 浮层按 NI 插件安装状态显示。自动化检查验证了未安装时隐藏该行,以及版本可读时显示实际版本。Windows 实测验证了 NI 插件已安装但驱动查询失败时显示 `--`,同时 SonoDAQ SDK 显示 `1.4.0`。鼠标移开后浮层关闭。更新后的前后端构建通过,前端 27 项和后端 30 项测试通过。截图为 `retest-ni-version-placeholder.png`。