refactor(frontend): 重构前端第二版
This commit is contained in:
1 parent
2631f78b00
commit
4b562cfa82
205 files changed
+15399
-12015
No files matched your search
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* features/chat/composables/chat.context.ts
|
||||
* 对话页 provide/inject 上下文类型与注入 key。
|
||||
*
|
||||
* provide 时使用 `reactive(useChatPage())`,嵌套 Ref/ComputedRef 在消费侧自动解包,
|
||||
* template 与 script 均可直接 `page.input` / `page.isThinking` 而无需 `.value`。
|
||||
*/
|
||||
import { inject, type InjectionKey, type Reactive, type UnwrapNestedRefs } from 'vue';
|
||||
import type { useChatPage } from './useChatPage';
|
||||
|
||||
/** useChatPage() 原始返回(含 Ref/ComputedRef) */
|
||||
export type ChatPageContext = ReturnType<typeof useChatPage>;
|
||||
|
||||
/** ChatView provide 后经 reactive() 包装、供子组件 inject 的类型 */
|
||||
export type ChatPageContextProvided = Reactive<UnwrapNestedRefs<ChatPageContext>>;
|
||||
|
||||
export const CHAT_PAGE_KEY: InjectionKey<ChatPageContextProvided> = Symbol('chatPage');
|
||||
|
||||
/**
|
||||
* 在 ChatView 子树中获取对话页上下文。
|
||||
* 必须在已 provide(CHAT_PAGE_KEY) 的组件树内调用。
|
||||
*/
|
||||
export function useChatPageContext(): ChatPageContextProvided {
|
||||
const ctx = inject(CHAT_PAGE_KEY);
|
||||
if (!ctx) {
|
||||
throw new Error('[chat] useChatPageContext() must be used inside ChatView (provide CHAT_PAGE_KEY)');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
/**
|
||||
* 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';
|
||||
import type { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
export interface ChatDeps {
|
||||
t: ComposerTranslation;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/composables/useChat.ts
|
||||
* SSE 流式对话核心:消息列表、runs、发送与接收。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { getAuthHeaders } from '@/utils/auth';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
|
||||
|
||||
const normalizeResources = (resources: unknown) => {
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* features/chat/composables/useChatAgent.ts
|
||||
* 当前 Agent 元数据、知识库选项、推荐问题与用户可切换 Agent 列表。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { getUserAgent, listUserAgents } from '@/features/auth/api/user.api';
|
||||
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import type { UseChatGuidesReturn } from './useChatGuides';
|
||||
|
||||
export type AgentSuggestedQuestionItem = {
|
||||
question: string;
|
||||
group: string;
|
||||
};
|
||||
|
||||
const DEFAULT_KB = '企业知识库';
|
||||
const ERP_KB = 'ERP知识库';
|
||||
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
|
||||
|
||||
const DEFAULT_AGENT_DESCRIPTIONS: Record<string, string> = {
|
||||
人事规章: '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。',
|
||||
通用入口: '我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。',
|
||||
};
|
||||
|
||||
const DEFAULT_AGENT_SUGGESTED_QUESTIONS: Record<string, { style: 'plain' | 'styled'; questions: AgentSuggestedQuestionItem[] }> = {
|
||||
人事规章: {
|
||||
style: 'styled',
|
||||
questions: [
|
||||
{ question: '查询我有多少假期?', group: '考勤与休假' },
|
||||
{ question: '如何进行请假?', group: '考勤与休假' },
|
||||
{ question: '查公司法定节假日?', group: '考勤与休假' },
|
||||
{ question: '新员工入职须知', group: '规章与日常' },
|
||||
{ question: '怎么开具在职证明?', group: '规章与日常' },
|
||||
{ question: '查公司薪酬及福利待遇怎么样?', group: '规章与日常' },
|
||||
],
|
||||
},
|
||||
通用入口: {
|
||||
style: 'plain',
|
||||
questions: [
|
||||
{ question: '新员工入职须知', group: '' },
|
||||
{ question: '查询我有多少假期?', group: '' },
|
||||
{ question: '如何进行请假?', group: '' },
|
||||
{ question: '查公司法定节假日?', group: '' },
|
||||
{ question: '查公司薪酬及福利待遇怎么样?', group: '' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const normalizeAgentSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item) => {
|
||||
if (typeof item === 'string') {
|
||||
const question = item.trim();
|
||||
return question ? { question, group: '' } : null;
|
||||
}
|
||||
if (!item || typeof item !== 'object') return null;
|
||||
const record = item as Record<string, unknown>;
|
||||
const question = String(record.question || record.text || '').trim();
|
||||
const group = String(record.group || '').trim();
|
||||
return question ? { question, group } : null;
|
||||
})
|
||||
.filter((item): item is AgentSuggestedQuestionItem => !!item);
|
||||
};
|
||||
|
||||
export interface UseChatAgentOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
chatGuides: Pick<UseChatGuidesReturn, 'loadGuides' | 'clearGuides'>;
|
||||
}
|
||||
|
||||
export function useChatAgent(options: UseChatAgentOptions) {
|
||||
const { deps, currentAgentId, chatGuides } = options;
|
||||
const { t, msg, router } = deps;
|
||||
|
||||
const currentAgent = ref<any>(null);
|
||||
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
|
||||
const showAgentPanel = ref(true);
|
||||
const selectedKb = ref(DEFAULT_KB);
|
||||
const kbOptions = [DEFAULT_KB, ERP_KB];
|
||||
|
||||
const getKbLabel = (kb: string) => {
|
||||
if (kb === DEFAULT_KB) return t('chat.kb.enterprise');
|
||||
if (kb === ERP_KB) return t('chat.kb.erp');
|
||||
return kb;
|
||||
};
|
||||
|
||||
const currentAgentName = computed(() => String(currentAgent.value?.name || '').trim());
|
||||
const canSelectErpKnowledgeBase = computed(() => ERP_KB_ENABLED_AGENT_NAMES.has(currentAgentName.value));
|
||||
const availableKbOptions = computed(() => (
|
||||
canSelectErpKnowledgeBase.value
|
||||
? kbOptions
|
||||
: kbOptions.filter((option) => option !== ERP_KB)
|
||||
));
|
||||
const kbDropdownDisabled = computed(() => availableKbOptions.value.length <= 1);
|
||||
|
||||
watch(canSelectErpKnowledgeBase, (allowed) => {
|
||||
if (allowed) {
|
||||
selectedKb.value = ERP_KB;
|
||||
return;
|
||||
}
|
||||
if (selectedKb.value === ERP_KB) {
|
||||
selectedKb.value = DEFAULT_KB;
|
||||
}
|
||||
}, { immediate: true });
|
||||
|
||||
const agentDescription = computed(() => {
|
||||
const text = String(currentAgent.value?.description || '').trim();
|
||||
return text || DEFAULT_AGENT_DESCRIPTIONS[currentAgentName.value] || '';
|
||||
});
|
||||
|
||||
const suggestedQuestionsStyle = computed<'plain' | 'styled'>(() => {
|
||||
const style = String(currentAgent.value?.extra_config?.suggested_questions_style || '').trim().toLowerCase();
|
||||
if (style === 'styled') return 'styled';
|
||||
if (style === 'plain') return 'plain';
|
||||
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.style || 'plain';
|
||||
});
|
||||
|
||||
const agentSuggestedQuestions = computed<AgentSuggestedQuestionItem[]>(() => {
|
||||
const configured = normalizeAgentSuggestedQuestions(
|
||||
currentAgent.value?.suggested_questions ?? currentAgent.value?.extra_config?.suggested_questions,
|
||||
);
|
||||
if (configured.length > 0) return configured;
|
||||
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.questions || [];
|
||||
});
|
||||
|
||||
const styledSuggestedQuestionSections = computed(() => {
|
||||
const groups = new Map<string, AgentSuggestedQuestionItem[]>();
|
||||
for (const item of agentSuggestedQuestions.value) {
|
||||
const groupName = String(item.group || '').trim() || '常见问题';
|
||||
if (!groups.has(groupName)) {
|
||||
groups.set(groupName, []);
|
||||
}
|
||||
groups.get(groupName)?.push(item);
|
||||
}
|
||||
const iconTypes: Array<'calendar' | 'building'> = ['calendar', 'building'];
|
||||
return Array.from(groups.entries()).map(([title, questions], index) => ({
|
||||
title,
|
||||
questions,
|
||||
iconType: iconTypes[index % iconTypes.length] as 'calendar' | 'building',
|
||||
}));
|
||||
});
|
||||
|
||||
const loadAgent = async () => {
|
||||
try {
|
||||
currentAgent.value = await getUserAgent(currentAgentId.value);
|
||||
await chatGuides.loadGuides();
|
||||
} catch (e) {
|
||||
if (e instanceof BusinessError && e.status === 403) {
|
||||
msg.error(t('workspace.permission.denied') || 'Access denied');
|
||||
router.push('/workspace?no_redirect=1');
|
||||
return;
|
||||
}
|
||||
console.error('Failed to load agent', e);
|
||||
currentAgent.value = { name: t('workspace.unknownAgent') };
|
||||
chatGuides.clearGuides();
|
||||
}
|
||||
};
|
||||
|
||||
const loadUserAgents = async () => {
|
||||
try {
|
||||
const agents = await listUserAgents();
|
||||
userAgents.value = Array.isArray(agents)
|
||||
? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow')
|
||||
: [];
|
||||
if (userAgents.value.length === 0) {
|
||||
showAgentPanel.value = false;
|
||||
}
|
||||
} catch {
|
||||
userAgents.value = [];
|
||||
showAgentPanel.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const switchToAgent = (agent: { id: number; name: string }) => {
|
||||
if (agent.id === currentAgentId.value) return;
|
||||
setLastChatAgentId(agent.id);
|
||||
router.push(`/chat/${agent.id}`);
|
||||
};
|
||||
|
||||
return {
|
||||
currentAgent,
|
||||
userAgents,
|
||||
showAgentPanel,
|
||||
selectedKb,
|
||||
getKbLabel,
|
||||
availableKbOptions,
|
||||
kbDropdownDisabled,
|
||||
agentDescription,
|
||||
suggestedQuestionsStyle,
|
||||
agentSuggestedQuestions,
|
||||
styledSuggestedQuestionSections,
|
||||
loadAgent,
|
||||
loadUserAgents,
|
||||
switchToAgent,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
/**
|
||||
* features/chat/composables/useChatAttachments.ts
|
||||
* Dify 附件策略解析、本地/URL 附件管理与发送前上传。
|
||||
*/
|
||||
import { computed, ref, type ComputedRef, type Ref } from 'vue';
|
||||
import { uploadChatFile } from '../api/chat.api';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
|
||||
type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
|
||||
export type ChatUploadFileSpec =
|
||||
| { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string }
|
||||
| { type: ChatUploadFileType; transfer_method: 'remote_url'; url: string };
|
||||
|
||||
const DIFY_SUPPORTED_EXTS: Record<Exclude<ChatUploadFileType, 'custom'>, Set<string>> = {
|
||||
document: new Set([
|
||||
'txt', 'md', 'markdown', 'mdx', 'pdf', 'html', 'htm', 'xlsx', 'xls', 'vtt', 'properties',
|
||||
'doc', 'docx', 'csv', 'eml', 'msg', 'pptx', 'ppt', 'xml', 'epub',
|
||||
]),
|
||||
image: new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']),
|
||||
audio: new Set(['mp3', 'm4a', 'wav', 'webm', 'mpga']),
|
||||
video: new Set(['mp4', 'mov', 'mpeg', 'webm']),
|
||||
};
|
||||
|
||||
const extractExt = (value: string) => {
|
||||
const text = (value || '').trim().toLowerCase();
|
||||
const withoutQuery = (text.split('?')[0] || '').split('#')[0] || '';
|
||||
const idx = withoutQuery.lastIndexOf('.');
|
||||
if (idx < 0) return '';
|
||||
return withoutQuery.slice(idx + 1).trim();
|
||||
};
|
||||
|
||||
const isKnownDifyExt = (ext: string) => {
|
||||
if (!ext) return false;
|
||||
return (
|
||||
DIFY_SUPPORTED_EXTS.image.has(ext)
|
||||
|| DIFY_SUPPORTED_EXTS.document.has(ext)
|
||||
|| DIFY_SUPPORTED_EXTS.audio.has(ext)
|
||||
|| DIFY_SUPPORTED_EXTS.video.has(ext)
|
||||
);
|
||||
};
|
||||
|
||||
const resolveDifyType = (ext: string, mime?: string): Exclude<ChatUploadFileType, 'custom'> | null => {
|
||||
const m = (mime || '').toLowerCase();
|
||||
if (m.startsWith('image/')) return 'image';
|
||||
if (m.startsWith('audio/')) return 'audio';
|
||||
if (m.startsWith('video/')) return 'video';
|
||||
if (DIFY_SUPPORTED_EXTS.image.has(ext)) return 'image';
|
||||
if (DIFY_SUPPORTED_EXTS.document.has(ext)) return 'document';
|
||||
const inAudio = DIFY_SUPPORTED_EXTS.audio.has(ext);
|
||||
const inVideo = DIFY_SUPPORTED_EXTS.video.has(ext);
|
||||
if (inAudio && !inVideo) return 'audio';
|
||||
if (inVideo) return 'video';
|
||||
return null;
|
||||
};
|
||||
|
||||
export interface UseChatAttachmentsOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
currentAgent: Ref<any>;
|
||||
}
|
||||
|
||||
export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const { deps, currentAgentId, currentAgent } = options;
|
||||
const { msg } = deps;
|
||||
|
||||
const attachments = ref<PendingAttachment[]>([]);
|
||||
const isUploadingAttachments = ref(false);
|
||||
|
||||
const difyFileUploadConfig = computed<Record<string, any>>(() => {
|
||||
return (currentAgent.value?.dify_parameters?.file_upload as any) || {};
|
||||
});
|
||||
|
||||
const difySystemParameters = computed<Record<string, any>>(() => {
|
||||
return (currentAgent.value?.dify_parameters?.system_parameters as any) || {};
|
||||
});
|
||||
|
||||
const attachmentPolicy = computed(() => {
|
||||
const types: ChatUploadFileType[] = ['image', 'document', 'audio', 'video', 'custom'];
|
||||
const enabled: Record<ChatUploadFileType, { local: boolean; remote: boolean; limit?: number }> = {
|
||||
image: { local: false, remote: false },
|
||||
document: { local: false, remote: false },
|
||||
audio: { local: false, remote: false },
|
||||
video: { local: false, remote: false },
|
||||
custom: { local: false, remote: false },
|
||||
};
|
||||
const raw = difyFileUploadConfig.value as any;
|
||||
const normalizedAllowedExts = Array.isArray(raw?.allowed_file_extensions)
|
||||
? raw.allowed_file_extensions
|
||||
.map((v: any) => String(v || '').trim())
|
||||
.filter(Boolean)
|
||||
.map((v: string) => (v.startsWith('.') ? v.slice(1) : v).toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const allowedExts: Set<string> | null = normalizedAllowedExts.length > 0 ? new Set<string>(normalizedAllowedExts) : null;
|
||||
|
||||
const allowedTypes = Array.isArray(raw?.allowed_file_types)
|
||||
? raw.allowed_file_types
|
||||
.map((v: any) => String(v || '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const allowedTypeSet = allowedTypes.length > 0 ? new Set(allowedTypes) : null;
|
||||
|
||||
const allowedMethods = Array.isArray(raw?.allowed_file_upload_methods)
|
||||
? raw.allowed_file_upload_methods
|
||||
.map((v: any) => String(v || '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const allowedMethodSet = allowedMethods.length > 0 ? new Set(allowedMethods) : null;
|
||||
|
||||
const isNewSchema = Boolean(raw && raw.enabled === true && allowedTypeSet && allowedMethodSet);
|
||||
if (isNewSchema && allowedTypeSet && allowedMethodSet) {
|
||||
for (const t of types) {
|
||||
const cfg = raw?.[t];
|
||||
const cfgEnabled = typeof cfg?.enabled === 'boolean' ? Boolean(cfg.enabled) : null;
|
||||
const typeAllowed = allowedTypeSet.has(t);
|
||||
if (cfgEnabled === false) continue;
|
||||
if (cfgEnabled !== true && !typeAllowed) continue;
|
||||
|
||||
const transferMethods = Array.isArray(cfg?.transfer_methods)
|
||||
? cfg.transfer_methods
|
||||
.map((v: any) => String(v || '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const methodSet = transferMethods.length > 0 ? new Set(transferMethods) : allowedMethodSet;
|
||||
|
||||
enabled[t] = {
|
||||
local: methodSet.has('local_file'),
|
||||
remote: methodSet.has('remote_url'),
|
||||
limit: Number.isFinite(Number(cfg?.number_limits))
|
||||
? Number(cfg.number_limits)
|
||||
: (Number.isFinite(Number(raw?.number_limits)) ? Number(raw.number_limits) : undefined),
|
||||
};
|
||||
}
|
||||
} else {
|
||||
for (const t of types) {
|
||||
const cfg = raw?.[t];
|
||||
if (!cfg || !cfg.enabled) continue;
|
||||
const transferMethods = Array.isArray(cfg.transfer_methods) ? cfg.transfer_methods : [];
|
||||
enabled[t] = {
|
||||
local: transferMethods.includes('local_file'),
|
||||
remote: transferMethods.includes('remote_url'),
|
||||
limit: Number.isFinite(Number(cfg.number_limits)) ? Number(cfg.number_limits) : undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const mergedLimits = {
|
||||
...(difySystemParameters.value || {}),
|
||||
...(raw?.fileUploadConfig || {}),
|
||||
} as any;
|
||||
const system = mergedLimits || {};
|
||||
const sizeLimitMb: Record<ChatUploadFileType, number | null> = {
|
||||
image: Number.isFinite(Number(system.image_file_size_limit)) ? Number(system.image_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
|
||||
audio: Number.isFinite(Number(system.audio_file_size_limit)) ? Number(system.audio_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
|
||||
video: Number.isFinite(Number(system.video_file_size_limit)) ? Number(system.video_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
|
||||
document: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null,
|
||||
custom: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null,
|
||||
};
|
||||
|
||||
const anyEnabled = Object.values(enabled).some((v) => v.local || v.remote);
|
||||
const canLocal = Object.values(enabled).some((v) => v.local);
|
||||
const canRemote = Object.values(enabled).some((v) => v.remote);
|
||||
const totalLimit = (() => {
|
||||
const v1 = raw?.fileUploadConfig?.file_upload_limit;
|
||||
if (Number.isFinite(Number(v1))) return Number(v1);
|
||||
const v2 = raw?.number_limits;
|
||||
if (Number.isFinite(Number(v2))) return Number(v2);
|
||||
return null;
|
||||
})();
|
||||
|
||||
const effectiveAllowedExts: Set<string> | null = (() => {
|
||||
if (!allowedExts) return null;
|
||||
const filtered = new Set<string>();
|
||||
for (const ext of allowedExts) {
|
||||
const t = resolveDifyType(ext);
|
||||
if (!t) {
|
||||
if (enabled.custom.local || enabled.custom.remote) filtered.add(ext);
|
||||
continue;
|
||||
}
|
||||
if (enabled[t]?.local || enabled[t]?.remote) filtered.add(ext);
|
||||
}
|
||||
return filtered.size > 0 ? filtered : null;
|
||||
})();
|
||||
|
||||
const accept = (() => {
|
||||
if (enabled.custom.local) return '';
|
||||
if (effectiveAllowedExts) {
|
||||
return Array.from(effectiveAllowedExts).map((e) => `.${e}`).join(',');
|
||||
}
|
||||
const parts = new Set<string>();
|
||||
const pushExts = (exts: Set<string>) => {
|
||||
for (const e of exts) parts.add(`.${e}`);
|
||||
};
|
||||
if (enabled.image.local) pushExts(DIFY_SUPPORTED_EXTS.image);
|
||||
if (enabled.audio.local) pushExts(DIFY_SUPPORTED_EXTS.audio);
|
||||
if (enabled.video.local) pushExts(DIFY_SUPPORTED_EXTS.video);
|
||||
if (enabled.document.local) pushExts(DIFY_SUPPORTED_EXTS.document);
|
||||
return Array.from(parts).join(',');
|
||||
})();
|
||||
|
||||
return {
|
||||
anyEnabled,
|
||||
enabled,
|
||||
sizeLimitMb,
|
||||
canLocal,
|
||||
canRemote,
|
||||
accept,
|
||||
allowedExts: effectiveAllowedExts,
|
||||
totalLimit,
|
||||
};
|
||||
});
|
||||
|
||||
const inferFileTypeFromUrl = (url: string): ChatUploadFileType | null => resolveDifyType(extractExt(url));
|
||||
|
||||
const inferFileTypeFromFile = (file: File): ChatUploadFileType | null => {
|
||||
const ext = extractExt(file.name || '');
|
||||
return resolveDifyType(ext, file.type || '');
|
||||
};
|
||||
|
||||
const removeAttachment = (id: string) => {
|
||||
attachments.value = attachments.value.filter((a) => a.id !== id);
|
||||
};
|
||||
|
||||
const handleLocalFilesSelected = (event: Event) => {
|
||||
const inputEl = event.target as HTMLInputElement | null;
|
||||
const fileList = inputEl?.files;
|
||||
if (!fileList) return;
|
||||
const files = Array.from(fileList);
|
||||
for (const f of files) {
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
break;
|
||||
}
|
||||
const ext = extractExt(f.name || '');
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
continue;
|
||||
}
|
||||
let type = inferFileTypeFromFile(f);
|
||||
if (!type) {
|
||||
if (attachmentPolicy.value.enabled.custom.local && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.local) {
|
||||
msg.warning(`当前应用不支持上传此类型附件:${type}`);
|
||||
continue;
|
||||
}
|
||||
const limit = attachmentPolicy.value.sizeLimitMb[type];
|
||||
if (limit && f.size > limit * 1024 * 1024) {
|
||||
msg.warning(`附件过大(上限 ${limit}MB):${f.name}`);
|
||||
continue;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
continue;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'local', file: f, type });
|
||||
}
|
||||
if (inputEl) inputEl.value = '';
|
||||
};
|
||||
|
||||
const addRemoteUrlAttachment = (urlFromInput?: string) => {
|
||||
const raw = (urlFromInput ?? '').trim();
|
||||
if (!raw) return;
|
||||
const url = raw.startsWith('//') ? `${window.location.protocol}${raw}` : raw;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
msg.warning('仅支持 http/https URL');
|
||||
return;
|
||||
}
|
||||
if (!attachmentPolicy.value.canRemote) {
|
||||
msg.warning('当前应用不支持 URL 附件');
|
||||
return;
|
||||
}
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
return;
|
||||
}
|
||||
const ext = extractExt(url);
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
return;
|
||||
}
|
||||
let type = inferFileTypeFromUrl(url);
|
||||
if (!type) {
|
||||
if (attachmentPolicy.value.enabled.custom.remote && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
return;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.remote) {
|
||||
msg.warning(`当前应用不支持该类型 URL 附件:${type}`);
|
||||
return;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
return;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
|
||||
};
|
||||
|
||||
const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
|
||||
if (!attachmentPolicy.value.anyEnabled) return [];
|
||||
if (attachments.value.length === 0) return [];
|
||||
|
||||
const specs: ChatUploadFileSpec[] = [];
|
||||
const locals = attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
|
||||
const remotes = attachments.value.filter((a) => a.kind === 'remote') as Array<Extract<PendingAttachment, { kind: 'remote' }>>;
|
||||
|
||||
if (locals.length > 0) {
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
for (const item of locals) {
|
||||
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
|
||||
if (!uploaded?.id) {
|
||||
throw new Error('Missing upload id');
|
||||
}
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
|
||||
}
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of remotes) {
|
||||
specs.push({ type: item.type, transfer_method: 'remote_url', url: item.url });
|
||||
}
|
||||
|
||||
return specs;
|
||||
};
|
||||
|
||||
const clearAttachments = () => {
|
||||
attachments.value = [];
|
||||
};
|
||||
|
||||
return {
|
||||
attachments,
|
||||
isUploadingAttachments,
|
||||
attachmentPolicy,
|
||||
removeAttachment,
|
||||
handleLocalFilesSelected,
|
||||
addRemoteUrlAttachment,
|
||||
buildFileSpecsForSend,
|
||||
clearAttachments,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* features/chat/composables/useChatBrowserPanel.ts
|
||||
* 内置浏览器侧栏:URL 规范化、iframe 加载与桌面端宽度拖拽。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
const MIN_BROWSER_PANEL_WIDTH = 320;
|
||||
const MAX_BROWSER_PANEL_WIDTH = 960;
|
||||
|
||||
export interface UseChatBrowserPanelOptions {
|
||||
/** 无效 URL 等提示 */
|
||||
warn: (message: string) => void;
|
||||
invalidUrlMessage: string;
|
||||
enterUrlMessage: string;
|
||||
}
|
||||
|
||||
const normalizeBrowserInput = (value: string) => {
|
||||
const raw = (value || '').trim();
|
||||
if (!raw) return '';
|
||||
if (/^https?:\/\//i.test(raw)) return raw;
|
||||
if (/^localhost(?::\d+)?(\/.*)?$/i.test(raw)) return `http://${raw}`;
|
||||
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?(\/.*)?$/.test(raw)) return `http://${raw}`;
|
||||
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\/.*)?$/.test(raw)) return `https://${raw}`;
|
||||
return '';
|
||||
};
|
||||
|
||||
export function useChatBrowserPanel(options: UseChatBrowserPanelOptions) {
|
||||
const open = ref(false);
|
||||
const draftUrl = ref('');
|
||||
const currentUrl = ref('');
|
||||
const frameKey = ref(0);
|
||||
const panelWidth = ref(420);
|
||||
const isResizing = ref(false);
|
||||
const viewportWidth = ref(typeof window === 'undefined' ? 1440 : window.innerWidth);
|
||||
|
||||
const clampPanelWidth = (width: number) => {
|
||||
const maxAllowed = Math.min(
|
||||
MAX_BROWSER_PANEL_WIDTH,
|
||||
Math.max(MIN_BROWSER_PANEL_WIDTH, Math.floor(window.innerWidth * 0.7)),
|
||||
);
|
||||
return Math.min(Math.max(width, MIN_BROWSER_PANEL_WIDTH), maxAllowed);
|
||||
};
|
||||
|
||||
const panelStyle = computed(() => {
|
||||
if (viewportWidth.value < 1024) return undefined;
|
||||
return { width: `${panelWidth.value}px` };
|
||||
});
|
||||
|
||||
const loadPage = () => {
|
||||
const normalized = normalizeBrowserInput(draftUrl.value);
|
||||
if (!normalized) {
|
||||
options.warn(options.invalidUrlMessage);
|
||||
return;
|
||||
}
|
||||
currentUrl.value = normalized;
|
||||
draftUrl.value = normalized;
|
||||
frameKey.value += 1;
|
||||
open.value = true;
|
||||
};
|
||||
|
||||
const refreshPage = () => {
|
||||
if (!currentUrl.value) {
|
||||
loadPage();
|
||||
return;
|
||||
}
|
||||
frameKey.value += 1;
|
||||
};
|
||||
|
||||
const openInNewTab = () => {
|
||||
const normalized = currentUrl.value || normalizeBrowserInput(draftUrl.value);
|
||||
if (!normalized) {
|
||||
options.warn(options.enterUrlMessage);
|
||||
return;
|
||||
}
|
||||
window.open(normalized, '_blank', 'noopener,noreferrer');
|
||||
};
|
||||
|
||||
const onUrlEnter = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Enter') return;
|
||||
event.preventDefault();
|
||||
loadPage();
|
||||
};
|
||||
|
||||
const handleResizeMove = (event: MouseEvent) => {
|
||||
if (!isResizing.value) return;
|
||||
panelWidth.value = clampPanelWidth(window.innerWidth - event.clientX);
|
||||
};
|
||||
|
||||
const stopResize = () => {
|
||||
if (!isResizing.value) return;
|
||||
isResizing.value = false;
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
window.removeEventListener('mousemove', handleResizeMove);
|
||||
window.removeEventListener('mouseup', stopResize);
|
||||
};
|
||||
|
||||
const startResize = (event: MouseEvent) => {
|
||||
if (viewportWidth.value < 1024) return;
|
||||
event.preventDefault();
|
||||
isResizing.value = true;
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
window.addEventListener('mousemove', handleResizeMove);
|
||||
window.addEventListener('mouseup', stopResize);
|
||||
};
|
||||
|
||||
const syncViewportWidth = () => {
|
||||
viewportWidth.value = window.innerWidth;
|
||||
if (viewportWidth.value >= 1024) {
|
||||
panelWidth.value = clampPanelWidth(panelWidth.value);
|
||||
}
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
open.value = false;
|
||||
};
|
||||
|
||||
const toggle = () => {
|
||||
open.value = !open.value;
|
||||
};
|
||||
|
||||
return {
|
||||
open,
|
||||
draftUrl,
|
||||
currentUrl,
|
||||
frameKey,
|
||||
panelStyle,
|
||||
isResizing,
|
||||
loadPage,
|
||||
refreshPage,
|
||||
openInNewTab,
|
||||
onUrlEnter,
|
||||
startResize,
|
||||
stopResize,
|
||||
syncViewportWidth,
|
||||
close,
|
||||
toggle,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* features/chat/composables/useChatGuides.ts
|
||||
* Agent 学习之窗:指南列表加载与弹窗状态。
|
||||
*/
|
||||
import { computed, ref, type ComputedRef } from 'vue';
|
||||
import { listAgentGuides } from '@/features/auth/api/user.api';
|
||||
|
||||
export interface AgentGuide {
|
||||
id: number;
|
||||
file_name: string;
|
||||
file_type?: string;
|
||||
file_url?: string;
|
||||
file_path?: string;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
export interface UseChatGuidesOptions {
|
||||
currentAgentId: ComputedRef<number>;
|
||||
}
|
||||
|
||||
export function useChatGuides(options: UseChatGuidesOptions) {
|
||||
const { currentAgentId } = options;
|
||||
|
||||
const guides = ref<AgentGuide[]>([]);
|
||||
const showModal = ref(false);
|
||||
const activeGuideId = ref<number | null>(null);
|
||||
const showSidebar = ref(true);
|
||||
|
||||
const activeGuide = computed(() => guides.value.find((g) => g.id === activeGuideId.value));
|
||||
|
||||
const loadGuides = async () => {
|
||||
try {
|
||||
const res = await listAgentGuides(currentAgentId.value || 0);
|
||||
guides.value = Array.isArray(res) ? (res as AgentGuide[]) : [];
|
||||
} catch (error) {
|
||||
console.error('Failed to load agent guides:', error);
|
||||
guides.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const clearGuides = () => {
|
||||
guides.value = [];
|
||||
};
|
||||
|
||||
const openModal = () => {
|
||||
const first = guides.value[0];
|
||||
if (!first) return;
|
||||
activeGuideId.value = first.id;
|
||||
showModal.value = true;
|
||||
showSidebar.value = true;
|
||||
};
|
||||
|
||||
const closeModal = () => {
|
||||
showModal.value = false;
|
||||
};
|
||||
|
||||
return {
|
||||
guides,
|
||||
showModal,
|
||||
activeGuideId,
|
||||
activeGuide,
|
||||
showSidebar,
|
||||
loadGuides,
|
||||
clearGuides,
|
||||
openModal,
|
||||
closeModal,
|
||||
};
|
||||
}
|
||||
|
||||
export type UseChatGuidesReturn = ReturnType<typeof useChatGuides>;
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/composables/useChatHistory.ts
|
||||
* 跨 Agent 聊天历史列表(工作台 History 页 / 移动端 Tab)。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { getAuthHeaders } from '@/utils/auth';
|
||||
import { requestJson } from '@/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import type { ChatCrossAgentHistoryItem } from '../types/chat.types';
|
||||
|
||||
export function useChatHistory() {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* features/chat/composables/useChatLeave.ts
|
||||
* 请假(OA)编排层:组合 leave/* 子模块,对外暴露 ChatView 所需 API。
|
||||
*
|
||||
* 消息类型约定(写入 messages 列表):
|
||||
* - leave-form:可编辑表单
|
||||
* - leave-confirmation:提交前确认
|
||||
* - leave-result:OA 提交结果
|
||||
*/
|
||||
import { computed, type ComputedRef, type Ref } from 'vue';
|
||||
import { getUserProfile } from '@/features/auth/api/user.api';
|
||||
import { LEAVE_FEATURE_AGENT_NAMES, LEAVE_TYPES } from '../constants/leave';
|
||||
import {
|
||||
createLeaveAgentPickerApi,
|
||||
createLeaveFlowApi,
|
||||
createLeaveFormApi,
|
||||
createLeaveLocalMessageApi,
|
||||
createLeaveOaLoginApi,
|
||||
formatDurationLabel,
|
||||
formatYesNoLabel,
|
||||
getLeaveAgentDisplayValue,
|
||||
getLeaveConfirmationPayload,
|
||||
getLeaveFormPayload,
|
||||
getLeaveResultPayload,
|
||||
syncLeaveDuration,
|
||||
} from '../leave';
|
||||
import { getLeaveTypeLabel } from '../leave/leaveDisplay';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
|
||||
export interface UseChatLeaveOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgent: Ref<{ name?: string } | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
currentUser: Ref<Record<string, unknown> | null>;
|
||||
currentUserDisplayName: ComputedRef<string>;
|
||||
currentUserEmployeeId: ComputedRef<string>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
isThinking: Ref<boolean>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function useChatLeave(options: UseChatLeaveOptions) {
|
||||
const {
|
||||
deps: { t, msg },
|
||||
currentAgent,
|
||||
currentAgentId,
|
||||
currentUser,
|
||||
currentUserDisplayName,
|
||||
currentUserEmployeeId,
|
||||
messages,
|
||||
conversationId,
|
||||
isThinking,
|
||||
history,
|
||||
loadHistory,
|
||||
} = options;
|
||||
|
||||
const canUseLeaveFeature = computed(() =>
|
||||
LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim()),
|
||||
);
|
||||
|
||||
const { newLocalMessageId, saveLocalMessageToBackend } = createLeaveLocalMessageApi({
|
||||
conversationId,
|
||||
currentAgentId,
|
||||
});
|
||||
|
||||
const oaLogin = createLeaveOaLoginApi({
|
||||
currentUserEmployeeId,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const agentPicker = createLeaveAgentPickerApi({
|
||||
currentAgentId,
|
||||
messages,
|
||||
saveLocalMessageToBackend,
|
||||
});
|
||||
|
||||
const formApi = createLeaveFormApi({
|
||||
messages,
|
||||
currentUserDisplayName,
|
||||
currentUserEmployeeId,
|
||||
newLocalMessageId,
|
||||
saveLocalMessageToBackend,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const flowApi = createLeaveFlowApi({
|
||||
canUseLeaveFeature,
|
||||
isThinking,
|
||||
messages,
|
||||
conversationId,
|
||||
history,
|
||||
currentAgentId,
|
||||
loadHistory,
|
||||
newLocalMessageId,
|
||||
saveLocalMessageToBackend,
|
||||
createLeaveFormData: formApi.createLeaveFormData,
|
||||
checkLeaveBalance: formApi.checkLeaveBalance,
|
||||
formatLeaveBalanceNumber: formApi.formatLeaveBalanceNumber,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const syncCurrentUserProfile = async () => {
|
||||
if (currentUser.value?.real_name && String(currentUser.value.real_name).trim()) return;
|
||||
try {
|
||||
const data = await getUserProfile();
|
||||
currentUser.value = { ...currentUser.value, ...data };
|
||||
} catch (e) {
|
||||
console.error('Failed to load current user profile', e);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
LEAVE_TYPES,
|
||||
canUseLeaveFeature,
|
||||
...oaLogin,
|
||||
...agentPicker,
|
||||
getLeaveTypeLabel,
|
||||
formatDurationLabel: (hours: number, leaveType?: string) => formatDurationLabel(hours, leaveType, t),
|
||||
formatYesNoLabel,
|
||||
syncLeaveDuration,
|
||||
getLeaveFormPayload,
|
||||
getLeaveConfirmationPayload,
|
||||
getLeaveResultPayload,
|
||||
getLeaveAgentDisplayValue,
|
||||
submitLeaveForm: formApi.submitLeaveForm,
|
||||
editLeaveConfirmation: formApi.editLeaveConfirmation,
|
||||
confirmLeaveSubmission: formApi.confirmLeaveSubmission,
|
||||
tryHandleLeaveSend: flowApi.tryHandleLeaveSend,
|
||||
handleLeaveMarkdownClick: flowApi.handleLeaveMarkdownClick,
|
||||
syncCurrentUserProfile,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
/**
|
||||
* features/chat/composables/useChatPage.ts
|
||||
* 对话页主编排:组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
|
||||
*/
|
||||
import { computed, markRaw, ref, watch } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { config } from '@/config';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useIsMobile } from '@/shared/composables/useIsMobile';
|
||||
import { useTheme } from '@/shared/composables/useTheme';
|
||||
import { stripReasoningPrelude } from '../utils/chatText';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { useChat } from './useChat';
|
||||
import { useChatAgent } from './useChatAgent';
|
||||
import { useChatAttachments } from './useChatAttachments';
|
||||
import { useChatBrowserPanel } from './useChatBrowserPanel';
|
||||
import { useChatGuides } from './useChatGuides';
|
||||
import { useChatLeave } from './useChatLeave';
|
||||
import { useChatQueryPreview } from './useChatQueryPreview';
|
||||
import { useChatRouteSync } from './useChatRouteSync';
|
||||
import { useChatScroll } from './useChatScroll';
|
||||
import { useChatSessions } from './useChatSessions';
|
||||
import { useChatShipping } from './useChatShipping';
|
||||
import { useChatSourceFiles } from './useChatSourceFiles';
|
||||
import { useChatStore } from '../stores/chat.store';
|
||||
import {
|
||||
createChatPageConversationApi,
|
||||
createChatPageLocalMessageApi,
|
||||
createChatPageMarkdownApi,
|
||||
createChatPageSendApi,
|
||||
createLeaveMessageHandlers,
|
||||
createShippingMappingHandlers,
|
||||
createShippingPickerRefHolder,
|
||||
useChatPageDialogs,
|
||||
useChatPageUser,
|
||||
useChatPageVoice,
|
||||
} from '../page';
|
||||
|
||||
export function useChatPage() {
|
||||
const { t, locale } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const msg = useMessage();
|
||||
const { isMobile } = useIsMobile();
|
||||
const { appliedTheme, toggleLightDark } = useTheme();
|
||||
const deps: ChatDeps = { t, locale, msg, router, route };
|
||||
const chatStore = useChatStore();
|
||||
const { sidebarCollapsed } = storeToRefs(chatStore);
|
||||
|
||||
const currentAgentId = computed(() => {
|
||||
const id = Number(route.params.agentId);
|
||||
return Number.isFinite(id) && id > 0 ? id : 0;
|
||||
});
|
||||
|
||||
const { currentUser, currentUserDisplayName, currentUserEmployeeId, onAuthLogout, handleLogout, goToAdmin } =
|
||||
useChatPageUser(router);
|
||||
|
||||
const chatScrollContainer = ref<HTMLElement | null>(null);
|
||||
/** markRaw:避免 reactive(page) 解包内部 Ref,供 template ref 回写 */
|
||||
const scrollContainerHolder = markRaw({ el: chatScrollContainer });
|
||||
const input = ref('');
|
||||
const isSidebarOpen = ref(false);
|
||||
const copiedIndex = ref<number | null>(null);
|
||||
|
||||
const {
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
runs,
|
||||
activeRunId,
|
||||
activateRun,
|
||||
createNewChatView,
|
||||
loadConversationState,
|
||||
sendMessage,
|
||||
} = useChat();
|
||||
|
||||
const browser = useChatBrowserPanel({
|
||||
warn: (text) => msg.warning(text),
|
||||
invalidUrlMessage: t('chat.invalidBrowserUrl'),
|
||||
enterUrlMessage: t('chat.enterBrowserUrl'),
|
||||
});
|
||||
|
||||
const queryPreview = useChatQueryPreview({ currentAgentId });
|
||||
const scroll = useChatScroll({ container: chatScrollContainer, messages });
|
||||
scroll.setupThinkingScrollWatch(isThinking, conversationId);
|
||||
|
||||
const resetPeripheralState = () => {
|
||||
browser.close();
|
||||
queryPreview.close();
|
||||
};
|
||||
|
||||
const disposePeripherals = () => {
|
||||
browser.stopResize();
|
||||
scroll.dispose();
|
||||
};
|
||||
|
||||
const chatGuides = useChatGuides({ currentAgentId });
|
||||
const agent = useChatAgent({ deps, currentAgentId, chatGuides });
|
||||
const attachmentApi = useChatAttachments({
|
||||
deps,
|
||||
currentAgentId,
|
||||
currentAgent: agent.currentAgent,
|
||||
});
|
||||
|
||||
const sourceFiles = useChatSourceFiles({ agentId: currentAgentId, t, msg, isMobile });
|
||||
const {
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
getSourceTitle,
|
||||
getSourceMeta,
|
||||
getSourceBrief,
|
||||
getSourceLinks,
|
||||
getMessageLinks,
|
||||
getDisplayRetrieverResources,
|
||||
shouldExpandSourceDetails,
|
||||
openPreview,
|
||||
parsePlmPreviewLink,
|
||||
} = sourceFiles;
|
||||
|
||||
watch(currentAgentId, (id) => {
|
||||
chatStore.setCurrentAgentId(id > 0 ? id : null);
|
||||
}, { immediate: true });
|
||||
|
||||
const dialogs = useChatPageDialogs(messages);
|
||||
const { openDeleteConfirmDialog } = dialogs;
|
||||
|
||||
let loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
let startNewChat: () => void;
|
||||
|
||||
const {
|
||||
history,
|
||||
loadHistory,
|
||||
clearHistory,
|
||||
displayHistory,
|
||||
activeHistoryKey,
|
||||
handleHistorySelect,
|
||||
refreshHistoryAfterSend,
|
||||
setupConversationIdHistoryWatch,
|
||||
clearAllHistory,
|
||||
deleteHistoryItem,
|
||||
} = useChatSessions({
|
||||
deps,
|
||||
currentAgentId,
|
||||
conversationId,
|
||||
activeRunId,
|
||||
runs,
|
||||
activateRun,
|
||||
loadConversation: (id, opts) => loadConversation(id, opts),
|
||||
isSidebarOpen,
|
||||
onConfirmDelete: openDeleteConfirmDialog,
|
||||
startNewChat: () => startNewChat(),
|
||||
});
|
||||
|
||||
setupConversationIdHistoryWatch();
|
||||
|
||||
const voice = useChatPageVoice({ input, isThinking, msg, t });
|
||||
|
||||
const leave = useChatLeave({
|
||||
deps,
|
||||
currentAgent: agent.currentAgent,
|
||||
currentAgentId,
|
||||
currentUser,
|
||||
currentUserDisplayName,
|
||||
currentUserEmployeeId,
|
||||
messages,
|
||||
conversationId,
|
||||
isThinking,
|
||||
history,
|
||||
loadHistory,
|
||||
});
|
||||
|
||||
const { newLocalMessageId, saveLocalMessageToBackend } = createChatPageLocalMessageApi({
|
||||
conversationId,
|
||||
currentAgentId,
|
||||
});
|
||||
|
||||
const presetQuestion = computed(() => {
|
||||
const q = route.query.preset;
|
||||
return typeof q === 'string' ? q : '';
|
||||
});
|
||||
|
||||
const shipping = useChatShipping({
|
||||
deps,
|
||||
currentAgent: agent.currentAgent,
|
||||
currentAgentId,
|
||||
messages,
|
||||
conversationId,
|
||||
isThinking,
|
||||
history,
|
||||
loadHistory,
|
||||
input,
|
||||
chatScrollContainer,
|
||||
attachments: attachmentApi.attachments,
|
||||
selectedKb: agent.selectedKb,
|
||||
isUploadingAttachments: attachmentApi.isUploadingAttachments,
|
||||
attachmentPolicy: attachmentApi.attachmentPolicy,
|
||||
presetQuestion,
|
||||
saveLocalMessageToBackend,
|
||||
newLocalMessageId,
|
||||
stripReasoningPrelude,
|
||||
sendMessage,
|
||||
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
|
||||
loadConversation: (id, opts) => loadConversation(id, opts),
|
||||
createNewChatView,
|
||||
});
|
||||
|
||||
const conversationApi = createChatPageConversationApi({
|
||||
deps,
|
||||
route,
|
||||
router,
|
||||
currentAgentId,
|
||||
conversationId,
|
||||
activeRunId,
|
||||
messages,
|
||||
isThinking,
|
||||
loadConversationState,
|
||||
createNewChatView,
|
||||
onConversationIdChanging: shipping.onConversationIdChanging,
|
||||
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
|
||||
onConversationLoadFailed: shipping.onConversationLoadFailed,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
|
||||
clearHistory,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
input,
|
||||
resetCurrentAgent: () => { agent.currentAgent.value = null; },
|
||||
copiedIndex,
|
||||
resetPeripheralState,
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
});
|
||||
|
||||
({ loadConversation, startNewChat } = conversationApi);
|
||||
const { resetChatStateForAgentChange } = conversationApi;
|
||||
|
||||
const markdown = createChatPageMarkdownApi({
|
||||
messages,
|
||||
isThinking,
|
||||
prepareMarkdownDisplayText: shipping.prepareMarkdownDisplayText,
|
||||
handleLeaveMarkdownClick: leave.handleLeaveMarkdownClick,
|
||||
parsePlmPreviewLink,
|
||||
openPreview,
|
||||
getMessageLinks,
|
||||
getDisplayRetrieverResources,
|
||||
getSourceLinks,
|
||||
shouldExpandSourceDetails,
|
||||
getSourceTitle,
|
||||
getSourceMeta,
|
||||
getSourceBrief,
|
||||
getShippingInventoryMappingPayload: shipping.getShippingInventoryMappingPayload,
|
||||
canOpenQueryPreview: queryPreview.canOpen,
|
||||
getQueryPreviewSummary: queryPreview.getSummary,
|
||||
openQueryPreviewDialog: queryPreview.openDialog,
|
||||
shippingActionButtonClass: shipping.shippingActionButtonClass,
|
||||
onShippingActionClick: shipping.handleShippingActionClick,
|
||||
});
|
||||
|
||||
const sendApi = createChatPageSendApi({
|
||||
input,
|
||||
messages,
|
||||
isThinking,
|
||||
currentAgentId,
|
||||
selectedKb: agent.selectedKb,
|
||||
isUploadingAttachments: attachmentApi.isUploadingAttachments,
|
||||
attachmentPolicy: attachmentApi.attachmentPolicy,
|
||||
attachments: attachmentApi.attachments,
|
||||
allowsSendWithAttachmentsOnly: shipping.allowsSendWithAttachmentsOnly,
|
||||
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
sendMessage,
|
||||
refreshHistoryAfterSend,
|
||||
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
|
||||
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
||||
tryHandleShippingSend: shipping.tryHandleShippingSend,
|
||||
msg,
|
||||
t,
|
||||
copiedIndex,
|
||||
});
|
||||
|
||||
shipping.shippingBindSend(() => sendApi.handleSend());
|
||||
|
||||
const leaveMessageHandlers = createLeaveMessageHandlers(leave);
|
||||
const shippingMappingHandlers = createShippingMappingHandlers(shipping);
|
||||
const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef));
|
||||
|
||||
const showChatRating = ref(false);
|
||||
|
||||
const routeSync = useChatRouteSync({
|
||||
deps,
|
||||
currentAgentId,
|
||||
presetQuestion,
|
||||
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
resetChatStateForAgentChange,
|
||||
cancelVoiceInput: voice.cancelVoiceInput,
|
||||
syncCurrentUserProfile: leave.syncCurrentUserProfile,
|
||||
loadAgent: agent.loadAgent,
|
||||
loadUserAgents: agent.loadUserAgents,
|
||||
loadHistory,
|
||||
loadConversation,
|
||||
resumeShippingTaskFromQuery: shipping.resumeShippingTaskFromQuery,
|
||||
handleSend: sendApi.handleSend,
|
||||
createNewChatView,
|
||||
onAuthLogout,
|
||||
onViewportResize: () => browser.syncViewportWidth(),
|
||||
disposePeripherals,
|
||||
scheduleScrollToBottom: () => scroll.scheduleScrollToBottom(),
|
||||
onMountedExtra: () => {
|
||||
showChatRating.value = config.workspace?.showChatRating ?? true;
|
||||
},
|
||||
input,
|
||||
});
|
||||
|
||||
watch(locale, (newLang) => {
|
||||
localStorage.setItem('hxops_lang', String(newLang));
|
||||
});
|
||||
|
||||
const handleSidebarNewChat = () => {
|
||||
startNewChat();
|
||||
isSidebarOpen.value = false;
|
||||
};
|
||||
|
||||
return {
|
||||
t,
|
||||
msg,
|
||||
isMobile,
|
||||
appliedTheme,
|
||||
toggleLightDark,
|
||||
currentAgentId,
|
||||
currentUser,
|
||||
chatScrollContainer,
|
||||
scrollContainerHolder,
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
input,
|
||||
browser,
|
||||
queryPreview,
|
||||
browserPanelOpen: browser.open,
|
||||
browserDraftUrl: browser.draftUrl,
|
||||
browserCurrentUrl: browser.currentUrl,
|
||||
browserFrameKey: browser.frameKey,
|
||||
browserPanelStyle: browser.panelStyle,
|
||||
isBrowserResizing: browser.isResizing,
|
||||
showQueryPreviewDialog: queryPreview.show,
|
||||
queryPreviewLoading: queryPreview.loading,
|
||||
queryPreviewError: queryPreview.error,
|
||||
queryPreviewState: queryPreview.state,
|
||||
...agent,
|
||||
agentGuides: chatGuides.guides,
|
||||
showGuideModal: chatGuides.showModal,
|
||||
activeGuideId: chatGuides.activeGuideId,
|
||||
activeGuide: chatGuides.activeGuide,
|
||||
showGuideSidebar: chatGuides.showSidebar,
|
||||
openGuideModal: chatGuides.openModal,
|
||||
...attachmentApi,
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
isSidebarOpen,
|
||||
sidebarCollapsed,
|
||||
toggleBrowserPanel: browser.toggle,
|
||||
copiedIndex,
|
||||
displayHistory,
|
||||
activeHistoryKey,
|
||||
handleHistorySelect,
|
||||
clearAllHistory,
|
||||
deleteHistoryItem,
|
||||
isVoiceRecording: voice.isVoiceRecording,
|
||||
isVoiceTranscribing: voice.isVoiceTranscribing,
|
||||
handleVoiceFeatureClick: voice.handleVoiceFeatureClick,
|
||||
...leave,
|
||||
leaveMessageHandlers,
|
||||
shippingMappingHandlers,
|
||||
shippingPickerRefHolder,
|
||||
shouldShowThinkingBubble: markdown.shouldShowThinkingBubble,
|
||||
messageBubbleHandlers: markdown.messageBubbleHandlers,
|
||||
shouldRenderMessage: markdown.shouldRenderMessage,
|
||||
canSendMessage: sendApi.canSendMessage,
|
||||
handleSend: sendApi.handleSend,
|
||||
copyToClipboard: sendApi.copyToClipboard,
|
||||
regenerate: sendApi.regenerate,
|
||||
handleOpenFeedback: dialogs.handleOpenFeedback,
|
||||
activeFeedbackMessageIndex: dialogs.activeFeedbackMessageIndex,
|
||||
showGeneralFeedbackDialog: dialogs.showGeneralFeedbackDialog,
|
||||
currentGeneralFeedbackChatLogId: dialogs.currentGeneralFeedbackChatLogId,
|
||||
showDeleteConfirmDialog: dialogs.showDeleteConfirmDialog,
|
||||
deleteConfirmMessage: dialogs.deleteConfirmMessage,
|
||||
closeDeleteConfirmDialog: dialogs.closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm: dialogs.handleDeleteConfirm,
|
||||
showChatRating,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
|
||||
handleShippingInventorySelected: shipping.handleShippingInventorySelected,
|
||||
useShippingSuggestedPrompt: shipping.useShippingSuggestedPrompt,
|
||||
handleSidebarNewChat,
|
||||
goToWorkspace: routeSync.goToWorkspace,
|
||||
switchToAgent: agent.switchToAgent,
|
||||
loadUserAgents: agent.loadUserAgents,
|
||||
handleLogout,
|
||||
goToAdmin,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* features/chat/composables/useChatQueryPreview.ts
|
||||
* Text2SQL 查询结果全量预览弹窗:分页加载与消息 payload 解析。
|
||||
*/
|
||||
import { ref, type ComputedRef } from 'vue';
|
||||
import { getChatQueryPreviewPage } from '../api/chat.api';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
type QueryPreviewPayload = {
|
||||
kind: 'text2sql_result_preview';
|
||||
previewable?: boolean;
|
||||
total_count?: number;
|
||||
preview_row_count?: number;
|
||||
query?: string;
|
||||
};
|
||||
|
||||
export interface QueryPreviewState {
|
||||
chatLogId: number;
|
||||
title: string;
|
||||
query: string;
|
||||
columns: string[];
|
||||
rows: unknown[][];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface UseChatQueryPreviewOptions {
|
||||
currentAgentId: ComputedRef<number>;
|
||||
}
|
||||
|
||||
export function useChatQueryPreview(options: UseChatQueryPreviewOptions) {
|
||||
const { currentAgentId } = options;
|
||||
|
||||
const show = ref(false);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const state = ref<QueryPreviewState>({
|
||||
chatLogId: 0,
|
||||
title: '',
|
||||
query: '',
|
||||
columns: [],
|
||||
rows: [],
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
total: 0,
|
||||
});
|
||||
|
||||
const getPayload = (msg: ChatMessage): QueryPreviewPayload | null => {
|
||||
const payload = msg?.payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
if ((payload as QueryPreviewPayload).kind !== 'text2sql_result_preview') return null;
|
||||
return payload as QueryPreviewPayload;
|
||||
};
|
||||
|
||||
const canOpen = (msg: ChatMessage) => {
|
||||
const payload = getPayload(msg);
|
||||
return !!(payload?.previewable && Number(msg?.chat_log_id) > 0);
|
||||
};
|
||||
|
||||
const getSummary = (msg: ChatMessage) => {
|
||||
const payload = getPayload(msg);
|
||||
const total = Number(payload?.total_count || 0);
|
||||
if (total > 0) return `查看全部预览(共 ${total} 条)`;
|
||||
return '查看全部预览';
|
||||
};
|
||||
|
||||
const totalPages = () =>
|
||||
Math.max(1, Math.ceil((state.value.total || 0) / (state.value.pageSize || 100)));
|
||||
|
||||
const close = () => {
|
||||
show.value = false;
|
||||
error.value = '';
|
||||
};
|
||||
|
||||
const loadPage = async (chatLogId: number, page = 1) => {
|
||||
if (!currentAgentId.value) {
|
||||
error.value = '当前 Agent 未就绪,请稍后重试';
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const result = await getChatQueryPreviewPage(currentAgentId.value, chatLogId, {
|
||||
page,
|
||||
page_size: state.value.pageSize,
|
||||
});
|
||||
state.value = {
|
||||
...state.value,
|
||||
chatLogId,
|
||||
title: String(result.query || state.value.title || '查询结果全量预览').trim() || '查询结果全量预览',
|
||||
query: String(result.query || '').trim(),
|
||||
columns: Array.isArray(result.columns) ? result.columns : [],
|
||||
rows: Array.isArray(result.rows) ? result.rows : [],
|
||||
page: Number(result.page || page || 1),
|
||||
pageSize: Number(result.page_size || state.value.pageSize || 100),
|
||||
total: Number(result.total || 0),
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
error.value = (err as { message?: string })?.message || '加载全量预览失败';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openDialog = async (msg: ChatMessage) => {
|
||||
const chatLogId = Number(msg?.chat_log_id || 0);
|
||||
if (!chatLogId) return;
|
||||
const payload = getPayload(msg);
|
||||
state.value = {
|
||||
...state.value,
|
||||
chatLogId,
|
||||
title: String(payload?.query || msg?.content || '查询结果全量预览').trim() || '查询结果全量预览',
|
||||
query: String(payload?.query || '').trim(),
|
||||
page: 1,
|
||||
total: Number(payload?.total_count || 0),
|
||||
};
|
||||
show.value = true;
|
||||
await loadPage(chatLogId, 1);
|
||||
};
|
||||
|
||||
const changePage = async (delta: number) => {
|
||||
const nextPage = state.value.page + delta;
|
||||
if (nextPage < 1 || nextPage > totalPages()) return;
|
||||
await loadPage(state.value.chatLogId, nextPage);
|
||||
};
|
||||
|
||||
return {
|
||||
show,
|
||||
loading,
|
||||
error,
|
||||
state,
|
||||
totalPages,
|
||||
getPayload,
|
||||
canOpen,
|
||||
getSummary,
|
||||
openDialog,
|
||||
close,
|
||||
changePage,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* features/chat/composables/useChatRouteSync.ts
|
||||
* 路由与 Agent 切换时的状态同步、挂载/卸载生命周期。
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted, watch, type ComputedRef, type Ref } from 'vue';
|
||||
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
|
||||
import { registerOpenAgentId } from '@/shared/utils/agentTabs';
|
||||
import { workspacePathFromLegacyView } from '@/features/workspace/constants/routes';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
|
||||
export interface UseChatRouteSyncOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
presetQuestion: ComputedRef<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string | null>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
resetChatStateForAgentChange: () => void;
|
||||
cancelVoiceInput: () => void;
|
||||
syncCurrentUserProfile: () => Promise<void>;
|
||||
loadAgent: () => Promise<void>;
|
||||
loadUserAgents: () => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
resumeShippingTaskFromQuery: () => Promise<void>;
|
||||
handleSend: (textOrEvent?: string | Event) => Promise<void>;
|
||||
createNewChatView: () => void;
|
||||
onAuthLogout: () => void;
|
||||
onViewportResize: () => void;
|
||||
disposePeripherals: () => void;
|
||||
scheduleScrollToBottom: () => void;
|
||||
onMountedExtra?: () => void | Promise<void>;
|
||||
input: Ref<string>;
|
||||
}
|
||||
|
||||
export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
const {
|
||||
deps: { route, router },
|
||||
currentAgentId,
|
||||
presetQuestion,
|
||||
shippingTaskIdFromQuery,
|
||||
resetChatStateForAgentChange,
|
||||
cancelVoiceInput,
|
||||
syncCurrentUserProfile,
|
||||
loadAgent,
|
||||
loadUserAgents,
|
||||
loadHistory,
|
||||
loadConversation,
|
||||
resumeShippingTaskFromQuery,
|
||||
handleSend,
|
||||
createNewChatView,
|
||||
onAuthLogout,
|
||||
onViewportResize,
|
||||
disposePeripherals,
|
||||
scheduleScrollToBottom,
|
||||
onMountedExtra,
|
||||
input,
|
||||
} = options;
|
||||
|
||||
let routeSyncToken = 0;
|
||||
|
||||
const syncOpenAgentRegistration = () => {
|
||||
const id = Number(route.params.agentId);
|
||||
registerOpenAgentId(Number.isFinite(id) && id > 0 ? id : null);
|
||||
};
|
||||
|
||||
const onPageHide = () => {
|
||||
registerOpenAgentId(null);
|
||||
};
|
||||
|
||||
const goToWorkspace = (view?: string) => {
|
||||
setLastChatAgentId(currentAgentId.value);
|
||||
registerOpenAgentId(null);
|
||||
router.push({ path: workspacePathFromLegacyView(view), query: { no_redirect: '1' } });
|
||||
};
|
||||
|
||||
const syncChatStateForRoute = async () => {
|
||||
const agentId = currentAgentId.value;
|
||||
if (!agentId) return;
|
||||
|
||||
const syncToken = ++routeSyncToken;
|
||||
resetChatStateForAgentChange();
|
||||
cancelVoiceInput();
|
||||
setLastChatAgentId(agentId);
|
||||
syncOpenAgentRegistration();
|
||||
|
||||
await syncCurrentUserProfile();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
await loadAgent();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
await loadUserAgents();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
await loadHistory();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
const convId = route.query.conversation_id as string;
|
||||
if (convId) {
|
||||
await loadConversation(convId, { force: true });
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
} else if (shippingTaskIdFromQuery.value) {
|
||||
await resumeShippingTaskFromQuery();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
}
|
||||
|
||||
if (presetQuestion.value) {
|
||||
input.value = presetQuestion.value;
|
||||
await handleSend();
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
window.addEventListener('pagehide', onPageHide);
|
||||
window.addEventListener('hxops:logout', onAuthLogout);
|
||||
window.addEventListener('resize', onViewportResize);
|
||||
await syncChatStateForRoute();
|
||||
await onMountedExtra?.();
|
||||
scheduleScrollToBottom();
|
||||
});
|
||||
|
||||
watch(
|
||||
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id],
|
||||
async ([nextAgentId, nextConversationId, nextPreset, nextTaskId], [prevAgentId, prevConversationId, prevPreset, prevTaskId]) => {
|
||||
if (
|
||||
nextAgentId === prevAgentId
|
||||
&& nextConversationId === prevConversationId
|
||||
&& nextPreset === prevPreset
|
||||
&& nextTaskId === prevTaskId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
nextAgentId === prevAgentId
|
||||
&& nextPreset === prevPreset
|
||||
&& nextTaskId === prevTaskId
|
||||
&& nextConversationId !== prevConversationId
|
||||
) {
|
||||
if (typeof nextConversationId === 'string' && nextConversationId) {
|
||||
await loadConversation(nextConversationId, { force: true });
|
||||
} else {
|
||||
createNewChatView();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await syncChatStateForRoute();
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('pagehide', onPageHide);
|
||||
window.removeEventListener('hxops:logout', onAuthLogout);
|
||||
window.removeEventListener('resize', onViewportResize);
|
||||
disposePeripherals();
|
||||
});
|
||||
|
||||
return {
|
||||
goToWorkspace,
|
||||
syncChatStateForRoute,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* features/chat/composables/useChatScroll.ts
|
||||
* 聊天主区域滚动:贴底、滚到最新用户问题与思考态切换时的滚动策略。
|
||||
*/
|
||||
import { nextTick, watch, type Ref } from 'vue';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
export interface UseChatScrollOptions {
|
||||
container: Ref<HTMLElement | null>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
}
|
||||
|
||||
export function useChatScroll(options: UseChatScrollOptions) {
|
||||
const { container, messages } = options;
|
||||
let scrollToBottomFrame: number | null = null;
|
||||
|
||||
const scrollToBottom = async () => {
|
||||
await nextTick();
|
||||
const el = container.value;
|
||||
if (!el) return;
|
||||
el.scrollTo({
|
||||
top: el.scrollHeight,
|
||||
behavior: 'auto',
|
||||
});
|
||||
};
|
||||
|
||||
const scrollToUserQuestion = async () => {
|
||||
if (scrollToBottomFrame !== null) {
|
||||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||||
scrollToBottomFrame = null;
|
||||
}
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
const el = container.value;
|
||||
if (!el) return;
|
||||
let lastUserIndex = -1;
|
||||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||||
if (messages.value[i]?.role === 'user') {
|
||||
lastUserIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastUserIndex < 0) return;
|
||||
const target = el.querySelector(`[data-msg-index="${lastUserIndex}"]`) as HTMLElement | null;
|
||||
target?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
};
|
||||
|
||||
const scheduleScrollToBottom = () => {
|
||||
if (scrollToBottomFrame !== null) {
|
||||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||||
}
|
||||
scrollToBottomFrame = window.requestAnimationFrame(() => {
|
||||
scrollToBottomFrame = null;
|
||||
void scrollToBottom();
|
||||
});
|
||||
};
|
||||
|
||||
const dispose = () => {
|
||||
if (scrollToBottomFrame !== null) {
|
||||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||||
scrollToBottomFrame = null;
|
||||
}
|
||||
};
|
||||
|
||||
/** 消息/思考态变化时自动滚动(思考结束滚到用户问题,否则贴底) */
|
||||
const setupThinkingScrollWatch = (isThinking: Ref<boolean>, conversationId?: Ref<string | null>) => {
|
||||
let wasThinking = false;
|
||||
watch(
|
||||
() => ({
|
||||
messageCount: messages.value.length,
|
||||
lastMessageContent: messages.value[messages.value.length - 1]?.content || '',
|
||||
lastMessageRole: messages.value[messages.value.length - 1]?.role || '',
|
||||
isThinking: isThinking.value,
|
||||
conversationId: conversationId?.value || '',
|
||||
}),
|
||||
() => {
|
||||
if (wasThinking && !isThinking.value) {
|
||||
wasThinking = false;
|
||||
void scrollToUserQuestion();
|
||||
} else {
|
||||
if (isThinking.value) wasThinking = true;
|
||||
scheduleScrollToBottom();
|
||||
}
|
||||
},
|
||||
{ deep: false },
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
scrollToBottom,
|
||||
scrollToUserQuestion,
|
||||
scheduleScrollToBottom,
|
||||
setupThinkingScrollWatch,
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* 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 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;
|
||||
}
|
||||
|
||||
await loadConversation(item.conversation_id, { force: true });
|
||||
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) 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();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ── 删除单条 / 清空全部 ───────────────────────────────────
|
||||
const clearAllHistory = async () => {
|
||||
onConfirmDelete(t('chat.confirmClearHistory'), async () => {
|
||||
try {
|
||||
const agentId = currentAgentId.value;
|
||||
await deleteAllChatSessions(agentId);
|
||||
history.value = [];
|
||||
chatStore.setSessionHistory(agentId, []);
|
||||
runs.value = [];
|
||||
if (conversationId.value || activeRunId.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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
/**
|
||||
* features/chat/composables/useChatShipping.ts
|
||||
* 发货通知(出货)编排层:组合 shipping/* 子模块,对外暴露 ChatView 所需 API。
|
||||
*
|
||||
* 子模块职责:
|
||||
* shippingText / shippingMenu / shippingIntents … 纯函数
|
||||
* useChatShippingRefresh 动作按钮刷新
|
||||
* useChatShippingMappingForm 库存列映射表单
|
||||
* useChatShippingDecision 人工决策与手工上传
|
||||
* useChatShippingMenuHandler 气泡动作按钮点击
|
||||
* useChatShippingUploadHandler 文件上传与建议提示
|
||||
* useChatShippingSendHandler handleSend 前置拦截
|
||||
*
|
||||
* 消息类型约定(写入 messages 列表):
|
||||
* - shipping-inventory-mapping:库存列映射表单
|
||||
*/
|
||||
|
||||
import {
|
||||
computed,
|
||||
ref,
|
||||
watch,
|
||||
type ComputedRef,
|
||||
type Ref,
|
||||
} from 'vue';
|
||||
import { SHIPPING_NOTICE_AGENT_NAME } from '@/features/chat/api/shipping.api';
|
||||
|
||||
import {
|
||||
createShippingActionsRefresher,
|
||||
createShippingConversationHelpers,
|
||||
createShippingDecisionHandlers,
|
||||
createShippingLocalMessages,
|
||||
createShippingMappingFormHandlers,
|
||||
createShippingMenuHandlers,
|
||||
createShippingSendHandlers,
|
||||
createShippingUploadHandlers,
|
||||
extractShippingActionsDirective,
|
||||
findHistorySessionForShippingTask,
|
||||
findLatestShippingTaskId,
|
||||
getShippingInventoryMappingPayload,
|
||||
getShippingInventorySampleRowText,
|
||||
hasShippingInventorySampleRows,
|
||||
normalizeShippingHeaderForDisplay,
|
||||
sanitizeShippingConversationText,
|
||||
shippingActionButtonClass,
|
||||
} from '../shipping';
|
||||
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
|
||||
export interface UseChatShippingOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgent: Ref<{ name?: string } | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
isThinking: Ref<boolean>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
input: Ref<string>;
|
||||
chatScrollContainer: Ref<HTMLElement | null>;
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
selectedKb: Ref<string>;
|
||||
isUploadingAttachments: Ref<boolean>;
|
||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||
presetQuestion: ComputedRef<string>;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
stripReasoningPrelude: (text: string) => string;
|
||||
sendMessage: (
|
||||
content: string,
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
) => Promise<void>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
createNewChatView: () => void;
|
||||
}
|
||||
|
||||
export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const {
|
||||
deps: { t, msg, router, route },
|
||||
currentAgent,
|
||||
currentAgentId,
|
||||
messages,
|
||||
conversationId,
|
||||
isThinking,
|
||||
history,
|
||||
loadHistory,
|
||||
input,
|
||||
chatScrollContainer,
|
||||
attachments,
|
||||
selectedKb,
|
||||
isUploadingAttachments,
|
||||
attachmentPolicy,
|
||||
presetQuestion,
|
||||
saveLocalMessageToBackend,
|
||||
newLocalMessageId,
|
||||
stripReasoningPrelude,
|
||||
sendMessage,
|
||||
buildFileSpecsForSend,
|
||||
loadConversation,
|
||||
createNewChatView,
|
||||
} = options;
|
||||
|
||||
let invokeHandleSend: (() => Promise<void>) | null = null;
|
||||
const shippingBindSend = (fn: () => Promise<void>) => {
|
||||
invokeHandleSend = fn;
|
||||
};
|
||||
|
||||
// ── 功能开关与 UI refs ────────────────────────────────────
|
||||
const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME);
|
||||
const allowsSendWithAttachmentsOnly = computed(
|
||||
() => isShippingNoticeAgent.value && attachments.value.length > 0,
|
||||
);
|
||||
const shippingAutoFlowRequested = ref(false);
|
||||
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
|
||||
const pendingShippingUploadTaskId = ref('');
|
||||
|
||||
const prepareMarkdownDisplayText = (text: string) => {
|
||||
const stripped = isShippingNoticeAgent.value ? extractShippingActionsDirective(text).cleanedText : text;
|
||||
return sanitizeShippingConversationText(stripReasoningPrelude(stripped), isShippingNoticeAgent.value);
|
||||
};
|
||||
|
||||
// ── 任务编号状态 ──────────────────────────────────────────
|
||||
const shippingTaskIdFromQuery = computed(() => {
|
||||
const value = route.query.task_id;
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
});
|
||||
const resolvedShippingTaskId = ref('');
|
||||
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
|
||||
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
|
||||
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
|
||||
|
||||
const getActiveShippingTaskId = () =>
|
||||
findLatestShippingTaskId(messages.value)
|
||||
|| resolvedShippingTaskId.value
|
||||
|| shippingTaskIdFromQuery.value
|
||||
|| '';
|
||||
|
||||
const lastAssistantMessageContent = () => {
|
||||
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
|
||||
const item = messages.value[i];
|
||||
if (item?.role === 'assistant') return String(item.content || '');
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const { refreshShippingActions } = createShippingActionsRefresher({
|
||||
isShippingNoticeAgent,
|
||||
messages,
|
||||
conversationId,
|
||||
isThinking,
|
||||
history,
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery,
|
||||
shippingConversationTaskIdCache,
|
||||
});
|
||||
|
||||
const { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage } = createShippingLocalMessages({
|
||||
messages,
|
||||
newLocalMessageId,
|
||||
saveLocalMessageToBackend,
|
||||
});
|
||||
|
||||
const { sendShippingMenuMessage } = createShippingConversationHelpers({
|
||||
conversationId,
|
||||
history,
|
||||
loadHistory,
|
||||
getActiveShippingTaskId,
|
||||
currentAgentId,
|
||||
selectedKb,
|
||||
sendMessage,
|
||||
});
|
||||
|
||||
const {
|
||||
openShippingInventoryMappingFormForTask,
|
||||
applyShippingInventoryMappingForm,
|
||||
reuploadShippingInventoryFromMappingForm,
|
||||
} = createShippingMappingFormHandlers({
|
||||
messages,
|
||||
chatScrollContainer,
|
||||
shippingInventorySchemaPreviewCache,
|
||||
shippingInventoryPickerRef,
|
||||
pendingShippingUploadTaskId,
|
||||
resolvedShippingTaskId,
|
||||
newLocalMessageId,
|
||||
saveLocalMessageToBackend,
|
||||
pushShippingLocalAssistantMessage,
|
||||
refreshShippingActions,
|
||||
msg,
|
||||
});
|
||||
|
||||
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
|
||||
messages,
|
||||
conversationId,
|
||||
history,
|
||||
isShippingNoticeAgent,
|
||||
shippingInventorySchemaPreviewCache,
|
||||
getActiveShippingTaskId,
|
||||
newLocalMessageId,
|
||||
saveLocalMessageToBackend,
|
||||
loadHistory,
|
||||
openShippingInventoryMappingFormForTask,
|
||||
refreshShippingActions,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const {
|
||||
handleShippingAutoUploadFile,
|
||||
openShippingInventoryPicker,
|
||||
handleShippingInventorySelected,
|
||||
shippingSuggestedPrompt,
|
||||
useShippingSuggestedPrompt,
|
||||
} = createShippingUploadHandlers({
|
||||
conversationId,
|
||||
attachments,
|
||||
input,
|
||||
shippingAutoFlowRequested,
|
||||
shippingInventoryPickerRef,
|
||||
pendingShippingUploadTaskId,
|
||||
resolvedShippingTaskId,
|
||||
shippingInventorySchemaPreviewCache,
|
||||
getActiveShippingTaskId,
|
||||
sendShippingMenuMessage,
|
||||
pushShippingLocalAssistantMessage,
|
||||
refreshShippingActions,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const { handleShippingActionClick } = createShippingMenuHandlers({
|
||||
isThinking,
|
||||
getActiveShippingTaskId,
|
||||
messages,
|
||||
newLocalMessageId,
|
||||
saveLocalMessageToBackend,
|
||||
sendShippingMenuMessage,
|
||||
openShippingInventoryMappingFormForTask,
|
||||
openShippingInventoryPicker,
|
||||
executeShippingDecision,
|
||||
executeShippingManualUpload,
|
||||
refreshShippingActions,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers({
|
||||
isShippingNoticeAgent,
|
||||
isThinking,
|
||||
isUploadingAttachments,
|
||||
messages,
|
||||
conversationId,
|
||||
history,
|
||||
input,
|
||||
attachments,
|
||||
shippingAutoFlowRequested,
|
||||
resolvedShippingTaskId,
|
||||
currentAgentId,
|
||||
selectedKb,
|
||||
attachmentPolicy,
|
||||
getActiveShippingTaskId,
|
||||
lastAssistantMessageContent,
|
||||
sendMessage,
|
||||
buildFileSpecsForSend,
|
||||
loadHistory,
|
||||
sendShippingMenuMessage,
|
||||
pushShippingLocalUserMessage,
|
||||
pushShippingLocalAssistantMessage,
|
||||
openShippingInventoryPicker,
|
||||
executeShippingDecision,
|
||||
executeShippingManualUpload,
|
||||
handleShippingAutoUploadFile,
|
||||
refreshShippingActions,
|
||||
shippingSuggestedPrompt,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
// ── 路由 / 会话生命周期 ───────────────────────────────────
|
||||
const resumeShippingTaskFromQuery = async () => {
|
||||
const taskId = shippingTaskIdFromQuery.value;
|
||||
if (!taskId || !isShippingNoticeAgent.value) return;
|
||||
if (route.query.conversation_id) return;
|
||||
if (presetQuestion.value) return;
|
||||
if (autoResumedShippingTasks.value[taskId]) return;
|
||||
const existing = findHistorySessionForShippingTask(history.value, taskId);
|
||||
if (existing) {
|
||||
await loadConversation(existing.conversation_id, { force: true });
|
||||
return;
|
||||
}
|
||||
autoResumedShippingTasks.value[taskId] = true;
|
||||
input.value = t('chat.shippingNoticeContinue', { taskId });
|
||||
await invokeHandleSend?.();
|
||||
};
|
||||
|
||||
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
|
||||
if (prevId !== nextId) {
|
||||
resolvedShippingTaskId.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const onConversationLoadedEmpty = async () => {
|
||||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
|
||||
await router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
|
||||
};
|
||||
|
||||
const onConversationLoadFailed = async () => {
|
||||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
|
||||
createNewChatView();
|
||||
void router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
|
||||
input.value = t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value });
|
||||
await invokeHandleSend?.();
|
||||
};
|
||||
|
||||
// ── 动作按钮 watch ────────────────────────────────────────
|
||||
const shippingActionsWatchKey = computed(() => {
|
||||
const msgs = messages.value;
|
||||
const last = msgs.length ? msgs[msgs.length - 1] : null;
|
||||
return [
|
||||
String(conversationId.value || ''),
|
||||
String(msgs.length),
|
||||
String(last?.role || ''),
|
||||
String(last?.content || '').slice(-120),
|
||||
].join('|');
|
||||
});
|
||||
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
|
||||
void refreshShippingActions();
|
||||
});
|
||||
|
||||
return {
|
||||
shippingBindSend,
|
||||
isShippingNoticeAgent,
|
||||
prepareMarkdownDisplayText,
|
||||
shippingAutoFlowRequested,
|
||||
shippingInventoryPickerRef,
|
||||
pendingShippingUploadTaskId,
|
||||
allowsSendWithAttachmentsOnly,
|
||||
shippingTaskIdFromQuery,
|
||||
resumeShippingTaskFromQuery,
|
||||
normalizeShippingHeaderForDisplay,
|
||||
getShippingInventoryMappingPayload,
|
||||
hasShippingInventorySampleRows,
|
||||
getShippingInventorySampleRowText,
|
||||
applyShippingInventoryMappingForm,
|
||||
reuploadShippingInventoryFromMappingForm,
|
||||
handleShippingActionClick,
|
||||
handleShippingInventorySelected,
|
||||
shippingActionButtonClass,
|
||||
shippingSuggestedPrompt,
|
||||
useShippingSuggestedPrompt,
|
||||
tryHandleShippingAttachmentAutoFlow,
|
||||
tryHandleShippingSend,
|
||||
onConversationIdChanging,
|
||||
onConversationLoadedEmpty,
|
||||
onConversationLoadFailed,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/composables/useChatSourceFiles.ts
|
||||
* 检索来源 / 源文件链接解析与预览。
|
||||
*/
|
||||
@@ -6,7 +6,7 @@ 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';
|
||||
import type { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const PREFERRED_SOURCE_EXTS = new Set([
|
||||
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
|
||||
|
||||
Reference in new issue
Block a user