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

Reworks search from a siloed /platform/knowledge-search page into a
universal ⌘K palette plus natural, in-context entry points.

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

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

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

i18n: zh-CN / en-US / ko-KR / ru-RU updated together — new
commandPalette.*, kb.*, and menu.search keys; obsolete session.search.*
and menu.knowledgeSearch removed.
This commit is contained in:
wizardchen
2026-05-06 16:20:50 +08:00
committed by lyingbug
parent 0be4572bd5
commit 2d3f32de5c
18 changed files with 2229 additions and 1197 deletions
@@ -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>
@@ -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>
@@ -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>
@@ -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
})
}
@@ -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
}
@@ -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,
}
}
@@ -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 }
}
+71 -23
View File
@@ -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;