feat(scanner): 完善补扫、执行监控及资源释放

完善扫描流式预览、成果归档与PLY/STL查看、补扫历史、执行步骤及日志展示,支持局域网访问和改名节点的原始组件识别。修复试运行终止后的占用释放及未采集时重复暂停SDK的问题,增加终止中交互与回归验证。

验证:后端1114项通过、18项既有跳过;前端109项通过,类型检查及构建通过;Python脚本54项通过;模拟扫描设备7组试运行/终止接口回归通过。
This commit is contained in:
lixiaolong 2026-10-26 11:04:07 +08:00
parent cfff7295a6
commit 6f8a40644c
134 changed files with 9082 additions and 530 deletions

View File

@ -7,3 +7,7 @@
- 用户明确要求的永久在线模拟机器人 `am-freescan-sim-robot` 和模拟设备 `am-freescan-sim-agv` 继续保留,除非用户另行要求删除。
- 2026-10-22 用户另行要求创建并保留两条全流程演示数据:前缀 `DEMO-20261022-091650`,任务 `T-20261022-0005`、`T-20261022-0006`,导入批次 `IB-20261022-0009`。对应测试用例、样品、夹具、技术资料、执行日志和输出均供用户查看,不纳入开发验证自动清理;清单见 `docs/full-flow-demo-20261022.json`。
- 不删除运行配置、凭据、来源指纹、实际业务数据或回归测试代码。不要输出 `.local/runtime.json` 中的敏感信息。
- 2026-10-23 用户要求保留真实扫描待运行数据:前缀 `REAL-SCAN-20261023-001`,任务 `T-20261023-0001`,导入批次 `IB-20261023-0001`;清单见 `docs/real-scan-ready-20261023.json`。对应样品、夹具预设、用例、流程版本及真实扫描工位 `am-freescan-station-001` / 设备 `am-freescan-scanner-001` 不纳入验证数据清理。准备脚本不能自动执行扫描,也不能代替用户确认实物与装夹。
- 上述真实任务的用户首次运行在 SDK 三维快照报 `scene_data_unavailable`,失败执行 `2113504832933294082` 保留;旧任务已停止并取消以释放占用。修正版为 `T-20261023-0002`(`REAL-SCAN-20261023-001-R1`,批次 `IB-20261023-0002`,流程 V3),增加独立 Trak 工程并在停止采集前请求快照,同样保留且不纳入验证清理。新任务必须重新由操作人确认收样与装夹,不能复制这些物理确认状态。
- 2026-10-23 用户再次要求创建并保留两条现场测试任务:`T-20261023-0003`(流式预览采集)、`T-20261023-0004`(网格化及PLY/STL导出),前缀 `USER-SCAN-20261023`、批次 `IB-20261023-0003`;清单为 `docs/user-scan-two-tasks-20261023.json`。关联用例、流程版本、样品和导入文件不纳入开发验证清理;两条任务都不调用已知故障的原始场景快照接口。准备脚本为 `scripts/prepare_user_scan_pair.py`,不自动确认实物或启动设备,用户按顺序现场测试。
- `T-20261023-0003` 被用户运行后因创建工程时仍在采集而失败,已保留失败记录并取消释放占用;对应流式测试替代任务为 `T-20261023-0005`(`USER-SCAN-20261023-STREAM-R1`,批次 `IB-20261023-0004`)。当前供用户测试的两条任务为 `0005` 和 `0004`,均绑定 V2,创建工程前先停止采集并等待成功回执;两条任务及旧失败历史全部保留,不自动清理。

View File

