fix: 支持原文件下载,同时将postgres地址由localhost变更为8.152.207.171

This commit is contained in:
sophie committed 2026-04-03 11:30:49 +08:00
1 parent 70f95e9f5c
commit c380248502
12 files changed
+1273 -273

No files matched your search

+97 -1
View File
@@ -1,4 +1,13 @@
<script setup lang="ts">
/**
* FilePreviewModal.vue
* 文件用途:文件预览弹窗,用于在聊天页预览来源文件内容
* 引用文件:vue, marked
* 逻辑关系:
* - 接收 ChatView 传入的 file(name/url)与弹窗显隐状态
* - 根据扩展名选择预览模式(markdown/image/iframe)
* - 对 Office 文档在可公网 HTTPS 访问时走 Office 在线预览,否则降级为打开/下载
*/
import { computed, ref, watch } from 'vue';
import { marked } from 'marked';
@@ -20,6 +29,11 @@ const isLoading = ref(false);
const error = ref('');
const markdownHtml = ref('');
/**
* Extract extension from URL or filename.
* - Drops query string first (for signed URLs).
* - Returns lowercase extension without dot.
*/
const getExt = (raw: string) => {
const clean = (raw.split('?')[0] ?? '').toLowerCase();
const i = clean.lastIndexOf('.');
@@ -40,9 +54,50 @@ const preferredMode = computed<'markdown' | 'image' | 'iframe'>(() => {
});
const resolvedMode = ref<'markdown' | 'image' | 'iframe'>('iframe');
const isOfficeDoc = computed(() => ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value));
/**
* Decide whether Office Online Viewer can be used safely.
* Requirements (practical):
* - Office-like file type.
* - HTTPS URL.
* - Publicly reachable host (not localhost/private subnet).
*/
const canUseOfficeOnlineViewer = computed(() => {
const raw = props.file?.url || '';
if (!raw || !isOfficeDoc.value) return false;
try {
const u = new URL(raw, window.location.origin);
// Office online viewer usually requires a publicly reachable HTTPS URL.
// Private-network or local addresses typically render as blank pages.
if (u.protocol !== 'https:') return false;
const host = u.hostname;
if (
host === 'localhost' ||
host === '127.0.0.1' ||
host === '::1' ||
/^10\./.test(host) ||
/^192\.168\./.test(host) ||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)
) {
return false;
}
return true;
} catch {
return false;
}
});
const needsOfficeFallback = computed(() => isOfficeDoc.value && !canUseOfficeOnlineViewer.value);
/**
* Compute iframe source.
* - Office docs with public HTTPS: use Office Online embed endpoint.
* - Otherwise: fallback to raw file URL (browser/native handling).
*/
const iframeSrc = computed(() => {
if (!props.file?.url) return '';
if (['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value)) {
if (isOfficeDoc.value && canUseOfficeOnlineViewer.value) {
return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(props.file.url)}`;
}
return props.file.url;
@@ -50,6 +105,14 @@ const iframeSrc = computed(() => {
const close = () => emit('update:modelValue', false);
/**
* Load preview content when modal/file changes.
* Strategy:
* 1) Reset state and choose preferred mode by extension.
* 2) Only actively fetch for markdown/text mode.
* 3) Auto-switch mode by response content-type (image/binary/text).
* 4) Parse markdown to HTML on success; set error on failure.
*/
const loadContent = async () => {
error.value = '';
markdownHtml.value = '';
@@ -87,6 +150,12 @@ const loadContent = async () => {
}
};
/**
* Reactively reload preview when:
* - modal visibility changes
* - file URL changes
* - file name changes
*/
watch(
() => [props.modelValue, props.file?.url, props.file?.name],
() => {
@@ -121,6 +190,33 @@ watch(
<div v-else-if="resolvedMode === 'image'" class="h-full flex items-center justify-center bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg p-2">
<img :src="file.url" :alt="file.name" class="max-w-full max-h-full object-contain" />
</div>
<div
v-else-if="needsOfficeFallback"
class="h-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 p-6"
>
<!-- Graceful fallback for private/non-HTTPS Office links:
show actions instead of an empty iframe. -->
<div class="text-sm text-slate-700 dark:text-slate-200 font-semibold">Preview not available for this file URL</div>
<div class="mt-2 text-sm text-slate-500 dark:text-slate-400">
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
</div>
<div class="mt-4 flex gap-3">
<a
:href="file.url"
target="_blank"
class="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700"
>
Open in new tab
</a>
<a
:href="file.url"
download
class="px-3 py-2 rounded-lg border border-slate-300 dark:border-slate-600 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-800"
>
Download file
</a>
</div>
</div>
<iframe
v-else
:src="iframeSrc"
+148 -105
View File
@@ -23,6 +23,75 @@ interface ChatMessage {
attribution_parts?: string[];
}
const normalizeResources = (resources: any): RetrieverResource[] => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
if (Array.isArray(resources.data)) return resources.data;
return [];
};
const addRetrieverResources = (msg: ChatMessage, resources: any) => {
const list = normalizeResources(resources);
if (list.length === 0) return;
if (!msg.retriever_resources) msg.retriever_resources = [];
for (const item of list) {
const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`;
const exists = msg.retriever_resources.some(
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
);
if (!exists) {
msg.retriever_resources.push(item);
}
}
};
const addAttributionParts = (msg: ChatMessage, value: any) => {
if (!value) return;
if (!msg.attribution_parts) msg.attribution_parts = [];
const pushUnique = (text: string) => {
const v = text.trim();
if (!v) return;
if (!msg.attribution_parts!.includes(v)) {
msg.attribution_parts!.push(v);
}
};
if (typeof value === 'string') {
pushUnique(value);
return;
}
if (Array.isArray(value)) {
for (const item of value) {
if (typeof item === 'string') {
pushUnique(item);
} else if (item && typeof item === 'object') {
pushUnique(item.content || item.text || item.title || JSON.stringify(item));
}
}
return;
}
if (typeof value === 'object') {
pushUnique(value.content || value.text || value.title || JSON.stringify(value));
}
};
const applyEventMetadata = (msg: ChatMessage, data: any) => {
const metadata = data?.metadata || {};
addRetrieverResources(msg, data?.retriever_resources);
addRetrieverResources(msg, metadata?.retriever_resources);
addRetrieverResources(msg, metadata?.retrieverResources);
addAttributionParts(msg, data?.annotations);
addAttributionParts(msg, data?.annotation_reply);
addAttributionParts(msg, metadata?.annotations);
addAttributionParts(msg, metadata?.annotation_reply);
addAttributionParts(msg, data?.citation);
addAttributionParts(msg, metadata?.citation);
};
export function useChat() {
/**
* messages: 响应式消息列表,用于 UI 渲染
@@ -81,6 +150,11 @@ export function useChat() {
* agentId: 目标 Agent ID
*/
const sendMessage = async (query: string, agentId: number) => {
console.info('[chat][send] start', {
agentId,
queryLength: query.length,
conversationId: conversationId.value,
});
// 1. 乐观 UI 更新:立即将用户消息推入列表
messages.value.push({ role: 'user', content: query });
// 创建一个空的 Assistant 消息用于流式追加,并记录其索引
@@ -105,8 +179,15 @@ export function useChat() {
})
});
console.info('[chat][send] response', {
ok: response.ok,
status: response.status,
contentType: response.headers.get('content-type'),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
console.error('[chat][send] non-ok response', err);
throw new Error(err.error || `Request failed with status ${response.status}`);
}
@@ -116,128 +197,90 @@ export function useChat() {
if (!reader) throw new Error('No reader');
// 循环读取流数据
// Loop read SSE stream; use a buffer to avoid dropping partial chunks.
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
// 解码二进制块为文本
const chunk = decoder.decode(value);
// SSE 数据可能包含多行,按双换行符分割
const lines = chunk.split('\n\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
// 解析 JSON 数据
const data = JSON.parse(line.slice(6));
// 仅处理 message 事件,追加 answer 到当前消息
if (data.event === 'message') {
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
botMsg.content += data.answer;
applyEventMetadata(botMsg, data);
} else if (data.event === 'message_end') {
// 记录会话 ID,便于后续发送反馈
if (data.conversation_id) {
conversationId.value = data.conversation_id;
}
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
applyEventMetadata(botMsg, data);
} else if (data.event === 'agent_message' || data.event === 'workflow_finished') {
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
applyEventMetadata(botMsg, data);
} else if (data.event === 'error') {
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
botMsg.content += `\n[Error: ${data.message}]`;
}
} catch (e) {
// 忽略 JSON 解析错误 (可能是 keep-alive 或非完整 JSON)
// Decode as stream and normalize CRLF so Windows-style SSE frames are parsed correctly.
buffer += decoder.decode(value, { stream: true });
buffer = buffer.replace(/\r\n/g, '\n');
const frames = buffer.split('\n\n');
buffer = frames.pop() || '';
for (const frame of frames) {
const dataLines = frame
.split('\n')
.map((l) => l.trim())
.filter((l) => l.startsWith('data:'));
if (dataLines.length === 0) continue;
// SSE allows multiple data lines in one event.
const payload = dataLines
.map((l) => l.replace(/^data:\s?/, ''))
.join('\n');
if (!payload) continue;
try {
const data = JSON.parse(payload);
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
console.debug('[chat][sse] event', {
event: data?.event,
answerLength: typeof data?.answer === 'string' ? data.answer.length : 0,
hasRetrieverResources: Boolean(data?.retriever_resources || data?.metadata?.retriever_resources),
conversationId: data?.conversation_id || conversationId.value,
});
if (data.event === 'message' || data.event === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
botMsg.content += data.answer;
console.debug('[chat][sse] append answer chunk', {
event: data.event,
appended: data.answer.length,
total: botMsg.content.length,
});
}
applyEventMetadata(botMsg, data);
} else if (data.event === 'message_end' || data.event === 'workflow_finished') {
if (data.conversation_id) {
conversationId.value = data.conversation_id;
}
// Some providers may put final answer on message_end/workflow events.
if (typeof data.answer === 'string' && data.answer.length > 0) {
botMsg.content += data.answer;
console.debug('[chat][sse] append final answer', {
event: data.event,
appended: data.answer.length,
total: botMsg.content.length,
});
}
applyEventMetadata(botMsg, data);
} else if (data.event === 'error') {
botMsg.content += `\n[Error: ${data.message}]`;
console.error('[chat][sse] backend error event', data);
}
} catch (e) {
// Ignore malformed or partial payload fragments.
console.warn('[chat][sse] parse failed', { payloadPreview: payload.slice(0, 200), error: e });
}
}
}
} catch (e: any) {
console.error(e);
console.error('[chat][send] failed', e);
const botMsg = messages.value[botMsgIndex];
if (botMsg) {
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
}
} finally {
isThinking.value = false;
console.info('[chat][send] end', {
messages: messages.value.length,
conversationId: conversationId.value,
});
}
};
return { messages, isThinking, conversationId, sendMessage };
}
const normalizeResources = (resources: any): RetrieverResource[] => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
if (Array.isArray(resources.data)) return resources.data;
return [];
};
const addRetrieverResources = (msg: ChatMessage, resources: any) => {
const list = normalizeResources(resources);
if (list.length === 0) return;
if (!msg.retriever_resources) msg.retriever_resources = [];
for (const item of list) {
const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`;
const exists = msg.retriever_resources.some(
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
);
if (!exists) {
msg.retriever_resources.push(item);
}
}
};
const addAttributionParts = (msg: ChatMessage, value: any) => {
if (!value) return;
if (!msg.attribution_parts) msg.attribution_parts = [];
const pushUnique = (text: string) => {
const v = text.trim();
if (!v) return;
if (!msg.attribution_parts!.includes(v)) {
msg.attribution_parts!.push(v);
}
};
if (typeof value === 'string') {
pushUnique(value);
return;
}
if (Array.isArray(value)) {
for (const item of value) {
if (typeof item === 'string') {
pushUnique(item);
} else if (item && typeof item === 'object') {
pushUnique(item.content || item.text || item.title || JSON.stringify(item));
}
}
return;
}
if (typeof value === 'object') {
pushUnique(value.content || value.text || value.title || JSON.stringify(value));
}
};
const applyEventMetadata = (msg: ChatMessage, data: any) => {
const metadata = data?.metadata || {};
addRetrieverResources(msg, data?.retriever_resources);
addRetrieverResources(msg, metadata?.retriever_resources);
addRetrieverResources(msg, metadata?.retrieverResources);
addAttributionParts(msg, data?.annotations);
addAttributionParts(msg, data?.annotation_reply);
addAttributionParts(msg, metadata?.annotations);
addAttributionParts(msg, metadata?.annotation_reply);
addAttributionParts(msg, data?.citation);
addAttributionParts(msg, metadata?.citation);
};
+16 -3
View File
@@ -33,8 +33,17 @@ const messages = {
rememberMe: 'Remember me for 30 days',
forgotPasswordDesc: 'Enter your email to reset your password',
findPassword: 'Find Password',
announcements: 'Announcements',
passwordResetEmailSent: 'If the account exists, a reset link has been sent to your email.',
passwordResetRequestFailed: 'Failed to request password reset',
wecomLogin: 'Login with WeCom',
wecomConnecting: 'Connecting to WeCom...'
wecomConnecting: 'Connecting to WeCom...',
wecomStartFailed: 'Failed to start WeCom login',
wecomInvalidState: 'Invalid WeCom login state',
wecomStateExpired: 'WeCom login session expired, please try again.',
wecomBindRequired: 'Current WeCom account is not bound to a local user, please contact admin.',
wecomAccountDisabled: 'Account is disabled, please contact admin.',
wecomLoginFailed: 'WeCom login failed'
},
landing: {
hero: {
@@ -57,12 +66,16 @@ const messages = {
failed: 'Registration failed',
inputError: 'Please enter username and password',
requestFailed: 'Request failed',
emailRequired: 'Email is required',
fields: {
realName: 'Real Name',
employeeId: 'Employee ID',
phone: 'Phone Number'
}
},
common: {
errorOccurred: 'An error occurred'
},
workspace: {
title: 'AI Workspace',
userTitle: '{username}\'s AI Workspace',
@@ -586,8 +599,8 @@ const messages = {
landing: {
hero: {
prefix: '释放',
highlight: '生成式 AI 的力量',
subtitle: '访问为您企业量身定制的强大 AI 助手套件。安全、可扩展、智能。'
highlight: '生成式 AI 的强大力量',
subtitle: '获取一套专为企业需求打造的强大 AI 智能体,安全、可扩展且智能。'
},
agent: {
role: 'AI 助手'
+68 -28
View File
@@ -63,6 +63,12 @@ interface SourceFileLink {
url: string;
}
const PREFERRED_SOURCE_EXTS = new Set([
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp',
'txt', 'rtf', 'md', 'markdown',
]);
const safeDecode = (value: string) => {
try {
return decodeURIComponent(value);
@@ -92,6 +98,43 @@ const normalizeUrl = (url: string) => {
return '';
};
const getUrlExt = (url: string) => {
const clean = (url.split('?')[0] || '').toLowerCase();
const idx = clean.lastIndexOf('.');
if (idx < 0) return '';
return clean.slice(idx + 1);
};
const isChunkLikeLink = (url: string) => {
// Keep original Markdown files; only filter explicit chunk/segment-style links.
return /segment|chunk|fragments?|split/i.test(url);
};
const isPreferredSourceLink = (url: string) => {
const ext = getUrlExt(url);
return PREFERRED_SOURCE_EXTS.has(ext);
};
const isNoisySourceUrl = (url: string) => {
// Raw signed download links are noisy in UI (e.g. download?version_id=...&token=...).
return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
};
const isNoisySourceName = (name: string) => {
// Guard against names that are actually query strings instead of human-readable filenames.
const n = (name || '').trim().toLowerCase();
return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
};
const looksLikeFileName = (name: string) => {
const n = (name || '').trim();
if (!n) return false;
// Keep Chinese/English file labels such as 员工手册.doc
return /\.[A-Za-z0-9]{2,8}$/.test(n);
};
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
const extractUrlsFromText = (text: string) => {
if (!text) return [];
const urls: string[] = [];
@@ -139,11 +182,13 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
for (const item of resources) {
const directCandidates = [
item?.source_download_url,
item?.url,
item?.file_url,
item?.document_url,
item?.source_url,
item?.download_url,
item?.metadata?.source_download_url,
item?.metadata?.url,
item?.metadata?.file_url,
item?.metadata?.document_url,
@@ -167,14 +212,21 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
}
for (const url of discovered) {
const name = item?.document_name || item?.title || decodeURIComponent(url.split('/').pop() || 'source-file');
if (isChunkLikeLink(url)) continue;
// If URL is noisy and we don't have an explicit filename from metadata, skip it.
if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
const name = item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file');
// Skip links whose display name itself is noisy.
if (isNoisySourceName(name)) continue;
const key = `${name}|${url}`;
if (!map.has(key)) {
map.set(key, { name, url });
}
}
}
return Array.from(map.values());
const links = Array.from(map.values());
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
return preferred.length > 0 ? preferred : links;
};
const getMessageLinks = (msg: any): SourceFileLink[] => {
@@ -182,41 +234,29 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
const merge = (links: SourceFileLink[]) => {
for (const link of links) {
if (isChunkLikeLink(link.url)) continue;
// Keep file buttons if name is valid, even when URL is signed/temporary.
if (isNoisySourceName(link.name)) continue;
if (isMarkdownFileName(link.name)) {
const key = `${link.name}|${link.url}`;
if (!map.has(key)) map.set(key, link);
continue;
}
if (isNoisySourceUrl(link.url) && !looksLikeFileName(link.name)) continue;
const key = `${link.name}|${link.url}`;
if (!map.has(key)) map.set(key, link);
}
};
if (msg?.retriever_resources) {
// Only use structured retriever resources for source buttons,
// so we don't accidentally show random URLs from answer text.
merge(getSourceLinks(msg.retriever_resources));
}
const contentLinks = extractUrlsFromText(msg?.content || '');
for (const url of contentLinks) {
const name = safeDecode(url.split('/').pop() || 'source-file');
merge([{ name, url }]);
}
if (Array.isArray(msg?.attribution_parts)) {
for (const part of msg.attribution_parts) {
const urls = extractUrlsFromText(typeof part === 'string' ? part : JSON.stringify(part));
for (const url of urls) {
const name = safeDecode(url.split('/').pop() || 'source-file');
merge([{ name, url }]);
}
}
}
// 5) 最后兜底:扫描整条 assistant 消息的 JSON 字符串。
// 用途:覆盖 Dify 在未知嵌套字段里返回链接但未被上面路径命中的情况。
const fullMessageText = JSON.stringify(msg || {});
const allUrls = extractUrlsFromText(fullMessageText);
for (const url of allUrls) {
const name = safeDecode(url.split('/').pop() || 'source-file');
merge([{ name, url }]);
}
return Array.from(map.values());
const links = Array.from(map.values());
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
return preferred.length > 0 ? preferred : links;
};
const filePreviewVisible = ref(false);
+36 -35
View File
@@ -1,8 +1,8 @@
<script setup lang="ts">
/**
* WorkspaceView.vue
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口
* 鏂囦欢鐢ㄩ€旓細鐢ㄦ埛宸ヤ綔鍙帮紝鏀寔鑷畾涔夊竷灞€銆佹敹钘忋€佸祵鍏?Agent
* 寮曠敤鏂囦欢锛歷ue, vue-router, lucide-vue-next, 鍚庣 /api/user 鎺ュ彛
*/
import { ref, onMounted, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
@@ -19,6 +19,7 @@ import {
Edit,
ExternalLink,
Bot,
Lock,
User,
LogOut,
Megaphone,
@@ -120,7 +121,7 @@ const isWecomLoggingIn = ref(false);
const handleForgotPassword = async () => {
if (!forgotPasswordForm.value.email) {
alert(t('register.email') + ' is required');
alert(t('register.emailRequired'));
return;
}
@@ -133,21 +134,21 @@ const handleForgotPassword = async () => {
const data = await res.json();
if (res.ok) {
alert(t('login.passwordResetEmailSent') || 'If the account exists, a reset link has been sent to your email.');
alert(t('login.passwordResetEmailSent'));
showForgotPasswordModal.value = false;
forgotPasswordForm.value = { email: '' };
} else {
alert(data.error || 'Failed to request password reset');
alert(data.error || t('login.passwordResetRequestFailed'));
}
} catch (e) {
console.error('Password reset error', e);
alert('An error occurred');
alert(t('common.errorOccurred'));
}
};
/*
const showLoginTip = () => {
alert(t('login.pleaseLoginFirst') || 'Please login to access this agent.');
alert(t('login.pleaseLoginFirst'));
};
*/
const userReport = ref<any>(null);
@@ -399,11 +400,11 @@ const handleLogin = async () => {
const err = await res.json();
// Handle specific error messages if needed, or just alert
let msg = err.error || t('login.failed');
if (err.error === 'User not found') msg = t('login.userNotFound') || 'User not found';
if (err.error === 'Incorrect password') msg = t('login.incorrectPassword') || 'Incorrect password';
if (err.error === 'Account is disabled') msg = t('login.accountDisabled') || 'Account is disabled';
if (err.error === 'Database connection failed') msg = t('login.dbConnectionFailed') || 'Database connection failed';
if (err.error === 'Internal server error') msg = t('login.internalError') || 'Internal server error';
if (err.error === 'User not found') msg = t('login.userNotFound');
if (err.error === 'Incorrect password') msg = t('login.incorrectPassword');
if (err.error === 'Account is disabled') msg = t('login.accountDisabled');
if (err.error === 'Database connection failed') msg = t('login.dbConnectionFailed');
if (err.error === 'Internal server error') msg = t('login.internalError');
alert(msg);
return;
@@ -426,7 +427,7 @@ const handleLogin = async () => {
}
} catch (e) {
console.error(e);
alert(t('login.requestFailed') || 'Login request failed. Please check your network or server status.');
alert(t('login.requestFailed'));
}
};
@@ -438,7 +439,7 @@ const handleWecomLogin = async () => {
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
const data = await res.json();
if (!res.ok || !data.url) {
alert(data.error || 'Failed to start WeCom login');
alert(data.error || t('login.wecomStartFailed'));
return;
}
if (data.state) {
@@ -447,7 +448,7 @@ const handleWecomLogin = async () => {
window.location.href = data.url;
} catch (e) {
console.error(e);
alert('Failed to start WeCom login');
alert(t('login.wecomStartFailed'));
}
};
@@ -461,7 +462,7 @@ const tryWecomCallbackLogin = async () => {
const expectedState = sessionStorage.getItem('hxops_wecom_state');
if (expectedState && state && state !== expectedState) {
alert('Invalid WeCom login state');
alert(t('login.wecomInvalidState'));
return true;
}
@@ -476,13 +477,13 @@ const tryWecomCallbackLogin = async () => {
const data = await res.json();
if (!res.ok) {
const rawError = String(data.error || '');
let friendly = rawError || 'WeCom login failed';
let friendly = rawError || t('login.wecomLoginFailed');
if (rawError.includes('Invalid or expired WeCom state')) {
friendly = '企业微信登录会话已过期,请重新点击企业微信登录';
friendly = t('login.wecomStateExpired');
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
friendly = '当前企业微信账号未绑定本系统用户,请联系管理员在后台完成绑定';
friendly = t('login.wecomBindRequired');
} else if (rawError.includes('Account is disabled')) {
friendly = '账号已被禁用,请联系管理员';
friendly = t('login.wecomAccountDisabled');
}
alert(friendly);
return true;
@@ -495,7 +496,7 @@ const tryWecomCallbackLogin = async () => {
return true;
} catch (e) {
console.error(e);
alert('WeCom login failed');
alert(t('login.wecomLoginFailed'));
return true;
} finally {
isWecomLoggingIn.value = false;
@@ -587,7 +588,7 @@ const toggleFavorite = async (agentId: number) => {
// Quick Questions
const getAgentName = (agentId: number) => {
const agent = agents.value.find(a => a.id === agentId);
return agent ? agent.name : t('workspace.unknownAgent', 'Unknown Agent');
return agent ? agent.name : t('workspace.unknownAgent');
};
const openAddQuestionForm = () => {
@@ -614,7 +615,7 @@ const cancelAddQuestion = () => {
const saveQuickQuestion = async () => {
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
alert(t('workspace.quickQuestions.addTitle') + ' (Please fill all fields)');
alert(t('workspace.quickQuestions.msg.fillAll'));
return;
}
@@ -737,7 +738,7 @@ onMounted(async () => {
<button @click="showUserDropdown = !showUserDropdown" class="flex items-center gap-3 pl-3 pr-2 py-1.5 rounded-full hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors border border-transparent hover:border-slate-200 dark:hover:border-slate-700">
<div class="text-right hidden sm:block">
<div class="text-sm font-bold text-slate-900 dark:text-slate-100 leading-tight">{{ currentUser?.username }}</div>
<div class="text-[10px] font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">{{ currentUser?.role === 'admin' ? 'Admin' : 'User' }}</div>
<div class="text-[10px] font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">{{ currentUser?.role }}</div>
</div>
<div class="w-9 h-9 bg-brand-100 rounded-full flex items-center justify-center text-brand-600 font-bold border-2 border-white shadow-sm">
{{ (currentUser?.username || 'U').charAt(0).toUpperCase() }}
@@ -755,7 +756,7 @@ onMounted(async () => {
<button @click="navigateToProfile" class="w-full text-left px-4 py-2 text-sm text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 hover:text-brand-600 flex items-center gap-2">
<User class="w-4 h-4" />
{{ $t('profile.title') || 'My Profile' }}
{{ $t('profile.title') }}
</button>
<button v-if="currentUser?.role === 'admin'" @click="router.push('/admin')" class="w-full text-left px-4 py-2 text-sm text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 hover:text-brand-600 flex items-center gap-2">
@@ -795,21 +796,21 @@ onMounted(async () => {
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-brand-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-2 w-2 bg-brand-500"></span>
</span>
Enterprise AI Gateway
{{ $t('title') }}
</div>
<h1 class="text-5xl font-bold text-slate-900 leading-tight">
Unleash the Power of <br/>
<span class="text-transparent bg-clip-text bg-gradient-to-r from-brand-600 to-purple-600">Generative AI</span>
{{ $t('landing.hero.prefix') }} <br/>
<span class="text-transparent bg-clip-text bg-gradient-to-r from-brand-600 to-purple-600">{{ $t('landing.hero.highlight') }}</span>
</h1>
<p class="text-lg text-slate-600 max-w-md leading-relaxed">
Access a suite of powerful AI agents tailored for your enterprise needs. Secure, scalable, and intelligent.
{{ $t('landing.hero.subtitle') }}
</p>
<!-- Announcements List -->
<div v-if="announcements.length > 0" class="bg-white/60 dark:bg-slate-900/70 backdrop-blur-sm rounded-2xl border border-slate-100 dark:border-slate-700 p-6 shadow-sm">
<h3 class="text-sm font-bold text-slate-900 mb-4 flex items-center gap-2">
<Megaphone class="w-4 h-4 text-brand-600" />
{{ $t('login.announcements') || 'Announcements' }}
{{ $t('login.announcements') }}
</h3>
<div class="space-y-3">
<div v-for="ann in announcements.slice(0, 3)" :key="ann.id"
@@ -832,7 +833,7 @@ onMounted(async () => {
</div>
<div class="truncate">
<div class="font-semibold text-slate-900 text-sm truncate">{{ agent.name }}</div>
<div class="text-xs text-slate-500 truncate">AI Assistant</div>
<div class="text-xs text-slate-500 truncate">{{ $t('landing.agent.role') }}</div>
</div>
</div>
@@ -864,7 +865,7 @@ onMounted(async () => {
<div class="flex items-center gap-2 mt-2">
<input type="checkbox" id="rememberMe" v-model="rememberMe" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500 w-4 h-4" />
<label for="rememberMe" class="text-sm text-slate-600 cursor-pointer select-none">{{ $t('login.rememberMe') || 'Remember me for 30 days' }}</label>
<label for="rememberMe" class="text-sm text-slate-600 cursor-pointer select-none">{{ $t('login.rememberMe') }}</label>
</div>
<button @click="handleLogin" class="btn-primary w-full py-3 text-base shadow-brand-500/40 hover:shadow-brand-500/50 transform hover:-translate-y-0.5 transition-all mt-4">
@@ -877,7 +878,7 @@ onMounted(async () => {
:disabled="isWecomLoggingIn"
class="btn-secondary w-full py-3 text-base mt-3 disabled:opacity-60 disabled:cursor-not-allowed"
>
{{ isWecomLoggingIn ? ($t('login.wecomConnecting') || 'Connecting to WeCom...') : ($t('login.wecomLogin') || 'Login with WeCom') }}
{{ isWecomLoggingIn ? $t('login.wecomConnecting') : $t('login.wecomLogin') }}
</button>
<div class="flex justify-between items-center pt-4 mt-2 border-t border-slate-100/50">
@@ -1097,7 +1098,7 @@ onMounted(async () => {
<Lock class="w-6 h-6" />
</div>
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">{{ $t('login.forgotPassword') }}</h3>
<p class="text-slate-500 dark:text-slate-400 text-sm mt-2">{{ $t('login.forgotPasswordDesc') || 'Enter your email to reset your password' }}</p>
<p class="text-slate-500 dark:text-slate-400 text-sm mt-2">{{ $t('login.forgotPasswordDesc') }}</p>
</div>
<div class="space-y-4">
@@ -1107,7 +1108,7 @@ onMounted(async () => {
<div class="flex justify-end gap-3 mt-8">
<button @click="showForgotPasswordModal = false" class="btn-secondary flex-1">{{ $t('register.cancel') }}</button>
<button @click="handleForgotPassword" class="btn-primary flex-1">{{ $t('login.findPassword') || 'Find Password' }}</button>
<button @click="handleForgotPassword" class="btn-primary flex-1">{{ $t('login.findPassword') }}</button>
</div>
</div>
</div>