refactor(chat + workspace): chat和workspace重构,子路由、懒加载等

This commit is contained in:
sophie committed 2026-06-10 16:39:05 +08:00
1 parent 0a647a0b79
commit 1f1f7236b0
57 files changed
+4356 -3798

No files matched your search

@@ -0,0 +1,75 @@
/**
* features/chat/api/chat.api.ts
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
*/
import { getAuthHeaders } from '@/utils/auth';
import { requestJson } from '@/api/client';
import type {
ChatCrossAgentHistoryItem,
ChatMessage,
ChatSessionItem,
ChatSourceFileResult,
ChatUploadResult,
OaEmployeesResponse,
} from '../types/chat.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
export const listChatSessions = (agentId: number) =>
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
export const deleteAllChatSessions = (agentId: number) =>
requestJson(`/api/chat/sessions?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
export const deleteChatSession = (conversationId: string, agentId: number) =>
requestJson(`/api/chat/sessions/${conversationId}?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
export const listChatMessages = (conversationId: string, agentId: number) =>
requestJson<ChatMessage[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(payload),
});
export const resolveChatSourceFile = (params: {
agent_id: number;
dataset_id: string;
remote_document_id: string;
}) => {
const qs = new URLSearchParams({
agent_id: String(params.agent_id),
dataset_id: params.dataset_id,
remote_document_id: params.remote_document_id,
});
return requestJson<ChatSourceFileResult>(`/api/chat/source-file?${qs.toString()}`, auth());
};
export const listOaEmployees = (
agentId: number,
query: { keyword?: string; page?: number; page_size?: number },
) => {
const qs = new URLSearchParams({
agent_id: String(agentId),
keyword: query.keyword || '',
page: String(query.page ?? 1),
page_size: String(query.page_size ?? 20),
});
return requestJson<OaEmployeesResponse>(`/api/chat/oa/employees?${qs.toString()}`, auth());
};
export const uploadChatFile = (agentId: number, file: File) => {
const qs = new URLSearchParams({ agent_id: String(agentId) });
const fd = new FormData();
fd.append('file', file);
return requestJson<ChatUploadResult>(`/api/chat/files/upload?${qs.toString()}`, {
method: 'POST',
body: fd,
headers: getAuthHeaders(),
});
};
export type { ChatSessionItem, ChatCrossAgentHistoryItem };
@@ -0,0 +1,16 @@
/**
* features/chat/composables/chat.deps.ts
* 聊天 composables 共享依赖。
*/
import type { WritableComputedRef } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import type { useMessage } from '@/composables/useMessage';
export interface ChatDeps {
t: ComposerTranslation;
locale: WritableComputedRef<string>;
msg: ReturnType<typeof useMessage>;
router: Router;
route: RouteLocationNormalizedLoaded;
}
@@ -0,0 +1,292 @@
/**
* features/chat/composables/useChat.ts
* SSE 流式对话核心:消息列表、runs、发送与接收。
*/
import { ref } from 'vue';
import { getAuthHeaders } from '@/utils/auth';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
const normalizeResources = (resources: unknown) => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
if (typeof resources === 'object' && resources !== null && Array.isArray((resources as { data?: unknown }).data)) {
return (resources as { data: unknown[] }).data;
}
return [];
};
const addRetrieverResources = (msg: ChatMessage, resources: unknown) => {
const list = normalizeResources(resources);
if (list.length === 0) return;
if (!msg.retriever_resources) msg.retriever_resources = [];
for (const item of list) {
const r = item as Record<string, unknown>;
const key = `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}`;
const existingIndex = msg.retriever_resources.findIndex(
(x) => `${x.document_name || ''}|${x.segment_id || ''}|${x.content || ''}` === key,
);
if (existingIndex < 0) {
msg.retriever_resources.push(item as RetrieverResource);
} else {
msg.retriever_resources[existingIndex] = {
...msg.retriever_resources[existingIndex],
...(item as object),
};
}
}
};
const addAttributionParts = (msg: ChatMessage, value: unknown) => {
if (!value) return;
if (!msg.attribution_parts) msg.attribution_parts = [];
const pushUnique = (text: string) => {
const v = text.trim();
if (!v) return;
if (!msg.attribution_parts!.includes(v)) {
msg.attribution_parts!.push(v);
}
};
if (typeof value === 'string') {
pushUnique(value);
return;
}
if (Array.isArray(value)) {
for (const item of value) {
if (typeof item === 'string') {
pushUnique(item);
} else if (item && typeof item === 'object') {
const o = item as Record<string, unknown>;
pushUnique(String(o.content || o.text || o.title || JSON.stringify(item)));
}
}
return;
}
if (typeof value === 'object' && value !== null) {
const o = value as Record<string, unknown>;
pushUnique(String(o.content || o.text || o.title || JSON.stringify(value)));
}
};
const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) => {
const metadata = (data?.metadata || {}) as Record<string, unknown>;
addRetrieverResources(msg, data?.retriever_resources);
addRetrieverResources(msg, metadata?.retriever_resources);
addRetrieverResources(msg, metadata?.retrieverResources);
addAttributionParts(msg, data?.annotations);
addAttributionParts(msg, data?.annotation_reply);
addAttributionParts(msg, metadata?.annotations);
addAttributionParts(msg, metadata?.annotation_reply);
addAttributionParts(msg, data?.citation);
addAttributionParts(msg, metadata?.citation);
};
export function useChat() {
const messages = ref<ChatMessage[]>([]);
const isThinking = ref(false);
const viewId = ref(0);
const runs = ref<ChatRun[]>([]);
const activeRunId = ref<number | null>(null);
let runSeq = 0;
const conversationId = ref<string | null>(null);
const activateRun = (runId: number) => {
const run = runs.value.find((r) => r.runId === runId);
if (!run) return;
messages.value = run.messages;
conversationId.value = run.conversationId;
isThinking.value = run.status === 'running';
activeRunId.value = runId;
};
const createNewChatView = () => {
viewId.value += 1;
messages.value = [];
conversationId.value = null;
isThinking.value = false;
activeRunId.value = null;
};
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
viewId.value += 1;
activeRunId.value = null;
isThinking.value = false;
messages.value = nextMessages;
conversationId.value = id;
};
const normalizeStreamText = (text: string) => {
if (!text) return '';
return text.replace(/\\n/g, '\n');
};
const sendMessage = async (
query: string,
agentId: number,
kbType = '企业知识库',
files?: Array<
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
>,
) => {
const runViewId = viewId.value;
const runMessages = messages.value;
const run: ChatRun = {
runId: ++runSeq,
agentId,
viewId: runViewId,
query,
messages: runMessages,
conversationId: conversationId.value,
status: 'running',
createdAt: new Date().toISOString(),
};
runs.value.unshift(run);
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
activeRunId.value = run.runId;
runMessages.push({ role: 'user', content: query });
let botMsgIndex: number | null = null;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = runMessages.push({
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: [],
}) - 1;
}
return runMessages[botMsgIndex] || null;
};
isThinking.value = true;
try {
const response = await fetch('/api/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
query,
agent_id: agentId,
conversation_id: conversationId.value,
kb_type: kbType,
files: files && files.length > 0 ? files : undefined,
}),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error((err as { error?: string }).error || `Request failed with status ${response.status}`);
}
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) throw new Error('No reader');
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
buffer = buffer.replace(/\r\n/g, '\n');
const frames = buffer.split('\n\n');
buffer = frames.pop() || '';
for (const frame of frames) {
const dataLines = frame
.split('\n')
.map((l) => l.trim())
.filter((l) => l.startsWith('data:'));
if (dataLines.length === 0) continue;
const payload = dataLines.map((l) => l.replace(/^data:\s?/, '')).join('\n');
if (!payload) continue;
try {
const data = JSON.parse(payload) as Record<string, unknown>;
if (data?.conversation_id) {
const cid = String(data.conversation_id);
if (!run.conversationId) run.conversationId = cid;
if (messages.value === runMessages) conversationId.value = cid;
}
const eventName = String(data.event || '');
if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
}
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
run.status = 'done';
if (messages.value === runMessages) isThinking.value = false;
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) currentBotMsg.chat_log_id = Number(data.chat_log_id);
}
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
const normalizedAnswer = normalizeStreamText(data.answer);
if (data.replace_answer) {
botMsg.content = normalizedAnswer;
} else {
botMsg.content += normalizedAnswer;
}
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
}
} else if (eventName === 'error') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += `\n[Error: ${data.message}]`;
run.status = 'error';
if (messages.value === runMessages) isThinking.value = false;
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
}
} catch {
// ignore malformed SSE frames
}
}
}
} catch (e: unknown) {
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
const message = e instanceof Error ? e.message : 'Network Issue';
botMsg.content += `\n[Error: ${message}]`;
}
} finally {
if (messages.value === runMessages) {
isThinking.value = false;
}
}
};
return {
messages,
isThinking,
conversationId,
runs,
activeRunId,
activateRun,
createNewChatView,
loadConversationState,
sendMessage,
};
}
@@ -0,0 +1,45 @@
/**
* features/chat/composables/useChatHistory.ts
* 跨 Agent 聊天历史列表(工作台 History 页 / 移动端 Tab)。
*/
import { ref } from 'vue';
import { getAuthHeaders } from '@/utils/auth';
import { requestJson } from '@/api/client';
import type { ChatCrossAgentHistoryItem } from '../types/chat.types';
export function useChatHistory() {
const chatHistories = ref<ChatCrossAgentHistoryItem[]>([]);
const isLoadingHistories = ref(false);
const loadChatHistories = async () => {
isLoadingHistories.value = true;
try {
const agentList = await requestJson<Array<{ id: number; name: string }>>('/api/agents', {
headers: getAuthHeaders(),
});
const allHistories: ChatCrossAgentHistoryItem[] = [];
await Promise.all(
(Array.isArray(agentList) ? agentList : []).map(async (agent) => {
try {
const sessions = await requestJson<ChatCrossAgentHistoryItem[]>(
`/api/chat/sessions?agent_id=${agent.id}`,
{ headers: getAuthHeaders() },
);
for (const s of Array.isArray(sessions) ? sessions : []) {
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
}
} catch {
// ignore per-agent failures
}
}),
);
allHistories.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
chatHistories.value = allHistories;
} catch {
// ignore
}
isLoadingHistories.value = false;
};
return { chatHistories, isLoadingHistories, loadChatHistories };
}
@@ -0,0 +1,408 @@
/**
* features/chat/composables/useChatSourceFiles.ts
* 检索来源 / 源文件链接解析与预览。
*/
import { ref, type ComputedRef, type Ref } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import { resolveChatSourceFile } from '../api/chat.api';
import type { SourceFileLink } from '../types/chat.types';
import type { useMessage } from '@/composables/useMessage';
const PREFERRED_SOURCE_EXTS = new Set([
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp',
'txt', 'rtf', 'md', 'markdown',
]);
const safeDecode = (value: string) => {
try {
return decodeURIComponent(value);
} catch {
return value;
}
};
const normalizeUrl = (url: string) => {
let v = url
.trim()
.replace(/^['"]|['"]$/g, '')
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/')
.replace(/&amp;/g, '&');
v = v.replace(/[),.;]+$/g, '');
if (!v) return '';
if (v.startsWith('//')) return `${window.location.protocol}${v}`;
if (/^https?:\/\//i.test(v) || v.startsWith('/')) return v;
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\//.test(v)) return `http://${v}`;
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\//.test(v)) return `http://${v}`;
return '';
};
const getUrlExt = (url: string) => {
const clean = (url.split('?')[0] || '').toLowerCase();
const idx = clean.lastIndexOf('.');
if (idx < 0) return '';
return clean.slice(idx + 1);
};
const isChunkLikeLink = (url: string) => /segment|chunk|fragments?|split/i.test(url);
const isPreferredSourceLink = (url: string) => PREFERRED_SOURCE_EXTS.has(getUrlExt(url));
const isNoisySourceUrl = (_url: string) => false;
const isNoisySourceName = (_name: string) => false;
const looksLikeFileName = (name: string) => {
const n = (name || '').trim();
if (!n) return false;
return /\.[A-Za-z0-9]{2,8}$/.test(n);
};
const findFirstByKeys = (payload: unknown, keyCandidates: string[]): string => {
if (payload == null) return '';
if (Array.isArray(payload)) {
for (const item of payload) {
const found = findFirstByKeys(item, keyCandidates);
if (found) return found;
}
return '';
}
if (typeof payload !== 'object') return '';
const obj = payload as Record<string, unknown>;
for (const key of keyCandidates) {
const value = obj[key];
if (value != null && String(value).trim()) return String(value).trim();
}
for (const value of Object.values(obj)) {
const found = findFirstByKeys(value, keyCandidates);
if (found) return found;
}
return '';
};
const findDirectByKeys = (payloads: unknown[], keyCandidates: string[]): string => {
for (const payload of payloads) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) continue;
const obj = payload as Record<string, unknown>;
for (const key of keyCandidates) {
const value = obj[key];
if (value != null && String(value).trim()) return String(value).trim();
}
}
return '';
};
const getResourceIds = (item: Record<string, unknown>) => {
const metadata = item?.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata)
? (item.metadata as Record<string, unknown>)
: null;
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
const remoteDocumentId = findDirectByKeys([item, metadata], [
'remote_document_id', 'dify_document_id', 'source_document_id', 'doc_id',
]) || findFirstByKeys(item, ['remote_document_id', 'dify_document_id', 'source_document_id', 'doc_id'])
|| findDirectByKeys([item, metadata], ['document_id']);
return { datasetId, remoteDocumentId };
};
const canPreviewSourceLink = (link: Partial<SourceFileLink> | null | undefined) => {
if (!link) return false;
return Boolean(link.url || (link.datasetId && link.remoteDocumentId));
};
const buildSourceLinkKey = (name: string, datasetId?: string, remoteDocumentId?: string, url?: string) => {
const normalizedName = String(name || '').trim();
const normalizedDatasetId = String(datasetId || '').trim();
const normalizedRemoteDocumentId = String(remoteDocumentId || '').trim();
const normalizedUrl = String(url || '').split('?')[0];
if (normalizedDatasetId && normalizedRemoteDocumentId) {
return `${normalizedName}|${normalizedDatasetId}|${normalizedRemoteDocumentId}`;
}
if (looksLikeFileName(normalizedName)) {
return normalizedUrl ? `${normalizedName}|${normalizedUrl}` : normalizedName;
}
return `${normalizedName}|${normalizedUrl}`;
};
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
const extractUrlsFromText = (text: string) => {
if (!text) return [];
const urls: string[] = [];
const normalizedText = text
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/');
const mdRegex = /\[[^\]]+\]\(([^)]+)\)/g;
let m: RegExpExecArray | null;
while ((m = mdRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
const htmlAttrRegex = /\b(?:href|src)\s*=\s*["']([^"']+)["']/gi;
while ((m = htmlAttrRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
const angleRegex = /<\s*((?:https?:\/\/|\/\/)[^>\s]+)\s*>/gi;
while ((m = angleRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
const rawRegex =
/((?:https?:\/\/|\/\/)[^\s"'<>]+|(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\/[^\s"'<>]+|[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\/[^\s"'<>]+|\/[^\s"'<>]+\.(?:md|markdown|txt|pdf|doc|docx|ppt|pptx|xls|xlsx|jpg|jpeg|png|gif|webp|svg|bmp))/gi;
while ((m = rawRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
return urls;
};
const getSourceContent = (item: Record<string, unknown>) =>
String(item?.content || item?.segment_content || item?.text || '');
export interface UseChatSourceFilesOptions {
agentId: ComputedRef<number>;
t: ComposerTranslation;
msg: ReturnType<typeof useMessage>;
isMobile: Ref<boolean>;
}
export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceFilesOptions) {
const filePreviewVisible = ref(false);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const getSourceTitle = (item: Record<string, unknown>) =>
String(item?.document_name || item?.title || item?.source || 'Untitled Source');
const getSourceMeta = (item: Record<string, unknown>) => {
const parts: string[] = [];
if (item?.dataset_name) parts.push(String(item.dataset_name));
if (item?.segment_id) parts.push(`segment: ${item.segment_id}`);
if (typeof item?.score === 'number') parts.push(`score: ${(item.score as number).toFixed(3)}`);
return parts.join(' | ');
};
const getSourceBrief = (item: Record<string, unknown>) => {
const raw = getSourceContent(item);
const plain = raw
.replace(/\[[^\]]+\]\(([^)]+)\)/g, '$1')
.replace(/[#>*`]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!plain) return '';
return plain.length > 180 ? `${plain.slice(0, 180)}...` : plain;
};
const getSourceLinks = (resources: unknown[] = []): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
const mergeSourceLink = (key: string, nextLink: SourceFileLink) => {
const existing = map.get(key);
if (!existing) {
map.set(key, nextLink);
return;
}
map.set(key, {
...existing,
...(nextLink.url ? { url: nextLink.url } : {}),
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
});
};
for (const raw of resources) {
const item = (raw || {}) as Record<string, unknown>;
const { datasetId, remoteDocumentId } = getResourceIds(item);
const directCandidates = [
item?.source_download_url, item?.url, item?.file_url, item?.document_url,
item?.source_url, item?.download_url,
(item?.metadata as Record<string, unknown> | undefined)?.source_download_url,
(item?.metadata as Record<string, unknown> | undefined)?.url,
(item?.metadata as Record<string, unknown> | undefined)?.file_url,
(item?.metadata as Record<string, unknown> | undefined)?.document_url,
].filter(Boolean) as string[];
const content = getSourceContent(item);
const forceName = String(item?.source_filename || item?.document_name || item?.title || '');
const forceUrl = normalizeUrl(String(item?.source_download_url || item?.url || ''));
if (forceName && (forceUrl || (datasetId && remoteDocumentId))) {
const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl);
mergeSourceLink(key, {
name: forceName,
...(forceUrl ? { url: forceUrl } : {}),
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
const serialized = JSON.stringify(item || {});
const discovered = [
...directCandidates.map(normalizeUrl).filter(Boolean),
...extractUrlsFromText(content),
...extractUrlsFromText(serialized),
];
const files = Array.isArray(item?.files) ? item.files : [];
for (const f of files) {
const file = f as Record<string, unknown>;
const fu = normalizeUrl(String(file?.url || file?.download_url || file?.file_url || ''));
if (fu) discovered.push(fu);
}
for (const url of discovered) {
if (isChunkLikeLink(url)) continue;
const name = String(item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file'));
if (isNoisySourceName(name)) continue;
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url);
mergeSourceLink(key, {
name,
url,
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
}
return Array.from(map.values()).filter((link) => canPreviewSourceLink(link));
};
const getMessageLinks = (message: Record<string, unknown>): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
const merge = (links: SourceFileLink[]) => {
for (const link of links) {
if (!canPreviewSourceLink(link)) continue;
const linkUrl = link.url || '';
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
if (isNoisySourceName(link.name)) continue;
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
const existing = map.get(key);
if (!existing) {
map.set(key, link);
} else {
map.set(key, {
...existing,
...(link.url ? { url: link.url } : {}),
...(link.datasetId ? { datasetId: link.datasetId } : {}),
...(link.remoteDocumentId ? { remoteDocumentId: link.remoteDocumentId } : {}),
});
}
}
};
if (message?.retriever_resources) {
merge(getSourceLinks(message.retriever_resources as unknown[]));
}
const links = Array.from(map.values());
const preferred = links.filter((l) => l.url && isPreferredSourceLink(l.url));
return preferred.length > 0 ? preferred : links;
};
const getDisplayRetrieverResources = (message: Record<string, unknown>): Record<string, unknown>[] => {
const list = Array.isArray(message?.retriever_resources) ? message.retriever_resources as Record<string, unknown>[] : [];
return list.filter((doc) => {
const name = String(doc?.source_filename || doc?.document_name || doc?.title || '');
const url = String(doc?.source_download_url || doc?.url || doc?.file_url || doc?.document_url || '');
return !(isMarkdownFileName(name) || isMarkdownByUrl(url));
});
};
const shouldExpandSourceDetails = (message: Record<string, unknown>): boolean =>
getMessageLinks(message).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url || ''));
const getSourcePreviewExt = (file: { name?: string; url?: string; actualExt?: string }) => {
const actual = String(file?.actualExt || '').trim().toLowerCase();
if (actual) return actual;
const byName = getUrlExt(file?.name || '');
if (byName) return byName;
return getUrlExt(file?.url || '');
};
const isWeComMobileWebView = () => {
if (typeof navigator === 'undefined') return false;
const ua = navigator.userAgent || '';
return /wxwork/i.test(ua) && /mobile/i.test(ua);
};
const shouldBypassEmbeddedPreview = (file: { name?: string; url?: string; actualExt?: string }) => {
const ext = getSourcePreviewExt(file);
if (!isMobile.value || !isWeComMobileWebView()) return false;
if (!/^https?:\/\//i.test(file?.url || '')) return false;
return ['pdf', 'xls', 'xlsx'].includes(ext);
};
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {
if (file.datasetId && file.remoteDocumentId) {
const data = await resolveChatSourceFile({
agent_id: agentId.value,
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (resolvedUrl) {
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
};
}
}
if (!file.url) throw new Error('当前源文件暂未返回可预览链接');
return { name: file.name, url: file.url, actualExt: file.actualExt };
};
const openPreview = async (file: SourceFileLink) => {
try {
const resolvedFile = await resolveSourceLink(file);
if (shouldBypassEmbeddedPreview(resolvedFile)) {
window.location.href = resolvedFile.url;
return;
}
previewFile.value = resolvedFile;
filePreviewVisible.value = true;
} catch (error: unknown) {
const message = error instanceof Error ? error.message : t('chat.previewUnavailable');
msg.warning(message);
}
};
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
const rawHref = (href || '').trim();
if (!rawHref.startsWith('#plm-preview?')) return null;
const params = new URLSearchParams(rawHref.slice('#plm-preview?'.length));
const name = (params.get('name') || '').trim();
const url = (params.get('url') || '').trim();
if (!name || !url) return null;
return { name, url };
};
return {
filePreviewVisible,
previewFile,
getSourceTitle,
getSourceMeta,
getSourceBrief,
getSourceLinks,
getMessageLinks,
getDisplayRetrieverResources,
shouldExpandSourceDetails,
openPreview,
parsePlmPreviewLink,
};
}
+9
View File
@@ -0,0 +1,9 @@
/**
* features/chat/index.ts
* 聊天域对外导出。
*/
export { useChat } from './composables/useChat';
export { useChatHistory } from './composables/useChatHistory';
export { useChatSourceFiles } from './composables/useChatSourceFiles';
export * from './api/chat.api';
export type * from './types/chat.types';
@@ -0,0 +1,47 @@
<script setup lang="ts">
/**
* features/chat/pages/HistoryPage.vue
* 跨 Agent 聊天历史列表,点击跳转对应会话(工作台 / 移动端 Tab 入口)。
*/
import { inject } from 'vue';
import { Bot } from 'lucide-vue-next';
import { WORKSPACE_KEY } from '@/features/workspace/composables/workspace.context';
const ws = inject(WORKSPACE_KEY)! as any;
</script>
<template>
<div class="space-y-3">
<div v-if="ws.isLoadingHistories" class="flex justify-center py-20">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
<div v-else-if="ws.chatHistories.length === 0" class="flex flex-col items-center justify-center py-20 text-muted">
<Bot class="h-10 w-10 mb-2" />
<p class="text-sm">{{ $t('workspace.history.empty') }}</p>
</div>
<div v-else>
<button
v-for="item in ws.chatHistories"
:key="item.id"
@click="ws.router.push(`/chat/${item.agent_id || 16}?conversation_id=${item.conversation_id}`)"
class="ws-history-card mb-2"
:class="ws.isMobile ? 'p-2.5 rounded-xl' : ''"
>
<div class="flex items-start gap-3">
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand-50 text-xs font-bold text-brand-600" :class="ws.isMobile ? 'h-7 w-7 text-[10px]' : ''">
{{ (item.agent_name || 'AI').charAt(0) }}
</div>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span class="truncate text-sm font-medium text-primary">{{ item.title || $t('workspace.history.untitled') }}</span>
</div>
<div class="mt-0.5 flex items-center gap-2 text-xs text-muted">
<span>{{ item.agent_name || '' }}</span>
<span>{{ new Date(item.created_at).toLocaleDateString() }}</span>
</div>
</div>
</div>
</button>
</div>
</div>
</template>
@@ -2,7 +2,8 @@ import { defineStore } from 'pinia';
import { ref } from 'vue';
/**
* 聊天域共享状态骨架。Phase 2 迁移 ChatView 时会话列表、当前 agent 等迁入此处。
* features/chat/stores/chat.store.ts
* 聊天域共享状态:当前 agent、侧栏折叠等(会话列表逐步迁入)。
*/
export const useChatStore = defineStore('chat', () => {
const currentAgentId = ref<number | null>(null);
@@ -0,0 +1,103 @@
/**
* features/chat/types/chat.types.ts
* 聊天域核心类型定义。
*/
export interface RetrieverResource {
dataset_name?: string;
document_name?: string;
segment_id?: string;
content?: string;
score?: number;
[key: string]: unknown;
}
export interface ChatMessage {
role: 'user' | 'assistant';
content: string;
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
payload?: unknown;
local_id?: string;
local_only?: boolean;
rated?: boolean;
shipping_actions?: Array<{
id: string;
label: string;
message: string;
variant?: 'primary' | 'secondary' | 'danger';
}>;
shipping_actions_used?: boolean;
}
export type ChatRunStatus = 'running' | 'done' | 'error';
export interface ChatRun {
runId: number;
agentId: number;
viewId: number;
query: string;
messages: ChatMessage[];
conversationId: string | null;
status: ChatRunStatus;
createdAt: string;
}
export interface ChatSessionItem {
id: number;
conversation_id: string;
title: string;
created_at: string;
}
export type DisplayHistoryItem = ChatSessionItem & { __runId?: number; __status?: string };
export interface ChatHistoryItem extends ChatSessionItem {}
/** 跨 Agent 历史(工作台 / 移动端 Tab) */
export interface ChatCrossAgentHistoryItem extends ChatSessionItem {
agent_id?: number;
agent_name?: string;
}
export interface SourceFileLink {
name: string;
url?: string;
datasetId?: string;
remoteDocumentId?: string;
actualExt?: string;
}
export interface LeaveAgentOption {
uid: string;
employeeId: string;
name: string;
jobtitle?: string;
jobtitleName?: string;
departmentid?: string;
subcompanyid1?: string;
departmentName?: string;
subcompanyName?: string;
}
export interface OaEmployeesResponse {
items: LeaveAgentOption[];
total: number;
}
export interface ChatSourceFileResult {
source_download_url?: string;
source_filename?: string;
source_ext?: string;
}
export interface ChatUploadResult {
id: string;
name?: string;
size?: number;
extension?: string;
mime_type?: string;
type?: 'image' | 'document' | 'audio' | 'video' | 'custom';
}
File diff suppressed because it is too large. Load diff