feat(chat): add request info button and debug payload for stream requests

- Introduced a new `ChatRequestInfoButton` component to display detailed request information for chat sessions.
- Enhanced the `useStream` function to track the last stream request, including request ID, URL, method, and sanitized body.
- Updated localization files to include new strings for request information in both English and Chinese.
- Integrated the request info button into the chat interface, allowing users to easily access and copy request details.
- Improved handling of stream requests by attaching debug information to messages for better tracking and debugging.
This commit is contained in:
wizardchen
2026-06-03 15:23:34 +08:00
committed by lyingbug
parent 362bc7f6e5
commit bd1a764a91
8 changed files with 333 additions and 4 deletions
+14
View File
@@ -3,6 +3,10 @@ import { ref, onUnmounted } from 'vue';
import { generateRandomString } from '@/utils/index';
import i18n from '@/i18n';
import { getApiBaseUrl } from '@/utils/api-base';
import {
sanitizeStreamRequestBody,
type StreamRequestMeta,
} from '@/utils/chatRequestDebug';
@@ -23,6 +27,7 @@ export function useStream() {
const isStreaming = ref(false) // 流状态
const isLoading = ref(false) // 初始加载
const error = ref<string | null>(null)// 错误信息
const lastStreamRequest = ref<StreamRequestMeta | null>(null)
let controller = new AbortController()
// 流式渲染缓冲
@@ -128,6 +133,14 @@ export function useStream() {
postBody.attachment_uploads = params.attachment_uploads;
}
postBody.channel = "web";
lastStreamRequest.value = {
requestId: requestID,
url,
method: params.method,
body: params.method === 'POST' ? sanitizeStreamRequestBody(postBody) : null,
sentAt: Date.now(),
};
await fetchEventSource(url, {
method: params.method,
@@ -204,6 +217,7 @@ export function useStream() {
isStreaming, // 是否在流式传输中
isLoading, // 初始连接状态
error,
lastStreamRequest,
onChunk,
startStream, // 启动流
stopStream // 手动停止
@@ -0,0 +1,176 @@
<template>
<t-popup
v-model:visible="visible"
trigger="click"
placement="top"
:show-arrow="true"
destroy-on-close
overlay-class-name="chat-request-info-popup"
:overlay-inner-style="{ padding: 0 }"
>
<t-button
size="small"
variant="outline"
shape="round"
:title="$t('chat.requestInfoTitle')"
>
<t-icon name="bug" />
</t-button>
<template #content>
<div class="chat-request-card" @click.stop>
<div class="chat-request-card-header">
<span class="chat-request-card-title">{{ $t('chat.requestInfoTitle') }}</span>
<t-button
v-if="rows.length > 0"
size="small"
variant="text"
shape="square"
:title="$t('common.copy')"
@click="copyAll"
>
<t-icon name="copy" />
</t-button>
</div>
<div v-if="rows.length === 0" class="chat-request-empty">
{{ $t('chat.requestInfoEmpty') }}
</div>
<div v-else class="chat-request-card-body">
<div v-for="row in rows" :key="row.key" class="chat-request-row">
<span class="chat-request-label">{{ row.label }}</span>
<span class="chat-request-value">{{ row.value }}</span>
</div>
</div>
</div>
</template>
</t-popup>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { MessagePlugin } from 'tdesign-vue-next';
import {
buildChatRequestDebugPayload,
type ChatRequestDebugInfo,
} from '@/utils/chatRequestDebug';
import { copyTextToClipboard } from '@/utils/chatMessageShared';
const props = defineProps<{
session: Record<string, unknown>;
sessionId?: string;
}>();
const { t } = useI18n();
const visible = ref(false);
const debugInfo = computed((): ChatRequestDebugInfo => {
const s = props.session;
const dr = s.debugRequest as ChatRequestDebugInfo | undefined;
return {
requestId: (s.request_id as string) || dr?.requestId,
messageId: (s.id as string) || undefined,
sessionId: props.sessionId || dr?.sessionId,
url: dr?.url,
method: dr?.method,
body: dr?.body ?? null,
sentAt: dr?.sentAt,
};
});
const rows = computed(() => {
const info = debugInfo.value;
const list: { key: string; label: string; value: string }[] = [];
const add = (key: string, labelKey: string, val?: string) => {
if (!val) return;
list.push({ key, label: t(labelKey), value: val });
};
add('requestId', 'chat.requestInfoRequestId', info.requestId);
add('messageId', 'chat.requestInfoMessageId', info.messageId);
add('sessionId', 'chat.requestInfoSessionId', info.sessionId);
if (info.method && info.url) {
list.push({ key: 'url', label: t('chat.requestInfoUrl'), value: `${info.method} ${info.url}` });
}
if (info.sentAt) {
add('sentAt', 'chat.requestInfoSentAt', new Date(info.sentAt).toLocaleString());
}
return list;
});
const copyAll = async () => {
try {
await copyTextToClipboard(buildChatRequestDebugPayload(debugInfo.value));
MessagePlugin.success(t('common.copied'));
visible.value = false;
} catch {
MessagePlugin.error(t('common.copyFailed'));
}
};
</script>
<style lang="less">
.chat-request-info-popup {
.t-popup__content {
padding: 0;
border-radius: 8px;
box-shadow: var(--td-shadow-2);
}
}
</style>
<style scoped lang="less">
.chat-request-card {
min-width: 260px;
max-width: 360px;
padding: 10px 12px;
font-size: 12px;
color: var(--td-text-color-primary);
}
.chat-request-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 8px;
padding-bottom: 6px;
border-bottom: 1px solid var(--td-component-stroke);
}
.chat-request-card-title {
font-size: 12px;
font-weight: 600;
}
.chat-request-card-body {
display: flex;
flex-direction: column;
gap: 2px;
}
.chat-request-row {
display: flex;
align-items: flex-start;
gap: 8px;
padding: 3px 0;
line-height: 1.5;
}
.chat-request-label {
flex: 0 0 72px;
color: var(--td-text-color-secondary);
}
.chat-request-value {
flex: 1;
font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: 11px;
color: var(--td-text-color-primary);
word-break: break-all;
}
.chat-request-empty {
color: var(--td-text-color-placeholder);
padding: 4px 0 8px;
}
</style>
+7
View File
@@ -2682,6 +2682,13 @@ export default {
referencesDocAndWebCount: 'Referenced {docCount} document(s) and {webCount} web page(s)',
referenceChunkCount: '{count} chunk(s)',
fallbackHint: 'No relevant content found in knowledge base. Above is a direct response from the model.',
requestInfoTitle: 'Request info',
requestInfoRequestId: 'Request ID',
requestInfoMessageId: 'Message ID',
requestInfoSessionId: 'Session ID',
requestInfoUrl: 'Request',
requestInfoSentAt: 'Sent at',
requestInfoEmpty: 'No request info available',
channelWeb: 'Web',
channelApi: 'API',
channelIm: 'IM',
+7
View File
@@ -791,6 +791,13 @@ export default {
referencesDocAndWebCount: "引用了{docCount}篇文档和{webCount}条网页",
referenceChunkCount: "{count}个片段",
fallbackHint: "未从知识库中检索到相关内容,以上为模型直接回答",
requestInfoTitle: "请求信息",
requestInfoRequestId: "Request ID",
requestInfoMessageId: "消息 ID",
requestInfoSessionId: "会话 ID",
requestInfoUrl: "请求",
requestInfoSentAt: "发起时间",
requestInfoEmpty: "暂无请求信息",
channelWeb: "网页",
channelApi: "API",
channelIm: "IM",
+46
View File
@@ -0,0 +1,46 @@
/** Sanitize stream POST body for display (strip large base64 payloads). */
export function sanitizeStreamRequestBody(body: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = { ...body };
if (Array.isArray(out.images)) {
out.images = out.images.map((img: { data?: string }, i: number) => ({
_placeholder: `image[${i}]`,
bytes: typeof img?.data === 'string' ? img.data.length : 0,
}));
}
if (Array.isArray(out.attachment_uploads)) {
out.attachment_uploads = out.attachment_uploads.map(
(att: { file_name?: string; file_size?: number; data?: string }, i: number) => ({
file_name: att.file_name,
file_size: att.file_size,
_placeholder: `attachment[${i}]`,
bytes: typeof att?.data === 'string' ? att.data.length : 0,
}),
);
}
if (typeof out.query === 'string' && out.query.length > 500) {
out.query = `${out.query.slice(0, 500)}… (${out.query.length} chars)`;
}
return out;
}
export interface StreamRequestMeta {
requestId: string;
url: string;
method: string;
body: Record<string, unknown> | null;
sentAt: number;
}
export interface ChatRequestDebugInfo {
requestId?: string;
messageId?: string;
sessionId?: string;
url?: string;
method?: string;
body?: Record<string, unknown> | null;
sentAt?: number;
}
export function buildChatRequestDebugPayload(info: ChatRequestDebugInfo): string {
return JSON.stringify(info, null, 2);
}
@@ -330,6 +330,9 @@
</div>
</div>
</template>
<div v-if="showRequestInfo && isConversationDone" class="answer-toolbar">
<ChatRequestInfoButton :session="session" :session-id="sessionId" />
</div>
<!-- Loading Indicator (inside container so it scrolls into view) -->
<div v-if="!isConversationDone && eventStream.length > 0" class="loading-indicator">
<div class="loading-typing">
@@ -408,6 +411,7 @@ import 'katex/dist/katex.min.css';
import DOMPurify from 'dompurify';
import ToolResultRenderer from './ToolResultRenderer.vue';
import ToolApprovalCard from './ToolApprovalCard.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import picturePreview from '@/components/picture-preview.vue';
import { getChunkByIdOnly } from '@/api/knowledge-base';
import { getRootZoom, rectToCssPx } from '@/utils/zoom';
@@ -764,6 +768,9 @@ import fileAddIcon from '@/assets/img/file-add-green.svg';
import webSearchGlobeGreenIcon from '@/assets/img/websearch-globe-green.svg';
interface SessionData {
id?: string;
request_id?: string;
debugRequest?: Record<string, unknown>;
isAgentMode?: boolean;
agentEventStream?: any[];
knowledge_references?: any[];
@@ -771,9 +778,12 @@ interface SessionData {
const props = defineProps<{
session: SessionData;
sessionId?: string;
userQuery?: string;
}>();
const showRequestInfo = computed(() => !!(props.session?.request_id || props.session?.id));
// Configure marked for security
marked.use({});
marked.use(markedKatex({ throwOnError: false, nonStandard: true }));
+13 -1
View File
@@ -19,7 +19,7 @@
</span>
</div>
<docInfo :session="session"></docInfo>
<AgentStreamDisplay :session="session" :user-query="userQuery" v-if="session.isAgentMode"></AgentStreamDisplay>
<AgentStreamDisplay :session="session" :session-id="sessionId" :user-query="userQuery" v-if="session.isAgentMode"></AgentStreamDisplay>
<deepThink :deepSession="session" v-if="session.showThink && !session.isAgentMode"></deepThink>
</div>
<!-- 非 Agent 模式下才显示传统的 markdown 渲染 -->
@@ -52,6 +52,11 @@
<t-icon name="info-circle" />
</t-button>
</t-tooltip>
<ChatRequestInfoButton
v-if="showRequestInfo"
:session="session"
:session-id="sessionId"
/>
</div>
<div v-if="isImgLoading" class="img_loading"><t-loading size="small"></t-loading><span>{{ $t('common.loading') }}</span></div>
</div>
@@ -66,6 +71,7 @@ import 'katex/dist/katex.min.css';
import docInfo from './docInfo.vue';
import deepThink from './deepThink.vue';
import AgentStreamDisplay from './AgentStreamDisplay.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import picturePreview from '@/components/picture-preview.vue';
import { sanitizeHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages } from '@/utils/security';
import { useI18n } from 'vue-i18n';
@@ -130,9 +136,15 @@ const props = defineProps({
embeddedMode: {
type: Boolean,
default: false
},
sessionId: {
type: String,
default: ''
}
});
const showRequestInfo = computed(() => !!(props.session?.request_id || props.session?.id));
const preview = (url) => {
nextTick(() => {
reviewUrl.value = url;
+60 -3
View File
@@ -63,7 +63,8 @@
<usermsg :content="session.content" :mentioned_items="session.mentioned_items" :images="session.images" :attachments="session.attachments" :embeddedMode="embeddedMode"></usermsg>
</div>
<div v-if="session.role == 'assistant'">
<botmsg :content="session.content" :session="session" :user-query="getUserQuery(index)" @scroll-bottom="scrollToBottom"
<botmsg :content="session.content" :session="session" :session-id="session_id"
:user-query="getUserQuery(index)" @scroll-bottom="scrollToBottom"
:isFirstEnter="isFirstEnter" :embeddedMode="embeddedMode"></botmsg>
</div>
</div>
@@ -134,7 +135,32 @@ const uiStore = useUIStore();
const { navigateToKnowledgeBaseList } = useKnowledgeBaseCreationNavigation();
const { t } = useI18n();
const { menuArr, isFirstSession, firstQuery, firstMentionedItems, firstModelId, firstImageFiles, firstAttachmentFiles } = storeToRefs(usemenuStore);
const { output, onChunk, isStreaming, isLoading, error, startStream, stopStream } = useStream();
const { output, onChunk, isStreaming, isLoading, error, startStream, stopStream, lastStreamRequest } = useStream();
/** Snapshot of the in-flight HTTP request for attaching to the next assistant message. */
const pendingStreamDebug = ref(null);
const buildStreamDebugPayload = () => {
const meta = lastStreamRequest.value;
if (!meta) return null;
return {
requestId: meta.requestId,
url: meta.url,
method: meta.method,
body: meta.body,
sentAt: meta.sentAt,
sessionId: session_id.value,
};
};
const attachStreamDebugToMessage = (message) => {
if (!message) return;
const payload = pendingStreamDebug.value || buildStreamDebugPayload();
if (!payload) return;
if (payload.requestId && !message.request_id) {
message.request_id = payload.requestId;
}
message.debugRequest = payload;
};
const route = useRoute();
const router = useRouter();
const session_id = ref(props.session_id || route.params.chatid);
@@ -742,6 +768,14 @@ onChunk((data) => {
// 处理 agent query 事件 - 保存 assistant message ID 并保持 loading 状态
if (data.response_type === 'agent_query') {
pendingStreamDebug.value = buildStreamDebugPayload();
if (data.id) {
const earlyMsg = findLastMessage((item) => item.role === 'assistant' && !item.is_completed);
if (earlyMsg) {
earlyMsg.request_id = data.id;
attachStreamDebugToMessage(earlyMsg);
}
}
if (data.assistant_message_id) {
currentAssistantMessageId.value = data.assistant_message_id;
console.log('[Agent Query] Saved assistant message ID:', data.assistant_message_id);
@@ -821,6 +855,7 @@ onChunk((data) => {
knowledge_references: []
};
messagesList.push(existingMessage);
attachStreamDebugToMessage(existingMessage);
loading.value = false; // 消息已创建,关闭 loading
scrollToBottom(true);
}
@@ -941,10 +976,15 @@ const handleAgentChunk = (data) => {
knowledge_references: []
};
messagesList.push(newMsg);
attachStreamDebugToMessage(newMsg);
pendingStreamDebug.value = null;
loading.value = false; // 消息已创建,关闭 loading
scrollToBottom(true);
// Don't return - continue to process the current event data
message = newMsg;
} else {
attachStreamDebugToMessage(message);
pendingStreamDebug.value = null;
}
message.isAgentMode = true;
@@ -1233,6 +1273,8 @@ const handleAgentChunk = (data) => {
if (data.done && !answerEvent.done) {
answerEvent.done = true;
console.log('[Agent] Answer done, content length:', message.content?.length || 0, 'answerEvent.content length:', answerEvent.content?.length || 0);
attachStreamDebugToMessage(message);
pendingStreamDebug.value = null;
// 完成 - 关闭所有状态
loading.value = false;
@@ -1295,6 +1337,9 @@ const updateAssistantSession = (payload) => {
return item.id === payload.id;
});
if (message) {
if (payload.id && !message.request_id) {
message.request_id = payload.id;
}
message.content = payload.content;
message.thinking = payload.thinking;
message.thinkContent = payload.thinkContent;
@@ -1308,8 +1353,20 @@ const updateAssistantSession = (payload) => {
if (payload.is_completed) {
message.is_completed = true;
}
attachStreamDebugToMessage(message);
if (payload.is_completed) {
pendingStreamDebug.value = null;
}
} else {
messagesList.push(payload);
const entry = { ...payload };
if (entry.id && !entry.request_id) {
entry.request_id = entry.id;
}
messagesList.push(entry);
attachStreamDebugToMessage(entry);
if (payload.is_completed) {
pendingStreamDebug.value = null;
}
}
scrollToBottom();
}