Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(frontend): replace standalone search page with global command palette

wizardchen2d3f32de5c47
diff --git a/frontend/src/components/GlobalCommandPalette.vue b/frontend/src/components/GlobalCommandPalette.vue
new file mode 100644
index 000000000..b499a873c
--- /dev/null
+++ b/frontend/src/components/GlobalCommandPalette.vue
@@ -0,0 +1,970 @@
+<template>
+ <t-dialog
+ v-model:visible="dialogVisible"
+ :footer="false"
+ :header="false"
+ :close-btn="false"
+ width="640px"
+ top="10vh"
+ destroy-on-close
+ class="cmdk-dialog"
+ @close="handleClose"
+ @opened="onDialogOpened"
+ >
+ <div class="cmdk" @keydown="onKeyDown">
+ <!-- Input row -->
+ <div class="cmdk__input-row">
+ <t-icon name="search" class="cmdk__input-icon" />
+ <span v-if="activeKbScope" class="cmdk__scope-chip" :title="activeKbScope.name">
+ <t-icon name="folder" size="12px" />
+ <span class="cmdk__scope-chip-name">{{ activeKbScope.name }}</span>
+ <button
+ type="button"
+ class="cmdk__scope-chip-x"
+ :title="t('commandPalette.scope.remove')"
+ :aria-label="t('commandPalette.scope.remove')"
+ @click="clearKbScope"
+ >
+ <t-icon name="close" size="12px" />
+ </button>
+ </span>
+ <input
+ ref="inputRef"
+ v-model="query"
+ type="text"
+ class="cmdk__input"
+ :placeholder="activeKbScope ? t('commandPalette.scope.placeholder') : t('commandPalette.placeholder')"
+ autofocus
+ spellcheck="false"
+ @keydown="onInputKeyDown"
+ />
+ <span v-if="loading" class="cmdk__input-spinner">
+ <t-loading size="small" />
+ </span>
+ <t-tooltip :content="t('commandPalette.retrieval')" placement="bottom">
+ <button
+ type="button"
+ class="cmdk__icon-btn"
+ :class="{ active: drawerVisible }"
+ @click="drawerVisible = true"
+ >
+ <t-icon name="setting" size="16px" />
+ </button>
+ </t-tooltip>
+ <button
+ type="button"
+ class="cmdk__icon-btn"
+ :aria-label="t('commandPalette.hotkey.esc')"
+ @click="handleClose"
+ >
+ <t-icon name="close" size="16px" />
+ </button>
+ </div>
+
+ <!-- Results -->
+ <div ref="scrollRef" class="cmdk__results">
+ <!-- Empty idle state: recent + quick actions -->
+ <template v-if="!query.trim()">
+ <ResultGroup
+ v-if="recentQueries.length"
+ :label="t('commandPalette.group.recent')"
+ :action="t('commandPalette.clearRecent')"
+ @action="commandPaletteStore.clearRecent()"
+ >
+ <ResultItem
+ v-for="(q, i) in recentQueries"
+ :key="'r-' + q"
+ icon-name="history"
+ :index="flatIndexFor('recent', i)"
+ :selected="selectedIndex === flatIndexFor('recent', i)"
+ :shortcut="shortcutFor(flatIndexFor('recent', i))"
+ :title="q"
+ @primary="query = q"
+ @hover="selectItemAt($event)"
+ />
+ </ResultGroup>
+
+ <ResultGroup :label="t('commandPalette.group.quickActions')">
+ <ResultItem
+ v-for="(c, i) in allCommands"
+ :key="'cmd-' + c.id"
+ :index="flatIndexFor('commands', i)"
+ :selected="selectedIndex === flatIndexFor('commands', i)"
+ :shortcut="shortcutFor(flatIndexFor('commands', i))"
+ :icon-name="c.icon"
+ :title="c.label"
+ @primary="c.run"
+ @hover="selectItemAt($event)"
+ />
+ </ResultGroup>
+ </template>
+
+ <!-- Active search results -->
+ <template v-else>
+ <!-- Chunks (per file) -->
+ <ResultGroup
+ v-if="isGroupVisible('chunks') && fileGroups.length"
+ :label="t('commandPalette.group.chunks')"
+ :count="totalChunks"
+ >
+ <template v-for="(item, i) in flatChunkItems" :key="'c-' + item.file.knowledgeId + '-' + item.chunk.id">
+ <ResultItem
+ :index="flatIndexFor('chunks', i)"
+ :selected="selectedIndex === flatIndexFor('chunks', i)"
+ :shortcut="shortcutFor(flatIndexFor('chunks', i))"
+ icon-name="file"
+ :badge="item.chunk.match_type === 'vector' ? t('commandPalette.match.vector') : t('commandPalette.match.keyword')"
+ :badge-variant="item.chunk.match_type === 'vector' ? 'vector' : 'keyword'"
+ :score="item.chunk.score"
+ @primary="openChunk(item)"
+ @hover="selectItemAt($event)"
+ >
+ <template #title>
+ <span class="cmdk-chunk-title">{{ item.file.title }}</span>
+ <span v-if="item.file.kbName" class="cmdk-chunk-kb">{{ item.file.kbName }}</span>
+ </template>
+ <template #subtitle>
+ <span v-html="highlight(item.chunk.matched_content || item.chunk.content)" />
+ </template>
+ </ResultItem>
+ </template>
+ </ResultGroup>
+
+ <!-- Messages -->
+ <ResultGroup
+ v-if="isGroupVisible('messages') && messageGroups.length"
+ :label="t('commandPalette.group.messages')"
+ :count="totalMessages"
+ >
+ <template v-for="(item, i) in flatMessageItems" :key="'m-' + item.msg.request_id">
+ <ResultItem
+ :index="flatIndexFor('messages', i)"
+ :selected="selectedIndex === flatIndexFor('messages', i)"
+ :shortcut="shortcutFor(flatIndexFor('messages', i))"
+ icon-name="chat"
+ :score="item.msg.score"
+ @primary="openMessage(item)"
+ @hover="selectItemAt($event)"
+ >
+ <template #title>
+ <span>{{ item.group.sessionTitle || t('commandPalette.untitledSession') }}</span>
+ </template>
+ <template #subtitle>
+ <span class="cmdk-msg-role">{{ item.msg.query_content ? 'Q' : 'A' }}</span>
+ <span v-html="highlight(item.msg.query_content || item.msg.answer_content)" />
+ </template>
+ </ResultItem>
+ </template>
+ </ResultGroup>
+
+ <!-- KB name matches -->
+ <ResultGroup
+ v-if="isGroupVisible('kbs') && kbMatches.length"
+ :label="t('commandPalette.group.kbs')"
+ >
+ <ResultItem
+ v-for="(kb, i) in kbMatches"
+ :key="'k-' + kb.id"
+ :index="flatIndexFor('kbs', i)"
+ :selected="selectedIndex === flatIndexFor('kbs', i)"
+ :shortcut="shortcutFor(flatIndexFor('kbs', i))"
+ icon-name="folder"
+ :title="kb.name"
+ @primary="openKb(kb.id)"
+ @hover="selectItemAt($event)"
+ />
+ </ResultGroup>
+
+ <!-- Agent matches -->
+ <ResultGroup
+ v-if="isGroupVisible('agents') && agentMatches.length"
+ :label="t('commandPalette.group.agents')"
+ >
+ <ResultItem
+ v-for="(a, i) in agentMatches"
+ :key="'a-' + a.id"
+ :index="flatIndexFor('agents', i)"
+ :selected="selectedIndex === flatIndexFor('agents', i)"
+ :shortcut="shortcutFor(flatIndexFor('agents', i))"
+ icon-name="user-circle"
+ :title="a.name"
+ :subtitle="a.description"
+ @primary="openAgent(a.id)"
+ @hover="selectItemAt($event)"
+ />
+ </ResultGroup>
+
+ <!-- Session (chat) title matches -->
+ <ResultGroup
+ v-if="isGroupVisible('sessions') && sessionMatches.length"
+ :label="t('commandPalette.group.sessionsByTitle')"
+ >
+ <ResultItem
+ v-for="(s, i) in sessionMatches"
+ :key="'s-' + s.id"
+ :index="flatIndexFor('sessions', i)"
+ :selected="selectedIndex === flatIndexFor('sessions', i)"
+ :shortcut="shortcutFor(flatIndexFor('sessions', i))"
+ icon-name="chat"
+ :title="s.title"
+ @primary="openSession(s.id)"
+ @hover="selectItemAt($event)"
+ />
+ </ResultGroup>
+
+ <!-- Commands matching the query -->
+ <ResultGroup
+ v-if="isGroupVisible('commands') && filteredCommands.length"
+ :label="t('commandPalette.group.commands')"
+ >
+ <ResultItem
+ v-for="(c, i) in filteredCommands"
+ :key="'fcmd-' + c.id"
+ :index="flatIndexFor('commands', i)"
+ :selected="selectedIndex === flatIndexFor('commands', i)"
+ :shortcut="shortcutFor(flatIndexFor('commands', i))"
+ :icon-name="c.icon"
+ :title="c.label"
+ @primary="c.run"
+ @hover="selectItemAt($event)"
+ />
+ </ResultGroup>
+
+ <!-- No results -->
+ <div
+ v-if="!loading && !hasAnyResults && hasSearched"
+ class="cmdk__empty"
+ >
+ <p>{{ t('commandPalette.empty.noResults') }}</p>
+ <div class="cmdk__empty-actions">
+ <t-button theme="primary" variant="outline" size="small" @click="askAi">
+ <template #icon><t-icon name="chat" size="14px" /></template>
+ {{ t('commandPalette.empty.askAi') }}
+ </t-button>
+ <t-button variant="outline" size="small" @click="drawerVisible = true">
+ <template #icon><t-icon name="setting" size="14px" /></template>
+ {{ t('commandPalette.empty.adjustRetrieval') }}
+ </t-button>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <!-- Hotkey footer -->
+ <div class="cmdk__footer">
+ <span class="cmdk__hotkey"><kbd>↑</kbd><kbd>↓</kbd> {{ t('commandPalette.hotkey.select') }}</span>
+ <span class="cmdk__hotkey"><kbd>↵</kbd> {{ t('commandPalette.hotkey.enter') }}</span>
+ <span class="cmdk__hotkey"><kbd>⌘</kbd><kbd>1</kbd>-<kbd>9</kbd> {{ t('commandPalette.hotkey.cmdNumber') }}</span>
+ <span class="cmdk__hotkey"><kbd>⌘</kbd><kbd>↵</kbd> {{ t('commandPalette.hotkey.cmdEnter') }}</span>
+ <span class="cmdk__hotkey"><kbd>Esc</kbd> {{ t('commandPalette.hotkey.esc') }}</span>
+ </div>
+ </div>
+
+ <!-- Retrieval settings drawer (layered on top of the palette) -->
+ <t-drawer
+ v-model:visible="drawerVisible"
+ :header="t('retrievalSettings.title')"
+ size="420px"
+ :footer="false"
+ :close-on-overlay-click="true"
+ class="cmdk-retrieval-drawer"
+ >
+ <RetrievalSettings />
+ </t-drawer>
+ </t-dialog>
+</template>
+
+<script setup lang="ts">
+import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { useRoute, useRouter } from 'vue-router'
+import { storeToRefs } from 'pinia'
+import { useCommandPaletteStore } from '@/stores/commandPalette'
+import { useCmdkSearch, type CmdkFileGroup, type CmdkChunk, type CmdkMsgGroup } from './GlobalCommandPalette/useSearch'
+import { highlightText } from './GlobalCommandPalette/useHighlight'
+import { useStartChat } from './GlobalCommandPalette/useStartChat'
+import { buildCommands, filterCommands } from './GlobalCommandPalette/commands'
+import ResultGroup from './GlobalCommandPalette/ResultGroup.vue'
+import ResultItem from './GlobalCommandPalette/ResultItem.vue'
+import RetrievalSettings from '@/views/settings/RetrievalSettings.vue'
+import type { MessageSearchGroupItem } from '@/api/chat-history'
+
+const { t } = useI18n()
+const route = useRoute()
+const router = useRouter()
+const commandPaletteStore = useCommandPaletteStore()
+const { open, initialQuery, recentQueries } = storeToRefs(commandPaletteStore)
+const { startChat } = useStartChat()
+
+// Per-group display caps — keep the palette compact.
+const CHUNK_LIMIT = 5
+const MSG_LIMIT = 4
+
+// Active KB scope: when the palette opens on a KB detail page, we default to
+// searching within that KB. The user can remove the chip to expand scope.
+const activeKbScope = ref<{ id: string; name: string } | null>(null)
+const scopeDismissed = ref(false) // user clicked ✕, remember for this session
+
+const {
+ query, loading, hasSearched,
+ fileGroups, messageGroups, kbMatches,
+ knowledgeBases,
+ agentMatches, sessionMatches,
+ totalChunks, totalMessages,
+ clearResults,
+} = useCmdkSearch({
+ lockedKbIds: () => (activeKbScope.value ? [activeKbScope.value.id] : []),
+})
+
+const drawerVisible = ref(false)
+const inputRef = ref<HTMLInputElement | null>(null)
+const scrollRef = ref<HTMLElement | null>(null)
+
+// Selection is identity-based (by item key) rather than positional, so
+// results arriving asynchronously (e.g. slow KB search) can't silently
+// reassign the user's highlight to a different row. `selectedIndex` is
+// derived: it's the current position of `selectedKey` in flatItems, or 0 if
+// the selected item is gone.
+const selectedKey = ref<string | null>(null)
+
+// Proxy the store's `open` to t-dialog v-model.
+const dialogVisible = computed<boolean>({
+ get: () => open.value,
+ set: (v) => {
+ if (!v) handleClose()
+ },
+})
+
+// Flatten visible items into one indexable list for keyboard nav.
+interface FlatChunkItem { kind: 'chunk'; file: CmdkFileGroup; chunk: CmdkChunk }
+interface FlatMsgItem { kind: 'msg'; group: CmdkMsgGroup; msg: MessageSearchGroupItem }
+
+const flatChunkItems = computed<FlatChunkItem[]>(() => {
+ const out: FlatChunkItem[] = []
+ for (const f of fileGroups.value) {
+ for (const c of f.chunks) {
+ out.push({ kind: 'chunk', file: f, chunk: c })
+ if (out.length >= CHUNK_LIMIT) return out
+ }
+ }
+ return out
+})
+
+const flatMessageItems = computed<FlatMsgItem[]>(() => {
+ const out: FlatMsgItem[] = []
+ for (const g of messageGroups.value) {
+ for (const m of g.items) {
+ out.push({ kind: 'msg', group: g, msg: m })
+ if (out.length >= MSG_LIMIT) return out
+ }
+ }
+ return out
+})
+
+// ─── Commands ───
+// All palette commands live in a shared module so quick-action (empty state)
+// and the "commands" tab can use the same data.
+const allCommands = computed(() =>
+ buildCommands({
+ router,
+ t,
+ close: () => commandPaletteStore.closePalette(),
+ }),
+)
+
+const filteredCommands = computed(() => filterCommands(allCommands.value, query.value))
+
+// Stable index layout — keep group order consistent so flatIndexFor is cheap.
+// Groups always render in the same order; individual groups hide themselves
+// when their backing list is empty, so users with nothing to show don't see
+// empty headers.
+const groupOrder = computed<readonly string[]>(() => {
+ if (!query.value.trim()) {
+ // Empty state: recents + full command list.
+ return ['recent', 'commands'] as const
+ }
+ if (activeKbScope.value) {
+ // Scoped to one KB: only chunks make sense (messages disabled in useSearch).
+ return ['chunks'] as const
+ }
+ return ['chunks', 'messages', 'kbs', 'agents', 'sessions', 'commands'] as const
+})
+
+const groupSizes = computed<Record<string, number>>(() => ({
+ recent: recentQueries.value.length,
+ commands: query.value.trim() ? filteredCommands.value.length : allCommands.value.length,
+ chunks: flatChunkItems.value.length,
+ messages: flatMessageItems.value.length,
+ kbs: kbMatches.value.length,
+ agents: agentMatches.value.length,
+ sessions: sessionMatches.value.length,
+}))
+
+const flatIndexFor = (group: string, localIndex: number): number => {
+ let base = 0
+ for (const g of groupOrder.value) {
+ if (g === group) return base + localIndex
+ base += groupSizes.value[g] || 0
+ }
+ return base + localIndex
+}
+
+/**
+ * Unified flattened list driving keyboard nav, ⌘N shortcuts and the primary
+ * action. Each entry carries a stable `key` (so selection survives async
+ * result arrivals) plus a `run` callback. Order follows `groupOrder`.
+ */
+interface FlatItem {
+ key: string
+ group: string
+ run: (ev?: { cmd: boolean }) => void
+}
+
+const flatItems = computed<FlatItem[]>(() => {
+ const out: FlatItem[] = []
+ for (const g of groupOrder.value) {
+ if (g === 'recent') {
+ recentQueries.value.forEach((q, i) => {
+ out.push({
+ key: `recent:${i}:${q}`,
+ group: g,
+ run: () => { query.value = q },
+ })
+ })
+ } else if (g === 'commands') {
+ const list = query.value.trim() ? filteredCommands.value : allCommands.value
+ list.forEach((cmd) => {
+ out.push({ key: `cmd:${cmd.id}`, group: g, run: () => cmd.run() })
+ })
+ } else if (g === 'chunks') {
+ flatChunkItems.value.forEach((item) => {
+ out.push({
+ key: `chunk:${item.chunk.id}`,
+ group: g,
+ run: (ev) => (ev?.cmd ? cmdEnterChunk(item) : openChunk(item)),
+ })
+ })
+ } else if (g === 'messages') {
+ flatMessageItems.value.forEach((item) => {
+ out.push({
+ key: `msg:${item.msg.request_id}`,
+ group: g,
+ run: () => openMessage(item),
+ })
+ })
+ } else if (g === 'kbs') {
+ kbMatches.value.forEach((kb) => {
+ out.push({ key: `kb:${kb.id}`, group: g, run: () => openKb(kb.id) })
+ })
+ } else if (g === 'agents') {
+ agentMatches.value.forEach((a) => {
+ out.push({ key: `agent:${a.id}`, group: g, run: () => openAgent(a.id) })
+ })
+ } else if (g === 'sessions') {
+ sessionMatches.value.forEach((s) => {
+ out.push({ key: `session:${s.id}`, group: g, run: () => openSession(s.id) })
+ })
+ }
+ }
+ return out
+})
+
+const totalItems = computed(() => flatItems.value.length)
+
+/** Derived: position of the currently-selected item, or 0 if it no longer exists. */
+const selectedIndex = computed<number>(() => {
+ if (!selectedKey.value) return 0
+ const idx = flatItems.value.findIndex((it) => it.key === selectedKey.value)
+ return idx >= 0 ? idx : 0
+})
+
+const hasAnyResults = computed(() => {
+ // "Any result" means at least one of the groups visible under the current
+ // state has items. The empty-state message should only appear when the user
+ // really has nothing to click on.
+ for (const g of groupOrder.value) {
+ if ((groupSizes.value[g] || 0) > 0) return true
+ }
+ return false
+})
+
+/** Whether a named group should be rendered under the current state. */
+const isGroupVisible = (name: string): boolean => groupOrder.value.includes(name as never)
+
+// ─── Navigation helpers ───
+
+const primaryActionForSelected = (ev?: { cmd: boolean }) => {
+ const item = flatItems.value[selectedIndex.value]
+ item?.run(ev)
+}
+
+const openChunk = (item: FlatChunkItem) => {
+ commandPaletteStore.pushRecent(query.value)
+ commandPaletteStore.closePalette()
+ if (!item.file.kbId) return
+ const currentKbId = typeof route.params.kbId === 'string' ? route.params.kbId : ''
+ // If the user is already on this KB page, router.push to the same path+query
+ // is a no-op (vue-router dedupes identical navigations), so the document
+ // auto-open logic never fires. Dispatch a global event that KnowledgeBase.vue
+ // listens for instead; this also avoids reloading the KB list on every click.
+ if (currentKbId === item.file.kbId) {
+ window.dispatchEvent(
+ new CustomEvent('weknora:open-knowledge', {
+ detail: { kbId: item.file.kbId, knowledgeId: item.file.knowledgeId },
+ }),
+ )
+ return
+ }
+ router.push({
+ path: `/platform/knowledge-bases/${item.file.kbId}`,
+ query: { knowledge_id: item.file.knowledgeId },
+ })
+}
+
+const cmdEnterChunk = (item: FlatChunkItem) => {
+ commandPaletteStore.pushRecent(query.value)
+ commandPaletteStore.closePalette()
+ const kbIds = item.file.kbId ? [item.file.kbId] : []
+ startChat(query.value, kbIds, [item.file.knowledgeId])
+}
+
+const openMessage = (item: FlatMsgItem) => {
+ commandPaletteStore.pushRecent(query.value)
+ commandPaletteStore.closePalette()
+ if (item.group.sessionId) {
+ router.push(`/platform/chat/${item.group.sessionId}`)
+ }
+}
+
+const openKb = (kbId: string) => {
+ commandPaletteStore.pushRecent(query.value)
+ commandPaletteStore.closePalette()
+ router.push(`/platform/knowledge-bases/${kbId}`)
+}
+
+// Agents have no standalone detail route; the natural "jump" is opening a new
+// chat pre-scoped to that agent — the agent editor is a modal that requires
+// more context (permissions, edit intent) so we don't trigger it from ⌘K.
+const openAgent = (agentId: string) => {
+ commandPaletteStore.pushRecent(query.value)
+ commandPaletteStore.closePalette()
+ router.push({ path: '/platform/creatChat', query: { agent_id: agentId } })
+}
+
+const openSession = (sessionId: string) => {
+ if (!sessionId) return
+ commandPaletteStore.pushRecent(query.value)
+ commandPaletteStore.closePalette()
+ router.push(`/platform/chat/${sessionId}`)
+}
+
+const askAi = () => {
+ if (!query.value.trim()) return
+ commandPaletteStore.pushRecent(query.value)
+ commandPaletteStore.closePalette()
+ startChat(query.value)
+}
+
+const highlight = (text: string) => highlightText(text, query.value)
+
+// ─── Keyboard navigation ───
+
+const scrollSelectedIntoView = () => {
+ nextTick(() => {
+ const el = scrollRef.value?.querySelector<HTMLElement>(`[data-cmdk-index="${selectedIndex.value}"]`)
+ el?.scrollIntoView({ block: 'nearest' })
+ })
+}
+
+const moveSelection = (delta: number) => {
+ const total = totalItems.value
+ if (total === 0) return
+ const next = (selectedIndex.value + delta + total) % total
+ selectedKey.value = flatItems.value[next]?.key || null
+ scrollSelectedIntoView()
+}
+
+const selectItemAt = (idx: number) => {
+ const item = flatItems.value[idx]
+ if (!item) return
+ selectedKey.value = item.key
+}
+
+/**
+ * Return the ⌘N shortcut digit for the item at the given flat index, or
+ * undefined if it's past the 9th slot. The ResultItem renders a kbd hint
+ * iff this is defined, which is the only cue the user has that ⌘1-9 works.
+ */
+const shortcutFor = (flatIndex: number): number | undefined => {
+ if (flatIndex < 0 || flatIndex > 8) return undefined
+ return flatIndex + 1
+}
+
+const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault()
+ moveSelection(1)
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault()
+ moveSelection(-1)
+ } else if (
+ (e.metaKey || e.ctrlKey) &&
+ e.key >= '1' && e.key <= '9'
+ ) {
+ // ⌘1-9 — jump straight to the Nth visible item (shortcut badge on each
+ // row reveals the binding). No modifier combos with ⌘Enter: digits take
+ // precedence because ⌘+digit can't be confused with ⌘+enter.
+ const n = parseInt(e.key, 10)
+ const item = flatItems.value[n - 1]
+ if (item) {
+ e.preventDefault()
+ item.run({ cmd: false })
+ }
+ } else if (e.key === 'Enter') {
+ e.preventDefault()
+ primaryActionForSelected({ cmd: e.metaKey || e.ctrlKey })
+ } else if (e.key === 'Escape') {
+ e.preventDefault()
+ handleClose()
+ }
+}
+
+// Keys handled specifically on the input element. Main purpose: let the user
+// escape a KB scope chip with the keyboard. Mirrors how chat apps treat
+// pill/tag tokens — Backspace on an empty input removes the preceding chip.
+const onInputKeyDown = (e: KeyboardEvent) => {
+ if (
+ e.key === 'Backspace' &&
+ !query.value &&
+ activeKbScope.value
+ ) {
+ e.preventDefault()
+ clearKbScope()
+ }
+}
+
+const handleClose = () => {
+ drawerVisible.value = false
+ commandPaletteStore.closePalette()
+}
+
+// ─── Global ⌘K shortcut ───
+
+const isEditingElement = (el: EventTarget | null): boolean => {
+ if (!el) return false
+ const node = el as HTMLElement
+ const tag = (node.tagName || '').toUpperCase()
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true
+ if (node.isContentEditable) return true
+ return false
+}
+
+const onGlobalKey = (e: KeyboardEvent) => {
+ const isCmd = e.metaKey || e.ctrlKey
+ if (isCmd && e.key.toLowerCase() === 'k') {
+ // Always allow ⌘K to open, even from an input.
+ e.preventDefault()
+ if (open.value) handleClose()
+ else commandPaletteStore.openPalette('')
+ return
+ }
+ // Plain "/" opens the palette when nothing is focused.
+ if (e.key === '/' && !open.value && !isEditingElement(e.target)) {
+ e.preventDefault()
+ commandPaletteStore.openPalette('')
+ }
+}
+
+// When the palette opens programmatically (from router redirect or elsewhere),
+// sync the query and initialize scope. Focus is moved to the input by
+// `onDialogOpened` once the dialog's enter animation has finished — doing it
+// here in a plain `nextTick` is too early for t-dialog (the input may not be
+// attached to the document yet, so `.focus()` silently no-ops).
+watch(open, (val) => {
+ if (val) {
+ query.value = initialQuery.value || ''
+ selectedKey.value = null
+ // Infer KB scope from current route. Reset scopeDismissed on each open so
+ // the default behavior is "scope to current KB unless user clicks ✕".
+ scopeDismissed.value = false
+ const kbIdFromRoute = typeof route.params.kbId === 'string' ? route.params.kbId : ''
+ if (kbIdFromRoute) {
+ // Best-effort name resolution; falls back to short id.
+ const match = knowledgeBases.value.find((k) => k.id === kbIdFromRoute)
+ activeKbScope.value = {
+ id: kbIdFromRoute,
+ name: match?.name || kbIdFromRoute,
+ }
+ } else {
+ activeKbScope.value = null
+ }
+ } else {
+ clearResults()
+ query.value = ''
+ drawerVisible.value = false
+ activeKbScope.value = null
+ }
+})
+
+// Fired by t-dialog after its open animation finishes — DOM is guaranteed
+// attached, focus sticks. We also schedule a couple of retries because
+// some browsers defer focus when the dialog is mid-layout; costs nothing.
+const focusInputWithRetry = () => {
+ const tryFocus = () => {
+ const el = inputRef.value
+ if (!el) return false
+ el.focus()
+ // Move cursor to end so an initialQuery is editable, not overwritten.
+ if (typeof el.setSelectionRange === 'function' && el.value) {
+ const len = el.value.length
+ try { el.setSelectionRange(len, len) } catch { /* not all input types support this */ }
+ }
+ return document.activeElement === el
+ }
+ if (tryFocus()) return
+ requestAnimationFrame(() => {
+ if (tryFocus()) return
+ setTimeout(tryFocus, 50)
+ })
+}
+
+const onDialogOpened = () => {
+ focusInputWithRetry()
+}
+
+// Once KB list loads, backfill the scope name if we only had an id at open time.
+watch(knowledgeBases, (list) => {
+ if (activeKbScope.value && activeKbScope.value.name === activeKbScope.value.id) {
+ const match = list.find((k) => k.id === activeKbScope.value!.id)
+ if (match) activeKbScope.value = { id: match.id, name: match.name }
+ }
+})
+
+const clearKbScope = () => {
+ activeKbScope.value = null
+ scopeDismissed.value = true
+ nextTick(() => inputRef.value?.focus())
+}
+
+onMounted(() => {
+ window.addEventListener('keydown', onGlobalKey)
+})
+
+onUnmounted(() => {
+ window.removeEventListener('keydown', onGlobalKey)
+})
+</script>
+
+<style lang="less" scoped>
+.cmdk {
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ min-height: 320px;
+ max-height: 60vh;
+}
+
+.cmdk__input-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 12px 14px;
+ border-bottom: 1px solid var(--td-component-stroke);
+}
+
+.cmdk__input-icon {
+ color: var(--td-text-color-placeholder);
+ font-size: 16px;
+}
+
+.cmdk__scope-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ max-width: 220px;
+ height: 26px;
+ padding: 0 2px 0 8px;
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-primary);
+ border-radius: 4px;
+ font-size: 12px;
+ font-weight: 500;
+ flex-shrink: 0;
+
+ :deep(.t-icon:first-child) {
+ color: var(--td-text-color-secondary);
+ }
+}
+
+.cmdk__scope-chip-name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cmdk__scope-chip-x {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ border: none;
+ border-radius: 3px;
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+ line-height: 1;
+ padding: 0;
+
+ :deep(svg) {
+ width: 12px;
+ height: 12px;
+ display: block;
+ }
+
+ &:hover {
+ color: var(--td-text-color-primary);
+ background: rgba(0, 0, 0, 0.05);
+ }
+}
+
+.cmdk__input {
+ flex: 1;
+ border: none;
+ outline: none;
+ background: transparent;
+ font-size: 15px;
+ color: var(--td-text-color-primary);
+ font-family: inherit;
+
+ &::placeholder {
+ color: var(--td-text-color-placeholder);
+ }
+}
+
+.cmdk__input-spinner {
+ display: flex;
+ align-items: center;
+}
+
+.cmdk__icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border: none;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ cursor: pointer;
+ transition: background 0.1s;
+
+ &:hover,
+ &.active {
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-primary);
+ }
+}
+
+.cmdk__results {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ padding: 6px 4px;
+}
+
+.cmdk__empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 12px;
+ padding: 40px 20px 20px;
+ color: var(--td-text-color-placeholder);
+ font-size: 13px;
+
+ p {
+ margin: 0;
+ }
+}
+
+.cmdk__empty-actions {
+ display: flex;
+ gap: 8px;
+}
+
+.cmdk__footer {
+ display: flex;
+ gap: 16px;
+ padding: 8px 14px;
+ border-top: 1px solid var(--td-component-stroke);
+ font-size: 11px;
+ color: var(--td-text-color-placeholder);
+ flex-wrap: wrap;
+}
+
+.cmdk__hotkey {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+
+ kbd {
+ display: inline-block;
+ padding: 1px 5px;
+ min-width: 16px;
+ 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);
+ }
+}
+
+.cmdk-chunk-kb {
+ font-size: 11px;
+ color: var(--td-text-color-placeholder);
+ padding: 1px 6px;
+ background: var(--td-bg-color-secondarycontainer);
+ border-radius: 3px;
+ font-weight: 400;
+}
+
+.cmdk-chunk-title {
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.cmdk-msg-role {
+ display: inline-block;
+ margin-right: 6px;
+ padding: 0 5px;
+ font-size: 10px;
+ font-weight: 600;
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-secondary);
+ border-radius: 3px;
+}
+</style>
+
+<style lang="less">
+/* Unscoped overrides — dialog renders in teleport. */
+.cmdk-dialog {
+ .t-dialog__body {
+ padding: 0;
+ }
+
+ .t-dialog {
+ padding: 0;
+ overflow: hidden;
+ }
+}
+
+.cmdk-retrieval-drawer {
+ .section-header {
+ font-weight: 600;
+ }
+}
+</style>
diff --git a/frontend/src/components/GlobalCommandPalette/ResultGroup.vue b/frontend/src/components/GlobalCommandPalette/ResultGroup.vue
new file mode 100644
index 000000000..337458a0c
--- /dev/null
+++ b/frontend/src/components/GlobalCommandPalette/ResultGroup.vue
@@ -0,0 +1,89 @@
+<template>
+ <div class="cmdk-group" v-if="$slots.default">
+ <div class="cmdk-group__header">
+ <span class="cmdk-group__label">{{ label }}</span>
+ <span v-if="count != null" class="cmdk-group__count">({{ count }})</span>
+ <span v-if="action" class="cmdk-group__spacer" />
+ <button
+ v-if="action"
+ type="button"
+ class="cmdk-group__action"
+ @click="$emit('action')"
+ >
+ {{ action }}
+ </button>
+ </div>
+ <div class="cmdk-group__body">
+ <slot />
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+defineProps<{
+ label: string
+ count?: number
+ action?: string
+}>()
+
+defineEmits<{
+ (e: 'action'): void
+}>()
+</script>
+
+<style lang="less" scoped>
+.cmdk-group {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 4px 0;
+
+ & + & {
+ border-top: 1px solid var(--td-component-stroke);
+ margin-top: 4px;
+ padding-top: 8px;
+ }
+}
+
+.cmdk-group__header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 12px 2px;
+ font-size: 11px;
+ font-weight: 500;
+ letter-spacing: 0.3px;
+ color: var(--td-text-color-placeholder);
+ text-transform: uppercase;
+}
+
+.cmdk-group__count {
+ color: var(--td-text-color-disabled);
+ font-weight: 400;
+}
+
+.cmdk-group__spacer {
+ flex: 1;
+}
+
+.cmdk-group__action {
+ border: none;
+ background: transparent;
+ padding: 2px 6px;
+ border-radius: 4px;
+ font-size: 11px;
+ color: var(--td-brand-color);
+ cursor: pointer;
+ text-transform: none;
+ letter-spacing: normal;
+
+ &:hover {
+ background: rgba(7, 192, 95, 0.08);
+ }
+}
+
+.cmdk-group__body {
+ display: flex;
+ flex-direction: column;
+}
+</style>
diff --git a/frontend/src/components/GlobalCommandPalette/ResultItem.vue b/frontend/src/components/GlobalCommandPalette/ResultItem.vue
new file mode 100644
index 000000000..596367743
--- /dev/null
+++ b/frontend/src/components/GlobalCommandPalette/ResultItem.vue
@@ -0,0 +1,202 @@
+<template>
+ <button
+ type="button"
+ :class="['cmdk-item', { 'cmdk-item--selected': selected }]"
+ :data-cmdk-index="index"
+ @click="$emit('primary')"
+ @mousemove="onHover"
+ >
+ <div class="cmdk-item__icon">
+ <slot name="icon">
+ <t-icon :name="iconName" size="14px" />
+ </slot>
+ </div>
+ <div class="cmdk-item__body">
+ <div class="cmdk-item__title">
+ <slot name="title">
+ <span v-html="title" />
+ </slot>
+ <span v-if="badge" :class="['cmdk-item__badge', `cmdk-item__badge--${badgeVariant || 'default'}`]">
+ {{ badge }}
+ </span>
+ <span v-if="score != null" class="cmdk-item__score">{{ (score * 100).toFixed(0) }}%</span>
+ </div>
+ <div v-if="$slots.subtitle || subtitle" class="cmdk-item__subtitle">
+ <slot name="subtitle">
+ <span v-html="subtitle" />
+ </slot>
+ </div>
+ </div>
+ <div class="cmdk-item__actions">
+ <slot name="actions" />
+ <span v-if="shortcut" class="cmdk-item__shortcut">
+ <kbd>⌘</kbd><kbd>{{ shortcut }}</kbd>
+ </span>
+ </div>
+ </button>
+</template>
+
+<script setup lang="ts">
+/**
+ * A single result row inside the command palette.
+ * Host component owns selection state; this one just mirrors it via the
+ * `selected` prop and emits hover/primary events.
+ */
+defineProps<{
+ index: number
+ selected?: boolean
+ iconName?: string
+ title?: string
+ subtitle?: string
+ badge?: string
+ badgeVariant?: 'vector' | 'keyword' | 'default'
+ score?: number
+ /** Visible hint for the ⌘N shortcut that triggers this row (N: 1-9). */
+ shortcut?: number | string
+}>()
+
+const emit = defineEmits<{
+ (e: 'primary'): void
+ (e: 'hover', index: number): void
+}>()
+
+const onHover = (e: MouseEvent) => {
+ const idx = Number((e.currentTarget as HTMLElement).dataset.cmdkIndex)
+ if (!Number.isNaN(idx)) emit('hover', idx)
+}
+</script>
+
+<style lang="less" scoped>
+.cmdk-item {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ width: 100%;
+ padding: 8px 12px;
+ border-radius: 8px;
+ border: none;
+ background: transparent;
+ cursor: pointer;
+ text-align: left;
+ font: inherit;
+ color: var(--td-text-color-primary);
+ transition: background 0.1s ease;
+}
+
+.cmdk-item--selected {
+ background: var(--td-bg-color-secondarycontainer);
+}
+
+.cmdk-item__icon {
+ flex-shrink: 0;
+ width: 20px;
+ height: 20px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--td-text-color-secondary);
+ margin-top: 2px;
+}
+
+.cmdk-item__body {
+ flex: 1;
+ min-width: 0;
+}
+
+.cmdk-item__title {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 20px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.cmdk-item__badge {
+ font-size: 10px;
+ padding: 1px 5px;
+ border-radius: 3px;
+ font-weight: 500;
+ flex-shrink: 0;
+ line-height: 1.4;
+
+ &--vector {
+ background: rgba(7, 192, 95, 0.1);
+ color: var(--td-brand-color);
+ }
+
+ &--keyword {
+ background: rgba(255, 152, 0, 0.1);
+ color: var(--td-warning-color);
+ }
+
+ &--default {
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-secondary);
+ }
+}
+
+.cmdk-item__score {
+ margin-left: auto;
+ font-size: 11px;
+ color: var(--td-text-color-placeholder);
+ flex-shrink: 0;
+}
+
+.cmdk-item__subtitle {
+ margin-top: 2px;
+ font-size: 12px;
+ line-height: 18px;
+ color: var(--td-text-color-secondary);
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ word-break: break-word;
+}
+
+.cmdk-item__actions {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.cmdk-item__shortcut {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ font-size: 10px;
+ color: var(--td-text-color-placeholder);
+ opacity: 0.55;
+ transition: opacity 0.1s;
+
+ kbd {
+ display: inline-block;
+ padding: 0 4px;
+ min-width: 14px;
+ 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);
+ }
+}
+
+.cmdk-item--selected .cmdk-item__shortcut {
+ opacity: 1;
+}
+
+:deep(.search-highlight) {
+ background: rgba(255, 213, 0, 0.35);
+ color: inherit;
+ padding: 0 1px;
+ border-radius: 2px;
+}
+</style>
diff --git a/frontend/src/components/GlobalCommandPalette/commands.ts b/frontend/src/components/GlobalCommandPalette/commands.ts
new file mode 100644
index 000000000..365f91273
--- /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 000000000..3d8bf687f
--- /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 <mark> 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, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#039;')
+}
+
+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, '<mark class="search-highlight">$1</mark>')
+ }
+ return result
+}
diff --git a/frontend/src/components/GlobalCommandPalette/useSearch.ts b/frontend/src/components/GlobalCommandPalette/useSearch.ts
new file mode 100644
index 000000000..72683abad
--- /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<CmdkKb[]>([])
+ const kbsLoaded = ref(false)
+ let kbsLoadingPromise: Promise<void> | null = null
+
+ const fileGroups = ref<CmdkFileGroup[]>([])
+ const messageGroups = ref<CmdkMsgGroup[]>([])
+ const totalChunks = ref(0)
+ const totalMessages = ref(0)
+
+ // Agents the current user can access (own + builtin + shared via orgs).
+ const agents = ref<CmdkAgent[]>([])
+ const agentsLoaded = ref(false)
+ let agentsLoadingPromise: Promise<void> | null = null
+
+ const orgStore = useOrganizationStore()
+ const menuStore = useMenuStore()
+
+ const ensureKbs = async (): Promise<void> => {
+ 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<CmdkKb[]>(() => {
+ 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<void> => {
+ 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<CmdkAgent[]>(() => {
+ 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<CmdkSessionItem[]>(() => {
+ 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<CmdkSessionItem[]>(() => {
+ 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<typeof setTimeout> | 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<string, CmdkFileGroup>()
+ 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<string, CmdkMsgGroup>()
+ 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 000000000..172a8f553
--- /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 898e3d7a3..11ccb830f 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -42,6 +42,25 @@
<!-- 上半部分:知识库和对话 -->
<div class="menu_top">
+ <!-- 全局搜索入口:点击打开命令面板(⌘K)。放在一级导航最上方,
+ 展开态展示快捷键提示,折叠态仅图标 + tooltip。 -->
+ <div class="menu_box menu_box--cmdk">
+ <t-tooltip :content="cmdkTooltip" placement="right" :disabled="!uiStore.sidebarCollapsed">
+ <div class="menu_item menu_item--cmdk" @click="commandPaletteStore.openPalette('')">
+ <div class="menu_item-box">
+ <div class="menu_icon">
+ <img class="icon" :src="getImgSrc('search.svg')" alt="">
+ </div>
+ <template v-if="!uiStore.sidebarCollapsed">
+ <span class="menu_title">{{ t('menu.search') }}</span>
+ <span class="menu-cmdk-hint" aria-hidden="true">
+ <kbd>{{ cmdModKeyLabel }}</kbd><kbd>K</kbd>
+ </span>
+ </template>
+ </div>
+ </div>
+ </t-tooltip>
+ </div>
<div class="menu_box" :class="{ 'has-submenu': item.children }" v-for="(item, index) in topMenuItems" :key="index">
<t-tooltip :content="item.title" placement="right" :disabled="!uiStore.sidebarCollapsed">
<div @click="handleMenuClick(item.path)"
@@ -49,7 +68,7 @@
:class="['menu_item', item.childrenPath && item.childrenPath == currentpath ? 'menu_item_c_active' : isMenuItemActive(item.path) ? 'menu_item_active' : '']">
<div class="menu_item-box">
<div class="menu_icon">
- <img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'search' ? searchIcon : item.icon == 'agent' ? agentIcon : item.icon == 'organization' ? organizationIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)" alt="">
+ <img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'agent' ? agentIcon : item.icon == 'organization' ? organizationIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)" alt="">
</div>
<template v-if="!uiStore.sidebarCollapsed">
<span class="menu_title" :title="item.title">{{ item.title }}</span>
@@ -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<MenuItem[]>(() => {
- 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<MenuItem[]>(() => {
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 47ba24199..7c954498e 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 8d3390bac..283ffa5cc 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 6e98cf360..6e9f6ccf5 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 9ad2ca054..94edd23e8 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 1623fd19d..ae9ced414 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 000000000..4d145f5b0
--- /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<string[]>([])
+
+ 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 9bc418d20..bb9fb7317 100644
--- a/frontend/src/stores/menu.ts
+++ b/frontend/src/stores/menu.ts
@@ -19,7 +19,6 @@ const createMenuChildren = () => reactive<MenuChild[]>([])
export const useMenuStore = defineStore('menuStore', () => {
const menuArr = reactive<MenuItem[]>([
{ 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 ab3b007d2..db6270ba1 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<string | null>(
(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 33919ec60..000000000
--- a/frontend/src/views/knowledge/KnowledgeSearch.vue
+++ /dev/null
@@ -1,1163 +0,0 @@
-<template>
- <div class="ks-container">
- <div class="ks-content">
- <div class="header" style="--wails-draggable: drag">
- <div class="header-title" style="--wails-draggable: drag">
- <h2 style="--wails-draggable: drag">{{ $t('knowledgeSearch.title') }}</h2>
- <p class="header-subtitle" style="--wails-draggable: drag">{{ $t('knowledgeSearch.subtitle') }}</p>
- </div>
- <div class="header-actions" style="--wails-draggable: no-drag">
- <t-button variant="text" shape="square" :class="{ active: showSettings }" style="--wails-draggable: no-drag" @click="showSettings = !showSettings">
- <template #icon><t-icon name="setting" /></template>
- </t-button>
- </div>
- </div>
-
- <!-- Retrieval settings drawer -->
- <t-drawer
- v-model:visible="showSettings"
- :header="$t('retrievalSettings.title')"
- size="420px"
- :footer="false"
- :close-on-overlay-click="true"
- class="retrieval-drawer"
- >
- <RetrievalSettings />
- </t-drawer>
-
- <!-- Tab 切换 -->
- <div class="search-tabs">
- <div
- :class="['search-tab', { active: activeTab === 'knowledge' }]"
- @click="switchTab('knowledge')"
- >
- <t-icon name="file-search" size="16px" />
- {{ $t('knowledgeSearch.tabKnowledge') }}
- </div>
- <div
- :class="['search-tab', { active: activeTab === 'messages' }]"
- @click="switchTab('messages')"
- >
- <t-icon name="chat" size="16px" />
- {{ $t('knowledgeSearch.tabMessages') }}
- </div>
- </div>
-
- <div class="search-bar">
- <t-input
- v-model="query"
- :placeholder="activeTab === 'knowledge' ? $t('knowledgeSearch.placeholder') : $t('knowledgeSearch.messagePlaceholder')"
- clearable
- class="search-input"
- @enter="handleSearch"
- >
- <template #prefixIcon>
- <t-icon name="search" />
- </template>
- </t-input>
- <t-select
- v-if="activeTab === 'knowledge'"
- v-model="selectedKbIds"
- :placeholder="$t('knowledgeSearch.allKb')"
- multiple
- clearable
- filterable
- class="kb-filter"
- :loading="kbLoading"
- >
- <t-option
- v-for="kb in knowledgeBases"
- :key="kb.id"
- :value="kb.id"
- :label="kb.name"
- >
- <div class="kb-option-row">
- <span class="kb-option-name">{{ kb.name }}</span>
- <span :class="['kb-type-badge', kb.type === 'faq' ? 'faq' : 'doc']">
- {{ kb.type === 'faq' ? 'FAQ' : 'DOC' }}
- </span>
- </div>
- </t-option>
- </t-select>
- <t-button
- theme="primary"
- :loading="loading"
- :disabled="!query.trim()"
- class="search-btn"
- @click="handleSearch"
- >
- {{ $t('knowledgeSearch.searchBtn') }}
- </t-button>
- </div>
-
- <div class="ks-main">
- <!-- ==================== Knowledge Search Tab ==================== -->
- <template v-if="activeTab === 'knowledge'">
- <!-- Before search -->
- <div v-if="!hasSearched && !loading" class="empty-hint">
- <div class="empty-hint-icon">
- <t-icon name="search" size="36px" />
- </div>
- <p>{{ $t('knowledgeSearch.emptyHint') }}</p>
- </div>
-
- <!-- Loading -->
- <div v-else-if="loading" class="empty-hint">
- <t-loading size="small" :text="$t('knowledgeSearch.searching')" />
- </div>
-
- <!-- No results -->
- <div v-else-if="hasSearched && groupedResults.length === 0" class="empty-hint">
- <div class="empty-hint-icon muted">
- <t-icon name="info-circle" size="36px" />
- </div>
- <p>{{ $t('knowledgeSearch.noResults') }}</p>
- </div>
-
- <!-- Results grouped by file -->
- <template v-else>
- <div class="results-summary">
- <span>
- {{ $t('knowledgeSearch.resultCount', { count: totalChunks }) }}
- <span class="results-file-count">&middot; {{ groupedResults.length }} {{ $t('knowledgeSearch.fileCount') }}</span>
- </span>
- <span class="start-chat-link" @click="startChat()">
- <t-icon name="chat" size="14px" />
- {{ $t('knowledgeSearch.startChat') }}
- </span>
- </div>
-
- <div class="file-groups">
- <div
- v-for="(group, gIdx) in groupedResults"
- :key="group.knowledgeId"
- class="file-group"
- >
- <div class="file-group-header" @click="toggleFileExpand(gIdx)">
- <div class="file-group-left">
- <svg class="file-icon" width="16" height="16" viewBox="0 0 24 24" fill="none">
- <path d="M14 2H6C5.46957 2 4.96086 2.21071 4.58579 2.58579C4.21071 2.96086 4 3.46957 4 4V20C4 20.5304 4.21071 21.0391 4.58579 21.4142C4.96086 21.7893 5.46957 22 6 22H18C18.5304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20V8L14 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
- <path d="M14 2V8H20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- <span class="file-group-title">{{ group.title }}</span>
- <span class="file-group-kb" v-if="group.kbName">{{ group.kbName }}</span>
- </div>
- <div class="file-group-right">
- <span class="chunk-count">{{ group.chunks.length }} {{ $t('knowledgeSearch.chunk') }}</span>
- <span
- class="go-detail-link"
- @click.stop="startChat(group)"
- >
- <t-icon name="chat" size="14px" />
- {{ $t('knowledgeSearch.chatWithFile') }}
- </span>
- <span
- v-if="group.kbId"
- class="go-detail-link"
- @click.stop="goToDetail(group)"
- >
- {{ $t('knowledgeSearch.viewDetail') }}
- <t-icon name="jump" size="14px" />
- </span>
- <t-icon :name="expandedFiles.has(gIdx) ? 'chevron-up' : 'chevron-down'" size="16px" />
- </div>
- </div>
-
- <div v-if="expandedFiles.has(gIdx)" class="file-group-chunks">
- <div
- v-for="(chunk, cIdx) in group.chunks"
- :key="chunk.id || cIdx"
- class="chunk-item"
- >
- <div class="chunk-item-meta">
- <span class="chunk-index">#{{ chunk.chunk_index }}</span>
- <span :class="['match-badge', chunk.match_type === 'vector' ? 'vector' : 'keyword']">
- {{ chunk.match_type === 'vector' ? $t('knowledgeSearch.matchTypeVector') : $t('knowledgeSearch.matchTypeKeyword') }}
- </span>
- <span class="chunk-score">{{ (chunk.score * 100).toFixed(1) }}%</span>
- </div>
- <div
- class="chunk-content"
- :class="{ expanded: expandedChunks.has(`${gIdx}-${cIdx}`) }"
- @click="toggleChunkExpand(gIdx, cIdx)"
- v-html="highlightText(chunk.matched_content || chunk.content)"
- ></div>
- </div>
- </div>
- </div>
- </div>
- </template>
- </template>
-
- <!-- ==================== Message Search Tab ==================== -->
- <template v-if="activeTab === 'messages'">
- <!-- Before search -->
- <div v-if="!msgHasSearched && !msgLoading" class="empty-hint">
- <div class="empty-hint-icon">
- <t-icon name="chat" size="36px" />
- </div>
- <p>{{ $t('knowledgeSearch.messageEmptyHint') }}</p>
- </div>
-
- <!-- Loading -->
- <div v-else-if="msgLoading" class="empty-hint">
- <t-loading size="small" :text="$t('knowledgeSearch.searching')" />
- </div>
-
- <!-- No results -->
- <div v-else-if="msgHasSearched && msgGroupedResults.length === 0" class="empty-hint">
- <div class="empty-hint-icon muted">
- <t-icon name="info-circle" size="36px" />
- </div>
- <p>{{ $t('knowledgeSearch.noResults') }}</p>
- </div>
-
- <!-- Message results grouped by session -->
- <template v-else>
- <div class="results-summary">
- <span>{{ $t('knowledgeSearch.resultCount', { count: msgTotal }) }}</span>
- </div>
-
- <div class="msg-session-groups">
- <div
- v-for="group in msgGroupedResults"
- :key="group.sessionId"
- class="msg-session-group"
- >
- <div class="msg-session-header" @click="goToSessionById(group.sessionId)">
- <t-icon name="chat" size="16px" class="msg-session-icon" />
- <span class="msg-session-name">{{ group.sessionTitle || $t('knowledgeSearch.untitledSession') }}</span>
- <span class="msg-session-count">{{ group.items.length }} {{ $t('knowledgeSearch.matchCount') }}</span>
- <t-icon name="jump" size="14px" class="msg-session-jump" />
- </div>
-
- <div class="msg-qa-list">
- <div
- v-for="(item, idx) in group.items"
- :key="item.request_id || idx"
- class="msg-qa-item"
- >
- <!-- Q -->
- <div class="msg-qa-row" v-if="item.query_content">
- <span class="msg-role-badge user">Q</span>
- <div class="msg-qa-content" v-html="highlightText(item.query_content)"></div>
- <span class="msg-time">{{ formatTime(item.created_at) }}</span>
- </div>
- <!-- A -->
- <div class="msg-qa-row" v-if="item.answer_content">
- <span class="msg-role-badge assistant">A</span>
- <div class="msg-qa-content answer" v-html="highlightText(item.answer_content)"></div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </template>
- </template>
- </div>
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { ref, reactive, computed, onMounted } from 'vue'
-import { useI18n } from 'vue-i18n'
-import { useRouter } from 'vue-router'
-import { MessagePlugin } from 'tdesign-vue-next'
-import { listKnowledgeBases, knowledgeSemanticSearch } from '@/api/knowledge-base'
-import { searchMessages, type MessageSearchGroupItem } from '@/api/chat-history'
-import RetrievalSettings from '@/views/settings/RetrievalSettings.vue'
-import { useMenuStore } from '@/stores/menu'
-import { useSettingsStore } from '@/stores/settings'
-import { useOrganizationStore } from '@/stores/organization'
-
-const { t } = useI18n()
-const router = useRouter()
-const menuStore = useMenuStore()
-const settingsStore = useSettingsStore()
-const orgStore = useOrganizationStore()
-
-// ─── Shared state ───
-const query = ref('')
-const activeTab = ref<'knowledge' | 'messages'>('knowledge')
-const showSettings = ref(false)
-
-// ─── Knowledge search state ───
-const loading = ref(false)
-const kbLoading = ref(false)
-const hasSearched = ref(false)
-const selectedKbIds = ref<string[]>([])
-const results = ref<any[]>([])
-const expandedFiles = reactive(new Set<number>())
-const expandedChunks = reactive(new Set<string>())
-const knowledgeBases = ref<any[]>([])
-
-// ─── Message search state ───
-const msgLoading = ref(false)
-const msgHasSearched = ref(false)
-const msgResults = ref<MessageSearchGroupItem[]>([])
-const msgTotal = ref(0)
-
-interface MsgSessionGroup {
- sessionId: string
- sessionTitle: string
- items: MessageSearchGroupItem[]
-}
-
-const msgGroupedResults = computed<MsgSessionGroup[]>(() => {
- const map = new Map<string, MsgSessionGroup>()
- for (const item of msgResults.value) {
- const sid = item.session_id || 'unknown'
- if (!map.has(sid)) {
- map.set(sid, {
- sessionId: sid,
- sessionTitle: item.session_title || '',
- items: [],
- })
- }
- map.get(sid)!.items.push(item)
- }
- return Array.from(map.values())
-})
-
-interface FileGroup {
- knowledgeId: string
- kbId: string
- title: string
- kbName: string
- chunks: any[]
-}
-
-const groupedResults = computed<FileGroup[]>(() => {
- const map = new Map<string, FileGroup>()
- for (const item of results.value) {
- const kid = item.knowledge_id || 'unknown'
- if (!map.has(kid)) {
- map.set(kid, {
- knowledgeId: kid,
- kbId: item.knowledge_base_id || '',
- title: item.knowledge_title || item.knowledge_filename || kid,
- kbName: getKbName(item.knowledge_base_id),
- chunks: [],
- })
- }
- map.get(kid)!.chunks.push(item)
- }
- return Array.from(map.values())
-})
-
-const totalChunks = computed(() => results.value.length)
-
-const mergeKnowledgeBases = (myKbs: any[], sharedShares: any[]) => {
- const ownKbIds = new Set(myKbs.map((kb: any) => String(kb.id)))
- const sharedKbs = (sharedShares || [])
- .filter((share: any) => share?.knowledge_base != null)
- .map((share: any) => ({
- id: String(share.knowledge_base.id),
- name: share.knowledge_base.name,
- type: share.knowledge_base.type || 'document',
- org_name: share.org_name || '',
- }))
- .filter((kb: any) => !ownKbIds.has(kb.id))
-
- return [...myKbs, ...sharedKbs]
-}
-
-const switchTab = (tab: 'knowledge' | 'messages') => {
- activeTab.value = tab
-}
-
-const fetchKnowledgeBases = async () => {
- kbLoading.value = true
- try {
- const [kbRes, sharedKbs] = await Promise.all([
- listKnowledgeBases(),
- orgStore.fetchSharedKnowledgeBases(),
- ])
-
- const myKbs = (kbRes?.data || []).map((kb: any) => ({
- ...kb,
- id: String(kb.id),
- }))
-
- knowledgeBases.value = mergeKnowledgeBases(myKbs, sharedKbs)
- } catch (e) {
- console.error('Failed to load knowledge bases', e)
- } finally {
- kbLoading.value = false
- }
-}
-
-const handleSearch = async () => {
- if (activeTab.value === 'knowledge') {
- await handleKnowledgeSearch()
- } else {
- await handleMessageSearch()
- }
-}
-
-const handleKnowledgeSearch = async () => {
- const q = query.value.trim()
- if (!q) return
-
- loading.value = true
- hasSearched.value = true
- expandedFiles.clear()
- expandedChunks.clear()
-
- try {
- const kbIds = selectedKbIds.value.length > 0
- ? selectedKbIds.value
- : knowledgeBases.value.map((kb: any) => kb.id)
-
- const res: any = await knowledgeSemanticSearch({
- query: q,
- knowledge_base_ids: kbIds,
- })
- if (res?.success && res.data) {
- results.value = res.data
- } else {
- results.value = []
- }
- } catch (e: any) {
- console.error('Search failed', e)
- MessagePlugin.error(e?.message || 'Search failed')
- results.value = []
- } finally {
- loading.value = false
- }
-}
-
-const handleMessageSearch = async () => {
- const q = query.value.trim()
- if (!q) return
-
- msgLoading.value = true
- msgHasSearched.value = true
-
- try {
- const res: any = await searchMessages({
- query: q,
- mode: 'hybrid',
- limit: 30,
- })
- if (res?.success && res.data) {
- msgResults.value = res.data.items || []
- msgTotal.value = res.data.total || 0
- } else {
- msgResults.value = []
- msgTotal.value = 0
- }
- } catch (e: any) {
- console.error('Message search failed', e)
- MessagePlugin.error(e?.message || 'Search failed')
- msgResults.value = []
- msgTotal.value = 0
- } finally {
- msgLoading.value = false
- }
-}
-
-const toggleFileExpand = (idx: number) => {
- if (expandedFiles.has(idx)) {
- expandedFiles.delete(idx)
- } else {
- expandedFiles.add(idx)
- }
-}
-
-const toggleChunkExpand = (gIdx: number, cIdx: number) => {
- const key = `${gIdx}-${cIdx}`
- if (expandedChunks.has(key)) {
- expandedChunks.delete(key)
- } else {
- expandedChunks.add(key)
- }
-}
-
-const goToDetail = (group: FileGroup) => {
- if (!group.kbId) return
- router.push({
- path: `/platform/knowledge-bases/${group.kbId}`,
- query: { knowledge_id: group.knowledgeId },
- })
-}
-
-const startChat = (group?: FileGroup) => {
- const q = query.value.trim()
- if (!q) return
-
- let kbIds: string[] = []
- let fileIds: string[] = []
-
- if (group) {
- if (group.kbId) {
- kbIds = [group.kbId]
- }
- fileIds = [group.knowledgeId]
- } else {
- kbIds = selectedKbIds.value.length > 0
- ? selectedKbIds.value
- : knowledgeBases.value.map((kb: any) => kb.id)
- }
-
- settingsStore.selectKnowledgeBases(kbIds)
- for (const fid of fileIds) {
- settingsStore.addFile(fid)
- }
-
- menuStore.setPrefillQuery(q)
- router.push('/platform/creatChat')
-}
-
-const goToSessionById = (sessionId: string) => {
- if (sessionId) {
- router.push(`/platform/chat/${sessionId}`)
- }
-}
-
-const highlightText = (text: string): string => {
- const q = query.value.trim()
- if (!q || !text) return escapeHtml(text || '')
- // Escape HTML first, then highlight
- const escaped = escapeHtml(text)
- const keywords = q.split(/\s+/).filter(Boolean)
- let result = escaped
- for (const kw of keywords) {
- const escapedKw = escapeHtml(kw).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
- const regex = new RegExp(`(${escapedKw})`, 'gi')
- result = result.replace(regex, '<mark class="search-highlight">$1</mark>')
- }
- return result
-}
-
-const escapeHtml = (str: string): string => {
- return str
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&#039;')
-}
-
-const formatTime = (timeStr: string) => {
- if (!timeStr) return ''
- try {
- const d = new Date(timeStr)
- return d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
- } catch {
- return timeStr
- }
-}
-
-const getKbName = (kbId: string): string => {
- if (!kbId) return ''
- const kb = knowledgeBases.value.find((k: any) => k.id === kbId)
- return kb?.name || ''
-}
-
-onMounted(() => {
- fetchKnowledgeBases()
-})
-</script>
-
-<style lang="less" scoped>
-.ks-container {
- margin: 0 16px 0 0;
- height: calc(100vh);
- box-sizing: border-box;
- flex: 1;
- display: flex;
- position: relative;
- min-height: 0;
-}
-
-.ks-content {
- flex: 1;
- display: flex;
- flex-direction: column;
- min-width: 0;
- padding: 24px 32px 0 32px;
-}
-
-.header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: 16px;
-
- .header-title {
- display: flex;
- flex-direction: column;
- gap: 4px;
- }
-
- h2 {
- margin: 0;
- color: var(--td-text-color-primary);
- font-family: var(--app-font-family);
- font-size: 24px;
- font-weight: 600;
- line-height: 32px;
- }
-}
-
-.header-subtitle {
- margin: 0;
- color: var(--td-text-color-placeholder);
- font-family: var(--app-font-family);
- font-size: 14px;
- font-weight: 400;
- line-height: 20px;
-}
-
-.header-actions {
- :deep(.t-button) {
- color: var(--td-text-color-secondary);
-
- &.active {
- color: var(--td-brand-color);
- background: rgba(7, 192, 95, 0.08);
- }
- }
-}
-
-/* Tab 切换 */
-.search-tabs {
- display: flex;
- gap: 4px;
- margin-bottom: 16px;
- padding: 3px;
- background: var(--td-bg-color-secondarycontainer);
- border-radius: 8px;
- width: fit-content;
-}
-
-.search-tab {
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 7px 16px;
- border-radius: 6px;
- cursor: pointer;
- font-size: 13px;
- font-weight: 500;
- color: var(--td-text-color-secondary);
- transition: all 0.2s ease;
- user-select: none;
-
- &:hover {
- color: var(--td-text-color-primary);
- background: var(--td-bg-color-container-hover);
- }
-
- &.active {
- color: var(--td-brand-color);
- background: var(--td-bg-color-container);
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
- }
-}
-
-.search-bar {
- display: flex;
- gap: 10px;
- align-items: center;
- margin-bottom: 20px;
-
- :deep(.t-input) {
- font-size: 13px;
- background-color: var(--td-bg-color-container);
- border-color: var(--td-component-stroke);
- border-radius: 6px;
-
- &:hover,
- &:focus,
- &.t-is-focused {
- border-color: var(--td-brand-color);
- background-color: var(--td-bg-color-container);
- }
- }
-
- :deep(.t-select .t-input) {
- font-size: 13px;
- background-color: var(--td-bg-color-container);
- border-color: var(--td-component-stroke);
- border-radius: 6px;
-
- &:hover,
- &.t-is-focused {
- border-color: var(--td-brand-color);
- background-color: var(--td-bg-color-container);
- }
- }
-}
-
-.search-input {
- flex: 1;
- min-width: 0;
-}
-
-.kb-filter {
- width: 200px;
- flex-shrink: 0;
-}
-
-.search-btn {
- flex-shrink: 0;
- background: linear-gradient(135deg, var(--td-brand-color) 0%, #00a67e 100%);
- border: none;
- color: var(--td-text-color-anti);
- border-radius: 6px;
-
- &:hover {
- background: linear-gradient(135deg, var(--td-brand-color) 0%, var(--td-brand-color-active) 100%);
- }
-}
-
-.kb-option-row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- width: 100%;
- gap: 8px;
-}
-
-.kb-option-name {
- flex: 1;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.kb-type-badge {
- font-size: 10px;
- padding: 1px 5px;
- border-radius: 3px;
- font-weight: 500;
- flex-shrink: 0;
-
- &.doc {
- background: rgba(7, 192, 95, 0.1);
- color: var(--td-brand-color);
- }
- &.faq {
- background: rgba(255, 152, 0, 0.1);
- color: var(--td-warning-color);
- }
-}
-
-.ks-main {
- flex: 1;
- min-height: 0;
- overflow-y: auto;
- padding-bottom: 24px;
-}
-
-.empty-hint {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 100px 0 60px;
- gap: 12px;
- color: var(--td-text-color-disabled);
- font-size: 14px;
-
- p {
- margin: 0;
- }
-}
-
-.empty-hint-icon {
- width: 64px;
- height: 64px;
- border-radius: 50%;
- background: var(--td-bg-color-secondarycontainer);
- display: flex;
- align-items: center;
- justify-content: center;
- color: var(--td-text-color-disabled);
-
- &.muted {
- color: var(--td-text-color-disabled);
- }
-}
-
-.results-summary {
- display: flex;
- align-items: center;
- justify-content: space-between;
- font-size: 13px;
- color: var(--td-text-color-placeholder);
- margin-bottom: 16px;
- padding: 0 2px;
-}
-
-.start-chat-link {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- font-size: 13px;
- color: var(--td-brand-color);
- cursor: pointer;
- padding: 4px 10px;
- border-radius: 6px;
- border: 1px solid rgba(7, 192, 95, 0.3);
- transition: all 0.15s;
-
- &:hover {
- background: rgba(7, 192, 95, 0.08);
- border-color: var(--td-brand-color);
- }
-}
-
-.results-file-count {
- color: var(--td-text-color-disabled);
-}
-
-.file-groups {
- display: flex;
- flex-direction: column;
- gap: 12px;
-}
-
-.file-group {
- border: 1px solid var(--td-component-stroke);
- border-radius: 10px;
- background: var(--td-bg-color-container);
- overflow: hidden;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
- transition: box-shadow 0.2s;
-
- &:hover {
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
- }
-}
-
-.file-group-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 14px 18px;
- cursor: pointer;
- user-select: none;
- transition: background 0.15s;
-
- &:hover {
- background: var(--td-bg-color-container);
- }
-}
-
-.file-group-left {
- display: flex;
- align-items: center;
- gap: 10px;
- flex: 1;
- min-width: 0;
-}
-
-.file-icon {
- flex-shrink: 0;
- color: var(--td-brand-color);
-}
-
-.file-group-title {
- font-size: 14px;
- font-weight: 600;
- color: var(--td-text-color-primary);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.file-group-kb {
- font-size: 12px;
- color: var(--td-text-color-disabled);
- padding: 1px 8px;
- background: var(--td-bg-color-secondarycontainer);
- border-radius: 4px;
- flex-shrink: 0;
- max-width: 160px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.file-group-right {
- display: flex;
- align-items: center;
- gap: 8px;
- flex-shrink: 0;
- color: var(--td-text-color-disabled);
-}
-
-.chunk-count {
- font-size: 12px;
- color: var(--td-text-color-disabled);
-}
-
-.go-detail-link {
- display: inline-flex;
- align-items: center;
- gap: 3px;
- font-size: 12px;
- color: var(--td-brand-color);
- cursor: pointer;
- padding: 2px 6px;
- border-radius: 4px;
- transition: all 0.15s;
-
- &:hover {
- background: rgba(7, 192, 95, 0.08);
- color: var(--td-brand-color-active);
- }
-}
-
-.file-group-chunks {
- border-top: 1px solid var(--td-component-stroke);
-}
-
-.chunk-item {
- padding: 12px 18px 12px 44px;
- border-bottom: 1px solid var(--td-component-stroke);
-
- &:last-child {
- border-bottom: none;
- }
-}
-
-.chunk-item-meta {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-bottom: 6px;
-}
-
-.chunk-index {
- font-size: 11px;
- color: var(--td-text-color-disabled);
- font-weight: 600;
- font-family: var(--app-font-family-mono);
-}
-
-.match-badge {
- font-size: 10px;
- padding: 1px 6px;
- border-radius: 3px;
- font-weight: 500;
-
- &.vector {
- background: rgba(22, 119, 255, 0.08);
- color: var(--td-brand-color);
- }
- &.keyword {
- background: rgba(255, 152, 0, 0.08);
- color: var(--td-warning-color);
- }
-}
-
-.chunk-score {
- font-size: 11px;
- color: var(--td-text-color-placeholder);
- font-family: var(--app-font-family-mono);
-}
-
-.chunk-content {
- font-size: 13px;
- color: var(--td-text-color-primary);
- line-height: 1.7;
- white-space: pre-wrap;
- word-break: break-word;
- max-height: 66px;
- overflow: hidden;
- cursor: pointer;
- position: relative;
- transition: max-height 0.3s ease;
-
- &::after {
- content: '';
- position: absolute;
- bottom: 0;
- left: 0;
- right: 0;
- height: 24px;
- background: linear-gradient(transparent, var(--td-bg-color-container));
- pointer-events: none;
- }
-
- &.expanded {
- max-height: none;
-
- &::after {
- display: none;
- }
- }
-}
-
-/* ─── Message search results (session-grouped Q&A) ─── */
-.msg-session-groups {
- display: flex;
- flex-direction: column;
- gap: 12px;
-}
-
-.msg-session-group {
- border: 1px solid var(--td-component-stroke);
- border-radius: 10px;
- background: var(--td-bg-color-container);
- overflow: hidden;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
- transition: box-shadow 0.2s;
-
- &:hover {
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
- }
-}
-
-.msg-session-header {
- display: flex;
- align-items: center;
- gap: 10px;
- padding: 12px 18px;
- cursor: pointer;
- user-select: none;
- border-bottom: 1px solid var(--td-component-stroke);
- transition: background 0.15s;
-
- &:hover {
- background: var(--td-bg-color-secondarycontainer);
- }
-}
-
-.msg-session-icon {
- flex-shrink: 0;
- color: var(--td-brand-color);
-}
-
-.msg-session-name {
- font-size: 14px;
- font-weight: 600;
- color: var(--td-text-color-primary);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- flex: 1;
- min-width: 0;
-}
-
-.msg-session-count {
- font-size: 12px;
- color: var(--td-text-color-disabled);
- flex-shrink: 0;
-}
-
-.msg-session-jump {
- flex-shrink: 0;
- color: var(--td-text-color-disabled);
- transition: color 0.15s;
-
- .msg-session-header:hover & {
- color: var(--td-brand-color);
- }
-}
-
-.msg-qa-list {
- display: flex;
- flex-direction: column;
-}
-
-.msg-qa-item {
- padding: 12px 18px;
- border-bottom: 1px solid var(--td-component-stroke);
-
- &:last-child {
- border-bottom: none;
- }
-}
-
-.msg-time {
- font-size: 11px;
- color: var(--td-text-color-disabled);
- flex-shrink: 0;
- align-self: flex-start;
- margin-top: 2px;
- white-space: nowrap;
-}
-
-.msg-qa-row {
- display: flex;
- gap: 10px;
- margin-bottom: 6px;
-
- &:last-child {
- margin-bottom: 0;
- }
-}
-
-.msg-role-badge {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 22px;
- height: 22px;
- border-radius: 4px;
- font-size: 11px;
- font-weight: 700;
- flex-shrink: 0;
- margin-top: 1px;
-
- &.user {
- background: rgba(22, 119, 255, 0.1);
- color: #1677ff;
- }
- &.assistant {
- background: rgba(7, 192, 95, 0.1);
- color: var(--td-brand-color);
- }
-}
-
-.msg-qa-content {
- font-size: 13px;
- color: var(--td-text-color-primary);
- line-height: 1.7;
- word-break: break-word;
- flex: 1;
- min-width: 0;
- max-height: 66px;
- overflow: hidden;
- position: relative;
-
- &::after {
- content: '';
- position: absolute;
- bottom: 0;
- left: 0;
- right: 0;
- height: 24px;
- background: linear-gradient(transparent, var(--td-bg-color-container));
- pointer-events: none;
- }
-
- &.answer {
- color: var(--td-text-color-secondary);
- }
-}
-
-/* ─── Search highlight ─── */
-:deep(.search-highlight) {
- background: rgba(255, 213, 0, 0.35);
- color: inherit;
- padding: 0 1px;
- border-radius: 2px;
-}
-
-</style>
-
-<style lang="less">
-/* Unscoped: drawer renders outside component scope */
-.retrieval-drawer {
- .section-header {
- display: none;
- }
-}
-</style>
diff --git a/frontend/src/views/platform/index.vue b/frontend/src/views/platform/index.vue
index ff20a7c0f..0fd75e3a8 100644
--- a/frontend/src/views/platform/index.vue
+++ b/frontend/src/views/platform/index.vue
@@ -10,21 +10,27 @@
</div>
<!-- 全局设置模态框,供所有 platform 子路由使用 -->
<Settings />
+ <!-- 全局命令面板 (⌘K),随 platform 路由存活 -->
+ <GlobalCommandPalette />
</div>
</template>
<script setup lang="ts">
import Menu from '@/components/menu.vue'
-import { ref, onMounted, onUnmounted, nextTick, provide } from 'vue';
-import { useRoute } from 'vue-router'
+import { ref, onMounted, onUnmounted, nextTick, provide, watch } from 'vue';
+import { useRoute, useRouter } from 'vue-router'
import useKnowledgeBase from '@/hooks/useKnowledgeBase'
import UploadMask from '@/components/upload-mask.vue'
import Settings from '@/views/settings/Settings.vue'
+import GlobalCommandPalette from '@/components/GlobalCommandPalette.vue'
+import { useCommandPaletteStore } from '@/stores/commandPalette'
import { getKnowledgeBaseById } from '@/api/knowledge-base/index'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
let { requestMethod } = useKnowledgeBase()
const route = useRoute();
+const router = useRouter();
+const commandPaletteStore = useCommandPaletteStore();
let ismask = ref(false)
let uploadInput = ref();
const { t } = useI18n();
@@ -186,8 +192,26 @@ onMounted(() => {
reloadApp()
})
}
+ // 支持通过 URL 查询参数打开全局命令面板,例如旧路径
+ // /platform/knowledge-search?q=foo 重定向后携带 ?cmdk=foo
+ maybeOpenCmdkFromRoute()
});
+// 监听路由变化,兼容 SPA 内部跳转时的 ?cmdk= 参数
+watch(() => route.query.cmdk, () => {
+ maybeOpenCmdkFromRoute()
+})
+
+function maybeOpenCmdkFromRoute() {
+ if (!('cmdk' in route.query)) return
+ const q = String(route.query.cmdk ?? '')
+ commandPaletteStore.openPalette(q)
+ // 清除 query,避免回退/刷新时反复触发
+ const newQuery = { ...route.query }
+ delete (newQuery as any).cmdk
+ router.replace({ path: route.path, query: newQuery, hash: route.hash })
+}
+
// 组件卸载时移除全局事件监听器
onUnmounted(() => {
document.removeEventListener('dragenter', handleGlobalDragEnter, true);