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

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

No files matched your search

+3 -5
View File
@@ -7,11 +7,9 @@ import LevelMessageDialog from './components/LevelMessageDialog.vue';
import { useGlobalMessageDialog } from './composables/useGlobalMessageDialog';
import { useRouter } from 'vue-router';
import { getAuthHeaders, logoutAuth } from './utils/auth';
import { isPublicPath } from '@/shared/constants/routes';
const router = useRouter();
const PUBLIC_PATHS = ['/', '/workspace', '/casdoor-callback', '/reset-password'];
const { locale } = useI18n();
const { themePreference, initTheme, setThemePreference } = useTheme();
const {
@@ -72,8 +70,8 @@ const onLogout = (event: Event) => {
showMessageDialog('info', '您已在其他标签页退出登录');
}
const path = router.currentRoute.value.path;
if (!PUBLIC_PATHS.includes(path)) {
router.push('/workspace');
if (!isPublicPath(path)) {
router.push('/login');
}
};
+4 -100
View File
@@ -1,100 +1,4 @@
import { getAuthHeaders } from '../utils/auth';
import { requestJson } from './client';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
export interface ChatSessionItem {
id: number;
conversation_id: string;
title: string;
created_at: string;
}
export interface LeaveAgentOption {
uid: string;
employeeId: string;
name: string;
jobtitle?: string;
jobtitleName?: string;
departmentid?: string;
subcompanyid1?: string;
departmentName?: string;
subcompanyName?: string;
}
export interface OaEmployeesResponse {
items: LeaveAgentOption[];
total: number;
}
export interface ChatSourceFileResult {
source_download_url?: string;
source_filename?: string;
source_ext?: string;
}
export interface ChatUploadResult {
id: string;
name?: string;
size?: number;
extension?: string;
mime_type?: string;
type?: 'image' | 'document' | 'audio' | 'video' | 'custom';
}
export const listChatSessions = (agentId: number) =>
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
export const deleteAllChatSessions = (agentId: number) =>
requestJson(`/api/chat/sessions?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
export const deleteChatSession = (conversationId: string, agentId: number) =>
requestJson(`/api/chat/sessions/${conversationId}?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
export const listChatMessages = (conversationId: string, agentId: number) =>
requestJson<any[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(payload),
});
export const resolveChatSourceFile = (params: {
agent_id: number;
dataset_id: string;
remote_document_id: string;
}) => {
const qs = new URLSearchParams({
agent_id: String(params.agent_id),
dataset_id: params.dataset_id,
remote_document_id: params.remote_document_id,
});
return requestJson<ChatSourceFileResult>(`/api/chat/source-file?${qs.toString()}`, auth());
};
export const listOaEmployees = (
agentId: number,
query: { keyword?: string; page?: number; page_size?: number },
) => {
const qs = new URLSearchParams({
agent_id: String(agentId),
keyword: query.keyword || '',
page: String(query.page ?? 1),
page_size: String(query.page_size ?? 20),
});
return requestJson<OaEmployeesResponse>(`/api/chat/oa/employees?${qs.toString()}`, auth());
};
export const uploadChatFile = (agentId: number, file: File) => {
const qs = new URLSearchParams({ agent_id: String(agentId) });
const fd = new FormData();
fd.append('file', file);
return requestJson<ChatUploadResult>(`/api/chat/files/upload?${qs.toString()}`, {
method: 'POST',
body: fd,
headers: getAuthHeaders(),
});
};
/**
* @deprecated 请使用 @/features/chat/api/chat.api
*/
export * from '@/features/chat/api/chat.api';
+2 -46
View File
@@ -1,46 +1,2 @@
import { getAuthHeaders } from '../utils/auth';
import { requestJson } from './client';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
export const getUserProfile = () => requestJson<Record<string, any>>('/api/user/profile', auth());
export interface LeaveBalanceResult {
has_balance: boolean;
leave_type_label: string;
year: number;
total_hours: number | null;
used_hours: number | null;
remaining_hours: number | null;
}
export const getLeaveBalance = (leaveType: string) =>
requestJson<LeaveBalanceResult>(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveType)}`, auth());
export interface LeaveWorkflowSubmitResult {
request_id?: string;
submitted_at?: string;
request_name?: string;
}
export const submitLeaveWorkflow = (form: Record<string, any>) =>
requestJson<LeaveWorkflowSubmitResult>('/api/user/leave-workflow/submit', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(form),
});
export const resetPasswordConfirm = (token: string, newPassword: string) =>
requestJson('/api/user/reset-password-confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, new_password: newPassword }),
});
export const getUserAgent = (agentId: number) =>
requestJson<Record<string, any>>(`/api/user/agents/${agentId}`, auth());
export const listUserAgents = () => requestJson<any[]>('/api/agents', auth());
export const listAgentGuides = (agentId: number) => requestJson<any[]>(`/api/agents/${agentId}/guides`, auth());
/** @deprecated 请改用 `@/features/auth/api/user.api` */
export * from '@/features/auth/api/user.api';
+8 -3
View File
@@ -20,7 +20,7 @@ export function setupRouterGuards(router: Router): void {
if (to.matched.some((r) => r.meta.requiresAdmin)) {
if (!auth.isAdmin) {
next('/workspace');
next('/workspace/applications');
return;
}
}
@@ -30,12 +30,17 @@ export function setupRouterGuards(router: Router): void {
next(`/chat/${DEFAULT_CHAT_AGENT_ID}`);
return;
}
next('/workspace');
next('/login');
return;
}
if (to.path === '/login' && auth.isLoggedIn) {
next('/workspace/applications');
return;
}
if (!auth.isLoggedIn && !isPublicPath(to.path)) {
next('/workspace');
next('/login');
return;
}
+108 -143
View File
@@ -1,218 +1,183 @@
/**
* app/router/routes/admin.routes.ts
* 管理后台嵌套路由;全部 admin 模块已独立拆分。
*/
import type { RouteRecordRaw } from 'vue-router';
import type { RouteRecordRaw } from "vue-router";
const AdminLayout = () => import("@/features/admin/views/AdminLayout.vue");
const AgentsPage = () =>
import("@/features/admin/modules/agents/AgentsPage.vue");
const AdminLayout = () => import('@/features/admin/views/AdminLayout.vue');
const UsersPage = () => import("@/features/admin/modules/users/UsersPage.vue");
const AgentsPage = () => import('@/features/admin/modules/agents/AgentsPage.vue');
const DepartmentsPage = () =>
import("@/features/admin/modules/departments/DepartmentsPage.vue");
const UsersPage = () => import('@/features/admin/modules/users/UsersPage.vue');
const ApprovalsPage = () =>
import("@/features/admin/modules/approvals/ApprovalsPage.vue");
const DepartmentsPage = () => import('@/features/admin/modules/departments/DepartmentsPage.vue');
const AnnouncementsPage = () =>
import("@/features/admin/modules/announcements/AnnouncementsPage.vue");
const ApprovalsPage = () => import('@/features/admin/modules/approvals/ApprovalsPage.vue');
const QuestionsPage = () =>
import("@/features/admin/modules/questions/QuestionsPage.vue");
const AnnouncementsPage = () => import('@/features/admin/modules/announcements/AnnouncementsPage.vue');
const RequestsPage = () =>
import("@/features/admin/modules/requests/RequestsPage.vue");
const QuestionsPage = () => import('@/features/admin/modules/questions/QuestionsPage.vue');
const PermissionsPage = () =>
import("@/features/admin/modules/permissions/PermissionsPage.vue");
const PlatformAppsPage = () =>
import("@/features/admin/modules/platform-apps/PlatformAppsPage.vue");
const DashboardPage = () =>
import("@/features/admin/modules/dashboard/DashboardPage.vue");
const RequestsPage = () => import('@/features/admin/modules/requests/RequestsPage.vue');
const SchedulesPage = () =>
import("@/features/admin/modules/schedules/SchedulesPage.vue");
const PermissionsPage = () => import('@/features/admin/modules/permissions/PermissionsPage.vue');
const PlatformAppsPage = () => import('@/features/admin/modules/platform-apps/PlatformAppsPage.vue');
const DashboardPage = () => import('@/features/admin/modules/dashboard/DashboardPage.vue');
const SchedulesPage = () => import('@/features/admin/modules/schedules/SchedulesPage.vue');
const KnowledgeBasePage = () => import('@/features/admin/modules/knowledge-base/KnowledgeBasePage.vue');
const WecomPage = () => import('@/features/admin/modules/wecom/WecomPage.vue');
const ReportsPage = () => import('@/features/admin/modules/reports/ReportsPage.vue');
const KnowledgeBasePage = () =>
import("@/features/admin/modules/knowledge-base/KnowledgeBasePage.vue");
const WecomPage = () => import("@/features/admin/modules/wecom/WecomPage.vue");
const ReportsPage = () =>
import("@/features/admin/modules/reports/ReportsPage.vue");
export const adminRoutes: RouteRecordRaw[] = [
{
path: '/admin',
path: "/admin",
component: AdminLayout,
meta: { requiresAdmin: true },
children: [
{ path: '', redirect: '/admin/dashboard' },
{ path: "", redirect: "/admin/dashboard" },
{
path: 'dashboard',
name: 'AdminDashboard',
path: "dashboard",
name: "AdminDashboard",
component: DashboardPage,
meta: { requiresAdmin: true, adminModule: 'dashboard', title: '概览' },
meta: { requiresAdmin: true, adminModule: "dashboard", title: "概览" },
},
{
path: 'schedules',
name: 'AdminSchedules',
path: "schedules",
name: "AdminSchedules",
component: SchedulesPage,
meta: { requiresAdmin: true, adminModule: 'schedules', title: '定时任务' },
meta: {
requiresAdmin: true,
adminModule: "schedules",
title: "定时任务",
},
},
{
path: 'knowledge-base',
name: 'AdminKnowledgeBase',
path: "knowledge-base",
name: "AdminKnowledgeBase",
component: KnowledgeBasePage,
meta: { requiresAdmin: true, adminModule: 'knowledge_base', title: '知识库' },
meta: {
requiresAdmin: true,
adminModule: "knowledge_base",
title: "知识库",
},
},
{
path: 'wecom',
name: 'AdminWecom',
path: "wecom",
name: "AdminWecom",
component: WecomPage,
meta: { requiresAdmin: true, adminModule: 'wecom', title: '企业微信' },
meta: { requiresAdmin: true, adminModule: "wecom", title: "企业微信" },
},
{
path: 'approvals',
name: 'AdminApprovals',
path: "approvals",
name: "AdminApprovals",
component: ApprovalsPage,
meta: { requiresAdmin: true, adminModule: 'approvals', title: '用户审批' },
meta: {
requiresAdmin: true,
adminModule: "approvals",
title: "用户审批",
},
},
{
path: 'agents',
name: 'AdminAgents',
path: "agents",
name: "AdminAgents",
component: AgentsPage,
meta: { requiresAdmin: true, adminModule: 'agents', title: '应用管理' },
meta: { requiresAdmin: true, adminModule: "agents", title: "应用管理" },
},
{
path: 'users',
name: 'AdminUsers',
path: "users",
name: "AdminUsers",
component: UsersPage,
meta: { requiresAdmin: true, adminModule: 'users', title: '用户管理' },
meta: { requiresAdmin: true, adminModule: "users", title: "用户管理" },
},
{
path: 'departments',
name: 'AdminDepartments',
path: "departments",
name: "AdminDepartments",
component: DepartmentsPage,
meta: { requiresAdmin: true, adminModule: 'departments', title: '部门管理' },
meta: {
requiresAdmin: true,
adminModule: "departments",
title: "部门管理",
},
},
{
path: 'announcements',
name: 'AdminAnnouncements',
path: "announcements",
name: "AdminAnnouncements",
component: AnnouncementsPage,
meta: { requiresAdmin: true, adminModule: 'announcements', title: '公告管理' },
meta: {
requiresAdmin: true,
adminModule: "announcements",
title: "公告管理",
},
},
{
path: 'questions',
name: 'AdminQuestions',
path: "questions",
name: "AdminQuestions",
component: QuestionsPage,
meta: { requiresAdmin: true, adminModule: 'questions', title: '常用问题' },
meta: {
requiresAdmin: true,
adminModule: "questions",
title: "常用问题",
},
},
{
path: 'requests',
name: 'AdminRequests',
path: "requests",
name: "AdminRequests",
component: RequestsPage,
meta: { requiresAdmin: true, adminModule: 'requests', title: '权限申请' },
meta: {
requiresAdmin: true,
adminModule: "requests",
title: "权限申请",
},
},
{
path: 'permissions',
name: 'AdminPermissions',
path: "permissions",
name: "AdminPermissions",
component: PermissionsPage,
meta: { requiresAdmin: true, adminModule: 'permissions', title: '权限管理' },
meta: {
requiresAdmin: true,
adminModule: "permissions",
title: "权限管理",
},
},
{
path: 'platform-apps',
name: 'AdminPlatformApps',
path: "platform-apps",
name: "AdminPlatformApps",
component: PlatformAppsPage,
meta: { requiresAdmin: true, adminModule: 'platform_apps', title: '平台应用说明' },
meta: {
requiresAdmin: true,
adminModule: "platform_apps",
title: "平台应用说明",
},
},
{
path: 'reports/:table?',
name: 'AdminReports',
path: "reports/:table?",
name: "AdminReports",
component: ReportsPage,
meta: { requiresAdmin: true, adminModule: 'reports', title: '报表' },
meta: { requiresAdmin: true, adminModule: "reports", title: "报表" },
},
],
},
];
@@ -1,14 +1,13 @@
/**
* app/router/routes/auth.routes.ts
* 认证 / 工作台相关路由。
* 认证路由:/login 登录页、/casdoor-callback OAuth 回调、/reset-password 重置密码。
*/
import type { RouteRecordRaw } from 'vue-router';
import WorkspaceView from '@/views/WorkspaceView.vue';
import ResetPasswordView from '@/views/ResetPasswordView.vue';
import LoginView from '@/features/auth/views/LoginView.vue';
import ResetPasswordView from '@/features/auth/views/ResetPasswordView.vue';
export const authRoutes: RouteRecordRaw[] = [
{ path: '/', name: 'Home', component: WorkspaceView },
{ path: '/workspace', name: 'Workspace', component: WorkspaceView },
{ path: '/casdoor-callback', name: 'CasdoorCallback', component: WorkspaceView },
{ path: '/login', name: 'Login', component: LoginView },
{ path: '/casdoor-callback', name: 'CasdoorCallback', component: LoginView },
{ path: '/reset-password', name: 'ResetPassword', component: ResetPasswordView },
];
@@ -3,8 +3,12 @@
* 对话相关路由。
*/
import type { RouteRecordRaw } from 'vue-router';
import ChatView from '@/views/ChatView.vue';
export const chatRoutes: RouteRecordRaw[] = [
{ path: '/chat/:agentId', name: 'Chat', component: ChatView, props: true },
{
path: '/chat/:agentId',
name: 'Chat',
component: () => import('@/features/chat/views/ChatView.vue'),
props: true,
},
];
+2
View File
@@ -7,9 +7,11 @@ import { adminRoutes } from './admin.routes';
import { authRoutes } from './auth.routes';
import { chatRoutes } from './chat.routes';
import { kbRoutes } from './kb.routes';
import { workspaceRoutes } from './workspace.routes';
export const appRoutes: RouteRecordRaw[] = [
...authRoutes,
...workspaceRoutes,
...chatRoutes,
...adminRoutes,
...kbRoutes,
@@ -0,0 +1,64 @@
/**
* app/router/routes/workspace.routes.ts
* 工作台路由表:/workspace 布局壳 + 各业务子页面懒加载。
*/
import type { RouteRecordRaw } from 'vue-router';
export const workspaceRoutes: RouteRecordRaw[] = [
{
path: '/workspace',
component: () => import('@/features/workspace/views/WorkspaceLayout.vue'),
meta: { title: 'AI工作台' },
children: [
{ path: '', redirect: '/workspace/applications' },
{
path: 'profile',
name: 'workspace-profile',
component: () => import('@/features/workspace/pages/ProfilePage.vue'),
meta: { title: '个人中心' },
},
{
path: 'applications',
name: 'workspace-applications',
component: () => import('@/features/workspace/pages/HomePage.vue'),
meta: { workspaceFocus: 'applications' },
},
{
path: 'updates',
name: 'workspace-updates',
component: () => import('@/features/workspace/pages/HomePage.vue'),
meta: { workspaceFocus: 'updates' },
},
{
path: 'knowledge-base',
name: 'workspace-knowledge-base',
component: () => import('@/features/workspace/pages/KnowledgeBasePage.vue'),
meta: { title: '知识库管理' },
},
{
path: 'schedule-runs',
name: 'workspace-schedule-runs',
component: () => import('@/features/workspace/pages/ScheduleRunsPage.vue'),
meta: { title: '排程记录' },
},
{
path: 'shipping-notice',
name: 'workspace-shipping-notice',
component: () => import('@/features/workspace/pages/ShippingNoticePage.vue'),
meta: { title: '货代发货' },
},
{
path: 'feedback',
name: 'workspace-feedback',
component: () => import('@/features/workspace/pages/FeedbackPage.vue'),
meta: { title: '意见反馈' },
},
{
path: 'history',
name: 'workspace-history',
component: () => import('@/features/chat/pages/HistoryPage.vue'),
meta: { title: '聊天历史' },
},
],
},
];
+2 -412
View File
@@ -1,414 +1,4 @@
/**
* frontend/src/composables/useChat.ts
* 文件用途:前端 SSE 聊天 Hook
* 引用文件:vue
* 逻辑关系:封装 Fetch API 处理流式响应,供 ChatView 组件使用
* @deprecated 请使用 @/features/chat/composables/useChat
*/
import { ref } from 'vue';
import { getAuthHeaders } from '../utils/auth';
interface RetrieverResource {
// 知识库/检索来源的基础字段,具体键可能因后端返回而扩展
dataset_name?: string;
document_name?: string;
segment_id?: string;
content?: string;
score?: number;
[key: string]: any;
}
interface ChatMessage {
// 对话消息结构:用户/助手文本 + 可选的来源与归因信息
role: 'user' | 'assistant';
content: string;
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
payload?: any;
local_id?: string;
local_only?: boolean;
rated?: boolean;
shipping_actions?: Array<{
id: string;
label: string;
message: string;
variant?: 'primary' | 'secondary' | 'danger';
}>;
shipping_actions_used?: boolean;
}
type RunStatus = 'running' | 'done' | 'error';
interface ChatRun {
runId: number;
agentId: number;
viewId: number;
query: string;
messages: ChatMessage[];
conversationId: string | null;
status: RunStatus;
createdAt: string;
}
// 统一资源格式为数组,兼容 list 或 { data: list } 两种结构
const normalizeResources = (resources: any): RetrieverResource[] => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
if (Array.isArray(resources.data)) return resources.data;
return [];
};
// 将检索来源资源合并到消息中,并按文档名+片段ID+内容做去重和更新
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 existingIndex = msg.retriever_resources.findIndex(
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
);
if (existingIndex < 0) {
msg.retriever_resources.push(item);
} else {
// 存在则合并,确保后续带有 enrich 链接的字段能覆盖进去
msg.retriever_resources[existingIndex] = {
...msg.retriever_resources[existingIndex],
...item
};
}
}
};
// 归一化并合并归因内容(支持 string/array/object),按文本去重
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));
}
};
// 从事件顶层与 metadata 中提取来源/归因信息并写回当前消息
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 渲染
* 结构: [{ role: 'user'|'assistant', content: string }]
*/
const messages = ref<ChatMessage[]>([]);
/**
* isThinking: 标记 AI 是否正在生成回答,用于控制 Loading 状态和输入框禁用
*/
const isThinking = ref(false);
const viewId = ref(0);
const runs = ref<ChatRun[]>([]);
const activeRunId = ref<number | null>(null);
let runSeq = 0;
/**
* conversationId: 当前会话 ID
* 用于在多轮对话中关联上下文,并在反馈时找到对应 ChatLog
*/
const conversationId = ref<string | null>(null);
const activateRun = (runId: number) => {
const run = runs.value.find((r) => r.runId === runId);
if (!run) return;
messages.value = run.messages;
conversationId.value = run.conversationId;
isThinking.value = run.status === 'running';
activeRunId.value = runId;
};
const createNewChatView = () => {
viewId.value += 1;
messages.value = [];
conversationId.value = null;
isThinking.value = false;
activeRunId.value = null;
};
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
viewId.value += 1;
activeRunId.value = null;
isThinking.value = false;
messages.value = nextMessages;
conversationId.value = id;
};
/**
* sendMessage
* 用途:发送消息并处理 SSE 流式响应
* 核心逻辑:
* 1. 乐观更新 UI (立即显示用户消息)
* 2. Create assistant message lazily only after receiving real answer chunks.
* 3. 发起 Fetch POST 请求
* 4. 获取 Reader 流式读取
* 5. 逐块解码并追加到当前 AI 消息中
* 参数:
* query: 用户输入文本
* agentId: 目标 Agent ID
*/
const sendMessage = async (
query: string,
agentId: number,
kbType: string = '企业知识库',
files?: Array<
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
>,
) => {
const runViewId = viewId.value;
const runMessages = messages.value;
const run: ChatRun = {
runId: ++runSeq,
agentId,
viewId: runViewId,
query,
messages: runMessages,
conversationId: conversationId.value,
status: 'running',
createdAt: new Date().toISOString(),
};
runs.value.unshift(run);
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
activeRunId.value = run.runId;
console.info('[chat][send] start', {
agentId,
kbType,
queryLength: query.length,
conversationId: conversationId.value,
});
// 1. 乐观 UI 更新:立即将用户消息推入列表
runMessages.push({ role: 'user', content: query });
// Lazily create assistant message only when answer/error arrives.
let botMsgIndex: number | null = null;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = runMessages.push({
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: []
}) - 1;
}
return runMessages[botMsgIndex] || null;
};
isThinking.value = true;
try {
// 指向本地 Flask 端口 (需通过 Vite Proxy 转发到 5000)
const response = await fetch('/api/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
query,
agent_id: agentId,
conversation_id: conversationId.value,
kb_type: kbType,
files: files && files.length > 0 ? files : undefined,
})
});
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}`);
}
// 获取 ReadableStream 读取器
const reader = response.body?.getReader();
const decoder = new TextDecoder();
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;
// 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);
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?.conversation_id) {
const cid = String(data.conversation_id);
if (!run.conversationId) run.conversationId = cid;
if (messages.value === runMessages) conversationId.value = cid;
}
const eventName = String(data.event || '');
if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
console.debug('[chat][sse] append answer chunk', {
event: data.event,
appended: data.answer.length,
total: botMsg.content.length,
});
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) {
applyEventMetadata(currentBotMsg, data);
}
}
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
run.status = 'done';
if (messages.value === runMessages) isThinking.value = false;
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) {
currentBotMsg.chat_log_id = Number(data.chat_log_id);
}
}
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
const normalizedAnswer = normalizeStreamText(data.answer);
if (data.replace_answer) {
botMsg.content = normalizedAnswer;
} else {
botMsg.content += normalizedAnswer;
}
console.debug('[chat][sse] apply final answer', {
event: data.event,
replace: Boolean(data.replace_answer),
appended: data.answer.length,
total: botMsg.content.length,
});
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) {
applyEventMetadata(currentBotMsg, data);
}
}
} else if (eventName === 'error') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += `\n[Error: ${data.message}]`;
console.error('[chat][sse] backend error event', data);
run.status = 'error';
if (messages.value === runMessages) isThinking.value = false;
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
}
} catch (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('[chat][send] failed', e);
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
}
} finally {
if (messages.value === runMessages) {
isThinking.value = false;
console.info('[chat][send] end', {
messages: messages.value.length,
conversationId: conversationId.value,
});
} else {
console.info('[chat][send] end (detached)', {
activeConversationId: conversationId.value,
runViewId,
});
}
}
};
const normalizeStreamText = (text: string) => {
if (!text) return '';
return text.replace(/\\n/g, '\n');
};
return { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, loadConversationState, sendMessage };
}
export { useChat } from '@/features/chat/composables/useChat';
@@ -0,0 +1,50 @@
/**
* features/auth/api/user.api.ts
* 用户域 HTTP API:资料、请假、密码重置、Agent 列表等。
*/
import { getAuthHeaders } from '@/utils/auth';
import { requestJson } from '@/shared/api/client';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
export const getUserProfile = () => requestJson<Record<string, any>>('/api/user/profile', auth());
export interface LeaveBalanceResult {
has_balance: boolean;
leave_type_label: string;
year: number;
total_hours: number | null;
used_hours: number | null;
remaining_hours: number | null;
}
export const getLeaveBalance = (leaveType: string) =>
requestJson<LeaveBalanceResult>(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveType)}`, auth());
export interface LeaveWorkflowSubmitResult {
request_id?: string;
submitted_at?: string;
request_name?: string;
}
export const submitLeaveWorkflow = (form: Record<string, any>) =>
requestJson<LeaveWorkflowSubmitResult>('/api/user/leave-workflow/submit', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(form),
});
export const resetPasswordConfirm = (token: string, newPassword: string) =>
requestJson('/api/user/reset-password-confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, new_password: newPassword }),
});
export const getUserAgent = (agentId: number) =>
requestJson<Record<string, any>>(`/api/user/agents/${agentId}`, auth());
export const listUserAgents = () => requestJson<any[]>('/api/agents', auth());
export const listAgentGuides = (agentId: number) => requestJson<any[]>(`/api/agents/${agentId}/guides`, auth());
@@ -0,0 +1,195 @@
<script setup lang="ts">
/**
* features/auth/components/LoginModals.vue
* 登录相关弹窗:找回密码、公告详情、企微登录/绑定提示、注册。
*/
import { inject } from 'vue';
import { useI18n } from 'vue-i18n';
import { Lock, User, X } from 'lucide-vue-next';
import { formatWecomFieldLabel } from '@/utils/wecom';
import { LOGIN_KEY } from '../composables/login.context';
const { t } = useI18n();
const lk = inject(LOGIN_KEY)! as any;
</script>
<template>
<div>
<div
v-if="lk.showForgotPasswordModal"
class="dialog-overlay z-50 items-center animate-fade-in"
@click.self="lk.showForgotPasswordModal = false"
>
<div class="dialog-panel max-w-md animate-slide-up">
<div class="dialog-header dialog-header--compact relative border-0 pb-0">
<div class="flex-1" />
<button type="button" class="btn-icon-ds" :aria-label="$t('admin.close')" @click="lk.showForgotPasswordModal = false">
<X class="w-5 h-5" />
</button>
</div>
<div class="dialog-body pt-0 text-center">
<div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-brand-100 text-brand-600">
<Lock class="w-6 h-6" />
</div>
<h3 class="text-xl font-bold text-primary">{{ $t('login.forgotPassword') }}</h3>
<p class="mt-2 text-sm text-muted">{{ $t('login.forgotPasswordDesc') }}</p>
<div class="mt-6 space-y-2 text-left">
<label class="label-field ml-1">{{ $t('register.email') }}</label>
<input v-model="lk.forgotPasswordForm.email" :placeholder="$t('register.email')" class="input-field" @keyup.enter="lk.handleForgotPassword" />
</div>
</div>
<div class="dialog-footer">
<button type="button" @click="lk.showForgotPasswordModal = false" class="btn-secondary flex-1">{{ $t('register.cancel') }}</button>
<button type="button" @click="lk.handleForgotPassword" class="btn-primary flex-1">{{ $t('login.findPassword') }}</button>
</div>
</div>
</div>
<div
v-if="lk.showAnnouncementModal && lk.selectedAnnouncement"
class="dialog-overlay z-50 items-center animate-fade-in"
@click.self="lk.showAnnouncementModal = false"
>
<div class="dialog-panel max-w-2xl max-h-[85vh] animate-slide-up">
<div class="dialog-header">
<div class="min-w-0">
<span class="inline-flex rounded-full bg-brand-50 px-2 py-1 text-xs font-bold text-brand-600">{{ new Date(lk.selectedAnnouncement.created_at).toLocaleDateString() }}</span>
<h3 class="mt-2 text-2xl font-bold text-primary">{{ lk.selectedAnnouncement.title }}</h3>
</div>
<button type="button" class="btn-icon-ds shrink-0" :aria-label="$t('admin.close')" @click="lk.showAnnouncementModal = false">
<X class="w-5 h-5" />
</button>
</div>
<div class="dialog-body">
<p class="whitespace-pre-wrap leading-relaxed text-secondary">{{ lk.selectedAnnouncement.content }}</p>
</div>
<div class="dialog-footer">
<button type="button" @click="lk.showAnnouncementModal = false" class="btn-primary">
{{ $t('admin.close') }}
</button>
</div>
</div>
</div>
<div
v-if="lk.wecomLoginDialog"
class="dialog-overlay z-50 items-center animate-fade-in"
@click.self="lk.wecomLoginDialog = null"
>
<div class="dialog-panel max-w-lg animate-slide-up">
<div class="dialog-header dialog-header--compact">
<div class="flex items-start gap-3 min-w-0">
<div class="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-amber-100 text-amber-700">
<Lock class="w-6 h-6" />
</div>
<div class="min-w-0">
<h3 class="text-xl font-bold text-primary">{{ lk.wecomLoginDialog.title }}</h3>
<p class="mt-2 text-sm leading-6 text-secondary">{{ lk.wecomLoginDialog.summary }}</p>
</div>
</div>
<button type="button" class="btn-icon-ds shrink-0" :aria-label="$t('admin.close')" @click="lk.wecomLoginDialog = null">
<X class="w-5 h-5" />
</button>
</div>
<div
v-if="lk.wecomLoginDialog?.details?.length || lk.wecomLoginDialog?.technical"
class="dialog-body border-t-0 pt-0 space-y-4"
>
<div v-if="lk.wecomLoginDialog?.details?.length" class="rounded-2xl border border-default bg-surface-soft/80 px-4 py-4 space-y-3">
<p v-for="(detail, index) in lk.wecomLoginDialog.details" :key="`${detail}-${index}`" class="text-sm leading-6 text-secondary">
{{ detail }}
</p>
</div>
<p v-if="lk.wecomLoginDialog.technical" class="break-all text-xs text-muted">
{{ $t('login.wecomTechnicalInfo', { detail: lk.wecomLoginDialog.technical }) }}
</p>
</div>
<div class="dialog-footer">
<button type="button" @click="lk.wecomLoginDialog = null" class="btn-secondary">{{ $t('admin.close') }}</button>
<button type="button" @click="lk.wecomLoginDialog = null; lk.handleWecomLogin()" class="btn-primary" :disabled="lk.isWecomLoggingIn">
{{ $t('login.wecomRetry') }}
</button>
</div>
</div>
</div>
<div
v-if="lk.wecomBindPrompt"
class="dialog-overlay z-50 items-center animate-fade-in"
@click.self="lk.wecomBindPrompt = null"
>
<div class="dialog-panel max-w-lg animate-slide-up">
<div class="dialog-header dialog-header--compact">
<div class="flex items-start gap-3 min-w-0">
<div class="mb-0 flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-blue-100 text-blue-700">
<User class="w-6 h-6" />
</div>
<div class="min-w-0">
<h3 class="text-xl font-bold text-primary">{{ $t('login.wecomBindPromptTitle') }}</h3>
<p class="mt-2 text-sm leading-6 text-secondary">
{{ $t('login.wecomBindPromptDesc', { name: lk.wecomBindPrompt.wecom_name || '-' }) }}
</p>
</div>
</div>
<button type="button" class="btn-icon-ds shrink-0" :aria-label="$t('admin.close')" @click="lk.wecomBindPrompt = null">
<X class="w-5 h-5" />
</button>
</div>
<div class="dialog-body space-y-4 border-t-0 pt-0">
<div>
<label class="label-field mb-1.5 block">{{ $t('login.wecomBindField') }}</label>
<select v-model="lk.wecomBindPrompt.field" class="input-field">
<option v-for="field in lk.wecomBindPrompt.allowed_fields" :key="field" :value="field">
{{ formatWecomFieldLabel(field, t) }}
</option>
</select>
</div>
<div>
<label class="label-field mb-1.5 block">{{ $t('login.wecomBindValue') }}</label>
<input
v-model="lk.wecomBindPrompt.value"
class="input-field"
:placeholder="$t('login.wecomBindValuePlaceholder', { field: formatWecomFieldLabel(lk.wecomBindPrompt.field, t) })"
@keyup.enter="lk.submitWecomCompleteBind"
/>
</div>
<p class="text-xs leading-5 text-muted">{{ $t('login.wecomBindPromptHint') }}</p>
<p v-if="lk.wecomBindPrompt.error" class="text-sm leading-6 text-red-600">{{ lk.wecomBindPrompt.error }}</p>
</div>
<div class="dialog-footer">
<button type="button" @click="lk.wecomBindPrompt = null" class="btn-secondary">{{ $t('admin.close') }}</button>
<button type="button" @click="lk.submitWecomCompleteBind" class="btn-primary" :disabled="lk.wecomBindPrompt.submitting">
{{ lk.wecomBindPrompt.submitting ? $t('login.wecomConnecting') : $t('login.wecomBindSubmit') }}
</button>
</div>
</div>
</div>
<div
v-if="lk.showRegisterModal"
class="dialog-overlay z-50 items-center animate-fade-in"
@click.self="lk.showRegisterModal = false"
>
<div class="dialog-panel max-w-md animate-slide-up">
<div class="dialog-header">
<h3 class="section-title">{{ $t('register.title') }}</h3>
<button type="button" class="btn-icon-ds" :aria-label="$t('admin.close')" @click="lk.showRegisterModal = false">
<X class="w-5 h-5" />
</button>
</div>
<div class="dialog-body space-y-4">
<input v-model="lk.registerForm.real_name" :placeholder="$t('register.fields.realName')" class="input-field" />
<input v-model="lk.registerForm.employee_id" :placeholder="$t('register.fields.employeeId')" class="input-field" />
<input v-model="lk.registerForm.phone_number" :placeholder="$t('register.fields.phone')" class="input-field" />
<input v-model="lk.registerForm.username" :placeholder="$t('register.username')" class="input-field" />
<input v-model="lk.registerForm.email" :placeholder="$t('register.email')" class="input-field" />
<input v-model="lk.registerForm.password" type="password" :placeholder="$t('register.password')" class="input-field" />
</div>
<div class="dialog-footer">
<button type="button" @click="lk.showRegisterModal = false" class="btn-secondary">{{ $t('register.cancel') }}</button>
<button type="button" @click="lk.handleRegister" class="btn-primary">{{ $t('register.submit') }}</button>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,109 @@
<script setup lang="ts">
/**
* features/auth/components/LoginPage.vue
* 登录页主内容:营销文案、公告列表与用户名/密码/企微登录表单。
*/
import { inject } from 'vue';
import { Bot, Megaphone } from 'lucide-vue-next';
import { LOGIN_KEY } from '../composables/login.context';
const lk = inject(LOGIN_KEY)! as any;
</script>
<template>
<div>
<div v-if="lk.isLoading" class="animate-pulse space-y-8">
<div class="h-48 bg-gray-200 rounded-2xl"></div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
<div class="h-40 bg-gray-200 rounded-2xl"></div>
<div class="h-40 bg-gray-200 rounded-2xl"></div>
<div class="h-40 bg-gray-200 rounded-2xl"></div>
</div>
</div>
<div
v-else
class="relative min-h-[calc(100vh-4rem)] overflow-hidden rounded-[2rem] flex items-center justify-center"
:style="lk.loginBackgroundStyle"
>
<div class="absolute inset-0 bg-white/55 backdrop-blur-[1px]"></div>
<div class="relative z-10 w-full max-w-6xl grid grid-cols-1 lg:grid-cols-2 gap-12 items-center p-4">
<div class="hidden lg:block space-y-8 animate-slide-up">
<h1 class="text-5xl font-bold text-black leading-tight drop-shadow-sm">
{{ $t('landing.hero.prefix') }} <br/>
<span class="text-transparent bg-clip-text bg-gradient-to-r from-[#005a9c] to-[#7a1fd0] drop-shadow-sm">{{ $t('landing.hero.highlight') }}</span>
</h1>
<p class="text-lg text-primary max-w-md leading-relaxed font-semibold drop-shadow-sm">
{{ $t('landing.hero.subtitle') }}
</p>
<div v-if="lk.announcements.length > 0" class="bg-white/70 backdrop-blur-sm rounded-2xl border border-default p-6 shadow-sm">
<h3 class="text-sm font-bold text-slate-950 mb-4 flex items-center gap-2">
<Megaphone class="w-4 h-4 text-brand-600" />
{{ $t('login.announcements') }}
</h3>
<div class="space-y-3">
<div
v-for="ann in lk.announcements.slice(0, 3)"
:key="ann.id"
class="group cursor-pointer hover:bg-white/50 p-2 rounded-lg transition-colors"
@click="lk.openAnnouncement(ann)"
>
<div class="flex justify-between items-start gap-2">
<h4 class="text-sm font-semibold text-primary group-hover:text-brand-800 line-clamp-1">{{ ann.title }}</h4>
<span class="text-[10px] text-muted whitespace-nowrap">{{ new Date(ann.created_at).toLocaleDateString() }}</span>
</div>
<p class="text-xs text-secondary line-clamp-2 mt-1">{{ ann.content }}</p>
</div>
</div>
</div>
</div>
<div class="w-full max-w-md mx-auto">
<div class="bg-white/90 backdrop-blur-xl rounded-3xl border border-white/20 shadow-2xl shadow-brand-900/10 p-8 md:p-10 animate-fade-in relative overflow-hidden">
<div class="absolute top-0 left-0 w-full h-1.5 bg-gradient-to-r from-brand-500 to-purple-600"></div>
<div class="text-center mb-8">
<div class="w-12 h-12 bg-brand-600 rounded-xl mx-auto flex items-center justify-center text-white shadow-lg shadow-brand-600/30 mb-4 lg:hidden">
<Bot class="w-7 h-7" />
</div>
<h2 class="text-2xl font-bold text-primary">{{ $t('login.submit') }}</h2>
<p class="text-secondary text-sm mt-2">{{ $t('login.subtitle') }}</p>
</div>
<div class="space-y-5">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-primary uppercase ml-1">{{ $t('login.username') }}</label>
<input v-model="lk.loginUsername" type="text" class="input-field" :placeholder="$t('login.placeholder.username')" @keyup.enter="lk.handleLogin" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-primary uppercase ml-1">{{ $t('login.password') }}</label>
<input v-model="lk.loginPassword" type="password" class="input-field" :placeholder="$t('login.placeholder.password')" @keyup.enter="lk.handleLogin" />
</div>
<button type="button" @click="lk.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">
{{ $t('login.submit') }}
</button>
<button
type="button"
v-if="lk.config.auth?.wecom?.enabled && (!lk.config.auth?.wecom?.loginViaCasdoor || lk.config.auth?.casdoor?.enabled)"
@click="lk.handleWecomLogin"
:disabled="lk.isWecomLoggingIn"
class="btn-secondary w-full py-3 text-base mt-3 disabled:opacity-60 disabled:cursor-not-allowed"
>
{{ lk.isWecomLoggingIn ? $t('login.wecomConnecting') : $t('login.wecomLogin') }}
</button>
<div class="flex justify-between items-center pt-4 mt-2 border-t border-subtle/50">
<button type="button" @click="lk.showForgotPasswordModal = true" class="text-sm text-secondary hover:text-brand-700 transition-colors">
{{ $t('login.forgotPassword') }}
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,9 @@
/**
* features/auth/composables/login.context.ts
* 登录页 provide/inject 上下文类型与注入 key。
*/
import type { InjectionKey } from 'vue';
import type { useLogin } from './useLogin';
export type LoginContext = ReturnType<typeof useLogin>;
export const LOGIN_KEY: InjectionKey<LoginContext> = Symbol('login');
@@ -0,0 +1,19 @@
/**
* features/auth/composables/login.deps.ts
* 登录页 composables 共享依赖(i18n、路由、主题、消息等)。
*/
import type { ComputedRef, WritableComputedRef } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import type { useMessage } from '@/composables/useMessage';
import type { ThemePreference } from '@/composables/useTheme';
export interface LoginDeps {
t: ComposerTranslation;
locale: WritableComputedRef<string>;
msg: ReturnType<typeof useMessage>;
router: Router;
route: RouteLocationNormalizedLoaded;
setThemePreference: (pref: ThemePreference) => void;
appliedTheme: ComputedRef<ThemePreference>;
}
@@ -0,0 +1,77 @@
/**
* features/auth/composables/useLogin.ts
* 登录页编排层:组合认证、公告展示与 OAuth 回调,provide 给 LoginView 子组件。
*/
import { onMounted, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { config } from '@/config';
import { useTheme } from '@/composables/useTheme';
import { useMessage } from '@/composables/useMessage';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import loginBg from '@/assets/login-bg.png';
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
import { useWorkspaceLocale } from '@/features/workspace/composables/useWorkspaceLocale';
import { useLoginAuth } from './useLoginAuth';
import { useLoginLanding } from './useLoginLanding';
export function useLogin() {
const { t, locale } = useI18n();
const msg = useMessage();
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const { setThemePreference, appliedTheme } = useTheme();
const deps = { t, locale, msg, router, route, setThemePreference, appliedTheme };
const landing = useLoginLanding();
const completePasswordLogin = async () => {
authStore.syncFromStorage();
await router.replace(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
};
const completeOAuthLogin = async () => {
authStore.syncFromStorage();
await router.replace('/workspace/applications');
};
const loginAuth = useLoginAuth(deps, { completePasswordLogin, completeOAuthLogin });
const localeApi = useWorkspaceLocale(deps);
const loginBackgroundStyle = {
backgroundImage: `url(${loginBg})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
};
onMounted(async () => {
localeApi.loadLanguagePreference();
void landing.fetchAnnouncements();
const handledCasdoor = await loginAuth.tryCasdoorCallbackLogin();
if (handledCasdoor) return;
const handledWecom = await loginAuth.tryWecomCallbackLogin();
if (handledWecom) return;
authStore.syncFromStorage();
if (authStore.isLoggedIn) {
await router.replace('/workspace/applications');
return;
}
await landing.fetchPublicAgents();
landing.isLoading.value = false;
});
return reactive({
config,
msg,
loginBackgroundStyle,
...localeApi,
...landing,
...loginAuth,
});
}
@@ -0,0 +1,380 @@
/**
* features/auth/composables/useLoginAuth.ts
* 登录表单、企微/Casdoor OAuth 回调、注册与找回密码逻辑。
*/
import { ref } from 'vue';
import { config } from '@/config';
import { resolveCasdoorErrorMessage } from '@/utils/casdoor';
import {
buildWecomLoginDialogContent,
normalizeWecomMatchRules,
type WecomMatchField,
} from '@/utils/wecom';
import { saveAuthUser } from '@/utils/auth';
import { BusinessError, requestJson } from '@/api/client';
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
import type { WecomBindPromptState, WecomLoginDialogContent } from '@/features/workspace/types/workspace.types';
import type { LoginDeps } from './login.deps';
interface LoginAuthOptions {
completePasswordLogin: () => Promise<void>;
completeOAuthLogin: () => Promise<void>;
}
const LOGIN_CALLBACK_PATHS = ['/login', '/workspace'] as const;
function isLoginCallbackPath(path: string, extraPaths: string[] = []): boolean {
return LOGIN_CALLBACK_PATHS.includes(path as (typeof LOGIN_CALLBACK_PATHS)[number])
|| extraPaths.includes(path);
}
export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
const { t, msg } = deps;
const { completePasswordLogin, completeOAuthLogin } = options;
const loginUsername = ref('');
const loginPassword = ref('');
const rememberMe = ref(false);
const showRegisterModal = ref(false);
const showForgotPasswordModal = ref(false);
const registerForm = ref({
username: '',
password: '',
email: '',
real_name: '',
employee_id: '',
phone_number: '',
});
const forgotPasswordForm = ref({ email: '' });
const isWecomLoggingIn = ref(false);
const wecomLoginDialog = ref<WecomLoginDialogContent | null>(null);
const wecomBindPrompt = ref<WecomBindPromptState | null>(null);
const clearWecomCallbackQuery = () => {
const nextUrl = `${window.location.pathname}${window.location.hash || ''}`;
window.history.replaceState({}, '', nextUrl);
};
const persistLoginUser = (user: Record<string, unknown>) => {
saveAuthUser({ ...(user || {}) }, rememberMe.value);
};
const handleForgotPassword = async () => {
if (!forgotPasswordForm.value.email) {
msg.warning(t('register.emailRequired'));
return;
}
try {
await requestJson('/api/user/reset-password-by-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(forgotPasswordForm.value),
});
msg.success(t('login.passwordResetEmailSent'));
showForgotPasswordModal.value = false;
forgotPasswordForm.value = { email: '' };
} catch (e) {
console.error('Password reset error', e);
msg.error((e as Error)?.message || t('login.passwordResetRequestFailed'));
}
};
const handleLogin = async (event?: Event) => {
event?.preventDefault();
event?.stopPropagation();
if (!loginUsername.value.trim()) {
msg.warning(t('login.usernameRequired'));
return;
}
try {
const loginMode = String(config.auth?.loginMode || 'casdoor').toLowerCase();
const isCasdoorMode = loginMode === 'casdoor';
const loginApi = isCasdoorMode
? (config.auth?.casdoor?.passwordLoginApi || '/api/user/casdoor/password-login')
: '/api/user/login';
const user = await requestJson<Record<string, unknown>>(loginApi, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: loginUsername.value.trim(),
password: loginPassword.value,
}),
});
persistLoginUser(user);
await completePasswordLogin();
} catch (e) {
const err = e as BusinessError;
const rawError = String(err.message || '');
let errorText = resolveCasdoorErrorMessage(err, t);
if (rawError === 'User not found') errorText = t('login.userNotFound');
if (rawError === 'Incorrect password') errorText = t('login.incorrectPassword');
if (rawError === 'Account is disabled') errorText = t('login.accountDisabled');
if (rawError === 'Database connection failed') errorText = t('login.dbConnectionFailed');
if (rawError === 'Internal server error') errorText = t('login.internalError');
console.error(e);
msg.error(errorText || t('login.requestFailed'));
}
};
const tryCasdoorCallbackLogin = async () => {
if (!config.auth?.casdoor?.enabled) return false;
const casdoorPath = config.auth.casdoor.callbackPath || '/casdoor-callback';
const path = window.location.pathname;
if (!isLoginCallbackPath(path, [casdoorPath])) return false;
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const state = params.get('state');
if (!code) return false;
const expectedState = sessionStorage.getItem('hxops_casdoor_state');
const shouldStrictCheck = !!expectedState && !!state && !String(state).startsWith('hxops_casdoor_v1.');
if (shouldStrictCheck && state !== expectedState) {
msg.error(t('login.casdoorErrors.stateExpired'));
clearWecomCallbackQuery();
return true;
}
try {
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
const data = await requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
persistLoginUser(data);
sessionStorage.removeItem('hxops_casdoor_state');
await completeOAuthLogin();
return true;
} catch (e) {
const err = e as BusinessError;
console.error(e);
msg.error(resolveCasdoorErrorMessage(err, t));
clearWecomCallbackQuery();
return true;
}
};
const handleWecomLogin = async () => {
if (!config.auth?.wecom?.enabled) return;
const wecomCfg = config.auth.wecom as { loginViaCasdoor?: boolean; callbackPath?: string; authorizeApi?: string };
const viaCasdoor = Boolean(wecomCfg?.loginViaCasdoor);
try {
if (viaCasdoor) {
if (!config.auth?.casdoor?.enabled) {
msg.error(t('login.wecomStartFailed'));
return;
}
const callbackPath = config.auth.casdoor.callbackPath || '/casdoor-callback';
const redirectUri = `${window.location.origin}${callbackPath}`;
const api = config.auth.casdoor.authorizeApi || '/api/user/casdoor/authorize-url';
const qs = new URLSearchParams({ redirect_uri: redirectUri, default_provider: 'wecom' });
const hint = (config.auth.casdoor as { wecomProviderHint?: string }).wecomProviderHint?.trim();
if (hint) qs.set('provider_hint', hint);
const data = await requestJson<{ url?: string; state?: string }>(`${api}?${qs.toString()}`);
if (!data?.url) {
msg.error(t('login.wecomStartFailed'));
return;
}
if (data.state) sessionStorage.setItem('hxops_casdoor_state', data.state);
window.location.href = data.url;
return;
}
const callbackPath = wecomCfg.callbackPath || '/login';
const redirectUri = `${window.location.origin}${callbackPath}`;
const api = wecomCfg.authorizeApi || '/api/user/wecom/authorize-url';
const data = await requestJson<{ url?: string; state?: string }>(
`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`,
);
if (!data?.url) {
msg.error(t('login.wecomStartFailed'));
return;
}
if (data.state) sessionStorage.setItem('hxops_wecom_state', data.state);
window.location.href = data.url;
} catch (e) {
console.error(e);
msg.error((e as Error)?.message || t('login.wecomStartFailed'));
}
};
const openWecomLoginDialog = (payload: Record<string, unknown>) => {
wecomLoginDialog.value = buildWecomLoginDialogContent(payload, t);
};
const openWecomBindPrompt = (payload: Record<string, unknown>) => {
const allowedFields = normalizeWecomMatchRules(payload.allowed_fields).fields;
const fallbackFields: WecomMatchField[] = ['employee_id', 'mobile', 'email'];
const fields: WecomMatchField[] = allowedFields.length ? allowedFields : fallbackFields;
wecomBindPrompt.value = {
binding_token: String(payload.binding_token || ''),
allowed_fields: fields,
wecom_name: String(payload.wecom_name || ''),
field: fields[0] || 'employee_id',
value: '',
submitting: false,
error: '',
};
};
const formatWecomBindPromptError = (payload: Record<string, unknown>) => {
const errorCode = String(payload.error_code || '');
if (errorCode === 'WECOM_BIND_INPUT_NOT_FOUND') return t('login.wecomBindInputNotFound');
if (errorCode === 'WECOM_BIND_INPUT_AMBIGUOUS') return t('login.wecomBindInputAmbiguous');
if (errorCode === 'WECOM_BIND_SESSION_EXPIRED') return t('login.wecomBindSessionExpired');
if (errorCode === 'WECOM_BIND_CONFLICT') return t('login.wecomBindConflict');
if (errorCode === 'WECOM_BIND_FIELD_NOT_ALLOWED') return t('login.wecomBindFieldNotAllowed');
if (errorCode === 'WECOM_BIND_INPUT_VALUE_REQUIRED') return t('login.wecomBindValueRequired');
if (String(payload.error || '').includes('Account is disabled')) return t('login.wecomAccountDisabled');
return String(payload.error || t('login.wecomLoginFailed'));
};
const submitWecomCompleteBind = async () => {
if (!wecomBindPrompt.value) return;
if (!wecomBindPrompt.value.value.trim()) {
wecomBindPrompt.value.error = t('login.wecomBindValueRequired');
return;
}
wecomBindPrompt.value.submitting = true;
wecomBindPrompt.value.error = '';
try {
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
const data = await requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
binding_token: wecomBindPrompt.value.binding_token,
field: wecomBindPrompt.value.field,
value: wecomBindPrompt.value.value.trim(),
}),
});
wecomLoginDialog.value = null;
persistLoginUser(data);
sessionStorage.removeItem('hxops_wecom_state');
wecomBindPrompt.value = null;
await completeOAuthLogin();
} catch (e) {
const err = e as BusinessError;
if (wecomBindPrompt.value) {
const errorPayload = { error: err.message, error_code: err.code };
wecomBindPrompt.value.error = formatWecomBindPromptError(errorPayload);
if (String(err.code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
openWecomLoginDialog(errorPayload);
wecomBindPrompt.value = null;
}
}
console.error(e);
} finally {
if (wecomBindPrompt.value) wecomBindPrompt.value.submitting = false;
}
};
const tryWecomCallbackLogin = async () => {
if (!config.auth?.wecom?.enabled) return false;
if ((config.auth.wecom as { loginViaCasdoor?: boolean }).loginViaCasdoor) return false;
const wecomPath = config.auth.wecom.callbackPath || '/login';
const path = window.location.pathname;
if (path !== wecomPath && !isLoginCallbackPath(path)) return false;
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const state = params.get('state');
if (!code) return false;
const expectedState = sessionStorage.getItem('hxops_wecom_state');
if (expectedState && state && state !== expectedState) {
msg.error(t('login.wecomInvalidState'));
openWecomLoginDialog({ error: 'Invalid or expired WeCom state' });
clearWecomCallbackQuery();
return true;
}
isWecomLoggingIn.value = true;
try {
const api = config.auth.wecom.loginApi || '/api/user/wecom/login';
const data = await requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
wecomLoginDialog.value = null;
persistLoginUser(data);
sessionStorage.removeItem('hxops_wecom_state');
await completeOAuthLogin();
return true;
} catch (e) {
const err = e as BusinessError;
const rawError = String(err.message || '');
const errorCode = String(err.code || '');
let friendly = rawError || t('login.wecomLoginFailed');
if (rawError.includes('Invalid or expired WeCom state')) friendly = t('login.wecomStateExpired');
else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
friendly = t('login.wecomBindRequired');
} else if (rawError.includes('Account is disabled')) friendly = t('login.wecomAccountDisabled');
console.error(e);
msg.error(friendly);
sessionStorage.removeItem('hxops_wecom_state');
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
openWecomBindPrompt({ error: rawError, error_code: errorCode });
} else {
openWecomLoginDialog({ error: rawError || t('login.wecomLoginFailed'), error_code: errorCode });
}
clearWecomCallbackQuery();
return true;
} finally {
isWecomLoggingIn.value = false;
}
};
const handleRegister = async () => {
const form = registerForm.value;
if (!form.username || !form.password || !form.real_name || !form.employee_id || !form.phone_number) {
msg.warning(t('register.inputError'));
return;
}
try {
await requestJson('/api/user/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
msg.success(t('register.success'));
showRegisterModal.value = false;
registerForm.value = {
username: '',
password: '',
email: '',
real_name: '',
employee_id: '',
phone_number: '',
};
} catch (e) {
console.error('Register error:', e);
msg.error((e as Error)?.message || t('register.requestFailed'));
}
};
return {
loginUsername,
loginPassword,
rememberMe,
showRegisterModal,
showForgotPasswordModal,
registerForm,
forgotPasswordForm,
isWecomLoggingIn,
wecomLoginDialog,
wecomBindPrompt,
clearWecomCallbackQuery,
handleForgotPassword,
handleLogin,
tryCasdoorCallbackLogin,
handleWecomLogin,
submitWecomCompleteBind,
tryWecomCallbackLogin,
handleRegister,
DEFAULT_POST_LOGIN_AGENT_ID,
};
}
@@ -0,0 +1,47 @@
/**
* features/auth/composables/useLoginLanding.ts
* 登录页营销区:公告列表、公开 Agent 与公告弹窗状态。
*/
import { ref } from 'vue';
import { requestJson } from '@/api/client';
import type { WorkspaceAgent, WorkspaceAnnouncement } from '@/features/workspace/types/workspace.types';
export function useLoginLanding() {
const isLoading = ref(true);
const announcements = ref<WorkspaceAnnouncement[]>([]);
const publicAgents = ref<WorkspaceAgent[]>([]);
const showAnnouncementModal = ref(false);
const selectedAnnouncement = ref<WorkspaceAnnouncement | null>(null);
const fetchAnnouncements = async () => {
try {
announcements.value = await requestJson<WorkspaceAnnouncement[]>('/api/user/announcements');
} catch (e) {
console.error('Failed to load announcements', e);
}
};
const fetchPublicAgents = async () => {
try {
publicAgents.value = await requestJson<WorkspaceAgent[]>('/api/agents/public');
} catch {
publicAgents.value = [];
}
};
const openAnnouncement = (ann: WorkspaceAnnouncement) => {
selectedAnnouncement.value = ann;
showAnnouncementModal.value = true;
};
return {
isLoading,
announcements,
publicAgents,
showAnnouncementModal,
selectedAnnouncement,
fetchAnnouncements,
fetchPublicAgents,
openAnnouncement,
};
}
+16
View File
@@ -1,2 +1,18 @@
/**
* features/auth/index.ts
* 认证 feature 对外导出:store、登录 composable、用户 API。
*/
export { useAuthStore, bindAuthStoreSync } from './stores/auth.store';
export { useAuth } from './composables/useAuth';
export { useLogin } from './composables/useLogin';
export {
getUserProfile,
getLeaveBalance,
submitLeaveWorkflow,
resetPasswordConfirm,
getUserAgent,
listUserAgents,
listAgentGuides,
type LeaveBalanceResult,
type LeaveWorkflowSubmitResult,
} from './api/user.api';
@@ -0,0 +1,28 @@
<script setup lang="ts">
/**
* features/auth/views/LoginView.vue
* 登录页路由入口:MarketingShell + useLogin provide + LoginPage/LoginModals。
*/
import { provide } from 'vue';
import ThemeToggleButton from '@/components/ThemeToggleButton.vue';
import LocaleToggleButton from '@/components/LocaleToggleButton.vue';
import MarketingShell from '@/layouts/MarketingShell.vue';
import LoginPage from '../components/LoginPage.vue';
import LoginModals from '../components/LoginModals.vue';
import { useLogin } from '../composables/useLogin';
import { LOGIN_KEY } from '../composables/login.context';
const login = useLogin();
provide(LOGIN_KEY, login);
</script>
<template>
<MarketingShell>
<template #tools>
<ThemeToggleButton />
<LocaleToggleButton />
</template>
<LoginPage />
<LoginModals />
</MarketingShell>
</template>
@@ -1,9 +1,13 @@
<script setup lang="ts">
/**
* features/auth/views/ResetPasswordView.vue
* 邮件链接重置密码页(/reset-password?token=...)。
*/
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Lock, AlertCircle, CheckCircle } from 'lucide-vue-next';
import MinimalShell from '../layouts/MinimalShell.vue';
import { resetPasswordConfirm } from '../api/user';
import MinimalShell from '@/layouts/MinimalShell.vue';
import { resetPasswordConfirm } from '@/features/auth/api/user.api';
const route = useRoute();
const router = useRouter();
@@ -0,0 +1,75 @@
/**
* features/chat/api/chat.api.ts
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
*/
import { getAuthHeaders } from '@/utils/auth';
import { requestJson } from '@/api/client';
import type {
ChatCrossAgentHistoryItem,
ChatMessage,
ChatSessionItem,
ChatSourceFileResult,
ChatUploadResult,
OaEmployeesResponse,
} from '../types/chat.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
export const listChatSessions = (agentId: number) =>
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
export const deleteAllChatSessions = (agentId: number) =>
requestJson(`/api/chat/sessions?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
export const deleteChatSession = (conversationId: string, agentId: number) =>
requestJson(`/api/chat/sessions/${conversationId}?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
export const listChatMessages = (conversationId: string, agentId: number) =>
requestJson<ChatMessage[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(payload),
});
export const resolveChatSourceFile = (params: {
agent_id: number;
dataset_id: string;
remote_document_id: string;
}) => {
const qs = new URLSearchParams({
agent_id: String(params.agent_id),
dataset_id: params.dataset_id,
remote_document_id: params.remote_document_id,
});
return requestJson<ChatSourceFileResult>(`/api/chat/source-file?${qs.toString()}`, auth());
};
export const listOaEmployees = (
agentId: number,
query: { keyword?: string; page?: number; page_size?: number },
) => {
const qs = new URLSearchParams({
agent_id: String(agentId),
keyword: query.keyword || '',
page: String(query.page ?? 1),
page_size: String(query.page_size ?? 20),
});
return requestJson<OaEmployeesResponse>(`/api/chat/oa/employees?${qs.toString()}`, auth());
};
export const uploadChatFile = (agentId: number, file: File) => {
const qs = new URLSearchParams({ agent_id: String(agentId) });
const fd = new FormData();
fd.append('file', file);
return requestJson<ChatUploadResult>(`/api/chat/files/upload?${qs.toString()}`, {
method: 'POST',
body: fd,
headers: getAuthHeaders(),
});
};
export type { ChatSessionItem, ChatCrossAgentHistoryItem };
@@ -0,0 +1,16 @@
/**
* features/chat/composables/chat.deps.ts
* 聊天 composables 共享依赖。
*/
import type { WritableComputedRef } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import type { useMessage } from '@/composables/useMessage';
export interface ChatDeps {
t: ComposerTranslation;
locale: WritableComputedRef<string>;
msg: ReturnType<typeof useMessage>;
router: Router;
route: RouteLocationNormalizedLoaded;
}
@@ -0,0 +1,292 @@
/**
* features/chat/composables/useChat.ts
* SSE 流式对话核心:消息列表、runs、发送与接收。
*/
import { ref } from 'vue';
import { getAuthHeaders } from '@/utils/auth';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
const normalizeResources = (resources: unknown) => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
if (typeof resources === 'object' && resources !== null && Array.isArray((resources as { data?: unknown }).data)) {
return (resources as { data: unknown[] }).data;
}
return [];
};
const addRetrieverResources = (msg: ChatMessage, resources: unknown) => {
const list = normalizeResources(resources);
if (list.length === 0) return;
if (!msg.retriever_resources) msg.retriever_resources = [];
for (const item of list) {
const r = item as Record<string, unknown>;
const key = `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}`;
const existingIndex = msg.retriever_resources.findIndex(
(x) => `${x.document_name || ''}|${x.segment_id || ''}|${x.content || ''}` === key,
);
if (existingIndex < 0) {
msg.retriever_resources.push(item as RetrieverResource);
} else {
msg.retriever_resources[existingIndex] = {
...msg.retriever_resources[existingIndex],
...(item as object),
};
}
}
};
const addAttributionParts = (msg: ChatMessage, value: unknown) => {
if (!value) return;
if (!msg.attribution_parts) msg.attribution_parts = [];
const pushUnique = (text: string) => {
const v = text.trim();
if (!v) return;
if (!msg.attribution_parts!.includes(v)) {
msg.attribution_parts!.push(v);
}
};
if (typeof value === 'string') {
pushUnique(value);
return;
}
if (Array.isArray(value)) {
for (const item of value) {
if (typeof item === 'string') {
pushUnique(item);
} else if (item && typeof item === 'object') {
const o = item as Record<string, unknown>;
pushUnique(String(o.content || o.text || o.title || JSON.stringify(item)));
}
}
return;
}
if (typeof value === 'object' && value !== null) {
const o = value as Record<string, unknown>;
pushUnique(String(o.content || o.text || o.title || JSON.stringify(value)));
}
};
const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) => {
const metadata = (data?.metadata || {}) as Record<string, unknown>;
addRetrieverResources(msg, data?.retriever_resources);
addRetrieverResources(msg, metadata?.retriever_resources);
addRetrieverResources(msg, metadata?.retrieverResources);
addAttributionParts(msg, data?.annotations);
addAttributionParts(msg, data?.annotation_reply);
addAttributionParts(msg, metadata?.annotations);
addAttributionParts(msg, metadata?.annotation_reply);
addAttributionParts(msg, data?.citation);
addAttributionParts(msg, metadata?.citation);
};
export function useChat() {
const messages = ref<ChatMessage[]>([]);
const isThinking = ref(false);
const viewId = ref(0);
const runs = ref<ChatRun[]>([]);
const activeRunId = ref<number | null>(null);
let runSeq = 0;
const conversationId = ref<string | null>(null);
const activateRun = (runId: number) => {
const run = runs.value.find((r) => r.runId === runId);
if (!run) return;
messages.value = run.messages;
conversationId.value = run.conversationId;
isThinking.value = run.status === 'running';
activeRunId.value = runId;
};
const createNewChatView = () => {
viewId.value += 1;
messages.value = [];
conversationId.value = null;
isThinking.value = false;
activeRunId.value = null;
};
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
viewId.value += 1;
activeRunId.value = null;
isThinking.value = false;
messages.value = nextMessages;
conversationId.value = id;
};
const normalizeStreamText = (text: string) => {
if (!text) return '';
return text.replace(/\\n/g, '\n');
};
const sendMessage = async (
query: string,
agentId: number,
kbType = '企业知识库',
files?: Array<
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
>,
) => {
const runViewId = viewId.value;
const runMessages = messages.value;
const run: ChatRun = {
runId: ++runSeq,
agentId,
viewId: runViewId,
query,
messages: runMessages,
conversationId: conversationId.value,
status: 'running',
createdAt: new Date().toISOString(),
};
runs.value.unshift(run);
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
activeRunId.value = run.runId;
runMessages.push({ role: 'user', content: query });
let botMsgIndex: number | null = null;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = runMessages.push({
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: [],
}) - 1;
}
return runMessages[botMsgIndex] || null;
};
isThinking.value = true;
try {
const response = await fetch('/api/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
query,
agent_id: agentId,
conversation_id: conversationId.value,
kb_type: kbType,
files: files && files.length > 0 ? files : undefined,
}),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error((err as { error?: string }).error || `Request failed with status ${response.status}`);
}
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) throw new Error('No reader');
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
buffer = buffer.replace(/\r\n/g, '\n');
const frames = buffer.split('\n\n');
buffer = frames.pop() || '';
for (const frame of frames) {
const dataLines = frame
.split('\n')
.map((l) => l.trim())
.filter((l) => l.startsWith('data:'));
if (dataLines.length === 0) continue;
const payload = dataLines.map((l) => l.replace(/^data:\s?/, '')).join('\n');
if (!payload) continue;
try {
const data = JSON.parse(payload) as Record<string, unknown>;
if (data?.conversation_id) {
const cid = String(data.conversation_id);
if (!run.conversationId) run.conversationId = cid;
if (messages.value === runMessages) conversationId.value = cid;
}
const eventName = String(data.event || '');
if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
}
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
run.status = 'done';
if (messages.value === runMessages) isThinking.value = false;
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) currentBotMsg.chat_log_id = Number(data.chat_log_id);
}
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
const normalizedAnswer = normalizeStreamText(data.answer);
if (data.replace_answer) {
botMsg.content = normalizedAnswer;
} else {
botMsg.content += normalizedAnswer;
}
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
}
} else if (eventName === 'error') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += `\n[Error: ${data.message}]`;
run.status = 'error';
if (messages.value === runMessages) isThinking.value = false;
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
}
} catch {
// ignore malformed SSE frames
}
}
}
} catch (e: unknown) {
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
const message = e instanceof Error ? e.message : 'Network Issue';
botMsg.content += `\n[Error: ${message}]`;
}
} finally {
if (messages.value === runMessages) {
isThinking.value = false;
}
}
};
return {
messages,
isThinking,
conversationId,
runs,
activeRunId,
activateRun,
createNewChatView,
loadConversationState,
sendMessage,
};
}
@@ -0,0 +1,45 @@
/**
* features/chat/composables/useChatHistory.ts
* 跨 Agent 聊天历史列表(工作台 History 页 / 移动端 Tab)。
*/
import { ref } from 'vue';
import { getAuthHeaders } from '@/utils/auth';
import { requestJson } from '@/api/client';
import type { ChatCrossAgentHistoryItem } from '../types/chat.types';
export function useChatHistory() {
const chatHistories = ref<ChatCrossAgentHistoryItem[]>([]);
const isLoadingHistories = ref(false);
const loadChatHistories = async () => {
isLoadingHistories.value = true;
try {
const agentList = await requestJson<Array<{ id: number; name: string }>>('/api/agents', {
headers: getAuthHeaders(),
});
const allHistories: ChatCrossAgentHistoryItem[] = [];
await Promise.all(
(Array.isArray(agentList) ? agentList : []).map(async (agent) => {
try {
const sessions = await requestJson<ChatCrossAgentHistoryItem[]>(
`/api/chat/sessions?agent_id=${agent.id}`,
{ headers: getAuthHeaders() },
);
for (const s of Array.isArray(sessions) ? sessions : []) {
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
}
} catch {
// ignore per-agent failures
}
}),
);
allHistories.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
chatHistories.value = allHistories;
} catch {
// ignore
}
isLoadingHistories.value = false;
};
return { chatHistories, isLoadingHistories, loadChatHistories };
}
@@ -0,0 +1,408 @@
/**
* features/chat/composables/useChatSourceFiles.ts
* 检索来源 / 源文件链接解析与预览。
*/
import { ref, type ComputedRef, type Ref } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import { resolveChatSourceFile } from '../api/chat.api';
import type { SourceFileLink } from '../types/chat.types';
import type { useMessage } from '@/composables/useMessage';
const PREFERRED_SOURCE_EXTS = new Set([
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp',
'txt', 'rtf', 'md', 'markdown',
]);
const safeDecode = (value: string) => {
try {
return decodeURIComponent(value);
} catch {
return value;
}
};
const normalizeUrl = (url: string) => {
let v = url
.trim()
.replace(/^['"]|['"]$/g, '')
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/')
.replace(/&amp;/g, '&');
v = v.replace(/[),.;]+$/g, '');
if (!v) return '';
if (v.startsWith('//')) return `${window.location.protocol}${v}`;
if (/^https?:\/\//i.test(v) || v.startsWith('/')) return v;
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\//.test(v)) return `http://${v}`;
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\//.test(v)) return `http://${v}`;
return '';
};
const getUrlExt = (url: string) => {
const clean = (url.split('?')[0] || '').toLowerCase();
const idx = clean.lastIndexOf('.');
if (idx < 0) return '';
return clean.slice(idx + 1);
};
const isChunkLikeLink = (url: string) => /segment|chunk|fragments?|split/i.test(url);
const isPreferredSourceLink = (url: string) => PREFERRED_SOURCE_EXTS.has(getUrlExt(url));
const isNoisySourceUrl = (_url: string) => false;
const isNoisySourceName = (_name: string) => false;
const looksLikeFileName = (name: string) => {
const n = (name || '').trim();
if (!n) return false;
return /\.[A-Za-z0-9]{2,8}$/.test(n);
};
const findFirstByKeys = (payload: unknown, keyCandidates: string[]): string => {
if (payload == null) return '';
if (Array.isArray(payload)) {
for (const item of payload) {
const found = findFirstByKeys(item, keyCandidates);
if (found) return found;
}
return '';
}
if (typeof payload !== 'object') return '';
const obj = payload as Record<string, unknown>;
for (const key of keyCandidates) {
const value = obj[key];
if (value != null && String(value).trim()) return String(value).trim();
}
for (const value of Object.values(obj)) {
const found = findFirstByKeys(value, keyCandidates);
if (found) return found;
}
return '';
};
const findDirectByKeys = (payloads: unknown[], keyCandidates: string[]): string => {
for (const payload of payloads) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) continue;
const obj = payload as Record<string, unknown>;
for (const key of keyCandidates) {
const value = obj[key];
if (value != null && String(value).trim()) return String(value).trim();
}
}
return '';
};
const getResourceIds = (item: Record<string, unknown>) => {
const metadata = item?.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata)
? (item.metadata as Record<string, unknown>)
: null;
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
const remoteDocumentId = findDirectByKeys([item, metadata], [
'remote_document_id', 'dify_document_id', 'source_document_id', 'doc_id',
]) || findFirstByKeys(item, ['remote_document_id', 'dify_document_id', 'source_document_id', 'doc_id'])
|| findDirectByKeys([item, metadata], ['document_id']);
return { datasetId, remoteDocumentId };
};
const canPreviewSourceLink = (link: Partial<SourceFileLink> | null | undefined) => {
if (!link) return false;
return Boolean(link.url || (link.datasetId && link.remoteDocumentId));
};
const buildSourceLinkKey = (name: string, datasetId?: string, remoteDocumentId?: string, url?: string) => {
const normalizedName = String(name || '').trim();
const normalizedDatasetId = String(datasetId || '').trim();
const normalizedRemoteDocumentId = String(remoteDocumentId || '').trim();
const normalizedUrl = String(url || '').split('?')[0];
if (normalizedDatasetId && normalizedRemoteDocumentId) {
return `${normalizedName}|${normalizedDatasetId}|${normalizedRemoteDocumentId}`;
}
if (looksLikeFileName(normalizedName)) {
return normalizedUrl ? `${normalizedName}|${normalizedUrl}` : normalizedName;
}
return `${normalizedName}|${normalizedUrl}`;
};
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
const extractUrlsFromText = (text: string) => {
if (!text) return [];
const urls: string[] = [];
const normalizedText = text
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/');
const mdRegex = /\[[^\]]+\]\(([^)]+)\)/g;
let m: RegExpExecArray | null;
while ((m = mdRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
const htmlAttrRegex = /\b(?:href|src)\s*=\s*["']([^"']+)["']/gi;
while ((m = htmlAttrRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
const angleRegex = /<\s*((?:https?:\/\/|\/\/)[^>\s]+)\s*>/gi;
while ((m = angleRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
const rawRegex =
/((?:https?:\/\/|\/\/)[^\s"'<>]+|(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\/[^\s"'<>]+|[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\/[^\s"'<>]+|\/[^\s"'<>]+\.(?:md|markdown|txt|pdf|doc|docx|ppt|pptx|xls|xlsx|jpg|jpeg|png|gif|webp|svg|bmp))/gi;
while ((m = rawRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
return urls;
};
const getSourceContent = (item: Record<string, unknown>) =>
String(item?.content || item?.segment_content || item?.text || '');
export interface UseChatSourceFilesOptions {
agentId: ComputedRef<number>;
t: ComposerTranslation;
msg: ReturnType<typeof useMessage>;
isMobile: Ref<boolean>;
}
export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceFilesOptions) {
const filePreviewVisible = ref(false);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const getSourceTitle = (item: Record<string, unknown>) =>
String(item?.document_name || item?.title || item?.source || 'Untitled Source');
const getSourceMeta = (item: Record<string, unknown>) => {
const parts: string[] = [];
if (item?.dataset_name) parts.push(String(item.dataset_name));
if (item?.segment_id) parts.push(`segment: ${item.segment_id}`);
if (typeof item?.score === 'number') parts.push(`score: ${(item.score as number).toFixed(3)}`);
return parts.join(' | ');
};
const getSourceBrief = (item: Record<string, unknown>) => {
const raw = getSourceContent(item);
const plain = raw
.replace(/\[[^\]]+\]\(([^)]+)\)/g, '$1')
.replace(/[#>*`]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!plain) return '';
return plain.length > 180 ? `${plain.slice(0, 180)}...` : plain;
};
const getSourceLinks = (resources: unknown[] = []): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
const mergeSourceLink = (key: string, nextLink: SourceFileLink) => {
const existing = map.get(key);
if (!existing) {
map.set(key, nextLink);
return;
}
map.set(key, {
...existing,
...(nextLink.url ? { url: nextLink.url } : {}),
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
});
};
for (const raw of resources) {
const item = (raw || {}) as Record<string, unknown>;
const { datasetId, remoteDocumentId } = getResourceIds(item);
const directCandidates = [
item?.source_download_url, item?.url, item?.file_url, item?.document_url,
item?.source_url, item?.download_url,
(item?.metadata as Record<string, unknown> | undefined)?.source_download_url,
(item?.metadata as Record<string, unknown> | undefined)?.url,
(item?.metadata as Record<string, unknown> | undefined)?.file_url,
(item?.metadata as Record<string, unknown> | undefined)?.document_url,
].filter(Boolean) as string[];
const content = getSourceContent(item);
const forceName = String(item?.source_filename || item?.document_name || item?.title || '');
const forceUrl = normalizeUrl(String(item?.source_download_url || item?.url || ''));
if (forceName && (forceUrl || (datasetId && remoteDocumentId))) {
const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl);
mergeSourceLink(key, {
name: forceName,
...(forceUrl ? { url: forceUrl } : {}),
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
const serialized = JSON.stringify(item || {});
const discovered = [
...directCandidates.map(normalizeUrl).filter(Boolean),
...extractUrlsFromText(content),
...extractUrlsFromText(serialized),
];
const files = Array.isArray(item?.files) ? item.files : [];
for (const f of files) {
const file = f as Record<string, unknown>;
const fu = normalizeUrl(String(file?.url || file?.download_url || file?.file_url || ''));
if (fu) discovered.push(fu);
}
for (const url of discovered) {
if (isChunkLikeLink(url)) continue;
const name = String(item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file'));
if (isNoisySourceName(name)) continue;
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url);
mergeSourceLink(key, {
name,
url,
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
}
return Array.from(map.values()).filter((link) => canPreviewSourceLink(link));
};
const getMessageLinks = (message: Record<string, unknown>): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
const merge = (links: SourceFileLink[]) => {
for (const link of links) {
if (!canPreviewSourceLink(link)) continue;
const linkUrl = link.url || '';
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
if (isNoisySourceName(link.name)) continue;
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
const existing = map.get(key);
if (!existing) {
map.set(key, link);
} else {
map.set(key, {
...existing,
...(link.url ? { url: link.url } : {}),
...(link.datasetId ? { datasetId: link.datasetId } : {}),
...(link.remoteDocumentId ? { remoteDocumentId: link.remoteDocumentId } : {}),
});
}
}
};
if (message?.retriever_resources) {
merge(getSourceLinks(message.retriever_resources as unknown[]));
}
const links = Array.from(map.values());
const preferred = links.filter((l) => l.url && isPreferredSourceLink(l.url));
return preferred.length > 0 ? preferred : links;
};
const getDisplayRetrieverResources = (message: Record<string, unknown>): Record<string, unknown>[] => {
const list = Array.isArray(message?.retriever_resources) ? message.retriever_resources as Record<string, unknown>[] : [];
return list.filter((doc) => {
const name = String(doc?.source_filename || doc?.document_name || doc?.title || '');
const url = String(doc?.source_download_url || doc?.url || doc?.file_url || doc?.document_url || '');
return !(isMarkdownFileName(name) || isMarkdownByUrl(url));
});
};
const shouldExpandSourceDetails = (message: Record<string, unknown>): boolean =>
getMessageLinks(message).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url || ''));
const getSourcePreviewExt = (file: { name?: string; url?: string; actualExt?: string }) => {
const actual = String(file?.actualExt || '').trim().toLowerCase();
if (actual) return actual;
const byName = getUrlExt(file?.name || '');
if (byName) return byName;
return getUrlExt(file?.url || '');
};
const isWeComMobileWebView = () => {
if (typeof navigator === 'undefined') return false;
const ua = navigator.userAgent || '';
return /wxwork/i.test(ua) && /mobile/i.test(ua);
};
const shouldBypassEmbeddedPreview = (file: { name?: string; url?: string; actualExt?: string }) => {
const ext = getSourcePreviewExt(file);
if (!isMobile.value || !isWeComMobileWebView()) return false;
if (!/^https?:\/\//i.test(file?.url || '')) return false;
return ['pdf', 'xls', 'xlsx'].includes(ext);
};
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {
if (file.datasetId && file.remoteDocumentId) {
const data = await resolveChatSourceFile({
agent_id: agentId.value,
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (resolvedUrl) {
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
};
}
}
if (!file.url) throw new Error('当前源文件暂未返回可预览链接');
return { name: file.name, url: file.url, actualExt: file.actualExt };
};
const openPreview = async (file: SourceFileLink) => {
try {
const resolvedFile = await resolveSourceLink(file);
if (shouldBypassEmbeddedPreview(resolvedFile)) {
window.location.href = resolvedFile.url;
return;
}
previewFile.value = resolvedFile;
filePreviewVisible.value = true;
} catch (error: unknown) {
const message = error instanceof Error ? error.message : t('chat.previewUnavailable');
msg.warning(message);
}
};
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
const rawHref = (href || '').trim();
if (!rawHref.startsWith('#plm-preview?')) return null;
const params = new URLSearchParams(rawHref.slice('#plm-preview?'.length));
const name = (params.get('name') || '').trim();
const url = (params.get('url') || '').trim();
if (!name || !url) return null;
return { name, url };
};
return {
filePreviewVisible,
previewFile,
getSourceTitle,
getSourceMeta,
getSourceBrief,
getSourceLinks,
getMessageLinks,
getDisplayRetrieverResources,
shouldExpandSourceDetails,
openPreview,
parsePlmPreviewLink,
};
}
+9
View File
@@ -0,0 +1,9 @@
/**
* features/chat/index.ts
* 聊天域对外导出。
*/
export { useChat } from './composables/useChat';
export { useChatHistory } from './composables/useChatHistory';
export { useChatSourceFiles } from './composables/useChatSourceFiles';
export * from './api/chat.api';
export type * from './types/chat.types';
@@ -0,0 +1,47 @@
<script setup lang="ts">
/**
* features/chat/pages/HistoryPage.vue
* 跨 Agent 聊天历史列表,点击跳转对应会话(工作台 / 移动端 Tab 入口)。
*/
import { inject } from 'vue';
import { Bot } from 'lucide-vue-next';
import { WORKSPACE_KEY } from '@/features/workspace/composables/workspace.context';
const ws = inject(WORKSPACE_KEY)! as any;
</script>
<template>
<div class="space-y-3">
<div v-if="ws.isLoadingHistories" class="flex justify-center py-20">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
<div v-else-if="ws.chatHistories.length === 0" class="flex flex-col items-center justify-center py-20 text-muted">
<Bot class="h-10 w-10 mb-2" />
<p class="text-sm">{{ $t('workspace.history.empty') }}</p>
</div>
<div v-else>
<button
v-for="item in ws.chatHistories"
:key="item.id"
@click="ws.router.push(`/chat/${item.agent_id || 16}?conversation_id=${item.conversation_id}`)"
class="ws-history-card mb-2"
:class="ws.isMobile ? 'p-2.5 rounded-xl' : ''"
>
<div class="flex items-start gap-3">
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand-50 text-xs font-bold text-brand-600" :class="ws.isMobile ? 'h-7 w-7 text-[10px]' : ''">
{{ (item.agent_name || 'AI').charAt(0) }}
</div>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span class="truncate text-sm font-medium text-primary">{{ item.title || $t('workspace.history.untitled') }}</span>
</div>
<div class="mt-0.5 flex items-center gap-2 text-xs text-muted">
<span>{{ item.agent_name || '' }}</span>
<span>{{ new Date(item.created_at).toLocaleDateString() }}</span>
</div>
</div>
</div>
</button>
</div>
</div>
</template>
@@ -2,7 +2,8 @@ import { defineStore } from 'pinia';
import { ref } from 'vue';
/**
* 聊天域共享状态骨架。Phase 2 迁移 ChatView 时会话列表、当前 agent 等迁入此处。
* features/chat/stores/chat.store.ts
* 聊天域共享状态:当前 agent、侧栏折叠等(会话列表逐步迁入)。
*/
export const useChatStore = defineStore('chat', () => {
const currentAgentId = ref<number | null>(null);
@@ -0,0 +1,103 @@
/**
* features/chat/types/chat.types.ts
* 聊天域核心类型定义。
*/
export interface RetrieverResource {
dataset_name?: string;
document_name?: string;
segment_id?: string;
content?: string;
score?: number;
[key: string]: unknown;
}
export interface ChatMessage {
role: 'user' | 'assistant';
content: string;
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
payload?: unknown;
local_id?: string;
local_only?: boolean;
rated?: boolean;
shipping_actions?: Array<{
id: string;
label: string;
message: string;
variant?: 'primary' | 'secondary' | 'danger';
}>;
shipping_actions_used?: boolean;
}
export type ChatRunStatus = 'running' | 'done' | 'error';
export interface ChatRun {
runId: number;
agentId: number;
viewId: number;
query: string;
messages: ChatMessage[];
conversationId: string | null;
status: ChatRunStatus;
createdAt: string;
}
export interface ChatSessionItem {
id: number;
conversation_id: string;
title: string;
created_at: string;
}
export type DisplayHistoryItem = ChatSessionItem & { __runId?: number; __status?: string };
export interface ChatHistoryItem extends ChatSessionItem {}
/** 跨 Agent 历史(工作台 / 移动端 Tab) */
export interface ChatCrossAgentHistoryItem extends ChatSessionItem {
agent_id?: number;
agent_name?: string;
}
export interface SourceFileLink {
name: string;
url?: string;
datasetId?: string;
remoteDocumentId?: string;
actualExt?: string;
}
export interface LeaveAgentOption {
uid: string;
employeeId: string;
name: string;
jobtitle?: string;
jobtitleName?: string;
departmentid?: string;
subcompanyid1?: string;
departmentName?: string;
subcompanyName?: string;
}
export interface OaEmployeesResponse {
items: LeaveAgentOption[];
total: number;
}
export interface ChatSourceFileResult {
source_download_url?: string;
source_filename?: string;
source_ext?: string;
}
export interface ChatUploadResult {
id: string;
name?: string;
size?: number;
extension?: string;
mime_type?: string;
type?: 'image' | 'document' | 'audio' | 'video' | 'custom';
}
@@ -1,44 +1,40 @@
<script setup lang="ts">
/**
* ChatView.vue
* 文件用途:单个 Agent 的对话界面
* 引用文件:vue, vue-router, lucide-vue-next, useChat 组合函数
* 逻辑关系:
* - 使用 useChat 发送消息并接收 SSE 流
* - 支持从首页携带预设问题快速发起对话
* - 在回答结束后允许用户对本次回答进行评分与意见反馈
* features/chat/views/ChatView.vue
* 单个 Agent 对话页编排:组合 SSE、侧栏历史、源文件预览与各 Agent 特性模块。
*/
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { useChat } from '../composables/useChat';
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, Briefcase, History, Sun, Moon, CalendarDays, Building, Paperclip, Link2, BookOpen, FileText, Play, Image as ImageIcon } from 'lucide-vue-next';
import LocaleToggleButton from '../components/LocaleToggleButton.vue';
import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router';
import { config } from '../config';
import FilePreviewModal from '../components/FilePreviewModal.vue';
import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
import { useMessage } from '../composables/useMessage';
import { useIsMobile } from '../composables/useIsMobile';
import { getVoiceUnavailableErrorKey, useAudioTranscription } from '../composables/useAudioTranscription';
import { useTheme } from '../composables/useTheme';
import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth';
import { copyTextToClipboard } from '../utils/clipboard';
import { setLastChatAgentId } from '../utils/lastChatAgent';
import { registerOpenAgentId } from '../utils/agentTabs';
import ChatShell from '../layouts/ChatShell.vue';
import { BusinessError } from '../api/client';
import { marked } from 'marked';
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, Briefcase, History, Sun, Moon, CalendarDays, Building, Paperclip, Link2, BookOpen, FileText, Play, Image as ImageIcon, Settings } from 'lucide-vue-next';
import LocaleToggleButton from '@/components/LocaleToggleButton.vue';
import FilePreviewModal from '@/components/FilePreviewModal.vue';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '@/components/GeneralFeedbackDialog.vue';
import ChatShell from '@/layouts/ChatShell.vue';
import { useChat } from '@/features/chat/composables/useChat';
import { useChatSourceFiles } from '@/features/chat/composables/useChatSourceFiles';
import { config } from '@/config';
import {
listChatSessions,
deleteAllChatSessions,
deleteChatSession,
listChatMessages,
saveLocalChatMessage,
resolveChatSourceFile,
listOaEmployees,
uploadChatFile,
} from '../api/chat';
} from '@/features/chat/api/chat.api';
import { useMessage } from '@/composables/useMessage';
import { useIsMobile } from '@/composables/useIsMobile';
import { getVoiceUnavailableErrorKey, useAudioTranscription } from '@/composables/useAudioTranscription';
import { useTheme } from '@/composables/useTheme';
import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '@/utils/auth';
import { copyTextToClipboard } from '@/utils/clipboard';
import { setLastChatAgentId } from '@/utils/lastChatAgent';
import { registerOpenAgentId } from '@/utils/agentTabs';
import { workspacePathFromLegacyView } from '@/features/workspace/constants/routes';
import { BusinessError } from '@/api/client';
import {
getUserProfile,
getLeaveBalance,
@@ -46,7 +42,7 @@ import {
getUserAgent,
listUserAgents,
listAgentGuides,
} from '../api/user';
} from '@/features/auth/api/user.api';
import {
createWorkspaceShippingTask,
createWorkspaceShippingTaskFromNotice,
@@ -62,13 +58,19 @@ import {
submitWorkspaceShippingDecision,
uploadWorkspaceShippingInventory,
workspaceShippingExportUrl,
} from '../api/shippingNotice';
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET, SHIPPING_TERMINAL_CHECKPOINTS } from '../constants/shippingNoticeActions';
} from '@/api/shippingNotice';
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET, SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
const { t, locale } = useI18n();
const { appliedTheme, toggleLightDark } = useTheme();
const msg = useMessage();
const { isMobile } = useIsMobile();
const route = useRoute();
const router = useRouter();
const currentAgentId = computed(() => {
const id = Number(route.params.agentId);
return Number.isFinite(id) && id > 0 ? id : 0;
});
const showMobileAgentPopover = ref(false);
const mobileAgentPopoverRef = ref<HTMLElement | null>(null);
@@ -146,11 +148,17 @@ const onAuthLogout = () => {
};
const handleLogout = () => {
showUserDropdown.value = false;
logoutAuth();
onAuthLogout();
router.push('/');
};
const goToAdmin = () => {
showUserDropdown.value = false;
router.push('/admin');
};
watch(locale, (newLang) => {
localStorage.setItem('hxops_lang', String(newLang));
});
@@ -257,403 +265,19 @@ const renderMarkdown = (text: string) => {
}
};
const getSourceTitle = (item: any) => {
return item?.document_name || item?.title || item?.source || 'Untitled Source';
};
const getSourceMeta = (item: any) => {
const parts: string[] = [];
if (item?.dataset_name) parts.push(item.dataset_name);
if (item?.segment_id) parts.push(`segment: ${item.segment_id}`);
if (typeof item?.score === 'number') parts.push(`score: ${item.score.toFixed(3)}`);
return parts.join(' | ');
};
const getSourceContent = (item: any) => {
return item?.content || item?.segment_content || item?.text || '';
};
const getSourceBrief = (item: any) => {
const raw = getSourceContent(item);
const plain = raw
.replace(/\[[^\]]+\]\(([^)]+)\)/g, '$1')
.replace(/[#>*`]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!plain) return '';
return plain.length > 180 ? `${plain.slice(0, 180)}...` : plain;
};
interface SourceFileLink {
name: string;
url?: string;
datasetId?: string;
remoteDocumentId?: string;
actualExt?: string;
}
// 源文件展示配置(来自 config.ts)
// const sourceFileConfig = {
// // 是否显示整个“源文件”区域
// showSourceFiles: config.workspace?.sourceFiles?.showSourceFiles !== false,
// // 是否显示 MD 源文件(.md/.markdown)
// showMdFiles: config.workspace?.sourceFiles?.showMdFiles !== false,
// // MD 源文件是否默认展开“源文档”详情
// expandMdByDefault: config.workspace?.sourceFiles?.expandMdByDefault === true,
// };
const PREFERRED_SOURCE_EXTS = new Set([
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp',
'txt', 'rtf', 'md', 'markdown',
]);
const safeDecode = (value: string) => {
try {
return decodeURIComponent(value);
} catch {
return value;
}
};
const normalizeUrl = (url: string) => {
// 统一清洗 URL:去掉包裹引号、还原转义字符、剔除末尾标点。
// 目的:让后续提取逻辑面对 Dify 返回的不同转义形态时保持稳定。
let v = url
.trim()
.replace(/^['"]|['"]$/g, '')
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/')
.replace(/&amp;/g, '&');
v = v.replace(/[),.;]+$/g, '');
if (!v) return '';
if (v.startsWith('//')) return `${window.location.protocol}${v}`;
if (/^https?:\/\//i.test(v) || v.startsWith('/')) return v;
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\//.test(v)) return `http://${v}`;
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\//.test(v)) return `http://${v}`;
return '';
};
const getUrlExt = (url: string) => {
const clean = (url.split('?')[0] || '').toLowerCase();
const idx = clean.lastIndexOf('.');
if (idx < 0) return '';
return clean.slice(idx + 1);
};
const isChunkLikeLink = (url: string) => {
// 保留原始 Markdown 文件链接;仅过滤明显的分片/切片类链接。
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) => {
// 带签名参数的下载链接在 UI 中可读性差(如 download?version_id=...&token=...)。
// 暂时注释掉这段校验逻辑,保证有元数据能被展示出来
// return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
return false;
};
const isNoisySourceName = (_name: string) => {
// 兜底过滤:名称如果本质是查询串而不是文件名,则不展示。
// 注释掉,允许带参数的链接在没有文件名时也可以显示(作为退路)
// return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
return false;
};
const looksLikeFileName = (name: string) => {
const n = (name || '').trim();
if (!n) return false;
// 保留中英文文件名,如 员工手册.doc
return /\.[A-Za-z0-9]{2,8}$/.test(n);
};
const findFirstByKeys = (payload: any, keyCandidates: string[]): string => {
if (payload == null) return '';
if (Array.isArray(payload)) {
for (const item of payload) {
const found = findFirstByKeys(item, keyCandidates);
if (found) return found;
}
return '';
}
if (typeof payload !== 'object') return '';
for (const key of keyCandidates) {
const value = payload?.[key];
if (value != null && String(value).trim()) {
return String(value).trim();
}
}
for (const value of Object.values(payload)) {
const found = findFirstByKeys(value, keyCandidates);
if (found) return found;
}
return '';
};
const findDirectByKeys = (payloads: any[], keyCandidates: string[]): string => {
for (const payload of payloads) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) continue;
for (const key of keyCandidates) {
const value = payload?.[key];
if (value != null && String(value).trim()) {
return String(value).trim();
}
}
}
return '';
};
const getResourceIds = (item: any) => {
const metadata = item?.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata)
? item.metadata
: null;
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
const remoteDocumentId = findDirectByKeys([item, metadata], [
'remote_document_id',
'dify_document_id',
'source_document_id',
'doc_id',
]) || findFirstByKeys(item, [
'remote_document_id',
'dify_document_id',
'source_document_id',
'doc_id',
]) || findDirectByKeys([item, metadata], ['document_id']);
return { datasetId, remoteDocumentId };
};
const canPreviewSourceLink = (link: Partial<SourceFileLink> | null | undefined) => {
if (!link) return false;
return Boolean(link.url || (link.datasetId && link.remoteDocumentId));
};
const buildSourceLinkKey = (name: string, datasetId?: string, remoteDocumentId?: string, url?: string) => {
const normalizedName = String(name || '').trim();
const normalizedDatasetId = String(datasetId || '').trim();
const normalizedRemoteDocumentId = String(remoteDocumentId || '').trim();
const normalizedUrl = String(url || '').split('?')[0];
if (normalizedDatasetId && normalizedRemoteDocumentId) {
return `${normalizedName}|${normalizedDatasetId}|${normalizedRemoteDocumentId}`;
}
if (looksLikeFileName(normalizedName)) {
return normalizedUrl ? `${normalizedName}|${normalizedUrl}` : normalizedName;
}
return `${normalizedName}|${normalizedUrl}`;
};
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
const extractUrlsFromText = (text: string) => {
if (!text) return [];
const urls: string[] = [];
// 先把常见 JSON/Markdown 转义做一次反转义,避免 regex 漏抓。
const normalizedText = text
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/');
// 1) Markdown 链接: [name](url)
const mdRegex = /\[[^\]]+\]\(([^)]+)\)/g;
let m;
while ((m = mdRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
// 2) HTML 链接: href/src 属性
const htmlAttrRegex = /\b(?:href|src)\s*=\s*["']([^"']+)["']/gi;
while ((m = htmlAttrRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
// 3) 尖括号 URL: <http://...>
const angleRegex = /<\s*((?:https?:\/\/|\/\/)[^>\s]+)\s*>/gi;
while ((m = angleRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
// 4) 原始 URL:支持带/不带协议、内网 IP、相对路径文件等
const rawRegex =
/((?:https?:\/\/|\/\/)[^\s"'<>]+|(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\/[^\s"'<>]+|[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\/[^\s"'<>]+|\/[^\s"'<>]+\.(?:md|markdown|txt|pdf|doc|docx|ppt|pptx|xls|xlsx|jpg|jpeg|png|gif|webp|svg|bmp))/gi;
while ((m = rawRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
return urls;
};
const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
const mergeSourceLink = (key: string, nextLink: SourceFileLink) => {
const existing = map.get(key);
if (!existing) {
map.set(key, nextLink);
return;
}
map.set(key, {
...existing,
...(nextLink.url ? { url: nextLink.url } : {}),
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
});
};
for (const item of resources) {
const { datasetId, remoteDocumentId } = getResourceIds(item);
const directCandidates = [
item?.source_download_url,
item?.url,
item?.file_url,
item?.document_url,
item?.source_url,
item?.download_url,
item?.metadata?.source_download_url,
item?.metadata?.url,
item?.metadata?.file_url,
item?.metadata?.document_url,
].filter(Boolean) as string[];
const content = getSourceContent(item);
// 直接强制从对象的顶层属性里获取文件名和链接
const forceName = item?.source_filename || item?.document_name || item?.title;
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
if (forceName && (forceUrl || (datasetId && remoteDocumentId))) {
const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl);
mergeSourceLink(key, {
name: forceName,
...(forceUrl ? { url: forceUrl } : {}),
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
const serialized = JSON.stringify(item || {});
const discovered = [
...directCandidates.map(normalizeUrl).filter(Boolean),
...extractUrlsFromText(content),
...extractUrlsFromText(serialized),
];
// 若 Dify 返回了 files 数组,额外补充其显式文件链接。
const files = Array.isArray(item?.files) ? item.files : [];
for (const f of files) {
const fu = normalizeUrl(f?.url || f?.download_url || f?.file_url || '');
if (fu) {
discovered.push(fu);
}
}
for (const url of discovered) {
if (isChunkLikeLink(url)) continue;
// URL 若为噪声签名链接,且没有可用文件名元数据,则跳过。
// 这里去掉 isNoisySourceUrl 判断的直接 continue,让有名的链接能过
// 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;
// 根据配置决定是否显示 MD 文件
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url);
mergeSourceLink(key, {
name,
url,
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
}
const links = Array.from(map.values()).filter((link) => canPreviewSourceLink(link));
// 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
// return preferred.length > 0 ? preferred : links;
return links;
};
const getMessageLinks = (msg: any): SourceFileLink[] => {
// if (!sourceFileConfig.showSourceFiles) {
// console.info('showSourceFiles is false');
// return [];
// }
const map = new Map<string, SourceFileLink>();
const merge = (links: SourceFileLink[]) => {
const mergeMessageLink = (key: string, nextLink: SourceFileLink) => {
const existing = map.get(key);
if (!existing) {
map.set(key, nextLink);
return;
}
map.set(key, {
...existing,
...(nextLink.url ? { url: nextLink.url } : {}),
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
});
};
for (const link of links) {
if (!canPreviewSourceLink(link)) continue;
const linkUrl = link.url || '';
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
if (isNoisySourceName(link.name)) continue;
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
if (isMarkdownFileName(link.name)) {
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
mergeMessageLink(key, link);
continue;
}
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
mergeMessageLink(key, link);
}
};
if (msg?.retriever_resources) {
// 仅使用结构化 retriever_resources 生成源文件按钮,
// 避免把回答正文里的普通 URL 误显示为“源文件”。
merge(getSourceLinks(msg.retriever_resources));
}
const links = Array.from(map.values());
const preferred = links.filter((l) => l.url && isPreferredSourceLink(l.url));
return preferred.length > 0 ? preferred : links;
};
const getDisplayRetrieverResources = (msg: any): any[] => {
// if (!sourceFileConfig.showSourceFiles) return [];
const list = Array.isArray(msg?.retriever_resources) ? msg.retriever_resources : [];
// if (sourceFileConfig.showMdFiles) return list;
return list.filter((doc: any) => {
const name = doc?.source_filename || doc?.document_name || doc?.title || '';
const url = doc?.source_download_url || doc?.url || doc?.file_url || doc?.document_url || '';
return !(isMarkdownFileName(String(name)) || isMarkdownByUrl(String(url)));
});
};
const shouldExpandSourceDetails = (msg: any): boolean => {
// if (!sourceFileConfig.showSourceFiles) {
// console.info('showSourceFiles is false');
// return false;
// }
// if (!sourceFileConfig.showMdFiles || !sourceFileConfig.expandMdByDefault) return false;
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url || ''));
};
const {
filePreviewVisible,
previewFile,
getSourceTitle,
getSourceMeta,
getSourceBrief,
getSourceLinks,
getMessageLinks,
getDisplayRetrieverResources,
shouldExpandSourceDetails,
openPreview,
parsePlmPreviewLink,
} = useChatSourceFiles({ agentId: currentAgentId, t, msg, isMobile });
const shouldRenderMessage = (msg: any): boolean => {
if (msg?.role === 'user') return true;
@@ -683,90 +307,6 @@ const shouldShowThinkingBubble = computed(() => {
.some((msg) => msg?.role === 'assistant' && shouldRenderMessage(msg));
});
const filePreviewVisible = ref(false);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const getSourcePreviewExt = (file: { name?: string; url?: string; actualExt?: string }) => {
const actual = String(file?.actualExt || '').trim().toLowerCase();
if (actual) return actual;
const byName = getUrlExt(file?.name || '');
if (byName) return byName;
return getUrlExt(file?.url || '');
};
const isWeComMobileWebView = () => {
if (typeof navigator === 'undefined') return false;
const ua = navigator.userAgent || '';
return /wxwork/i.test(ua) && /mobile/i.test(ua);
};
const shouldBypassEmbeddedPreview = (file: { name?: string; url?: string; actualExt?: string }) => {
const ext = getSourcePreviewExt(file);
if (!isMobile.value || !isWeComMobileWebView()) return false;
if (!/^https?:\/\//i.test(file?.url || '')) return false;
return ['pdf', 'xls', 'xlsx'].includes(ext);
};
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {
if (file.datasetId && file.remoteDocumentId) {
const data = await resolveChatSourceFile({
agent_id: currentAgentId.value,
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (resolvedUrl) {
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
};
}
}
if (!file.url) {
throw new Error('当前源文件暂未返回可预览链接');
}
return {
name: file.name,
url: file.url,
actualExt: file.actualExt,
};
};
const openPreview = async (file: SourceFileLink) => {
try {
const resolvedFile = await resolveSourceLink(file);
if (shouldBypassEmbeddedPreview(resolvedFile)) {
window.location.href = resolvedFile.url;
return;
}
previewFile.value = resolvedFile;
filePreviewVisible.value = true;
} catch (error: any) {
msg.warning(error?.message || t('chat.previewUnavailable'));
}
};
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
const rawHref = (href || '').trim();
if (!rawHref.startsWith('#plm-preview?')) return null;
const params = new URLSearchParams(rawHref.slice('#plm-preview?'.length));
const name = (params.get('name') || '').trim();
const url = (params.get('url') || '').trim();
if (!name || !url) return null;
return { name, url };
};
const route = useRoute();
const router = useRouter();
const currentAgentId = computed(() => {
const id = Number(route.params.agentId);
return Number.isFinite(id) && id > 0 ? id : 0;
});
// Sidebar state for mobile
const isSidebarOpen = ref(false);
const isSidebarCollapsed = ref(false);
@@ -4002,9 +3542,7 @@ const onPageHide = () => {
const goToWorkspace = (view?: string) => {
setLastChatAgentId(currentAgentId.value);
registerOpenAgentId(null);
const query: Record<string, string> = { no_redirect: '1' };
if (view) query.view = view;
router.push({ path: '/workspace', query });
router.push({ path: workspacePathFromLegacyView(view), query: { no_redirect: '1' } });
};
const resetChatStateForAgentChange = () => {
@@ -4317,6 +3855,16 @@ const showChatRating = ref(false);
</div>
</div>
<button
v-if="currentUser?.role === 'admin'"
type="button"
@click="goToAdmin"
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-secondary transition-colors hover:bg-surface-soft"
>
<Settings class="w-4 h-4" />
{{ $t('workspace.nav.admin') }}
</button>
<button @click="handleLogout" class="flex w-full items-center gap-2 border-t border-subtle px-4 py-2 text-left text-sm text-red-600 transition-colors hover:bg-red-50">
<LogOut class="w-4 h-4" />
{{ $t('chat.logout') }}
@@ -0,0 +1,129 @@
<script setup lang="ts">
/**
* features/workspace/components/WorkspaceModals.vue
* 工作台弹窗:公告详情、修改密码、快捷问题删除、意见反馈。
*/
import { inject } from 'vue';
import { X } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '@/components/GeneralFeedbackDialog.vue';
import { getAuthHeaders } from '@/utils/auth';
import { WORKSPACE_KEY } from '../composables/workspace.context';
const ws = inject(WORKSPACE_KEY)! as any;
</script>
<template>
<div>
<div
v-if="ws.showAnnouncementModal && ws.selectedAnnouncement"
class="dialog-overlay z-50 items-center animate-fade-in"
@click.self="ws.showAnnouncementModal = false"
>
<div class="dialog-panel max-w-2xl max-h-[85vh] animate-slide-up">
<div class="dialog-header">
<div class="min-w-0">
<span class="inline-flex rounded-full bg-brand-50 px-2 py-1 text-xs font-bold text-brand-600">{{ new Date(ws.selectedAnnouncement.created_at).toLocaleDateString() }}</span>
<h3 class="mt-2 text-2xl font-bold text-primary">{{ ws.selectedAnnouncement.title }}</h3>
</div>
<button type="button" class="btn-icon-ds shrink-0" :aria-label="$t('admin.close')" @click="ws.showAnnouncementModal = false">
<X class="w-5 h-5" />
</button>
</div>
<div class="dialog-body">
<p class="whitespace-pre-wrap leading-relaxed text-secondary">{{ ws.selectedAnnouncement.content }}</p>
</div>
<div class="dialog-footer">
<button type="button" @click="ws.showAnnouncementModal = false" class="btn-primary">
{{ $t('admin.close') }}
</button>
</div>
</div>
</div>
<div
v-if="ws.CHANGE_PASSWORD_ENABLED && ws.showPasswordModal"
class="dialog-overlay z-50 items-center"
>
<div class="dialog-panel max-w-md">
<div class="dialog-header">
<h3 class="section-title">{{ $t('profile.changePassword') || 'Change Password' }}</h3>
<button
type="button"
class="btn-icon-ds"
:aria-label="$t('admin.close')"
:disabled="ws.isChangingPassword"
@click="ws.showPasswordModal = false"
>
<X class="w-5 h-5" />
</button>
</div>
<form @submit.prevent="ws.handleChangePassword">
<div class="dialog-body">
<div>
<label class="label-field">{{ $t('profile.currentPassword') || 'Current Password' }}</label>
<input
v-model="ws.passwordForm.current"
type="password"
class="input-field mt-1"
:disabled="ws.isChangingPassword"
required
/>
</div>
<div>
<label class="label-field">{{ $t('profile.newPassword') || 'New Password' }}</label>
<input
v-model="ws.passwordForm.new"
type="password"
class="input-field mt-1"
:disabled="ws.isChangingPassword"
required
/>
</div>
<div>
<label class="label-field">{{ $t('profile.confirmPassword') || 'Confirm Password' }}</label>
<input
v-model="ws.passwordForm.confirm"
type="password"
class="input-field mt-1"
:disabled="ws.isChangingPassword"
required
/>
</div>
</div>
<div class="dialog-footer">
<button
type="button"
:disabled="ws.isChangingPassword"
@click="ws.showPasswordModal = false"
class="btn-secondary flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ $t('profile.cancel') || 'Cancel' }}
</button>
<button
type="submit"
:disabled="ws.isChangingPassword"
class="btn-primary flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ ws.isChangingPassword ? $t('profile.changingPassword') : ($t('profile.changePassword') || 'Update') }}
</button>
</div>
</form>
</div>
</div>
<DeleteConfirmDialog
v-model="ws.showDeleteQuickQuestionDialog"
:title="$t('workspace.quickQuestions.deleteDialog.title')"
:message="$t('workspace.quickQuestions.deleteDialog.message')"
@confirm="ws.confirmRemoveQuickQuestion"
@cancel="ws.cancelRemoveQuickQuestion"
/>
<GeneralFeedbackDialog
v-model="ws.showGeneralFeedbackDialog"
:auth-headers="getAuthHeaders()"
source-page="workspace"
@submitted="ws.msg.success('反馈提交成功')"
/>
</div>
</template>
@@ -0,0 +1,86 @@
<script setup lang="ts">
/**
* features/workspace/components/WorkspaceSidebar.vue
* 工作台左侧导航:子路由链接、返回聊天与退出登录。
*/
import { inject } from 'vue';
import { useRoute } from 'vue-router';
import {
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package,
} from 'lucide-vue-next';
import { WORKSPACE_PATHS } from '../constants/routes';
import { WORKSPACE_KEY } from '../composables/workspace.context';
const ws = inject(WORKSPACE_KEY)! as any;
const route = useRoute();
const linkItems = [
{ path: WORKSPACE_PATHS.profile, labelKey: 'workspace.nav.profile', icon: User, match: ['workspace-profile'] },
{ path: WORKSPACE_PATHS.applications, labelKey: 'workspace.nav.applications', icon: LayoutGrid, match: ['workspace-applications'] },
{ path: WORKSPACE_PATHS.scheduleRuns, labelKey: 'workspace.nav.scheduleRuns', icon: Clock, match: ['workspace-schedule-runs'] },
{ path: WORKSPACE_PATHS.shippingNotice, labelKey: 'workspace.nav.shippingNotice', icon: Package, match: ['workspace-shipping-notice'] },
{ path: WORKSPACE_PATHS.feedback, labelKey: 'workspace.nav.feedback', icon: Edit, match: ['workspace-feedback'] },
{ path: WORKSPACE_PATHS.updates, labelKey: 'workspace.nav.updates', icon: Megaphone, match: ['workspace-updates'] },
] as const;
function isActive(match: readonly string[]) {
return match.includes(String(route.name || ''));
}
</script>
<template>
<aside class="lg:sticky lg:top-0 lg:h-screen">
<div class="flex h-full flex-col border-r border-default bg-surface px-5 py-6 shadow-sm">
<div class="border-b border-subtle pb-6">
<div class="flex items-center gap-3">
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-purple-600 text-white shadow-lg shadow-brand-500/25">
<Bot class="h-6 w-6" />
</div>
<div class="min-w-0">
<div class="text-2xl font-extrabold tracking-tight text-primary">{{ $t('workspace.brandTitle') }}</div>
<div class="truncate text-xs font-medium text-muted">
{{ ws.currentUser?.username }} / {{ ws.currentUser?.role }}
</div>
</div>
</div>
</div>
<div class="flex-1 py-6">
<nav class="space-y-2">
<RouterLink
v-for="item in linkItems"
:key="item.path"
:to="item.path"
class="ws-nav-btn"
:class="{ 'ws-nav-btn--active': isActive(item.match) }"
>
<component :is="item.icon" class="h-4 w-4" />
<span>{{ $t(item.labelKey) }}</span>
</RouterLink>
<button
type="button"
class="ws-nav-btn w-full"
:class="{ 'ws-nav-btn--active': isActive(['workspace-knowledge-base']) }"
@click="ws.navigateToKnowledgeBase"
>
<FileText class="h-4 w-4" />
<span>{{ $t('workspace.nav.knowledgeBase') }}</span>
</button>
</nav>
</div>
<div class="border-t border-subtle pt-6">
<div class="space-y-2">
<button type="button" @click="ws.navigateToGeneralChat" class="ws-nav-btn">
<Bot class="h-4 w-4" />
<span>{{ $t('workspace.nav.backToChat') }}</span>
</button>
<button type="button" @click="ws.handleLogout" class="ws-nav-btn ws-nav-btn--danger">
<LogOut class="h-4 w-4" />
<span>{{ $t('workspace.nav.logout') }}</span>
</button>
</div>
</div>
</div>
</aside>
</template>
@@ -0,0 +1,106 @@
/**
* features/workspace/composables/useWorkspace.ts
* 工作台编排层:组合各子 composable,挂载生命周期,provide 给 Layout 与子页面。
*/
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { config } from '@/config';
import { useTheme } from '@/composables/useTheme';
import { useMessage } from '@/composables/useMessage';
import { useIsMobile } from '@/composables/useIsMobile';
import { WORKSPACE_PATHS } from '../constants/routes';
import type { WorkspaceUser } from '../types/workspace.types';
import { useChatHistory } from '@/features/chat/composables/useChatHistory';
import { useWorkspaceHome } from './useWorkspaceHome';
import { useWorkspaceLocale } from './useWorkspaceLocale';
import { useWorkspaceNavigation } from './useWorkspaceNavigation';
import { useWorkspaceProfile } from './useWorkspaceProfile';
import { useWorkspaceSchedule } from './useWorkspaceSchedule';
import { useWorkspaceSession } from './useWorkspaceSession';
export function useWorkspace() {
const { t, locale } = useI18n();
const msg = useMessage();
const router = useRouter();
const route = useRoute();
const { setThemePreference, appliedTheme } = useTheme();
const { isMobile } = useIsMobile();
const deps = { t, locale, msg, router, route, setThemePreference, appliedTheme };
const isLoading = ref(true);
const currentUser = ref<WorkspaceUser | null>(null);
const sessionRef: { handleLogout?: () => void } = {};
const home = useWorkspaceHome(deps, {
currentUser,
isLoading,
onUnauthorized: () => sessionRef.handleLogout?.(),
});
const session = useWorkspaceSession(deps, {
currentUser,
clearHome: home.clearHomeData,
});
sessionRef.handleLogout = session.handleLogout;
const profile = useWorkspaceProfile(deps);
const schedule = useWorkspaceSchedule(deps);
const history = useChatHistory();
const navigation = useWorkspaceNavigation(deps, {
isLoggedIn: session.isLoggedIn,
hasKnowledgeBaseAccess: session.hasKnowledgeBaseAccess,
KB_ACCESS_DENIED_MESSAGE: session.KB_ACCESS_DENIED_MESSAGE,
agents: home.agents,
layoutSections: home.layoutSections,
profileUserId: computed(() => profile.profileUser.value.id),
fetchProfile: profile.fetchProfile,
chatHistoriesLength: computed(() => history.chatHistories.value.length),
loadChatHistories: history.loadChatHistories,
loadWorkspaceScheduleRuns: schedule.loadWorkspaceScheduleRuns,
});
const localeApi = useWorkspaceLocale(deps);
onMounted(async () => {
window.addEventListener('hxops:logout', session.onAuthLogout);
localeApi.loadLanguagePreference();
session.loadAuthUser();
if (!session.isLoggedIn.value) {
await router.replace('/login');
return;
}
await home.fetchHome();
await navigation.redirectLegacyViewQuery();
await navigation.handleWecomDeeplinkContext();
await navigation.handleRouteSideEffects();
});
watch(session.hasKnowledgeBaseAccess, (allowed) => {
if (!allowed && route.name === 'workspace-knowledge-base') {
void router.replace(WORKSPACE_PATHS.applications);
}
});
onBeforeUnmount(() => {
window.removeEventListener('hxops:logout', session.onAuthLogout);
});
return reactive({
config,
msg,
router,
route,
isMobile,
isLoading,
...localeApi,
...session,
...home,
...profile,
...schedule,
...history,
...navigation,
});
}
@@ -0,0 +1,4 @@
/**
* @deprecated 请使用 @/features/chat/composables/useChatHistory
*/
export { useChatHistory as useWorkspaceHistory } from '@/features/chat/composables/useChatHistory';
@@ -0,0 +1,358 @@
/**
* features/workspace/composables/useWorkspaceHome.ts
* 应用管理/最近更新:首页数据、布局分区、收藏、快捷问题。
*/
import { computed, ref, type Ref } from 'vue';
import { config } from '@/config';
import { getAuthHeaders } from '@/utils/auth';
import { BusinessError, requestJson } from '@/api/client';
import {
SECTION_TITLE_KEY_MAP,
type WorkspaceAgent,
type WorkspaceAnnouncement,
type WorkspaceEmbeddedAgent,
type WorkspaceLayoutSection,
type WorkspaceQuickQuestion,
type WorkspaceUser,
} from '../types/workspace.types';
import type { WorkspaceDeps } from './workspace.deps';
interface HomeOptions {
currentUser: Ref<WorkspaceUser | null>;
isLoading: Ref<boolean>;
onUnauthorized: () => void;
}
export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
const { t, msg } = deps;
const { currentUser, isLoading, onUnauthorized } = options;
const agents = ref<WorkspaceAgent[]>([]);
const publicAgents = ref<WorkspaceAgent[]>([]);
const announcements = ref<WorkspaceAnnouncement[]>([]);
const quickQuestions = ref<WorkspaceQuickQuestion[]>([]);
const favoriteAgentIds = ref<number[]>([]);
const embeddedAgents = ref<WorkspaceEmbeddedAgent[]>([]);
const layoutSections = ref<WorkspaceLayoutSection[]>([
{ id: 'announcements', visible: true, collapsed: false, title: 'workspace.announcements.title' },
{ id: 'favorites', visible: true, collapsed: false, title: 'workspace.favorites' },
{ id: 'quick_questions', visible: true, collapsed: false, title: 'workspace.quickQuestions.title' },
{ id: 'embedded', visible: true, collapsed: false, title: 'workspace.embedded.title' },
{ id: 'all_agents', visible: true, collapsed: false, title: 'workspace.availableAgents' },
]);
const searchQuery = ref('');
const showAnnouncementModal = ref(false);
const selectedAnnouncement = ref<WorkspaceAnnouncement | null>(null);
const userReport = ref<unknown>(null);
const isAddingQuestion = ref(false);
const editingQuestionId = ref<number | null>(null);
const newQuestion = ref({ title: '', question: '', agent_id: null as number | null });
const draggedSectionIndex = ref<number | null>(null);
const showDeleteQuickQuestionDialog = ref(false);
const pendingDeleteQuickQuestionId = ref<number | null>(null);
const favoriteAgents = computed(() => agents.value.filter((a) => favoriteAgentIds.value.includes(a.id)));
const otherAgents = computed(() => {
const chatflowAgents = agents.value.filter((a) => (a.dify_app_type || 'chatflow') === 'chatflow');
if (!searchQuery.value.trim()) return chatflowAgents;
const q = searchQuery.value.toLowerCase();
return chatflowAgents.filter(
(a) => a.name.toLowerCase().includes(q) || a.description.toLowerCase().includes(q),
);
});
const filteredQuickQuestions = computed(() => {
if (!searchQuery.value.trim()) return quickQuestions.value;
const q = searchQuery.value.toLowerCase();
return quickQuestions.value.filter(
(qq) => qq.title.toLowerCase().includes(q) || qq.question.toLowerCase().includes(q),
);
});
const normalizeSectionId = (id: string) => {
if (id === 'quice_questions' || id === 'quickQuestions') return 'quick_questions';
if (id === 'allAgents') return 'all_agents';
return id;
};
const getSectionTitleKey = (sectionId: string) =>
SECTION_TITLE_KEY_MAP[normalizeSectionId(sectionId)] || normalizeSectionId(sectionId);
const clearHomeData = () => {
agents.value = [];
quickQuestions.value = [];
favoriteAgentIds.value = [];
embeddedAgents.value = [];
userReport.value = null;
};
const fetchHome = async () => {
try {
const data = await requestJson<any>('/api/user/home', { headers: getAuthHeaders() });
if (!data) {
throw new Error('Missing /api/user/home payload');
}
currentUser.value = {
id: data.user.id,
username: data.user.username,
role: data.user.role,
default_agent_id: data.user.default_agent_id,
};
agents.value = data.agents || [];
quickQuestions.value = data.quick_questions || [];
favoriteAgentIds.value = data.favorite_agent_ids || [];
embeddedAgents.value = data.embedded_agents || [];
if (data.layout?.sections) {
const backendSections = (data.layout.sections as WorkspaceLayoutSection[]).map((s) => ({
...s,
id: normalizeSectionId(s.id),
}));
const defaultSections = [
{ id: 'announcements', visible: true, title: getSectionTitleKey('announcements') },
{ id: 'favorites', visible: true, title: getSectionTitleKey('favorites') },
{ id: 'quick_questions', visible: true, title: getSectionTitleKey('quick_questions') },
{ id: 'embedded', visible: true, title: getSectionTitleKey('embedded') },
{ id: 'all_agents', visible: true, title: getSectionTitleKey('all_agents') },
];
const merged: WorkspaceLayoutSection[] = [];
const backendIds = new Set(backendSections.map((s) => s.id));
const mapKey = (id: string) =>
normalizeSectionId(id) === 'quick_questions'
? 'quickQuestions'
: normalizeSectionId(id) === 'all_agents'
? 'allAgents'
: normalizeSectionId(id);
backendSections.forEach((s) => {
const def = defaultSections.find((d) => d.id === s.id);
if (config.workspace.modules[mapKey(s.id) as keyof typeof config.workspace.modules] === false) return;
merged.push({ ...def, ...s, title: getSectionTitleKey(s.id) });
});
defaultSections.forEach((d) => {
if (!backendIds.has(d.id)) {
if (config.workspace.modules[mapKey(d.id) as keyof typeof config.workspace.modules] === false) return;
merged.push(d);
}
});
layoutSections.value = merged.filter((s) => {
const key = mapKey(s.id) as keyof typeof config.workspace.modules;
return config.workspace.modules[key] !== false;
});
} else {
const defaultSections = [
{ id: 'announcements', visible: true, collapsed: false, title: getSectionTitleKey('announcements') },
{ id: 'favorites', visible: true, collapsed: false, title: getSectionTitleKey('favorites') },
{ id: 'quick_questions', visible: true, collapsed: false, title: getSectionTitleKey('quick_questions') },
{ id: 'embedded', visible: true, collapsed: false, title: getSectionTitleKey('embedded') },
{ id: 'all_agents', visible: true, collapsed: false, title: getSectionTitleKey('all_agents') },
];
layoutSections.value = defaultSections.filter((s) => {
const key = (s.id === 'quick_questions'
? 'quickQuestions'
: s.id === 'all_agents'
? 'allAgents'
: s.id) as keyof typeof config.workspace.modules;
return config.workspace.modules[key] !== false;
});
}
} catch (e) {
if ((e as BusinessError)?.status === 401) {
msg.error(t('login.loginRequired'));
onUnauthorized();
return;
}
console.error('Failed to load user home', e);
} finally {
isLoading.value = false;
}
};
const fetchPublicAgents = async () => {
try {
publicAgents.value = await requestJson<WorkspaceAgent[]>('/api/agents/public');
} catch {
publicAgents.value = [];
}
};
const fetchAnnouncements = async () => {
try {
announcements.value = await requestJson<WorkspaceAnnouncement[]>('/api/user/announcements');
} catch (e) {
console.error('Failed to load announcements', e);
}
};
const openAnnouncement = (ann: WorkspaceAnnouncement) => {
selectedAnnouncement.value = ann;
showAnnouncementModal.value = true;
};
const toggleFavorite = async (agentId: number) => {
try {
if (favoriteAgentIds.value.includes(agentId)) {
await requestJson(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
favoriteAgentIds.value = favoriteAgentIds.value.filter((id) => id !== agentId);
} else {
await requestJson(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
favoriteAgentIds.value.push(agentId);
}
} catch (e) {
msg.error((e as Error)?.message || t('common.errorOccurred'));
}
};
const getAgentName = (agentId: number) => {
const agent = agents.value.find((a) => a.id === agentId);
return agent ? agent.name : t('workspace.unknownAgent');
};
const openAddQuestionForm = () => {
isAddingQuestion.value = true;
editingQuestionId.value = null;
newQuestion.value = { title: '', question: '', agent_id: null };
};
const editQuickQuestion = (qq: WorkspaceQuickQuestion) => {
isAddingQuestion.value = true;
editingQuestionId.value = qq.id;
newQuestion.value = { title: qq.title, question: qq.question, agent_id: qq.agent_id };
};
const cancelAddQuestion = () => {
isAddingQuestion.value = false;
editingQuestionId.value = null;
newQuestion.value = { title: '', question: '', agent_id: null };
};
const saveQuickQuestion = async () => {
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
msg.warning(t('workspace.quickQuestions.msg.fillAll'));
return;
}
const url = editingQuestionId.value
? `/api/user/quick-questions/${editingQuestionId.value}`
: '/api/user/quick-questions';
const method = editingQuestionId.value ? 'PUT' : 'POST';
try {
await requestJson(url, {
method,
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(newQuestion.value),
});
await fetchHome();
isAddingQuestion.value = false;
editingQuestionId.value = null;
} catch (e) {
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
}
};
const removeQuickQuestion = async (id: number) => {
pendingDeleteQuickQuestionId.value = id;
showDeleteQuickQuestionDialog.value = true;
};
const confirmRemoveQuickQuestion = async () => {
if (pendingDeleteQuickQuestionId.value === null) return;
try {
await requestJson(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
await fetchHome();
pendingDeleteQuickQuestionId.value = null;
showDeleteQuickQuestionDialog.value = false;
} catch (e) {
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
}
};
const cancelRemoveQuickQuestion = () => {
pendingDeleteQuickQuestionId.value = null;
showDeleteQuickQuestionDialog.value = false;
};
const saveLayout = async () => {
try {
await requestJson('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } }),
});
} catch (e) {
msg.error((e as Error)?.message || t('common.errorOccurred'));
}
};
const toggleSectionCollapse = async (section: WorkspaceLayoutSection) => {
section.collapsed = !section.collapsed;
await saveLayout();
};
const onDragStart = (index: number) => {
draggedSectionIndex.value = index;
};
const onDragOver = (event: DragEvent) => {
event.preventDefault();
};
const onDrop = async (index: number) => {
if (draggedSectionIndex.value === null) return;
const draggedItem = layoutSections.value[draggedSectionIndex.value];
if (!draggedItem) return;
layoutSections.value.splice(draggedSectionIndex.value, 1);
layoutSections.value.splice(index, 0, draggedItem);
draggedSectionIndex.value = null;
await saveLayout();
};
return {
agents,
publicAgents,
announcements,
quickQuestions,
favoriteAgentIds,
embeddedAgents,
SECTION_TITLE_KEY_MAP,
layoutSections,
searchQuery,
showAnnouncementModal,
selectedAnnouncement,
userReport,
isAddingQuestion,
editingQuestionId,
newQuestion,
draggedSectionIndex,
showDeleteQuickQuestionDialog,
pendingDeleteQuickQuestionId,
favoriteAgents,
otherAgents,
filteredQuickQuestions,
normalizeSectionId,
getSectionTitleKey,
clearHomeData,
fetchHome,
fetchPublicAgents,
fetchAnnouncements,
openAnnouncement,
toggleFavorite,
getAgentName,
openAddQuestionForm,
editQuickQuestion,
cancelAddQuestion,
saveQuickQuestion,
removeQuickQuestion,
confirmRemoveQuickQuestion,
cancelRemoveQuickQuestion,
toggleSectionCollapse,
onDragStart,
onDragOver,
onDrop,
};
}
@@ -0,0 +1,25 @@
/**
* features/workspace/composables/useWorkspaceLocale.ts
* 语言偏好本地存储与 i18n 同步。
*/
import { watch } from 'vue';
import type { WritableComputedRef } from 'vue';
export function useWorkspaceLocale({ locale }: { locale: WritableComputedRef<string> }) {
const loadLanguagePreference = () => {
const storedLang = localStorage.getItem('hxops_lang');
if (storedLang) {
locale.value = storedLang;
}
};
const saveLanguagePreference = (lang: string) => {
localStorage.setItem('hxops_lang', lang);
};
watch(locale, (newLang) => {
saveLanguagePreference(newLang);
});
return { loadLanguagePreference, saveLanguagePreference };
}
@@ -0,0 +1,254 @@
/**
* features/workspace/composables/useWorkspaceNavigation.ts
* 子路由导航、移动端 Tab、聊天跳转、企微 deeplink 与旧 view 参数兼容。
*/
import { computed, nextTick, ref, watch, type ComputedRef, type Ref } from 'vue';
import { config } from '@/config';
import { getAuthHeaders } from '@/utils/auth';
import { getLastChatAgentId } from '@/utils/lastChatAgent';
import { requestJson } from '@/api/client';
import { WORKSPACE_PATHS, workspacePathFromLegacyView } from '../constants/routes';
import { DEFAULT_POST_LOGIN_AGENT_ID, type WorkspaceAgent, type WorkspaceSidebarItem } from '../types/workspace.types';
import type { WorkspaceLayoutSection } from '../types/workspace.types';
import type { WorkspaceDeps } from './workspace.deps';
const ROUTE_NAME_TO_SIDEBAR: Record<string, WorkspaceSidebarItem> = {
'workspace-profile': 'profile',
'workspace-applications': 'applications',
'workspace-updates': 'updates',
'workspace-knowledge-base': 'knowledge_base',
'workspace-schedule-runs': 'schedule_runs',
'workspace-shipping-notice': 'shipping_notice',
'workspace-feedback': 'feedback',
'workspace-history': 'history',
};
interface NavigationOptions {
isLoggedIn: ComputedRef<boolean>;
hasKnowledgeBaseAccess: ComputedRef<boolean>;
KB_ACCESS_DENIED_MESSAGE: string;
agents: Ref<WorkspaceAgent[]>;
layoutSections: Ref<WorkspaceLayoutSection[]>;
profileUserId: ComputedRef<number>;
fetchProfile: () => Promise<void>;
chatHistoriesLength: Ref<number>;
loadChatHistories: () => Promise<void>;
loadWorkspaceScheduleRuns: () => Promise<void>;
}
export function useWorkspaceNavigation(deps: WorkspaceDeps, options: NavigationOptions) {
const { t, msg, router, route } = deps;
const {
isLoggedIn,
hasKnowledgeBaseAccess,
KB_ACCESS_DENIED_MESSAGE,
agents,
layoutSections,
profileUserId,
fetchProfile,
chatHistoriesLength,
loadChatHistories,
loadWorkspaceScheduleRuns,
} = options;
const showGeneralFeedbackDialog = ref(false);
const wecomEntryHint = ref('');
const activeSidebarItem = computed<WorkspaceSidebarItem>(() => {
const name = String(route.name || '');
return ROUTE_NAME_TO_SIDEBAR[name] || 'applications';
});
const mobileTabActive = computed({
get: () => {
if (activeSidebarItem.value === 'profile') return 'profile';
if (activeSidebarItem.value === 'history') return 'history';
return 'applications';
},
set: (tab: 'applications' | 'profile' | 'history') => {
if (tab === 'profile') void router.push(WORKSPACE_PATHS.profile);
else if (tab === 'history') void router.push(WORKSPACE_PATHS.history);
else void router.push(WORKSPACE_PATHS.applications);
},
});
const mobileTabTitle = computed(() => {
if (mobileTabActive.value === 'profile') return t('workspace.mobileTabs.me');
if (mobileTabActive.value === 'history') return t('workspace.mobileTabs.history');
return t('workspace.mobileTabs.applications');
});
const openGeneralFeedback = () => {
void router.push(WORKSPACE_PATHS.feedback);
showGeneralFeedbackDialog.value = true;
};
const openWorkspaceSection = async (sectionId: 'announcements' | 'favorites' | 'all_agents') => {
const targetSection = layoutSections.value.find((section) => section.id === sectionId);
if (targetSection) targetSection.collapsed = false;
await nextTick();
document.getElementById(`workspace-section-${sectionId}`)?.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
};
const navigateToApplications = () => router.push(WORKSPACE_PATHS.applications);
const navigateToUpdates = () => router.push(WORKSPACE_PATHS.updates);
const showKnowledgeBaseAccessDenied = () => {
msg.warning(KB_ACCESS_DENIED_MESSAGE);
};
const navigateToKnowledgeBase = () => {
if (!hasKnowledgeBaseAccess.value) {
showKnowledgeBaseAccessDenied();
return;
}
void router.push(WORKSPACE_PATHS.knowledgeBase);
};
const navigateToScheduleRuns = () => {
void router.push(WORKSPACE_PATHS.scheduleRuns);
};
const navigateToShippingNotice = () => {
void router.push(WORKSPACE_PATHS.shippingNotice);
};
const navigateToProfile = async () => {
await router.push(WORKSPACE_PATHS.profile);
if (!profileUserId.value) await fetchProfile();
};
const navigateToGeneralChat = () => {
router.push(`/chat/${getLastChatAgentId(DEFAULT_POST_LOGIN_AGENT_ID)}`);
};
const openAdminPanel = () => {
router.push('/admin');
};
const navigateToChat = (id: number) => {
if (!isLoggedIn.value) {
router.push('/login');
return;
}
router.push(`/chat/${id}`);
};
const navigateWithQuickQuestion = (agentId: number, question: string) => {
if (!isLoggedIn.value) {
router.push('/login');
return;
}
router.push({ path: `/chat/${agentId}`, query: { preset: question } });
};
const redirectLegacyViewQuery = async () => {
const viewParam = route.query.view as string | undefined;
if (!viewParam) return;
if (viewParam === 'knowledge_base' && !hasKnowledgeBaseAccess.value) {
showKnowledgeBaseAccessDenied();
await router.replace(WORKSPACE_PATHS.applications);
return;
}
const target = workspacePathFromLegacyView(viewParam);
const nextQuery = { ...route.query };
delete nextQuery.view;
await router.replace({ path: target, query: nextQuery });
};
const handleRouteSideEffects = async () => {
const name = String(route.name || '');
if (name === 'workspace-profile' && !profileUserId.value) {
await fetchProfile();
}
if (name === 'workspace-history' && chatHistoriesLength.value === 0) {
await loadChatHistories();
}
if (name === 'workspace-schedule-runs') {
await loadWorkspaceScheduleRuns();
}
if (name === 'workspace-knowledge-base' && !hasKnowledgeBaseAccess.value) {
showKnowledgeBaseAccessDenied();
await router.replace(WORKSPACE_PATHS.applications);
}
if (name === 'workspace-feedback') {
showGeneralFeedbackDialog.value = true;
}
if (name === 'workspace-applications') {
await openWorkspaceSection('favorites');
}
if (name === 'workspace-updates') {
await openWorkspaceSection('announcements');
}
};
watch(() => route.name, () => {
void handleRouteSideEffects();
});
const handleWecomDeeplinkContext = async () => {
const params = new URLSearchParams(window.location.search);
const traceId = params.get('wecom_trace');
const target = params.get('target');
const agentIdRaw = params.get('agent_id');
const preset = params.get('preset');
if (!traceId && !target) return;
wecomEntryHint.value = t('workspace.wecomEntryNotice');
if (traceId && isLoggedIn.value) {
try {
const api = config.auth?.wecom?.deeplinkTraceApi || '/api/user/wecom/deeplink-opened';
await requestJson(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ trace_id: traceId }),
});
} catch (e) {
console.warn('Failed to mark WeCom deeplink opened', e);
}
}
if (target === 'chat' && agentIdRaw && isLoggedIn.value) {
const agentId = Number(agentIdRaw);
if (Number.isInteger(agentId) && agents.value.some((a) => a.id === agentId)) {
await router.push({ path: `/chat/${agentId}`, query: preset ? { preset } : {} });
return;
}
}
if (traceId || target) {
window.history.replaceState({}, '', WORKSPACE_PATHS.applications);
}
};
return {
activeSidebarItem,
showGeneralFeedbackDialog,
wecomEntryHint,
mobileTabActive,
mobileTabTitle,
openGeneralFeedback,
openWorkspaceSection,
navigateToApplications,
navigateToUpdates,
showKnowledgeBaseAccessDenied,
navigateToKnowledgeBase,
navigateToScheduleRuns,
navigateToShippingNotice,
navigateToProfile,
navigateToGeneralChat,
openAdminPanel,
navigateToChat,
navigateWithQuickQuestion,
redirectLegacyViewQuery,
handleRouteSideEffects,
handleWecomDeeplinkContext,
};
}
@@ -0,0 +1,190 @@
/**
* features/workspace/composables/useWorkspaceProfile.ts
* 个人中心:资料读取/编辑、主题偏好、修改密码。
*/
import { computed, ref } from 'vue';
import type { ThemePreference } from '@/composables/useTheme';
import { resolveCasdoorErrorMessage } from '@/utils/casdoor';
import { getAuthHeaders } from '@/utils/auth';
import { BusinessError, requestJson } from '@/api/client';
import { CHANGE_PASSWORD_ENABLED, type WorkspaceProfileForm } from '../types/workspace.types';
import type { WorkspaceDeps } from './workspace.deps';
export function useWorkspaceProfile(deps: WorkspaceDeps) {
const { t, locale, msg, setThemePreference, appliedTheme } = deps;
const isProfileLoading = ref(false);
const isProfileSaving = ref(false);
const isChangingPassword = ref(false);
const isProfileEditing = ref(false);
const showPasswordModal = ref(false);
const profileUser = ref<WorkspaceProfileForm>({
id: 0,
username: '',
real_name: '',
email: '',
phone_number: '',
department: '',
role: '',
employee_id: '',
language: 'zh-CN',
theme_preference: 'system' as ThemePreference,
});
const originalProfile = ref<WorkspaceProfileForm | null>(null);
const passwordForm = ref({ current: '', new: '', confirm: '' });
const themeOptions: Array<{ value: ThemePreference; label: () => string }> = [
{ value: 'light', label: () => t('theme.light') || 'Light' },
{ value: 'dark', label: () => t('theme.dark') || 'Dark' },
{ value: 'system', label: () => t('theme.system') || 'Follow System' },
];
const hasProfileUnsavedChanges = computed(() => {
if (!originalProfile.value) return false;
return (
profileUser.value.real_name !== originalProfile.value.real_name ||
profileUser.value.phone_number !== originalProfile.value.phone_number ||
profileUser.value.language !== originalProfile.value.language ||
profileUser.value.theme_preference !== originalProfile.value.theme_preference ||
profileUser.value.email !== originalProfile.value.email ||
profileUser.value.employee_id !== originalProfile.value.employee_id ||
profileUser.value.department !== originalProfile.value.department
);
});
const captureOriginalProfile = () => {
originalProfile.value = { ...profileUser.value };
};
const handleChangePasswordClick = () => {
if (!CHANGE_PASSWORD_ENABLED) {
msg.warning(t('profile.changePasswordContactAdmin'));
return;
}
showPasswordModal.value = true;
};
const fetchProfile = async () => {
isProfileLoading.value = true;
try {
const data = await requestJson<Partial<WorkspaceProfileForm>>('/api/user/profile', {
headers: getAuthHeaders(),
});
if (!data) {
msg.error(t('workspace.profile.msg.loadFailed'));
return;
}
profileUser.value = { ...profileUser.value, ...data };
if (data.language) locale.value = data.language;
if (data.theme_preference) {
setThemePreference(data.theme_preference);
} else {
profileUser.value.theme_preference = appliedTheme.value;
}
captureOriginalProfile();
isProfileEditing.value = false;
} catch (e) {
console.error(e);
msg.error(t('workspace.profile.msg.loadFailed'));
} finally {
isProfileLoading.value = false;
}
};
const startProfileEditing = () => {
isProfileEditing.value = true;
};
const cancelProfileEditing = () => {
if (originalProfile.value) {
profileUser.value = { ...originalProfile.value };
locale.value = profileUser.value.language;
setThemePreference(profileUser.value.theme_preference);
}
isProfileEditing.value = false;
};
const saveProfile = async () => {
if (!hasProfileUnsavedChanges.value) {
isProfileEditing.value = false;
return;
}
const payload = {
real_name: profileUser.value.real_name,
phone_number: profileUser.value.phone_number,
language: profileUser.value.language,
theme_preference: profileUser.value.theme_preference,
email: profileUser.value.email,
employee_id: profileUser.value.employee_id,
department: profileUser.value.department,
};
locale.value = profileUser.value.language;
setThemePreference(profileUser.value.theme_preference);
try {
isProfileSaving.value = true;
await requestJson('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
msg.success(t('workspace.profile.msg.saved'));
captureOriginalProfile();
isProfileEditing.value = false;
} catch (e) {
console.error(e);
msg.error((e as Error)?.message || t('workspace.profile.msg.saveFailed'));
} finally {
isProfileSaving.value = false;
}
};
const handleChangePassword = async () => {
if (isChangingPassword.value) return;
if (passwordForm.value.new !== passwordForm.value.confirm) {
msg.warning(t('profile.passwordMismatch') || 'Passwords do not match');
return;
}
try {
isChangingPassword.value = true;
await requestJson('/api/user/change-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
current_password: passwordForm.value.current,
new_password: passwordForm.value.new,
}),
});
msg.success(t('profile.passwordChanged') || 'Password changed successfully');
passwordForm.value = { current: '', new: '', confirm: '' };
showPasswordModal.value = false;
} catch (e) {
console.error(e);
msg.error(
resolveCasdoorErrorMessage(e as BusinessError, t) || t('workspace.profile.msg.changePasswordFailed'),
);
} finally {
isChangingPassword.value = false;
}
};
return {
isProfileLoading,
isProfileSaving,
isChangingPassword,
isProfileEditing,
showPasswordModal,
CHANGE_PASSWORD_ENABLED,
handleChangePasswordClick,
profileUser,
originalProfile,
passwordForm,
themeOptions,
hasProfileUnsavedChanges,
captureOriginalProfile,
fetchProfile,
startProfileEditing,
cancelProfileEditing,
saveProfile,
handleChangePassword,
};
}
@@ -0,0 +1,126 @@
/**
* features/workspace/composables/useWorkspaceSchedule.ts
* 排程记录:筛选条件、列表加载、状态展示与 Excel 下载。
*/
import { ref } from 'vue';
import { getAuthHeaders } from '@/utils/auth';
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '@/api/schedule';
import { WS_SCHEDULE_FILTER_INPUT_CLASS } from '../types/workspace.types';
import type { WorkspaceDeps } from './workspace.deps';
export function useWorkspaceSchedule(deps: WorkspaceDeps) {
const { t, msg } = deps;
const workspaceScheduleRuns = ref<ScheduleRun[]>([]);
const workspaceScheduleLoading = ref(false);
const wsScheduleStatusFilter = ref('all');
const wsScheduleNameFilter = ref('');
const toDateTimeLocalValue = (date: Date) => {
const pad = (n: number) => String(n).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};
const todayStartLocal = () => {
const d = new Date();
d.setHours(0, 0, 0, 0);
return toDateTimeLocalValue(d);
};
const todayEndLocal = () => {
const d = new Date();
d.setHours(23, 59, 59, 0);
return toDateTimeLocalValue(d);
};
const wsScheduleStartedAfter = ref(todayStartLocal());
const wsScheduleStartedBefore = ref(todayEndLocal());
const wsScheduleStatusOptions = [
{ value: 'all', label: t('workspace.schedule.status.all') },
{ value: 'success', label: t('workspace.schedule.status.success') },
{ value: 'partial_failed', label: t('workspace.schedule.status.partialFailed') },
{ value: 'failed', label: t('workspace.schedule.status.failed') },
{ value: 'running', label: t('workspace.schedule.status.running') },
];
const getWsScheduleStatusBadge = (status: string) => {
const map: Record<string, { cls: string; label: string }> = {
success: { cls: 'bg-emerald-100 text-emerald-700', label: t('workspace.schedule.status.success') },
partial_failed: { cls: 'bg-blue-100 text-blue-700', label: t('workspace.schedule.status.partialFailed') },
failed: { cls: 'bg-rose-100 text-rose-700', label: t('workspace.schedule.status.failed') },
running: { cls: 'bg-amber-100 text-amber-700', label: t('workspace.schedule.status.running') },
queued: { cls: 'bg-slate-100 text-secondary', label: t('workspace.schedule.status.queued') },
};
return map[status] || { cls: 'bg-slate-100 text-secondary', label: status };
};
const formatDateTime = (iso?: string | null) => {
if (!iso) return '-';
const d = new Date(iso);
if (isNaN(d.getTime())) return iso;
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
const loadWorkspaceScheduleRuns = async () => {
workspaceScheduleLoading.value = true;
try {
const params: { status?: string; schedule_name?: string; started_after?: string; started_before?: string } = {};
if (wsScheduleStatusFilter.value !== 'all') params.status = wsScheduleStatusFilter.value;
if (wsScheduleNameFilter.value.trim()) params.schedule_name = wsScheduleNameFilter.value.trim();
if (wsScheduleStartedAfter.value) params.started_after = new Date(wsScheduleStartedAfter.value).toISOString();
if (wsScheduleStartedBefore.value) params.started_before = new Date(wsScheduleStartedBefore.value).toISOString();
workspaceScheduleRuns.value = await listWorkspaceScheduleRuns(params);
} catch {
workspaceScheduleRuns.value = [];
} finally {
workspaceScheduleLoading.value = false;
}
};
const resetWsScheduleFilters = () => {
wsScheduleStatusFilter.value = 'all';
wsScheduleNameFilter.value = '';
wsScheduleStartedAfter.value = todayStartLocal();
wsScheduleStartedBefore.value = todayEndLocal();
void loadWorkspaceScheduleRuns();
};
const downloadWsScheduleExcel = async (runId: number) => {
const res = await fetch(workspaceRunExcelUrl(runId), { headers: getAuthHeaders() });
if (!res.ok) {
msg.error(t('workspace.schedule.msg.downloadExcelFailed'));
return;
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
const disposition = res.headers.get('content-disposition');
a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'result.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
return {
wsScheduleFilterInputClass: WS_SCHEDULE_FILTER_INPUT_CLASS,
workspaceScheduleRuns,
workspaceScheduleLoading,
wsScheduleStatusFilter,
wsScheduleNameFilter,
toDateTimeLocalValue,
todayStartLocal,
todayEndLocal,
wsScheduleStartedAfter,
wsScheduleStartedBefore,
wsScheduleStatusOptions,
getWsScheduleStatusBadge,
formatDateTime,
loadWorkspaceScheduleRuns,
resetWsScheduleFilters,
downloadWsScheduleExcel,
};
}
@@ -0,0 +1,88 @@
/**
* features/workspace/composables/useWorkspaceSession.ts
* 登录态:当前用户、知识库权限判断、登出与 401 清理。
*/
import { computed, type Ref } from 'vue';
import { logoutAuth, getStoredAuthUser } from '@/utils/auth';
import { KB_ACCESS_DENIED_MESSAGE } from '../types/workspace.types';
import type { WorkspaceUser } from '../types/workspace.types';
import type { WorkspaceDeps } from './workspace.deps';
interface SessionOptions {
currentUser: Ref<WorkspaceUser | null>;
clearHome: () => void;
}
export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions) {
const { router } = deps;
const { currentUser } = options;
const isLoggedIn = computed(() => !!currentUser.value && currentUser.value.role !== 'guest');
const hasKnowledgeBaseAccess = computed(
() => String(currentUser.value?.username || '').trim().toLowerCase() === 'admin',
);
const loadAuthUser = () => {
let stored = localStorage.getItem('hxops_user');
if (stored) {
try {
const parsed = JSON.parse(stored);
if (parsed.expiry && new Date().getTime() > parsed.expiry) {
localStorage.removeItem('hxops_user');
stored = null;
}
} catch {
// ignore
}
}
if (!stored) {
stored = sessionStorage.getItem('hxops_user');
}
if (!stored) {
currentUser.value = null;
return;
}
try {
const user = getStoredAuthUser();
if (!user) return;
currentUser.value = {
id: user.id || 0,
username: user.username || '',
role: user.role || 'user',
};
} catch {
localStorage.removeItem('hxops_user');
sessionStorage.removeItem('hxops_user');
}
};
const applyLoggedOutState = () => {
currentUser.value = null;
options.clearHome();
};
const handleLogout = () => {
logoutAuth();
applyLoggedOutState();
router.push('/login');
};
const onAuthLogout = () => {
applyLoggedOutState();
};
return {
currentUser,
isLoggedIn,
hasKnowledgeBaseAccess,
KB_ACCESS_DENIED_MESSAGE,
loadAuthUser,
applyLoggedOutState,
handleLogout,
onAuthLogout,
};
}
@@ -0,0 +1,10 @@
/**
* features/workspace/composables/workspace.context.ts
* 工作台 provide/inject 上下文类型与注入 key。
*/
import type { InjectionKey } from 'vue';
import type { useWorkspace } from './useWorkspace';
export type WorkspaceContext = ReturnType<typeof useWorkspace>;
export const WORKSPACE_KEY: InjectionKey<WorkspaceContext> = Symbol('workspace');
@@ -0,0 +1,19 @@
/**
* features/workspace/composables/workspace.deps.ts
* 工作台 composables 共享依赖(i18n、路由、主题、消息等)。
*/
import type { ComputedRef, WritableComputedRef } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import type { useMessage } from '@/composables/useMessage';
import type { ThemePreference } from '@/composables/useTheme';
export interface WorkspaceDeps {
t: ComposerTranslation;
locale: WritableComputedRef<string>;
msg: ReturnType<typeof useMessage>;
router: Router;
route: RouteLocationNormalizedLoaded;
setThemePreference: (pref: ThemePreference) => void;
appliedTheme: ComputedRef<ThemePreference>;
}
@@ -0,0 +1,32 @@
/**
* features/workspace/constants/routes.ts
* 工作台子路由 path 常量,以及旧 ?view= 查询参数到新 path 的映射。
*/
export const WORKSPACE_PATHS = {
root: '/workspace',
profile: '/workspace/profile',
applications: '/workspace/applications',
updates: '/workspace/updates',
knowledgeBase: '/workspace/knowledge-base',
scheduleRuns: '/workspace/schedule-runs',
shippingNotice: '/workspace/shipping-notice',
feedback: '/workspace/feedback',
history: '/workspace/history',
} as const;
/** 旧 ?view= 参数 → 子路由 path */
export const LEGACY_VIEW_TO_PATH: Record<string, string> = {
profile: WORKSPACE_PATHS.profile,
applications: WORKSPACE_PATHS.applications,
feedback: WORKSPACE_PATHS.feedback,
updates: WORKSPACE_PATHS.updates,
knowledge_base: WORKSPACE_PATHS.knowledgeBase,
schedule_runs: WORKSPACE_PATHS.scheduleRuns,
shipping_notice: WORKSPACE_PATHS.shippingNotice,
history: WORKSPACE_PATHS.history,
};
export function workspacePathFromLegacyView(view?: string): string {
if (!view) return WORKSPACE_PATHS.applications;
return LEGACY_VIEW_TO_PATH[view] || WORKSPACE_PATHS.applications;
}
+8
View File
@@ -0,0 +1,8 @@
/**
* features/workspace/index.ts
* 工作台 feature 对外导出:编排 composable、inject key、路由常量。
*/
export { useWorkspace } from './composables/useWorkspace';
export { WORKSPACE_KEY } from './composables/workspace.context';
export type { WorkspaceContext } from './composables/workspace.context';
export { WORKSPACE_PATHS, workspacePathFromLegacyView } from './constants/routes';
@@ -0,0 +1,12 @@
<script setup lang="ts">
/**
* features/workspace/pages/FeedbackPage.vue
* 意见反馈占位页;进入路由时由编排层打开 GeneralFeedbackDialog。
*/
</script>
<template>
<div class="flex flex-col items-center justify-center py-20 text-muted">
<p class="text-sm">{{ $t('workspace.nav.feedback') }}</p>
</div>
</template>
@@ -0,0 +1,10 @@
<script setup lang="ts">
/**
* @deprecated 请使用 @/features/chat/pages/HistoryPage.vue
*/
import HistoryPage from '@/features/chat/pages/HistoryPage.vue';
</script>
<template>
<HistoryPage />
</template>
@@ -0,0 +1,192 @@
<script setup lang="ts">
/**
* features/workspace/pages/HomePage.vue
* 应用管理 / 最近更新:收藏应用、快捷问题、嵌入 Agent、公告与应用列表。
*/
import { inject } from 'vue';
import {
LayoutGrid, Star, GripVertical, Plus, Trash2, Edit, ExternalLink,
Bot, Megaphone, ChevronDown, ChevronUp,
} from 'lucide-vue-next';
import { WORKSPACE_KEY } from '../composables/workspace.context';
const ws = inject(WORKSPACE_KEY)! as any;
</script>
<template>
<div v-if="ws.wecomEntryHint" class="rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
{{ ws.wecomEntryHint }}
</div>
<div
v-for="(section, index) in ws.layoutSections"
:id="`workspace-section-${section.id}`"
:key="section.id"
class="bg-transparent md:bg-surface md:rounded-3xl md:border md:border-subtle md:p-8 md:shadow-soft relative group transition-all scroll-mt-6"
:class="{ 'opacity-50 border-brand-300 border-dashed': ws.draggedSectionIndex === index }"
draggable="true"
@dragstart="ws.onDragStart(index)"
@dragover="ws.onDragOver"
@drop="ws.onDrop(index)"
>
<div class="absolute left-2 top-8 cursor-move opacity-0 group-hover:opacity-100 p-2 text-slate-300 hover:text-muted transition-opacity hidden md:block">
<GripVertical class="w-5 h-5" />
</div>
<div class="md:pl-6">
<div class="flex justify-between items-center mb-6">
<h2 class="text-lg md:text-xl font-semibold text-primary flex items-center gap-2.5 cursor-pointer select-none" @click="ws.toggleSectionCollapse(section)">
<div class="p-2 rounded-lg" :class="{
'bg-emerald-50 text-emerald-600': section.id === 'announcements',
'bg-yellow-50 text-yellow-600': section.id === 'favorites',
'bg-brand-50 text-brand-600': section.id === 'quick_questions',
'bg-purple-50 text-purple-600': section.id === 'embedded',
'bg-slate-100 text-secondary': section.id === 'all_agents'
}">
<component :is="section.id === 'announcements' ? Megaphone : (section.id === 'favorites' ? Star : (section.id === 'embedded' ? Bot : LayoutGrid))" class="w-5 h-5" />
</div>
{{ $t(ws.getSectionTitleKey(section.id)) }}
<component :is="section.collapsed ? ChevronDown : ChevronUp" class="w-4 h-4 text-muted" />
</h2>
<button v-if="section.id === 'quick_questions' && !ws.isAddingQuestion && !section.collapsed" @click="ws.openAddQuestionForm" class="btn-ghost text-sm text-brand-600 hover:text-brand-700 hover:bg-brand-50">
<Plus class="w-4 h-4" /> {{ $t('workspace.quickQuestions.add') }}
</button>
</div>
<div v-show="!section.collapsed" class="animate-fade-in">
<!-- Content: Announcements -->
<div v-if="section.id === 'announcements'">
<div v-if="ws.announcements.length === 0" class="text-muted text-sm italic py-8 text-center bg-surface-soft rounded-xl border border-dashed border-default">{{ $t('workspace.announcements.noData') }}</div>
<div v-else class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
<div
v-for="ann in ws.announcements"
:key="ann.id"
class="group border border-default rounded-2xl bg-surface p-5 hover:border-emerald-300 hover:shadow-md transition-all cursor-pointer"
@click="ws.openAnnouncement(ann)"
>
<div class="flex items-start justify-between gap-3 mb-2">
<h4 class="font-bold text-primary line-clamp-2 group-hover:text-emerald-700 transition-colors">{{ ann.title }}</h4>
<span class="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full whitespace-nowrap">{{ new Date(ann.created_at).toLocaleDateString() }}</span>
</div>
<p class="text-sm text-secondary line-clamp-3">{{ ann.content }}</p>
</div>
</div>
</div>
<!-- Content: Favorites -->
<div v-if="section.id === 'favorites'">
<div v-if="ws.favoriteAgents.length === 0" class="text-muted text-sm italic py-4 bg-surface-soft rounded-xl text-center border border-dashed border-default">{{ $t('workspace.noFavorites') }}</div>
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-6">
<div v-for="agent in ws.favoriteAgents" :key="agent.id" @click="ws.navigateToChat(agent.id)"
class="card p-4 sm:p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:shadow-lg hover:border-brand-200 bg-gradient-to-br from-white to-slate-50/50">
<div class="w-8 h-8 sm:w-12 sm:h-12 bg-brand-100 rounded-xl flex items-center justify-center text-brand-600 mb-3 sm:mb-4 shadow-sm group-hover/card:scale-110 transition-transform duration-300">
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-5 h-5 sm:w-7 sm:h-7" />
<Bot v-else class="w-5 h-5 sm:w-7 sm:h-7" />
</div>
<div class="text-[15px] sm:text-base font-semibold text-primary mb-1 group-hover/card:text-brand-700 transition-colors truncate">{{ agent.name }}</div>
<div class="text-[13px] sm:text-xs text-muted truncate">{{ agent.description }}</div>
<button @click.stop="ws.toggleFavorite(agent.id)" class="absolute top-3 right-3 text-yellow-400 hover:text-yellow-500 hover:scale-110 transition-all opacity-0 group-hover/card:opacity-100">
<Star class="w-5 h-5 fill-current" />
</button>
</div>
</div>
</div>
<!-- Content: Quick Questions -->
<div v-if="section.id === 'quick_questions'">
<!-- Add Question Form -->
<div v-if="ws.isAddingQuestion" class="mb-6 p-6 bg-surface-soft border border-default rounded-2xl space-y-4 animate-fade-in">
<h3 class="font-bold text-primary">{{ ws.editingQuestionId ? $t('workspace.quickQuestions.edit') : $t('workspace.quickQuestions.addNew') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-muted uppercase">{{ $t('workspace.quickQuestions.fields.title') }}</label>
<input v-model="ws.newQuestion.title" class="input-field" :placeholder="$t('workspace.quickQuestions.fields.titlePlaceholder')" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-muted uppercase">{{ $t('workspace.quickQuestions.fields.targetAgent') }}</label>
<select v-model="ws.newQuestion.agent_id" class="input-field" :disabled="ws.agents.length === 0">
<option :value="null" disabled>{{ ws.agents.length === 0 ? $t('workspace.noAgents') : $t('workspace.quickQuestions.fields.selectAgent') }}</option>
<option v-for="agent in ws.agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
</select>
</div>
<div class="col-span-1 md:col-span-2 space-y-1.5">
<label class="text-xs font-semibold text-muted uppercase">{{ $t('workspace.quickQuestions.fields.content') }}</label>
<textarea v-model="ws.newQuestion.question" rows="3" class="input-field" :placeholder="$t('workspace.quickQuestions.fields.contentPlaceholder')"></textarea>
</div>
</div>
<div class="flex justify-end gap-3 pt-2">
<button @click="ws.cancelAddQuestion" class="btn-secondary">{{ $t('workspace.cancel') }}</button>
<button @click="ws.saveQuickQuestion" class="btn-primary">{{ $t('workspace.save') }}</button>
</div>
</div>
<div v-if="ws.filteredQuickQuestions.length === 0 && !ws.isAddingQuestion" class="text-muted text-sm italic py-8 text-center bg-surface-soft rounded-xl border border-dashed border-default">{{ $t('workspace.quickQuestions.noDefined') }}</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<div v-for="qq in ws.filteredQuickQuestions" :key="qq.id"
@click="ws.navigateWithQuickQuestion(qq.agent_id, qq.question)"
class="group/item p-4 bg-surface border border-default rounded-xl hover:border-brand-500 hover:shadow-md transition-all cursor-pointer flex flex-col gap-3 relative h-full">
<div class="flex justify-between items-start">
<h4 class="font-bold text-primary group-hover/item:text-brand-600 transition-colors">{{ qq.title }}</h4>
<span class="text-[10px] font-bold px-2 py-0.5 bg-slate-100 text-secondary rounded-full uppercase tracking-wide">
{{ ws.getAgentName(qq.agent_id) }}
</span>
</div>
<p class="text-sm text-secondary line-clamp-2 leading-relaxed">{{ qq.question }}</p>
<div class="absolute top-2 right-2 flex gap-1 opacity-0 group-hover/item:opacity-100 transition-opacity bg-surface/90 backdrop-blur-sm p-1 rounded-lg">
<button @click.stop="ws.editQuickQuestion(qq)" class="p-1.5 rounded-lg text-muted hover:text-brand-600 hover:bg-brand-50 transition-colors">
<Edit class="w-4 h-4" />
</button>
<button @click.stop="ws.removeQuickQuestion(qq.id)" class="p-1.5 rounded-lg text-muted hover:text-red-600 hover:bg-red-50 transition-colors">
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
</div>
</div>
<!-- Content: Embedded Agents -->
<div v-if="section.id === 'embedded'">
<div v-if="ws.embeddedAgents.length === 0" class="text-muted text-sm italic py-4 bg-surface-soft rounded-xl text-center border border-dashed border-default">{{ $t('workspace.embedded.noData') }}</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div v-for="agent in ws.embeddedAgents" :key="agent.id" class="border border-default rounded-2xl overflow-hidden bg-surface shadow-sm hover:shadow-md transition-shadow h-[500px] flex flex-col">
<div class="bg-surface-soft px-4 py-3 text-sm font-bold text-secondary flex justify-between items-center border-b border-subtle">
<span>{{ agent.name }}</span>
<a :href="`/chat/${agent.id}`" target="_blank" class="text-brand-600 hover:text-brand-700 hover:bg-brand-50 p-1.5 rounded-lg transition-colors"><ExternalLink class="w-4 h-4"/></a>
</div>
<iframe v-if="agent.iframe_url" :src="agent.iframe_url" class="w-full flex-1 border-none bg-surface"></iframe>
<div v-else class="flex items-center justify-center flex-1 text-muted bg-surface-soft/50">{{ $t('workspace.embedded.noUrl') }}</div>
</div>
</div>
</div>
<!-- Content: All Agents -->
<div v-if="section.id === 'all_agents'">
<div class="mb-6">
<input v-model="ws.searchQuery" type="text" :placeholder="$t('workspace.search')" class="input-field max-w-md shadow-sm" />
</div>
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-6">
<div v-for="agent in ws.otherAgents" :key="agent.id"
@click="ws.navigateToChat(agent.id)"
class="card card-mobile-compact cursor-pointer relative group/card hover:-translate-y-1 hover:border-brand-200">
<div class="flex items-start justify-between mb-2 sm:mb-4">
<div class="w-8 h-8 sm:w-10 sm:h-10 bg-surface-soft rounded-xl flex items-center justify-center text-muted group-hover/card:bg-brand-50 group-hover/card:text-brand-600 transition-colors">
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-4 h-4 sm:w-6 sm:h-6" />
<Bot v-else class="w-4 h-4 sm:w-6 sm:h-6" />
</div>
<button @click.stop="ws.toggleFavorite(agent.id)" class="text-slate-200 hover:text-yellow-400 transition-colors">
<Star class="w-5 h-5" :class="{ 'fill-yellow-400 text-yellow-400': ws.favoriteAgentIds.includes(agent.id) }" />
</button>
</div>
<h3 class="text-[15px] sm:text-base font-semibold text-primary mb-1 group-hover/card:text-brand-700 transition-colors line-clamp-1 sm:line-clamp-2 leading-tight">{{ agent.name }}</h3>
<p class="text-[13px] sm:text-xs text-muted line-clamp-1 sm:line-clamp-2 h-4 sm:h-8 leading-relaxed">{{ agent.description }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,11 @@
<script setup lang="ts">
/**
* features/workspace/pages/KnowledgeBasePage.vue
* 知识库管理嵌入页,复用 KbWorkspaceView 的 embedded 模式。
*/
import KbWorkspaceView from '@/views/KbWorkspaceView.vue';
</script>
<template>
<KbWorkspaceView :embedded="true" />
</template>
@@ -0,0 +1,199 @@
<script setup lang="ts">
/**
* features/workspace/pages/ProfilePage.vue
* 个人中心:用户资料展示与编辑、语言/主题偏好、修改密码入口。
*/
import { inject } from 'vue';
import {
User, Mail, Building, CreditCard, Globe, Save, Palette,
} from 'lucide-vue-next';
import { WORKSPACE_KEY } from '../composables/workspace.context';
const ws = inject(WORKSPACE_KEY)! as any;
</script>
<template>
<div v-if="ws.isProfileLoading" class="flex justify-center py-20">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
<div v-else class="space-y-6">
<div class="rounded-3xl border border-default bg-surface px-6 py-6 shadow-sm md:px-8">
<div class="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
<div class="flex flex-1 flex-col gap-6 sm:flex-row sm:items-center sm:justify-start">
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600" :class="ws.isMobile ? 'h-14 w-14 text-2xl' : ''">
{{ (ws.profileUser.real_name || ws.profileUser.username || 'U').charAt(0).toUpperCase() }}
</div>
<div class="grid flex-1 text-left" :class="ws.isMobile ? 'grid-cols-2 gap-x-4 gap-y-1' : 'grid-cols-1 gap-x-12 gap-y-3 sm:grid-cols-2'">
<div :class="ws.isMobile ? '' : ''">
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.realName') : (ws.profileUser.username || '-') }}</div>
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.real_name || ws.profileUser.username || '-' }}</div>
</div>
<div>
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.employeeId') : (ws.profileUser.employee_id || '-') }}</div>
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.employee_id || '-' }}</div>
</div>
<div>
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.department') : (ws.profileUser.department || '-') }}</div>
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.department || '-' }}</div>
</div>
<div>
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.role') : (ws.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User')) }}</div>
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User') }}</div>
</div>
<div :class="ws.isMobile ? 'col-span-2' : 'sm:col-span-2'">
<div :class="ws.isMobile ? 'text-xs text-muted' : 'break-all text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.email') : (ws.profileUser.email || '-') }}</div>
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.email || '-' }}</div>
</div>
</div>
</div>
<div v-if="!ws.isMobile" class="flex shrink-0 items-center gap-2 self-start lg:ml-6">
<button @click="ws.handleChangePasswordClick" class="btn-primary px-6 py-3 text-base">
{{ $t('profile.changePassword') }}
</button>
</div>
</div>
<div v-if="ws.isMobile" class="mt-4 flex items-center justify-center gap-4">
<button @click="ws.handleChangePasswordClick" class="btn-primary flex-1 py-2.5 text-sm text-center">
{{ $t('profile.changePassword') }}
</button>
<button @click="ws.handleLogout" class="btn-secondary flex-1 py-2.5 text-sm text-center text-red-600 hover:bg-red-50">
{{ $t('workspace.nav.logout') }}
</button>
</div>
</div>
<div class="space-y-6">
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm" :class="ws.isMobile ? 'p-4' : ''">
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between" :class="ws.isMobile ? 'mb-4 gap-2' : ''">
<div class="flex items-center" :class="ws.isMobile ? 'w-full justify-center gap-2' : ''">
<h3 class="flex items-center gap-3 text-3xl font-bold text-primary" :class="ws.isMobile ? 'text-lg gap-2' : ''">
<User class="h-6 w-6 text-brand-500" :class="ws.isMobile ? 'h-4 w-4' : ''" />
{{ $t('profile.basicInfo') }}
</h3>
<button v-if="ws.isMobile && !ws.isProfileEditing" @click="ws.startProfileEditing" class="btn-secondary px-3 py-1 text-xs">
{{ $t('profile.edit') }}
</button>
</div>
<p v-if="!ws.isMobile" class="mt-2 text-sm text-muted">
{{ ws.isProfileEditing ? $t('profile.directEditHint') : $t('profile.switchEditHint') }}
</p>
<div v-if="!ws.isMobile" class="flex items-center gap-2">
<button v-if="!ws.isProfileEditing" @click="ws.startProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
{{ $t('profile.edit') }}
</button>
<template v-else>
<button @click="ws.cancelProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
{{ $t('profile.cancel') || 'Cancel' }}
</button>
<button
@click="ws.saveProfile"
:disabled="ws.isProfileSaving || !ws.hasProfileUnsavedChanges"
class="btn-primary px-5 py-2.5 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
>
<Save class="w-4 h-4" />
<span>{{ ws.isProfileSaving ? $t('profile.saving') : $t('workspace.save') }}</span>
</button>
</template>
</div>
</div>
<div class="grid grid-cols-1 gap-5 md:grid-cols-2" :class="ws.isMobile ? 'gap-3' : ''">
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
<User class="h-4 w-4" /> {{ $t('profile.username') }}
</label>
<div class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ ws.profileUser.username || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
<CreditCard class="h-4 w-4" /> {{ $t('profile.employeeId') }}
</label>
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.employee_id" type="text" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ ws.profileUser.employee_id || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
<User class="h-4 w-4" /> {{ $t('profile.realName') }}
</label>
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.real_name" type="text" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ ws.profileUser.real_name || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
<Building class="h-4 w-4" /> {{ $t('profile.department') }}
</label>
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.department" type="text" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ ws.profileUser.department || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
<Mail class="h-4 w-4" /> {{ $t('profile.email') }}
</label>
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.email" type="email" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ ws.profileUser.email || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
<Globe class="h-4 w-4" /> {{ $t('profile.phoneNumber') }}
</label>
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.phone_number" type="text" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ ws.profileUser.phone_number || '-' }}
</div>
</div>
</div>
</div>
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm">
<h3 class="mb-6 flex items-center gap-3 text-2xl font-bold text-primary">
<Palette class="h-5 w-5 text-brand-500" />
{{ $t('profile.preferences') }}
</h3>
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('workspace.languageLabel') }}</label>
<select v-model="ws.profileUser.language" :disabled="!ws.isProfileEditing" class="input-field h-[58px]">
<option value="en">English</option>
<option value="zh-CN">{{ $t('workspace.lang.zhCN') }}</option>
<option value="zh-TW">{{ $t('workspace.lang.zhTW') }}</option>
<option value="th">ไทย</option>
</select>
</div>
<div>
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('profile.theme') }}</label>
<div
class="segment-control segment-control--cols-3 segment-control--md"
role="radiogroup"
:aria-label="$t('profile.theme')"
>
<button
v-for="item in ws.themeOptions"
:key="item.value"
type="button"
role="radio"
:aria-checked="ws.profileUser.theme_preference === item.value"
:disabled="!ws.isProfileEditing"
class="segment-item"
:class="ws.profileUser.theme_preference === item.value ? 'segment-item--active' : ''"
@click="ws.profileUser.theme_preference = item.value"
>
{{ item.label() }}
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,116 @@
<script setup lang="ts">
/**
* features/workspace/pages/ScheduleRunsPage.vue
* 排程执行记录:筛选、列表展示与结果 Excel 下载。
*/
import { inject } from 'vue';
import { RefreshCw, Search, Download } from 'lucide-vue-next';
import { WORKSPACE_KEY } from '../composables/workspace.context';
const ws = inject(WORKSPACE_KEY)! as any;
</script>
<template>
<div class="space-y-5 animate-fade-in-up">
<div class="flex items-center justify-between">
<h2 class="text-2xl font-bold text-primary">{{ $t('workspace.schedule.title') }}</h2>
<button
@click="ws.loadWorkspaceScheduleRuns"
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('workspace.schedule.refresh') }}
</button>
</div>
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default/80 bg-surface/70 px-4 py-3 shadow-sm">
<div>
<label class="mb-1 block text-xs font-medium text-muted">{{ $t('workspace.schedule.filters.name') }}</label>
<input type="text" v-model="ws.wsScheduleNameFilter" :placeholder="$t('workspace.schedule.filters.namePlaceholder')" :class="['!w-[150px]', ws.wsScheduleFilterInputClass]" />
</div>
<div>
<label class="mb-1 block text-xs font-medium text-muted">{{ $t('workspace.schedule.filters.start') }}</label>
<input type="datetime-local" step="1" v-model="ws.wsScheduleStartedAfter" :class="['!w-[170px]', ws.wsScheduleFilterInputClass]" />
</div>
<div>
<label class="mb-1 block text-xs font-medium text-muted">{{ $t('workspace.schedule.filters.end') }}</label>
<input type="datetime-local" step="1" v-model="ws.wsScheduleStartedBefore" :class="['!w-[170px]', ws.wsScheduleFilterInputClass]" />
</div>
<div>
<label class="mb-1 block text-xs font-medium text-muted">{{ $t('workspace.schedule.filters.status') }}</label>
<select v-model="ws.wsScheduleStatusFilter" :class="['!w-[120px]', ws.wsScheduleFilterInputClass]">
<option v-for="o in ws.wsScheduleStatusOptions" :key="o.value" :value="o.value">{{ o.label }}</option>
</select>
</div>
<button
@click="ws.loadWorkspaceScheduleRuns"
class="inline-flex items-center gap-1 rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-brand-700"
>
<Search class="h-3.5 w-3.5" />
{{ $t('workspace.schedule.search') }}
</button>
<button
@click="ws.resetWsScheduleFilters"
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
>
{{ $t('workspace.schedule.reset') }}
</button>
</div>
<div v-if="ws.workspaceScheduleLoading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">{{ $t('workspace.schedule.loading') }}</div>
<div v-else-if="ws.workspaceScheduleRuns.length === 0" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">{{ $t('workspace.schedule.empty') }}</div>
<div v-else class="overflow-hidden rounded-2xl border border-default bg-surface">
<div class="max-h-[calc(100vh-17rem)] overflow-auto scrollbar-thin">
<table class="w-full min-w-[1080px] text-sm">
<thead class="sticky top-0 z-10">
<tr class="border-b border-subtle bg-surface-soft">
<th class="min-w-[120px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.name') }}</th>
<th class="min-w-[168px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.runNo') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.triggerType') }}</th>
<th class="min-w-[152px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.start') }}</th>
<th class="min-w-[152px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.end') }}</th>
<th class="min-w-[64px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.duration') }}</th>
<th class="min-w-[88px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.status') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.total') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.success') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.failed') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.detail') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="r in ws.workspaceScheduleRuns" :key="r.id" class="border-b border-slate-50 transition-colors hover:bg-surface-soft/50">
<td class="whitespace-nowrap px-4 py-3 font-medium text-primary">{{ r.schedule_name || '-' }}</td>
<td class="whitespace-nowrap px-4 py-3 font-mono text-xs text-muted">{{ r.run_no }}</td>
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ r.trigger_type === 'manual' ? $t('workspace.schedule.trigger.manual') : r.trigger_type === 'test' ? $t('workspace.schedule.trigger.test') : $t('workspace.schedule.trigger.timed') }}</td>
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ ws.formatDateTime(r.started_at) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ ws.formatDateTime(r.finished_at) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ r.duration_ms != null ? (r.duration_ms >= 1000 ? (r.duration_ms / 1000).toFixed(1) + 's' : r.duration_ms + 'ms') : '-' }}</td>
<td class="whitespace-nowrap px-4 py-3">
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold" :class="ws.getWsScheduleStatusBadge(r.status).cls">
{{ ws.getWsScheduleStatusBadge(r.status).label }}
</span>
<span v-if="r.error_message && r.error_message !== '无待处理数据'" class="ml-1 text-xs text-muted" :title="r.error_message">...</span>
<span v-else-if="r.error_message === '无待处理数据'" class="ml-1 text-xs text-muted">({{ $t('workspace.schedule.noPendingData') }})</span>
</td>
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ r.total_count || 0 }}</td>
<td class="whitespace-nowrap px-4 py-3 font-medium text-emerald-600">{{ r.success_count ?? 0 }}</td>
<td class="whitespace-nowrap px-4 py-3 font-medium text-rose-600">{{ r.failed_count ?? 0 }}</td>
<td class="whitespace-nowrap px-4 py-3">
<a
v-if="r.total_count > 0 && r.excel_file_name"
href="#"
@click.prevent="ws.downloadWsScheduleExcel(r.id)"
class="inline-flex items-center gap-1 rounded-lg border border-default px-2 py-1 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
>
<Download class="h-3 w-3" />
{{ $t('workspace.schedule.download') }}
</a>
<span v-else class="text-xs text-slate-300">-</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
@@ -0,0 +1,11 @@
<script setup lang="ts">
/**
* features/workspace/pages/ShippingNoticePage.vue
* 货代发货通知嵌入页,复用 ShippingNoticeView 的 embedded 模式。
*/
import ShippingNoticeView from '@/views/ShippingNoticeView.vue';
</script>
<template>
<ShippingNoticeView :embedded="true" />
</template>
@@ -0,0 +1,99 @@
/**
* features/workspace/types/workspace.types.ts
* 工作台相关 TypeScript 类型与业务常量。
*/
import type { ThemePreference } from '@/composables/useTheme';
import type { WecomMatchField } from '@/utils/wecom';
import type { WecomLoginDialogContent } from '@/utils/wecom';
export interface WorkspaceUser {
id: number;
username: string;
role: string;
default_agent_id?: number | null;
}
export type WorkspaceSidebarItem =
| 'profile'
| 'applications'
| 'feedback'
| 'updates'
| 'knowledge_base'
| 'schedule_runs'
| 'shipping_notice'
| 'history';
export interface WorkspaceAgent {
id: number;
name: string;
description: string;
icon_url?: string;
dify_app_type?: 'chatflow' | 'workflow';
}
export interface WorkspaceQuickQuestion {
id: number;
title: string;
question: string;
agent_id: number;
}
export interface WorkspaceEmbeddedAgent {
id: number;
name: string;
iframe_url?: string;
}
export interface WorkspaceLayoutSection {
id: string;
visible: boolean;
collapsed?: boolean;
title?: string;
}
export interface WorkspaceAnnouncement {
id: number;
title: string;
content: string;
created_at: string;
}
export interface WecomBindPromptState {
binding_token: string;
allowed_fields: WecomMatchField[];
wecom_name?: string;
field: WecomMatchField;
value: string;
submitting: boolean;
error: string;
}
export interface WorkspaceProfileForm {
id: number;
username: string;
real_name: string;
email: string;
phone_number: string;
department: string;
role: string;
employee_id: string;
language: string;
theme_preference: ThemePreference;
}
export type { ChatCrossAgentHistoryItem as WorkspaceChatHistoryItem } from '@/features/chat/types/chat.types';
export type { WecomLoginDialogContent };
export const SECTION_TITLE_KEY_MAP: Record<string, string> = {
announcements: 'workspace.announcements.title',
favorites: 'workspace.favorites',
quick_questions: 'workspace.quickQuestions.title',
embedded: 'workspace.embedded.title',
all_agents: 'workspace.availableAgents',
};
export const DEFAULT_POST_LOGIN_AGENT_ID = 16;
export const KB_ACCESS_DENIED_MESSAGE = '暂无权限,请登录admin账号操作知识库!';
export const WS_SCHEDULE_FILTER_INPUT_CLASS = 'admin-table-filter-input text-xs py-1.5 px-2';
export const CHANGE_PASSWORD_ENABLED = true;
@@ -0,0 +1,71 @@
<script setup lang="ts">
/**
* features/workspace/views/WorkspaceLayout.vue
* 工作台布局壳:初始化 composable、侧边栏、子路由出口与全局弹窗。
*/
import { provide } from 'vue';
import { LayoutGrid, Bot, User } from 'lucide-vue-next';
import { WORKSPACE_PATHS } from '../constants/routes';
import { useWorkspace } from '../composables/useWorkspace';
import { WORKSPACE_KEY } from '../composables/workspace.context';
import WorkspaceSidebar from '../components/WorkspaceSidebar.vue';
import WorkspaceModals from '../components/WorkspaceModals.vue';
const ws = useWorkspace();
provide(WORKSPACE_KEY, ws);
const mobileTabs = [
{ key: 'applications', path: WORKSPACE_PATHS.applications, icon: LayoutGrid, labelKey: 'workspace.mobileTabs.applications' },
{ key: 'history', path: WORKSPACE_PATHS.history, icon: Bot, labelKey: 'workspace.mobileTabs.history' },
{ key: 'profile', path: WORKSPACE_PATHS.profile, icon: User, labelKey: 'workspace.mobileTabs.me' },
] as const;
</script>
<template>
<div class="page-shell min-h-screen font-sans animate-fade-in">
<div v-if="ws.isLoading" class="animate-pulse p-8 space-y-8">
<div class="h-48 bg-surface-strong rounded-2xl"></div>
</div>
<div v-else>
<header v-if="ws.isMobile" class="sticky top-0 z-30 flex items-center justify-between border-b border-default bg-surface px-4 py-2.5">
<div class="flex items-center gap-2">
<button
type="button"
@click="ws.navigateToGeneralChat"
class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-purple-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20"
:title="$t('workspace.nav.backToChat')"
>
返
</button>
<span class="text-sm font-semibold text-primary">{{ ws.mobileTabTitle }}</span>
</div>
</header>
<div class="grid min-h-screen gap-0 lg:grid-cols-[232px_minmax(0,1fr)]">
<WorkspaceSidebar v-if="!ws.isMobile" />
<section class="ws-main" :class="ws.isMobile ? 'pb-20' : ''">
<RouterView />
</section>
</div>
<nav v-if="ws.isMobile" class="fixed bottom-0 left-0 right-0 z-40 border-t border-default bg-surface safe-bottom">
<div class="flex h-14 items-center justify-around">
<RouterLink
v-for="tab in mobileTabs"
:key="tab.key"
:to="tab.path"
class="flex flex-1 flex-col items-center justify-center gap-0.5 py-1 transition-colors"
:class="ws.mobileTabActive === tab.key ? 'text-brand-600' : 'text-muted'"
>
<component :is="tab.icon" class="h-5 w-5" />
<span class="text-[10px] font-medium">{{ $t(tab.labelKey) }}</span>
</RouterLink>
</div>
</nav>
</div>
<WorkspaceModals />
</div>
</template>
-109
View File
@@ -1,111 +1,2 @@
import { createRouter, createWebHistory } from 'vue-router';
import WorkspaceView from '../views/WorkspaceView.vue';
import ChatView from '../views/ChatView.vue';
import AdminView from '../views/AdminView.vue';
import ResetPasswordView from '../views/ResetPasswordView.vue';
import KbWorkspaceView from '../views/KbWorkspaceView.vue';
import ShippingNoticeView from '../views/ShippingNoticeView.vue';
import { config } from '../config';
import { getStoredAuthUser } from '../utils/auth';
const routes = [
{
path: '/',
name: 'Home',
component: WorkspaceView
},
{
path: '/workspace',
name: 'Workspace',
component: WorkspaceView
},
{
path: '/casdoor-callback',
name: 'CasdoorCallback',
component: WorkspaceView
},
{
path: '/reset-password',
name: 'ResetPassword',
component: ResetPasswordView
},
{
path: '/chat/:agentId',
name: 'Chat',
component: ChatView,
props: true
},
{
path: '/admin',
name: 'Admin',
component: AdminView
},
{
path: '/kb/workspace',
name: 'KbWorkspace',
component: KbWorkspaceView,
meta: { title: '知识库工作台' }
},
{
path: '/shipping-notice',
name: 'ShippingNotice',
component: ShippingNoticeView,
meta: { title: '货代发货通知' }
},
{
path: '/kb/admin',
redirect: { path: '/admin', query: { module: 'knowledge_base' } }
},
];
const router = createRouter({
history: createWebHistory(),
routes
});
const DEFAULT_CHAT_AGENT_ID = 16;
const publicPaths = ['/', '/workspace', '/casdoor-callback', '/reset-password'];
router.beforeEach((to, _from, next) => {
const user = getStoredAuthUser();
const isLoggedIn = !!user && user.role !== 'guest';
if (to.path === '/admin') {
if (!user || user.role !== 'admin') {
next('/workspace');
return;
}
}
if (to.path === '/') {
if (isLoggedIn) {
next(`/chat/${DEFAULT_CHAT_AGENT_ID}`);
return;
}
next('/workspace');
return;
}
if (!isLoggedIn && !publicPaths.includes(to.path)) {
next('/workspace');
return;
}
next();
});
router.afterEach((to) => {
const baseTitle = config.appTitle || 'AI工作台';
if (to.meta.title) {
document.title = `${to.meta.title} - ${baseTitle}`;
} else {
document.title = baseTitle;
}
});
/** @deprecated 请改用 `@/app/router`;保留此文件以兼容现有 import。 */
export { default } from '@/app/router';
+1 -1
View File
@@ -1,5 +1,5 @@
/** 无需登录即可访问的路由 path */
export const PUBLIC_PATHS = ['/', '/workspace', '/casdoor-callback', '/reset-password'] as const;
export const PUBLIC_PATHS = ['/', '/login', '/casdoor-callback', '/reset-password'] as const;
/** 登录后首页默认跳转的 Agent ID */
export const DEFAULT_CHAT_AGENT_ID = 16;
File diff suppressed because it is too large. Load diff