|
|
@@ -34,6 +34,7 @@ import com.zsjz.ai.module.agent.vo.MessageVO;
|
|
|
import com.zsjz.ai.module.agent.vo.SubagentTaskVO;
|
|
|
import com.zsjz.ai.module.graph.service.GraphService;
|
|
|
import com.zsjz.ai.common.model.graph.query.GraphQuery;
|
|
|
+import io.agentscope.core.agent.AgentRun;
|
|
|
import io.agentscope.core.agent.RuntimeContext;
|
|
|
import io.agentscope.core.event.*;
|
|
|
import io.agentscope.core.message.Msg;
|
|
|
@@ -59,6 +60,7 @@ import java.time.LocalDate;
|
|
|
import java.time.LocalDateTime;
|
|
|
import java.util.*;
|
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
|
+import java.util.concurrent.CancellationException;
|
|
|
import java.util.concurrent.atomic.AtomicBoolean;
|
|
|
import java.util.concurrent.atomic.AtomicReference;
|
|
|
import java.util.concurrent.Semaphore;
|
|
|
@@ -466,7 +468,10 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
|
|
|
@Override
|
|
|
public List<SubagentTaskVO> listSubagentTasks(Long sessionId) {
|
|
|
- AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId));
|
|
|
+ // 任务接口用「404 不泄露」语义:未开案/案件不符与任务不存在同样返回 404,
|
|
|
+ // 不经由 requireSessionInOpenCase(那里未开案抛 400、案件不符抛 403 并回显 ID,
|
|
|
+ // 会向越权方泄露会话/案件的存在性与归属)。
|
|
|
+ AgentChatSession session = requireOwnedSessionForTasks(sessionId);
|
|
|
Long userId = StpUtil.getLoginIdAsLong();
|
|
|
String sid = String.valueOf(sessionId);
|
|
|
return subagentTaskRegistry.list(userId, session.getCaseId(), sid).stream()
|
|
|
@@ -485,7 +490,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
|
|
|
@Override
|
|
|
public void cancelSubagentTask(Long sessionId, String taskId) {
|
|
|
- AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId));
|
|
|
+ // 同 listSubagentTasks:404 不泄露语义(未开案/案件不符与任务不存在同响应)
|
|
|
+ AgentChatSession session = requireOwnedSessionForTasks(sessionId);
|
|
|
Long userId = StpUtil.getLoginIdAsLong();
|
|
|
String sid = String.valueOf(sessionId);
|
|
|
// 必须先按 userId+caseId+sessionId 命中注册表,再查运行态;只凭 taskId 一律 404
|
|
|
@@ -507,7 +513,11 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId));
|
|
|
Long userId = StpUtil.getLoginIdAsLong();
|
|
|
String sid = String.valueOf(sessionId);
|
|
|
- // 先取消在途父流(用户在界面上点「停止」),再清理后台任务与并发许可
|
|
|
+ // 取消在途父流(用户在界面上点「停止」)。ActiveStream.cancel 会先对框架执行句柄
|
|
|
+ // (AgentRun,见 doStreamLocked)调用 cancel():直接触发 RunControl 取消,
|
|
|
+ // 立即掐断模型调用与工具链——单纯 dispose SSE 订阅拦不住在途运行(僵尸流实测可跑
|
|
|
+ // 十几分钟,期间会话闸门不释放、所有新消息被「正在回复中」拒绝)。
|
|
|
+ // 随后清理后台任务与并发许可。
|
|
|
ActiveStream active = activeStreams.get(sessionId);
|
|
|
if (active != null) {
|
|
|
active.cancel();
|
|
|
@@ -529,24 +539,58 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
// 过程累积器随请求创建并下传:出错时错误消息要把「深度思考 + 工具调用 + 产物元数据」一并落库,
|
|
|
// 否则出错轮次刷新后只剩一行错误提示,本轮跑过的思考/工具/产物全部消失
|
|
|
StreamProcess process = new StreamProcess();
|
|
|
- return Flux.defer(() -> doStream(req, process, openCaseId))
|
|
|
- .onErrorResume(ex -> {
|
|
|
- String errorMsg = ex.getMessage() != null ? ex.getMessage() : "未知错误";
|
|
|
- log.error("Chat stream error: sessionKey={}, ", req.getSessionKey(), ex);
|
|
|
- // 错误信息持久化:确保刷新后仍可见(含本轮已产生的过程数据)
|
|
|
- Long sessionId = parseSessionId(req.getSessionKey());
|
|
|
- if (sessionId != null) {
|
|
|
- // 出错前已生成的文件也登记为产物(帧已失败,事件只用于落库)
|
|
|
- appendGeneratedArtifactEvents(process.caseId, process.userId, process.agentRowId,
|
|
|
- String.valueOf(sessionId), process.turnStart, process, new ArrayList<>(),
|
|
|
- process.toolInputs, process.toolResults, process.toolNames);
|
|
|
- Mono.fromRunnable(() -> persistErrorMessage(sessionId, errorMsg, process))
|
|
|
+ // SSE 的 Spring MVC 异步派发在超时/断连后可能对同一 Flux 再订阅一次:
|
|
|
+ // 原流已终态(含用户停止),重订阅会重新走一遍 doStream(重复落库/重跑模型)。
|
|
|
+ // 这里按 AgentRun 的「单次订阅」语义,只允许第一个订阅者拿到真实流。
|
|
|
+ AtomicBoolean subscribed = new AtomicBoolean();
|
|
|
+ return Flux.defer(() -> {
|
|
|
+ if (!subscribed.compareAndSet(false, true)) {
|
|
|
+ return Flux.empty();
|
|
|
+ }
|
|
|
+ return doStream(req, process, openCaseId);
|
|
|
+ }).onErrorResume(ex -> {
|
|
|
+ boolean userStopped = ex instanceof CancellationException
|
|
|
+ || ex.getCause() instanceof CancellationException;
|
|
|
+ Long sessionId = parseSessionId(req.getSessionKey());
|
|
|
+ if (userStopped) {
|
|
|
+ // 用户点「停止」触发的框架取消:走「中断」落库(与 doOnCancel 同一样式),
|
|
|
+ // 不发 error 帧——前端本地已显示「已停止生成」,连接也已断开。
|
|
|
+ // interruptPersisted 与 body.doOnCancel 共用:run.cancel 后 SSE 侧 dispose
|
|
|
+ // 可能仍在飞行,两条取消路径竞态时只落一条。
|
|
|
+ log.info("会话流被用户停止: sessionKey={}", req.getSessionKey());
|
|
|
+ if (sessionId != null && !process.resultPersisted.get()
|
|
|
+ && process.interruptPersisted.compareAndSet(false, true)) {
|
|
|
+ appendGeneratedArtifactEvents(process.caseId, process.userId, process.agentRowId,
|
|
|
+ String.valueOf(sessionId), process.turnStart, process, new ArrayList<>(),
|
|
|
+ process.toolInputs, process.toolResults, process.toolNames);
|
|
|
+ String partialText = process.text.get().toString().trim();
|
|
|
+ String toolEventsJson = buildToolEventsJson(process.toolInputs,
|
|
|
+ process.toolResults, process.toolNames);
|
|
|
+ String thinkingJson = buildThinkingMetadata(process.thinking.get().toString());
|
|
|
+ if (!partialText.isEmpty() || !toolEventsJson.isEmpty()) {
|
|
|
+ Mono.fromRunnable(() -> persistPartialMessage(sessionId, partialText,
|
|
|
+ toolEventsJson, thinkingJson))
|
|
|
.subscribeOn(Schedulers.boundedElastic())
|
|
|
.subscribe();
|
|
|
}
|
|
|
- return Flux.just(sse("error",
|
|
|
- Map.of("type", "error", "error", errorMsg)));
|
|
|
- });
|
|
|
+ }
|
|
|
+ return Flux.empty();
|
|
|
+ }
|
|
|
+ String errorMsg = ex.getMessage() != null ? ex.getMessage() : "未知错误";
|
|
|
+ log.error("Chat stream error: sessionKey={}, ", req.getSessionKey(), ex);
|
|
|
+ // 错误信息持久化:确保刷新后仍可见(含本轮已产生的过程数据)
|
|
|
+ if (sessionId != null) {
|
|
|
+ // 出错前已生成的文件也登记为产物(帧已失败,事件只用于落库)
|
|
|
+ appendGeneratedArtifactEvents(process.caseId, process.userId, process.agentRowId,
|
|
|
+ String.valueOf(sessionId), process.turnStart, process, new ArrayList<>(),
|
|
|
+ process.toolInputs, process.toolResults, process.toolNames);
|
|
|
+ Mono.fromRunnable(() -> persistErrorMessage(sessionId, errorMsg, process))
|
|
|
+ .subscribeOn(Schedulers.boundedElastic())
|
|
|
+ .subscribe();
|
|
|
+ }
|
|
|
+ return Flux.just(sse("error",
|
|
|
+ Map.of("type", "error", "error", errorMsg)));
|
|
|
+ });
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -571,7 +615,7 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
ActiveStream active = new ActiveStream();
|
|
|
activeStreams.put(sessionId, active);
|
|
|
try {
|
|
|
- return doStreamLocked(sessionId, req, process, openCaseId)
|
|
|
+ return doStreamLocked(sessionId, req, process, openCaseId, active)
|
|
|
.doOnSubscribe(sub -> active.attach(sub::cancel))
|
|
|
.doFinally(signal -> {
|
|
|
activeStreams.remove(sessionId, active);
|
|
|
@@ -585,7 +629,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
}
|
|
|
|
|
|
private Flux<ServerSentEvent<String>> doStreamLocked(Long sessionId, ChatRequestDTO req,
|
|
|
- StreamProcess process, Long openCaseId) {
|
|
|
+ StreamProcess process, Long openCaseId,
|
|
|
+ ActiveStream active) {
|
|
|
AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId), openCaseId);
|
|
|
// 本轮流的案件上下文:get_case_graph 的全量图谱补取要用它显式绑定,
|
|
|
// 因为 GraphService 的 @DS 路由只认 CaseContextHolder。
|
|
|
@@ -665,7 +710,13 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
process.userId = graphUserId;
|
|
|
process.agentRowId = agentRowId;
|
|
|
process.turnStart = turnStart;
|
|
|
- Flux<AgentEvent> events = agent.streamEvents(msgs, ctx);
|
|
|
+ // 用框架的一等执行句柄(AgentRun)而不是直接 streamEvents:
|
|
|
+ // stopSession 时对句柄 cancel() 会直接触发 RunControl.cancellation,
|
|
|
+ // guard(takeUntilOther) 立即掐断上游(含模型 HTTP 连接)——
|
|
|
+ // 单纯 dispose SSE 订阅实测拦不住在途运行(僵尸流可跑十几分钟)。
|
|
|
+ AgentRun<AgentEvent> run = agent.prepareRun(msgs, ctx);
|
|
|
+ active.attachRun(run);
|
|
|
+ Flux<AgentEvent> events = run.stream();
|
|
|
|
|
|
long startMs = System.currentTimeMillis();
|
|
|
String sessionKey = String.valueOf(sessionId);
|
|
|
@@ -831,8 +882,9 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
if (deletingSessions.contains(sessionId)) {
|
|
|
return;
|
|
|
}
|
|
|
- // 用户主动中止:若 AgentResultEvent 尚未到达,保存已流式输出的部分内容
|
|
|
- if (!resultPersisted.get()) {
|
|
|
+ // 用户主动中止:若 AgentResultEvent 尚未到达,保存已流式输出的部分内容。
|
|
|
+ // interruptPersisted 与 stream() onErrorResume 的取消分支共用,防止双写
|
|
|
+ if (!resultPersisted.get() && process.interruptPersisted.compareAndSet(false, true)) {
|
|
|
// 中断前已生成的文件也登记为产物(帧已取消,事件只用于落库)
|
|
|
appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, sessionKey, turnStart,
|
|
|
process, new ArrayList<>(), toolInputs, toolResults, toolNames);
|
|
|
@@ -893,6 +945,24 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
return session;
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 子代理任务接口(列表/取消)专用守卫:404 不泄露语义。
|
|
|
+ *
|
|
|
+ * <p>未开案、会话不存在归属案件上下文或案件不符,一律 404「任务不存在或无权操作」,
|
|
|
+ * 不区分原因、不回显会话/案件 ID——与 registry 未命中时的响应完全一致,
|
|
|
+ * 越权方无法据此探测会话是否存在。区别于 {@link #requireSessionInOpenCase}
|
|
|
+ * (未开案抛 400、案件不符抛 403 并回显 ID,供正常用户排障)。
|
|
|
+ */
|
|
|
+ private AgentChatSession requireOwnedSessionForTasks(Long sessionId) {
|
|
|
+ AgentChatSession session = requireSession(sessionId);
|
|
|
+ Long openCaseId = CaseContextHolder.currentCaseId();
|
|
|
+ if (openCaseId == null || session.getCaseId() == null
|
|
|
+ || !openCaseId.equals(session.getCaseId())) {
|
|
|
+ throw new ServerException(404, "任务不存在或无权操作");
|
|
|
+ }
|
|
|
+ return session;
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 将 AI 回复持久化为 assistant 消息。失败不影响流式输出。
|
|
|
*
|
|
|
@@ -1652,6 +1722,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
*/
|
|
|
private static final class ActiveStream {
|
|
|
private final AtomicReference<Disposable> disposable = new AtomicReference<>();
|
|
|
+ /** 框架执行句柄:cancel() 直接触发 RunControl 取消,不依赖订阅 dispose 的传播 */
|
|
|
+ private volatile AgentRun<?> run;
|
|
|
private volatile boolean cancelRequested;
|
|
|
|
|
|
void attach(Disposable value) {
|
|
|
@@ -1661,8 +1733,20 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ void attachRun(AgentRun<?> value) {
|
|
|
+ run = value;
|
|
|
+ if (cancelRequested) {
|
|
|
+ value.cancel();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
void cancel() {
|
|
|
cancelRequested = true;
|
|
|
+ // 先掐执行句柄(立即中断模型调用/工具链),再断 SSE 订阅
|
|
|
+ AgentRun<?> current = run;
|
|
|
+ if (current != null) {
|
|
|
+ current.cancel();
|
|
|
+ }
|
|
|
Disposable value = disposable.get();
|
|
|
if (value != null) {
|
|
|
value.dispose();
|
|
|
@@ -1685,6 +1769,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
final AtomicReference<StringBuilder> thinking = new AtomicReference<>(new StringBuilder());
|
|
|
/** 完整回答是否已落库(落库后出错不再重复携带过程数据) */
|
|
|
final AtomicBoolean resultPersisted = new AtomicBoolean(false);
|
|
|
+ /** 中断消息是否已落库:停止时 doOnCancel 与 onErrorResume(取消) 可能竞态双触发,只落一条 */
|
|
|
+ final AtomicBoolean interruptPersisted = new AtomicBoolean(false);
|
|
|
/** 生成文件是否已扫描登记(正常结束/中断/异常三条路径只扫一次) */
|
|
|
final AtomicBoolean artifactsScanned = new AtomicBoolean(false);
|
|
|
/** 本轮案件上下文:异常收尾路径也要用它扫描生成文件(可能跨线程读写) */
|