@ -29,6 +29,8 @@ public interface ResourceRobotMapper extends BaseMapper<ResourceRobot> {
int updateAgvRuntimeStatus(ResourceRobot robot);
int updateHttpScannerState(ResourceRobot robot);
List<String> lockByRobotIds(@Param("robotIds") List<String> robotIds);
int markHeartbeatExpiredOffline(@Param("id") String id,

View File

@ -12,11 +12,14 @@ import org.springframework.stereotype.Service;
public class ResourceRobotExecutionTargetResolver implements RobotExecutionTargetResolver {
private final ResourceRobotEndpointResolver endpointResolver;
private final ResourceRobotStateProperties stateProperties;
private final com.cmvr.scanner.ScannerResourceSynchronizer scannerResources;
@Override
public RobotExecutionTarget resolve(String robotId) {
String normalized = StringUtils.trimToNull(robotId);
if (!stateProperties.isVirtualRobot(normalized)) {
if (scannerResources.handles(normalized)) {
scannerResources.validateTarget(normalized);
} else if (!stateProperties.isVirtualRobot(normalized)) {
endpointResolver.resolve(normalized);
}
return new RobotExecutionTarget(normalized);

View File

@ -40,7 +40,7 @@ public class ScannerHttpClient {
URI uri=new URI("http",null,settings.getHost(),settings.getPort(),op.route(id),null,null);
HttpRequest.Builder builder=HttpRequest.newBuilder(uri).timeout(Duration.ofMillis(Math.max(1,timeoutMs)))
.header("Accept",op.binary()?"*/*":"application/json");
if(op!=ScannerOperation.METADATA)builder.header("X-Api-Key",settings.getApiKey());
if(op!=ScannerOperation.METADATA)builder.header("Authorization","Bearer "+settings.getApiKey());
if(op.control())builder.header("Content-Type","application/json; charset=utf-8")
.POST(HttpRequest.BodyPublishers.ofString(body,StandardCharsets.UTF_8));
else builder.GET();

View File

@ -108,6 +108,17 @@ public class ScannerMonitoringService {
return status;
}
public record Frame(byte[] bytes,Map<String,List<String>> headers) {}
public ScannerPreviewStream stream(JsonNode binding) {
status(binding);
var source=scanner.binary(ScannerOperation.PREVIEW_STREAM,null);
try{return new ScannerPreviewStream(source);}
catch(RuntimeException invalid){try{source.close();}catch(IOException ignored){}throw invalid;}
}
public long streamSequence(JsonNode binding,Frame frame) {
status(binding); // Validate the project after reading each complete frame, before publishing it.
try{return Long.parseLong(header(frame.headers(),"x-frame-sequence"));}
catch(Exception invalid){throw new ScannerException("invalid_frame","扫描流缺少有效帧编号",502);}
}
public Frame image(JsonNode binding) {
status(binding);
try(var binary=scanner.binary(ScannerOperation.PREVIEW_IMAGE,null)) {

View File

@ -0,0 +1,62 @@
package com.cmvr.scanner;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
/** Bounded multipart reader; one JPEG is retained and HTTP chunking is decoded by HttpClient. */
public final class ScannerPreviewStream implements AutoCloseable {
private final ScannerHttpClient.Binary source;
private final InputStream input;
private final String boundary;
public ScannerPreviewStream(ScannerHttpClient.Binary source) {
this.source=source;
String type=source.headers().entrySet().stream().filter(e->e.getKey().equalsIgnoreCase("content-type"))
.flatMap(e->e.getValue().stream()).findFirst().orElse("");
var match=java.util.regex.Pattern.compile("boundary=\"?([A-Za-z0-9_-]{1,100})\"?",java.util.regex.Pattern.CASE_INSENSITIVE).matcher(type);
if(!type.toLowerCase(Locale.ROOT).startsWith("multipart/x-mixed-replace")||!match.find())
throw new ScannerException("invalid_stream","扫描服务未返回有效MJPEG流",502);
boundary="--"+match.group(1); input=new BufferedInputStream(source.stream(),16384);
}
public ScannerMonitoringService.Frame next() throws IOException {
String line;
do {line=line();} while(line!=null&&line.isEmpty());
if(line==null||line.equals(boundary+"--"))return null;
if(!line.equals(boundary))throw new IOException("Invalid MJPEG boundary");
Map<String,List<String>> headers=new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int total=0;
while(true) {
line=line(); if(line==null)throw new EOFException("Truncated MJPEG headers");
total+=line.length()+2; if(total>16384)throw new IOException("MJPEG headers too large");
if(line.isEmpty())break;
int colon=line.indexOf(':'); if(colon<=0)throw new IOException("Invalid MJPEG header");
String key=line.substring(0,colon).trim(),value=line.substring(colon+1).trim();
if(headers.putIfAbsent(key,List.of(value))!=null)throw new IOException("Duplicate MJPEG header");
}
int length;
try {length=Integer.parseInt(headers.getOrDefault("content-length",List.of("")).get(0));}
catch(NumberFormatException invalid){throw new IOException("Missing MJPEG length",invalid);}
if(length<4||length>8*1024*1024)throw new IOException("Invalid MJPEG length");
if(!headers.getOrDefault("content-type",List.of("")).get(0).equalsIgnoreCase("image/jpeg"))throw new IOException("Invalid MJPEG media type");
byte[] bytes=input.readNBytes(length);
if(bytes.length!=length)throw new EOFException("Truncated MJPEG frame");
if((bytes[0]&255)!=255||(bytes[1]&255)!=216||(bytes[length-2]&255)!=255||(bytes[length-1]&255)!=217)
throw new IOException("Invalid JPEG frame");
return new ScannerMonitoringService.Frame(bytes,headers);
}
private String line() throws IOException {
var bytes=new ByteArrayOutputStream(); int value;
while((value=input.read())!=-1) {
if(bytes.size()>=16384)throw new IOException("MJPEG header line too large");
if(value=='\n') {
byte[] raw=bytes.toByteArray();
if(raw.length==0||raw[raw.length-1]!='\r')throw new IOException("Invalid MJPEG line ending");
return new String(raw,0,raw.length-1,StandardCharsets.US_ASCII);
}
bytes.write(value);
}
if(bytes.size()!=0)throw new EOFException("Truncated MJPEG line");
return null;
}
@Override public void close() throws IOException {source.close();}
}

View File

@ -0,0 +1,100 @@
package com.cmvr.scanner;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.resource.config.ResourceRobotStateProperties;
import com.cmvr.resource.domain.ResourceDevice;
import com.cmvr.resource.domain.ResourceRobot;
import com.cmvr.resource.mapper.ResourceDeviceMapper;
import com.cmvr.resource.mapper.ResourceRobotMapper;
import com.fasterxml.jackson.databind.JsonNode;
import cmvr.quic_edge.v1.QuicEdge.ManagedDeviceState;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.UUID;
/** HTTP stations report real status; they never advertise the HTTP port as a gRPC endpoint. */
@Component
@RequiredArgsConstructor
public class ScannerResourceSynchronizer {
private final ScannerProperties settings;
private final ScannerHttpClient client;
private final ResourceRobotMapper robots;
private final ResourceDeviceMapper devices;
private final ResourceRobotStateProperties stateProperties;
public boolean handles(String robotId) {
return robotId != null && !robotId.isBlank() && robotId.equals(settings.getRobotId())
&& settings.getDeviceId() != null && !settings.getDeviceId().isBlank();
}
@Scheduled(initialDelayString = "${cmvr.scanner.resource-initial-delay-ms:3000}",
fixedDelayString = "${cmvr.scanner.resource-refresh-ms:5000}")
public synchronized void refresh() {
if (!handles(settings.getRobotId())) return;
ResourceRobot robot = robots.selectByRobotIdentity(settings.getRobotId());
if (robot == null || "1".equals(robot.getArchivedStatus())) return;
var matches = devices.selectByIdentity(settings.getRobotId(), settings.getDeviceId());
if (matches.size() > 1 || (!matches.isEmpty() && !Integer.valueOf(14).equals(matches.get(0).getDeviceKind()))) return;
JsonNode status = null;
try {
status = client.json(ScannerOperation.STATUS, null, null, 3000);
} catch (ScannerException unavailable) {
// A failed read must immediately remove readiness, without sending any control command.
}
Date now = new Date();
// During SDK work the supplier returns a compact busy response. Missing/null
// deviceOnline is unknown, not an explicit offline report. Keep the last
// measured device state, and update only the reachable HTTP station heartbeat.
boolean partialBusy = status != null && status.path("busy").asBoolean()
&& !status.path("deviceOnline").isBoolean()
&& !(status.path("initialized").isBoolean() && !status.path("initialized").asBoolean())
&& !"disconnected".equals(status.path("state").asText())
&& !status.path("restartRequired").asBoolean() && !status.path("stateUncertain").asBoolean();
if (partialBusy) {
ResourceRobot update = new ResourceRobot();update.setId(robot.getId());
update.setConnectStatus(robot.getConnectStatus());update.setStatus("3");
update.setLastHeartbeatTime(now);update.setUpdateTime(now);robots.updateHttpScannerState(update);
return; // Do not discover a device, enable it, or refresh its last measured online time.
}
boolean online = status != null && status.path("deviceOnline").asBoolean(false);
ResourceRobot update = new ResourceRobot();
update.setId(robot.getId());
update.setConnectStatus(online ? "1" : "0");
update.setStatus(!online ? "1" : status.path("scanning").asBoolean() || status.path("busy").asBoolean() ? "3" : "2");
update.setLastHeartbeatTime(status == null ? robot.getLastHeartbeatTime() : now);
update.setUpdateTime(now);
robots.updateHttpScannerState(update);
if (matches.isEmpty() && status == null) return;
ResourceDevice device = matches.isEmpty() ? new ResourceDevice() : matches.get(0);
if (matches.isEmpty()) {
device.setId(UUID.randomUUID().toString().replace("-", ""));
device.setRobotId(settings.getRobotId()); device.setDeviceId(settings.getDeviceId());
device.setDeviceName("FreeScan 现场扫描仪"); device.setDeviceKind(14);
device.setTypeName("FreeScan HTTP API"); device.setEnabled("1");
device.setCreateBy("scanner-http"); device.setCreateTime(now);
}
boolean fault = status != null && (status.path("restartRequired").asBoolean() || status.path("stateUncertain").asBoolean());
device.setOnlineStatus(online ? "1" : "0"); device.setHasError(fault ? "1" : "0");
device.setErrorMessage(fault ? "扫描服务要求重启或设备状态不确定,请核对现场" : online ? "" : "扫描仪离线或状态查询失败");
device.setHealthStatus(fault ? 3 : online ? 1 : 0);
ManagedDeviceState managerState = "0".equals(device.getEnabled()) ? ManagedDeviceState.MANAGED_DEVICE_STATE_DISABLED
: fault ? ManagedDeviceState.MANAGED_DEVICE_STATE_ERROR
: !online ? ManagedDeviceState.MANAGED_DEVICE_STATE_STOPPED
: status.path("scanning").asBoolean() || status.path("busy").asBoolean()
? ManagedDeviceState.MANAGED_DEVICE_STATE_RUNNING : ManagedDeviceState.MANAGED_DEVICE_STATE_READY;
device.setManagerState(managerState.getNumber());
device.setStatusUpdatedTime(now); if (status != null) device.setLastSeenTime(now);
device.setOfflineTime(online ? null : now); device.setUpdateBy("scanner-http"); device.setUpdateTime(now);
if (matches.isEmpty()) devices.insert(device); else devices.updateRuntimeState(device);
}
public void validateTarget(String robotId) {
ResourceRobot robot = robots.selectByRobotIdentity(robotId);
if (!settings.configured() || robot == null || "1".equals(robot.getArchivedStatus())
|| !"1".equals(robot.getConnectStatus()) || robot.getLastHeartbeatTime() == null
|| robot.getLastHeartbeatTime().before(stateProperties.heartbeatCutoff(new Date())))
throw new GlobalException("扫描工位离线或状态已过期,请检查扫描服务连接");
}
}

View File

@ -51,12 +51,24 @@ public class ScannerService {
ScannerCommandJournal.Entry active=journal.active(client.endpointKey());
if(active!=null){requireKnown(active);refresh(active,deadline);if(journal.active(client.endpointKey())!=null)throw new ScannerException("command_busy","上一控制任务尚未结束,请先等待任务终态",409);}
JsonNode status=query(ScannerOperation.STATUS,null,deadline);
if(expectedContext!=null&&(!expectedContext.path("sessionId").asText().equals(status.path("sessionId").asText())||!expectedContext.path("projectId").asText().equals(status.path("projectId").asText())))throw new ScannerException("project_changed","扫描工程已切换,不能为旧工程获取快照",409);
if(expectedContext!=null&&(!expectedContext.path("endpoint").asText(client.endpointKey()).equals(client.endpointKey())||!expectedContext.path("sessionId").asText().equals(status.path("sessionId").asText())||!expectedContext.path("projectId").asText().equals(status.path("projectId").asText())))throw new ScannerException("project_changed","扫描会话或工程已切换,不能继续原工程操作",409);
if(status.path("restartRequired").asBoolean())throw new ScannerException("restart_required","设备服务要求正常重启,禁止自动重连",409);
if(status.path("stateUncertain").asBoolean())throw new ScannerException("state_uncertain","设备状态不确定,请先核对任务和现场状态",409);
if(status.path("busy").asBoolean())throw new ScannerException("device_busy","扫描设备正在处理其他控制任务",409);
requestBudget(deadline);
journal.intent(key,client.endpointKey(),op,hash,body.toString(),owner);
// Pausing an idle SDK with no project can hang Sn3DPauseScanSync.
// Only explicit, healthy device status can confirm an idempotent stop;
// pending commands and project/session checks above still apply.
if(op==ScannerOperation.SCAN_STOP&&List.of("scanning","busy","stateUncertain","restartRequired").stream()
.allMatch(field->status.path(field).isBoolean()&&!status.path(field).booleanValue())) {
ObjectNode stopped=ScannerRequestValidator.JSON.createObjectNode();
stopped.put("state","succeeded");
stopped.putObject("result").put("scanning",false).put("alreadyStopped",true)
.put("confirmationSource","device_status");
journal.finish(key,true,stopped,null);
return accepted(journal.get(key));
}
JsonNode response;
try {response=client.json(op,null,body.toString(),requestBudget(deadline));}
catch(ScannerException error){
@ -73,10 +85,13 @@ public class ScannerService {
} finally {commandLock.unlock();}
}
public JsonNode executeAndWait(ScannerOperation op,ObjectNode body,String key,String owner,long timeoutMs) {
return executeBoundAndWait(op,body,key,owner,timeoutMs,null);
}
public JsonNode executeBoundAndWait(ScannerOperation op,ObjectNode body,String key,String owner,long timeoutMs,JsonNode expectedContext) {
long deadline=deadline(timeoutMs);
ObjectNode accepted;
while(true){
try {accepted=submit(op,body,key,owner,null,deadline);break;}
try {accepted=submit(op,body,key,owner,expectedContext,deadline);break;}
catch(ScannerException error){if(!Set.of("command_busy","device_busy").contains(error.scannerCode))throw error;sleep(deadline);}
}
return waitCommandUntil(accepted.path("commandKey").asText(),deadline);
@ -135,7 +150,9 @@ public class ScannerService {
if(deadline==0)return Math.max(1,settings.getRequestTimeoutMs());
long remaining=deadline-System.nanoTime();
if(remaining<=0)throw waitTimeout();
return Math.max(1,Math.min(settings.getRequestTimeoutMs(),TimeUnit.NANOSECONDS.toMillis(remaining)));
// HTTP timeouts use whole milliseconds; rounding down can expire the
// final query before the operation deadline and misclassify its result.
return Math.max(1,Math.min(settings.getRequestTimeoutMs(),TimeUnit.NANOSECONDS.toMillis(remaining-1)+1));
}
private JsonNode query(ScannerOperation operation,String id,long deadline) {
try {

View File

@ -15,6 +15,6 @@ public class ScannerStreamingConfiguration implements WebMvcConfigurer {
@Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (request.isAsyncStarted()) request.getAsyncContext().setTimeout(0);
}
}).addPathPatterns("/admin-api/cmvr/scanner/preview/stream");
}).addPathPatterns("/admin-api/cmvr/scanner/preview/stream", "/admin-api/lab/execution/scanner-view/stream");
}
}

View File

@ -0,0 +1,42 @@
package com.cmvr.scanner;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.*;
import com.cmvr.test.flow.runtime.operator.edge.WorkcellDeviceAdapter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
/** Only original-project continuation; never creates, loads or replaces a project. */
@Service @RequiredArgsConstructor
public class ScannerSupplementAdapter implements WorkcellDeviceAdapter {
private final ScannerWorkflowAdapter driver;
private final ScannerService scanner;
private final ScannerMonitoringService monitoring;
private final ScannerSupplementSignals signals;
@Override public boolean supports(ActionEnum action){return action==ActionEnum.SCANNER_SUPPLEMENT_PREPARE||action==ActionEnum.SCANNER_SUPPLEMENT_WAIT;}
@Override public void validateConfiguration(String robot,String device){driver.validateConfiguration(robot,device);}
@Override public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message){
var input=message.getInputParams();validateConfiguration(message.getRobotId(),input.getString("deviceId"));
if(message.getInstId()==null||message.getInstId().isBlank())throw new ScannerException("runtime_pending","补扫必须由任务工作台启动",409);
var expected=ScannerRequestValidator.parse(input.getString("expectedContextJson"));
var status=monitoring.status(expected);
if(message.getAction()==ActionEnum.SCANNER_SUPPLEMENT_PREPARE){
if(status.path("scanning").asBoolean()||status.path("busy").asBoolean())throw new ScannerException("device_busy","请先停止当前采集,再开始补扫",409);
String mesh=status.path("meshState").asText();
if(!java.util.Set.of("none","preview","confirmed").contains(mesh))throw new ScannerException("mesh_state_unknown","当前网格状态无法确认,不能补扫",409);
if(!"none".equals(mesh))scanner.executeBoundAndWait(ScannerOperation.MESH_UNDO,ScannerRequestValidator.parse("{}"),
ScannerService.hash("supplement-undo:"+message.getInstId()),"workflow:"+message.getInstId(),input.getLongValue("timeoutMs"),expected);
status=monitoring.status(expected);
if(!"none".equals(status.path("meshState").asText()))throw new ScannerException("mesh_not_cleared","原工程网格尚未撤销,不能开始补扫",409);
}else{
long end=System.nanoTime()+java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(input.getLongValue("durationMs"));
signals.collecting(message.getInstId());
while(System.nanoTime()<end&&!signals.finishRequested(message.getInstId())){
try{Thread.sleep(200);}catch(InterruptedException interrupted){Thread.currentThread().interrupt();throw new ScannerException("interrupted","补扫等待已中断",409);}
}
signals.processing(message.getInstId());
}
return TaskNodeExecuteResult.success(new JSONObject().fluentPut("projectId",expected.path("projectId").asText()));
}
}

View File

@ -0,0 +1,22 @@
package com.cmvr.scanner;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
/** Finish requests are durable and scoped to one immutable native execution. */
@Service @RequiredArgsConstructor
public class ScannerSupplementSignals {
private final StringRedisTemplate redis;
private String key(String instance){if(instance==null||instance.isBlank())throw new ScannerException("runtime_pending","补扫尚未启动",409);return "am-freescan:scanner-supplement:"+instance;}
public void collecting(String instance){redis.opsForValue().setIfAbsent(key(instance),"COLLECTING",Duration.ofDays(2));}
public boolean finishRequested(String instance){return "FINISH".equals(redis.opsForValue().get(key(instance)));}
public boolean isCollecting(String instance){return "COLLECTING".equals(redis.opsForValue().get(key(instance)));}
public void processing(String instance){redis.opsForValue().set(key(instance),"PROCESSING",Duration.ofDays(2));}
public void finish(String instance){
String value=redis.opsForValue().get(key(instance));
if(!"COLLECTING".equals(value)&&!"FINISH".equals(value))throw new ScannerException("not_collecting","当前不在补扫采集阶段,请等待或刷新状态",409);
redis.opsForValue().set(key(instance),"FINISH",Duration.ofDays(2));
}
}

View File

@ -14,6 +14,7 @@ public class ScannerWorkflowAdapter implements WorkcellDeviceAdapter {
private final ScannerProperties settings;
private final ScannerAccessService access;
private final ScannerMonitoringService monitoring;
private final ScannerResourceSynchronizer resources;
@Override public boolean supports(ActionEnum action){return action!=null&&ScannerOperation.forAction(action.getAction())!=null;}
@Override public void validateConfiguration(String robotId,String deviceId) {
if(!settings.configured())throw new ScannerException("not_configured","扫描服务地址、端口和密钥待配置",503);
@ -38,16 +39,24 @@ public class ScannerWorkflowAdapter implements WorkcellDeviceAdapter {
if(message.getInstId()==null || message.getInstId().isBlank()) {
var submitted=access.submit(op,body,commandKey);
result=service.waitCommand(submitted.path("commandKey").asText(),timeout);
}else if(input.containsKey("expectedContextJson")) {
var expected=ScannerRequestValidator.parse(input.getString("expectedContextJson"));monitoring.status(expected);
result=service.executeBoundAndWait(op,ScannerRequestValidator.parse(body),commandKey,"workflow:"+message.getInstId(),timeout,expected);
}else result=service.executeAndWait(op,ScannerRequestValidator.parse(body),commandKey,"workflow:"+message.getInstId(),timeout);
}
// A control's terminal acknowledgement can precede the next periodic status
// refresh. Refresh now so the next node sees measured post-command readiness.
if(op.control())resources.refresh();
JSONObject output=JSONObject.parseObject(result.toString());
output.put("responseJson",result.toString());
if(op.control()&&message.getInstId()!=null&&!message.getInstId().isBlank()) {
String key=ScannerService.hash(JSONObject.toJSONString(java.util.Arrays.asList(message.getInstId(),message.getItemId(),message.getItemOrder(),message.getItemOccurrence(),message.getNodeId(),message.getIterations(),message.getSubFlowExecutionId())));
try {
var context=monitoring.capture(op,key,message.getInstId(),message.getRobotId(),input.getString("deviceId"));
if(input.containsKey("expectedContextJson")&&context==null&&(op==ScannerOperation.SCAN_START||op==ScannerOperation.EXPORT))
throw new ScannerException("binding_invalid","补扫未能关联实时画面或成果,请保留原工程并检查设备状态",409);
if(context!=null)output.put("scannerContext",JSONObject.parseObject(context.toString()));
}catch(ScannerException error){output.put("scannerPreviewMessage",error.getMessage());}
}catch(ScannerException error){if(input.containsKey("expectedContextJson"))throw error;output.put("scannerPreviewMessage",error.getMessage());}
}
return TaskNodeExecuteResult.success(output);
}

View File

@ -75,6 +75,8 @@ public enum ActionEnum {
SCANNER_CAPABILITIES("EDGE", "SCANNER_CAPABILITIES", "读取扫描能力"),
SCANNER_METRICS("EDGE", "SCANNER_METRICS", "读取预览指标"),
SCANNER_WAIT("EDGE", "SCANNER_WAIT", "等待扫描设备任务"),
SCANNER_SUPPLEMENT_PREPARE("EDGE", "SCANNER_SUPPLEMENT_PREPARE", "核对原工程并准备补扫"),
SCANNER_SUPPLEMENT_WAIT("EDGE", "SCANNER_SUPPLEMENT_WAIT", "补扫采集,等待结束或到时"),
MOTOR_ENABLE("EDGE", "MOTOR_ENABLE", "电机使能"),
MOTOR_DISABLE("EDGE", "MOTOR_DISABLE", "电机去使能"),
MOTOR_HOME("EDGE", "MOTOR_HOME", "电机回零"),

View File

@ -92,6 +92,9 @@ public class TaskContext {
*/
private volatile boolean stopped = false;
/** All assigned devices acknowledged stop and interrupted nodes have exited. */
private volatile boolean deviceStopConfirmed = false;
/**
* 是否锁定终端(标识该终端是否被占用)
*/

View File

@ -54,10 +54,16 @@ public class TaskContextManager {
* 注销任务上下文(任务结束 / 终止后调用)
*/
public synchronized void unregister(String instId) {
TaskContext ctx = instContextMap.remove(instId);
TaskContext ctx = instContextMap.get(instId);
if (ctx != null) {
// Failure keeps a durable pending lease until physical stop is acknowledged.
if(occupationGuards!=null)occupationGuards.orderedStream().forEach(guard -> guard.release(instId,ctx.getStatus()==TaskStatusEnum.SUCCESS));
// Termination is not task success, but a confirmed physical stop is
// sufficient to release its native lease. Failed/uncertain cleanup
// keeps the durable STOP_PENDING lease for explicit confirmation.
boolean safeToRelease = ctx.getStatus() == TaskStatusEnum.SUCCESS
|| (ctx.getStatus() == TaskStatusEnum.STOPPED && ctx.isDeviceStopConfirmed());
if(occupationGuards!=null)occupationGuards.orderedStream().forEach(guard -> guard.release(instId,safeToRelease));
// Keep context and in-memory locks if the durable release failed.
instContextMap.remove(instId, ctx);
ctx.setTerminalStatus(TerminalStatusEnum.READY);
ctx.setTerminalLocked(false);
effectiveLockKeys(ctx).forEach(lockKey -> robotInstMap.remove(lockKey, instId));

View File

@ -77,26 +77,46 @@ public class FlowControlService {
stopPersistedTaskWithoutContext(instId, true);
return;
}
if (ctx.isStopped()) {
return;
}
// 先阻止节点继续执行,再清理设备与本地媒体会话,避免终止过程中重新登记录音/录像。
taskInstHolder.syncStatus(instId, TaskStatusEnum.STOPPED);
if (asyncMediaAnalysisCoordinator != null) {
asyncMediaAnalysisCoordinator.cancelAll(instId);
}
taskThreadRegistry.interruptAll(instId);
// 终止必须等设备和后端媒体会话完成清理后再返回,防止立即重跑命中旧录音/录像状态。
stopAllRobots(ctx);
deviceLifecycle.forEach(extension -> extension.afterStop(instId));
taskInstHolder.unRegister(instId);
// 被中断的节点 状态修改成 PAUSED
for (TaskNodeExecuteContext pendingNode : taskThreadRegistry.getPendingNodes(instId)) {
String nodeId = pendingNode.getNode().getNodeId();
nodeInstService.update(instId, nodeId, TaskStatusEnum.STOPPED);
synchronized (ctx) {
if (ctx.isStopped()) {
if (!ctx.isDeviceStopConfirmed()) throw stopUnconfirmed();
// Retry a previously failed durable release without issuing another stop.
taskInstHolder.unRegister(instId);
return;
}
// 先阻止节点继续执行,再清理设备与本地媒体会话,避免终止过程中重新登记录音/录像。
taskInstHolder.syncStatus(instId, TaskStatusEnum.STOPPED);
if (asyncMediaAnalysisCoordinator != null) {
asyncMediaAnalysisCoordinator.cancelAll(instId);
}
List<TaskNodeExecuteContext> interruptedNodes = taskThreadRegistry.getPendingNodes(instId);
taskThreadRegistry.interruptAll(instId);
// 终止必须等设备和后端媒体会话完成清理后再返回,防止立即重跑命中旧录音/录像状态。
boolean devicesStopped = stopAllRobotsAndWait(ctx);
boolean nodesFinished = waitForInterruptedNodes(instId, interruptedNodes);
boolean lifecycleStopped = true;
for (FlowDeviceLifecycleExtension extension : deviceLifecycle) {
try { extension.afterStop(instId); }
catch (RuntimeException error) {
lifecycleStopped = false;
log.warn("终止设备会话清理未确认: instId={}, error={}", instId, error.getMessage());
}
}
ctx.setDeviceStopConfirmed(devicesStopped && nodesFinished && lifecycleStopped);
taskInstHolder.unRegister(instId);
// 被中断的节点状态修改成 STOPPED。
for (TaskNodeExecuteContext pendingNode : taskThreadRegistry.getPendingNodes(instId)) {
String nodeId = pendingNode.getNode().getNodeId();
nodeInstService.update(instId, nodeId, TaskStatusEnum.STOPPED);
}
if (!ctx.isDeviceStopConfirmed()) throw stopUnconfirmed();
}
}
private GlobalException stopUnconfirmed() {
return new GlobalException("流程已终止,但设备停止或旧节点退出尚未确认,资源占用已保留,请核对现场后确认停止并释放");
}
/** Startup recovery entry: persistently closes an orphan without per-task warning logs. */
public void stopOrphaned(String instId) {
TaskContext ctx = taskInstHolder.getContext(instId);
@ -335,23 +355,6 @@ public class FlowControlService {
taskInstHolder.syncStatusAsResumed(instId);
}
private void stopAllRobots(TaskContext context) {
List<String> robotIds = context.getRobotIds() == null || context.getRobotIds().isEmpty()
? Collections.singletonList(context.getRobotId())
: context.getRobotIds();
robotIds.stream()
.filter(robotId -> robotId != null && !robotId.isBlank())
.distinct()
.forEach(robotId -> {
abortLocalMediaRecordings(robotId);
try {
edgeSystemService.stopAll(robotId);
} catch (RuntimeException exception) {
log.warn("终止机器人设备失败: robotId={}, error={}", robotId, exception.getMessage());
}
});
}
private List<String> robotIds(TaskContext context) {
return context.getRobotIds() == null || context.getRobotIds().isEmpty()
? Collections.singletonList(context.getRobotId()) : context.getRobotIds();
@ -371,7 +374,7 @@ public class FlowControlService {
edgeSystemService.stopAll(robotId);
} catch (RuntimeException exception) {
success = false;
log.warn("暂停机器人设备失败,恢复时将重试: robotId={}, error={}",
log.warn("停止机器人设备未确认,保留停止待确认状态: robotId={}, error={}",
robotId, exception.getMessage());
}
}

View File

@ -4,6 +4,7 @@ package com.cmvr.test.flow.runtime.engine;
public interface RobotTaskOccupationGuard {
void check(String robotId, String nativeTaskId);
default void occupy(String instId, String nativeTaskId, java.util.List<String> robotIds) {}
default void release(String instId, boolean success) {}
/** Release only after successful completion or confirmed stop; otherwise retain a pending lease. */
default void release(String instId, boolean safeToRelease) {}
default AutoCloseable manual(String robotId) { check(robotId,null);return ()->{}; }
}

View File

@ -17,14 +17,17 @@ public final class WorkcellNodeContract {
ActionEnum.MOTOR_WAIT, ActionEnum.MOTOR_STOP, ActionEnum.MOTOR_STATUS);
private WorkcellNodeContract() {}
private static boolean supplement(ActionEnum action) {
return action == ActionEnum.SCANNER_SUPPLEMENT_PREPARE || action == ActionEnum.SCANNER_SUPPLEMENT_WAIT;
}
public static boolean supports(ActionEnum action) {
return action != null && (ScannerOperation.forAction(action.getAction()) != null || MOTOR.contains(action));
return action != null && (supplement(action) || ScannerOperation.forAction(action.getAction()) != null || MOTOR.contains(action));
}
public static int deviceKind(ActionEnum action) {
if (!supports(action)) throw new GlobalException("不是扫描仪或电机节点");
return ScannerOperation.forAction(action.getAction()) != null ? 14 : 10;
return supplement(action) || ScannerOperation.forAction(action.getAction()) != null ? 14 : 10;
}
public static void validate(ActionEnum action, JSONObject input) {
@ -34,6 +37,16 @@ public final class WorkcellNodeContract {
throw new GlobalException("timeoutMs 必须是 1 至 3600000 的整数毫秒");
}
ScannerOperation scanner = ScannerOperation.forAction(action.getAction());
if (supplement(action)) {
var context = ScannerRequestValidator.parse(required(input,"expectedContextJson"));
for (String name : java.util.List.of("sessionId","projectId","robotId","deviceId","endpoint"))
if (!context.path(name).isTextual() || context.path(name).asText().isBlank()) throw new GlobalException("补扫缺少原工程关联:"+name);
if (action == ActionEnum.SCANNER_SUPPLEMENT_WAIT) {
double duration=number(input,"durationMs");
if(duration<1000 || duration>1800000 || duration!=Math.rint(duration))throw new GlobalException("补扫时长必须为1至1800秒");
}
return;
}
if (scanner != null) {
if (scanner == ScannerOperation.TASK) scanner.route(required(input, "taskId"));
else if (scanner.control()) {

View File

@ -119,6 +119,12 @@
for update
</select>
<update id="updateHttpScannerState">
update iot_robot set connect_status=#{connectStatus}, runtime_status=#{status},
last_heartbeat_time=#{lastHeartbeatTime}, update_by='scanner-http', update_time=#{updateTime}
where id=#{id} and coalesce(archived_status,'0')='0'
</update>
<update id="markHeartbeatExpiredOffline">
update iot_robot set connect_status = '0', runtime_status = '1',
update_by = 'heartbeat-timeout', update_time = #{offlineTime}

View File

@ -30,6 +30,7 @@ public class ScannerIntegrationTest {
private final AtomicInteger postDelayMs=new AtomicInteger();
private final java.util.concurrent.CountDownLatch statusEntered=new java.util.concurrent.CountDownLatch(1);
private final AtomicReference<String> session=new AtomicReference<>("S1");
private final AtomicReference<String> statusOverride=new AtomicReference<>();
private final List<String> seen=new ArrayList<>();
private final String taskId="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
@ -38,7 +39,9 @@ public class ScannerIntegrationTest {
server.createContext("/",exchange->{
synchronized(seen){seen.add(exchange.getRequestMethod()+" "+exchange.getRequestURI());}
assertNull(exchange.getRequestURI().getQuery());
if(!exchange.getRequestURI().getPath().equals("/"))assertEquals("test-key",exchange.getRequestHeaders().getFirst("X-Api-Key"));
if(!exchange.getRequestURI().getPath().equals("/"))assertEquals("Bearer test-key",exchange.getRequestHeaders().getFirst("Authorization"));
else assertNull(exchange.getRequestHeaders().getFirst("Authorization"));
assertNull(exchange.getRequestHeaders().getFirst("X-Api-Key"));
byte[] response;int code=200;
if(exchange.getRequestMethod().equals("POST")){
assertTrue(exchange.getRequestHeaders().getFirst("Content-Type").startsWith("application/json"));
@ -53,7 +56,7 @@ public class ScannerIntegrationTest {
response=("{\"taskId\":\""+(wrongTask.get()?"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb":taskId)+"\",\"state\":\""+(runningTask.get()?"running":failedTask.get()?"failed":"succeeded")+"\",\"result\":{\"projectId\":\"P1\"},\"error\":{\"code\":\"sdk_failed\",\"message\":\"device fault\"}}").getBytes(StandardCharsets.UTF_8);
}else if(exchange.getRequestURI().getPath().contains("/files/")||exchange.getRequestURI().getPath().equals("/api/v1/preview/image")||exchange.getRequestURI().getPath().equals("/api/v1/preview/stream")){
response=new byte[]{1,2,3,4};exchange.getResponseHeaders().set("Content-Type","application/octet-stream");exchange.getResponseHeaders().set("X-Frame-Sequence","7");
}else {statusEntered.countDown();delay(statusDelayMs.get());response=("{\"busy\":false,\"scanning\":"+scanning.get()+",\"sessionId\":\""+session.get()+"\",\"projectId\":\"P1\",\"stateUncertain\":false,\"restartRequired\":false}").getBytes(StandardCharsets.UTF_8);}
}else {statusEntered.countDown();delay(statusDelayMs.get());response=(statusOverride.get()!=null?statusOverride.get():"{\"busy\":false,\"scanning\":"+scanning.get()+",\"sessionId\":\""+session.get()+"\",\"projectId\":\"P1\",\"stateUncertain\":false,\"restartRequired\":false}").getBytes(StandardCharsets.UTF_8);}
exchange.sendResponseHeaders(code,response.length);try(var out=exchange.getResponseBody()){out.write(response);}
});
server.start();
@ -64,6 +67,74 @@ public class ScannerIntegrationTest {
journal=new ScannerCommandJournal(jdbc);service=new ScannerService(config,client,journal);
}
@After public void close(){if(server!=null)server.stop(0);}
@Test public void stoppedScannerWithoutAProjectConfirmsLocallyAndReplaysWithoutAnSdkTask() {
statusOverride.set("{\"scanning\":false,\"busy\":false,\"stateUncertain\":false,\"restartRequired\":false,\"projectId\":null}");
var body=ScannerRequestValidator.parse("{}");
var first=service.executeAndWait(ScannerOperation.SCAN_STOP,body,"idle-stop-confirm","test",3000);
assertEquals("succeeded",first.path("state").asText());
assertFalse(first.path("result").path("scanning").asBoolean(true));
assertTrue(first.path("result").path("alreadyStopped").asBoolean());
assertEquals("device_status",first.path("result").path("confirmationSource").asText());
assertEquals("SUCCEEDED",journal.get("idle-stop-confirm").state());
assertNull(journal.get("idle-stop-confirm").taskId());assertNull(journal.active(client.endpointKey()));
service=new ScannerService(config,client,journal);scanning.set(true);statusOverride.set(null);
assertEquals(first,service.executeAndWait(ScannerOperation.SCAN_STOP,body,"idle-stop-confirm","test",3000));
var receipt=service.submit(ScannerOperation.SCAN_STOP,body,"idle-stop-confirm","test");
assertTrue(receipt.path("taskId").isNull());assertTrue(receipt.path("statusUrl").isNull());
assertEquals(0,submissions.get()); // Replaying a completed stop cannot stop a later acquisition.
}
@Test public void activeAcquisitionStillRequiresTheRealSdkStopAndItsSuccessfulTask() {
scanning.set(true);failedTask.set(true);
assertEquals("sdk_failed",assertThrows(ScannerException.class,()->service.executeAndWait(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"active-stop-error","test",3000)).scannerCode);
assertEquals(1,submissions.get());assertEquals("FAILED",journal.get("active-stop-error").state());
scanning.set(true);failedTask.set(false);
service.executeAndWait(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"active-stop-ok","test",3000);
assertEquals(2,submissions.get());assertFalse(scanning.get());assertEquals(taskId,journal.get("active-stop-ok").taskId());
}
@Test public void incompleteOrNonBooleanStatusCannotPretendToConfirmAnIdleStop() {
int index=0;
for(String field:List.of("scanning","busy","stateUncertain","restartRequired")) {
for(JsonNode invalid:List.of(ScannerRequestValidator.JSON.getNodeFactory().nullNode(),ScannerRequestValidator.JSON.getNodeFactory().textNode("false"))) {
var status=ScannerRequestValidator.parse("{\"scanning\":false,\"busy\":false,\"stateUncertain\":false,\"restartRequired\":false}");
status.set(field,invalid);statusOverride.set(status.toString());
var receipt=service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"incomplete-stop-"+index++,"test");
assertEquals("ACCEPTED",receipt.path("state").asText());
assertEquals(taskId,receipt.path("taskId").asText());
service.waitCommand(receipt.path("commandKey").asText(),3000);
}
var missing=ScannerRequestValidator.parse(statusOverride.get());missing.remove(field);statusOverride.set(missing.toString());
var receipt=service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"missing-stop-"+index++,"test");
assertEquals("ACCEPTED",receipt.path("state").asText());service.waitCommand(receipt.path("commandKey").asText(),3000);
}
assertEquals(12,submissions.get());
}
@Test public void unhealthyIdleStatusAndChangedProjectStillRejectStopBeforeAnyPost() {
for(String field:List.of("busy","stateUncertain","restartRequired")) {
var status=ScannerRequestValidator.parse("{\"scanning\":false,\"busy\":false,\"stateUncertain\":false,\"restartRequired\":false}");
status.put(field,true);statusOverride.set(status.toString());
assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"unsafe-stop-"+field,"test"));
assertNull(journal.get("unsafe-stop-"+field));
}
statusOverride.set(null);
assertEquals("project_changed",assertThrows(ScannerException.class,()->service.submitBound(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"changed-idle-stop","test",ScannerRequestValidator.parse("{\"sessionId\":\"OTHER\",\"projectId\":\"P1\"}"))).scannerCode);
assertEquals(0,submissions.get());
}
@Test public void idleStatusCannotBypassAnUnfinishedOrUncertainCommand() {
runningTask.set(true);
service.submit(ScannerOperation.CONNECT,ScannerRequestValidator.parse("{}"),"pending-initialize","test");
assertEquals("command_busy",assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"pending-idle-stop","test")).scannerCode);
journal.uncertain("pending-initialize","acceptance unknown");
assertEquals("command_uncertain",assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"unknown-idle-stop","test")).scannerCode);
assertNull(journal.get("pending-idle-stop"));assertNull(journal.get("unknown-idle-stop"));assertEquals(1,submissions.get());
}
@Test public void supplementalControlsCheckProjectAndEndpointBeforeAnyPost(){
var expected=ScannerRequestValidator.parse("{\"endpoint\":\""+client.endpointKey()+"\",\"sessionId\":\"S1\",\"projectId\":\"P1\"}");
session.set("OTHER");
assertEquals("project_changed",assertThrows(ScannerException.class,()->service.executeBoundAndWait(ScannerOperation.MESH_UNDO,ScannerRequestValidator.parse("{}"),"bound-undo","workflow:inst",2000,expected)).scannerCode);
session.set("S1");expected.put("endpoint","another-endpoint");
assertThrows(ScannerException.class,()->service.executeBoundAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"bound-start","workflow:inst",2000,expected));
assertEquals(0,submissions.get());assertNull(journal.get("bound-undo"));
}
private static void delay(int milliseconds) {try{Thread.sleep(milliseconds);}catch(InterruptedException error){Thread.currentThread().interrupt();}}
@Test public void remoteWaitRejectsAnotherTasksSuccessfulResponse() {

View File

@ -59,6 +59,16 @@ public class ScannerMonitoringTest {
assertThrows(ScannerException.class,()->monitoring.image(bound));
verify(scanner,never()).submit(any(),any(),anyString(),anyString());
}
@Test public void continuousFramesAreBoundToCurrentProjectAndRequireSequence() throws Exception {
var bound=capture();
var frame=new ScannerMonitoringService.Frame(new byte[]{1},Map.of("X-Frame-Sequence",List.of("11")));
assertEquals(11,monitoring.streamSequence(bound,frame));
assertEquals("invalid_frame",assertThrows(ScannerException.class,()->monitoring.streamSequence(bound,new ScannerMonitoringService.Frame(new byte[0],Map.of()))).scannerCode);
when(scanner.get(ScannerOperation.STATUS,null)).thenReturn(status("S1","other-project"));
assertEquals("project_changed",assertThrows(ScannerException.class,()->monitoring.streamSequence(bound,frame)).scannerCode);
assertThrows(ScannerException.class,()->monitoring.stream(bound));
verify(scanner,never()).binary(ScannerOperation.PREVIEW_STREAM,null);
}
@Test public void snapshotAndItsFilesBelongToOneExecutionOnly() {
capture();
when(scanner.submitBound(eq(ScannerOperation.SNAPSHOT),any(),anyString(),eq("workflow:inst-1"),any())).thenAnswer(invocation->{

View File

@ -0,0 +1,40 @@
package com.cmvr.scanner;
import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static org.junit.Assert.*;
public class ScannerPreviewStreamTest {
private ScannerPreviewStream reader(byte[] bytes) {
InputStream fragmented=new ByteArrayInputStream(bytes) {
@Override public synchronized int read(byte[] b,int offset,int length){return super.read(b,offset,Math.min(length,3));}
};
return new ScannerPreviewStream(new ScannerHttpClient.Binary(fragmented,Map.of("Content-Type",List.of("multipart/x-mixed-replace; boundary=scanframe"))));
}
private byte[] part(String headers,byte[] jpeg) throws IOException {
var output=new ByteArrayOutputStream();
output.write(("--scanframe\r\nContent-Type: image/jpeg\r\n"+headers+"\r\n").getBytes(StandardCharsets.US_ASCII));
output.write(jpeg);output.write("\r\n".getBytes(StandardCharsets.US_ASCII));return output.toByteArray();
}
@Test public void parsesMultipleFragmentedFramesAndClosesAtFinalBoundary() throws Exception {
byte[] jpeg={(byte)255,(byte)216,13,10,(byte)255,(byte)217};var bytes=new ByteArrayOutputStream();
bytes.write(part("Content-Length: 6\r\nX-Frame-Sequence: 20\r\n",jpeg));
bytes.write(part("content-length: 6\r\nx-frame-sequence: 21\r\n",jpeg));bytes.write("--scanframe--\r\n".getBytes());
try(var source=reader(bytes.toByteArray())) {
var one=source.next();assertArrayEquals(jpeg,one.bytes());assertEquals("20",one.headers().get("x-frame-sequence").get(0));
assertArrayEquals(jpeg,source.next().bytes());assertNull(source.next());
}
}
@Test public void rejectsOversizeDuplicateMissingAndTruncatedParts() throws Exception {
byte[] jpeg={(byte)255,(byte)216,(byte)255,(byte)217};
for(String header:List.of("Content-Length: 99999999\r\n","Content-Length: 4\r\nContent-Length: 4\r\n","X-Frame-Sequence: 1\r\n","Content-Length: 20\r\n"))
try(var source=reader(part(header,jpeg))) {assertThrows(IOException.class,source::next);}
try(var source=reader(part("Content-Length: 4\r\n",new byte[4]))) {assertThrows(IOException.class,source::next);}
try(var source=reader(("--scanframe\r\nX-Test: "+"a".repeat(17000)).getBytes())) {assertThrows(IOException.class,source::next);}
}
@Test public void requiresMultipartAndSafeBoundary() {
assertThrows(ScannerException.class,()->new ScannerPreviewStream(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[0]),Map.of("content-type",List.of("image/jpeg")))));
}
}

View File

@ -0,0 +1,106 @@
package com.cmvr.scanner;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.resource.config.ResourceRobotStateProperties;
import com.cmvr.resource.domain.ResourceDevice;
import com.cmvr.resource.domain.ResourceRobot;
import com.cmvr.resource.mapper.ResourceDeviceMapper;
import com.cmvr.resource.mapper.ResourceRobotMapper;
import com.cmvr.resource.service.ResourceRobotEndpointResolver;
import com.cmvr.resource.service.ResourceRobotExecutionTargetResolver;
import org.junit.*;
import java.util.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class ScannerResourceSynchronizerTest {
ScannerProperties settings = new ScannerProperties();
ScannerHttpClient client = mock(ScannerHttpClient.class);
ResourceRobotMapper robots = mock(ResourceRobotMapper.class);
ResourceDeviceMapper devices = mock(ResourceDeviceMapper.class);
ResourceRobotStateProperties state = new ResourceRobotStateProperties();
ScannerResourceSynchronizer sync;
ResourceRobot robot;
@Before public void setup() {
settings.setHost("localhost"); settings.setPort(18888); settings.setApiKey("test-key");
settings.setRobotId("station"); settings.setDeviceId("scanner");
sync = new ScannerResourceSynchronizer(settings, client, robots, devices, state);
robot = new ResourceRobot(); robot.setId("record"); robot.setRobotId("station");
robot.setArchivedStatus("0"); robot.setConnectStatus("1"); robot.setLastHeartbeatTime(new Date());
when(robots.selectByRobotIdentity("station")).thenReturn(robot);
when(devices.selectByIdentity("station", "scanner")).thenReturn(List.of());
when(client.json(ScannerOperation.STATUS, null, null, 3000)).thenReturn(
ScannerRequestValidator.parse("{\"deviceOnline\":true,\"scanning\":false}"));
}
@Test public void discoversRealDeviceUsingOnlyBoundedStatusRead() {
sync.refresh();
verify(client).json(ScannerOperation.STATUS, null, null, 3000); verifyNoMoreInteractions(client);
verify(robots).updateHttpScannerState(argThat(r -> "1".equals(r.getConnectStatus()) && r.getIpAddress() == null && r.getPort() == null));
verify(devices).insert(argThat((ResourceDevice d) -> "station".equals(d.getRobotId()) && "scanner".equals(d.getDeviceId()) && d.getDeviceKind() == 14 && "1".equals(d.getOnlineStatus()) && d.getManagerState() == 4));
}
@Test public void unavailableStatusMarksOfflineWithoutInventingDiscovery() {
when(client.json(ScannerOperation.STATUS, null, null, 3000)).thenThrow(new ScannerException("unavailable", "offline", 503));
sync.refresh();
verify(robots).updateHttpScannerState(argThat(r -> "0".equals(r.getConnectStatus())));
verify(devices, never()).insert(any(ResourceDevice.class));
}
@Test public void respectsDisabledDeviceAndReportsUncertainStateAsFault() {
ResourceDevice device = new ResourceDevice(); device.setId("device-record"); device.setDeviceKind(14); device.setEnabled("0");
when(devices.selectByIdentity("station", "scanner")).thenReturn(List.of(device));
when(client.json(ScannerOperation.STATUS, null, null, 3000)).thenReturn(ScannerRequestValidator.parse("{\"deviceOnline\":true,\"stateUncertain\":true}"));
sync.refresh(); verify(devices).updateRuntimeState(argThat(d -> "0".equals(d.getEnabled()) && "1".equals(d.getHasError()) && d.getHealthStatus() == 3));
}
@Test public void archivedUnboundAndConflictingDevicesAreNeverOverwritten() {
robot.setArchivedStatus("1"); sync.refresh(); verifyNoInteractions(client);
robot.setArchivedStatus("0");
ResourceDevice wrong = new ResourceDevice(); wrong.setDeviceKind(1);
when(devices.selectByIdentity("station", "scanner")).thenReturn(List.of(wrong)); sync.refresh(); verifyNoInteractions(client);
settings.setDeviceId(""); sync.refresh(); verifyNoInteractions(client);
}
@Test public void expiredOrOfflineStationCannotResolve() {
sync.validateTarget("station");
robot.setConnectStatus("0"); assertThrows(GlobalException.class, () -> sync.validateTarget("station"));
robot.setConnectStatus("1"); robot.setLastHeartbeatTime(new Date(0));
assertThrows(GlobalException.class, () -> sync.validateTarget("station"));
}
@Test public void httpStationDoesNotResolveAsGrpcButOtherRobotsStillDo() {
ResourceRobotEndpointResolver endpoints = mock(ResourceRobotEndpointResolver.class);
var resolver = new ResourceRobotExecutionTargetResolver(endpoints, state, sync);
assertEquals("station", resolver.resolve("station").getRobotId()); verifyNoInteractions(endpoints);
resolver.resolve("other"); verify(endpoints).resolve("other");
}
@Test public void compactBusyResponseNeverOverwritesMeasuredDeviceOnlineState() {
for(String json:List.of("{\"busy\":true,\"state\":\"busy\"}","{\"busy\":true,\"deviceOnline\":null}")) {
clearInvocations(robots,devices);
when(client.json(ScannerOperation.STATUS,null,null,3000)).thenReturn(ScannerRequestValidator.parse(json));
sync.refresh();
verify(robots).updateHttpScannerState(argThat(r->"1".equals(r.getConnectStatus())&&"3".equals(r.getStatus())));
verify(devices,never()).updateRuntimeState(any());verify(devices,never()).insert(any(ResourceDevice.class));
}
robot.setConnectStatus("0");sync.refresh();
verify(robots).updateHttpScannerState(argThat(r->"0".equals(r.getConnectStatus())));
}
@Test public void explicitOfflineDisconnectedAndFaultAreNotHiddenByBusy() {
for(String json:List.of("{\"busy\":true,\"deviceOnline\":false}","{\"busy\":true,\"initialized\":false,\"state\":\"disconnected\"}","{\"busy\":true,\"stateUncertain\":true}")) {
clearInvocations(robots,devices);
when(client.json(ScannerOperation.STATUS,null,null,3000)).thenReturn(ScannerRequestValidator.parse(json));
sync.refresh();verify(robots).updateHttpScannerState(argThat(r->"0".equals(r.getConnectStatus())));
}
}
@Test public void runtimeStateUsesPlatformEnumRatherThanOnlineBoolean() {
ResourceDevice device = new ResourceDevice();device.setId("device-record");device.setDeviceKind(14);device.setEnabled("1");
when(devices.selectByIdentity("station","scanner")).thenReturn(List.of(device));
String[] statuses={"{\"deviceOnline\":true,\"scanning\":true}","{\"deviceOnline\":true,\"busy\":true}","{\"deviceOnline\":true,\"stateUncertain\":true}","{\"deviceOnline\":false}"};
int[] expected={5,5,7,6};
for(int i=0;i<statuses.length;i++) {
clearInvocations(devices);
when(client.json(ScannerOperation.STATUS,null,null,3000)).thenReturn(ScannerRequestValidator.parse(statuses[i]));
sync.refresh();int value=expected[i];
verify(devices).updateRuntimeState(argThat(d->d.getManagerState()==value));
}
device.setEnabled("0");clearInvocations(devices);
when(client.json(ScannerOperation.STATUS,null,null,3000)).thenReturn(ScannerRequestValidator.parse("{\"deviceOnline\":true}"));
sync.refresh();verify(devices).updateRuntimeState(argThat(d->d.getManagerState()==1&&"0".equals(d.getEnabled())));
}
}

View File

@ -0,0 +1,41 @@
package com.cmvr.scanner;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.operator.edge.WorkcellNodeContract;
import org.junit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class ScannerSupplementAdapterTest {
private final ScannerWorkflowAdapter driver=mock(ScannerWorkflowAdapter.class);
private final ScannerService scanner=mock(ScannerService.class);
private final ScannerMonitoringService monitoring=mock(ScannerMonitoringService.class);
private final ScannerSupplementSignals signals=mock(ScannerSupplementSignals.class);
private final ScannerSupplementAdapter adapter=new ScannerSupplementAdapter(driver,scanner,monitoring,signals);
private final String context="{\"endpoint\":\"endpoint\",\"sessionId\":\"S1\",\"projectId\":\"P1\",\"robotId\":\"station\",\"deviceId\":\"scanner\"}";
private TaskNodeExecuteMessage message(ActionEnum action){var m=new TaskNodeExecuteMessage();m.setInstId("inst");m.setRobotId("station");m.setAction(action);m.setInputParams(JSONObject.of("deviceId","scanner","timeoutMs",1000,"durationMs",1000,"expectedContextJson",context));return m;}
@Test public void completedMeshIsUndoneOnceBeforeReusingOriginalProject(){
when(monitoring.status(any())).thenReturn(ScannerRequestValidator.parse("{\"meshState\":\"confirmed\"}"),ScannerRequestValidator.parse("{\"meshState\":\"none\"}"));
var m=message(ActionEnum.SCANNER_SUPPLEMENT_PREPARE);WorkcellNodeContract.validate(m.getAction(),m.getInputParams());adapter.execute(m);
verify(scanner).executeBoundAndWait(eq(ScannerOperation.MESH_UNDO),any(),anyString(),eq("workflow:inst"),eq(1000L),any());verifyNoMoreInteractions(scanner);
}
@Test public void unmeshedProjectIsNotChangedAndBusyOrForeignProjectsNeverSendControls(){
when(monitoring.status(any())).thenReturn(ScannerRequestValidator.parse("{\"meshState\":\"none\"}"));adapter.execute(message(ActionEnum.SCANNER_SUPPLEMENT_PREPARE));verifyNoInteractions(scanner);
when(monitoring.status(any())).thenReturn(ScannerRequestValidator.parse("{\"meshState\":\"none\",\"scanning\":true}"));
assertThrows(ScannerException.class,()->adapter.execute(message(ActionEnum.SCANNER_SUPPLEMENT_PREPARE)));verifyNoInteractions(scanner);
when(monitoring.status(any())).thenThrow(new ScannerException("project_changed","wrong project",409));
assertThrows(ScannerException.class,()->adapter.execute(message(ActionEnum.SCANNER_SUPPLEMENT_PREPARE)));verifyNoInteractions(scanner);
}
@Test public void manualFinishLeavesTheWaitForTheNormalStopAndExportNodes(){
when(monitoring.status(any())).thenReturn(ScannerRequestValidator.parse("{}"));when(signals.finishRequested("inst")).thenReturn(true);
adapter.execute(message(ActionEnum.SCANNER_SUPPLEMENT_WAIT));verify(signals).collecting("inst");verify(signals).processing("inst");verifyNoInteractions(scanner);
}
@Test public void waitContractRequiresOriginalIdentityAndBoundsAcquisitionTime(){
var m=message(ActionEnum.SCANNER_SUPPLEMENT_WAIT);WorkcellNodeContract.validate(m.getAction(),m.getInputParams());
assertEquals(14,WorkcellNodeContract.deviceKind(m.getAction()));
m.getInputParams().put("durationMs",1800001);assertThrows(RuntimeException.class,()->WorkcellNodeContract.validate(m.getAction(),m.getInputParams()));
m.getInputParams().put("durationMs",1000);m.getInputParams().put("expectedContextJson","{}");assertThrows(RuntimeException.class,()->WorkcellNodeContract.validate(m.getAction(),m.getInputParams()));
}
}

View File

@ -0,0 +1,45 @@
package com.cmvr.scanner;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
public class ScannerWorkflowReadinessTest {
@Test public void supplementCannotSucceedWithoutBindingItsOwnPreviewAndResults() {
var scanner=mock(ScannerService.class);var monitoring=mock(ScannerMonitoringService.class);var resources=mock(ScannerResourceSynchronizer.class);
var settings=new ScannerProperties();settings.setHost("localhost");settings.setPort(18888);settings.setApiKey("test-key");settings.setRobotId("station");settings.setDeviceId("scanner");
var adapter=new ScannerWorkflowAdapter(scanner,settings,mock(ScannerAccessService.class),monitoring,resources);
var message=new TaskNodeExecuteMessage();message.setInstId("instance");message.setRobotId("station");message.setAction(ActionEnum.SCANNER_START);
message.setInputParams(JSONObject.of("deviceId","scanner","timeoutMs",120000,"requestJson","{}","expectedContextJson","{\"sessionId\":\"s\",\"projectId\":\"p\"}"));
when(scanner.executeBoundAndWait(any(),any(),anyString(),anyString(),anyLong(),any())).thenReturn(ScannerRequestValidator.parse("{\"state\":\"succeeded\"}"));
assertEquals("binding_invalid",assertThrows(ScannerException.class,()->adapter.execute(message)).scannerCode);
verify(scanner).executeBoundAndWait(any(),any(),anyString(),anyString(),anyLong(),any());
}
@Test public void refreshesRealResourceStatusAfterCommandCompletesBeforeBindingPreview() {
var scanner=mock(ScannerService.class);var access=mock(ScannerAccessService.class);
var monitoring=mock(ScannerMonitoringService.class);var resources=mock(ScannerResourceSynchronizer.class);
var settings=new ScannerProperties();settings.setHost("localhost");settings.setPort(18888);settings.setApiKey("test-key");settings.setRobotId("station");settings.setDeviceId("scanner");
var adapter=new ScannerWorkflowAdapter(scanner,settings,access,monitoring,resources);
var message=new TaskNodeExecuteMessage();message.setInstId("instance");message.setNodeId("create");message.setRobotId("station");message.setAction(ActionEnum.SCANNER_CREATE_PROJECT);
var input=new JSONObject();input.put("deviceId","scanner");input.put("timeoutMs",120000);input.put("requestJson","{\"mode\":\"trak\"}");message.setInputParams(input);
when(scanner.executeAndWait(eq(ScannerOperation.CREATE_PROJECT),any(),anyString(),eq("workflow:instance"),eq(120000L)))
.thenReturn(ScannerRequestValidator.parse("{\"state\":\"succeeded\"}"));
adapter.execute(message);
var ordered=inOrder(scanner,resources,monitoring);
ordered.verify(scanner).executeAndWait(eq(ScannerOperation.CREATE_PROJECT),any(),anyString(),eq("workflow:instance"),eq(120000L));
ordered.verify(resources).refresh();ordered.verify(monitoring).capture(eq(ScannerOperation.CREATE_PROJECT),anyString(),eq("instance"),eq("station"),eq("scanner"));
verifyNoInteractions(access);
}
@Test public void failedCommandNeverPretendsToRefreshIntoSuccess() {
var scanner=mock(ScannerService.class);var resources=mock(ScannerResourceSynchronizer.class);var monitoring=mock(ScannerMonitoringService.class);
var settings=new ScannerProperties();settings.setHost("localhost");settings.setPort(18888);settings.setApiKey("test-key");settings.setRobotId("station");settings.setDeviceId("scanner");
var adapter=new ScannerWorkflowAdapter(scanner,settings,mock(ScannerAccessService.class),monitoring,resources);
var message=new TaskNodeExecuteMessage();message.setInstId("instance");message.setRobotId("station");message.setAction(ActionEnum.SCANNER_STOP);
var input=new JSONObject();input.put("deviceId","scanner");input.put("timeoutMs",120000);input.put("requestJson","{}");message.setInputParams(input);
when(scanner.executeAndWait(any(),any(),anyString(),anyString(),anyLong())).thenThrow(new ScannerException("sdk_timeout","timeout",504));
assertThrows(ScannerException.class,()->adapter.execute(message));verifyNoInteractions(resources,monitoring);
}
}

View File

@ -0,0 +1,81 @@
package com.cmvr.test.flow.control;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.edge.client.service.*;
import com.cmvr.test.enums.*;
import com.cmvr.test.flow.builder.FlowNodeWrapper;
import com.cmvr.test.flow.context.*;
import com.cmvr.test.flow.runtime.engine.RobotTaskOccupationGuard;
import com.cmvr.test.flow.runtime.event.FlowExecutionEventPublisher;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteContext;
import com.cmvr.test.service.*;
import org.junit.*;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.*;
public class FlowStopOccupationTest {
private TaskContext context;
private TaskContextManager manager;
private RobotTaskOccupationGuard guard;
private EdgeSystemService edge;
private TaskThreadRegistry threads;
private FlowControlService control;
@Before public void setup() {
guard=mock(RobotTaskOccupationGuard.class);
@SuppressWarnings("unchecked") ObjectProvider<RobotTaskOccupationGuard> provider=mock(ObjectProvider.class);
when(provider.orderedStream()).thenAnswer(call->Stream.of(guard));
manager=new TaskContextManager();ReflectionTestUtils.setField(manager,"occupationGuards",provider);
context=new TaskContext();context.setInstId("trial-1");context.setRobotId("scanner");
context.setRobotIds(List.of("scanner"));context.setLockKeys(List.of("robot:scanner"));context.setStatus(TaskStatusEnum.RUNNING);
manager.register(context);
var nodes=mock(ITeNodeInstService.class);var tasks=mock(ITeTaskInstService.class);
var holder=new TaskInstHolder(nodes,manager,tasks,mock(FlowExecutionEventPublisher.class));
edge=mock(EdgeSystemService.class);when(edge.stopAll(anyString())).thenReturn("ACKNOWLEDGED");
threads=mock(TaskThreadRegistry.class);when(threads.getPendingNodes("trial-1")).thenReturn(List.of());
control=new FlowControlService(null,holder,nodes,threads,null,edge,mock(EdgeMicrophoneService.class),mock(EdgeCameraService.class),tasks);
}
@Test public void acknowledgedTrialStopReleasesWithoutPretendingTaskSucceeded() {
control.stop("trial-1");
assertEquals(TaskStatusEnum.STOPPED,context.getStatus());assertTrue(context.isDeviceStopConfirmed());
verify(guard).release("trial-1",true);assertNull(manager.get("trial-1"));assertFalse(manager.isRobotLocked("robot:scanner"));
}
@Test public void failedPhysicalStopRetainsDurableOccupationAndReturnsActionableError() {
when(edge.stopAll("scanner")).thenThrow(new GlobalException("stop timeout"));
var error=assertThrows(GlobalException.class,()->control.stop("trial-1"));
assertTrue(error.getMessage().contains("占用已保留"));assertFalse(context.isDeviceStopConfirmed());
verify(guard).release("trial-1",false);verify(guard,never()).release("trial-1",true);
}
@Test public void everyAssignedRobotMustAcknowledgeStop() {
context.setRobotIds(List.of("scanner","motor"));when(edge.stopAll("motor")).thenThrow(new GlobalException("offline"));
assertThrows(GlobalException.class,()->control.stop("trial-1"));
verify(edge).stopAll("scanner");verify(edge).stopAll("motor");verify(guard).release("trial-1",false);
}
@Test public void acknowledgedDeviceDoesNotReleaseWhileAnOldNodeHasNotExited() throws Exception {
var pending=mock(TaskNodeExecuteContext.class);var node=mock(FlowNodeWrapper.class);
when(node.getNodeType()).thenReturn(NodeTypeEnum.SLEEP);when(node.getNodeId()).thenReturn("wait");when(pending.getNode()).thenReturn(node);
when(pending.awaitExecutionFinished(anyLong(),eq(TimeUnit.NANOSECONDS))).thenReturn(false);
when(threads.getPendingNodes("trial-1")).thenReturn(List.of(pending));
assertThrows(GlobalException.class,()->control.stop("trial-1"));
verify(guard).release("trial-1",false);assertFalse(context.isDeviceStopConfirmed());
}
@Test public void durableReleaseFailureKeepsContextAndRetryDoesNotSendAnotherStop() {
doThrow(new GlobalException("database unavailable")).doNothing().when(guard).release("trial-1",true);
assertThrows(GlobalException.class,()->control.stop("trial-1"));
assertSame(context,manager.get("trial-1"));assertTrue(manager.isRobotLocked("robot:scanner"));
control.stop("trial-1");
verify(edge,times(1)).stopAll("scanner");verify(guard,times(2)).release("trial-1",true);
assertNull(manager.get("trial-1"));assertFalse(manager.isRobotLocked("robot:scanner"));
}
@Test public void failedTaskDoesNotReuseAStopAcknowledgementToRelease() {
context.setStatus(TaskStatusEnum.FAILED);context.setDeviceStopConfirmed(true);
manager.unregister("trial-1");verify(guard).release("trial-1",false);
}
}

View File

@ -54,7 +54,7 @@ public class EdgeWorkcellOperateServiceTest {
@Test public void scannerConfigurationAndIdentityAreCheckedWithoutSendingCommands() {
var settings=new com.cmvr.scanner.ScannerProperties();
var adapter=new com.cmvr.scanner.ScannerWorkflowAdapter(null,settings,null,null);
var adapter=new com.cmvr.scanner.ScannerWorkflowAdapter(null,settings,null,null,null);
assertEquals("not_configured",assertThrows(com.cmvr.scanner.ScannerException.class,
()->adapter.validateConfiguration("station","scanner")).scannerCode);
settings.setHost("127.0.0.1");settings.setPort(18888);settings.setApiKey("fixture");

View File

@ -49,6 +49,25 @@ public class LabScannerViewController {
frame.headers().forEach((name,values)->{if(name.toLowerCase(Locale.ROOT).startsWith("x-frame-")&&!values.isEmpty())headers.put(name,values);});
return ResponseEntity.ok().headers(headers).body(frame.bytes());
}
@GetMapping("/stream")
public ResponseEntity<StreamingResponseBody> stream(@RequestParam Long executionId) {
views.checkStream(executionId);
Long tenant=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getRequiredTenantId();
return ResponseEntity.ok().contentType(MediaType.parseMediaType("multipart/x-mixed-replace; boundary=scanframe"))
.cacheControl(CacheControl.noStore()).header("X-Accel-Buffering","no").body(output->{
Long previous=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getTenantId();
boolean ignored=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.isIgnore();
try {
cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setTenantId(tenant);
cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setIgnore(false);
views.stream(executionId,output);
}catch(ScannerException closed){/* End multipart on task/project changes; the client rechecks metadata. */}
finally {
cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setTenantId(previous);
cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setIgnore(ignored);
}
});
}
@ExceptionHandler(ScannerException.class)
public CommonResult<?> scannerError(ScannerException error){return CommonResult.error(error.remoteStatus,error.getMessage());}
}

View File

@ -37,6 +37,12 @@ public class ScanOnlyTaskController {
public CommonResult<Boolean> clearOccupation(@Valid @RequestBody ScanTaskRequests.ClearOccupation request) { resources.clearOccupation(request.getOwnerKey(),request.getReason());return success(true); }
@PostMapping("/start-unit") @PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public CommonResult<Long> start(@Valid @RequestBody ScanTaskRequests.Start request) { return success(service.startUnit(request)); }
@GetMapping("/supplement-option") @PreAuthorize("@ss.hasPermission('lab:task:query')")
public CommonResult<Map<String,Object>> supplementOption(@RequestParam Long taskId,@RequestParam Long unitId){return success(service.supplementOption(taskId,unitId));}
@PostMapping("/supplement") @PreAuthorize("@ss.hasPermission('lab:execution:dispatch')")
public CommonResult<Long> supplement(@Valid @RequestBody ScanTaskRequests.Supplement request){return success(service.startSupplement(request));}
@PostMapping("/finish-supplement") @PreAuthorize("@ss.hasPermission('lab:execution:control')")
public CommonResult<Boolean> finishSupplement(@Valid @RequestBody ScanTaskRequests.FinishSupplement request){service.finishSupplement(request);return success(true);}
@PostMapping("/cancel") @PreAuthorize("@ss.hasPermission('lab:execution:cancel')")
public CommonResult<Boolean> cancel(@Valid @RequestBody ScanTaskRequests.Task request) { service.cancel(request.getTaskId(),request.getReason()); return success(true); }
@PostMapping("/confirm-stop") @PreAuthorize("@ss.hasPermission('lab:execution:cancel')")

View File

@ -340,7 +340,9 @@ public class DetectionFlowEngine {
Files.writeString(arguments, String.join(System.lineSeparator(), command.subList(1, command.size())
.stream().map(this::launcherArgument).toList()), StandardCharsets.UTF_8);
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
Process process = new ProcessBuilder(command.get(0), "@" + arguments).redirectErrorStream(true).start();
// Standard output is the worker's JSON protocol. JVM diagnostics belong to stderr.
Process process = new ProcessBuilder(command.get(0), "@" + arguments)
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
FutureTask<byte[]> readOutput = new FutureTask<>(() -> process.getInputStream().readNBytes(1_100_000));
Thread reader = new Thread(readOutput, "detection-script-output"); reader.setDaemon(true); reader.start();
try {
@ -349,6 +351,7 @@ public class DetectionFlowEngine {
long remaining = Math.max(0, deadline - System.nanoTime());
if (!process.waitFor(remaining, TimeUnit.NANOSECONDS))
throw new IllegalArgumentException("脚本执行超时(" + timeoutSeconds + "秒,含 JVM 冷启动)");
if (process.exitValue() != 0) throw new IllegalArgumentException("脚本子进程异常退出,退出码:" + process.exitValue());
String text = new String(readOutput.get(2, TimeUnit.SECONDS), StandardCharsets.UTF_8);
JsonNode response = read(text);
if (!response.path("ok").asBoolean(false)) throw new IllegalArgumentException(response.path("error").asText("脚本执行失败"));

View File

@ -15,6 +15,9 @@ public final class DetectionScriptWorker {
if (bytes.length > 2_097_152) throw new IllegalArgumentException("脚本参数超过 2MB");
var request = json.readTree(new String(bytes, StandardCharsets.UTF_8));
var engine = new NashornScriptEngineFactory().getScriptEngine(new String[]{"--language=es6"}, null, className -> false);
// Script print() must not corrupt the JSON response written to System.out.
engine.getContext().setWriter(java.io.Writer.nullWriter());
engine.getContext().setErrorWriter(java.io.Writer.nullWriter());
String wrapped = "(function(){'use strict';\n" + request.path("code").asText() +
"\n;return JSON.stringify(handler(JSON.parse(" + json.writeValueAsString(request.path("params").toString()) + ")));})()";
Object result = engine.eval(wrapped);

View File

@ -91,6 +91,11 @@ public class LabDocumentServiceImpl implements LabDocumentService {
}
private Long persistReport(LabReportSaveReqVO reqVO, boolean integration) {
if (StrUtil.isBlank(reqVO.getTitle())) throw cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException("报告标题不能为空");
requireTextLength(reqVO.getTitle(),256,"报告标题");
requireTextLength(reqVO.getReportType(),32,"报告类型");
requireTextLength(reqVO.getIdempotencyKey(),64,"幂等标识");
requireTextLength(reqVO.getExternalReportNo(),64,"外部报告编号");
String key = StrUtil.blankToDefault(reqVO.getIdempotencyKey(), UUID.randomUUID().toString());
LabReportDO existed = reportMapper.selectByIdempotencyKey(key);
if (existed != null) {
@ -133,6 +138,7 @@ public class LabDocumentServiceImpl implements LabDocumentService {
@Override
@Transactional(rollbackFor = Exception.class)
public void updateDraft(Long id, String contentHtml, String title) {
requireTextLength(title,256,"报告标题");
LabReportDO report = lockReport(id);
List<LabReportVersionDO> versions = versionMapper.selectListByReportId(id);
LabReportVersionDO existingDraft = versions.stream().filter(item -> "DRAFT".equals(item.getStatus()))
@ -169,6 +175,10 @@ public class LabDocumentServiceImpl implements LabDocumentService {
}
}
private static void requireTextLength(String value,int maximum,String label) {
if (value != null && value.length() > maximum) throw cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException(label + "最多" + maximum + "个字符");
}
@Override
@Transactional(rollbackFor = Exception.class)
public void publish(Long id) {

View File

@ -0,0 +1,67 @@
package cn.iocoder.yudao.module.lab.service.execution;
import cn.iocoder.yudao.module.lab.framework.config.LabBizProperties;
import com.cmvr.scanner.*;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.io.*;
import java.nio.file.*;
import java.util.*;
/** Execution-scoped copies keep old exports stable when the vendor reuses output names. */
@Service @RequiredArgsConstructor
public class LabScannerAssetArchive {
private final LabBizProperties properties;
private final ScannerMonitoringService monitoring;
private Path path(Long execution,String file){
CmvrMethodBindingService.requirePrimaryTenant();
if(execution==null||execution<=0||file==null||!file.matches("[a-fA-F0-9]{32}"))throw new ScannerException("invalid_file","成果编号无效",400);
return Path.of(properties.getArtifact().getNasRoot()).toAbsolutePath().normalize().resolve("1").resolve(execution.toString()).resolve("scanner-files").resolve(file);
}
public void archive(Long execution,String instance){
for(JsonNode file:monitoring.assets(instance)){
String id=file.path("fileId").asText();Path target=path(execution,id),temporary=null;
if(Files.isRegularFile(target)&&Files.isRegularFile(target.resolveSibling(id+".json")))continue;
try{
Files.createDirectories(target.getParent());temporary=Files.createTempFile(target.getParent(),id,".part");long bytes=0;
var digest=java.security.MessageDigest.getInstance("SHA-256");
try(var source=monitoring.asset(instance,id);var out=Files.newOutputStream(temporary)){
byte[] buffer=new byte[65536];int n;
while((n=source.stream().read(buffer))!=-1){bytes+=n;if(bytes>100L*1024*1024)throw new IOException("单个成果超过100MiB归档限制");digest.update(buffer,0,n);out.write(buffer,0,n);}
}
if(bytes==0||file.path("bytes").asLong()>0&&bytes!=file.path("bytes").asLong())throw new IOException("成果长度与设备登记不一致");
var metadata=(com.fasterxml.jackson.databind.node.ObjectNode)file.deepCopy();metadata.remove("binding");metadata.put("bytes",bytes);metadata.put("sha256",HexFormat.of().formatHex(digest.digest()));
Files.move(temporary,target,StandardCopyOption.REPLACE_EXISTING);temporary=null;
Files.writeString(target.resolveSibling(id+".json"),metadata.toString(),java.nio.charset.StandardCharsets.UTF_8);
}catch(Exception error){throw new ScannerException("archive_failed","成果归档失败,请保留原扫描工程并重试:"+error.getMessage(),503);}
finally{if(temporary!=null)try{Files.deleteIfExists(temporary);}catch(IOException ignored){}}
}
}
/** The execution directory is the ownership boundary, independent of a live device or command lookup. */
public List<JsonNode> list(Long execution){
Path directory=path(execution,"00000000000000000000000000000000").getParent();
if(!Files.isDirectory(directory))return List.of();
try(var entries=Files.list(directory)){
List<JsonNode> files=new ArrayList<>();
for(Path metadata:entries.filter(p->p.getFileName().toString().matches("[a-fA-F0-9]{32}\\.json")).toList()){
String id=metadata.getFileName().toString().substring(0,32);Path target=directory.resolve(id);
if(!Files.isRegularFile(target))continue;
var record=ScannerRequestValidator.JSON.readTree(Files.readString(metadata));
if(!record.isObject()||record.path("bytes").asLong()<=0||Files.size(target)!=record.path("bytes").asLong())throw new IOException("归档长度校验失败");
var item=(com.fasterxml.jackson.databind.node.ObjectNode)record.deepCopy();item.remove(List.of("binding","sha256"));item.put("fileId",id);item.put("archived",true);files.add(item);
}
files.sort(Comparator.comparingLong((JsonNode file)->file.path("capturedAt").asLong()).reversed().thenComparing(file->file.path("fileId").asText()));
return files;
}catch(IOException error){throw new ScannerException("archive_unavailable","本次执行归档不可读,请检查成果存储",503);}
}
public ScannerHttpClient.Binary open(Long execution,String file){
Path target=path(execution,file),metadata=target.resolveSibling(file+".json");
if(!Files.isRegularFile(target)||!Files.isRegularFile(metadata))return null;
try{
var record=ScannerRequestValidator.JSON.readTree(Files.readString(metadata));
if(Files.size(target)!=record.path("bytes").asLong())throw new IOException("归档长度校验失败");
return new ScannerHttpClient.Binary(Files.newInputStream(target),Map.of("content-type",List.of("application/octet-stream"),"content-length",List.of(String.valueOf(Files.size(target)))));
}catch(IOException error){throw new ScannerException("archive_unavailable","本次执行归档不可读,请检查成果存储",503);}
}
}

View File

@ -15,11 +15,13 @@ import java.util.List;
@Service
@RequiredArgsConstructor
public class LabScannerViewService {
private static final java.util.concurrent.Semaphore STREAM_SLOTS=new java.util.concurrent.Semaphore(4);
private final LabExecutionMapper executions;
private final CmvrExecutionBridge bridge;
private final TaskInstHolder runtime;
private final ScannerProperties settings;
private final ScannerMonitoringService monitoring;
private final LabScannerAssetArchive archives;
public ObjectNode view(Long executionId) {
LabExecutionDO execution=required(executionId);
@ -55,6 +57,28 @@ public class LabScannerViewService {
var link=requiredRuntime(id);
return monitoring.snapshot(link.getCmvrInstId(),key);
}
public void checkStream(Long id) {
var link=requiredRuntime(id);monitoring.status(monitoring.binding(link.getCmvrInstId()));
}
public void stream(Long id,java.io.OutputStream output) throws java.io.IOException {
if(!STREAM_SLOTS.tryAcquire())throw new ScannerException("stream_busy","实时预览连接已满,请关闭其他预览窗口",429);
try {
var link=requiredRuntime(id);JsonNode binding=monitoring.binding(link.getCmvrInstId());
long sequence=binding==null?0:binding.path("baselineSequence").asLong();
try(var source=monitoring.stream(binding)) {
ScannerMonitoringService.Frame frame;
while((frame=source.next())!=null) {
var current=requiredRuntime(id);var latest=monitoring.binding(current.getCmvrInstId());
if(!current.getCmvrInstId().equals(link.getCmvrInstId())||latest==null||!latest.path("commandKey").equals(binding.path("commandKey")))
throw new ScannerException("execution_changed","扫描工程关联已变化,停止原画面流",409);
long next=monitoring.streamSequence(binding,frame);if(next<=sequence)continue;sequence=next;
String header="--scanframe\r\nContent-Type: image/jpeg\r\nContent-Length: "+frame.bytes().length+"\r\nX-Frame-Sequence: "+sequence+"\r\n\r\n";
output.write(header.getBytes(java.nio.charset.StandardCharsets.US_ASCII));output.write(frame.bytes());
output.write(new byte[]{13,10});output.flush();
}
}
}finally{STREAM_SLOTS.release();}
}
public ScannerCommandJournal.Entry snapshotCommand(Long id,String key) {
required(id);var link=bridge.get(id);
if(link==null||link.getCmvrInstId()==null)throw new ScannerException("runtime_pending","没有本次执行的工作流记录",404);
@ -62,12 +86,23 @@ public class LabScannerViewService {
}
public List<JsonNode> assets(Long id) {
required(id);var link=bridge.get(id);
if(link==null||link.getCmvrInstId()==null)return List.of();
return monitoring.assets(link.getCmvrInstId()).stream().map(file->{var value=(ObjectNode)file.deepCopy();value.remove("binding");return (JsonNode)value;}).toList();
var files=new java.util.LinkedHashMap<String,JsonNode>();
if(link!=null&&link.getCmvrInstId()!=null)for(var file:monitoring.assets(link.getCmvrInstId())) {
var value=(ObjectNode)file.deepCopy();value.remove("binding");files.put(value.path("fileId").asText(),value);
}
for(var file:archives.list(id)) {
var existing=files.get(file.path("fileId").asText());
var value=existing==null?(ObjectNode)file.deepCopy():(ObjectNode)existing.deepCopy();
value.setAll((ObjectNode)file);files.put(value.path("fileId").asText(),value);
}
return files.values().stream().sorted(java.util.Comparator.comparingLong((JsonNode file)->file.path("capturedAt").asLong()).reversed()).toList();
}
public ScannerHttpClient.Binary asset(Long id,String fileId) {
required(id);var link=bridge.get(id);
required(id);
var archived=archives.open(id,fileId);if(archived!=null)return archived;
var link=bridge.get(id);
if(link==null||link.getCmvrInstId()==null)throw new ScannerException("file_not_owned","没有本次执行的扫描文件",404);
if(monitoring.assets(link.getCmvrInstId()).stream().noneMatch(file->fileId.equals(file.path("fileId").asText())))throw new ScannerException("file_not_owned","文件不属于本次执行",404);
return monitoring.asset(link.getCmvrInstId(),fileId);
}
private LabExecutionDO required(Long id) {

View File

@ -26,7 +26,7 @@ public class ScanRobotOccupationAdapter implements RobotTaskOccupationGuard {
resources.assertRobotAvailable(canonical,nativeTaskId);
}
@Override public void occupy(String instId,String nativeTaskId,java.util.List<String> robotIds) { resources.occupyNative(instId,nativeTaskId,robotIds); }
@Override public void release(String instId,boolean success) { TenantUtils.execute(1L,()->resources.finishNative(instId,success)); }
@Override public void release(String instId,boolean safeToRelease) { TenantUtils.execute(1L,()->resources.finishNative(instId,safeToRelease)); }
@Override public AutoCloseable manual(String robotId) {
var robot=robots.selectByRobotIdentity(robotId);if(robot==null)robot=robots.selectById(robotId);
String canonical=robot==null?robotId:robot.getRobotId();

View File

@ -8,6 +8,14 @@ import java.util.Set;
/** Physical sample lifecycle policy, independent of HTTP and persistence. */
public final class ScanOnlyRules {
private ScanOnlyRules() {}
/** Keep existing short keys stable; bound longer browser/API keys to varchar(64). */
public static String executionKey(String kind, Long taskId, String requestKey) {
if (!Set.of("SCAN", "SUPPLEMENT").contains(kind) || taskId == null || taskId <= 0
|| blank(requestKey) || requestKey.length() > 128)
throw new IllegalArgumentException("请提供有效的执行幂等标识");
String scoped = kind + "-" + taskId + "-" + requestKey;
return scoped.length() <= 64 ? scoped : cn.hutool.crypto.digest.DigestUtil.sha256Hex(scoped);
}
public static String aggregate(Collection<String> states, boolean stopPending) {
if (stopPending) return "STOP_PENDING";
if (!states.isEmpty() && states.stream().allMatch("SUCCEEDED"::equals)) return "COMPLETED";

View File

@ -17,6 +17,9 @@ public interface ScanOnlyTaskService {
ScanTaskConfigDO releaseResources(ScanTaskRequests.Release request);
ScanTaskConfigDO extendResources(ScanTaskRequests.Extend request);
Long startUnit(ScanTaskRequests.Start request);
Map<String,Object> supplementOption(Long taskId,Long unitId);
Long startSupplement(ScanTaskRequests.Supplement request);
void finishSupplement(ScanTaskRequests.FinishSupplement request);
void cancel(Long taskId,String reason);
void confirmStop(Long taskId,String reason);
void pause(Long taskId);

View File

@ -81,6 +81,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
@Resource private SecurityFrameworkService security;
@Resource private LabBizProperties properties;
@Resource private LabArtifactService artifacts;
@Resource private ScanSupplementWorkflow supplements;
@Resource @Lazy private ScanOnlyTaskServiceImpl self;
@Override public boolean isScanTask(Long taskId) {
@ -136,7 +137,10 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
List<LabExecutionDO> attempts=executions.selectListByTaskId(taskId);List<Map<String,Object>> rows=new ArrayList<>();
for(ScanSampleUnitDO unit:units.byTask(taskId)) {
Map<String,Object> row=JSON.parseObject(JSON.toJSONString(unit),new TypeReference<LinkedHashMap<String,Object>>(){});
row.put("attempts",attempts.stream().filter(e->Objects.equals(unit.getId(),e.getSampleUnitId())).toList());rows.add(row);
row.put("attempts",attempts.stream().filter(e->Objects.equals(unit.getId(),e.getSampleUnitId())).map(e->{
Map<String,Object> value=JSON.parseObject(JSON.toJSONString(e),new TypeReference<LinkedHashMap<String,Object>>(){});
if("SUPPLEMENT".equals(e.getExecutionType()))value.put("supplementCollecting","RUNNING".equals(e.getStatus())&&supplements.collecting(e.getId()));return value;
}).toList());rows.add(row);
}
return map("task",task,"config",c,"units",rows,"flowData",c.getFlowData(),"inputConfig",c.getInputConfig(),
"resourceState",resources.state(c),"recommendations",recommend(c,c.getLengthMm(),c.getWidthMm(),c.getHeightMm()),"attachments",attachmentMapper.selectList(ScanAttachmentDO::getTaskId,taskId));
@ -198,7 +202,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
public Long startUnit(ScanTaskRequests.Start request) {
LabTestTaskDO task=owned(request.getTaskId(),false);ScanTaskConfigDO c=config(task.getId());
if(ScanOnlyRules.blank(request.getIdempotencyKey())||request.getIdempotencyKey().length()>128) throw invalidParamException("请提供有效的执行幂等标识");
String key="SCAN-"+task.getId()+"-"+request.getIdempotencyKey();
String key=ScanOnlyRules.executionKey("SCAN",task.getId(),request.getIdempotencyKey());
LabExecutionDO duplicate=executions.selectByIdempotencyKey(key);
if(duplicate!=null) {
if(!Objects.equals(duplicate.getSampleUnitId(),request.getUnitId())) throw invalidParamException("幂等标识已用于其他单件");
@ -208,6 +212,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
if(Boolean.TRUE.equals(c.getStopPending())||Boolean.TRUE.equals(c.getCancelRequested())) throw invalidParamException("任务正在等待停止确认或已取消");
List<ScanSampleUnitDO> list=units.byTask(task.getId());
ScanSampleUnitDO unit=list.stream().filter(u->Objects.equals(u.getId(),request.getUnitId())).findFirst().orElseThrow(()->invalidParamException("单件不属于当前任务"));
if(unit.getCurrentExecutionId()!=null){var previous=executions.selectById(unit.getCurrentExecutionId());if(previous!=null&&"SUPPLEMENT".equals(previous.getExecutionType()))throw invalidParamException("补扫请使用原工程补扫入口,不能重新执行完整流程");}
rules(()->ScanOnlyRules.validateStart(unit.getStatus(),Boolean.TRUE.equals(request.getLoadedConfirmed()),request.getReason()));
if(list.stream().anyMatch(u->Set.of("RUNNING","PAUSED","QUEUED").contains(u.getStatus()))) throw invalidParamException("同一任务只能逐件执行,请等待当前单件结束");
// Do not skip an earlier pending/failed physical sample accidentally.
@ -242,6 +247,74 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
return id;
}
@Override public Map<String,Object> supplementOption(Long taskId,Long unitId){
primary();LabTestTaskDO task=required(taskId,false);ScanTaskConfigDO c=config(taskId);
try{
var unit=units.byTask(taskId).stream().filter(u->Objects.equals(u.getId(),unitId)).findFirst().orElseThrow(()->invalidParamException("单件不属于当前任务"));
var parent=supplementParent(task,c,unit,null);var context=supplements.context(parent);
return map("available",true,"parentExecutionId",parent.getId().toString(),"parentExecutionNo",parent.getExecutionNo(),"projectId",context.path("projectId").asText(),"physicalSerial",unit.getPhysicalSerial(),
"message","将在原工程继续采集;如已有网格,将撤销当前网格后补扫,旧导出文件保留。");
}catch(RuntimeException error){return map("available",false,"message",safeMessage(error));}
}
private LabExecutionDO supplementParent(LabTestTaskDO task,ScanTaskConfigDO c,ScanSampleUnitDO unit,Long expected){
if(!Set.of("COMPLETED","BLOCKED").contains(task.getStatus())||Boolean.TRUE.equals(c.getCancelRequested())||Boolean.TRUE.equals(c.getStopPending()))throw invalidParamException("请先完成当前任务或确认停止后再补扫");
var list=units.byTask(task.getId());
if(list.stream().anyMatch(u->!Objects.equals(u.getId(),unit.getId())&&!"SUCCEEDED".equals(u.getStatus()))||!Set.of("SUCCEEDED","FAILED").contains(unit.getStatus())||!executions.selectActiveByTaskId(task.getId()).isEmpty())throw invalidParamException("其他样件尚未完成或仍有执行,请先处理当前任务");
if("FAILED".equals(unit.getStatus())){var latest=executions.selectById(unit.getCurrentExecutionId());if(latest==null||!"SUPPLEMENT".equals(latest.getExecutionType()))throw invalidParamException("原扫描失败,请先完成原扫描,不能作为补扫继续");}
var parent=executions.selectListByTaskId(task.getId()).stream().filter(e->Objects.equals(e.getSampleUnitId(),unit.getId())&&"SUCCEEDED".equals(e.getStatus()))
.max(Comparator.comparing(LabExecutionDO::getId)).orElseThrow(()->invalidParamException("该样件没有成功扫描记录,不能补扫"));
if(expected!=null&&!Objects.equals(parent.getId(),expected))throw invalidParamException("扫描成果已更新,请重新核对补扫来源");
return parent;
}
@Override @Transactional(rollbackFor=Exception.class)
public Long startSupplement(ScanTaskRequests.Supplement request){
LabTestTaskDO task=owned(request.getTaskId(),false);ScanTaskConfigDO c=config(task.getId());
if(ScanOnlyRules.blank(request.getIdempotencyKey())||request.getIdempotencyKey().length()>128)throw invalidParamException("请提供有效的补扫幂等标识");
String key=ScanOnlyRules.executionKey("SUPPLEMENT",task.getId(),request.getIdempotencyKey());var duplicate=executions.selectByIdempotencyKey(key);
if(duplicate!=null){if(!"SUPPLEMENT".equals(duplicate.getExecutionType())||!Objects.equals(duplicate.getSampleUnitId(),request.getUnitId())||!Objects.equals(duplicate.getParentExecutionId(),request.getParentExecutionId())||!Objects.equals(duplicate.getReason(),request.getReason())||!Objects.equals(duplicate.getRunParams().get("supplementDurationSeconds"),request.getDurationSeconds()))throw invalidParamException("幂等标识已用于其他补扫请求");return duplicate.getId();}
if(!Boolean.TRUE.equals(request.getSampleConfirmed())||!Boolean.TRUE.equals(request.getFixtureConfirmed())||!Boolean.TRUE.equals(request.getLoadedConfirmed())||ScanOnlyRules.blank(request.getReason())||request.getReason().length()>2000)throw invalidParamException("请填写补扫原因,并重新确认原样件、装夹和现场执行条件");
if(request.getParentExecutionId()==null)throw invalidParamException("请核对补扫来源执行");
if(request.getDurationSeconds()==null||request.getDurationSeconds()<1||request.getDurationSeconds()>1800)throw invalidParamException("补扫时长必须为1至1800秒");
if(!Objects.equals(c.getRevision(),request.getExpectedRevision()))throw invalidParamException("配置已更新,请刷新后重新准备补扫");
var unit=units.byTask(task.getId()).stream().filter(u->Objects.equals(u.getId(),request.getUnitId())).findFirst().orElseThrow(()->invalidParamException("单件不属于当前任务"));
var parent=supplementParent(task,c,unit,request.getParentExecutionId());var context=supplements.context(parent);
if(!robotIds(c).contains(supplements.robotId()))throw invalidParamException("原任务资源与当前扫描工位不一致,不能补扫");
// A completed booking has ended. Acquire a new immediate window; keep the frozen method unchanged.
// A failed supplement can retain its old IN_USE booking after stop confirmation.
// Close/reacquire it in this same transaction so a fresh window is not compared
// with the expired attempt's window and no committed occupation gap is created.
resources.release(task.getId(),false);
c.setResourcesAcquiredAt(null);c.setPlannedStartAt(null);c.setPlannedEndAt(null);c.setReservationMode("IMMEDIATE");c.setExpectedMinutes((request.getDurationSeconds()+59)/60+30);
task.setStatus("PREPARING");var checked=checks(task,c);
if(!Boolean.TRUE.equals(checked.get("passed")))throw invalidParamException("补扫资源或夹具检查未通过:{}",JSON.toJSONString(checked.get("items")));
resources.acquire(task,c);
supplements.archive(parent);supplements.context(parent); // No mesh mutation until all original exports are safely copied.
int attempt=unit.getAttemptNo()+1;Map<String,Object> params=new LinkedHashMap<>();
params.put("_cmvrRobotId",supplements.robotId());params.put("_cmvrRuntimeAssignments",List.of(supplements.assignment()));
params.put("sampleUnitId",unit.getId().toString());params.put("sampleUnitNo",unit.getUnitNo());params.put("attemptNo",attempt);params.put("physicalSerial",Objects.toString(unit.getPhysicalSerial(),""));
params.put("supplementDurationSeconds",request.getDurationSeconds());params.put("supplementSourceExecutionNo",parent.getExecutionNo());
var execution=LabExecutionDO.builder().executionNo(numbers.nextExecutionNo()).taskId(task.getId()).sampleUnitId(unit.getId()).attemptNo(attempt).parentExecutionId(parent.getId()).executionType("SUPPLEMENT")
.methodRefId(parent.getMethodRefId()).methodExternalId(parent.getMethodExternalId()).methodVersion(parent.getMethodVersion()).methodCode(parent.getMethodCode()).scanPlanCode(parent.getScanPlanCode()).scanPlanName(parent.getScanPlanName())
.runParams(params).idempotencyKey(key).dispatchSyncStatus("PUBLISHED").status("QUEUED").scanStage("QUEUED").progress(BigDecimal.ZERO).latestSequence(0L).reason(request.getReason()).version(0)
.publishedAt(LocalDateTime.now()).dispatchedAt(LocalDateTime.now()).acceptedAt(LocalDateTime.now()).startedAt(LocalDateTime.now()).build();
executions.insert(execution);supplements.freeze(execution,parent,context,request.getDurationSeconds());
for(String robot:robotIds(c))acquire(robot,task.getId(),execution.getId());
unit.setStatus("QUEUED");unit.setAttemptNo(attempt);unit.setCurrentExecutionId(execution.getId());units.updateById(unit);
c.setRevision(c.getRevision()+1);configs.updateById(c);task.setStatus("EXECUTING");tasks.updateById(task);
tasks.update(null,new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<LabTestTaskDO>().eq(LabTestTaskDO::getId,task.getId()).set(LabTestTaskDO::getCompletedAt,null));
audit(task,"SCAN_SUPPLEMENT_STARTED",map("unitId",unit.getId(),"executionId",execution.getId(),"sourceExecutionId",parent.getId(),"projectId",context.path("projectId").asText(),"reason",request.getReason(),"durationSeconds",request.getDurationSeconds(),"sampleConfirmed",true,"fixtureConfirmed",true));
Long id=execution.getId();afterCommit(()->{try{bridge.submit(id);}catch(RuntimeException error){log.error("Supplement dispatch failed: {}",id,error);self.onExecutionFinished(id,false,"{}",safeMessage(error));}});return id;
}
@Override @Transactional(rollbackFor=Exception.class)
public void finishSupplement(ScanTaskRequests.FinishSupplement request){
LabTestTaskDO task=owned(request.getTaskId(),false);var c=config(task.getId());var execution=executions.selectById(request.getExecutionId());
if(execution==null||!Objects.equals(execution.getTaskId(),task.getId())||!"SUPPLEMENT".equals(execution.getExecutionType())||!"RUNNING".equals(execution.getStatus())||Boolean.TRUE.equals(c.getStopPending())||Boolean.TRUE.equals(c.getCancelRequested()))throw invalidParamException("当前没有可结束采集的补扫执行");
supplements.finish(execution.getId());audit(task,"SCAN_SUPPLEMENT_FINISH_REQUESTED",map("executionId",execution.getId()));
}
@Override @Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED)
public void onExecutionFinished(Long executionId,boolean success,String outputJson,String error) {
LabExecutionDO reference=executions.selectById(executionId);if(reference==null||!isScanTask(reference.getTaskId()))return;
@ -251,6 +324,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
ScanSampleUnitDO unit=units.selectById(execution.getSampleUnitId());
if(unit==null||!Objects.equals(unit.getCurrentExecutionId(),executionId))return;
boolean cancelled=Boolean.TRUE.equals(c.getCancelRequested());
if(success&&!cancelled)try{supplements.archive(execution);}catch(RuntimeException archiveError){success=false;error=safeMessage(archiveError);}
execution.setStatus(cancelled?"CANCELLED":success?"SUCCEEDED":"FAILED");execution.setScanStage(cancelled?"CANCELLED":success?"COMPLETED":"FAILED");
execution.setSupplierScanStage(execution.getScanStage());execution.setFailureReason(error);execution.setFinishedAt(LocalDateTime.now());
execution.setResultDeliveryStatus(success?"AVAILABLE":"FAILED");if(success)execution.setProgress(new BigDecimal("100"));executions.updateById(execution);
@ -354,6 +428,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
if(Boolean.TRUE.equals(c.getStopPending())||Boolean.TRUE.equals(c.getCancelRequested()))throw invalidParamException("请先处理停止待确认状态");
List<LabExecutionDO> active=executions.selectActiveByTaskId(taskId);if(active.size()!=1)throw invalidParamException("当前没有可控制的执行");
LabExecutionDO e=active.get(0);if(pause&&!"RUNNING".equals(e.getStatus()))throw invalidParamException("当前单件尚未运行或已暂停");
if("SUPPLEMENT".equals(e.getExecutionType()))throw invalidParamException("补扫请使用结束采集并生成成果;如需终止任务请取消并确认停止");
if(!pause&&!"PAUSED".equals(e.getStatus()))throw invalidParamException("当前单件未暂停");
afterCommit(()->{try{if(pause)bridge.pause(e.getId());else bridge.resume(e.getId());}catch(RuntimeException error){self.markControlUncertain(taskId,safeMessage(error));}});
audit(task,pause?"SCAN_PAUSE_REQUESTED":"SCAN_RESUME_REQUESTED",map("executionId",e.getId()));

View File

@ -66,8 +66,8 @@ public class ScanResourceService extends ResourceOccupationStore {
acquireSet("NATIVE:"+instId,host,instId,catalog.lockedResources(runtimeConfig(robots),true,List.of()),instant(),false);
}
@Transactional(rollbackFor=Exception.class)
public void finishNative(String instId,boolean success) {
if(success)jdbc.update("DELETE FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1","NATIVE:"+instId);
public void finishNative(String instId,boolean safeToRelease) {
if(safeToRelease)jdbc.update("DELETE FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1","NATIVE:"+instId);
else jdbc.update("UPDATE lab_resource_occupation SET status='STOP_PENDING' WHERE owner_key=? AND tenant_id=1","NATIVE:"+instId);
}
@Transactional(rollbackFor=Exception.class)

View File

@ -0,0 +1,78 @@
package cn.iocoder.yudao.module.lab.service.scanonly;
import cn.hutool.crypto.digest.DigestUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.lab.dal.dataobject.execution.*;
import cn.iocoder.yudao.module.lab.dal.mysql.execution.LabCmvrExecutionMapper;
import cn.iocoder.yudao.module.lab.service.execution.CmvrMethodBindingService;
import com.alibaba.fastjson2.*;
import com.cmvr.scanner.*;
import com.cmvr.test.mapper.*;
import com.cmvr.test.model.domain.*;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.util.*;
/** An immutable supplemental plan is separate from the user's original published method. */
@Service
public class ScanSupplementWorkflow {
@Resource private ScannerMonitoringService monitoring;
@Resource private ScannerProperties settings;
@Resource private ScannerSupplementSignals signals;
@Resource private LabCmvrExecutionMapper bindings;
@Resource private TeDetectionItemMapper items;
@Resource private TeDetectionItemVersionMapper versions;
@Resource private cn.iocoder.yudao.module.lab.service.execution.LabScannerAssetArchive archives;
public JsonNode context(LabExecutionDO parent){
CmvrMethodBindingService.requirePrimaryTenant();
var link=bindings.selectById(parent.getId());
if(link==null||link.getCmvrInstId()==null)throw new ScannerException("project_not_bound","原执行没有可核对的扫描工程,不能补扫",409);
JsonNode context=monitoring.binding(link.getCmvrInstId());JsonNode status=monitoring.status(context);
if(!status.path("initialized").asBoolean()||!status.path("deviceOnline").asBoolean()||status.path("scanning").asBoolean()||status.path("busy").asBoolean())
throw new ScannerException("scanner_not_ready","扫描仪须在线、就绪且停止采集,才能补扫",409);
if(!Set.of("none","preview","confirmed").contains(status.path("meshState").asText()))throw new ScannerException("mesh_state_unknown","网格状态无法确认,暂不能补扫",409);
return context.deepCopy();
}
public Map<String,Object> assignment(){return Map.of("roleKey","scanner","members",List.of(Map.of("memberKey","scanner","robotId",settings.getRobotId(),"devices",Map.of("scanner",settings.getDeviceId()))));}
public String robotId(){return settings.getRobotId();}
public void finish(Long execution){var link=bindings.selectById(execution);if(link==null)throw new ScannerException("runtime_pending","补扫尚未启动",409);signals.finish(link.getCmvrInstId());}
public boolean collecting(Long execution){var link=bindings.selectById(execution);return link!=null&&link.getCmvrInstId()!=null&&signals.isCollecting(link.getCmvrInstId());}
public void archive(LabExecutionDO execution){var link=bindings.selectById(execution.getId());if(link==null||link.getCmvrInstId()==null)throw new ScannerException("project_not_bound","缺少成果所属执行",409);archives.archive(execution.getId(),link.getCmvrInstId());}
public void freeze(LabExecutionDO execution,LabExecutionDO parent,JsonNode context,int seconds){
var source=bindings.selectById(parent.getId());
String itemId=UUID.randomUUID().toString().replace("-",""),versionId=UUID.randomUUID().toString().replace("-","");
String graph=graph(context,seconds),hash=DigestUtil.sha256Hex(graph+"\n[]");
var item=TeDetectionItem.builder().id(itemId).detectName("补扫 "+execution.getExecutionNo()).detectDesc("来源执行 "+parent.getExecutionNo()+",继续原工程,不新建工程")
.flowData(graph).config("[]").status("0").isDeploy("0").sceneCode("NORMAL").draftRevision(1).draftHash(hash)
.publishedDraftHash(hash).publishedVersionId(versionId).publishedVersionNo(1).build();items.insert(item);
var version=new TeDetectionItemVersion();version.setId(versionId);version.setDetectionItemId(itemId);version.setVersionNo(1);
version.setFlowData(graph);version.setConfig("[]");version.setSchemaVersion(2);version.setContentHash(hash);version.setSourceVersionId(source.getVersionId());
version.setPublishNote("系统补扫方案;来源 "+parent.getExecutionNo()+";"+seconds+"秒,可提前结束采集");version.setCreateBy(Objects.toString(SecurityFrameworkUtils.getLoginUserId(),""));versions.insert(version);
var binding=new LabCmvrExecutionDO();binding.setExecutionId(execution.getId());binding.setTestCaseId(source.getTestCaseId());binding.setDetectionItemId(itemId);
binding.setVersionId(versionId);binding.setVersionNo(1);binding.setFlowData(graph);binding.setInputConfig("[]");binding.setActorUserId(SecurityFrameworkUtils.getLoginUserId());binding.setCmvrStatus("NOT_STARTED");bindings.insert(binding);
}
public static String graph(JsonNode context,int seconds){
if(seconds<1||seconds>1800)throw new IllegalArgumentException("补扫时长必须为1至1800秒");
JSONArray nodes=new JSONArray(),edges=new JSONArray();
JSONObject start=JSONObject.of("name","开始补扫","action","START","schemaVersion",2,"inputParams",new JSONArray(),
"resourceRoles",List.of(Map.of("roleKey","scanner","displayName","原扫描工位","required",true,"deviceSlots",List.of(Map.of("slotKey","scanner","displayName","原扫描仪","deviceKind",14,"required",true,"allowReuse",false)))));
nodes.add(JSONObject.of("id","start","type","start","properties",start,"x",100,"y",180));
String[][] actions={{"prepare","核对原工程并撤销网格","SCANNER_SUPPLEMENT_PREPARE"},{"preview","开启原工程实时预览","SCANNER_PREVIEW_START"},{"scan","继续原样件采集","SCANNER_START"},
{"wait","补扫采集(可提前结束)","SCANNER_SUPPLEMENT_WAIT"},{"stop","停止并确认采集","SCANNER_STOP"},{"mesh","重新生成网格","SCANNER_MESH"},{"confirm","确认补扫网格","SCANNER_MESH_CONFIRM"},{"export","导出补扫PLY与STL","SCANNER_EXPORT"}};
for(String[] a:actions){
JSONArray params=new JSONArray();params.add(JSONObject.of("name","timeoutMs","type","input","input",a[0].equals("wait")?seconds*1000+30000:600000));
params.add(JSONObject.of("name","expectedContextJson","type","input","input",context.toString()));
if(a[0].equals("wait"))params.add(JSONObject.of("name","durationMs","type","input","input",seconds*1000));
params.add(JSONObject.of("name","requestJson","type","input","input",a[0].equals("export")?"{\"formats\":[\"PLY\",\"STL\"]}":"{}"));
var p=JSONObject.of("name",a[1],"action",a[2],"nodeType","EDGE","executionTarget",Map.of("roleKey","scanner","deviceSlotKey","scanner"),"nodeParams",params,"inputParams",new JSONArray());
nodes.add(JSONObject.of("id",a[0],"type","serviceNode","properties",p,"x",100+250*nodes.size(),"y",180));
}
nodes.add(JSONObject.of("id","end","type","end","properties",JSONObject.of("name","补扫成果已生成","action","END"),"x",100+250*nodes.size(),"y",180));
for(int i=1;i<nodes.size();i++)edges.add(JSONObject.of("id","edge-"+i,"sourceNodeId",nodes.getJSONObject(i-1).getString("id"),"targetNodeId",nodes.getJSONObject(i).getString("id")));
return JSONObject.of("schemaVersion",2,"nodes",nodes,"edges",edges).toJSONString();
}
}

View File

@ -44,6 +44,15 @@ public final class ScanTaskRequests {
@NotBlank @Size(max=2048) private String fileUrl;
@Size(max=64) private String fileType;
}
@Data public static class Supplement {
@NotNull private Long taskId,unitId,parentExecutionId;
@NotNull private Integer expectedRevision;
@NotBlank @Size(max=128) private String idempotencyKey;
@NotBlank @Size(max=2000) private String reason;
@NotNull @AssertTrue private Boolean sampleConfirmed,fixtureConfirmed,loadedConfirmed;
@NotNull @Min(1) @Max(1800) private Integer durationSeconds;
}
@Data public static class FinishSupplement { @NotNull private Long taskId,executionId; }
@Data public static class FixtureRange {
@NotNull private Long fixtureId;
@NotNull @DecimalMin("0.001") private BigDecimal maxLengthMm,maxWidthMm,maxHeightMm;

View File

@ -78,13 +78,22 @@ public class DetectionFlowEngineTest {
/** 脚本异常必须留下失败日志并终止工作流。 */
@Test void persistsScriptFailure() {
var result = engine.execute(graph("""
{"id":"a","type":"code","data":{"params":{"code":"function handler(p){throw new Error('sensor invalid');}"}}}
{"id":"a","type":"code","data":{"params":{"code":"function handler(p){print('diagnostic before failure');throw new Error('sensor invalid');}"}}}
""", ""), Map.of(), ignored -> {});
assertFalse(result.success());
assertTrue(result.error().contains("sensor invalid"));
assertEquals("FAILED", result.logs().get(result.logs().size()-1).status());
}
/** 脚本打印内容不得破坏返回协议或替代真实计算结果。 */
@Test void scriptConsoleOutputCannotCorruptStructuredResult() {
var result = engine.execute(graph("""
{"id":"a","type":"code","data":{"params":{"code":"function handler(p){print('diagnostic before result');return {answer:42};}"}}}
""", ""), Map.of(), ignored -> {});
assertTrue(result.success(), result.error());
assertEquals(42, result.output().path("a").path("result").path("answer").asInt());
}
/** 缺失引用必须失败,不能把空值带入检测判定。 */
@Test void rejectsUnavailableReference() {
var result = engine.execute(graph("""

View File

@ -0,0 +1,49 @@
package cn.iocoder.yudao.module.lab.service.execution;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.lab.framework.config.LabBizProperties;
import com.cmvr.scanner.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
class LabScannerAssetArchiveTest {
@TempDir Path directory;
ScannerMonitoringService monitoring=mock(ScannerMonitoringService.class);
LabScannerAssetArchive archive;
final String file="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
@BeforeEach void setup(){TenantContextHolder.setTenantId(1L);var properties=new LabBizProperties();properties.getArtifact().setNasRoot(directory.toString());archive=new LabScannerAssetArchive(properties,monitoring);}
@AfterEach void cleanup(){TenantContextHolder.clear();}
@Test void oldFileStaysStableWhenSupplierFileChangesAndRepeatedArchiveDoesNotRedownload() throws Exception {
when(monitoring.assets("inst")).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\""+file+"\",\"name\":\"old.stl\",\"bytes\":3}")));
when(monitoring.asset("inst",file)).thenReturn(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[]{1,2,3}),Map.of()));
archive.archive(7L,"inst");archive.archive(7L,"inst");verify(monitoring,times(1)).asset("inst",file);
try(var saved=archive.open(7L,file)){assertArrayEquals(new byte[]{1,2,3},saved.stream().readAllBytes());}
assertNull(archive.open(8L,file));assertThrows(ScannerException.class,()->archive.open(7L,"../wrong"));
TenantContextHolder.setTenantId(2L);assertThrows(RuntimeException.class,()->archive.open(7L,file));
}
@Test void incompleteDownloadNeverBecomesAnArchivedResult() throws Exception {
when(monitoring.assets("inst")).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\""+file+"\",\"bytes\":4}")));
when(monitoring.asset("inst",file)).thenReturn(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[]{1}),Map.of()));
assertThrows(ScannerException.class,()->archive.archive(7L,"inst"));assertNull(archive.open(7L,file));
try(var paths=Files.walk(directory)){assertFalse(paths.anyMatch(p->p.getFileName().toString().endsWith(".part")));}
}
@Test void durableListSurvivesMissingCommandRecordsAndKeepsExecutionsSeparate() throws Exception {
when(monitoring.assets("inst")).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\""+file+"\",\"name\":\"original.ply\",\"bytes\":3,\"projectId\":\"old-project\",\"capturedAt\":456,\"binding\":{\"endpoint\":\"private\"}}")));
when(monitoring.asset("inst",file)).thenReturn(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[]{1,2,3}),Map.of()));
archive.archive(7L,"inst");reset(monitoring);
var listed=archive.list(7L);assertEquals(1,listed.size());assertEquals(file,listed.get(0).path("fileId").asText());assertEquals("old-project",listed.get(0).path("projectId").asText());assertEquals(456,listed.get(0).path("capturedAt").asLong());assertFalse(listed.get(0).has("binding"));assertFalse(listed.get(0).has("sha256"));
assertTrue(archive.list(8L).isEmpty());verifyNoInteractions(monitoring);
TenantContextHolder.setTenantId(2L);assertThrows(RuntimeException.class,()->archive.list(7L));
}
@Test void legacyMetadataIsListedButBrokenArchiveDoesNotPretendToBeEmpty() throws Exception {
Path target=directory.resolve("1/7/scanner-files/"+file);Files.createDirectories(target.getParent());Files.write(target,new byte[]{1,2,3});
Files.writeString(target.resolveSibling(file+".json"),"{\"name\":\"legacy.stl\",\"bytes\":3,\"sha256\":\"old\"}");
assertEquals("legacy.stl",archive.list(7L).get(0).path("name").asText());
Files.write(target,new byte[]{1});assertEquals("archive_unavailable",assertThrows(ScannerException.class,()->archive.list(7L)).scannerCode);
}
}

View File

@ -0,0 +1,31 @@
package cn.iocoder.yudao.module.lab.service.execution;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.lab.controller.admin.cmvr.LabScannerViewController;
import com.cmvr.scanner.ScannerException;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class LabScannerStreamControllerTest {
@AfterEach void cleanup(){TenantContextHolder.clear();}
@Test void asyncStreamRestoresTenantAndChecksAccessBeforeOpeningResponse() throws Exception {
var service=mock(LabScannerViewService.class);var controller=new LabScannerViewController(service);
TenantContextHolder.setTenantId(1L);
var response=controller.stream(42L);verify(service).checkStream(42L);
assertTrue(response.getHeaders().getContentType().toString().startsWith("multipart/x-mixed-replace"));
assertEquals("no",response.getHeaders().getFirst("X-Accel-Buffering"));
TenantContextHolder.setTenantId(7L);TenantContextHolder.setIgnore(true);
doAnswer(call->{assertEquals(1L,TenantContextHolder.getTenantId());assertFalse(TenantContextHolder.isIgnore());return null;})
.when(service).stream(eq(42L),any());
response.getBody().writeTo(new java.io.ByteArrayOutputStream());
assertEquals(7L,TenantContextHolder.getTenantId());assertTrue(TenantContextHolder.isIgnore());
}
@Test void projectChangeEndsStreamWithoutAppendingJsonAndRestoresTenant() throws Exception {
var service=mock(LabScannerViewService.class);var controller=new LabScannerViewController(service);
TenantContextHolder.setTenantId(1L);var response=controller.stream(42L);TenantContextHolder.clear();
doThrow(new ScannerException("project_changed","changed",409)).when(service).stream(eq(42L),any());
var output=new java.io.ByteArrayOutputStream();response.getBody().writeTo(output);
assertEquals(0,output.size());assertNull(TenantContextHolder.getTenantId());assertFalse(TenantContextHolder.isIgnore());
}
}

View File

@ -17,7 +17,8 @@ class LabScannerViewServiceTest {
private final TaskInstHolder runtime=mock(TaskInstHolder.class);
private final ScannerMonitoringService monitoring=mock(ScannerMonitoringService.class);
private final ScannerProperties settings=new ScannerProperties();
private final LabScannerViewService views=new LabScannerViewService(executions,bridge,runtime,settings,monitoring);
private final LabScannerAssetArchive archives=mock(LabScannerAssetArchive.class);
private final LabScannerViewService views=new LabScannerViewService(executions,bridge,runtime,settings,monitoring,archives);
private LabExecutionDO execution;
@BeforeEach void setup(){
@ -43,6 +44,22 @@ class LabScannerViewServiceTest {
execution.setStatus("SUCCEEDED");assertFalse(views.view(1L).path("available").asBoolean());
assertThrows(ScannerException.class,()->views.image(1L));verifyNoInteractions(monitoring);
}
@Test void originalAndSupplementAssetsStaySeparatedAndArchivesDoNotNeedRuntime() throws Exception {
execution.setStatus("SUCCEEDED");when(bridge.get(1L)).thenReturn(null);
var file=ScannerRequestValidator.parse("{\"fileId\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\":\"original.ply\",\"bytes\":3,\"archived\":true}");
when(archives.list(1L)).thenReturn(List.of(file));
assertEquals("original.ply",views.assets(1L).get(0).path("name").asText());
var binary=new ScannerHttpClient.Binary(new java.io.ByteArrayInputStream(new byte[]{1,2,3}),Map.of());
when(archives.open(1L,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")).thenReturn(binary);
try(var saved=views.asset(1L,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")){assertArrayEquals(new byte[]{1,2,3},saved.stream().readAllBytes());}
assertThrows(ScannerException.class,()->views.asset(1L,"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
verifyNoInteractions(monitoring,runtime);
}
@Test void mergesArchivedAndJournalMetadataWithoutDuplicatesOrPrivateBinding(){
when(monitoring.assets("inst-1")).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\"a\",\"capturedAt\":123,\"projectId\":\"original\",\"binding\":{\"endpoint\":\"private\"}}")));
when(archives.list(1L)).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\"a\",\"name\":\"old.ply\",\"archived\":true}")));
var files=views.assets(1L);assertEquals(1,files.size());assertEquals(123,files.get(0).path("capturedAt").asLong());assertEquals("original",files.get(0).path("projectId").asText());assertFalse(files.get(0).has("binding"));
}
@Test void blocksWrongTenantInactiveRuntimeAndWrongWorkstation(){
TenantContextHolder.setTenantId(2L);assertThrows(RuntimeException.class,()->views.view(1L));
TenantContextHolder.setTenantId(1L);when(runtime.getContext("inst-1")).thenReturn(null);
@ -62,4 +79,29 @@ class LabScannerViewServiceTest {
@Test void emptyConfigurationShowsPendingWithoutContactingHardware(){
settings.setHost("");assertEquals("not_configured",views.view(1L).path("state").asText());verifyNoInteractions(monitoring);
}
@Test void streamsOneConnectionAndStopsBeforePublishingAFrameFromCompletedExecution() throws Exception {
byte[] jpeg={(byte)255,(byte)216,(byte)255,(byte)217};
var raw=new java.io.ByteArrayOutputStream();
for(int sequence=1;sequence<=2;sequence++) {
raw.write(("--frame\r\nContent-Type: image/jpeg\r\nContent-Length: 4\r\nX-Frame-Sequence: "+sequence+"\r\n\r\n").getBytes());
raw.write(jpeg);raw.write(new byte[]{13,10});
}
var source=new ScannerPreviewStream(new ScannerHttpClient.Binary(new java.io.ByteArrayInputStream(raw.toByteArray()),Map.of("content-type",List.of("multipart/x-mixed-replace; boundary=frame"))));
when(monitoring.stream(any())).thenReturn(source);when(monitoring.streamSequence(any(),any())).thenReturn(1L,2L);
var done=LabExecutionDO.builder().id(1L).taskId(2L).status("FAILED").build();
when(executions.selectById(1L)).thenReturn(execution,execution,done);
var output=new java.io.ByteArrayOutputStream();
assertThrows(ScannerException.class,()->views.stream(1L,output));
String sent=output.toString(java.nio.charset.StandardCharsets.ISO_8859_1);
assertTrue(sent.contains("X-Frame-Sequence: 1"));assertFalse(sent.contains("X-Frame-Sequence: 2"));
verify(monitoring,times(1)).stream(any());
}
@Test void rejectsHistoricalStreamAndReleasesSlotEvenWhenValidationFails() {
execution.setStatus("FAILED");
for(int attempt=0;attempt<8;attempt++) {
var failure=assertThrows(ScannerException.class,()->views.stream(1L,new java.io.ByteArrayOutputStream()));
assertEquals("execution_finished",failure.scannerCode);
}
verifyNoInteractions(monitoring);
}
}

View File

@ -43,4 +43,22 @@ class ReportRevisionTest {
assertThrows(cn.iocoder.yudao.framework.common.exception.ServiceException.class,()->service.publish(1L));
verifyNoInteractions(versions);
}
@Test void oversizedReportFieldsAreRejectedBeforeAnyDatabaseWrite(){
for (String field:List.of("title","reportType","idempotencyKey","externalReportNo")) {
var request=new cn.iocoder.yudao.module.lab.controller.admin.document.vo.LabReportSaveReqVO();request.setTaskId(1L);request.setTitle("valid");
ReflectionTestUtils.setField(request,field,"x".repeat(field.equals("title")?257:field.equals("reportType")?33:65));
assertThrows(cn.iocoder.yudao.framework.common.exception.ServiceException.class,()->service.createReport(request));
}
verifyNoInteractions(reports,versions);
}
@Test void oversizedRevisionCannotCreateDraftOrChangePublishedReport(){
assertThrows(cn.iocoder.yudao.framework.common.exception.ServiceException.class,()->service.updateDraft(1L,"new content","x".repeat(257)));
verifyNoInteractions(reports,versions);
}
@Test void maximumLengthTitleIsAcceptedWithoutTruncation(){
var draft=LabReportVersionDO.builder().id(12L).versionNo(2).status("DRAFT").build();
when(versions.selectListByReportId(1L)).thenReturn(List.of(draft));
String title="x".repeat(256);service.updateDraft(1L,"content",title);
assertEquals(title,report.getTitle());verify(reports).updateById(report);
}
}

View File

@ -6,6 +6,24 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
public class ScanOnlyRulesTest {
@Test void browserUuidAndMaximumApiKeysFitTheDatabaseAndRemainTaskScoped() {
long task=2113518333730902017L;
String browserKey="50eb650e-9a18-43db-bc91-745f8c783423";
assertTrue(("SUPPLEMENT-"+task+"-"+browserKey).length()>64);
for(String kind:List.of("SCAN","SUPPLEMENT"))for(String input:List.of(browserKey,"a".repeat(128),"b".repeat(32))){
String key=ScanOnlyRules.executionKey(kind,task,input);
assertTrue(key.length()<=64);assertEquals(key,ScanOnlyRules.executionKey(kind,task,input));
assertNotEquals(key,ScanOnlyRules.executionKey(kind,task+1,input));
String different=(input.charAt(0)=='z'?"y":"z")+input.substring(1);
assertNotEquals(key,ScanOnlyRules.executionKey(kind,task,different));
}
}
@Test void shortExistingKeysStayCompatibleAndInvalidKeysAreRejected() {
assertEquals("SCAN-1-short-key",ScanOnlyRules.executionKey("SCAN",1L,"short-key"));
assertEquals("SUPPLEMENT-1-short-key",ScanOnlyRules.executionKey("SUPPLEMENT",1L,"short-key"));
for(String invalid:List.of(""," ","x".repeat(129)))assertThrows(IllegalArgumentException.class,()->ScanOnlyRules.executionKey("SUPPLEMENT",1L,invalid));
assertThrows(IllegalArgumentException.class,()->ScanOnlyRules.executionKey("OTHER",1L,"key"));
}
@Test void taskCompletesOnlyWhenAllPhysicalUnitsSucceeded() {
assertEquals("PREPARING", ScanOnlyRules.aggregate(List.of("SUCCEEDED", "PENDING", "PENDING"), false));
assertEquals("BLOCKED", ScanOnlyRules.aggregate(List.of("SUCCEEDED", "FAILED", "PENDING"), false));

View File

@ -38,6 +38,7 @@ class ScanOnlyTaskServiceTest {
private ScanSampleUnitMapper units;
private ScanRobotOccupationMapper occupations;
private ScanResourceService resources;
private ScanSupplementWorkflow supplements;
@BeforeEach void setup() {
service=new ScanOnlyTaskServiceImpl(); tasks=mock(LabTestTaskMapper.class); configs=mock(ScanTaskConfigMapper.class);
executions=mock(LabExecutionMapper.class);
@ -46,6 +47,7 @@ class ScanOnlyTaskServiceTest {
units=mock(ScanSampleUnitMapper.class);occupations=mock(ScanRobotOccupationMapper.class);
ReflectionTestUtils.setField(service,"units",units);ReflectionTestUtils.setField(service,"occupations",occupations);
resources=mock(ScanResourceService.class);ReflectionTestUtils.setField(service,"resources",resources);
supplements=mock(ScanSupplementWorkflow.class);ReflectionTestUtils.setField(service,"supplements",supplements);
ReflectionTestUtils.setField(service,"timeline",mock(LabTaskTimelineMapper.class));ReflectionTestUtils.setField(service,"events",mock(LabExecutionEventMapper.class));
TenantContextHolder.setTenantId(1L); identity=mockStatic(SecurityFrameworkUtils.class); identity.when(SecurityFrameworkUtils::getLoginUserId).thenReturn(7L);
}
@ -148,22 +150,36 @@ class ScanOnlyTaskServiceTest {
List<?> items=(List<?>)result.get("items");assertTrue(items.stream().anyMatch(row->row instanceof Map<?,?> r&&"RELEASE".equals(r.get("code"))&&Boolean.FALSE.equals(r.get("passed"))));
verify(methods,never()).ensureMethod(anyString(),anyString());
}
@Test void thirdUnitSuccessCompletesTaskWithoutResultsOrReport(@org.junit.jupiter.api.io.TempDir java.nio.file.Path outputRoot) throws Exception {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings={"INITIAL","RETEST","SUPPLEMENT"})
void thirdUnitSuccessArchivesEveryScanTypeBeforeCompletingTask(String type,@org.junit.jupiter.api.io.TempDir java.nio.file.Path outputRoot) throws Exception {
LabTestTaskDO task=task();ScanTaskConfigDO c=config();c.setStopPending(false);c.setCancelRequested(false);
LabExecutionDO e=LabExecutionDO.builder().id(2L).taskId(1L).sampleUnitId(3L).status("RUNNING").build();e.setTenantId(1L);
LabExecutionDO e=LabExecutionDO.builder().id(2L).taskId(1L).sampleUnitId(3L).executionType(type).status("RUNNING").build();e.setTenantId(1L);
ScanSampleUnitDO one=new ScanSampleUnitDO();one.setStatus("SUCCEEDED");ScanSampleUnitDO two=new ScanSampleUnitDO();two.setStatus("SUCCEEDED");
ScanSampleUnitDO three=new ScanSampleUnitDO();three.setId(3L);three.setCurrentExecutionId(2L);three.setStatus("RUNNING");
when(executions.selectById(2L)).thenReturn(e);when(executions.selectByIdForUpdate(2L)).thenReturn(e);when(units.selectById(3L)).thenReturn(three);when(units.byTask(1L)).thenReturn(List.of(one,two,three));
LabBizProperties properties=new LabBizProperties();properties.getArtifact().setNasRoot(outputRoot.toString());
ReflectionTestUtils.setField(service,"properties",properties);ReflectionTestUtils.setField(service,"artifacts",mock(LabArtifactService.class));
service.onExecutionFinished(2L,true,"{}",null);
verify(supplements).archive(e);
assertEquals("SUCCEEDED",three.getStatus());assertEquals("COMPLETED",task.getStatus());assertNotNull(task.getCompletedAt());
verify(occupations).release(1L,1L);
service.onExecutionFinished(2L,true,"{}",null);verify(occupations,times(1)).release(1L,1L);
verify(supplements,times(1)).archive(e);
}
private LabTestTaskDO task(){
LabTestTaskDO task=LabTestTaskDO.builder().id(1L).ownerId(7L).status("EXECUTING").processType("SCAN_ONLY").build();
when(tasks.selectById(1L)).thenReturn(task);when(tasks.selectByIdForUpdate(1L)).thenReturn(task);return task;
}
@Test void failedNormalExportArchiveCannotBeReportedAsSuccessful(@org.junit.jupiter.api.io.TempDir java.nio.file.Path outputRoot) {
LabTestTaskDO task=task();ScanTaskConfigDO c=config();c.setStopPending(false);c.setCancelRequested(false);
var execution=LabExecutionDO.builder().id(2L).taskId(1L).sampleUnitId(3L).executionType("INITIAL").status("RUNNING").build();execution.setTenantId(1L);
var unit=new ScanSampleUnitDO();unit.setId(3L);unit.setCurrentExecutionId(2L);unit.setStatus("RUNNING");
when(executions.selectById(2L)).thenReturn(execution);when(executions.selectByIdForUpdate(2L)).thenReturn(execution);when(units.selectById(3L)).thenReturn(unit);when(units.byTask(1L)).thenReturn(List.of(unit));
var properties=new LabBizProperties();properties.getArtifact().setNasRoot(outputRoot.toString());ReflectionTestUtils.setField(service,"properties",properties);ReflectionTestUtils.setField(service,"artifacts",mock(LabArtifactService.class));
doThrow(new IllegalStateException("archive disk full")).when(supplements).archive(execution);
service.onExecutionFinished(2L,true,"{}",null);
assertEquals("FAILED",execution.getStatus());assertEquals("FAILED",unit.getStatus());assertNotEquals("COMPLETED",task.getStatus());assertTrue(execution.getFailureReason().contains("archive disk full"));
}
private ScanTaskConfigDO config(){ScanTaskConfigDO c=new ScanTaskConfigDO();c.setTaskId(1L);c.setRuntimeAssignments(List.of());when(configs.byTask(1L)).thenReturn(c);return c;}
}

View File

@ -77,6 +77,21 @@ class ScanResourceServiceTest {
tx.executeWithoutResult(s->service.release(1L,false));assertEquals(0,count("lab_resource_occupation"));
assertEquals("FINISHED",jdbc.queryForObject("SELECT status FROM lab_device_reservation",String.class));
}
@Test void unconfirmedNativeStopKeepsAllLeasesUntilAcknowledgement() {
tx.executeWithoutResult(s->service.acquireSet("NATIVE:trial",null,"trial",resources("r1",101),window(),false));
tx.executeWithoutResult(s->service.finishNative("trial",false));
assertEquals(3,count("lab_resource_occupation"));
assertEquals(3,jdbc.queryForObject("SELECT COUNT(*) FROM lab_resource_occupation WHERE status='STOP_PENDING'",Integer.class));
tx.executeWithoutResult(s->service.finishNative("trial",true));
assertEquals(0,count("lab_resource_occupation"));
}
@Test void acknowledgedNativeStopReleasesOnlyItsOwnLease() {
tx.executeWithoutResult(s->service.acquireSet("NATIVE:trial",null,"trial",resources("r1",101),window(),false));
jdbc.update("INSERT INTO lab_resource_occupation(id,resource_key,resource_type,resource_id,owner_key,status) VALUES(999,'R:other','ROBOT','other','NATIVE:other','HELD')");
tx.executeWithoutResult(s->service.finishNative("trial",true));
assertEquals(1,count("lab_resource_occupation"));
assertEquals("NATIVE:other",jdbc.queryForObject("SELECT owner_key FROM lab_resource_occupation",String.class));
}
@Test void differentRobotsCannotShareAnExclusiveLabAndFailureRollsBackAllClaims() {
acquire(1,"r1",101);
assertThrows(RuntimeException.class,()->acquire(2,"r2",102));

View File

@ -0,0 +1,45 @@
package cn.iocoder.yudao.module.lab.service.scanonly;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.lab.dal.dataobject.execution.*;
import cn.iocoder.yudao.module.lab.dal.mysql.execution.LabCmvrExecutionMapper;
import com.alibaba.fastjson2.*;
import com.cmvr.scanner.*;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.operator.edge.WorkcellNodeContract;
import org.junit.jupiter.api.*;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class ScanSupplementWorkflowTest {
private final ScanSupplementWorkflow service=new ScanSupplementWorkflow();
private final ScannerMonitoringService monitor=mock(ScannerMonitoringService.class);
private final LabCmvrExecutionMapper bindings=mock(LabCmvrExecutionMapper.class);
@BeforeEach void setup(){TenantContextHolder.setTenantId(1L);ReflectionTestUtils.setField(service,"monitoring",monitor);ReflectionTestUtils.setField(service,"bindings",bindings);}
@AfterEach void cleanup(){TenantContextHolder.clear();}
@Test void generatedFrozenPlanNeverCreatesOrSwitchesProjectsAndAllNodesPassContracts(){
var context=ScannerRequestValidator.parse("{\"endpoint\":\"e\",\"sessionId\":\"s\",\"projectId\":\"p\",\"robotId\":\"r\",\"deviceId\":\"d\"}");
var graph=JSON.parseObject(ScanSupplementWorkflow.graph(context,60));var nodes=graph.getJSONArray("nodes");
List<String> actions=new ArrayList<>();
for(int i=0;i<nodes.size();i++){
var p=nodes.getJSONObject(i).getJSONObject("properties");String action=p.getString("action");actions.add(action);
if(!"EDGE".equals(p.getString("nodeType")))continue;
JSONObject input=new JSONObject();for(Object value:p.getJSONArray("nodeParams")){var parameter=(JSONObject)value;input.put(parameter.getString("name"),parameter.get("input"));}
WorkcellNodeContract.validate(ActionEnum.fromAction(action),input);
assertEquals(context.toString(),input.getString("expectedContextJson"));
}
assertEquals(List.of("START","SCANNER_SUPPLEMENT_PREPARE","SCANNER_PREVIEW_START","SCANNER_START","SCANNER_SUPPLEMENT_WAIT","SCANNER_STOP","SCANNER_MESH","SCANNER_MESH_CONFIRM","SCANNER_EXPORT","END"),actions);
assertEquals(nodes.size()-1,graph.getJSONArray("edges").size());
}
@Test void disconnectedBusyOrChangedOriginalSessionIsUnavailable(){
var parent=LabExecutionDO.builder().id(1L).status("SUCCEEDED").build();var link=new LabCmvrExecutionDO();link.setCmvrInstId("old");when(bindings.selectById(1L)).thenReturn(link);
var context=ScannerRequestValidator.parse("{\"projectId\":\"p\"}");when(monitor.binding("old")).thenReturn(context);
when(monitor.status(context)).thenReturn(ScannerRequestValidator.parse("{\"initialized\":true,\"deviceOnline\":true,\"meshState\":\"confirmed\"}"));
assertEquals(context,service.context(parent));
when(monitor.status(context)).thenReturn(ScannerRequestValidator.parse("{\"initialized\":true,\"deviceOnline\":true,\"busy\":true,\"meshState\":\"none\"}"));assertThrows(ScannerException.class,()->service.context(parent));
when(monitor.status(context)).thenThrow(new ScannerException("project_changed","工程已切换",409));assertThrows(ScannerException.class,()->service.context(parent));
TenantContextHolder.setTenantId(2L);assertThrows(RuntimeException.class,()->service.context(parent));
}
}

View File

@ -1,8 +1,8 @@
cmvr:
scanner:
# 待现场确认。端口为空时不连接设备;18888/18890不能混用。
host: ${AM_FREESCAN_SCANNER_HOST:}
port: ${AM_FREESCAN_SCANNER_PORT:}
# 现场API地址;访问密钥待配置。18888为API端口,不能使用18890网页代理端口。
host: ${AM_FREESCAN_SCANNER_HOST:192.168.0.121}
port: ${AM_FREESCAN_SCANNER_PORT:18888}
api-key: ${AM_FREESCAN_SCANNER_API_KEY:}
robot-id: ${AM_FREESCAN_SCANNER_ROBOT_ID:}
device-id: ${AM_FREESCAN_SCANNER_DEVICE_ID:}
@ -12,6 +12,8 @@ cmvr:
poll-interval-ms: 500
spring:
config:
import: optional:file:./.local/scanner-private.yaml
application:
name: am-freescan
profiles:

View File

@ -2,7 +2,9 @@
VITE_APP_TITLE=AM FreeScan
VITE_PORT=5180
VITE_OPEN=false
VITE_BASE_URL=http://localhost:48090
# 页面与接口使用同一入口,兼容 localhost 和局域网 IP。
VITE_BASE_URL=
VITE_DEV_PROXY_TARGET=http://127.0.0.1:48090
VITE_API_URL=/admin-api
VITE_BASE_PATH=/
VITE_APP_TENANT_ENABLE=true

View File

@ -4,7 +4,8 @@ NODE_ENV=development
VITE_DEV=true
# 请求路径
VITE_BASE_URL=http://localhost:48090
VITE_BASE_URL=
VITE_DEV_PROXY_TARGET=http://127.0.0.1:48090
# 文件上传类型:server - 后端上传, client - 前端直连上传,仅支持 S3 服务
VITE_UPLOAD_TYPE=server

View File

@ -9,6 +9,7 @@ export interface LabExecutionVO {
taskNo?: string
parentExecutionId?: number | string
executionType: string
supplementCollecting?: boolean
methodRefId?: number | string
methodExternalId?: string
methodVersion?: string

View File

@ -108,6 +108,10 @@ export interface ScanPrecheck {
items: { code: string; passed: boolean; message: string }[]
}
const base = '/lab/scan-task'
export interface SupplementOption { available: boolean; parentExecutionId?: Id; parentExecutionNo?: string; projectId?: string; physicalSerial?: string; message?: string }
export const getSupplementOption = (taskId: Id, unitId: Id) => request.get<SupplementOption>({ url: base + '/supplement-option', params: { taskId, unitId } })
export const startSupplement = (data: { taskId: Id; unitId: Id; parentExecutionId: Id; expectedRevision: number; durationSeconds: number; reason: string; idempotencyKey: string; sampleConfirmed: boolean; fixtureConfirmed: boolean; loadedConfirmed: boolean }) => request.post<Id>({ url: base + '/supplement', data })
export const finishSupplement = (taskId: Id, executionId: Id) => request.post({ url: base + '/finish-supplement', data: { taskId, executionId } })
export const acquireResources = (taskId: Id, expectedRevision: number) =>
request.post<ScanConfig>({ url: base + '/acquire-resources', data: { taskId, expectedRevision } })
export const releaseResources = (taskId: Id, reason: string) =>

View File

@ -1,6 +1,7 @@
import request from '@/config/axios'
import { getAccessToken, getTenantId, getVisitTenantId } from '@/utils/auth'
import { readScannerBinary } from '@/views/lab/scan-task/scannerBinary.mjs'
import { consumeScannerMjpeg } from '@/cmvr/common/utils/scannerMjpeg.mjs'
export interface ScannerExecutionView {
executionId: string
@ -61,3 +62,15 @@ export async function getScannerExecutionImage(executionId: string | number, sig
}
return response.blob()
}
export async function streamScannerExecution(executionId: string | number, onFrame: (bytes: Uint8Array) => void, signal: AbortSignal) {
const response = await fetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/stream?executionId=${encodeURIComponent(executionId)}`, {
headers: scannerHeaders(), signal, cache: 'no-store'
})
if (!response.ok || !response.headers.get('content-type')?.startsWith('multipart/x-mixed-replace') || !response.body) {
const error = await response.json().catch(() => ({}))
throw new Error(error.msg || '扫描流暂不可用,正在重新核对状态')
}
await consumeScannerMjpeg(response.body, onFrame, signal)
if (!signal.aborted) throw new Error('扫描流已断开,正在重新连接')
}

View File

@ -73,6 +73,7 @@ export function flowView(data) {
export function flowPause(instId) {
return request({
url: `/flow/pause/${instId}`,
timeout: 300000,
method: 'post'
})
}
@ -80,6 +81,7 @@ export function flowPause(instId) {
export function flowResume(instId) {
return request({
url: `/flow/resume/${instId}`,
timeout: 300000,
method: 'post'
})
}
@ -87,6 +89,7 @@ export function flowResume(instId) {
export function flowStop(instId) {
return request({
url: `/flow/stop/${instId}`,
timeout: 300000,
method: 'post'
})
}

View File

@ -0,0 +1,18 @@
// Hold one control request through its response handling, including errors.
export function createFlowControlGate(onPending) {
let pending = false
return {
async run(action, request) {
if (pending) return false
pending = true
onPending(action)
try {
await request()
return true
} finally {
pending = false
onPending('')
}
}
}
}

View File

@ -0,0 +1,32 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { createFlowControlGate } from './flowControlGate.mjs'
test('终止请求及响应处理完成前,重复终止与暂停恢复都不下发', async () => {
const states = [], calls = []
const gate = createFlowControlGate(action => states.push(action))
let finish, handleResponse
const first = gate.run('stop', async () => {
calls.push('stop')
await new Promise(resolve => { finish = resolve })
await new Promise(resolve => { handleResponse = resolve })
})
assert.deepEqual(states, ['stop'])
for (const action of ['stop', 'pause', 'resume'])
assert.equal(await gate.run(action, () => calls.push(action)), false)
finish(); await Promise.resolve()
assert.equal(await gate.run('stop', () => calls.push('duplicate')), false)
handleResponse(); assert.equal(await first, true)
assert.deepEqual(calls, ['stop']); assert.deepEqual(states, ['stop', ''])
})
test('请求失败后恢复按钮状态,并继续向调用方传递失败', async () => {
const states = [], gate = createFlowControlGate(action => states.push(action))
await assert.rejects(gate.run('stop', async () => { throw new Error('停止尚未确认') }), /停止尚未确认/)
assert.deepEqual(states, ['stop', ''])
assert.equal(await gate.run('pause', async () => {}), true)
})
test('同步异常同样清理操作锁,不能让按钮永久停在终止中', async () => {
const states = [], gate = createFlowControlGate(action => states.push(action))
await assert.rejects(gate.run('stop', () => { throw new Error('network unavailable') }), /network/)
assert.deepEqual(states, ['stop', ''])
})

View File

@ -0,0 +1,39 @@
const normalizeAction = value => String(value || '').trim().toUpperCase()
const terminalActions = { START: '流程开始', END: '流程结束', SUB_START: '单次循环开始', SUB_END: '单次循环结束' }
// The editable node name is never evidence of its component type.
export function createNodeIdentityResolver(groups) {
const byAction = new Map(), byType = new Map()
for (const group of groups || []) {
for (const node of group.nodeList || []) {
const identity = Object.freeze({
label: node.name, category: group.collapseTitle || '', known: true,
})
const action = normalizeAction(node.action)
if (action && action !== 'NONE') byAction.set(action, identity)
if (node.type) {
const candidates = byType.get(node.type) || []
candidates.push(identity)
byType.set(node.type, candidates)
}
}
}
return node => {
const properties = node?.properties || node || {}
const action = normalizeAction(properties.action)
const type = node?.type || properties.type
let identity = byAction.get(action)
if (!identity && Object.hasOwn(terminalActions, action)) {
identity = { label: terminalActions[action], category: '流程', known: true }
}
// Old data may omit action. Only an unambiguous renderer type is safe.
if (!identity && (!action || action === 'NONE')) {
const candidates = byType.get(type) || []
if (candidates.length === 1) identity = candidates[0]
else if (type === 'start') identity = { label: '流程开始', category: '流程', known: true }
else if (type === 'end') identity = { label: '流程结束', category: '流程', known: true }
else if (type === 'selectArea') identity = { label: '分组', category: '流程', known: true }
}
return { ...(identity || { label: '未识别组件', category: '', known: false }), action }
}
}

View File

@ -0,0 +1,46 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { createNodeIdentityResolver } from './nodeIdentity.mjs'
import { createWorkcellNodeGroups } from './scanMotorNodes.mjs'
const groups = [...createWorkcellNodeGroups(), {
collapseTitle: '功能', nodeList: [
{ name: '睡眠', action: 'sleep', type: 'sleep' },
{ name: 'HTTP请求', action: 'HTTP', type: 'http' },
{ name: '分支', action: 'BRANCH', type: 'branch' },
],
}]
const identify = createNodeIdentityResolver(groups)
test('扫描和电机所有组件改名、保存重载后仍能识别原组件,不改写流程数据', () => {
for (const group of createWorkcellNodeGroups()) for (const definition of group.nodeList) {
const node = JSON.parse(JSON.stringify({ type: definition.type, properties: { ...definition, name: '我的步骤' } }))
const before = JSON.stringify(node)
assert.equal(identify(node).label, definition.name)
assert.equal(identify(node).category, group.collapseTitle)
assert.equal(identify(node).known, true)
assert.equal(JSON.stringify(node), before)
}
})
test('普通功能节点及大小写不同的旧动作标识可以识别,当前名称不参与匹配', () => {
assert.equal(identify({ action: ' sleep ', name: '等待采集' }).label, '睡眠')
assert.equal(identify({ properties: { action: 'http', name: '发送通知' } }).label, 'HTTP请求')
assert.equal(identify({ properties: { action: 'BRANCH', name: '判断采集结果' } }).label, '分支')
})
test('缺少动作标识的旧流程仅按唯一类型回退,共用serviceNode不能误认成某个扫描组件', () => {
assert.equal(identify({ type: 'sleep', properties: { name: '等待' } }).label, '睡眠')
assert.equal(identify({ type: 'serviceNode', properties: { name: '创建扫描工程' } }).known, false)
assert.equal(identify({ type: 'start', properties: { name: '入口' } }).label, '流程开始')
assert.equal(identify({ type: 'end', properties: {} }).label, '流程结束')
assert.equal(identify({ type: 'selectArea', properties: { action: 'NONE' } }).label, '分组')
})
test('不认识的动作保留标识,不能因名称或渲染类型相同误认已有组件', () => {
const unknown = identify({ type: 'sleep', properties: { action: 'CUSTOM_DELAY', name: '睡眠' } })
assert.deepEqual(unknown, { label: '未识别组件', category: '', known: false, action: 'CUSTOM_DELAY' })
assert.equal(identify(null).known, false)
})
test('画布内置入口、出口和循环入口出口无需在可拖拽组件库中重复登记', () => {
for (const [action, label] of Object.entries({ START: '流程开始', END: '流程结束', SUB_START: '单次循环开始', SUB_END: '单次循环结束' })) {
assert.equal(identify({ properties: { action: action.toLowerCase(), name: '自定义入口' } }).label, label)
}
})

View File

@ -6,7 +6,7 @@
<div class="node-title">
<div class="node-title__main">
<div class="node-title__identity">
<div class="node-title__icon">
<div class="node-title__icon" :title="componentHint">
<img v-if="displayedIcon" :src="displayedIcon" alt="" @error="handleIconLoadError" />
<el-icon v-else><Operation /></el-icon>
</div>
@ -14,7 +14,7 @@
<div class="node-title__text">
<div v-if="!isEditing" class="node-title__name-row">
<span class="node-title__name" :title="localName">{{ localName }}</span>
<span v-if="typeLabel" class="node-title__type">{{ typeLabel }}</span>
<span v-if="typeLabel" class="node-title__type" :title="componentHint">{{ typeLabel }}</span>
<el-tooltip content="重命名" placement="top">
<button
type="button"
@ -76,7 +76,7 @@ import { computed, nextTick, onMounted, ref, watch } from "vue";
import { CloseBold, Delete, EditPen, FolderRemove, Operation, Select, VideoPlay } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { emitter } from "@/cmvr/common/utils/eventBus";
import { getFlowNodeIconByAction } from "../config";
import { getFlowNodeIconByAction, getFlowNodeIdentity } from "../config";
const props = defineProps({
icon: { type: String, default: "" },
@ -94,6 +94,15 @@ const nameInputRef = ref();
const displayedIcon = ref("");
const isSelectArea = computed(() => props.nodeType === "selectArea");
const configuredIcon = computed(() => getFlowNodeIconByAction(props.nodeProperties?.action));
const componentIdentity = computed(() => getFlowNodeIdentity({
type: props.nodeProperties?.type || window.lf?.getNodeModelById(props.nodeId)?.type,
properties: props.nodeProperties,
}));
const componentHint = computed(() => [
`组件类型:${componentIdentity.value.label}`,
componentIdentity.value.category,
componentIdentity.value.action ? `动作标识:${componentIdentity.value.action}` : '',
].filter(Boolean).join(' · '));
const flowContextActions = new Set([
"NONE",
"START",
@ -112,6 +121,7 @@ const canExecute = computed(() => {
return Boolean(action) && !flowContextActions.has(action);
});
const typeLabel = computed(() => {
if (componentIdentity.value.label !== localName.value.trim()) return componentIdentity.value.label;
if (!props.nodeType || ["NONE", "selectArea"].includes(props.nodeType)) return "";
return { EDGE: "设备", LLM: "模型", AE: "评估" }[props.nodeType] || props.nodeType;
});
@ -267,6 +277,7 @@ onMounted(() => {
}
.node-title__name {
min-width: 0;
overflow: hidden;
color: #1f2937;
font-size: 15px;
@ -278,6 +289,10 @@ onMounted(() => {
.node-title__type {
flex: 0 0 auto;
max-width: 110px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 1px 6px;
border: 1px solid #dfe4ec;
border-radius: 4px;

View File

@ -14,6 +14,11 @@
:close-on-click-modal="false"
:before-close="confirmSave"
>
<div class="flow-component-identity">
<span>组件类型</span>
<strong :title="componentIdentity.action ? `动作标识:${componentIdentity.action}` : componentIdentity.label">{{ componentIdentity.label }}</strong>
<span v-if="componentIdentity.category" class="flow-component-identity__category">{{ componentIdentity.category }}</span>
</div>
<component
:is="currentComponent"
ref="paramsComponentRef"
@ -30,6 +35,7 @@
<script setup>
import { ref, computed } from 'vue'
import { emitter } from '@/cmvr/common/utils/eventBus'
import { getFlowNodeIdentity } from '../config'
// 导入各子组件
const StartParams = defineAsyncComponent(() => import('./params/StartParams.vue'))
@ -57,6 +63,7 @@ const props = defineProps({
const emits = defineEmits(['close', 'extract-step'])
const paramsComponentRef = ref(null)
const componentIdentity = computed(() => getFlowNodeIdentity(props.data))
/**
* 分支条件包含左值、运算符和右值三列,仅为分支节点提供更宽的编辑空间。
@ -150,6 +157,20 @@ const handleExtractStep = (payload) => emits('extract-step', payload)
overflow-x: hidden;
}
.flow-component-identity {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 6px 10px;
margin: 14px 0 6px;
color: #7a8494;
font-size: 12px;
line-height: 20px;
strong { color: #344054; font-weight: 500; overflow-wrap: anywhere; }
&__category { margin-left: auto; }
}
.el-collapse {
border-top: 0;
}

View File

@ -19,6 +19,7 @@ import { DEFAULT_CHAT_SYSTEM_PROMPT } from './chatPrompt.js'
import scannerSvg from './icon/scanner.svg'
import motorSvg from './icon/motor.svg'
import { createWorkcellNodeGroups } from '../../utils/scanMotorNodes.mjs'
import { createNodeIdentityResolver } from '../../utils/nodeIdentity.mjs'
const pointOutputChildren = () => [
{ name: 'x', type: 'number', desc: 'X坐标' },
@ -982,6 +983,9 @@ function handler(params) {
},
]
// 自定义名称不覆盖组件身份,旧流程也按稳定动作标识识别组件库定义。
export const getFlowNodeIdentity = createNodeIdentityResolver(collapseList)
// 流程数据会长期保存,而 Vite 生成的图标地址只对当前构建有效。
// 这里用稳定的 action 建立索引,使旧流程或后端缺失 icon 时可以恢复为当前版本的内置图标。
const flowNodeIconByAction = new Map(

View File

@ -7,10 +7,11 @@
<el-container class="page__container">
<el-header v-if="!flowInfoData.isLog">
<div class="flow-heading">
<div class="flow-heading__name">{{ flowInfoData.name || "未命名流程" }}</div>
<div class="flow-status" :class="`flow-status--${flowState}`">
<el-button v-if="!flowStore.disableForm" class="palette-toggle" :aria-expanded="paletteVisible" @click="paletteVisible = !paletteVisible">{{ paletteVisible ? '收起组件库' : '组件库' }}</el-button>
<div class="flow-heading__name" :title="flowInfoData.name">{{ flowInfoData.name || "未命名流程" }}</div>
<div class="flow-status" :class="`flow-status--${controlAction ? 'pending' : flowState}`" role="status">
<span class="flow-status__dot"></span>
<span>{{ stateMap[flowState] }}</span>
<span>{{ controlLabels[controlAction] || stateMap[flowState] }}</span>
</div>
<el-tag v-if="publishedVersionNo" size="small" type="success" effect="plain">
当前发布 V{{ publishedVersionNo }}
@ -24,50 +25,33 @@
<el-tag v-if="hasRunResult && ['testRunError', 'testRunFinish'].includes(flowState)" :type="flowState === 'testRunFinish' ? 'success' : 'danger'">
{{ totalRunningTime }}ms
</el-tag>
<el-button v-if="hasRunResult" @click="clearRun">
<el-icon><Delete /></el-icon>清除结果
</el-button>
<el-button v-if="groupSelectionPending" @click="group">取消分组</el-button>
<el-button
type="warning"
plain
:loading="restoreOperationalLoading"
:disabled="flowState === 'testRunning'"
@click="openRestoreOperationalDialog"
>
<el-icon><Warning /></el-icon>清除错误状态
</el-button>
<el-button :type="groupSelectionPending ? 'primary' : 'default'" @click="group">
<el-icon><CollectionTag /></el-icon>{{ groupSelectionPending ? "取消分组" : "分组" }}
</el-button>
<el-button
v-if="flowState !== 'testRunning'"
v-if="!['testRunning', 'pause'].includes(flowState) && !controlAction"
:loading="trialPreparing"
:disabled="draftSaving"
@click="testRun"
>
<el-icon><VideoPlay /></el-icon>试运行
</el-button>
<el-button v-if="flowState === 'testRunning'" @click="flowPauseFn">
<el-icon><VideoPause /></el-icon>暂停
<el-button v-if="flowState === 'testRunning'" :loading="controlAction === 'pause'" :disabled="!!controlAction" @click="flowPauseFn">
<el-icon v-if="controlAction !== 'pause'"><VideoPause /></el-icon>{{ controlAction === 'pause' ? '暂停中…' : '暂停' }}
</el-button>
<el-button v-if="flowState === 'pause'" @click="flowResumeFn">
<el-icon><VideoPlay /></el-icon>恢复
<el-button v-if="flowState === 'pause'" :loading="controlAction === 'resume'" :disabled="!!controlAction" @click="flowResumeFn">
<el-icon v-if="controlAction !== 'resume'"><VideoPlay /></el-icon>{{ controlAction === 'resume' ? '恢复中…' : '恢复' }}
</el-button>
<el-button v-if="['testRunning', 'pause'].includes(flowState)" @click="flowStopFn">
<el-icon><CircleClose /></el-icon>终止
<el-button v-if="['testRunning', 'pause'].includes(flowState) || controlAction === 'stop'" :loading="controlAction === 'stop'" :disabled="!!controlAction" @click="flowStopFn">
<el-icon v-if="controlAction !== 'stop'"><CircleClose /></el-icon>{{ controlAction === 'stop' ? '终止中…' : '终止' }}
</el-button>
</div>
<div class="btn publish-actions">
<el-button
:loading="draftSaving"
:disabled="!draftDirty || ['testRunning', 'pause'].includes(flowState)"
:disabled="!!controlAction || !draftDirty || ['testRunning', 'pause'].includes(flowState)"
@click="saveDraft"
>
<el-icon><DocumentChecked /></el-icon>保存
</el-button>
<el-button :disabled="['testRunning', 'pause'].includes(flowState)" @click="openVersionHistory">
<el-icon><Clock /></el-icon>发布记录
</el-button>
<el-tooltip
class="box-item"
effect="dark"
@ -77,7 +61,16 @@
>
<el-button type="primary" :disabled="true"><el-icon><Upload /></el-icon>发布</el-button>
</el-tooltip>
<el-button v-else @click="deployFlow" type="primary"><el-icon><Upload /></el-icon>发布</el-button>
<el-button v-else :disabled="!!controlAction" @click="deployFlow" type="primary"><el-icon><Upload /></el-icon>发布</el-button>
<el-dropdown trigger="click" placement="bottom-end" :disabled="!!controlAction">
<el-button aria-label="更多流程操作">更多</el-button>
<template #dropdown><el-dropdown-menu>
<el-dropdown-item :disabled="['testRunning', 'pause'].includes(flowState)" @click="openVersionHistory">发布记录</el-dropdown-item>
<el-dropdown-item v-if="!groupSelectionPending" @click="group">分组节点</el-dropdown-item>
<el-dropdown-item :disabled="flowState === 'testRunning' || restoreOperationalLoading" @click="openRestoreOperationalDialog">清除错误状态</el-dropdown-item>
<el-dropdown-item v-if="hasRunResult" divided @click="clearRun">清除运行结果</el-dropdown-item>
</el-dropdown-menu></template>
</el-dropdown>
<el-popover
:width="260"
@ -116,8 +109,10 @@
<el-button type="primary" @click="exitVersionPreview">退出预览</el-button>
</div>
</el-header>
<el-container class="container">
<el-aside v-if="!flowStore.disableForm">
<el-alert v-if="controlAction === 'stop'" title="终止中,正在等待设备停止并确认资源释放,请勿重复操作。" type="info" :closable="false" show-icon />
<el-alert v-else-if="controlError" :title="controlError" type="warning" :closable="false" show-icon />
<el-container class="flow-workspace">
<el-aside v-if="!flowStore.disableForm && paletteVisible" class="flow-palette">
<Aside :flowId="flowInfoData.itemId" />
</el-aside>
<el-main>
@ -417,11 +412,9 @@ import { getRobotList, getRobotDevicesByRobotId } from '@/cmvr/common/api/resour
import { restoreOperationalState } from '@/cmvr/common/api/device/system'
import { getDeviceKindForAction, toDeviceOptions } from '@/cmvr/common/utils/robotDevice'
import { sanitizeFlowResourceDefinition } from '@/cmvr/common/utils/flowResources'
import { createFlowControlGate } from '@/cmvr/common/utils/flowControlGate.mjs'
import {
CircleClose,
Clock,
CollectionTag,
Delete,
DocumentChecked,
FullScreen,
Location,
@ -431,13 +424,14 @@ import {
Upload,
VideoPause,
VideoPlay,
Warning,
} from "@element-plus/icons-vue";
const flowContainerRef = ref(null);
const paletteVisible = ref(window.innerWidth >= 960);
const lfRef = ref(null);
const vueFlow = useVueFlow("main-flow");
const lf = createFlowFacade(vueFlow);
watch(paletteVisible, () => nextTick(() => lf.fitView()));
const loopChildDragContexts = new Map();
const actionQueueDragOrigins = new Map();
const queueDropTargetId = ref("");
@ -885,6 +879,31 @@ const stateMap = {
stop: "已终止",
};
const flowState = ref("unpublished");
const controlAction = ref("");
const controlError = ref("");
const controlLabels = { stop: "终止中…", pause: "暂停中…", resume: "恢复中…" };
let flowPollEpoch = 0;
const controlGate = createFlowControlGate(action => {
controlAction.value = action;
if (action) { flowPollEpoch++; clearFlowPollTimer(); }
});
const runFlowControl = async (action, request, onSuccess) => {
if (!instId.value) return;
const id = instId.value;
try {
await controlGate.run(action, async () => {
controlError.value = "";
const response = await request(id);
if (!isCurrentFlowPoll(id)) return;
if (response.code !== 200) throw new Error(response.msg || "操作未确认");
onSuccess(response);
});
} catch (error) {
if (!isCurrentFlowPoll(id)) return;
controlError.value = `${action === 'stop' ? '终止结果尚未确认,请核对设备与资源占用' : '操作未完成,请核对当前状态'}:${error?.message || '连接失败'}`;
loopFlowView(id);
}
};
const draftRevision = ref(0);
const draftDirty = ref(false);
const draftSaving = ref(false);
@ -911,7 +930,7 @@ const flowInfoData = ref({
* 试运行
*/
const testRun = async () => {
if (trialPreparing.value || draftSaving.value) return;
if (controlAction.value || ['testRunning', 'pause'].includes(flowState.value) || trialPreparing.value || draftSaving.value) return;
// 1、验证画布内所有的表单通过验证
const { nodes, edges } = lf.getGraphData();
@ -963,13 +982,10 @@ const testRun = async () => {
/**
* 处理 flowPauseFn 对应的数据或交互;作用范围仅限当前组件或模块。
*/
const flowPauseFn = async () => {
const res = await flowPause(instId.value);
if (res.code === 200) {
const flowPauseFn = () => runFlowControl('pause', flowPause, (res) => {
flowState.value = "pause";
ElMessage.success(res.msg);
}
};
});
const totalRunningTime = ref(0);
const hasRunResult = ref(false);
@ -1026,29 +1042,23 @@ const scheduleFlowView = (currentInstId, taskId = null, delay = 2000) => {
/**
* 处理 flowResumeFn 对应的数据或交互;作用范围仅限当前组件或模块。
*/
const flowResumeFn = async () => {
const res = await flowResume(instId.value);
if (res.code === 200) {
const flowResumeFn = () => runFlowControl('resume', flowResume, (res) => {
flowState.value = "testRunning";
clearFlowPollTimer();
loopFlowView(instId.value);
ElMessage.success(res.msg);
}
};
});
/**
* 处理 flowStopFn 对应的数据或交互;作用范围仅限当前组件或模块。
*/
const flowStopFn = async () => {
const res = await flowStop(instId.value);
if (res.code === 200) {
const flowStopFn = () => runFlowControl('stop', flowStop, (res) => {
clearFlowPollTimer();
flowState.value = "stop";
hasRunResult.value = true;
flowStore.updateDisableForm(false);
ElMessage.success(res.msg);
}
};
});
const initFlowData = {
nodes: [
@ -1148,6 +1158,8 @@ const validEdge = (data) => {
const instId = ref(null);
const changeState = (value) => {
controlError.value = "";
flowPollEpoch++;
oldFlowData = JSON.parse(JSON.stringify(lf.getGraphData()));
isOpen.value = false;
flowStore.updateDisableForm(true);
@ -1562,6 +1574,7 @@ const completeTrialRun = async (currentInstId, mainEnd, first) => {
* @returns {Promise<void>} 状态同步完成后结束
*/
const loopFlowView = async (currentInstId, taskId = null) => {
const pollEpoch = flowPollEpoch;
const params = {
itemId: flowInfoData.value.itemId,
instId: currentInstId,
@ -1574,12 +1587,12 @@ const loopFlowView = async (currentInstId, taskId = null) => {
res = await flowView(params);
} catch {
// 查询异常不代表试运行失败;保留当前节点结果并继续查询,直到拿到后端明确终态。
if (!flowInfoData.value.isLog && isCurrentFlowPoll(currentInstId)) {
if (pollEpoch === flowPollEpoch && !flowInfoData.value.isLog && isCurrentFlowPoll(currentInstId)) {
scheduleFlowView(currentInstId, taskId);
}
return;
}
if (!isCurrentFlowPoll(currentInstId)) return;
if (pollEpoch !== flowPollEpoch || !isCurrentFlowPoll(currentInstId)) return;
if (res.code !== 200) {
if (!flowInfoData.value.isLog) scheduleFlowView(currentInstId, taskId);
return;
@ -1812,6 +1825,7 @@ const deployFlow = async () => {
const loadFlowData = async (id, lf) => {
try {
const res = await getDetect(id);
if (res.data?.detectName) flowInfoData.value.name = res.data.detectName;
if (res.data && res.data.flowData) {
draftRevision.value = res.data.draftRevision ?? 0;
publishedVersionId.value = res.data.publishedVersionId || "";
@ -1867,7 +1881,7 @@ const justLoadFlow = () => {
instId: locationParams?.instId || "",
taskId: locationParams?.taskId || "",
isLog: locationParams?.isLog || false,
name: decodeURIComponent(locationParams.name),
name: locationParams.name ? decodeURIComponent(locationParams.name) : "",
};
if (flowInfoData.value.isLog) {
@ -2296,7 +2310,7 @@ const execute = async () => {
const payload = nodeAction.value === 'IMAGE_ANALYZE'
? buildImageAnalysisSingleNodePayload(formData.nodeParams)
: buildSingleNodePayload(formData.nodeParams);
if (String(nodeAction.value).startsWith('SCANNER_')) payload.commandKey = crypto.randomUUID();
if (String(nodeAction.value).startsWith('SCANNER_')) payload.commandKey = uuid();
const res = await flowAction({
action: nodeAction.value,
payload,
@ -2869,24 +2883,35 @@ onUnmounted(() => {
.page {
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
overflow: hidden;
.page__container {
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
flex-direction: column;
position: relative;
.el-header {
display: flex;
height: auto;
min-height: 60px;
flex-shrink: 0;
flex-wrap: wrap;
box-sizing: border-box;
align-items: center;
justify-content: space-between;
padding: 0 16px;
padding: 12px 16px;
border-bottom: 1px solid #e3e7ee;
background: #fff;
gap: 18px;
gap: 12px 18px;
.flow-heading {
display: flex;
flex: 1 1 280px;
min-width: 0;
align-items: center;
gap: 10px;
@ -2931,6 +2956,7 @@ onUnmounted(() => {
}
.flow-status--testRunning,
.flow-status--pending,
.flow-status--updateData {
border-color: #cbdcf8;
background: #f0f6ff;
@ -2953,11 +2979,13 @@ onUnmounted(() => {
.btn__container {
display: flex;
min-width: 0;
flex-wrap: wrap;
align-items: center;
gap: 10px;
.btn {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
@ -2971,11 +2999,18 @@ onUnmounted(() => {
}
}
.container {
height: calc(100% - 60px);
.flow-workspace {
position: relative;
flex: 1;
width: 100%;
min-width: 0;
min-height: 0;
overflow: hidden;
}
.el-main {
min-width: 0;
min-height: 0;
padding: 0;
position: relative;
overflow: hidden;
@ -2984,6 +3019,7 @@ onUnmounted(() => {
.el-aside {
margin: 0;
width: 272px;
flex-shrink: 0;
padding: 0;
border-right: 1px solid #e3e7ee;
background: #f8fafc;
@ -3102,6 +3138,25 @@ onUnmounted(() => {
}
}
}
@media (max-width: 959px) {
.page .page__container {
.el-header .flow-heading {
flex-wrap: wrap;
.flow-heading__name { max-width: min(320px, 65vw); }
}
.flow-palette {
position: absolute;
inset: 0 auto 0 0;
z-index: 30;
max-width: 85%;
box-shadow: 6px 0 20px rgba(20, 33, 61, 0.12);
}
.el-header .btn__container .publish-actions {
padding-left: 0;
border-left: 0;
}
}
}
</style>
<style lang="scss">
.node-relationship-network-popover {

View File

@ -41,7 +41,7 @@ export function setupCmvr(app: App) {
for (const [name, component] of Object.entries({ Pagination, RightToolbar, DictTag, FileUpload, ImageUpload, ImagePreview, Editor, SvgIcon })) app.component(`Cmvr${name}`, component)
app.component('JsonViewer', JsonViewer)
Object.assign(app.config.globalProperties, ruoyi, { useDict, download, getConfigKey, $modal: modal, $cache: cache })
const wsUrl = cmvrApiBase.replace(/^http/, 'ws') + '/ws'
const wsUrl = new URL(cmvrApiBase, window.location.origin).href.replace(/^http/, 'ws') + '/ws'
app.use(WebSocketPlugin, { url: wsUrl, userId: () => getAccessToken() ? getCurrentUserId() : 0 })
// The host loads identity after login; connect once it becomes available.
const user = useUserStore()

View File

@ -7,4 +7,11 @@
background: var(--el-bg-color);
> .app-container { height: 100%; box-sizing: border-box; }
}
.cmvr-flow { height: 100vh; min-height: 480px; }
.cmvr-flow {
width: 100%;
height: 100vh;
height: 100dvh;
min-width: 0;
min-height: 0;
overflow: hidden;
}

View File

@ -229,7 +229,8 @@ service.interceptors.response.use(
return data
}
},
(error: AxiosError) => {
(error: AxiosError) => rejectRequestFailure(error, (failure: AxiosError) => {
const error = failure
console.log('err' + error) // for debug
let { message } = error
const { t } = useI18n()
@ -241,8 +242,7 @@ service.interceptors.response.use(
message = t('sys.api.apiRequestFailed') + message.substr(message.length - 3)
}
ElMessage.error(message)
return Promise.reject(error)
}
})
)
const refreshToken = async () => {

View File

@ -88,7 +88,7 @@ export default defineComponent({
<Collapse class="custom-hover" color="var(--top-header-text-color)"></Collapse>
) : undefined}
{showBreadcrumb.value && breadcrumb.value ? (
<Breadcrumb class="lt-lg:hidden"></Breadcrumb>
<Breadcrumb class="shrink-0 whitespace-nowrap lt-xl:hidden"></Breadcrumb>
) : undefined}
{search.value ? (
<RouterSearch
@ -142,5 +142,9 @@ $prefix-cls: #{$namespace}-tool-header;
.#{$prefix-cls} {
transition: left var(--transition-time-02);
box-shadow: 0 1px 0 rgba(31, 64, 120, 0.06);
:deep(.aima-header-search) {
min-width: 0;
}
}
</style>

View File

@ -0,0 +1,35 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import vm from 'node:vm'
import { webcrypto } from 'node:crypto'
import ts from 'typescript'
// Compile the public helper itself without loading unrelated browser utilities.
const source = fs.readFileSync(new URL('./index.ts', import.meta.url), 'utf8')
const ast = ts.createSourceFile('index.ts', source, ts.ScriptTarget.Latest, true)
const definition = ast.statements.find(statement => ts.isVariableStatement(statement) &&
statement.declarationList.declarations.some(declaration => declaration.name.getText(ast) === 'generateUUID'))
const compiled = ts.transpileModule(definition.getText(ast), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
}).outputText
function generator(crypto) {
const exports = {}
vm.runInNewContext(compiled, { exports, crypto, Uint8Array, Date, Math, performance })
return exports.generateUUID
}
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
test('UUID优先使用安全环境的原生实现', () => {
const expected = '12345678-1234-4234-8234-123456789abc'
assert.equal(generator({ randomUUID: () => expected })(), expected)
})
test('局域网HTTP缺少randomUUID时仍生成有效且不重复的命令标识', () => {
const generate = generator({ getRandomValues: webcrypto.getRandomValues.bind(webcrypto) })
const values = Array.from({ length: 100 }, generate)
assert.ok(values.every(value => uuid.test(value)))
assert.equal(new Set(values).size, values.length)
})
test('旧浏览器缺少crypto时仍可创建普通业务幂等标识', () => {
assert.match(generator(undefined)(), uuid)
})

View File

@ -1,15 +1,24 @@
<template>
<ContentWrap>
<el-form class="-mb-15px" :model="queryParams" inline>
<el-form-item label="报告编号"><el-input v-model="queryParams.reportNo" clearable class="!w-160px" /></el-form-item>
<el-form-item label="报告编号"
><el-input v-model="queryParams.reportNo" clearable class="!w-160px"
/></el-form-item>
<el-form-item label="状态">
<el-select v-model="queryParams.status" clearable class="!w-140px">
<el-option v-for="dict in getStrDictOptions(DICT_TYPE.LAB_REPORT_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
<el-option
v-for="dict in getStrDictOptions(DICT_TYPE.LAB_REPORT_STATUS)"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button @click="getList">搜索</el-button>
<el-button type="primary" plain v-hasPermi="['lab:document:update']" @click="createVisible = true">新建报告</el-button>
<el-button type="primary" plain v-hasPermi="['lab:document:update']" @click="openCreate"
>新建报告</el-button
>
</el-form-item>
</el-form>
</ContentWrap>
@ -19,10 +28,14 @@
<el-table-column label="任务" prop="taskNo" min-width="130" />
<el-table-column label="标题" prop="title" min-width="180" />
<el-table-column label="类型" width="110">
<template #default="scope"><dict-tag :type="DICT_TYPE.LAB_REPORT_TYPE" :value="scope.row.reportType" /></template>
<template #default="scope"
><dict-tag :type="DICT_TYPE.LAB_REPORT_TYPE" :value="scope.row.reportType"
/></template>
</el-table-column>
<el-table-column label="状态" width="100">
<template #default="scope"><dict-tag :type="DICT_TYPE.LAB_REPORT_STATUS" :value="scope.row.status" /></template>
<template #default="scope"
><dict-tag :type="DICT_TYPE.LAB_REPORT_STATUS" :value="scope.row.status"
/></template>
</el-table-column>
<el-table-column label="操作" width="120">
<template #default="scope">
@ -30,27 +43,46 @@
</template>
</el-table-column>
</el-table>
<Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
<Pagination
:total="total"
v-model:page="queryParams.pageNo"
v-model:limit="queryParams.pageSize"
@pagination="getList"
/>
</ContentWrap>
<Dialog v-model="createVisible" title="新建报告" width="480">
<el-form label-width="90px">
<el-form-item label="任务ID" required><el-input v-model="form.taskId" /></el-form-item>
<el-form-item label="标题" required><el-input v-model="form.title" /></el-form-item>
<el-form
ref="createFormRef"
:model="form"
:rules="createRules"
label-width="90px"
@submit.prevent="submitCreate"
>
<el-form-item label="任务ID" prop="taskId"><el-input v-model="form.taskId" /></el-form-item>
<el-form-item label="标题" prop="title"
><el-input v-model="form.title" maxlength="256" show-word-limit
/></el-form-item>
<el-form-item label="类型">
<el-select v-model="form.reportType" class="!w-full">
<el-option v-for="dict in getStrDictOptions(DICT_TYPE.LAB_REPORT_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value" />
<el-option
v-for="dict in getStrDictOptions(DICT_TYPE.LAB_REPORT_TYPE)"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
</el-form>
<template #footer>
<el-button type="primary" @click="submitCreate">创建</el-button>
<el-button @click="createVisible = false">取消</el-button>
<el-button type="primary" :loading="creating" @click="submitCreate">创建</el-button>
<el-button :disabled="creating" @click="createVisible = false">取消</el-button>
</template>
</Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import * as DocumentApi from '@/api/lab/document'
import type { FormInstance, FormRules } from 'element-plus'
defineOptions({ name: 'LabReport' })
const { push } = useRouter()
@ -58,9 +90,27 @@ const message = useMessage()
const loading = ref(false)
const total = ref(0)
const list = ref<DocumentApi.LabReportVO[]>([])
const queryParams = reactive({ pageNo: 1, pageSize: 10, reportNo: '', status: undefined as string | undefined })
const queryParams = reactive({
pageNo: 1,
pageSize: 10,
reportNo: '',
status: undefined as string | undefined
})
const createVisible = ref(false)
const createFormRef = ref<FormInstance>()
const creating = ref(false)
const form = reactive({ taskId: '', title: '', reportType: 'PROFESSIONAL' })
const createRules: FormRules = {
taskId: [{ required: true, whitespace: true, message: '请填写所属任务ID', trigger: 'blur' }],
title: [{ required: true, whitespace: true, message: '请填写报告标题', trigger: 'blur' }]
}
const openCreate = async () => {
if (creating.value) return
Object.assign(form, { taskId: '', title: '', reportType: 'PROFESSIONAL' })
createVisible.value = true
await nextTick()
createFormRef.value?.clearValidate()
}
const getList = async () => {
loading.value = true
try {
@ -71,12 +121,23 @@ const getList = async () => {
loading.value = false
}
}
const open = (row: DocumentApi.LabReportVO) => push({ name: 'LabReportDetail', params: { id: String(row.id) } })
const open = (row: DocumentApi.LabReportVO) =>
push({ name: 'LabReportDetail', params: { id: String(row.id) } })
const submitCreate = async () => {
const id = await DocumentApi.createReport(form)
createVisible.value = false
push({ name: 'LabReportDetail', params: { id: String(id) } })
message.success('已创建')
if (creating.value || !(await createFormRef.value?.validate().catch(() => false))) return
creating.value = true
try {
const id = await DocumentApi.createReport({
...form,
taskId: form.taskId.trim(),
title: form.title.trim()
})
createVisible.value = false
push({ name: 'LabReportDetail', params: { id: String(id) } })
message.success('已创建')
} finally {
creating.value = false
}
}
onMounted(getList)
</script>

View File

@ -1,84 +1,110 @@
<template>
<ContentWrap>
<el-alert
title="任务按样件逐件执行。先完成接收、夹具与扫描方案准备,再确认装夹并开始每一件。"
type="info"
:closable="false"
class="mb-16px"
/>
<el-form inline :model="query" @submit.prevent="search">
<el-form-item label="任务编号"
><el-input v-model="query.taskNo" clearable @keyup.enter="search"
/></el-form-item>
<el-form-item label="状态"
><el-select v-model="query.status" clearable class="!w-160px"
><el-option
v-for="status in statuses"
:key="status"
:value="status"
:label="statusLabel(status)" /></el-select
></el-form-item>
<el-form-item
><el-button type="primary" @click="search">搜索</el-button
><el-button @click="load">刷新</el-button
><el-button @click="push('/lab/task/import')">任务导入</el-button></el-form-item
<div class="execution-page">
<header class="execution-header">
<div class="execution-heading">
<h1>执行任务</h1><span class="task-total">{{ total }} 项</span>
</div>
<div class="header-actions">
<el-button :loading="loading" @click="load"
><Icon icon="ep:refresh" class="mr-6px" />刷新</el-button
>
<el-button type="primary" @click="push('/lab/task/import')"
><Icon icon="ep:upload" class="mr-6px" />导入任务</el-button
>
</div>
</header>
<ContentWrap class="execution-content" :body-style="{ padding: '0' }">
<el-form inline :model="query" class="execution-filters" @submit.prevent="search">
<el-form-item
><el-input
v-model="query.taskNo"
aria-label="任务编号"
placeholder="搜索任务编号"
clearable
@keyup.enter="search"
/></el-form-item>
<el-form-item
><el-select v-model="query.status" aria-label="状态" placeholder="全部状态" clearable class="!w-140px" @change="search"
><el-option
v-for="status in statuses"
:key="status"
:value="status"
:label="status === 'CLAIMED' ? '已领取' : statusLabel(status)" /></el-select
></el-form-item>
<el-form-item
><el-button @click="search"
><Icon icon="ep:search" class="mr-6px" />查询</el-button
><el-button text @click="resetFilters">重置</el-button></el-form-item
>
</el-form>
<el-table
v-loading="loading"
:data="rows"
row-key="id"
class="execution-table"
:row-style="{ height: '64px' }"
>
</el-form>
</ContentWrap>
<ContentWrap>
<el-table v-loading="loading" :data="rows">
<el-table-column label="任务编号" prop="taskNo" min-width="180" />
<el-table-column label="任务名称" prop="taskName" min-width="180" show-overflow-tooltip />
<el-table-column label="外部任务编号" prop="externalTaskNo" min-width="160" />
<el-table-column label="扫描方案 / 测试用例" min-width="200"
><template #default="{ row }">{{
row.caseName || row.testCaseId || '待关联'
}}</template></el-table-column
>
<el-table-column label="完成件数" width="110"
><template #default="{ row }"
>{{ row.completedCount || 0 }} / {{ row.quantity || 0 }}</template
></el-table-column
>
<el-table-column label="状态" width="130"
><template #default="{ row }"
><el-tag
:type="
row.status === 'COMPLETED'
? 'success'
: ['FAILED', 'BLOCKED', 'STOP_PENDING'].includes(row.status)
? 'danger'
: 'info'
"
>{{ statusLabel(row.status) }}</el-tag
></template
></el-table-column
>
<el-table-column label="负责人" width="120"
><template #default="{ row }">{{
row.ownerName || (row.ownerId ? row.ownerId : '未领取')
}}</template></el-table-column
>
<el-table-column label="操作" width="150" fixed="right"
><template #default="{ row }"
><el-button
link
type="primary"
@click="push({ name: 'LabScanTaskWorkbench', params: { id: String(row.id) } })"
>{{
['COMPLETED', 'CANCELLED'].includes(row.status) ? '查看记录' : '准备与执行'
}}</el-button
></template
></el-table-column
>
</el-table>
<Pagination
:total="total"
v-model:page="query.pageNo"
v-model:limit="query.pageSize"
@pagination="load"
/>
</ContentWrap>
<el-table-column type="expand" width="40">
<template #default="{ row }"><div class="row-details"><span>外部编号:{{ row.externalTaskNo || '未填写' }}</span><span>负责人:{{ row.ownerName || row.ownerId || '未领取' }}</span></div></template>
</el-table-column>
<el-table-column label="任务" min-width="260">
<template #default="{ row }">
<div class="task-cell">
<strong :title="row.taskName">{{ row.taskName || '未命名任务' }}</strong>
<span class="task-number">{{ row.taskNo }}</span>
</div>
</template>
</el-table-column>
<el-table-column label="扫描方案" min-width="180" show-overflow-tooltip
><template #default="{ row }"
><span :class="{ 'muted-text': !row.caseName && !row.testCaseId }">{{
row.caseName || row.testCaseId || '尚未关联方案'
}}</span></template
></el-table-column
>
<el-table-column label="样件进度" min-width="145"
><template #default="{ row }"
><div class="completion-cell"
><span
><strong>{{ row.completedCount || 0 }}</strong> / {{ row.quantity || 0 }} 件</span
>
<el-progress
:percentage="completion(row)"
:show-text="false"
:stroke-width="5"
:status="row.status === 'COMPLETED' ? 'success' : undefined" /></div></template
></el-table-column>
<el-table-column label="任务状态" width="120"
><template #default="{ row }"
><span class="task-state" :data-state="row.status"><i />{{ statusLabel(row.status) }}</span></template
></el-table-column
>
<el-table-column label="操作" width="110" fixed="right"
><template #default="{ row }"
><el-button
link
type="primary"
@click="push({ name: 'LabScanTaskWorkbench', params: { id: String(row.id) } })"
>{{
['COMPLETED', 'CANCELLED'].includes(row.status) ? '查看记录' : '进入工作台'
}}</el-button
></template
></el-table-column
>
<template #empty
><el-empty description="没有符合条件的任务,可调整筛选条件或导入任务" :image-size="88"
/></template>
</el-table>
<div class="execution-pagination">
<Pagination
:total="total"
v-model:page="query.pageNo"
v-model:limit="query.pageSize"
@pagination="load"
/>
</div>
</ContentWrap>
</div>
</template>
<script setup lang="ts">
import * as ScanApi from '@/api/lab/scan-task'
@ -128,6 +154,15 @@ const search = () => {
query.pageNo = 1
load()
}
const resetFilters = () => {
query.taskNo = ''
query.status = undefined
search()
}
const completion = (row: ScanApi.ScanTaskRow) =>
row.quantity > 0
? Math.min(100, Math.max(0, Math.round(((row.completedCount || 0) / row.quantity) * 100)))
: 0
let timer: ReturnType<typeof setInterval> | undefined
const startPolling = () => {
if (timer) return
@ -143,12 +178,125 @@ const stopPolling = () => {
loading.value = false
}
onMounted(startPolling)
watch(() => [route.query.taskNo, route.query.status], () => {
query.taskNo = String(route.query.taskNo || '')
query.status = route.query.status === 'RUNNING' ? 'EXECUTING' : route.query.status ? String(route.query.status) : undefined
search()
})
watch(
() => [route.query.taskNo, route.query.status],
() => {
query.taskNo = String(route.query.taskNo || '')
query.status =
route.query.status === 'RUNNING'
? 'EXECUTING'
: route.query.status
? String(route.query.status)
: undefined
search()
}
)
onActivated(startPolling)
onDeactivated(stopPolling)
onUnmounted(stopPolling)
</script>
<style scoped>
.execution-page {
color: var(--el-text-color-primary);
}
.execution-header,
.execution-heading,
.header-actions {
display: flex;
align-items: center;
gap: 14px;
}
.execution-header {
justify-content: space-between;
flex-wrap: wrap;
margin: 0 0 14px;
}
.execution-heading {
min-width: 0;
gap: 10px;
}
h1 {
margin: 0;
font-size: 18px;
font-weight: 600;
}
.task-total {
color: var(--el-text-color-secondary);
font-size: 13px;
}
.header-actions {
gap: 10px;
}
.header-actions .el-button + .el-button {
margin-left: 0;
}
.execution-content {
border-radius: 6px;
}
.execution-filters {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
align-items: center;
padding: 12px 16px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.execution-filters :deep(.el-form-item) {
margin: 0;
}
.execution-filters :deep(.el-input) {
width: 210px;
}
.muted-text {
color: var(--el-text-color-secondary);
font-size: 12px;
}
.execution-table :deep(th.el-table__cell) {
background: var(--el-fill-color-lighter);
color: var(--el-text-color-secondary);
font-size: 12px;
font-weight: 500;
}
.execution-table :deep(.cell) {
padding-left: 14px;
padding-right: 14px;
}
.task-cell {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
}
.task-cell strong {
font-size: 14px;
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.task-number {
font-size: 12px;
color: var(--el-text-color-regular);
font-variant-numeric: tabular-nums;
}
.completion-cell {
display: grid;
gap: 6px;
padding-right: 12px;
color: var(--el-text-color-secondary);
font-size: 12px;
}
.completion-cell strong {
color: var(--el-text-color-primary);
font-weight: 500;
}
.execution-pagination {
padding: 4px 16px 12px;
}
.row-details { display: flex; flex-wrap: wrap; gap: 8px 28px; padding: 12px 54px; background: var(--el-fill-color-lighter); font-size: 12px; color: var(--el-text-color-regular); overflow-wrap: anywhere; }
.task-state { display: inline-flex; align-items: center; gap: 7px; font-size: 13px; white-space: nowrap; }
.task-state i { width: 6px; height: 6px; border-radius: 50%; background: var(--el-text-color-placeholder); }
.task-state[data-state='COMPLETED'] i { background: var(--el-color-success); }
.task-state[data-state='EXECUTING'] i { background: var(--el-color-primary); }
.task-state[data-state='BLOCKED'] i, .task-state[data-state='STOP_PENDING'] i, .task-state[data-state='FAILED'] i { background: var(--el-color-danger); }
</style>

View File

@ -0,0 +1,378 @@
<template>
<section class="scan-log" aria-label="步骤执行日志">
<div class="log-heading">
<div
><div class="log-switch" role="group" aria-label="执行记录显示方式">
<button type="button" :aria-pressed="view === 'steps'" @click="view = 'steps'"
>执行步骤</button
>
<button type="button" :aria-pressed="view === 'logs'" @click="view = 'logs'"
>详细日志</button
> </div
><span class="log-count"
>{{
view === 'steps'
? steps.length
? `${stepCounts.completed} 步已完成`
: '等待流程步骤'
: summary.total
? `${summary.total} 条记录`
: '等待步骤记录'
}}<span v-if="view === 'steps' ? stepCounts.failed : summary.failed">
· {{ view === 'steps' ? stepCounts.failed : summary.failed }} 步失败</span
></span
></div
>
<div
><el-checkbox v-model="onlyIssues" size="small">只看异常</el-checkbox
><el-button v-if="rows.length" link size="small" @click="latest">{{
view === 'steps' ? '定位当前' : '定位最新'
}}</el-button></div
>
</div>
<template v-if="view === 'steps'">
<p v-if="!hasPlan && !loading" class="plan-note">尚未取得完整流程,先展示已收到的步骤。</p>
<p v-if="loading && !steps.length" class="empty-log" role="status">正在加载执行步骤…</p>
<p v-else-if="!visibleSteps.length" class="empty-log">{{
onlyIssues ? '当前没有异常步骤' : '等待流程步骤'
}}</p>
<ScanExecutionSteps
v-else
ref="stepList"
:steps="visibleSteps"
:focus-id="focusId"
:height="height"
@inspect="inspect"
/>
</template>
<p v-else-if="loading && !rows.length" class="empty-log" role="status">正在加载执行日志…</p>
<p v-else-if="!visibleRows.length" class="empty-log">{{
onlyIssues ? '当前没有异常步骤' : '本次执行暂未产生步骤日志'
}}</p>
<div v-else ref="list" class="log-list" :style="{ maxHeight: `${Math.max(280, height)}px` }">
<article
v-for="row in visibleRows"
:key="row.key"
class="log-row"
:data-state="row.status.key"
:data-node="row.raw.nodeId"
>
<details>
<summary>
<span class="step-state">{{ row.status.label }}</span>
<span class="step-content"
><strong>{{ row.name }}</strong
><span class="step-result">{{ row.summary }}</span
><span class="step-time"
>{{ row.start }} <span>耗时 {{ row.duration }}</span></span
></span
>
<span class="step-detail">详情</span>
</summary>
<div class="log-raw">
<dl
><dt>日志编号</dt><dd>{{ row.key }}</dd
><dt>节点编号</dt><dd>{{ row.raw.nodeId || '—' }}</dd
><dt>原始状态</dt><dd>{{ row.raw.status ?? '—' }}</dd
><dt>结束时间</dt><dd>{{ logTime(row.raw.endTime) }}</dd></dl
>
<details
><summary>原始消息</summary><pre>{{ row.raw.message || '无' }}</pre>
</details>
<details
><summary>输入参数</summary><pre>{{ readablePayload(row.raw.paramsIn) }}</pre>
</details>
<details
><summary>输出结果</summary><pre>{{ readablePayload(row.raw.paramsOut) }}</pre>
</details>
<details v-if="row.raw.actualResult || row.raw.extraInfo"
><summary>扩展记录</summary
><pre
>{{ readablePayload(row.raw.actualResult) }}
{{ readablePayload(row.raw.extraInfo) }}</pre
>
</details>
</div>
</details>
</article>
</div>
</section>
</template>
<script setup lang="ts">
import ScanExecutionSteps from './ScanExecutionSteps.vue'
import {
logTime,
presentScannerLogs,
scannerLogSummary,
readablePayload
} from './scannerLogPresentation.mjs'
const props = withDefaults(
defineProps<{
logs: any[]
status?: string
active?: boolean
loading?: boolean
height?: number
steps?: any[]
focusId?: string
hasPlan?: boolean
}>(),
{ active: true, height: 480, steps: () => [] }
)
const view = ref<'steps' | 'logs'>('steps')
const stepList = ref<InstanceType<typeof ScanExecutionSteps>>()
const onlyIssues = ref(false),
now = ref(Date.now())
const list = ref<HTMLDivElement>()
const rows = computed(() => presentScannerLogs(props.logs, props.status, now.value))
const summary = computed(() => scannerLogSummary(rows.value))
const stepCounts = computed(() => ({
completed: props.steps.filter((step) => ['success', 'skipped'].includes(step.state)).length,
failed: props.steps.filter((step) => step.state === 'failed').length
}))
const visibleRows = computed(() =>
onlyIssues.value
? rows.value.filter((row) =>
['failed', 'interrupted', 'cancelled', 'paused', 'pending'].includes(row.status.key)
)
: rows.value
)
const visibleSteps = computed(() =>
onlyIssues.value
? props.steps.filter((step) =>
['failed', 'interrupted', 'cancelled', 'paused'].includes(step.state)
)
: props.steps
)
let positioned = false
async function latest() {
onlyIssues.value = false
await nextTick()
if (view.value === 'steps') await stepList.value?.locate()
else if (list.value) list.value.scrollTop = list.value.scrollHeight
}
async function inspect(nodeId: string) {
onlyIssues.value = false
view.value = 'logs'
await nextTick()
const matches = [...(list.value?.querySelectorAll<HTMLElement>('[data-node]') || [])].filter(
(el) => el.dataset.node === nodeId
)
const target = matches.at(-1)
if (!list.value || !target) return
const details = target.querySelector('details')
if (details) details.open = true
list.value.scrollTop = target.offsetTop
}
watch(
() => rows.value.map((row) => `${row.key}:${row.status.key}`).join(','),
async () => {
const el = list.value
const follow = !positioned || (!!el && el.scrollHeight - el.scrollTop - el.clientHeight < 40)
await nextTick()
if (!list.value || !rows.value.length || !follow) return
const failure = list.value.querySelector<HTMLElement>('[data-state="failed"]')
list.value.scrollTop = !positioned && failure ? failure.offsetTop : list.value.scrollHeight
positioned = true
},
{ immediate: true }
)
let suspended = false
onActivated(() => {
suspended = false
now.value = Date.now()
})
onDeactivated(() => {
suspended = true
})
const timer = setInterval(() => {
if (
!suspended &&
props.active &&
!document.hidden &&
props.logs.some((log) => ['RUNNING', '1'].includes(String(log.status).toUpperCase()))
)
now.value = Date.now()
}, 1000)
onBeforeUnmount(() => clearInterval(timer))
</script>
<style scoped>
.scan-log {
min-width: 0;
}
.log-heading,
.log-heading > div {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.log-heading {
justify-content: space-between;
margin-bottom: 10px;
}
.log-switch {
display: flex;
gap: 14px;
}
.log-switch button {
padding: 3px 0;
border: 0;
border-bottom: 2px solid transparent;
background: none;
color: var(--el-text-color-secondary);
font-size: 13px;
cursor: pointer;
}
.log-switch button[aria-pressed='true'] {
color: var(--el-color-primary);
border-bottom-color: var(--el-color-primary);
font-weight: 600;
}
.log-switch button:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: 2px;
}
.plan-note {
color: var(--el-text-color-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.log-count,
.empty-log,
.step-time,
.step-detail {
color: var(--el-text-color-secondary);
font-size: 12px;
}
.empty-log {
padding: 18px 0;
}
.log-list {
position: relative;
overflow-y: auto;
scrollbar-gutter: stable;
padding-right: 4px;
}
.log-row {
border-bottom: 1px solid var(--el-border-color-lighter);
}
.log-row:last-child {
border: 0;
}
.log-row > details > summary {
display: flex;
gap: 10px;
align-items: flex-start;
padding: 12px 0;
cursor: pointer;
list-style: none;
}
.log-row > details > summary::-webkit-details-marker {
display: none;
}
.log-row > details > summary:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: -2px;
}
.step-state {
width: 64px;
flex-shrink: 0;
font-size: 12px;
color: var(--el-text-color-secondary);
padding-top: 1px;
}
.step-state::before {
content: '';
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
margin-right: 6px;
vertical-align: 1px;
}
[data-state='success'] .step-state {
color: var(--el-color-success);
}
[data-state='failed'] .step-state,
[data-state='failed'] .step-result {
color: var(--el-color-danger);
}
[data-state='running'] .step-state {
color: var(--el-color-primary);
}
[data-state='paused'] .step-state,
[data-state='interrupted'] .step-state {
color: var(--el-color-warning);
}
.step-content {
display: flex;
flex-direction: column;
gap: 5px;
flex: 1;
min-width: 0;
}
.step-content strong {
font-size: 13px;
font-weight: 500;
overflow-wrap: anywhere;
}
.step-result {
color: var(--el-text-color-regular);
font-size: 12px;
line-height: 1.6;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.step-time {
display: flex;
gap: 12px;
flex-wrap: wrap;
font-variant-numeric: tabular-nums;
}
.step-detail {
flex-shrink: 0;
}
.log-row > details[open] .step-detail {
color: var(--el-color-primary);
}
.log-raw {
padding: 0 0 12px 74px;
font-size: 12px;
}
.log-raw dl {
display: grid;
grid-template-columns: 70px minmax(0, 1fr);
gap: 6px;
}
.log-raw dt {
color: var(--el-text-color-secondary);
}
.log-raw dd {
margin: 0;
overflow-wrap: anywhere;
}
.log-raw summary {
padding: 6px 0;
cursor: pointer;
}
.log-raw pre {
margin: 4px 0 10px;
padding: 10px;
background: var(--el-fill-color-light);
max-height: 240px;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 12px;
}
@media (max-width: 700px) {
.step-state {
width: 54px;
}
.log-raw {
padding-left: 0;
}
}
</style>

View File

@ -1,32 +1,79 @@
<template>
<section class="execution-monitor" :aria-busy="loading">
<div class="executed-case">
<span class="monitor-caption">{{ execution?.id ? '本次执行测试用例' : '准备执行测试用例' }}</span>
<strong>{{ identity.caseName }}</strong>
<span>方法号 / 测试用例 ID:<code>{{ identity.testCaseId || '-' }}</code></span>
<span>发布版本:{{ identity.versionNo != null ? `V${identity.versionNo}` : '尚未选择' }}</span>
</div>
<el-alert v-if="!identity.matchesPreparation" type="warning" :closable="false" class="mb-12px"
title="当前查看的是历史执行记录,以下用例和版本以本次执行时的冻结记录为准。" />
<div class="monitor-heading">
<div>
<h3>本次执行进度</h3>
<span class="monitor-caption">{{ execution?.executionNo || '尚未开始执行' }}</span>
</div>
<header class="execution-overview">
<div class="overview-main"
><strong>{{ statusLabel(execution?.status || 'PENDING') }}</strong
><span class="monitor-caption">{{ execution?.executionNo || '尚未开始' }}</span></div
>
<div class="monitor-actions">
<el-tag v-if="binding">V{{ binding.versionNo }}</el-tag>
<el-popover trigger="click" :width="360" placement="bottom-start"
><template #reference><el-button text size="small">执行信息</el-button></template>
<div class="case-reference"
>扫描方案:{{ identity.caseName }} ·
{{ identity.versionNo != null ? `V${identity.versionNo}` : '版本待确认' }}</div
>
<div class="case-reference"
>方法号 / 测试用例 ID:<code>{{ identity.testCaseId || '-' }}</code></div
>
<p class="case-reference">执行编号:{{ execution?.executionNo || '尚未开始' }}</p>
<p v-if="execution?.executionType === 'SUPPLEMENT'" class="case-reference"
>补扫来源:{{
execution.runParams?.supplementSourceExecutionNo || execution.parentExecutionId
}}。原成果可从执行记录切换查看。</p
>
<p v-if="!identity.matchesPreparation" class="case-reference"
>历史记录的方案与版本,以本次执行时保存的信息为准。</p
>
</el-popover>
<el-button v-if="binding?.cmvrInstId" link type="primary" @click="openFlow"
>流程运行图</el-button
>
<el-button :loading="loading" :disabled="!execution?.id" @click="load(true)"
<el-button
text
size="small"
:loading="loading"
:disabled="!execution?.id"
@click="load(true)"
>刷新日志</el-button
>
</div>
</div>
<el-progress :percentage="percentage" :status="progressStatus" :stroke-width="10" />
<div class="node-summary">
<span>状态:{{ statusLabel(execution?.status || 'PENDING') }}</span>
<span v-if="currentNode">当前节点:{{ currentNode }}</span>
</header>
<div
v-if="execution?.id"
class="progress-overview"
:data-status="execution.status"
aria-label="本次执行进度"
>
<div class="progress-heading"
><strong>{{ stepPlan.heading }}</strong
><span class="elapsed">总耗时 {{ stepPlan.duration }}</span></div
>
<div class="progress-line">
<el-progress
class="execution-progress"
:percentage="stepPlan.percent"
:status="progressStatus"
:stroke-width="6"
:show-text="false"
/>
<span class="progress-number">{{ stepPlan.percent }}%</span>
<span class="step-count">{{
stepPlan.hasPlan
? `已完成 ${stepPlan.completed} / ${stepPlan.total} 步`
: `已收到 ${stepPlan.total} 步记录`
}}</span>
<el-tooltip :content="stepPlan.hint" placement="top"
><button class="progress-help" type="button" aria-label="步骤进度说明"
>?</button
></el-tooltip
>
</div>
<p v-if="stepPlan.unrecorded" class="progress-note"
>{{
stepPlan.unrecorded
}}
步未收到执行记录,未计入已完成步骤;可结合流程分支和详细日志核对。</p
>
</div>
<el-alert
v-if="execution?.failureReason"
@ -36,19 +83,28 @@
:title="execution.failureReason"
/>
<el-alert v-if="error" class="mb-12px" type="warning" :closable="false" :title="error" />
<ScannerExecutionViews v-if="execution?.id" :key="String(execution.id)" :execution-id="execution.id"
:execution-no="execution.executionNo" :status="execution.status" :active="active" />
<h3 class="log-heading">执行日志</h3>
<NativeTaskLog
v-if="execution?.id"
:key="String(execution.id)"
:items="items"
:list="logs"
:task-status="nativeStatus"
:height="height"
item-label="测试用例"
/>
<el-empty v-else description="确认本件装夹并开始后,这里将显示执行进度和节点日志。" />
<div v-if="execution?.id" class="monitor-layout">
<div class="monitor-visual"
><ScannerExecutionViews
:key="String(execution.id)"
:execution-id="execution.id"
:execution-no="execution.executionNo"
:status="execution.status"
:active="active"
/></div>
<ScanExecutionLog
:key="String(execution.id)"
:logs="logs"
:status="execution.status"
:loading="loading"
:active="active"
:height="height"
:steps="stepPlan.steps"
:focus-id="stepPlan.focusId"
:has-plan="stepPlan.hasPlan"
/>
</div>
<p v-else class="monitor-caption">确认本件装夹并开始后,可查看扫描画面和执行记录。</p>
</section>
</template>
@ -56,9 +112,10 @@
import * as ScanApi from '@/api/lab/scan-task'
import type { LabExecutionVO } from '@/api/lab/execution'
import { getInst } from '@/cmvr/common/api/test/log'
import NativeTaskLog from '@/cmvr/aima/views/intelligenceTest/runningTask/task-log.vue'
import ScanExecutionLog from './ScanExecutionLog.vue'
import ScannerExecutionViews from './ScannerExecutionViews.vue'
import { executionIdentity, executionProgress, readableLogs } from './executionPresentation.mjs'
import { executionIdentity, readableLogs } from './executionPresentation.mjs'
import { executionStepPlan } from './executionSteps.mjs'
import { statusLabel } from './scanForm.mjs'
import { scannerLogCursor, mergeScannerLogs } from './scannerLogs.mjs'
@ -75,14 +132,25 @@ const props = withDefaults(
{ active: true, height: 420 }
)
const binding = ref<any>()
const terminal = computed(() =>
['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(props.execution?.status || '')
)
const nativeLogs = ref<any[]>([])
const loading = ref(false)
const error = ref('')
const identity = computed(() => executionIdentity(props.execution, binding.value, {
testCaseId: props.testCaseId, caseName: props.caseName, versionNo: props.versionNo, flowData: props.flowData
}))
const now = ref(Date.now())
const identity = computed(() =>
executionIdentity(props.execution, binding.value, {
testCaseId: props.testCaseId,
caseName: props.caseName,
versionNo: props.versionNo,
flowData: props.flowData
})
)
const logs = computed(() => readableLogs(nativeLogs.value, identity.value.flowData))
const percentage = computed(() => executionProgress(props.execution, logs.value, identity.value.flowData))
const stepPlan = computed(() =>
executionStepPlan(props.execution, logs.value, identity.value.flowData, now.value)
)
const progressStatus = computed(() =>
props.execution?.status === 'SUCCEEDED'
? 'success'
@ -92,27 +160,6 @@ const progressStatus = computed(() =>
? 'warning'
: undefined
)
const nativeStatusCodes: Record<string, number> = {
SUCCEEDED: 0,
RUNNING: 1,
FAILED: 2,
PAUSED: 3,
CANCELLED: 4
}
const nativeStatus = computed(() => nativeStatusCodes[props.execution?.status || ''] ?? 1)
const items = computed(() => [
{
id: binding.value?.detectionItemId || identity.value.testCaseId,
detectItemId: binding.value?.detectionItemId,
testCaseId: identity.value.testCaseId,
caseName: identity.value.caseName
}
])
const currentNode = computed(() => {
const running = logs.value.filter((log: any) => ['RUNNING', '1'].includes(String(log.status)))
const last = running.at(-1) || logs.value.at(-1)
return last?.nodeName || ''
})
let generation = 0
let pending: { id: string; token: number } | undefined
let controller: AbortController | undefined
@ -128,7 +175,8 @@ async function load(force = false) {
loading.value = true
error.value = ''
try {
const result = (!force && binding.value?.cmvrInstId) ? binding.value : await ScanApi.getCmvrBinding(id, signal)
const result =
!force && binding.value?.cmvrInstId ? binding.value : await ScanApi.getCmvrBinding(id, signal)
if (token !== generation) return
binding.value = result
if (!result?.cmvrInstId) {
@ -139,7 +187,10 @@ async function load(force = false) {
const afterId = force ? undefined : scannerLogCursor(nativeLogs.value)
let pageNum = 1
while (true) {
const response: any = await getInst({ instId: result.cmvrInstId, afterId, pageNum, pageSize: 100 }, signal)
const response: any = await getInst(
{ instId: result.cmvrInstId, afterId, pageNum, pageSize: 100 },
signal
)
if (token !== generation) return
const rows = response.rows || []
found.push(...rows)
@ -148,7 +199,8 @@ async function load(force = false) {
}
nativeLogs.value = force ? found : mergeScannerLogs(nativeLogs.value, found)
} catch (failure: any) {
if (token === generation && !signal.aborted) error.value = failure.message || '日志加载失败,请刷新重试。'
if (token === generation && !signal.aborted)
error.value = failure.message || '日志加载失败,请刷新重试。'
} finally {
if (token === generation) loading.value = false
if (pending?.token === token) pending = undefined
@ -169,6 +221,8 @@ watch(
() => props.execution?.id,
() => {
generation++
controller?.abort()
pending = undefined
binding.value = undefined
nativeLogs.value = []
loading.value = false
@ -177,13 +231,15 @@ watch(
},
{ immediate: true }
)
watch(
[() => props.active, () => props.execution?.status],
() => {
if (props.active && !suspended) load(true)
else { generation++; controller?.abort(); pending = undefined; loading.value = false }
watch([() => props.active, () => props.execution?.status], () => {
if (props.active && !suspended) load(true)
else {
generation++
controller?.abort()
pending = undefined
loading.value = false
}
)
})
const timer = setInterval(() => {
if (
props.active &&
@ -193,50 +249,164 @@ const timer = setInterval(() => {
)
load()
}, 2000)
onActivated(() => { suspended = false; if (props.active) load(true) })
onDeactivated(() => { suspended = true; generation++; controller?.abort(); pending = undefined; loading.value = false })
const clock = setInterval(() => {
if (props.active && !suspended && !document.hidden && !terminal.value) now.value = Date.now()
}, 1000)
onActivated(() => {
suspended = false
if (props.active) load(true)
})
onDeactivated(() => {
suspended = true
generation++
controller?.abort()
pending = undefined
loading.value = false
})
onBeforeUnmount(() => {
generation++
controller?.abort()
clearInterval(timer)
clearInterval(clock)
})
</script>
<style scoped>
.executed-case {
display: grid;
gap: 8px;
padding: 12px 16px;
margin-bottom: 20px;
background: var(--el-fill-color-light);
border-radius: 6px;
.execution-monitor {
container-type: inline-size;
}
.execution-overview,
.overview-main {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
}
.execution-overview {
justify-content: space-between;
padding: 0 0 12px;
border-bottom: 1px solid var(--el-border-color-lighter);
margin-bottom: 12px;
}
.overview-main {
min-width: 0;
font-size: 13px;
}
.overview-main strong {
font-weight: 500;
}
.current-step {
color: var(--el-text-color-regular);
font-size: 12px;
overflow-wrap: anywhere;
}
.monitor-heading,
.monitor-actions,
.node-summary {
.execution-progress {
flex: 1;
min-width: 60px;
}
.progress-overview {
margin-bottom: 14px;
}
.progress-heading {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin-bottom: 9px;
}
.progress-heading strong {
font-size: 14px;
font-weight: 600;
overflow-wrap: anywhere;
}
.elapsed,
.step-count,
.progress-note {
color: var(--el-text-color-secondary);
font-size: 12px;
}
.elapsed {
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.progress-line {
display: flex;
align-items: center;
gap: 10px;
}
.progress-number {
font-size: 13px;
color: var(--el-color-primary);
font-variant-numeric: tabular-nums;
}
.step-count {
white-space: nowrap;
}
.progress-help {
width: 17px;
height: 17px;
flex-shrink: 0;
border: 1px solid var(--el-border-color);
border-radius: 50%;
background: none;
padding: 0;
font-size: 11px;
color: var(--el-text-color-secondary);
cursor: help;
}
.progress-note {
margin: 7px 0 0;
line-height: 1.6;
}
[data-status='SUCCEEDED'] .progress-number {
color: var(--el-color-success);
}
[data-status='FAILED'] .progress-number {
color: var(--el-color-danger);
}
[data-status='PAUSED'] .progress-number {
color: var(--el-color-warning);
}
.monitor-layout {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
}
.monitor-visual {
min-width: 0;
}
.monitor-layout > .scan-log {
order: -1;
padding-bottom: 12px;
border-bottom: 1px solid var(--el-border-color-lighter);
--execution-step-list-height: 220px;
}
@container (min-width: 900px) {
.monitor-layout {
grid-template-columns: minmax(0, 1.6fr) minmax(330px, 1fr);
align-items: start;
}
.monitor-layout > .scan-log {
order: 0;
border-bottom: 0;
border-left: 1px solid var(--el-border-color-lighter);
padding: 12px 0 0 16px;
--execution-step-list-height: 1000px;
}
}
.case-reference {
color: var(--el-text-color-regular);
font-size: 12px;
overflow-wrap: anywhere;
}
.monitor-actions {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.monitor-heading {
justify-content: space-between;
margin-bottom: 16px;
}
h3 {
margin: 0 0 6px;
font-size: 16px;
}
.monitor-caption,
.node-summary {
.monitor-caption {
color: var(--el-text-color-secondary);
font-size: 13px;
}
.node-summary {
margin: 10px 0 20px;
}
.log-heading {
margin-top: 20px;
}
</style>

View File

@ -0,0 +1,210 @@
<template>
<div
ref="list"
class="step-list"
:style="{
maxHeight: `min(var(--execution-step-list-height, 1000px), ${Math.max(280, height)}px)`
}"
@scroll.passive="trackFollowing"
>
<ol aria-label="本次执行步骤">
<li
v-for="step in steps"
:key="step.id"
:data-node="step.id"
:data-state="step.state"
:aria-current="['running', 'paused'].includes(step.state) ? 'step' : undefined"
>
<span class="step-marker" aria-hidden="true">{{
step.state === 'success' ? '✓' : step.number
}}</span>
<div class="step-body">
<div class="step-line"
><strong>{{ step.name }}</strong
><span class="step-label">{{ step.label }}</span></div
>
<p
v-if="['running', 'paused', 'failed', 'interrupted'].includes(step.state)"
class="step-message"
>{{ step.summary }}</p
>
<div v-if="step.recorded" class="step-meta">
<span>耗时 {{ step.duration }}</span>
<span v-if="step.repetitions > 1">{{ step.repetitions }} 次记录</span>
<button
type="button"
@click="$emit('inspect', step.id)"
:aria-label="`查看${step.name}的日志`"
>查看日志</button
>
</div>
</div>
</li>
</ol>
</div>
</template>
<script setup lang="ts">
const props = withDefaults(defineProps<{ steps: any[]; focusId?: string; height?: number }>(), {
height: 420
})
defineEmits<{ inspect: [nodeId: string] }>()
const list = ref<HTMLDivElement>()
let following = true
function currentElement() {
return [...(list.value?.querySelectorAll<HTMLElement>('[data-node]') || [])].find(
(el) => el.dataset.node === props.focusId
)
}
function trackFollowing() {
const target = currentElement(),
el = list.value
if (target && el)
following =
target.offsetTop >= el.scrollTop - 8 && target.offsetTop < el.scrollTop + el.clientHeight - 24
}
async function locate() {
following = true
await nextTick()
const target = currentElement()
if (list.value && target) list.value.scrollTop = Math.max(0, target.offsetTop - 64)
}
watch(
() => props.steps.map((step) => `${step.id}:${step.state}`).join(','),
async () => {
if (following) await locate()
},
{ immediate: true }
)
defineExpose({ locate })
</script>
<style scoped>
.step-list {
position: relative;
overflow-y: auto;
scrollbar-gutter: stable;
padding-right: 4px;
}
ol {
list-style: none;
margin: 0;
padding: 0;
}
li {
position: relative;
display: flex;
gap: 12px;
padding: 10px 8px;
border-radius: 6px;
}
li:not(:last-child)::after {
content: '';
position: absolute;
top: 36px;
left: 20px;
bottom: -7px;
width: 1px;
background: var(--el-border-color-lighter);
}
.step-marker {
position: relative;
z-index: 1;
flex: 0 0 24px;
width: 24px;
height: 24px;
border: 1px solid var(--el-border-color);
border-radius: 50%;
display: grid;
place-items: center;
background: var(--el-bg-color);
color: var(--el-text-color-secondary);
font-size: 12px;
font-variant-numeric: tabular-nums;
box-sizing: border-box;
}
.step-body {
flex: 1;
min-width: 0;
}
.step-line {
display: flex;
gap: 10px;
align-items: baseline;
justify-content: space-between;
line-height: 24px;
}
.step-line strong {
font-size: 13px;
font-weight: 500;
overflow-wrap: anywhere;
}
.step-label {
color: var(--el-text-color-secondary);
font-size: 12px;
white-space: nowrap;
}
.step-message {
margin: 3px 0 5px;
color: var(--el-text-color-regular);
font-size: 12px;
line-height: 1.6;
overflow-wrap: anywhere;
}
.step-meta {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
font-size: 12px;
color: var(--el-text-color-secondary);
line-height: 20px;
}
.step-meta button {
border: 0;
padding: 0;
background: none;
color: var(--el-color-primary);
cursor: pointer;
font: inherit;
}
.step-meta button:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: 2px;
}
[data-state='success'] .step-marker {
background: var(--el-color-success-light-9);
border-color: var(--el-color-success-light-5);
color: var(--el-color-success);
}
[data-state='success'] .step-label {
color: var(--el-color-success);
}
[data-state='running'] {
background: var(--el-color-primary-light-9);
}
[data-state='running'] .step-marker {
color: white;
background: var(--el-color-primary);
border-color: var(--el-color-primary);
}
[data-state='running'] .step-label {
color: var(--el-color-primary);
}
[data-state='failed'] {
background: var(--el-color-danger-light-9);
}
[data-state='failed'] .step-marker,
[data-state='failed'] .step-label,
[data-state='failed'] .step-message {
color: var(--el-color-danger);
border-color: var(--el-color-danger-light-5);
}
[data-state='paused'] .step-marker,
[data-state='paused'] .step-label,
[data-state='interrupted'] .step-label {
color: var(--el-color-warning);
border-color: var(--el-color-warning-light-5);
}
[data-state='pending'] .step-line strong {
color: var(--el-text-color-secondary);
}
</style>

View File

@ -0,0 +1,100 @@
<template>
<template v-if="eligible">
<el-button type="primary" plain v-hasPermi="['lab:execution:dispatch']" :disabled="busy || checking || !option?.available" :loading="checking" @click="open">补扫当前样件</el-button>
<span v-if="!checking && !option?.available" class="text-12px text-[var(--el-color-warning)]" role="status">{{ availabilityError || '原工程尚未核对,暂不能补扫' }}</span>
</template>
<el-button v-if="execution?.executionType === 'SUPPLEMENT' && execution?.supplementCollecting" type="primary" v-hasPermi="['lab:execution:control']" :loading="finishing" @click="finish">结束采集并生成成果</el-button>
<el-dialog v-model="visible" title="补扫当前样件" width="600px" append-to-body :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy">
<el-alert class="mb-16px" type="info" :closable="false" title="仅支持在未切换的原扫描工程中补扫;切换工程或扫描会话后不能补扫。旧结果保留,补扫结束后重新生成网格并导出 PLY / STL。" />
<div v-loading="checking">
<el-alert v-if="error || availabilityError || (option && !option.available)" type="warning" :closable="false" :title="error || availabilityError || option?.message || '暂不能补扫'" class="mb-16px" />
<el-descriptions :column="1" border class="mb-16px">
<el-descriptions-item label="当前样件">{{ unit?.unitNo }}</el-descriptions-item>
<el-descriptions-item label="实物编号">{{ unit?.physicalSerial || '未填写,请现场核对样件编号' }}</el-descriptions-item>
<el-descriptions-item label="来源执行">{{ option?.parentExecutionNo || '-' }}</el-descriptions-item>
<el-descriptions-item label="原扫描工程">{{ option?.projectId || '-' }}</el-descriptions-item>
</el-descriptions>
<el-form label-position="top" :disabled="busy || checking || !option?.available">
<el-form-item label="补扫原因" required><el-input v-model="form.reason" type="textarea" :maxlength="2000" show-word-limit placeholder="例如:背面局部漏扫,需要补充采集" /></el-form-item>
<el-form-item label="最长采集时长(秒)" required><el-input-number v-model="form.durationSeconds" :min="1" :max="1800" :precision="0" /><span class="ml-12px">到时自动结束,也可提前结束采集。</span></el-form-item>
<el-checkbox v-model="form.sampleConfirmed">已核对是原任务的同一件实物样件</el-checkbox><br />
<el-checkbox v-model="form.fixtureConfirmed">已重新确认夹具、装夹及扫描位置适合继续采集</el-checkbox><br />
<el-checkbox v-model="form.loadedConfirmed">已确认原工程和现场条件,允许撤销当前网格并开始补扫</el-checkbox>
</el-form>
</div>
<template #footer><el-button :disabled="busy" @click="visible = false">返回</el-button><el-button :disabled="checking || !validSupplement(form, option)" :loading="busy" type="primary" @click="start">开始补扫</el-button></template>
</el-dialog>
</template>
<script setup lang="ts">
import * as ScanApi from '@/api/lab/scan-task'
import { generateUUID } from '@/utils'
import type { LabExecutionVO } from '@/api/lab/execution'
import { canSupplement, validSupplement, supplementFailure, createSupplementPrecheck } from './scannerSupplement.mjs'
const props = defineProps<{ detail: ScanApi.ScanTaskDetail; unit?: ScanApi.ScanUnit; execution?: Partial<LabExecutionVO> }>()
const emit = defineEmits<{ changed: [id?: ScanApi.Id] }>()
const message = useMessage()
const visible = ref(false), busy = ref(false), checking = ref(false), finishing = ref(false)
const error = ref(''), availabilityError = ref(''), option = ref<ScanApi.SupplementOption>()
const form = reactive({ reason: '', durationSeconds: 60, sampleConfirmed: false, fixtureConfirmed: false, loadedConfirmed: false })
let key = '', revision = 0, unitId: ScanApi.Id = '', taskId: ScanApi.Id = ''
const eligible = computed(() => !!canSupplement(props.detail, props.unit))
const precheck = createSupplementPrecheck(ScanApi.getSupplementOption, (state) => {
checking.value = state.checking
if ('option' in state) option.value = state.option
if ('error' in state) availabilityError.value = state.error
})
let active = true
let timer: ReturnType<typeof setInterval> | undefined
function checkAvailability() {
if (!active || document.hidden || !eligible.value || busy.value || !props.unit) return
return precheck.check(props.detail.task.id!, props.unit.id)
}
watch([() => props.detail.task.id, () => props.unit?.id, () => props.unit?.currentExecutionId, () => props.detail.config.revision, () => eligible.value], () => {
precheck.invalidate()
if (!busy.value) { visible.value = false; error.value = '' }
checkAvailability()
}, { immediate: true })
onMounted(() => {
timer = setInterval(checkAvailability, 5000)
document.addEventListener('visibilitychange', checkAvailability)
window.addEventListener('focus', checkAvailability)
})
onActivated(() => { active = true; checkAvailability() })
onDeactivated(() => { active = false; precheck.invalidate() })
onUnmounted(() => {
active = false; precheck.invalidate()
if (timer) clearInterval(timer)
document.removeEventListener('visibilitychange', checkAvailability)
window.removeEventListener('focus', checkAvailability)
})
async function open() {
if (!props.unit || !eligible.value || busy.value || checking.value || !option.value?.available) return
taskId = props.detail.task.id!; unitId = props.unit.id; revision = props.detail.config.revision
key = generateUUID(); error.value = ''; visible.value = true
Object.assign(form, { reason: '', durationSeconds: 60, sampleConfirmed: false, fixtureConfirmed: false, loadedConfirmed: false })
await checkAvailability()
}
async function start() {
if (!validSupplement(form, option.value) || busy.value || checking.value) return
busy.value = true; error.value = ''
try {
const id = await ScanApi.startSupplement({ taskId, unitId, parentExecutionId: option.value!.parentExecutionId!, expectedRevision: revision, ...form, reason: form.reason.trim(), idempotencyKey: key })
visible.value = false; message.success('补扫已提交,原结果已保留'); emit('changed', id)
} catch (failure: any) {
const blocked = supplementFailure(failure.message || '补扫提交失败,请刷新后核对状态')
error.value = blocked.message
if (blocked.projectChanged) {
availabilityError.value = blocked.message
if (option.value) option.value.available = false
}
}
finally { busy.value = false }
}
async function finish() {
if (!props.execution?.id || finishing.value) return
finishing.value = true
try { await ScanApi.finishSupplement(props.detail.task.id!, props.execution.id); message.success('已请求结束采集,接下来将生成并导出成果'); emit('changed') }
finally { finishing.value = false }
}
</script>

View File

@ -3,7 +3,7 @@
<el-tab-pane label="实时扫描画面" name="live">
<ScannerLiveView :execution-id="executionId" :execution-no="executionNo" :status="status" :active="active && tab === 'live'" />
</el-tab-pane>
<el-tab-pane label="三维点云 / 网格" name="model" lazy>
<el-tab-pane label="三维成果" name="model" lazy>
<ScannerModelPanel :execution-id="executionId" :status="status" :active="active && tab === 'model'" />
</el-tab-pane>
</el-tabs>
@ -11,6 +11,9 @@
<script setup lang="ts">
import ScannerLiveView from './ScannerLiveView.vue'
const ScannerModelPanel = defineAsyncComponent(() => import('./ScannerModelPanel.vue'))
withDefaults(defineProps<{ executionId: string | number; executionNo?: string; status?: string; active?: boolean }>(), { active: true })
const tab = ref('live')
const props = withDefaults(defineProps<{ executionId: string | number; executionNo?: string; status?: string; active?: boolean }>(), { active: true })
const initialTab = () => ['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(props.status || '') ? 'model' : 'live'
const tab = ref(initialTab())
watch(() => props.executionId, () => { tab.value = initialTab() })
watch(() => props.status, () => { if (tab.value === 'live' && initialTab() === 'model') tab.value = 'model' })
</script>

View File

@ -12,7 +12,9 @@
<span>扫描工程 <code>{{ view.projectId }}</code></span>
<span>工位 <code>{{ view.robotId }}</code> / 设备 <code>{{ view.deviceId }}</code></span>
<span v-if="receivedAt">画面更新 {{ receivedAt }}</span>
<span>MJPEG 流式预览<span v-if="streamFps"> · {{ streamFps }} 帧/秒</span></span>
</div>
<el-alert v-if="error" :title="error" type="warning" :closable="false" class="mb-12px" />
<div class="view-canvas" v-loading="loading">
<img v-if="imageUrl" :src="imageUrl" decoding="async" alt="本次样件扫描过程中绘制的三维画面" />
<el-empty v-else :description="error || caption" :image-size="80" />
@ -25,8 +27,9 @@
</template>
<script setup lang="ts">
import { getScannerExecutionImage, getScannerExecutionView, type ScannerExecutionView } from '@/api/lab/scan-task/scannerView'
import { streamScannerExecution, getScannerExecutionView, type ScannerExecutionView } from '@/api/lab/scan-task/scannerView'
import { acceptsScannerFrame, isLiveScannerExecution, scannerViewCaption } from './scannerView.mjs'
import { createScannerFramePump } from './scannerFramePump.mjs'
const props = withDefaults(defineProps<{
executionId?: string | number
@ -41,6 +44,7 @@ const receivedAt = ref('')
const error = ref('')
const loading = ref(false)
const expanded = ref(false)
const streamFps = ref(0)
const live = computed(() => isLiveScannerExecution(props.status))
const caption = computed(() => scannerViewCaption(view.value, props.active, watching.value))
let generation = 0
@ -48,6 +52,48 @@ let controller: AbortController | undefined
let timer: ReturnType<typeof setTimeout> | undefined
let nextMetadata = 0
let suspended = false
let streamController: AbortController | undefined
let framePump: ReturnType<typeof createScannerFramePump> | undefined
let frames = 0, fpsStarted = 0
function stopStream() {
streamController?.abort(); streamController = undefined
framePump?.stop(); framePump = undefined
streamFps.value = 0; frames = 0; fpsStarted = 0
}
function startStream(id: string | number, token: number, signal: AbortSignal) {
if (streamController || signal.aborted) return
const source = new AbortController(); streamController = source
const abort = () => source.abort()
signal.addEventListener('abort', abort, { once: true })
const pump = createScannerFramePump({
async decode(bytes: Uint8Array) {
const url = URL.createObjectURL(new Blob([new Uint8Array(bytes).buffer], { type: 'image/jpeg' }))
try { const image = new Image(); image.src = url; await image.decode(); return url }
catch (failure) { URL.revokeObjectURL(url); throw failure }
},
publish(url: string) {
if (!acceptsScannerFrame({ generation: token, executionId: id }, current()) || source.signal.aborted) { URL.revokeObjectURL(url); return }
const previous = imageUrl.value; imageUrl.value = url
if (previous) URL.revokeObjectURL(previous)
receivedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
loading.value = false; error.value = ''
const now = performance.now(); if (!fpsStarted) fpsStarted = now
frames++
if (now - fpsStarted >= 1000) { streamFps.value = Math.round(frames * 1000 / (now - fpsStarted)); fpsStarted = now; frames = 0 }
},
dispose: (url: string) => URL.revokeObjectURL(url),
onError: () => { if (token === generation) error.value = '扫描帧解码失败,等待后续画面' }
})
framePump = pump
void streamScannerExecution(id, (bytes) => pump.push(bytes), source.signal).catch((failure: any) => {
if (token !== generation || signal.aborted || source.signal.aborted) return
clearImage(); error.value = failure.message || '扫描流暂不可用'; nextMetadata = 0
}).finally(() => {
signal.removeEventListener('abort', abort); pump.stop()
if (streamController === source) { streamController = undefined; framePump = undefined; streamFps.value = 0; loading.value = false }
})
}
function clearImage() {
if (imageUrl.value) URL.revokeObjectURL(imageUrl.value)
@ -58,36 +104,27 @@ function current() { return { generation, executionId: props.executionId, active
async function tick(token: number, signal: AbortSignal) {
const id = props.executionId
if (id == null || token !== generation || !props.active || document.hidden || suspended) return
let delay = 800
const delay = 1000
try {
if (Date.now() >= nextMetadata) {
const result = await getScannerExecutionView(id, signal)
if (token !== generation) return
view.value = result
error.value = ''
nextMetadata = Date.now() + 3000
}
if (!live.value || !watching.value || !view.value.available || !view.value.previewEnabled) {
clearImage()
delay = 3000
stopStream(); clearImage(); error.value = ''
return
}
const blob = await getScannerExecutionImage(id, signal)
if (!acceptsScannerFrame({ generation: token, executionId: id }, current())) return
const url = URL.createObjectURL(blob)
clearImage()
imageUrl.value = url
receivedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
error.value = ''
startStream(id, token, signal)
} catch (failure: any) {
if (token !== generation || signal.aborted) return
clearImage()
stopStream(); clearImage()
error.value = failure.message || '扫描画面暂不可用'
nextMetadata = 0
delay = 3000
} finally {
if (token === generation) {
loading.value = false
if (!streamController) loading.value = false
if (!signal.aborted && !suspended && props.active && !document.hidden && live.value && watching.value) timer = setTimeout(() => tick(token, signal), delay)
}
}
@ -95,6 +132,7 @@ async function tick(token: number, signal: AbortSignal) {
function restart(reset = false) {
generation++
controller?.abort()
stopStream()
clearTimeout(timer)
clearImage()
error.value = ''
@ -113,6 +151,7 @@ onDeactivated(() => { suspended = true; restart() })
onBeforeUnmount(() => {
generation++
controller?.abort()
stopStream()
clearTimeout(timer)
clearImage()
document.removeEventListener('visibilitychange', onVisibility)
@ -120,10 +159,10 @@ onBeforeUnmount(() => {
</script>
<style scoped>
.scanner-live-view { margin: 20px 0; padding: 16px; border: 1px solid var(--el-border-color-light); border-radius: 6px; }
.scanner-live-view { margin: 12px 0; }
.view-heading, .view-controls, .view-identity { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
.view-heading { justify-content: space-between; margin-bottom: 12px; }
h3 { margin: 0 0 6px; font-size: 16px; }
h3 { margin: 0 0 6px; font-size: 14px; }
.view-hint, .view-identity { font-size: 13px; color: var(--el-text-color-secondary); }
.view-identity { margin-bottom: 12px; overflow-wrap: anywhere; }
.view-canvas { display: flex; justify-content: center; align-items: center; min-height: 300px; background: var(--el-fill-color-lighter); border-radius: 4px; }

View File

@ -1,36 +1,44 @@
<template>
<section class="scanner-model-panel" aria-label="本次执行三维数据">
<div class="model-heading">
<div><h3>三维点云与网格</h3><span class="model-hint">按本次执行的快照、导出文件查看,可旋转、缩放和平移</span></div>
<el-alert v-if="snapshotMessage" :title="snapshotMessage" type="info" :closable="false" class="mb-12px" />
<el-alert v-if="error" :title="error" type="warning" :closable="false" class="mb-12px" />
<div class="model-toolbar"><div v-if="models.length" class="file-controls">
<el-select v-model="selectedId" class="file-select" @change="followLatest = false"><el-option v-for="file in models" :key="file.fileId" :value="file.fileId" :label="file.name" /></el-select>
<el-checkbox v-model="followLatest" @change="chooseFile">跟随最新数据</el-checkbox>
<el-button link type="primary" :loading="downloading" @click="download">下载文件</el-button>
<el-popover v-if="selected" trigger="click" :width="360" placement="bottom-start">
<template #reference><el-button text size="small">文件信息</el-button></template>
<div class="model-hint file-info">{{ selected.name }}<br />工程:{{ selected.projectId || '-' }}<template v-if="selected.capturedAt"><br />生成时间:{{ new Date(selected.capturedAt).toLocaleString('zh-CN', { hour12: false }) }}</template></div>
</el-popover>
</div>
<div class="model-actions">
<el-button @click="refresh" :disabled="!active" :loading="loading">刷新文件</el-button>
<el-button text size="small" @click="refresh" :disabled="!active" :loading="loading">刷新文件</el-button>
<el-button v-if="live" type="primary" v-hasPermi="['lab:execution:dispatch']" :disabled="!view.available" :loading="snapshotBusy" @click="updateSnapshot">{{ snapshotKey ? '查询快照状态' : '更新三维数据' }}</el-button>
</div>
</div>
<el-alert v-if="snapshotMessage" :title="snapshotMessage" type="info" :closable="false" class="mb-12px" />
<el-alert v-if="error" :title="error" type="warning" :closable="false" class="mb-12px" />
<div v-if="models.length" class="file-controls">
<el-select v-model="selectedId" class="file-select" @change="followLatest = false"><el-option v-for="file in models" :key="file.fileId" :value="file.fileId" :label="file.name" /></el-select>
<el-checkbox v-model="followLatest" @change="chooseFile">跟随最新数据</el-checkbox>
<el-button link type="primary" :loading="downloading" @click="download">下载当前文件</el-button>
</div>
<template v-if="selected">
<div class="model-hint file-info">{{ selected.name }} · 工程 {{ selected.projectId || '-' }} <template v-if="selected.capturedAt"> · {{ new Date(selected.capturedAt).toLocaleString('zh-CN', { hour12: false }) }}</template></div>
<ScannerModelViewer v-if="active" :key="selected.fileId" :execution-id="executionId" :asset="selected" />
<ScannerModelViewer v-if="viewerReady" :key="selected.fileId" :execution-id="executionId" :asset="selected" :active="active" />
</template>
<el-empty v-else :description="!view.available && live ? view.message || '等待扫描工程就绪' : '暂无三维数据。可更新快照,或由流程中的快照、导出步骤生成文件。'" :image-size="80" />
<p class="model-hint">过程快照最多取10万点,文件可能包含采样数据;完整扫描成果按流程导出。设备忙时请等待当前步骤完成后再更新。</p>
<p v-else-if="loading" class="model-hint" role="status">正在加载本次执行的三维文件…</p>
<el-empty v-else :description="error ? '文件加载失败,请刷新重试' : live ? view.message || '等待本次执行生成三维文件' : '本次执行未生成三维文件'" :image-size="80">
<p v-if="!error" class="model-hint">实时预览不会自动保存三维模型,需在流程中完成三维快照或网格导出。</p>
</el-empty>
<el-popover trigger="click" :width="360"><template #reference><el-button text size="small">数据说明</el-button></template><p class="model-hint">过程快照最多取10万点,文件可能包含采样数据;完整扫描成果按流程导出。设备忙时请等待当前步骤完成后再更新。</p></el-popover>
</section>
</template>
<script setup lang="ts">
import { saveAs } from 'file-saver'
import { generateUUID } from '@/utils'
import { createScannerSnapshot, getScannerAssets, getScannerAsset, getScannerExecutionView, getScannerSnapshotCommand, type ScannerAsset, type ScannerSnapshotCommand, type ScannerExecutionView } from '@/api/lab/scan-task/scannerView'
import { isLiveScannerExecution } from './scannerView.mjs'
import { modelFormat } from './scannerModel.mjs'
import { loadScannerAssets } from './scannerAssets.mjs'
const ScannerModelViewer = defineAsyncComponent(() => import('./ScannerModelViewer.vue'))
const props = withDefaults(defineProps<{ executionId: string | number; status?: string; active?: boolean }>(), { active: true })
const viewerReady = ref(props.active)
watch(() => props.active, value => { if (value) viewerReady.value = true })
const view = ref<Partial<ScannerExecutionView>>({})
const files = ref<ScannerAsset[]>([])
const models = computed(() => files.value.filter(file => !!modelFormat(file.name)))
@ -70,9 +78,14 @@ async function refreshNow() {
const token = generation, id = props.executionId, signal = controller?.signal
if (!props.active || document.hidden || suspended || !signal || signal.aborted) return
try {
const [state, assets] = await Promise.all([getScannerExecutionView(id, signal), getScannerAssets(id, signal)])
const { view: state, viewError } = await loadScannerAssets({
readAssets: () => getScannerAssets(id, signal),
readView: () => getScannerExecutionView(id, signal),
live: live.value,
publish: (assets) => { if (token === generation && !signal.aborted) { files.value = assets; chooseFile() } }
})
if (token !== generation) return
view.value = state; files.value = assets || []; error.value = ''; chooseFile()
view.value = state; error.value = viewError ? '实时设备状态暂不可用,已有三维成果仍可查看和下载。' : ''
if (snapshotKey.value) {
const command = await getScannerSnapshotCommand(id, snapshotKey.value, signal)
if (token !== generation) return
@ -92,7 +105,7 @@ function refresh() {
async function updateSnapshot() {
if (snapshotKey.value) { loading.value = true; await refresh(); return }
const token = generation
requestedKey ||= crypto.randomUUID()
requestedKey ||= generateUUID()
snapshotBusy.value = true; error.value = ''
try {
const command = await createScannerSnapshot(props.executionId, requestedKey, controller?.signal)
@ -138,11 +151,12 @@ onBeforeUnmount(() => { generation++; controller?.abort(); clearTimeout(timer);
</script>
<style scoped>
.scanner-model-panel { margin: 20px 0; padding: 16px; border: 1px solid var(--el-border-color-light); border-radius: 6px; }
.model-heading, .model-actions, .file-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
.model-heading { justify-content: space-between; margin-bottom: 16px; }
h3 { margin: 0 0 6px; font-size: 16px; }
.model-hint { color: var(--el-text-color-secondary); font-size: 13px; line-height: 1.6; }
.file-select { width: min(420px, 100%); }
.scanner-model-panel { margin: 12px 0; }
.model-toolbar, .model-actions, .file-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
.model-toolbar { justify-content: space-between; margin-bottom: 12px; }
.model-hint { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; }
.file-controls { flex: 1; min-width: 0; }
.file-select { width: 320px; max-width: 100%; }
.file-info { margin: 12px 0; overflow-wrap: anywhere; }
.scanner-model-panel :deep(.el-empty) { padding: 16px 0; }
</style>

View File

@ -1,15 +1,21 @@
<template>
<div class="model-viewer" :data-model-parse-ms="parseMs" :data-model-render-count="renderCount" :data-model-hydrate-ms="hydrateMs">
<el-dialog v-model="expanded" :title="asset.name || '三维成果'" fullscreen append-to-body :close-on-click-modal="false">
<div ref="expandedHost" />
</el-dialog>
<Teleport :to="expandedHost || 'body'" :disabled="!expanded || !expandedHost">
<div class="model-viewer" :class="{ 'model-viewer--expanded': expanded }" :data-model-parse-ms="parseMs" :data-model-render-count="renderCount" :data-model-hydrate-ms="hydrateMs">
<div class="model-toolbar">
<el-button size="small" @click="fit">复位视角</el-button>
<el-button size="small" @click="expanded = !expanded">{{ expanded ? '退出全屏' : '全屏查看' }}</el-button>
<el-checkbox v-model="axesVisible" @change="updateAxes">坐标轴</el-checkbox>
<template v-if="info.points"><span>点大小</span><el-slider v-model="pointSize" :min="1" :max="6" :step="0.5" class="point-slider" @input="updatePointSize" /></template>
<span class="model-hint">拖动旋转 · 滚轮缩放 · 右键平移</span>
</div>
<div ref="container" class="model-canvas" v-loading="loading"><el-empty v-if="error" :description="error" /></div>
<div ref="container" class="model-canvas" v-loading="loading"><el-empty v-if="error" :description="error"><el-button @click="retry">重新加载</el-button></el-empty></div>
<div class="model-hint" v-if="info.vertices">{{ info.points ? `点数 ${info.points.toLocaleString()}` : `顶点 ${info.vertices.toLocaleString()} · 三角面 ${info.triangles.toLocaleString()}` }} · 按文件原始坐标显示</div>
<div class="model-hint" v-if="info.points > info.displayedPoints">当前预览 {{ info.displayedPoints.toLocaleString() }} 点,完整数据保留在原始文件中,可下载查看。</div>
</div>
</Teleport>
</template>
<script setup>
@ -21,17 +27,40 @@ import { hydrateScannerModel } from './scannerModelTransfer.mjs'
import { parseScannerModelAsync } from './scannerModelWorker.mjs'
import { createScannerRenderer } from './scannerRender.mjs'
const props = defineProps({ executionId: { type: [String, Number], required: true }, asset: { type: Object, required: true } })
const props = defineProps({ executionId: { type: [String, Number], required: true }, asset: { type: Object, required: true }, active: { type: Boolean, default: true } })
const container = ref()
const expanded = ref(false), expandedHost = ref()
const loading = ref(false), error = ref(''), axesVisible = ref(false), pointSize = ref(2)
const info = ref({ vertices: 0, points: 0, displayedPoints: 0, triangles: 0 })
const parseMs = ref(0), hydrateMs = ref(0), renderCount = ref(0)
let renderer, scene, camera, controls, model, axes, resizeObserver, intersectionObserver, controller, frames
let renderer, scene, camera, controls, model, axes, resizeObserver, intersectionObserver, controller, frames, restoreTimer
let intersecting = true, suspended = false
let generation = 0
function updateAxes() { if (axes) axes.visible = axesVisible.value; frames?.invalidate() }
function updatePointSize() { model?.object.traverse(item => { if (item.isPoints) item.material.size = pointSize.value }); frames?.invalidate() }
function visibility() { frames?.setVisible(intersecting && !document.hidden && !suspended) }
function visibility() { frames?.setVisible(props.active && intersecting && !document.hidden && !suspended && !renderer?.getContext().isContextLost()) }
function resize() {
if (!container.value || !renderer || !camera) return
const width = container.value.clientWidth, height = container.value.clientHeight
if (!width || !height) return
renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); frames?.invalidate()
}
function contextLost(event) {
event.preventDefault()
generation++; controller?.abort(); loading.value = false; frames?.setVisible(false)
error.value = '三维显示暂时中断,点击重新加载可恢复;原始成果文件仍保留。'
}
function contextRestored() {
clearTimeout(restoreTimer); error.value = ''; resize(); visibility()
if (props.active && !suspended) load()
}
function retry() {
if (renderer?.getContext().isContextLost()) {
loading.value = true; renderer.forceContextRestore()
clearTimeout(restoreTimer)
restoreTimer = setTimeout(() => { loading.value = false; error.value = '浏览器三维显示尚未恢复,请刷新页面重试;也可下载原始成果。' }, 10000)
} else load()
}
function fit() {
if (!model || !camera) return
const center = model.bounds.getCenter(new THREE.Vector3())
@ -75,34 +104,42 @@ onMounted(() => {
const light = new THREE.DirectionalLight(0xffffff, 2); light.position.set(1, 2, 3); scene.add(light)
axes = new THREE.AxesHelper(1); axes.visible = axesVisible.value; scene.add(axes)
container.value.appendChild(renderer.domElement)
resizeObserver = new ResizeObserver(() => {
const width = container.value.clientWidth, height = container.value.clientHeight
if (!width || !height) return
renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); frames.invalidate()
})
renderer.domElement.addEventListener('webglcontextlost', contextLost)
renderer.domElement.addEventListener('webglcontextrestored', contextRestored)
resize()
resizeObserver = new ResizeObserver(resize)
resizeObserver.observe(container.value)
intersectionObserver = new IntersectionObserver(entries => { intersecting = entries[0].isIntersecting; visibility() })
intersectionObserver.observe(container.value)
document.addEventListener('visibilitychange', visibility)
visibility()
} catch { error.value = '当前浏览器无法启用三维显示,请检查浏览器图形支持' }
load()
if (props.active) load()
})
watch([() => props.executionId, () => props.asset.fileId], () => { if (container.value) load() })
onActivated(() => { suspended = false; visibility(); if (!model && !loading.value && container.value) load() })
onDeactivated(() => { suspended = true; generation++; controller?.abort(); loading.value = false; visibility() })
watch([() => props.executionId, () => props.asset.fileId], () => { if (container.value && props.active) load() })
watch(() => props.active, active => {
if (!active) { expanded.value = false; generation++; controller?.abort(); loading.value = false }
visibility()
if (active) { nextTick(resize); if (!model && !loading.value && container.value) load() }
})
onActivated(() => { suspended = false; visibility(); if (props.active && !model && !loading.value && container.value) load() })
onDeactivated(() => { expanded.value = false; suspended = true; generation++; controller?.abort(); loading.value = false; visibility() })
onBeforeUnmount(() => {
generation++; controller?.abort(); resizeObserver?.disconnect(); intersectionObserver?.disconnect()
generation++; controller?.abort(); resizeObserver?.disconnect(); intersectionObserver?.disconnect(); clearTimeout(restoreTimer)
document.removeEventListener('visibilitychange', visibility)
frames?.dispose(); controls?.dispose()
disposeScannerModel(model?.object); axes?.geometry.dispose(); axes?.material.dispose()
renderer?.dispose(); renderer?.domElement.remove()
renderer?.domElement.removeEventListener('webglcontextlost', contextLost)
renderer?.domElement.removeEventListener('webglcontextrestored', contextRestored)
renderer?.dispose(); renderer?.forceContextLoss(); renderer?.domElement.remove()
})
</script>
<style scoped>
.model-toolbar { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; }
.model-canvas { height: 440px; position: relative; overflow: hidden; border-radius: 4px; background: #f5f7fa; }
.model-canvas { height: clamp(280px, 40dvh, 440px); position: relative; overflow: hidden; border-radius: 4px; background: #f5f7fa; }
.model-viewer--expanded { display: flex; flex-direction: column; height: calc(100dvh - 110px); min-height: 200px; }
.model-viewer--expanded .model-canvas { flex: 1; height: auto; min-height: 0; }
.model-canvas :deep(canvas) { display: block; }
.model-canvas :deep(.el-empty) { position: absolute; inset: 0; z-index: 1; background: #f5f7fa; }
.model-hint { color: var(--el-text-color-secondary); font-size: 13px; margin-top: 8px; }

View File

@ -1,4 +1,7 @@
const round = (n) => Math.round(n * 100) / 100
export const attemptLabel = (attempt) => `${attempt.executionNo || `第 ${attempt.attemptNo || 1} 次`} · ${attempt.executionType === 'SUPPLEMENT' ? '补扫' : attempt.executionType === 'RETEST' ? '重试' : '初次扫描'}`
export const sourceAttempt = (unit, execution) => execution?.executionType !== 'SUPPLEMENT' || execution?.parentExecutionId == null ? undefined :
unit?.attempts?.find(attempt => String(attempt.id) === String(execution.parentExecutionId))
const succeeded = (value) =>
['SUCCESS', 'SUCCEEDED', 'COMPLETED', '0'].includes(String(value).toUpperCase())
export const graphNodes = (flow) => {

View File

@ -79,6 +79,17 @@ test('readable logs use frozen names without losing native IDs or output payload
assert.equal(converted[0].paramsOut, source[0].paramsOut)
assert.equal(source[0].nodeName, undefined)
})
test('supplement history resolves its own source with full precision and preserves original selection', () => {
const original={id:'2113528291822292993',executionNo:'EX-original',executionType:'RETEST',attemptNo:5}
const supplement={id:'2113544590975799298',executionNo:'EX-supplement',executionType:'SUPPLEMENT',parentExecutionId:original.id,attemptNo:6}
const unit={currentExecutionId:supplement.id,attempts:[supplement,original]}
assert.equal(presentation.sourceAttempt(unit,supplement),original)
assert.equal(unitExecution(unit,original.id),original)
assert.equal(presentation.attemptLabel(original),'EX-original · 重试')
assert.equal(presentation.attemptLabel(supplement),'EX-supplement · 补扫')
assert.equal(presentation.sourceAttempt({attempts:[]},supplement),undefined)
assert.equal(presentation.sourceAttempt(unit,{...original,parentExecutionId:supplement.id}),undefined)
})
test('a completed scan finishes all five preparation steps while a cancelled scan does not imply completion', () => {
assert.equal(preparationStage({ startedAt: '2026-10-21' }, 'COMPLETED'), 5)
assert.equal(preparationStage({ startedAt: '2026-10-21' }, 'CANCELLED'), 4)

View File

@ -0,0 +1,152 @@
import { executionProgress, graphNodes } from './executionPresentation.mjs'
import { logDuration, presentScannerLogs } from './scannerLogPresentation.mjs'
const terminalStates = new Set(['SUCCEEDED', 'FAILED', 'CANCELLED'])
const finishedStates = new Set(['success', 'skipped'])
const parseFlow = (flow) => {
try {
return typeof flow === 'string' ? JSON.parse(flow) : flow || {}
} catch {
return {}
}
}
// Canvas array order is not execution order. Keep branches stable, and retain
// cyclic nodes once instead of expanding a loop into a fictitious step count.
export function orderedExecutionNodes(flow) {
const graph = parseFlow(flow)
const nodes = Array.isArray(graphNodes(graph)) ? graphNodes(graph) : []
const byId = new Map(
nodes.filter((node) => node?.id != null).map((node) => [String(node.id), node])
)
const incoming = new Map([...byId.keys()].map((id) => [id, new Set()]))
const outgoing = new Map([...byId.keys()].map((id) => [id, new Set()]))
for (const edge of Array.isArray(graph.edges) ? graph.edges : []) {
const from = String(edge?.sourceNodeId),
to = String(edge?.targetNodeId)
if (from === to || !byId.has(from) || !byId.has(to)) continue
outgoing.get(from).add(to)
incoming.get(to).add(from)
}
const queue = [...byId.keys()].filter((id) => !incoming.get(id).size),
ordered = []
for (let index = 0; index < queue.length; index++) {
const id = queue[index]
ordered.push(id)
for (const next of outgoing.get(id)) {
incoming.get(next).delete(id)
if (!incoming.get(next).size) queue.push(next)
}
}
const seen = new Set(ordered)
return [...ordered, ...[...byId.keys()].filter((id) => !seen.has(id))].map((id) => byId.get(id))
}
function sortedLogs(logs) {
return logs
.filter((log) => log && log.nodeId != null)
.map((log, index) => ({ log, index }))
.sort((a, b) =>
/^\d+$/.test(String(a.log.id)) && /^\d+$/.test(String(b.log.id))
? BigInt(a.log.id) < BigInt(b.log.id)
? -1
: BigInt(a.log.id) > BigInt(b.log.id)
? 1
: a.index - b.index
: a.index - b.index
)
.map((item) => item.log)
}
export function executionStepPlan(execution = {}, logs = [], flow, now = Date.now()) {
execution ||= {}
const terminal = terminalStates.has(execution.status)
const recorded = sortedLogs(logs)
const groups = new Map()
for (const log of recorded) {
const id = String(log.nodeId)
if (!groups.has(id)) groups.set(id, [])
groups.get(id).push(log)
}
const nodes = orderedExecutionNodes(flow)
const hasPlan = nodes.length > 0
const definitions = hasPlan
? nodes
: [...groups].map(([id, entries]) => ({
id,
properties: { name: entries.at(-1).nodeName || id }
}))
const steps = definitions.map((node, index) => {
const id = String(node.id),
entries = groups.get(id) || [],
latest = entries.at(-1)
const name = node.properties?.name || node.data?.label || latest?.nodeName || id
const presented = latest
? presentScannerLogs([{ ...latest, nodeName: name }], execution.status, now)[0]
: undefined
let state = presented?.status.key || 'pending'
let label = presented?.status.label || (terminal ? '未记录' : '待执行')
let summary = presented?.summary || ''
if (execution.status === 'PAUSED' && state === 'running') {
state = 'paused'
label = '已暂停'
summary = '流程已暂停,等待恢复'
}
return {
id,
number: index + 1,
name,
state,
label,
summary,
duration: presented?.duration || '—',
entries,
latest,
recorded: Boolean(latest),
repetitions: entries.length
}
})
const failed = steps.filter((step) => step.state === 'failed')
const running = steps.filter((step) => ['running', 'paused'].includes(step.state))
const completed = steps.filter((step) => finishedStates.has(step.state)).length
const focus =
failed.at(-1) || running[0] || [...steps].reverse().find((step) => step.recorded) || steps[0]
const current = failed.length ? failed : running
const currentName = current.map((step) => step.name).join('、')
const heading =
execution.status === 'SUCCEEDED'
? '本次执行已完成'
: execution.status === 'FAILED'
? `失败步骤:${currentName || execution.currentStepName || '等待日志确认'}`
: execution.status === 'CANCELLED'
? '本次执行已终止'
: execution.status === 'PAUSED'
? `已暂停${currentName ? `:${currentName}` : ''}`
: currentName
? `正在执行:${currentName}`
: execution.id
? '等待下一步骤'
: '等待开始执行'
const latestLogs = steps.filter((step) => step.latest).map((step) => step.latest)
const percent = executionProgress(execution, latestLogs, hasPlan ? { nodes } : undefined)
const started = execution.startedAt ?? recorded.find((log) => log.startTime != null)?.startTime
const ended =
execution.finishedAt ??
(terminal ? [...recorded].reverse().find((log) => log.endTime != null)?.endTime : now)
return {
steps,
hasPlan,
completed,
total: steps.length,
percent,
heading,
focusId: focus?.id,
failed: failed.length,
running: running.length,
duration: logDuration(started, ended),
unrecorded: terminal ? steps.filter((step) => !step.recorded).length : 0,
hint: hasPlan
? '按本次执行保存的流程展示;步骤进度不代表扫描覆盖率,分支或循环以实际日志为准。'
: '流程步骤暂未加载,先展示已收到的执行记录。'
}
}

View File

@ -0,0 +1,157 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { executionStepPlan, orderedExecutionNodes } from './executionSteps.mjs'
const flow = {
nodes: ['end', 'scan', 'start', 'export'].map((id) => ({
id,
properties: { name: `步骤-${id}` }
})),
edges: [
['start', 'scan'],
['scan', 'export'],
['export', 'end']
].map(([sourceNodeId, targetNodeId]) => ({ sourceNodeId, targetNodeId }))
}
const row = (id, nodeId, status, extra = {}) => ({ id, nodeId, status, ...extra })
test('步骤按冻结流程连线排序,保留后续待执行步骤,而不是画布数组顺序', () => {
const plan = executionStepPlan(
{ id: '1', status: 'RUNNING' },
[row('1', 'start', 'SUCCESS'), row('2', 'scan', 'RUNNING', { startTime: 1000 })],
flow,
6000
)
assert.deepEqual(
plan.steps.map((s) => s.id),
['start', 'scan', 'export', 'end']
)
assert.deepEqual(
plan.steps.map((s) => s.label),
['成功', '执行中', '待执行', '待执行']
)
assert.equal(plan.heading, '正在执行:步骤-scan')
assert.equal(plan.focusId, 'scan')
assert.equal(plan.completed, 1)
assert.equal(plan.total, 4)
assert.equal(plan.percent, 25)
assert.equal(plan.steps[1].duration, '5.0 秒')
})
test('循环同一步只计一次,以最新记录为准,64位日志ID排序不丢精度', () => {
const logs = [
row('9007199254740995', 'scan', 'RUNNING'),
row('9007199254740994', 'scan', 'SUCCESS'),
row('9007199254740993', 'start', 'SUCCESS')
]
const plan = executionStepPlan({ status: 'RUNNING' }, logs, flow)
assert.equal(plan.completed, 1)
assert.equal(plan.percent, 25)
assert.equal(plan.steps[1].state, 'running')
assert.equal(plan.steps[1].repetitions, 2)
assert.equal(plan.steps[1].entries[0].id, '9007199254740994')
assert.equal(logs[0].id, '9007199254740995')
})
test('暂停不冒充持续运行;失败后未结束日志不继续计时,后续步骤不伪造完成', () => {
const logs = [row('1', 'start', 'SUCCESS'), row('2', 'scan', 'RUNNING', { startTime: 1000 })]
const paused = executionStepPlan({ status: 'PAUSED' }, logs, flow, 6000)
assert.equal(paused.steps[1].state, 'paused')
assert.match(paused.heading, /已暂停/)
const failed = executionStepPlan(
{ status: 'FAILED' },
[...logs, row('3', 'export', 'FAILED', { message: '磁盘满' })],
flow,
9000
)
assert.equal(failed.focusId, 'export')
assert.equal(failed.steps[1].state, 'interrupted')
assert.equal(failed.steps[1].duration, '—')
assert.equal(failed.steps[3].label, '未记录')
assert.equal(failed.steps[2].summary, '磁盘满')
assert.match(failed.heading, /失败步骤:步骤-export/)
})
test('分支并发显示全部运行步骤;未选择分支在成功后不伪造绿色成功', () => {
const branch = {
nodes: ['start', 'a', 'b', 'end'].map((id) => ({ id })),
edges: [
['start', 'a'],
['start', 'b'],
['a', 'end'],
['b', 'end']
].map(([sourceNodeId, targetNodeId]) => ({ sourceNodeId, targetNodeId }))
}
const concurrent = executionStepPlan(
{ status: 'RUNNING' },
[row('1', 'a', 'RUNNING'), row('2', 'b', 'RUNNING')],
branch
)
assert.equal(concurrent.running, 2)
assert.match(concurrent.heading, /a、b/)
const ended = executionStepPlan(
{ status: 'SUCCEEDED' },
[row('1', 'start', 'SUCCESS'), row('2', 'a', 'SUCCESS'), row('3', 'end', 'SUCCESS')],
branch
)
assert.equal(ended.percent, 100)
assert.equal(ended.completed, 3)
assert.equal(ended.total, 4)
assert.equal(ended.steps.find((s) => s.id === 'b').label, '未记录')
assert.equal(ended.unrecorded, 1)
})
test('不能根据步骤全部成功推断整件成功;取消保留已完成进度', () => {
const logs = flow.nodes.map((node, i) => row(String(i + 1), node.id, 'SUCCESS'))
assert.equal(executionStepPlan({ status: 'RUNNING' }, logs, flow).percent, 99)
const cancelled = executionStepPlan({ status: 'CANCELLED' }, logs.slice(0, 1), flow)
assert.notEqual(cancelled.percent, 100)
assert.equal(cancelled.heading, '本次执行已终止')
})
test('嵌套子节点日志不进入顶层步骤计数,但原始记录仍由日志视图保留', () => {
const plan = executionStepPlan(
{ status: 'RUNNING' },
[row('1', 'start', 'SUCCESS'), row('2', 'sub:child', 'SUCCESS')],
flow
)
assert.equal(plan.completed, 1)
assert.equal(plan.total, 4)
assert.equal(plan.percent, 25)
})
test('无流程时只展示确实收到的记录,不能臆造剩余步骤和预计时间', () => {
const plan = executionStepPlan(
{ status: 'RUNNING' },
[row('1', 'x', 'RUNNING', { nodeName: '真实名称' })],
'{bad'
)
assert.equal(plan.hasPlan, false)
assert.equal(plan.steps[0].name, '真实名称')
assert.equal(plan.percent, 0)
assert.match(plan.hint, /暂未加载/)
assert.equal(executionStepPlan(undefined, [], undefined).heading, '等待开始执行')
})
test('总耗时随运行时钟增长,终态使用固定结束时间,避免历史记录无限增长', () => {
const execution = { status: 'RUNNING', startedAt: '1792739387000' }
assert.equal(executionStepPlan(execution, [], flow, 1792739392000).duration, '5.0 秒')
assert.equal(
executionStepPlan(
{ ...execution, status: 'SUCCEEDED', finishedAt: '1792739390000' },
[],
flow,
1792739999000
).duration,
'3.0 秒'
)
})
test('循环、重复连线和悬空边不重复步骤,也不使显示卡死', () => {
const graph = {
nodes: [{ id: 'a' }, { id: 'b' }, { id: 'c' }],
edges: [
['a', 'b'],
['a', 'b'],
['b', 'a'],
['missing', 'c']
].map(([sourceNodeId, targetNodeId]) => ({ sourceNodeId, targetNodeId }))
}
assert.deepEqual(
orderedExecutionNodes(JSON.stringify(graph)).map((n) => n.id),
['c', 'a', 'b']
)
assert.deepEqual(orderedExecutionNodes({ nodes: 'broken' }), [])
})

View File

@ -1,5 +1,5 @@
<template>
<ContentWrap v-loading="loading">
<ContentWrap v-loading="loading" class="scan-task-header" :body-style="{ padding: '14px 16px' }">
<el-page-header @back="router.push('/cmvr/intelligence-test/execution')">
<template #content
><span class="task-title" :title="detail?.task.taskName">{{
@ -9,20 +9,28 @@
</el-page-header>
<template v-if="detail">
<div class="task-summary">
<strong>{{ detail.task.taskNo }}</strong>
<el-tag>{{ statusLabel(detail.task.status) }}</el-tag>
<span>完成 {{ completedCount }} / {{ detail.units.length }} 件</span>
<span class="summary-count">完成 {{ completedCount }} / {{ detail.units.length }} 件</span>
<span class="summary-spacer" />
<el-popover trigger="click" placement="bottom-end" :width="360">
<template #reference><el-button text>任务信息</el-button></template>
<div class="task-metadata">
<div><span>任务编号</span><strong>{{ detail.task.taskNo }}</strong></div>
<div><span>外部任务编号</span><strong>{{ detail.task.externalTaskNo || '-' }}</strong></div>
<div><span>执行测试用例</span><strong>{{ detail.config.caseName || '-' }}</strong></div>
<div><span>原始方法号</span><code>{{ detail.config.importedTestCaseId || '-' }}</code></div>
</div>
</el-popover>
<el-button @click="manualRefresh">刷新状态</el-button>
<el-button
v-if="activeExecution?.status === 'RUNNING' && !detail.config.stopPending"
v-if="activeExecution?.status === 'RUNNING' && activeExecution?.executionType !== 'SUPPLEMENT' && !detail.config.stopPending"
:loading="busy"
v-hasPermi="['lab:execution:control']"
@click="pauseTask"
>暂停执行</el-button
>
<el-button
v-if="activeExecution?.status === 'PAUSED' && !detail.config.stopPending"
v-if="activeExecution?.status === 'PAUSED' && activeExecution?.executionType !== 'SUPPLEMENT' && !detail.config.stopPending"
:loading="busy"
v-hasPermi="['lab:execution:control']"
@click="resumeTask"
@ -38,24 +46,6 @@
>取消任务</el-button
>
</div>
<div class="task-metadata">
<div
><span>外部任务编号</span
><strong :title="detail.task.externalTaskNo">{{
detail.task.externalTaskNo
}}</strong></div
>
<div
><span>执行测试用例</span
><strong :title="detail.config.caseName">{{ detail.config.caseName || '-' }}</strong></div
>
<div
><span>原始方法号</span
><code :title="detail.config.importedTestCaseId">{{
detail.config.importedTestCaseId
}}</code></div
>
</div>
<el-alert
v-if="detail.config.stopPending"
type="error"
@ -73,19 +63,7 @@
>
</el-alert>
<el-alert
v-else-if="detail.task.status === 'COMPLETED'"
type="success"
:closable="false"
:title="`本任务 ${detail.units.length} 件样件已全部执行完成,可查看每件进度、日志与重试历史。`"
/>
<el-alert
v-else-if="detail.task.status === 'CANCELLED'"
type="warning"
:closable="false"
title="任务已取消,已执行的记录和日志保留供查看。"
/>
<el-alert
v-else-if="locked"
v-else-if="locked && activeTab === 'prepare'"
type="info"
:closable="false"
title="本任务已进入装夹准备或执行,扫描方案、版本、参数和资源已冻结。暂停和换件期间保留占用;未开始时可释放准备占用。"
@ -109,7 +87,7 @@
</template>
</ContentWrap>
<template v-if="detail">
<ContentWrap v-loading="busy">
<ContentWrap v-loading="busy" class="scan-task-content" :body-style="{ padding: '0 16px 16px' }">
<el-tabs v-model="activeTab">
<el-tab-pane label="准备与资源" name="prepare">
<el-row :gutter="24">
@ -388,21 +366,14 @@
class="mb-16px"
title="准备配置尚未保存。请回到“准备与资源”保存并预检,再开始执行所选测试用例。"
/>
<el-alert
v-if="!terminal"
type="info"
:closable="false"
class="mb-16px"
title="上一件完成后,请更换并装夹下一件。失败只重试当前件,已成功样件不会再次执行。"
/>
<div class="batch-progress">
<div v-if="detail.units.length > 1" class="batch-progress">
<div class="section-heading"
><h3>任务执行进度</h3
><h3>批次进度</h3
><span>已完成 {{ completedCount }} / {{ detail.units.length }} 件</span></div
>
<el-progress
:percentage="overallProgress"
:stroke-width="12"
:stroke-width="6"
:status="
detail.task.status === 'COMPLETED'
? 'success'
@ -411,10 +382,9 @@
: undefined
"
/>
<NativeTaskSteps :list="sampleSteps" :active-step="activeSampleStep" />
</div>
<div class="execution-layout">
<aside class="sample-queue" aria-label="样件执行队列">
<div class="execution-layout" :class="{ 'single-unit': detail.units.length === 1 }">
<aside v-if="detail.units.length > 1" class="sample-queue" aria-label="样件执行队列">
<h3>样件队列</h3>
<button
v-for="(unit, index) in detail.units"
@ -445,12 +415,12 @@
}}</span>
</button>
</aside>
<div class="selected-execution" v-if="selectedUnit">
<div ref="executionPanel" class="selected-execution" v-if="selectedUnit">
<div class="selected-unit-heading">
<div
><h3 :title="selectedUnit.unitNo">{{ selectedUnit.unitNo }}</h3
><span class="hint"
>实物编号:{{ selectedUnit.physicalSerial || '未填写' }}</span
><h3 :title="selectedUnit.unitNo">样件 {{ detail.units.findIndex(unit => String(unit.id) === String(selectedUnit?.id)) + 1 }}</h3
><span v-if="selectedUnit.physicalSerial" class="hint"
>实物编号:{{ selectedUnit.physicalSerial }}</span
></div
>
<div class="selected-unit-actions">
@ -464,7 +434,7 @@
v-for="attempt in selectedUnit.attempts"
:key="String(attempt.id)"
:value="String(attempt.id)"
:label="`第 ${attempt.attemptNo || 1} 次 · ${statusLabel(attempt.status)}`"
:label="`${attemptLabel(attempt)} · ${statusLabel(attempt.status)}`"
/>
</el-select>
<el-button
@ -475,8 +445,16 @@
@click="openStart(selectedUnit)"
>{{ selectedUnit.attemptNo ? '重新装夹并重试' : '确认装夹并开始' }}</el-button
>
<ScanSupplementActions :detail="detail" :unit="selectedUnit" :execution="selectedExecution" @changed="supplementChanged" />
</div>
</div>
<div v-if="selectedExecution" class="execution-record-context">
<span>当前查看:{{ attemptLabel(selectedExecution) }}</span>
<el-button v-if="sourceAttempt(selectedUnit, selectedExecution)" link type="primary"
@click="selectedAttemptId = String(sourceAttempt(selectedUnit, selectedExecution)!.id)">查看补扫前记录与成果</el-button>
<el-button v-if="String(selectedExecution.id) !== String(selectedUnit.currentExecutionId)" link type="primary"
@click="selectedAttemptId = String(selectedUnit.currentExecutionId)">查看最新执行</el-button>
</div>
<ScanExecutionMonitor
:execution="selectedExecution"
:case-name="detail.config.caseName"
@ -497,7 +475,7 @@
label="执行编号"
prop="executionNo"
min-width="200"
/><el-table-column label="尝试" prop="attemptNo" width="80" /><el-table-column
/><el-table-column label="类型" width="90"><template #default="{ row: attempt }">{{ attempt.executionType === 'SUPPLEMENT' ? '补扫' : attempt.executionType === 'RETEST' ? '重试' : '初次扫描' }}</template></el-table-column><el-table-column label="尝试" prop="attemptNo" width="80" /><el-table-column
label="状态"
width="130"
><template #default="{ row: attempt }">{{
@ -507,9 +485,9 @@
label="失败原因"
prop="failureReason"
min-width="180"
/><el-table-column label="操作" width="120"
/><el-table-column label="操作" width="200"
><template #default="{ row: attempt }"
><el-button link type="primary" @click="openLogs(attempt)"
><el-button link type="primary" @click="viewAttempt(row, attempt)">查看记录与成果</el-button><el-button link type="primary" @click="openLogs(attempt)"
>流程与日志</el-button
></template
></el-table-column
@ -652,7 +630,9 @@
<script setup lang="ts">
import { ElMessageBox } from 'element-plus'
import { generateUUID } from '@/utils'
import * as ScanApi from '@/api/lab/scan-task'
import ScanSupplementActions from './ScanSupplementActions.vue'
import * as FileApi from '@/api/infra/file'
import type { LabExecutionVO } from '@/api/lab/execution'
import { getTestCaseList } from '@/cmvr/aima/api/intelligenceTest/testCase'
@ -660,10 +640,9 @@ import { getDetect } from '@/cmvr/common/api/test/detect'
import { flowVersionList, flowVersionDetail } from '@/cmvr/common/api/flow/flow'
import { getResourceRoles, normalizeFlowResourceSchema } from '@/cmvr/common/utils/flowResources'
import RuntimeAssignmentsEditor from '@/cmvr/common/views/flow/components/RuntimeAssignmentsEditor.vue'
import NativeTaskSteps from '@/cmvr/aima/views/intelligenceTest/runningTask/task-steps.vue'
import ScanExecutionMonitor from './ScanExecutionMonitor.vue'
import ResourceSchedule, { type ScheduleForm } from './ResourceSchedule.vue'
import { batchProgress, preparationStage, unitExecution } from './executionPresentation.mjs'
import { attemptLabel, sourceAttempt, batchProgress, preparationStage, unitExecution } from './executionPresentation.mjs'
import ParameterFields from './ParameterFields.vue'
import {
readJson,
@ -760,20 +739,9 @@ const activeExecution = computed(() =>
)
const stage = computed(() => preparationStage(form, detail.value?.task.status))
const overallProgress = computed(() => batchProgress(detail.value?.units || []))
const sampleSteps = computed(() =>
(detail.value?.units || []).map((unit, index) => ({
id: unit.id,
caseName: `第 ${index + 1} 件`,
remark: statusLabel(unit.status)
}))
)
const activeSampleStep = computed(() => {
const units = detail.value?.units || []
const index = units.findIndex((unit) => unit.status !== 'SUCCEEDED')
return index < 0 ? units.length : index
})
const selectedUnitId = ref('')
const selectedAttemptId = ref('')
const executionPanel = ref<HTMLElement>()
const selectedUnit = computed(() => {
const units = detail.value?.units || []
return (
@ -787,6 +755,14 @@ const selectUnit = (unit: ScanApi.ScanUnit) => {
selectedUnitId.value = String(unit.id)
selectedAttemptId.value = unit.currentExecutionId ? String(unit.currentExecutionId) : ''
}
const viewAttempt = async (unit: ScanApi.ScanUnit, execution: Partial<LabExecutionVO>) => {
selectUnit(unit)
await nextTick()
selectedAttemptId.value = String(execution.id)
activeTab.value = 'units'
await nextTick()
executionPanel.value?.scrollIntoView({ block: 'start', behavior: 'smooth' })
}
watch(
() => selectedUnit.value?.id,
() => {
@ -1109,8 +1085,14 @@ const startForm = reactive({
})
const canStart = (unit: ScanApi.ScanUnit) =>
!terminal.value &&
!unit.attempts?.some(attempt => String(attempt.id) === String(unit.currentExecutionId) && attempt.executionType === 'SUPPLEMENT') &&
!detail.value?.config.stopPending &&
String(nextRunnableUnit(detail.value?.units || [])?.id) === String(unit.id)
const supplementChanged = async (id?: ScanApi.Id) => {
await refresh(true)
if (id != null) selectedAttemptId.value = String(id)
activeTab.value = 'units'
}
const releasePreparation = () =>
action(async () => {
const result = await ElMessageBox.prompt(
@ -1138,7 +1120,7 @@ const openStart = (unit: ScanApi.ScanUnit) =>
physicalSerial: unit.physicalSerial || '',
reason: '',
loadedConfirmed: false,
idempotencyKey: crypto.randomUUID()
idempotencyKey: generateUUID()
})
startVisible.value = true
})
@ -1297,12 +1279,24 @@ onUnmounted(() => {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 16px;
font-weight: 600;
}
.scan-task-header, .scan-task-content { border-radius: 6px; }
.scan-task-header :deep(.el-card__body) { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 8px 12px; }
.scan-task-header :deep(.el-page-header) { flex: 1; min-width: 240px; }
.scan-task-header :deep(.el-page-header__left) { flex-shrink: 0; white-space: nowrap; }
.scan-task-header :deep(.el-page-header__content) { min-width: 0; }
.scan-task-header :deep(.el-card__body > .el-alert), .scan-task-header :deep(.el-card__body > .el-steps) { flex-basis: 100%; }
.scan-task-header .task-title { max-width: min(420px, 65vw); }
.scan-task-header :deep(.el-alert) { font-size: 12px; }
.scan-task-content :deep(.el-tabs__header) { margin-bottom: 14px; }
.scan-task-content :deep(.el-tabs__item) { height: 44px; }
.summary-count { font-size: 12px; color: var(--el-text-color-secondary); }
.task-metadata {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 16px;
padding: 0 0 18px;
grid-template-columns: minmax(0, 1fr);
gap: 14px;
}
.task-metadata > div {
min-width: 0;
@ -1316,9 +1310,7 @@ onUnmounted(() => {
}
.task-metadata strong,
.task-metadata code {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
overflow-wrap: anywhere;
font-size: 13px;
font-weight: 400;
}
@ -1337,43 +1329,49 @@ onUnmounted(() => {
.sample-queue h3,
.selected-unit-heading h3 {
margin: 0 0 8px;
font-size: 16px;
font-size: 14px;
}
.section-heading > span {
font-size: 13px;
color: var(--el-text-color-secondary);
}
.batch-progress {
padding-top: 8px;
padding: 0 0 14px;
margin-bottom: 14px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.execution-layout {
display: grid;
grid-template-columns: 250px minmax(0, 1fr);
gap: 24px;
margin: 8px 0 20px;
grid-template-columns: 180px minmax(0, 1fr);
gap: 16px;
margin: 0 0 16px;
}
.execution-layout.single-unit { grid-template-columns: minmax(0, 1fr); }
.sample-queue {
min-width: 0;
max-height: 640px;
overflow: auto;
padding-right: 10px;
padding-right: 2px;
}
.sample-card {
display: block;
width: 100%;
text-align: left;
padding: 14px;
padding: 10px;
margin-bottom: 10px;
border: 1px solid var(--el-border-color-light);
border-radius: 8px;
border-radius: 5px;
background: var(--el-bg-color);
cursor: pointer;
color: var(--el-text-color-primary);
transition: border-color .15s, background-color .15s;
}
.sample-card:hover,
.sample-card.selected {
border-color: var(--el-color-primary);
background: var(--el-color-primary-light-9);
}
.sample-card.selected { box-shadow: inset 3px 0 0 var(--el-color-primary); }
.sample-card-heading {
display: flex;
align-items: center;
@ -1394,13 +1392,10 @@ onUnmounted(() => {
}
.selected-execution {
min-width: 0;
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
padding: 20px;
}
.selected-unit-heading {
padding-bottom: 18px;
margin-bottom: 18px;
padding-bottom: 12px;
margin-bottom: 12px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.selected-unit-heading > div {
@ -1414,10 +1409,16 @@ onUnmounted(() => {
flex-wrap: wrap;
align-items: center;
gap: 10px;
min-width: 0;
max-width: 100%;
}
.selected-unit-actions > [role='status'] { flex-basis: 100%; line-height: 1.65; }
.selected-unit-actions :deep(.el-button + .el-button) { margin-left: 0; }
.attempt-select {
width: 190px;
width: 300px;
max-width: 100%;
}
.execution-record-context { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; margin: 0 0 12px; font-size: 12px; color: var(--el-text-color-secondary); }
.execution-history {
margin-top: 20px;
}
@ -1450,7 +1451,11 @@ onUnmounted(() => {
flex-wrap: wrap;
gap: 12px;
align-items: center;
margin: 16px 0;
margin: 0;
}
@media (max-width: 780px) {
.task-metadata { grid-template-columns: minmax(0, 1fr); gap: 12px; }
.task-title { max-width: 65vw; font-size: 16px; }
}
.dimensions {
display: flex;

View File

@ -0,0 +1,8 @@
// Archived results remain usable even when the current device session is unavailable.
export async function loadScannerAssets({ readAssets, readView, live, publish }) {
const assets = await readAssets()
publish(assets || [])
if (!live) return { view: { available: false } }
try { return { view: await readView() } }
catch (viewError) { return { view: { available: false }, viewError } }
}

View File

@ -0,0 +1,34 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { loadScannerAssets } from './scannerAssets.mjs'
test('历史成果不依赖设备在线或当前工程,完整保留 PLY 和 STL', async () => {
const files = [{fileId:'ply',name:'result.ply'}, {fileId:'stl',name:'result.stl'}]
let published, deviceReads = 0
await loadScannerAssets({ readAssets:async()=>files, readView:async()=>{deviceReads++;throw new Error('project_changed')}, live:false, publish:value=>{published=value} })
assert.deepEqual(published, files)
assert.equal(deviceReads, 0)
})
test('设备状态请求未完成时,已有三维成果立即可用', async () => {
let resolveView, published
const files=[{fileId:'ply'}]
const pending=loadScannerAssets({readAssets:async()=>files, readView:()=>new Promise(resolve=>{resolveView=resolve}), live:true, publish:value=>{published=value}})
await Promise.resolve()
assert.equal(published, files)
resolveView({available:true})
assert.equal((await pending).view.available, true)
})
test('设备状态失败只影响实时控制,不清空已有成果', async () => {
const files=[{fileId:'stl'}], failure=new Error('设备状态超时')
let published
const result=await loadScannerAssets({readAssets:async()=>files, readView:async()=>{throw failure}, live:true, publish:value=>{published=value}})
assert.equal(published, files)
assert.equal(result.view.available, false)
assert.equal(result.viewError, failure)
})
test('成果列表读取失败保留真实错误,不伪装成没有三维文件', async () => {
let published=false, deviceReads=0
await assert.rejects(loadScannerAssets({readAssets:async()=>{throw new Error('成果读取失败')}, readView:async()=>{deviceReads++}, live:true, publish:()=>{published=true}}), /成果读取失败/)
assert.equal(published, false)
assert.equal(deviceReads, 0)
})

View File

@ -0,0 +1,23 @@
// Decode at most one JPEG while retaining only the newest pending frame.
// Slow browsers drop old frames instead of accumulating seconds of preview latency.
export function createScannerFramePump({ decode, publish, dispose, onError }) {
let active = true, running = false, latest
async function drain() {
if (running) return
running = true
try {
while (active && latest) {
const bytes = latest; latest = undefined
try {
const frame = await decode(bytes)
if (active) publish(frame)
else dispose(frame)
} catch (error) { if (active) onError(error) }
}
} finally { running = false }
}
return {
push(bytes) { if (active) { latest = bytes; void drain() } },
stop() { active = false; latest = undefined }
}
}

View File

@ -0,0 +1,28 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { createScannerFramePump } from './scannerFramePump.mjs'
const settle = () => new Promise(resolve => setImmediate(resolve))
test('slow decoder holds one frame and keeps only newest pending frame', async () => {
const decoded = [], published = [], waiting = []
const pump = createScannerFramePump({ decode: frame => { decoded.push(frame); return new Promise(resolve => waiting.push(resolve)) },
publish: frame => published.push(frame), dispose: () => {}, onError: assert.fail })
pump.push(1); pump.push(2); pump.push(3); pump.push(4)
assert.deepEqual(decoded, [1]); waiting.shift()(1); await settle()
assert.deepEqual(decoded, [1, 4]); waiting.shift()(4); await settle()
assert.deepEqual(published, [1, 4]); pump.stop()
})
test('stop disposes in-flight output and never publishes stale frames', async () => {
let finish; const disposed = []
const pump = createScannerFramePump({ decode: () => new Promise(resolve => { finish = resolve }), publish: assert.fail,
dispose: frame => disposed.push(frame), onError: assert.fail })
pump.push(1); pump.push(2); pump.stop(); finish('old-url'); await settle(); pump.push(3)
assert.deepEqual(disposed, ['old-url'])
})
test('a bad frame does not block later valid frames', async () => {
const errors = [], frames = []
const pump = createScannerFramePump({ decode: async frame => { if (frame === 1) throw new Error('bad jpeg'); return frame },
publish: frame => frames.push(frame), dispose: () => {}, onError: error => errors.push(error.message) })
pump.push(1); pump.push(2); await settle()
assert.deepEqual(errors, ['bad jpeg']); assert.deepEqual(frames, [2]); pump.stop()
})

View File

@ -0,0 +1,131 @@
const object = (value) => {
if (value && typeof value === 'object' && !Array.isArray(value)) return value
try {
const parsed = JSON.parse(value)
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
} catch {
return {}
}
}
export function logStatus(value) {
const status = String(value ?? '').toUpperCase()
if (['SUCCESS', 'SUCCEEDED', 'COMPLETED', '0'].includes(status))
return { key: 'success', label: '成功' }
if (['FAILED', 'FAILURE', 'ERROR', '2'].includes(status)) return { key: 'failed', label: '失败' }
if (['RUNNING', '1'].includes(status)) return { key: 'running', label: '执行中' }
if (['PAUSED', '3'].includes(status)) return { key: 'paused', label: '已暂停' }
if (['STOPPED', 'CANCELLED', '4'].includes(status)) return { key: 'cancelled', label: '已终止' }
if (status === 'SKIPPED') return { key: 'skipped', label: '已跳过' }
return { key: 'pending', label: status ? '状态待确认' : '等待执行' }
}
const timestamp = (value) =>
new Date(typeof value === 'string' && /^\d{10,16}$/.test(value) ? Number(value) : value).getTime()
export function logTime(value) {
if (value == null || value === '') return '—'
const date = new Date(timestamp(value))
return Number.isFinite(date.getTime()) ? date.toLocaleString('zh-CN', { hour12: false }) : '—'
}
export function logDuration(start, end) {
if (start == null || end == null || start === '' || end === '') return '—'
const ms = timestamp(end) - timestamp(start)
if (!Number.isFinite(ms) || ms < 0) return '—'
const seconds = ms / 1000
if (seconds < 60) return `${seconds.toFixed(1)} 秒`
const minutes = Math.floor(seconds / 60),
rest = Math.floor(seconds % 60)
return minutes < 60
? `${minutes} 分 ${rest} 秒`
: `${Math.floor(minutes / 60)} 时 ${minutes % 60} 分`
}
function errorText(log, output) {
const extra = object(log.extraInfo),
actual = object(log.actualResult)
const values = [
log.errorMessage,
actual.errorMessage,
actual.error,
extra.errorMessage,
extra.error,
output.errorMessage,
output.error,
log.message
]
const value = values.find(
(value) =>
(typeof value === 'string' && value.trim()) ||
(value && typeof value === 'object' && typeof value.message === 'string')
)
return (
typeof value === 'object' ? value.message : value || '设备未返回失败原因,请展开查看原始记录。'
)
.split(/\r?\n/)[0]
.replace(/^执行异常[::]\s*/, '')
.replace(/^(?:[\w$.]+(?:Exception|Error):\s*)+/, '')
.trim()
}
function summary(log, status, output) {
if (status.key === 'failed') return errorText(log, output)
if (status.key === 'running') return '正在执行,等待设备或流程返回结果'
if (status.key !== 'success') return status.label
const result = object(output.result)
if (Array.isArray(result.files) && result.files.length) {
if (result.files.some((file) => !file || typeof file.name !== 'string' || !file.name.trim()))
return '成果文件信息不完整,请展开输出结果核对'
return `已生成 ${result.files.length} 个文件:${result.files.map((file) => file.name || '未命名文件').join('、')}`
}
if (log.action === 'SCANNER_CREATE_PROJECT' && result.projectId)
return `已创建工程 ${result.projectId}`
if (
['SCANNER_PREVIEW_START', 'SCANNER_PREVIEW_STOP'].includes(log.action) &&
typeof result.previewEnabled === 'boolean'
)
return result.previewEnabled ? '实时预览已开启' : '实时预览已关闭'
if (typeof result.scanning === 'boolean') return result.scanning ? '采集已启动' : '采集已停止'
if (typeof result.previewEnabled === 'boolean')
return result.previewEnabled ? '实时预览已开启' : '实时预览已关闭'
if (result.meshState === 'preview') return '网格预览已生成,等待后续确认'
if (result.meshState === 'confirmed') return '网格已确认,可进行导出'
if (typeof output.result === 'string' && output.result.trim()) return output.result
if (['START', 'END'].includes(String(log.action).toUpperCase()))
return log.action.toUpperCase() === 'START' ? '本次流程已开始' : '本次流程已结束'
if (String(log.action).toUpperCase() === 'SLEEP') return '等待已完成,继续下一步'
return '操作已完成'
}
export function presentScannerLogs(logs = [], executionStatus, now = Date.now()) {
const ended = ['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(executionStatus)
return logs.map((log, index) => {
const status = logStatus(log.status),
output = object(log.paramsOut)
if (ended && ['running', 'paused'].includes(status.key)) {
status.key = 'interrupted'
status.label = '未确认完成'
}
return {
key: String(log.id ?? `row-${index}`),
name: log.nodeName || log.nodeId || '未命名步骤',
status,
start: logTime(log.startTime),
duration: logDuration(
log.startTime,
log.endTime ?? (!ended && status.key === 'running' ? now : undefined)
),
summary: summary(log, status, output),
raw: log
}
})
}
export function scannerLogSummary(rows) {
const failed = rows.filter((row) => row.status.key === 'failed')
const running = rows.filter((row) => row.status.key === 'running')
return {
total: rows.length,
succeeded: rows.filter((row) => row.status.key === 'success').length,
failed: failed.length,
current: failed.at(-1) || running.at(-1) || rows.at(-1)
}
}
export function readablePayload(value) {
if (value == null || value === '') return '无'
// Keep the original JSON text: parsing 64-bit identifiers in the browser loses precision.
return typeof value === 'string' ? value : JSON.stringify(value, null, 2)
}

View File

@ -0,0 +1,120 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {
logStatus,
logTime,
logDuration,
presentScannerLogs,
scannerLogSummary,
readablePayload
} from './scannerLogPresentation.mjs'
test('实际导出结果直接显示文件名,保留原始日志编号和数据', () => {
const log = {
id: '9007199254740993',
nodeName: '导出PLY和STL模型',
action: 'SCANNER_EXPORT',
status: 'SUCCESS',
startTime: 1000,
endTime: 4100,
paramsOut: JSON.stringify({ result: { files: [{ name: 'part.ply' }, { name: 'part.stl' }] } })
}
const [row] = presentScannerLogs([log], 'SUCCEEDED')
assert.equal(row.key, log.id)
assert.equal(row.raw, log)
assert.equal(row.summary, '已生成 2 个文件:part.ply、part.stl')
assert.equal(row.duration, '3.1 秒')
})
test('读取设备实际返回的工程、采集和网格状态,不因动作名称伪造结果', () => {
const row = (action, result) =>
presentScannerLogs(
[{ action, status: 'SUCCESS', paramsOut: JSON.stringify({ result }) }],
'SUCCEEDED'
)[0].summary
assert.equal(
row('SCANNER_CREATE_PROJECT', { projectId: 'original-project' }),
'已创建工程 original-project'
)
assert.equal(row('SCANNER_START', { scanning: true }), '采集已启动')
assert.equal(row('SCANNER_STOP', { scanning: false }), '采集已停止')
assert.equal(
row('SCANNER_PREVIEW_START', { previewEnabled: true, scanning: false }),
'实时预览已开启'
)
assert.equal(row('SCANNER_MESH', { meshState: 'preview' }), '网格预览已生成,等待后续确认')
assert.equal(row('SCANNER_EXPORT', {}), '操作已完成')
})
test('失败节点优先展示异常,未完成旧记录不能冒充仍在执行或成功', () => {
const rows = presentScannerLogs(
[
{ id: '1', nodeName: '开始采集', status: 'RUNNING', startTime: 1000 },
{
id: '2',
nodeName: '导出成果',
status: 'FAILED',
message: '执行异常:ScannerException: 扫描设备[export_failed] 文件保存失败\nstack details'
}
],
'FAILED',
5000
)
assert.equal(rows[0].status.label, '未确认完成')
assert.equal(rows[0].duration, '—')
assert.equal(rows[1].summary, '扫描设备[export_failed] 文件保存失败')
assert.equal(scannerLogSummary(rows).current.name, '导出成果')
assert.equal(scannerLogSummary(rows).failed, 1)
})
test('运行中耗时随时钟更新,但已完成步骤耗时固定,不输出 NaN', () => {
const logs = [
{ status: 'RUNNING', startTime: 1000 },
{ status: 'SUCCESS', startTime: 1000, endTime: 2000 }
]
assert.equal(presentScannerLogs(logs, 'RUNNING', 61000)[0].duration, '1 分 0 秒')
assert.equal(presentScannerLogs(logs, 'RUNNING', 90000)[1].duration, '1.0 秒')
for (const args of [
[undefined, 1],
['bad', 1],
[100, 1],
['', 1]
])
assert.equal(logDuration(...args), '—')
assert.equal(logDuration(1, 1), '0.0 秒')
assert.equal(logTime('invalid'), '—')
})
test('未知状态不标成功,重复节点各自保留,异常 JSON 不阻断日志', () => {
assert.equal(logStatus('UNRECOGNIZED').label, '状态待确认')
assert.equal(logStatus(0).key, 'success')
const rows = presentScannerLogs(
[
{ id: '1', nodeId: 'same', status: 'SUCCESS', paramsOut: '{bad' },
{ id: '2', nodeId: 'same', status: 'PAUSED' }
],
'PAUSED'
)
assert.equal(rows.length, 2)
assert.equal(scannerLogSummary(rows).succeeded, 1)
})
test('原始 JSON 的64位数据不通过浮点数解析,也不改变原始内容', () => {
const raw = '{"pointId":9007199254740993,"error":"<script>bad</script>"}'
assert.equal(readablePayload(raw), raw)
assert.equal(readablePayload(null), '无')
})
test('设备返回空文件条目时不使整个日志区域崩溃,也不把无效条目计为成果', () => {
const rows = presentScannerLogs(
[
{
status: 'SUCCESS',
action: 'SCANNER_EXPORT',
paramsOut: JSON.stringify({ result: { files: [null, {}, { name: 'part.ply' }] } })
},
{ status: 'SUCCESS', nodeName: '后续步骤' }
],
'SUCCEEDED'
)
assert.match(rows[0].summary, /信息不完整/)
assert.equal(rows[1].name, '后续步骤')
})
test('字符串时间戳与数值时间戳显示一致,耗时不会丢失', () => {
assert.equal(logTime('1792739387603'), logTime(1792739387603))
assert.equal(logDuration('1792739387603', '1792739387706'), '0.1 秒')
})

View File

@ -18,6 +18,11 @@ export function parseScannerModel(buffer, name) {
if (format === 'obj') group.add(new OBJLoader().parse(new TextDecoder().decode(buffer)))
else if (format === 'ply' || format === 'stl') {
const geometry = format === 'ply' ? new PLYLoader().parse(buffer) : new STLLoader().parse(buffer)
// Some scanner STL exports contain NaN normals on collapsed triangles.
// Normals are derived display data; rebuild them from the original positions.
// Invalid positions are still rejected below, and the source file is untouched.
if (format === 'stl' && geometry.getAttribute('normal')?.array.some(value => !Number.isFinite(value)))
geometry.computeVertexNormals()
const header = format === 'ply' ? new TextDecoder().decode(new Uint8Array(buffer, 0, Math.min(buffer.byteLength, 65536))).split('end_header')[0] : ''
const mesh = format === 'stl' || Number(/element\s+face\s+(\d+)/i.exec(header)?.[1] || 0) > 0
if (mesh) {

View File

@ -66,3 +66,24 @@ test('正常四边形和逐面颜色PLY仍能展开为可用三角面', () => {
disposeScannerModel(model.object)
}
})
test('STL退化面的NaN法向量从原坐标重建,正常三角面和原文件保持不变', () => {
const bytes = new Uint8Array(184), view = new DataView(bytes.buffer)
view.setUint32(80, 2, true)
for (let face = 0; face < 2; face++) {
const start = 84 + face * 50
for (let i = 0; i < 3; i++) view.setFloat32(start + i * 4, NaN, true)
const positions = face ? [0,0,0, 1,0,0, 0,1,0] : [1,2,3, 1,2,3, 1,2,3]
positions.forEach((value, i) => view.setFloat32(start + 12 + i * 4, value, true))
}
const original = bytes.slice()
const model = parseScannerModel(bytes.buffer, 'scanner.stl')
assert.equal(model.triangles, 2)
const normals = model.object.children[0].geometry.getAttribute('normal').array
assert.ok(normals.every(Number.isFinite)); assert.deepEqual([...normals.slice(0,9)], Array(9).fill(0))
assert.deepEqual([...normals.slice(9)], [0,0,1, 0,0,1, 0,0,1])
assert.deepEqual(bytes, original)
disposeScannerModel(model.object)
view.setFloat32(96, Infinity, true)
assert.throws(() => parseScannerModel(bytes.buffer, 'broken.stl'), /无效坐标/)
})

View File

@ -3,7 +3,8 @@ import { parseScannerModel, disposeScannerModel } from './scannerModel.mjs'
export const MAX_MODEL_BYTES = 100 * 1024 * 1024
export const MAX_DISPLAY_POINTS = 500000
const MAX_MESH_VERTICES = 3000000
export const MAX_MESH_BYTES = 256 * 1024 * 1024
export const MAX_MESH_TRIANGLES = 2500000
const MAX_OBJECTS = 256
/** Runs only in a worker. Transfer typed arrays instead of cloning millions of numbers. */
@ -17,7 +18,7 @@ export function prepareScannerModel(buffer, name, pointLimit = MAX_DISPLAY_POINT
const model = parseScannerModel(buffer, name)
const drawables = []
const transfer = new Set()
let remainingPoints = Math.max(1, Math.floor(pointLimit)), displayedPoints = 0, meshVertices = 0
let remainingPoints = Math.max(1, Math.floor(pointLimit)), displayedPoints = 0, meshBytes = 0
try {
model.object.updateMatrixWorld(true)
model.object.traverse(item => {
@ -26,8 +27,12 @@ export function prepareScannerModel(buffer, name, pointLimit = MAX_DISPLAY_POINT
if (drawables.length >= MAX_OBJECTS) throw new Error('模型分组过多,请下载原始成果查看')
const count = geometry.getAttribute('position').count
if (!item.isPoints) {
meshVertices += count
if (meshVertices > MAX_MESH_VERTICES) throw new Error('网格超出在线查看规模,请下载原始成果查看')
// STL repeats three vertices per face while PLY can share vertices. Bound
// actual GPU buffers and triangle count so equivalent geometry is accepted.
meshBytes += Object.values(geometry.attributes).reduce((sum, attribute) => sum + attribute.array.byteLength, 0)
+ (geometry.index?.array.byteLength || 0)
if (meshBytes > MAX_MESH_BYTES || model.triangles > MAX_MESH_TRIANGLES)
throw new Error('网格超过在线查看的256MiB缓冲区或250万三角面限制,请下载原始成果查看')
}
const sample = item.isPoints ? Math.min(count, remainingPoints, Math.max(1, Math.floor(pointLimit * count / model.points))) : count
if (!sample) return

View File

@ -45,6 +45,30 @@ test('STL与OBJ经线程传输后保留三角面、坐标、材质和已计算
}
assert.throws(() => prepareScannerModel(new TextEncoder().encode('ply\nformat ascii 1.0\nelement vertex 999999999\nend_header\n').buffer,'bad.ply'), /超出/)
})
test('百万三角面的STL不因展开顶点数误拒绝,完整网格在线程中解析且UI保持响应', async () => {
const triangles = 1000001
const buffer = new ArrayBuffer(84 + triangles * 50), view = new DataView(buffer)
view.setUint32(80, triangles, true)
for (let face = 0; face < triangles; face++) {
const start = 84 + face * 50
view.setFloat32(start + 8, 1, true)
view.setFloat32(start + 24, 1, true)
view.setFloat32(start + 40, 1, true)
}
let ticks = 0
const timer = setInterval(() => ticks++, 5)
try {
const data = await parseScannerModelAsync(buffer, 'large.stl', undefined, nodeModelWorker)
assert.ok(ticks > 1)
assert.equal(data.triangles, triangles); assert.equal(data.vertices, triangles * 3)
const model = hydrateScannerModel(data)
assert.equal(model.object.children[0].geometry.getAttribute('position').count, triangles * 3)
assert.equal(model.object.children[0].geometry.getAttribute('normal').count, triangles * 3)
assert.deepEqual(model.bounds.max.toArray(), [1,1,0])
disposeScannerModel(model.object)
} finally { clearInterval(timer) }
})
test('静止模型不持续绘制;交互合并一帧,隐藏及卸载取消绘制', () => {
let next = 0, rendered = 0
const frames = new Map()

View File

@ -0,0 +1,45 @@
export function canSupplement(detail, unit) {
if (!detail || !unit || detail.config?.stopPending || detail.config?.cancelRequested || !['COMPLETED', 'BLOCKED'].includes(detail.task?.status)) return false
if (detail.units.some(other => String(other.id) !== String(unit.id) && other.status !== 'SUCCEEDED')) return false
if (unit.status === 'SUCCEEDED') return true
return unit.status === 'FAILED' && unit.attempts?.some(attempt => String(attempt.id) === String(unit.currentExecutionId) && attempt.executionType === 'SUPPLEMENT')
}
export function validSupplement(form, option) {
return !!option?.available && !!option.parentExecutionId && !!form.reason?.trim() && form.reason.trim().length <= 2000
&& Number.isInteger(form.durationSeconds) && form.durationSeconds >= 1 && form.durationSeconds <= 1800
&& form.sampleConfirmed === true && form.fixtureConfirmed === true && form.loadedConfirmed === true
}
export function supplementFailure(message) {
const projectChanged = /\[project_changed\]/.test(String(message || ''))
return {
projectChanged,
message: projectChanged
? '扫描工程或会话已切换,当前样件不能补扫。原扫描成果仍可查看和下载。'
: message || '原工程核对失败'
}
}
// Ignore responses for a previously selected sample and share an in-flight check.
export function createSupplementPrecheck(load, publish) {
let generation = 0, pending
return {
invalidate() {
generation++
pending = undefined
publish({ checking: false, option: undefined, error: '' })
},
check(taskId, unitId) {
if (pending) return pending
const current = generation
publish({ checking: true })
pending = Promise.resolve().then(() => load(taskId, unitId)).then(option => {
if (current === generation) publish({ checking: false, option,
error: option?.available ? '' : supplementFailure(option?.message).message })
}, failure => {
if (current === generation) publish({ checking: false, option: undefined,
error: supplementFailure(failure?.message).message })
}).finally(() => { if (current === generation) pending = undefined })
return pending
}
}
}

View File

@ -0,0 +1,103 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { canSupplement, validSupplement, supplementFailure, createSupplementPrecheck } from './scannerSupplement.mjs'
test('成功样件可补扫,未完成批次、停止待确认和取消任务均阻止', () => {
const unit={id:'9007199254740993',status:'SUCCEEDED',attempts:[]}
const detail={task:{status:'COMPLETED'},config:{},units:[unit]}
assert.equal(canSupplement(detail,unit),true)
for(const status of ['EXECUTING','CANCELLED','STOP_PENDING'])assert.equal(canSupplement({...detail,task:{status}},unit),false)
assert.equal(canSupplement({...detail,config:{stopPending:true}},unit),false)
assert.equal(canSupplement({...detail,units:[unit,{id:'other',status:'PENDING'}]},unit),false)
})
test('补扫失败走补扫入口,原始扫描失败不能冒充补扫', () => {
const unit={id:'u',status:'FAILED',currentExecutionId:'e',attempts:[{id:'e',executionType:'SUPPLEMENT'}]}
const detail={task:{status:'BLOCKED'},config:{},units:[unit]}
assert.equal(canSupplement(detail,unit),true)
unit.attempts[0].executionType='INITIAL';assert.equal(canSupplement(detail,unit),false)
})
test('开始补扫要求三项人工确认、来源可用、原因和有效限时', () => {
const form={reason:'漏扫背面',durationSeconds:60,sampleConfirmed:true,fixtureConfirmed:true,loadedConfirmed:true}
const option={available:true,parentExecutionId:'9007199254740993'}
assert.equal(validSupplement(form,option),true)
for(const key of ['sampleConfirmed','fixtureConfirmed','loadedConfirmed'])assert.equal(validSupplement({...form,[key]:false},option),false)
for(const durationSeconds of [0,1801,1.5])assert.equal(validSupplement({...form,durationSeconds},option),false)
assert.equal(validSupplement({...form,reason:' '},option),false)
assert.equal(validSupplement(form,{...option,available:false}),false)
})
test('工程在打开弹窗或提交前切换时,明确禁止补扫且保留成果说明', () => {
for (const message of [
'扫描设备[project_changed] 扫描会话或工程已切换,当前画面不属于这次执行',
'扫描设备[project_changed] 扫描会话或工程已切换,不能继续原工程操作'
]) {
const failure = supplementFailure(message)
assert.equal(failure.projectChanged, true)
assert.match(failure.message, /不能补扫/)
assert.match(failure.message, /成果仍可查看和下载/)
}
assert.deepEqual(supplementFailure('扫描仪须在线'), {projectChanged:false,message:'扫描仪须在线'})
})
test('入口提前检查工程,重复触发共用请求,工程切换后返回不可用', async () => {
let resolve, calls = 0
const states = []
const precheck = createSupplementPrecheck(() => {
calls++
return new Promise(done => { resolve = done })
}, state => states.push(state))
precheck.invalidate()
assert.equal(states.at(-1).option, undefined)
const first = precheck.check('task', 'sample')
assert.equal(states.at(-1).checking, true)
assert.equal(precheck.check('task', 'sample'), first)
await Promise.resolve()
assert.equal(calls, 1)
resolve({available:false,message:'扫描设备[project_changed] 工程已切换'})
await first
assert.equal(states.at(-1).checking, false)
assert.equal(states.at(-1).option.available, false)
assert.match(states.at(-1).error, /不能补扫/)
})
test('切换样件后,较晚返回的旧工程检查不能覆盖当前样件', async () => {
const responses = new Map(), states = []
const precheck = createSupplementPrecheck((task, unit) => new Promise(done => responses.set(unit, done)), state => states.push(state))
const old = precheck.check('task', 'old')
await Promise.resolve()
precheck.invalidate()
const current = precheck.check('task', 'current')
await Promise.resolve()
responses.get('current')({available:false,message:'扫描设备[project_changed] 工程已切换'})
await current
const count = states.length
responses.get('old')({available:true,parentExecutionId:'old'})
await old
assert.equal(states.length, count)
assert.equal(states.at(-1).option.available, false)
})
test('网络故障清除上次可用状态,恢复后可重新验证', async () => {
let fail = false
const states = [], precheck = createSupplementPrecheck(async () => {
if (fail) throw new Error('连接失败')
return {available:true,parentExecutionId:'source'}
}, state => states.push(state))
await precheck.check('task', 'sample')
assert.equal(states.at(-1).option.available, true)
fail = true
await precheck.check('task', 'sample')
assert.equal(states.at(-1).option, undefined)
assert.equal(states.at(-1).error, '连接失败')
fail = false
await precheck.check('task', 'sample')
assert.equal(states.at(-1).option.available, true)
assert.equal(states.at(-1).error, '')
})
test('页面离开时作废未完成检查,不再更新入口状态', async () => {
let resolve
const states = [], precheck = createSupplementPrecheck(() => new Promise(done => {resolve=done}), state => states.push(state))
const pending = precheck.check('task', 'sample')
await Promise.resolve()
precheck.invalidate()
const count = states.length
resolve({available:true,parentExecutionId:'source'})
await pending
assert.equal(states.length, count)
assert.equal(states.at(-1).option, undefined)
})

View File

@ -19,13 +19,8 @@ function getRelativeScssUsePath(filename: string, targetPath: string) {
// https://vitejs.dev/config/
export default ({command, mode}: ConfigEnv): UserConfig => {
let env = {} as any
const isBuild = command === 'build'
if (!isBuild) {
env = loadEnv((process.argv[3] === '--mode' ? process.argv[4] : process.argv[3]), root)
} else {
env = loadEnv(mode, root)
}
const env = loadEnv(mode, root)
const variablesScssPath = pathResolve('src/styles/variables.scss')
return {
base: env.VITE_BASE_PATH,
@ -33,18 +28,18 @@ export default ({command, mode}: ConfigEnv): UserConfig => {
root: root,
// 服务端渲染
server: {
port: env.VITE_PORT, // 端口号
port: Number(env.VITE_PORT) || 5180,
host: "0.0.0.0",
open: env.VITE_OPEN === 'true',
// 本地跨域代理. 目前注释的原因:暂时没有用途,server 端已经支持跨域
// proxy: {
// ['/admin-api']: {
// target: env.VITE_BASE_URL,
// ws: false,
// changeOrigin: true,
// rewrite: (path) => path.replace(new RegExp(`^/admin-api`), ''),
// },
// },
// Same-origin access keeps API, scanner streams and WebSocket usable
// from another computer without referring to that computer's localhost.
proxy: env.VITE_BASE_URL ? undefined : {
'/admin-api': {
target: env.VITE_DEV_PROXY_TARGET || 'http://127.0.0.1:48090',
changeOrigin: true,
ws: true
}
},
},
// 项目使用的vite插件。 单独提取到build/vite/plugin中管理
plugins: createVitePlugins(isBuild, env),

View File

@ -0,0 +1,163 @@
{
"date": "2026-10-26",
"passed": true,
"changes": [
"顶部始终显示本次执行的步骤进度、已完成/总步数、当前步骤与总耗时",
"执行步骤基于本次执行的冻结流程,按连线排序,并列出后续待执行步骤",
"运行、暂停、失败、取消、未收到记录使用不同状态,不伪造成功",
"循环节点只计一次,保留各次详细日志;分支与子节点不会抬高顶层进度",
"步骤可一键定位详细日志;异常筛选和定位当前保留",
"宽屏双栏显示画面与步骤,窄屏优先显示220px步骤列表,实时画面和三维成果继续保留"
],
"tests": {
"frontendUnit": {
"passed": 98,
"new": 9,
"failed": 0
},
"typecheck": "passed",
"productionBuild": "passed",
"softwareFlow": [
{
"name": "无设备绑定的软件流程启动,后续步骤可由冻结流程读取",
"passed": true
},
{
"name": "执行暂停后状态正确",
"passed": true
},
{
"name": "执行恢复后继续同一执行",
"passed": true
},
{
"name": "执行取消后保留已完成步骤及未执行步骤",
"passed": true
}
],
"ui": [
"运行中显示40%、2/5步、当前第3步和两步待执行",
"点击步骤打开对应wait-ui原始日志",
"暂停明确显示已暂停,恢复继续同一执行",
"取消保留40%和未记录的后续步骤",
"既有失败记录显示失败步骤、4/12步和33.33%",
"只看异常仅显示失败步骤,定位当前恢复完整列表",
"既有补扫成功记录显示10/10步及100%,仍可查看三维模型及补扫前成果",
"672px无横向溢出,步骤优先;1280px双栏无溢出",
"只读查看用户正在执行的前叉尺寸扫描:持续采集60秒、6/12步、50%,实时预览与待执行步骤同时保留"
]
},
"progressMeaning": "按步骤完成情况计算,不代表扫描覆盖率或预计剩余时间;仅执行成功显示100%。",
"cleanup": {
"prefixes": [
"E2E-STEPS-1026091114-162b",
"E2E-STEPS-1026091158-61d8"
],
"remaining": {},
"physicalScannerControlRequests": 0
},
"protected": {
"tasks": 10,
"executions": 17,
"activeExecutions": 1,
"history": {
"taskId": "2113518333730902017",
"taskNo": "T-20261023-0004",
"attempts": [
{
"executionId": "2113544590975799298",
"executionNo": "EX-20261023-0026",
"type": "SUPPLEMENT",
"status": "SUCCEEDED",
"files": [
{
"fileId": "76b99248841b4034a5a69cbd83da85b2",
"name": "ScanResult_Project1.ply",
"bytes": 49233955,
"archived": true
},
{
"fileId": "43c30d7c9b8844338652a957083124b8",
"name": "ScanResult_Project1.stl",
"bytes": 90036334,
"archived": true
}
]
},
{
"executionId": "2113528291822292993",
"executionNo": "EX-20261023-0009",
"type": "RETEST",
"status": "SUCCEEDED",
"files": [
{
"fileId": "66dc537173f2422c8a1173c4dbe10f0d",
"name": "ScanResult_Project1.ply",
"bytes": 49235651,
"archived": true
},
{
"fileId": "69a5ddbb497d4124a48777b4d0242af8",
"name": "ScanResult_Project1.stl",
"bytes": 90039534,
"archived": true
}
]
},
{
"executionId": "2113522960404729857",
"executionNo": "EX-20261023-0008",
"type": "RETEST",
"status": "FAILED",
"files": []
},
{
"executionId": "2113522794889105409",
"executionNo": "EX-20261023-0007",
"type": "RETEST",
"status": "FAILED",
"files": []
},
{
"executionId": "2113521932007526401",
"executionNo": "EX-20261023-0006",
"type": "RETEST",
"status": "FAILED",
"files": []
},
{
"executionId": "2113521769096564738",
"executionNo": "EX-20261023-0005",
"type": "INITIAL",
"status": "FAILED",
"files": []
}
]
},
"observedUserTask": {
"taskId": "2114527232101691393",
"taskNo": "T-20261026-0002",
"name": "前叉尺寸扫描",
"externalTaskNo": "EXT-10011",
"executionId": "2114527472942821377",
"executionNo": "EX-20261026-0002",
"observedStatus": "RUNNING",
"scope": "不是本轮验证数据,仅只读打开,不暂停、不取消、不清理"
}
},
"screenshots": [
".local/execution-steps-running-20261026.png",
".local/execution-steps-display-20261026.png",
".local/execution-steps-current-task-20261026.png"
],
"buildWarnings": [
"既有编辑器等产物存在大于2MB分块提示"
],
"runtime": {
"frontend": "http://localhost:5180",
"backend": "http://localhost:48090",
"backendProfile": "dev"
},
"committed": false,
"pushed": false
}

View File

@ -0,0 +1,22 @@
{
"date": "2026-10-26",
"implemented": true,
"changes": [
"终止按钮和流程状态立即显示终止中并带loading",
"终止请求完成前互斥暂停、恢复、再次终止、试运行、保存和发布",
"旧轮询响应不能抢先结束终止中的状态",
"请求失败后恢复按钮并提示核对设备及占用",
"暂停和恢复也显示对应处理中状态",
"控制接口等待上限与设备停止确认流程对齐为300秒"
],
"tests": {
"typecheck": "passed",
"newRequestGateTests": 3,
"build": "passed",
"frontendPassed": 104
},
"backendRestarted": false,
"businessDataCreated": false,
"committed": false,
"pushed": false
}

Some files were not shown because too many files have changed in this diff Show More