AI不追问,组件新增旋转轴字段
This commit is contained in:
+3
-2
@@ -39,8 +39,9 @@ public class DemandConfiguration {
|
||||
}
|
||||
@Bean DemandAttachmentStore demandAttachmentStore(DemandRepository repository, DemandProperties properties) { return new DemandAttachmentStore(repository, properties); }
|
||||
@Bean DemandRetentionService demandRetentionService(DemandRepository repository, DemandAttachmentStore attachments) { return new DemandRetentionService(repository, attachments); }
|
||||
@Bean DemandAnalysisService demandAnalysisService(DemandRepository repository, DemandAttachmentStore attachments, DemandModelClient model, DemandNormalizer normalizer, DemandProperties properties) {
|
||||
return new DemandAnalysisService(repository, attachments, model, normalizer, properties);
|
||||
@Bean DemandAnalysisService demandAnalysisService(DemandRepository repository, DemandAttachmentStore attachments, DemandModelClient model,
|
||||
DemandNormalizer normalizer, DemandMatchService matches, DemandProperties properties) {
|
||||
return new DemandAnalysisService(repository, attachments, model, normalizer, matches, properties);
|
||||
}
|
||||
@Bean DemandAssemblyValidator demandAssemblyValidator(DemandProperties properties) { return new DemandAssemblyValidator(properties); }
|
||||
@Bean DemandRequirementChecker demandRequirementChecker(ObjectMapper json, MatchTextService text) { return new DemandRequirementChecker(json, text); }
|
||||
|
||||
+1
-37
@@ -1,21 +1,16 @@
|
||||
package com.linkerbot.cadworld.api.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.dto.demand.DemandAcceptanceRequest;
|
||||
import com.linkerbot.cadworld.dto.demand.DemandConfirmRequest;
|
||||
import com.linkerbot.cadworld.dto.demand.DemandMessageRequest;
|
||||
import com.linkerbot.cadworld.service.demand.DemandAnalysisService;
|
||||
import com.linkerbot.cadworld.service.demand.DemandAttachmentStore;
|
||||
import com.linkerbot.cadworld.service.demand.DemandMatchService;
|
||||
import com.linkerbot.cadworld.service.demand.DemandRepository;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import java.io.IOException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -34,6 +29,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
/** 消息接口自动完成需求理解、选件和装配校验;完成事件直接包含机器人方案。 */
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
@Validated
|
||||
@@ -44,7 +40,6 @@ public class RobotDemandController {
|
||||
private final DemandRepository repository;
|
||||
private final DemandAttachmentStore attachments;
|
||||
private final DemandAnalysisService analyses;
|
||||
private final DemandMatchService matches;
|
||||
|
||||
@PostMapping("/robot-conversations")
|
||||
public ApiResponse<DemandRepository.Conversation> create(HttpServletRequest request, HttpServletResponse response) {
|
||||
@@ -94,36 +89,5 @@ public class RobotDemandController {
|
||||
return ApiResponse.success(analyses.cancel(analysisId, owners.resolve(request, response)));
|
||||
}
|
||||
|
||||
@PostMapping("/robot-analyses/{analysisId}/confirm")
|
||||
public ApiResponse<JsonNode> confirm(@PathVariable @NotBlank String analysisId, @Valid @RequestBody DemandConfirmRequest input,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
String owner = owners.resolve(request, response);
|
||||
JsonNode result = repository.confirm(analysisId, owner, input.revision(), (String matchId, DemandRepository.Analysis analysis) -> matches.match(matchId, analysis));
|
||||
return ApiResponse.success(matches.publicResult(result));
|
||||
}
|
||||
|
||||
@GetMapping("/robot-demand-matches/{matchId}")
|
||||
public ApiResponse<JsonNode> match(@PathVariable @NotBlank String matchId, HttpServletRequest request, HttpServletResponse response) {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
return ApiResponse.success(matches.publicResult(repository.match(matchId, owners.resolve(request, response))));
|
||||
}
|
||||
|
||||
@PostMapping("/robot-analyses/{analysisId}/rematch")
|
||||
public ApiResponse<JsonNode> rematch(@PathVariable @NotBlank String analysisId, @Valid @RequestBody DemandConfirmRequest input,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
String owner = owners.resolve(request, response);
|
||||
JsonNode result = repository.rematch(analysisId, owner, input.revision(), (String matchId, DemandRepository.Analysis analysis) -> matches.match(matchId, analysis));
|
||||
return ApiResponse.success(matches.publicResult(result));
|
||||
}
|
||||
|
||||
@PostMapping("/robot-demand-matches/{matchId}/accept-degradation")
|
||||
public ApiResponse<JsonNode> accept(@PathVariable @NotBlank String matchId, @Valid @RequestBody DemandAcceptanceRequest input,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
String owner = owners.resolve(request, response);
|
||||
JsonNode result = repository.accept(matchId, owner, input.revision(), (String code, DemandRepository.Analysis analysis) -> matches.accept(code, analysis, repository.match(code, owner)));
|
||||
log.info("匹配降级方案接受 requestId={} matchId={} revision={} assemblyStatus={}", RequestIdHolder.get(), matchId, input.revision(), result.path("assembly").path("status").asText());
|
||||
return ApiResponse.success(matches.publicResult(result));
|
||||
}
|
||||
|
||||
public record AttachmentView(String attachmentId, String mimeType, long sizeBytes, String previewUrl) { }
|
||||
}
|
||||
|
||||
@@ -5,10 +5,12 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.service.demand.DemandMessage;
|
||||
import com.linkerbot.cadworld.service.demand.DemandModelClient;
|
||||
import com.linkerbot.cadworld.service.demand.DemandMatchService;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -29,8 +31,13 @@ import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
@@ -60,6 +67,9 @@ class DemandFlowApiTest {
|
||||
@Autowired private com.linkerbot.cadworld.service.demand.DemandRepository repository;
|
||||
@Autowired private com.linkerbot.cadworld.service.demand.DemandAttachmentStore attachments;
|
||||
@MockitoBean private DemandModelClient model;
|
||||
@MockitoSpyBean private DemandMatchService matches;
|
||||
@Autowired @org.springframework.beans.factory.annotation.Qualifier("requestMappingHandlerMapping")
|
||||
private RequestMappingHandlerMapping mappings;
|
||||
|
||||
@DynamicPropertySource static void configuration(DynamicPropertyRegistry registry) { registry.add("app.demand.attachment-directory", () -> DIRECTORY.toString()); }
|
||||
|
||||
@@ -76,6 +86,7 @@ class DemandFlowApiTest {
|
||||
component_name VARCHAR(128) NOT NULL DEFAULT '',category VARCHAR(64) NOT NULL DEFAULT '',
|
||||
description CLOB NOT NULL DEFAULT '',material VARCHAR(128) NOT NULL DEFAULT '',
|
||||
mass_kg DECIMAL(18,6) NOT NULL DEFAULT 0,degrees_of_freedom INT NOT NULL DEFAULT 0,
|
||||
rotation_axis CHAR(1) DEFAULT NULL CHECK (rotation_axis IN ('X','Y','Z')),
|
||||
function_description VARCHAR(512) NOT NULL DEFAULT '',shape VARCHAR(128) NOT NULL DEFAULT '',
|
||||
size VARCHAR(128) NOT NULL DEFAULT '',torque_nm DECIMAL(18,6) NOT NULL DEFAULT 0,
|
||||
bom_list CLOB NOT NULL,urdf_info CLOB NOT NULL,basic_fields CLOB NOT NULL DEFAULT '[]',parameter_fields CLOB NOT NULL DEFAULT '[]',
|
||||
@@ -88,14 +99,62 @@ class DemandFlowApiTest {
|
||||
when(model.analyze(anyList())).thenAnswer(invocation -> raw(invocation.getArgument(0)));
|
||||
}
|
||||
|
||||
@Test void confirmsSavedRequirementsIdempotentlyAndReturnsOriginalJsonAndResources() throws Exception {
|
||||
@Test void demandControllerExposesExactlySevenRoutesAndRemovedEndpointsReturn404() throws Exception {
|
||||
List<String> routes = new ArrayList<>();
|
||||
for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : mappings.getHandlerMethods().entrySet()) {
|
||||
if (!entry.getValue().getBeanType().equals(com.linkerbot.cadworld.api.controller.RobotDemandController.class)) continue;
|
||||
for (RequestMethod method : entry.getKey().getMethodsCondition().getMethods()) {
|
||||
for (String path : entry.getKey().getPatternValues()) routes.add(method.name() + " " + path);
|
||||
}
|
||||
}
|
||||
assertThat(routes).containsExactlyInAnyOrder(
|
||||
"POST /api/robot-conversations",
|
||||
"POST /api/robot-conversations/{conversationId}/attachments",
|
||||
"GET /api/robot-conversations/{conversationId}/attachments/{attachmentId}",
|
||||
"POST /api/robot-conversations/{conversationId}/messages",
|
||||
"GET /api/robot-analyses/{analysisId}",
|
||||
"POST /api/robot-analyses/{analysisId}/retry",
|
||||
"DELETE /api/robot-analyses/{analysisId}");
|
||||
Session session = create();
|
||||
JsonNode generated = submit(session, "m1", TEXT, List.of());
|
||||
String analysisId = generated.path("analysisId").asText();
|
||||
String matchId = generated.path("match").path("matchId").asText();
|
||||
for (String action : List.of("confirm", "rematch")) {
|
||||
mvc.perform(post("/api/robot-analyses/" + analysisId + "/" + action).cookie(session.cookie())
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"confirmed\":true}"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
mvc.perform(get("/api/robot-demand-matches/" + matchId).cookie(session.cookie())).andExpect(status().isNotFound());
|
||||
mvc.perform(post("/api/robot-demand-matches/" + matchId + "/accept-degradation").cookie(session.cookie())
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"accepted\":true}"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test void statusQueriesDoNotExposeInternalSnapshotsFromLegacyRecords() throws Exception {
|
||||
Session session = create();
|
||||
JsonNode generated = submit(session, "m1", TEXT, List.of());
|
||||
String analysisId = generated.path("analysisId").asText();
|
||||
ObjectNode legacy = generated.path("match").deepCopy();
|
||||
legacy.putObject("snapshot").put("id", 123);
|
||||
jdbc.update("UPDATE robot_demand_match SET result_json=? WHERE analysis_code=?", json.writeValueAsString(legacy), analysisId);
|
||||
JsonNode queried = generatedMatch(session, analysisId, 1);
|
||||
assertThat(queried).isEqualTo(generated.path("match"));
|
||||
assertThat(queried.has("snapshot")).isFalse();
|
||||
org.mockito.Mockito.verify(model, org.mockito.Mockito.times(1)).analyze(anyList());
|
||||
}
|
||||
|
||||
@Test void messageAutomaticallyReturnsAssemblyAndQueriesRemainIdempotent() throws Exception {
|
||||
components(true, 20);
|
||||
jdbc.update("UPDATE component SET rotation_axis='Z' WHERE component_code='CW-ARM'");
|
||||
jdbc.update("UPDATE component SET rotation_axis='X' WHERE component_code='CW-ARM-ALT'");
|
||||
Session session = create();
|
||||
JsonNode completed = submit(session, "m1", TEXT, List.of());
|
||||
assertThat(completed.path("status").asText()).isEqualTo("ready");
|
||||
assertThat(completed.path("canSubmit").asBoolean()).isTrue();
|
||||
String analysis = completed.path("analysisId").asText();
|
||||
JsonNode match = confirm(session, analysis, 1);
|
||||
assertThat(completed.path("questions")).isEmpty();
|
||||
JsonNode match = completed.path("match");
|
||||
assertThat(match.path("components").get(1).path("component").path("rotationAxis").asText()).isEqualTo("Z");
|
||||
assertThat(match.path("status").asText()).isEqualTo("complete");
|
||||
assertThat(match.path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(match.path("requirementChecks")).hasSize(3);
|
||||
@@ -106,16 +165,178 @@ class DemandFlowApiTest {
|
||||
String body = match.toString();
|
||||
for (String field : List.of("\"id\"", "urdfPrefix", "urdfMainObjectKey", "ownerHash", "snapshot", "model_version", "thinking", "apiKey")) assertThat(body).doesNotContain(field);
|
||||
JsonNode alternate = match.path("alternatives").get(1).path("items").get(0);
|
||||
assertThat(alternate.path("component").path("rotationAxis").asText()).isEqualTo("X");
|
||||
assertThat(alternate.path("component").has("bomList")).isTrue();
|
||||
assertThat(alternate.path("component").path("urdfInfo").path("rootLink").asText()).isEqualTo("ARM_V2_ROOT");
|
||||
assertThat(alternate.path("assembly").path("connections").get(0).path("childRootLink").asText()).isEqualTo("ARM_V2_ROOT");
|
||||
assertThat(confirm(session, analysis, 1).path("matchId").asText()).isEqualTo(match.path("matchId").asText());
|
||||
mvc.perform(get("/api/robot-demand-matches/" + match.path("matchId").asText()).cookie(session.cookie())).andExpect(status().isOk()).andExpect(jsonPath("$.data.snapshot").doesNotExist());
|
||||
assertThat(generatedMatch(session, analysis, 1).path("matchId").asText()).isEqualTo(match.path("matchId").asText());
|
||||
JsonNode queried = data(mvc.perform(get("/api/robot-analyses/" + analysis).cookie(session.cookie())).andExpect(status().isOk()).andReturn());
|
||||
assertThat(queried.path("match")).isEqualTo(match);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_match", Integer.class)).isEqualTo(1);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_message WHERE message_role='assistant'", Integer.class)).isZero();
|
||||
mvc.perform(get("/api/robot-analyses/" + analysis).cookie(session.cookie())).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.match.snapshot").doesNotExist());
|
||||
}
|
||||
|
||||
@Test void unspecifiedFormGeneratesDefaultRobotWithoutQuestionsOrInventedParameters() throws Exception {
|
||||
components(true, 20);
|
||||
doAnswer(invocation -> {
|
||||
ObjectNode raw = raw(invocation.getArgument(0));
|
||||
for (String field : List.of("constraints", "intentItems", "partCategories")) raw.putArray(field);
|
||||
raw.withArray("questions").add("请确认机器人类型和参数?");
|
||||
return raw;
|
||||
}).when(model).analyze(anyList());
|
||||
JsonNode generated = submit(create(), "m1", "给我拼一个机器人", List.of());
|
||||
assertThat(generated.path("status").asText()).isEqualTo("ready");
|
||||
assertThat(generated.path("questions")).isEmpty();
|
||||
assertThat(generated.path("warnings").toString()).contains("默认").doesNotContain("请确认");
|
||||
assertThat(generated.path("result").path("analysis").path("defaultTemplate").asText()).isEqualTo("biped");
|
||||
assertThat(generated.path("result").path("request").path("robotRequirements")).isEmpty();
|
||||
assertThat(generated.path("match").path("components")).hasSize(2);
|
||||
assertThat(generated.path("match").path("status").asText()).isEqualTo("partial");
|
||||
assertThat(generated.path("match").path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(generated.path("match").path("degradationAcceptanceRequired").asBoolean()).isFalse();
|
||||
}
|
||||
|
||||
@Test void explicitlyExcludedTorsoIsNotSilentlyAddedByStructuredMatching() throws Exception {
|
||||
components(true, 20);
|
||||
doAnswer(invocation -> {
|
||||
ObjectNode raw = raw(invocation.getArgument(0));
|
||||
raw.withArray("excludedCategories").addObject().put("category", "torso_0").putArray("evidenceIds").add("e1");
|
||||
intent(raw, "exclusion", "躯干", "不要躯干");
|
||||
return raw;
|
||||
}).when(model).analyze(anyList());
|
||||
JsonNode generated = submit(create(), "m1", TEXT + ",不要躯干", List.of());
|
||||
assertThat(generated.path("status").asText()).isEqualTo("ready");
|
||||
assertThat(generated.path("questions")).isEmpty();
|
||||
assertThat(generated.path("match").path("status").asText()).isEqualTo("no_match");
|
||||
assertThat(generated.path("match").path("components")).isEmpty();
|
||||
assertThat(generated.path("match").path("missingParts").get(0).path("reason").asText()).isEqualTo("EXCLUDED_TORSO");
|
||||
assertThat(generated.path("match").path("assembly").path("status").asText()).isEqualTo("blocked");
|
||||
}
|
||||
|
||||
@Test void analysisRemainsProcessingUntilSelectionAndAssemblyAreSavedTogether() throws Exception {
|
||||
components(true, 20);
|
||||
CountDownLatch selecting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
selecting.countDown();
|
||||
if (!release.await(5, TimeUnit.SECONDS)) throw new AssertionError("Selection not released");
|
||||
return invocation.callRealMethod();
|
||||
}).when(matches).match(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any());
|
||||
Session session = create();
|
||||
MvcResult pending = message(session, "m1", TEXT, List.of());
|
||||
try {
|
||||
assertThat(selecting.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
String id = jdbc.queryForObject("SELECT analysis_code FROM robot_demand_analysis", String.class);
|
||||
mvc.perform(get("/api/robot-analyses/" + id).cookie(session.cookie())).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.status").value("processing"))
|
||||
.andExpect(jsonPath("$.data.result").isEmpty()).andExpect(jsonPath("$.data.match").isEmpty());
|
||||
assertThat(jdbc.queryForObject("SELECT result_json FROM robot_demand_analysis", String.class)).isEqualTo("{}");
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_match", Integer.class)).isZero();
|
||||
} finally { release.countDown(); }
|
||||
JsonNode generated = completed(pending);
|
||||
assertThat(generated.path("match").path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(pending.getResponse().getContentAsString()).contains("assembling_robot");
|
||||
}
|
||||
|
||||
@Test void failedSelectionDoesNotPublishReadyAnalysisOrPartialSnapshot() throws Exception {
|
||||
org.mockito.Mockito.doThrow(new com.linkerbot.cadworld.common.exception.BizException(503, "DEMAND_UNAVAILABLE", "组件读取失败"))
|
||||
.when(matches).match(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any());
|
||||
Session session = create();
|
||||
MvcResult pending = message(session, "m1", TEXT, List.of());
|
||||
pending.getAsyncResult(5000);
|
||||
mvc.perform(asyncDispatch(pending)).andExpect(status().isOk());
|
||||
assertThat(pending.getResponse().getContentAsString()).contains("event:analysis.failed").doesNotContain("event:analysis.completed");
|
||||
String id = jdbc.queryForObject("SELECT analysis_code FROM robot_demand_analysis", String.class);
|
||||
mvc.perform(get("/api/robot-analyses/" + id).cookie(session.cookie())).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.status").value("failed"))
|
||||
.andExpect(jsonPath("$.data.result").isEmpty()).andExpect(jsonPath("$.data.match").isEmpty());
|
||||
assertThat(jdbc.queryForObject("SELECT result_json FROM robot_demand_analysis", String.class)).isEqualTo("{}");
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_match", Integer.class)).isZero();
|
||||
}
|
||||
|
||||
@Test void failedSnapshotInsertRollsBackReadyAnalysis() throws Exception {
|
||||
components(true, 20);
|
||||
doAnswer(invocation -> {
|
||||
JsonNode matched = (JsonNode) invocation.callRealMethod();
|
||||
// 模拟生成编码与已有匹配编码发生唯一索引冲突。
|
||||
jdbc.update("INSERT INTO robot_demand_match (match_code,analysis_code,revision,result_json,degradation_accepted,created_at,updated_at) VALUES (?,? ,1,'{}',0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
|
||||
invocation.getArgument(0, String.class), "DN-OTHER");
|
||||
return matched;
|
||||
}).when(matches).match(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any());
|
||||
Session session = create();
|
||||
MvcResult pending = message(session, "m1", TEXT, List.of());
|
||||
pending.getAsyncResult(5000);
|
||||
mvc.perform(asyncDispatch(pending)).andExpect(status().isOk());
|
||||
assertThat(pending.getResponse().getContentAsString()).contains("event:analysis.failed").doesNotContain("event:analysis.completed");
|
||||
String id = jdbc.queryForObject("SELECT analysis_code FROM robot_demand_analysis", String.class);
|
||||
assertThat(jdbc.queryForObject("SELECT result_json FROM robot_demand_analysis", String.class)).isEqualTo("{}");
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_match WHERE analysis_code=?", Integer.class, id)).isZero();
|
||||
mvc.perform(get("/api/robot-analyses/" + id).cookie(session.cookie())).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.status").value("failed")).andExpect(jsonPath("$.data.match").isEmpty());
|
||||
}
|
||||
|
||||
@Test void lostSseSubscriptionContinuesGeneratingAndCanBeRecoveredByQuery() throws Exception {
|
||||
components(true, 20);
|
||||
CountDownLatch analyzing = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
analyzing.countDown();
|
||||
if (!release.await(5, TimeUnit.SECONDS)) throw new AssertionError("Model not released");
|
||||
return raw(invocation.getArgument(0));
|
||||
}).when(model).analyze(anyList());
|
||||
Session session = create();
|
||||
MvcResult pending = message(session, "m1", TEXT, List.of());
|
||||
String id;
|
||||
try {
|
||||
assertThat(analyzing.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
id = jdbc.queryForObject("SELECT analysis_code FROM robot_demand_analysis", String.class);
|
||||
org.springframework.mock.web.MockAsyncContext context = (org.springframework.mock.web.MockAsyncContext) pending.getRequest().getAsyncContext();
|
||||
for (jakarta.servlet.AsyncListener listener : context.getListeners()) {
|
||||
listener.onError(new jakarta.servlet.AsyncEvent(context, pending.getRequest(), pending.getResponse(), new IOException("Stream disconnected")));
|
||||
}
|
||||
mvc.perform(get("/api/robot-analyses/" + id).cookie(session.cookie())).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.status").value("processing"));
|
||||
} finally { release.countDown(); }
|
||||
org.awaitility.Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(() ->
|
||||
mvc.perform(get("/api/robot-analyses/" + id).cookie(session.cookie())).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.status").value("ready"))
|
||||
.andExpect(jsonPath("$.data.match.components.length()").value(2)));
|
||||
org.mockito.Mockito.verify(model, org.mockito.Mockito.times(1)).analyze(anyList());
|
||||
}
|
||||
|
||||
@Test void newMessageDuringSelectionCannotPublishSupersededRobot() throws Exception {
|
||||
components(true, 20);
|
||||
CountDownLatch selecting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
com.linkerbot.cadworld.service.demand.DemandRepository.Analysis analysis = invocation.getArgument(1);
|
||||
if (analysis.revision() == 1) {
|
||||
selecting.countDown();
|
||||
if (!release.await(5, TimeUnit.SECONDS)) throw new AssertionError("Selection not released");
|
||||
}
|
||||
return invocation.callRealMethod();
|
||||
}).when(matches).match(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any());
|
||||
Session session = create();
|
||||
MvcResult first = message(session, "m1", TEXT, List.of());
|
||||
try {
|
||||
assertThat(selecting.await(5, TimeUnit.SECONDS)).isTrue();
|
||||
String old = jdbc.queryForObject("SELECT analysis_code FROM robot_demand_analysis WHERE revision=1", String.class);
|
||||
JsonNode current = submit(session, "m2", TEXT, List.of());
|
||||
assertThat(current.path("revision").asInt()).isEqualTo(2);
|
||||
assertThat(current.path("match").path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
first.getAsyncResult(5000);
|
||||
mvc.perform(get("/api/robot-analyses/" + old).cookie(session.cookie())).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.status").value("superseded")).andExpect(jsonPath("$.data.match").isEmpty());
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_match", Integer.class)).isEqualTo(1);
|
||||
assertThat(jdbc.queryForObject("SELECT revision FROM robot_demand_match", Integer.class)).isEqualTo(2);
|
||||
} finally { release.countDown(); }
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"step_object_key", "urdf_main_object_key"})
|
||||
void confirmAndRematchExcludeComponentsWithoutStepOrUploadedUrdf(String resourceColumn) throws Exception {
|
||||
void newMessagesRecheckComponentsWithoutStepOrUploadedUrdf(String resourceColumn) throws Exception {
|
||||
components(true, 20);
|
||||
String originalKey = jdbc.queryForObject("SELECT " + resourceColumn + " FROM component WHERE component_code='CW-ARM-ALT'", String.class);
|
||||
jdbc.update("UPDATE component SET " + resourceColumn + "='' WHERE component_code='CW-ARM'");
|
||||
@@ -123,7 +344,7 @@ class DemandFlowApiTest {
|
||||
Session session = create();
|
||||
JsonNode parsed = submit(session, "m1", TEXT, List.of());
|
||||
String analysisId = parsed.path("analysisId").asText();
|
||||
JsonNode result = confirm(session, analysisId, 1);
|
||||
JsonNode result = generatedMatch(session, analysisId, 1);
|
||||
assertThat(result.path("status").asText()).isEqualTo("partial");
|
||||
assertThat(result.path("components").findValuesAsText("componentCode")).containsExactly("CW-TORSO");
|
||||
assertThat(result.path("missingParts").findValuesAsText("category")).containsExactly("arm_r");
|
||||
@@ -133,9 +354,7 @@ class DemandFlowApiTest {
|
||||
.andExpect(jsonPath("$.data.id").doesNotExist());
|
||||
|
||||
jdbc.update("UPDATE component SET " + resourceColumn + "=? WHERE component_code='CW-ARM-ALT'", originalKey);
|
||||
JsonNode refreshed = data(mvc.perform(post("/api/robot-analyses/" + analysisId + "/rematch")
|
||||
.cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"revision\":1,\"confirmed\":true}")).andExpect(status().isOk()).andReturn());
|
||||
JsonNode refreshed = submit(session, "m2", TEXT, List.of()).path("match");
|
||||
assertThat(refreshed.path("status").asText()).isEqualTo("complete");
|
||||
assertThat(refreshed.path("components").findValuesAsText("componentCode")).containsExactly("CW-TORSO", "CW-ARM-ALT");
|
||||
assertThat(refreshed.path("alternatives").findValuesAsText("componentCode")).doesNotContain("CW-ARM");
|
||||
@@ -152,14 +371,14 @@ class DemandFlowApiTest {
|
||||
}).when(model).analyze(anyList());
|
||||
Session session = create();
|
||||
JsonNode parsed = submit(session, "m1", TEXT.replace("至少20N·m", "最好至少30N·m"), List.of());
|
||||
JsonNode matched = confirm(session, parsed.path("analysisId").asText(), 1);
|
||||
JsonNode matched = generatedMatch(session, parsed.path("analysisId").asText(), 1);
|
||||
assertThat(matched.path("components").get(1).path("component").path("componentCode").asText()).isEqualTo("CW-ARM");
|
||||
assertThat(matched.path("requirementChecks").get(2).path("status").asText()).isEqualTo("unmet");
|
||||
assertThat(matched.path("status").asText()).isEqualTo("complete");
|
||||
assertThat(matched.path("degradationAcceptanceRequired").asBoolean()).isFalse();
|
||||
assertThat(matched.path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
jdbc.update("UPDATE component SET mass_kg=1.2 WHERE component_code='CW-ARM-ALT'");
|
||||
JsonNode refreshed = data(mvc.perform(post("/api/robot-analyses/" + parsed.path("analysisId").asText() + "/rematch").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"confirmed\":true}")).andExpect(status().isOk()).andReturn());
|
||||
JsonNode refreshed = submit(session, "m2", TEXT.replace("至少20N·m", "最好至少30N·m"), List.of()).path("match");
|
||||
assertThat(refreshed.path("components").get(1).path("component").path("componentCode").asText()).isEqualTo("CW-ARM-ALT");
|
||||
}
|
||||
|
||||
@@ -185,7 +404,7 @@ class DemandFlowApiTest {
|
||||
}).when(model).analyze(anyList());
|
||||
Session session = create();
|
||||
JsonNode parsed = submit(session, "m1", TEXT.replace("20N·m", "30N·m") + ",躯干用铝合金,还需要头部", List.of());
|
||||
JsonNode result = confirm(session, parsed.path("analysisId").asText(), 1);
|
||||
JsonNode result = generatedMatch(session, parsed.path("analysisId").asText(), 1);
|
||||
assertThat(result.path("rootCategory").asText()).isEqualTo("torso_0");
|
||||
assertThat(result.path("components")).hasSize(2);
|
||||
assertThat(result.path("components").get(0).path("component").path("componentCode").asText()).isEqualTo("CW-TORSO");
|
||||
@@ -193,13 +412,13 @@ class DemandFlowApiTest {
|
||||
assertThat(result.path("components").get(1).path("component").path("torqueNm").asInt()).isEqualTo(20);
|
||||
assertThat(result.path("missingParts").get(0).path("category").asText()).isEqualTo("head_0");
|
||||
assertThat(result.path("status").asText()).isEqualTo("partial");
|
||||
assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isTrue();
|
||||
assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isFalse();
|
||||
assertThat(result.path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(result.path("assembly").path("issues")).isEmpty();
|
||||
assertThat(result.path("assembly").path("connections").get(0).path("parentInstanceId").asText()).endsWith(":torso_0");
|
||||
}
|
||||
|
||||
@Test void missingPartsAllowAssemblyBeforeDegradationAcceptanceIncludingAlternatives() throws Exception {
|
||||
@Test void missingPartsAllowImmediateAssemblyIncludingAlternatives() throws Exception {
|
||||
components(true, 20);
|
||||
doAnswer(invocation -> {
|
||||
ObjectNode raw = raw(invocation.getArgument(0));
|
||||
@@ -210,43 +429,31 @@ class DemandFlowApiTest {
|
||||
Session session = create();
|
||||
JsonNode parsed = submit(session, "m1", TEXT + ",还需要头部", List.of());
|
||||
String analysisId = parsed.path("analysisId").asText();
|
||||
JsonNode result = confirm(session, analysisId, 1);
|
||||
JsonNode result = generatedMatch(session, analysisId, 1);
|
||||
|
||||
assertThat(result.path("status").asText()).isEqualTo("partial");
|
||||
assertThat(result.path("components")).hasSize(2);
|
||||
assertThat(result.path("components").get(0).path("component").path("category").asText()).isEqualTo("torso_0");
|
||||
assertThat(result.path("missingParts").findValuesAsText("category")).containsExactly("head_0");
|
||||
assertThat(result.path("requirementChecks").findValuesAsText("status")).contains("unverified");
|
||||
assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isTrue();
|
||||
assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isFalse();
|
||||
assertThat(result.path("degradationAccepted").asBoolean()).isFalse();
|
||||
assertThat(result.path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(result.path("assembly").path("issues")).isEmpty();
|
||||
assertThat(result.path("assembly").path("connections")).hasSize(1);
|
||||
assertThat(result.path("assembly").path("connections").get(0).path("childRootRelativeToParentRoot")).hasSize(16);
|
||||
JsonNode alternative = result.path("alternatives").get(1).path("items").get(0);
|
||||
assertThat(alternative.path("degradationAcceptanceRequired").asBoolean()).isTrue();
|
||||
assertThat(alternative.path("degradationAcceptanceRequired").asBoolean()).isFalse();
|
||||
assertThat(alternative.path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(alternative.path("assembly").path("issues")).isEmpty();
|
||||
assertThat(alternative.path("assembly").path("connections")).hasSize(1);
|
||||
|
||||
JsonNode cached = data(mvc.perform(get("/api/robot-demand-matches/" + result.path("matchId").asText()).cookie(session.cookie()))
|
||||
.andExpect(status().isOk()).andReturn());
|
||||
JsonNode cached = generatedMatch(session, analysisId, 1);
|
||||
assertThat(cached.path("assembly")).isEqualTo(result.path("assembly"));
|
||||
assertThat(confirm(session, analysisId, 1).path("matchId").asText()).isEqualTo(result.path("matchId").asText());
|
||||
JsonNode accepted = data(mvc.perform(post("/api/robot-demand-matches/" + result.path("matchId").asText() + "/accept-degradation")
|
||||
.cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"accepted\":true}"))
|
||||
.andExpect(status().isOk()).andReturn());
|
||||
assertThat(accepted.path("status").asText()).isEqualTo("partial");
|
||||
assertThat(accepted.path("missingParts")).isEqualTo(result.path("missingParts"));
|
||||
assertThat(accepted.path("components")).isEqualTo(result.path("components"));
|
||||
assertThat(accepted.path("assembly")).isEqualTo(result.path("assembly"));
|
||||
assertThat(accepted.path("degradationAccepted").asBoolean()).isTrue();
|
||||
assertThat(accepted.path("degradationAcceptanceRequired").asBoolean()).isFalse();
|
||||
assertThat(cached.path("matchId").asText()).isEqualTo(result.path("matchId").asText());
|
||||
|
||||
jdbc.update("UPDATE component SET urdf_files='[]' WHERE category='arm_r'");
|
||||
JsonNode invalidResources = data(mvc.perform(post("/api/robot-analyses/" + analysisId + "/rematch")
|
||||
.cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"confirmed\":true}"))
|
||||
.andExpect(status().isOk()).andReturn());
|
||||
JsonNode invalidResources = submit(session, "m2", TEXT + ",还需要头部", List.of()).path("match");
|
||||
assertThat(invalidResources.path("status").asText()).isEqualTo("partial");
|
||||
assertThat(invalidResources.path("missingParts")).isEqualTo(result.path("missingParts"));
|
||||
assertThat(invalidResources.path("assembly").path("status").asText()).isEqualTo("blocked");
|
||||
@@ -258,11 +465,11 @@ class DemandFlowApiTest {
|
||||
save("CW-TORSO", "torso_0", 0, "2", 0, "BASE", true);
|
||||
Session session = create();
|
||||
JsonNode parsed = submit(session, "m1", TEXT, List.of());
|
||||
JsonNode result = confirm(session, parsed.path("analysisId").asText(), 1);
|
||||
JsonNode result = generatedMatch(session, parsed.path("analysisId").asText(), 1);
|
||||
assertThat(result.path("status").asText()).isEqualTo("partial");
|
||||
assertThat(result.path("missingParts").findValuesAsText("category")).containsExactly("arm_r");
|
||||
assertThat(result.path("components")).hasSize(1);
|
||||
assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isTrue();
|
||||
assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isFalse();
|
||||
assertThat(result.path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(result.path("assembly").path("rootInstanceId").asText()).endsWith(":torso_0");
|
||||
assertThat(result.path("assembly").path("connections")).isEmpty();
|
||||
@@ -271,18 +478,18 @@ class DemandFlowApiTest {
|
||||
|
||||
@Test void noInventoryAndIncompleteResourceManifestReturnDiagnosableResults() throws Exception {
|
||||
Session session = create(); JsonNode parsed = submit(session, "m1", TEXT, List.of());
|
||||
JsonNode empty = confirm(session, parsed.path("analysisId").asText(), 1);
|
||||
JsonNode empty = generatedMatch(session, parsed.path("analysisId").asText(), 1);
|
||||
assertThat(empty.path("status").asText()).isEqualTo("no_match");
|
||||
assertThat(empty.path("assembly").path("status").asText()).isEqualTo("blocked");
|
||||
components(true, 20);
|
||||
jdbc.update("UPDATE component SET urdf_files='[]'");
|
||||
JsonNode refreshed = data(mvc.perform(post("/api/robot-analyses/" + parsed.path("analysisId").asText() + "/rematch").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"confirmed\":true}")).andExpect(status().isOk()).andReturn());
|
||||
JsonNode refreshed = submit(session, "m2", TEXT, List.of()).path("match");
|
||||
assertThat(refreshed.path("components")).hasSize(2);
|
||||
assertThat(refreshed.path("assembly").path("status").asText()).isEqualTo("blocked");
|
||||
assertThat(refreshed.path("assembly").path("issues").findValuesAsText("code")).contains("INCOMPLETE_RESOURCE_MANIFEST");
|
||||
}
|
||||
|
||||
@Test void oneInstancePerRoleIsVerifiedAndMultipleInstancesAreClarified() throws Exception {
|
||||
@Test void unsupportedQuantitiesReturnPartialAssemblyWithoutQuestions() throws Exception {
|
||||
components(true, 20);
|
||||
doAnswer(invocation -> {
|
||||
List<DemandMessage> history = invocation.getArgument(0);
|
||||
@@ -293,12 +500,15 @@ class DemandFlowApiTest {
|
||||
Session session = create();
|
||||
JsonNode parsed = submit(session, "m1", TEXT + ",一个右臂", List.of());
|
||||
assertThat(parsed.path("status").asText()).isEqualTo("ready");
|
||||
JsonNode matched = confirm(session, parsed.path("analysisId").asText(), 1);
|
||||
JsonNode matched = generatedMatch(session, parsed.path("analysisId").asText(), 1);
|
||||
assertThat(matched.path("requirementChecks").get(3).path("status").asText()).isEqualTo("satisfied");
|
||||
assertThat(matched.path("requirementChecks").get(3).path("actual").asInt()).isEqualTo(1);
|
||||
JsonNode unsupported = submit(session, "m2", TEXT + ",两个右臂", List.of());
|
||||
assertThat(unsupported.path("status").asText()).isEqualTo("needs_clarification");
|
||||
assertThat(unsupported.path("canSubmit").asBoolean()).isFalse();
|
||||
assertThat(unsupported.path("status").asText()).isEqualTo("ready");
|
||||
assertThat(unsupported.path("questions")).isEmpty();
|
||||
assertThat(unsupported.path("match").path("status").asText()).isEqualTo("partial");
|
||||
assertThat(unsupported.path("match").path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(unsupported.path("match").path("requirementChecks").get(3).path("status").asText()).isEqualTo("unverified");
|
||||
}
|
||||
|
||||
@Test void expiredConversationsCleanOnlyOwnedDemandRowsAndPrivateFiles() throws Exception {
|
||||
@@ -314,39 +524,43 @@ class DemandFlowApiTest {
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_conversation WHERE conversation_code=?", Integer.class, active.id())).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test void invalidModelEvidenceFailsSseAndCannotBeConfirmed() throws Exception {
|
||||
@Test void invalidModelEvidenceFailsSseWithoutSavingRobot() throws Exception {
|
||||
doAnswer(invocation -> { ObjectNode raw = raw(invocation.getArgument(0)); ((ObjectNode) raw.path("observations").get(0)).put("content", "伪造用户证据"); return raw; }).when(model).analyze(anyList());
|
||||
Session session = create(); MvcResult result = message(session, "m1", TEXT, List.of());
|
||||
result.getAsyncResult(10000); mvc.perform(asyncDispatch(result)).andExpect(status().isOk());
|
||||
assertThat(result.getResponse().getContentAsString()).contains("event:analysis.failed", "DEMAND_INVALID_OUTPUT").doesNotContain("伪造用户证据");
|
||||
String analysis = jdbc.queryForObject("SELECT analysis_code FROM robot_demand_analysis WHERE conversation_code=?", String.class, session.id());
|
||||
mvc.perform(get("/api/robot-analyses/" + analysis).cookie(session.cookie())).andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("failed")).andExpect(jsonPath("$.data.result").isEmpty());
|
||||
mvc.perform(post("/api/robot-analyses/" + analysis + "/confirm").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"confirmed\":true}")).andExpect(status().isConflict());
|
||||
}
|
||||
|
||||
@Test void newMessageInvalidatesOldConfirmationAndMessageReplayDoesNotCreateRevision() throws Exception {
|
||||
@Test void newMessageInvalidatesOldRobotAndMessageReplayDoesNotCreateRevision() throws Exception {
|
||||
Session session = create();
|
||||
JsonNode first = submit(session, "m1", TEXT, List.of());
|
||||
JsonNode replay = submit(session, "m1", TEXT, List.of());
|
||||
assertThat(replay.path("analysisId").asText()).isEqualTo(first.path("analysisId").asText());
|
||||
assertThat(replay.path("match")).isEqualTo(first.path("match"));
|
||||
org.mockito.Mockito.verify(model, org.mockito.Mockito.times(1)).analyze(anyList());
|
||||
org.mockito.Mockito.verify(matches, org.mockito.Mockito.times(1)).match(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any());
|
||||
assertThat(jdbc.queryForObject("SELECT revision FROM robot_demand_conversation WHERE conversation_code=?", Integer.class, session.id())).isEqualTo(1);
|
||||
submit(session, "m2", TEXT, List.of());
|
||||
mvc.perform(post("/api/robot-analyses/" + first.path("analysisId").asText() + "/confirm").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"confirmed\":true}"))
|
||||
.andExpect(status().isConflict()).andExpect(jsonPath("$.code").value("DEMAND_REVISION_CONFLICT"));
|
||||
mvc.perform(get("/api/robot-analyses/" + first.path("analysisId").asText()).cookie(session.cookie()))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("superseded")).andExpect(jsonPath("$.data.canSubmit").value(false)).andExpect(jsonPath("$.data.result").isEmpty());
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("superseded")).andExpect(jsonPath("$.data.canSubmit").value(false))
|
||||
.andExpect(jsonPath("$.data.result").isEmpty()).andExpect(jsonPath("$.data.match").isEmpty());
|
||||
}
|
||||
|
||||
@Test void anonymousOwnersCannotReadConfirmOrAttachToAnotherConversation() throws Exception {
|
||||
@Test void anonymousOwnersCannotAccessOtherVisitorsTasksOrAttachments() throws Exception {
|
||||
Session first = create(); Session other = create();
|
||||
JsonNode analysis = submit(first, "m1", TEXT, List.of());
|
||||
mvc.perform(get("/api/robot-analyses/" + analysis.path("analysisId").asText()).cookie(other.cookie())).andExpect(status().isNotFound());
|
||||
mvc.perform(post("/api/robot-analyses/" + analysis.path("analysisId").asText() + "/confirm").cookie(other.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"confirmed\":true}"))
|
||||
mvc.perform(post("/api/robot-analyses/" + analysis.path("analysisId").asText() + "/retry").cookie(other.cookie()))
|
||||
.andExpect(status().isNotFound());
|
||||
mvc.perform(delete("/api/robot-analyses/" + analysis.path("analysisId").asText()).cookie(other.cookie()))
|
||||
.andExpect(status().isNotFound());
|
||||
mvc.perform(multipart("/api/robot-conversations/" + first.id() + "/attachments").file(image()).cookie(other.cookie())).andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test void imageOnlyMessagesUseOwnedPrivateAttachmentsAndPreserveOcrSources() throws Exception {
|
||||
components(true, 20);
|
||||
Session session = create();
|
||||
MvcResult uploaded = mvc.perform(multipart("/api/robot-conversations/" + session.id() + "/attachments").file(image()).cookie(session.cookie())).andExpect(status().isOk()).andReturn();
|
||||
JsonNode file = data(uploaded);
|
||||
@@ -362,13 +576,15 @@ class DemandFlowApiTest {
|
||||
}).when(model).analyze(anyList());
|
||||
JsonNode completed = submit(session, "m1", "", List.of(id));
|
||||
assertThat(completed.path("status").asText()).isEqualTo("ready");
|
||||
assertThat(completed.path("match").path("components")).hasSize(2);
|
||||
assertThat(completed.path("match").path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(completed.path("result").path("request").path("userInput").asText()).isEqualTo("[图片:" + id + "]");
|
||||
assertThat(completed.path("result").path("analysis").path("observations").get(0).path("kind").asText()).isEqualTo("image_text");
|
||||
mvc.perform(get(file.path("previewUrl").asText()).cookie(session.cookie())).andExpect(status().isOk());
|
||||
mvc.perform(get(file.path("previewUrl").asText()).cookie(create().cookie())).andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test void clarifiesUnitsUsingRealHistoryAndRejectsPrematureConfirmation() throws Exception {
|
||||
@Test void missingUnitsGeneratePartialAssemblyAndLaterUserEditsApplyWithoutQuestions() throws Exception {
|
||||
components(true, 30);
|
||||
Session session = create();
|
||||
doAnswer(invocation -> {
|
||||
@@ -379,7 +595,7 @@ class DemandFlowApiTest {
|
||||
ObjectNode row = constraint(raw, "part", "torqueNm", history.size() > 1 ? "30N·m" : "30", "gte", "arm_r");
|
||||
intent(raw, "performance", "右臂", "右臂扭矩至少30");
|
||||
if (history.size() > 1) {
|
||||
assertThat(history.stream().anyMatch((DemandMessage message) -> "assistant".equals(message.role()))).isTrue();
|
||||
assertThat(history.stream().anyMatch((DemandMessage message) -> "assistant".equals(message.role()))).isFalse();
|
||||
DemandMessage answer = history.get(history.size() - 1);
|
||||
raw.withArray("observations").addObject().put("id", "e2").put("messageId", answer.id()).put("imageId", "").put("kind", "user_text").put("content", answer.text()).put("clarity", "clear").putArray("region");
|
||||
row.withArray("evidenceIds").add("e2");
|
||||
@@ -388,17 +604,19 @@ class DemandFlowApiTest {
|
||||
return raw;
|
||||
}).when(model).analyze(anyList());
|
||||
JsonNode first = submit(session, "m1", "右臂扭矩至少30,单位未确定", List.of());
|
||||
assertThat(first.path("status").asText()).isEqualTo("needs_clarification");
|
||||
assertThat(first.path("questions")).isNotEmpty();
|
||||
mvc.perform(post("/api/robot-analyses/" + first.path("analysisId").asText() + "/confirm").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"confirmed\":true}"))
|
||||
.andExpect(status().isConflict());
|
||||
assertThat(first.path("status").asText()).isEqualTo("ready");
|
||||
assertThat(first.path("questions")).isEmpty();
|
||||
assertThat(first.path("result").path("request").path("partRequirements")).isEmpty();
|
||||
assertThat(first.path("match").path("status").asText()).isEqualTo("partial");
|
||||
assertThat(first.path("match").path("assembly").path("status").asText()).isEqualTo("ready");
|
||||
assertThat(first.path("match").path("requirementChecks").get(0).path("status").asText()).isEqualTo("unverified");
|
||||
JsonNode second = submit(session, "m2", "单位是N·m", List.of());
|
||||
assertThat(second.path("status").asText()).isEqualTo("ready");
|
||||
assertThat(second.path("revision").asInt()).isEqualTo(2);
|
||||
assertThat(second.path("result").path("request").path("partRequirements").get(0).path("torqueNm").asInt()).isEqualTo(30);
|
||||
assertThat(second.path("result").path("request").path("requiredParts")).hasSize(2);
|
||||
assertThat(second.path("result").path("request").path("requiredParts").get(0).asText()).isEqualTo("torso_0");
|
||||
JsonNode matched = confirm(session, second.path("analysisId").asText(), 2);
|
||||
JsonNode matched = second.path("match");
|
||||
assertThat(matched.path("requirementChecks").get(0).path("status").asText()).isEqualTo("satisfied");
|
||||
}
|
||||
|
||||
@@ -421,7 +639,7 @@ class DemandFlowApiTest {
|
||||
assertThat(result.path("status").asText()).isEqualTo("ready");
|
||||
}
|
||||
|
||||
@Test void degradationAcceptanceDoesNotPretendUnsupportedCapabilitiesOrMissingMountsAreSatisfied() throws Exception {
|
||||
@Test void unsupportedCapabilitiesAndMissingMountsRemainVisibleInGeneratedResult() throws Exception {
|
||||
components(false, 15);
|
||||
doAnswer(invocation -> {
|
||||
ObjectNode raw = raw(invocation.getArgument(0));
|
||||
@@ -431,31 +649,30 @@ class DemandFlowApiTest {
|
||||
}).when(model).analyze(anyList());
|
||||
Session session = create();
|
||||
JsonNode analysis = submit(session, "m1", TEXT + ",预算不超过2万元", List.of());
|
||||
JsonNode result = confirm(session, analysis.path("analysisId").asText(), 1);
|
||||
JsonNode result = generatedMatch(session, analysis.path("analysisId").asText(), 1);
|
||||
assertThat(result.path("status").asText()).isEqualTo("partial");
|
||||
assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isTrue();
|
||||
assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isFalse();
|
||||
assertThat(result.path("requirementChecks").get(3).path("status").asText()).isEqualTo("unverified");
|
||||
String id = result.path("matchId").asText();
|
||||
JsonNode accepted = data(mvc.perform(post("/api/robot-demand-matches/" + id + "/accept-degradation").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"accepted\":true}")).andExpect(status().isOk()).andReturn());
|
||||
assertThat(accepted.path("degradationAccepted").asBoolean()).isTrue();
|
||||
assertThat(accepted.path("status").asText()).isEqualTo("partial");
|
||||
assertThat(accepted.path("assembly").path("status").asText()).isEqualTo("blocked");
|
||||
assertThat(accepted.path("assembly").path("issues").toString()).contains("MISSING_MOUNTING_REFERENCE").doesNotContain("DEGRADATION_NOT_ACCEPTED");
|
||||
assertThat(accepted.path("snapshot").isMissingNode()).isTrue();
|
||||
assertThat(result.path("assembly").path("status").asText()).isEqualTo("blocked");
|
||||
assertThat(result.path("assembly").path("issues").toString()).contains("MISSING_MOUNTING_REFERENCE").doesNotContain("DEGRADATION_NOT_ACCEPTED");
|
||||
assertThat(result.path("snapshot").isMissingNode()).isTrue();
|
||||
}
|
||||
|
||||
@Test void changedComponentsRequireRematchAndDoNotReinvokeTheModel() throws Exception {
|
||||
components(true, 20); Session session = create();
|
||||
@Test void componentChangesAreAppliedByNewMessagesWhileOldResultsStayCached() throws Exception {
|
||||
components(true, 20);
|
||||
Session session = create();
|
||||
JsonNode analysis = submit(session, "m1", TEXT, List.of());
|
||||
String id = analysis.path("analysisId").asText();
|
||||
JsonNode original = confirm(session, id, 1);
|
||||
JsonNode original = analysis.path("match");
|
||||
jdbc.update("UPDATE component SET version=2 WHERE component_code='CW-ARM'");
|
||||
mvc.perform(post("/api/robot-demand-matches/" + original.path("matchId").asText() + "/accept-degradation").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"accepted\":true}"))
|
||||
.andExpect(status().isConflict()).andExpect(jsonPath("$.code").value("COMPONENT_REVISION_CONFLICT"));
|
||||
JsonNode refreshed = data(mvc.perform(post("/api/robot-analyses/" + id + "/rematch").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":1,\"confirmed\":true}"))
|
||||
.andExpect(status().isOk()).andReturn());
|
||||
assertThat(generatedMatch(session, id, 1)).isEqualTo(original);
|
||||
JsonNode regenerated = submit(session, "m2", TEXT, List.of());
|
||||
JsonNode refreshed = regenerated.path("match");
|
||||
assertThat(refreshed.path("matchId").asText()).isNotEqualTo(original.path("matchId").asText());
|
||||
org.mockito.Mockito.verify(model, org.mockito.Mockito.times(1)).analyze(anyList());
|
||||
assertThat(refreshed.path("components").get(1).path("component").path("version").asInt()).isEqualTo(2);
|
||||
mvc.perform(get("/api/robot-analyses/" + id).cookie(session.cookie())).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.status").value("superseded")).andExpect(jsonPath("$.data.match").isEmpty());
|
||||
org.mockito.Mockito.verify(model, org.mockito.Mockito.times(2)).analyze(anyList());
|
||||
}
|
||||
|
||||
@Test void invalidPayloadsImagesAndPublicRuleDownloadsAreRejected() throws Exception {
|
||||
@@ -491,9 +708,11 @@ class DemandFlowApiTest {
|
||||
}
|
||||
throw new AssertionError("No completed event: " + events);
|
||||
}
|
||||
private JsonNode confirm(Session session, String id, int revision) throws Exception {
|
||||
return data(mvc.perform(post("/api/robot-analyses/" + id + "/confirm").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsBytes(Map.of("revision", revision, "confirmed", true)))).andExpect(status().isOk()).andReturn());
|
||||
private JsonNode generatedMatch(Session session, String id, int revision) throws Exception {
|
||||
JsonNode generated = data(mvc.perform(get("/api/robot-analyses/" + id).cookie(session.cookie()))
|
||||
.andExpect(status().isOk()).andReturn());
|
||||
assertThat(generated.path("revision").asInt()).isEqualTo(revision);
|
||||
return generated.path("match");
|
||||
}
|
||||
private JsonNode data(MvcResult result) throws Exception { return json.readTree(result.getResponse().getContentAsByteArray()).path("data"); }
|
||||
private ObjectNode raw(List<DemandMessage> history) {
|
||||
|
||||
@@ -67,6 +67,7 @@ class MatchingApiTest {
|
||||
component_name VARCHAR(128) NOT NULL DEFAULT '', category VARCHAR(64) NOT NULL DEFAULT '',
|
||||
description CLOB NOT NULL DEFAULT '', material VARCHAR(128) NOT NULL DEFAULT '',
|
||||
mass_kg DECIMAL(18,6) NOT NULL DEFAULT 0, degrees_of_freedom INT NOT NULL DEFAULT 0,
|
||||
rotation_axis CHAR(1) DEFAULT NULL CHECK (rotation_axis IN ('X','Y','Z')),
|
||||
function_description VARCHAR(512) NOT NULL DEFAULT '', shape VARCHAR(128) NOT NULL DEFAULT '',
|
||||
size VARCHAR(128) NOT NULL DEFAULT '', torque_nm DECIMAL(18,6) NOT NULL DEFAULT 0,
|
||||
bom_list CLOB NOT NULL, urdf_info CLOB NOT NULL,
|
||||
@@ -93,6 +94,22 @@ class MatchingApiTest {
|
||||
assertThat(empty.path("missingParts").get(0).path("reason").asText()).isEqualTo("NO_COMPONENT");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"X", "Y", "Z"})
|
||||
void rotationAxisIsReturnedInPublicDetailsSelectedPartsAndAlternatives(String axis) throws Exception {
|
||||
save("CW-A", "torso_0", 0, "1", "0", "", metadata("BASE"), json.readTree("[]"));
|
||||
save("CW-B", "torso_0", 0, "1", "0", "", metadata("BASE"), json.readTree("[]"));
|
||||
String alternativeAxis = "X".equals(axis) ? "Y" : "X";
|
||||
jdbc.update("UPDATE component SET rotation_axis=? WHERE component_code='CW-A'", axis);
|
||||
jdbc.update("UPDATE component SET rotation_axis=? WHERE component_code='CW-B'", alternativeAxis);
|
||||
mvc.perform(get("/api/components/CW-A")).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.rotationAxis").value(axis)).andExpect(jsonPath("$.data.id").doesNotExist());
|
||||
JsonNode result = match(request("torso_0"));
|
||||
assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-A");
|
||||
assertThat(part(result, "torso_0").path("rotationAxis").asText()).isEqualTo(axis);
|
||||
assertThat(alternatives(result, "torso_0").get(0).path("component").path("rotationAxis").asText()).isEqualTo(alternativeAxis);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapsEveryRoleAndDeduplicatesAliasesWithoutSwappingFeetOrSides() throws Exception {
|
||||
List<String> english = List.of("head_0", "waist_0", "arm_l", "arm_r", "hand_l", "hand_r",
|
||||
@@ -143,12 +160,17 @@ class MatchingApiTest {
|
||||
mvc.perform(get("/api/components/" + id)).andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicDetailAlsoPreservesJsonArraysThatAreNotAssemblyMetadata() throws Exception {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"CW-7K3M9Q2R6V8X4T5N", "CW-0123456789ABCDEF0123456789ABCDEF"})
|
||||
void publicDetailPreservesJsonArraysForShortAndLegacyCodes(String componentCode) throws Exception {
|
||||
JsonNode info = json.readTree("[{\"robotName\":\"legacy\"}]");
|
||||
save("CW-LEGACY", "torso_0", 0, "1", "0", "", info, json.readTree("{}"));
|
||||
MvcResult detail = mvc.perform(get("/api/components/CW-LEGACY")).andExpect(status().isOk()).andReturn();
|
||||
assertThat(json.readTree(detail.getResponse().getContentAsString()).path("data").get("urdfInfo")).isEqualTo(info);
|
||||
save(componentCode, "torso_0", 0, "1", "0", "", info, json.readTree("{}"));
|
||||
MvcResult detail = mvc.perform(get("/api/components/{componentCode}", componentCode))
|
||||
.andExpect(status().isOk()).andReturn();
|
||||
JsonNode component = json.readTree(detail.getResponse().getContentAsString()).path("data");
|
||||
assertThat(component.path("componentCode").asText()).isEqualTo(componentCode);
|
||||
assertThat(component.get("urdfInfo")).isEqualTo(info);
|
||||
assertPublic(component);
|
||||
JsonNode result = match(request("torso_0"));
|
||||
assertThat(result.path("status").asText()).isEqualTo("NO_MATCH");
|
||||
assertThat(result.path("missingParts").get(0).path("reason").asText()).isEqualTo("INVALID_ASSEMBLY_METADATA");
|
||||
|
||||
Reference in New Issue
Block a user