Files
syops/frontend/src/features/chat/composables/useChatSessions.ts
T

238 lines
8.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* features/chat/composables/useChatSessions.ts
* 单 Agent 侧栏会话历史:服务端列表加载、进行中 run 合并展示、选中/删除/清空。
*/
import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';
import {
deleteAllChatSessions,
deleteChatSession,
listChatSessions,
} from '../api/chat.api';
import { listWorkspaceShippingOrderExtractionRuns } from '../api/shipping.api';
import type { ChatRun, ChatSessionItem, DisplayHistoryItem } from '../types/chat.types';
import type { ChatDeps } from './chat.deps';
import { useChatStore } from '../stores/chat.store';
export interface UseChatSessionsOptions {
deps: ChatDeps;
currentAgentId: ComputedRef<number>;
conversationId: Ref<string | null>;
activeRunId: Ref<number | null>;
runs: Ref<ChatRun[]>;
activateRun: (runId: number) => void;
/** 延迟绑定:ChatView 中 loadConversation 在 composable 初始化之后才赋值 */
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
isSidebarOpen: Ref<boolean>;
/** 删除确认弹窗(由 ChatView 提供) */
onConfirmDelete: (message: string, action: () => Promise<void> | void) => void;
/** 新建对话:清空视图并同步路由 query */
startNewChat: () => void;
}
export function useChatSessions(options: UseChatSessionsOptions) {
const {
deps: { t, router, route },
currentAgentId,
conversationId,
activeRunId,
runs,
activateRun,
loadConversation,
isSidebarOpen,
onConfirmDelete,
startNewChat,
} = options;
const chatStore = useChatStore();
// ── 服务端会话列表 ────────────────────────────────────────
const history = ref<ChatSessionItem[]>([]);
const hydrateHistoryFromStore = (agentId: number) => {
const cached = chatStore.getSessionHistory(agentId);
history.value = cached ? [...cached] : [];
};
const loadHistory = async () => {
const agentId = currentAgentId.value;
if (!agentId) return;
hydrateHistoryFromStore(agentId);
try {
const items = await listChatSessions(agentId);
history.value = items;
chatStore.setSessionHistory(agentId, items);
} catch (e) {
console.error('Failed to load history', e);
}
};
/** Agent 切换时先展示该 Agent 的缓存列表 */
const clearHistory = () => {
const agentId = currentAgentId.value;
if (agentId) {
hydrateHistoryFromStore(agentId);
return;
}
history.value = [];
};
// ── 展示列表:合并进行中 run 与服务端记录 ─────────────────
const activeHistoryKey = computed(() => {
if (conversationId.value) return conversationId.value;
if (activeRunId.value) return `pending:${activeRunId.value}`;
return '';
});
const displayHistory = computed<DisplayHistoryItem[]>(() => {
const server = history.value || [];
const serverIds = new Set(server.map((h) => h.conversation_id));
const pending: DisplayHistoryItem[] = (runs.value || [])
.filter((r) => r.agentId === currentAgentId.value)
.filter((r) => r.status === 'running')
.filter((r) => r.runId !== activeRunId.value)
.map((r) => ({
id: 0,
conversation_id: r.conversationId || `pending:${r.runId}`,
title: (r.query || '').trim(),
created_at: r.createdAt,
__runId: r.runId,
__status: r.status,
}))
.filter((item) => item.conversation_id.startsWith('pending:') || !serverIds.has(item.conversation_id));
const merged = [...pending, ...server] as DisplayHistoryItem[];
merged.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')));
return merged;
});
// ── 选中会话:优先恢复 run,否则拉取消息并同步路由 ───────
const handleHistorySelect = async (item: DisplayHistoryItem) => {
if (item.__runId) {
activateRun(item.__runId);
isSidebarOpen.value = false;
return;
}
const run = runs.value.find(
(r) => r.agentId === currentAgentId.value && r.conversationId === item.conversation_id,
);
if (run && run.status === 'running') {
activateRun(run.runId);
isSidebarOpen.value = false;
return;
}
isSidebarOpen.value = false;
if (item.conversation_id.startsWith('pending:')) return;
const currentConvId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
if (currentConvId === item.conversation_id) {
if (conversationId.value !== item.conversation_id || activeRunId.value) {
await loadConversation(item.conversation_id, { force: true });
}
return;
}
const isOrderReview = route.query.mode === 'order-review';
if (isOrderReview) {
// 复核工作台的 Run/Case/文档上下文属于旧会话,切换时必须整体重建,不能只替换 conversation_id。
const restored = await listWorkspaceShippingOrderExtractionRuns(item.conversation_id, 20);
const nextRun = (restored.items || []).find((candidate) =>
['review_required', 'partially_completed'].includes(String(candidate.status || '')),
);
const nextQuery: Record<string, string> = { conversation_id: item.conversation_id };
if (nextRun?.run_no) {
nextQuery.mode = 'order-review';
nextQuery.run_no = String(nextRun.run_no);
}
await router.replace({ path: route.path, query: nextQuery });
return;
}
const nextQuery: Record<string, string | string[]> = { ...route.query, conversation_id: item.conversation_id };
delete nextQuery.task_id;
delete nextQuery.preset;
await router.replace({ path: route.path, query: nextQuery });
};
// ── 发送后 / 新会话 ID:按需刷新侧栏 ─────────────────────
const refreshHistoryAfterSend = async () => {
if (!conversationId.value && history.value.length === 0) {
await loadHistory();
return;
}
if (conversationId.value) {
const exists = history.value.some((h) => h.conversation_id === conversationId.value);
if (!exists) await loadHistory();
}
};
const setupConversationIdHistoryWatch = () =>
watch(
() => conversationId.value,
async (id, prev) => {
if (!id || id === prev) return;
const exists = history.value.some((item) => item.conversation_id === id);
if (!exists) {
await loadHistory();
}
},
);
// ── 删除单条 / 清空全部 ───────────────────────────────────
/**
* 清空当前 Agent 的全部会话历史,并回到干净的新会话视图。
*
* 核心逻辑:服务端删除成功后同步清空本地 history/run 缓存,并始终触发 `startNewChat`;
* 这样即使当前页面没有 `conversationId`,也能把发货通知顶部进度条等会话外残留 UI 一并复位。
*/
const clearAllHistory = async () => {
onConfirmDelete(t('chat.confirmClearHistory'), async () => {
try {
const agentId = currentAgentId.value;
await deleteAllChatSessions(agentId);
history.value = [];
chatStore.setSessionHistory(agentId, []);
runs.value = [];
startNewChat();
} catch (e) {
console.error('Failed to clear history', e);
}
});
};
const deleteHistoryItem = async (id: string, event: Event) => {
event.stopPropagation();
onConfirmDelete(t('chat.confirmDeleteHistoryItem'), async () => {
try {
const agentId = currentAgentId.value;
await deleteChatSession(id, agentId);
history.value = history.value.filter((h) => h.conversation_id !== id);
chatStore.patchSessionHistory(agentId, history.value);
runs.value = runs.value.filter(
(r) => !(r.agentId === currentAgentId.value && r.conversationId === id),
);
if (conversationId.value === id) {
startNewChat();
}
} catch (e) {
console.error('Failed to delete history item', e);
}
});
};
return {
history,
loadHistory,
clearHistory,
displayHistory,
activeHistoryKey,
handleHistorySelect,
refreshHistoryAfterSend,
setupConversationIdHistoryWatch,
clearAllHistory,
deleteHistoryItem,
};
}