fix(chat): 修复固资管理首轮问答残留中断与历史会话异常
This commit is contained in:
1 parent
25876f94bd
commit
3b771fc0b6
16 files changed
+1042
-35
No files matched your search
@@ -3,7 +3,7 @@
|
|||||||
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
|
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
|
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||||
import type { Ref } from 'vue';
|
import type { Ref } from 'vue';
|
||||||
import {
|
import {
|
||||||
Check,
|
Check,
|
||||||
@@ -56,6 +56,7 @@ const emit = defineEmits<{
|
|||||||
}>();
|
}>();
|
||||||
|
|
||||||
const filePickerRef = ref<HTMLInputElement | null>(null);
|
const filePickerRef = ref<HTMLInputElement | null>(null);
|
||||||
|
const textareaRef = ref<HTMLTextAreaElement | null>(null);
|
||||||
const attachmentMenuRef = ref<HTMLElement | null>(null);
|
const attachmentMenuRef = ref<HTMLElement | null>(null);
|
||||||
const kbMenuRef = ref<HTMLElement | null>(null);
|
const kbMenuRef = ref<HTMLElement | null>(null);
|
||||||
const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
|
const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
|
||||||
@@ -63,7 +64,6 @@ const showAttachmentMenu = ref(false);
|
|||||||
const showAttachmentUrlPanel = ref(false);
|
const showAttachmentUrlPanel = ref(false);
|
||||||
const showKbDropdown = ref(false);
|
const showKbDropdown = ref(false);
|
||||||
const attachmentUrlInput = ref('');
|
const attachmentUrlInput = ref('');
|
||||||
|
|
||||||
const closeAttachmentMenu = () => {
|
const closeAttachmentMenu = () => {
|
||||||
showAttachmentMenu.value = false;
|
showAttachmentMenu.value = false;
|
||||||
showAttachmentUrlPanel.value = false;
|
showAttachmentUrlPanel.value = false;
|
||||||
@@ -138,6 +138,26 @@ onBeforeUnmount(() => {
|
|||||||
document.removeEventListener('mousedown', handleDocumentPointerDown);
|
document.removeEventListener('mousedown', handleDocumentPointerDown);
|
||||||
document.removeEventListener('touchstart', handleDocumentPointerDown);
|
document.removeEventListener('touchstart', handleDocumentPointerDown);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.isThinking,
|
||||||
|
async (thinking, prevThinking) => {
|
||||||
|
if (thinking || !prevThinking || props.isVoiceTranscribing) return;
|
||||||
|
await nextTick();
|
||||||
|
textareaRef.value?.focus();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => inputValue.value,
|
||||||
|
async (value) => {
|
||||||
|
if (value) return;
|
||||||
|
await nextTick();
|
||||||
|
if (textareaRef.value && textareaRef.value.value !== '') {
|
||||||
|
textareaRef.value.value = '';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -145,12 +165,13 @@ onBeforeUnmount(() => {
|
|||||||
<div class="relative mx-auto max-w-4xl">
|
<div class="relative mx-auto max-w-4xl">
|
||||||
<div class="flex flex-col rounded-2xl bg-surface p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
|
<div class="flex flex-col rounded-2xl bg-surface p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
|
||||||
<textarea
|
<textarea
|
||||||
|
ref="textareaRef"
|
||||||
v-model="inputValue"
|
v-model="inputValue"
|
||||||
rows="1"
|
rows="1"
|
||||||
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')"
|
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')"
|
||||||
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
|
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
|
||||||
style="min-height: 44px; max-height: 220px;"
|
style="min-height: 44px; max-height: 220px;"
|
||||||
:disabled="isThinking || isVoiceTranscribing"
|
:disabled="isVoiceTranscribing"
|
||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
autocorrect="off"
|
autocorrect="off"
|
||||||
autocapitalize="off"
|
autocapitalize="off"
|
||||||
@@ -320,13 +341,14 @@ onBeforeUnmount(() => {
|
|||||||
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
|
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
|
||||||
@click="emit('send')"
|
@click="emit('send')"
|
||||||
>
|
>
|
||||||
<Loader2 v-if="isUploadingAttachments" class="h-4 w-4 animate-spin" />
|
<Loader2 v-if="isUploadingAttachments || isThinking" class="h-4 w-4 animate-spin" />
|
||||||
<Send v-else class="h-4 w-4" />
|
<Send v-else class="h-4 w-4" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="mt-3 text-center text-[11px] text-muted">
|
<div class="mt-3 text-center text-[11px] text-muted">
|
||||||
{{ $t('chat.disclaimer') }}
|
<span v-if="isThinking">{{ $t('chat.thinking') }}</span>
|
||||||
|
<span v-else>{{ $t('chat.disclaimer') }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|||||||
@@ -54,6 +54,16 @@ const emit = defineEmits<{
|
|||||||
const bindScrollContainer = (node: unknown) => {
|
const bindScrollContainer = (node: unknown) => {
|
||||||
scrollContainerHolder.el.value = (node as HTMLElement | null) ?? null;
|
scrollContainerHolder.el.value = (node as HTMLElement | null) ?? null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成稳定的消息 key,避免切换历史会话时仅因条数相同而复用旧气泡组件。
|
||||||
|
* 核心逻辑:优先使用服务端/本地消息 ID,其次拼接角色、run_id 与内容摘要。
|
||||||
|
*/
|
||||||
|
const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||||
|
msg.local_id
|
||||||
|
|| (typeof msg.chat_log_id === 'number' ? `chat-log:${msg.chat_log_id}` : '')
|
||||||
|
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -72,7 +82,7 @@ const bindScrollContainer = (node: unknown) => {
|
|||||||
@select-question="emit('select-question', $event)"
|
@select-question="emit('select-question', $event)"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<template v-for="(msg, index) in messages" :key="index">
|
<template v-for="(msg, index) in messages" :key="getMessageKey(msg, index)">
|
||||||
<ChatMessageBubble
|
<ChatMessageBubble
|
||||||
v-if="shouldRenderMessage(msg)"
|
v-if="shouldRenderMessage(msg)"
|
||||||
:message="msg"
|
:message="msg"
|
||||||
|
|||||||
@@ -126,6 +126,7 @@ const page = useChatPageContext();
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<ChatInputBar
|
<ChatInputBar
|
||||||
|
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
|
||||||
v-model="page.input"
|
v-model="page.input"
|
||||||
v-model:selected-kb="page.selectedKb"
|
v-model:selected-kb="page.selectedKb"
|
||||||
:attachments="page.attachments"
|
:attachments="page.attachments"
|
||||||
|
|||||||
@@ -1,20 +1,24 @@
|
|||||||
/**
|
/**
|
||||||
* features/chat/components/messages/ChatMessageBubble.vue
|
* features/chat/components/messages/ChatMessageBubble.vue
|
||||||
* 单条聊天消息:用户气泡、助手 Markdown、请假/出货子组件、来源引用与操作栏。
|
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
|
||||||
|
* 依赖:Vue computed、lucide 图标、Leave/Shipping 子消息组件、chat.types 与页面级 handlers。
|
||||||
|
* 逻辑:由 ChatMessageList 按消息逐条挂载;正文渲染与特殊交互委托 useChatPageMarkdown 等页面编排层提供的 handlers。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
import { Check, Copy, Edit2, LayoutGrid, MessageSquareText, RotateCw } from 'lucide-vue-next';
|
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
||||||
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
||||||
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
|
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
|
||||||
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
|
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
|
||||||
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
|
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
|
||||||
import type { ChatMessage, SourceFileLink } from '../../types/chat.types';
|
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
|
||||||
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
|
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||||
|
|
||||||
export interface ChatMessageBubbleHandlers {
|
export interface ChatMessageBubbleHandlers {
|
||||||
renderMarkdown: (text: string) => string;
|
renderMarkdown: (text: string) => string;
|
||||||
onMarkdownClick: (event: MouseEvent) => void;
|
onMarkdownClick: (event: MouseEvent) => void;
|
||||||
|
getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] };
|
||||||
|
downloadInlineFile: (file: InlineDownloadFile) => void;
|
||||||
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
|
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
|
||||||
getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
|
getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
|
||||||
canOpenQueryPreview: (msg: ChatMessage) => boolean;
|
canOpenQueryPreview: (msg: ChatMessage) => boolean;
|
||||||
@@ -87,6 +91,12 @@ const showShippingActionsPanel = computed(() =>
|
|||||||
);
|
);
|
||||||
const isLastMessage = computed(() => index === messageCount - 1);
|
const isLastMessage = computed(() => index === messageCount - 1);
|
||||||
const isCopied = computed(() => copiedIndex === index);
|
const isCopied = computed(() => copiedIndex === index);
|
||||||
|
const renderedMarkdown = computed(() => (
|
||||||
|
message.role === 'assistant' ? handlers.renderMarkdown(message.content) : ''
|
||||||
|
));
|
||||||
|
const inlineDownloadFiles = computed(() => (
|
||||||
|
message.role === 'assistant' ? handlers.getInlineDownloadFiles(message.content).files : []
|
||||||
|
));
|
||||||
const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() => ({
|
const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() => ({
|
||||||
getPayload: shippingHandlers.getParseReviewPayload,
|
getPayload: shippingHandlers.getParseReviewPayload,
|
||||||
updateHeader: shippingHandlers.updateHeader,
|
updateHeader: shippingHandlers.updateHeader,
|
||||||
@@ -94,6 +104,335 @@ const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() =>
|
|||||||
addLine: shippingHandlers.addLine,
|
addLine: shippingHandlers.addLine,
|
||||||
removeLine: shippingHandlers.removeLine,
|
removeLine: shippingHandlers.removeLine,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
interface InlinePreviewTable {
|
||||||
|
rawHeaders: string[];
|
||||||
|
headers: string[];
|
||||||
|
allRows: string[][];
|
||||||
|
totalRows: number;
|
||||||
|
isCsv: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InlineFileEntry {
|
||||||
|
file: InlineDownloadFile;
|
||||||
|
fileIndex: number;
|
||||||
|
table: InlinePreviewTable;
|
||||||
|
}
|
||||||
|
|
||||||
|
const FIXED_ASSET_HEADER_LABELS: Record<string, string> = {
|
||||||
|
id: '序号',
|
||||||
|
asset_id: '资产编号',
|
||||||
|
asset_no: '资产编号',
|
||||||
|
asset_name: '资产名称',
|
||||||
|
currency_amount: '本币金额(元)',
|
||||||
|
specification: '规格型号',
|
||||||
|
account_period: '账套',
|
||||||
|
operating_center_code: '账套',
|
||||||
|
custodian_person: '保管人姓名',
|
||||||
|
custodian_name: '保管人姓名',
|
||||||
|
custodian_dept: '保管部门名称',
|
||||||
|
department_name: '保管部门名称',
|
||||||
|
storage_location: '存放位置名称',
|
||||||
|
location_name: '存放位置名称',
|
||||||
|
asset_status: '资产状态',
|
||||||
|
reserved_field: '预留残值',
|
||||||
|
residual_value: '预留残值',
|
||||||
|
supplier: '供应厂商',
|
||||||
|
vendor_name: '供应厂商',
|
||||||
|
asset_nature: '资产性质',
|
||||||
|
nature: '资产性质',
|
||||||
|
amount_local: '本币金额(元)',
|
||||||
|
unit_price: '本币金额(元)',
|
||||||
|
quantity: '数量',
|
||||||
|
unit: '计量单位',
|
||||||
|
unit_of_measurement: '计量单位',
|
||||||
|
acquisition_date: '取得日期',
|
||||||
|
acquired_date: '取得日期',
|
||||||
|
accounting_date: '入账日期',
|
||||||
|
recorded_date: '入账日期',
|
||||||
|
created_at: '创建时间',
|
||||||
|
created_time: '创建时间',
|
||||||
|
updated_at: '更新时间',
|
||||||
|
snapshot_time: '快照时间',
|
||||||
|
};
|
||||||
|
const INLINE_DIALOG_PAGE_SIZE = 15;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析 CSV 行,支持双引号包裹字段与转义双引号。
|
||||||
|
* 核心逻辑:逐字符扫描,避免简单 split(',') 破坏包含逗号的单元格。
|
||||||
|
* @param line - 单行 CSV 文本。
|
||||||
|
* @returns 当前行拆分后的列值数组。
|
||||||
|
*/
|
||||||
|
function parseCsvLine(line: string): string[] {
|
||||||
|
const cells: string[] = [];
|
||||||
|
let current = '';
|
||||||
|
let inQuotes = false;
|
||||||
|
|
||||||
|
for (let i = 0; i < line.length; i += 1) {
|
||||||
|
const char = line[i];
|
||||||
|
const nextChar = line[i + 1];
|
||||||
|
if (char === '"') {
|
||||||
|
if (inQuotes && nextChar === '"') {
|
||||||
|
current += '"';
|
||||||
|
i += 1;
|
||||||
|
} else {
|
||||||
|
inQuotes = !inQuotes;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (char === ',' && !inQuotes) {
|
||||||
|
cells.push(current);
|
||||||
|
current = '';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
current += char;
|
||||||
|
}
|
||||||
|
|
||||||
|
cells.push(current);
|
||||||
|
return cells;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将固定资产 CSV 的英文列名转换成面向业务展示的中文列名。
|
||||||
|
* 核心逻辑:优先命中已知字段映射;未知字段保留原值,避免误伤其他 Agent 的文件。
|
||||||
|
* @param header - CSV 原始表头。
|
||||||
|
* @returns 中文表头或原始表头。
|
||||||
|
*/
|
||||||
|
function localizeInlineTableHeader(header: string): string {
|
||||||
|
const normalizedHeader = String(header || '').trim().toLowerCase();
|
||||||
|
return FIXED_ASSET_HEADER_LABELS[normalizedHeader] || header || '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一表格中的空值展示。
|
||||||
|
* 核心逻辑:对空串、短横线、null/none 等占位值统一显示“无”,但保留数字 0 与正常文本。
|
||||||
|
* @param value - 原始单元格值。
|
||||||
|
* @returns 归一化后的展示值。
|
||||||
|
*/
|
||||||
|
function normalizeInlineTableCell(value: string): string {
|
||||||
|
const normalized = String(value ?? '').trim();
|
||||||
|
if (!normalized) return '无';
|
||||||
|
if (['-', '--', 'null', 'none', 'n/a', 'na'].includes(normalized.toLowerCase())) return '无';
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 兼容一批固定资产字段别名,定位筛选栏对应的列索引。
|
||||||
|
* 核心逻辑:同一业务字段可能出现多种英文命名,命中任一别名即可。
|
||||||
|
* @param headers - CSV 原始表头。
|
||||||
|
* @param aliases - 候选字段名列表。
|
||||||
|
* @returns 命中的列索引;未找到时返回 -1。
|
||||||
|
*/
|
||||||
|
function findInlineTableHeaderIndex(headers: string[], aliases: string[]): number {
|
||||||
|
const normalizedAliases = aliases.map((item) => item.trim().toLowerCase());
|
||||||
|
return headers.findIndex((header) => normalizedAliases.includes(String(header || '').trim().toLowerCase()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将用户输入与单元格内容统一成可搜索的文本。
|
||||||
|
* 核心逻辑:统一 trim + lowerCase,避免筛选时受大小写和首尾空白干扰。
|
||||||
|
* @param value - 原始值。
|
||||||
|
* @returns 可用于 includes 的归一化字符串。
|
||||||
|
*/
|
||||||
|
function normalizeInlineFilterKeyword(value: string): string {
|
||||||
|
return String(value ?? '').trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将二维表格重新序列化为 CSV 文本,并自动处理逗号、换行、双引号转义。
|
||||||
|
* 核心逻辑:展示层与下载层共用这一序列化逻辑,保证用户看到的列头与下载文件完全一致。
|
||||||
|
* @param rows - 需要写回 CSV 的二维数组,首行为表头。
|
||||||
|
* @returns 可直接下载的 CSV 文本。
|
||||||
|
*/
|
||||||
|
function serializeCsvRows(rows: string[][]): string {
|
||||||
|
return rows.map((row) => row.map((cell) => {
|
||||||
|
const value = String(cell ?? '');
|
||||||
|
if (/[",\r\n]/.test(value)) {
|
||||||
|
return `"${value.replace(/"/g, '""')}"`;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}).join(',')).join('\r\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将 CSV 文本转成结构化表格,供聊天文件弹窗展示全部数据。
|
||||||
|
* 核心逻辑:首行先做中文列名转换;若存在 id 列则重写为从 1 递增的序号,确保弹窗与下载文件显示一致。
|
||||||
|
* @param file - 当前预览文件。
|
||||||
|
* @returns 表头、完整数据行和总行数。
|
||||||
|
*/
|
||||||
|
function buildInlinePreviewTable(file: InlineDownloadFile): InlinePreviewTable {
|
||||||
|
const isCsv = (file.mime_type || '').includes('csv') || /\.csv$/i.test(file.name);
|
||||||
|
if (!isCsv || !file.data) {
|
||||||
|
return { rawHeaders: [], headers: [], allRows: [], totalRows: 0, isCsv: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = file.data
|
||||||
|
.replace(/\r\n/g, '\n')
|
||||||
|
.replace(/\r/g, '\n')
|
||||||
|
.split('\n')
|
||||||
|
.filter((line) => line.length > 0);
|
||||||
|
|
||||||
|
if (lines.length === 0) {
|
||||||
|
return { rawHeaders: [], headers: [], allRows: [], totalRows: 0, isCsv: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const headerLine = lines[0] || '';
|
||||||
|
const rawHeaders = parseCsvLine(headerLine);
|
||||||
|
const dataRows = lines.slice(1).map((line) => parseCsvLine(line));
|
||||||
|
const idColumnIndex = rawHeaders.findIndex((header) => String(header || '').trim().toLowerCase() === 'id');
|
||||||
|
const headers = rawHeaders.map((header) => localizeInlineTableHeader(header));
|
||||||
|
const allRows = dataRows.map((row, rowIndex) => rawHeaders.map((_, columnIndex) => {
|
||||||
|
if (columnIndex === idColumnIndex) {
|
||||||
|
return String(rowIndex + 1);
|
||||||
|
}
|
||||||
|
return normalizeInlineTableCell(row[columnIndex] ?? '');
|
||||||
|
}));
|
||||||
|
return {
|
||||||
|
rawHeaders,
|
||||||
|
headers,
|
||||||
|
allRows,
|
||||||
|
totalRows: dataRows.length,
|
||||||
|
isCsv: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组装当前消息内嵌文件的展示模型。
|
||||||
|
* 核心逻辑:为每个文件预先计算 CSV 行数与表格内容,供按钮显示条件和弹窗直接复用。
|
||||||
|
* @returns 当前消息可操作的文件条目列表。
|
||||||
|
*/
|
||||||
|
const inlineFileEntries = computed<InlineFileEntry[]>(() => inlineDownloadFiles.value.map((file, fileIndex) => ({
|
||||||
|
file,
|
||||||
|
fileIndex,
|
||||||
|
table: buildInlinePreviewTable(file),
|
||||||
|
})));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仅当数据量大于 5 行时展示“查看全部数据”入口。
|
||||||
|
* 核心逻辑:小结果集直接依赖聊天正文里的预览表格,不再额外重复提供 CSV 附件按钮。
|
||||||
|
*/
|
||||||
|
const actionableInlineFileEntries = computed(() => inlineFileEntries.value.filter((entry) => (
|
||||||
|
entry.table.totalRows === 0 || entry.table.totalRows > 5
|
||||||
|
)));
|
||||||
|
const activeInlineDialogEntry = ref<InlineFileEntry | null>(null);
|
||||||
|
const inlineDialogAssetIdKeyword = ref('');
|
||||||
|
const inlineDialogCustodianKeyword = ref('');
|
||||||
|
const inlineDialogDeptKeyword = ref('');
|
||||||
|
const inlineDialogPage = ref(1);
|
||||||
|
|
||||||
|
const activeInlineFilterIndexes = computed(() => {
|
||||||
|
const table = activeInlineDialogEntry.value?.table;
|
||||||
|
if (!table) {
|
||||||
|
return { assetId: -1, custodianPerson: -1, custodianDept: -1 };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
assetId: findInlineTableHeaderIndex(table.rawHeaders, ['asset_id', 'asset_no']),
|
||||||
|
custodianPerson: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_person', 'custodian_name']),
|
||||||
|
custodianDept: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_dept', 'department_name']),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const activeInlineFilteredRows = computed(() => {
|
||||||
|
const entry = activeInlineDialogEntry.value;
|
||||||
|
if (!entry) return [];
|
||||||
|
|
||||||
|
const filters = {
|
||||||
|
assetId: normalizeInlineFilterKeyword(inlineDialogAssetIdKeyword.value),
|
||||||
|
custodianPerson: normalizeInlineFilterKeyword(inlineDialogCustodianKeyword.value),
|
||||||
|
custodianDept: normalizeInlineFilterKeyword(inlineDialogDeptKeyword.value),
|
||||||
|
};
|
||||||
|
const indexes = activeInlineFilterIndexes.value;
|
||||||
|
|
||||||
|
return entry.table.allRows.filter((row) => {
|
||||||
|
const assetIdValue = indexes.assetId >= 0 ? normalizeInlineFilterKeyword(row[indexes.assetId] ?? '') : '';
|
||||||
|
const custodianValue = indexes.custodianPerson >= 0 ? normalizeInlineFilterKeyword(row[indexes.custodianPerson] ?? '') : '';
|
||||||
|
const deptValue = indexes.custodianDept >= 0 ? normalizeInlineFilterKeyword(row[indexes.custodianDept] ?? '') : '';
|
||||||
|
return (!filters.assetId || assetIdValue.includes(filters.assetId))
|
||||||
|
&& (!filters.custodianPerson || custodianValue.includes(filters.custodianPerson))
|
||||||
|
&& (!filters.custodianDept || deptValue.includes(filters.custodianDept));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const activeInlineTotalPages = computed(() => Math.max(1, Math.ceil(activeInlineFilteredRows.value.length / INLINE_DIALOG_PAGE_SIZE)));
|
||||||
|
const activeInlinePageRows = computed(() => {
|
||||||
|
const startIndex = (inlineDialogPage.value - 1) * INLINE_DIALOG_PAGE_SIZE;
|
||||||
|
return activeInlineFilteredRows.value.slice(startIndex, startIndex + INLINE_DIALOG_PAGE_SIZE);
|
||||||
|
});
|
||||||
|
const activeInlineRangeStart = computed(() => (activeInlineFilteredRows.value.length === 0 ? 0 : (inlineDialogPage.value - 1) * INLINE_DIALOG_PAGE_SIZE + 1));
|
||||||
|
const activeInlineRangeEnd = computed(() => Math.min(inlineDialogPage.value * INLINE_DIALOG_PAGE_SIZE, activeInlineFilteredRows.value.length));
|
||||||
|
|
||||||
|
watch(activeInlineTotalPages, (totalPages) => {
|
||||||
|
if (inlineDialogPage.value > totalPages) {
|
||||||
|
inlineDialogPage.value = totalPages;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(
|
||||||
|
[inlineDialogAssetIdKeyword, inlineDialogCustodianKeyword, inlineDialogDeptKeyword],
|
||||||
|
() => {
|
||||||
|
inlineDialogPage.value = 1;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开聊天文件全量预览弹窗。
|
||||||
|
* 核心逻辑:点击按钮后把目标文件条目写入弹窗状态,在独立弹层中展示全部数据,避免聊天正文只保留 5 行。
|
||||||
|
* @param entry - 当前消息中的可预览文件条目。
|
||||||
|
*/
|
||||||
|
function openInlinePreviewDialog(entry: InlineFileEntry): void {
|
||||||
|
activeInlineDialogEntry.value = entry;
|
||||||
|
inlineDialogAssetIdKeyword.value = '';
|
||||||
|
inlineDialogCustodianKeyword.value = '';
|
||||||
|
inlineDialogDeptKeyword.value = '';
|
||||||
|
inlineDialogPage.value = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭聊天文件全量预览弹窗。
|
||||||
|
*/
|
||||||
|
function closeInlinePreviewDialog(): void {
|
||||||
|
activeInlineDialogEntry.value = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 重置弹窗顶部筛选条件。
|
||||||
|
*/
|
||||||
|
function resetInlineDialogFilters(): void {
|
||||||
|
inlineDialogAssetIdKeyword.value = '';
|
||||||
|
inlineDialogCustodianKeyword.value = '';
|
||||||
|
inlineDialogDeptKeyword.value = '';
|
||||||
|
inlineDialogPage.value = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 切换弹窗分页页码。
|
||||||
|
* 核心逻辑:统一做边界保护,防止筛选后页码越界。
|
||||||
|
* @param nextPage - 目标页码。
|
||||||
|
*/
|
||||||
|
function changeInlineDialogPage(nextPage: number): void {
|
||||||
|
inlineDialogPage.value = Math.min(Math.max(1, nextPage), activeInlineTotalPages.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 响应聊天消息里的内嵌文件下载按钮点击。
|
||||||
|
* 核心逻辑:复用页面层 handlers 生成 Blob 下载,组件层只负责把当前文件对象回传出去。
|
||||||
|
* @param file - 从当前消息内容解析出的单个可下载文件。
|
||||||
|
*/
|
||||||
|
function handleInlineDownload(file: InlineDownloadFile): void {
|
||||||
|
const table = buildInlinePreviewTable(file);
|
||||||
|
if (!table.isCsv || table.headers.length === 0) {
|
||||||
|
handlers.downloadInlineFile(file);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const exportRows = activeInlineDialogEntry.value?.file === file ? activeInlineFilteredRows.value : table.allRows;
|
||||||
|
const transformedCsv = serializeCsvRows([table.headers, ...exportRows]);
|
||||||
|
handlers.downloadInlineFile({
|
||||||
|
...file,
|
||||||
|
data: `\uFEFF${transformedCsv}`,
|
||||||
|
mime_type: 'text/csv;charset=utf-8',
|
||||||
|
});
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -142,12 +481,28 @@ const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() =>
|
|||||||
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
|
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
|
||||||
/>
|
/>
|
||||||
<div
|
<div
|
||||||
v-else
|
v-else-if="renderedMarkdown"
|
||||||
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
|
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
|
||||||
@click="handlers.onMarkdownClick"
|
@click="handlers.onMarkdownClick"
|
||||||
v-html="handlers.renderMarkdown(message.content)"
|
v-html="renderedMarkdown"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<div v-if="actionableInlineFileEntries.length > 0" class="mt-4">
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
<button
|
||||||
|
v-for="entry in actionableInlineFileEntries"
|
||||||
|
:key="`${message.local_id || index}-inline-file-${entry.file.name}-${entry.fileIndex}`"
|
||||||
|
type="button"
|
||||||
|
class="inline-flex max-w-full items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
|
||||||
|
:title="$t('chat.inlineFile.preview')"
|
||||||
|
@click="openInlinePreviewDialog(entry)"
|
||||||
|
>
|
||||||
|
<Eye class="h-3.5 w-3.5 shrink-0" />
|
||||||
|
<span class="truncate">{{ entry.file.name }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
v-if="message.role === 'assistant' && handlers.canOpenQueryPreview(message)"
|
v-if="message.role === 'assistant' && handlers.canOpenQueryPreview(message)"
|
||||||
class="mt-4"
|
class="mt-4"
|
||||||
@@ -296,6 +651,148 @@ const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() =>
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<Teleport to="body">
|
||||||
|
<div
|
||||||
|
v-if="activeInlineDialogEntry"
|
||||||
|
class="dialog-overlay z-[130] items-center"
|
||||||
|
@click.self="closeInlinePreviewDialog"
|
||||||
|
>
|
||||||
|
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,1360px)] max-w-[1360px] flex-col">
|
||||||
|
<div class="dialog-header">
|
||||||
|
<div>
|
||||||
|
<h3 class="section-title">{{ activeInlineDialogEntry.file.name }}</h3>
|
||||||
|
<p class="section-desc mt-1">
|
||||||
|
{{ $t('chat.inlineFile.previewHint', { rows: activeInlineDialogEntry.table.totalRows }) }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
|
||||||
|
@click="handleInlineDownload(activeInlineDialogEntry.file)"
|
||||||
|
>
|
||||||
|
<Download class="h-3.5 w-3.5" />
|
||||||
|
{{ $t('chat.inlineFile.download') }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="closeInlinePreviewDialog">
|
||||||
|
<X class="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
|
||||||
|
<div
|
||||||
|
v-if="activeInlineDialogEntry.table.headers.length > 0"
|
||||||
|
class="grid gap-3 md:grid-cols-4"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
v-model="inlineDialogAssetIdKeyword"
|
||||||
|
type="text"
|
||||||
|
class="rounded-xl border border-default bg-surface px-3 py-2 text-sm text-primary outline-none transition focus:border-blue-400"
|
||||||
|
:placeholder="$t('chat.inlineFile.filters.assetId')"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
v-model="inlineDialogCustodianKeyword"
|
||||||
|
type="text"
|
||||||
|
class="rounded-xl border border-default bg-surface px-3 py-2 text-sm text-primary outline-none transition focus:border-blue-400"
|
||||||
|
:placeholder="$t('chat.inlineFile.filters.custodianPerson')"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
v-model="inlineDialogDeptKeyword"
|
||||||
|
type="text"
|
||||||
|
class="rounded-xl border border-default bg-surface px-3 py-2 text-sm text-primary outline-none transition focus:border-blue-400"
|
||||||
|
:placeholder="$t('chat.inlineFile.filters.custodianDept')"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft"
|
||||||
|
@click="resetInlineDialogFilters"
|
||||||
|
>
|
||||||
|
{{ $t('chat.inlineFile.filters.reset') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
|
||||||
|
<table
|
||||||
|
v-if="activeInlineDialogEntry.table.headers.length > 0"
|
||||||
|
class="min-w-full border-collapse text-sm"
|
||||||
|
>
|
||||||
|
<thead class="sticky top-0 z-10 bg-slate-50">
|
||||||
|
<tr>
|
||||||
|
<th
|
||||||
|
v-for="(header, headerIndex) in activeInlineDialogEntry.table.headers"
|
||||||
|
:key="`${activeInlineDialogEntry.file.name}-dialog-header-${headerIndex}`"
|
||||||
|
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
|
||||||
|
>
|
||||||
|
{{ header || '-' }}
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr
|
||||||
|
v-for="(row, rowIndex) in activeInlinePageRows"
|
||||||
|
:key="`${activeInlineDialogEntry.file.name}-dialog-row-${rowIndex}`"
|
||||||
|
class="odd:bg-white even:bg-slate-50/50"
|
||||||
|
>
|
||||||
|
<td
|
||||||
|
v-for="(cell, cellIndex) in row"
|
||||||
|
:key="`${activeInlineDialogEntry.file.name}-dialog-cell-${rowIndex}-${cellIndex}`"
|
||||||
|
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
|
||||||
|
>
|
||||||
|
<div class="whitespace-pre-wrap break-all">{{ cell || '-' }}</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<div v-else class="p-4 text-sm text-secondary">
|
||||||
|
<div class="whitespace-pre-wrap break-all">{{ activeInlineDialogEntry.file.data }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-if="activeInlineDialogEntry.table.headers.length > 0"
|
||||||
|
class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between"
|
||||||
|
>
|
||||||
|
<div class="text-sm text-muted">
|
||||||
|
{{
|
||||||
|
activeInlineFilteredRows.length > 0
|
||||||
|
? $t('chat.inlineFile.pagination.range', {
|
||||||
|
start: activeInlineRangeStart,
|
||||||
|
end: activeInlineRangeEnd,
|
||||||
|
total: activeInlineFilteredRows.length,
|
||||||
|
})
|
||||||
|
: $t('chat.inlineFile.pagination.empty')
|
||||||
|
}}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="activeInlineFilteredRows.length > INLINE_DIALOG_PAGE_SIZE"
|
||||||
|
class="flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
|
:disabled="inlineDialogPage <= 1"
|
||||||
|
@click="changeInlineDialogPage(inlineDialogPage - 1)"
|
||||||
|
>
|
||||||
|
{{ $t('chat.inlineFile.pagination.prev') }}
|
||||||
|
</button>
|
||||||
|
<div class="text-sm text-muted">
|
||||||
|
{{ $t('chat.inlineFile.pagination.page', { page: inlineDialogPage, total: activeInlineTotalPages }) }}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
|
:disabled="inlineDialogPage >= activeInlineTotalPages"
|
||||||
|
@click="changeInlineDialogPage(inlineDialogPage + 1)"
|
||||||
|
>
|
||||||
|
{{ $t('chat.inlineFile.pagination.next') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -124,6 +124,94 @@ export function useChat() {
|
|||||||
const activeRunId = ref<number | null>(null);
|
const activeRunId = ref<number | null>(null);
|
||||||
let runSeq = 0;
|
let runSeq = 0;
|
||||||
const conversationId = ref<string | null>(null);
|
const conversationId = ref<string | null>(null);
|
||||||
|
const activeStreamController = ref<AbortController | null>(null);
|
||||||
|
let likelyCompletedStreamTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消当前仍在进行的流式请求。
|
||||||
|
*
|
||||||
|
* 说明:
|
||||||
|
* - 固资管理这类长文本/文件回答有时会在答案已经完整展示后,SSE 连接迟迟不结束;
|
||||||
|
* - 若不主动取消,`isThinking` 可能持续为 true,导致输入栏、重新提问和切换 Agent 都像“卡死”。
|
||||||
|
*/
|
||||||
|
const cancelActiveStream = () => {
|
||||||
|
if (!activeStreamController.value) return;
|
||||||
|
activeStreamController.value.abort();
|
||||||
|
activeStreamController.value = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将当前流式请求从可见视图脱离,但不主动中止网络连接。
|
||||||
|
*
|
||||||
|
* 说明:
|
||||||
|
* - 用户切换历史会话时,旧会话回答往往已经接近完成,只是上游 SSE 还没来得及收尾;
|
||||||
|
* - 若这里直接 abort,浏览器会把 `/api/chat/completions` 记成 `ERR_ABORTED`;
|
||||||
|
* - 改为“脱离当前视图”后,旧流可以在后台自然结束,当前页面也能立即切到目标历史会话。
|
||||||
|
*/
|
||||||
|
const detachActiveStreamFromView = () => {
|
||||||
|
activeStreamController.value = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理“疑似已完成回答”的静默定时器。
|
||||||
|
* 说明:固资管理的完整报告有时已经展示出来,但上游流连接没有及时结束,
|
||||||
|
* 这里需要在收到新帧或完成收尾时把旧定时器清掉,避免重复收尾。
|
||||||
|
*/
|
||||||
|
const clearLikelyCompletedStreamTimer = () => {
|
||||||
|
if (!likelyCompletedStreamTimer) return;
|
||||||
|
clearTimeout(likelyCompletedStreamTimer);
|
||||||
|
likelyCompletedStreamTimer = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断当前助手内容是否已经像一份完整报告。
|
||||||
|
*
|
||||||
|
* 说明:
|
||||||
|
* - 固资管理 / ERP 问数最终答案通常会携带 `<details>`、结果表格或导出文件块;
|
||||||
|
* - 若这些终态标记已经出现,而连接仍未结束,说明前端可以在短暂静默后主动解锁输入区。
|
||||||
|
*/
|
||||||
|
const looksLikeCompletedAssistantReply = (content: string) => {
|
||||||
|
if (!content) return false;
|
||||||
|
return (
|
||||||
|
content.includes('<details>')
|
||||||
|
|| content.includes('**查询结果如下:**')
|
||||||
|
|| content.includes('**错误详情**')
|
||||||
|
|| content.includes('[FILE_START]')
|
||||||
|
|| content.includes('【💡 数据概述】')
|
||||||
|
|| content.includes('【📊 数据预览】')
|
||||||
|
|| content.includes('【📈 数据分析汇总报告】')
|
||||||
|
|| content.includes('系统为您从数据库中检索到共计')
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对“已看到完整报告但流未结束”的情况做兜底收尾。
|
||||||
|
*
|
||||||
|
* 核心逻辑:
|
||||||
|
* - 仅当当前回答内容已具备终态标记时才启动;
|
||||||
|
* - 若短时间内没有任何新帧到来,则主动将 run 标记为 done 并中止挂起连接;
|
||||||
|
* - 这样可以修复固资管理首轮问答后输入框一直被锁住的问题。
|
||||||
|
*/
|
||||||
|
const armLikelyCompletedStreamTimer = (
|
||||||
|
controller: AbortController,
|
||||||
|
run: ChatRun,
|
||||||
|
runMessages: ChatMessage[],
|
||||||
|
currentAssistantContent: string,
|
||||||
|
onUnlock: () => void,
|
||||||
|
) => {
|
||||||
|
clearLikelyCompletedStreamTimer();
|
||||||
|
if (!looksLikeCompletedAssistantReply(currentAssistantContent)) return;
|
||||||
|
likelyCompletedStreamTimer = setTimeout(() => {
|
||||||
|
likelyCompletedStreamTimer = null;
|
||||||
|
if (activeStreamController.value !== controller) return;
|
||||||
|
if (run.status !== 'running') return;
|
||||||
|
run.status = 'done';
|
||||||
|
if (messages.value === runMessages) {
|
||||||
|
isThinking.value = false;
|
||||||
|
}
|
||||||
|
onUnlock();
|
||||||
|
}, 600);
|
||||||
|
};
|
||||||
|
|
||||||
const activateRun = (runId: number) => {
|
const activateRun = (runId: number) => {
|
||||||
const run = runs.value.find((r) => r.runId === runId);
|
const run = runs.value.find((r) => r.runId === runId);
|
||||||
@@ -135,6 +223,8 @@ export function useChat() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const createNewChatView = () => {
|
const createNewChatView = () => {
|
||||||
|
clearLikelyCompletedStreamTimer();
|
||||||
|
cancelActiveStream();
|
||||||
viewId.value += 1;
|
viewId.value += 1;
|
||||||
messages.value = [];
|
messages.value = [];
|
||||||
conversationId.value = null;
|
conversationId.value = null;
|
||||||
@@ -143,6 +233,8 @@ export function useChat() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
|
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
|
||||||
|
clearLikelyCompletedStreamTimer();
|
||||||
|
detachActiveStreamFromView();
|
||||||
viewId.value += 1;
|
viewId.value += 1;
|
||||||
activeRunId.value = null;
|
activeRunId.value = null;
|
||||||
isThinking.value = false;
|
isThinking.value = false;
|
||||||
@@ -193,6 +285,10 @@ export function useChat() {
|
|||||||
>,
|
>,
|
||||||
context?: { task_id?: string; batch_no?: string },
|
context?: { task_id?: string; batch_no?: string },
|
||||||
) => {
|
) => {
|
||||||
|
clearLikelyCompletedStreamTimer();
|
||||||
|
cancelActiveStream();
|
||||||
|
const controller = new AbortController();
|
||||||
|
activeStreamController.value = controller;
|
||||||
const runViewId = viewId.value;
|
const runViewId = viewId.value;
|
||||||
const runMessages = messages.value;
|
const runMessages = messages.value;
|
||||||
const run: ChatRun = {
|
const run: ChatRun = {
|
||||||
@@ -213,6 +309,7 @@ export function useChat() {
|
|||||||
let botMsgIndex: number | null = null;
|
let botMsgIndex: number | null = null;
|
||||||
let hasAssistantContent = false;
|
let hasAssistantContent = false;
|
||||||
let hasTerminalEvent = false;
|
let hasTerminalEvent = false;
|
||||||
|
let ignoreFurtherStreamEvents = false;
|
||||||
const ensureBotMessage = () => {
|
const ensureBotMessage = () => {
|
||||||
if (botMsgIndex === null) {
|
if (botMsgIndex === null) {
|
||||||
botMsgIndex = runMessages.push({
|
botMsgIndex = runMessages.push({
|
||||||
@@ -231,6 +328,7 @@ export function useChat() {
|
|||||||
const response = await fetch('/api/chat/completions', {
|
const response = await fetch('/api/chat/completions', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
|
signal: controller.signal,
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
query,
|
query,
|
||||||
agent_id: agentId,
|
agent_id: agentId,
|
||||||
@@ -255,6 +353,10 @@ export function useChat() {
|
|||||||
while (true) {
|
while (true) {
|
||||||
const { done, value } = await reader.read();
|
const { done, value } = await reader.read();
|
||||||
if (done) break;
|
if (done) break;
|
||||||
|
if (ignoreFurtherStreamEvents) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
clearLikelyCompletedStreamTimer();
|
||||||
|
|
||||||
buffer += decoder.decode(value, { stream: true });
|
buffer += decoder.decode(value, { stream: true });
|
||||||
buffer = buffer.replace(/\r\n/g, '\n');
|
buffer = buffer.replace(/\r\n/g, '\n');
|
||||||
@@ -297,6 +399,10 @@ export function useChat() {
|
|||||||
if (!botMsg) continue;
|
if (!botMsg) continue;
|
||||||
botMsg.content += normalizeStreamText(data.answer);
|
botMsg.content += normalizeStreamText(data.answer);
|
||||||
hasAssistantContent = true;
|
hasAssistantContent = true;
|
||||||
|
armLikelyCompletedStreamTimer(controller, run, runMessages, botMsg.content || '', () => {
|
||||||
|
ignoreFurtherStreamEvents = true;
|
||||||
|
detachActiveStreamFromView();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (botMsgIndex !== null) {
|
if (botMsgIndex !== null) {
|
||||||
const currentBotMsg = runMessages[botMsgIndex];
|
const currentBotMsg = runMessages[botMsgIndex];
|
||||||
@@ -304,6 +410,7 @@ export function useChat() {
|
|||||||
}
|
}
|
||||||
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
|
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
|
||||||
hasTerminalEvent = true;
|
hasTerminalEvent = true;
|
||||||
|
ignoreFurtherStreamEvents = true;
|
||||||
const relay = (data.hxops_relay || {}) as Record<string, unknown>;
|
const relay = (data.hxops_relay || {}) as Record<string, unknown>;
|
||||||
if (relay.total_relay_ms != null) {
|
if (relay.total_relay_ms != null) {
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
@@ -312,14 +419,30 @@ export function useChat() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
run.status = 'done';
|
run.status = 'done';
|
||||||
|
clearLikelyCompletedStreamTimer();
|
||||||
if (messages.value === runMessages) isThinking.value = false;
|
if (messages.value === runMessages) isThinking.value = false;
|
||||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||||
const botMsg = ensureBotMessage();
|
const botMsg = ensureBotMessage();
|
||||||
if (!botMsg) continue;
|
if (!botMsg) continue;
|
||||||
const normalizedAnswer = normalizeStreamText(data.answer);
|
const normalizedAnswer = normalizeStreamText(data.answer);
|
||||||
hasAssistantContent = true;
|
hasAssistantContent = true;
|
||||||
|
const currentContent = botMsg.content || '';
|
||||||
if (data.replace_answer) {
|
if (data.replace_answer) {
|
||||||
botMsg.content = normalizedAnswer;
|
botMsg.content = normalizedAnswer;
|
||||||
|
} else if (
|
||||||
|
normalizedAnswer
|
||||||
|
&& currentContent
|
||||||
|
&& normalizedAnswer.length >= currentContent.length
|
||||||
|
&& normalizedAnswer.includes(currentContent)
|
||||||
|
) {
|
||||||
|
// [STEP 1] 某些 Dify 结束事件会重复携带整段完整 answer,这里直接替换,避免正文和内嵌文件按钮重复。
|
||||||
|
botMsg.content = normalizedAnswer;
|
||||||
|
} else if (
|
||||||
|
normalizedAnswer
|
||||||
|
&& currentContent
|
||||||
|
&& currentContent.includes(normalizedAnswer)
|
||||||
|
) {
|
||||||
|
botMsg.content = currentContent;
|
||||||
} else {
|
} else {
|
||||||
botMsg.content += normalizedAnswer;
|
botMsg.content += normalizedAnswer;
|
||||||
}
|
}
|
||||||
@@ -333,29 +456,46 @@ export function useChat() {
|
|||||||
if (!botMsg) continue;
|
if (!botMsg) continue;
|
||||||
applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
|
applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
|
||||||
run.status = 'error';
|
run.status = 'error';
|
||||||
|
clearLikelyCompletedStreamTimer();
|
||||||
if (messages.value === runMessages) isThinking.value = false;
|
if (messages.value === runMessages) isThinking.value = false;
|
||||||
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
|
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||||
const botMsg = ensureBotMessage();
|
const botMsg = ensureBotMessage();
|
||||||
if (!botMsg) continue;
|
if (!botMsg) continue;
|
||||||
botMsg.content += normalizeStreamText(data.answer);
|
botMsg.content += normalizeStreamText(data.answer);
|
||||||
hasAssistantContent = true;
|
hasAssistantContent = true;
|
||||||
|
armLikelyCompletedStreamTimer(controller, run, runMessages, botMsg.content || '', () => {
|
||||||
|
ignoreFurtherStreamEvents = true;
|
||||||
|
detachActiveStreamFromView();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// ignore malformed SSE frames
|
// ignore malformed SSE frames
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
if (!hasTerminalEvent && hasAssistantContent && run.status === 'running') {
|
if (!hasTerminalEvent && hasAssistantContent && run.status === 'running') {
|
||||||
run.status = 'done';
|
run.status = 'done';
|
||||||
}
|
}
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
run.status = 'error';
|
clearLikelyCompletedStreamTimer();
|
||||||
const botMsg = ensureBotMessage();
|
if (controller.signal.aborted) {
|
||||||
if (botMsg) {
|
if (run.status === 'running') {
|
||||||
const message = e instanceof Error ? e.message : 'Network Issue';
|
run.status = hasAssistantContent || hasTerminalEvent ? 'done' : 'error';
|
||||||
applyStreamErrorToMessage(botMsg, message, streamErrorLabels());
|
}
|
||||||
|
} else {
|
||||||
|
run.status = 'error';
|
||||||
|
const botMsg = ensureBotMessage();
|
||||||
|
if (botMsg) {
|
||||||
|
const message = e instanceof Error ? e.message : 'Network Issue';
|
||||||
|
applyStreamErrorToMessage(botMsg, message, streamErrorLabels());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
|
clearLikelyCompletedStreamTimer();
|
||||||
|
if (activeStreamController.value === controller) {
|
||||||
|
activeStreamController.value = null;
|
||||||
|
}
|
||||||
if (messages.value === runMessages) {
|
if (messages.value === runMessages) {
|
||||||
isThinking.value = false;
|
isThinking.value = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { config } from '@/config';
|
|||||||
import { useMessage } from '@/shared/composables/useMessage';
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
import { useIsMobile } from '@/shared/composables/useIsMobile';
|
import { useIsMobile } from '@/shared/composables/useIsMobile';
|
||||||
import { useTheme } from '@/shared/composables/useTheme';
|
import { useTheme } from '@/shared/composables/useTheme';
|
||||||
|
import { listChatMessages } from '../api/chat.api';
|
||||||
import { stripReasoningPrelude } from '../utils/chatText';
|
import { stripReasoningPrelude } from '../utils/chatText';
|
||||||
import type { ChatDeps } from './chat.deps';
|
import type { ChatDeps } from './chat.deps';
|
||||||
import { useChat } from './useChat';
|
import { useChat } from './useChat';
|
||||||
@@ -38,6 +39,39 @@ import {
|
|||||||
useChatPageVoice,
|
useChatPageVoice,
|
||||||
useChatPageToolRun,
|
useChatPageToolRun,
|
||||||
} from '../page';
|
} from '../page';
|
||||||
|
import type { ChatMessage } from '../types/chat.types';
|
||||||
|
|
||||||
|
const getLatestAssistantMessage = (items: ChatMessage[]) => {
|
||||||
|
for (let i = items.length - 1; i >= 0; i -= 1) {
|
||||||
|
if (items[i]?.role === 'assistant') {
|
||||||
|
return items[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const hasMeaningfulAssistantMessage = (message: ChatMessage | null | undefined) => {
|
||||||
|
if (!message) return false;
|
||||||
|
if (String(message.content || '').trim()) return true;
|
||||||
|
return Boolean(message.type && message.type !== 'text');
|
||||||
|
};
|
||||||
|
|
||||||
|
const shouldApplyServerConversationSnapshot = (localMessages: ChatMessage[], serverMessages: ChatMessage[]) => {
|
||||||
|
if (serverMessages.length < localMessages.length) return false;
|
||||||
|
|
||||||
|
const localAssistant = getLatestAssistantMessage(localMessages);
|
||||||
|
if (!hasMeaningfulAssistantMessage(localAssistant)) return true;
|
||||||
|
|
||||||
|
const serverAssistant = getLatestAssistantMessage(serverMessages);
|
||||||
|
if (!hasMeaningfulAssistantMessage(serverAssistant)) return false;
|
||||||
|
|
||||||
|
const localContent = String(localAssistant?.content || '').trim();
|
||||||
|
const serverContent = String(serverAssistant?.content || '').trim();
|
||||||
|
if (!localContent) return true;
|
||||||
|
if (!serverContent) return false;
|
||||||
|
if (serverContent.length < localContent.length) return false;
|
||||||
|
return serverContent.includes(localContent);
|
||||||
|
};
|
||||||
|
|
||||||
export function useChatPage() {
|
export function useChatPage() {
|
||||||
const { t, locale } = useI18n();
|
const { t, locale } = useI18n();
|
||||||
@@ -290,6 +324,28 @@ export function useChatPage() {
|
|||||||
sendMessage,
|
sendMessage,
|
||||||
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
|
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
|
||||||
refreshHistoryAfterSend,
|
refreshHistoryAfterSend,
|
||||||
|
refreshConversationAfterSend: async () => {
|
||||||
|
const currentConversationId = conversationId.value;
|
||||||
|
const currentAgent = currentAgentId.value;
|
||||||
|
if (!currentConversationId || !currentAgent) return;
|
||||||
|
|
||||||
|
// [STEP 1] 发送刚结束时先保留当前内存快照,避免服务端尚未完整落库的旧消息把新回答覆盖掉。
|
||||||
|
const localSnapshot = [...messages.value];
|
||||||
|
const loaded = await listChatMessages(currentConversationId, currentAgent);
|
||||||
|
const serverMessages = Array.isArray(loaded) ? loaded : [];
|
||||||
|
|
||||||
|
// [STEP 2] 若用户已切到其他 Agent/会话,丢弃这个迟到的刷新结果,避免把右侧问答区又切回旧会话。
|
||||||
|
if (conversationId.value !== currentConversationId || currentAgentId.value !== currentAgent) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// [STEP 3] 仅当服务端快照不比本地旧时才覆盖,修复“答案刚出来就消失”和后续发送被锁死的问题。
|
||||||
|
if (!shouldApplyServerConversationSnapshot(localSnapshot, serverMessages)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
loadConversationState(currentConversationId, serverMessages);
|
||||||
|
},
|
||||||
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
|
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
|
||||||
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
||||||
tryHandleShippingSend: shipping.tryHandleShippingSend,
|
tryHandleShippingSend: shipping.tryHandleShippingSend,
|
||||||
|
|||||||
@@ -121,13 +121,17 @@ export function useChatSessions(options: UseChatSessionsOptions) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await loadConversation(item.conversation_id, { force: true });
|
|
||||||
isSidebarOpen.value = false;
|
isSidebarOpen.value = false;
|
||||||
|
|
||||||
if (item.conversation_id.startsWith('pending:')) return;
|
if (item.conversation_id.startsWith('pending:')) return;
|
||||||
|
|
||||||
const currentConvId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
|
const currentConvId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
|
||||||
if (currentConvId === item.conversation_id) return;
|
if (currentConvId === item.conversation_id) {
|
||||||
|
if (conversationId.value !== item.conversation_id || activeRunId.value) {
|
||||||
|
await loadConversation(item.conversation_id, { force: true });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const nextQuery: Record<string, string | string[]> = { ...route.query, conversation_id: item.conversation_id };
|
const nextQuery: Record<string, string | string[]> = { ...route.query, conversation_id: item.conversation_id };
|
||||||
delete nextQuery.task_id;
|
delete nextQuery.task_id;
|
||||||
|
|||||||
@@ -42,6 +42,11 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
|||||||
|
|
||||||
const prevConversationId = ctx.conversationId.value;
|
const prevConversationId = ctx.conversationId.value;
|
||||||
try {
|
try {
|
||||||
|
/**
|
||||||
|
* 切换会话前先清空输入框草稿,避免 textarea DOM 里残留上一会话的可见文本,
|
||||||
|
* 但父级 `input` 已经是空字符串,最终出现“看起来输入了内容,发送时却被当成空串”的错觉。
|
||||||
|
*/
|
||||||
|
ctx.input.value = '';
|
||||||
ctx.onConversationIdChanging(id, prevConversationId);
|
ctx.onConversationIdChanging(id, prevConversationId);
|
||||||
const loaded = await listChatMessages(id, ctx.currentAgentId.value);
|
const loaded = await listChatMessages(id, ctx.currentAgentId.value);
|
||||||
ctx.loadConversationState(id, Array.isArray(loaded) ? loaded : []);
|
ctx.loadConversationState(id, Array.isArray(loaded) ? loaded : []);
|
||||||
|
|||||||
@@ -1,15 +1,62 @@
|
|||||||
/**
|
/**
|
||||||
* 对话页:Markdown 渲染、消息可见性判断、PLM/请假链接点击。
|
* features/chat/page/useChatPageMarkdown.ts
|
||||||
|
* 用途:统一处理聊天页 Markdown 渲染、内嵌文件块提取、消息可见性判断与特殊链接点击。
|
||||||
|
* 依赖:Vue computed、marked、ChatMessageBubble handlers、聊天消息类型。
|
||||||
|
* 逻辑:由 useChatPage 组装上下文后创建页面级 Markdown API,再分发给 ChatMessageBubble 做消息渲染和交互。
|
||||||
*/
|
*/
|
||||||
import { computed } from 'vue';
|
import { computed } from 'vue';
|
||||||
import { marked } from 'marked';
|
import { marked } from 'marked';
|
||||||
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
|
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
|
||||||
import type { ChatMessage, SourceFileLink } from '../types/chat.types';
|
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../types/chat.types';
|
||||||
import type { ShippingMatchResultPayload } from '../types/shipping.types';
|
import type { ShippingMatchResultPayload } from '../types/shipping.types';
|
||||||
import type { Ref } from 'vue';
|
import type { Ref } from 'vue';
|
||||||
|
|
||||||
marked.setOptions({ gfm: true, breaks: true });
|
marked.setOptions({ gfm: true, breaks: true });
|
||||||
|
|
||||||
|
const INLINE_FILE_BLOCK_REGEX = /\[FILE_START\]([\s\S]*?)\[FILE_END\]/g;
|
||||||
|
const INLINE_ATTACHMENT_HINT_REGEX = /^.*(?:如果您需要查看全部数据,请下载附件。?|请下载附件。?).*$/gim;
|
||||||
|
|
||||||
|
interface InlineFileExtractResult {
|
||||||
|
cleanedText: string;
|
||||||
|
files: InlineDownloadFile[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const INLINE_DOWNLOAD_LINK_LINE_REGEX = /^[ \t>*-]*\[[^\]]*下载(?:全部|全量)?数据[^\]]*\]\([^)]+\)\s*$/gim;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在 JSON.parse 失败时兜底提取文件字段,兼容 Dify 偶发返回的近似 JSON 文本。
|
||||||
|
* 核心逻辑:优先抽取 name/data/mime_type 三个字段;若缺失关键字段则返回 null,避免伪造按钮。
|
||||||
|
* @param rawPayload - FILE_START/FILE_END 包裹的原始文本。
|
||||||
|
* @returns 尽力恢复后的文件对象;恢复失败时返回 null。
|
||||||
|
*/
|
||||||
|
function decodeLooseJsonString(rawValue: string): string {
|
||||||
|
return String(rawValue || '')
|
||||||
|
.replace(/\\u([0-9a-fA-F]{4})/g, (_match, code: string) => String.fromCharCode(Number.parseInt(code, 16)))
|
||||||
|
.replace(/\\r/g, '\r')
|
||||||
|
.replace(/\\n/g, '\n')
|
||||||
|
.replace(/\\t/g, '\t')
|
||||||
|
.replace(/\\f/g, '\f')
|
||||||
|
.replace(/\\b/g, '\b')
|
||||||
|
.replace(/\\"/g, '"')
|
||||||
|
.replace(/\\\\/g, '\\');
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryParseInlineFileFallback(rawPayload: string): InlineDownloadFile | null {
|
||||||
|
const raw = String(rawPayload || '').trim();
|
||||||
|
const nameMatch = raw.match(/"name"\s*:\s*"((?:\\.|[^"\\])*)"/i);
|
||||||
|
const dataMatch = raw.match(/"data"\s*:\s*"([\s\S]*?)"\s*(?:,\s*"mime_type"|\s*}$)/i);
|
||||||
|
const mimeMatch = raw.match(/"mime_type"\s*:\s*"((?:\\.|[^"\\])*)"/i);
|
||||||
|
const name = nameMatch?.[1] ? decodeLooseJsonString(nameMatch[1]).trim() : '';
|
||||||
|
const data = dataMatch?.[1] ? decodeLooseJsonString(dataMatch[1]) : '';
|
||||||
|
const mimeType = mimeMatch?.[1] ? decodeLooseJsonString(mimeMatch[1]).trim() : '';
|
||||||
|
if (!name || !data) return null;
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
data,
|
||||||
|
mime_type: mimeType || 'application/octet-stream',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export interface ChatPageMarkdownContext {
|
export interface ChatPageMarkdownContext {
|
||||||
messages: Ref<ChatMessage[]>;
|
messages: Ref<ChatMessage[]>;
|
||||||
isThinking: Ref<boolean>;
|
isThinking: Ref<boolean>;
|
||||||
@@ -33,6 +80,104 @@ export interface ChatPageMarkdownContext {
|
|||||||
onShippingActionClick: ChatMessageBubbleHandlers['onShippingActionClick'];
|
onShippingActionClick: ChatMessageBubbleHandlers['onShippingActionClick'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提取 Dify 返回文本中的内嵌文件块,并把原始 JSON 从聊天正文里剥离。
|
||||||
|
* 核心逻辑:使用 FILE_START/FILE_END 正则定位片段,逐个 JSON.parse 成可下载文件;解析失败时保留原文避免误伤正常消息。
|
||||||
|
* @param text - 助手原始 answer 文本,可能混有 Markdown 与文件 JSON。
|
||||||
|
* @returns 清理后的展示文本与可下载文件列表。
|
||||||
|
*/
|
||||||
|
function extractInlineDownloadFiles(text: string): InlineFileExtractResult {
|
||||||
|
if (!text) {
|
||||||
|
return { cleanedText: '', files: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const files: InlineDownloadFile[] = [];
|
||||||
|
const seenKeys = new Set<string>();
|
||||||
|
|
||||||
|
let cleanedText = text.replace(INLINE_FILE_BLOCK_REGEX, (_match, rawPayload: string) => {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(String(rawPayload || '').trim()) as Partial<InlineDownloadFile>;
|
||||||
|
const name = String(parsed.name || '').trim();
|
||||||
|
const data = typeof parsed.data === 'string' ? parsed.data : '';
|
||||||
|
const mimeType = String(parsed.mime_type || '').trim() || 'application/octet-stream';
|
||||||
|
|
||||||
|
if (!name || !data) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const dedupeKey = `${name}::${mimeType}::${data}`;
|
||||||
|
if (!seenKeys.has(dedupeKey)) {
|
||||||
|
seenKeys.add(dedupeKey);
|
||||||
|
files.push({
|
||||||
|
name,
|
||||||
|
data,
|
||||||
|
mime_type: mimeType,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
} catch {
|
||||||
|
const fallbackFile = tryParseInlineFileFallback(rawPayload);
|
||||||
|
if (fallbackFile) {
|
||||||
|
const dedupeKey = `${fallbackFile.name}::${fallbackFile.mime_type || ''}::${fallbackFile.data}`;
|
||||||
|
if (!seenKeys.has(dedupeKey)) {
|
||||||
|
seenKeys.add(dedupeKey);
|
||||||
|
files.push(fallbackFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// [STEP 1] 流式消息可能先到 FILE_START、后到 FILE_END,这一阶段先把未闭合块整体隐藏,避免原始 CSV/JSON 外露。
|
||||||
|
const danglingStartIndex = cleanedText.indexOf('[FILE_START]');
|
||||||
|
if (danglingStartIndex >= 0) {
|
||||||
|
cleanedText = cleanedText.slice(0, danglingStartIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
// [STEP 2] 如果消息正文已经内置了 Markdown 下载链接,保留说明文案但移除直接下载入口,统一交给预览卡片处理。
|
||||||
|
if (files.length > 0) {
|
||||||
|
cleanedText = cleanedText.replace(INLINE_DOWNLOAD_LINK_LINE_REGEX, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
// [STEP 3] 无论是否存在附件按钮,都移除“请下载附件”类兜底文案,避免 <=5 条时误导用户,也避免 >5 条时重复提示。
|
||||||
|
cleanedText = cleanedText.replace(INLINE_ATTACHMENT_HINT_REGEX, '');
|
||||||
|
|
||||||
|
return {
|
||||||
|
cleanedText: cleanedText.trim(),
|
||||||
|
files,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeExtractInlineDownloadFiles(text: string): InlineFileExtractResult {
|
||||||
|
try {
|
||||||
|
return extractInlineDownloadFiles(text);
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
cleanedText: String(text || '').replace(/\[FILE_START\][\s\S]*$/g, '').trim(),
|
||||||
|
files: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将内嵌文件内容转成浏览器本地下载。
|
||||||
|
* 核心逻辑:按 mime/type 生成 Blob 与 object URL,触发隐藏 a 标签点击后立即回收 URL,避免把大段 CSV 暴露在 DOM 中。
|
||||||
|
* @param file - 已从消息中解析出的单个可下载文件,要求 name/data 均非空。
|
||||||
|
*/
|
||||||
|
function downloadInlineFile(file: InlineDownloadFile): void {
|
||||||
|
if (!file.name || !file.data) return;
|
||||||
|
const blob = new Blob([file.data], { type: file.mime_type || 'application/octet-stream;charset=utf-8' });
|
||||||
|
const objectUrl = URL.createObjectURL(blob);
|
||||||
|
const anchor = document.createElement('a');
|
||||||
|
anchor.href = objectUrl;
|
||||||
|
anchor.download = file.name;
|
||||||
|
anchor.style.display = 'none';
|
||||||
|
document.body.appendChild(anchor);
|
||||||
|
anchor.click();
|
||||||
|
document.body.removeChild(anchor);
|
||||||
|
URL.revokeObjectURL(objectUrl);
|
||||||
|
}
|
||||||
|
|
||||||
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||||
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
|
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
|
||||||
if (msgItem?.role === 'user') return true;
|
if (msgItem?.role === 'user') return true;
|
||||||
@@ -44,6 +189,24 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
|||||||
return Array.isArray(msgItem?.attribution_parts) && msgItem.attribution_parts.length > 0;
|
return Array.isArray(msgItem?.attribution_parts) && msgItem.attribution_parts.length > 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断某条 assistant 消息是否已经具备“正文已出现”的特征。
|
||||||
|
* 核心逻辑:仅把真正可读的正文或结构化子消息视为已开始回复;
|
||||||
|
* 单纯的引用源、空内容或中间元数据不应压掉“思考中”提示。
|
||||||
|
*/
|
||||||
|
const hasMeaningfulAssistantReply = (msgItem: ChatMessage): boolean => {
|
||||||
|
if (msgItem?.role !== 'assistant') return false;
|
||||||
|
if (msgItem?.type === 'leave-form'
|
||||||
|
|| msgItem?.type === 'leave-confirmation'
|
||||||
|
|| msgItem?.type === 'leave-result'
|
||||||
|
|| msgItem?.type === 'shipping-inventory-mapping'
|
||||||
|
|| msgItem?.type === 'shipping-parse-review'
|
||||||
|
|| msgItem?.type === 'shipping-match-result') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return Boolean(String(msgItem?.content || '').trim());
|
||||||
|
};
|
||||||
|
|
||||||
const shouldShowThinkingBubble = computed(() => {
|
const shouldShowThinkingBubble = computed(() => {
|
||||||
if (!ctx.isThinking.value) return false;
|
if (!ctx.isThinking.value) return false;
|
||||||
let lastUserIndex = -1;
|
let lastUserIndex = -1;
|
||||||
@@ -56,7 +219,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
|||||||
if (lastUserIndex < 0) return true;
|
if (lastUserIndex < 0) return true;
|
||||||
return !ctx.messages.value
|
return !ctx.messages.value
|
||||||
.slice(lastUserIndex + 1)
|
.slice(lastUserIndex + 1)
|
||||||
.some((msgItem) => msgItem?.role === 'assistant' && shouldRenderMessage(msgItem));
|
.some((msgItem) => hasMeaningfulAssistantReply(msgItem));
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleChatMarkdownClick = (event: MouseEvent) => {
|
const handleChatMarkdownClick = (event: MouseEvent) => {
|
||||||
@@ -71,15 +234,26 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
|||||||
ctx.handleLeaveMarkdownClick(event);
|
ctx.handleLeaveMarkdownClick(event);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。
|
||||||
|
* 核心逻辑:先抽取 FILE_START/FILE_END 文件,再走既有 Markdown 清洗与 marked 渲染,保证聊天气泡只展示可读文本。
|
||||||
|
* @param text - 原始聊天文本。
|
||||||
|
* @returns 供 v-html 使用的安全展示字符串。
|
||||||
|
*/
|
||||||
const renderMarkdown = (text: string) => {
|
const renderMarkdown = (text: string) => {
|
||||||
if (!text) return '';
|
if (!text) return '';
|
||||||
const displayText = ctx.prepareMarkdownDisplayText(text);
|
const extracted = safeExtractInlineDownloadFiles(text);
|
||||||
|
const displayText = ctx.prepareMarkdownDisplayText(extracted.cleanedText);
|
||||||
try {
|
try {
|
||||||
const rendered = marked.parse(displayText);
|
const rendered = marked.parse(displayText);
|
||||||
const html = typeof rendered === 'string' ? rendered : displayText;
|
const html = typeof rendered === 'string' ? rendered : displayText;
|
||||||
return html.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml: string) => (
|
return html
|
||||||
`<div class="chat-table-scroll"><div class="chat-table-inner">${tableHtml}</div></div>`
|
.replace(/<(td|th)\b([^>]*)>(?:\s| |<br\s*\/?>)*<\/\1>/gi, (_match, tagName: string, attrs: string) => (
|
||||||
));
|
`<${tagName}${attrs}>无</${tagName}>`
|
||||||
|
))
|
||||||
|
.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml: string) => (
|
||||||
|
`<div class="chat-table-scroll"><div class="chat-table-inner">${tableHtml}</div></div>`
|
||||||
|
));
|
||||||
} catch {
|
} catch {
|
||||||
return displayText;
|
return displayText;
|
||||||
}
|
}
|
||||||
@@ -88,6 +262,8 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
|||||||
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
|
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
|
||||||
renderMarkdown,
|
renderMarkdown,
|
||||||
onMarkdownClick: handleChatMarkdownClick,
|
onMarkdownClick: handleChatMarkdownClick,
|
||||||
|
getInlineDownloadFiles: safeExtractInlineDownloadFiles,
|
||||||
|
downloadInlineFile,
|
||||||
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
|
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
|
||||||
getShippingMatchResultPayload: ctx.getShippingMatchResultPayload,
|
getShippingMatchResultPayload: ctx.getShippingMatchResultPayload,
|
||||||
canOpenQueryPreview: ctx.canOpenQueryPreview,
|
canOpenQueryPreview: ctx.canOpenQueryPreview,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
/**
|
/**
|
||||||
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
|
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
|
||||||
*/
|
*/
|
||||||
import { computed } from 'vue';
|
import { computed } from 'vue';
|
||||||
@@ -28,6 +28,7 @@ export interface ChatPageSendContext {
|
|||||||
context?: { task_id?: string; batch_no?: string },
|
context?: { task_id?: string; batch_no?: string },
|
||||||
) => Promise<void>;
|
) => Promise<void>;
|
||||||
refreshHistoryAfterSend: () => Promise<void>;
|
refreshHistoryAfterSend: () => Promise<void>;
|
||||||
|
refreshConversationAfterSend?: () => Promise<void>;
|
||||||
tryHandleShippingAttachmentAutoFlow: (
|
tryHandleShippingAttachmentAutoFlow: (
|
||||||
textOrEvent: string | Event | undefined,
|
textOrEvent: string | Event | undefined,
|
||||||
content: string,
|
content: string,
|
||||||
@@ -61,8 +62,12 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
|||||||
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
|
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) return;
|
if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) {
|
||||||
if (ctx.tryHandleLeaveSend(content)) return;
|
return;
|
||||||
|
}
|
||||||
|
if (ctx.tryHandleLeaveSend(content)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (await ctx.tryHandleShippingSend(textOrEvent, content, trimmed)) {
|
if (await ctx.tryHandleShippingSend(textOrEvent, content, trimmed)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -100,6 +105,7 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
|||||||
ctx.getChatContext?.(),
|
ctx.getChatContext?.(),
|
||||||
);
|
);
|
||||||
await ctx.refreshHistoryAfterSend();
|
await ctx.refreshHistoryAfterSend();
|
||||||
|
await ctx.refreshConversationAfterSend?.();
|
||||||
await ctx.refreshToolRunProgressAfterSend();
|
await ctx.refreshToolRunProgressAfterSend();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* features/chat/types/chat.types.ts
|
* features/chat/types/chat.types.ts
|
||||||
* 聊天域核心类型定义。
|
* 用途:定义聊天域的消息、会话、预览与附件下载等共享类型。
|
||||||
|
* 依赖:被 chat 页面 composables、消息气泡组件、API 封装共同引用。
|
||||||
|
* 逻辑:作为 features/chat 域的类型中枢,向上提供页面编排约束,向下约束消息渲染与交互结构。
|
||||||
*/
|
*/
|
||||||
import type { LeaveAgentOption } from './leave.types';
|
import type { LeaveAgentOption } from './leave.types';
|
||||||
|
|
||||||
@@ -39,6 +41,12 @@ export interface ChatMessage {
|
|||||||
stream_error?: boolean;
|
stream_error?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface InlineDownloadFile {
|
||||||
|
name: string;
|
||||||
|
data: string;
|
||||||
|
mime_type?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export type ChatRunStatus = 'running' | 'done' | 'error';
|
export type ChatRunStatus = 'running' | 'done' | 'error';
|
||||||
|
|
||||||
export interface ChatRun {
|
export interface ChatRun {
|
||||||
|
|||||||
@@ -338,5 +338,24 @@
|
|||||||
"copySuccess": "Copied",
|
"copySuccess": "Copied",
|
||||||
"copyFailed": "Copy failed. Please allow clipboard access or try again.",
|
"copyFailed": "Copy failed. Please allow clipboard access or try again.",
|
||||||
"copyEmpty": "Nothing to copy"
|
"copyEmpty": "Nothing to copy"
|
||||||
|
},
|
||||||
|
"inlineFile": {
|
||||||
|
"preview": "Preview Data",
|
||||||
|
"download": "Download Data",
|
||||||
|
"previewHint": "{rows} rows in total. This dialog shows the full dataset",
|
||||||
|
"previewTruncated": "Only the first 5 rows are shown here. The full file contains {rows} rows",
|
||||||
|
"filters": {
|
||||||
|
"assetId": "Filter by asset ID",
|
||||||
|
"custodianPerson": "Filter by custodian",
|
||||||
|
"custodianDept": "Filter by custodian dept",
|
||||||
|
"reset": "Reset Filters"
|
||||||
|
},
|
||||||
|
"pagination": {
|
||||||
|
"prev": "Previous",
|
||||||
|
"next": "Next",
|
||||||
|
"page": "Page {page} / {total}",
|
||||||
|
"range": "Showing {start}-{end} of {total}",
|
||||||
|
"empty": "No matching data"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -338,5 +338,24 @@
|
|||||||
"copySuccess": "คัดลอกแล้ว",
|
"copySuccess": "คัดลอกแล้ว",
|
||||||
"copyFailed": "คัดลอกไม่สำเร็จ โปรดอนุญาตการเข้าถึงคลิปบอร์ดแล้วลองอีกครั้ง",
|
"copyFailed": "คัดลอกไม่สำเร็จ โปรดอนุญาตการเข้าถึงคลิปบอร์ดแล้วลองอีกครั้ง",
|
||||||
"copyEmpty": "ไม่มีเนื้อหาให้คัดลอก"
|
"copyEmpty": "ไม่มีเนื้อหาให้คัดลอก"
|
||||||
|
},
|
||||||
|
"inlineFile": {
|
||||||
|
"preview": "ดูตัวอย่างข้อมูล",
|
||||||
|
"download": "ดาวน์โหลดข้อมูล",
|
||||||
|
"previewHint": "มีข้อมูลทั้งหมด {rows} แถว และกล่องโต้ตอบนี้แสดงข้อมูลทั้งหมด",
|
||||||
|
"previewTruncated": "ขณะนี้แสดงเพียง 5 แถวแรกเท่านั้น ไฟล์เต็มมีทั้งหมด {rows} แถว",
|
||||||
|
"filters": {
|
||||||
|
"assetId": "กรองตามรหัสทรัพย์สิน",
|
||||||
|
"custodianPerson": "กรองตามผู้ดูแล",
|
||||||
|
"custodianDept": "กรองตามหน่วยงานผู้ดูแล",
|
||||||
|
"reset": "ล้างตัวกรอง"
|
||||||
|
},
|
||||||
|
"pagination": {
|
||||||
|
"prev": "ก่อนหน้า",
|
||||||
|
"next": "ถัดไป",
|
||||||
|
"page": "หน้า {page} / {total}",
|
||||||
|
"range": "แสดง {start}-{end} จากทั้งหมด {total}",
|
||||||
|
"empty": "ไม่พบข้อมูลที่ตรงเงื่อนไข"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -342,5 +342,24 @@
|
|||||||
"copySuccess": "已复制",
|
"copySuccess": "已复制",
|
||||||
"copyFailed": "复制失败,请允许剪贴板权限后重试",
|
"copyFailed": "复制失败,请允许剪贴板权限后重试",
|
||||||
"copyEmpty": "没有可复制的内容"
|
"copyEmpty": "没有可复制的内容"
|
||||||
|
},
|
||||||
|
"inlineFile": {
|
||||||
|
"preview": "预览数据",
|
||||||
|
"download": "下载数据",
|
||||||
|
"previewHint": "共 {rows} 行数据,当前弹窗展示全部数据",
|
||||||
|
"previewTruncated": "当前仅预览前 5 行,完整数据共 {rows} 行",
|
||||||
|
"filters": {
|
||||||
|
"assetId": "按资产编号筛选",
|
||||||
|
"custodianPerson": "按保管人筛选",
|
||||||
|
"custodianDept": "按保管部门筛选",
|
||||||
|
"reset": "重置筛选"
|
||||||
|
},
|
||||||
|
"pagination": {
|
||||||
|
"prev": "上一页",
|
||||||
|
"next": "下一页",
|
||||||
|
"page": "第 {page} / {total} 页",
|
||||||
|
"range": "显示第 {start}-{end} 条,共 {total} 条",
|
||||||
|
"empty": "暂无符合条件的数据"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -338,5 +338,24 @@
|
|||||||
"copySuccess": "已複製",
|
"copySuccess": "已複製",
|
||||||
"copyFailed": "複製失敗,請允許剪貼簿權限後重試",
|
"copyFailed": "複製失敗,請允許剪貼簿權限後重試",
|
||||||
"copyEmpty": "沒有可複製的內容"
|
"copyEmpty": "沒有可複製的內容"
|
||||||
|
},
|
||||||
|
"inlineFile": {
|
||||||
|
"preview": "預覽資料",
|
||||||
|
"download": "下載資料",
|
||||||
|
"previewHint": "共 {rows} 行資料,當前彈窗展示全部資料",
|
||||||
|
"previewTruncated": "目前僅預覽前 5 行,完整資料共 {rows} 行",
|
||||||
|
"filters": {
|
||||||
|
"assetId": "依資產編號篩選",
|
||||||
|
"custodianPerson": "依保管人篩選",
|
||||||
|
"custodianDept": "依保管部門篩選",
|
||||||
|
"reset": "重設篩選"
|
||||||
|
},
|
||||||
|
"pagination": {
|
||||||
|
"prev": "上一頁",
|
||||||
|
"next": "下一頁",
|
||||||
|
"page": "第 {page} / {total} 頁",
|
||||||
|
"range": "顯示第 {start}-{end} 條,共 {total} 條",
|
||||||
|
"empty": "暫無符合條件的資料"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,21 +1,26 @@
|
|||||||
/**
|
/**
|
||||||
* shared/composables/useIsMobile.ts
|
* shared/composables/useIsMobile.ts
|
||||||
* 检测竖屏/横屏,供移动端布局切换。
|
* 用途:按视口宽度提供统一的移动端判定,供聊天页与工作台切换布局。
|
||||||
|
* 依赖:浏览器 `matchMedia` 与 Vue 生命周期。
|
||||||
|
* 逻辑:组件挂载后监听 `max-width: 767px`,避免把“窄屏横屏”误判成桌面布局。
|
||||||
*/
|
*/
|
||||||
import { ref, onMounted, onBeforeUnmount, readonly } from 'vue';
|
import { ref, onMounted, onBeforeUnmount, readonly } from 'vue';
|
||||||
|
|
||||||
const isMobile = ref(false);
|
const isMobile = ref(false);
|
||||||
|
const mobileMediaQuery = '(max-width: 767px)';
|
||||||
|
|
||||||
let listeners = 0;
|
let listeners = 0;
|
||||||
|
let mediaQueryList: MediaQueryList | null = null;
|
||||||
|
|
||||||
const update = () => {
|
const update = () => {
|
||||||
isMobile.value = window.innerHeight > window.innerWidth;
|
isMobile.value = window.matchMedia(mobileMediaQuery).matches;
|
||||||
};
|
};
|
||||||
|
|
||||||
const startListening = () => {
|
const startListening = () => {
|
||||||
if (listeners === 0) {
|
if (listeners === 0) {
|
||||||
|
mediaQueryList = window.matchMedia(mobileMediaQuery);
|
||||||
update();
|
update();
|
||||||
window.addEventListener('resize', update);
|
mediaQueryList.addEventListener('change', update);
|
||||||
}
|
}
|
||||||
listeners++;
|
listeners++;
|
||||||
};
|
};
|
||||||
@@ -24,7 +29,8 @@ const stopListening = () => {
|
|||||||
listeners--;
|
listeners--;
|
||||||
if (listeners <= 0) {
|
if (listeners <= 0) {
|
||||||
listeners = 0;
|
listeners = 0;
|
||||||
window.removeEventListener('resize', update);
|
mediaQueryList?.removeEventListener('change', update);
|
||||||
|
mediaQueryList = null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user