Files
Enterprise-Knowledge-Base/frontend/src/router/index.ts
T
wizardchen 2d3f32de5c feat(frontend): replace standalone search page with global command palette
Reworks search from a siloed /platform/knowledge-search page into a
universal ⌘K palette plus natural, in-context entry points.

Why the old page felt out of place:
- "Search" was an action pinned next to entity routes (knowledge base,
  agent, organization), mixing noun- and verb-level navigation items.
- Its two tabs (knowledge vs. chat messages) forced users to pick a
  mental model before they knew what they wanted.
- It was also the only way to search at all — no global shortcut, no
  context-aware entry.

What this replaces it with:
- A new ⌘K/Ctrl+K command palette (GlobalCommandPalette.vue) mounted
  once in views/platform/index.vue. Results are grouped by type
  (files, messages, knowledge bases, agents, chat titles, commands)
  so users never need to pre-filter. Debounced, identity-keyed
  selection survives async arrivals (slow KB results no longer yank
  the highlight off the user's current row). ⌘1-9 jump shortcuts are
  rendered inline on each row for discoverability.
- Sidebar gets a visible "Search" entry at the top — clicking it
  opens the palette (no route change), with a platform-aware kbd hint
  (⌘K on Mac, Ctrl K elsewhere).
- KB detail page: opening ⌘K there auto-scopes the search to the
  current KB via a removable chip (Backspace in empty input also
  clears it); no separate embedded search bar needed.
- The legacy route /platform/knowledge-search now redirects to the KB
  list with ?cmdk= set, so existing bookmarks still work.
- KnowledgeBase.vue now handles both route-query changes and a
  window event (weknora:open-knowledge) for intra-KB navigation,
  fixing the silent-no-op when the palette jumps to a chunk in the
  already-open KB.

Dropped:
- frontend/src/views/knowledge/KnowledgeSearch.vue (1163 lines).
- The exploratory SessionSearchBar mode-switching widget in the chat
  submenu; ⌘K covers its use cases without a two-mode UI.

i18n: zh-CN / en-US / ko-KR / ru-RU updated together — new
commandPalette.*, kb.*, and menu.search keys; obsolete session.search.*
and menu.knowledgeSearch removed.
2026-05-06 16:26:22 +08:00

317 lines
9.9 KiB
TypeScript

import { createRouter, createWebHistory } from 'vue-router'
import type { RouteLocationNormalized } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { autoSetup, getCurrentUser } from '@/api/auth'
/** Lite /桌面 WebView 硬刷新时可能只打开 `/`,用 session 记住上次页面以便恢复 */
const LITE_LAST_PATH_KEY = 'weknora_lite_last_path'
const AUTO_SETUP_FAILED_KEY = 'weknora_auto_setup_failed'
function shouldTryAutoSetup() {
return localStorage.getItem(AUTO_SETUP_FAILED_KEY) !== 'true'
}
function markAutoSetupFailed() {
localStorage.setItem(AUTO_SETUP_FAILED_KEY, 'true')
}
function isLiteEdition(authStore: ReturnType<typeof useAuthStore>) {
return authStore.isLiteMode || localStorage.getItem('weknora_lite_mode') === 'true'
}
function isLiteSpaDefaultEntry(to: RouteLocationNormalized) {
return (
to.path === '/' ||
to.path === '/platform' ||
to.path === '/platform/knowledge-bases' ||
to.name === 'knowledgeBaseList'
)
}
function isSafeLiteRestoreTarget(path: string) {
return path.startsWith('/platform/') && !path.startsWith('/platform/organizations')
}
function hasPendingOIDCCallback() {
if (typeof window === 'undefined') return false
const hash = window.location.hash || ''
return hash.includes('oidc_result=') || hash.includes('oidc_error=')
}
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "/",
redirect: "/platform/knowledge-bases",
},
{
path: "/login",
name: "login",
component: () => import("../views/auth/Login.vue"),
meta: { requiresAuth: false, requiresInit: false }
},
{
path: "/join",
name: "joinOrganization",
// 重定向到组织列表页,并将 code 参数转换为 invite_code
redirect: (to) => {
const code = to.query.code as string
return {
path: '/platform/organizations',
query: code ? { invite_code: code } : {}
}
},
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "/knowledgeBase",
name: "home",
component: () => import("../views/knowledge/KnowledgeBase.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "/platform",
name: "Platform",
redirect: "/platform/knowledge-bases",
component: () => import("../views/platform/index.vue"),
meta: { requiresInit: true, requiresAuth: true },
children: [
{
path: "tenant",
redirect: "/platform/settings"
},
{
path: "settings",
name: "settings",
component: () => import("../views/settings/Settings.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "knowledge-bases",
name: "knowledgeBaseList",
component: () => import("../views/knowledge/KnowledgeBaseList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "knowledge-bases/:kbId",
name: "knowledgeBaseDetail",
component: () => import("../views/knowledge/KnowledgeBase.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "knowledge-search",
// 旧路径保留为重定向,打开全局命令面板(⌘K),带上可选的 q 参数
redirect: (to) => {
const q = to.query.q
return {
path: '/platform/knowledge-bases',
query: typeof q === 'string' ? { cmdk: q } : { cmdk: '' },
}
},
},
{
path: "agents",
name: "agentList",
component: () => import("../views/agent/AgentList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "creatChat",
name: "globalCreatChat",
component: () => import("../views/creatChat/creatChat.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "knowledge-bases/:kbId/creatChat",
name: "kbCreatChat",
component: () => import("../views/creatChat/creatChat.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "chat/:chatid",
name: "chat",
component: () => import("../views/chat/index.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "organizations",
name: "organizationList",
component: () => import("../views/organization/OrganizationList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
],
},
// Dev-only markdown rendering test page
...(import.meta.env.DEV ? [{
path: '/platform/dev/markdown',
name: 'markdownTest',
component: () => import('../views/dev/MarkdownTestPage.vue'),
meta: { requiresAuth: false, requiresInit: false }
}] : []),
],
});
// 持久化 auto-setup / login 返回的认证信息到 store
function persistLoginResponse(authStore: ReturnType<typeof useAuthStore>, response: any) {
if (response.user && response.tenant && response.token) {
authStore.setUser({
id: response.user.id || '',
username: response.user.username || '',
email: response.user.email || '',
avatar: response.user.avatar,
tenant_id: String(response.tenant.id) || '',
can_access_all_tenants: response.user.can_access_all_tenants || false,
created_at: response.user.created_at || new Date().toISOString(),
updated_at: response.user.updated_at || new Date().toISOString()
})
authStore.setToken(response.token)
if (response.refresh_token) {
authStore.setRefreshToken(response.refresh_token)
}
authStore.setTenant({
id: String(response.tenant.id) || '',
name: response.tenant.name || '',
api_key: response.tenant.api_key || '',
owner_id: response.user.id || '',
created_at: response.tenant.created_at || new Date().toISOString(),
updated_at: response.tenant.updated_at || new Date().toISOString()
})
}
}
async function hydrateSessionFromToken(authStore: ReturnType<typeof useAuthStore>) {
const token = localStorage.getItem('weknora_token')
if (!token) return false
if (!authStore.token) {
authStore.setToken(token)
}
const storedRefreshToken = localStorage.getItem('weknora_refresh_token')
if (storedRefreshToken && !authStore.refreshToken) {
authStore.setRefreshToken(storedRefreshToken)
}
try {
const response = await getCurrentUser()
const user = response.data?.user
if (!response.success || !user) {
return false
}
authStore.setUser({
id: user.id || '',
username: user.username || '',
email: user.email || '',
avatar: user.avatar,
tenant_id: String(user.tenant_id || response.data?.tenant?.id || ''),
can_access_all_tenants: user.can_access_all_tenants || false,
created_at: user.created_at || new Date().toISOString(),
updated_at: user.updated_at || new Date().toISOString(),
})
const tenant = response.data?.tenant
if (tenant) {
authStore.setTenant({
id: String(tenant.id) || '',
name: tenant.name || '',
api_key: tenant.api_key || '',
owner_id: tenant.owner_id || user.id || '',
description: tenant.description,
status: tenant.status,
business: tenant.business,
storage_quota: tenant.storage_quota,
storage_used: tenant.storage_used,
created_at: tenant.created_at || new Date().toISOString(),
updated_at: tenant.updated_at || new Date().toISOString(),
})
}
return true
} catch {
return false
}
}
let autoSetupAttempted = false
let liteDeepLinkRestoreDone = false
// 路由守卫:检查认证状态和系统初始化状态
router.beforeEach(async (to, from, next) => {
const authStore = useAuthStore()
// OIDC 回跳登录结果依赖 App.vue 在挂载后消费 URL hash。
// 如果这里先按“未登录”拦截到 /login,会导致回调结果没有机会落盘。
if (hasPendingOIDCCallback()) {
next()
return
}
// Lite:硬刷新后若落在默认首页,恢复本次会话中最后访问的 /platform 子路径
if (!liteDeepLinkRestoreDone) {
liteDeepLinkRestoreDone = true
if (isLiteEdition(authStore)) {
const saved = sessionStorage.getItem(LITE_LAST_PATH_KEY)
if (saved && isSafeLiteRestoreTarget(saved) && isLiteSpaDefaultEntry(to)) {
if (saved !== to.fullPath) {
next(saved)
return
}
}
}
}
// 如果访问的是登录页面或初始化页面,直接放行
if (to.meta.requiresAuth === false || to.meta.requiresInit === false) {
// 如果已登录用户访问登录页面,重定向到知识库列表页面
if (to.path === '/login' && authStore.isLoggedIn) {
next('/platform/knowledge-bases')
return
}
next()
return
}
// 检查用户认证状态
if (to.meta.requiresAuth !== false) {
if (!authStore.isLoggedIn) {
const restored = await hydrateSessionFromToken(authStore)
if (restored) {
next(to.fullPath)
return
}
if (!autoSetupAttempted && shouldTryAutoSetup()) {
autoSetupAttempted = true
try {
const response = await autoSetup()
if (response.success) {
persistLoginResponse(authStore, response)
authStore.setLiteMode(true)
next(to.fullPath)
return
} else {
markAutoSetupFailed()
}
} catch {
markAutoSetupFailed()
}
}
next('/login')
return
}
}
next()
})
router.afterEach((to) => {
if (!isLiteEdition(useAuthStore())) return
if (to.path === '/login') return
if (!to.path.startsWith('/platform')) return
sessionStorage.setItem(LITE_LAST_PATH_KEY, to.fullPath)
})
export default router