|
|
@@ -40,7 +40,10 @@ import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.http.codec.ServerSentEvent;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
|
+import org.springframework.transaction.support.TransactionSynchronization;
|
|
|
+import org.springframework.transaction.support.TransactionSynchronizationManager;
|
|
|
import org.springframework.util.StringUtils;
|
|
|
+import reactor.core.Disposable;
|
|
|
import reactor.core.publisher.Flux;
|
|
|
import reactor.core.publisher.Mono;
|
|
|
import reactor.core.publisher.Sinks;
|
|
|
@@ -91,6 +94,12 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
*/
|
|
|
private final ConcurrentHashMap<Long, Semaphore> streamLocks = new ConcurrentHashMap<>();
|
|
|
|
|
|
+ /** 当前会话的在途流订阅:删除会话时先取消它,再等闸门释放 */
|
|
|
+ private final ConcurrentHashMap<Long, ActiveStream> activeStreams = new ConcurrentHashMap<>();
|
|
|
+
|
|
|
+ /** 正在删除的会话:取消/中断回调不应再把半截消息或产物写回 */
|
|
|
+ private final Set<Long> deletingSessions = ConcurrentHashMap.newKeySet();
|
|
|
+
|
|
|
private final AgentChatSessionMapper chatSessionMapper;
|
|
|
private final AgentMessageMapper messageMapper;
|
|
|
private final AgentService agentService;
|
|
|
@@ -134,6 +143,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
AgentChatSession entity = new AgentChatSession();
|
|
|
entity.setId(generateId());
|
|
|
entity.setCaseId(caseId);
|
|
|
+ // 记录创建者:删除会话时按它清理 Redis 记忆槽位(RuntimeContext 也用它作 userId)
|
|
|
+ entity.setUserId(StpUtil.getLoginIdAsLong());
|
|
|
entity.setAgentId(dto.getAgentId() != null ? dto.getAgentId() : AgentService.DEFAULT_AGENT_ROW_ID);
|
|
|
|
|
|
entity.setTitle(dto.getTitle() != null ? dto.getTitle() : DEFAULT_TITLE);
|
|
|
@@ -195,20 +206,99 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
AgentChatSession session = requireSession(sessionId);
|
|
|
requireSessionInOpenCase(session);
|
|
|
|
|
|
- // 删除会话下的所有消息
|
|
|
- messageMapper.delete(
|
|
|
- new LambdaQueryWrapper<AgentMessage>()
|
|
|
- .eq(AgentMessage::getSessionId, sessionId)
|
|
|
- );
|
|
|
+ // 删除期间持有会话闸门:先自动取消在途流,等它释放闸门后再删;
|
|
|
+ // 删除提交前也不允许新流进来,否则旧流会在删除后把 AgentState 写回 Redis,
|
|
|
+ // 或往已删会话补消息。
|
|
|
+ Semaphore gate = streamLocks.computeIfAbsent(sessionId, k -> new Semaphore(1));
|
|
|
+ deletingSessions.add(sessionId);
|
|
|
+ boolean gateAcquired = false;
|
|
|
+ boolean releasedAfterTransaction = false;
|
|
|
+ try {
|
|
|
+ ActiveStream active = activeStreams.get(sessionId);
|
|
|
+ if (active != null) {
|
|
|
+ active.cancel();
|
|
|
+ }
|
|
|
+ gateAcquired = acquireGateAfterCancel(sessionId, gate);
|
|
|
+ if (!gateAcquired) {
|
|
|
+ // 取消可能和订阅竞态,给第二次机会
|
|
|
+ active = activeStreams.get(sessionId);
|
|
|
+ if (active != null) {
|
|
|
+ active.cancel();
|
|
|
+ }
|
|
|
+ gateAcquired = acquireGateAfterCancel(sessionId, gate);
|
|
|
+ }
|
|
|
+ if (!gateAcquired) {
|
|
|
+ throw new ServerException(409, "会话停止超时,请稍后重试");
|
|
|
+ }
|
|
|
+
|
|
|
+ // 删除会话下的所有消息
|
|
|
+ messageMapper.delete(
|
|
|
+ new LambdaQueryWrapper<AgentMessage>()
|
|
|
+ .eq(AgentMessage::getSessionId, sessionId)
|
|
|
+ );
|
|
|
+
|
|
|
+ // 删除会话
|
|
|
+ chatSessionMapper.deleteById(sessionId);
|
|
|
+ // 会话附件:数据库行 + 向量 + cases/{caseId}/ai/sessions/{sessionId} 目录
|
|
|
+ chatAttachmentService.deleteBySession(session.getCaseId(), sessionId);
|
|
|
+ // 记忆槽位 = (userId, sessionId)。会话创建者与当前操作者都要清;
|
|
|
+ // 只清当前用户会在"创建者 ≠ 删除者"时留下创建者的 Redis 状态。
|
|
|
+ Set<String> memoryUsers = new LinkedHashSet<>();
|
|
|
+ if (session.getUserId() != null) {
|
|
|
+ memoryUsers.add(String.valueOf(session.getUserId()));
|
|
|
+ }
|
|
|
+ memoryUsers.add(StpUtil.getLoginIdAsString());
|
|
|
+ Long agentRowId = session.getAgentId() != null
|
|
|
+ ? session.getAgentId() : AgentService.DEFAULT_AGENT_ROW_ID;
|
|
|
+ for (String memoryUser : memoryUsers) {
|
|
|
+ agentService.deleteSessionMemory(memoryUser, String.valueOf(sessionId));
|
|
|
+ agentService.deleteSessionTranscript(session.getCaseId(), agentRowId,
|
|
|
+ memoryUser, String.valueOf(sessionId));
|
|
|
+ }
|
|
|
+ releaseSessionGateAfterTransaction(sessionId, gate);
|
|
|
+ releasedAfterTransaction = true;
|
|
|
+ log.info("删除会话成功: {}", sessionId);
|
|
|
+ } finally {
|
|
|
+ if (!releasedAfterTransaction) {
|
|
|
+ if (gateAcquired) {
|
|
|
+ gate.release();
|
|
|
+ }
|
|
|
+ deletingSessions.remove(sessionId);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 取消流后等它释放闸门;超时返回 false,由调用方决定是否重试。
|
|
|
+ */
|
|
|
+ private static boolean acquireGateAfterCancel(Long sessionId, Semaphore gate) {
|
|
|
+ try {
|
|
|
+ return gate.tryAcquire(5, java.util.concurrent.TimeUnit.SECONDS);
|
|
|
+ } catch (InterruptedException e) {
|
|
|
+ Thread.currentThread().interrupt();
|
|
|
+ log.info("等待会话流停止时被中断: sessionId={}", sessionId);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
- // 删除会话
|
|
|
- chatSessionMapper.deleteById(sessionId);
|
|
|
- // 会话附件:数据库行 + 向量 + cases/{caseId}/ai/sessions/{sessionId} 目录
|
|
|
- chatAttachmentService.deleteBySession(session.getCaseId(), sessionId);
|
|
|
- // 记忆槽位与对话时一致(RuntimeContext 的 userId = 登录用户 ID,sessionId = 会话主键),
|
|
|
- // 会话状态已落 Redis,不跟着删就会永久残留
|
|
|
- agentService.deleteSessionMemory(StpUtil.getLoginIdAsString(), String.valueOf(sessionId));
|
|
|
- log.info("删除会话成功: {}", sessionId);
|
|
|
+ /**
|
|
|
+ * 事务提交后再释放删除闸门并移除条目;非事务调用(单测/内部直调)立即释放。
|
|
|
+ */
|
|
|
+ private void releaseSessionGateAfterTransaction(Long sessionId, Semaphore gate) {
|
|
|
+ if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
|
|
+ TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
|
|
+ @Override
|
|
|
+ public void afterCompletion(int status) {
|
|
|
+ gate.release();
|
|
|
+ streamLocks.remove(sessionId, gate);
|
|
|
+ deletingSessions.remove(sessionId);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ } else {
|
|
|
+ gate.release();
|
|
|
+ streamLocks.remove(sessionId, gate);
|
|
|
+ deletingSessions.remove(sessionId);
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
@Override
|
|
|
@@ -371,7 +461,7 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
if (sessionId != null) {
|
|
|
// 出错前已生成的文件也登记为产物(帧已失败,事件只用于落库)
|
|
|
appendGeneratedArtifactEvents(process.caseId, process.userId, process.agentRowId,
|
|
|
- process.turnStart, process, new ArrayList<>(),
|
|
|
+ String.valueOf(sessionId), process.turnStart, process, new ArrayList<>(),
|
|
|
process.toolInputs, process.toolResults, process.toolNames);
|
|
|
Mono.fromRunnable(() -> persistErrorMessage(sessionId, errorMsg, process))
|
|
|
.subscribeOn(Schedulers.boundedElastic())
|
|
|
@@ -401,10 +491,17 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
if (!gate.tryAcquire()) {
|
|
|
return Flux.just(sse("error", Map.of("type", "error", "error", "该会话正在回复中,请等待当前回复完成后再发送")));
|
|
|
}
|
|
|
+ ActiveStream active = new ActiveStream();
|
|
|
+ activeStreams.put(sessionId, active);
|
|
|
try {
|
|
|
return doStreamLocked(sessionId, req, process, openCaseId)
|
|
|
- .doFinally(signal -> gate.release());
|
|
|
+ .doOnSubscribe(sub -> active.attach(sub::cancel))
|
|
|
+ .doFinally(signal -> {
|
|
|
+ activeStreams.remove(sessionId, active);
|
|
|
+ gate.release();
|
|
|
+ });
|
|
|
} catch (RuntimeException e) {
|
|
|
+ activeStreams.remove(sessionId, active);
|
|
|
gate.release();
|
|
|
throw e;
|
|
|
}
|
|
|
@@ -599,7 +696,7 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
}
|
|
|
// 模型/沙箱生成的文件(HTML/PNG/Word 等)登记为产物,并补发合成 tool 事件,
|
|
|
// 前端产物栏与工具卡片随本轮实时出现;同一份事件也会随消息落库,刷新后可恢复
|
|
|
- appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, turnStart,
|
|
|
+ appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, sessionKey, turnStart,
|
|
|
process, frames, toolInputs, toolResults, toolNames);
|
|
|
String toolEventsJson = buildToolEventsJson(toolInputs, toolResults, toolNames);
|
|
|
String thinkingJson = buildThinkingMetadata(accumulatedThinking.get().toString());
|
|
|
@@ -612,10 +709,14 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
}
|
|
|
return Flux.fromIterable(frames);
|
|
|
}).doOnCancel(() -> {
|
|
|
+ // 删除会话触发的取消不落半截消息/产物:随后整个会话都会被删掉
|
|
|
+ if (deletingSessions.contains(sessionId)) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
// 用户主动中止:若 AgentResultEvent 尚未到达,保存已流式输出的部分内容
|
|
|
if (!resultPersisted.get()) {
|
|
|
// 中断前已生成的文件也登记为产物(帧已取消,事件只用于落库)
|
|
|
- appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, turnStart,
|
|
|
+ appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, sessionKey, turnStart,
|
|
|
process, new ArrayList<>(), toolInputs, toolResults, toolNames);
|
|
|
String partialText = accumulatedText.get().toString().trim();
|
|
|
String toolEventsJson = buildToolEventsJson(toolInputs, toolResults, toolNames);
|
|
|
@@ -788,6 +889,10 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
*/
|
|
|
private void persistErrorMessage(Long sessionId, String errorMsg, StreamProcess process) {
|
|
|
try {
|
|
|
+ if (deletingSessions.contains(sessionId)
|
|
|
+ || chatSessionMapper.selectById(sessionId) == null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
// 完整回答已落库时(AgentResultEvent 先到、后置环节才出错)不再重复携带过程数据,
|
|
|
// 避免同轮的时间线/产物在历史里出现两份
|
|
|
boolean processLost = process != null && !process.resultPersisted.get();
|
|
|
@@ -823,6 +928,10 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
*/
|
|
|
private void persistPartialMessage(Long sessionId, String partialText, String toolEventsJson, String thinkingJson) {
|
|
|
try {
|
|
|
+ if (deletingSessions.contains(sessionId)
|
|
|
+ || chatSessionMapper.selectById(sessionId) == null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
AgentMessage msg = new AgentMessage();
|
|
|
msg.setSessionId(sessionId);
|
|
|
msg.setRole("assistant");
|
|
|
@@ -979,7 +1088,7 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
* 扫描内部已吃掉异常,失败不影响回复落库。
|
|
|
*/
|
|
|
private void appendGeneratedArtifactEvents(Long caseId, Long userId, Long agentRowId,
|
|
|
- Instant since, StreamProcess process,
|
|
|
+ String sessionId, Instant since, StreamProcess process,
|
|
|
List<ServerSentEvent<String>> frames,
|
|
|
Map<String, StringBuilder> toolInputs,
|
|
|
Map<String, StringBuilder> toolResults,
|
|
|
@@ -987,13 +1096,17 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
if (caseId == null || userId == null || agentRowId == null) {
|
|
|
return;
|
|
|
}
|
|
|
+ Long parsedSessionId = parseSessionId(sessionId);
|
|
|
+ if (parsedSessionId != null && deletingSessions.contains(parsedSessionId)) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
if (!process.artifactsScanned.compareAndSet(false, true)) {
|
|
|
return;
|
|
|
}
|
|
|
List<Map<String, Object>> artifacts;
|
|
|
try {
|
|
|
artifacts = CaseContextHolder.callWith(caseId, userId,
|
|
|
- () -> artifactScanner.scanAndRegister(userId, caseId, agentRowId, since));
|
|
|
+ () -> artifactScanner.scanAndRegister(userId, caseId, agentRowId, sessionId, since));
|
|
|
} catch (Exception e) {
|
|
|
log.info("扫描生成文件产物失败: caseId={}, error={}", caseId, e.getMessage());
|
|
|
return;
|
|
|
@@ -1149,6 +1262,32 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
|
|
|
* 用户中止随 interrupted 消息落库,<b>中途出错也要随错误消息落库</b> ——
|
|
|
* 三处共用同一份数据,任何终态都不丢过程记录。条目极少、随请求释放,不额外清理。
|
|
|
*/
|
|
|
+ /**
|
|
|
+ * 一条在途流的可取消句柄。
|
|
|
+ *
|
|
|
+ * <p>Flux 可能在删除请求到达时还没被订阅(attach 尚未发生),所以先记 cancelRequested;
|
|
|
+ * 订阅时再补一次 dispose,避免竞态下停在半路。
|
|
|
+ */
|
|
|
+ private static final class ActiveStream {
|
|
|
+ private final AtomicReference<Disposable> disposable = new AtomicReference<>();
|
|
|
+ private volatile boolean cancelRequested;
|
|
|
+
|
|
|
+ void attach(Disposable value) {
|
|
|
+ disposable.set(value);
|
|
|
+ if (cancelRequested) {
|
|
|
+ value.dispose();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ void cancel() {
|
|
|
+ cancelRequested = true;
|
|
|
+ Disposable value = disposable.get();
|
|
|
+ if (value != null) {
|
|
|
+ value.dispose();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
private static final class StreamProcess {
|
|
|
final Map<String, StringBuilder> toolInputs = new ConcurrentHashMap<>();
|
|
|
final Map<String, StringBuilder> toolResults = new ConcurrentHashMap<>();
|