Skip to content

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

feat(web-studio): search modes, panel collapse, and structured JSONL rendering (#4470)

Zayn Jarvis303e117238ab
diff --git a/web-studio/package-lock.json b/web-studio/package-lock.json
index ab4ff93e3..b673e85e4 100644
--- a/web-studio/package-lock.json
+++ b/web-studio/package-lock.json
@@ -38,7 +38,6 @@
"@tanstack/react-router": "latest",
"@tanstack/react-router-devtools": "latest",
"@tanstack/react-table": "^8.21.3",
- "@tanstack/router-plugin": "^1.132.0",
"@uiw/react-heat-map": "^2.3.3",
"axios": "^1.14.0",
"class-variance-authority": "^0.7.1",
@@ -59,6 +58,7 @@
"recharts": "^3.8.1",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
+ "remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
"shadcn": "^4.1.2",
"sonner": "^2.0.7",
@@ -73,7 +73,7 @@
"@tailwindcss/typography": "^0.5.16",
"@tanstack/devtools-vite": "latest",
"@tanstack/eslint-config": "latest",
- "@tanstack/router-plugin": "latest",
+ "@tanstack/router-plugin": "1.167.12",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.6",
@@ -3595,6 +3595,64 @@
"node": ">=14.0.0"
}
},
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
+ "version": "1.8.1",
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.1.0",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
+ "version": "1.8.1",
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
+ "version": "1.1.0",
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.1.1",
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/core": "^1.7.1",
+ "@emnapi/runtime": "^1.7.1",
+ "@tybys/wasm-util": "^0.10.1"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
+ "version": "0.10.1",
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
+ "version": "2.8.1",
+ "inBundle": true,
+ "license": "0BSD",
+ "optional": true
+ },
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.2.2.tgz",
@@ -10527,6 +10585,20 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/mdast-util-newline-to-break": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-newline-to-break/-/mdast-util-newline-to-break-2.0.0.tgz",
+ "integrity": "sha512-MbgeFca0hLYIEx/2zGsszCSEJJ1JSCdiY5xQxRcLDDGa8EPvlLPupJ4DSajbMPAnC0je8jfb9TiUATnxxrHUog==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-find-and-replace": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/mdast-util-phrasing": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",
@@ -12689,6 +12761,21 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/remark-breaks": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/remark-breaks/-/remark-breaks-4.0.0.tgz",
+ "integrity": "sha512-IjEjJOkH4FuJvHZVIW0QCDWxcG96kCq7An/KVH2NfJe6rKZU2AsHeB3OEjPNRxi4QC34Xdx7I2KGYn6IpT7gxQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-newline-to-break": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/remark-cjk-friendly": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.0.1.tgz",
diff --git a/web-studio/package.json b/web-studio/package.json
index 81647098f..7aa6c95bd 100644
--- a/web-studio/package.json
+++ b/web-studio/package.json
@@ -48,7 +48,6 @@
"@tanstack/react-router": "latest",
"@tanstack/react-router-devtools": "latest",
"@tanstack/react-table": "^8.21.3",
- "@tanstack/router-plugin": "^1.132.0",
"@uiw/react-heat-map": "^2.3.3",
"axios": "^1.14.0",
"class-variance-authority": "^0.7.1",
@@ -69,6 +68,7 @@
"recharts": "^3.8.1",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
+ "remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
"shadcn": "^4.1.2",
"sonner": "^2.0.7",
@@ -83,7 +83,7 @@
"@tailwindcss/typography": "^0.5.16",
"@tanstack/devtools-vite": "latest",
"@tanstack/eslint-config": "latest",
- "@tanstack/router-plugin": "latest",
+ "@tanstack/router-plugin": "1.167.12",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.6",
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index 4d324b3b4..9ec011c3b 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -490,7 +490,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
>
<span
className={cn(
- 'absolute h-8 min-w-10 rounded-xl bg-foreground shadow-sm transition-transform duration-200 ease-in-out',
+ 'absolute h-8 min-w-10 rounded-xl bg-background shadow-sm transition-transform duration-200 ease-in-out',
currentLanguage === 'en' && 'translate-x-full',
)}
/>
@@ -504,7 +504,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
aria-pressed={isActive}
className={cn(
'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',
+ isActive && 'text-foreground',
)}
onClick={() => {
if (!isActive) {
diff --git a/web-studio/src/i18n/locales/en/activity.ts b/web-studio/src/i18n/locales/en/activity.ts
index 31c08e881..e3331ecc6 100644
--- a/web-studio/src/i18n/locales/en/activity.ts
+++ b/web-studio/src/i18n/locales/en/activity.ts
@@ -146,6 +146,10 @@ const activity = {
terminal: 'Terminal',
agent: 'Agent',
},
+ actionPanel: {
+ collapse: 'Collapse panel',
+ expand: 'Open panel',
+ },
addResource: {
title: 'Add resource',
description:
diff --git a/web-studio/src/i18n/locales/en/resources.ts b/web-studio/src/i18n/locales/en/resources.ts
index a88c0bff7..7516aa2e9 100644
--- a/web-studio/src/i18n/locales/en/resources.ts
+++ b/web-studio/src/i18n/locales/en/resources.ts
@@ -349,6 +349,10 @@ const resources = {
},
},
searchPalette: {
+ modes: {
+ name: 'files',
+ switchHint: 'switch mode',
+ },
ariaLabel: 'Search',
openContainingDirectory: 'Open containing directory',
placeholder: 'Search',
@@ -431,12 +435,11 @@ const resources = {
unsupportedBinary: 'Binary files do not support text preview.',
jsonl: {
collapse: 'Collapse',
- dialogMode: 'Dialog',
+ dialogMode: 'Dialog mode',
emptyJsonl: 'Empty JSONL.',
emptyMessage: 'Empty message',
expand: 'Expand',
noArguments: 'No arguments',
- rawMode: 'JSONL',
recordCount: '{{count}} record',
recordCount_other: '{{count}} records',
toolcall: 'toolcall',
diff --git a/web-studio/src/i18n/locales/zh-CN/activity.ts b/web-studio/src/i18n/locales/zh-CN/activity.ts
index 9299cfce3..e82cfbb35 100644
--- a/web-studio/src/i18n/locales/zh-CN/activity.ts
+++ b/web-studio/src/i18n/locales/zh-CN/activity.ts
@@ -139,6 +139,10 @@ const activity = {
terminal: '终端',
agent: 'Agent',
},
+ actionPanel: {
+ collapse: '收起面板',
+ expand: '展开面板',
+ },
addResource: {
title: '添加资源',
description: '添加完成后左侧上下文树会刷新,右侧终端可继续定位新资源。',
diff --git a/web-studio/src/i18n/locales/zh-CN/resources.ts b/web-studio/src/i18n/locales/zh-CN/resources.ts
index f4f3a63ea..a1785c323 100644
--- a/web-studio/src/i18n/locales/zh-CN/resources.ts
+++ b/web-studio/src/i18n/locales/zh-CN/resources.ts
@@ -330,6 +330,10 @@ const resources = {
},
},
searchPalette: {
+ modes: {
+ name: '文件名',
+ switchHint: '切换模式',
+ },
ariaLabel: '搜索',
openContainingDirectory: '打开所在目录',
placeholder: '搜索',
@@ -411,12 +415,11 @@ const resources = {
unsupportedBinary: '二进制文件不支持文本预览。',
jsonl: {
collapse: '收起',
- dialogMode: '对话',
+ dialogMode: '对话模式',
emptyJsonl: '空 JSONL。',
emptyMessage: '空消息',
expand: '展开',
noArguments: '无参数',
- rawMode: 'JSONL',
recordCount: '{{count}} 条记录',
recordCount_other: '{{count}} 条记录',
toolcall: '工具调用',
diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.ts
index f9c4e3ee8..d883864d5 100644
--- a/web-studio/src/routeTree.gen.ts
+++ b/web-studio/src/routeTree.gen.ts
@@ -9,50 +9,45 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
-import { Route as IndexRouteImport } from './routes/index'
-import { Route as HomeRouteRouteImport } from './routes/home/route'
-import { Route as MonitoringRouteRouteImport } from './routes/monitoring/route'
-import { Route as PlaygroundRouteRouteImport } from './routes/playground/route'
-import { Route as RequestLogsRouteRouteImport } from './routes/request-logs/route'
-import { Route as RetrievalRouteRouteImport } from './routes/retrieval/route'
-import { Route as SessionsRouteRouteImport } from './routes/sessions/route'
-import { Route as SettingsRouteRouteImport } from './routes/settings/route'
-import { Route as SkillsRouteRouteImport } from './routes/skills/route'
-import { Route as TasksRouteRouteImport } from './routes/tasks/route'
-import { Route as UsersRouteRouteImport } from './routes/users/route'
import { Route as WatchesRouteRouteImport } from './routes/watches/route'
-import { Route as OauthConsentRouteImport } from './routes/oauth/consent'
-import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'
+import { Route as UsersRouteRouteImport } from './routes/users/route'
+import { Route as TasksRouteRouteImport } from './routes/tasks/route'
+import { Route as SkillsRouteRouteImport } from './routes/skills/route'
+import { Route as SettingsRouteRouteImport } from './routes/settings/route'
+import { Route as SessionsRouteRouteImport } from './routes/sessions/route'
+import { Route as RetrievalRouteRouteImport } from './routes/retrieval/route'
+import { Route as RequestLogsRouteRouteImport } from './routes/request-logs/route'
+import { Route as PlaygroundRouteRouteImport } from './routes/playground/route'
+import { Route as MonitoringRouteRouteImport } from './routes/monitoring/route'
+import { Route as HomeRouteRouteImport } from './routes/home/route'
+import { Route as IndexRouteImport } from './routes/index'
import { Route as SessionsIndexRouteImport } from './routes/sessions/index'
+import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'
+import { Route as OauthConsentRouteImport } from './routes/oauth/consent'
-const IndexRoute = IndexRouteImport.update({
- id: '/',
- path: '/',
- getParentRoute: () => rootRouteImport,
-} as any)
-const HomeRouteRoute = HomeRouteRouteImport.update({
- id: '/home',
- path: '/home',
+const WatchesRouteRoute = WatchesRouteRouteImport.update({
+ id: '/watches',
+ path: '/watches',
getParentRoute: () => rootRouteImport,
} as any)
-const MonitoringRouteRoute = MonitoringRouteRouteImport.update({
- id: '/monitoring',
- path: '/monitoring',
+const UsersRouteRoute = UsersRouteRouteImport.update({
+ id: '/users',
+ path: '/users',
getParentRoute: () => rootRouteImport,
} as any)
-const PlaygroundRouteRoute = PlaygroundRouteRouteImport.update({
- id: '/playground',
- path: '/playground',
+const TasksRouteRoute = TasksRouteRouteImport.update({
+ id: '/tasks',
+ path: '/tasks',
getParentRoute: () => rootRouteImport,
} as any)
-const RequestLogsRouteRoute = RequestLogsRouteRouteImport.update({
- id: '/request-logs',
- path: '/request-logs',
+const SkillsRouteRoute = SkillsRouteRouteImport.update({
+ id: '/skills',
+ path: '/skills',
getParentRoute: () => rootRouteImport,
} as any)
-const RetrievalRouteRoute = RetrievalRouteRouteImport.update({
- id: '/retrieval',
- path: '/retrieval',
+const SettingsRouteRoute = SettingsRouteRouteImport.update({
+ id: '/settings',
+ path: '/settings',
getParentRoute: () => rootRouteImport,
} as any)
const SessionsRouteRoute = SessionsRouteRouteImport.update({
@@ -60,45 +55,50 @@ const SessionsRouteRoute = SessionsRouteRouteImport.update({
path: '/sessions',
getParentRoute: () => rootRouteImport,
} as any)
-const SettingsRouteRoute = SettingsRouteRouteImport.update({
- id: '/settings',
- path: '/settings',
+const RetrievalRouteRoute = RetrievalRouteRouteImport.update({
+ id: '/retrieval',
+ path: '/retrieval',
getParentRoute: () => rootRouteImport,
} as any)
-const SkillsRouteRoute = SkillsRouteRouteImport.update({
- id: '/skills',
- path: '/skills',
+const RequestLogsRouteRoute = RequestLogsRouteRouteImport.update({
+ id: '/request-logs',
+ path: '/request-logs',
getParentRoute: () => rootRouteImport,
} as any)
-const TasksRouteRoute = TasksRouteRouteImport.update({
- id: '/tasks',
- path: '/tasks',
+const PlaygroundRouteRoute = PlaygroundRouteRouteImport.update({
+ id: '/playground',
+ path: '/playground',
getParentRoute: () => rootRouteImport,
} as any)
-const UsersRouteRoute = UsersRouteRouteImport.update({
- id: '/users',
- path: '/users',
+const MonitoringRouteRoute = MonitoringRouteRouteImport.update({
+ id: '/monitoring',
+ path: '/monitoring',
getParentRoute: () => rootRouteImport,
} as any)
-const WatchesRouteRoute = WatchesRouteRouteImport.update({
- id: '/watches',
- path: '/watches',
+const HomeRouteRoute = HomeRouteRouteImport.update({
+ id: '/home',
+ path: '/home',
getParentRoute: () => rootRouteImport,
} as any)
-const OauthConsentRoute = OauthConsentRouteImport.update({
- id: '/oauth/consent',
- path: '/oauth/consent',
+const IndexRoute = IndexRouteImport.update({
+ id: '/',
+ path: '/',
getParentRoute: () => rootRouteImport,
} as any)
+const SessionsIndexRoute = SessionsIndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => SessionsRouteRoute,
+} as any)
const OauthVerifyRoute = OauthVerifyRouteImport.update({
id: '/oauth/verify',
path: '/oauth/verify',
getParentRoute: () => rootRouteImport,
} as any)
-const SessionsIndexRoute = SessionsIndexRouteImport.update({
- id: '/',
- path: '/',
- getParentRoute: () => SessionsRouteRoute,
+const OauthConsentRoute = OauthConsentRouteImport.update({
+ id: '/oauth/consent',
+ path: '/oauth/consent',
+ getParentRoute: () => rootRouteImport,
} as any)
export interface FileRoutesByFullPath {
@@ -224,46 +224,39 @@ export interface RootRouteChildren {
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
- '/': {
- id: '/'
- path: '/'
- fullPath: '/'
- preLoaderRoute: typeof IndexRouteImport
- parentRoute: typeof rootRouteImport
- }
- '/home': {
- id: '/home'
- path: '/home'
- fullPath: '/home'
- preLoaderRoute: typeof HomeRouteRouteImport
+ '/watches': {
+ id: '/watches'
+ path: '/watches'
+ fullPath: '/watches'
+ preLoaderRoute: typeof WatchesRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/monitoring': {
- id: '/monitoring'
- path: '/monitoring'
- fullPath: '/monitoring'
- preLoaderRoute: typeof MonitoringRouteRouteImport
+ '/users': {
+ id: '/users'
+ path: '/users'
+ fullPath: '/users'
+ preLoaderRoute: typeof UsersRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/playground': {
- id: '/playground'
- path: '/playground'
- fullPath: '/playground'
- preLoaderRoute: typeof PlaygroundRouteRouteImport
+ '/tasks': {
+ id: '/tasks'
+ path: '/tasks'
+ fullPath: '/tasks'
+ preLoaderRoute: typeof TasksRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/request-logs': {
- id: '/request-logs'
- path: '/request-logs'
- fullPath: '/request-logs'
- preLoaderRoute: typeof RequestLogsRouteRouteImport
+ '/skills': {
+ id: '/skills'
+ path: '/skills'
+ fullPath: '/skills'
+ preLoaderRoute: typeof SkillsRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/retrieval': {
- id: '/retrieval'
- path: '/retrieval'
- fullPath: '/retrieval'
- preLoaderRoute: typeof RetrievalRouteRouteImport
+ '/settings': {
+ id: '/settings'
+ path: '/settings'
+ fullPath: '/settings'
+ preLoaderRoute: typeof SettingsRouteRouteImport
parentRoute: typeof rootRouteImport
}
'/sessions': {
@@ -273,48 +266,55 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SessionsRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/settings': {
- id: '/settings'
- path: '/settings'
- fullPath: '/settings'
- preLoaderRoute: typeof SettingsRouteRouteImport
+ '/retrieval': {
+ id: '/retrieval'
+ path: '/retrieval'
+ fullPath: '/retrieval'
+ preLoaderRoute: typeof RetrievalRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/skills': {
- id: '/skills'
- path: '/skills'
- fullPath: '/skills'
- preLoaderRoute: typeof SkillsRouteRouteImport
+ '/request-logs': {
+ id: '/request-logs'
+ path: '/request-logs'
+ fullPath: '/request-logs'
+ preLoaderRoute: typeof RequestLogsRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/tasks': {
- id: '/tasks'
- path: '/tasks'
- fullPath: '/tasks'
- preLoaderRoute: typeof TasksRouteRouteImport
+ '/playground': {
+ id: '/playground'
+ path: '/playground'
+ fullPath: '/playground'
+ preLoaderRoute: typeof PlaygroundRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/users': {
- id: '/users'
- path: '/users'
- fullPath: '/users'
- preLoaderRoute: typeof UsersRouteRouteImport
+ '/monitoring': {
+ id: '/monitoring'
+ path: '/monitoring'
+ fullPath: '/monitoring'
+ preLoaderRoute: typeof MonitoringRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/watches': {
- id: '/watches'
- path: '/watches'
- fullPath: '/watches'
- preLoaderRoute: typeof WatchesRouteRouteImport
+ '/home': {
+ id: '/home'
+ path: '/home'
+ fullPath: '/home'
+ preLoaderRoute: typeof HomeRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/oauth/consent': {
- id: '/oauth/consent'
- path: '/oauth/consent'
- fullPath: '/oauth/consent'
- preLoaderRoute: typeof OauthConsentRouteImport
+ '/': {
+ id: '/'
+ path: '/'
+ fullPath: '/'
+ preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
+ '/sessions/': {
+ id: '/sessions/'
+ path: '/'
+ fullPath: '/sessions/'
+ preLoaderRoute: typeof SessionsIndexRouteImport
+ parentRoute: typeof SessionsRouteRoute
+ }
'/oauth/verify': {
id: '/oauth/verify'
path: '/oauth/verify'
@@ -322,12 +322,12 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof OauthVerifyRouteImport
parentRoute: typeof rootRouteImport
}
- '/sessions/': {
- id: '/sessions/'
- path: '/'
- fullPath: '/sessions/'
- preLoaderRoute: typeof SessionsIndexRouteImport
- parentRoute: typeof SessionsRouteRoute
+ '/oauth/consent': {
+ id: '/oauth/consent'
+ path: '/oauth/consent'
+ fullPath: '/oauth/consent'
+ preLoaderRoute: typeof OauthConsentRouteImport
+ parentRoute: typeof rootRouteImport
}
}
}
diff --git a/web-studio/src/routes/playground/-components/context-explorer.tsx b/web-studio/src/routes/playground/-components/context-explorer.tsx
index 2a41a6580..474f9f616 100644
--- a/web-studio/src/routes/playground/-components/context-explorer.tsx
+++ b/web-studio/src/routes/playground/-components/context-explorer.tsx
@@ -496,7 +496,7 @@ export function PanelTab({
className={cn(
'inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-xs font-medium transition-colors',
active
- ? 'bg-foreground text-background shadow-sm'
+ ? 'bg-muted text-foreground'
: 'text-muted-foreground hover:bg-muted hover:text-foreground',
)}
onClick={onClick}
diff --git a/web-studio/src/routes/playground/-components/terminal-panel.tsx b/web-studio/src/routes/playground/-components/terminal-panel.tsx
index 8c6ab6048..09aac2867 100644
--- a/web-studio/src/routes/playground/-components/terminal-panel.tsx
+++ b/web-studio/src/routes/playground/-components/terminal-panel.tsx
@@ -1379,12 +1379,6 @@ export function TerminalPanel({
{toolbarContainer
? createPortal(
<>
- <span
- className="min-w-0 max-w-40 truncate rounded-md border bg-muted/40 px-2 py-1 font-mono text-[11px] text-foreground"
- title={currentUri}
- >
- {t('terminal.scopeLabel', { uri: currentUri })}
- </span>
<Button
type="button"
variant="ghost"
@@ -1447,6 +1441,12 @@ export function TerminalPanel({
void runCommand(command)
}}
>
+ <span
+ className="max-w-[45%] shrink-0 truncate font-mono text-[11px] text-muted-foreground"
+ title={t('terminal.scopeLabel', { uri: currentUri })}
+ >
+ {currentUri}
+ </span>
<input
ref={inputRef}
value={command}
diff --git a/web-studio/src/routes/playground/-lib/constants.ts b/web-studio/src/routes/playground/-lib/constants.ts
index 5238c63d0..1c00d57a9 100644
--- a/web-studio/src/routes/playground/-lib/constants.ts
+++ b/web-studio/src/routes/playground/-lib/constants.ts
@@ -5,6 +5,8 @@ export const PLAYGROUND_LEFT_WIDTH_STORAGE_KEY =
'openviking.playground.leftWidth'
export const PLAYGROUND_RIGHT_WIDTH_STORAGE_KEY =
'openviking.playground.rightWidth'
+export const PLAYGROUND_RIGHT_COLLAPSED_STORAGE_KEY =
+ 'openviking.playground.rightCollapsed'
export const PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY =
'openviking.playground.agentSessions'
export const PLAYGROUND_EXPANDED_URIS_STORAGE_KEY =
diff --git a/web-studio/src/routes/playground/route.tsx b/web-studio/src/routes/playground/route.tsx
index bd7245904..af9fefdda 100644
--- a/web-studio/src/routes/playground/route.tsx
+++ b/web-studio/src/routes/playground/route.tsx
@@ -6,6 +6,8 @@ import {
ArrowLeftIcon,
BotIcon,
ClipboardIcon,
+ PanelRightCloseIcon,
+ PanelRightOpenIcon,
TerminalIcon,
} from 'lucide-react'
import { toast } from 'sonner'
@@ -54,6 +56,7 @@ import {
PLAYGROUND_LEFT_WIDTH,
PLAYGROUND_LEFT_WIDTH_STORAGE_KEY,
PLAYGROUND_MAIN_MIN_WIDTH,
+ PLAYGROUND_RIGHT_COLLAPSED_STORAGE_KEY,
PLAYGROUND_RIGHT_WIDTH,
PLAYGROUND_RIGHT_WIDTH_STORAGE_KEY,
} from './-lib/constants'
@@ -155,6 +158,23 @@ function PlaygroundWorkbench() {
const [resizingPane, setResizingPane] = useState<'context' | 'action' | null>(
null,
)
+ const [rightCollapsed, setRightCollapsed] = useState(
+ () =>
+ typeof window !== 'undefined' &&
+ window.localStorage.getItem(PLAYGROUND_RIGHT_COLLAPSED_STORAGE_KEY) ===
+ '1',
+ )
+ const toggleRightCollapsed = useCallback(
+ () =>
+ setRightCollapsed((collapsed) => {
+ window.localStorage.setItem(
+ PLAYGROUND_RIGHT_COLLAPSED_STORAGE_KEY,
+ collapsed ? '0' : '1',
+ )
+ return !collapsed
+ }),
+ [],
+ )
const isDraggingPaneRef = useRef(false)
const activeResizeTeardownRef = useRef<(() => void) | null>(null)
const leftWidthRef = useRef(leftWidth)
@@ -385,6 +405,13 @@ function PlaygroundWorkbench() {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
event.preventDefault()
setFindPaletteOpen((open) => !open)
+ return
+ }
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'f') {
+ // Let CodeMirror keep its own in-file search when it has focus.
+ if ((event.target as HTMLElement | null)?.closest('.cm-editor')) return
+ event.preventDefault()
+ setFindPaletteOpen(true)
}
}
@@ -590,6 +617,19 @@ function PlaygroundWorkbench() {
<BotIcon className="size-4" />
</Button>
</div>
+ {rightCollapsed ? (
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ className="hidden shrink-0 lg:inline-flex"
+ title={t('actionPanel.expand')}
+ aria-label={t('actionPanel.expand')}
+ onClick={toggleRightCollapsed}
+ >
+ <PanelRightOpenIcon className="size-4" />
+ </Button>
+ ) : null}
</div>
<div className="min-h-0 flex-1">
<LazyFilePreview
@@ -601,18 +641,21 @@ function PlaygroundWorkbench() {
/>
</div>
</main>
- <PlaygroundResizeHandle
- active={resizingPane === 'action'}
- label={t('resizeAction')}
- onPointerDown={(event) => handleResizeStart('action', event)}
- />
+ {!rightCollapsed ? (
+ <PlaygroundResizeHandle
+ active={resizingPane === 'action'}
+ label={t('resizeAction')}
+ onPointerDown={(event) => handleResizeStart('action', event)}
+ />
+ ) : null}
- {!isCompactLayout ? (
+ {!isCompactLayout && !rightCollapsed ? (
<aside className="hidden min-h-0 min-w-0 flex-col bg-muted/15 lg:flex lg:w-[var(--playground-right-width)] lg:min-w-[var(--playground-right-width)]">
<PlaygroundActionPanel
activePanel={activePanel}
currentUri={currentUri}
entries={entries}
+ onCollapse={toggleRightCollapsed}
onOpenAddResource={() => setUploadDialogOpen(true)}
onOpenResource={revealResource}
onPanelChange={handlePanelChange}
@@ -707,6 +750,7 @@ function PlaygroundActionPanel({
activePanel,
currentUri,
entries,
+ onCollapse,
onOpenAddResource,
onOpenResource,
onPanelChange,
@@ -717,6 +761,7 @@ function PlaygroundActionPanel({
activePanel: PlaygroundPanel
currentUri: string
entries: VikingFsEntry[]
+ onCollapse: () => void
onOpenAddResource: () => void
onOpenResource: ResourceOpenHandler
onPanelChange: (panel: PlaygroundPanel) => void
@@ -739,6 +784,17 @@ function PlaygroundActionPanel({
ref={setToolbarContainer}
className="ml-auto flex min-w-0 items-center gap-1"
/>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ className="shrink-0"
+ title={t('actionPanel.collapse')}
+ aria-label={t('actionPanel.collapse')}
+ onClick={onCollapse}
+ >
+ <PanelRightCloseIcon className="size-4" />
+ </Button>
</div>
<PlaygroundActionContent
diff --git a/web-studio/src/routes/resources/-components/file-preview.test.tsx b/web-studio/src/routes/resources/-components/file-preview.test.tsx
index 4ed1ca967..f56188afe 100644
--- a/web-studio/src/routes/resources/-components/file-preview.test.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.test.tsx
@@ -1,12 +1,21 @@
// @vitest-environment jsdom
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import type { PropsWithChildren } from 'react'
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { VikingFsEntry } from '../-types/viking-fm'
-import { FilePreview } from './file-preview'
+import {
+ FilePreview,
+ getJsonlMessage,
+ normalizeJsonlDisplayText,
+ parseJsonlRecords,
+} from './file-preview'
+
+const previewState = vi.hoisted(() => ({
+ override: null as { content: string; fileType: string } | null,
+}))
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
@@ -39,6 +48,7 @@ vi.mock('../-hooks/viking-fm', () => ({
content: '[Target](./target.md)',
fileType: 'markdown',
shouldAutoRead: true,
+ ...(previewState.override ?? {}),
},
refetch: vi.fn(),
}),
@@ -195,3 +205,445 @@ describe('FilePreview Markdown links', () => {
expect(onNavigate).not.toHaveBeenCalled()
})
})
+
+describe('normalizeJsonlDisplayText', () => {
+ it('restores encoded and carriage-return line breaks', () => {
+ expect(normalizeJsonlDisplayText('a↵b')).toBe('a\nb')
+ expect(normalizeJsonlDisplayText('a⏎b')).toBe('a\nb')
+ expect(normalizeJsonlDisplayText('a\r\nb')).toBe('a\nb')
+ expect(normalizeJsonlDisplayText('a\rb')).toBe('a\nb')
+ })
+
+ it('leaves plain text untouched', () => {
+ expect(normalizeJsonlDisplayText('a\nb')).toBe('a\nb')
+ expect(normalizeJsonlDisplayText('plain text')).toBe('plain text')
+ })
+})
+
+function classify(...lines: Array<string>) {
+ return parseJsonlRecords(lines.join('\n')).map(getJsonlMessage)
+}
+
+describe('JSONL message classification', () => {
+ it('classifies a plain-text user message from the OpenViking parts shape', () => {
+ const [message] = classify(
+ JSON.stringify({
+ created_at: '2026-08-04T12:00:00Z',
+ id: 'm1',
+ parts: [{ text: 'hello there', type: 'text' }],
+ role: 'user',
+ }),
+ )
+
+ expect(message.role).toBe('user')
+ expect(message.label).toBe('user')
+ expect(message.toolShape).toBe('none')
+ expect(message.parts).toEqual([{ kind: 'text', text: 'hello there' }])
+ })
+
+ it('classifies a plain-text assistant message', () => {
+ const [message] = classify(
+ JSON.stringify({
+ id: 'm2',
+ parts: [{ text: 'sure thing', type: 'text' }],
+ role: 'assistant',
+ }),
+ )
+
+ expect(message.role).toBe('assistant')
+ expect(message.toolShape).toBe('none')
+ expect(message.parts).toEqual([{ kind: 'text', text: 'sure thing' }])
+ })
+
+ it('keeps text and tool_use as separate parts on one assistant message', () => {
+ const [message] = classify(
+ JSON.stringify({
+ message: {
+ content: [
+ { text: 'Let me read that file.', type: 'text' },
+ {
+ id: 'call_1',
+ input: { file_path: '/tmp/a.txt' },
+ name: 'Read',
+ type: 'tool_use',
+ },
+ ],
+ role: 'assistant',
+ },
+ type: 'assistant',
+ uuid: 'u1',
+ }),
+ )
+
+ expect(message.role).toBe('assistant')
+ // A message carrying its own text is styled by role, not as a tool card.
+ expect(message.toolShape).toBe('none')
+ expect(message.parts).toEqual([
+ { kind: 'text', text: 'Let me read that file.' },
+ {
+ input: { file_path: '/tmp/a.txt' },
+ kind: 'tool-call',
+ toolName: 'Read',
+ },
+ ])
+ const textParts = message.parts.filter((part) => part.kind === 'text')
+ expect(textParts).toHaveLength(1)
+ for (const part of textParts) {
+ expect(part.text).not.toContain('[tool:')
+ }
+ })
+
+ it('classifies a tool_use-only assistant message as a tool call', () => {
+ const [message] = classify(
+ JSON.stringify({
+ message: {
+ content: [{ id: 'c', input: {}, name: 'Bash', type: 'tool_use' }],
+ role: 'assistant',
+ },
+ type: 'assistant',
+ }),
+ )
+
+ expect(message.role).toBe('assistant')
+ expect(message.toolShape).toBe('call')
+ expect(message.label).toBe('assistant')
+ })
+
+ it('classifies a tool_result carried by a user message', () => {
+ const [message] = classify(
+ JSON.stringify({
+ message: {
+ content: [
+ {
+ content: 'file contents',
+ tool_use_id: 'call_1',
+ type: 'tool_result',
+ },
+ ],
+ role: 'user',
+ },
+ type: 'user',
+ }),
+ )
+
+ // tool-result wins over role=user so the dashed tool-result card is kept.
+ expect(message.role).toBe('user')
+ expect(message.toolShape).toBe('result')
+ expect(message.label).toBe('tool-result')
+ expect(message.parts).toEqual([
+ { kind: 'tool-result', text: 'file contents', toolName: '' },
+ ])
+ })
+
+ it('flattens a tool_result whose content is a list of text blocks', () => {
+ const [message] = classify(
+ JSON.stringify({
+ message: {
+ content: [
+ {
+ content: [
+ { text: 'line one', type: 'text' },
+ { text: 'line two', type: 'text' },
+ ],
+ type: 'tool_result',
+ },
+ ],
+ role: 'user',
+ },
+ }),
+ )
+
+ expect(message.parts).toEqual([
+ { kind: 'tool-result', text: 'line one\nline two', toolName: '' },
+ ])
+ })
+
+ it('expands an OpenViking tool part into a call and its output', () => {
+ const [message] = classify(
+ JSON.stringify({
+ parts: [
+ {
+ tool_input: { pattern: '*.md' },
+ tool_name: 'glob',
+ tool_output: 'a.md\nb.md',
+ type: 'tool',
+ },
+ ],
+ role: 'assistant',
+ }),
+ )
+
+ expect(message.toolShape).toBe('call')
+ expect(message.parts).toEqual([
+ { input: { pattern: '*.md' }, kind: 'tool-call', toolName: 'glob' },
+ { kind: 'tool-result', text: 'a.md\nb.md', toolName: 'glob' },
+ ])
+ })
+
+ it('classifies an OpenViking tool part with only an output as a result', () => {
+ // Shape written by the claude-code peer: the result lands as its own
+ // role=user record with no `tool_input` at all.
+ const [message] = classify(
+ JSON.stringify({
+ id: 'msg_dca71c5d',
+ parts: [
+ {
+ tool_name: 'Bash',
+ tool_output: '33 failed, 392 passed',
+ tool_status: 'completed',
+ type: 'tool',
+ },
+ ],
+ role: 'user',
+ }),
+ )
+
+ expect(message.parts).toEqual([
+ { kind: 'tool-result', text: '33 failed, 392 passed', toolName: 'Bash' },
+ ])
+ expect(message.toolShape).toBe('result')
+ expect(message.label).toBe('tool-result')
+ })
+
+ it('treats a null tool_input with an output as a result-only part', () => {
+ const [message] = classify(
+ JSON.stringify({
+ parts: [
+ {
+ tool_input: null,
+ tool_name: 'Bash',
+ tool_output: 'ok',
+ type: 'tool',
+ },
+ ],
+ role: 'user',
+ }),
+ )
+
+ expect(message.parts).toEqual([
+ { kind: 'tool-result', text: 'ok', toolName: 'Bash' },
+ ])
+ expect(message.toolShape).toBe('result')
+ })
+
+ it('keeps a call part for a tool part that has no output yet', () => {
+ const [message] = classify(
+ JSON.stringify({
+ parts: [{ tool_name: 'Bash', type: 'tool' }],
+ role: 'assistant',
+ }),
+ )
+
+ expect(message.toolShape).toBe('call')
+ expect(message.parts).toEqual([
+ { input: {}, kind: 'tool-call', toolName: 'Bash' },
+ ])
+ })
+
+ it('reads the role and timestamp from a nested message field', () => {
+ const [message] = classify(
+ JSON.stringify({
+ message: { content: 'nested body', role: 'assistant' },
+ timestamp: '2026-08-04T12:00:00Z',
+ uuid: 'u9',
+ }),
+ )
+
+ expect(message.role).toBe('assistant')
+ expect(message.id).toBe('u9')
+ expect(message.time).toBe('2026-08-04T12:00:00Z')
+ expect(message.parts).toEqual([{ kind: 'text', text: 'nested body' }])
+ })
+
+ it('treats a plain string content as a single text part', () => {
+ const [message] = classify(
+ JSON.stringify({ content: 'just a string', role: 'user' }),
+ )
+
+ expect(message.toolShape).toBe('none')
+ expect(message.parts).toEqual([{ kind: 'text', text: 'just a string' }])
+ })
+
+ it('falls back to a raw part for an unknown record shape', () => {
+ const [message] = classify(
+ JSON.stringify({ event: 'ping', type: 'system' }),
+ )
+
+ expect(message.role).toBe('other')
+ expect(message.parts).toHaveLength(1)
+ expect(message.parts[0].kind).toBe('raw')
+ })
+
+ it('marks an unparsable line as invalid and keeps it verbatim', () => {
+ const [message] = classify('{not json')
+
+ expect(message.role).toBe('invalid')
+ expect(message.label).toBe('invalid')
+ expect(message.parts).toEqual([{ kind: 'raw', text: '{not json' }])
+ })
+
+ it('skips blank lines and numbers records by their source line', () => {
+ const messages = classify(
+ JSON.stringify({ content: 'one', role: 'user' }),
+ '',
+ JSON.stringify({ content: 'two', role: 'assistant' }),
+ )
+
+ expect(messages).toHaveLength(2)
+ expect(messages.map((message) => message.lineNo)).toEqual([1, 3])
+ })
+})
+
+describe('FilePreview JSONL rendering', () => {
+ beforeEach(() => {
+ // Auto-cleanup is off in this setup, so each render starts from a bare DOM.
+ cleanup()
+ // This environment ships a non-functional window.localStorage.
+ vi.stubGlobal('localStorage', {
+ getItem: () => null,
+ setItem: () => undefined,
+ })
+ })
+
+ afterEach(() => {
+ previewState.override = null
+ vi.unstubAllGlobals()
+ })
+
+ it('renders text and tool_use of one assistant message separately', () => {
+ previewState.override = {
+ content: JSON.stringify({
+ message: {
+ content: [
+ { text: 'Let me read that file.', type: 'text' },
+ {
+ id: 'call_1',
+ input: { file_path: '/tmp/a.txt' },
+ name: 'Read',
+ type: 'tool_use',
+ },
+ ],
+ role: 'assistant',
+ },
+ type: 'assistant',
+ }),
+ fileType: 'jsonl',
+ }
+
+ const { container } = renderPreview(file, vi.fn())
+
+ expect(screen.getByText('Let me read that file.')).toBeTruthy()
+ // The tool name is a badge, and the input renders as JSON, not as a
+ // "[tool: ...]" prefix smuggled into the message body.
+ expect(screen.getByText('Read')).toBeTruthy()
+ expect(container.textContent).toContain('"file_path"')
+ expect(container.textContent).not.toContain('[tool:')
+ })
+
+ it('renders a result-only tool record without an empty input block', () => {
+ previewState.override = {
+ content: JSON.stringify({
+ parts: [
+ {
+ tool_name: 'Bash',
+ tool_output: '33 failed, 392 passed',
+ tool_status: 'completed',
+ type: 'tool',
+ },
+ ],
+ role: 'user',
+ }),
+ fileType: 'jsonl',
+ }
+
+ const { container } = renderPreview(file, vi.fn())
+
+ expect(container.textContent).not.toContain('{}')
+ // The tool name badge survives on a card that carries only the result.
+ expect(screen.getByText('Bash')).toBeTruthy()
+ expect(screen.getByText('33 failed, 392 passed')).toBeTruthy()
+ expect(screen.getByText('tool-result')).toBeTruthy()
+ })
+
+ it('shows the no-arguments placeholder for an empty tool_use input', () => {
+ previewState.override = {
+ content: JSON.stringify({
+ message: {
+ content: [{ id: 'c', input: {}, name: 'Bash', type: 'tool_use' }],
+ role: 'assistant',
+ },
+ type: 'assistant',
+ }),
+ fileType: 'jsonl',
+ }
+
+ const { container } = renderPreview(file, vi.fn())
+
+ expect(container.textContent).not.toContain('{}')
+ expect(screen.getByText('filePreview.jsonl.noArguments')).toBeTruthy()
+ })
+
+ it('keeps the dialog-mode label and the tool toggle in both modes', () => {
+ previewState.override = {
+ content: JSON.stringify({
+ parts: [
+ { tool_name: 'Bash', tool_output: 'done', type: 'tool' },
+ { text: 'hi', type: 'text' },
+ ],
+ role: 'assistant',
+ }),
+ fileType: 'jsonl',
+ }
+
+ const { container } = renderPreview(file, vi.fn())
+ const modeToggle = () => {
+ const boxes = container.querySelectorAll('input[type="checkbox"]')
+ return boxes[boxes.length - 1]
+ }
+
+ expect(screen.getByText('filePreview.jsonl.dialogMode')).toBeTruthy()
+ expect(screen.getByText('filePreview.jsonl.toolcall')).toBeTruthy()
+
+ fireEvent.click(modeToggle())
+
+ expect(screen.getByText('filePreview.jsonl.dialogMode')).toBeTruthy()
+ expect(screen.queryByText('filePreview.jsonl.rawMode')).toBeNull()
+ // The tool toggle stays reachable once the raw list is showing.
+ expect(screen.getByText('filePreview.jsonl.toolcall')).toBeTruthy()
+ })
+
+ it('hides tool-only records in raw mode when tool calls are off', () => {
+ vi.stubGlobal('localStorage', {
+ getItem: () => 'false',
+ setItem: () => undefined,
+ })
+ previewState.override = {
+ content: [
+ JSON.stringify({
+ parts: [{ text: 'hello there', type: 'text' }],
+ role: 'user',
+ }),
+ JSON.stringify({
+ parts: [
+ { tool_name: 'Bash', tool_output: 'tool output', type: 'tool' },
+ ],
+ role: 'user',
+ }),
+ ].join('\n'),
+ fileType: 'jsonl',
+ }
+
+ const { container } = renderPreview(file, vi.fn())
+
+ // Dialog mode: the tool-only message drops out entirely.
+ expect(screen.queryByText('Bash')).toBeNull()
+ expect(screen.getByText('hello there')).toBeTruthy()
+
+ const boxes = container.querySelectorAll('input[type="checkbox"]')
+ fireEvent.click(boxes[boxes.length - 1])
+
+ // Raw mode: line 1 still listed, the tool-only line 2 is gone.
+ expect(screen.getByText('1')).toBeTruthy()
+ expect(screen.queryByText('2')).toBeNull()
+ })
+})
diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsx
index 953a56024..b625c2183 100644
--- a/web-studio/src/routes/resources/-components/file-preview.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.tsx
@@ -5,6 +5,7 @@ import hljs from 'highlight.js/lib/core'
import ReactMarkdown, { defaultUrlTransform } from 'react-markdown'
import rehypeRaw from 'rehype-raw'
import rehypeSanitize from 'rehype-sanitize'
+import remarkBreaks from 'remark-breaks'
import remarkGfm from 'remark-gfm'
import { X, Pencil, Save, XCircle, Loader2 } from 'lucide-react'
import { useTranslation } from 'react-i18next'
@@ -151,15 +152,22 @@ type JsonlRecord = {
parsed: unknown
}
+/** One renderable unit of a JSONL message, classified by its structural type. */
+type JsonlPart =
+ | { input: unknown; kind: 'tool-call'; toolName: string }
+ | { kind: 'raw'; text: string }
+ | { kind: 'text'; text: string }
+ | { kind: 'tool-result'; text: string; toolName: string }
+
type JsonlMessage = {
id: string
- kind: 'agent' | 'assistant' | 'invalid' | 'other' | 'tool-result' | 'user'
label: string
lineNo: number
+ parts: JsonlPart[]
+ role: 'agent' | 'assistant' | 'invalid' | 'other' | 'user'
roleId: string
- text: string
time: string
- toolName: string
+ toolShape: 'call' | 'none' | 'result'
}
function toDownloadUrl(vikingUri: string): string {
@@ -719,7 +727,7 @@ const markdownComponents = {
),
}
-function parseJsonlRecords(text: string): JsonlRecord[] {
+export function parseJsonlRecords(text: string): JsonlRecord[] {
return text
.replace(/\r\n/g, '\n')
.split('\n')
@@ -742,90 +750,194 @@ function parseJsonlRecords(text: string): JsonlRecord[] {
})
}
-function formatJsonlPart(part: unknown): string {
- if (typeof part === 'string') return part
- if (!isRecord(part)) return JSON.stringify(part)
+export function normalizeJsonlDisplayText(text: string): string {
+ return text.replace(/↵|⏎|\r\n?/g, '\n')
+}
- if (typeof part.text === 'string') return part.text
+/** Flatten a tool_result `content` (string, or a list of text blocks) to text. */
+function jsonlContentToText(value: unknown): string {
+ if (typeof value === 'string') return value
+ if (Array.isArray(value)) {
+ return value
+ .map((item) =>
+ typeof item === 'string'
+ ? item
+ : isRecord(item) && typeof item.text === 'string'
+ ? item.text
+ : JSON.stringify(item, null, 2),
+ )
+ .join('\n')
+ }
+ if (value === undefined || value === null) return ''
+ return JSON.stringify(value, null, 2)
+}
+
+/**
+ * Classify one content entry by its structural `type` field, never by a
+ * rendered string prefix. Covers the Anthropic transcript shape
+ * (`text` / `tool_use` / `tool_result`) and the OpenViking parts shape
+ * (`text` / `tool`, see openviking/message/part.py). An OpenViking `tool`
+ * part carries both the call and its output, so it expands to two entries.
+ */
+function toJsonlParts(part: unknown): JsonlPart[] {
+ if (typeof part === 'string') return [{ kind: 'text', text: part }]
+ if (!isRecord(part)) return [{ kind: 'raw', text: JSON.stringify(part) }]
+
+ const type = String(part.type ?? '')
+
+ if (type === 'tool_use') {
+ return [
+ {
+ input: part.input ?? part.arguments ?? {},
+ kind: 'tool-call',
+ toolName: typeof part.name === 'string' ? part.name : 'tool',
+ },
+ ]
+ }
- if (part.type === 'tool_use') {
- const name = typeof part.name === 'string' ? part.name : 'tool'
- const input = part.input ?? part.arguments ?? {}
- return `[tool: ${name}]\n${JSON.stringify(input, null, 2)}`
+ if (type === 'tool_result') {
+ return [
+ {
+ kind: 'tool-result',
+ text: jsonlContentToText(part.content ?? part.result ?? ''),
+ toolName: '',
+ },
+ ]
}
- if (part.type === 'tool_result') {
- const content = part.content ?? part.result ?? ''
- return `[tool result]\n${
- typeof content === 'string' ? content : JSON.stringify(content, null, 2)
- }`
+ if (type === 'tool') {
+ const toolName = typeof part.tool_name === 'string' ? part.tool_name : ''
+ const output = typeof part.tool_output === 'string' ? part.tool_output : ''
+ // A tool result arrives as its own record with `tool_output` and no
+ // `tool_input` (the call was logged on the preceding message). Inventing an
+ // empty call part there would classify the record as a call and print `{}`.
+ const hasInput =
+ isRecord(part.tool_input) && Object.keys(part.tool_input).length > 0
+ const parts: JsonlPart[] = []
+ if (hasInput || !output) {
+ parts.push({ input: part.tool_input ?? {}, kind: 'tool-call', toolName })
+ }
+ if (output) parts.push({ kind: 'tool-result', text: output, toolName })
+ return parts
}
+ if (type === 'text' || typeof part.text === 'string') {
+ return [
+ { kind: 'text', text: typeof part.text === 'string' ? part.text : '' },
+ ]
+ }
+
+ // Unknown part type: dump it verbatim. The `[type]` tag here is display-only
+ // and is never parsed back into a classification.
const payload = { ...part }
delete payload.type
- const type = String(part.type || 'part')
const body = Object.keys(payload).length
? JSON.stringify(payload, null, 2)
: ''
- return body ? `[${type}]\n${body}` : `[${type}]`
+ const label = type || 'part'
+ return [{ kind: 'raw', text: body ? `[${label}]\n${body}` : `[${label}]` }]
}
-function stringifyJsonlContent(value: unknown): string {
- if (typeof value === 'string') return value
- if (Array.isArray(value)) return value.map(formatJsonlPart).join('\n\n')
- if (value === undefined || value === null) return ''
- return JSON.stringify(value, null, 2)
+function toJsonlMessageParts(content: unknown): JsonlPart[] {
+ if (typeof content === 'string') {
+ return content ? [{ kind: 'text', text: content }] : []
+ }
+ if (Array.isArray(content)) return content.flatMap(toJsonlParts)
+ if (content === undefined || content === null) return []
+ return [{ kind: 'raw', text: JSON.stringify(content, null, 2) }]
+}
+
+export function hasJsonlToolPart(parts: JsonlPart[]): boolean {
+ return parts.some(
+ (part) => part.kind === 'tool-call' || part.kind === 'tool-result',
+ )
+}
+
+/**
+ * How the card should be styled. A message counts as tool-shaped only when it
+ * carries no text of its own: an assistant turn holding both `text` and
+ * `tool_use` is styled as a plain assistant message, because the text is the
+ * readable content and the calls are an aside. Pure `tool_result` messages
+ * (which arrive with role=user in Anthropic transcripts) keep the dashed
+ * tool-result look, so the tool-result check has to win over the role.
+ */
+function getJsonlToolShape(parts: JsonlPart[]): JsonlMessage['toolShape'] {
+ if (parts.some((part) => part.kind === 'text')) return 'none'
+ if (parts.some((part) => part.kind === 'tool-call')) return 'call'
+ if (parts.some((part) => part.kind === 'tool-result')) return 'result'
+ return 'none'
}
-function getJsonlMessage(record: JsonlRecord): JsonlMessage {
+export function getJsonlMessage(record: JsonlRecord): JsonlMessage {
const { error, index, line, parsed } = record
if (error || !isRecord(parsed)) {
return {
id: '',
- kind: 'invalid',
label: 'invalid',
lineNo: index + 1,
+ parts: [{ kind: 'raw', text: line }],
+ role: 'invalid',
roleId: '',
- text: line,
time: '',
- toolName: '',
+ toolShape: 'none',
}
}
const nestedMessage = isRecord(parsed.message) ? parsed.message : null
const source = nestedMessage ?? parsed
- const role = String(source.role ?? parsed.role ?? parsed.type ?? 'message')
+ const rawRole = String(source.role ?? parsed.role ?? parsed.type ?? 'message')
.trim()
.toLowerCase()
const content =
source.content ?? source.parts ?? parsed.parts ?? parsed.content ?? parsed
- const text = stringifyJsonlContent(content)
- const toolCall = text.match(/^\[tool:\s*([^\]]+)\]/)
- const toolResult = /^\[tool result\]/.test(text)
- const kind = toolResult
- ? 'tool-result'
- : role === 'user'
- ? 'user'
- : role === 'assistant' || role === 'agent'
- ? role
- : 'other'
+ const parts = toJsonlMessageParts(content)
+ const toolShape = getJsonlToolShape(parts)
return {
id: String(parsed.uuid ?? parsed.id ?? source.id ?? ''),
- kind,
- label: toolResult ? 'tool-result' : role,
+ label: toolShape === 'result' ? 'tool-result' : rawRole,
lineNo: index + 1,
+ parts,
+ role:
+ rawRole === 'user'
+ ? 'user'
+ : rawRole === 'assistant' || rawRole === 'agent'
+ ? rawRole
+ : 'other',
roleId: String(parsed.peer_id ?? source.peer_id ?? ''),
- text,
time: String(
parsed.timestamp ?? parsed.created_at ?? source.created_at ?? '',
),
- toolName: toolCall?.[1] ?? '',
+ toolShape,
}
}
-function isJsonlMarkdownMessage(kind: JsonlMessage['kind']): boolean {
- return kind === 'assistant' || kind === 'agent' || kind === 'user'
+function isJsonlMarkdownMessage(role: JsonlMessage['role']): boolean {
+ return role === 'assistant' || role === 'agent' || role === 'user'
+}
+
+/** Trim text parts against a shared character budget; tool parts pass through. */
+function collapseJsonlParts(parts: JsonlPart[], limit: number): JsonlPart[] {
+ let budget = limit
+ const collapsed: JsonlPart[] = []
+ for (const part of parts) {
+ if (part.kind !== 'text') {
+ collapsed.push(part)
+ continue
+ }
+ if (budget <= 0) continue
+ if (part.text.length <= budget) {
+ collapsed.push(part)
+ budget -= part.text.length
+ continue
+ }
+ collapsed.push({
+ kind: 'text',
+ text: `${part.text.slice(0, budget).trimEnd()}...`,
+ })
+ budget = 0
+ }
+ return collapsed
}
function formatJsonlTime(value: string): string {
@@ -896,25 +1008,25 @@ function JsonlRawRow({ record }: { record: JsonlRecord }) {
)
}
-function JsonlToolBody({ text, toolName }: { text: string; toolName: string }) {
+function JsonlToolBody({ input }: { input: unknown }) {
const { t } = useTranslation('resources')
- const afterTag = text.replace(/^\[tool:\s*[^\]]+\]\s*/, '')
- const parsed = useMemo(() => {
- if (!toolName || !afterTag.trim()) return null
- try {
- return JSON.parse(afterTag) as unknown
- } catch {
- return null
- }
- }, [afterTag, toolName])
-
- return parsed ? (
+ // The input is already structured, so no normalization and no re-parsing.
+ const text =
+ input === undefined ||
+ input === null ||
+ (isRecord(input) && Object.keys(input).length === 0)
+ ? ''
+ : typeof input === 'string'
+ ? input
+ : JSON.stringify(input, null, 2)
+
+ return text ? (
<pre className="max-h-96 overflow-auto rounded border bg-muted/30 p-2 text-xs leading-5">
- {JSON.stringify(parsed, null, 2)}
+ {text}
</pre>
) : (
<pre className="whitespace-pre-wrap break-words text-xs leading-5">
- {afterTag || t('filePreview.jsonl.noArguments')}
+ {t('filePreview.jsonl.noArguments')}
</pre>
)
}
@@ -924,7 +1036,7 @@ function JsonlMarkdownBody({ content }: { content: string }) {
return (
<div className="prose prose-sm max-w-none break-words dark:prose-invert dark:prose-pre:bg-muted-foreground/20">
<ReactMarkdown
- remarkPlugins={[remarkGfm]}
+ remarkPlugins={[remarkGfm, remarkBreaks]}
components={markdownComponents}
>
{content || t('filePreview.jsonl.emptyMessage')}
@@ -933,25 +1045,82 @@ function JsonlMarkdownBody({ content }: { content: string }) {
)
}
-function JsonlMessageCard({ record }: { record: JsonlRecord }) {
+/**
+ * Render one part by its kind: text goes through Markdown (for roles that get
+ * Markdown at all), a tool call shows its structured input as JSON, everything
+ * else falls back to a `pre`. Only free text is normalized — a tool input is a
+ * structured object, and raw dumps are already JSON.
+ */
+function JsonlPartBody({
+ markdown,
+ part,
+}: {
+ markdown: boolean
+ part: JsonlPart
+}) {
+ const { t } = useTranslation('resources')
+ if (part.kind === 'tool-call') return <JsonlToolBody input={part.input} />
+ if (part.kind === 'text' && markdown) {
+ return <JsonlMarkdownBody content={normalizeJsonlDisplayText(part.text)} />
+ }
+ if (part.kind === 'tool-result') {
+ return (
+ <pre className="max-h-96 overflow-auto whitespace-pre-wrap break-words rounded border bg-muted/30 p-2 text-xs leading-5">
+ {normalizeJsonlDisplayText(part.text) ||
+ t('filePreview.jsonl.emptyMessage')}
+ </pre>
+ )
+ }
+ const text =
+ part.kind === 'raw' ? part.text : normalizeJsonlDisplayText(part.text)
+ return (
+ <pre
+ className={`whitespace-pre-wrap break-words text-xs leading-5 ${
+ part.kind === 'raw' ? 'text-muted-foreground' : ''
+ }`}
+ >
+ {text || t('filePreview.jsonl.emptyMessage')}
+ </pre>
+ )
+}
+
+function JsonlMessageCard({ message }: { message: JsonlMessage }) {
const { t } = useTranslation('resources')
const [expanded, setExpanded] = useState(false)
- const message = useMemo(() => getJsonlMessage(record), [record])
- const isTool = Boolean(message.toolName || message.kind === 'tool-result')
- const needsExpand =
- !isTool && message.text.length > JSONL_MESSAGE_PREVIEW_LIMIT
- const body =
+ const textLength = message.parts.reduce(
+ (total, part) => (part.kind === 'text' ? total + part.text.length : total),
+ 0,
+ )
+ const needsExpand = textLength > JSONL_MESSAGE_PREVIEW_LIMIT
+ const displayParts =
expanded || !needsExpand
- ? message.text
- : `${message.text.slice(0, JSONL_MESSAGE_PREVIEW_LIMIT).trimEnd()}...`
+ ? message.parts
+ : collapseJsonlParts(message.parts, JSONL_MESSAGE_PREVIEW_LIMIT)
+ const toolNames = [
+ ...new Set(
+ message.parts.flatMap((part) =>
+ (part.kind === 'tool-call' || part.kind === 'tool-result') &&
+ part.toolName
+ ? [part.toolName]
+ : [],
+ ),
+ ),
+ ]
+ const markdown = isJsonlMarkdownMessage(message.role)
+ // Tool-result first: it must win over role=user, since Anthropic transcripts
+ // deliver tool results as user messages.
const alignClass =
- message.kind === 'user'
- ? 'bg-primary/10 border-primary/25'
- : message.kind === 'tool-result'
- ? 'border-dashed bg-muted/50'
- : message.kind === 'invalid' || message.kind === 'other'
- ? 'bg-muted/40'
- : 'bg-background'
+ message.toolShape === 'result'
+ ? 'border-dashed bg-muted/50'
+ : message.role === 'user'
+ ? 'bg-primary/10 border-primary/25'
+ : message.role === 'invalid'
+ ? 'border-destructive/30 bg-muted/40'
+ : message.role === 'other'
+ ? 'bg-muted/40'
+ : message.toolShape === 'call'
+ ? 'border-dashed bg-background'
+ : 'border-l-2 border-l-primary/50 bg-background'
return (
<article
@@ -964,23 +1133,32 @@ function JsonlMessageCard({ record }: { record: JsonlRecord }) {
{message.roleId}
</span>
) : null}
- {message.toolName ? (
- <span className="truncate rounded border bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">
- {message.toolName}
+ {toolNames.map((toolName) => (
+ <span
+ key={toolName}
+ className="truncate rounded border bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground"
+ >
+ {toolName}
</span>
- ) : null}
+ ))}
<span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">
#{message.lineNo}
</span>
</div>
- {message.toolName ? (
- <JsonlToolBody text={message.text} toolName={message.toolName} />
- ) : isJsonlMarkdownMessage(message.kind) ? (
- <JsonlMarkdownBody content={body} />
+ {displayParts.length ? (
+ <div className="grid gap-2">
+ {displayParts.map((part, index) => (
+ <JsonlPartBody
+ key={`${part.kind}-${index}`}
+ markdown={markdown}
+ part={part}
+ />
+ ))}
+ </div>
) : (
<pre className="whitespace-pre-wrap break-words text-xs leading-5">
- {body || t('filePreview.jsonl.emptyMessage')}
+ {t('filePreview.jsonl.emptyMessage')}
</pre>
)}
@@ -1014,20 +1192,29 @@ function JsonlPreview({ content }: { content: string }) {
return stored === null ? true : stored === 'true'
})
const records = useMemo(() => parseJsonlRecords(content), [content])
- const filteredRecords = useMemo(() => {
- if (!dialogMode || showTools) return records
- return records.filter((record) => {
- const message = getJsonlMessage(record)
- return !message.toolName && message.kind !== 'tool-result'
- })
- }, [dialogMode, records, showTools])
+ const messages = useMemo(() => records.map(getJsonlMessage), [records])
+ // Hiding tool calls strips the tool parts but keeps any text the same message
+ // carried; a message left with nothing to show drops out entirely.
+ const visibleMessages = useMemo(() => {
+ if (showTools) return messages
+ return messages
+ .map((message) => ({
+ ...message,
+ parts: message.parts.filter(
+ (part) => part.kind !== 'tool-call' && part.kind !== 'tool-result',
+ ),
+ }))
+ .filter((message) => message.parts.length > 0)
+ }, [messages, showTools])
+ // Raw rows cannot be split part by part, so a record hidden in dialog mode is
+ // hidden here too; a mixed text+tool record keeps its whole line.
+ const visibleLineNos = useMemo(
+ () => new Set(visibleMessages.map((message) => message.lineNo)),
+ [visibleMessages],
+ )
const hasTools = useMemo(
- () =>
- records.some((record) => {
- const message = getJsonlMessage(record)
- return Boolean(message.toolName || message.kind === 'tool-result')
- }),
- [records],
+ () => messages.some((message) => hasJsonlToolPart(message.parts)),
+ [messages],
)
if (!records.length) {
@@ -1045,7 +1232,7 @@ function JsonlPreview({ content }: { content: string }) {
{t('filePreview.jsonl.recordCount', { count: records.length })}
</span>
<div className="flex items-center gap-2">
- {dialogMode && hasTools ? (
+ {hasTools ? (
<label className="inline-flex cursor-pointer items-center gap-2">
<span className="font-medium">
{t('filePreview.jsonl.toolcall')}
@@ -1067,9 +1254,7 @@ function JsonlPreview({ content }: { content: string }) {
) : null}
<label className="inline-flex cursor-pointer items-center gap-2">
<span className="font-medium">
- {dialogMode
- ? t('filePreview.jsonl.dialogMode')
- : t('filePreview.jsonl.rawMode')}
+ {t('filePreview.jsonl.dialogMode')}
</span>
<input
type="checkbox"
@@ -1084,15 +1269,17 @@ function JsonlPreview({ content }: { content: string }) {
{dialogMode ? (
<div className="flex min-w-0 flex-col gap-3">
- {filteredRecords.map((record) => (
- <JsonlMessageCard key={record.index} record={record} />
+ {visibleMessages.map((message) => (
+ <JsonlMessageCard key={message.lineNo} message={message} />
))}
</div>
) : (
<div className="overflow-hidden rounded-md border">
- {records.map((record) => (
- <JsonlRawRow key={record.index} record={record} />
- ))}
+ {records
+ .filter((record) => visibleLineNos.has(record.index + 1))
+ .map((record) => (
+ <JsonlRawRow key={record.index} record={record} />
+ ))}
</div>
)}
</div>
@@ -1518,7 +1705,7 @@ export function FilePreview({
type="button"
className={`inline-flex items-baseline gap-1.5 rounded-full border px-3 py-1 text-xs transition-colors ${
active
- ? 'border-primary bg-primary text-primary-foreground'
+ ? 'border-border bg-muted text-foreground'
: 'border-border bg-background text-muted-foreground hover:border-foreground/30 hover:text-foreground'
}`}
title={level.title}
@@ -1534,13 +1721,7 @@ export function FilePreview({
})
}
>
- <span
- className={`font-mono text-[10px] font-semibold uppercase tracking-wide ${
- active
- ? 'text-primary-foreground'
- : 'text-primary'
- }`}
- >
+ <span className="font-mono text-[10px] font-semibold uppercase tracking-wide text-primary">
{level.name}
</span>
<span className="font-medium">{level.label}</span>
diff --git a/web-studio/src/routes/resources/-components/find-palette.tsx b/web-studio/src/routes/resources/-components/find-palette.tsx
index 1257c4dd0..8c6db9332 100644
--- a/web-studio/src/routes/resources/-components/find-palette.tsx
+++ b/web-studio/src/routes/resources/-components/find-palette.tsx
@@ -11,6 +11,8 @@ import { useTranslation } from 'react-i18next'
import { cn } from '#/lib/utils'
import { useTransientScrollbar } from '#/hooks/use-transient-scrollbar'
+import { useRetrievalQuery } from '#/routes/retrieval/-hooks/use-retrieval-query'
+import type { RetrievalMode } from '#/routes/retrieval/-types/retrieval'
import {
fileNameFromUri,
@@ -20,13 +22,18 @@ import {
import {
filterResourceSearchEntries,
getResourceSearchSpec,
+ normalizeGlobPattern,
+ retrievalItemsToEntries,
} from '../-lib/find-search'
import {
PALETTE_ROOT_URI,
+ PALETTE_SEARCH_MODES,
buildDirBrowseQuery,
+ cycleSearchMode,
isResetGlobalCommand,
parsePaletteMode,
} from '../-lib/palette-mode'
+import type { PaletteSearchMode } from '../-lib/palette-mode'
import {
useVikingFsList,
useVikingFsStat,
@@ -46,6 +53,7 @@ interface FindPaletteProps {
scopeUri?: string
}
const KEY_ESCAPE_LABEL = 'esc'
+const KEY_TAB_LABEL = 'Tab'
function displayName(uri: string): { name: string; parent: string } {
const name = fileNameFromUri(uri)
@@ -81,8 +89,9 @@ export function FindPalette({
onNavigateDir,
scopeUri,
}: FindPaletteProps) {
- const { t } = useTranslation('resources')
+ const { t } = useTranslation(['resources', 'retrieval'])
const [query, setQuery] = useState('')
+ const [searchMode, setSearchMode] = useState<PaletteSearchMode>('name')
const [findTargetUri, setFindTargetUri] = useState(() =>
normalizeDirUri(scopeUri || PALETTE_ROOT_URI),
)
@@ -117,15 +126,57 @@ export function FindPalette({
[showIdleBrowse, idleBrowseQuery.data?.entries],
)
+ const isNameMode = searchMode === 'name'
const treeQuery = useVikingFsTree(
searchSpec?.rootUri || PALETTE_ROOT_URI,
{ output: 'agent', showAllHidden: true, nodeLimit: 2000, levelLimit: 100 },
- mode.kind === 'search' && Boolean(searchSpec),
+ isNameMode && mode.kind === 'search' && Boolean(searchSpec),
+ )
+
+ // ponytail: 400ms debounce auto-fires find/search semantic retrieval; switch
+ // to Enter-to-run if it turns out too expensive.
+ const debouncedQuery = useDebouncedValue(
+ mode.kind === 'search' ? mode.query : '',
+ 400,
)
+ const retrievalOptions = useMemo(
+ () => ({
+ contextTypes: [],
+ customPathInput: '',
+ ignoreCase: true,
+ includeProvenance: false,
+ levels: [],
+ resultCount: 20,
+ scope: 'custom' as const,
+ tags: [],
+ targetUri: isRoot ? undefined : findTargetUri,
+ timeField: 'updated_at' as const,
+ }),
+ [isRoot, findTargetUri],
+ )
+ const retrievalQuery = useRetrievalQuery({
+ enabled: mode.kind === 'search' && !isNameMode && debouncedQuery.length > 0,
+ mode: searchMode as RetrievalMode,
+ options: retrievalOptions,
+ query:
+ searchMode === 'glob'
+ ? normalizeGlobPattern(debouncedQuery)
+ : debouncedQuery,
+ })
+
const filteredEntries = useMemo(() => {
- if (mode.kind !== 'search' || !treeQuery.data?.nodes) return []
+ if (mode.kind !== 'search') return []
+ if (!isNameMode) return retrievalItemsToEntries(retrievalQuery.data)
+ if (!treeQuery.data?.nodes) return []
return filterResourceSearchEntries(treeQuery.data.nodes, searchSpec)
- }, [mode.kind, treeQuery.data?.nodes, searchSpec])
+ }, [
+ mode.kind,
+ isNameMode,
+ retrievalQuery.data,
+ treeQuery.data?.nodes,
+ searchSpec,
+ ])
+ const searchQuery = isNameMode ? treeQuery : retrievalQuery
// Directory listing lifted up from DirBrowser so the cursor (activeIndex) and
// keyboard handling can live in one place. DirBrowser is now a pure view.
@@ -298,6 +349,13 @@ export function FindPalette({
return
}
+ // Outside dirBrowse, Tab cycles the search mode (query is untouched).
+ if (e.key === 'Tab') {
+ e.preventDefault()
+ setSearchMode((current) => cycleSearchMode(current, e.shiftKey))
+ return
+ }
+
// search / idle list navigation
if (visibleEntries.length === 0) return
switch (e.key) {
@@ -339,11 +397,16 @@ export function FindPalette({
if (!open) return null
- const showPreview =
- mode.kind !== 'dirBrowse' && activeEntry !== null && !activeEntry.isDir
- const paletteWidth = showPreview
- ? 'w-[min(92vw,67rem)]'
- : 'w-[min(90vw,45rem)]'
+ // Directories preview too: FilePreview renders their L0/L1 pages.
+ const showPreview = mode.kind !== 'dirBrowse' && activeEntry !== null
+ // Width tracks the palette mode, not the cursor: searching and directory
+ // browsing are both wide, so an empty result set or a `/` command never
+ // resizes the dialog out from under the user. Only the empty idle prompt,
+ // which has nothing to show yet, stays narrow.
+ const paletteWidth =
+ mode.kind === 'idle' && !showPreview
+ ? 'w-[min(90vw,45rem)]'
+ : 'w-[min(92vw,67rem)]'
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center px-4 sm:items-start sm:px-6 sm:pt-[12vh]"
@@ -370,7 +433,11 @@ export function FindPalette({
<input
ref={inputRef}
type="text"
- placeholder={t('searchPalette.placeholder')}
+ placeholder={
+ searchMode === 'name'
+ ? t('searchPalette.placeholder')
+ : t(`placeholders.${searchMode}`, { ns: 'retrieval' })
+ }
value={query}
onChange={(e) => setQuery(e.target.value)}
onCompositionStart={() => {
@@ -410,6 +477,35 @@ export function FindPalette({
</span>
</div>
+ {/* Search mode switcher */}
+ {mode.kind !== 'dirBrowse' && (
+ <div className="flex items-center gap-1 border-b px-4 py-1.5">
+ {PALETTE_SEARCH_MODES.map((item) => (
+ <button
+ key={item}
+ type="button"
+ className={cn(
+ 'rounded px-1.5 py-0.5 font-mono text-[11px] transition-colors',
+ searchMode === item
+ ? 'bg-muted text-foreground'
+ : 'text-muted-foreground/60 hover:text-foreground',
+ )}
+ onClick={() => setSearchMode(item)}
+ >
+ {item === 'name'
+ ? t('searchPalette.modes.name')
+ : t(`controls.modes.${item}`, { ns: 'retrieval' })}
+ </button>
+ ))}
+ <span className="ml-auto text-[11px] text-muted-foreground/50">
+ <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">
+ {KEY_TAB_LABEL}
+ </kbd>{' '}
+ {t('searchPalette.modes.switchHint')}
+ </span>
+ </div>
+ )}
+
{/* Body */}
<div className="flex min-h-0 flex-1" ref={resultsRef}>
{mode.kind === 'dirBrowse' ? (
@@ -487,21 +583,21 @@ export function FindPalette({
</div>
</div>
)
- ) : treeQuery.isLoading ? (
+ ) : searchQuery.isLoading ? (
<div className="flex flex-col items-center gap-3 py-12">
<Loader2 className="size-5 animate-spin text-muted-foreground/50" />
<p className="text-xs text-muted-foreground/60">
{t('searchPalette.scopeState.validatingTitle')}
</p>
</div>
- ) : treeQuery.error ? (
+ ) : searchQuery.error ? (
<div
role="alert"
className="flex flex-col items-center gap-1 px-4 py-6 text-center text-xs text-destructive"
>
<span>{t('searchPalette.error')}</span>
<span className="max-w-[32rem] text-muted-foreground">
- {errorDescription(treeQuery.error)}
+ {errorDescription(searchQuery.error)}
</span>
</div>
) : !hasResults ? (
@@ -600,7 +696,7 @@ export function FindPalette({
</span>
<span className="ml-auto tabular-nums">
{t('searchPalette.footer.resultMode.count', {
- count: filteredEntries.length,
+ count: visibleEntries.length,
})}
</span>
</div>
@@ -644,7 +740,7 @@ function DirResultList({
return (
<div
- key={entry.uri}
+ key={`${entry.uri}#${i}`}
data-active={isActive}
className={cn(
'animate-palette-row group relative flex w-full items-start gap-3 border-b border-border/50 px-4 py-3 text-left transition-colors last:border-b-0',
@@ -673,7 +769,7 @@ function DirResultList({
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium">{name}</div>
<div className="mt-0.5 truncate text-xs text-muted-foreground/80">
- {parent}
+ {entry.abstract.trim() ? entry.abstract : parent}
</div>
</div>
</button>
diff --git a/web-studio/src/routes/resources/-lib/find-search.test.ts b/web-studio/src/routes/resources/-lib/find-search.test.ts
index 5f39689b2..64623351e 100644
--- a/web-studio/src/routes/resources/-lib/find-search.test.ts
+++ b/web-studio/src/routes/resources/-lib/find-search.test.ts
@@ -3,7 +3,10 @@ import { describe, expect, it } from 'vitest'
import {
filterResourceSearchEntries,
getResourceSearchSpec,
+ normalizeGlobPattern,
+ retrievalItemsToEntries,
} from './find-search'
+import type { FindResultItem } from '#/lib/retrieval'
import type { VikingFsEntry } from '../-types/viking-fm'
function entry(uri: string, isDir = false): VikingFsEntry {
@@ -65,3 +68,65 @@ describe('resource path search', () => {
])
})
})
+
+describe('normalizeGlobPattern', () => {
+ it('prefixes bare patterns so they match at any depth', () => {
+ expect(normalizeGlobPattern('*.md')).toBe('**/*.md')
+ expect(normalizeGlobPattern(' *.md ')).toBe('**/*.md')
+ })
+
+ it('leaves anchored patterns untouched', () => {
+ expect(normalizeGlobPattern('docs/*.md')).toBe('docs/*.md')
+ expect(normalizeGlobPattern('**/*.md')).toBe('**/*.md')
+ })
+})
+
+describe('retrievalItemsToEntries', () => {
+ function item(overrides: Partial<FindResultItem>): FindResultItem {
+ return {
+ uri: 'viking://resources/a.md',
+ context_type: 'resources',
+ level: 0,
+ score: 0,
+ abstract: '',
+ category: '',
+ match_reason: '',
+ ...overrides,
+ }
+ }
+
+ it('appends the line number and keeps the snippet for grep hits', () => {
+ const [hit] = retrievalItemsToEntries({
+ memories: [],
+ resources: [
+ item({ abstract: 'hit line', line: 42, result_kind: 'grep' }),
+ ],
+ skills: [],
+ total: 1,
+ })
+
+ expect(hit.name).toBe('a.md:42')
+ expect(hit.size).toBe('')
+ expect(hit.abstract).toBe('hit line')
+ })
+
+ it('shows the score for semantic hits and nothing for glob hits', () => {
+ const entries = retrievalItemsToEntries({
+ memories: [],
+ resources: [
+ item({ result_kind: 'semantic', score: 0.8421 }),
+ item({ uri: 'viking://resources/b.md', result_kind: 'glob' }),
+ ],
+ skills: [],
+ total: 2,
+ })
+
+ expect(entries[0].size).toBe('0.84')
+ expect(entries[0].name).toBe('a.md')
+ expect(entries[1].size).toBe('')
+ })
+
+ it('returns nothing without a result', () => {
+ expect(retrievalItemsToEntries(undefined)).toEqual([])
+ })
+})
diff --git a/web-studio/src/routes/resources/-lib/find-search.ts b/web-studio/src/routes/resources/-lib/find-search.ts
index 1af1d00fd..d7be9ff35 100644
--- a/web-studio/src/routes/resources/-lib/find-search.ts
+++ b/web-studio/src/routes/resources/-lib/find-search.ts
@@ -1,5 +1,12 @@
+import type { GroupedFindResult } from '#/lib/retrieval'
+
import type { VikingFsEntry } from '../-types/viking-fm'
-import { normalizeDirUri, normalizeFileUri, parentUri } from './normalize'
+import {
+ fileNameFromUri,
+ normalizeDirUri,
+ normalizeFileUri,
+ parentUri,
+} from './normalize'
const VIKING_URI_PREFIX = 'viking://'
@@ -101,3 +108,34 @@ export function filterResourceSearchEntries(
return entries.filter((entry) => matchesResourceSearch(entry, spec))
}
+
+// A pattern without `/` matches at any depth (implicit `**/` prefix); one that
+// contains `/` is treated as already anchored — matches gitignore / VS Code
+// files-to-include / fd conventions.
+export function normalizeGlobPattern(pattern: string): string {
+ const trimmed = pattern.trim()
+ return trimmed.includes('/') ? trimmed : `**/${trimmed}`
+}
+
+export function retrievalItemsToEntries(
+ result: GroupedFindResult | undefined,
+): Array<VikingFsEntry> {
+ if (!result) return []
+ const items = [...result.resources, ...result.memories, ...result.skills]
+ return items.map((item) => ({
+ uri: item.uri,
+ name:
+ fileNameFromUri(item.uri) +
+ (item.line === undefined ? '' : `:${item.line}`),
+ isDir: item.uri.endsWith('/'),
+ abstract: item.abstract,
+ // ponytail: reuse the `size` slot to surface the semantic score.
+ size:
+ item.result_kind === 'grep' || item.result_kind === 'glob'
+ ? ''
+ : item.score.toFixed(2),
+ sizeBytes: null,
+ modTime: '',
+ modTimestamp: null,
+ }))
+}
diff --git a/web-studio/src/routes/resources/-lib/palette-mode.ts b/web-studio/src/routes/resources/-lib/palette-mode.ts
index 3b377ae03..4a881786d 100644
--- a/web-studio/src/routes/resources/-lib/palette-mode.ts
+++ b/web-studio/src/routes/resources/-lib/palette-mode.ts
@@ -69,3 +69,24 @@ export function buildDirBrowseQuery(uri: string): string {
const path = normalized.slice(PALETTE_ROOT_URI.length)
return `${PALETTE_COMMANDS.dir}${path}`
}
+
+// `name` is the original client-side filename filter; the rest map 1:1 onto
+// RETRIEVAL_MODES and go through the shared retrieval hook.
+export const PALETTE_SEARCH_MODES = [
+ 'name',
+ 'find',
+ 'search',
+ 'grep',
+ 'glob',
+] as const
+
+export type PaletteSearchMode = (typeof PALETTE_SEARCH_MODES)[number]
+
+export function cycleSearchMode(
+ current: PaletteSearchMode,
+ backwards = false,
+): PaletteSearchMode {
+ const index = PALETTE_SEARCH_MODES.indexOf(current)
+ const size = PALETTE_SEARCH_MODES.length
+ return PALETTE_SEARCH_MODES[(index + (backwards ? -1 : 1) + size) % size]
+}