This commit is contained in:
lxp
2026-10-16 17:01:53 +08:00
parent 909abe9f1d
commit 7d0267d2f3
13 changed files with 347 additions and 82 deletions
@@ -15,12 +15,12 @@ import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/community/ai")
@Tag(name = "AI 项目助手")
@Tag(name = "Maker AI")
public class AiSearchController {
private final AiSearchService searches;
@PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@Operation(summary = "通过连续对话查找社区项目、创建空项目或 Fork 项目,返回 SSE 进度和结果")
@Operation(summary = "与 Maker AI 连续聊天、问答、查找社区项目、创建空项目或 Fork 项目,返回 SSE 进度和结果")
public SseEmitter chat(@Valid @RequestBody ChatRequest request, HttpServletResponse response) {
SseEmitter emitter = searches.chat(CurrentUser.required(), request);
response.setHeader("Cache-Control", "no-cache, no-store");
@@ -17,6 +17,8 @@ import java.time.LocalDateTime;
import java.util.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.context.SpringBootTest;
@@ -30,6 +32,7 @@ import org.springframework.test.web.servlet.*;
"spring.datasource.url=jdbc:h2:mem:ai-live;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa", "spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver", "community.ai.enabled=true",
"community.ai.requests-per-minute=120", "community.oss.enabled=false",
"logging.level.root=INFO", "logging.level.com.linkerbot.community=INFO", "debug=false"
})
@ActiveProfiles("test")
@@ -42,6 +45,47 @@ class AiSearchLiveTest {
@Autowired UserService users;
@Autowired TokenService tokens;
@Test void realModelIntroducesMakerAiAndAnswersWithChatHistory() throws Exception {
SchemaSupport.reset(jdbc);
User user = users.login("live-chat@example.invalid");
String token = tokens.issue(user.getId());
JsonNode introduction = chat(token, Map.of("message", "你是谁"));
assertChat(introduction);
assertThat(introduction.path("reply").asText()).containsIgnoringCase("Maker AI").doesNotContain("社区项目助手");
List<Map<String, String>> history = new ArrayList<>(List.of(
Map.of("role", "user", "content", "你是谁"),
Map.of("role", "assistant", "content", introduction.path("reply").asText())));
String question = "我准备使用 Java 编程。请给一个循环输出数字的简短代码示例,不创建项目。";
JsonNode explanation = chat(token, Map.of("message", question, "history", history));
assertChat(explanation);
assertThat(explanation.path("reply").asText()).contains("for");
history.add(Map.of("role", "user", "content", question));
history.add(Map.of("role", "assistant", "content", explanation.path("reply").asText()));
JsonNode followup = chat(token, Map.of("message", "我刚才准备使用什么编程语言?", "history", history));
assertChat(followup);
assertThat(followup.path("reply").asText()).containsIgnoringCase("Java");
assertThat(projects.selectCount(null)).isZero();
}
@ParameterizedTest
@ValueSource(strings = {"pending_create", "pending_fork", "created", "forked"})
void realModelChitChatDoesNotResumeProjectWrites(String context) throws Exception {
SchemaSupport.reset(jdbc);
User user = users.login("live-chat-write@example.invalid");
String question = context.endsWith("create") || context.equals("created") ? "创建教学项目" : "Fork 一个教学项目";
String previousReply = switch (context) {
case "pending_create" -> "请描述想创建的项目,例如用途或名称。";
case "pending_fork" -> "请描述要 Fork 的项目需求,或提供来源项目编码。";
case "created" -> "已创建项目「教学项目」,可以进入工作区继续编辑。";
default -> "已 Fork 为项目「教学项目」,可以进入工作区继续编辑。";
};
JsonNode result = chat(tokens.issue(user.getId()), Map.of("message", "谢谢,今天有点累,想先聊聊天。",
"history", List.of(Map.of("role", "user", "content", question),
Map.of("role", "assistant", "content", previousReply))));
assertChat(result);
assertThat(projects.selectCount(null)).isZero();
}
@Test void realModelFindsProjectsAndChangesTypeAcrossTurns() throws Exception {
SchemaSupport.reset(jdbc);
User user = users.login("live-fixture@example.invalid");
@@ -54,9 +98,16 @@ class AiSearchLiveTest {
assertType(first, "QUADRUPED");
List<String> codes = new ArrayList<>();
first.path("projects").forEach(card -> codes.add(card.path("project").path("projectCode").asText()));
List<Map<String, String>> history = new ArrayList<>(List.of(
Map.of("role", "user", "content", question),
Map.of("role", "assistant", "content", first.path("reply").asText())));
JsonNode conversation = chat(token, Map.of("message", "谢谢,陪我聊两句吧。", "history", history,
"previousProjectCodes", codes));
assertChat(conversation);
history.add(Map.of("role", "user", "content", "谢谢,陪我聊两句吧。"));
history.add(Map.of("role", "assistant", "content", conversation.path("reply").asText()));
JsonNode second = chat(token, Map.of("message", "改成轮式,其他要求不变。",
"history", List.of(Map.of("role", "user", "content", question),
Map.of("role", "assistant", "content", first.path("reply").asText())),
"history", history,
"previousProjectCodes", codes));
assertType(second, "WHEELED");
}
@@ -95,4 +146,11 @@ class AiSearchLiveTest {
result.path("projects").forEach(card ->
assertThat(card.path("project").path("projectType").asText()).isEqualTo(type));
}
private void assertChat(JsonNode result) {
assertThat(result.path("status").asText()).isEqualTo("CHAT");
assertThat(result.path("reply").asText()).isNotBlank().hasSizeLessThanOrEqualTo(2000);
assertThat(result.path("projects").isEmpty()).isTrue();
assertThat(result.path("project").isNull()).isTrue();
}
}
@@ -138,7 +138,8 @@ class AiSearchTest {
}
private ObjectNode intent(String type, List<String> keywords) {
ObjectNode node = json.createObjectNode().put("action", "SEARCH").put("projectType", type).put("clarification", "");
ObjectNode node = json.createObjectNode().put("action", "SEARCH").put("reply", "")
.put("projectType", type).put("clarification", "");
node.set("keywords", json.valueToTree(keywords));
node.putArray("requirements"); node.putArray("preferences"); node.putArray("focusProjectCodes");
node.putNull("projectName").putNull("description").putNull("coverUrl").putNull("sourceProjectCode");
@@ -186,6 +187,165 @@ class AiSearchTest {
return events.getLast();
}
private ObjectNode chatIntent(String reply) {
return intent(null, List.of()).put("action", "CHAT").put("reply", reply);
}
@ParameterizedTest
@ValueSource(strings = {"你是谁", "你好", "谢谢你", "什么是 ROS2", "用 Java 写一个循环示例"})
void returnsChatWithoutSearchingRankingOrWriting(String message) throws Exception {
Project previous = project("教学机器人", "GENERAL", "ROS2 教学项目");
String reply = switch (message) {
case "你是谁" -> "我是 Maker AI,可以陪你聊天、解答问题,也能帮助查找、创建和 Fork 社区项目。";
case "你好" -> "你好!今天想聊点什么?";
case "谢谢你" -> "不客气,很高兴能帮上忙!";
case "什么是 ROS2" -> "ROS2 是用于开发机器人应用的一组开源软件库和工具。";
default -> "可以这样写:\n```java\nfor (int index = 0; index < 3; index++) {\n System.out.println(index);\n}\n```";
};
model.handler = (name, input) -> chatIntent(reply);
List<JsonNode> events = finish(start(Map.of("message", message,
"previousProjectCodes", List.of(previous.getProjectCode()))));
JsonNode data = events.getLast().path("data");
assertThat(events).hasSize(2);
assertThat(events.getFirst().path("data").path("stage").asText()).isEqualTo("understanding");
assertThat(data.path("status").asText()).isEqualTo("CHAT");
assertThat(data.path("reply").asText()).isEqualTo(reply);
assertThat(data.path("projects").isArray()).isTrue();
assertThat(data.path("projects").isEmpty()).isTrue();
assertThat(data.path("project").isNull()).isTrue();
assertThat(data.findValues("id")).isEmpty();
assertThat(data.findValues("giteaRepoId")).isEmpty();
assertThat(model.inputs).hasSize(1);
assertThat(projects.selectCount(null)).isEqualTo(1L);
}
@Test void keepsFullChatReplyWithinHistoryLimitAcrossTurns() throws Exception {
String reply = "答".repeat(2000);
model.handler = (name, input) -> chatIntent(reply);
JsonNode first = finish(start(Map.of("message", "请解释一下变量"))).getLast().path("data");
assertThat(first.path("reply").asText()).isEqualTo(reply);
List<Map<String, String>> history = List.of(
Map.of("role", "user", "content", "请解释一下变量"),
Map.of("role", "assistant", "content", first.path("reply").asText()));
model.handler = (name, input) -> {
assertThat(input.path("history")).isEqualTo(json.valueToTree(history));
return chatIntent("变量可以保存之后会使用的数据。");
};
JsonNode second = finish(start(Map.of("message", "再简单一点", "history", history))).getLast().path("data");
assertThat(second.path("status").asText()).isEqualTo("CHAT");
assertThat(second.path("reply").asText()).isEqualTo("变量可以保存之后会使用的数据。");
assertThat(model.inputs).hasSize(2);
assertThat(projects.selectCount(null)).isZero();
}
@ParameterizedTest
@ValueSource(strings = {"empty", "blank", "control", "long", "missing", "null", "number", "extra", "missing_projectType"})
void rejectsInvalidChatRepliesAndShapes(String scenario) throws Exception {
ObjectNode response = chatIntent("我是 Maker AI。");
switch (scenario) {
case "empty" -> response.put("reply", "");
case "blank" -> response.put("reply", " \t\n");
case "control" -> response.put("reply", String.valueOf((char) 0));
case "long" -> response.put("reply", "答".repeat(2001));
case "missing" -> response.remove("reply");
case "null" -> response.putNull("reply");
case "number" -> response.put("reply", 123);
case "extra" -> response.put("extra", "unexpected");
case "missing_projectType" -> response.remove("projectType");
default -> throw new IllegalArgumentException(scenario);
}
model.handler = (name, input) -> response;
JsonNode result = finish(start(Map.of("message", "你是谁"))).getLast();
assertThat(result.path("code").asText()).isEqualTo("AI_INVALID_RESPONSE");
assertThat(model.inputs).hasSize(1);
assertThat(projects.selectCount(null)).isZero();
}
@ParameterizedTest
@ValueSource(strings = {"projectType", "keywords", "requirements", "preferences", "focusProjectCodes",
"projectName", "description", "coverUrl", "sourceProjectCode", "clarification"})
void rejectsProjectParametersInChatEvenWithClarification(String field) throws Exception {
Project previous = project("教学机器人", "GENERAL", "ROS2 教学项目");
ObjectNode response = chatIntent("不客气!");
switch (field) {
case "projectType" -> response.put(field, "GENERAL");
case "keywords", "requirements", "preferences" -> response.withArray(field).add("教学");
case "focusProjectCodes" -> response.withArray(field).add(previous.getProjectCode());
case "sourceProjectCode" -> response.put(field, previous.getProjectCode());
case "coverUrl" -> response.put(field, "https://images.example.invalid/cover.png");
default -> response.put(field, "不应携带项目参数");
}
model.handler = (name, input) -> response;
JsonNode result = finish(start(Map.of("message", "谢谢", "previousProjectCodes",
List.of(previous.getProjectCode())))).getLast();
assertThat(result.path("code").asText()).isEqualTo("AI_INVALID_RESPONSE");
assertThat(model.inputs).hasSize(1);
assertThat(projects.selectCount(null)).isEqualTo(1L);
}
@ParameterizedTest
@ValueSource(strings = {"SEARCH", "CREATE", "FORK"})
void rejectsChatReplyInProjectActionsBeforeClarificationOrWrite(String action) throws Exception {
Project source = project("教学机器人", "GENERAL", "教学项目");
ObjectNode response = switch (action) {
case "CREATE" -> createIntent(null, "教学项目");
case "FORK" -> forkIntent(source.getProjectCode(), null);
default -> intent(null, List.of());
};
response.put("reply", "不应包含聊天回复").put("clarification", "请补充需求。");
model.handler = (name, input) -> response;
JsonNode result = finish(start(Map.of("message", "处理项目", "previousProjectCodes",
List.of(source.getProjectCode())))).getLast();
assertThat(result.path("code").asText()).isEqualTo("AI_INVALID_RESPONSE");
assertThat(projects.selectCount(null)).isEqualTo(1L);
}
@ParameterizedTest
@ValueSource(strings = {"CREATE", "FORK"})
void chatDoesNotReplayCompletedWrites(String action) throws Exception {
String message;
if (action.equals("FORK")) {
Project source = publishedRepository("教学项目");
message = "Fork " + source.getProjectCode();
model.handler = (name, input) -> forkIntent(source.getProjectCode(), null);
} else {
message = "创建教学项目";
model.handler = (name, input) -> createIntent(null, "教学项目");
}
JsonNode completed = finish(start(Map.of("message", message))).getLast().path("data");
assertThat(completed.path("status").asText()).isEqualTo(action.equals("CREATE") ? "CREATED" : "FORKED");
long count = projects.selectCount(null);
model.handler = (name, input) -> chatIntent("不客气!");
JsonNode result = finish(start(Map.of("message", "谢谢你", "history", List.of(
Map.of("role", "user", "content", message),
Map.of("role", "assistant", "content", completed.path("reply").asText()))))).getLast().path("data");
assertThat(result.path("status").asText()).isEqualTo("CHAT");
assertThat(projects.selectCount(null)).isEqualTo(count);
assertThat(model.inputs).hasSize(2);
}
@Test void chatBetweenClarificationAndCreationDoesNotTriggerPendingWrite() throws Exception {
model.handler = (name, input) -> createIntent(null, null).put("clarification", "请描述想创建的项目。");
JsonNode clarification = finish(start(Map.of("message", "创建项目"))).getLast().path("data");
List<Map<String, String>> history = new ArrayList<>(List.of(
Map.of("role", "user", "content", "创建项目"),
Map.of("role", "assistant", "content", clarification.path("reply").asText())));
model.handler = (name, input) -> chatIntent("我是 Maker AI。");
JsonNode introduction = finish(start(Map.of("message", "你是谁", "history", history))).getLast().path("data");
assertThat(introduction.path("status").asText()).isEqualTo("CHAT");
assertThat(projects.selectCount(null)).isZero();
history.add(Map.of("role", "user", "content", "你是谁"));
history.add(Map.of("role", "assistant", "content", introduction.path("reply").asText()));
model.handler = (name, input) -> {
assertThat(input.path("history")).isEqualTo(json.valueToTree(history));
return createIntent(null, "导航实验");
};
JsonNode created = finish(start(Map.of("message", "想创建导航实验项目", "history", history))).getLast().path("data");
assertThat(created.path("status").asText()).isEqualTo("CREATED");
assertThat(projects.selectCount(null)).isEqualTo(1L);
assertThat(model.inputs).hasSize(3);
}
@Test
void crossOriginSseKeepsCorsHeadersAcrossAsyncDispatch() throws Exception {
String origin = "https://dev-vibemake.robotquan.com";
@@ -417,7 +577,9 @@ class AiSearchTest {
assertThat(model.inputs).hasSize(2);
}
@Test void returnsMultipleCandidatesAndForksOnlyAfterFollowupSelection() throws Exception {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void returnsMultipleCandidatesAndForksOnlyAfterFollowupSelection(boolean interleaveChat) throws Exception {
publishedRepository("ROS2 教学甲");
publishedRepository("ROS2 教学乙");
model.handler = (name, input) -> {
@@ -439,19 +601,31 @@ class AiSearchTest {
assertThat(projects.selectCount(null)).isEqualTo(2L);
List<String> codes = new ArrayList<>();
selection.path("projects").forEach(card -> codes.add(card.path("project").path("projectCode").asText()));
List<Map<String, String>> history = new ArrayList<>(List.of(
Map.of("role", "user", "content", question),
Map.of("role", "assistant", "content", selection.path("reply").asText())));
if (interleaveChat) {
model.handler = (name, input) -> chatIntent("可以,我们慢慢挑选。");
JsonNode conversation = finish(start(Map.of("message", "谢谢,先让我想想", "previousProjectCodes", codes,
"history", history))).getLast().path("data");
assertThat(conversation.path("status").asText()).isEqualTo("CHAT");
assertThat(conversation.path("projects").isEmpty()).isTrue();
assertThat(projects.selectCount(null)).isEqualTo(2L);
history.add(Map.of("role", "user", "content", "谢谢,先让我想想"));
history.add(Map.of("role", "assistant", "content", conversation.path("reply").asText()));
}
model.handler = (name, input) -> {
assertThat(input.path("history").size()).isEqualTo(2);
assertThat(input.path("history")).isEqualTo(json.valueToTree(history));
assertThat(input.path("previousProjects").get(1).path("projectCode").asText()).isEqualTo(codes.get(1));
return forkIntent(codes.get(1), "我的学习副本");
};
JsonNode result = finish(start(Map.of("message", "第二个", "previousProjectCodes", codes, "history", List.of(
Map.of("role", "user", "content", question),
Map.of("role", "assistant", "content", selection.path("reply").asText()))))).getLast().path("data");
JsonNode result = finish(start(Map.of("message", "第二个", "previousProjectCodes", codes, "history", history)))
.getLast().path("data");
assertThat(result.path("status").asText()).isEqualTo("FORKED");
assertThat(result.path("project").path("name").asText()).isEqualTo("我的学习副本");
assertThat(result.path("project").path("sourceProjectCode").asText()).isEqualTo(codes.get(1));
assertThat(projects.selectCount(null)).isEqualTo(3L);
assertThat(model.inputs).hasSize(3);
assertThat(model.inputs).hasSize(interleaveChat ? 4 : 3);
}
@Test void searchAndForkReturnsNoMatchWithoutCreating() throws Exception {