Skip to content

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

feat(web-studio): enhance retrieval workflows and result inspection (#3576)

yufeng291e9c580ffb
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index b9434af84..f317457e2 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -98,7 +98,7 @@ const en = {
models: 'VLM, embedding, and rerank model services.',
filesystem: 'OpenViking filesystem and mount services.',
lock: 'Transaction locks and concurrency control.',
- retrieval: 'Context retrieval and recall service.',
+ retrieval: 'Context retrieval service.',
},
},
offline: {
@@ -912,10 +912,50 @@ const en = {
sessionId: 'Session ID',
sessionPlaceholder: 'session_id (optional)',
},
+ advanced: {
+ title: 'More filters',
+ contextTypes: 'Context types',
+ levels: 'Content levels',
+ scoreThreshold: 'Minimum relevance',
+ tags: 'Search tags',
+ tagsPlaceholder: 'For example env=prod, team=search',
+ tagsInvalid: 'Tags must use key=value format, separated by commas',
+ timeRange: 'Time range',
+ since: 'Start, e.g. 7d',
+ until: 'End, e.g. 2026-07-27',
+ anyTime: 'Any time',
+ quickRange: 'Quick range',
+ last24Hours: 'Last 24 hours',
+ last7Days: 'Last 7 days',
+ last30Days: 'Last 30 days',
+ customRange: 'Custom dates',
+ startDate: 'Start date',
+ endDate: 'End date',
+ clearTimeRange: 'Clear time range',
+ timeField: 'Time field',
+ updatedAt: 'Updated time',
+ createdAt: 'Created time',
+ provenance: 'Include retrieval provenance',
+ reset: 'Reset filters',
+ },
+ detail: {
+ score: 'Score',
+ level: 'Level',
+ openPlayground: 'Open in Playground',
+ uri: 'URI',
+ summary: 'Summary',
+ noSummary: 'No summary available',
+ matchReason: 'Match reason',
+ },
results: {
title: 'Search Results',
topN: 'Search Results (Top{{count}})',
line: 'Line {{line}}',
+ lineLabel: 'Line',
+ score: 'Score',
+ uri: 'URI',
+ description: 'Description',
+ provenance: 'Retrieval provenance ({{count}})',
},
types: {
resource: 'Resources',
@@ -940,7 +980,15 @@ const en = {
description: 'Upload your first resource to get started.',
upload: 'Upload File',
},
- error: 'Search failed',
+ error: {
+ title: 'Search failed',
+ fallback: 'The request could not be completed. Please try again.',
+ network:
+ 'The OpenViking service could not be reached. Check the connection URL, service status, or CORS configuration.',
+ code: 'Error code',
+ status: 'HTTP status',
+ requestId: 'Request ID',
+ },
noResults: {
title: 'No matching content found',
subtitle: 'Try another keyword or adjust the path scope',
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index c3ab0daa8..88b4f54c4 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -98,7 +98,7 @@ const zhCN = {
models: 'VLM、Embedding 和 Rerank 模型服务。',
filesystem: 'OpenViking 文件系统与挂载点。',
lock: '事务锁与并发控制服务。',
- retrieval: '上下文检索与召回服务。',
+ retrieval: '上下文检索服务。',
},
},
offline: {
@@ -882,10 +882,50 @@ const zhCN = {
sessionId: 'Session ID',
sessionPlaceholder: 'session_id(可选)',
},
+ advanced: {
+ title: '更多筛选',
+ contextTypes: '上下文类型',
+ levels: '内容层级',
+ scoreThreshold: '最低相关度',
+ tags: '检索标签',
+ tagsPlaceholder: '例如 env=prod, team=search',
+ tagsInvalid: '标签必须使用 key=value 格式,多个标签用逗号分隔',
+ timeRange: '时间范围',
+ since: '开始时间,如 7d',
+ until: '结束时间,如 2026-07-27',
+ anyTime: '不限时间',
+ quickRange: '快捷范围',
+ last24Hours: '近 24 小时',
+ last7Days: '近 7 天',
+ last30Days: '近 30 天',
+ customRange: '自定义日期',
+ startDate: '开始日期',
+ endDate: '结束日期',
+ clearTimeRange: '清除时间范围',
+ timeField: '时间字段',
+ updatedAt: '更新时间',
+ createdAt: '创建时间',
+ provenance: '返回检索过程',
+ reset: '重置筛选',
+ },
+ detail: {
+ score: '相关度',
+ level: '层级',
+ openPlayground: '在 Playground 打开',
+ uri: 'URI',
+ summary: '摘要',
+ noSummary: '暂无可展示的摘要',
+ matchReason: '匹配原因',
+ },
results: {
title: '检索结果',
topN: '检索结果(Top{{count}})',
line: '第 {{line}} 行',
+ lineLabel: '行号',
+ score: '相关度',
+ uri: 'URI',
+ description: '描述',
+ provenance: '检索过程({{count}})',
},
types: {
resource: 'Resources',
@@ -910,7 +950,15 @@ const zhCN = {
description: '先上传您的第一份资源吧~',
upload: '上传文件',
},
- error: '检索出错',
+ error: {
+ title: '检索失败',
+ fallback: '请求未能完成,请稍后重试。',
+ network:
+ '请求未能到达 OpenViking 服务,请检查连接地址、服务状态或跨域配置。',
+ code: '错误码',
+ status: 'HTTP 状态',
+ requestId: 'Request ID',
+ },
noResults: {
title: '没有找到匹配的内容',
subtitle: '试试换个关键词或调整路径范围',
diff --git a/web-studio/src/lib/retrieval.test.ts b/web-studio/src/lib/retrieval.test.ts
index 8002e4e32..a019fa6d4 100644
--- a/web-studio/src/lib/retrieval.test.ts
+++ b/web-studio/src/lib/retrieval.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { fetchFindAllTypes, fetchGlob, fetchGrep } from './retrieval'
+import { fetchFind, fetchFindAllTypes, fetchGlob, fetchGrep } from './retrieval'
const { postSearchFindMock, postSearchGlobMock, postSearchGrepMock } =
vi.hoisted(() => ({
@@ -38,6 +38,36 @@ describe('pattern retrieval', () => {
postSearchGrepMock.mockReset()
})
+ it('passes advanced semantic filters through one find request', async () => {
+ postSearchFindMock.mockReturnValue(response({ total: 0 }))
+
+ await fetchFind('authentication', {
+ contextTypes: ['memory', 'resource'],
+ includeProvenance: true,
+ levels: [0, 1],
+ limit: 20,
+ scoreThreshold: 0.25,
+ since: '7d',
+ tags: ['env=prod', 'team=search'],
+ timeField: 'created_at',
+ until: '2026-07-27',
+ })
+
+ expect(postSearchFindMock).toHaveBeenCalledWith({
+ body: expect.objectContaining({
+ context_type: ['memory', 'resource'],
+ include_provenance: true,
+ level: [0, 1],
+ limit: 20,
+ score_threshold: 0.25,
+ since: '7d',
+ tags: ['env=prod', 'team=search'],
+ time_field: 'created_at',
+ until: '2026-07-27',
+ }),
+ })
+ })
+
it('uses one find request for the server-grouped result types', async () => {
postSearchFindMock.mockReturnValue(
response({
diff --git a/web-studio/src/lib/retrieval.ts b/web-studio/src/lib/retrieval.ts
index 677051ebb..ab9db8822 100644
--- a/web-studio/src/lib/retrieval.ts
+++ b/web-studio/src/lib/retrieval.ts
@@ -48,15 +48,23 @@ export interface GroupedFindResult {
export interface VikingApiError {
code: string
message: string
+ requestId?: string
statusCode?: number
details?: unknown
}
export interface FetchFindOptions {
+ contextTypes?: FindContextType[]
+ includeProvenance?: boolean
+ levels?: number[]
targetUri?: string
limit?: number
scoreThreshold?: number
filter?: Record<string, unknown>
+ since?: string
+ tags?: string[]
+ timeField?: 'created_at' | 'updated_at'
+ until?: string
}
export interface FetchSearchOptions extends FetchFindOptions {
@@ -82,6 +90,7 @@ function toVikingApiError(error: unknown): VikingApiError {
code: normalized.code,
details: normalized.details,
message: normalized.message,
+ requestId: normalized.requestId,
statusCode: normalized.statusCode,
}
}
@@ -199,10 +208,24 @@ export async function fetchFind(
postSearchFind({
body: {
filter: options.filter,
+ context_type:
+ options.contextTypes && options.contextTypes.length > 0
+ ? options.contextTypes
+ : undefined,
+ include_provenance: options.includeProvenance,
+ level:
+ options.levels && options.levels.length > 0
+ ? options.levels
+ : undefined,
limit: options.limit ?? 10,
query,
score_threshold: options.scoreThreshold,
+ since: options.since,
+ tags:
+ options.tags && options.tags.length > 0 ? options.tags : undefined,
target_uri: options.targetUri,
+ time_field: options.timeField,
+ until: options.until,
},
}),
)
@@ -222,11 +245,25 @@ export async function fetchSearch(
postSearchSearch({
body: {
filter: options.filter,
+ context_type:
+ options.contextTypes && options.contextTypes.length > 0
+ ? options.contextTypes
+ : undefined,
+ include_provenance: options.includeProvenance,
+ level:
+ options.levels && options.levels.length > 0
+ ? options.levels
+ : undefined,
limit: options.limit ?? 10,
query,
score_threshold: options.scoreThreshold,
+ since: options.since,
session_id: options.sessionId,
+ tags:
+ options.tags && options.tags.length > 0 ? options.tags : undefined,
target_uri: options.targetUri,
+ time_field: options.timeField,
+ until: options.until,
},
}),
)
diff --git a/web-studio/src/routes/request-logs/-components/metric-card.tsx b/web-studio/src/routes/request-logs/-components/metric-card.tsx
index 1ace2a76d..f907d6e91 100644
--- a/web-studio/src/routes/request-logs/-components/metric-card.tsx
+++ b/web-studio/src/routes/request-logs/-components/metric-card.tsx
@@ -10,8 +10,8 @@ type MetricCardProps = {
export function MetricCard({ icon, label, value }: MetricCardProps) {
return (
- <Card className="bg-card/70">
- <CardContent className="flex items-center justify-between gap-4 p-4">
+ <Card className="bg-card/70 py-0">
+ <CardContent className="flex min-h-20 items-center justify-between gap-4 px-5 py-3">
<div>
<p className="text-sm text-muted-foreground">{label}</p>
<p className="mt-1 text-2xl font-semibold tabular-nums">{value}</p>
diff --git a/web-studio/src/routes/retrieval/-components/date-range-picker.test.tsx b/web-studio/src/routes/retrieval/-components/date-range-picker.test.tsx
new file mode 100644
index 000000000..28842d127
--- /dev/null
+++ b/web-studio/src/routes/retrieval/-components/date-range-picker.test.tsx
@@ -0,0 +1,65 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import type { TFunction } from 'i18next'
+import { useState } from 'react'
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { DateRangePicker } from './date-range-picker'
+
+const labels: Record<string, string> = {
+ 'advanced.anyTime': 'Any time',
+ 'advanced.clearTimeRange': 'Clear',
+ 'advanced.customRange': 'Custom dates',
+ 'advanced.endDate': 'End date',
+ 'advanced.last24Hours': 'Last 24 hours',
+ 'advanced.last30Days': 'Last 30 days',
+ 'advanced.last7Days': 'Last 7 days',
+ 'advanced.quickRange': 'Quick range',
+ 'advanced.startDate': 'Start date',
+ 'advanced.timeRange': 'Time range',
+}
+
+const t = ((key: string) => labels[key] ?? key) as TFunction<'retrieval'>
+
+afterEach(cleanup)
+
+function DateRangePickerHarness() {
+ const [range, setRange] = useState<{
+ since?: string
+ until?: string
+ }>({})
+
+ return (
+ <DateRangePicker
+ onChange={setRange}
+ since={range.since}
+ t={t}
+ until={range.until}
+ />
+ )
+}
+
+describe('DateRangePicker', () => {
+ it('supports quick and custom date ranges', () => {
+ render(<DateRangePickerHarness />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Any time' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Last 7 days' }))
+ expect(screen.getByRole('button', { name: 'Last 7 days' })).toBeDefined()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Last 7 days' }))
+ fireEvent.change(screen.getByLabelText('Start date'), {
+ target: { value: '2026-07-01' },
+ })
+ fireEvent.change(screen.getByLabelText('End date'), {
+ target: { value: '2026-07-27' },
+ })
+
+ expect(
+ screen.getByRole('button', {
+ name: '2026-07-01 → 2026-07-27',
+ }),
+ ).toBeDefined()
+ })
+})
diff --git a/web-studio/src/routes/retrieval/-components/date-range-picker.tsx b/web-studio/src/routes/retrieval/-components/date-range-picker.tsx
new file mode 100644
index 000000000..001b4fdb8
--- /dev/null
+++ b/web-studio/src/routes/retrieval/-components/date-range-picker.tsx
@@ -0,0 +1,135 @@
+import { CalendarRange, ChevronDown } from 'lucide-react'
+import type { TFunction } from 'i18next'
+import { useState } from 'react'
+
+import { Button } from '#/components/ui/button'
+import { ButtonGroup } from '#/components/ui/button-group'
+import { Field, FieldGroup, FieldLabel } from '#/components/ui/field'
+import { Input } from '#/components/ui/input'
+import {
+ Popover,
+ PopoverContent,
+ PopoverHeader,
+ PopoverTitle,
+ PopoverTrigger,
+} from '#/components/ui/popover'
+
+const QUICK_RANGES = [
+ { labelKey: 'advanced.last24Hours', value: '24h' },
+ { labelKey: 'advanced.last7Days', value: '7d' },
+ { labelKey: 'advanced.last30Days', value: '30d' },
+] as const
+
+const DATE_VALUE_PATTERN = /^\d{4}-\d{2}-\d{2}$/
+
+export function DateRangePicker({
+ onChange,
+ since,
+ t,
+ until,
+}: {
+ onChange: (range: { since?: string; until?: string }) => void
+ since?: string
+ t: TFunction<'retrieval'>
+ until?: string
+}) {
+ const [open, setOpen] = useState(false)
+ const quickRange = QUICK_RANGES.find(({ value }) => value === since && !until)
+ const rangeLabel = quickRange
+ ? t(quickRange.labelKey)
+ : since || until
+ ? `${since || '…'} → ${until || '…'}`
+ : t('advanced.anyTime')
+
+ return (
+ <Popover onOpenChange={setOpen} open={open}>
+ <PopoverTrigger className="flex h-8 w-full items-center justify-between gap-2 rounded-md border bg-background px-2.5 text-left text-xs font-normal shadow-xs outline-none transition-colors hover:bg-muted focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50">
+ <span className="flex min-w-0 items-center gap-2">
+ <CalendarRange className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{rangeLabel}</span>
+ </span>
+ <ChevronDown className="size-3.5 shrink-0 text-muted-foreground" />
+ </PopoverTrigger>
+
+ <PopoverContent align="start" className="w-80">
+ <PopoverHeader>
+ <PopoverTitle>{t('advanced.timeRange')}</PopoverTitle>
+ </PopoverHeader>
+
+ <FieldGroup className="gap-4">
+ <Field className="gap-2">
+ <FieldLabel className="text-xs text-muted-foreground">
+ {t('advanced.quickRange')}
+ </FieldLabel>
+ <ButtonGroup className="w-full">
+ {QUICK_RANGES.map(({ labelKey, value }) => (
+ <Button
+ className="flex-1"
+ key={value}
+ onClick={() => {
+ onChange({ since: value, until: undefined })
+ setOpen(false)
+ }}
+ size="sm"
+ type="button"
+ variant={
+ quickRange?.value === value ? 'secondary' : 'outline'
+ }
+ >
+ {t(labelKey)}
+ </Button>
+ ))}
+ </ButtonGroup>
+ </Field>
+
+ <Field className="gap-2">
+ <FieldLabel className="text-xs text-muted-foreground">
+ {t('advanced.customRange')}
+ </FieldLabel>
+ <div className="grid grid-cols-2 gap-2">
+ <Input
+ aria-label={t('advanced.startDate')}
+ className="h-8 text-xs"
+ onChange={(event) =>
+ onChange({
+ since: event.target.value || undefined,
+ until,
+ })
+ }
+ type="date"
+ value={since && DATE_VALUE_PATTERN.test(since) ? since : ''}
+ />
+ <Input
+ aria-label={t('advanced.endDate')}
+ className="h-8 text-xs"
+ onChange={(event) =>
+ onChange({
+ since,
+ until: event.target.value || undefined,
+ })
+ }
+ type="date"
+ value={until && DATE_VALUE_PATTERN.test(until) ? until : ''}
+ />
+ </div>
+ </Field>
+ </FieldGroup>
+
+ {since || until ? (
+ <Button
+ className="self-end"
+ onClick={() => {
+ onChange({ since: undefined, until: undefined })
+ setOpen(false)
+ }}
+ size="sm"
+ type="button"
+ variant="ghost"
+ >
+ {t('advanced.clearTimeRange')}
+ </Button>
+ ) : null}
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx b/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx
index 02995483d..9e08135a6 100644
--- a/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx
+++ b/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx
@@ -1,8 +1,16 @@
-import { FolderOpen } from 'lucide-react'
+import {
+ ChevronDown,
+ FolderOpen,
+ RotateCcw,
+ SlidersHorizontal,
+} from 'lucide-react'
+import { useMemo, useState } from 'react'
import type { TFunction } from 'i18next'
+import { Button } from '#/components/ui/button'
import { Checkbox } from '#/components/ui/checkbox'
import { Input } from '#/components/ui/input'
+import { Label } from '#/components/ui/label'
import {
Select,
SelectContent,
@@ -10,131 +18,403 @@ import {
SelectTrigger,
SelectValue,
} from '#/components/ui/select'
+import { Switch } from '#/components/ui/switch'
+import { cn } from '#/lib/utils'
+import type { FindContextType } from '#/lib/retrieval'
import {
RESULT_COUNT_OPTIONS,
RETRIEVAL_MODES,
RETRIEVAL_SCOPES,
} from '../-constants/retrieval'
-import type { RetrievalMode, RetrievalScope } from '../-types/retrieval'
+import type {
+ RetrievalMode,
+ RetrievalRequestOptions,
+} from '../-types/retrieval'
+import { DateRangePicker } from './date-range-picker'
+import { TagFilterInput } from './tag-filter-input'
+
+const CONTEXT_TYPES: FindContextType[] = ['resource', 'memory', 'skill']
+const LEVELS = [0, 1, 2] as const
export function RetrievalControls({
- customPathInput,
- ignoreCase,
mode,
- onCustomPathInputChange,
- onIgnoreCaseChange,
onModeChange,
- onResultCountChange,
- onScopeChange,
- onSessionIdInputChange,
- resultCount,
- scope,
- sessionIdInput,
+ onOptionsChange,
+ options,
t,
- targetUri,
}: {
- customPathInput: string
- ignoreCase: boolean
mode: RetrievalMode
- onCustomPathInputChange: (value: string) => void
- onIgnoreCaseChange: (value: boolean) => void
onModeChange: (value: RetrievalMode) => void
- onResultCountChange: (value: number) => void
- onScopeChange: (value: RetrievalScope) => void
- onSessionIdInputChange: (value: string) => void
- resultCount: number
- scope: RetrievalScope
- sessionIdInput: string
+ onOptionsChange: (patch: Partial<RetrievalRequestOptions>) => void
+ options: RetrievalRequestOptions
t: TFunction<'retrieval'>
- targetUri?: string
}) {
+ const [advancedOpen, setAdvancedOpen] = useState(false)
+ const semanticMode = mode === 'find' || mode === 'search'
+ const advancedCount = useMemo(
+ () =>
+ [
+ options.contextTypes.length > 0,
+ options.tags.length > 0,
+ options.scoreThreshold !== undefined,
+ options.levels.length > 0,
+ Boolean(options.since || options.until),
+ options.includeProvenance,
+ ].filter(Boolean).length,
+ [
+ options.contextTypes.length,
+ options.includeProvenance,
+ options.levels.length,
+ options.scoreThreshold,
+ options.since,
+ options.tags.length,
+ options.until,
+ ],
+ )
+
+ const toggleContextType = (type: FindContextType, checked: boolean) => {
+ onOptionsChange({
+ contextTypes: checked
+ ? [...options.contextTypes, type]
+ : options.contextTypes.filter((item) => item !== type),
+ })
+ }
+
+ const toggleLevel = (level: number, checked: boolean) => {
+ onOptionsChange({
+ levels: checked
+ ? [...options.levels, level].toSorted()
+ : options.levels.filter((item) => item !== level),
+ })
+ }
+
+ const resetAdvanced = () => {
+ onOptionsChange({
+ contextTypes: [],
+ includeProvenance: false,
+ levels: [],
+ scoreThreshold: undefined,
+ since: undefined,
+ tags: [],
+ timeField: 'updated_at',
+ until: undefined,
+ })
+ }
+
return (
- <div className="flex flex-wrap items-center gap-2">
- <Select
- value={mode}
- onValueChange={(value) => onModeChange(value as RetrievalMode)}
+ <div className="space-y-3">
+ <div
+ aria-label={t('controls.function')}
+ className="inline-flex flex-wrap gap-1 rounded-lg border bg-muted/30 p-1"
+ role="tablist"
>
- <SelectTrigger size="sm" aria-label={t('controls.function')}>
- <SelectValue>{t(`controls.modes.${mode}`)}</SelectValue>
- </SelectTrigger>
- <SelectContent>
- {RETRIEVAL_MODES.map((item) => (
- <SelectItem key={item} value={item}>
- {t(`controls.modes.${item}`)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- <Select
- value={String(resultCount)}
- onValueChange={(value) => onResultCountChange(Number(value))}
- >
- <SelectTrigger size="sm" aria-label={t('controls.resultCount')}>
- <SelectValue>
- {t('controls.resultCount')} {resultCount}
- </SelectValue>
- </SelectTrigger>
- <SelectContent>
- {RESULT_COUNT_OPTIONS.map((option) => (
- <SelectItem key={option} value={String(option)}>
- {option}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- <Select
- value={scope}
- onValueChange={(value) => onScopeChange(value as RetrievalScope)}
- >
- <SelectTrigger size="sm" aria-label={t('controls.scope')}>
- <SelectValue>{t(`controls.scopes.${scope}.label`)}</SelectValue>
- </SelectTrigger>
- <SelectContent>
- {RETRIEVAL_SCOPES.map((item) => (
- <SelectItem key={item} value={item}>
- {t(`controls.scopes.${item}.label`)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- {scope === 'custom' && (
- <Input
- value={customPathInput}
- onChange={(event) => onCustomPathInputChange(event.target.value)}
- placeholder={t('controls.customScopePlaceholder')}
- aria-label={t('controls.customScope')}
- className="h-8 w-64 font-mono text-sm"
- />
- )}
+ {RETRIEVAL_MODES.map((item) => (
+ <Button
+ aria-selected={mode === item}
+ className="h-7 px-3 font-mono text-xs"
+ key={item}
+ onClick={() => onModeChange(item)}
+ role="tab"
+ size="sm"
+ variant={mode === item ? 'secondary' : 'ghost'}
+ >
+ {t(`controls.modes.${item}`)}
+ </Button>
+ ))}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Select
+ value={String(options.resultCount)}
+ onValueChange={(value) =>
+ onOptionsChange({ resultCount: Number(value) })
+ }
+ >
+ <SelectTrigger size="sm" aria-label={t('controls.resultCount')}>
+ <SelectValue>
+ {t('controls.resultCount')} {options.resultCount}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {RESULT_COUNT_OPTIONS.map((option) => (
+ <SelectItem key={option} value={String(option)}>
+ {option}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
- <div className="inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border bg-muted/30 px-2.5 text-xs text-muted-foreground">
- <FolderOpen className="size-3.5 shrink-0" />
- <span className="shrink-0">{t('controls.effectiveScope')}</span>
- <span className="max-w-64 truncate font-mono text-foreground">
- {targetUri ?? t('controls.allContexts')}
- </span>
+ <Select
+ value={options.scope}
+ onValueChange={(value) =>
+ onOptionsChange({
+ scope: value as RetrievalRequestOptions['scope'],
+ })
+ }
+ >
+ <SelectTrigger size="sm" aria-label={t('controls.scope')}>
+ <SelectValue>
+ {t(`controls.scopes.${options.scope}.label`)}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {RETRIEVAL_SCOPES.map((item) => (
+ <SelectItem key={item} value={item}>
+ {t(`controls.scopes.${item}.label`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ {options.scope === 'custom' ? (
+ <Input
+ aria-label={t('controls.customScope')}
+ className="h-8 w-64 font-mono text-sm"
+ onChange={(event) =>
+ onOptionsChange({ customPathInput: event.target.value })
+ }
+ placeholder={t('controls.customScopePlaceholder')}
+ value={options.customPathInput}
+ />
+ ) : null}
+
+ <div className="inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border bg-muted/30 px-2.5 text-xs text-muted-foreground">
+ <FolderOpen className="size-3.5 shrink-0" />
+ <span className="shrink-0">{t('controls.effectiveScope')}</span>
+ <span className="max-w-64 truncate font-mono text-foreground">
+ {options.targetUri ?? t('controls.allContexts')}
+ </span>
+ </div>
+
+ {mode === 'search' ? (
+ <Input
+ aria-label={t('controls.sessionId')}
+ className="h-8 w-52 font-mono text-sm"
+ onChange={(event) =>
+ onOptionsChange({ sessionId: event.target.value })
+ }
+ placeholder={t('controls.sessionPlaceholder')}
+ value={options.sessionId ?? ''}
+ />
+ ) : null}
+
+ {mode === 'grep' ? (
+ <label className="inline-flex h-8 cursor-pointer items-center gap-2 rounded-md border bg-muted/20 px-2.5 text-xs text-foreground">
+ <Checkbox
+ checked={options.ignoreCase}
+ onCheckedChange={(checked) =>
+ onOptionsChange({ ignoreCase: checked === true })
+ }
+ />
+ {t('controls.ignoreCase')}
+ </label>
+ ) : null}
+
+ {semanticMode ? (
+ <Button
+ className="h-8 gap-1.5"
+ onClick={() => setAdvancedOpen((open) => !open)}
+ size="sm"
+ variant="outline"
+ >
+ <SlidersHorizontal className="size-3.5" />
+ {t('advanced.title')}
+ {advancedCount > 0 ? (
+ <span className="rounded-full bg-primary/10 px-1.5 text-[10px] text-primary">
+ {advancedCount}
+ </span>
+ ) : null}
+ <ChevronDown
+ className={cn(
+ 'size-3.5 transition-transform',
+ advancedOpen && 'rotate-180',
+ )}
+ />
+ </Button>
+ ) : null}
</div>
- {mode === 'search' && (
- <Input
- value={sessionIdInput}
- onChange={(event) => onSessionIdInputChange(event.target.value)}
- placeholder={t('controls.sessionPlaceholder')}
- aria-label={t('controls.sessionId')}
- className="h-8 w-52 font-mono text-sm"
+ {semanticMode && advancedOpen ? (
+ <SemanticAdvancedControls
+ onOptionsChange={onOptionsChange}
+ onReset={resetAdvanced}
+ options={options}
+ t={t}
+ toggleContextType={toggleContextType}
+ toggleLevel={toggleLevel}
/>
- )}
+ ) : null}
+ </div>
+ )
+}
+
+function SemanticAdvancedControls({
+ onOptionsChange,
+ onReset,
+ options,
+ t,
+ toggleContextType,
+ toggleLevel,
+}: {
+ onOptionsChange: (patch: Partial<RetrievalRequestOptions>) => void
+ onReset: () => void
+ options: RetrievalRequestOptions
+ t: TFunction<'retrieval'>
+ toggleContextType: (type: FindContextType, checked: boolean) => void
+ toggleLevel: (level: number, checked: boolean) => void
+}) {
+ return (
+ <div className="rounded-xl border bg-card/50 p-4">
+ <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
+ <ControlGroup label={t('advanced.contextTypes')}>
+ <div className="flex flex-wrap gap-2">
+ {CONTEXT_TYPES.map((type) => (
+ <CheckPill
+ checked={options.contextTypes.includes(type)}
+ key={type}
+ label={t(`types.${type}`)}
+ onCheckedChange={(checked) => toggleContextType(type, checked)}
+ />
+ ))}
+ </div>
+ </ControlGroup>
+
+ <ControlGroup label={t('advanced.levels')}>
+ <div className="flex gap-2">
+ {LEVELS.map((level) => (
+ <CheckPill
+ checked={options.levels.includes(level)}
+ key={level}
+ label={`L${level}`}
+ onCheckedChange={(checked) => toggleLevel(level, checked)}
+ />
+ ))}
+ </div>
+ </ControlGroup>
+
+ <ControlGroup label={t('advanced.scoreThreshold')}>
+ <Input
+ aria-label={t('advanced.scoreThreshold')}
+ className="h-8"
+ max={1}
+ min={0}
+ onChange={(event) => {
+ const value = event.target.value
+ onOptionsChange({
+ scoreThreshold: value === '' ? undefined : Number(value),
+ })
+ }}
+ placeholder="0.1"
+ step={0.05}
+ type="number"
+ value={options.scoreThreshold ?? ''}
+ />
+ </ControlGroup>
+
+ <ControlGroup label={t('advanced.tags')}>
+ <TagFilterInput
+ ariaLabel={t('advanced.tags')}
+ invalidMessage={t('advanced.tagsInvalid')}
+ onChange={(tags) => onOptionsChange({ tags })}
+ placeholder={t('advanced.tagsPlaceholder')}
+ value={options.tags}
+ />
+ </ControlGroup>
+
+ <ControlGroup label={t('advanced.timeRange')}>
+ <DateRangePicker
+ onChange={onOptionsChange}
+ since={options.since}
+ t={t}
+ until={options.until}
+ />
+ </ControlGroup>
- {mode === 'grep' && (
- <label className="inline-flex h-8 cursor-pointer items-center gap-2 rounded-md border bg-muted/20 px-2.5 text-xs text-foreground">
- <Checkbox checked={ignoreCase} onCheckedChange={onIgnoreCaseChange} />
- {t('controls.ignoreCase')}
+ <ControlGroup label={t('advanced.timeField')}>
+ <Select
+ onValueChange={(value) =>
+ onOptionsChange({
+ timeField: value as RetrievalRequestOptions['timeField'],
+ })
+ }
+ value={options.timeField}
+ >
+ <SelectTrigger
+ aria-label={t('advanced.timeField')}
+ className="h-8 w-full"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="updated_at">
+ {t('advanced.updatedAt')}
+ </SelectItem>
+ <SelectItem value="created_at">
+ {t('advanced.createdAt')}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </ControlGroup>
+ </div>
+
+ <div className="mt-4 flex items-center justify-between border-t pt-3">
+ <label className="flex items-center gap-2 text-xs">
+ <Switch
+ checked={options.includeProvenance}
+ onCheckedChange={(checked) =>
+ onOptionsChange({ includeProvenance: checked })
+ }
+ />
+ {t('advanced.provenance')}
</label>
- )}
+ <Button className="gap-1.5" onClick={onReset} size="sm" variant="ghost">
+ <RotateCcw className="size-3.5" />
+ {t('advanced.reset')}
+ </Button>
+ </div>
</div>
)
}
+
+function ControlGroup({
+ children,
+ label,
+}: {
+ children: React.ReactNode
+ label: string
+}) {
+ return (
+ <div className="space-y-1.5">
+ <Label className="text-xs text-muted-foreground">{label}</Label>
+ {children}
+ </div>
+ )
+}
+
+function CheckPill({
+ checked,
+ label,
+ onCheckedChange,
+}: {
+ checked: boolean
+ label: string
+ onCheckedChange: (checked: boolean) => void
+}) {
+ return (
+ <label
+ className={cn(
+ 'flex h-8 cursor-pointer items-center gap-2 rounded-md border px-2.5 text-xs',
+ checked
+ ? 'border-primary/30 bg-primary/5 text-primary'
+ : 'bg-background',
+ )}
+ >
+ <Checkbox
+ checked={checked}
+ onCheckedChange={(value) => onCheckedChange(value === true)}
+ />
+ {label}
+ </label>
+ )
+}
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.test.tsx b/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.test.tsx
new file mode 100644
index 000000000..4ecd4db82
--- /dev/null
+++ b/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.test.tsx
@@ -0,0 +1,34 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from '@testing-library/react'
+import type { TFunction } from 'i18next'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { RetrievalDetailSheet } from './retrieval-detail-sheet'
+
+const t = ((key: string) => key) as TFunction<'retrieval'>
+
+afterEach(() => {
+ cleanup()
+})
+
+describe('RetrievalDetailSheet', () => {
+ it('shows only the result summary without loading full content', () => {
+ render(
+ <RetrievalDetailSheet
+ detail={{
+ abstract: 'Result summary',
+ contextType: 'memory',
+ score: 0.8,
+ uri: 'viking://user/default/memories/test.md',
+ }}
+ onClose={vi.fn()}
+ t={t}
+ />,
+ )
+
+ expect(screen.getByText('detail.summary')).toBeDefined()
+ expect(screen.getByText('Result summary')).toBeDefined()
+ expect(screen.queryByText('detail.content')).toBeNull()
+ })
+})
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.tsx b/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.tsx
new file mode 100644
index 000000000..e284305ea
--- /dev/null
+++ b/web-studio/src/routes/retrieval/-components/retrieval-detail-sheet.tsx
@@ -0,0 +1,177 @@
+import { Link } from '@tanstack/react-router'
+import { Brain, ExternalLink, FileText, FolderOpen, Wrench } from 'lucide-react'
+import type { TFunction } from 'i18next'
+
+import { Badge } from '#/components/ui/badge'
+import { Button } from '#/components/ui/button'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '#/components/ui/sheet'
+import { cn } from '#/lib/utils'
+
+import { displayName, resourceSearchForResult } from '../-lib/results'
+import type { FindContextType, FindResultItem } from '#/lib/retrieval'
+
+const DETAIL_TYPE_META: Record<
+ FindContextType,
+ { icon: typeof Brain; color: string }
+> = {
+ resource: {
+ icon: FileText,
+ color: 'text-blue-500',
+ },
+ memory: {
+ icon: Brain,
+ color: 'text-amber-500',
+ },
+ skill: {
+ icon: Wrench,
+ color: 'text-emerald-500',
+ },
+}
+
+export interface RetrievalDetail {
+ abstract?: string
+ contextType: FindContextType
+ item?: FindResultItem
+ memoryType?: string
+ score: number
+ summary?: string
+ uri: string
+}
+
+export function RetrievalDetailSheet({
+ detail,
+ onClose,
+ t,
+}: {
+ detail: RetrievalDetail | null
+ onClose: () => void
+ t: TFunction<'retrieval'>
+}) {
+ const { name, parent } = displayName(detail?.uri ?? '')
+ const summary = detail?.summary ?? detail?.abstract
+ const resourceSearch = detail?.item
+ ? resourceSearchForResult(detail.item)
+ : undefined
+ const typeMeta = DETAIL_TYPE_META[detail?.contextType ?? 'memory']
+ const TypeIcon = typeMeta.icon
+
+ return (
+ <Sheet open={detail !== null} onOpenChange={(open) => !open && onClose()}>
+ <SheetContent className="gap-0 data-[side=right]:sm:max-w-3xl">
+ <SheetHeader className="border-b px-6 py-5">
+ <div className="flex items-start gap-3 pr-10">
+ <div
+ className={cn(
+ 'flex size-6 shrink-0 items-center justify-center',
+ typeMeta.color,
+ )}
+ >
+ <TypeIcon className="size-4" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <SheetTitle className="truncate text-lg">{name}</SheetTitle>
+ {detail?.memoryType ? (
+ <Badge
+ className="h-6 bg-transparent font-mono text-[10px] font-medium text-muted-foreground"
+ variant="outline"
+ >
+ {detail.memoryType}
+ </Badge>
+ ) : null}
+ </div>
+ <SheetDescription className="mt-1 flex items-center gap-1.5">
+ <FolderOpen className="size-3" />
+ <span className="truncate">{parent}</span>
+ </SheetDescription>
+ </div>
+ </div>
+ </SheetHeader>
+
+ <div className="flex flex-wrap items-center gap-2 border-b bg-muted/20 px-6 py-3">
+ <MetaBadge
+ label={t('detail.score')}
+ value={detail?.score.toFixed(3) ?? '0'}
+ />
+ {detail?.item ? (
+ <MetaText
+ label={t('detail.level')}
+ value={`L${detail.item.level}`}
+ />
+ ) : null}
+ {resourceSearch ? (
+ <Button
+ className="ml-auto gap-1.5"
+ nativeButton={false}
+ render={
+ <Link
+ rel="noreferrer noopener"
+ search={resourceSearch}
+ target="_blank"
+ to="/playground"
+ />
+ }
+ size="sm"
+ variant="outline"
+ >
+ {t('detail.openPlayground')}
+ <ExternalLink className="size-3.5" />
+ </Button>
+ ) : null}
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium text-muted-foreground">
+ {t('detail.uri')}
+ </h3>
+ <code className="block break-all rounded-lg border bg-muted/30 px-3 py-2 text-xs">
+ {detail?.uri}
+ </code>
+ </section>
+
+ <section className="mt-5 space-y-2">
+ <h3 className="text-xs font-medium text-muted-foreground">
+ {t('detail.summary')}
+ </h3>
+ <p className="whitespace-pre-wrap text-sm leading-6">
+ {summary || t('detail.noSummary')}
+ </p>
+ </section>
+
+ {detail?.item?.match_reason ? (
+ <section className="mt-5 space-y-2">
+ <h3 className="text-xs font-medium text-muted-foreground">
+ {t('detail.matchReason')}
+ </h3>
+ <p className="text-sm">{detail.item.match_reason}</p>
+ </section>
+ ) : null}
+ </div>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function MetaBadge({ label, value }: { label: string; value: string }) {
+ return (
+ <span className="rounded-md border bg-background px-2 py-1 font-mono text-[11px] text-muted-foreground">
+ {label}: <span className="text-foreground">{value}</span>
+ </span>
+ )
+}
+
+function MetaText({ label, value }: { label: string; value: string }) {
+ return (
+ <span className="px-1 font-mono text-[11px] text-muted-foreground/50">
+ {label}
+ <span className="ml-1 text-muted-foreground/75">{value}</span>
+ </span>
+ )
+}
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-results.test.tsx b/web-studio/src/routes/retrieval/-components/retrieval-results.test.tsx
new file mode 100644
index 000000000..23b1f7284
--- /dev/null
+++ b/web-studio/src/routes/retrieval/-components/retrieval-results.test.tsx
@@ -0,0 +1,101 @@
+// @vitest-environment jsdom
+
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { cleanup, render, screen } from '@testing-library/react'
+import type { TFunction } from 'i18next'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { RetrievalResults } from './retrieval-results'
+
+const t = ((key: string) => key) as TFunction<'retrieval'>
+
+afterEach(cleanup)
+
+describe('RetrievalResults', () => {
+ it('exposes provenance returned by semantic retrieval', () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <RetrievalResults
+ data={{
+ memories: [],
+ provenance: [{ query: 'expanded query', stage: 'rerank' }],
+ resources: [
+ {
+ abstract: 'Result summary',
+ category: '',
+ context_type: 'resource',
+ level: 2,
+ match_reason: '',
+ relations: [],
+ score: 0.8,
+ uri: 'viking://resources/result.md',
+ },
+ ],
+ skills: [],
+ total: 1,
+ }}
+ hasRetrievableContext
+ hasSubmitted
+ isCheckingContext={false}
+ isError={false}
+ isLoading={false}
+ onUploadClick={vi.fn()}
+ resultCount={10}
+ t={t}
+ />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByText('results.provenance')).toBeDefined()
+ expect(screen.getByText(/expanded query/)).toBeDefined()
+ })
+
+ it('shows the API error message and diagnostic metadata', () => {
+ render(
+ <RetrievalResults
+ error={{
+ code: 'INVALID_ARGUMENT',
+ message: 'The glob pattern is invalid.',
+ requestId: 'req-123',
+ statusCode: 400,
+ }}
+ hasRetrievableContext
+ hasSubmitted
+ isCheckingContext={false}
+ isError
+ isLoading={false}
+ onUploadClick={vi.fn()}
+ resultCount={10}
+ t={t}
+ />,
+ )
+
+ expect(screen.getByText('The glob pattern is invalid.')).toBeDefined()
+ expect(screen.getByText(/INVALID_ARGUMENT/)).toBeDefined()
+ expect(screen.getByText(/400/)).toBeDefined()
+ expect(screen.getByText(/req-123/)).toBeDefined()
+ })
+
+ it('explains network failures instead of showing a generic error', () => {
+ render(
+ <RetrievalResults
+ error={{ code: 'NETWORK_ERROR', message: 'Network Error' }}
+ hasRetrievableContext
+ hasSubmitted
+ isCheckingContext={false}
+ isError
+ isLoading={false}
+ onUploadClick={vi.fn()}
+ resultCount={10}
+ t={t}
+ />,
+ )
+
+ expect(screen.getByText('error.network')).toBeDefined()
+ expect(screen.queryByText('Network Error')).toBeNull()
+ })
+})
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-results.tsx b/web-studio/src/routes/retrieval/-components/retrieval-results.tsx
index 66aaa47ae..a52f73dc6 100644
--- a/web-studio/src/routes/retrieval/-components/retrieval-results.tsx
+++ b/web-studio/src/routes/retrieval/-components/retrieval-results.tsx
@@ -1,6 +1,6 @@
-import { Link } from '@tanstack/react-router'
import {
Brain,
+ CircleAlert,
FileText,
FolderOpen,
Loader2,
@@ -9,104 +9,193 @@ import {
Workflow,
Wrench,
} from 'lucide-react'
+import { useMemo, useState } from 'react'
import type { TFunction } from 'i18next'
import { Button } from '#/components/ui/button'
import { cn } from '#/lib/utils'
-import type { FindContextType, FindQueryPlanItem } from '#/lib/retrieval'
+import type {
+ FindContextType,
+ FindQueryPlanItem,
+ GroupedFindResult,
+} from '#/lib/retrieval'
import { LoadingHint } from './loading-hint'
-import { displayName, resourceSearchForResult } from '../-lib/results'
+import { RetrievalDetailSheet } from './retrieval-detail-sheet'
+import type { RetrievalDetail } from './retrieval-detail-sheet'
+import { displayName, flattenResults, memoryTypeFromUri } from '../-lib/results'
import type { FlatRetrievalItem } from '../-types/retrieval'
const TYPE_META: Record<
FindContextType,
- { icon: typeof Brain; color: string; bgColor: string }
+ { icon: typeof Brain; color: string }
> = {
resource: {
icon: FileText,
color: 'text-blue-500',
- bgColor: 'bg-blue-500/15',
},
- memory: { icon: Brain, color: 'text-amber-500', bgColor: 'bg-amber-500/15' },
+ memory: { icon: Brain, color: 'text-amber-500' },
skill: {
icon: Wrench,
color: 'text-emerald-500',
- bgColor: 'bg-emerald-500/15',
},
}
export function RetrievalResults({
- flatItems,
+ data,
+ error,
hasRetrievableContext,
- hasResults,
hasSubmitted,
isCheckingContext,
isError,
isLoading,
onUploadClick,
- queryPlanItems,
resultCount,
t,
}: {
- flatItems: FlatRetrievalItem[]
+ data?: GroupedFindResult
+ error?: unknown
hasRetrievableContext: boolean
- hasResults: boolean
hasSubmitted: boolean
isCheckingContext: boolean
isError: boolean
isLoading: boolean
onUploadClick: () => void
- queryPlanItems: FindQueryPlanItem[]
resultCount: number
t: TFunction<'retrieval'>
}) {
+ const [detail, setDetail] = useState<RetrievalDetail | null>(null)
+ const flatItems = useMemo(() => (data ? flattenResults(data) : []), [data])
+ const queryPlanItems = data?.query_plan?.queries ?? []
+ const provenance = data?.provenance ?? []
+ const hasResults = flatItems.length > 0
+
return (
- <div className="flex flex-col gap-3">
- <h2 className="text-base font-medium">
- {hasSubmitted && hasResults
- ? t('results.topN', {
- count: Math.min(flatItems.length, resultCount),
- })
- : t('results.title')}
- </h2>
+ <>
+ <div className="flex flex-col gap-3">
+ <h2 className="text-base font-medium">
+ {hasSubmitted && hasResults
+ ? t('results.topN', {
+ count: Math.min(flatItems.length, resultCount),
+ })
+ : t('results.title')}
+ </h2>
- <div className="min-h-80 rounded-lg border border-dashed bg-card/50">
- {!hasSubmitted ? (
- <EmptyRetrievalState
- hasRetrievableContext={hasRetrievableContext}
- isCheckingContext={isCheckingContext}
- onUploadClick={onUploadClick}
- t={t}
- />
- ) : isLoading ? (
- <LoadingHint />
- ) : isError ? (
- <div className="flex min-h-80 items-center justify-center text-sm text-destructive">
- {t('error')}
- </div>
- ) : !hasResults ? (
- <div className="flex min-h-80 flex-col items-center justify-center gap-2 text-center">
- <SearchIcon className="size-8 text-muted-foreground/25" />
- <p className="text-sm text-muted-foreground/60">
- {t('noResults.title')}
- </p>
- <p className="text-xs text-muted-foreground/40">
- {t('noResults.subtitle')}
- </p>
- </div>
- ) : (
- <ResultList
- flatItems={flatItems}
- queryPlanItems={queryPlanItems}
- t={t}
- />
- )}
+ <div className="min-h-80 overflow-hidden rounded-lg border border-dashed bg-card/50">
+ {!hasSubmitted ? (
+ <EmptyRetrievalState
+ hasRetrievableContext={hasRetrievableContext}
+ isCheckingContext={isCheckingContext}
+ onUploadClick={onUploadClick}
+ t={t}
+ />
+ ) : isLoading ? (
+ <LoadingHint />
+ ) : isError ? (
+ <RetrievalError error={error} t={t} />
+ ) : !hasResults ? (
+ <div className="flex min-h-80 flex-col items-center justify-center gap-2 text-center">
+ <SearchIcon className="size-8 text-muted-foreground/25" />
+ <p className="text-sm text-muted-foreground/60">
+ {t('noResults.title')}
+ </p>
+ <p className="text-xs text-muted-foreground/40">
+ {t('noResults.subtitle')}
+ </p>
+ </div>
+ ) : (
+ <ResultList
+ flatItems={flatItems}
+ onSelect={setDetail}
+ provenance={provenance}
+ queryPlanItems={queryPlanItems}
+ t={t}
+ />
+ )}
+ </div>
+ </div>
+
+ <RetrievalDetailSheet
+ detail={detail}
+ onClose={() => setDetail(null)}
+ t={t}
+ />
+ </>
+ )
+}
+
+function RetrievalError({
+ error,
+ t,
+}: {
+ error?: unknown
+ t: TFunction<'retrieval'>
+}) {
+ const details = getErrorDetails(error, t)
+
+ return (
+ <div className="flex min-h-80 items-center justify-center px-6 py-10">
+ <div className="flex max-w-xl flex-col items-center text-center">
+ <div className="flex size-10 items-center justify-center rounded-full bg-destructive/10 text-destructive">
+ <CircleAlert className="size-5" />
+ </div>
+ <h3 className="mt-3 text-sm font-medium text-foreground">
+ {t('error.title')}
+ </h3>
+ <p className="mt-1.5 text-sm leading-6 text-muted-foreground">
+ {details.message}
+ </p>
+ <div className="mt-3 flex flex-wrap justify-center gap-2">
+ {details.code ? (
+ <ErrorMeta label={t('error.code')} value={details.code} />
+ ) : null}
+ {details.statusCode ? (
+ <ErrorMeta
+ label={t('error.status')}
+ value={String(details.statusCode)}
+ />
+ ) : null}
+ {details.requestId ? (
+ <ErrorMeta label={t('error.requestId')} value={details.requestId} />
+ ) : null}
+ </div>
</div>
</div>
)
}
+function getErrorDetails(error: unknown, t: TFunction<'retrieval'>) {
+ if (!error || typeof error !== 'object') {
+ return { message: t('error.fallback') }
+ }
+
+ const data = error as Record<string, unknown>
+ const code = typeof data.code === 'string' ? data.code : undefined
+ const rawMessage =
+ typeof data.message === 'string' && data.message.trim()
+ ? data.message.trim()
+ : undefined
+
+ return {
+ code,
+ message:
+ code === 'NETWORK_ERROR'
+ ? t('error.network')
+ : (rawMessage ?? t('error.fallback')),
+ requestId: typeof data.requestId === 'string' ? data.requestId : undefined,
+ statusCode:
+ typeof data.statusCode === 'number' ? data.statusCode : undefined,
+ }
+}
+
+function ErrorMeta({ label, value }: { label: string; value: string }) {
+ return (
+ <span className="rounded-md border bg-muted/30 px-2 py-1 font-mono text-[10px] text-muted-foreground">
+ {label}: <span className="text-foreground">{value}</span>
+ </span>
+ )
+}
+
function EmptyRetrievalState({
hasRetrievableContext,
isCheckingContext,
@@ -143,10 +232,10 @@ function EmptyRetrievalState({
{t('empty.description')}
</p>
<Button
- size="sm"
- variant="secondary"
className="mt-1 gap-1.5"
onClick={onUploadClick}
+ size="sm"
+ variant="secondary"
>
<Upload className="size-4" />
{t('empty.upload')}
@@ -159,16 +248,20 @@ function EmptyRetrievalState({
function ResultList({
flatItems,
+ onSelect,
+ provenance,
queryPlanItems,
t,
}: {
flatItems: FlatRetrievalItem[]
+ onSelect: (detail: RetrievalDetail) => void
+ provenance: NonNullable<GroupedFindResult['provenance']>
queryPlanItems: FindQueryPlanItem[]
t: TFunction<'retrieval'>
}) {
return (
<div className="divide-y">
- {queryPlanItems.length > 0 && (
+ {queryPlanItems.length > 0 ? (
<div className="border-b bg-muted/20 px-4 py-3">
<div className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
<Workflow className="size-3.5" />
@@ -179,10 +272,10 @@ function ResultList({
<div className="mt-2 flex flex-wrap gap-1.5">
{queryPlanItems.slice(0, 4).map((plan, index) => (
<span
- key={`${plan.query}-${index}`}
className="inline-flex max-w-full items-center gap-1 rounded-md border bg-background px-2 py-1 text-xs text-muted-foreground"
+ key={`${plan.query}-${index}`}
>
- {plan.context_type && (
+ {plan.context_type ? (
<span
className={cn(
'font-medium',
@@ -191,76 +284,162 @@ function ResultList({
>
{t(`types.${plan.context_type}`)}
</span>
- )}
+ ) : null}
<span className="truncate">{plan.query}</span>
</span>
))}
- {queryPlanItems.length > 4 && (
+ {queryPlanItems.length > 4 ? (
<span className="rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground">
{t('queryPlan.more', { count: queryPlanItems.length - 4 })}
</span>
- )}
+ ) : null}
</div>
</div>
- )}
- {flatItems.map((fi) => (
- <ResultRow key={`${fi.item.uri}-${fi.flatIndex}`} item={fi} t={t} />
+ ) : null}
+ {provenance.length > 0 ? (
+ <details className="border-b bg-muted/10 px-4 py-3">
+ <summary className="flex cursor-pointer items-center gap-2 text-xs font-medium text-muted-foreground">
+ <Workflow className="size-3.5" />
+ {t('results.provenance', { count: provenance.length })}
+ </summary>
+ <pre className="mt-3 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-md border bg-background/70 p-3 font-mono text-xs leading-5 text-muted-foreground">
+ {JSON.stringify(provenance, null, 2)}
+ </pre>
+ </details>
+ ) : null}
+ {flatItems.map((item) => (
+ <ResultRow
+ item={item}
+ key={`${item.item.uri}-${item.flatIndex}`}
+ onSelect={onSelect}
+ t={t}
+ />
))}
</div>
)
}
function ResultRow({
+ item,
+ onSelect,
+ t,
+}: {
+ item: FlatRetrievalItem
+ onSelect: (detail: RetrievalDetail) => void
+ t: TFunction<'retrieval'>
+}) {
+ const row = <ResultRowContent item={item} t={t} />
+
+ return (
+ <button
+ className="group w-full px-5 py-4 text-left transition-colors hover:bg-muted/35 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-inset"
+ onClick={() =>
+ onSelect({
+ abstract: item.item.abstract,
+ contextType: item.type,
+ item: item.item,
+ memoryType:
+ item.type === 'memory'
+ ? (memoryTypeFromUri(item.item.uri) ?? 'MEMORY')
+ : undefined,
+ score: item.item.score,
+ uri: item.item.uri,
+ })
+ }
+ type="button"
+ >
+ {row}
+ </button>
+ )
+}
+
+function ResultRowContent({
item,
t,
}: {
item: FlatRetrievalItem
t: TFunction<'retrieval'>
}) {
- const { name, parent } = displayName(item.item.uri)
+ const { name } = displayName(item.item.uri)
const meta = TYPE_META[item.type]
const Icon = meta.icon
- const resourceSearch = resourceSearchForResult(item.item)
+ const memoryType =
+ item.type === 'memory' ? memoryTypeFromUri(item.item.uri) : undefined
return (
- <Link
- to="/playground"
- search={resourceSearch}
- target="_blank"
- rel="noreferrer noopener"
- className="flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-inset"
- >
- <div
- className={cn(
- 'mt-0.5 inline-flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-[11px] font-semibold uppercase tracking-wide',
- meta.bgColor,
- meta.color,
- )}
- >
- <Icon className="size-3" />
- <span>{t(`types.${item.type}`)}</span>
- </div>
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-medium">{name}</div>
- <div className="mt-0.5 flex items-center gap-1.5 text-xs text-muted-foreground/70">
- <FolderOpen className="size-3 shrink-0" />
- <span className="truncate">{parent}</span>
+ <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-x-5">
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <Icon
+ aria-hidden="true"
+ className={cn('size-3.5 shrink-0', meta.color)}
+ />
+ <h3 className="min-w-0 truncate text-sm font-semibold text-foreground">
+ {name}
+ </h3>
+ <span className="sr-only">{t(`types.${item.type}`)}</span>
+ {memoryType ? (
+ <span className="shrink-0 rounded border border-border/60 px-1.5 py-0.5 font-mono text-[9px] font-medium tracking-wide text-muted-foreground/70">
+ {memoryType}
+ </span>
+ ) : null}
+ <span
+ className="shrink-0 font-mono text-[10px] font-medium tabular-nums text-muted-foreground/45"
+ title={`${t('detail.level')}: L${item.item.level}`}
+ >
+ L{item.item.level}
+ </span>
</div>
- {item.item.abstract && (
- <p className="mt-1 line-clamp-2 text-xs text-muted-foreground/60">
- {item.item.abstract}
- </p>
- )}
+
+ <dl className="mt-2.5 grid min-w-0 grid-cols-[3.25rem_minmax(0,1fr)] gap-x-2.5 gap-y-1.5">
+ <dt className="pt-px text-[10px] font-medium uppercase tracking-[0.1em] text-muted-foreground/55">
+ {t('results.uri')}
+ </dt>
+ <dd
+ className="flex min-w-0 items-center gap-1.5 font-mono text-[11px] text-muted-foreground/75"
+ title={item.item.uri}
+ >
+ <FolderOpen className="size-3 shrink-0 text-muted-foreground/45" />
+ <span className="truncate">{item.item.uri}</span>
+ </dd>
+
+ {item.item.abstract ? (
+ <>
+ <dt className="pt-0.5 text-[10px] font-medium uppercase tracking-[0.1em] text-muted-foreground/55">
+ {t('results.description')}
+ </dt>
+ <dd className="line-clamp-2 text-xs leading-5 text-muted-foreground/70">
+ {item.item.abstract}
+ </dd>
+ </>
+ ) : null}
+ </dl>
</div>
+
{item.item.result_kind === 'grep' && item.item.line !== undefined ? (
- <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">
- {t('results.line', { line: item.item.line })}
- </span>
+ <ResultMetric
+ label={t('results.lineLabel')}
+ value={String(item.item.line)}
+ />
) : item.item.result_kind !== 'glob' ? (
- <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] tabular-nums text-muted-foreground">
- {item.item.score.toFixed(3)}
- </span>
+ <ResultMetric
+ label={t('results.score')}
+ value={item.item.score.toFixed(3)}
+ />
) : null}
- </Link>
+ </div>
+ )
+}
+
+function ResultMetric({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="min-w-16 self-start rounded-md border border-border/60 bg-muted/35 px-2.5 py-2 text-right transition-colors group-hover:bg-background/70">
+ <div className="text-[9px] font-medium uppercase tracking-[0.1em] text-muted-foreground/50">
+ {label}
+ </div>
+ <div className="mt-0.5 font-mono text-xs font-semibold tabular-nums text-foreground/75">
+ {value}
+ </div>
+ </div>
)
}
diff --git a/web-studio/src/routes/retrieval/-components/search-bar.tsx b/web-studio/src/routes/retrieval/-components/search-bar.tsx
index a5367d631..550fdd885 100644
--- a/web-studio/src/routes/retrieval/-components/search-bar.tsx
+++ b/web-studio/src/routes/retrieval/-components/search-bar.tsx
@@ -9,12 +9,14 @@ export function RetrievalSearchBar({
onSubmit,
placeholder,
query,
+ submitLabel,
}: {
inputRef: RefObject<HTMLInputElement | null>
onChange: (value: string) => void
onSubmit: () => void
placeholder: string
query: string
+ submitLabel: string
}) {
const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter' && !event.nativeEvent.isComposing) {
@@ -35,6 +37,7 @@ export function RetrievalSearchBar({
className="flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground/60 md:text-sm"
/>
<Button
+ aria-label={submitLabel}
variant="ghost"
size="icon"
className="size-8 shrink-0"
diff --git a/web-studio/src/routes/retrieval/-components/tag-filter-input.test.tsx b/web-studio/src/routes/retrieval/-components/tag-filter-input.test.tsx
new file mode 100644
index 000000000..3d6fd2be3
--- /dev/null
+++ b/web-studio/src/routes/retrieval/-components/tag-filter-input.test.tsx
@@ -0,0 +1,36 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { TagFilterInput } from './tag-filter-input'
+
+afterEach(cleanup)
+
+describe('TagFilterInput', () => {
+ it('reports invalid tags and only publishes strict key=value values', () => {
+ const onChange = vi.fn()
+ const placeholder = 'env=prod'
+ render(
+ <TagFilterInput
+ ariaLabel="Search tags"
+ invalidMessage="Use key=value"
+ onChange={onChange}
+ placeholder={placeholder}
+ value={[]}
+ />,
+ )
+
+ fireEvent.change(screen.getByRole('textbox', { name: 'Search tags' }), {
+ target: { value: 'invalid-tag' },
+ })
+ expect(screen.getByText('Use key=value')).toBeDefined()
+ expect(onChange).not.toHaveBeenCalled()
+
+ fireEvent.change(screen.getByRole('textbox', { name: 'Search tags' }), {
+ target: { value: 'env=prod, team=search' },
+ })
+ expect(screen.queryByText('Use key=value')).toBeNull()
+ expect(onChange).toHaveBeenLastCalledWith(['env=prod', 'team=search'])
+ })
+})
diff --git a/web-studio/src/routes/retrieval/-components/tag-filter-input.tsx b/web-studio/src/routes/retrieval/-components/tag-filter-input.tsx
new file mode 100644
index 000000000..60790bc35
--- /dev/null
+++ b/web-studio/src/routes/retrieval/-components/tag-filter-input.tsx
@@ -0,0 +1,71 @@
+import { useState } from 'react'
+
+import { Input } from '#/components/ui/input'
+
+const TAG_PATTERN = /^[^=,\s]+=[^=,\s]+$/
+
+export function parseTagFilterInput(input: string): {
+ tags: string[]
+ valid: boolean
+} {
+ const tags = input
+ .split(',')
+ .map((tag) => tag.trim())
+ .filter(Boolean)
+
+ return {
+ tags: Array.from(new Set(tags)),
+ valid: tags.every((tag) => TAG_PATTERN.test(tag)),
+ }
+}
+
+export function TagFilterInput({
+ ariaLabel,
+ invalidMessage,
+ onChange,
+ placeholder,
+ value,
+}: {
+ ariaLabel: string
+ invalidMessage: string
+ onChange: (tags: string[]) => void
+ placeholder: string
+ value: string[]
+}) {
+ const serializedValue = value.join(', ')
+ const [draft, setDraft] = useState(serializedValue)
+ const [lastValue, setLastValue] = useState(serializedValue)
+ const [invalid, setInvalid] = useState(false)
+
+ if (lastValue !== serializedValue) {
+ setLastValue(serializedValue)
+ setDraft(serializedValue)
+ setInvalid(false)
+ }
+
+ return (
+ <div className="space-y-1">
+ <Input
+ aria-invalid={invalid}
+ aria-label={ariaLabel}
+ className="h-8 font-mono text-xs"
+ onChange={(event) => {
+ const nextDraft = event.target.value
+ const parsed = parseTagFilterInput(nextDraft)
+ setDraft(nextDraft)
+ setInvalid(!parsed.valid)
+ if (parsed.valid) {
+ onChange(parsed.tags)
+ }
+ }}
+ placeholder={placeholder}
+ value={draft}
+ />
+ {invalid ? (
+ <p className="text-xs text-destructive" role="alert">
+ {invalidMessage}
+ </p>
+ ) : null}
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/retrieval/-hooks/use-retrieval-query.ts b/web-studio/src/routes/retrieval/-hooks/use-retrieval-query.ts
index 2e503b54e..44f490581 100644
--- a/web-studio/src/routes/retrieval/-hooks/use-retrieval-query.ts
+++ b/web-studio/src/routes/retrieval/-hooks/use-retrieval-query.ts
@@ -3,60 +3,71 @@ import { useQuery } from '@tanstack/react-query'
import { fetchFind, fetchGlob, fetchGrep, fetchSearch } from '#/lib/retrieval'
import type { GroupedFindResult } from '#/lib/retrieval'
-import type { RetrievalMode } from '../-types/retrieval'
+import type {
+ RetrievalMode,
+ RetrievalRequestOptions,
+} from '../-types/retrieval'
export function useRetrievalQuery({
enabled,
- ignoreCase,
mode,
query,
- resultCount,
- sessionId,
- targetUri,
+ options,
}: {
enabled: boolean
- ignoreCase: boolean
mode: RetrievalMode
query: string
- resultCount: number
- sessionId?: string
- targetUri?: string
+ options: RetrievalRequestOptions
}) {
return useQuery<GroupedFindResult>({
enabled,
gcTime: 5 * 60_000,
- placeholderData: (prev) => prev,
queryFn: () => {
if (mode === 'search') {
- return fetchSearch(query, { limit: resultCount, sessionId, targetUri })
+ return fetchSearch(query, {
+ contextTypes: options.contextTypes,
+ includeProvenance: options.includeProvenance,
+ levels: options.levels,
+ limit: options.resultCount,
+ scoreThreshold: options.scoreThreshold,
+ sessionId: options.sessionId,
+ since: options.since,
+ tags: options.tags,
+ targetUri: options.targetUri,
+ timeField: options.timeField,
+ until: options.until,
+ })
}
if (mode === 'grep') {
return fetchGrep(query, {
- caseInsensitive: ignoreCase,
- limit: resultCount,
- uri: targetUri ?? 'viking://',
+ caseInsensitive: options.ignoreCase,
+ limit: options.resultCount,
+ uri: options.targetUri ?? 'viking://',
})
}
if (mode === 'glob') {
return fetchGlob(query, {
- limit: resultCount,
- uri: targetUri ?? 'viking://',
+ limit: options.resultCount,
+ uri: options.targetUri ?? 'viking://',
})
}
- return fetchFind(query, { limit: resultCount, targetUri })
+ return fetchFind(query, {
+ contextTypes: options.contextTypes,
+ includeProvenance: options.includeProvenance,
+ levels: options.levels,
+ limit: options.resultCount,
+ scoreThreshold: options.scoreThreshold,
+ since: options.since,
+ tags: options.tags,
+ targetUri: options.targetUri,
+ timeField: options.timeField,
+ until: options.until,
+ })
},
- queryKey: [
- 'retrieval',
- mode,
- query,
- targetUri,
- resultCount,
- sessionId,
- ignoreCase,
- ],
+ queryKey: ['retrieval', mode, query, options],
staleTime: 60_000,
})
}
diff --git a/web-studio/src/routes/retrieval/-lib/results.ts b/web-studio/src/routes/retrieval/-lib/results.ts
index 830bcb809..7f5d88819 100644
--- a/web-studio/src/routes/retrieval/-lib/results.ts
+++ b/web-studio/src/routes/retrieval/-lib/results.ts
@@ -28,6 +28,14 @@ export function displayName(uri: string): { name: string; parent: string } {
return { name, parent }
}
+const MEMORY_TYPE_PATTERN = /\/memories\/([^/]+)(?:\/|$)/i
+
+export function memoryTypeFromUri(uri: string): string | undefined {
+ const match = MEMORY_TYPE_PATTERN.exec(uri)
+ const type = match?.[1]?.trim().replace(/\.(?:md|json|jsonl)$/i, '')
+ return type ? type.toUpperCase() : undefined
+}
+
export function isDirectoryResult(item: FindResultItem): boolean {
return item.uri.endsWith('/') || item.level < 2
}
diff --git a/web-studio/src/routes/retrieval/-lib/search-state.test.ts b/web-studio/src/routes/retrieval/-lib/search-state.test.ts
new file mode 100644
index 000000000..df6206f1a
--- /dev/null
+++ b/web-studio/src/routes/retrieval/-lib/search-state.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ buildSubmittedSearch,
+ createRetrievalSubmission,
+ parseLevels,
+ validateRetrievalSearch,
+} from './search-state'
+import { memoryTypeFromUri } from './results'
+import type { RetrievalRequestOptions } from '../-types/retrieval'
+
+describe('retrieval search state', () => {
+ it('validates advanced parameters from URL search values', () => {
+ expect(
+ validateRetrievalSearch({
+ levels: '0,2',
+ minScore: '0.25',
+ provenance: 'true',
+ tags: 'env=prod,team=search',
+ timeField: 'created_at',
+ types: 'memory,resource',
+ }),
+ ).toMatchObject({
+ levels: '0,2',
+ minScore: 0.25,
+ provenance: true,
+ tags: 'env=prod,team=search',
+ timeField: 'created_at',
+ types: 'memory,resource',
+ })
+ expect(parseLevels('0,2,8')).toEqual([0, 2])
+ })
+
+ it('builds a new submission for the selected mode', () => {
+ const options: RetrievalRequestOptions = {
+ contextTypes: [],
+ customPathInput: 'resources/',
+ ignoreCase: false,
+ includeProvenance: false,
+ levels: [],
+ resultCount: 10,
+ scope: 'all',
+ tags: [],
+ timeField: 'updated_at',
+ }
+
+ expect(
+ createRetrievalSubmission(' openviking ', 'search', options),
+ ).toEqual({
+ query: 'openviking',
+ search: { mode: 'search', q: 'openviking' },
+ })
+ expect(createRetrievalSubmission(' ', 'find', options)).toBeUndefined()
+ })
+
+ it('drops the retired recall mode and its parameters', () => {
+ expect(
+ validateRetrievalSearch({
+ maxChars: 6500,
+ mode: 'recall',
+ peerScope: 'all',
+ q: 'OpenViking',
+ recallQuotas: 'events:10',
+ render: false,
+ }),
+ ).toEqual({ q: 'OpenViking' })
+ })
+
+ it('derives memory type labels without leaking file extensions', () => {
+ expect(
+ memoryTypeFromUri(
+ 'viking://user/default/memories/trajectories/.abstract.md',
+ ),
+ ).toBe('TRAJECTORIES')
+ expect(memoryTypeFromUri('viking://user/default/memories/profile.md')).toBe(
+ 'PROFILE',
+ )
+ })
+})
diff --git a/web-studio/src/routes/retrieval/-lib/search-state.ts b/web-studio/src/routes/retrieval/-lib/search-state.ts
index e740eecae..72c9714ce 100644
--- a/web-studio/src/routes/retrieval/-lib/search-state.ts
+++ b/web-studio/src/routes/retrieval/-lib/search-state.ts
@@ -10,8 +10,10 @@ import {
import type {
ResultCountOption,
RetrievalMode,
+ RetrievalRequestOptions,
RetrievalScope,
RetrievalSearch,
+ RetrievalTimeField,
} from '../-types/retrieval'
export function isRetrievalMode(value: unknown): value is RetrievalMode {
@@ -50,6 +52,10 @@ export function validateRetrievalSearch(
typeof search.session === 'string' ? search.session.trim() : undefined
const ignoreCase =
search.ignoreCase === true || search.ignoreCase === 'true' || undefined
+ const provenance =
+ search.provenance === true || search.provenance === 'true' || undefined
+ const minScore = parseFiniteNumber(search.minScore)
+ const timeField = isTimeField(search.timeField) ? search.timeField : undefined
return {
...(q && { q }),
@@ -59,6 +65,19 @@ export function validateRetrievalSearch(
...(path && { path }),
...(session && { session }),
...(ignoreCase && { ignoreCase }),
+ ...(typeof search.types === 'string' &&
+ search.types.trim() && { types: search.types.trim() }),
+ ...(typeof search.tags === 'string' &&
+ search.tags.trim() && { tags: search.tags.trim() }),
+ ...(minScore !== undefined && { minScore }),
+ ...(typeof search.levels === 'string' &&
+ search.levels.trim() && { levels: search.levels.trim() }),
+ ...(typeof search.since === 'string' &&
+ search.since.trim() && { since: search.since.trim() }),
+ ...(typeof search.until === 'string' &&
+ search.until.trim() && { until: search.until.trim() }),
+ ...(timeField && { timeField }),
+ ...(provenance && { provenance }),
}
}
@@ -70,10 +89,32 @@ export function hasRetrievalSearch(search: RetrievalSearch): boolean {
search.scope ||
search.path ||
search.session ||
- search.ignoreCase,
+ search.ignoreCase ||
+ search.types ||
+ search.tags ||
+ search.minScore !== undefined ||
+ search.levels ||
+ search.since ||
+ search.until ||
+ search.timeField ||
+ search.provenance,
)
}
+function parseFiniteNumber(value: unknown): number | undefined {
+ const numeric =
+ typeof value === 'number'
+ ? value
+ : typeof value === 'string'
+ ? Number(value)
+ : NaN
+ return Number.isFinite(numeric) ? numeric : undefined
+}
+
+function isTimeField(value: unknown): value is RetrievalTimeField {
+ return value === 'created_at' || value === 'updated_at'
+}
+
export function readLastRetrievalSearch(): RetrievalSearch | undefined {
if (typeof window === 'undefined') {
return undefined
@@ -120,11 +161,23 @@ export function buildSubmittedSearch(params: {
path: string
session: string
ignoreCase: boolean
+ types: string[]
+ tags: string[]
+ scoreThreshold?: number
+ levels: number[]
+ since: string
+ until: string
+ timeField: RetrievalTimeField
+ includeProvenance: boolean
}): RetrievalSearch {
const q = params.q.trim()
const path = params.path.trim()
const session = params.session.trim()
-
+ const types = params.types.join(',')
+ const tags = params.tags.join(',')
+ const levels = params.levels.join(',')
+ const since = params.since.trim()
+ const until = params.until.trim()
return {
q,
...(params.mode !== DEFAULT_RETRIEVAL_MODE && { mode: params.mode }),
@@ -133,5 +186,85 @@ export function buildSubmittedSearch(params: {
...(params.scope === 'custom' && path && { path }),
...(params.mode === 'search' && session && { session }),
...(params.mode === 'grep' && params.ignoreCase && { ignoreCase: true }),
+ ...((params.mode === 'find' || params.mode === 'search') &&
+ types && { types }),
+ ...((params.mode === 'find' || params.mode === 'search') &&
+ tags && { tags }),
+ ...((params.mode === 'find' || params.mode === 'search') &&
+ params.scoreThreshold !== undefined && {
+ minScore: params.scoreThreshold,
+ }),
+ ...((params.mode === 'find' || params.mode === 'search') &&
+ levels && { levels }),
+ ...((params.mode === 'find' || params.mode === 'search') &&
+ since && { since }),
+ ...((params.mode === 'find' || params.mode === 'search') &&
+ until && { until }),
+ ...((params.mode === 'find' || params.mode === 'search') &&
+ (since || until) &&
+ params.timeField !== 'updated_at' && { timeField: params.timeField }),
+ ...((params.mode === 'find' || params.mode === 'search') &&
+ params.includeProvenance && { provenance: true }),
+ }
+}
+
+export function buildSearchFromOptions(
+ q: string,
+ mode: RetrievalMode,
+ options: RetrievalRequestOptions,
+): RetrievalSearch {
+ return buildSubmittedSearch({
+ count: options.resultCount,
+ ignoreCase: options.ignoreCase,
+ includeProvenance: options.includeProvenance,
+ levels: options.levels,
+ mode,
+ path: options.customPathInput,
+ q,
+ scoreThreshold: options.scoreThreshold,
+ scope: options.scope,
+ session: options.sessionId ?? '',
+ since: options.since ?? '',
+ tags: options.tags,
+ timeField: options.timeField,
+ types: options.contextTypes,
+ until: options.until ?? '',
+ })
+}
+
+export function createRetrievalSubmission(
+ query: string,
+ mode: RetrievalMode,
+ options: RetrievalRequestOptions,
+):
+ | {
+ query: string
+ search: RetrievalSearch
+ }
+ | undefined {
+ const trimmedQuery = query.trim()
+ if (!trimmedQuery) return undefined
+
+ return {
+ query: trimmedQuery,
+ search: buildSearchFromOptions(trimmedQuery, mode, options),
}
}
+
+export function parseCsv(value?: string): string[] {
+ if (!value) return []
+ return Array.from(
+ new Set(
+ value
+ .split(',')
+ .map((item) => item.trim())
+ .filter(Boolean),
+ ),
+ )
+}
+
+export function parseLevels(value?: string): number[] {
+ return parseCsv(value)
+ .map(Number)
+ .filter((level) => level === 0 || level === 1 || level === 2)
+}
diff --git a/web-studio/src/routes/retrieval/-types/retrieval.ts b/web-studio/src/routes/retrieval/-types/retrieval.ts
index 61deceb2e..06f8f4469 100644
--- a/web-studio/src/routes/retrieval/-types/retrieval.ts
+++ b/web-studio/src/routes/retrieval/-types/retrieval.ts
@@ -8,6 +8,7 @@ import type { FindContextType, FindResultItem } from '#/lib/retrieval'
export type RetrievalMode = (typeof RETRIEVAL_MODES)[number]
export type RetrievalScope = (typeof RETRIEVAL_SCOPES)[number]
export type ResultCountOption = (typeof RESULT_COUNT_OPTIONS)[number]
+export type RetrievalTimeField = 'created_at' | 'updated_at'
export type RetrievalSearch = {
q?: string
@@ -17,6 +18,14 @@ export type RetrievalSearch = {
path?: string
session?: string
ignoreCase?: boolean
+ types?: string
+ tags?: string
+ minScore?: number
+ levels?: string
+ since?: string
+ until?: string
+ timeField?: RetrievalTimeField
+ provenance?: boolean
}
export interface FlatRetrievalItem {
@@ -24,3 +33,20 @@ export interface FlatRetrievalItem {
item: FindResultItem
flatIndex: number
}
+
+export interface RetrievalRequestOptions {
+ contextTypes: FindContextType[]
+ customPathInput: string
+ ignoreCase: boolean
+ includeProvenance: boolean
+ levels: number[]
+ resultCount: number
+ scoreThreshold?: number
+ sessionId?: string
+ since?: string
+ scope: RetrievalScope
+ tags: string[]
+ targetUri?: string
+ timeField: RetrievalTimeField
+ until?: string
+}
diff --git a/web-studio/src/routes/retrieval/route.tsx b/web-studio/src/routes/retrieval/route.tsx
index 2b8ce5ed3..3921f1572 100644
--- a/web-studio/src/routes/retrieval/route.tsx
+++ b/web-studio/src/routes/retrieval/route.tsx
@@ -13,22 +13,60 @@ import {
} from './-constants/retrieval'
import { useResourceContextProbe } from './-hooks/use-resource-context-probe'
import { useRetrievalQuery } from './-hooks/use-retrieval-query'
-import { flattenResults } from './-lib/results'
import { resolveScopeTargetUri } from './-lib/scope'
import {
- buildSubmittedSearch,
+ buildSearchFromOptions,
+ createRetrievalSubmission,
hasRetrievalSearch,
+ parseCsv,
+ parseLevels,
readLastRetrievalSearch,
validateRetrievalSearch,
writeLastRetrievalSearch,
} from './-lib/search-state'
-import type { RetrievalMode, RetrievalScope } from './-types/retrieval'
+import type {
+ RetrievalMode,
+ RetrievalRequestOptions,
+ RetrievalSearch,
+} from './-types/retrieval'
+import type { FindContextType } from '#/lib/retrieval'
export const Route = createFileRoute('/retrieval')({
validateSearch: validateRetrievalSearch,
component: RetrievalPage,
})
+const FIND_CONTEXT_TYPES = new Set<FindContextType>([
+ 'memory',
+ 'resource',
+ 'skill',
+])
+
+function optionsFromSearch(search: RetrievalSearch): RetrievalRequestOptions {
+ const scope = search.scope ?? DEFAULT_RETRIEVAL_SCOPE
+ const customPathInput = search.path ?? DEFAULT_CUSTOM_PATH_INPUT
+
+ return {
+ contextTypes: parseCsv(search.types).filter(
+ (type): type is FindContextType =>
+ FIND_CONTEXT_TYPES.has(type as FindContextType),
+ ),
+ customPathInput,
+ ignoreCase: search.ignoreCase ?? false,
+ includeProvenance: search.provenance ?? false,
+ levels: parseLevels(search.levels),
+ resultCount: search.count ?? DEFAULT_RESULT_COUNT,
+ scoreThreshold: search.minScore,
+ sessionId: search.session,
+ since: search.since,
+ scope,
+ tags: parseCsv(search.tags),
+ targetUri: resolveScopeTargetUri(scope, customPathInput),
+ timeField: search.timeField ?? 'updated_at',
+ until: search.until,
+ }
+}
+
function RetrievalPage() {
const { t } = useTranslation('retrieval')
const navigate = useNavigate({ from: Route.fullPath })
@@ -39,81 +77,71 @@ function RetrievalPage() {
[hasUrlSearch],
)
const activeSearch = hasUrlSearch ? search : (restoredSearch ?? search)
-
- const initialQuery = activeSearch.q ?? ''
const initialMode = activeSearch.mode ?? DEFAULT_RETRIEVAL_MODE
- const initialResultCount = activeSearch.count ?? DEFAULT_RESULT_COUNT
- const initialScope = activeSearch.scope ?? DEFAULT_RETRIEVAL_SCOPE
- const initialCustomPath = activeSearch.path ?? DEFAULT_CUSTOM_PATH_INPUT
- const initialSessionId = activeSearch.session ?? ''
- const initialIgnoreCase = activeSearch.ignoreCase ?? false
+ const initialOptions = useMemo(
+ () => optionsFromSearch(activeSearch),
+ [activeSearch],
+ )
const [retrievalMode, setRetrievalMode] = useState<RetrievalMode>(initialMode)
- const [query, setQuery] = useState(initialQuery)
- const [submittedQuery, setSubmittedQuery] = useState(initialQuery)
- const [resultCount, setResultCount] = useState<number>(initialResultCount)
- const [retrievalScope, setRetrievalScope] =
- useState<RetrievalScope>(initialScope)
- const [customPathInput, setCustomPathInput] = useState(initialCustomPath)
- const [sessionIdInput, setSessionIdInput] = useState(initialSessionId)
- const [ignoreCase, setIgnoreCase] = useState(initialIgnoreCase)
+ const [submittedMode, setSubmittedMode] = useState<RetrievalMode>(initialMode)
+ const [query, setQuery] = useState(activeSearch.q ?? '')
+ const [submittedQuery, setSubmittedQuery] = useState(activeSearch.q ?? '')
+ const [options, setOptions] =
+ useState<RetrievalRequestOptions>(initialOptions)
+ const [submittedOptions, setSubmittedOptions] =
+ useState<RetrievalRequestOptions>(initialOptions)
const inputRef = useRef<HTMLInputElement>(null)
- const targetUri = useMemo(() => {
- return resolveScopeTargetUri(retrievalScope, customPathInput)
- }, [customPathInput, retrievalScope])
-
const hasSubmitted = submittedQuery.trim().length > 0
- const sessionId = sessionIdInput.trim() || undefined
const retrievalQuery = useRetrievalQuery({
enabled: hasSubmitted,
- ignoreCase,
- mode: retrievalMode,
+ mode: submittedMode,
+ options: submittedOptions,
query: submittedQuery,
- resultCount,
- sessionId,
- targetUri,
})
const resourceProbeQuery = useResourceContextProbe()
- const data = hasSubmitted ? retrievalQuery.data : undefined
- const hasResults = Boolean(data && data.total > 0)
- const hasRetrievableContext = resourceProbeQuery.data?.hasContext ?? false
- const flatItems = useMemo(() => (data ? flattenResults(data) : []), [data])
- const queryPlanItems = data?.query_plan?.queries ?? []
+ const handleOptionsChange = useCallback(
+ (patch: Partial<RetrievalRequestOptions>) => {
+ setOptions((current) => {
+ const next = { ...current, ...patch }
+ return {
+ ...next,
+ targetUri: resolveScopeTargetUri(next.scope, next.customPathInput),
+ }
+ })
+ },
+ [],
+ )
+
+ const submitQuery = useCallback(
+ (mode: RetrievalMode) => {
+ const submission = createRetrievalSubmission(query, mode, options)
+ if (!submission) return
+
+ setSubmittedMode(mode)
+ setSubmittedOptions(options)
+ setSubmittedQuery(submission.query)
+ writeLastRetrievalSearch(submission.search)
+ void navigate({ replace: true, search: submission.search })
+ },
+ [navigate, options, query],
+ )
const handleSubmit = useCallback(() => {
- const trimmed = query.trim()
- if (trimmed.length === 0) {
- return
- }
+ submitQuery(retrievalMode)
+ }, [retrievalMode, submitQuery])
- const nextSearch = buildSubmittedSearch({
- count: resultCount,
- ignoreCase,
- mode: retrievalMode,
- path: customPathInput,
- q: trimmed,
- scope: retrievalScope,
- session: sessionIdInput,
- })
-
- setSubmittedQuery(trimmed)
- writeLastRetrievalSearch(nextSearch)
- void navigate({
- replace: true,
- search: nextSearch,
- })
- }, [
- customPathInput,
- ignoreCase,
- navigate,
- query,
- resultCount,
- retrievalMode,
- retrievalScope,
- sessionIdInput,
- ])
+ const handleModeChange = useCallback(
+ (nextMode: RetrievalMode) => {
+ if (nextMode === retrievalMode) return
+
+ setRetrievalMode(nextMode)
+ submitQuery(nextMode)
+ },
+ [retrievalMode, submitQuery],
+ )
const handleUploadClick = useCallback(() => {
void navigate({ to: '/playground', search: { upload: true } })
@@ -124,55 +152,28 @@ function RetrievalPage() {
}, [])
useEffect(() => {
- if (!activeSearch.q) {
- return
- }
+ if (!activeSearch.q) return
const nextMode = activeSearch.mode ?? DEFAULT_RETRIEVAL_MODE
- const nextResultCount = activeSearch.count ?? DEFAULT_RESULT_COUNT
- const nextScope = activeSearch.scope ?? DEFAULT_RETRIEVAL_SCOPE
- const nextCustomPath = activeSearch.path ?? DEFAULT_CUSTOM_PATH_INPUT
- const nextSessionId = activeSearch.session ?? ''
- const nextIgnoreCase = activeSearch.ignoreCase ?? false
-
+ const nextOptions = optionsFromSearch(activeSearch)
setRetrievalMode(nextMode)
+ setSubmittedMode(nextMode)
setQuery(activeSearch.q)
setSubmittedQuery(activeSearch.q)
- setResultCount(nextResultCount)
- setRetrievalScope(nextScope)
- setCustomPathInput(nextCustomPath)
- setSessionIdInput(nextSessionId)
- setIgnoreCase(nextIgnoreCase)
-
- const nextSearch = buildSubmittedSearch({
- count: nextResultCount,
- ignoreCase: nextIgnoreCase,
- mode: nextMode,
- path: nextCustomPath,
- q: activeSearch.q,
- scope: nextScope,
- session: nextSessionId,
- })
-
+ setOptions(nextOptions)
+ setSubmittedOptions(nextOptions)
+
+ const nextSearch = buildSearchFromOptions(
+ activeSearch.q,
+ nextMode,
+ nextOptions,
+ )
writeLastRetrievalSearch(nextSearch)
if (!hasUrlSearch) {
- void navigate({
- replace: true,
- search: nextSearch,
- })
+ void navigate({ replace: true, search: nextSearch })
}
- }, [
- activeSearch.count,
- activeSearch.ignoreCase,
- activeSearch.mode,
- activeSearch.path,
- activeSearch.q,
- activeSearch.scope,
- activeSearch.session,
- hasUrlSearch,
- navigate,
- ])
+ }, [activeSearch, hasUrlSearch, navigate])
return (
<div className="flex w-full min-w-0 flex-col gap-5">
@@ -182,36 +183,27 @@ function RetrievalPage() {
onSubmit={handleSubmit}
placeholder={t(`placeholders.${retrievalMode}`)}
query={query}
+ submitLabel={t('send')}
/>
<RetrievalControls
- customPathInput={customPathInput}
- ignoreCase={ignoreCase}
mode={retrievalMode}
- onCustomPathInputChange={setCustomPathInput}
- onIgnoreCaseChange={setIgnoreCase}
- onModeChange={setRetrievalMode}
- onResultCountChange={setResultCount}
- onScopeChange={setRetrievalScope}
- onSessionIdInputChange={setSessionIdInput}
- resultCount={resultCount}
- scope={retrievalScope}
- sessionIdInput={sessionIdInput}
+ onModeChange={handleModeChange}
+ onOptionsChange={handleOptionsChange}
+ options={options}
t={t}
- targetUri={targetUri}
/>
<RetrievalResults
- flatItems={flatItems}
- hasRetrievableContext={hasRetrievableContext}
- hasResults={hasResults}
+ data={hasSubmitted ? retrievalQuery.data : undefined}
+ hasRetrievableContext={resourceProbeQuery.data?.hasContext ?? false}
hasSubmitted={hasSubmitted}
+ error={retrievalQuery.error}
isCheckingContext={resourceProbeQuery.isLoading}
isError={retrievalQuery.isError}
isLoading={retrievalQuery.isLoading}
onUploadClick={handleUploadClick}
- queryPlanItems={queryPlanItems}
- resultCount={resultCount}
+ resultCount={submittedOptions.resultCount}
t={t}
/>
</div>
diff --git a/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx b/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx
index be6b5e707..22928d8c3 100644
--- a/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx
+++ b/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx
@@ -72,7 +72,7 @@ export function TaskDetailSheet({
return (
<Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent className="gap-0 sm:max-w-xl">
+ <SheetContent className="gap-0 data-[side=right]:sm:max-w-3xl">
<SheetHeader className="border-b px-6 py-5">
<div className="flex items-center gap-3 pr-10">
<div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary ring-1 ring-primary/15">