Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-06-29 18:03:01 +08:00
commit ca32191c77
30 files changed
+1181 -79

No files matched your search

+1 -1
View File
@@ -28,7 +28,7 @@ EDKB_SOFFICE_TIMEOUT_SEC=600
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
EDKB_WORD_TIMEOUT_SEC=300
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
EDKB_FILE_TIMEOUT_SEC=180
EDKB_FILE_TIMEOUT_SEC=300
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
EDKB_WORD_FILE_TIMEOUT_SEC=420
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
+7
View File
@@ -1320,6 +1320,8 @@ def _apply_chat_logs_report_filters(query):
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
elif key == 'username':
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
elif key == 'real_name':
query = query.filter(User.real_name.cast(db.String).ilike(f'%{value}%'))
elif hasattr(ChatLog, key):
col = getattr(ChatLog, key)
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
@@ -1391,6 +1393,11 @@ def get_table_count(table):
"""
Return total row count for admin report tables.
"""
if table == 'chat_logs':
query = _apply_chat_logs_report_filters(_chat_logs_report_query())
total = query.count()
return jsonify({'table': table, 'total': int(total or 0)})
model_map = {'users': User, 'agents': Agent, 'chat_logs': ChatLog, 'feedbacks': Feedback, 'permission_requests': PermissionRequest, 'departments': Department, 'quick_questions': QuickQuestion, 'user_homepage_configs': UserHomepageConfig, 'user_favorite_agents': UserFavoriteAgent, 'user_default_agents': UserDefaultAgent}
model = model_map.get(table)
if not model:
+27 -1
View File
@@ -1,5 +1,5 @@
import pytest
from app.models import Agent, User, PermissionRequest
from app.models import Agent, ChatLog, User, PermissionRequest
from app import db
def test_agent_lifecycle(client, admin_headers):
@@ -278,3 +278,29 @@ def test_reports(client, admin_headers):
data = response.json
assert 'avg_score' in data
assert 'distribution' in data
def test_chat_logs_report_filters_by_real_name(client, app, admin_headers):
"""聊天日志报表真实姓名筛选:real_name 是 User 关联字段,列表与计数必须使用同一过滤条件。"""
with app.app_context():
agent = Agent(name='HR Assistant', type='api', dify_app_id='hr-app', dify_api_key='hr-key')
sophie = User(username='26030025', email='sophie@example.com', real_name='sophie', role='user')
admin = User(username='admin-user', email='admin-user@example.com', real_name='admin', role='user')
db.session.add_all([agent, sophie, admin])
db.session.flush()
db.session.add_all([
ChatLog(user_id=sophie.id, agent_id=agent.id, query='人事规章', answer='A', tokens_used=1),
ChatLog(user_id=admin.id, agent_id=agent.id, query='上班时间', answer='B', tokens_used=1),
])
db.session.commit()
response = client.get('/api/admin/database/chat_logs?real_name=sophie', headers=admin_headers)
assert response.status_code == 200
rows = response.json
assert len(rows) == 1
assert rows[0]['real_name'] == 'sophie'
assert rows[0]['username'] == '26030025'
count_response = client.get('/api/admin/database/chat_logs/count?real_name=sophie', headers=admin_headers)
assert count_response.status_code == 200
assert count_response.json['total'] == 1
@@ -3,7 +3,7 @@
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
*/
<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 {
Check,
@@ -60,6 +60,7 @@ const emit = defineEmits<{
}>();
const filePickerRef = ref<HTMLInputElement | null>(null);
const textareaRef = ref<HTMLTextAreaElement | null>(null);
const attachmentMenuRef = ref<HTMLElement | null>(null);
const kbMenuRef = ref<HTMLElement | null>(null);
const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
@@ -67,7 +68,6 @@ const showAttachmentMenu = ref(false);
const showAttachmentUrlPanel = ref(false);
const showKbDropdown = ref(false);
const attachmentUrlInput = ref('');
const closeAttachmentMenu = () => {
showAttachmentMenu.value = false;
showAttachmentUrlPanel.value = false;
@@ -151,6 +151,26 @@ onBeforeUnmount(() => {
document.removeEventListener('mousedown', 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>
<template>
@@ -174,12 +194,13 @@ onBeforeUnmount(() => {
</button>
</div>
<textarea
ref="textareaRef"
v-model="inputValue"
rows="1"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : shippingFocusTaskNo ? $t('chat.shippingNoticeUi.focusInputPlaceholder', { taskId: shippingFocusTaskNo }) : $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"
style="min-height: 44px; max-height: 220px;"
:disabled="isThinking || isVoiceTranscribing"
:disabled="isVoiceTranscribing"
spellcheck="false"
autocorrect="off"
autocapitalize="off"
@@ -349,13 +370,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'"
@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" />
</button>
</div>
</div>
<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>
</footer>
@@ -56,23 +56,52 @@ const emit = defineEmits<{
const bindScrollContainer = (node: unknown) => {
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>
<template>
<main class="relative min-h-0 flex-1">
<div
:ref="bindScrollContainer"
class="h-full p-3 md:p-8"
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
>
<div :class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'">
<ChatWelcomePanel
v-if="messages.length === 0"
:agent-name="agentName"
:suggested-questions-style="suggestedQuestionsStyle"
:styled-sections="styledSections"
:suggested-questions="suggestedQuestions"
@select-question="emit('select-question', $event)"
<main
:ref="bindScrollContainer"
class="flex-1 p-3 md:p-8"
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
>
<div :class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'">
<ChatWelcomePanel
v-if="messages.length === 0"
:agent-name="agentName"
:suggested-questions-style="suggestedQuestionsStyle"
:styled-sections="styledSections"
:suggested-questions="suggestedQuestions"
@select-question="emit('select-question', $event)"
/>
<template v-for="(msg, index) in messages" :key="getMessageKey(msg, index)">
<ChatMessageBubble
v-if="shouldRenderMessage(msg)"
:message="msg"
:index="index"
:message-count="messages.length"
:is-thinking="isThinking"
:show-chat-rating="showChatRating"
:copied-index="copiedIndex"
:is-shipping-notice-agent="isShippingNoticeAgent"
:handlers="handlers"
:leave-handlers="leaveHandlers"
:shipping-handlers="shippingHandlers"
@copy="emit('copy', { message: msg, index })"
@edit="emit('edit', $event)"
@resend="emit('resend', $event)"
@regenerate="emit('regenerate')"
@open-feedback="emit('open-feedback', index)"
/>
<template v-for="(msg, index) in messages" :key="index">
@@ -12,6 +12,7 @@ export interface ChatMobileHeaderAgent extends AgentWithCategory {}
defineProps<{
agentName: string;
activeAgentId: number;
hasAgentGuides: boolean;
userAgents: ChatMobileHeaderAgent[];
}>();
@@ -101,6 +102,7 @@ onBeforeUnmount(() => {
<AgentCategoryList
v-if="userAgents.length > 0"
:agents="userAgents"
:active-agent-id="activeAgentId"
@select="onSwitchAgent"
/>
<div v-else class="py-3 text-center text-xs text-muted">{{ $t('chat.noOtherAgents') }}</div>
@@ -1,12 +1,16 @@
/**
* features/chat/components/ChatSidebar.vue
* 桌面端聊天侧栏:Agent 信息、会话历史、Agent 切换面板与底部用户菜单。
* 用途:桌面端聊天侧栏,承载 Agent 信息、会话历史、Agent 切换面板与底部用户菜单。
* 依赖:lucide-vue-next、LocaleToggleButton、AgentCategoryList、chat.types。
* 逻辑:由聊天页面传入当前 Agent、历史记录与用户可用 Agent;通过事件把新会话、切换 Agent、反馈等操作回传给页面。
*/
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import {
BookOpen,
Briefcase,
ChevronDown,
ChevronUp,
LayoutGrid,
LogOut,
MessageSquareText,
@@ -32,6 +36,7 @@ const agentPanelOpen = defineModel<boolean>('agentPanelOpen', { required: true }
const { currentUser } = defineProps<{
isOpen: boolean;
currentAgent: { name?: string } | null;
currentAgentId: number;
agentDescription: string;
hasAgentGuides: boolean;
displayHistory: DisplayHistoryItem[];
@@ -225,23 +230,31 @@ const userInitial = (fallback: string) => {
</div>
<div class="mt-auto flex flex-col p-4">
<div v-if="userAgents.length > 0" class="chat-agent-panel">
<div class="mb-2 flex items-center justify-between gap-2">
<div
v-if="userAgents.length > 0"
class="chat-agent-panel"
:class="{ 'chat-agent-panel--collapsed': !agentPanelOpen }"
>
<div class="flex items-center justify-between gap-2" :class="agentPanelOpen ? 'mb-2' : 'mb-0'">
<div class="flex items-center gap-1.5 text-xs font-semibold text-muted">
<LayoutGrid class="h-3.5 w-3.5" /> {{ $t('chat.agents') }}
<span class="font-normal opacity-70">({{ userAgents.length }})</span>
</div>
<button
type="button"
class="text-[10px] font-medium text-brand-600 hover:text-brand-700"
class="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-md text-brand-600 transition-colors hover:bg-brand-50 hover:text-brand-700 dark:hover:bg-brand-900/30"
:title="agentPanelOpen ? $t('chat.collapseAgents') : $t('chat.expandAgents')"
:aria-label="agentPanelOpen ? $t('chat.collapseAgents') : $t('chat.expandAgents')"
@click="agentPanelOpen = !agentPanelOpen"
>
{{ agentPanelOpen ? $t('chat.collapseAgents') : $t('chat.expandAgents') }}
<ChevronUp v-if="agentPanelOpen" class="h-4 w-4" />
<ChevronDown v-else class="h-4 w-4" />
</button>
</div>
<AgentCategoryList
v-show="agentPanelOpen"
:agents="userAgents"
:active-agent-id="currentAgentId"
compact
@select="emit('switch-agent', $event)"
/>
@@ -294,15 +307,6 @@ const userInitial = (fallback: string) => {
</div>
<div class="flex gap-3">
<button
type="button"
:class="agentPanelOpen && userAgents.length > 0 ? 'text-brand-600' : ''"
class="transition-colors hover:text-secondary"
:title="userAgents.length === 0 ? $t('chat.noAvailableAgents') : (agentPanelOpen ? $t('chat.collapseAgents') : $t('chat.expandAgents'))"
@click="userAgents.length === 0 ? undefined : (agentPanelOpen = !agentPanelOpen)"
>
<LayoutGrid class="h-4 w-4" />
</button>
<button
type="button"
class="transition-colors hover:text-secondary"
@@ -36,6 +36,7 @@ const page = useChatPageContext();
v-model:agent-panel-open="page.showAgentPanel"
:is-open="page.isSidebarOpen"
:current-agent="page.currentAgent"
:current-agent-id="page.currentAgentId"
:agent-description="page.agentDescription"
:has-agent-guides="page.agentGuides.length > 0"
:display-history="page.displayHistory"
@@ -60,6 +61,7 @@ const page = useChatPageContext();
<ChatMobileHeader
v-if="page.isMobile && page.currentAgent"
:agent-name="page.currentAgent?.name || 'AI'"
:active-agent-id="page.currentAgentId"
:has-agent-guides="page.agentGuides.length > 0"
:user-agents="page.userAgents"
@open-guide="page.openGuideModal"
@@ -129,6 +131,7 @@ const page = useChatPageContext();
/>
<ChatInputBar
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
v-model="page.input"
v-model:selected-kb="page.selectedKb"
:attachments="page.attachments"
@@ -1,20 +1,24 @@
/**
* features/chat/components/messages/ChatMessageBubble.vue
* 单条聊天消息:用户气泡、助手 Markdown、请假/出货子组件、来源引用与操作栏。
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
* 依赖:Vue computed、lucide 图标、Leave/Shipping 子消息组件、chat.types 与页面级 handlers。
* 逻辑:由 ChatMessageList 按消息逐条挂载;正文渲染与特殊交互委托 useChatPageMarkdown 等页面编排层提供的 handlers。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { Check, Copy, Edit2, LayoutGrid, MessageSquareText, RotateCw } from 'lucide-vue-next';
import { computed, ref, watch } from 'vue';
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
import ShippingMatchResultCard from './ShippingMatchResultCard.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';
export interface ChatMessageBubbleHandlers {
renderMarkdown: (text: string) => string;
onMarkdownClick: (event: MouseEvent) => void;
getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] };
downloadInlineFile: (file: InlineDownloadFile) => void;
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
canOpenQueryPreview: (msg: ChatMessage) => boolean;
@@ -87,6 +91,12 @@ const showShippingActionsPanel = computed(() =>
);
const isLastMessage = computed(() => index === messageCount - 1);
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>(() => ({
getPayload: shippingHandlers.getParseReviewPayload,
updateHeader: shippingHandlers.updateHeader,
@@ -94,6 +104,335 @@ const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() =>
addLine: shippingHandlers.addLine,
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>
<template>
@@ -142,12 +481,28 @@ const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() =>
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
/>
<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"
@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
v-if="message.role === 'assistant' && handlers.canOpenQueryPreview(message)"
class="mt-4"
@@ -296,6 +651,148 @@ const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() =>
</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>
<style scoped>
@@ -128,6 +128,94 @@ export function useChat() {
const activeRunId = ref<number | null>(null);
let runSeq = 0;
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 run = runs.value.find((r) => r.runId === runId);
@@ -139,6 +227,8 @@ export function useChat() {
};
const createNewChatView = () => {
clearLikelyCompletedStreamTimer();
cancelActiveStream();
viewId.value += 1;
messages.value = [];
conversationId.value = null;
@@ -147,6 +237,8 @@ export function useChat() {
};
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
clearLikelyCompletedStreamTimer();
detachActiveStreamFromView();
viewId.value += 1;
activeRunId.value = null;
isThinking.value = false;
@@ -198,7 +290,14 @@ export function useChat() {
context?: { task_id?: string; batch_no?: string; display_query?: string },
hooks?: SendMessageLifecycleHooks,
) => {
<<<<<<< HEAD
const displayQuery = String(context?.display_query || query || '').trim();
=======
clearLikelyCompletedStreamTimer();
cancelActiveStream();
const controller = new AbortController();
activeStreamController.value = controller;
>>>>>>> dev
const runViewId = viewId.value;
const runMessages = messages.value;
const run: ChatRun = {
@@ -219,6 +318,7 @@ export function useChat() {
let botMsgIndex: number | null = null;
let hasAssistantContent = false;
let hasTerminalEvent = false;
let ignoreFurtherStreamEvents = false;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = runMessages.push({
@@ -237,6 +337,7 @@ export function useChat() {
const response = await fetch('/api/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
signal: controller.signal,
body: JSON.stringify({
query,
agent_id: agentId,
@@ -262,6 +363,10 @@ export function useChat() {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (ignoreFurtherStreamEvents) {
continue;
}
clearLikelyCompletedStreamTimer();
buffer += decoder.decode(value, { stream: true });
buffer = buffer.replace(/\r\n/g, '\n');
@@ -304,6 +409,10 @@ export function useChat() {
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
hasAssistantContent = true;
armLikelyCompletedStreamTimer(controller, run, runMessages, botMsg.content || '', () => {
ignoreFurtherStreamEvents = true;
detachActiveStreamFromView();
});
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
@@ -311,6 +420,7 @@ export function useChat() {
}
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
hasTerminalEvent = true;
ignoreFurtherStreamEvents = true;
const relay = (data.hxops_relay || {}) as Record<string, unknown>;
if (relay.total_relay_ms != null) {
// eslint-disable-next-line no-console
@@ -319,14 +429,30 @@ export function useChat() {
);
}
run.status = 'done';
clearLikelyCompletedStreamTimer();
if (messages.value === runMessages) isThinking.value = false;
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
const normalizedAnswer = normalizeStreamText(data.answer);
hasAssistantContent = true;
const currentContent = botMsg.content || '';
if (data.replace_answer) {
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 {
botMsg.content += normalizedAnswer;
}
@@ -340,29 +466,46 @@ export function useChat() {
if (!botMsg) continue;
applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
run.status = 'error';
clearLikelyCompletedStreamTimer();
if (messages.value === runMessages) isThinking.value = false;
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
hasAssistantContent = true;
armLikelyCompletedStreamTimer(controller, run, runMessages, botMsg.content || '', () => {
ignoreFurtherStreamEvents = true;
detachActiveStreamFromView();
});
}
} catch {
// ignore malformed SSE frames
}
}
}
if (!hasTerminalEvent && hasAssistantContent && run.status === 'running') {
run.status = 'done';
}
} catch (e: unknown) {
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
const message = e instanceof Error ? e.message : 'Network Issue';
applyStreamErrorToMessage(botMsg, message, streamErrorLabels());
clearLikelyCompletedStreamTimer();
if (controller.signal.aborted) {
if (run.status === 'running') {
run.status = hasAssistantContent || hasTerminalEvent ? 'done' : 'error';
}
} else {
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
const message = e instanceof Error ? e.message : 'Network Issue';
applyStreamErrorToMessage(botMsg, message, streamErrorLabels());
}
}
} finally {
clearLikelyCompletedStreamTimer();
if (activeStreamController.value === controller) {
activeStreamController.value = null;
}
if (messages.value === runMessages) {
isThinking.value = false;
}
@@ -173,7 +173,7 @@ export function useChatAgent(options: UseChatAgentOptions) {
try {
const agents = await listUserAgents();
const filtered = Array.isArray(agents)
? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow')
? agents.filter((a: any) => (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
userAgents.value = sortAgentsByCategory(filtered);
// [STEP 1] 有可切换智能体时默认展开面板;避免切换 Agent 后列表「消失」
@@ -10,6 +10,7 @@ import { config } from '@/config';
import { useMessage } from '@/shared/composables/useMessage';
import { useIsMobile } from '@/shared/composables/useIsMobile';
import { useTheme } from '@/shared/composables/useTheme';
import { listChatMessages } from '../api/chat.api';
import { stripReasoningPrelude } from '../utils/chatText';
import type { ChatDeps } from './chat.deps';
import { useChat } from './useChat';
@@ -38,6 +39,39 @@ import {
useChatPageVoice,
useChatPageToolRun,
} 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() {
const { t, locale } = useI18n();
@@ -291,6 +325,28 @@ export function useChatPage() {
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
onAssistantMessageFinished: shipping.finalizeShippingAssistantMessage,
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,
tryHandleLeaveSend: leave.tryHandleLeaveSend,
tryHandleShippingSend: shipping.tryHandleShippingSend,
@@ -121,13 +121,17 @@ export function useChatSessions(options: UseChatSessionsOptions) {
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;
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 };
delete nextQuery.task_id;
@@ -42,6 +42,11 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
const prevConversationId = ctx.conversationId.value;
try {
/**
* 切换会话前先清空输入框草稿,避免 textarea DOM 里残留上一会话的可见文本,
* 但父级 `input` 已经是空字符串,最终出现“看起来输入了内容,发送时却被当成空串”的错觉。
*/
ctx.input.value = '';
ctx.onConversationIdChanging(id, prevConversationId);
const loaded = await listChatMessages(id, ctx.currentAgentId.value);
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 { marked } from 'marked';
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 { Ref } from 'vue';
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 {
messages: Ref<ChatMessage[]>;
isThinking: Ref<boolean>;
@@ -33,6 +80,104 @@ export interface ChatPageMarkdownContext {
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) {
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
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;
};
/**
* 判断某条 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(() => {
if (!ctx.isThinking.value) return false;
let lastUserIndex = -1;
@@ -56,7 +219,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
if (lastUserIndex < 0) return true;
return !ctx.messages.value
.slice(lastUserIndex + 1)
.some((msgItem) => msgItem?.role === 'assistant' && shouldRenderMessage(msgItem));
.some((msgItem) => hasMeaningfulAssistantReply(msgItem));
});
const handleChatMarkdownClick = (event: MouseEvent) => {
@@ -71,15 +234,26 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
ctx.handleLeaveMarkdownClick(event);
};
/**
* 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。
* 核心逻辑:先抽取 FILE_START/FILE_END 文件,再走既有 Markdown 清洗与 marked 渲染,保证聊天气泡只展示可读文本。
* @param text - 原始聊天文本。
* @returns 供 v-html 使用的安全展示字符串。
*/
const renderMarkdown = (text: string) => {
if (!text) return '';
const displayText = ctx.prepareMarkdownDisplayText(text);
const extracted = safeExtractInlineDownloadFiles(text);
const displayText = ctx.prepareMarkdownDisplayText(extracted.cleanedText);
try {
const rendered = marked.parse(displayText);
const html = typeof rendered === 'string' ? rendered : displayText;
return html.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml: string) => (
`<div class="chat-table-scroll"><div class="chat-table-inner">${tableHtml}</div></div>`
));
return html
.replace(/<(td|th)\b([^>]*)>(?:\s|&nbsp;|<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 {
return displayText;
}
@@ -88,6 +262,8 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
renderMarkdown,
onMarkdownClick: handleChatMarkdownClick,
getInlineDownloadFiles: safeExtractInlineDownloadFiles,
downloadInlineFile,
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
getShippingMatchResultPayload: ctx.getShippingMatchResultPayload,
canOpenQueryPreview: ctx.canOpenQueryPreview,
@@ -1,4 +1,4 @@
/**
/**
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
*/
import { computed } from 'vue';
@@ -29,6 +29,7 @@ export interface ChatPageSendContext {
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
refreshHistoryAfterSend: () => Promise<void>;
refreshConversationAfterSend?: () => Promise<void>;
tryHandleShippingAttachmentAutoFlow: (
textOrEvent: string | Event | undefined,
content: string,
@@ -63,8 +64,12 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
return;
}
if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) return;
if (ctx.tryHandleLeaveSend(content)) return;
if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) {
return;
}
if (ctx.tryHandleLeaveSend(content)) {
return;
}
if (await ctx.tryHandleShippingSend(textOrEvent, content, trimmed)) {
return;
}
@@ -103,6 +108,7 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
{ onAssistantMessageFinished: ctx.onAssistantMessageFinished },
);
await ctx.refreshHistoryAfterSend();
await ctx.refreshConversationAfterSend?.();
await ctx.refreshToolRunProgressAfterSend();
};
@@ -1,6 +1,8 @@
/**
* features/chat/types/chat.types.ts
* 聊天域核心类型定义。
* 用途:定义聊天域的消息、会话、预览与附件下载等共享类型。
* 依赖:被 chat 页面 composables、消息气泡组件、API 封装共同引用。
* 逻辑:作为 features/chat 域的类型中枢,向上提供页面编排约束,向下约束消息渲染与交互结构。
*/
import type { LeaveAgentOption } from './leave.types';
@@ -39,6 +41,12 @@ export interface ChatMessage {
stream_error?: boolean;
}
export interface InlineDownloadFile {
name: string;
data: string;
mime_type?: string;
}
export type ChatRunStatus = 'running' | 'done' | 'error';
export interface ChatRun {
@@ -36,6 +36,7 @@ import {
type KbGroup,
type KbJob,
} from '../api/kb.api';
import { formatDateTime } from '../utils/kb-display.utils';
type GroupFilterMode = 'all' | 'withDocs' | 'empty';
type GroupSortMode = 'updatedDesc' | 'updatedAsc' | 'docsDesc' | 'docsAsc' | 'nameAsc';
@@ -99,6 +100,9 @@ const pagedGroups = computed(() => {
return filteredGroups.value.slice(start, start + pageSize.value);
});
/** 格式化分组更新时间,避免管理台表格直接暴露后端 ISO 时间字符串。 */
const formatGroupUpdatedAt = (value?: string | null) => formatDateTime(value);
/** 加载知识库治理页的分组与任务队列,供页面初始渲染和操作后刷新复用。 */
const loadData = async () => {
isRefreshing.value = true;
@@ -315,8 +319,8 @@ defineExpose({ loadData });
{{ group.description || t('kbAdmin.noDescription') }}
</div>
</td>
<td class="px-6 py-4 align-middle"><span class="kb-admin-badge whitespace-nowrap">{{ t('kbAdmin.documentCount', { count: group.document_count ?? 0 }) }}</span></td>
<td class="px-6 py-4 align-middle text-sm text-muted"><div class="truncate" :title="group.updated_at || '--'">{{ group.updated_at || '--' }}</div></td>
<td class="px-6 py-4 align-middle"><span class="kb-admin-badge whitespace-nowrap">{{ group.document_count ?? 0 }}</span></td>
<td class="px-6 py-4 align-middle text-sm text-muted"><div class="truncate" :title="formatGroupUpdatedAt(group.updated_at)">{{ formatGroupUpdatedAt(group.updated_at) }}</div></td>
<td class="px-6 py-4 align-middle">
<div class="flex justify-end gap-1.5">
<button type="button" class="btn-icon-ds border border-default" @click="openEditDrawer(group)" :title="t('common.edit')"><Pencil class="h-4 w-4" /></button>
@@ -335,10 +339,10 @@ defineExpose({ loadData });
<h3 class="font-semibold text-primary">{{ group.name }}</h3>
<p class="mt-1 line-clamp-2 text-sm text-muted" :title="group.description || t('kbAdmin.noDescription')">{{ group.description || t('kbAdmin.noDescription') }}</p>
</div>
<span class="kb-admin-badge">{{ t('kbAdmin.documentCount', { count: group.document_count ?? 0 }) }}</span>
<span class="kb-admin-badge">{{ group.document_count ?? 0 }}</span>
</div>
<div class="mt-3 flex items-center justify-between gap-3">
<span class="text-xs text-muted">{{ group.updated_at || '--' }}</span>
<span class="text-xs text-muted">{{ formatGroupUpdatedAt(group.updated_at) }}</span>
<div class="flex gap-1.5">
<button type="button" class="btn-icon-ds border border-default" @click="openEditDrawer(group)" :title="t('common.edit')"><Pencil class="h-4 w-4" /></button>
<button type="button" class="btn-icon-ds border border-rose-200 text-rose-600" @click="handleDeleteGroup(group)" :title="t('common.delete')"><Trash2 class="h-4 w-4" /></button>
@@ -3,7 +3,7 @@
* features/kb/views/KbWorkspaceView.vue
* 知识库作业面视图壳:模板与弹窗布局,业务逻辑见 useKbWorkspace。
*/
import { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, Info, RefreshCw, Search, Trash2, Upload } from 'lucide-vue-next';
import { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, Info, RefreshCw, Search, Settings, Trash2, Upload } from 'lucide-vue-next';
import KbWorkspaceOverlays from '../components/KbWorkspaceOverlays.vue';
import { useKbWorkspace } from '../composables/useKbWorkspace';
@@ -52,6 +52,15 @@ const kb = useKbWorkspace({ embedded: props.embedded });
<RefreshCw class="h-4 w-4" />
{{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.actions.refreshGroups') : kb.t('kbWorkspace.actions.refreshDocuments') }}
</button>
<button
v-if="kb.viewMode === 'group_overview'"
type="button"
@click="kb.router.push('/admin/knowledge-base')"
class="btn-primary"
>
<Settings class="h-4 w-4" />
{{ kb.t('kbWorkspace.actions.manageGroups') }}
</button>
</div>
</div>
@@ -65,24 +74,26 @@ const kb = useKbWorkspace({ embedded: props.embedded });
<div v-else-if="kb.groups.length === 0" class="kb-ws-empty py-10 text-center text-sm text-muted">
{{ kb.t('kbWorkspace.overview.emptyGroups') }}
</div>
<div v-else class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3 auto-rows-fr">
<div v-else class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">
<div
v-for="group in kb.groups"
:key="group.id"
@click="kb.openGroupDetail(group.id)"
class="kb-ws-card--interactive"
class="kb-ws-card--interactive !min-h-[150px]"
>
<div class="w-full text-left">
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="text-xl font-bold leading-tight text-primary break-words">{{ group.name }}</div>
<div class="mt-1 text-sm text-muted">{{ group.description || kb.t('kbWorkspace.overview.noDescription') }}</div>
<div class="mt-1 line-clamp-2 text-sm text-muted" :title="group.description || kb.t('kbWorkspace.overview.noDescription')">
{{ group.description || kb.t('kbWorkspace.overview.noDescription') }}
</div>
</div>
<div class="rounded-full bg-surface-soft px-2.5 py-1 text-xs font-medium text-secondary whitespace-nowrap">
{{ kb.t('kbWorkspace.overview.documentCount', { count: group.document_count ?? 0 }) }}
</div>
</div>
<div class="mt-4 text-xs text-muted">{{ kb.t('kbWorkspace.overview.updatedAt') }}{{ kb.formatDateTime(group.updated_at) }}</div>
<div class="mt-3 text-xs text-muted">{{ kb.t('kbWorkspace.overview.updatedAt') }}{{ kb.formatDateTime(group.updated_at) }}</div>
</div>
</div>
</div>
+19
View File
@@ -430,5 +430,24 @@
"copySuccess": "Copied",
"copyFailed": "Copy failed. Please allow clipboard access or try again.",
"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"
}
}
}
+2 -1
View File
@@ -117,7 +117,8 @@
"backToOverview": "Back to Group Overview",
"backToWorkspace": "Back to Workspace",
"refreshGroups": "Refresh Groups",
"refreshDocuments": "Refresh Documents"
"refreshDocuments": "Refresh Documents",
"manageGroups": "Manage Groups"
},
"overview": {
"title": "Select a Group",
+19
View File
@@ -430,5 +430,24 @@
"copySuccess": "คัดลอกแล้ว",
"copyFailed": "คัดลอกไม่สำเร็จ โปรดอนุญาตการเข้าถึงคลิปบอร์ดแล้วลองอีกครั้ง",
"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": "ไม่พบข้อมูลที่ตรงเงื่อนไข"
}
}
}
+2 -1
View File
@@ -117,7 +117,8 @@
"backToOverview": "กลับไปรายการกลุ่ม",
"backToWorkspace": "กลับไปเวิร์กสเปซ",
"refreshGroups": "รีเฟรชกลุ่ม",
"refreshDocuments": "รีเฟรชเอกสาร"
"refreshDocuments": "รีเฟรชเอกสาร",
"manageGroups": "จัดการกลุ่ม"
},
"overview": {
"title": "เลือกกลุ่ม",
+19
View File
@@ -430,5 +430,24 @@
"copySuccess": "已复制",
"copyFailed": "复制失败,请允许剪贴板权限后重试",
"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": "暂无符合条件的数据"
}
}
}
+2 -1
View File
@@ -117,7 +117,8 @@
"backToOverview": "返回分组列表",
"backToWorkspace": "返回工作台",
"refreshGroups": "刷新分组",
"refreshDocuments": "刷新文档"
"refreshDocuments": "刷新文档",
"manageGroups": "管理分组"
},
"overview": {
"title": "选择分组",
+19
View File
@@ -430,5 +430,24 @@
"copySuccess": "已複製",
"copyFailed": "複製失敗,請允許剪貼簿權限後重試",
"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": "暫無符合條件的資料"
}
}
}
+2 -1
View File
@@ -117,7 +117,8 @@
"backToOverview": "返回分組列表",
"backToWorkspace": "返回工作台",
"refreshGroups": "刷新分組",
"refreshDocuments": "刷新文檔"
"refreshDocuments": "刷新文檔",
"manageGroups": "管理分組"
},
"overview": {
"title": "選擇分組",
@@ -16,10 +16,12 @@ import {
const props = withDefaults(defineProps<{
agents: AgentWithCategory[];
activeAgentId?: number | null;
compact?: boolean;
showSearch?: boolean;
defaultExpanded?: boolean;
}>(), {
activeAgentId: null,
compact: false,
showSearch: true,
defaultExpanded: true,
@@ -72,7 +74,10 @@ const toggleCategory = (category: string) => {
const isCategoryCollapsed = (category: string) => collapsedCategories.value.has(category);
const isActiveAgent = (agent: AgentWithCategory) => agent.id === props.activeAgentId;
const onSelect = (agent: AgentWithCategory) => {
if (isActiveAgent(agent)) return;
emit('select', agent);
};
</script>
@@ -119,7 +124,11 @@ const onSelect = (agent: AgentWithCategory) => {
v-for="agent in subGroup.agents"
:key="agent.id"
type="button"
class="grid w-full min-w-0 grid-cols-[1rem_1fr] items-center gap-1.5 rounded-xl px-2 py-2 text-left text-xs font-medium text-secondary transition-colors hover-surface-soft hover:shadow-sm"
class="grid w-full min-w-0 grid-cols-[1rem_1fr] items-center gap-1.5 rounded-xl px-2 py-2 text-left text-xs font-medium transition-colors"
:class="isActiveAgent(agent)
? 'cursor-default bg-brand-50 text-brand-700 shadow-sm ring-1 ring-brand-100 dark:bg-brand-900/20 dark:text-brand-300 dark:ring-brand-800/50'
: 'text-secondary hover-surface-soft hover:shadow-sm'"
:aria-current="isActiveAgent(agent) ? 'page' : undefined"
@click="onSelect(agent)"
>
<div
+11 -5
View File
@@ -1,21 +1,26 @@
/**
/**
* shared/composables/useIsMobile.ts
* 检测竖屏/横屏,供移动端布局切换。
* 用途:按视口宽度提供统一的移动端判定,供聊天页与工作台切换布局。
* 依赖:浏览器 `matchMedia` 与 Vue 生命周期。
* 逻辑:组件挂载后监听 `max-width: 767px`,避免把“窄屏横屏”误判成桌面布局。
*/
import { ref, onMounted, onBeforeUnmount, readonly } from 'vue';
const isMobile = ref(false);
const mobileMediaQuery = '(max-width: 767px)';
let listeners = 0;
let mediaQueryList: MediaQueryList | null = null;
const update = () => {
isMobile.value = window.innerHeight > window.innerWidth;
isMobile.value = window.matchMedia(mobileMediaQuery).matches;
};
const startListening = () => {
if (listeners === 0) {
mediaQueryList = window.matchMedia(mobileMediaQuery);
update();
window.addEventListener('resize', update);
mediaQueryList.addEventListener('change', update);
}
listeners++;
};
@@ -24,7 +29,8 @@ const stopListening = () => {
listeners--;
if (listeners <= 0) {
listeners = 0;
window.removeEventListener('resize', update);
mediaQueryList?.removeEventListener('change', update);
mediaQueryList = null;
}
};
@@ -751,6 +751,10 @@
background-color: color-mix(in srgb, var(--bg-surface-soft) 85%, transparent);
}
.chat-agent-panel--collapsed {
@apply py-2.5;
}
.chat-icon-muted {
@apply text-muted transition-colors hover:text-secondary;
}