AI拼装接口更新

This commit is contained in:
lxp
2026-10-13 16:53:04 +08:00
parent 693f25acc5
commit 06d2d87ec0
52 changed files with 7734 additions and 56 deletions
@@ -1,6 +1,7 @@
package com.linkerbot.cadworld.api;
import com.linkerbot.cadworld.config.MatchingProperties;
import com.linkerbot.cadworld.config.DemandProperties;
import com.linkerbot.cadworld.config.MybatisPlusConfig;
import com.linkerbot.cadworld.config.StorageProperties;
import com.linkerbot.cadworld.mapper.ComponentMapper;
@@ -15,7 +16,7 @@ import org.springframework.context.annotation.Import;
"com.linkerbot.cadworld.api", "com.linkerbot.cadworld.common",
"com.linkerbot.cadworld.service.matching"
})
@EnableConfigurationProperties({StorageProperties.class, MatchingProperties.class})
@EnableConfigurationProperties({StorageProperties.class, MatchingProperties.class, DemandProperties.class})
@Import({MybatisPlusConfig.class, ObjectStorageUrlResolver.class})
@MapperScan(basePackageClasses = ComponentMapper.class)
public class ApiApplication {
@@ -0,0 +1,62 @@
package com.linkerbot.cadworld.api.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.cadworld.config.DemandProperties;
import com.linkerbot.cadworld.mapper.ComponentMapper;
import com.linkerbot.cadworld.service.demand.ArkDemandModelClient;
import com.linkerbot.cadworld.service.demand.DemandAnalysisService;
import com.linkerbot.cadworld.service.demand.DemandAssemblyValidator;
import com.linkerbot.cadworld.service.demand.DemandAttachmentStore;
import com.linkerbot.cadworld.service.demand.DemandMatchService;
import com.linkerbot.cadworld.service.demand.DemandModelClient;
import com.linkerbot.cadworld.service.demand.DemandNormalizer;
import com.linkerbot.cadworld.service.demand.DemandRepository;
import com.linkerbot.cadworld.service.demand.DemandRequirementChecker;
import com.linkerbot.cadworld.service.demand.DemandRetentionService;
import com.linkerbot.cadworld.service.demand.DemandRules;
import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver;
import com.linkerbot.cadworld.service.matching.MatchTextService;
import com.linkerbot.cadworld.service.matching.RobotMatchingService;
import java.io.IOException;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** 仅用户端启动时注册需求解析服务,管理端不会绑定模型或初始化会话业务。 */
@Configuration(proxyBeanMethods = false)
public class DemandConfiguration {
@Bean DemandRules demandRules(ObjectMapper json) throws IOException { return new DemandRules(json); }
@Bean DemandNormalizer demandNormalizer(DemandRules rules, ObjectMapper json) { return new DemandNormalizer(rules, json); }
@Bean DemandModelClient demandModelClient(ObjectMapper json, DemandRules rules, DemandProperties properties) { return new ArkDemandModelClient(json, rules, properties); }
@Bean DemandRepository demandRepository(JdbcTemplate jdbc, ObjectMapper json, DemandProperties properties, PlatformTransactionManager manager) {
return new DemandRepository(jdbc, json, properties, manager);
}
@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 DemandAssemblyValidator demandAssemblyValidator(DemandProperties properties) { return new DemandAssemblyValidator(properties); }
@Bean DemandRequirementChecker demandRequirementChecker(ObjectMapper json, MatchTextService text) { return new DemandRequirementChecker(json, text); }
@Bean DemandMatchService demandMatchService(ObjectMapper json, RobotMatchingService matching, ComponentMapper mapper,
ObjectStorageUrlResolver urls, DemandAssemblyValidator assembly, DemandRequirementChecker requirements) {
return new DemandMatchService(json, matching, mapper, urls, assembly, requirements);
}
@Bean WebMvcConfigurer demandCors(DemandProperties properties) {
return new WebMvcConfigurer() {
@Override public void addCorsMappings(CorsRegistry registry) {
List<String> origins = properties.allowedOrigins();
if (origins == null || origins.isEmpty()) return;
String[] allowed = origins.stream().filter((String origin) -> !origin.isBlank()).toArray(String[]::new);
if (allowed.length == 0) return;
for (String origin : allowed) if (origin.contains("*")) throw new IllegalArgumentException("需求接口凭证跨域必须配置具体前端域名");
registry.addMapping("/api/**").allowedOrigins(allowed).allowedMethods("GET", "POST", "DELETE", "OPTIONS")
.allowedHeaders("Content-Type", "X-Request-Id").exposedHeaders("X-Request-Id").allowCredentials(true).maxAge(3600);
}
};
}
}
@@ -0,0 +1,37 @@
package com.linkerbot.cadworld.api.controller;
import com.linkerbot.cadworld.config.DemandProperties;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Component;
/** 当前无账号登录,以高熵 HttpOnly 匿名会话 Cookie 隔离各访客的需求和图片。 */
@Component
@RequiredArgsConstructor
public class DemandOwner {
private static final SecureRandom RANDOM = new SecureRandom();
private final DemandProperties properties;
public String resolve(HttpServletRequest request, HttpServletResponse response) {
String token = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) for (Cookie cookie : cookies) if ("cadworld_demand_visitor".equals(cookie.getName()) && cookie.getValue().matches("[A-Za-z0-9_-]{43}")) token = cookie.getValue();
if (token == null) {
byte[] bytes = new byte[32]; RANDOM.nextBytes(bytes);
token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
response.addHeader(HttpHeaders.SET_COOKIE, ResponseCookie.from("cadworld_demand_visitor", token).httpOnly(true)
.secure(properties.secureCookie() || request.isSecure()).sameSite("Lax").path("/api").maxAge(properties.retention()).build().toString());
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.US_ASCII))); }
catch (Exception exception) { throw new IllegalStateException("SHA-256 unavailable"); }
}
}
@@ -0,0 +1,129 @@
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;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
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
@RequiredArgsConstructor
@Slf4j
public class RobotDemandController {
private final DemandOwner owners;
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) {
DemandRepository.Conversation conversation = repository.create(owners.resolve(request, response));
log.info("需求会话创建 requestId={} conversationId={}", RequestIdHolder.get(), conversation.conversationId());
return ApiResponse.success(conversation);
}
@PostMapping(value = "/robot-conversations/{conversationId}/attachments", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ApiResponse<AttachmentView> upload(@PathVariable @NotBlank String conversationId, @RequestPart("file") MultipartFile file,
HttpServletRequest request, HttpServletResponse response) throws IOException {
if (file.getSize() > 8 * 1024 * 1024) throw new BizException(422, "INVALID_REQUEST", "每张图片不能超过8MiB");
DemandRepository.Attachment saved = attachments.upload(conversationId, owners.resolve(request, response), file.getBytes(), file.getContentType());
log.info("需求图片保存 requestId={} conversationId={} attachmentId={} sizeBytes={}", RequestIdHolder.get(), conversationId, saved.attachmentId(), saved.sizeBytes());
return ApiResponse.success(new AttachmentView(saved.attachmentId(), saved.mimeType(), saved.sizeBytes(), "/api/robot-conversations/" + conversationId + "/attachments/" + saved.attachmentId()));
}
@GetMapping("/robot-conversations/{conversationId}/attachments/{attachmentId}")
public ResponseEntity<byte[]> image(@PathVariable @NotBlank String conversationId, @PathVariable @NotBlank String attachmentId,
HttpServletRequest request, HttpServletResponse response) {
DemandRepository.Attachment file = repository.attachment(conversationId, owners.resolve(request, response), attachmentId);
return ResponseEntity.ok().cacheControl(CacheControl.noStore()).contentType(MediaType.parseMediaType(file.mimeType()))
.header("X-Content-Type-Options", "nosniff").body(attachments.read(file));
}
@PostMapping(value = "/robot-conversations/{conversationId}/messages", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter message(@PathVariable @NotBlank String conversationId, @Valid @RequestBody DemandMessageRequest input,
HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Cache-Control", "no-cache"); response.setHeader("X-Accel-Buffering", "no");
return analyses.submit(conversationId, owners.resolve(request, response), input);
}
@GetMapping("/robot-analyses/{analysisId}")
public ApiResponse<DemandAnalysisService.AnalysisView> analysis(@PathVariable @NotBlank String analysisId, HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Cache-Control", "no-store");
return ApiResponse.success(analyses.get(analysisId, owners.resolve(request, response)));
}
@PostMapping(value = "/robot-analyses/{analysisId}/retry", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter retry(@PathVariable @NotBlank String analysisId, HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Cache-Control", "no-cache"); response.setHeader("X-Accel-Buffering", "no");
return analyses.retry(analysisId, owners.resolve(request, response));
}
@DeleteMapping("/robot-analyses/{analysisId}")
public ApiResponse<DemandAnalysisService.AnalysisView> cancel(@PathVariable @NotBlank String analysisId, HttpServletRequest request, HttpServletResponse response) {
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) { }
}
@@ -11,6 +11,8 @@ spring:
connection-timeout: 5000
app:
demand:
secure-cookie: true
storage:
root-prefix: ${OSS_ROOT_PREFIX:cadworld}
# 生产环境必须配置公开 OSS/CDN 域名,供前端直接加载模型。
@@ -9,6 +9,10 @@ spring:
jackson:
deserialization:
fail-on-unknown-properties: true
servlet:
multipart:
max-file-size: 8MB
max-request-size: 9MB
server:
port: ${SERVER_PORT:8991}
logging:
@@ -21,6 +25,17 @@ mybatis-plus:
configuration:
map-underscore-to-camel-case: true
app:
demand:
api-key: ${ARK_API_KEY:}
model: ${ARK_MODEL:doubao-seed-2-1-lite-260915}
endpoint: ${ARK_ENDPOINT:https://ark.cn-beijing.volces.com/api/v3/responses}
timeout: ${APP_DEMAND_TIMEOUT:PT3M}
attachment-directory: ${APP_DEMAND_ATTACHMENT_DIRECTORY:/data/cadworld/demand-attachments}
retention: ${APP_DEMAND_RETENTION:P7D}
concurrent-analyses: ${APP_DEMAND_CONCURRENT_ANALYSES:4}
allowed-origins: ${APP_DEMAND_ALLOWED_ORIGINS:}
# 仅在机械明确所有子组件根节点就是安装基准时启用;否则使用 urdfInfo.assembly。
root-is-mounting-frame: ${APP_DEMAND_ROOT_IS_MOUNTING_FRAME:false}
storage:
# 配置公开 OSS/CDN 域名,不能填管理端下载代理地址;对象键已包含环境根目录。
public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:}
@@ -0,0 +1,442 @@
package com.linkerbot.cadworld.api;
import com.fasterxml.jackson.databind.JsonNode;
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 jakarta.servlet.http.Cookie;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doAnswer;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(classes = ApiApplication.class, properties = {
"spring.datasource.url=jdbc:h2:mem:demandflow;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
"app.storage.public-base-url=https://models.example.test", "logging.file.path=target/test-logs",
"logging.level.com.linkerbot.cadworld=INFO", "app.demand.allowed-origins=http://localhost:5173"
})
@AutoConfigureMockMvc
class DemandFlowApiTest {
private static final String TEXT = "我要机器人躯干和右臂,整体4自由度,质量不超过4kg,右臂扭矩至少20N·m";
private static final Path DIRECTORY = directory();
@Autowired private MockMvc mvc;
@Autowired private ObjectMapper json;
@Autowired private JdbcTemplate jdbc;
@Autowired private com.linkerbot.cadworld.service.demand.DemandRepository repository;
@Autowired private com.linkerbot.cadworld.service.demand.DemandAttachmentStore attachments;
@MockitoBean private DemandModelClient model;
@DynamicPropertySource static void configuration(DynamicPropertyRegistry registry) { registry.add("app.demand.attachment-directory", () -> DIRECTORY.toString()); }
@BeforeEach void prepare() throws Exception {
assertThat(jdbc.execute((org.springframework.jdbc.core.ConnectionCallback<String>) connection -> connection.getMetaData().getDatabaseProductName())).isEqualTo("H2");
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_conversation (id BIGINT AUTO_INCREMENT PRIMARY KEY,conversation_code VARCHAR(64) NOT NULL UNIQUE,owner_hash VARCHAR(64) NOT NULL,revision INT NOT NULL,created_at TIMESTAMP NOT NULL,updated_at TIMESTAMP NOT NULL,expires_at TIMESTAMP NOT NULL)");
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_attachment (id BIGINT AUTO_INCREMENT PRIMARY KEY,attachment_code VARCHAR(64) NOT NULL UNIQUE,conversation_code VARCHAR(64) NOT NULL,message_code VARCHAR(80) NOT NULL,mime_type VARCHAR(32) NOT NULL,size_bytes BIGINT NOT NULL,sha256 VARCHAR(64) NOT NULL,created_at TIMESTAMP NOT NULL)");
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_message (id BIGINT AUTO_INCREMENT PRIMARY KEY,message_code VARCHAR(80) NOT NULL,conversation_code VARCHAR(64) NOT NULL,message_role VARCHAR(16) NOT NULL,message_text CLOB NOT NULL,attachment_codes CLOB NOT NULL,created_at TIMESTAMP NOT NULL,UNIQUE(conversation_code,message_code))");
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_analysis (id BIGINT AUTO_INCREMENT PRIMARY KEY,analysis_code VARCHAR(64) NOT NULL UNIQUE,conversation_code VARCHAR(64) NOT NULL,source_message_code VARCHAR(80) NOT NULL,revision INT NOT NULL,status VARCHAR(32) NOT NULL,result_json CLOB NOT NULL,model_version VARCHAR(128) NOT NULL,failure_code VARCHAR(64) NOT NULL,created_at TIMESTAMP NOT NULL,updated_at TIMESTAMP NOT NULL,UNIQUE(conversation_code,revision))");
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_match (id BIGINT AUTO_INCREMENT PRIMARY KEY,match_code VARCHAR(64) NOT NULL UNIQUE,analysis_code VARCHAR(64) NOT NULL UNIQUE,revision INT NOT NULL,result_json CLOB NOT NULL,degradation_accepted INT NOT NULL,created_at TIMESTAMP NOT NULL,updated_at TIMESTAMP NOT NULL)");
jdbc.execute("""
CREATE TABLE IF NOT EXISTS component (
id BIGINT AUTO_INCREMENT PRIMARY KEY,component_code VARCHAR(64) NOT NULL UNIQUE,
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,
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 '[]',
step_object_key VARCHAR(512) NOT NULL DEFAULT '',urdf_prefix VARCHAR(512) NOT NULL DEFAULT '',
urdf_main_object_key VARCHAR(512) NOT NULL DEFAULT '',urdf_files CLOB NOT NULL DEFAULT '[]',
version BIGINT NOT NULL DEFAULT 1,deleted INT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)
""");
for (String table : List.of("robot_demand_match", "robot_demand_analysis", "robot_demand_message", "robot_demand_attachment", "robot_demand_conversation", "component")) jdbc.update("DELETE FROM " + table);
when(model.analyze(anyList())).thenAnswer(invocation -> raw(invocation.getArgument(0)));
}
@Test void confirmsSavedRequirementsIdempotentlyAndReturnsOriginalJsonAndResources() throws Exception {
components(true, 20);
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(match.path("status").asText()).isEqualTo("complete");
assertThat(match.path("assembly").path("status").asText()).isEqualTo("ready");
assertThat(match.path("requirementChecks")).hasSize(3);
for (JsonNode check : match.path("requirementChecks")) assertThat(check.path("status").asText()).isEqualTo("satisfied");
assertThat(match.path("components").get(0).path("component").path("bomList").path("nested").path("parts").get(0).asText()).isEqualTo("BOLT");
assertThat(match.path("components").get(0).path("resources")).hasSize(2);
assertThat(match.path("assembly").path("connections").get(0).path("childRootRelativeToParentRoot").get(12).asDouble()).isEqualTo(1);
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").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());
}
@Test void prefersRequirementsOnlyAfterHardRequirementsAndDoesNotRequireDegradationForPreferences() throws Exception {
components(true, 20);
jdbc.update("UPDATE component SET mass_kg=8,torque_nm=40 WHERE component_code='CW-ARM-ALT'");
doAnswer(invocation -> {
ObjectNode raw = raw(invocation.getArgument(0));
((ObjectNode) raw.path("intentItems").get(2)).put("priority", "prefer").put("requirement", "右臂扭矩最好至少30N·m");
((ObjectNode) raw.path("constraints").get(2)).put("value", "30N·m");
return raw;
}).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);
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());
assertThat(refreshed.path("components").get(1).path("component").path("componentCode").asText()).isEqualTo("CW-ARM-ALT");
}
@Test void conversationMatchingFixesBestTorsoBeforeSearchingFallbackParts() throws Exception {
components(true, 20);
jdbc.update("UPDATE component SET material='铝合金',category='躯干_0' WHERE component_code='CW-TORSO'");
save("CW-TORSO-ALT", "torso_0", 0, "2", 0, "BASE", true);
jdbc.update("UPDATE component SET material='钢' WHERE component_code='CW-TORSO-ALT'");
save("CW-HEAD", "head_0", 0, "0.5", 0, "HEAD_ROOT", true);
ObjectNode info = (ObjectNode) json.readTree(jdbc.queryForObject("SELECT urdf_info FROM component WHERE component_code='CW-TORSO-ALT'", String.class));
ObjectNode headFrame = info.withArray("frames").addObject().put("name", "J_HEAD").put("kind", "joint").put("type", "fixed").put("parent", "BASE")
.put("child", "LINK_head").put("interfaceType", "head_0").put("originExplicit", true);
headFrame.putArray("xyz").add(0).add(1).add(0); headFrame.putArray("rpy").add(0).add(0).add(0);
jdbc.update("UPDATE component SET urdf_info=? WHERE component_code='CW-TORSO-ALT'", info.toString());
doAnswer(invocation -> {
ObjectNode raw = raw(invocation.getArgument(0));
((ObjectNode) raw.path("constraints").get(2)).put("value", "30N·m");
((ObjectNode) raw.path("intentItems").get(2)).put("requirement", "右臂扭矩至少30N·m");
constraint(raw, "part", "material", "铝合金", "eq", "torso_0");
intent(raw, "material", "躯干", "躯干用铝合金");
raw.withArray("partCategories").addObject().put("category", "head_0").put("source", "explicit").put("reason", "所需头部").putArray("evidenceIds").add("e1");
return raw;
}).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);
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");
assertThat(result.path("components").get(0).path("component").path("category").asText()).isEqualTo("torso_0");
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("assembly").path("connections").get(0).path("parentInstanceId").asText()).endsWith(":torso_0");
}
@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);
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());
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 {
components(true, 20);
doAnswer(invocation -> {
List<DemandMessage> history = invocation.getArgument(0);
ObjectNode raw = raw(history);
intent(raw, "quantity", "右臂", history.get(history.size() - 1).text().contains("两个右臂") ? "两个右臂" : "一个右臂");
return raw;
}).when(model).analyze(anyList());
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);
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();
}
@Test void expiredConversationsCleanOnlyOwnedDemandRowsAndPrivateFiles() throws Exception {
Session expired = create(); Session active = create();
JsonNode file = data(mvc.perform(multipart("/api/robot-conversations/" + expired.id() + "/attachments").file(image()).cookie(expired.cookie())).andExpect(status().isOk()).andReturn());
Path saved = DIRECTORY.resolve(file.path("attachmentId").asText() + ".bin");
assertThat(saved).exists();
submit(expired, "m1", TEXT, List.of());
jdbc.update("UPDATE robot_demand_conversation SET expires_at=? WHERE conversation_code=?", java.sql.Timestamp.from(java.time.Instant.now().minusSeconds(1)), expired.id());
assertThat(repository.purgeExpired(attachments::remove)).isEqualTo(1);
assertThat(saved).doesNotExist();
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_analysis", Integer.class)).isZero();
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_conversation WHERE conversation_code=?", Integer.class, active.id())).isEqualTo(1);
}
@Test void invalidModelEvidenceFailsSseAndCannotBeConfirmed() 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 {
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(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());
}
@Test void anonymousOwnersCannotReadConfirmOrAttachToAnotherConversation() 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}"))
.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 {
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);
String id = file.path("attachmentId").asText();
doAnswer(invocation -> {
List<DemandMessage> history = invocation.getArgument(0);
assertThat(history.get(0).images().get(0).dataUrl()).startsWith("data:image/png;base64,");
ObjectNode raw = raw(history);
ObjectNode source = (ObjectNode) raw.path("observations").get(0);
source.put("kind", "image_text").put("imageId", id).put("content", TEXT);
raw.withArray("images").addObject().put("imageId", id).put("type", "text_requirements").put("usage", "requirements").putArray("uncertainties");
return raw;
}).when(model).analyze(anyList());
JsonNode completed = submit(session, "m1", "", List.of(id));
assertThat(completed.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 {
components(true, 30);
Session session = create();
doAnswer(invocation -> {
List<DemandMessage> history = invocation.getArgument(0);
ObjectNode raw = raw(List.of(history.get(0)));
raw.putArray("constraints"); raw.putArray("intentItems"); raw.putArray("partCategories");
raw.withArray("partCategories").addObject().put("category", "arm_r").put("source", "explicit").put("reason", "右臂").putArray("evidenceIds").add("e1");
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();
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");
((ObjectNode) raw.path("intentItems").get(0)).withArray("evidenceIds").add("e2");
}
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());
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);
assertThat(matched.path("requirementChecks").get(0).path("status").asText()).isEqualTo("satisfied");
}
@Test void cancellationCannotProduceSubmittableResultsAndCanRetry() throws Exception {
Session session = create(); CountDownLatch entered = new CountDownLatch(1); CountDownLatch exited = new CountDownLatch(1);
doAnswer(invocation -> {
entered.countDown(); try { new CountDownLatch(1).await(10, TimeUnit.SECONDS); } finally { exited.countDown(); }
return raw(invocation.getArgument(0));
}).when(model).analyze(anyList());
MvcResult pending = message(session, "m1", TEXT, List.of());
assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue();
String id = jdbc.queryForObject("SELECT analysis_code FROM robot_demand_analysis WHERE conversation_code=?", String.class, session.id());
mvc.perform(delete("/api/robot-analyses/" + id).cookie(session.cookie())).andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("cancelled")).andExpect(jsonPath("$.data.canSubmit").value(false));
assertThat(exited.await(5, TimeUnit.SECONDS)).isTrue();
pending.getAsyncResult(5000);
doAnswer(invocation -> raw(invocation.getArgument(0))).when(model).analyze(anyList());
MvcResult retry = mvc.perform(post("/api/robot-analyses/" + id + "/retry").cookie(session.cookie())).andExpect(status().isOk()).andReturn();
JsonNode result = completed(retry);
assertThat(result.path("analysisId").asText()).isEqualTo(id);
assertThat(result.path("status").asText()).isEqualTo("ready");
}
@Test void degradationAcceptanceDoesNotPretendUnsupportedCapabilitiesOrMissingMountsAreSatisfied() throws Exception {
components(false, 15);
doAnswer(invocation -> {
ObjectNode raw = raw(invocation.getArgument(0));
intent(raw, "budget", "整机", "预算不超过2万元");
raw.withArray("unmodeled").addObject().put("text", "预算不超过2万元").put("reason", "缺少预算字段").putArray("evidenceIds").add("e1");
return raw;
}).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);
assertThat(result.path("status").asText()).isEqualTo("partial");
assertThat(result.path("degradationAcceptanceRequired").asBoolean()).isTrue();
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();
}
@Test void changedComponentsRequireRematchAndDoNotReinvokeTheModel() 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);
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(refreshed.path("matchId").asText()).isNotEqualTo(original.path("matchId").asText());
org.mockito.Mockito.verify(model, org.mockito.Mockito.times(1)).analyze(anyList());
}
@Test void invalidPayloadsImagesAndPublicRuleDownloadsAreRejected() throws Exception {
Session session = create();
mvc.perform(post("/api/robot-conversations/" + session.id() + "/messages").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"messageId\":\"m1\",\"text\":\"abc\",\"role\":\"system\"}"))
.andExpect(status().isUnprocessableEntity());
mvc.perform(post("/api/robot-conversations/" + session.id() + "/messages").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON).content("{\"messageId\":\"m1\",\"text\":\"\",\"attachmentIds\":[]}"))
.andExpect(status().isUnprocessableEntity());
mvc.perform(multipart("/api/robot-conversations/" + session.id() + "/attachments").file(new MockMultipartFile("file", "fake.png", "image/png", "invalid".getBytes(java.nio.charset.StandardCharsets.UTF_8))).cookie(session.cookie()))
.andExpect(status().isUnprocessableEntity());
for (String path : List.of("/robot-demand/system-prompt.txt", "/robot-demand/model-output.schema.json", "/robot-demand/part-catalog.json")) mvc.perform(get(path)).andExpect(status().isNotFound());
}
private Session create() throws Exception {
MvcResult result = mvc.perform(post("/api/robot-conversations")).andExpect(status().isOk()).andReturn();
String header = result.getResponse().getHeader("Set-Cookie");
assertThat(header).contains("HttpOnly", "SameSite=Lax");
String[] pair = header.substring(0, header.indexOf(';')).split("=", 2);
return new Session(data(result).path("conversationId").asText(), new Cookie(pair[0], pair[1]));
}
private MvcResult message(Session session, String id, String text, List<String> images) throws Exception {
return mvc.perform(post("/api/robot-conversations/" + session.id() + "/messages").cookie(session.cookie()).contentType(MediaType.APPLICATION_JSON)
.content(json.writeValueAsBytes(Map.of("messageId", id, "text", text, "attachmentIds", images)))).andExpect(status().isOk()).andReturn();
}
private JsonNode submit(Session session, String id, String text, List<String> images) throws Exception { return completed(message(session, id, text, images)); }
private JsonNode completed(MvcResult result) throws Exception {
result.getAsyncResult(10000);
mvc.perform(asyncDispatch(result)).andExpect(status().isOk());
String events = result.getResponse().getContentAsString(java.nio.charset.StandardCharsets.UTF_8);
for (String event : events.split("\n\n")) if (event.contains("event:analysis.completed")) {
int start = event.indexOf("data:");
return json.readTree(event.substring(start + 5).trim()).path("data");
}
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 data(MvcResult result) throws Exception { return json.readTree(result.getResponse().getContentAsByteArray()).path("data"); }
private ObjectNode raw(List<DemandMessage> history) {
DemandMessage user = history.stream().filter((DemandMessage message) -> "user".equals(message.role())).reduce((DemandMessage first, DemandMessage next) -> next).orElseThrow();
ObjectNode raw = json.createObjectNode().put("summary", "躯干和右臂需求");
for (String field : List.of("intentItems", "images", "observations", "keywords", "robotTypes", "partCategories", "excludedCategories", "constraints", "unmodeled", "questions")) raw.putArray(field);
raw.withArray("observations").addObject().put("id", "e1").put("messageId", user.id()).put("imageId", "").put("kind", "user_text").put("content", user.text()).put("clarity", "clear").putArray("region");
raw.withArray("keywords").addObject().put("term", "机器人").put("source", "explicit").put("reason", "机器人需求").put("negated", false).putArray("evidenceIds").add("e1");
for (String category : List.of("torso_0", "arm_r")) raw.withArray("partCategories").addObject().put("category", category).put("source", "explicit").put("reason", "所需组件").putArray("evidenceIds").add("e1");
constraint(raw, "robot", "degreesOfFreedom", "4", "eq", null);
constraint(raw, "robot", "massKg", "4kg", "lte", null);
constraint(raw, "part", "torqueNm", "20N·m", "gte", "arm_r");
intent(raw, "performance", "整机", "整体4自由度"); intent(raw, "performance", "整机", "质量不超过4kg"); intent(raw, "performance", "右臂", "右臂扭矩至少20N·m");
return raw;
}
private ObjectNode constraint(ObjectNode raw, String scope, String field, String value, String operator, String category) {
ObjectNode row = raw.withArray("constraints").addObject().put("scope", scope).put("field", field).put("value", value).put("upperValue", "").put("operator", operator);
row.putArray("categories"); if (category != null) row.withArray("categories").add(category); row.putArray("evidenceIds").add("e1"); return row;
}
private void intent(ObjectNode raw, String dimension, String subject, String requirement) {
raw.withArray("intentItems").addObject().put("id", "r" + (raw.path("intentItems").size() + 1)).put("dimension", dimension).put("subject", subject)
.put("requirement", requirement).put("priority", "must").put("source", "explicit").putArray("evidenceIds").add("e1");
}
private void components(boolean mount, int torque) {
save("CW-TORSO", "torso_0", 0, "2", 0, "BASE", true);
save("CW-ARM", "arm_r", 4, "1", torque, "ARM_ROOT", mount);
save("CW-ARM-ALT", "arm_r", 4, "1.2", torque, "ARM_V2_ROOT", mount);
}
private void save(String code, String category, int degrees, String mass, int torque, String root, boolean mount) {
ObjectNode info = json.createObjectNode().put("rootLink", root).put("robotName", code);
info.putArray("frames");
if ("torso_0".equals(category)) {
ObjectNode frame = info.withArray("frames").addObject().put("name", "J_ARM").put("kind", "joint").put("type", "fixed").put("parent", "BASE").put("child", "LINK_arm_r").put("interfaceType", "arm_r").put("originExplicit", true);
frame.putArray("xyz").add(1).add(0).add(0); frame.putArray("rpy").add(0).add(0).add(0); frame.putArray("axis").add(0).add(0).add(0); frame.putObject("limits");
}
if (mount) info.putObject("assembly").put("mountingFrame", root).put("pairingConvention", "coincident_frames");
String prefix = "cadworld/components/" + code + "/urdf/batch/";
jdbc.update("INSERT INTO component (component_code,component_name,category,description,mass_kg,degrees_of_freedom,torque_nm,bom_list,urdf_info,urdf_prefix,urdf_main_object_key,urdf_files) VALUES (?,?,?,'机器人',?,?,?,?,?,?,?,?)",
code, code, category, mass, degrees, torque, "{\"nested\":{\"parts\":[\"BOLT\"]}}", info.toString(), prefix, prefix + "robot.urdf", "[{\"relativePath\":\"robot.urdf\",\"sizeBytes\":10},{\"relativePath\":\"meshes/a.stl\",\"sizeBytes\":20}]");
}
private MockMultipartFile image() { return new MockMultipartFile("file", "private.png", "image/png", Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j2ioAAAAASUVORK5CYII=")); }
private static Path directory() { try { return Files.createTempDirectory("cadworld-demand-test-"); } catch (IOException exception) { throw new IllegalStateException(exception); } }
@AfterAll static void cleanup() throws IOException {
try (java.util.stream.Stream<Path> paths = Files.list(DIRECTORY)) { for (Path path : paths.toList()) Files.deleteIfExists(path); }
Files.deleteIfExists(DIRECTORY);
}
private record Session(String id, Cookie cookie) { }
}
@@ -174,7 +174,7 @@ class MatchingApiTest {
}
@Test
void completeConnectedAssemblyWinsOverSmallerAssemblyThatMeetsParameters() throws Exception {
void bestMatchingTorsoStaysSelectedEvenWhenAnotherTorsoCouldConnectMoreParts() throws Exception {
save("CW-EXACT-LEAF", "torso_0", 20, "1", "0", "铝合金");
save("CW-FALLBACK-T", "torso_0", 0, "8", "0", "steel", metadata("BASE", "arm_r"), json.readTree("[]"));
save("CW-FALLBACK-R", "arm_r", 4, "5", "10", "steel");
@@ -183,10 +183,12 @@ class MatchingApiTest {
body.put("partRequirements", List.of(Map.of("category", "torso_0", "material", "铝合金"),
Map.of("category", "arm_r", "torqueNm", 20, "operators", Map.of("torqueNm", "gte"))));
JsonNode result = match(body);
assertThat(result.path("status").asText()).isEqualTo("FALLBACK");
assertThat(result.path("parts").size()).isEqualTo(2);
assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-FALLBACK-T");
assertThat(result.path("unmetRequirements").size()).isEqualTo(4);
assertThat(result.path("status").asText()).isEqualTo("PARTIAL");
assertThat(result.path("parts").size()).isEqualTo(1);
assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-EXACT-LEAF");
assertThat(result.path("unmetRequirements")).isEmpty();
assertThat(result.path("missingParts").get(0).path("category").asText()).isEqualTo("arm_r");
assertThat(result.path("missingParts").get(0).path("reason").asText()).isEqualTo("NO_COMPATIBLE_CONNECTION");
}
@Test
@@ -205,6 +207,43 @@ class MatchingApiTest {
assertThat(result.path("totals").path("degreesOfFreedom").asInt()).isEqualTo(20);
}
@Test
void torsoKeywordRelevancePrecedesInterfaceCoverageAndIncludesTorsoWhenOmitted() throws Exception {
save("CW-A-RELEVANT", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]"));
save("CW-B-MORE-PORTS", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r", "head_0"), json.readTree("[]"));
save("CW-R", "arm_r", 4, "1", "20", "");
save("CW-H", "head_0", 0, "1", "0", "");
jdbc.update("UPDATE component SET function_description='用于奔跑' WHERE component_code='CW-A-RELEVANT'");
Map<String, Object> body = new LinkedHashMap<>(request("arm_r", "head_0"));
body.put("requirements", List.of("跑步"));
JsonNode result = match(body);
assertThat(result.path("rootCategory").asText()).isEqualTo("torso_0");
assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-A-RELEVANT");
assertThat(result.path("parts")).hasSize(2);
assertThat(result.path("status").asText()).isEqualTo("PARTIAL");
assertThat(result.path("missingParts").get(0).path("category").asText()).isEqualTo("head_0");
assertThat(result.path("unmatchedKeywords")).isEmpty();
}
@Test
void evaluatesWholeRobotTotalsAfterTorsoSelectionAndKeepsTorsoFixedInFallbackSearch() throws Exception {
save("CW-A", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]"));
save("CW-B", "torso_0", 16, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]"));
save("CW-R", "arm_r", 4, "1", "20", "");
Map<String, Object> body = new LinkedHashMap<>(request("躯干_0", "torso_0", "臂_r"));
body.put("robotRequirements", Map.of("degreesOfFreedom", 20));
body.put("partRequirements", List.of(Map.of("category", "arm_r", "torqueNm", 30, "operators", Map.of("torqueNm", "gte"))));
RobotMatchingService service = context.getBean(RobotMatchingService.class);
RobotMatchResponse result = service.matchConfirmed(json.convertValue(body, RobotMatchRequest.class));
assertThat(result.rootCategory()).isEqualTo("torso_0");
assertThat(result.parts()).filteredOn((com.linkerbot.cadworld.dto.matching.PublicComponentResponse component) -> component.category().equals("torso_0"))
.hasSize(1).extracting(com.linkerbot.cadworld.dto.matching.PublicComponentResponse::componentCode).containsExactly("CW-A");
assertThat(result.parts()).hasSize(2);
assertThat(result.totals().degreesOfFreedom()).isEqualTo(4);
assertThat(result.unmetRequirements()).extracting(RobotMatchResponse.UnmetRequirement::field).contains("degreesOfFreedom", "torqueNm");
assertThat(result.connections()).allMatch((RobotMatchResponse.Connection connection) -> !connection.childCategory().equals("torso_0"));
}
@Test
void followsChainsWithoutAssumingRequestedRoleOrderAndNeverCreatesCycles() throws Exception {
save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]"));
@@ -232,14 +271,17 @@ class MatchingApiTest {
}
@Test
void missingTorsoUsesRootWithMostReachableRequestedParts() throws Exception {
void missingTorsoCannotUseAnotherRoleAsAssemblyRoot() throws Exception {
save("CW-HEAD", "head_0", 0, "1", "0", "");
save("CW-R", "arm_r", 3, "1", "0", "", metadata("RIGHT", "hand_r"), json.readTree("[]"));
save("CW-HAND", "hand_r", 2, "1", "0", "");
JsonNode result = match(request("torso_0", "head_0", "arm_r", "hand_r"));
assertThat(result.path("status").asText()).isEqualTo("PARTIAL");
assertThat(result.path("rootCategory").asText()).isEqualTo("arm_r");
assertThat(result.path("parts").size()).isEqualTo(2);
assertThat(result.path("status").asText()).isEqualTo("NO_MATCH");
assertThat(result.path("rootCategory").isNull()).isTrue();
assertThat(result.path("parts")).isEmpty();
assertThat(result.path("connections")).isEmpty();
assertThat(result.path("missingParts")).hasSize(4);
assertThat(result.path("missingParts").toString()).contains("NO_TORSO");
}
@Test
@@ -381,6 +423,7 @@ class MatchingApiTest {
@Test
void defaultsNumericComparisonToEqualityAndUsesGteLteWithoutRounding() throws Exception {
save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]"));
save("CW-R", "arm_r", 5, "1.000001", "20.000001", "");
Map<String, Object> body = new LinkedHashMap<>(request("arm_r"));
body.put("robotRequirements", Map.of("degreesOfFreedom", 4, "operators", Map.of("degreesOfFreedom", "gte")));