feat(agent): 支持自建风格与智能体双模式对话系统
Some checks failed
Build and Deploy / deploy (push) Has been cancelled

- 新增 `source` 字段区分智能体(`agent`)与自建风格(`prompt`)两种对话来源
- 前端统一对话组件,根据来源动态构建请求参数、显示不同样式与文案
- 后端重构 Dify 会话与消息获取逻辑,支持合并查询 Pro 与 Standard 两个 Dify App 的会话历史
- 实现复合游标分页机制,支持跨双数据源的高效分页
- 新增 `clipboard-polyfill` 依赖,统一剪贴板复制功能,提升非 HTTPS 环境兼容性
- 扩展历史记录面板,支持按来源加载对应会话与消息
- 调整侧边抽屉宽度,优化大屏显示体验
This commit is contained in:
2026-04-11 18:13:08 +08:00
parent 09a567a542
commit eaef9a0e4c
15 changed files with 292 additions and 120 deletions

View File

@@ -68,29 +68,35 @@ public class AppDifyController {
}
@GetMapping("/conversations")
@Operation(summary = "获取会话列表")
@Operation(summary = "获取会话列表(合并 pro + standard")
@Parameter(name = "agentId", description = "智能体ID", required = true)
@Parameter(name = "lastId", description = "上一页最后一条记录ID")
@Parameter(name = "source", description = "来源类型agent-智能体 prompt-自建风格")
@Parameter(name = "cursor", description = "复合游标(首页不传)")
@Parameter(name = "limit", description = "返回条数默认20")
public CommonResult<DifyConversationListRespVO> getConversations(
@RequestParam("agentId") Long agentId,
@RequestParam(value = "lastId", required = false) String lastId,
@RequestParam(value = "source", required = false, defaultValue = "agent") String source,
@RequestParam(value = "cursor", required = false) String cursor,
@RequestParam(value = "limit", required = false) Integer limit) {
return CommonResult.success(difyService.getConversations(agentId, getCurrentUserId(), lastId, limit));
return CommonResult.success(difyService.getConversations(agentId, source, getCurrentUserId(), cursor, limit));
}
@GetMapping("/messages")
@Operation(summary = "获取会话历史消息")
@Operation(summary = "获取会话历史消息(自动定位 App")
@Parameter(name = "agentId", description = "智能体ID", required = true)
@Parameter(name = "source", description = "来源类型agent-智能体 prompt-自建风格")
@Parameter(name = "conversationId", description = "会话ID", required = true)
@Parameter(name = "appSource", description = "来源应用标识pro/standard")
@Parameter(name = "firstId", description = "当前页第一条记录ID")
@Parameter(name = "limit", description = "返回条数默认20")
public CommonResult<DifyMessageListRespVO> getMessages(
@RequestParam("agentId") Long agentId,
@RequestParam(value = "source", required = false, defaultValue = "agent") String source,
@RequestParam("conversationId") String conversationId,
@RequestParam(value = "appSource", required = false) String appSource,
@RequestParam(value = "firstId", required = false) String firstId,
@RequestParam(value = "limit", required = false) Integer limit) {
return CommonResult.success(difyService.getMessages(agentId, conversationId, getCurrentUserId(), firstId, limit));
return CommonResult.success(difyService.getMessages(agentId, source, conversationId, appSource, getCurrentUserId(), firstId, limit));
}
private String getCurrentUserId() {

View File

@@ -53,26 +53,29 @@ public interface DifyService {
Flux<DifyChatRespVO> promptAnalysisStream(PromptAnalysisReqVO reqVO, String userId);
/**
* 获取会话列表
* 获取会话列表(合并 pro + standard 两个 Dify App 的会话)
*
* @param agentId 智能体ID
* @param source 来源类型agent/prompt
* @param userId 用户ID
* @param lastId 上一页最后一条记录ID
* @param cursor 复合游标Base64 编码,首页传 null
* @param limit 返回条数
* @return 会话列表
*/
DifyConversationListRespVO getConversations(Long agentId, String userId, String lastId, Integer limit);
DifyConversationListRespVO getConversations(Long agentId, String source, String userId, String cursor, Integer limit);
/**
* 获取会话历史消息
* 获取会话历史消息(自动定位 pro/standard App
*
* @param agentId 智能体ID
* @param source 来源类型agent/prompt
* @param conversationId 会话ID
* @param appSource 来源应用标识pro/standard用于选择 API Key
* @param userId 用户ID
* @param firstId 当前页第一条记录ID
* @param limit 返回条数
* @return 消息列表
*/
DifyMessageListRespVO getMessages(Long agentId, String conversationId, String userId, String firstId, Integer limit);
DifyMessageListRespVO getMessages(Long agentId, String source, String conversationId, String appSource, String userId, String firstId, Integer limit);
}

View File

@@ -6,6 +6,7 @@ import cn.iocoder.yudao.module.tik.dify.vo.DifyChatReqVO;
import cn.iocoder.yudao.module.tik.dify.vo.PromptAnalysisReqVO;
import cn.iocoder.yudao.module.tik.dify.vo.DifyChatRespVO;
import cn.iocoder.yudao.module.tik.dify.vo.DifyConversationListRespVO;
import cn.iocoder.yudao.module.tik.dify.vo.DifyConversationRespVO;
import cn.iocoder.yudao.module.tik.dify.vo.DifyMessageListRespVO;
import cn.iocoder.yudao.module.tik.dify.vo.ForecastRewriteReqVO;
import cn.iocoder.yudao.module.tik.enums.AiModelTypeEnum;
@@ -21,7 +22,13 @@ import org.springframework.validation.annotation.Validated;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
@@ -50,9 +57,7 @@ public class DifyServiceImpl implements DifyService {
AtomicLong pendingRecordId = new AtomicLong();
AtomicReference<String> conversationIdRef = new AtomicReference<>(reqVO.getConversationId());
AtomicReference<DifyChatRespVO> tokenUsageRef = new AtomicReference<>();
String difyUserId = reqVO.getAgentId() != null
? "user-" + userId + "-agent-" + reqVO.getAgentId()
: "user-" + userId + "-prompt";
String difyUserId = buildDifyUserId(userId, reqVO.getSource(), reqVO.getAgentId());
String logPrefix = "chatStream";
return Mono.fromCallable(() -> {
@@ -380,55 +385,169 @@ public class DifyServiceImpl implements DifyService {
}
@Override
public DifyConversationListRespVO getConversations(Long agentId, String userId, String lastId, Integer limit) {
// 获取智能体配置
AiAgentDO agent = aiAgentService.getAiAgent(agentId);
if (agent == null) {
throw new RuntimeException("智能体不存在");
public DifyConversationListRespVO getConversations(Long agentId, String source, String userId, String cursor, Integer limit) {
if (limit == null || limit <= 0) {
limit = 20;
}
// 获取积分配置(使用标准模式的 API Key
AiServiceConfigDO config = pointsService.getConfig(
AiPlatformEnum.DIFY.getPlatform(),
AiModelTypeEnum.DIFY_WRITING_STANDARD.getModelCode());
AiServiceConfigDO proConfig = getDifyConfig(false);
AiServiceConfigDO standardConfig = getDifyConfig(true);
// Dify 用户标识(按 agentId 隔离会话)
String difyUserId = "user-" + userId + "-agent-" + agentId;
String difyUserId = buildDifyUserId(userId, source, agentId);
DifyConversationListRespVO result = difyClient.getConversations(config.getApiKey(), difyUserId, lastId, limit);
String proLastId = null;
String standardLastId = null;
if (cursor != null && !cursor.isEmpty()) {
try {
String json = new String(Base64.getDecoder().decode(cursor));
com.fasterxml.jackson.databind.JsonNode node = JsonUtils.parseTree(json);
proLastId = node.has("pro") ? node.get("pro").asText(null) : null;
standardLastId = node.has("standard") ? node.get("standard").asText(null) : null;
} catch (Exception e) {
log.warn("[getConversations] 游标解析失败,从头开始: {}", cursor, e);
}
}
List<DifyConversationRespVO> proList = Collections.emptyList();
List<DifyConversationRespVO> standardList = Collections.emptyList();
boolean proHasMore = false;
boolean standardHasMore = false;
try {
DifyConversationListRespVO proResult = difyClient.getConversations(
proConfig.getApiKey(), difyUserId, proLastId, limit);
if (proResult != null && proResult.getData() != null) {
proList = proResult.getData();
proList.forEach(c -> c.setAppSource("pro"));
proHasMore = proResult.getHasMore() != null && proResult.getHasMore();
}
} catch (Exception e) {
log.warn("[getConversations] 查询 Pro 会话列表失败", e);
}
try {
DifyConversationListRespVO standardResult = difyClient.getConversations(
standardConfig.getApiKey(), difyUserId, standardLastId, limit);
if (standardResult != null && standardResult.getData() != null) {
standardList = standardResult.getData();
standardList.forEach(c -> c.setAppSource("standard"));
standardHasMore = standardResult.getHasMore() != null && standardResult.getHasMore();
}
} catch (Exception e) {
log.warn("[getConversations] 查询 Standard 会话列表失败", e);
}
// 合并两个列表,按 updatedAt 降序排序,截取 limit 条
List<DifyConversationRespVO> merged = new ArrayList<>();
merged.addAll(proList);
merged.addAll(standardList);
merged.sort((a, b) -> {
long timeA = a.getUpdatedAt() != null ? a.getUpdatedAt() : (a.getCreatedAt() != null ? a.getCreatedAt() : 0);
long timeB = b.getUpdatedAt() != null ? b.getUpdatedAt() : (b.getCreatedAt() != null ? b.getCreatedAt() : 0);
return Long.compare(timeB, timeA); // 降序
});
// 判断是否有更多数据
boolean hasMore = proHasMore || standardHasMore;
List<DifyConversationRespVO> pageData;
if (merged.size() > limit) {
pageData = new ArrayList<>(merged.subList(0, limit));
hasMore = true;
} else {
pageData = merged;
}
// 过滤掉 inputs 中的敏感字段(如 sysPrompt
if (result != null && result.getData() != null) {
result.getData().forEach(conv -> {
if (conv.getInputs() != null) {
conv.getInputs().remove("sysPrompt");
}
});
}
pageData.forEach(conv -> {
if (conv.getInputs() != null) {
conv.getInputs().remove("sysPrompt");
}
});
// 构建下一页游标:收集当前页中 pro 和 standard 的最后一条记录ID
String nextCursor = buildNextCursor(pageData, proHasMore, standardHasMore);
DifyConversationListRespVO result = new DifyConversationListRespVO();
result.setLimit(limit);
result.setHasMore(hasMore);
result.setData(pageData);
result.setNextCursor(nextCursor);
return result;
}
@Override
public DifyMessageListRespVO getMessages(Long agentId, String conversationId, String userId, String firstId, Integer limit) {
// 获取智能体配置
AiAgentDO agent = aiAgentService.getAiAgent(agentId);
if (agent == null) {
throw new RuntimeException("智能体不存在");
/**
* 构建下一页复合游标
*/
private String buildNextCursor(List<DifyConversationRespVO> pageData,
boolean proHasMore, boolean standardHasMore) {
if (pageData.isEmpty()) return null;
String proLastId = null;
String standardLastId = null;
for (int i = pageData.size() - 1; i >= 0; i--) {
DifyConversationRespVO conv = pageData.get(i);
if ("pro".equals(conv.getAppSource()) && proLastId == null && proHasMore) {
proLastId = conv.getId();
}
if ("standard".equals(conv.getAppSource()) && standardLastId == null && standardHasMore) {
standardLastId = conv.getId();
}
if (proLastId != null && standardLastId != null) break;
}
// 获取积分配置(使用标准模式的 API Key
AiServiceConfigDO config = pointsService.getConfig(
AiPlatformEnum.DIFY.getPlatform(),
AiModelTypeEnum.DIFY_WRITING_STANDARD.getModelCode());
if (proLastId == null && standardLastId == null) return null;
// Dify 用户标识(按 agentId 隔离会话)
String difyUserId = "user-" + userId + "-agent-" + agentId;
try {
Map<String, String> cursorMap = new HashMap<>();
if (proLastId != null) cursorMap.put("pro", proLastId);
if (standardLastId != null) cursorMap.put("standard", standardLastId);
String json = JsonUtils.toJsonString(cursorMap);
return Base64.getEncoder().encodeToString(json.getBytes());
} catch (Exception e) {
log.warn("[buildNextCursor] 构建游标失败", e);
return null;
}
}
DifyMessageListRespVO result = difyClient.getMessages(config.getApiKey(), conversationId, difyUserId, firstId, limit);
@Override
public DifyMessageListRespVO getMessages(Long agentId, String source, String conversationId,
String appSource, String userId, String firstId, Integer limit) {
String difyUserId = buildDifyUserId(userId, source, agentId);
boolean isStandard = "standard".equals(appSource);
AiServiceConfigDO primaryConfig = getDifyConfig(isStandard);
AiServiceConfigDO fallbackConfig = null;
DifyMessageListRespVO result = null;
try {
result = difyClient.getMessages(primaryConfig.getApiKey(), conversationId, difyUserId, firstId, limit);
} catch (Exception e) {
log.warn("[getMessages] 主 Key 查询失败appSource: {}, 尝试降级", appSource, e);
}
if (result == null || result.getData() == null || result.getData().isEmpty()) {
fallbackConfig = getDifyConfig(!isStandard);
try {
DifyMessageListRespVO fallbackResult = difyClient.getMessages(
fallbackConfig.getApiKey(), conversationId, difyUserId, firstId, limit);
if (fallbackResult != null && fallbackResult.getData() != null && !fallbackResult.getData().isEmpty()) {
result = fallbackResult;
}
} catch (Exception e) {
log.warn("[getMessages] 降级 Key 查询也失败", e);
}
}
if (result == null) {
result = new DifyMessageListRespVO();
result.setData(Collections.emptyList());
result.setHasMore(false);
}
// 过滤掉 inputs 中的敏感字段(如 sysPrompt
if (result != null && result.getData() != null) {
if (result.getData() != null) {
result.getData().forEach(msg -> {
if (msg.getInputs() != null) {
msg.getInputs().remove("sysPrompt");
@@ -439,4 +558,18 @@ public class DifyServiceImpl implements DifyService {
return result;
}
private static String resolveScope(String source) {
return "prompt".equals(source) ? "prompt" : "agent";
}
private String buildDifyUserId(String userId, String source, Long agentId) {
return "user-" + userId + "-" + resolveScope(source) + "-" + agentId;
}
private AiServiceConfigDO getDifyConfig(boolean standard) {
return pointsService.getConfig(
AiPlatformEnum.DIFY.getPlatform(),
(standard ? AiModelTypeEnum.DIFY_WRITING_STANDARD : AiModelTypeEnum.DIFY_WRITING_PRO).getModelCode());
}
}

View File

@@ -28,4 +28,7 @@ public class DifyChatReqVO {
@Schema(description = "自定义系统提示词(使用用户自建风格时传入)")
private String customSystemPrompt;
@Schema(description = "来源类型agent-智能体 prompt-自建风格", example = "agent")
private String source;
}

View File

@@ -1,5 +1,6 @@
package cn.iocoder.yudao.module.tik.dify.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -23,4 +24,8 @@ public class DifyConversationListRespVO {
@Schema(description = "会话列表", requiredMode = Schema.RequiredMode.REQUIRED)
private List<DifyConversationRespVO> data;
@Schema(description = "下一页游标Base64 编码的复合游标)")
@JsonProperty("next_cursor")
private String nextCursor;
}

View File

@@ -38,4 +38,8 @@ public class DifyConversationRespVO {
@JsonProperty("updated_at")
private Long updatedAt;
@Schema(description = "来源应用标识pro/standard", example = "pro")
@JsonProperty("app_source")
private String appSource;
}