feat: Add stop session functionality to chat API and UI
- Implemented a new API endpoint to stop ongoing chat sessions, allowing users to cancel message generation. - Enhanced InputField component to include a stop button, enabling users to halt the assistant's response generation. - Updated chat view to manage the assistant message ID and loading state effectively during stop events. - Improved event handling in the backend to support stop events, ensuring proper session management and user feedback.
This commit is contained in:
@@ -46,4 +46,8 @@ export async function delSession(session_id: string) {
|
||||
|
||||
export async function getSession(session_id: string) {
|
||||
return get(`/api/v1/sessions/${session_id}`);
|
||||
}
|
||||
|
||||
export async function stopSession(session_id: string, message_id: string) {
|
||||
return post(`/api/v1/sessions/${session_id}/stop`, { message_id });
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { MessagePlugin } from "tdesign-vue-next";
|
||||
import { useSettingsStore } from '@/stores/settings';
|
||||
import { useUIStore } from '@/stores/ui';
|
||||
import { listKnowledgeBases } from '@/api/knowledge-base';
|
||||
import { stopSession } from '@/api/chat';
|
||||
import KnowledgeBaseSelector from './KnowledgeBaseSelector.vue';
|
||||
|
||||
const route = useRoute();
|
||||
@@ -20,6 +21,14 @@ const props = defineProps({
|
||||
isReplying: {
|
||||
type: Boolean,
|
||||
required: false
|
||||
},
|
||||
sessionId: {
|
||||
type: String,
|
||||
required: false
|
||||
},
|
||||
assistantMessageId: {
|
||||
type: String,
|
||||
required: false
|
||||
}
|
||||
});
|
||||
|
||||
@@ -68,7 +77,7 @@ watch(() => route.params.kbId, (newKbId) => {
|
||||
}
|
||||
});
|
||||
|
||||
const emit = defineEmits(['send-msg']);
|
||||
const emit = defineEmits(['send-msg', 'stop-generation']);
|
||||
|
||||
const createSession = (val: string) => {
|
||||
if (!val.trim()) {
|
||||
@@ -157,6 +166,32 @@ const removeKb = (kbId: string) => {
|
||||
settingsStore.removeKnowledgeBase(kbId);
|
||||
}
|
||||
|
||||
const handleStop = async () => {
|
||||
if (!props.sessionId) {
|
||||
MessagePlugin.warning('会话 ID 不存在');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!props.assistantMessageId) {
|
||||
console.error('[Stop] Assistant message ID is empty');
|
||||
MessagePlugin.warning('无法获取消息 ID,请刷新页面后重试');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[Stop] Stopping generation for message:', props.assistantMessageId);
|
||||
|
||||
// 发送 stop 事件,通知父组件立即清除 loading 状态
|
||||
emit('stop-generation');
|
||||
|
||||
try {
|
||||
await stopSession(props.sessionId, props.assistantMessageId);
|
||||
MessagePlugin.success('已停止生成');
|
||||
} catch (error) {
|
||||
console.error('Failed to stop session:', error);
|
||||
MessagePlugin.error('停止失败,请重试');
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeRouteUpdate((to, from, next) => {
|
||||
clearvalue()
|
||||
next()
|
||||
@@ -248,13 +283,33 @@ onBeforeRouteUpdate((to, from, next) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧发送按钮 -->
|
||||
<!-- 右侧控制按钮组 -->
|
||||
<div class="control-right">
|
||||
<!-- 停止按钮(仅在回复中时显示) -->
|
||||
<t-tooltip
|
||||
v-if="isReplying"
|
||||
content="停止生成"
|
||||
placement="top"
|
||||
>
|
||||
<div
|
||||
@click="handleStop"
|
||||
class="control-btn stop-btn"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
||||
<rect x="5" y="5" width="6" height="6" rx="1" />
|
||||
</svg>
|
||||
</div>
|
||||
</t-tooltip>
|
||||
|
||||
<!-- 发送按钮 -->
|
||||
<div
|
||||
v-if="!isReplying"
|
||||
@click="createSession(query)"
|
||||
class="control-btn send-btn"
|
||||
:class="{ 'disabled': !query.length || selectedKbIds.length === 0 }"
|
||||
>
|
||||
<img src="../assets/img/sending-aircraft.svg" alt="发送" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -492,6 +547,104 @@ const getImgSrc = (url: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
.control-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.stop-btn {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
background: rgba(7, 192, 95, 0.08);
|
||||
color: #07C05F;
|
||||
border: 1.5px solid rgba(7, 192, 95, 0.2);
|
||||
position: relative;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: stopBtnPulse 2s ease-in-out infinite;
|
||||
|
||||
&:hover {
|
||||
background: rgba(7, 192, 95, 0.12);
|
||||
border-color: #07C05F;
|
||||
transform: scale(1.05);
|
||||
box-shadow: 0 2px 4px rgba(7, 192, 95, 0.2);
|
||||
animation: none;
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: scale(0.95);
|
||||
background: rgba(7, 192, 95, 0.15);
|
||||
}
|
||||
|
||||
svg {
|
||||
display: none;
|
||||
}
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
background: #07C05F;
|
||||
border-radius: 50%;
|
||||
display: block;
|
||||
animation: stopDotPulse 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
&:hover::before {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid #07C05F;
|
||||
animation: stopRipple 2s ease-out infinite;
|
||||
}
|
||||
|
||||
&:hover::after {
|
||||
animation: none;
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes stopBtnPulse {
|
||||
0%, 100% {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
50% {
|
||||
box-shadow: 0 2px 4px rgba(7, 192, 95, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes stopDotPulse {
|
||||
0%, 100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
transform: scale(0.92);
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes stopRipple {
|
||||
0% {
|
||||
transform: scale(0.9);
|
||||
opacity: 0.4;
|
||||
}
|
||||
100% {
|
||||
transform: scale(2);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.send-btn {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
|
||||
@@ -175,7 +175,7 @@ const isLastThinking = (eventId: string): boolean => {
|
||||
return eventId === lastThinkingEventId.value;
|
||||
};
|
||||
|
||||
// Check if conversation is done (based on answer event with done=true)
|
||||
// Check if conversation is done (based on answer event with done=true or stop event)
|
||||
const isConversationDone = computed(() => {
|
||||
const stream = eventStream.value;
|
||||
if (!stream || stream.length === 0) {
|
||||
@@ -183,7 +183,14 @@ const isConversationDone = computed(() => {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only check for answer event with done=true
|
||||
// Check for stop event (user cancelled)
|
||||
const stopEvent = stream.find((e: any) => e.type === 'stop');
|
||||
if (stopEvent) {
|
||||
console.log('[Collapse] Found stop event, conversation done');
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for answer event with done=true
|
||||
const answerEvents = stream.filter((e: any) => e.type === 'answer');
|
||||
const doneAnswer = answerEvents.find((e: any) => e.done === true);
|
||||
|
||||
|
||||
@@ -18,7 +18,13 @@
|
||||
</div>
|
||||
</div>
|
||||
<div style="min-height: 115px; margin: 16px auto 4px;width: 100%;max-width: 800px;">
|
||||
<InputField @send-msg="sendMsg" :isReplying="isReplying"></InputField>
|
||||
<InputField
|
||||
@send-msg="sendMsg"
|
||||
@stop-generation="handleStopGeneration"
|
||||
:isReplying="isReplying"
|
||||
:sessionId="session_id"
|
||||
:assistantMessageId="currentAssistantMessageId"
|
||||
></InputField>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -46,6 +52,7 @@ const created_at = ref('');
|
||||
const limit = ref(20);
|
||||
const messagesList = reactive([]);
|
||||
const isReplying = ref(false);
|
||||
const currentAssistantMessageId = ref(''); // 当前正在生成的 assistant message ID
|
||||
const scrollLock = ref(false);
|
||||
const isNeedTitle = ref(false);
|
||||
const isFirstEnter = ref(true);
|
||||
@@ -208,7 +215,13 @@ const handleMsgList = async (data, isScrollType = false, newScrollHeight) => {
|
||||
}
|
||||
if (messagesList[messagesList.length - 1] && !messagesList[messagesList.length - 1].is_completed) {
|
||||
isReplying.value = true;
|
||||
await startStream({ session_id: session_id.value, query: messagesList[messagesList.length - 1].id, method: 'GET', url: '/api/v1/sessions/continue-stream' });
|
||||
// 保存正在 stream 的消息 ID,以便停止时使用
|
||||
const lastMessage = messagesList[messagesList.length - 1];
|
||||
if (lastMessage.role === 'assistant') {
|
||||
currentAssistantMessageId.value = lastMessage.id;
|
||||
console.log('[Continue Stream] Set assistant message ID:', lastMessage.id);
|
||||
}
|
||||
await startStream({ session_id: session_id.value, query: lastMessage.id, method: 'GET', url: '/api/v1/sessions/continue-stream' });
|
||||
}
|
||||
|
||||
}
|
||||
@@ -220,6 +233,15 @@ const checkmenuTitle = (session_id) => {
|
||||
});
|
||||
}
|
||||
// 发送消息
|
||||
// 处理停止生成事件 - 立即清除 loading 状态
|
||||
const handleStopGeneration = () => {
|
||||
console.log('[Stop Generation] Immediately clearing loading state');
|
||||
loading.value = false;
|
||||
isReplying.value = false;
|
||||
// 注意:不在这里清空 currentAssistantMessageId,因为需要它来调用 API
|
||||
// API 调用成功后,后端的 stop 事件会清空它
|
||||
};
|
||||
|
||||
const sendMsg = async (value) => {
|
||||
userquery.value = value;
|
||||
isReplying.value = true;
|
||||
@@ -238,6 +260,8 @@ const sendMsg = async (value) => {
|
||||
MessagePlugin.warning('请至少选择一个知识库');
|
||||
isReplying.value = false;
|
||||
loading.value = false;
|
||||
// 清空当前 assistant message ID
|
||||
currentAssistantMessageId.value = '';
|
||||
// Remove the user message that was just added
|
||||
messagesList.pop();
|
||||
return;
|
||||
@@ -262,6 +286,8 @@ watch(error, (newError) => {
|
||||
MessagePlugin.error(newError);
|
||||
isReplying.value = false;
|
||||
loading.value = false;
|
||||
// 清空当前 assistant message ID
|
||||
currentAssistantMessageId.value = '';
|
||||
}
|
||||
});
|
||||
|
||||
@@ -274,13 +300,20 @@ onChunk((data) => {
|
||||
done: data.done,
|
||||
content_length: data.content?.length || 0,
|
||||
content_preview: data.content ? data.content.substring(0, 50) : '',
|
||||
data: data.data
|
||||
data: data.data,
|
||||
session_id: data.session_id,
|
||||
assistant_message_id: data.assistant_message_id
|
||||
});
|
||||
|
||||
// 处理 agent query 事件 - 保持 loading 状态
|
||||
// 处理 agent query 事件 - 保存 assistant message ID 并保持 loading 状态
|
||||
if (data.response_type === 'agent_query') {
|
||||
if (data.assistant_message_id) {
|
||||
currentAssistantMessageId.value = data.assistant_message_id;
|
||||
console.log('[Agent Query] Saved assistant message ID:', data.assistant_message_id);
|
||||
}
|
||||
console.log('[Agent Query Event]', {
|
||||
session_id: data.data?.session_id,
|
||||
session_id: data.session_id || data.data?.session_id,
|
||||
assistant_message_id: data.assistant_message_id,
|
||||
query: data.data?.query,
|
||||
request_id: data.data?.request_id
|
||||
});
|
||||
@@ -308,12 +341,22 @@ onChunk((data) => {
|
||||
// 判断是否是 Agent 模式的响应
|
||||
const isAgentResponse = data.response_type === 'thinking' ||
|
||||
data.response_type === 'tool_call' ||
|
||||
data.response_type === 'references';
|
||||
data.response_type === 'references' ||
|
||||
data.response_type === 'stop';
|
||||
|
||||
// Agent 模式处理
|
||||
// Agent 模式处理(包括 stop 事件)
|
||||
if (isAgentResponse || messagesList[messagesList.length - 1]?.isAgentMode) {
|
||||
// 在 handleAgentChunk 中处理 loading 状态
|
||||
handleAgentChunk(data);
|
||||
|
||||
// 对于 stop 事件,额外处理全局状态
|
||||
if (data.response_type === 'stop') {
|
||||
console.log('[Stop Event] Generation stopped');
|
||||
loading.value = false;
|
||||
isReplying.value = false;
|
||||
// 清空当前 assistant message ID
|
||||
currentAssistantMessageId.value = '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -352,6 +395,8 @@ onChunk((data) => {
|
||||
// 如果标题还未生成,前端会通过 SSE 事件接收
|
||||
isReplying.value = false;
|
||||
fullContent.value = "";
|
||||
// 清空当前 assistant message ID
|
||||
currentAssistantMessageId.value = '';
|
||||
}
|
||||
updateAssistantSession(obj);
|
||||
})
|
||||
@@ -566,11 +611,30 @@ const handleAgentChunk = (data) => {
|
||||
// 完成
|
||||
isReplying.value = false;
|
||||
fullContent.value = '';
|
||||
// 清空当前 assistant message ID
|
||||
currentAssistantMessageId.value = '';
|
||||
|
||||
// 标题生成已改为异步事件推送,不再需要在这里手动调用
|
||||
// 如果标题还未生成,前端会通过 SSE 事件接收
|
||||
}
|
||||
break;
|
||||
|
||||
case 'stop':
|
||||
// 停止事件 - 添加到事件流并标记对话完成
|
||||
console.log('[Agent] Stop event received');
|
||||
if (!message.agentEventStream) message.agentEventStream = [];
|
||||
|
||||
// Add stop event to stream
|
||||
message.agentEventStream.push({
|
||||
type: 'stop',
|
||||
timestamp: Date.now(),
|
||||
reason: data.data?.reason || 'user_requested'
|
||||
});
|
||||
|
||||
// Mark conversation as stopped
|
||||
isReplying.value = false;
|
||||
fullContent.value = '';
|
||||
break;
|
||||
}
|
||||
|
||||
scrollToBottom();
|
||||
|
||||
Reference in New Issue
Block a user