Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix: harden Studio resource search (#2521)
yufeng37507571a950
diff --git a/tests/agfs/test_async_client.py b/tests/agfs/test_async_client.pyindex 201a06b96..f5746903e 100644--- a/tests/agfs/test_async_client.py+++ b/tests/agfs/test_async_client.py@@ -32,16 +32,29 @@ async def test_async_agfs_client_hides_threadpool(monkeypatch):agfs = AsyncAGFSClient(sync_agfs)assert agfs.sync_client is sync_agfs- assert await agfs.write("/tasks/1", b"data") == ("write", "/tasks/1", b"data", {})- assert await agfs.read("/queue/dequeue") == ("read", "/queue/dequeue", {})+ assert await agfs.write("/tasks/1", b"data") == (+ "write",+ "/tasks/1",+ b"data",+ {"ctx": {"account_id": "_system"}},+ )+ assert await agfs.read("/queue/dequeue") == (+ "read",+ "/queue/dequeue",+ {"ctx": {"account_id": "_system"}},+ )assert await agfs.rm("/redo/id", recursive=True) == ("rm","/redo/id",- {"recursive": True},+ {"recursive": True, "ctx": {"account_id": "_system"}},)assert to_thread_calls == [- ("write", ("/tasks/1", b"data"), {}),- ("read", ("/queue/dequeue",), {}),- ("rm", ("/redo/id",), {"recursive": True}),+ ("write", ("/tasks/1", b"data"), {"ctx": {"account_id": "_system"}}),+ ("read", ("/queue/dequeue",), {"ctx": {"account_id": "_system"}}),+ (+ "rm",+ ("/redo/id",),+ {"recursive": True, "ctx": {"account_id": "_system"}},+ ),]diff --git a/tests/cli/conftest.py b/tests/cli/conftest.pyindex 1036b86f7..e98413a59 100644--- a/tests/cli/conftest.py+++ b/tests/cli/conftest.py@@ -423,6 +423,22 @@ def ensure_resources_dir():pass[email protected](scope="session")+def ensure_user_skills_dir():+ uri = "viking://user/skills"+ for _attempt in range(5):+ r = ov(["mkdir", uri, "-o", "json"], timeout=120)+ if r["exit_code"] == 0 or "already exists" in (r.get("stderr") or "").lower():+ return++ stat_r = ov(["stat", uri, "-o", "json"], timeout=120)+ if stat_r["exit_code"] == 0:+ return++ time.sleep(5)+ assert r["exit_code"] == 0, f"mkdir {uri} failed after retries: {r['stderr']}"++@pytest.fixture(scope="session")def test_dir_uri(ensure_resources_dir):uri = f"viking://resources/cli_test_{uuid.uuid4().hex[:8]}"diff --git a/tests/cli/test_cli_skills.py b/tests/cli/test_cli_skills.pyindex f1a6341c5..ad2ef9c55 100644--- a/tests/cli/test_cli_skills.py+++ b/tests/cli/test_cli_skills.py@@ -72,7 +72,7 @@ class TestSkillAdd:class TestSkillList:- def test_list_skills(self):+ def test_list_skills(self, ensure_user_skills_dir):r = ov(["ls", "viking://user/skills/", "-o", "json"])assert r["exit_code"] == 0, (f"ov ls skills should exit 0, got {r['exit_code']}: {r['stderr'][:300]}"@@ -84,7 +84,7 @@ class TestSkillList:class TestSkillRead:- def test_read_skill(self):+ def test_read_skill(self, ensure_user_skills_dir):ls_r = ov(["ls", "viking://user/skills/", "-o", "json"])if ls_r["exit_code"] != 0 or not ls_r["json"] or not ls_r["json"].get("result"):pytest.skip("No skills available to test read")diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.tsindex c4123ea6a..6b108430c 100644--- a/web-studio/src/i18n/locales/en.ts+++ b/web-studio/src/i18n/locales/en.ts@@ -484,6 +484,68 @@ const en = {failed: 'Processing failed',},},+ searchPalette: {+ ariaLabel: 'Search',+ openContainingDirectory: 'Open containing directory',+ placeholder: 'Search',+ scope: {+ global: 'Search scope: Global',+ current: 'Search scope: {{name}}',+ resetToGlobal: 'Click to reset to global search',+ },+ scopeState: {+ validatingTitle: 'Validating search scope',+ validatingPrefix: 'Checking whether',+ validatingSuffix: 'exists',+ switchTitle: 'Switch search scope',+ switchPrefix: 'Press',+ switchMiddle: 'to switch to',+ invalidTitle: 'Search scope not found',+ invalidPrefix: 'Path',+ invalidSuffix: 'is inaccessible and cannot be switched to',+ },+ empty: {+ title: 'Search files and directories',+ },+ browseDirHint: {+ before: 'Enter',+ after: 'to browse directories',+ },+ globalScopeHint: {+ before: 'Enter',+ after: 'to switch search scope to global',+ },+ error: 'Search failed',+ emptyResults: {+ title: 'No matching files or directories found',+ subtitle: 'Try another keyword?',+ },+ footer: {+ dirMode: {+ select: 'Select',+ level: 'Level',+ confirm: 'Confirm',+ cancel: 'Cancel',+ },+ resultMode: {+ navigate: 'Navigate',+ open: 'Open',+ close: 'Close',+ count: '{{count}} results',+ },+ },+ },+ dirBrowser: {+ back: 'Back',+ loading: 'Loading directory',+ filesSection: 'Files',+ error: 'Failed to load directory',+ empty: {+ title: 'Empty directory',+ subtitle:+ 'There are currently no subdirectories to expand at this level',+ },+ },filePreview: {cancel: 'Cancel',edit: 'Edit',@@ -659,6 +721,7 @@ const en = {playground: {copyUri: 'Copy current URI',copied: 'URI copied',+ copyFailed: 'Copy failed',resizeContext: 'Resize context tree width',resizeAction: 'Resize Terminal and Agent width',readFailed: 'Failed to read {{uri}}',@@ -675,6 +738,7 @@ const en = {explorer: {title: 'Context tree',addResource: 'Add resource',+ search: 'Search context',refresh: 'Refresh tree',namespaces: {user: 'Personalized user memories',@@ -765,6 +829,8 @@ const en = {resource: 'Resource paths',history: 'History',},+ resourceSuggestion: 'Resource path',+ historySuggestion: 'History',groupLabels: {resources: 'resource',memories: 'memory',diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.tsindex 2d4bca519..591f378fb 100644--- a/web-studio/src/i18n/locales/zh-CN.ts+++ b/web-studio/src/i18n/locales/zh-CN.ts@@ -473,6 +473,67 @@ const zhCN = {failed: '处理失败',},},+ searchPalette: {+ ariaLabel: '搜索',+ openContainingDirectory: '打开所在目录',+ placeholder: '搜索',+ scope: {+ global: '搜索范围: 全局',+ current: '搜索范围: {{name}}',+ resetToGlobal: '点击重置为全局搜索',+ },+ scopeState: {+ validatingTitle: '正在校验搜索范围',+ validatingPrefix: '正在检查',+ validatingSuffix: '是否存在',+ switchTitle: '切换搜索范围',+ switchPrefix: '按',+ switchMiddle: '切换到',+ invalidTitle: '搜索范围不存在',+ invalidPrefix: '路径',+ invalidSuffix: '无法访问,不能切换',+ },+ empty: {+ title: '搜索文件和目录',+ },+ browseDirHint: {+ before: '输入',+ after: '浏览目录结构',+ },+ globalScopeHint: {+ before: '输入',+ after: '切换搜索范围到全局',+ },+ error: '搜索出错',+ emptyResults: {+ title: '没有找到匹配的文件或目录',+ subtitle: '试试换个关键词?',+ },+ footer: {+ dirMode: {+ select: '选择',+ level: '层级',+ confirm: '确定',+ cancel: '取消',+ },+ resultMode: {+ navigate: '导航',+ open: '打开',+ close: '关闭',+ count: '{{count}} 个结果',+ },+ },+ },+ dirBrowser: {+ back: '返回上一级',+ loading: '正在加载目录',+ filesSection: '文件',+ error: '加载目录失败',+ empty: {+ title: '空目录',+ subtitle: '这一层目前没有可继续展开的子目录',+ },+ },filePreview: {cancel: '取消',edit: '编辑',@@ -641,6 +702,7 @@ const zhCN = {playground: {copyUri: '复制当前 URI',copied: '已复制 URI',+ copyFailed: '复制失败',resizeContext: '调整上下文目录宽度',resizeAction: '调整 Terminal 和 Agent 宽度',readFailed: '无法读取 {{uri}}',@@ -657,6 +719,7 @@ const zhCN = {explorer: {title: '上下文目录',addResource: '添加资源',+ search: '搜索上下文',refresh: '刷新目录',namespaces: {user: '用户个性化记忆',@@ -745,6 +808,8 @@ const zhCN = {resource: '资源路径',history: '历史记录',},+ resourceSuggestion: '资源路径',+ historySuggestion: '历史记录',groupLabels: {resources: '资源',memories: '记忆',diff --git a/web-studio/src/lib/clipboard.ts b/web-studio/src/lib/clipboard.tsnew file mode 100644index 000000000..027c8825e--- /dev/null+++ b/web-studio/src/lib/clipboard.ts@@ -0,0 +1,31 @@+export async function copyTextToClipboard(value: string): Promise<void> {+ try {+ await navigator.clipboard.writeText(value)+ return+ } catch {+ // Clipboard API is unavailable on non-secure dev URLs such as http://10.x.x.x.+ }++ if (typeof document === 'undefined') {+ throw new Error('Clipboard is unavailable')+ }++ const textArea = document.createElement('textarea')+ textArea.value = value+ textArea.setAttribute('readonly', '')+ textArea.style.position = 'fixed'+ textArea.style.left = '-9999px'+ textArea.style.top = '0'+ document.body.appendChild(textArea)+ textArea.focus()+ textArea.select()++ try {+ const copied = document.execCommand('copy')+ if (!copied) {+ throw new Error('Clipboard copy failed')+ }+ } finally {+ document.body.removeChild(textArea)+ }+}diff --git a/web-studio/src/lib/viking-uri.test.ts b/web-studio/src/lib/viking-uri.test.tsnew file mode 100644index 000000000..46ec96c83--- /dev/null+++ b/web-studio/src/lib/viking-uri.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest'++import { cleanVikingUri } from './viking-uri'++describe('cleanVikingUri', () => {+ it('keeps spaces in direct viking uri values', () => {+ expect(+ cleanVikingUri(+ 'viking://user/default/memories/events/2026/06/01/OpenViking Agent文档国际化调整.md',+ ),+ ).toBe(+ 'viking://user/default/memories/events/2026/06/01/OpenViking Agent文档国际化调整.md',+ )+ })++ it('still extracts a uri from prose', () => {+ expect(cleanVikingUri('open viking://user/default/memory.md now')).toBe(+ 'viking://user/default/memory.md',+ )+ })+})diff --git a/web-studio/src/lib/viking-uri.ts b/web-studio/src/lib/viking-uri.tsindex f7e199dc6..144f71184 100644--- a/web-studio/src/lib/viking-uri.ts+++ b/web-studio/src/lib/viking-uri.ts@@ -66,6 +66,11 @@ export const VIKING_URI_RE = /viking:\/\/[^\s,,。;;'"`<>()\]}\\]+/g* URI) and strip trailing punctuation that bleeds in from surrounding prose.*/export function cleanVikingUri(value: string): string {+ const trimmed = value.trim()+ if (trimmed.toLowerCase().startsWith('viking://')) {+ return trimmed.replace(/[\\,。;;,.]+$/u, '')+ }+const match = value.match(VIKING_URI_RE)- return (match?.[0] ?? value).trim().replace(/[\\,。;;,.]+$/u, '')+ return (match?.[0] ?? trimmed).trim().replace(/[\\,。;;,.]+$/u, '')}diff --git a/web-studio/src/routes/index.tsx b/web-studio/src/routes/index.tsxindex c39811878..dcef54e25 100644--- a/web-studio/src/routes/index.tsx+++ b/web-studio/src/routes/index.tsx@@ -5,5 +5,5 @@ export const Route = createFileRoute('/')({})function IndexRoute() {- return <Navigate replace to="/home" />+ return <Navigate replace to="/playground" />}diff --git a/web-studio/src/routes/playground/-components/context-explorer.tsx b/web-studio/src/routes/playground/-components/context-explorer.tsxindex 917916c3f..c18110f64 100644--- a/web-studio/src/routes/playground/-components/context-explorer.tsx+++ b/web-studio/src/routes/playground/-components/context-explorer.tsx@@ -3,14 +3,15 @@ import type { PointerEvent as ReactPointerEvent } from 'react'import { useTranslation } from 'react-i18next'import {ChevronRightIcon,+ ClipboardListIcon,CommandIcon,FileTextIcon,FolderIcon,FolderTreeIcon,- LoaderCircleIcon,Loader2Icon,PlusIcon,RefreshCcwIcon,+ SearchIcon,} from 'lucide-react'import { Button } from '#/components/ui/button'@@ -32,21 +33,27 @@ const TREE_CHILD_CONTENT_OFFSET = 26export function ContextExplorerHeader({activeTaskCount,hasActiveTasks,+ hasTasks,isRefreshing,isRefreshingTasks,onAddResource,onOpenProcessingTasks,+ onOpenSearch,onRefresh,}: {activeTaskCount: numberhasActiveTasks: boolean+ hasTasks: booleanisRefreshing: booleanisRefreshingTasks: booleanonAddResource: () => voidonOpenProcessingTasks: () => void+ onOpenSearch: () => voidonRefresh: () => void}) {const { t } = useTranslation(['playground', 'resources'])+ const showProcessingTasks = hasTasks || isRefreshingTasks+return (<div className="border-b px-3 py-3"><div className="flex items-center gap-2">@@ -56,26 +63,36 @@ export function ContextExplorerHeader({<div className="min-w-0 flex-1"><div className="text-sm font-semibold">{t('explorer.title')}</div></div>+ {showProcessingTasks ? (+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ className="relative"+ title={t('processingTasks.title', { ns: 'resources' })}+ onClick={onOpenProcessingTasks}+ >+ <ClipboardListIcon+ className={cn(+ 'size-4',+ (hasActiveTasks || isRefreshingTasks) && 'text-primary',+ )}+ />+ {activeTaskCount > 0 ? (+ <span className="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold leading-none text-primary-foreground">+ {activeTaskCount}+ </span>+ ) : null}+ </Button>+ ) : null}<Buttontype="button"size="icon-sm"variant="ghost"- className="relative"- title={t('processingTasks.title', { ns: 'resources' })}- onClick={onOpenProcessingTasks}+ title={t('explorer.search')}+ onClick={onOpenSearch}>- <LoaderCircleIcon- className={cn(- 'size-4',- (hasActiveTasks || isRefreshingTasks) &&- 'animate-spin text-primary',- )}- />- {activeTaskCount > 0 ? (- <span className="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold leading-none text-primary-foreground">- {activeTaskCount}- </span>- ) : null}+ <SearchIcon className="size-4" /></Button><Buttontype="button"diff --git a/web-studio/src/routes/playground/-components/terminal-panel.tsx b/web-studio/src/routes/playground/-components/terminal-panel.tsxindex 5adce39c5..7240054e8 100644--- a/web-studio/src/routes/playground/-components/terminal-panel.tsx+++ b/web-studio/src/routes/playground/-components/terminal-panel.tsx@@ -50,6 +50,7 @@ import type {import {cleanVikingUri,entryToRef,+ getErrorMessage,readStoredJsonArray,removeStoredValue,searchResultToRefs,@@ -133,7 +134,9 @@ function loadTerminalHistory(): TerminalEntry[] {if (typeof record.id !== 'string' ||typeof record.title !== 'string' ||- !['command', 'error', 'info', 'success'].includes(String(record.kind)) ||+ !['command', 'error', 'info', 'success'].includes(+ String(record.kind),+ ) ||(record.body !== undefined && typeof record.body !== 'string')) {return undefined@@ -581,7 +584,7 @@ export function TerminalPanel({}} catch (error) {append({- body: error instanceof Error ? error.message : String(error),+ body: getErrorMessage(error),kind: 'error',title: t('terminal.commandFailed'),})@@ -803,7 +806,7 @@ export function TerminalPanel({key={suggestion.id}type="button"className={cn(- 'flex w-full min-w-0 items-start gap-3 rounded-md px-2 py-2 text-left transition-colors',+ 'grid w-full min-w-0 grid-cols-[minmax(5rem,12rem)_minmax(0,1fr)] items-start gap-3 rounded-md px-2 py-2 text-left transition-colors',index === activeSuggestionIndex? 'bg-primary/10 text-foreground': 'hover:bg-muted/60',@@ -814,7 +817,10 @@ export function TerminalPanel({setActiveSuggestionIndex(index)}>- <span className="w-24 shrink-0 font-mono text-xs font-semibold text-primary">+ <span+ className="min-w-0 truncate font-mono text-xs font-semibold text-primary"+ title={suggestion.command}+ >{suggestion.command}</span><span className="min-w-0 flex-1">diff --git a/web-studio/src/routes/playground/-lib/utils.ts b/web-studio/src/routes/playground/-lib/utils.tsindex d7f7899a4..614f31a94 100644--- a/web-studio/src/routes/playground/-lib/utils.ts+++ b/web-studio/src/routes/playground/-lib/utils.ts@@ -15,7 +15,27 @@ import type { ResourceRef } from './types'export { cleanVikingUri }export function getErrorMessage(error: unknown): string {- return error instanceof Error ? error.message : String(error)+ if (error instanceof Error) return error.message+ if (error && typeof error === 'object') {+ const data = error as {+ code?: unknown+ message?: unknown+ statusCode?: unknown+ }+ const code = typeof data.code === 'string' ? data.code : ''+ const message = typeof data.message === 'string' ? data.message : ''+ const status =+ typeof data.statusCode === 'number' ? `HTTP ${data.statusCode}` : ''+ const readable = [status, code, message].filter(Boolean).join(' · ')+ if (readable) return readable++ try {+ return JSON.stringify(error)+ } catch {+ return String(error)+ }+ }+ return String(error)}export function clampNumber(value: number, min: number, max: number): number {diff --git a/web-studio/src/routes/playground/route.tsx b/web-studio/src/routes/playground/route.tsxindex b6de708f4..a6ad96788 100644--- a/web-studio/src/routes/playground/route.tsx+++ b/web-studio/src/routes/playground/route.tsx@@ -20,6 +20,8 @@ import {ResourceUploadProvider,useResourceUpload,} from '#/routes/resources/-hooks/use-resource-upload'+import { FindPalette } from '#/routes/resources/-components/find-palette'+import { copyTextToClipboard } from '#/lib/clipboard'import {useInvalidateVikingFs,useVikingFsList,@@ -54,6 +56,7 @@ import {clampNumber,cleanVikingUri,createEntryFromUri,+ getErrorMessage,getAncestorUris,isDirectoryLevelFile,mergeExpanded,@@ -111,6 +114,7 @@ function PlaygroundWorkbench() {const [uploadDialogOpen, setUploadDialogOpen] = useState(() => search.upload ?? false,)+ const [findPaletteOpen, setFindPaletteOpen] = useState(false)const [taskDialogOpen, setTaskDialogOpen] = useState(false)const [openingUri, setOpeningUri] = useState<string | null>(null)const layoutRef = useRef<HTMLDivElement>(null)@@ -164,10 +168,12 @@ function PlaygroundWorkbench() {}) => {navigate({replace: true,- search: (prev) => ({- ...prev,- ...next,- }),+ search: (prev) => {+ const merged: Record<string, unknown> = { ...prev, ...next }+ return Object.fromEntries(+ Object.entries(merged).filter(([, value]) => value !== undefined),+ )+ },})},[navigate],@@ -249,19 +255,15 @@ function PlaygroundWorkbench() {: normalizeDirUri(parentUri(normalized))setCurrentUri(nextCurrentUri)- setSelectedFile(createEntryFromUri(normalized, fallbackIsDir))+ setSelectedFile(null)setExpandedKeys((prev) =>mergeExpanded(prev, getAncestorUris(nextCurrentUri)),)syncSearch({- file: fallbackIsDir ? undefined : normalized,+ file: undefined,uri: nextCurrentUri,})- toast.error(- error instanceof Error- ? error.message- : t('readFailed', { uri: cleaned }),- )+ toast.error(getErrorMessage(error) || t('readFailed', { uri: cleaned }))} finally {setOpeningUri(null)}@@ -318,6 +320,37 @@ function PlaygroundWorkbench() {void refreshTasks()}, [refreshTasks])+ const handleOpenSearch = useCallback(() => {+ setFindPaletteOpen(true)+ }, [])++ const handleNavigateDirectory = useCallback(+ (rawUri: string) => {+ const normalized = normalizeDirUri(rawUri)+ setCurrentUri(normalized)+ setSelectedFile(createEntryFromUri(normalized, true))+ setExpandedKeys((prev) =>+ mergeExpanded(prev, getAncestorUris(normalized)),+ )+ syncSearch({ file: undefined, uri: normalized })+ },+ [syncSearch],+ )++ useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {+ event.preventDefault()+ setFindPaletteOpen((open) => !open)+ }+ }++ document.addEventListener('keydown', handleKeyDown)+ return () => {+ document.removeEventListener('keydown', handleKeyDown)+ }+ }, [])+const selectedUri = selectedFile?.uri ?? currentUriconst displayUri =selectedUri === ROOT_URI ? selectedUri : selectedUri.replace(/\/$/, '')@@ -435,10 +468,12 @@ function PlaygroundWorkbench() {<ContextExplorerHeaderactiveTaskCount={activeTaskCount}hasActiveTasks={hasActiveTasks}+ hasTasks={tasks.length > 0}isRefreshing={listQuery.isFetching}isRefreshingTasks={isRefreshingTasks}onAddResource={() => setUploadDialogOpen(true)}onOpenProcessingTasks={handleOpenProcessingTasks}+ onOpenSearch={handleOpenSearch}onRefresh={() => {void invalidateList(currentUri)void listQuery.refetch()@@ -479,8 +514,13 @@ function PlaygroundWorkbench() {variant="ghost"title={t('copyUri')}onClick={() => {- void navigator.clipboard.writeText(selectedUri)- toast.success(t('copied'))+ void copyTextToClipboard(selectedUri)+ .then(() => {+ toast.success(t('copied'))+ })+ .catch(() => {+ toast.error(t('copyFailed'))+ })}}><ClipboardIcon className="size-4" />@@ -568,6 +608,13 @@ function PlaygroundWorkbench() {onOpenChange={setTaskDialogOpen}tasks={tasks}/>+ <FindPalette+ open={findPaletteOpen}+ onClose={() => setFindPaletteOpen(false)}+ onNavigate={(uri) => void revealResource(uri)}+ onNavigateDir={handleNavigateDirectory}+ scopeUri={currentUri}+ /></div>)}diff --git a/web-studio/src/routes/resources/-components/dir-browser.tsx b/web-studio/src/routes/resources/-components/dir-browser.tsxnew file mode 100644index 000000000..bbfbde067--- /dev/null+++ b/web-studio/src/routes/resources/-components/dir-browser.tsx@@ -0,0 +1,238 @@+import { useMemo } from 'react'+import type { TFunction } from 'i18next'+import { ArrowLeft, Folder, Loader2 } from 'lucide-react'+import { useTranslation } from 'react-i18next'++import { cn } from '#/lib/utils'++import { normalizeDirUri, fileNameFromUri } from '../-lib/normalize'+import { useVikingFsList, useDebouncedValue } from '../-hooks/viking-fm'+import type { VikingFsEntry } from '../-types/viking-fm'+import { FilePreview } from './file-preview'+import { ItemColumn } from './item-column'++const VIKING_ROOT_URI = 'viking://'++// Pure controlled view. The browsed directory (currentUri), the item list and+// the cursor (activeIndex) are all owned by FindPalette; this component only+// renders and reports intent via callbacks — no internal focus state, no+// document keyboard listener, no two-way sync ref.+interface DirBrowserProps {+ currentUri: string+ items: VikingFsEntry[]+ activeIndex: number+ loading?: boolean+ errored?: boolean+ onCursorChange: (index: number) => void+ onEnterDir: (uri: string) => void+ onOpenFile: (uri: string) => void+ onGoBack: () => void+}++// What the right (detail) pane shows, computed once as an explicit value so the+// render is a flat switch instead of a 6-deep ternary chain.+type DetailView =+ | { kind: 'preview'; file: VikingFsEntry }+ | { kind: 'loading' }+ | { kind: 'error' }+ | { kind: 'subdir'; items: VikingFsEntry[]; label: string }+ | { kind: 'empty' }+ | { kind: 'idle' }++export function DirBrowser({+ currentUri,+ items,+ activeIndex,+ loading = false,+ errored = false,+ onCursorChange,+ onEnterDir,+ onOpenFile,+ onGoBack,+}: DirBrowserProps) {+ const { t } = useTranslation('resources')++ // activeIndex can transiently fall out of range while the list reshapes, so+ // the cursor really is nullable (bounds check keeps the union honest).+ const cursorItem =+ activeIndex >= 0 && activeIndex < items.length ? items[activeIndex] : null++ // Peek (right pane) is a pure derivation of the cursor item. Debounced so+ // arrow-scanning a long directory doesn't fire a request per row.+ const subdirUri = cursorItem?.isDir ? normalizeDirUri(cursorItem.uri) : null+ const debouncedSubdirUri = useDebouncedValue(subdirUri, 150)+ const subdirQuery = useVikingFsList(+ debouncedSubdirUri || VIKING_ROOT_URI,+ { output: 'agent', showAllHidden: true, nodeLimit: 200 },+ Boolean(debouncedSubdirUri),+ )+ const subdirItems = useMemo(() => {+ if (!debouncedSubdirUri || !subdirQuery.data?.entries) return []+ const entries = subdirQuery.data.entries+ const dirs = entries.filter((e) => e.isDir)+ const files = entries.filter((e) => !e.isDir)+ return [...dirs, ...files]+ }, [debouncedSubdirUri, subdirQuery.data])+ const peekPending = Boolean(subdirUri) && subdirUri !== debouncedSubdirUri++ const canGoBack = currentUri !== VIKING_ROOT_URI++ const detail = useMemo<DetailView>(() => {+ if (!cursorItem) return { kind: 'idle' }+ if (!cursorItem.isDir) return { kind: 'preview', file: cursorItem }+ if (peekPending || subdirQuery.isLoading) return { kind: 'loading' }+ if (subdirQuery.isError) return { kind: 'error' }+ if (subdirItems.length > 0) {+ return {+ kind: 'subdir',+ items: subdirItems,+ label: fileNameFromUri(cursorItem.uri),+ }+ }+ return { kind: 'empty' }+ }, [+ cursorItem,+ peekPending,+ subdirQuery.isLoading,+ subdirQuery.isError,+ subdirItems,+ ])++ return (+ <div className="flex min-w-0 flex-1 flex-col overflow-hidden">+ <div className="flex items-center justify-between border-b bg-background/85 px-3 py-2 backdrop-blur-sm">+ <button+ type="button"+ onClick={() => {+ if (canGoBack) onGoBack()+ }}+ disabled={!canGoBack}+ className={cn(+ 'inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium transition-colors',+ canGoBack+ ? 'text-foreground/75 hover:bg-muted hover:text-foreground'+ : 'cursor-not-allowed text-muted-foreground/45',+ )}+ >+ <ArrowLeft className="size-3.5" />+ <span>{t('dirBrowser.back')}</span>+ </button>+ <div className="max-w-[55%] truncate rounded-md bg-blue-500/10 px-2.5 py-1 text-sm font-semibold text-blue-700 dark:text-blue-300">+ {currentUri}+ </div>+ </div>+ <div className="flex min-h-0 flex-1 min-w-0 justify-start overflow-hidden bg-[linear-gradient(180deg,color-mix(in_oklch,var(--muted)_35%,transparent),transparent_18%)]">+ {loading ? (+ <div className="flex flex-1 items-center justify-center">+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ </div>+ ) : errored ? (+ <div+ role="alert"+ className="flex flex-1 items-center justify-center px-6 text-sm text-destructive"+ >+ {t('dirBrowser.error')}+ </div>+ ) : (+ <>+ <ItemColumn+ className="w-[clamp(15rem,35vw,22rem)] shrink-0"+ label={fileNameFromUri(currentUri.replace(/\/$/, '')) || '/'}+ items={items}+ activeIndex={activeIndex}+ t={t}+ onSelect={(entry, i) =>+ entry.isDir ? onEnterDir(entry.uri) : onCursorChange(i)+ }+ />+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden border-l">+ <DetailPane+ detail={detail}+ t={t}+ onEnterDir={onEnterDir}+ onOpenFile={onOpenFile}+ />+ </div>+ </>+ )}+ </div>+ </div>+ )+}++function DetailPane({+ detail,+ t,+ onEnterDir,+ onOpenFile,+}: {+ detail: DetailView+ t: TFunction<'resources'>+ onEnterDir: (uri: string) => void+ onOpenFile: (uri: string) => void+}) {+ switch (detail.kind) {+ case 'preview':+ return (+ <FilePreview+ file={detail.file}+ onClose={() => {}}+ showCloseButton={false}+ />+ )+ case 'loading':+ return (+ <div className="flex flex-1 items-center justify-center">+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ </div>+ )+ case 'error':+ return (+ <div+ role="alert"+ className="flex flex-1 items-center justify-center px-6 text-sm text-destructive"+ >+ {t('dirBrowser.error')}+ </div>+ )+ case 'subdir':+ return (+ <ItemColumn+ className="min-w-0 flex-1"+ label={detail.label}+ items={detail.items}+ activeIndex={-1}+ t={t}+ onSelect={(entry) => {+ if (entry.isDir) {+ onEnterDir(entry.uri)+ return+ }+ onOpenFile(entry.uri)+ }}+ />+ )+ case 'empty':+ return (+ <div className="flex flex-1 items-center justify-center px-6">+ <div className="max-w-[13rem] text-center">+ <div className="mx-auto mb-3 flex size-10 items-center justify-center rounded-2xl bg-muted/60 text-muted-foreground/70 shadow-inner">+ <Folder className="size-4" />+ </div>+ <p className="text-sm font-medium text-foreground/70">+ {t('dirBrowser.empty.title')}+ </p>+ <p className="mt-1 text-xs leading-5 text-muted-foreground/75">+ {t('dirBrowser.empty.subtitle')}+ </p>+ </div>+ </div>+ )+ case 'idle':+ return (+ <div className="flex flex-1 items-center justify-center px-6 text-sm text-muted-foreground/60">+ {t('dirBrowser.empty.title')}+ </div>+ )+ }+}diff --git a/web-studio/src/routes/resources/-components/find-palette.tsx b/web-studio/src/routes/resources/-components/find-palette.tsxnew file mode 100644index 000000000..feefd39fc--- /dev/null+++ b/web-studio/src/routes/resources/-components/find-palette.tsx@@ -0,0 +1,698 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import {+ FileIcon,+ FolderIcon,+ FolderOpen,+ Loader2,+ Search,+ X,+} from 'lucide-react'+import { useTranslation } from 'react-i18next'++import { cn } from '#/lib/utils'+import { useTransientScrollbar } from '#/hooks/use-transient-scrollbar'++import {+ fileNameFromUri,+ normalizeDirUri,+ parentUri as getParentUri,+} from '../-lib/normalize'+import {+ filterResourceSearchEntries,+ getResourceSearchSpec,+} from '../-lib/find-search'+import {+ PALETTE_ROOT_URI,+ buildDirBrowseQuery,+ isResetGlobalCommand,+ parsePaletteMode,+} from '../-lib/palette-mode'+import {+ useVikingFsList,+ useVikingFsStat,+ useVikingFsTree,+ useDebouncedValue,+} from '../-hooks/viking-fm'+import { useListNavigation } from '../-hooks/use-list-navigation'+import type { VikingFsEntry } from '../-types/viking-fm'+import { FilePreview } from './file-preview'+import { DirBrowser } from './dir-browser'++interface FindPaletteProps {+ open: boolean+ onClose: () => void+ onNavigate: (uri: string) => void+ onNavigateDir: (uri: string) => void+ scopeUri?: string+}+const KEY_ESCAPE_LABEL = 'esc'++function displayName(uri: string): { name: string; parent: string } {+ const name = fileNameFromUri(uri)+ const dir = getParentUri(uri)+ const segments = dir.replace(/\/$/, '').split('/').filter(Boolean)+ const parent = segments.length > 1 ? segments.slice(-1)[0] : dir+ return { name, parent }+}++function errorDescription(error: unknown): string {+ if (!error) return ''+ if (error instanceof Error) return error.message+ if (typeof error === 'object') {+ const data = error as {+ code?: unknown+ message?: unknown+ statusCode?: unknown+ }+ const code = typeof data.code === 'string' ? data.code : ''+ const message = typeof data.message === 'string' ? data.message : ''+ const status =+ typeof data.statusCode === 'number' ? `HTTP ${data.statusCode}` : ''+ const readable = [status, code, message].filter(Boolean).join(' · ')+ if (readable) return readable+ }+ return String(error)+}++export function FindPalette({+ open,+ onClose,+ onNavigate,+ onNavigateDir,+ scopeUri,+}: FindPaletteProps) {+ const { t } = useTranslation('resources')+ const [query, setQuery] = useState('')+ const [findTargetUri, setFindTargetUri] = useState(() =>+ normalizeDirUri(scopeUri || PALETTE_ROOT_URI),+ )+ const inputRef = useRef<HTMLInputElement>(null)+ const resultsRef = useRef<HTMLDivElement>(null)+ const composingRef = useRef(false)+ const wasOpenRef = useRef(false)++ // Single parse entry point. No component code reads `query` structurally.+ const mode = useMemo(+ () => parsePaletteMode(query, findTargetUri),+ [query, findTargetUri],+ )+ const isRoot = findTargetUri === PALETTE_ROOT_URI+ const showIdleBrowse = mode.kind === 'idle' && !isRoot++ const searchSpec = useMemo(+ () =>+ mode.kind === 'search'+ ? getResourceSearchSpec(mode.query, findTargetUri)+ : null,+ [mode, findTargetUri],+ )++ const idleBrowseQuery = useVikingFsList(+ findTargetUri,+ { output: 'agent', showAllHidden: true },+ showIdleBrowse,+ )+ const idleEntries = useMemo(+ () => (showIdleBrowse ? idleBrowseQuery.data?.entries || [] : []),+ [showIdleBrowse, idleBrowseQuery.data?.entries],+ )++ const treeQuery = useVikingFsTree(+ searchSpec?.rootUri || PALETTE_ROOT_URI,+ { output: 'agent', showAllHidden: true, nodeLimit: 2000, levelLimit: 100 },+ mode.kind === 'search' && Boolean(searchSpec),+ )+ const filteredEntries = useMemo(() => {+ if (mode.kind !== 'search' || !treeQuery.data?.nodes) return []+ return filterResourceSearchEntries(treeQuery.data.nodes, searchSpec)+ }, [mode.kind, treeQuery.data?.nodes, searchSpec])++ // Directory listing lifted up from DirBrowser so the cursor (activeIndex) and+ // keyboard handling can live in one place. DirBrowser is now a pure view.+ const dirListQuery = useVikingFsList(+ mode.kind === 'dirBrowse' ? mode.uri : PALETTE_ROOT_URI,+ { output: 'agent', showAllHidden: true, nodeLimit: 200 },+ mode.kind === 'dirBrowse',+ )+ const dirItems = useMemo(() => {+ if (mode.kind !== 'dirBrowse') return []+ const entries = dirListQuery.data?.entries ?? []+ const dirs = entries.filter((e) => e.isDir)+ const files = entries.filter((e) => !e.isDir)+ const all = [...dirs, ...files]+ if (!mode.filter) return all+ const lower = mode.filter.toLowerCase()+ return all.filter((e) => e.name.toLowerCase().includes(lower))+ }, [mode, dirListQuery.data])+ const hasResults = filteredEntries.length > 0+ const visibleEntries = useMemo(() => {+ if (mode.kind === 'dirBrowse') return dirItems+ if (hasResults) return filteredEntries+ return idleEntries+ }, [mode.kind, dirItems, hasResults, filteredEntries, idleEntries])++ const {+ index: activeIndex,+ setIndex,+ moveUp,+ moveDown,+ reset,+ } = useListNavigation(visibleEntries.length)+ const activeEntry =+ activeIndex >= 0 ? (visibleEntries[activeIndex] ?? null) : null++ // Preview stat only for search / idle file cursor. dirBrowse renders its own+ // preview inside DirBrowser. Debounced so arrow-scanning doesn't storm stat.+ const statTargetUri =+ mode.kind !== 'dirBrowse' && activeEntry && !activeEntry.isDir+ ? activeEntry.uri+ : undefined+ const debouncedStatUri = useDebouncedValue(statTargetUri, 150)+ const statQuery = useVikingFsStat(debouncedStatUri)+ const previewEntry = useMemo(() => {+ if (!activeEntry) return null+ if (statQuery.data && debouncedStatUri === activeEntry.uri) {+ return {+ ...activeEntry,+ size: statQuery.data.size,+ sizeBytes: statQuery.data.sizeBytes,+ modTime: statQuery.data.modTime,+ }+ }+ return activeEntry+ }, [activeEntry, statQuery.data, debouncedStatUri])++ const focusInput = useCallback(() => {+ requestAnimationFrame(() => {+ inputRef.current?.focus()+ inputRef.current?.select()+ })+ }, [])++ useEffect(() => {+ if (open && !wasOpenRef.current) {+ setFindTargetUri(normalizeDirUri(scopeUri || PALETTE_ROOT_URI))+ reset()+ focusInput()+ }+ wasOpenRef.current = open+ }, [open, scopeUri, reset, focusInput])++ useEffect(() => {+ if (!open) return++ const restoreFocus = () => {+ if (document.visibilityState === 'visible') focusInput()+ }+ window.addEventListener('focus', focusInput)+ document.addEventListener('visibilitychange', restoreFocus)+ return () => {+ window.removeEventListener('focus', focusInput)+ document.removeEventListener('visibilitychange', restoreFocus)+ }+ }, [open, focusInput])++ // Cursor resets on query change (navigation / filter typing) and whenever the+ // visible list identity changes (new data arrives). Arrow moves don't touch+ // query or the list, so they don't trigger a reset.+ useEffect(() => {+ reset()+ }, [query, visibleEntries, reset])++ useEffect(() => {+ if (!resultsRef.current) return+ const el = resultsRef.current.querySelector('[data-active="true"]')+ el?.scrollIntoView({ block: 'nearest' })+ }, [activeIndex])+ // Navigation writes go through buildDirBrowseQuery — the only place that+ // turns a uri back into a query string. setQuery is the single owner.+ const enterDir = useCallback((uri: string) => {+ setQuery(buildDirBrowseQuery(uri))+ }, [])++ const goToParent = useCallback(() => {+ if (mode.kind !== 'dirBrowse') return+ const parent = getParentUri(mode.uri)+ if (parent !== mode.uri) {+ setQuery(buildDirBrowseQuery(parent))+ }+ }, [mode])++ const confirmDirScope = useCallback((uri: string) => {+ setFindTargetUri(normalizeDirUri(uri))+ setQuery('')+ }, [])++ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ if (composingRef.current) return++ // `//` + Enter resets scope to global root, regardless of mode.+ if (isResetGlobalCommand(query) && e.key === 'Enter') {+ e.preventDefault()+ setFindTargetUri(PALETTE_ROOT_URI)+ setQuery('')+ return+ }++ if (e.key === 'Escape') {+ e.preventDefault()+ onClose()+ return+ }++ if (mode.kind === 'dirBrowse') {+ switch (e.key) {+ case 'ArrowDown':+ e.preventDefault()+ moveDown()+ return+ case 'ArrowUp':+ e.preventDefault()+ moveUp()+ return+ case 'ArrowRight':+ case 'Tab':+ e.preventDefault()+ if (activeEntry?.isDir) {+ enterDir(activeEntry.uri)+ } else if (e.key === 'Tab' && activeEntry) {+ onNavigate(activeEntry.uri)+ onClose()+ }+ return+ case 'ArrowLeft':+ e.preventDefault()+ goToParent()+ return+ case 'Enter':+ e.preventDefault()+ if (activeEntry && !activeEntry.isDir) {+ onNavigate(activeEntry.uri)+ onClose()+ } else if (dirListQuery.isSuccess) {+ confirmDirScope(mode.uri)+ }+ return+ }+ return+ }++ // search / idle list navigation+ if (visibleEntries.length === 0) return+ switch (e.key) {+ case 'ArrowDown':+ e.preventDefault()+ moveDown()+ return+ case 'ArrowUp':+ e.preventDefault()+ moveUp()+ return+ case 'Enter':+ e.preventDefault()+ if (!activeEntry) return+ if (mode.kind === 'idle' && activeEntry.isDir) {+ confirmDirScope(activeEntry.uri)+ } else {+ onNavigate(activeEntry.uri)+ onClose()+ }+ return+ }+ },+ [+ query,+ mode,+ activeEntry,+ visibleEntries.length,+ dirListQuery.isSuccess,+ moveUp,+ moveDown,+ enterDir,+ goToParent,+ confirmDirScope,+ onNavigate,+ onClose,+ ],+ )++ if (!open) return null++ const showPreview =+ mode.kind !== 'dirBrowse' && activeEntry !== null && !activeEntry.isDir+ const paletteWidth = showPreview+ ? 'w-[min(92vw,67rem)]'+ : 'w-[min(90vw,45rem)]'+ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center px-4 sm:items-start sm:px-6 sm:pt-[12vh]"+ role="dialog"+ aria-modal="true"+ aria-label={t('searchPalette.ariaLabel')}+ >+ <div+ className="animate-palette-backdrop absolute inset-0 bg-background/60 backdrop-blur-sm"+ role="presentation"+ onClick={onClose}+ />++ <div+ className={cn(+ 'animate-palette-in relative flex h-[46rem] max-h-[calc(100svh-2rem)] max-w-full flex-col overflow-hidden rounded-xl border bg-background shadow-2xl shadow-black/20 transition-[width] duration-300 sm:max-h-[84vh]',+ paletteWidth,+ )}+ onKeyDown={handleKeyDown}+ >+ {/* Search input */}+ <div className="flex items-center gap-3 border-b px-4">+ <Search className="size-4 shrink-0 text-muted-foreground" />+ <input+ ref={inputRef}+ type="text"+ placeholder={t('searchPalette.placeholder')}+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ onCompositionStart={() => {+ composingRef.current = true+ }}+ onCompositionEnd={() => {+ composingRef.current = false+ }}+ className="h-12 flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground/70 md:text-sm"+ />+ {query && (+ <button+ type="button"+ className="rounded-md p-1 text-muted-foreground/70 transition-colors hover:text-foreground"+ onClick={() => setQuery('')}+ >+ <X className="size-3.5" />+ </button>+ )}+ <span className="flex items-center gap-1 text-xs text-muted-foreground/70">+ {isRoot ? (+ t('searchPalette.scope.global')+ ) : (+ <button+ type="button"+ className="flex items-center gap-1 rounded px-1 py-0.5 transition-colors hover:bg-muted hover:text-foreground"+ title={t('searchPalette.scope.resetToGlobal')}+ onClick={() => setFindTargetUri(PALETTE_ROOT_URI)}+ >+ <FolderOpen className="size-3" />+ {t('searchPalette.scope.current', {+ name: findTargetUri.split('/').filter(Boolean).pop(),+ })}+ <X className="size-3" />+ </button>+ )}+ </span>+ </div>++ {/* Body */}+ <div className="flex min-h-0 flex-1" ref={resultsRef}>+ {mode.kind === 'dirBrowse' ? (+ <DirBrowser+ currentUri={mode.uri}+ items={dirItems}+ activeIndex={activeIndex}+ loading={dirListQuery.isLoading}+ errored={dirListQuery.isError}+ onCursorChange={setIndex}+ onEnterDir={enterDir}+ onOpenFile={(uri) => {+ onNavigate(uri)+ onClose()+ }}+ onGoBack={goToParent}+ />+ ) : (+ <>+ {/* Results area */}+ <div+ className={cn(+ 'min-h-0 flex-1 overflow-hidden',+ showPreview && 'border-r',+ )}+ >+ {mode.kind === 'idle' ? (+ showIdleBrowse && idleBrowseQuery.isError ? (+ <div+ role="alert"+ className="px-4 py-6 text-center text-xs text-destructive"+ >+ {t('dirBrowser.error')}+ </div>+ ) : showIdleBrowse && idleEntries.length > 0 ? (+ <DirResultList+ className="h-full"+ items={idleEntries}+ activeIndex={activeIndex}+ onActiveChange={setIndex}+ onSelect={(entry) => {+ if (entry.isDir) {+ confirmDirScope(entry.uri)+ } else {+ onNavigate(entry.uri)+ onClose()+ }+ }}+ onOpenDir={(entry) => {+ onNavigateDir(getParentUri(entry.uri))+ onClose()+ }}+ />+ ) : (+ <div className="animate-palette-in flex flex-col items-center gap-3 px-4 py-12 text-center">+ <Search className="size-6 text-muted-foreground/30" />+ <div>+ <p className="text-sm text-muted-foreground/70">+ {t('searchPalette.empty.title')}+ </p>+ <p className="mt-1 text-xs text-muted-foreground/50">+ {t('searchPalette.browseDirHint.before')}{' '}+ <kbd className="rounded border border-border bg-muted/50 px-1 py-0.5 font-mono text-[11px] text-foreground/70">+ /+ </kbd>{' '}+ {t('searchPalette.browseDirHint.after')}+ </p>+ <p className="mt-1 text-xs text-muted-foreground/50">+ {t('searchPalette.globalScopeHint.before')}{' '}+ <kbd className="rounded border border-border bg-muted/50 px-1 py-0.5 font-mono text-[11px] text-foreground/70">+ //+ </kbd>{' '}+ {t('searchPalette.globalScopeHint.after')}+ </p>+ </div>+ </div>+ )+ ) : treeQuery.isLoading ? (+ <div className="flex flex-col items-center gap-3 py-12">+ <Loader2 className="size-5 animate-spin text-muted-foreground/50" />+ <p className="text-xs text-muted-foreground/60">+ {t('searchPalette.scopeState.validatingTitle')}+ </p>+ </div>+ ) : treeQuery.error ? (+ <div+ role="alert"+ className="flex flex-col items-center gap-1 px-4 py-6 text-center text-xs text-destructive"+ >+ <span>{t('searchPalette.error')}</span>+ <span className="max-w-[32rem] text-muted-foreground">+ {errorDescription(treeQuery.error)}+ </span>+ </div>+ ) : !hasResults ? (+ <div className="flex flex-col items-center gap-2 px-4 py-12 text-center">+ <Search className="size-5 text-muted-foreground/25" />+ <p className="text-sm text-muted-foreground/60">+ {t('searchPalette.emptyResults.title')}+ </p>+ <p className="text-xs text-muted-foreground/40">+ {t('searchPalette.emptyResults.subtitle')}+ </p>+ </div>+ ) : (+ <DirResultList+ className="h-full"+ items={filteredEntries}+ activeIndex={activeIndex}+ onActiveChange={setIndex}+ onSelect={(entry) => {+ onNavigate(entry.uri)+ onClose()+ }}+ onOpenDir={(entry) => {+ onNavigateDir(getParentUri(entry.uri))+ onClose()+ }}+ />+ )}+ </div>++ {/* Preview pane */}+ {showPreview && (+ <div className="animate-palette-preview flex h-full w-[32rem] flex-col overflow-hidden">+ <FilePreview+ file={previewEntry}+ onClose={() => setIndex(-1)}+ showCloseButton={false}+ />+ </div>+ )}+ </>+ )}+ </div>++ {mode.kind === 'dirBrowse' ? (+ <div className="flex items-center gap-3 border-t px-4 py-2 text-xs text-muted-foreground/70">+ <span>+ <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">+ ↑↓+ </kbd>{' '}+ {t('searchPalette.footer.dirMode.select')}+ </span>+ <span>+ <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">+ ←→+ </kbd>{' '}+ {t('searchPalette.footer.dirMode.level')}+ </span>+ <span>+ <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">+ ↵+ </kbd>{' '}+ {t('searchPalette.footer.dirMode.confirm')}+ </span>+ <span>+ <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">+ {KEY_ESCAPE_LABEL}+ </kbd>{' '}+ {t('searchPalette.footer.dirMode.cancel')}+ </span>+ </div>+ ) : (+ hasResults && (+ <div className="flex items-center gap-3 border-t px-4 py-2 text-xs text-muted-foreground/70">+ <span>+ <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">+ ↑↓+ </kbd>{' '}+ {t('searchPalette.footer.resultMode.navigate')}+ </span>+ <span>+ <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">+ ↵+ </kbd>{' '}+ {t('searchPalette.footer.resultMode.open')}+ </span>+ <span>+ <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">+ {KEY_ESCAPE_LABEL}+ </kbd>{' '}+ {t('searchPalette.footer.resultMode.close')}+ </span>+ <span className="ml-auto tabular-nums">+ {t('searchPalette.footer.resultMode.count', {+ count: filteredEntries.length,+ })}+ </span>+ </div>+ )+ )}+ </div>+ </div>+ )+}+function DirResultList({+ className,+ items,+ activeIndex,+ onActiveChange,+ onSelect,+ onOpenDir,+}: {+ className?: string+ items: VikingFsEntry[]+ activeIndex: number+ onActiveChange: (index: number) => void+ onSelect: (entry: VikingFsEntry) => void+ onOpenDir: (entry: VikingFsEntry) => void+}) {+ const { t } = useTranslation('resources')+ const { isScrolling, onScroll } = useTransientScrollbar()++ return (+ <div+ className={cn(+ 'scrollbar-fade min-h-0 flex-1 overflow-y-auto overscroll-contain',+ className,+ )}+ data-scrolling={isScrolling || undefined}+ onScroll={onScroll}+ >+ {items.map((entry, i) => {+ const { name, parent } = displayName(entry.uri)+ const isActive = i === activeIndex+ const EntryIcon = entry.isDir ? FolderIcon : FileIcon++ return (+ <div+ key={entry.uri}+ data-active={isActive}+ className={cn(+ 'animate-palette-row group relative flex w-full items-start gap-3 border-b border-border/50 px-4 py-3 text-left transition-colors last:border-b-0',+ isActive+ ? 'bg-primary/8 text-foreground'+ : 'text-foreground/80 hover:bg-muted/40',+ )}+ style={{ animationDelay: `${i * 24}ms` }}+ onMouseEnter={() => onActiveChange(i)}+ >+ {isActive && (+ <span className="absolute inset-y-0 left-0 w-0.5 rounded-r bg-primary" />+ )}+ <button+ type="button"+ className="flex min-w-0 flex-1 items-start gap-3 text-left outline-none"+ onFocus={() => onActiveChange(i)}+ onClick={() => onSelect(entry)}+ >+ <EntryIcon+ className={cn(+ 'mt-0.5 size-4 shrink-0',+ entry.isDir ? 'text-blue-500/70' : 'text-muted-foreground/70',+ )}+ />+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium">{name}</div>+ <div className="mt-0.5 truncate text-xs text-muted-foreground/80">+ {parent}+ </div>+ </div>+ </button>+ {entry.size && (+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground/60">+ {entry.size}+ </span>+ )}+ <button+ type="button"+ title={t('searchPalette.openContainingDirectory')}+ className="shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover:opacity-100 data-[active=true]:opacity-100"+ data-active={isActive}+ onClick={(e) => {+ e.stopPropagation()+ onOpenDir(entry)+ }}+ >+ <FolderOpen className="size-3.5" />+ </button>+ </div>+ )+ })}+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-components/item-column.tsx b/web-studio/src/routes/resources/-components/item-column.tsxnew file mode 100644index 000000000..3e741cae1--- /dev/null+++ b/web-studio/src/routes/resources/-components/item-column.tsx@@ -0,0 +1,101 @@+import { ChevronRight, FileText, Folder } from 'lucide-react'+import type { TFunction } from 'i18next'++import { cn } from '#/lib/utils'+import { useTransientScrollbar } from '#/hooks/use-transient-scrollbar'+import type { VikingFsEntry } from '../-types/viking-fm'++export function ItemColumn({+ className,+ label,+ items,+ activeIndex,+ t,+ onSelect,+}: {+ className?: string+ label: string+ items: VikingFsEntry[]+ activeIndex: number+ t: TFunction<'resources'>+ onSelect: (entry: VikingFsEntry, index: number) => void+}) {+ const { isScrolling, onScroll } = useTransientScrollbar()++ return (+ <div className={cn('flex min-w-0 flex-col overflow-hidden', className)}>+ <div className="flex min-h-11 items-center gap-1.5 border-b bg-blue-500/8 px-3 py-2 text-xs font-semibold tracking-[0.08em] text-blue-700/80 uppercase backdrop-blur-sm dark:text-blue-300/85">+ <Folder className="size-3.5 text-blue-600/75 dark:text-blue-300/75" />+ <span className="truncate normal-case tracking-normal text-sm font-semibold text-blue-700/90 dark:text-blue-200">+ {label}+ </span>+ </div>+ <div+ className="scrollbar-fade min-h-0 flex-1 overflow-y-auto overscroll-contain"+ data-scrolling={isScrolling || undefined}+ onScroll={onScroll}+ >+ {items.length === 0 ? (+ <div className="flex h-full items-center justify-center px-6 py-10">+ <div className="max-w-[13rem] text-center">+ <div className="mx-auto mb-3 flex size-10 items-center justify-center rounded-2xl bg-muted/60 text-muted-foreground/70 shadow-inner">+ <Folder className="size-4" />+ </div>+ <p className="text-sm font-medium text-foreground/70">+ {t('dirBrowser.empty.title')}+ </p>+ <p className="mt-1 text-xs leading-5 text-muted-foreground/75">+ {t('dirBrowser.empty.subtitle')}+ </p>+ </div>+ </div>+ ) : (+ items.map((entry, i) => {+ const isActive = i === activeIndex+ const isDir = entry.isDir++ return (+ <button+ key={entry.uri}+ type="button"+ data-active={isActive}+ className={cn(+ 'group relative flex w-full items-center gap-2.5 border-b border-border/40 px-3 py-2 text-left text-sm transition-colors',+ isActive+ ? 'bg-primary/8 text-foreground'+ : 'text-foreground/80 hover:bg-muted/35',+ )}+ onClick={() => onSelect(entry, i)}+ >+ {isActive && (+ <span className="absolute inset-y-1 left-0 w-0.5 rounded-r bg-primary" />+ )}+ {isDir ? (+ <Folder+ className={cn(+ 'size-3.5 shrink-0 transition-colors',+ isActive ? 'text-primary/80' : 'text-muted-foreground',+ )}+ />+ ) : (+ <FileText+ className={cn(+ 'size-3.5 shrink-0',+ isActive+ ? 'text-blue-600/75 dark:text-blue-300/75'+ : 'text-muted-foreground/65',+ )}+ />+ )}+ <span className="truncate font-medium">{entry.name}</span>+ {isDir && (+ <ChevronRight className="ml-auto size-3 shrink-0 text-muted-foreground/45 transition-transform group-hover:translate-x-0.5" />+ )}+ </button>+ )+ })+ )}+ </div>+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-hooks/use-list-navigation.ts b/web-studio/src/routes/resources/-hooks/use-list-navigation.tsnew file mode 100644index 000000000..e11484019--- /dev/null+++ b/web-studio/src/routes/resources/-hooks/use-list-navigation.ts@@ -0,0 +1,34 @@+import { useCallback, useEffect, useRef, useState } from 'react'++// Cursor movement for keyboard-driven lists. Shared by FindPalette across its+// idle / search / dirBrowse modes so the up/down/clamp logic lives once.+// `length` is read through a ref so move handlers stay referentially stable.+export function useListNavigation(length: number) {+ const [index, setIndex] = useState(0)+ const lengthRef = useRef(length)+ lengthRef.current = length++ const moveDown = useCallback(() => {+ setIndex((i) => {+ if (lengthRef.current <= 0) return 0+ return Math.min(i + 1, lengthRef.current - 1)+ })+ }, [])++ const moveUp = useCallback(() => {+ setIndex((i) => Math.max(i - 1, 0))+ }, [])++ useEffect(() => {+ setIndex((i) => {+ if (length <= 0) return 0+ return Math.min(Math.max(i, 0), length - 1)+ })+ }, [length])++ const reset = useCallback(() => {+ setIndex(0)+ }, [])++ return { index, setIndex, moveUp, moveDown, reset }+}diff --git a/web-studio/src/routes/resources/-lib/find-search.test.ts b/web-studio/src/routes/resources/-lib/find-search.test.tsnew file mode 100644index 000000000..5f39689b2--- /dev/null+++ b/web-studio/src/routes/resources/-lib/find-search.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest'++import {+ filterResourceSearchEntries,+ getResourceSearchSpec,+} from './find-search'+import type { VikingFsEntry } from '../-types/viking-fm'++function entry(uri: string, isDir = false): VikingFsEntry {+ return {+ uri,+ name: uri.replace(/\/$/, '').split('/').pop() || uri,+ isDir,+ size: '',+ sizeBytes: null,+ modTime: '',+ modTimestamp: null,+ abstract: '',+ }+}++describe('resource path search', () => {+ it('roots exact file path searches at the containing directory', () => {+ expect(+ getResourceSearchSpec(+ 'viking://resources/project/deep/file.md',+ 'viking://',+ ),+ ).toEqual({+ mode: 'path',+ query: 'viking://resources/project/deep/file.md',+ rootUri: 'viking://resources/project/deep/',+ })+ })++ it('keeps directory path searches scoped to that subtree', () => {+ expect(+ getResourceSearchSpec('viking://resources/project/deep/', 'viking://'),+ ).toEqual({+ mode: 'path',+ query: 'viking://resources/project/deep/',+ rootUri: 'viking://resources/project/deep/',+ })+ })++ it('matches exact files and descendant directory entries', () => {+ const spec = getResourceSearchSpec(+ 'viking://resources/project/deep',+ 'viking://',+ )++ expect(+ filterResourceSearchEntries(+ [+ entry('viking://resources/project/deep.md'),+ entry('viking://resources/project/deep/', true),+ entry('viking://resources/project/deep/child.md'),+ entry('viking://resources/project/other.md'),+ ],+ spec,+ ).map((item) => item.uri),+ ).toEqual([+ 'viking://resources/project/deep/',+ 'viking://resources/project/deep/child.md',+ ])+ })+})diff --git a/web-studio/src/routes/resources/-lib/find-search.ts b/web-studio/src/routes/resources/-lib/find-search.tsnew file mode 100644index 000000000..1af1d00fd--- /dev/null+++ b/web-studio/src/routes/resources/-lib/find-search.ts@@ -0,0 +1,103 @@+import type { VikingFsEntry } from '../-types/viking-fm'+import { normalizeDirUri, normalizeFileUri, parentUri } from './normalize'++const VIKING_URI_PREFIX = 'viking://'++export type ResourceSearchSpec =+ | {+ mode: 'name'+ query: string+ rootUri: string+ }+ | {+ mode: 'path'+ query: string+ rootUri: string+ }++function rootUriForPathSearch(query: string): string {+ if (query === VIKING_URI_PREFIX) {+ return VIKING_URI_PREFIX+ }+ if (query.endsWith('/')) {+ return normalizeDirUri(query)+ }+ return parentUri(normalizeFileUri(query))+}++export function isVikingPathSearchQuery(query: string): boolean {+ return query.trimStart().toLowerCase().startsWith(VIKING_URI_PREFIX)+}++export function normalizeVikingPathSearchQuery(query: string): string {+ const trimmed = query.trim()+ if (!isVikingPathSearchQuery(trimmed)) {+ return ''+ }++ const path = trimmed.slice(VIKING_URI_PREFIX.length)+ const hasTrailingSlash = path.endsWith('/')+ const normalizedPath = path.split('/').filter(Boolean).join('/')++ if (!normalizedPath) {+ return VIKING_URI_PREFIX+ }++ return `${VIKING_URI_PREFIX}${normalizedPath}${hasTrailingSlash ? '/' : ''}`+}++export function getResourceSearchSpec(+ query: string,+ scopeUri: string,+): ResourceSearchSpec | null {+ const trimmed = query.trim()+ if (!trimmed) {+ return null+ }++ if (isVikingPathSearchQuery(trimmed)) {+ const normalizedQuery = normalizeVikingPathSearchQuery(trimmed)+ return {+ mode: 'path',+ query: normalizedQuery,+ rootUri: rootUriForPathSearch(normalizedQuery),+ }+ }++ return {+ mode: 'name',+ query: trimmed.toLowerCase(),+ rootUri: normalizeDirUri(scopeUri),+ }+}++export function matchesResourceSearch(+ entry: VikingFsEntry,+ spec: ResourceSearchSpec,+): boolean {+ if (!entry.uri.startsWith(spec.rootUri)) {+ return false+ }++ if (spec.mode === 'path') {+ const dirPrefix = normalizeDirUri(spec.query)+ return (+ entry.uri === spec.query ||+ entry.uri === dirPrefix ||+ entry.uri.startsWith(dirPrefix)+ )+ }++ return entry.name.toLowerCase().includes(spec.query)+}++export function filterResourceSearchEntries(+ entries: Array<VikingFsEntry>,+ spec: ResourceSearchSpec | null,+): Array<VikingFsEntry> {+ if (!spec) {+ return []+ }++ return entries.filter((entry) => matchesResourceSearch(entry, spec))+}diff --git a/web-studio/src/routes/resources/-lib/palette-mode.ts b/web-studio/src/routes/resources/-lib/palette-mode.tsnew file mode 100644index 000000000..3b377ae03--- /dev/null+++ b/web-studio/src/routes/resources/-lib/palette-mode.ts@@ -0,0 +1,71 @@+import { normalizeDirUri } from './normalize'++// Single source of truth for interpreting the palette query string.+// Nothing else may structurally parse `query` (no startsWith('/'), === '//',+// slice, split, etc.) — route every read through parsePaletteMode and every+// write through buildDirBrowseQuery. This keeps the stringly state machine+// from spreading back into the components.++export const PALETTE_ROOT_URI = 'viking://'++export const PALETTE_COMMANDS = {+ dir: '/',+ resetGlobal: '//',+} as const++export type PaletteMode =+ | { kind: 'idle' }+ | { kind: 'search'; query: string }+ | { kind: 'dirBrowse'; uri: string; filter: string }++export function parsePaletteMode(query: string, scopeUri: string): PaletteMode {+ const trimmed = query.trim()+ if (trimmed.length === 0) {+ return { kind: 'idle' }+ }+ if (trimmed.startsWith(PALETTE_COMMANDS.dir)) {+ return { kind: 'dirBrowse', ...parseDirBrowse(trimmed, scopeUri) }+ }+ return { kind: 'search', query: trimmed }+}++function parseDirBrowse(+ trimmed: string,+ scopeUri: string,+): { uri: string; filter: string } {+ const raw = trimmed.slice(PALETTE_COMMANDS.dir.length)+ const lastSlash = raw.lastIndexOf('/')+ // No inner slash ("/", "/abc"): browse the current scope, optional filter.+ if (lastSlash === -1) {+ return { uri: normalizeDirUri(scopeUri), filter: raw }+ }+ // Inner/trailing slash: the path is root-absolute so it round-trips with+ // buildDirBrowseQuery (empty path -> root, which makes root representable).+ const pathPart = raw.slice(0, lastSlash)+ const filter = raw.slice(lastSlash + 1)+ const parts = pathPart+ .split('/')+ .map((p) => p.trim())+ .filter(Boolean)+ const uri =+ parts.length > 0+ ? normalizeDirUri(`${PALETTE_ROOT_URI}${parts.join('/')}`)+ : PALETTE_ROOT_URI+ return { uri, filter }+}++export function isResetGlobalCommand(query: string): boolean {+ return query.trim() === PALETTE_COMMANDS.resetGlobal+}++// Inverse of parseDirBrowse: the query string that navigates to `uri`.+// Confines the `viking://` literal to this module; when the URI domain module+// lands (deferred), only this file changes.+export function buildDirBrowseQuery(uri: string): string {+ const normalized = normalizeDirUri(uri)+ if (normalized === PALETTE_ROOT_URI) {+ return PALETTE_COMMANDS.resetGlobal+ }+ const path = normalized.slice(PALETTE_ROOT_URI.length)+ return `${PALETTE_COMMANDS.dir}${path}`+}diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsxindex 6c5505ecb..03ef5a555 100644--- a/web-studio/src/routes/settings/route.tsx+++ b/web-studio/src/routes/settings/route.tsx@@ -63,6 +63,7 @@ import {AlertDialogTitle,} from '#/components/ui/alert-dialog'import { useAppConnection } from '#/hooks/use-app-connection'+import { copyTextToClipboard } from '#/lib/clipboard'import { cn } from '#/lib/utils'import type { ConnectionDraft } from '#/hooks/use-app-connection'@@ -116,38 +117,6 @@ function maskApiKey(value: string | undefined): string {return `${value.slice(0, 10)}...${value.slice(-6)}`}-async function copyTextToClipboard(value: string): Promise<void> {- try {- await navigator.clipboard.writeText(value)- return- } catch {- // Clipboard API is unavailable on non-secure dev URLs such as http://10.x.x.x.- }-- if (typeof document === 'undefined') {- throw new Error('Clipboard is unavailable')- }-- const textArea = document.createElement('textarea')- textArea.value = value- textArea.setAttribute('readonly', '')- textArea.style.position = 'fixed'- textArea.style.left = '-9999px'- textArea.style.top = '0'- document.body.appendChild(textArea)- textArea.focus()- textArea.select()-- try {- const copied = document.execCommand('copy')- if (!copied) {- throw new Error('Clipboard copy failed')- }- } finally {- document.body.removeChild(textArea)- }-}-function resolveKeyLabel(user: AdminUser): string {return user.apiKey ? maskApiKey(user.apiKey) : user.keyPrefix || '-'}