Build lightweight AI agent admin

This commit is contained in:
Codex
2026-06-08 18:14:59 +08:00
commit e164840f43
2530 changed files with 435693 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
import type {
ComponentRecordType,
GenerateMenuAndRoutesOptions,
} from '@vben/types';
import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';
import { ElMessage } from 'element-plus';
import { getAllMenusApi } from '#/api';
import { BasicLayout, IFrameView } from '#/layouts';
import { $t } from '#/locales';
import { useAppContextStore } from '#/store/app-context';
const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');
async function generateAccess(options: GenerateMenuAndRoutesOptions) {
const pageMap: ComponentRecordType = import.meta.glob([
'../views/**/*.vue',
'!../views/**/components/**',
'!../views/**/modules/**',
'!../views/ai-platform/workflow/editor/components/**/*.vue',
'!../views/ai-platform/workflow/editor/edges/**/*.vue',
'!../views/ai-platform/workflow/editor/nodes/**/*.vue',
'!../views/ai-platform/workflow/editor/panels/**/*.vue',
]);
const layoutMap: ComponentRecordType = {
BasicLayout,
IFrameView,
};
return await generateAccessible(preferences.app.accessMode, {
...options,
fetchMenuListAsync: async () => {
ElMessage({
duration: 1500,
message: `${$t('common.loadingMenu')}...`,
});
// 获取应用上下文
const appContextStore = useAppContextStore();
// 如果是子应用模式,传递 appCode 和 devMode 参数
// - 开发模式 (isDevMode=true): 只返回系统菜单
// - 正常模式 (isDevMode=false): 只返回应用专属菜单
if (appContextStore.appCode) {
return await getAllMenusApi(
appContextStore.appCode,
appContextStore.isDevMode,
);
}
// 主应用模式,不传参数
return await getAllMenusApi();
},
// 可以指定没有权限跳转403页面
forbiddenComponent,
// 如果 route.meta.menuVisibleWithForbidden = true
layoutMap,
pageMap,
});
}
export { generateAccess };
+242
View File
@@ -0,0 +1,242 @@
import type { Router } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { useAccessStore, useTabbarStore, useUserStore } from '@vben/stores';
import { startProgress, stopProgress } from '@vben/utils';
import { accessRoutes, coreRouteNames } from '#/router/routes';
import { useAuthStore } from '#/store';
import { useAppContextStore } from '#/store/app-context';
import { generateAccess } from './access';
/**
* 通用守卫配置
* @param router
*/
function setupCommonGuard(router: Router) {
// 记录已经加载的页面
const loadedPaths = new Set<string>();
// 记录当前应用编码,用于检测应用切换
let currentAppCode: null | string = null;
// 为每个应用存储 tab 历史
const tabHistoryByApp = new Map<string, any>();
router.beforeEach((to) => {
// 检测应用切换(支持 /app/ 和 /app-dev/ 两种模式)
const devMatch = to.path.match(/^\/app-dev\/([^/]+)/);
const appMatch = to.path.match(/^\/app\/([^/]+)/);
const newAppCode =
(devMatch && devMatch[1]) || (appMatch && appMatch[1]) || null;
const isDevMode = !!(devMatch && devMatch[1]);
const appKey = newAppCode
? (isDevMode
? `${newAppCode}-dev`
: newAppCode)
: 'main';
// 如果应用切换了,保存当前应用的 tab 历史,加载新应用的 tab 历史
if (newAppCode !== currentAppCode) {
const tabbarStore = useTabbarStore();
// 保存当前应用的 tab 历史到内存
const currentAppKey = currentAppCode || 'main';
tabHistoryByApp.set(currentAppKey, {
tabs: [...tabbarStore.tabs],
cachedTabs: new Set(tabbarStore.cachedTabs),
});
// 从 sessionStorage 加载新应用的 tab 历史
const storageKey = `vben-admin-tabs-${appKey}`;
const savedHistory = sessionStorage.getItem(storageKey);
if (savedHistory) {
try {
const parsed = JSON.parse(savedHistory);
tabbarStore.tabs = parsed.tabs || [];
tabbarStore.cachedTabs = new Set(parsed.cachedTabs || []);
} catch (error) {
console.error('Failed to parse tab history:', error);
tabbarStore.tabs = [];
tabbarStore.cachedTabs = new Set();
}
} else {
// 如果没有保存的历史,清空
tabbarStore.tabs = [];
tabbarStore.cachedTabs = new Set();
}
currentAppCode = newAppCode;
}
to.meta.loaded = loadedPaths.has(to.path);
// 页面加载进度条
if (!to.meta.loaded && preferences.transition.progress) {
startProgress();
}
return true;
});
router.afterEach((to) => {
// 记录页面是否加载,如果已经加载,后续的页面切换动画等效果不在重复执行
loadedPaths.add(to.path);
// 保存当前应用的 tab 历史到 sessionStorage(支持 /app/ 和 /app-dev/ 两种模式)
const devMatch = to.path.match(/^\/app-dev\/([^/]+)/);
const appMatch = to.path.match(/^\/app\/([^/]+)/);
const appCode =
(devMatch && devMatch[1]) || (appMatch && appMatch[1]) || null;
const isDevMode = !!(devMatch && devMatch[1]);
const appKey = appCode ? (isDevMode ? `${appCode}-dev` : appCode) : 'main';
const storageKey = `vben-admin-tabs-${appKey}`;
const tabbarStore = useTabbarStore();
const tabHistory = {
tabs: tabbarStore.tabs,
cachedTabs: [...tabbarStore.cachedTabs],
};
sessionStorage.setItem(storageKey, JSON.stringify(tabHistory));
// 关闭页面加载进度条
if (preferences.transition.progress) {
stopProgress();
}
});
}
/**
* 权限访问守卫配置
* @param router
*/
function setupAccessGuard(router: Router) {
router.beforeEach(async (to, from) => {
const accessStore = useAccessStore();
const userStore = useUserStore();
const authStore = useAuthStore();
// 基本路由,这些路由不需要进入权限拦截
if (coreRouteNames.includes(to.name as string)) {
if (to.path === LOGIN_PATH && accessStore.accessToken) {
return decodeURIComponent(
(to.query?.redirect as string) ||
userStore.userInfo?.homePath ||
preferences.app.defaultHomePath,
);
}
return true;
}
// accessToken 检查
if (!accessStore.accessToken) {
// 明确声明忽略权限访问权限,则可以访问
if (to.meta.ignoreAccess) {
return true;
}
// 没有访问权限,跳转登录页面
if (to.fullPath !== LOGIN_PATH) {
return {
path: LOGIN_PATH,
// 如不需要,直接删除 query
query:
to.fullPath === preferences.app.defaultHomePath
? {}
: { redirect: encodeURIComponent(to.fullPath) },
// 携带当前跳转的页面,登录后重新跳转该页面
replace: true,
};
}
return to;
}
// 是否已经生成过动态路由
if (accessStore.isAccessChecked) {
return true;
}
// 检查重定向路径或目标路径是否为子应用路径
// 这是为了处理从子应用退出登录后再登录的情况
const appContextStore = useAppContextStore();
const redirectParam = from.query.redirect as string | undefined;
const targetPath = redirectParam
? decodeURIComponent(redirectParam)
: to.path;
// 支持 /app-dev/ 和 /app/ 两种模式
const devMatch = targetPath.match(/^\/app-dev\/([^/]+)/);
const appMatch = targetPath.match(/^\/app\/([^/]+)/);
const detectedAppCode =
(devMatch && devMatch[1]) || (appMatch && appMatch[1]) || null;
const detectedDevMode = !!(devMatch && devMatch[1]);
if (detectedAppCode && !appContextStore.appCode) {
// 从重定向路径中检测到子应用,初始化 appContextStore
await appContextStore.setAppCode(detectedAppCode, detectedDevMode);
}
// 生成路由表
// 当前登录用户拥有的角色标识列表
const userInfo = userStore.userInfo || (await authStore.fetchUserInfo());
const userRoles = userInfo.roles ?? [];
// 生成菜单和路由
const { accessibleMenus, accessibleRoutes } = await generateAccess({
roles: userRoles,
router,
// 则会在菜单中显示,但是访问会被重定向到403
routes: accessRoutes,
});
// 保存菜单信息和路由信息
accessStore.setAccessMenus(accessibleMenus);
accessStore.setAccessRoutes(accessibleRoutes);
accessStore.setIsAccessChecked(true);
// 子应用根路径重定向(/app/hr -> /app/hr/xxx 或 /app-dev/hr -> /app-dev/hr/xxx
if (appContextStore.isSubApp) {
const pathPrefix = appContextStore.isDevMode ? '/app-dev' : '/app';
const subAppRootPath = `${pathPrefix}/${appContextStore.appCode}`;
if (to.path === subAppRootPath) {
const defaultHome =
preferences.app.defaultHomePath || '/page-render/main_home';
// 确保路径包含子应用前缀
const subAppTargetPath = defaultHome.startsWith(subAppRootPath)
? defaultHome
: `${subAppRootPath}${defaultHome}`;
return {
path: subAppTargetPath,
replace: true,
};
}
}
// 重定向逻辑
const redirectPath = (from.query.redirect ??
(to.path === preferences.app.defaultHomePath
? userInfo.homePath || preferences.app.defaultHomePath
: to.fullPath)) as string;
return {
...router.resolve(decodeURIComponent(redirectPath)),
replace: true,
};
});
}
/**
* 项目守卫配置
* @param router
*/
function createRouterGuard(router: Router) {
/** 通用 */
setupCommonGuard(router);
/** 权限访问 */
setupAccessGuard(router);
}
export { createRouterGuard };
+37
View File
@@ -0,0 +1,37 @@
import {
createRouter,
createWebHashHistory,
createWebHistory,
} from 'vue-router';
import { resetStaticRoutes } from '@vben/utils';
import { createRouterGuard } from './guard';
import { routes } from './routes';
/**
* @zh_CN 创建vue-router实例
*/
const router = createRouter({
history:
import.meta.env.VITE_ROUTER_HISTORY === 'hash'
? createWebHashHistory(import.meta.env.VITE_BASE)
: createWebHistory(import.meta.env.VITE_BASE),
// 应该添加到路由的初始路由列表。
routes,
scrollBehavior: (to, _from, savedPosition) => {
if (savedPosition) {
return savedPosition;
}
return to.hash ? { behavior: 'smooth', el: to.hash } : { left: 0, top: 0 };
},
// 是否应该禁止尾部斜杠。
// strict: true,
});
const resetRoutes = () => resetStaticRoutes(router, routes);
// 创建路由守卫
createRouterGuard(router);
export { resetRoutes, router };
+113
View File
@@ -0,0 +1,113 @@
import type { RouteRecordRaw } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { $t } from '#/locales';
const BasicLayout = () => import('#/layouts/basic.vue');
const AuthPageLayout = () => import('#/layouts/auth.vue');
const fallbackNotFoundRoute: RouteRecordRaw = {
component: () => import('#/views/_core/fallback/not-found.vue'),
meta: {
hideInBreadcrumb: true,
hideInMenu: true,
hideInTab: true,
title: '404',
},
name: 'FallbackNotFound',
path: '/:path(.*)*',
};
const coreRoutes: RouteRecordRaw[] = [
{
component: BasicLayout,
meta: {
hideInBreadcrumb: true,
title: 'Root',
},
name: 'Root',
path: '/',
redirect: preferences.app.defaultHomePath,
children: [],
},
{
component: AuthPageLayout,
meta: {
hideInTab: true,
title: 'Authentication',
},
name: 'Authentication',
path: '/auth',
redirect: LOGIN_PATH,
children: [
{
name: 'Login',
path: 'login',
component: () => import('#/views/_core/authentication/login.vue'),
meta: {
title: $t('page.auth.login'),
},
},
{
name: 'CodeLogin',
path: 'code-login',
component: () => import('#/views/_core/authentication/code-login.vue'),
meta: {
title: $t('page.auth.codeLogin'),
},
},
{
name: 'QrCodeLogin',
path: 'qrcode-login',
component: () =>
import('#/views/_core/authentication/qrcode-login.vue'),
meta: {
title: $t('page.auth.qrcodeLogin'),
},
},
{
name: 'ForgetPassword',
path: 'forget-password',
component: () =>
import('#/views/_core/authentication/forget-password.vue'),
meta: {
title: $t('page.auth.forgetPassword'),
},
},
{
name: 'Register',
path: 'register',
component: () => import('#/views/_core/authentication/register.vue'),
meta: {
title: $t('page.auth.register'),
},
},
],
},
{
name: 'OAuthCallback',
path: '/oauth/:provider/callback',
component: () => import('#/views/_core/authentication/oauth-callback.vue'),
meta: {
hideInBreadcrumb: true,
hideInMenu: true,
hideInTab: true,
title: 'OAuth Callback',
},
},
{
name: 'FilePreview',
path: '/file-preview/:id',
component: () => import('#/views/_core/file-preview/index.vue'),
meta: {
hideInBreadcrumb: true,
hideInMenu: true,
hideInTab: true,
title: 'File Preview',
},
},
];
export { coreRoutes, fallbackNotFoundRoute };
@@ -0,0 +1,55 @@
import type { RouteRecordRaw } from 'vue-router';
import { mergeRouteModules, traverseTreeValues } from '@vben/utils';
import { coreRoutes, fallbackNotFoundRoute } from './core';
const dynamicRouteFiles = import.meta.glob('./modules/**/*.ts', {
eager: true,
});
// 有需要可以自行打开注释,并创建文件夹
// const externalRouteFiles = import.meta.glob('./external/**/*.ts', { eager: true });
// const staticRouteFiles = import.meta.glob('./static/**/*.ts', { eager: true });
/** 动态路由 */
const dynamicRoutes: RouteRecordRaw[] = mergeRouteModules(dynamicRouteFiles);
/** 外部路由列表,访问这些页面可以不需要Layout,可能用于内嵌在别的系统(不会显示在菜单中) */
// const externalRoutes: RouteRecordRaw[] = mergeRouteModules(externalRouteFiles);
// const staticRoutes: RouteRecordRaw[] = mergeRouteModules(staticRouteFiles);
const staticRoutes: RouteRecordRaw[] = [];
const externalRoutes: RouteRecordRaw[] = [];
/** 路由列表,由基本路由、外部路由和404兜底路由组成
* 无需走权限验证(会一直显示在菜单中) */
const routes: RouteRecordRaw[] = [
...coreRoutes,
...externalRoutes,
fallbackNotFoundRoute,
];
/** 基本路由列表,这些路由不需要进入权限拦截 */
const coreRouteNames = traverseTreeValues(coreRoutes, (route) => route.name);
/** 有权限校验的路由列表,包含动态路由和静态路由 */
const accessRoutes = [...dynamicRoutes, ...staticRoutes];
const componentKeys: string[] = Object.keys(
import.meta.glob([
'../../views/**/*.vue',
'!../../views/**/components/**',
'!../../views/**/modules/**',
'!../../views/ai-platform/workflow/editor/components/**/*.vue',
'!../../views/ai-platform/workflow/editor/edges/**/*.vue',
'!../../views/ai-platform/workflow/editor/nodes/**/*.vue',
'!../../views/ai-platform/workflow/editor/panels/**/*.vue',
]),
)
.filter((item) => !item.includes('/modules/'))
.map((v) => {
const path = v.replace('../../views/', '/');
return path.endsWith('.vue') ? path.slice(0, -4) : path;
});
export { accessRoutes, componentKeys, coreRouteNames, routes };
@@ -0,0 +1,129 @@
import type { RouteRecordRaw } from 'vue-router';
const routes: RouteRecordRaw[] = [
{
meta: {
hideInMenu: true,
title: '执行历史',
},
name: 'AIWorkflowRuns',
path: '/ai-platform/workflow-runs',
component: () => import('#/views/ai-platform/workflow-runs/index.vue'),
},
{
meta: {
hideInMenu: true,
title: '执行历史',
},
name: 'SubAppAIWorkflowRuns',
path: '/app/:appCode/ai-platform/workflow-runs',
component: () => import('#/views/ai-platform/workflow-runs/index.vue'),
},
{
meta: {
hideInMenu: true,
title: '执行历史',
},
name: 'SubAppDevAIWorkflowRuns',
path: '/app-dev/:appCode/ai-platform/workflow-runs',
component: () => import('#/views/ai-platform/workflow-runs/index.vue'),
},
// 工作流编辑器 - 主应用
{
meta: {
hideInMenu: true,
title: '工作流编辑器',
noBasicLayout: true,
},
name: 'AIWorkflowEditor',
path: '/ai-platform/workflow/editor/:id',
component: () => import('#/views/ai-platform/workflow/editor/index.vue'),
},
// 工作流编辑器 - 子应用
{
meta: {
hideInMenu: true,
title: '工作流编辑器',
noBasicLayout: true,
},
name: 'SubAppAIWorkflowEditor',
path: '/app/:appCode/ai-platform/workflow/editor/:id',
component: () => import('#/views/ai-platform/workflow/editor/index.vue'),
},
// 工作流编辑器 - 子应用开发模式
{
meta: {
hideInMenu: true,
title: '工作流编辑器',
noBasicLayout: true,
},
name: 'SubAppDevAIWorkflowEditor',
path: '/app-dev/:appCode/ai-platform/workflow/editor/:id',
component: () => import('#/views/ai-platform/workflow/editor/index.vue'),
},
// 智能体编辑器 - 主应用
{
meta: {
hideInMenu: true,
title: '智能体编辑器',
noBasicLayout: true,
},
name: 'AIAgentEditor',
path: '/ai-platform/agent/editor/:id',
component: () => import('#/views/ai-platform/agent/editor/index.vue'),
},
// 智能体编辑器 - 子应用
{
meta: {
hideInMenu: true,
title: '智能体编辑器',
noBasicLayout: true,
},
name: 'SubAppAIAgentEditor',
path: '/app/:appCode/ai-platform/agent/editor/:id',
component: () => import('#/views/ai-platform/agent/editor/index.vue'),
},
// 智能体编辑器 - 子应用开发模式
{
meta: {
hideInMenu: true,
title: '智能体编辑器',
noBasicLayout: true,
},
name: 'SubAppDevAIAgentEditor',
path: '/app-dev/:appCode/ai-platform/agent/editor/:id',
component: () => import('#/views/ai-platform/agent/editor/index.vue'),
},
// 知识库详情 - 主应用
{
meta: {
hideInMenu: true,
title: '知识库详情',
},
name: 'AIKnowledgeDetail',
path: '/ai-platform/knowledge/detail/:id',
component: () => import('#/views/ai-platform/knowledge/detail/index.vue'),
},
// // 知识库详情 - 子应用
{
meta: {
hideInMenu: true,
title: '知识库详情',
},
name: 'SubAppAIKnowledgeDetail',
path: '/app/:appCode/ai-platform/knowledge/detail/:id',
component: () => import('#/views/ai-platform/knowledge/detail/index.vue'),
},
// 知识库详情 - 子应用开发模式
{
meta: {
hideInMenu: true,
title: '知识库详情',
},
name: 'SubAppDevAIKnowledgeDetail',
path: '/app-dev/:appCode/ai-platform/knowledge/detail/:id',
component: () => import('#/views/ai-platform/knowledge/detail/index.vue'),
},
];
export default routes;
@@ -0,0 +1,18 @@
import type { RouteRecordRaw } from 'vue-router';
// import { $t } from '#/locales';
const routes: RouteRecordRaw[] = [
// {
// meta: {
// icon: 'lucide:message-square',
// title: $t('chat.title'),
// noBasicLayout: true,
// },
// name: 'ChatIndex',
// path: '/chat',
// component: () => import('#/views/_core/chat/index.vue'),
// },
];
export default routes;
@@ -0,0 +1,37 @@
import type { RouteRecordRaw } from 'vue-router';
// import { BasicLayout } from '#/layouts';
// import { BookOpenText } from '@vben/icons';
const routes: RouteRecordRaw[] = [
// {
// component: BasicLayout,
// meta: {
// icon: BookOpenText,
// order: 9999,
// title: '组件示例',
// },
// name: 'Demos',
// path: '/demos',
// children: [
// {
// meta: {
// title: 'Notion 编辑器',
// },
// name: 'NotionEditorDemo',
// path: '/demos/notion-editor',
// component: () => import('#/views/demos/notion-editor.vue'),
// },
// {
// meta: {
// title: '富文本编辑器',
// },
// name: 'RichTextEditorDemo',
// path: '/demos/rich-text-editor',
// component: () => import('#/views/demos/rich-text-editor.vue'),
// },
// ],
// },
];
export default routes;