From 2d3f32de5c470ac4f11a78fa52456fdf9eab4a1d Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 6 May 2026 16:20:50 +0800 Subject: [PATCH] feat(frontend): replace standalone search page with global command palette MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../src/components/GlobalCommandPalette.vue | 970 ++++++++++++++ .../GlobalCommandPalette/ResultGroup.vue | 89 ++ .../GlobalCommandPalette/ResultItem.vue | 202 +++ .../GlobalCommandPalette/commands.ts | 105 ++ .../GlobalCommandPalette/useHighlight.ts | 31 + .../GlobalCommandPalette/useSearch.ts | 378 ++++++ .../GlobalCommandPalette/useStartChat.ts | 41 + frontend/src/components/menu.vue | 94 +- frontend/src/i18n/locales/en-US.ts | 52 +- frontend/src/i18n/locales/ko-KR.ts | 52 +- frontend/src/i18n/locales/ru-RU.ts | 52 +- frontend/src/i18n/locales/zh-CN.ts | 52 +- frontend/src/router/index.ts | 11 +- frontend/src/stores/commandPalette.ts | 73 ++ frontend/src/stores/menu.ts | 1 - .../src/views/knowledge/KnowledgeBase.vue | 32 +- .../src/views/knowledge/KnowledgeSearch.vue | 1163 ----------------- frontend/src/views/platform/index.vue | 28 +- 18 files changed, 2229 insertions(+), 1197 deletions(-) create mode 100644 frontend/src/components/GlobalCommandPalette.vue create mode 100644 frontend/src/components/GlobalCommandPalette/ResultGroup.vue create mode 100644 frontend/src/components/GlobalCommandPalette/ResultItem.vue create mode 100644 frontend/src/components/GlobalCommandPalette/commands.ts create mode 100644 frontend/src/components/GlobalCommandPalette/useHighlight.ts create mode 100644 frontend/src/components/GlobalCommandPalette/useSearch.ts create mode 100644 frontend/src/components/GlobalCommandPalette/useStartChat.ts create mode 100644 frontend/src/stores/commandPalette.ts delete mode 100644 frontend/src/views/knowledge/KnowledgeSearch.vue diff --git a/frontend/src/components/GlobalCommandPalette.vue b/frontend/src/components/GlobalCommandPalette.vue new file mode 100644 index 00000000..b499a873 --- /dev/null +++ b/frontend/src/components/GlobalCommandPalette.vue @@ -0,0 +1,970 @@ + + + + + + + diff --git a/frontend/src/components/GlobalCommandPalette/ResultGroup.vue b/frontend/src/components/GlobalCommandPalette/ResultGroup.vue new file mode 100644 index 00000000..337458a0 --- /dev/null +++ b/frontend/src/components/GlobalCommandPalette/ResultGroup.vue @@ -0,0 +1,89 @@ + + + + + diff --git a/frontend/src/components/GlobalCommandPalette/ResultItem.vue b/frontend/src/components/GlobalCommandPalette/ResultItem.vue new file mode 100644 index 00000000..59636774 --- /dev/null +++ b/frontend/src/components/GlobalCommandPalette/ResultItem.vue @@ -0,0 +1,202 @@ + + + + + diff --git a/frontend/src/components/GlobalCommandPalette/commands.ts b/frontend/src/components/GlobalCommandPalette/commands.ts new file mode 100644 index 00000000..365f9127 --- /dev/null +++ b/frontend/src/components/GlobalCommandPalette/commands.ts @@ -0,0 +1,105 @@ +import type { Router } from 'vue-router' +import type { Composer } from 'vue-i18n' + +/** + * A single command that can be searched and invoked from the palette. + * Kept intentionally minimal — commands are "just do something now", not + * entities with detail pages. + */ +export interface CmdkCommand { + id: string + /** Localized display label. */ + label: string + /** TDesign icon name rendered on the left. */ + icon: string + /** Extra tokens used purely for fuzzy matching (aliases, synonyms). */ + keywords?: string[] + /** Executed on primary action. Should close the palette itself if needed. */ + run: () => void +} + +export interface CommandContext { + router: Router + t: Composer['t'] + /** Closes the palette; typically wires to commandPaletteStore.closePalette. */ + close: () => void +} + +/** + * Build the flat command list. Commands are intentionally static — dynamic + * entities (KBs / agents / sessions) live in their own result groups. + */ +export function buildCommands(ctx: CommandContext): CmdkCommand[] { + const { router, t, close } = ctx + return [ + { + id: 'new-chat', + label: t('commandPalette.quick.newChat'), + icon: 'chat-add', + keywords: ['new', 'chat', 'conversation', '新建', '对话', 'создать'], + run: () => { + close() + router.push('/platform/creatChat') + }, + }, + { + id: 'open-kb-list', + label: t('commandPalette.quick.knowledgeBases'), + icon: 'folder', + keywords: ['kb', 'knowledge', 'base', '知识库', '文档'], + run: () => { + close() + router.push('/platform/knowledge-bases') + }, + }, + { + id: 'open-agents', + label: t('commandPalette.quick.agents'), + icon: 'user-circle', + keywords: ['agent', 'bot', '智能体', '助手'], + run: () => { + close() + router.push('/platform/agents') + }, + }, + { + id: 'open-organizations', + label: t('commandPalette.quick.organizations'), + icon: 'usergroup', + keywords: ['org', 'organization', 'team', 'space', '组织', '共享'], + run: () => { + close() + router.push('/platform/organizations') + }, + }, + { + id: 'open-settings', + label: t('commandPalette.quick.settings'), + icon: 'setting', + keywords: ['settings', 'preferences', 'config', '设置', '配置'], + run: () => { + close() + router.push('/platform/settings') + }, + }, + ] +} + +/** + * Filter commands by a free-text query. Matches on label OR any keyword, + * case-insensitive. Empty query returns the full list unchanged so it can + * double as a "default" empty-state listing. + */ +export function filterCommands(commands: CmdkCommand[], query: string): CmdkCommand[] { + const q = (query || '').trim().toLowerCase() + if (!q) return commands + return commands.filter((cmd) => { + if (cmd.label.toLowerCase().includes(q)) return true + if (cmd.keywords) { + for (const kw of cmd.keywords) { + if (kw.toLowerCase().includes(q)) return true + } + } + return false + }) +} diff --git a/frontend/src/components/GlobalCommandPalette/useHighlight.ts b/frontend/src/components/GlobalCommandPalette/useHighlight.ts new file mode 100644 index 00000000..3d8bf687 --- /dev/null +++ b/frontend/src/components/GlobalCommandPalette/useHighlight.ts @@ -0,0 +1,31 @@ +/** + * Safely highlight query keywords inside a plain-text string by wrapping + * matches in tags. The input text is HTML-escaped first so the output + * is safe to bind with v-html. + * + * Extracted from the legacy KnowledgeSearch.vue so it can be reused by the + * global command palette and KB-scoped search bar. + */ +export function escapeHtml(str: string): string { + return (str || '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +export function highlightText(text: string, query: string): string { + const q = (query || '').trim() + const escaped = escapeHtml(text || '') + if (!q) return escaped + const keywords = q.split(/\s+/).filter(Boolean) + let result = escaped + for (const kw of keywords) { + const escapedKw = escapeHtml(kw).replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + if (!escapedKw) continue + const regex = new RegExp(`(${escapedKw})`, 'gi') + result = result.replace(regex, '$1') + } + return result +} diff --git a/frontend/src/components/GlobalCommandPalette/useSearch.ts b/frontend/src/components/GlobalCommandPalette/useSearch.ts new file mode 100644 index 00000000..72683aba --- /dev/null +++ b/frontend/src/components/GlobalCommandPalette/useSearch.ts @@ -0,0 +1,378 @@ +import { ref, watch, onMounted, computed } from 'vue' +import { listKnowledgeBases, knowledgeSemanticSearch } from '@/api/knowledge-base' +import { searchMessages, type MessageSearchGroupItem } from '@/api/chat-history' +import { listAgents } from '@/api/agent' +import { useOrganizationStore } from '@/stores/organization' +import { useMenuStore } from '@/stores/menu' + +export interface CmdkKb { + id: string + name: string + type?: string +} + +export interface CmdkAgent { + id: string + name: string + description?: string + avatar?: string + isBuiltin: boolean + source: 'own' | 'shared' + orgName?: string +} + +export interface CmdkSessionItem { + id: string + title: string +} + +export interface CmdkChunk { + id: string + chunk_index: number + knowledge_id: string + knowledge_base_id: string + knowledge_title: string + kb_name: string + content: string + matched_content?: string + match_type: 'vector' | 'keyword' | string + score: number +} + +export interface CmdkFileGroup { + knowledgeId: string + kbId: string + title: string + kbName: string + chunks: CmdkChunk[] +} + +export interface CmdkMsgGroup { + sessionId: string + sessionTitle: string + items: MessageSearchGroupItem[] +} + +/** + * useCmdkSearch — debounced, cancellable search that fans out to + * • /api/v1/knowledge-search (chunks / files) + * • /api/v1/messages/search (chat history) + * and produces three client-side groups: kbs / files / messages. + * + * Cancellation is implemented with a monotonically-increasing request id so + * that stale responses are dropped (AbortController is not used to keep the + * backend API untouched). + * + * `lockedKbIds` is a getter returning the current scope. When it returns a + * non-empty array, chunk search is limited to those KBs and message search + * is skipped. Changes to the getter's return value re-trigger the search. + */ +export function useCmdkSearch(options: { + /** When set, scopes knowledge search to these KBs. Re-evaluated on each search. */ + lockedKbIds?: () => string[] + /** How many knowledge chunks to keep after grouping; default no-cap. */ + chunkLimit?: number + /** Debounce delay in ms. */ + debounceMs?: number +}) { + const debounceMs = options.debounceMs ?? 350 + const query = ref('') + const loading = ref(false) + const hasSearched = ref(false) + + // All KBs the current user can see (own + shared). Loaded lazily & cached. + const knowledgeBases = ref([]) + const kbsLoaded = ref(false) + let kbsLoadingPromise: Promise | null = null + + const fileGroups = ref([]) + const messageGroups = ref([]) + const totalChunks = ref(0) + const totalMessages = ref(0) + + // Agents the current user can access (own + builtin + shared via orgs). + const agents = ref([]) + const agentsLoaded = ref(false) + let agentsLoadingPromise: Promise | null = null + + const orgStore = useOrganizationStore() + const menuStore = useMenuStore() + + const ensureKbs = async (): Promise => { + if (kbsLoaded.value) return + if (kbsLoadingPromise) return kbsLoadingPromise + kbsLoadingPromise = (async () => { + try { + const [kbRes, shared] = await Promise.all([ + listKnowledgeBases(), + orgStore.fetchSharedKnowledgeBases(), + ]) + const own: CmdkKb[] = ((kbRes as any)?.data || []).map((kb: any) => ({ + id: String(kb.id), + name: kb.name || '', + type: kb.type, + })) + const ownIds = new Set(own.map(k => k.id)) + const sharedList: CmdkKb[] = (shared || []) + .filter((s: any) => s?.knowledge_base != null) + .map((s: any) => ({ + id: String(s.knowledge_base.id), + name: s.knowledge_base.name || '', + type: s.knowledge_base.type, + })) + .filter((k: CmdkKb) => !ownIds.has(k.id)) + knowledgeBases.value = [...own, ...sharedList] + kbsLoaded.value = true + } catch (e) { + // Best-effort; silent failure keeps the palette usable. + console.error('[cmdk] failed to load knowledge bases', e) + } finally { + kbsLoadingPromise = null + } + })() + return kbsLoadingPromise + } + + // Derived: KB name lookup + const getKbName = (kbId: string): string => { + if (!kbId) return '' + const kb = knowledgeBases.value.find(k => k.id === kbId) + return kb?.name || '' + } + + // KB name hits (client-side, works even before a remote search returns). + const kbMatches = computed(() => { + const q = query.value.trim().toLowerCase() + if (!q) return [] + return knowledgeBases.value + .filter(k => k.name.toLowerCase().includes(q)) + .slice(0, 4) + }) + + // Agents (own + shared). Lazily loaded & cached; no backend search endpoint + // exists so we always filter client-side. + const ensureAgents = async (): Promise => { + if (agentsLoaded.value) return + if (agentsLoadingPromise) return agentsLoadingPromise + agentsLoadingPromise = (async () => { + try { + const [ownRes, shared] = await Promise.all([ + listAgents(), + orgStore.fetchSharedAgents(), + ]) + const own: CmdkAgent[] = ((ownRes as any)?.data || []).map((a: any) => ({ + id: String(a.id), + name: a.name || '', + description: a.description, + avatar: a.avatar, + isBuiltin: !!a.is_builtin, + source: 'own', + })) + const ownIds = new Set(own.map(a => a.id)) + const sharedList: CmdkAgent[] = (shared || []) + .filter((s: any) => s?.agent != null) + .map((s: any) => ({ + id: String(s.agent.id), + name: s.agent.name || '', + description: s.agent.description, + avatar: s.agent.avatar, + isBuiltin: !!s.agent.is_builtin, + source: 'shared' as const, + orgName: s.org_name, + })) + .filter((a: CmdkAgent) => !ownIds.has(a.id)) + agents.value = [...own, ...sharedList] + agentsLoaded.value = true + } catch (e) { + console.error('[cmdk] failed to load agents', e) + } finally { + agentsLoadingPromise = null + } + })() + return agentsLoadingPromise + } + + const agentMatches = computed(() => { + const q = query.value.trim().toLowerCase() + if (!q) return [] + return agents.value + .filter(a => { + const name = (a.name || '').toLowerCase() + const desc = (a.description || '').toLowerCase() + return name.includes(q) || desc.includes(q) + }) + .slice(0, 5) + }) + + // Sessions: no dedicated list API; we re-use whatever menuStore already has + // cached (the sidebar already paginates them). Good enough for "jump to a + // session I've seen recently" — not a substitute for message-content search. + const sessionList = computed(() => { + const chatMenu = (menuStore.menuArr as any[]).find((m: any) => m.path === 'creatChat') + const children = (chatMenu?.children as any[]) || [] + return children.map((c: any) => ({ + id: String(c.id || ''), + title: c.title || '', + })) + }) + + const sessionMatches = computed(() => { + const q = query.value.trim().toLowerCase() + if (!q) return [] + // If a session already appears in the message-content group, suppress it + // here — showing the same session title twice (once with a message hit, + // once by title match) is noise. The message-group entry is strictly + // more informative (it shows which message matched), so it wins. + const coveredBySession = new Set(messageGroups.value.map(g => g.sessionId)) + return sessionList.value + .filter(s => s.title && s.title.toLowerCase().includes(q)) + .filter(s => !coveredBySession.has(s.id)) + .slice(0, 5) + }) + + // Monotonic id to drop stale responses. + let requestSeq = 0 + let debounceTimer: ReturnType | null = null + + const clearResults = () => { + fileGroups.value = [] + messageGroups.value = [] + totalChunks.value = 0 + totalMessages.value = 0 + hasSearched.value = false + } + + const runSearch = async (q: string, seq: number) => { + loading.value = true + hasSearched.value = true + + // Determine knowledge_base_ids for chunk search. A non-empty lockedKbIds + // narrows the scope and also disables message search (out of scope). + const locked = options.lockedKbIds?.() || [] + const scoped = locked.length > 0 + let kbIds: string[] + if (scoped) { + kbIds = locked + } else { + await ensureKbs() + kbIds = knowledgeBases.value.map(k => k.id) + } + + const knowledgePromise = kbIds.length > 0 + ? knowledgeSemanticSearch({ query: q, knowledge_base_ids: kbIds }) + .then((res: any) => (res?.success && res.data ? res.data : [])) + .catch((e) => { + console.error('[cmdk] knowledge search failed', e) + return [] + }) + : Promise.resolve([]) + + const messagesPromise = scoped + ? Promise.resolve({ items: [], total: 0 }) + : searchMessages({ query: q, mode: 'hybrid', limit: 30 }) + .then((res: any) => (res?.success && res.data ? res.data : { items: [], total: 0 })) + .catch((e) => { + console.error('[cmdk] message search failed', e) + return { items: [], total: 0 } + }) + + const [chunks, msgRes] = await Promise.all([knowledgePromise, messagesPromise]) + + // Stale response guard. + if (seq !== requestSeq) return + + // Group chunks by knowledge_id. + const fmap = new Map() + for (const item of chunks as any[]) { + const kid = item.knowledge_id || 'unknown' + if (!fmap.has(kid)) { + fmap.set(kid, { + knowledgeId: kid, + kbId: item.knowledge_base_id || '', + title: item.knowledge_title || item.knowledge_filename || kid, + kbName: getKbName(item.knowledge_base_id), + chunks: [], + }) + } + fmap.get(kid)!.chunks.push({ + id: item.id, + chunk_index: item.chunk_index, + knowledge_id: kid, + knowledge_base_id: item.knowledge_base_id || '', + knowledge_title: item.knowledge_title || '', + kb_name: getKbName(item.knowledge_base_id), + content: item.content || '', + matched_content: item.matched_content, + match_type: item.match_type || 'vector', + score: item.score || 0, + }) + } + fileGroups.value = Array.from(fmap.values()) + totalChunks.value = (chunks as any[]).length + + // Group messages by session_id. + const mmap = new Map() + const items: MessageSearchGroupItem[] = (msgRes as any).items || [] + for (const m of items) { + const sid = m.session_id || 'unknown' + if (!mmap.has(sid)) { + mmap.set(sid, { + sessionId: sid, + sessionTitle: m.session_title || '', + items: [], + }) + } + mmap.get(sid)!.items.push(m) + } + messageGroups.value = Array.from(mmap.values()) + totalMessages.value = (msgRes as any).total || items.length + + loading.value = false + } + + // Watch query changes (debounced). lockedKbIds is tracked as a derived + // string so the search re-runs when the KB scope toggles. + const lockedSignature = () => + (options.lockedKbIds?.() || []).slice().sort().join(',') + + watch([query, lockedSignature], ([val]) => { + if (debounceTimer) clearTimeout(debounceTimer) + const trimmed = (val as string).trim() + if (!trimmed) { + requestSeq++ // cancel in-flight + loading.value = false + clearResults() + return + } + debounceTimer = setTimeout(() => { + const seq = ++requestSeq + runSearch(trimmed, seq) + }, debounceMs) + }) + + onMounted(() => { + // Preload KB and agent lists so name matches show up instantly on first + // keystroke. Sessions come from the menuStore (already populated by the + // sidebar) so no extra fetch needed here. + ensureKbs() + ensureAgents() + }) + + return { + query, + loading, + hasSearched, + knowledgeBases, + fileGroups, + messageGroups, + kbMatches, + agents, + agentMatches, + sessionMatches, + totalChunks, + totalMessages, + clearResults, + ensureKbs, + ensureAgents, + } +} diff --git a/frontend/src/components/GlobalCommandPalette/useStartChat.ts b/frontend/src/components/GlobalCommandPalette/useStartChat.ts new file mode 100644 index 00000000..172a8f55 --- /dev/null +++ b/frontend/src/components/GlobalCommandPalette/useStartChat.ts @@ -0,0 +1,41 @@ +import { useRouter } from 'vue-router' +import { useMenuStore } from '@/stores/menu' +import { useSettingsStore } from '@/stores/settings' + +/** + * Shared "start a new chat with query + KB/file preselected" helper. + * + * Used from: + * - Global command palette (⌘K) when user presses ⌘↵ on a result + * - KB-scoped search bar on the KB detail page + * - Empty-state "Ask AI directly" button in the palette + * + * Mirrors the legacy behavior of KnowledgeSearch.vue#startChat. + */ +export function useStartChat() { + const router = useRouter() + const menuStore = useMenuStore() + const settingsStore = useSettingsStore() + + /** + * @param query The user's query; it becomes the pre-filled first message + * @param kbIds Knowledge bases to scope the new chat to; empty means no constraint + * @param fileIds Specific knowledge/file ids to attach as context + */ + const startChat = (query: string, kbIds: string[] = [], fileIds: string[] = []) => { + const q = (query || '').trim() + if (!q) return + + if (kbIds.length > 0) { + settingsStore.selectKnowledgeBases(kbIds) + } + for (const fid of fileIds) { + settingsStore.addFile(fid) + } + + menuStore.setPrefillQuery(q) + router.push('/platform/creatChat') + } + + return { startChat } +} diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index 898e3d7a..11ccb830 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -42,6 +42,25 @@