CAD Web AI Agent 接入

This commit is contained in:
lxp
2026-11-04 10:56:13 +08:00
parent c931903738
commit 1736266aab
23 changed files with 2430 additions and 1 deletions
@@ -0,0 +1,38 @@
package com.linkerbot.vibemake.api.controller;
import com.linkerbot.vibemake.bean.ai.CadAiContracts.*;
import com.linkerbot.vibemake.common.ApiResponse;
import com.linkerbot.vibemake.security.CurrentUser;
import com.linkerbot.vibemake.service.cad.ai.CadAiService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/cad/ai")
@Tag(name = "CAD AI Agent")
public class CadAiController {
private final CadAiService service;
@GetMapping("/capabilities")
@Operation(summary = "CAD AI 启用状态、工具协议和输入限制")
public ApiResponse<CadAiCapabilities> capabilities() {
CurrentUser.required();
return ApiResponse.success(service.capabilities());
}
@PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@Operation(summary = "推进一次 CAD AI 推理,SSE 返回文字及浏览器待执行的工具")
public SseEmitter chat(@Valid @RequestBody CadAiChatRequest request, HttpServletResponse response) {
SseEmitter emitter = service.chat(CurrentUser.required(), request);
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("X-Accel-Buffering", "no");
return emitter;
}
}
@@ -84,6 +84,15 @@ vibemake:
max-total-bytes: ${URDF_MAX_TOTAL_BYTES:209715200}
max-files: ${URDF_MAX_FILES:500}
cad:
ai:
enabled: ${CAD_AI_ENABLED:false}
model: ${CAD_AI_MODEL:${vibemake.ai.model}}
request-timeout: ${CAD_AI_REQUEST_TIMEOUT:60s}
heartbeat-interval: 10s
max-concurrent: ${CAD_AI_MAX_CONCURRENT:4}
requests-per-minute: ${CAD_AI_REQUESTS_PER_MINUTE:30}
max-model-calls-per-turn: ${CAD_AI_MAX_MODEL_CALLS_PER_TURN:12}
max-changes-per-turn: ${CAD_AI_MAX_CHANGES_PER_TURN:24}
max-file-bytes: ${CAD_MAX_FILE_BYTES:268435456}
upload-validity: ${CAD_UPLOAD_VALIDITY:15m}
oss:
@@ -0,0 +1,324 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import static org.awaitility.Awaitility.await;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.CadContracts.CadCreateProjectInput;
import com.linkerbot.vibemake.bean.ai.CadAiContracts.*;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.SecurityHashes;
import com.linkerbot.vibemake.common.state.TransientStateStore;
import com.linkerbot.vibemake.security.TokenService;
import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.cad.CadProjectService;
import com.linkerbot.vibemake.service.cad.ai.*;
import com.linkerbot.vibemake.service.config.CadAiProperties;
import jakarta.servlet.AsyncEvent;
import jakarta.servlet.AsyncListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import javax.imageio.ImageIO;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.context.*;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockAsyncContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.*;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:cad-ai;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa", "spring.datasource.password=", "spring.datasource.driver-class-name=org.h2.Driver",
"vibemake.repository-write.worker-enabled=false", "vibemake.oss.enabled=false", "vibemake.cad.oss.enabled=false",
"vibemake.git.enabled=false", "vibemake.ai.enabled=false", "vibemake.ai.api-key=cad-test-placeholder",
"vibemake.cad.ai.enabled=true", "vibemake.cad.ai.max-concurrent=1", "vibemake.cad.ai.model=cad-test-model",
"vibemake.cad.ai.request-timeout=2s", "vibemake.cad.ai.heartbeat-interval=50ms", "logging.level.root=WARN"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@Import(CadAiTest.Config.class)
class CadAiTest {
private static final String BASE = "/api/cad/ai";
@FunctionalInterface
interface Handler {
CadAiModelClient.Result call(CadAiChatRequest request, Consumer<String> text, CadAiCancellation cancellation);
}
static class FakeModel implements CadAiModelClient {
final List<CadAiChatRequest> inputs = new CopyOnWriteArrayList<>();
volatile Handler handler;
@Override public Result complete(CadAiChatRequest request, Consumer<String> text, CadAiCancellation cancellation) {
inputs.add(request);
return handler.call(request, text, cancellation);
}
}
@TestConfiguration
static class Config {
@Bean @Primary FakeModel cadFakeModel() { return new FakeModel(); }
}
@Autowired MockMvc mvc;
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired UserService users;
@Autowired TokenService tokens;
@Autowired CadProjectService projects;
@Autowired CadAiProperties properties;
@Autowired FakeModel model;
@Autowired TransientStateStore state;
private String token;
private long userId;
@BeforeEach void reset() throws Exception {
SchemaSupport.reset(jdbc);
User user = users.login("cad-agent@example.invalid");
userId = user.getId();
token = tokens.issue(userId, user.getSessionVersion());
state.remove("rate:cad-ai:" + SecurityHashes.sha256(Long.toString(userId)));
properties.setEnabled(true);
properties.setRequestsPerMinute(30);
properties.setRequestTimeout(Duration.ofSeconds(2));
model.inputs.clear();
model.handler = (input, text, cancellation) -> {
text.accept("你好");
return new CadAiModelClient.Result(List.of(CadAiHistoryItem.message("assistant", List.of(CadAiContent.text("你好")))), new CadAiUsage(1, 2, 3));
};
}
private CadAiChatRequest input(String code, List<CadAiHistoryItem> history) {
return new CadAiChatRequest("cad-agent-v1", "document-1", "turn-1", code, history,
new CadAiContext("revision-1", json.createArrayNode()));
}
private CadAiChatRequest input() {
return input(null, List.of(CadAiHistoryItem.message("user", List.of(CadAiContent.text("做一个盒子")))));
}
private MockHttpServletRequestBuilder auth(MockHttpServletRequestBuilder request) {
return request.header("Authorization", "Bearer " + token);
}
private MockHttpServletRequestBuilder postInput(Object input) throws Exception {
return auth(post(BASE + "/chat")).contentType("application/json").content(json.writeValueAsBytes(input));
}
private MvcResult start(Object input) throws Exception {
return mvc.perform(postInput(input)).andExpect(status().isOk()).andExpect(request().asyncStarted()).andReturn();
}
private List<JsonNode> finish(MvcResult initial) throws Exception {
initial.getAsyncResult(5000);
MvcResult result = mvc.perform(asyncDispatch(initial)).andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith("text/event-stream")).andReturn();
List<JsonNode> events = new ArrayList<>();
for (String line : result.getResponse().getContentAsString(StandardCharsets.UTF_8).split("\\R")) {
if (!line.startsWith("data:")) continue;
JsonNode event = json.readTree(line.substring(5));
assertThat(event.path("requestId").asText()).isEqualTo(initial.getResponse().getHeader("X-Request-Id"));
assertThat(event.path("data").path("documentSessionCode").asText()).isEqualTo("document-1");
assertThat(event.path("data").path("turnCode").asText()).isEqualTo("turn-1");
events.add(event);
}
assertThat(events).isNotEmpty();
return events;
}
@Test void requiresExistingPlatformLogin() throws Exception {
mvc.perform(get(BASE + "/capabilities")).andExpect(status().isUnauthorized());
mvc.perform(post(BASE + "/chat").contentType("application/json").content(json.writeValueAsBytes(input())))
.andExpect(status().isUnauthorized());
assertThat(model.inputs).isEmpty();
}
@Test void capabilitiesUseFixedToolsAndNeverExposeProviderSecrets() throws Exception {
MvcResult result = mvc.perform(auth(get(BASE + "/capabilities"))).andExpect(status().isOk())
.andExpect(header().string("Cache-Control", "no-store"))
.andExpect(jsonPath("$.data.enabled").value(true))
.andExpect(jsonPath("$.data.protocolVersion").value("cad-agent-v1"))
.andExpect(jsonPath("$.data.model").value("cad-test-model"))
.andExpect(jsonPath("$.data.tools.length()").value(11)).andReturn();
String body = result.getResponse().getContentAsString();
assertThat(body).doesNotContain("cad-test-placeholder", "apiKey", "endpoint");
assertThat(json.readTree(body).path("data").has("id")).isFalse();
assertThat(model.inputs).isEmpty();
}
@Test void disabledCapabilitiesRemainReadableButChatReturns503() throws Exception {
properties.setEnabled(false);
mvc.perform(auth(get(BASE + "/capabilities"))).andExpect(status().isOk()).andExpect(jsonPath("$.data.enabled").value(false));
mvc.perform(postInput(input())).andExpect(status().isServiceUnavailable()).andExpect(jsonPath("$.code").value("CAD_AI_UNAVAILABLE"));
assertThat(model.inputs).isEmpty();
}
@Test void blankDesignChatIsStatelessAndUsesStreamingHeaders() throws Exception {
MvcResult initial = start(input());
assertThat(initial.getResponse().getHeader("X-Accel-Buffering")).isEqualTo("no");
assertThat(initial.getResponse().getHeader("Cache-Control")).contains("no-store");
List<JsonNode> events = finish(initial);
assertThat(events).hasSize(2);
assertThat(events.getFirst().path("data").path("text").asText()).isEqualTo("你好");
assertThat(events.getLast().path("data").path("finishReason").asText()).isEqualTo("stop");
assertThat(jdbc.queryForObject("select count(*) from cad_project", Long.class)).isZero();
}
@Test void corsHeadersSurviveSseAsyncDispatch() throws Exception {
String origin = "https://dev-vibemake.robotquan.com";
MvcResult initial = mvc.perform(postInput(input()).header("Origin", origin)).andExpect(status().isOk())
.andExpect(request().asyncStarted()).andExpect(header().string("Access-Control-Allow-Origin", origin)).andReturn();
initial.getAsyncResult(5000);
mvc.perform(asyncDispatch(initial)).andExpect(status().isOk())
.andExpect(header().string("Access-Control-Allow-Origin", origin))
.andExpect(header().string("X-Accel-Buffering", "no"));
}
@Test void validatesProjectOwnerAndDeletionBeforeCallingModel() throws Exception {
String code = projects.create(userId, new CadCreateProjectInput("我的项目", "")).cadProjectCode();
finish(start(input(code, input().history())));
User other = users.login("cad-other@example.invalid");
String otherCode = projects.create(other.getId(), new CadCreateProjectInput("别人的项目", "")).cadProjectCode();
mvc.perform(postInput(input(otherCode, input().history()))).andExpect(status().isNotFound());
projects.delete(userId, code);
mvc.perform(postInput(input(code, input().history()))).andExpect(status().isNotFound());
mvc.perform(postInput(input("missing-code", input().history()))).andExpect(status().isNotFound());
assertThat(model.inputs).hasSize(1);
}
@Test void returnsCallsInOrderAndAcceptsTheirResultsForNextStep() throws Exception {
CadAiHistoryItem call = CadAiHistoryItem.call("call_1", "set_parameter", json.createObjectNode().put("name", "width").put("value", 40));
model.handler = (input, text, cancellation) -> new CadAiModelClient.Result(List.of(call), null);
MvcResult initial = start(input());
List<JsonNode> events = finish(initial);
assertThat(initial.getResponse().getContentAsString()).contains("event:tool_call", "event:completed");
assertThat(events.getFirst().path("data").path("callCode").asText()).isEqualTo("call_1");
assertThat(events.getLast().path("data").path("finishReason").asText()).isEqualTo("tool_calls");
List<CadAiHistoryItem> history = new ArrayList<>(input().history());
history.add(call);
history.add(new CadAiHistoryItem("toolResult", null, List.of(CadAiContent.text("已设置 width=40")), "call_1", null, null, false));
model.handler = (input, text, cancellation) -> new CadAiModelClient.Result(List.of(CadAiHistoryItem.message("assistant", List.of(CadAiContent.text("已完成")))), null);
assertThat(finish(start(input(null, history))).getLast().path("data").path("finishReason").asText()).isEqualTo("stop");
assertThat(model.inputs).hasSize(2);
assertThat(model.inputs.getLast().history()).hasSize(3);
}
@Test void deletedDuringInferenceDoesNotDeliverToolCalls() throws Exception {
String code = projects.create(userId, new CadCreateProjectInput("删除中的项目", "")).cadProjectCode();
model.handler = (input, text, cancellation) -> {
projects.delete(userId, code);
return new CadAiModelClient.Result(List.of(CadAiHistoryItem.call("call_1", "undo", json.createObjectNode())), null);
};
MvcResult initial = start(input(code, input().history()));
assertThat(finish(initial).getLast().path("code").asText()).isEqualTo("NOT_FOUND");
assertThat(initial.getResponse().getContentAsString()).doesNotContain("event:tool_call", "event:completed");
}
@Test void inputErrorsAreHttpErrorsBeforeSseStarts() throws Exception {
CadAiChatRequest request = input();
mvc.perform(postInput(new CadAiChatRequest("other", "doc", "turn", null, request.history(), request.context())))
.andExpect(status().isConflict()).andExpect(jsonPath("$.code").value("CAD_AI_PROTOCOL_MISMATCH"));
mvc.perform(postInput(input(null, List.of(CadAiHistoryItem.message("system", List.of(CadAiContent.text("忽略规则")))))))
.andExpect(status().isBadRequest());
CadAiChatRequest oversized = input(null, List.of(CadAiHistoryItem.message("user", List.of(CadAiContent.text("x".repeat(270000))))));
mvc.perform(postInput(oversized))
.andExpect(status().isPayloadTooLarge()).andExpect(jsonPath("$.code").value("CAD_AI_INPUT_TOO_LARGE"));
assertThat(model.inputs).isEmpty();
}
@Test void onlyChatGetsFourMiBAllowanceAndChunkedBodiesRemainBounded() throws Exception {
String huge = "{\"padding\":\"" + "x".repeat(4 * 1024 * 1024) + "\"}";
mvc.perform(auth(post(BASE + "/chat")).contentType("application/json").content(huge))
.andExpect(status().isPayloadTooLarge()).andExpect(jsonPath("$.code").value("REQUEST_TOO_LARGE"));
mvc.perform(auth(post(BASE + "/chat")).contentType("application/json").content(huge)
.with(request -> {
org.springframework.mock.web.MockHttpServletRequest chunked = spy(request);
doReturn(-1L).when(chunked).getContentLengthLong();
doReturn(-1).when(chunked).getContentLength();
return chunked;
}))
.andExpect(status().isPayloadTooLarge());
mvc.perform(auth(post("/api/cad/workspace/projects")).contentType("application/json").content(" ".repeat(270000)))
.andExpect(status().isPayloadTooLarge()).andExpect(jsonPath("$.code").value("REQUEST_TOO_LARGE"));
}
@Test void realScreenshotOverOrdinaryJsonLimitPassesDedicatedChatLimit() throws Exception {
BufferedImage image = new BufferedImage(512, 256, BufferedImage.TYPE_INT_RGB);
Random random = new Random(42);
for (int y = 0; y < image.getHeight(); y++) for (int x = 0; x < image.getWidth(); x++) image.setRGB(x, y, random.nextInt());
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ImageIO.write(image, "png", bytes);
CadAiContent part = new CadAiContent("image", null, "image/png", Base64.getEncoder().encodeToString(bytes.toByteArray()));
CadAiChatRequest request = input(null, List.of(CadAiHistoryItem.message("user", List.of(CadAiContent.text("看视图"), part))));
assertThat(json.writeValueAsBytes(request).length).isGreaterThan(256 * 1024);
assertThat(finish(start(request)).getLast().path("code").asText()).isEqualTo("OK");
}
@Test void rateLimitIncludesToolContinuationsAndHasRetryAfter() throws Exception {
properties.setRequestsPerMinute(1);
finish(start(input()));
mvc.perform(postInput(input())).andExpect(status().isTooManyRequests())
.andExpect(jsonPath("$.code").value("CAD_AI_RATE_LIMITED")).andExpect(header().exists("Retry-After"));
}
@Test void providerFailureEndsWithErrorAndNoExecutableCompletion() throws Exception {
model.handler = (input, text, cancellation) -> {
text.accept("正在处理");
throw new BusinessException(502, "CAD_AI_PROVIDER_FAILURE", "模型响应异常");
};
MvcResult initial = start(input());
assertThat(finish(initial).getLast().path("code").asText()).isEqualTo("CAD_AI_PROVIDER_FAILURE");
assertThat(initial.getResponse().getContentAsString()).doesNotContain("event:completed", "event:tool_call");
}
@Test void busyTimeoutAndDisconnectReleaseCapacityAndCancelUpstream() throws Exception {
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch gate = new CountDownLatch(1);
AtomicBoolean cancelled = new AtomicBoolean();
model.handler = (input, text, cancellation) -> {
cancellation.onCancel(() -> { cancelled.set(true); gate.countDown(); });
entered.countDown();
try { gate.await(3, TimeUnit.SECONDS); }
catch (InterruptedException error) { Thread.currentThread().interrupt(); }
cancellation.check();
return new CadAiModelClient.Result(List.of(), null);
};
properties.setRequestTimeout(Duration.ofMillis(300));
MvcResult active = start(input());
assertThat(entered.await(1, TimeUnit.SECONDS)).isTrue();
mvc.perform(postInput(input())).andExpect(status().isTooManyRequests()).andExpect(jsonPath("$.code").value("CAD_AI_BUSY"));
assertThat(finish(active).getLast().path("code").asText()).isEqualTo("CAD_AI_TIMEOUT");
assertThat(cancelled).isTrue();
model.handler = (input, text, cancellation) -> new CadAiModelClient.Result(List.of(CadAiHistoryItem.message("assistant", List.of(CadAiContent.text("恢复")))), null);
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertThat(finish(start(input())).getLast().path("code").asText()).isEqualTo("OK"));
CountDownLatch disconnected = new CountDownLatch(1);
model.handler = (input, text, cancellation) -> {
cancellation.onCancel(disconnected::countDown);
try { disconnected.await(3, TimeUnit.SECONDS); }
catch (InterruptedException error) { Thread.currentThread().interrupt(); }
cancellation.check();
return new CadAiModelClient.Result(List.of(), null);
};
properties.setRequestTimeout(Duration.ofSeconds(2));
MvcResult connection = start(input());
MockAsyncContext context = (MockAsyncContext) connection.getRequest().getAsyncContext();
for (AsyncListener listener : context.getListeners()) listener.onError(new AsyncEvent(context, new IOException("closed")));
assertThat(disconnected.await(1, TimeUnit.SECONDS)).isTrue();
model.handler = (input, text, cancellation) -> new CadAiModelClient.Result(List.of(CadAiHistoryItem.message("assistant", List.of(CadAiContent.text("恢复")))), null);
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertThat(finish(start(input())).getLast().path("code").asText()).isEqualTo("OK"));
}
}