Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(web-studio): improve resource browser navigation, save latency, and palette L2 (#2346)

Feichuan7bcd66a45103
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index 17db480a8..db557a244 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -514,9 +514,15 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
<div className="flex items-center gap-3">
<div
aria-label={t('language.label', { ns: 'common' })}
- className="flex h-10 items-center rounded-2xl border border-border/80 bg-muted/60 p-1 text-xs shadow-xs"
+ className="relative flex h-10 items-center rounded-2xl border border-border/80 bg-muted/60 p-1 text-xs shadow-xs"
role="group"
>
+ <span
+ className={cn(
+ 'absolute h-8 min-w-10 rounded-xl bg-foreground shadow-sm transition-transform duration-200 ease-in-out',
+ currentLanguage === 'en' && 'translate-x-full',
+ )}
+ />
{LANGUAGE_OPTIONS.map((item) => {
const isActive = item.value === currentLanguage
@@ -526,8 +532,8 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
type="button"
aria-pressed={isActive}
className={cn(
- 'h-8 min-w-10 rounded-xl px-2 text-xs font-semibold text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
- isActive && 'bg-foreground text-background shadow-sm',
+ 'relative z-10 h-8 min-w-10 rounded-xl px-2 text-xs font-semibold text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
+ isActive && 'text-background',
)}
onClick={() => {
if (!isActive) {
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index 4351e7305..a6f6f2ad1 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -472,6 +472,9 @@ const en = {
directlyUploadMedia: 'Directly Upload Media',
'directlyUploadMedia.hint':
'When enabled, media files (images, audio, video) are stored as-is. When disabled, media files are processed through AI vision/audio pipeline for content extraction first.',
+ createParent: 'Auto-create Parent Folder',
+ 'createParent.hint':
+ 'When enabled, automatically creates the parent directory if it does not exist.',
reason: 'Reason',
'reason.placeholder': 'Why are you adding this resource?',
instruction: 'Instruction',
@@ -534,6 +537,7 @@ const en = {
scope: {
global: 'Search scope: Global',
current: 'Search scope: {{name}}',
+ resetToGlobal: 'Click to reset to global search',
},
scopeState: {
validatingTitle: 'Validating search scope',
@@ -581,6 +585,7 @@ const en = {
back: 'Back',
loading: 'Loading directory',
filesSection: 'Files',
+ error: 'Failed to load directory',
empty: {
title: 'Empty directory',
subtitle:
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index 0efe21050..fbbcf3709 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -464,6 +464,9 @@ const zhCN = {
directlyUploadMedia: '直接上传媒体文件',
'directlyUploadMedia.hint':
'开启时,媒体文件(图片、音频、视频)原样存储。关闭后,媒体文件会先通过 AI 视觉/音频管道提取内容再存储。',
+ createParent: '自动创建父文件夹',
+ 'createParent.hint':
+ '开启时,若目标父目录不存在则自动创建。',
reason: '添加原因',
'reason.placeholder': '为什么要添加这个资源?',
instruction: '处理指令',
@@ -524,6 +527,7 @@ const zhCN = {
scope: {
global: '搜索范围: 全局',
current: '搜索范围: {{name}}',
+ resetToGlobal: '点击重置为全局搜索',
},
scopeState: {
validatingTitle: '正在校验搜索范围',
@@ -571,6 +575,7 @@ const zhCN = {
back: '返回上一级',
loading: '正在加载目录',
filesSection: '文件',
+ error: '加载目录失败',
empty: {
title: '空目录',
subtitle: '这一层目前没有可继续展开的子目录',
diff --git a/web-studio/src/routes/resources/-components/add-resource-page.tsx b/web-studio/src/routes/resources/-components/add-resource-page.tsx
index 5891028a7..382de0777 100644
--- a/web-studio/src/routes/resources/-components/add-resource-page.tsx
+++ b/web-studio/src/routes/resources/-components/add-resource-page.tsx
@@ -79,6 +79,7 @@ export function AddResourceForm({
const [selectedFiles, setSelectedFiles] = useState<SelectedUploadFile[]>([])
const [targetUri, setTargetUri] = useState('viking://resources/')
const [strict, setStrict] = useState(false)
+ const [createParent, setCreateParent] = useState(true)
const [directlyUploadMedia, setDirectlyUploadMedia] = useState(true)
const [reason, setReason] = useState('')
const [instruction, setInstruction] = useState('')
@@ -165,6 +166,7 @@ export function AddResourceForm({
const body: Record<string, unknown> = {
parent: targetUri.trim() || undefined,
strict,
+ create_parent: createParent,
telemetry: true,
wait: false,
directly_upload_media: directlyUploadMedia,
@@ -410,6 +412,25 @@ export function AddResourceForm({
<TooltipContent>{t('strict.hint')}</TooltipContent>
</Tooltip>
</Label>
+ <Label className="flex items-center gap-2">
+ <Checkbox
+ checked={createParent}
+ onCheckedChange={(checked) =>
+ setCreateParent(Boolean(checked))
+ }
+ />
+ <span>{t('createParent')}</span>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Info className="size-3.5 text-muted-foreground" />
+ }
+ />
+ <TooltipContent>
+ {t('createParent.hint')}
+ </TooltipContent>
+ </Tooltip>
+ </Label>
<Label className="flex items-center gap-2">
<Checkbox
checked={directlyUploadMedia}
diff --git a/web-studio/src/routes/resources/-components/dir-browser.tsx b/web-studio/src/routes/resources/-components/dir-browser.tsx
index 9ca1e2ec5..bbfbde067 100644
--- a/web-studio/src/routes/resources/-components/dir-browser.tsx
+++ b/web-studio/src/routes/resources/-components/dir-browser.tsx
@@ -1,223 +1,111 @@
-import { useEffect, useMemo, useRef, useState } from 'react'
-import {
- ArrowLeft,
- ChevronRight,
- FileText,
- Folder,
- Loader2,
-} from 'lucide-react'
+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 { useTransientScrollbar } from '#/hooks/use-transient-scrollbar'
-import { normalizeDirUri, fileNameFromUri, parentUri } from '../-lib/normalize'
-import { useVikingFsList } from '../-hooks/viking-fm'
+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 {
- startUri: string
- onConfirm: (uri: string) => void
- onCancel: () => void
+ currentUri: string
+ items: VikingFsEntry[]
+ activeIndex: number
+ loading?: boolean
+ errored?: boolean
+ onCursorChange: (index: number) => void
+ onEnterDir: (uri: string) => void
+ onOpenFile: (uri: string) => void
+ onGoBack: () => void
}
-export function DirBrowser({ startUri, onConfirm, onCancel }: DirBrowserProps) {
+// 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')
- const [focusUri, setFocusUri] = useState(() => normalizeDirUri(startUri))
- const [activeCol, setActiveCol] = useState<'left' | 'right'>('left')
- const [leftIndex, setLeftIndex] = useState(0)
- const [rightIndex, setRightIndex] = useState(0)
- const [selectedFile, setSelectedFile] = useState<VikingFsEntry | null>(null)
- const containerRef = useRef<HTMLDivElement>(null)
- const leftParent = parentUri(focusUri)
- const isRootFocus = focusUri === VIKING_ROOT_URI
- const leftQuery = useVikingFsList(leftParent, {
- output: 'agent',
- showAllHidden: true,
- nodeLimit: 200,
- })
- const rightQuery = useVikingFsList(focusUri, {
- output: 'agent',
- showAllHidden: true,
- nodeLimit: 200,
- })
-
- const leftDirs = useMemo(
- () => (leftQuery.data?.entries ?? []).filter((e) => e.isDir),
- [leftQuery.data],
- )
- const rightDirs = useMemo(
- () => (rightQuery.data?.entries ?? []).filter((e) => e.isDir),
- [rightQuery.data],
+ // 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 rightFiles = useMemo(
- () => (rightQuery.data?.entries ?? []).filter((e) => !e.isDir),
- [rightQuery.data],
- )
-
- const visibleSingleColumn = isRootFocus
-
- useEffect(() => {
- if (visibleSingleColumn) return
- const idx = leftDirs.findIndex((e) => normalizeDirUri(e.uri) === focusUri)
- if (idx >= 0) setLeftIndex(idx)
- }, [visibleSingleColumn, leftDirs, focusUri])
-
- useEffect(() => {
- setRightIndex(0)
- setSelectedFile(null)
- }, [focusUri])
-
- useEffect(() => {
- if (!visibleSingleColumn) return
- setActiveCol('left')
- setLeftIndex(0)
- }, [visibleSingleColumn])
-
- useEffect(() => {
- setFocusUri(normalizeDirUri(startUri))
- setActiveCol('left')
- setLeftIndex(0)
- setRightIndex(0)
- }, [startUri])
-
- useEffect(() => {
- if (!containerRef.current) return
- const el = containerRef.current.querySelector('[data-active="true"]')
- el?.scrollIntoView({ block: 'nearest' })
- }, [leftIndex, rightIndex, activeCol])
-
- /** Called by parent (FindPalette) via onKeyDown forwarding */
- const handleKey = (key: string): boolean => {
- if (visibleSingleColumn) {
- switch (key) {
- case 'ArrowDown': {
- const next = Math.min(leftIndex + 1, rightDirs.length - 1)
- setLeftIndex(next)
- return true
- }
- case 'ArrowUp': {
- const next = Math.max(leftIndex - 1, 0)
- setLeftIndex(next)
- return true
- }
- case 'ArrowLeft':
- return true
- case 'ArrowRight': {
- const nextDir = rightDirs.at(leftIndex)
- if (nextDir) {
- setFocusUri(normalizeDirUri(nextDir.uri))
- setActiveCol('left')
- }
- return true
- }
- case 'Enter': {
- const nextDir = rightDirs.at(leftIndex)
- const selectedUri = nextDir ? normalizeDirUri(nextDir.uri) : focusUri
- onConfirm(selectedUri)
- return true
- }
- case 'Escape': {
- onCancel()
- return true
- }
- default:
- return false
- }
- }
-
- switch (key) {
- case 'ArrowDown': {
- if (activeCol === 'left') {
- const next = Math.min(leftIndex + 1, leftDirs.length - 1)
- setLeftIndex(next)
- if (leftDirs[next]) setFocusUri(normalizeDirUri(leftDirs[next].uri))
- } else {
- setRightIndex((i) => Math.min(i + 1, rightDirs.length - 1))
- }
- return true
- }
- case 'ArrowUp': {
- if (activeCol === 'left') {
- const next = Math.max(leftIndex - 1, 0)
- setLeftIndex(next)
- if (leftDirs[next]) setFocusUri(normalizeDirUri(leftDirs[next].uri))
- } else {
- setRightIndex((i) => Math.max(i - 1, 0))
- }
- return true
- }
- case 'ArrowRight': {
- if (activeCol === 'left' && rightDirs.length > 0) {
- setActiveCol('right')
- } else if (activeCol === 'right' && rightDirs[rightIndex]?.isDir) {
- setFocusUri(normalizeDirUri(rightDirs[rightIndex].uri))
- setActiveCol('left')
- }
- return true
- }
- case 'ArrowLeft': {
- if (activeCol === 'right') {
- setActiveCol('left')
- } else if (leftParent !== focusUri) {
- setFocusUri(leftParent)
- setActiveCol('left')
- }
- return true
- }
- case 'Enter': {
- const selectedUri =
- activeCol === 'left'
- ? focusUri
- : rightDirs[rightIndex]
- ? normalizeDirUri(rightDirs[rightIndex].uri)
- : focusUri
- onConfirm(selectedUri)
- return true
- }
- case 'Escape': {
- onCancel()
- return true
- }
- default:
- return false
- }
- }
-
- // Expose handleKey to parent via ref-like pattern using a stable callback
- // We use a useEffect + document listener approach but scoped to when component is mounted
- useEffect(() => {
- const handler = (e: KeyboardEvent) => {
- if (handleKey(e.key)) {
- e.preventDefault()
+ 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),
}
}
- document.addEventListener('keydown', handler)
- return () => document.removeEventListener('keydown', handler)
- })
-
- const isLoading = visibleSingleColumn
- ? rightQuery.isLoading
- : leftQuery.isLoading
- const canGoBack = focusUri !== VIKING_ROOT_URI
-
- const handleGoBack = () => {
- if (!canGoBack) return
- setFocusUri(leftParent)
- setActiveCol('left')
- setRightIndex(0)
- }
+ 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={handleGoBack}
+ 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',
@@ -230,78 +118,41 @@ export function DirBrowser({ startUri, onConfirm, onCancel }: DirBrowserProps) {
<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">
- {focusUri}
+ {currentUri}
</div>
</div>
- <div
- ref={containerRef}
- 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%)]"
- >
- {isLoading ? (
+ <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>
- ) : visibleSingleColumn ? (
- <DirColumn
- className="min-w-0 flex-1"
- label={VIKING_ROOT_URI}
- dirs={rightDirs}
- activeIndex={leftIndex}
- t={t}
- onSelect={(entry) => {
- setFocusUri(normalizeDirUri(entry.uri))
- setActiveCol('left')
- setSelectedFile(null)
- }}
- />
+ ) : errored ? (
+ <div
+ role="alert"
+ className="flex flex-1 items-center justify-center px-6 text-sm text-destructive"
+ >
+ {t('dirBrowser.error')}
+ </div>
) : (
<>
- <DirColumn
- className="w-[clamp(15rem,28vw,18rem)] shrink-0"
- label={
- leftParent === VIKING_ROOT_URI
- ? VIKING_ROOT_URI
- : fileNameFromUri(leftParent.replace(/\/$/, ''))
- }
- dirs={leftDirs}
- activeIndex={activeCol === 'left' ? leftIndex : -1}
- focusedUri={focusUri}
- t={t}
- onSelect={(entry) => {
- const uri = normalizeDirUri(entry.uri)
- setFocusUri(uri)
- setActiveCol('left')
- setSelectedFile(null)
- }}
- />
- <DirColumn
- className="min-w-0 flex-1"
- label={fileNameFromUri(focusUri.replace(/\/$/, ''))}
- dirs={rightDirs}
- files={rightFiles}
- activeIndex={activeCol === 'right' ? rightIndex : -1}
- isLoading={rightQuery.isLoading}
+ <ItemColumn
+ className="w-[clamp(15rem,35vw,22rem)] shrink-0"
+ label={fileNameFromUri(currentUri.replace(/\/$/, '')) || '/'}
+ items={items}
+ activeIndex={activeIndex}
t={t}
- onSelect={(entry) => {
- setFocusUri(normalizeDirUri(entry.uri))
- setActiveCol('right')
- setSelectedFile(null)
- }}
- selectedFileUri={selectedFile?.uri}
- onSelectFile={(entry) => {
- setSelectedFile(entry)
- setActiveCol('right')
- }}
+ onSelect={(entry, i) =>
+ entry.isDir ? onEnterDir(entry.uri) : onCursorChange(i)
+ }
/>
- {selectedFile && (
- <div className="flex h-full w-[28rem] min-w-0 flex-col overflow-hidden bg-background">
- <FilePreview
- file={selectedFile}
- onClose={() => setSelectedFile(null)}
- showCloseButton={false}
- />
- </div>
- )}
+ <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>
@@ -309,143 +160,79 @@ export function DirBrowser({ startUri, onConfirm, onCancel }: DirBrowserProps) {
)
}
-function DirColumn({
- className,
- label,
- dirs,
- files = [],
- activeIndex,
- focusedUri,
- isLoading,
- selectedFileUri,
+function DetailPane({
+ detail,
t,
- onSelect,
- onSelectFile,
+ onEnterDir,
+ onOpenFile,
}: {
- className?: string
- label: string
- dirs: VikingFsEntry[]
- files?: VikingFsEntry[]
- activeIndex: number
- focusedUri?: string
- isLoading?: boolean
- selectedFileUri?: string
- t: (key: string) => string
- onSelect: (entry: VikingFsEntry) => void
- onSelectFile?: (entry: VikingFsEntry) => void
+ detail: DetailView
+ t: TFunction<'resources'>
+ onEnterDir: (uri: string) => void
+ onOpenFile: (uri: string) => void
}) {
- const { isScrolling, onScroll } = useTransientScrollbar()
-
- return (
- <div
- className={cn(
- 'flex min-w-0 flex-col overflow-hidden border-r last:border-r-0',
- 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}
- >
- {isLoading ? (
- <div className="flex h-full items-center justify-center px-4 py-10">
- <div className="inline-flex items-center gap-2 rounded-full border bg-background/70 px-3 py-1.5 text-xs text-muted-foreground shadow-sm">
- <Loader2 className="size-3.5 animate-spin" />
- <span>{t('dirBrowser.loading')}</span>
- </div>
- </div>
- ) : dirs.length === 0 && files.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>
+ 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>
- ) : (
- <>
- {dirs.map((entry, i) => {
- const isActive = i === activeIndex
- const isFocused =
- focusedUri != null && normalizeDirUri(entry.uri) === focusedUri
-
- 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'
- : isFocused
- ? 'bg-muted/55 text-foreground'
- : 'text-foreground/80 hover:bg-muted/35',
- )}
- onClick={() => onSelect(entry)}
- >
- {isActive && (
- <span className="absolute inset-y-1 left-0 w-0.5 rounded-r bg-primary" />
- )}
- <Folder
- className={cn(
- 'size-3.5 shrink-0 transition-colors',
- isActive ? 'text-primary/80' : 'text-muted-foreground',
- )}
- />
- <span className="truncate font-medium">{entry.name}</span>
- <ChevronRight className="ml-auto size-3 shrink-0 text-muted-foreground/45 transition-transform group-hover:translate-x-0.5" />
- </button>
- )
- })}
- {files.length > 0 && (
- <div className="border-t border-border/50 bg-muted/10 px-3 py-2 text-[11px] font-medium text-muted-foreground/70">
- {t('dirBrowser.filesSection')}
- </div>
- )}
- {files.map((entry) => {
- const isSelectedFile = selectedFileUri === entry.uri
-
- return (
- <button
- key={entry.uri}
- type="button"
- className={cn(
- 'flex w-full items-center gap-2.5 border-b border-border/30 px-3 py-2 text-left text-sm last:border-b-0 transition-colors',
- isSelectedFile
- ? 'bg-blue-500/8 text-foreground'
- : 'text-muted-foreground/80 hover:bg-muted/25 hover:text-foreground/85',
- )}
- onClick={() => onSelectFile?.(entry)}
- >
- <FileText
- className={cn(
- 'size-3.5 shrink-0',
- isSelectedFile
- ? 'text-blue-600/75 dark:text-blue-300/75'
- : 'text-muted-foreground/65',
- )}
- />
- <span className="truncate">{entry.name}</span>
- </button>
- )
- })}
- </>
- )}
- </div>
- </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/file-tree.tsx b/web-studio/src/routes/resources/-components/file-tree.tsx
index ada4ca2d3..1487f635c 100644
--- a/web-studio/src/routes/resources/-components/file-tree.tsx
+++ b/web-studio/src/routes/resources/-components/file-tree.tsx
@@ -115,18 +115,26 @@ function TreeNode({
const handleToggle = useCallback(() => {
const next = new Set(expandedKeys)
- isOpen ? next.delete(entry.uri) : next.add(entry.uri)
+ if (isOpen) {
+ next.delete(entry.uri)
+ } else {
+ for (const key of next) {
+ if (key !== entry.uri && key.startsWith(entry.uri)) {
+ next.delete(key)
+ }
+ }
+ next.add(entry.uri)
+ }
onExpandedKeysChange(next)
}, [expandedKeys, isOpen, entry.uri, onExpandedKeysChange])
const handleSelect = useCallback(() => {
if (entryRef.current.isDir) {
onSelectDirectory(entryRef.current)
- handleToggle()
} else {
onSelectFile?.(entryRef.current)
}
- }, [onSelectDirectory, onSelectFile, handleToggle])
+ }, [onSelectDirectory, onSelectFile])
const handleMouseEnter = useCallback(() => {
if (entry.isDir && !isOpen && prefetch) prefetch(entry.uri)
diff --git a/web-studio/src/routes/resources/-components/find-palette.tsx b/web-studio/src/routes/resources/-components/find-palette.tsx
index 9123c8f69..816e83cfe 100644
--- a/web-studio/src/routes/resources/-components/find-palette.tsx
+++ b/web-studio/src/routes/resources/-components/find-palette.tsx
@@ -21,11 +21,19 @@ 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'
@@ -37,32 +45,8 @@ interface FindPaletteProps {
onNavigateDir: (uri: string) => void
scopeUri?: string
}
-
-const findPaletteSession = {
- inputQuery: '',
- targetUri: undefined as string | undefined,
-}
-const KEY_ENTER_LABEL = 'Enter'
const KEY_ESCAPE_LABEL = 'esc'
-function parseScopeCommand(query: string): string | null {
- const trimmed = query.trim()
- if (!trimmed.startsWith('/')) return null
-
- const rawPath = trimmed.slice(1).trim()
- if (!rawPath) return null
-
- const normalizedPath = rawPath
- .split('/')
- .map((part) => part.trim())
- .filter(Boolean)
- .join('/')
-
- if (!normalizedPath) return 'viking://'
-
- return normalizeDirUri(`viking://${normalizedPath}`)
-}
-
function displayName(uri: string): { name: string; parent: string } {
const name = fileNameFromUri(uri)
const dir = getParentUri(uri)
@@ -79,53 +63,89 @@ export function FindPalette({
scopeUri,
}: FindPaletteProps) {
const { t } = useTranslation('resources')
- const [query, setQuery] = useState(() => findPaletteSession.inputQuery)
+ const [query, setQuery] = useState('')
const [findTargetUri, setFindTargetUri] = useState(() =>
- normalizeDirUri(findPaletteSession.targetUri || scopeUri || 'viking://'),
+ normalizeDirUri(scopeUri || PALETTE_ROOT_URI),
)
- const [activeIndex, setActiveIndex] = useState(0)
const inputRef = useRef<HTMLInputElement>(null)
const resultsRef = useRef<HTMLDivElement>(null)
const composingRef = useRef(false)
- const isDirMode = query === '/'
- const scopeCommandUri = isDirMode ? null : parseScopeCommand(query)
- const trimmedQuery = query.trim()
- const hasQuery = trimmedQuery.length > 0 && !scopeCommandUri && !isDirMode
- const isRoot = findTargetUri === 'viking://'
- const searchSpec = useMemo(
- () => getResourceSearchSpec(query, findTargetUri),
+ // 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 scopeValidationQuery = useVikingFsList(
- scopeCommandUri || 'viking://',
- { output: 'agent', showAllHidden: true, nodeLimit: 1 },
- Boolean(scopeCommandUri && scopeCommandUri !== 'viking://'),
+ const idleBrowseQuery = useVikingFsList(
+ findTargetUri,
+ { output: 'agent', showAllHidden: true },
+ showIdleBrowse,
+ )
+ const idleEntries = useMemo(
+ () => (showIdleBrowse ? idleBrowseQuery.data?.entries || [] : []),
+ [showIdleBrowse, idleBrowseQuery.data?.entries],
)
- const isScopeCommandValid =
- Boolean(scopeCommandUri) &&
- (scopeCommandUri === 'viking://' || scopeValidationQuery.isSuccess)
const treeQuery = useVikingFsTree(
- searchSpec?.rootUri || 'viking://',
+ searchSpec?.rootUri || PALETTE_ROOT_URI,
{ output: 'agent', showAllHidden: true, nodeLimit: 2000, levelLimit: 100 },
- hasQuery && Boolean(searchSpec),
+ mode.kind === 'search' && Boolean(searchSpec),
)
-
const filteredEntries = useMemo(() => {
- if (!hasQuery || !treeQuery.data?.nodes) return []
+ if (mode.kind !== 'search' || !treeQuery.data?.nodes) return []
return filterResourceSearchEntries(treeQuery.data.nodes, searchSpec)
- }, [hasQuery, 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 activeEntry =
- activeIndex >= 0 ? (filteredEntries[activeIndex] ?? null) : null
-
- const statQuery = useVikingFsStat(activeEntry?.uri)
+ 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) {
+ if (statQuery.data && debouncedStatUri === activeEntry.uri) {
return {
...activeEntry,
size: statQuery.data.size,
@@ -134,112 +154,168 @@ export function FindPalette({
}
}
return activeEntry
- }, [activeEntry, statQuery.data])
+ }, [activeEntry, statQuery.data, debouncedStatUri])
+
+ const focusInput = useCallback(() => {
+ requestAnimationFrame(() => {
+ inputRef.current?.focus()
+ inputRef.current?.select()
+ })
+ }, [])
useEffect(() => {
if (open) {
- setActiveIndex(0)
- requestAnimationFrame(() => {
- inputRef.current?.focus()
- inputRef.current?.select()
- })
+ reset()
+ focusInput()
}
- }, [open])
+ }, [open, reset, focusInput])
useEffect(() => {
- setActiveIndex(0)
- }, [filteredEntries])
+ if (!open) return
- useEffect(() => {
- findPaletteSession.inputQuery = query
- }, [query])
+ 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(() => {
- findPaletteSession.targetUri = findTargetUri
- }, [findTargetUri])
+ 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
- if (isDirMode) {
- if (e.key === 'Escape') {
- e.preventDefault()
- onClose()
- }
+
+ // `//` + 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 (scopeCommandUri) {
+
+ if (mode.kind === 'dirBrowse') {
switch (e.key) {
- case 'Enter':
+ case 'ArrowDown':
e.preventDefault()
- if (!isScopeCommandValid) return
- setFindTargetUri(scopeCommandUri)
- setActiveIndex(0)
- setQuery('')
+ moveDown()
return
- case 'Escape':
+ case 'ArrowUp':
e.preventDefault()
- onClose()
+ 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
- }
- }
- if (!hasQuery || filteredEntries.length === 0) {
- if (e.key === 'Escape') {
- e.preventDefault()
- onClose()
}
return
}
+
+ // search / idle list navigation
+ if (visibleEntries.length === 0) return
switch (e.key) {
- case 'ArrowDown': {
+ case 'ArrowDown':
e.preventDefault()
- setActiveIndex((i) => Math.min(i + 1, filteredEntries.length - 1))
- break
- }
- case 'ArrowUp': {
+ moveDown()
+ return
+ case 'ArrowUp':
e.preventDefault()
- setActiveIndex((i) => Math.max(i - 1, 0))
- break
- }
+ moveUp()
+ return
case 'Enter':
e.preventDefault()
- if (activeEntry) {
+ if (!activeEntry) return
+ if (mode.kind === 'idle' && activeEntry.isDir) {
+ confirmDirScope(activeEntry.uri)
+ } else {
onNavigate(activeEntry.uri)
onClose()
}
- break
- case 'Escape':
- e.preventDefault()
- onClose()
- break
+ return
}
},
[
query,
- hasQuery,
- filteredEntries,
+ mode,
activeEntry,
+ visibleEntries.length,
+ dirListQuery.isSuccess,
+ moveUp,
+ moveDown,
+ enterDir,
+ goToParent,
+ confirmDirScope,
onNavigate,
onClose,
- isDirMode,
- scopeCommandUri,
- isScopeCommandValid,
],
)
if (!open) return null
- const showPreview = hasQuery && activeEntry !== null && !activeEntry.isDir
+ 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]"
@@ -281,10 +357,7 @@ export function FindPalette({
<button
type="button"
className="rounded-md p-1 text-muted-foreground/70 transition-colors hover:text-foreground"
- onClick={() => {
- setActiveIndex(0)
- setQuery('')
- }}
+ onClick={() => setQuery('')}
>
<X className="size-3.5" />
</button>
@@ -293,30 +366,38 @@ export function FindPalette({
{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}>
- {isDirMode ? (
+ {mode.kind === 'dirBrowse' ? (
<DirBrowser
- startUri={findTargetUri}
- onConfirm={(uri) => {
- setFindTargetUri(normalizeDirUri(uri))
- setActiveIndex(0)
- setQuery('')
- }}
- onCancel={() => {
- setActiveIndex(0)
- setQuery('')
+ currentUri={mode.uri}
+ items={dirItems}
+ activeIndex={activeIndex}
+ loading={dirListQuery.isLoading}
+ errored={dirListQuery.isError}
+ onCursorChange={setIndex}
+ onEnterDir={enterDir}
+ onOpenFile={(uri) => {
+ onNavigate(uri)
+ onClose()
}}
+ onGoBack={goToParent}
/>
) : (
<>
@@ -327,83 +408,56 @@ export function FindPalette({
showPreview && 'border-r',
)}
>
- {scopeCommandUri ? (
- <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">
- <FolderOpen
- className={cn(
- 'size-6',
- isScopeCommandValid
- ? 'text-blue-500/50'
- : 'text-destructive/60',
- )}
+ {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}
+ onSelect={(entry) => {
+ if (entry.isDir) {
+ confirmDirScope(entry.uri)
+ } else {
+ onNavigate(entry.uri)
+ onClose()
+ }
+ }}
+ onOpenDir={(entry) => {
+ onNavigateDir(getParentUri(entry.uri))
+ onClose()
+ }}
/>
- {scopeValidationQuery.isLoading ? (
- <div>
- <p className="text-sm font-medium text-foreground/80">
- {t('searchPalette.scopeState.validatingTitle')}
- </p>
- <p className="mt-1 text-xs text-muted-foreground/75">
- {t('searchPalette.scopeState.validatingPrefix')}{' '}
- <span className="font-medium text-foreground/80">
- {scopeCommandUri}
- </span>{' '}
- {t('searchPalette.scopeState.validatingSuffix')}
- </p>
- </div>
- ) : isScopeCommandValid ? (
+ ) : (
+ <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 font-medium text-foreground/80">
- {t('searchPalette.scopeState.switchTitle')}
+ <p className="text-sm text-muted-foreground/70">
+ {t('searchPalette.empty.title')}
</p>
- <p className="mt-1 text-xs text-muted-foreground/75">
- {t('searchPalette.scopeState.switchPrefix')}{' '}
+ <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">
- {KEY_ENTER_LABEL}
+ /
</kbd>{' '}
- {t('searchPalette.scopeState.switchMiddle')}{' '}
- <span className="font-medium text-foreground/80">
- {scopeCommandUri}
- </span>
- </p>
- </div>
- ) : (
- <div>
- <p className="text-sm font-medium text-destructive">
- {t('searchPalette.scopeState.invalidTitle')}
+ {t('searchPalette.browseDirHint.after')}
</p>
- <p className="mt-1 text-xs text-muted-foreground/75">
- {t('searchPalette.scopeState.invalidPrefix')}{' '}
- <span className="font-medium text-foreground/80">
- {scopeCommandUri}
- </span>{' '}
- {t('searchPalette.scopeState.invalidSuffix')}
+ <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>
- ) : !hasQuery ? (
- <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" />
@@ -412,7 +466,10 @@ export function FindPalette({
</p>
</div>
) : treeQuery.error ? (
- <div className="px-4 py-6 text-center text-xs text-destructive">
+ <div
+ role="alert"
+ className="px-4 py-6 text-center text-xs text-destructive"
+ >
{t('searchPalette.error')}
</div>
) : !hasResults ? (
@@ -447,7 +504,7 @@ export function FindPalette({
<div className="animate-palette-preview flex h-full w-[32rem] flex-col overflow-hidden">
<FilePreview
file={previewEntry}
- onClose={() => setActiveIndex(-1)}
+ onClose={() => setIndex(-1)}
showCloseButton={false}
/>
</div>
@@ -456,8 +513,7 @@ export function FindPalette({
)}
</div>
- {/* Footer */}
- {isDirMode ? (
+ {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">
@@ -517,7 +573,6 @@ export function FindPalette({
</div>
)
}
-
function DirResultList({
className,
items,
@@ -607,3 +662,4 @@ function DirResultList({
</div>
)
}
+
diff --git a/web-studio/src/routes/resources/-components/item-column.tsx b/web-studio/src/routes/resources/-components/item-column.tsx
new file mode 100644
index 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/-components/viking-file-manager.tsx b/web-studio/src/routes/resources/-components/viking-file-manager.tsx
index 8ac9e59fc..8ac0315d3 100644
--- a/web-studio/src/routes/resources/-components/viking-file-manager.tsx
+++ b/web-studio/src/routes/resources/-components/viking-file-manager.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react'
import {
+ ArrowLeft,
ChevronRight,
FolderOpen,
RefreshCcw,
@@ -109,13 +110,7 @@ export function VikingFileManager({
useEffect(() => {
const normalized = normalizeDirUri(initialUri || 'viking://')
setCurrentUri(normalized)
- setExpandedKeys((prev) => {
- const next = new Set(prev)
- for (const ancestor of getAncestorUris(normalized)) {
- next.add(ancestor)
- }
- return next
- })
+ setExpandedKeys(new Set(getAncestorUris(normalized)))
}, [initialUri])
useEffect(() => {
@@ -150,6 +145,7 @@ export function VikingFileManager({
const normalized = normalizeDirUri(uri)
setCurrentUri(normalized)
setSelectedFile(null)
+ setExpandedKeys(new Set(getAncestorUris(normalized)))
}, [])
const handleOpenDirectory = useCallback((entry: VikingFsEntry) => {
@@ -160,6 +156,7 @@ export function VikingFileManager({
uri: normalized,
isDir: true,
})
+ setExpandedKeys(new Set(getAncestorUris(normalized)))
}, [])
const handleNavigateFromSearch = useCallback((uri: string) => {
@@ -167,9 +164,11 @@ export function VikingFileManager({
const normalized = normalizeDirUri(uri)
setCurrentUri(normalized)
setSelectedFile(null)
+ setExpandedKeys(new Set(getAncestorUris(normalized)))
} else {
const dirUri = parentUri(uri)
- setCurrentUri(normalizeDirUri(dirUri))
+ const normalizedDir = normalizeDirUri(dirUri)
+ setCurrentUri(normalizedDir)
const name = uri.split('/').pop() || uri
setSelectedFile({
uri: normalizeFileUri(uri),
@@ -182,6 +181,7 @@ export function VikingFileManager({
abstract: '',
overview: '',
})
+ setExpandedKeys(new Set(getAncestorUris(normalizedDir)))
}
}, [])
@@ -400,8 +400,19 @@ export function VikingFileManager({
}
}, [])
+ const isRoot = currentUri === 'viking://'
+
const toolbar = (
<div className="flex h-10 items-center gap-1 border-b px-3">
+ <button
+ type="button"
+ disabled={isRoot}
+ aria-label={t('dirBrowser.back')}
+ className="inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40"
+ onClick={() => updateUri(parentUri(currentUri))}
+ >
+ <ArrowLeft className="size-3.5" />
+ </button>
<nav className="flex flex-1 items-center gap-0.5 overflow-x-auto whitespace-nowrap text-xs text-muted-foreground md:text-sm">
{breadcrumbs.map((crumb, i) => (
<span key={crumb.uri} className="flex shrink-0 items-center gap-0.5">
diff --git a/web-studio/src/routes/resources/-hooks/use-list-navigation.ts b/web-studio/src/routes/resources/-hooks/use-list-navigation.ts
new file mode 100644
index 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/-hooks/viking-fm.ts b/web-studio/src/routes/resources/-hooks/viking-fm.ts
index 0834ae975..62bc5d3c2 100644
--- a/web-studio/src/routes/resources/-hooks/viking-fm.ts
+++ b/web-studio/src/routes/resources/-hooks/viking-fm.ts
@@ -181,7 +181,7 @@ export function useInvalidateVikingFs() {
}
}
-function useDebouncedValue<T>(value: T, delay: number): T {
+export function useDebouncedValue<T>(value: T, delay: number): T {
const [debounced, setDebounced] = useState(value)
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay)
diff --git a/web-studio/src/routes/resources/-lib/api.ts b/web-studio/src/routes/resources/-lib/api.ts
index a4937ca34..58e2663bb 100644
--- a/web-studio/src/routes/resources/-lib/api.ts
+++ b/web-studio/src/routes/resources/-lib/api.ts
@@ -213,7 +213,7 @@ export async function saveFileContent(
uri,
content,
mode: 'replace',
- wait: true,
+ wait: false,
},
}),
)
diff --git a/web-studio/src/routes/resources/-lib/palette-mode.ts b/web-studio/src/routes/resources/-lib/palette-mode.ts
new file mode 100644
index 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}`
+}