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 @@ + + + + + + + + + {{ activeKbScope.name }} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {{ item.file.title }} + {{ item.file.kbName }} + + + + + + + + + + + + + + {{ item.group.sessionTitle || t('commandPalette.untitledSession') }} + + + {{ item.msg.query_content ? 'Q' : 'A' }} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {{ t('commandPalette.empty.noResults') }} + + + + {{ t('commandPalette.empty.askAi') }} + + + + {{ t('commandPalette.empty.adjustRetrieval') }} + + + + + + + + + + + + + + + + + + + + + + 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 @@ + + + + {{ label }} + ({{ count }}) + + + {{ action }} + + + + + + + + + + + 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 @@ + + + + + + + + + + + + + + {{ badge }} + + {{ (score * 100).toFixed(0) }}% + + + + + + + + + + + ⌘{{ shortcut }} + + + + + + + + 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 @@ + + + + + + + + + + {{ t('menu.search') }} + + {{ cmdModKeyLabel }}K + + + + + + - + {{ item.title }} @@ -148,6 +167,7 @@ import { useMenuStore } from '@/stores/menu'; import { useAuthStore } from '@/stores/auth'; import { useOrganizationStore } from '@/stores/organization'; import { useUIStore } from '@/stores/ui'; +import { useCommandPaletteStore } from '@/stores/commandPalette'; import { MessagePlugin, DialogPlugin, Icon as TIcon } from "tdesign-vue-next"; import UserMenu from '@/components/UserMenu.vue'; import TenantSelector from '@/components/TenantSelector.vue'; @@ -180,6 +200,14 @@ const usemenuStore = useMenuStore(); const authStore = useAuthStore(); const orgStore = useOrganizationStore(); const uiStore = useUIStore(); +const commandPaletteStore = useCommandPaletteStore(); + +// Platform-aware label for the ⌘K hint. navigator.platform is deprecated but +// the alternatives (userAgentData.platform) aren't universally available yet; +// this check is good enough for Mac vs. non-Mac. +const isMacLike = typeof navigator !== 'undefined' && /Mac|iPod|iPhone|iPad/.test(navigator.platform || ''); +const cmdModKeyLabel = isMacLike ? '⌘' : 'Ctrl'; +const cmdkTooltip = computed(() => `${t('menu.search')} · ${cmdModKeyLabel} K`); const route = useRoute(); const router = useRouter(); const currentpath = ref(''); @@ -254,11 +282,9 @@ const isMenuItemActive = (itemPath: string): boolean => { switch (itemPath) { case 'knowledge-bases': - return currentRoute === 'knowledgeBaseList' || - currentRoute === 'knowledgeBaseDetail' || + return currentRoute === 'knowledgeBaseList' || + currentRoute === 'knowledgeBaseDetail' || currentRoute === 'knowledgeBaseSettings'; - case 'knowledge-search': - return currentRoute === 'knowledgeSearch'; case 'agents': return currentRoute === 'agentList'; case 'organizations': @@ -290,14 +316,14 @@ const getIconActiveState = (itemPath: string) => { // 分离上下两部分菜单(使用 visibleMenuArr 以便 lite 模式过滤 logout) const topMenuItems = computed(() => { - return (visibleMenuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => - item.path === 'knowledge-bases' || item.path === 'knowledge-search' || item.path === 'agents' || item.path === 'organizations' || item.path === 'creatChat' + return (visibleMenuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => + item.path === 'knowledge-bases' || item.path === 'agents' || item.path === 'organizations' || item.path === 'creatChat' ); }); const bottomMenuItems = computed(() => { return (visibleMenuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => { - if (item.path === 'knowledge-bases' || item.path === 'knowledge-search' || item.path === 'agents' || item.path === 'organizations' || item.path === 'creatChat') { + if (item.path === 'knowledge-bases' || item.path === 'agents' || item.path === 'organizations' || item.path === 'creatChat') { return false; } return true; @@ -720,7 +746,6 @@ watch([() => route.name, () => route.params], (newvalue, oldvalue) => { } }); let knowledgeIcon = ref('zhishiku-green.svg'); -let searchIcon = ref('search.svg'); let prefixIcon = ref('prefixIcon.svg'); let logoutIcon = ref('logout.svg'); let settingIcon = ref('setting.svg'); @@ -734,26 +759,22 @@ let pathPrefix = ref(route.name) const settingsActiveState = getIconActiveState('settings'); const agentsActiveState = route.name === 'agentList'; const organizationsActiveState = route.name === 'organizationList'; - const knowledgeSearchActiveState = route.name === 'knowledgeSearch'; - + // 知识库图标:只在知识库页面显示绿色 knowledgeIcon.value = kbActiveState.isKbActive ? 'zhishiku-green.svg' : 'zhishiku.svg'; - - // 知识搜索图标:只在知识搜索页面显示绿色 - searchIcon.value = knowledgeSearchActiveState ? 'search-green.svg' : 'search.svg'; - + // 智能体图标:只在智能体页面显示绿色 agentIcon.value = agentsActiveState ? 'agent-green.svg' : 'agent.svg'; - + // 组织图标:只在组织页面显示绿色 organizationIcon.value = organizationsActiveState ? 'organization-green.svg' : 'organization.svg'; - + // 对话图标:只在对话创建页面显示绿色,其他情况显示默认 prefixIcon.value = creatChatActiveState.isCreatChatActive ? 'prefixIcon-green.svg' : 'prefixIcon.svg'; - + // 设置图标:只在设置页面显示绿色 settingIcon.value = settingsActiveState.isSettingsActive ? 'setting-green.svg' : 'setting.svg'; - + // 退出图标:始终显示默认 logoutIcon.value = 'logout.svg'; } @@ -767,8 +788,6 @@ const handleMenuClick = async (path: string) => { } else { router.push('/platform/knowledge-bases') } - } else if (path === 'knowledge-search') { - router.push('/platform/knowledge-search') } else if (path === 'agents') { router.push('/platform/agents') } else if (path === 'organizations') { @@ -1104,7 +1123,7 @@ const onDragHandleMouseDown = (e: MouseEvent) => { } .menu_title { - color: var(--td-text-color-secondary); + color: var(--td-text-color-primary); text-overflow: ellipsis; font-family: var(--app-font-family); font-size: 14px; @@ -1188,7 +1207,7 @@ const onDragHandleMouseDown = (e: MouseEvent) => { cursor: pointer; display: flex; align-items: center; - color: var(--td-text-color-secondary); + color: var(--td-text-color-primary); font-weight: 400; line-height: 22px; height: 36px; @@ -1400,6 +1419,35 @@ const onDragHandleMouseDown = (e: MouseEvent) => { opacity: 1; } +.menu-cmdk-hint { + margin-left: auto; + margin-right: 8px; + display: inline-flex; + align-items: center; + gap: 2px; + flex-shrink: 0; + opacity: 0.7; + transition: opacity 0.2s ease; + + kbd { + display: inline-block; + padding: 0 4px; + min-width: 14px; + font-size: 10px; + font-family: inherit; + line-height: 14px; + text-align: center; + background: var(--td-bg-color-secondarycontainer); + border: 1px solid var(--td-component-stroke); + border-radius: 3px; + color: var(--td-text-color-secondary); + } +} + +.menu_item--cmdk:hover .menu-cmdk-hint { + opacity: 1; +} + .menu-pending-badge { min-width: 18px; height: 18px; diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 47ba2419..7c954498 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -22,7 +22,7 @@ export default { unpinFailed: 'Failed to unpin, please try again later', confirmLogout: 'Are you sure you want to logout?', systemInfo: 'System Information', - knowledgeSearch: 'Search', + search: 'Search', collapseSidebar: 'Collapse Sidebar', expandSidebar: 'Expand Sidebar', logoutSuccess: 'Logged out successfully', @@ -146,6 +146,11 @@ export default { channelDingtalk: 'DingTalk', channelSlack: 'Slack', channelIm: 'IM Channel', + channelNotion: 'Notion', + channelYuque: 'Yuque', + channelUpload: 'Upload', + channelManual: 'Manual', + channelUrl: 'Web', channelUnknown: 'Unknown', urlSource: 'Source URL', documentTitle: 'Document Title', @@ -255,6 +260,7 @@ export default { columnTag: 'Tag', columnSize: 'Size', columnType: 'Type', + columnSource: 'Source', columnStatus: 'Status', columnUpdatedAt: 'Updated', columnActions: 'Actions', @@ -3363,6 +3369,50 @@ export default { audioLoading: 'Loading audio…', audioNotSupported: 'Your browser does not support audio playback', }, + commandPalette: { + placeholder: 'Search knowledge bases, files, conversations…', + searching: 'Searching…', + clearRecent: 'Clear', + retrieval: 'Retrieval settings', + untitledSession: 'Untitled conversation', + scope: { + placeholder: 'Search within this knowledge base…', + remove: 'Remove scope (Backspace)', + }, + group: { + chunks: 'Files', + messages: 'Messages', + kbs: 'Knowledge bases', + agents: 'Agents', + sessionsByTitle: 'Chats (by title)', + commands: 'Commands', + recent: 'Recent', + quickActions: 'Quick actions', + }, + match: { + vector: 'Vector', + keyword: 'Keyword', + }, + quick: { + newChat: 'New conversation', + knowledgeBases: 'Open knowledge bases', + agents: 'Open agents', + organizations: 'Open shared spaces', + settings: 'Open settings', + }, + empty: { + noResults: 'No matches found', + askAi: 'Ask the AI directly', + adjustRetrieval: 'Adjust retrieval', + }, + hotkey: { + select: 'Navigate', + enter: 'Open', + cmdNumber: 'Jump to', + cmdEnter: 'Start chat', + esc: 'Close', + }, + }, knowledgeSearch: { title: 'Search', subtitle: 'Semantic search across knowledge bases and chat history to find relevant content', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 8d3390ba..283ffa5c 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -22,7 +22,7 @@ export default { unpinFailed: "고정 해제 실패, 나중에 다시 시도해 주세요", confirmLogout: "정말 로그아웃 하시겠습니까?", systemInfo: "시스템 정보", - knowledgeSearch: "검색", + search: "검색", collapseSidebar: "사이드바 접기", expandSidebar: "사이드바 펼치기", logoutSuccess: "로그아웃되었습니다", @@ -146,6 +146,11 @@ export default { channelDingtalk: "DingTalk", channelSlack: "Slack", channelIm: "IM 채널", + channelNotion: "Notion", + channelYuque: "Yuque", + channelUpload: "업로드", + channelManual: "수동", + channelUrl: "웹", channelUnknown: "알 수 없음", urlSource: "원본 URL", documentTitle: "문서 제목", @@ -259,6 +264,7 @@ export default { columnTag: "태그", columnSize: "크기", columnType: "유형", + columnSource: "소스", columnStatus: "상태", columnUpdatedAt: "업데이트", columnActions: "작업", @@ -3431,6 +3437,50 @@ export default { audioLoading: '오디오 로딩 중…', audioNotSupported: '브라우저가 오디오 재생을 지원하지 않습니다', }, + commandPalette: { + placeholder: '지식베이스, 파일, 대화 검색…', + searching: '검색 중…', + clearRecent: '지우기', + retrieval: '검색 설정', + untitledSession: '제목 없는 대화', + scope: { + placeholder: '이 지식베이스에서 검색…', + remove: '범위 해제 (Backspace)', + }, + group: { + chunks: '지식베이스 파일', + messages: '대화 메시지', + kbs: '지식베이스', + agents: '에이전트', + sessionsByTitle: '대화(제목별)', + commands: '명령', + recent: '최근 검색', + quickActions: '빠른 작업', + }, + match: { + vector: '벡터', + keyword: '키워드', + }, + quick: { + newChat: '새 대화', + knowledgeBases: '지식베이스 열기', + agents: '에이전트 열기', + organizations: '공유 공간 열기', + settings: '설정 열기', + }, + empty: { + noResults: '일치하는 결과 없음', + askAi: 'AI에게 직접 질문하기', + adjustRetrieval: '검색 설정 조정', + }, + hotkey: { + select: '이동', + enter: '열기', + cmdNumber: '바로 이동', + cmdEnter: '대화 시작', + esc: '닫기', + }, + }, knowledgeSearch: { title: '검색', subtitle: '지식베이스와 대화 기록에서 시맨틱 검색으로 관련 콘텐츠를 빠르게 찾으세요', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 6e98cf36..6e9f6ccf 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -20,7 +20,7 @@ export default { unpinFailed: 'Не удалось открепить, попробуйте позже', confirmLogout: 'Вы уверены, что хотите выйти?', systemInfo: 'Информация о системе', - knowledgeSearch: 'Поиск', + search: 'Поиск', collapseSidebar: 'Свернуть боковую панель', expandSidebar: 'Развернуть боковую панель', logoutSuccess: 'Вы вышли из системы', @@ -127,6 +127,11 @@ export default { channelDingtalk: 'DingTalk', channelSlack: 'Slack', channelIm: 'IM канал', + channelNotion: 'Notion', + channelYuque: 'Yuque', + channelUpload: 'Загрузка', + channelManual: 'Вручную', + channelUrl: 'Веб', channelUnknown: 'Неизвестно', urlSource: 'Исходный URL', documentTitle: 'Название документа', @@ -227,6 +232,7 @@ export default { columnTag: 'Тег', columnSize: 'Размер', columnType: 'Тип', + columnSource: 'Источник', columnStatus: 'Статус', columnUpdatedAt: 'Обновлено', columnActions: 'Действия', @@ -3041,6 +3047,50 @@ export default { audioLoading: 'Загрузка аудио…', audioNotSupported: 'Ваш браузер не поддерживает воспроизведение аудио', }, + commandPalette: { + placeholder: 'Поиск по базам знаний, файлам, диалогам…', + searching: 'Поиск…', + clearRecent: 'Очистить', + retrieval: 'Параметры поиска', + untitledSession: 'Безымянный диалог', + scope: { + placeholder: 'Поиск в этой базе знаний…', + remove: 'Убрать область (Backspace)', + }, + group: { + chunks: 'Файлы базы знаний', + messages: 'Сообщения', + kbs: 'Базы знаний', + agents: 'Агенты', + sessionsByTitle: 'Диалоги (по названию)', + commands: 'Команды', + recent: 'Недавние', + quickActions: 'Быстрые действия', + }, + match: { + vector: 'Вектор', + keyword: 'Ключ.', + }, + quick: { + newChat: 'Новый диалог', + knowledgeBases: 'Открыть базы знаний', + agents: 'Открыть агенты', + organizations: 'Открыть общие пространства', + settings: 'Открыть настройки', + }, + empty: { + noResults: 'Совпадений не найдено', + askAi: 'Спросить ИИ', + adjustRetrieval: 'Настроить поиск', + }, + hotkey: { + select: 'Навигация', + enter: 'Открыть', + cmdNumber: 'Быстрый переход', + cmdEnter: 'Начать диалог', + esc: 'Закрыть', + }, + }, knowledgeSearch: { title: 'Поиск', subtitle: 'Семантический поиск по базам знаний и истории сообщений для быстрого нахождения релевантного контента', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 9ad2ca05..94edd23e 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -22,7 +22,7 @@ export default { unpinFailed: "取消置顶失败,请稍后再试", confirmLogout: "确定要退出登录吗?", systemInfo: "系统信息", - knowledgeSearch: "搜索", + search: "搜索", collapseSidebar: "收起侧边栏", expandSidebar: "展开侧边栏", logoutSuccess: "已退出登录", @@ -145,6 +145,11 @@ export default { channelDingtalk: "钉钉", channelSlack: "Slack", channelIm: "IM 渠道", + channelNotion: "Notion", + channelYuque: "语雀", + channelUpload: "上传", + channelManual: "手动", + channelUrl: "网页", channelUnknown: "未知", urlSource: "来源网址", documentTitle: "文档标题", @@ -256,6 +261,7 @@ export default { columnTag: "标签", columnSize: "大小", columnType: "类型", + columnSource: "来源", columnStatus: "状态", columnUpdatedAt: "更新时间", columnActions: "操作", @@ -3360,6 +3366,50 @@ export default { audioLoading: "加载音频中…", audioNotSupported: "您的浏览器不支持音频播放", }, + commandPalette: { + placeholder: "搜索知识库、文件、对话…", + searching: "搜索中…", + clearRecent: "清除", + retrieval: "检索参数", + untitledSession: "未命名对话", + scope: { + placeholder: "在本知识库中搜索…", + remove: "移除范围过滤(Backspace)", + }, + group: { + chunks: "知识库文件", + messages: "对话消息", + kbs: "知识库", + agents: "智能体", + sessionsByTitle: "对话(按标题)", + commands: "命令", + recent: "最近搜索", + quickActions: "快捷操作", + }, + match: { + vector: "向量", + keyword: "关键字", + }, + quick: { + newChat: "新建对话", + knowledgeBases: "打开知识库", + agents: "打开智能体", + organizations: "打开共享空间", + settings: "打开设置", + }, + empty: { + noResults: "没有找到匹配结果", + askAi: "直接向 AI 提问", + adjustRetrieval: "调整检索参数", + }, + hotkey: { + select: "选择", + enter: "打开", + cmdNumber: "直接打开", + cmdEnter: "发起对话", + esc: "关闭", + }, + }, knowledgeSearch: { title: "搜索", subtitle: "在知识库和历史对话中进行语义检索,快速查找相关内容", diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 1623fd19..ae9ced41 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -101,9 +101,14 @@ const router = createRouter({ }, { path: "knowledge-search", - name: "knowledgeSearch", - component: () => import("../views/knowledge/KnowledgeSearch.vue"), - meta: { requiresInit: true, requiresAuth: true } + // 旧路径保留为重定向,打开全局命令面板(⌘K),带上可选的 q 参数 + redirect: (to) => { + const q = to.query.q + return { + path: '/platform/knowledge-bases', + query: typeof q === 'string' ? { cmdk: q } : { cmdk: '' }, + } + }, }, { path: "agents", diff --git a/frontend/src/stores/commandPalette.ts b/frontend/src/stores/commandPalette.ts new file mode 100644 index 00000000..4d145f5b --- /dev/null +++ b/frontend/src/stores/commandPalette.ts @@ -0,0 +1,73 @@ +import { defineStore } from 'pinia' +import { ref } from 'vue' + +const RECENT_KEY = 'weknora_cmdk_recent' +const RECENT_LIMIT = 4 + +/** + * Pinia store for the global command palette (⌘K / Ctrl+K). + * The palette itself is rendered once in platform/index.vue. + * Any code (router redirect, deep link, programmatic trigger) can open it + * by calling openPalette(q). + */ +export const useCommandPaletteStore = defineStore('commandPalette', () => { + const open = ref(false) + const initialQuery = ref('') + const recentQueries = ref([]) + + const loadRecent = () => { + try { + const raw = localStorage.getItem(RECENT_KEY) + recentQueries.value = raw ? JSON.parse(raw) : [] + } catch { + recentQueries.value = [] + } + } + + const openPalette = (query = '') => { + initialQuery.value = query + open.value = true + } + + const closePalette = () => { + open.value = false + initialQuery.value = '' + } + + const pushRecent = (q: string) => { + const trimmed = q.trim() + if (!trimmed) return + recentQueries.value = [ + trimmed, + ...recentQueries.value.filter(x => x !== trimmed), + ].slice(0, RECENT_LIMIT) + try { + localStorage.setItem(RECENT_KEY, JSON.stringify(recentQueries.value)) + } catch { + /* ignore quota errors */ + } + } + + const clearRecent = () => { + recentQueries.value = [] + try { + localStorage.removeItem(RECENT_KEY) + } catch { + /* ignore */ + } + } + + // Load recent queries immediately on store creation. + loadRecent() + + return { + open, + initialQuery, + recentQueries, + openPalette, + closePalette, + pushRecent, + clearRecent, + loadRecent, + } +}) diff --git a/frontend/src/stores/menu.ts b/frontend/src/stores/menu.ts index 9bc418d2..bb9fb731 100644 --- a/frontend/src/stores/menu.ts +++ b/frontend/src/stores/menu.ts @@ -19,7 +19,6 @@ const createMenuChildren = () => reactive([]) export const useMenuStore = defineStore('menuStore', () => { const menuArr = reactive([ { title: '', titleKey: 'menu.knowledgeBase', icon: 'zhishiku', path: 'knowledge-bases' }, - { title: '', titleKey: 'menu.knowledgeSearch', icon: 'search', path: 'knowledge-search' }, { title: '', titleKey: 'menu.agents', icon: 'agent', path: 'agents' }, { title: '', titleKey: 'menu.organizations', icon: 'organization', path: 'organizations' }, { diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index ab3b007d..db6270ba 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -788,7 +788,12 @@ const handleOpenURLImportDialog = (event: CustomEvent) => { } }; -// Auto-open document detail when navigated with ?knowledge_id=xxx +// Auto-open document detail when navigated with ?knowledge_id=xxx. +// Note: this runs both when the KB page mounts with a query param AND when a +// subsequent in-page navigation (e.g. from the global command palette) only +// changes the query without re-mounting the component — in that case kbId is +// the same and cardList may already be populated, so relying solely on the +// cardList watcher misses the trigger. const pendingKnowledgeId = ref( (route.query.knowledge_id as string) || null ); @@ -807,6 +812,29 @@ const tryAutoOpenDocument = () => { } }; +// React to later ?knowledge_id= changes on the same KB route (no remount). +watch( + () => route.query.knowledge_id, + (newId) => { + if (typeof newId !== 'string' || !newId) return; + pendingKnowledgeId.value = newId; + // cardList is almost always already loaded at this point; if not, the + // cardList watcher below will pick it up. + tryAutoOpenDocument(); + }, +); + +// Dispatched by the global command palette when the user picks a chunk that +// lives in the KB they are already viewing — vue-router dedupes identical +// navigations, so we rely on this event instead of a URL change. +const handleOpenKnowledgeEvent = (e: Event) => { + const detail = (e as CustomEvent<{ kbId: string; knowledgeId: string }>).detail; + if (!detail || !detail.knowledgeId) return; + if (detail.kbId && detail.kbId !== kbId.value) return; + pendingKnowledgeId.value = detail.knowledgeId; + tryAutoOpenDocument(); +}; + onMounted(() => { loadKnowledgeBaseInfo(kbId.value); loadKnowledgeList(); @@ -818,11 +846,13 @@ onMounted(() => { window.addEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener); window.addEventListener('openURLImportDialog', handleOpenURLImportDialog as EventListener); + window.addEventListener('weknora:open-knowledge', handleOpenKnowledgeEvent as EventListener); }); onUnmounted(() => { window.removeEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener); window.removeEventListener('openURLImportDialog', handleOpenURLImportDialog as EventListener); + window.removeEventListener('weknora:open-knowledge', handleOpenKnowledgeEvent as EventListener); stopMovePoll(); if (timeout !== null) { clearTimeout(timeout); diff --git a/frontend/src/views/knowledge/KnowledgeSearch.vue b/frontend/src/views/knowledge/KnowledgeSearch.vue deleted file mode 100644 index 33919ec6..00000000 --- a/frontend/src/views/knowledge/KnowledgeSearch.vue +++ /dev/null @@ -1,1163 +0,0 @@ - - - - - - {{ $t('knowledgeSearch.title') }} - {{ $t('knowledgeSearch.subtitle') }} - - - - - - - - - - - - - - - - - - {{ $t('knowledgeSearch.tabKnowledge') }} - - - - {{ $t('knowledgeSearch.tabMessages') }} - - - - - - - - - - - - - {{ kb.name }} - - {{ kb.type === 'faq' ? 'FAQ' : 'DOC' }} - - - - - - {{ $t('knowledgeSearch.searchBtn') }} - - - - - - - - - - - - {{ $t('knowledgeSearch.emptyHint') }} - - - - - - - - - - - - - {{ $t('knowledgeSearch.noResults') }} - - - - - - - {{ $t('knowledgeSearch.resultCount', { count: totalChunks }) }} - · {{ groupedResults.length }} {{ $t('knowledgeSearch.fileCount') }} - - - - {{ $t('knowledgeSearch.startChat') }} - - - - - - - - - - - - {{ group.title }} - {{ group.kbName }} - - - {{ group.chunks.length }} {{ $t('knowledgeSearch.chunk') }} - - - {{ $t('knowledgeSearch.chatWithFile') }} - - - {{ $t('knowledgeSearch.viewDetail') }} - - - - - - - - - - #{{ chunk.chunk_index }} - - {{ chunk.match_type === 'vector' ? $t('knowledgeSearch.matchTypeVector') : $t('knowledgeSearch.matchTypeKeyword') }} - - {{ (chunk.score * 100).toFixed(1) }}% - - - - - - - - - - - - - - - - - {{ $t('knowledgeSearch.messageEmptyHint') }} - - - - - - - - - - - - - {{ $t('knowledgeSearch.noResults') }} - - - - - - {{ $t('knowledgeSearch.resultCount', { count: msgTotal }) }} - - - - - - - {{ group.sessionTitle || $t('knowledgeSearch.untitledSession') }} - {{ group.items.length }} {{ $t('knowledgeSearch.matchCount') }} - - - - - - - - Q - - {{ formatTime(item.created_at) }} - - - - A - - - - - - - - - - - - - - - - - - diff --git a/frontend/src/views/platform/index.vue b/frontend/src/views/platform/index.vue index ff20a7c0..0fd75e3a 100644 --- a/frontend/src/views/platform/index.vue +++ b/frontend/src/views/platform/index.vue @@ -10,21 +10,27 @@ + +
{{ t('commandPalette.empty.noResults') }}
{{ $t('knowledgeSearch.subtitle') }}
{{ $t('knowledgeSearch.emptyHint') }}
{{ $t('knowledgeSearch.noResults') }}
{{ $t('knowledgeSearch.messageEmptyHint') }}