Skip to content

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

Fix Studio admin/data API key handling (#2449)

Zayn Jarvis0dc206ae4e44
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index 778b618f9..6d73ae314 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -4,7 +4,6 @@ import {
BlocksIcon,
BookOpenIcon,
ChevronRightIcon,
- FolderTreeIcon,
HomeIcon,
GithubIcon,
KeyRoundIcon,
@@ -26,7 +25,6 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from '#/components/ui/collapsible'
-import { ConnectionDialog } from '#/components/connection-dialog'
import { OAuthSetupDialog } from '#/components/oauth-setup-dialog'
import { ScrollArea } from '#/components/ui/scroll-area'
import {
@@ -95,12 +93,6 @@ const NAV_ITEMS: readonly NavItem[] = [
titleKey: 'navigation.playground.title',
to: '/playground',
},
- {
- icon: FolderTreeIcon,
- id: 'resources',
- titleKey: 'navigation.resources.title',
- to: '/resources',
- },
{
icon: SearchIcon,
id: 'retrieval',
@@ -383,9 +375,9 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
className="flex h-svh overflow-hidden bg-sidebar"
>
<Sidebar variant="sidebar" collapsible="icon" className="!border-r-0">
- <SidebarHeader className="border-b border-sidebar-border/70 p-2">
- <div className="flex items-center justify-between gap-2 group-data-[collapsible=icon]:justify-center">
- <span className="truncate px-2 text-base font-semibold group-data-[collapsible=icon]:hidden">
+ <SidebarHeader className="h-12 border-b border-sidebar-border/70 px-2 py-0">
+ <div className="flex h-full items-center justify-between gap-2 group-data-[collapsible=icon]:justify-center">
+ <span className="flex h-8 min-w-0 items-center truncate px-2 text-base font-semibold leading-none group-data-[collapsible=icon]:hidden">
{t('sidebar.workspaceGroupLabel', { ns: 'appShell' })}
</span>
<SidebarTrigger className="hidden shrink-0 md:inline-flex" />
@@ -578,7 +570,6 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
</ScrollArea>
</SidebarInset>
- <ConnectionDialog />
<OAuthSetupDialog
open={oauthSetupOpen}
onOpenChange={setOauthSetupOpen}
diff --git a/web-studio/src/components/connection-dialog.tsx b/web-studio/src/components/connection-dialog.tsx
deleted file mode 100644
index dfaeae0f4..000000000
--- a/web-studio/src/components/connection-dialog.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-import * as React from 'react'
-import { useTranslation } from 'react-i18next'
-
-import { useAppConnection } from '#/hooks/use-app-connection'
-
-import { Button } from '#/components/ui/button'
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from '#/components/ui/card'
-import {
- Dialog,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '#/components/ui/dialog'
-import {
- Field,
- FieldContent,
- FieldGroup,
- FieldLabel,
- FieldSet,
-} from '#/components/ui/field'
-import { Input } from '#/components/ui/input'
-
-export function ConnectionDialog() {
- const { t } = useTranslation(['connection', 'common'])
- const {
- connection,
- isConnectionDialogOpen,
- saveConnection,
- serverMode,
- setConnectionDialogOpen,
- } = useAppConnection()
- const [draft, setDraft] = React.useState(connection)
- const [showAdvancedInDevMode, setShowAdvancedInDevMode] =
- React.useState(false)
-
- React.useEffect(() => {
- if (isConnectionDialogOpen) {
- setDraft(connection)
- setShowAdvancedInDevMode(false)
- }
- }, [connection, isConnectionDialogOpen])
-
- const isDevImplicit = serverMode === 'dev'
- const showIdentityFields = !isDevImplicit || showAdvancedInDevMode
-
- return (
- <Dialog
- open={isConnectionDialogOpen}
- onOpenChange={setConnectionDialogOpen}
- >
- <DialogContent className="max-w-2xl">
- <DialogHeader>
- <DialogTitle>{t('dialog.title', { ns: 'connection' })}</DialogTitle>
- </DialogHeader>
-
- <FieldSet>
- <FieldGroup>
- <Field>
- <FieldLabel htmlFor="ov-base-url">
- {t('fields.baseUrl.label', { ns: 'connection' })}
- </FieldLabel>
- <FieldContent>
- <Input
- id="ov-base-url"
- placeholder={t('fields.baseUrl.placeholder', {
- ns: 'connection',
- })}
- value={draft.baseUrl}
- onChange={(event) =>
- setDraft((current) => ({
- ...current,
- baseUrl: event.target.value,
- }))
- }
- />
- </FieldContent>
- </Field>
-
- <Card
- size="sm"
- className="min-h-56 gap-3 border bg-background/70 shadow-none"
- >
- {showIdentityFields ? (
- <>
- <CardHeader className="gap-1.5">
- <CardTitle className="text-sm">
- {t('fields.credentials.title', { ns: 'connection' })}
- </CardTitle>
- </CardHeader>
- <CardContent className="grid flex-1 content-start gap-3">
- <div className="grid gap-3 md:grid-cols-3">
- <Field>
- <FieldLabel htmlFor="ov-account-id">
- {t('fields.accountId.label', { ns: 'connection' })}
- </FieldLabel>
- <FieldContent>
- <Input
- id="ov-account-id"
- placeholder={t('fields.accountId.placeholder', {
- ns: 'connection',
- })}
- value={draft.accountId}
- onChange={(event) =>
- setDraft((current) => ({
- ...current,
- accountId: event.target.value,
- }))
- }
- />
- </FieldContent>
- </Field>
- <Field>
- <FieldLabel htmlFor="ov-user-id">
- {t('fields.userId.label', { ns: 'connection' })}
- </FieldLabel>
- <FieldContent>
- <Input
- id="ov-user-id"
- placeholder={t('fields.userId.placeholder', {
- ns: 'connection',
- })}
- value={draft.userId}
- onChange={(event) =>
- setDraft((current) => ({
- ...current,
- userId: event.target.value,
- }))
- }
- />
- </FieldContent>
- </Field>
- </div>
-
- <Field>
- <FieldLabel htmlFor="ov-api-key">
- {t('fields.apiKey.label', { ns: 'connection' })}
- </FieldLabel>
- <FieldContent>
- <Input
- id="ov-api-key"
- type="password"
- placeholder={t('fields.apiKey.placeholder', {
- ns: 'connection',
- })}
- value={draft.apiKey}
- onChange={(event) =>
- setDraft((current) => ({
- ...current,
- apiKey: event.target.value,
- }))
- }
- />
- </FieldContent>
- </Field>
- </CardContent>
- </>
- ) : (
- <>
- <CardHeader className="gap-2">
- <CardTitle className="text-sm">
- {t('devMode.title', { ns: 'connection' })}
- </CardTitle>
- <CardDescription>
- {t('devMode.description', { ns: 'connection' })}
- </CardDescription>
- </CardHeader>
- <CardContent className="flex flex-1 items-end">
- <Button
- variant="outline"
- size="sm"
- onClick={() => setShowAdvancedInDevMode(true)}
- >
- {t('showAdvancedIdentityFields', {
- ns: 'common',
- keyPrefix: 'action',
- })}
- </Button>
- </CardContent>
- </>
- )}
- </Card>
- </FieldGroup>
- </FieldSet>
-
- <DialogFooter>
- <Button
- variant="outline"
- onClick={() => setConnectionDialogOpen(false)}
- >
- {t('cancel', { ns: 'common', keyPrefix: 'action' })}
- </Button>
- <Button
- onClick={() => {
- saveConnection(draft)
- setConnectionDialogOpen(false)
- }}
- >
- {t('saveConnection', { ns: 'common', keyPrefix: 'action' })}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsx
index ac5948927..f19533bd2 100644
--- a/web-studio/src/hooks/use-app-connection.tsx
+++ b/web-studio/src/hooks/use-app-connection.tsx
@@ -1,5 +1,6 @@
import * as React from 'react'
import { useQueryClient } from '@tanstack/react-query'
+import { useNavigate, useRouterState } from '@tanstack/react-router'
import { isOvClientError, ovClient } from '#/lib/ov-client'
@@ -8,6 +9,7 @@ import type { ServerMode } from './use-server-mode'
export type ConnectionDraft = {
accountId: string
+ adminApiKey: string
apiKey: string
baseUrl: string
userId: string
@@ -22,11 +24,9 @@ export type ConnectionIdentitySummary = {
type AppConnectionContextValue = {
connection: ConnectionDraft
- isConnectionDialogOpen: boolean
- openConnectionDialog: () => void
+ openConnectionSettings: () => void
saveConnection: (next: ConnectionDraft) => void
serverMode: ServerMode
- setConnectionDialogOpen: (open: boolean) => void
}
const CONNECTION_STORAGE_KEY = 'ov_console_connection'
@@ -39,6 +39,10 @@ const ENV_API_KEY =
typeof import.meta.env.VITE_OV_API_KEY === 'string'
? import.meta.env.VITE_OV_API_KEY.trim()
: ''
+const ENV_ADMIN_API_KEY =
+ typeof import.meta.env.VITE_OV_ADMIN_API_KEY === 'string'
+ ? import.meta.env.VITE_OV_ADMIN_API_KEY.trim()
+ : ''
const ENV_ACCOUNT =
typeof import.meta.env.VITE_OV_ACCOUNT === 'string'
? import.meta.env.VITE_OV_ACCOUNT.trim()
@@ -50,6 +54,7 @@ const ENV_USER =
const DEFAULT_CONNECTION: ConnectionDraft = {
accountId: ENV_ACCOUNT || 'default',
+ adminApiKey: ENV_ADMIN_API_KEY,
apiKey: ENV_API_KEY,
baseUrl: ovClient.getOptions().baseUrl,
userId: ENV_USER || 'default',
@@ -101,6 +106,7 @@ function normalizeConnectionDraft(
): ConnectionDraft {
return {
accountId: connection.accountId.trim(),
+ adminApiKey: connection.adminApiKey.trim(),
apiKey: connection.apiKey.trim(),
baseUrl: normalizeBaseUrl(connection.baseUrl),
userId: connection.userId.trim(),
@@ -118,19 +124,28 @@ function resolveIdentityField(
return storedValue || defaultValue
}
-function applyConnection(connection: ConnectionDraft): void {
+function applyConnection(
+ connection: ConnectionDraft,
+ serverMode: ServerMode,
+): void {
ovClient.setOptions({
baseUrl: connection.baseUrl,
})
ovClient.setConnection({
accountId: connection.accountId,
+ adminApiKey: connection.adminApiKey,
apiKey: connection.apiKey,
+ identityHeaders: serverMode === 'trusted',
userId: connection.userId,
})
}
function readInitialConnection(): ConnectionDraft {
const storedConnection = readStoredConnection()
+ const adminApiKey =
+ ENV_ADMIN_API_KEY ||
+ storedConnection.adminApiKey ||
+ DEFAULT_CONNECTION.adminApiKey
const apiKey =
ENV_API_KEY ||
ovClient.getConnection().apiKey ||
@@ -144,6 +159,7 @@ function readInitialConnection(): ConnectionDraft {
storedConnection.accountId,
DEFAULT_CONNECTION.accountId,
),
+ adminApiKey,
apiKey,
baseUrl:
ENV_BASE_URL || storedConnection.baseUrl || DEFAULT_CONNECTION.baseUrl,
@@ -163,10 +179,7 @@ export function summarizeConnectionIdentity(
return { labelKey: 'identitySummary.dev' }
}
- const segments = [
- connection.accountId,
- connection.userId,
- ].filter(Boolean)
+ const segments = [connection.accountId, connection.userId].filter(Boolean)
if (!segments.length) {
return { labelKey: 'identitySummary.unset' }
}
@@ -196,24 +209,32 @@ export function AppConnectionProvider({
children: React.ReactNode
}) {
const queryClient = useQueryClient()
+ const navigate = useNavigate()
+ const pathname = useRouterState({
+ select: (state) => state.location.pathname,
+ })
const initialConnectionRef = React.useRef<ConnectionDraft | null>(null)
if (initialConnectionRef.current === null) {
initialConnectionRef.current = readInitialConnection()
- applyConnection(initialConnectionRef.current)
+ applyConnection(initialConnectionRef.current, 'checking')
}
const [connection, setConnection] = React.useState<ConnectionDraft>(
initialConnectionRef.current,
)
- const [isConnectionDialogOpen, setConnectionDialogOpen] =
- React.useState(false)
const [serverMode, setServerMode] = React.useState<ServerMode>('checking')
+ const openConnectionSettings = React.useCallback(() => {
+ if (pathname !== '/settings') {
+ void navigate({ to: '/settings' })
+ }
+ }, [navigate, pathname])
+
React.useEffect(() => {
- applyConnection(connection)
+ applyConnection(connection, serverMode)
persistConnection(connection)
void queryClient.invalidateQueries()
- }, [connection, queryClient])
+ }, [connection, queryClient, serverMode])
React.useEffect(() => {
let cancelled = false
@@ -238,7 +259,7 @@ export function AppConnectionProvider({
isOvClientError(error) &&
(error.statusCode === 401 || error.statusCode === 403)
) {
- setConnectionDialogOpen(true)
+ openConnectionSettings()
}
return Promise.reject(error)
},
@@ -247,18 +268,16 @@ export function AppConnectionProvider({
return () => {
ovClient.instance.interceptors.response.eject(interceptorId)
}
- }, [])
+ }, [openConnectionSettings])
const value = React.useMemo<AppConnectionContextValue>(
() => ({
connection,
- isConnectionDialogOpen,
- openConnectionDialog: () => setConnectionDialogOpen(true),
+ openConnectionSettings,
saveConnection: (next) => setConnection(normalizeConnectionDraft(next)),
serverMode,
- setConnectionDialogOpen,
}),
- [connection, isConnectionDialogOpen, serverMode],
+ [connection, openConnectionSettings, serverMode],
)
return (
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index ee6d29150..24fe424d3 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -6,7 +6,7 @@ const en = {
github: 'GitHub',
},
header: {
- defaultTitle: 'OpenViking Playground',
+ defaultTitle: 'OpenViking Studio',
},
navigation: {
home: {
@@ -21,9 +21,6 @@ const en = {
requestLogs: {
title: 'Request Logs',
},
- resources: {
- title: 'Context Management',
- },
retrieval: {
title: 'Retrieval',
},
@@ -37,7 +34,7 @@ const en = {
sidebar: {
loadingSessions: 'Loading...',
noSessions: 'No sessions',
- workspaceGroupLabel: 'OpenViking Playground',
+ workspaceGroupLabel: 'OpenViking Studio',
},
},
common: {
@@ -84,6 +81,10 @@ const en = {
label: 'API Key',
placeholder: 'Enter X-API-Key or Bearer token',
},
+ adminApiKey: {
+ label: 'Admin API key',
+ placeholder: 'Root or account-admin key',
+ },
baseUrl: {
label: 'Service URL',
placeholder: 'http://127.0.0.1:1933',
@@ -91,6 +92,9 @@ const en = {
credentials: {
title: 'Identity & Credentials',
},
+ dataApiKey: {
+ label: 'User API key',
+ },
userId: {
label: 'User',
placeholder: 'default',
@@ -120,13 +124,16 @@ const en = {
regenerate: 'Regenerate',
save: 'Save',
use: 'Use',
+ useForData: 'Use as user key',
},
connection: {
+ accountListLimited:
+ 'This key cannot list all accounts, but it can still manage the selected account if it has account-admin access.',
adminError: 'Could not load admin identities: {{message}}',
description:
- 'Select the account and user that Playground should send with OpenViking requests.',
+ 'Use a user API key for tenant data APIs and an optional root or account-admin key for control APIs.',
noKey:
- 'Enter an API key with admin access to load account and user choices.',
+ 'Enter a root or account-admin API key to load account and user choices.',
title: 'Connection settings',
},
dialogs: {
@@ -151,16 +158,29 @@ const en = {
'Use a root or account admin API key to list users, copy keys, add identities, or regenerate credentials.',
adminTitle: 'Admin access required',
usersDescription: 'Create a user to mint the first API key.',
- usersTitle: 'No users in this account',
+ usersTitle: 'No users in the selected accounts',
},
fields: {
account: 'Account',
adminUser: 'Admin user',
+ adminApiKey: 'Admin API key',
apiKey: 'API key',
baseUrl: 'Server URL',
+ dataApiKey: 'User API key',
+ userApiKey: 'User API key',
role: 'Role',
user: 'User',
},
+ health: {
+ admin: 'Admin control',
+ data: 'Data access',
+ state: {
+ checking: 'Checking',
+ error: 'Error',
+ ok: 'OK',
+ skipped: 'Not checked',
+ },
+ },
keyResult: {
description:
'Copy it now. OpenViking may only show a prefix after you leave this state.',
@@ -169,20 +189,23 @@ const en = {
},
loading: 'Loading identities...',
management: {
- accountFilter: 'Managed account',
+ accountFilter: 'Accounts',
description:
- 'Review users and credentials for one account, then add users or rotate keys from the web UI.',
+ 'Review users and credentials for selected accounts, then add users or rotate keys from the web UI.',
title: 'User management',
},
page: {
description:
- 'Configure the active OpenViking identity and manage accounts, users, and API keys from Playground.',
+ 'Configure the active OpenViking Studio identity and manage accounts, users, and API keys.',
title: 'Connection & Identity',
},
placeholders: {
account: 'team-account',
+ adminApiKey: 'Root or account-admin key',
apiKey: 'Enter X-API-Key or Bearer token',
baseUrl: 'http://127.0.0.1:1933',
+ devModeApiKey: '[dev mode, no api key required]',
+ userApiKey: 'User API key',
user: 'default',
},
roles: {
@@ -212,6 +235,7 @@ const en = {
accountCreated: 'Account created',
connectionSaved: 'Connection saved',
copied: 'Copied',
+ dataKeySelected: 'User API key selected',
keyRegenerated: 'API key regenerated',
userCreated: 'User created',
},
@@ -265,45 +289,10 @@ const en = {
skills: 'Skills',
title: 'Context Data Volume',
},
- menuIntro: {
- description:
- 'The left navigation is collapsible. Primary entries include overview, context management, recursive retrieval, request logs, settings, GitHub, and docs.',
- items: {
- github: {
- description: 'Open the OpenViking source repository.',
- title: 'GitHub',
- },
- overview: {
- description: 'Review context scale and usage overview.',
- title: 'Overview',
- },
- playground: {
- description: 'Open the docs site and Playground entry.',
- title: 'Playground',
- },
- requestLogs: {
- description: 'Inspect Playground requests, status, and latency.',
- title: 'Request Logs',
- },
- resources: {
- description: 'Manage files, skills, and context directories.',
- title: 'Context Management',
- },
- retrieval: {
- description: 'Run semantic retrieval with find() and search().',
- title: 'Recursive Retrieval',
- },
- settings: {
- description: 'Configure service URL, identity, and API key.',
- title: 'Settings',
- },
- },
- title: 'Overview + Menu Guide',
- },
page: {
description:
'Aligned with the product overview: menu entries, context data volume, today tokens, today retrievals, agent access, token trend, and context commit stats.',
- eyebrow: 'OpenViking Playground',
+ eyebrow: 'OpenViking Studio',
settings: 'Connection & Settings',
title: 'Overview',
},
@@ -479,30 +468,6 @@ const en = {
},
},
resources: {
- page: {
- placeholder: 'Resources workspace is under construction.',
- },
- toolbar: {
- parent: 'Go to Parent',
- refresh: 'Refresh Directory',
- search: 'Search ⌘K',
- processingTasks: 'File Processing Tasks',
- upload: 'Upload',
- },
- emptyState: {
- title: 'Your context space is empty',
- upload: 'Upload File',
- },
- uploadDialog: {
- title: 'Upload',
- description:
- 'Add a local file or remote resource to the context resource library.',
- },
- processingNotice: {
- prefix: 'Files are being processed.',
- action: 'File Processing Tasks',
- suffix: 'shows progress and results.',
- },
processingTasks: {
title: 'File Processing Tasks',
empty: 'No processing tasks',
@@ -518,71 +483,6 @@ const en = {
failed: 'Processing failed',
},
},
- searchPalette: {
- ariaLabel: 'Search',
- openContainingDirectory: 'Open containing directory',
- placeholder: 'Search',
- scope: {
- global: 'Search scope: Global',
- current: 'Search scope: {{name}}',
- resetToGlobal: 'Click to reset to global search',
- },
- scopeState: {
- validatingTitle: 'Validating search scope',
- validatingPrefix: 'Checking whether',
- validatingSuffix: 'exists',
- switchTitle: 'Switch search scope',
- switchPrefix: 'Press',
- switchMiddle: 'to switch to',
- invalidTitle: 'Search scope not found',
- invalidPrefix: 'Path',
- invalidSuffix: 'is inaccessible and cannot be switched to',
- },
- empty: {
- title: 'Search files and directories',
- },
- browseDirHint: {
- before: 'Enter',
- after: 'to browse directories',
- },
- globalScopeHint: {
- before: 'Enter',
- after: 'to switch search scope to global',
- },
- error: 'Search failed',
- emptyResults: {
- title: 'No matching files or directories found',
- subtitle: 'Try another keyword?',
- },
- footer: {
- dirMode: {
- select: 'Select',
- level: 'Level',
- confirm: 'Confirm',
- cancel: 'Cancel',
- },
- resultMode: {
- navigate: 'Navigate',
- open: 'Open',
- close: 'Close',
- count: '{{count}} results',
- },
- },
- },
- dirBrowser: {
- back: 'Back',
- loading: 'Loading directory',
- filesSection: 'Files',
- error: 'Failed to load directory',
- empty: {
- title: 'Empty directory',
- subtitle:
- 'There are currently no subdirectories to expand at this level',
- },
- },
- fileList: {
- empty: 'This directory is empty',
- },
filePreview: {
cancel: 'Cancel',
edit: 'Edit',
@@ -598,21 +498,6 @@ const en = {
save: 'Save',
unsupportedBinary: 'Binary files do not support text preview.',
},
- fileTree: {
- collapse: 'Collapse',
- expand: 'Expand',
- loading: 'Loading...',
- },
- findResults: {
- collapse: 'Collapse',
- expandDetails: 'Expand details',
- groups: {
- memories: 'Memories',
- resources: 'Resources',
- skills: 'Skills',
- },
- noResults: 'No matching results',
- },
},
retrieval: {
title: 'Retrieval',
@@ -734,8 +619,8 @@ const en = {
scopesLabel: 'Scopes',
scopesNone: '(none)',
signInRequired:
- 'Sign in to OpenViking Playground (Connection & Identity) or paste an API key below to authorize this client.',
- openConnectionDialog: 'Open Connection & Identity',
+ 'Sign in to OpenViking Studio (Connection & Identity) or paste an API key below to authorize this client.',
+ openConnectionSettings: 'Open Connection & Identity',
authorize: 'Authorize',
deny: 'Deny',
useAnotherDevice: 'Use another device →',
@@ -760,7 +645,7 @@ const en = {
verifyError: 'Authorization failed: {{message}}',
noApiKey: 'No API key available. Select an identity or paste a key.',
signInRequired:
- 'Sign in to OpenViking Playground (Connection & Identity) or paste an API key below to verify.',
+ 'Sign in to OpenViking Studio (Connection & Identity) or paste an API key below to verify.',
},
},
playground: {
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index c7fc9e821..d077f8e4a 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -6,7 +6,7 @@ const zhCN = {
github: 'GitHub',
},
header: {
- defaultTitle: 'OpenViking Playground',
+ defaultTitle: 'OpenViking Studio',
},
navigation: {
home: {
@@ -21,9 +21,6 @@ const zhCN = {
requestLogs: {
title: '请求日志',
},
- resources: {
- title: '上下文管理',
- },
retrieval: {
title: '检索',
},
@@ -37,7 +34,7 @@ const zhCN = {
sidebar: {
loadingSessions: '加载中...',
noSessions: '暂无会话',
- workspaceGroupLabel: 'OpenViking Playground',
+ workspaceGroupLabel: 'OpenViking Studio',
},
},
common: {
@@ -84,6 +81,10 @@ const zhCN = {
label: 'API Key',
placeholder: '输入 X-API-Key 或 Bearer token',
},
+ adminApiKey: {
+ label: 'Admin API key',
+ placeholder: 'Root 或 account-admin key',
+ },
baseUrl: {
label: '服务地址',
placeholder: 'http://127.0.0.1:1933',
@@ -91,6 +92,9 @@ const zhCN = {
credentials: {
title: '身份与凭证',
},
+ dataApiKey: {
+ label: 'User API key',
+ },
userId: {
label: 'User',
placeholder: 'default',
@@ -120,13 +124,16 @@ const zhCN = {
regenerate: '重新生成',
save: '保存',
use: '使用',
+ useForData: '用作 User key',
},
connection: {
+ accountListLimited:
+ '当前 key 不能列出所有 account;如果它有 account-admin 权限,仍可管理选中的 account。',
adminError: '加载 admin 身份失败:{{message}}',
description:
- '选择 Playground 调用 OpenViking API 时要携带的 account 和 user。',
+ '租户数据 API 使用 User API key;控制 API 可单独使用 root 或 account-admin key。',
noKey:
- '输入具备 admin 权限的 API key 后,可以加载 account 和 user 可选项。',
+ '输入 root 或 account-admin API key 后,可以加载 account 和 user 可选项。',
title: '连接设置',
},
dialogs: {
@@ -151,16 +158,29 @@ const zhCN = {
'使用 root 或 account admin API key 后,可以列出用户、复制 key、新增身份或轮换凭证。',
adminTitle: '需要 admin 权限',
usersDescription: '创建一个 user 来生成第一个 API key。',
- usersTitle: '当前 account 下没有 user',
+ usersTitle: '选中的 accounts 下没有 user',
},
fields: {
account: 'Account',
adminUser: 'Admin user',
+ adminApiKey: 'Admin API key',
apiKey: 'API key',
baseUrl: '服务地址',
+ dataApiKey: 'User API key',
+ userApiKey: 'User API key',
role: '角色',
user: 'User',
},
+ health: {
+ admin: '控制面权限',
+ data: '数据访问',
+ state: {
+ checking: '检查中',
+ error: '异常',
+ ok: '正常',
+ skipped: '未检查',
+ },
+ },
keyResult: {
description:
'请现在复制保存。离开当前状态后,OpenViking 可能只展示前缀。',
@@ -169,20 +189,23 @@ const zhCN = {
},
loading: '正在加载身份...',
management: {
- accountFilter: '管理的 account',
+ accountFilter: 'Accounts',
description:
- '查看某个 account 下的 users 和凭证,并在网页端新增 user 或轮换 key。',
+ '查看选中 accounts 下的 users 和凭证,并在网页端新增 user 或轮换 key。',
title: '用户管理',
},
page: {
description:
- '在 Playground 中配置当前 OpenViking 身份,并管理 accounts、users 和 API keys。',
+ '配置当前 OpenViking Studio 身份,并管理 accounts、users 和 API keys。',
title: '连接与身份',
},
placeholders: {
account: 'team-account',
+ adminApiKey: 'Root 或 account-admin key',
apiKey: '输入 X-API-Key 或 Bearer token',
baseUrl: 'http://127.0.0.1:1933',
+ devModeApiKey: '[dev mode,无需 API key]',
+ userApiKey: 'User API key',
user: 'default',
},
roles: {
@@ -212,6 +235,7 @@ const zhCN = {
accountCreated: 'Account 已创建',
connectionSaved: '连接已保存',
copied: '已复制',
+ dataKeySelected: '已选择 User API key',
keyRegenerated: 'API key 已重新生成',
userCreated: 'User 已创建',
},
@@ -258,52 +282,16 @@ const zhCN = {
},
},
contextData: {
- description:
- '包含文件、技能与用户记忆,用于衡量当前上下文资源规模。',
+ description: '包含文件、技能与用户记忆,用于衡量当前上下文资源规模。',
files: '文件',
memories: '记忆',
skills: '技能',
title: '上下文数据量',
},
- menuIntro: {
- description:
- '左侧导航可折叠;常用入口包括总览、上下文管理、目录递归检索、请求日志、设置、GitHub 和文档站。',
- items: {
- github: {
- description: '打开 OpenViking 源码仓库。',
- title: 'GitHub',
- },
- overview: {
- description: '查看上下文规模与使用概览。',
- title: '总览',
- },
- playground: {
- description: '打开文档站和 Playground 入口。',
- title: 'Playground',
- },
- requestLogs: {
- description: '查看 Playground 发出的请求、状态与耗时。',
- title: '请求日志',
- },
- resources: {
- description: '管理文件、技能和上下文目录。',
- title: '上下文管理',
- },
- retrieval: {
- description: '使用 find() 与 search() 做语义检索。',
- title: '目录递归检索',
- },
- settings: {
- description: '配置服务地址、身份和 API Key。',
- title: '设置',
- },
- },
- title: 'Overview + 整体菜单介绍',
- },
page: {
description:
'按产品需求对齐首页内容:菜单入口、上下文数据量、今日 tokens、今日检索、Agent 访问、tokens 趋势和上下文提交统计。',
- eyebrow: 'OpenViking Playground',
+ eyebrow: 'OpenViking Studio',
settings: '连接与设置',
title: 'Overview',
},
@@ -469,29 +457,6 @@ const zhCN = {
},
},
resources: {
- page: {
- placeholder: '资源工作区能力尚未接入。',
- },
- toolbar: {
- parent: '返回父级',
- refresh: '刷新目录',
- search: '搜索 ⌘K',
- processingTasks: '文件处理任务',
- upload: '上传',
- },
- emptyState: {
- title: '您的上下文空间还是空的',
- upload: '上传文件',
- },
- uploadDialog: {
- title: '上传',
- description: '添加本地文件或远程资源到当前上下文资源库。',
- },
- processingNotice: {
- prefix: '文件正在处理中,点击',
- action: '文件处理任务',
- suffix: '查看处理进度与结果。',
- },
processingTasks: {
title: '文件处理任务',
empty: '暂无处理任务',
@@ -507,70 +472,6 @@ const zhCN = {
failed: '处理失败',
},
},
- searchPalette: {
- ariaLabel: '搜索',
- openContainingDirectory: '打开所在目录',
- placeholder: '搜索',
- scope: {
- global: '搜索范围: 全局',
- current: '搜索范围: {{name}}',
- resetToGlobal: '点击重置为全局搜索',
- },
- scopeState: {
- validatingTitle: '正在校验搜索范围',
- validatingPrefix: '正在检查',
- validatingSuffix: '是否存在',
- switchTitle: '切换搜索范围',
- switchPrefix: '按',
- switchMiddle: '切换到',
- invalidTitle: '搜索范围不存在',
- invalidPrefix: '路径',
- invalidSuffix: '无法访问,不能切换',
- },
- empty: {
- title: '搜索文件和目录',
- },
- browseDirHint: {
- before: '输入',
- after: '浏览目录结构',
- },
- globalScopeHint: {
- before: '输入',
- after: '切换搜索范围到全局',
- },
- error: '搜索出错',
- emptyResults: {
- title: '没有找到匹配的文件或目录',
- subtitle: '试试换个关键词?',
- },
- footer: {
- dirMode: {
- select: '选择',
- level: '层级',
- confirm: '确定',
- cancel: '取消',
- },
- resultMode: {
- navigate: '导航',
- open: '打开',
- close: '关闭',
- count: '{{count}} 个结果',
- },
- },
- },
- dirBrowser: {
- back: '返回上一级',
- loading: '正在加载目录',
- filesSection: '文件',
- error: '加载目录失败',
- empty: {
- title: '空目录',
- subtitle: '这一层目前没有可继续展开的子目录',
- },
- },
- fileList: {
- empty: '当前目录为空',
- },
filePreview: {
cancel: '取消',
edit: '编辑',
@@ -586,21 +487,6 @@ const zhCN = {
save: '保存',
unsupportedBinary: '二进制文件不支持文本预览。',
},
- fileTree: {
- collapse: '收起',
- expand: '展开',
- loading: '加载中...',
- },
- findResults: {
- collapse: '收起',
- expandDetails: '展开详情',
- groups: {
- memories: '记忆',
- resources: '资源',
- skills: '技能',
- },
- noResults: '未找到相关结果',
- },
},
retrieval: {
title: '检索',
@@ -719,8 +605,8 @@ const zhCN = {
scopesLabel: '权限范围',
scopesNone: '(无)',
signInRequired:
- '请先在“连接与身份”中登录 OpenViking Playground,或在下方临时粘贴 API key 完成授权。',
- openConnectionDialog: '打开连接与身份',
+ '请先在“连接与身份”中登录 OpenViking Studio,或在下方临时粘贴 API key 完成授权。',
+ openConnectionSettings: '打开连接与身份',
authorize: '授权',
deny: '拒绝',
useAnotherDevice: '在另一台设备上授权 →',
@@ -742,7 +628,7 @@ const zhCN = {
verifyError: '授权失败:{{message}}',
noApiKey: '没有可用的 API key。请选择一个身份或粘贴 key。',
signInRequired:
- '请先在“连接与身份”中登录 OpenViking Playground,或在下方临时粘贴 API key 完成授权。',
+ '请先在“连接与身份”中登录 OpenViking Studio,或在下方临时粘贴 API key 完成授权。',
},
},
playground: {
diff --git a/web-studio/src/lib/ov-client/client.ts b/web-studio/src/lib/ov-client/client.ts
index 0a7ca7b17..79a19428e 100644
--- a/web-studio/src/lib/ov-client/client.ts
+++ b/web-studio/src/lib/ov-client/client.ts
@@ -18,6 +18,7 @@ const DEFAULT_TELEMETRY_PATHS = new Set([
'/api/v1/search/search',
'/api/v1/resources',
])
+const CONTROL_PLANE_PREFIXES = ['/api/v1/admin', '/api/v1/console'] as const
const SESSION_COMMIT_PATH = /^\/api\/v1\/sessions\/[^/]+\/commit$/
function isBrowser(): boolean {
@@ -118,6 +119,11 @@ function shouldInjectTelemetry(
)
}
+function shouldUseAdminApiKey(config: InternalAxiosRequestConfig): boolean {
+ const pathname = resolvePathname(config.url)
+ return CONTROL_PLANE_PREFIXES.some((prefix) => pathname.startsWith(prefix))
+}
+
function maybeInjectTelemetry(
config: InternalAxiosRequestConfig,
defaultTelemetry: boolean,
@@ -152,10 +158,12 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {
}
let connection: OvConnectionState = {
+ adminApiKey: options.connection?.adminApiKey ?? '',
apiKey:
options.connection?.apiKey ??
readSessionStorage(runtimeOptions.apiKeyStorageKey),
accountId: options.connection?.accountId ?? '',
+ identityHeaders: options.connection?.identityHeaders ?? false,
userId: options.connection?.userId ?? '',
}
@@ -175,9 +183,18 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {
headers.set(key, value)
}
- setOptionalHeader(headers, 'X-API-Key', connection.apiKey)
- setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)
- setOptionalHeader(headers, 'X-OpenViking-User', connection.userId)
+ const apiKey =
+ shouldUseAdminApiKey(config) && connection.adminApiKey
+ ? connection.adminApiKey
+ : connection.apiKey
+ setOptionalHeader(headers, 'X-API-Key', apiKey)
+ if (connection.identityHeaders) {
+ setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)
+ setOptionalHeader(headers, 'X-OpenViking-User', connection.userId)
+ } else {
+ headers.delete('X-OpenViking-Account')
+ headers.delete('X-OpenViking-User')
+ }
config.headers = headers
maybeInjectTelemetry(config, runtimeOptions.defaultTelemetry)
@@ -248,8 +265,10 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {
function clearConnection(): OvConnectionState {
connection = {
+ adminApiKey: '',
apiKey: '',
accountId: '',
+ identityHeaders: false,
userId: '',
}
persistApiKey()
diff --git a/web-studio/src/lib/ov-client/types.ts b/web-studio/src/lib/ov-client/types.ts
index 04a1ad37e..7304c6388 100644
--- a/web-studio/src/lib/ov-client/types.ts
+++ b/web-studio/src/lib/ov-client/types.ts
@@ -5,8 +5,10 @@ import type { Client } from '#/gen/ov-client/client'
export const DEFAULT_API_KEY_STORAGE_KEY = 'ov_console_api_key'
export interface OvConnectionState {
+ adminApiKey: string
apiKey: string
accountId: string
+ identityHeaders: boolean
userId: string
}
diff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.ts
index 99b6d9e01..08e9f5f56 100644
--- a/web-studio/src/lib/sessions/api.ts
+++ b/web-studio/src/lib/sessions/api.ts
@@ -147,8 +147,10 @@ function buildFetchHeaders(): Record<string, string> {
const conn = ovClient.getConnection()
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (conn.apiKey) headers['X-API-Key'] = conn.apiKey
- if (conn.accountId) headers['X-OpenViking-Account'] = conn.accountId
- if (conn.userId) headers['X-OpenViking-User'] = conn.userId
+ if (conn.identityHeaders) {
+ if (conn.accountId) headers['X-OpenViking-Account'] = conn.accountId
+ if (conn.userId) headers['X-OpenViking-User'] = conn.userId
+ }
return headers
}
diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.ts
index d67d1998a..a7e9608be 100644
--- a/web-studio/src/routeTree.gen.ts
+++ b/web-studio/src/routeTree.gen.ts
@@ -12,13 +12,11 @@ import { Route as rootRouteImport } from './routes/__root'
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 ResourcesRouteRouteImport } from './routes/resources/route'
import { Route as RequestLogsRouteRouteImport } from './routes/request-logs/route'
import { Route as PlaygroundRouteRouteImport } from './routes/playground/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 ResourcesIndexRouteImport } from './routes/resources/index'
import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'
import { Route as OauthSetupRouteImport } from './routes/oauth/setup'
import { Route as OauthConsentRouteImport } from './routes/oauth/consent'
@@ -38,11 +36,6 @@ const RetrievalRouteRoute = RetrievalRouteRouteImport.update({
path: '/retrieval',
getParentRoute: () => rootRouteImport,
} as any)
-const ResourcesRouteRoute = ResourcesRouteRouteImport.update({
- id: '/resources',
- path: '/resources',
- getParentRoute: () => rootRouteImport,
-} as any)
const RequestLogsRouteRoute = RequestLogsRouteRouteImport.update({
id: '/request-logs',
path: '/request-logs',
@@ -68,11 +61,6 @@ const SessionsIndexRoute = SessionsIndexRouteImport.update({
path: '/',
getParentRoute: () => SessionsRouteRoute,
} as any)
-const ResourcesIndexRoute = ResourcesIndexRouteImport.update({
- id: '/',
- path: '/',
- getParentRoute: () => ResourcesRouteRoute,
-} as any)
const OauthVerifyRoute = OauthVerifyRouteImport.update({
id: '/oauth/verify',
path: '/oauth/verify',
@@ -94,14 +82,12 @@ export interface FileRoutesByFullPath {
'/home': typeof HomeRouteRoute
'/playground': typeof PlaygroundRouteRoute
'/request-logs': typeof RequestLogsRouteRoute
- '/resources': typeof ResourcesRouteRouteWithChildren
'/retrieval': typeof RetrievalRouteRoute
'/sessions': typeof SessionsRouteRouteWithChildren
'/settings': typeof SettingsRouteRoute
'/oauth/consent': typeof OauthConsentRoute
'/oauth/setup': typeof OauthSetupRoute
'/oauth/verify': typeof OauthVerifyRoute
- '/resources/': typeof ResourcesIndexRoute
'/sessions/': typeof SessionsIndexRoute
}
export interface FileRoutesByTo {
@@ -114,7 +100,6 @@ export interface FileRoutesByTo {
'/oauth/consent': typeof OauthConsentRoute
'/oauth/setup': typeof OauthSetupRoute
'/oauth/verify': typeof OauthVerifyRoute
- '/resources': typeof ResourcesIndexRoute
'/sessions': typeof SessionsIndexRoute
}
export interface FileRoutesById {
@@ -123,14 +108,12 @@ export interface FileRoutesById {
'/home': typeof HomeRouteRoute
'/playground': typeof PlaygroundRouteRoute
'/request-logs': typeof RequestLogsRouteRoute
- '/resources': typeof ResourcesRouteRouteWithChildren
'/retrieval': typeof RetrievalRouteRoute
'/sessions': typeof SessionsRouteRouteWithChildren
'/settings': typeof SettingsRouteRoute
'/oauth/consent': typeof OauthConsentRoute
'/oauth/setup': typeof OauthSetupRoute
'/oauth/verify': typeof OauthVerifyRoute
- '/resources/': typeof ResourcesIndexRoute
'/sessions/': typeof SessionsIndexRoute
}
export interface FileRouteTypes {
@@ -140,14 +123,12 @@ export interface FileRouteTypes {
| '/home'
| '/playground'
| '/request-logs'
- | '/resources'
| '/retrieval'
| '/sessions'
| '/settings'
| '/oauth/consent'
| '/oauth/setup'
| '/oauth/verify'
- | '/resources/'
| '/sessions/'
fileRoutesByTo: FileRoutesByTo
to:
@@ -160,7 +141,6 @@ export interface FileRouteTypes {
| '/oauth/consent'
| '/oauth/setup'
| '/oauth/verify'
- | '/resources'
| '/sessions'
id:
| '__root__'
@@ -168,14 +148,12 @@ export interface FileRouteTypes {
| '/home'
| '/playground'
| '/request-logs'
- | '/resources'
| '/retrieval'
| '/sessions'
| '/settings'
| '/oauth/consent'
| '/oauth/setup'
| '/oauth/verify'
- | '/resources/'
| '/sessions/'
fileRoutesById: FileRoutesById
}
@@ -184,7 +162,6 @@ export interface RootRouteChildren {
HomeRouteRoute: typeof HomeRouteRoute
PlaygroundRouteRoute: typeof PlaygroundRouteRoute
RequestLogsRouteRoute: typeof RequestLogsRouteRoute
- ResourcesRouteRoute: typeof ResourcesRouteRouteWithChildren
RetrievalRouteRoute: typeof RetrievalRouteRoute
SessionsRouteRoute: typeof SessionsRouteRouteWithChildren
SettingsRouteRoute: typeof SettingsRouteRoute
@@ -216,13 +193,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof RetrievalRouteRouteImport
parentRoute: typeof rootRouteImport
}
- '/resources': {
- id: '/resources'
- path: '/resources'
- fullPath: '/resources'
- preLoaderRoute: typeof ResourcesRouteRouteImport
- parentRoute: typeof rootRouteImport
- }
'/request-logs': {
id: '/request-logs'
path: '/request-logs'
@@ -258,13 +228,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SessionsIndexRouteImport
parentRoute: typeof SessionsRouteRoute
}
- '/resources/': {
- id: '/resources/'
- path: '/'
- fullPath: '/resources/'
- preLoaderRoute: typeof ResourcesIndexRouteImport
- parentRoute: typeof ResourcesRouteRoute
- }
'/oauth/verify': {
id: '/oauth/verify'
path: '/oauth/verify'
@@ -289,18 +252,6 @@ declare module '@tanstack/react-router' {
}
}
-interface ResourcesRouteRouteChildren {
- ResourcesIndexRoute: typeof ResourcesIndexRoute
-}
-
-const ResourcesRouteRouteChildren: ResourcesRouteRouteChildren = {
- ResourcesIndexRoute: ResourcesIndexRoute,
-}
-
-const ResourcesRouteRouteWithChildren = ResourcesRouteRoute._addFileChildren(
- ResourcesRouteRouteChildren,
-)
-
interface SessionsRouteRouteChildren {
SessionsIndexRoute: typeof SessionsIndexRoute
}
@@ -318,7 +269,6 @@ const rootRouteChildren: RootRouteChildren = {
HomeRouteRoute: HomeRouteRoute,
PlaygroundRouteRoute: PlaygroundRouteRoute,
RequestLogsRouteRoute: RequestLogsRouteRoute,
- ResourcesRouteRoute: ResourcesRouteRouteWithChildren,
RetrievalRouteRoute: RetrievalRouteRoute,
SessionsRouteRoute: SessionsRouteRouteWithChildren,
SettingsRouteRoute: SettingsRouteRoute,
diff --git a/web-studio/src/routes/oauth/consent.tsx b/web-studio/src/routes/oauth/consent.tsx
index a68801c3f..b52d3c305 100644
--- a/web-studio/src/routes/oauth/consent.tsx
+++ b/web-studio/src/routes/oauth/consent.tsx
@@ -52,7 +52,7 @@ export const Route = createFileRoute('/oauth/consent')({
function ConsentPage() {
const { t } = useTranslation(['oauth', 'common'])
const { pending } = Route.useSearch()
- const { connection, openConnectionDialog, serverMode } = useAppConnection()
+ const { connection, openConnectionSettings, serverMode } = useAppConnection()
const currentIdentity = React.useMemo(() => {
const summary = summarizeConnectionIdentity(connection, serverMode)
@@ -243,12 +243,12 @@ function ConsentPage() {
variant="outline"
size="sm"
className="w-fit"
- onClick={openConnectionDialog}
+ onClick={openConnectionSettings}
disabled={
phase.kind === 'verifying' || phase.kind === 'denying'
}
>
- {t('consent.openConnectionDialog')}
+ {t('consent.openConnectionSettings')}
</Button>
</div>
) : null}
diff --git a/web-studio/src/routes/oauth/verify.tsx b/web-studio/src/routes/oauth/verify.tsx
index 584b33838..b8aaaeb84 100644
--- a/web-studio/src/routes/oauth/verify.tsx
+++ b/web-studio/src/routes/oauth/verify.tsx
@@ -35,7 +35,7 @@ export const Route = createFileRoute('/oauth/verify')({
function VerifyPage() {
const { t } = useTranslation(['oauth', 'common'])
- const { connection, openConnectionDialog, serverMode } = useAppConnection()
+ const { connection, openConnectionSettings, serverMode } = useAppConnection()
const currentIdentity = React.useMemo(() => {
const summary = summarizeConnectionIdentity(connection, serverMode)
@@ -124,10 +124,10 @@ function VerifyPage() {
variant="outline"
size="sm"
className="w-fit"
- onClick={openConnectionDialog}
+ onClick={openConnectionSettings}
disabled={phase.kind === 'verifying'}
>
- {t('consent.openConnectionDialog')}
+ {t('consent.openConnectionSettings')}
</Button>
</div>
) : null}
diff --git a/web-studio/src/routes/playground/-components/agent-panel.tsx b/web-studio/src/routes/playground/-components/agent-panel.tsx
index 34d123a06..0a47f59ad 100644
--- a/web-studio/src/routes/playground/-components/agent-panel.tsx
+++ b/web-studio/src/routes/playground/-components/agent-panel.tsx
@@ -191,8 +191,8 @@ export function AgentPanel({
return (
<>
<div className="flex min-h-0 flex-1 flex-col">
- <div className="border-b bg-background/70 px-4 py-3">
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <div className="flex h-14 shrink-0 items-center border-b bg-background/70 px-4">
+ <div className="flex min-w-0 flex-1 items-center gap-2 text-xs text-muted-foreground">
<BotIcon className="size-3.5 shrink-0" />
<span className="min-w-0 flex-1 truncate">
{t('agent.autoRetrieve')}
diff --git a/web-studio/src/routes/playground/-components/context-explorer.tsx b/web-studio/src/routes/playground/-components/context-explorer.tsx
index 9745b7a3c..917916c3f 100644
--- a/web-studio/src/routes/playground/-components/context-explorer.tsx
+++ b/web-studio/src/routes/playground/-components/context-explorer.tsx
@@ -7,6 +7,7 @@ import {
FileTextIcon,
FolderIcon,
FolderTreeIcon,
+ LoaderCircleIcon,
Loader2Icon,
PlusIcon,
RefreshCcwIcon,
@@ -29,15 +30,23 @@ const TREE_GUIDE_OFFSET = 8
const TREE_CHILD_CONTENT_OFFSET = 26
export function ContextExplorerHeader({
+ activeTaskCount,
+ hasActiveTasks,
isRefreshing,
+ isRefreshingTasks,
onAddResource,
+ onOpenProcessingTasks,
onRefresh,
}: {
+ activeTaskCount: number
+ hasActiveTasks: boolean
isRefreshing: boolean
+ isRefreshingTasks: boolean
onAddResource: () => void
+ onOpenProcessingTasks: () => void
onRefresh: () => void
}) {
- const { t } = useTranslation('playground')
+ const { t } = useTranslation(['playground', 'resources'])
return (
<div className="border-b px-3 py-3">
<div className="flex items-center gap-2">
@@ -47,6 +56,27 @@ export function ContextExplorerHeader({
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold">{t('explorer.title')}</div>
</div>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ className="relative"
+ title={t('processingTasks.title', { ns: 'resources' })}
+ onClick={onOpenProcessingTasks}
+ >
+ <LoaderCircleIcon
+ className={cn(
+ 'size-4',
+ (hasActiveTasks || isRefreshingTasks) &&
+ 'animate-spin text-primary',
+ )}
+ />
+ {activeTaskCount > 0 ? (
+ <span className="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold leading-none text-primary-foreground">
+ {activeTaskCount}
+ </span>
+ ) : null}
+ </Button>
<Button
type="button"
size="icon-sm"
@@ -226,11 +256,13 @@ export function ContextTreeNode({
const select = useCallback(() => {
if (entry.isDir) {
onSelectDirectory(entry)
- toggle()
+ if (!isOpen || isSelected) {
+ toggle()
+ }
} else {
onSelectFile(entry)
}
- }, [entry, onSelectDirectory, onSelectFile, toggle])
+ }, [entry, isOpen, isSelected, onSelectDirectory, onSelectFile, toggle])
return (
<div className="relative min-w-0">
diff --git a/web-studio/src/routes/playground/-lib/types.ts b/web-studio/src/routes/playground/-lib/types.ts
index b6b1965f6..a1a1e9cf2 100644
--- a/web-studio/src/routes/playground/-lib/types.ts
+++ b/web-studio/src/routes/playground/-lib/types.ts
@@ -7,6 +7,7 @@ export type PlaygroundSearch = {
file?: string
panel?: PlaygroundPanel
session?: string
+ upload?: boolean
}
export type ResourceRef = {
diff --git a/web-studio/src/routes/playground/route.tsx b/web-studio/src/routes/playground/route.tsx
index c60bf3ff1..b6de708f4 100644
--- a/web-studio/src/routes/playground/route.tsx
+++ b/web-studio/src/routes/playground/route.tsx
@@ -15,7 +15,11 @@ import {
} from '#/components/ui/dialog'
import { FilePreview } from '#/routes/resources/-components/file-preview'
import { AddResourceForm } from '#/routes/resources/-components/add-resource-page'
-import { ResourceUploadProvider } from '#/routes/resources/-hooks/use-resource-upload'
+import { UploadTaskDialog } from '#/routes/resources/-components/upload-task-dialog'
+import {
+ ResourceUploadProvider,
+ useResourceUpload,
+} from '#/routes/resources/-hooks/use-resource-upload'
import {
useInvalidateVikingFs,
useVikingFsList,
@@ -66,6 +70,7 @@ export const Route = createFileRoute('/playground')({
? search.panel
: undefined,
session: typeof search.session === 'string' ? search.session : undefined,
+ upload: search.upload === true || search.upload === 'true',
uri: typeof search.uri === 'string' ? search.uri : undefined,
}),
component: PlaygroundRoute,
@@ -103,7 +108,10 @@ function PlaygroundWorkbench() {
const [activePanel, setActivePanel] = useState<PlaygroundPanel>(
search.panel ?? 'agent',
)
- const [uploadDialogOpen, setUploadDialogOpen] = useState(false)
+ const [uploadDialogOpen, setUploadDialogOpen] = useState(
+ () => search.upload ?? false,
+ )
+ const [taskDialogOpen, setTaskDialogOpen] = useState(false)
const [openingUri, setOpeningUri] = useState<string | null>(null)
const layoutRef = useRef<HTMLDivElement>(null)
const [leftWidth, setLeftWidth] = useState(() =>
@@ -137,6 +145,13 @@ function PlaygroundWorkbench() {
showAllHidden: true,
nodeLimit: 500,
})
+ const {
+ activeTaskCount,
+ hasActiveTasks,
+ isRefreshingTasks,
+ refreshTasks,
+ tasks,
+ } = useResourceUpload()
const { invalidateList } = useInvalidateVikingFs()
const syncSearch = useCallback(
@@ -144,6 +159,7 @@ function PlaygroundWorkbench() {
file?: string
panel?: PlaygroundPanel
session?: string
+ upload?: boolean
uri?: string
}) => {
navigate({
@@ -176,6 +192,22 @@ function PlaygroundWorkbench() {
}
}, [search.panel])
+ useEffect(() => {
+ if (search.upload) {
+ setUploadDialogOpen(true)
+ }
+ }, [search.upload])
+
+ const handleUploadDialogOpenChange = useCallback(
+ (open: boolean) => {
+ setUploadDialogOpen(open)
+ if (!open && search.upload) {
+ syncSearch({ upload: undefined })
+ }
+ },
+ [search.upload, syncSearch],
+ )
+
const revealResource = useCallback(
async (rawUri: string) => {
const cleaned = cleanVikingUri(rawUri)
@@ -281,6 +313,11 @@ function PlaygroundWorkbench() {
[syncSearch],
)
+ const handleOpenProcessingTasks = useCallback(() => {
+ setTaskDialogOpen(true)
+ void refreshTasks()
+ }, [refreshTasks])
+
const selectedUri = selectedFile?.uri ?? currentUri
const displayUri =
selectedUri === ROOT_URI ? selectedUri : selectedUri.replace(/\/$/, '')
@@ -391,13 +428,17 @@ function PlaygroundWorkbench() {
<div className="-mx-4 -my-6 flex h-[calc(100svh-3rem)] min-h-0 flex-col bg-background md:-mx-6">
<div
ref={layoutRef}
- className="flex min-h-0 flex-1 flex-col border-t bg-background lg:flex-row"
+ className="flex min-h-0 flex-1 flex-col bg-background lg:flex-row"
style={layoutStyle}
>
<aside className="flex min-h-[260px] min-w-0 flex-col border-b bg-muted/20 lg:min-h-0 lg:w-[var(--playground-left-width)] lg:min-w-[var(--playground-left-width)] lg:border-b-0">
<ContextExplorerHeader
+ activeTaskCount={activeTaskCount}
+ hasActiveTasks={hasActiveTasks}
isRefreshing={listQuery.isFetching}
+ isRefreshingTasks={isRefreshingTasks}
onAddResource={() => setUploadDialogOpen(true)}
+ onOpenProcessingTasks={handleOpenProcessingTasks}
onRefresh={() => {
void invalidateList(currentUri)
void listQuery.refetch()
@@ -448,6 +489,7 @@ function PlaygroundWorkbench() {
<div className="min-h-0 flex-1">
<FilePreview
file={selectedFile}
+ hideDirectoryHeader
onClose={() => setSelectedFile(null)}
showCloseButton={false}
/>
@@ -497,7 +539,10 @@ function PlaygroundWorkbench() {
</aside>
</div>
- <Dialog open={uploadDialogOpen} onOpenChange={setUploadDialogOpen}>
+ <Dialog
+ open={uploadDialogOpen}
+ onOpenChange={handleUploadDialogOpenChange}
+ >
<DialogContent className="max-h-[min(86vh,760px)] gap-0 overflow-hidden p-0 sm:max-w-4xl">
<DialogHeader className="border-b px-6 py-5">
<DialogTitle className="text-xl">
@@ -510,7 +555,7 @@ function PlaygroundWorkbench() {
<div className="max-h-[calc(min(86vh,760px)-6rem)] overflow-y-auto px-6 py-5">
<AddResourceForm
onSubmitted={() => {
- setUploadDialogOpen(false)
+ handleUploadDialogOpenChange(false)
void invalidateList()
toast.success(t('addResource.submitted'))
}}
@@ -518,6 +563,11 @@ function PlaygroundWorkbench() {
</div>
</DialogContent>
</Dialog>
+ <UploadTaskDialog
+ open={taskDialogOpen}
+ onOpenChange={setTaskDialogOpen}
+ tasks={tasks}
+ />
</div>
)
}
diff --git a/web-studio/src/routes/resources/-components/dir-browser.tsx b/web-studio/src/routes/resources/-components/dir-browser.tsx
deleted file mode 100644
index bbfbde067..000000000
--- a/web-studio/src/routes/resources/-components/dir-browser.tsx
+++ /dev/null
@@ -1,238 +0,0 @@
-import { useMemo } from 'react'
-import type { TFunction } from 'i18next'
-import { ArrowLeft, Folder, Loader2 } from 'lucide-react'
-import { useTranslation } from 'react-i18next'
-
-import { cn } from '#/lib/utils'
-
-import { normalizeDirUri, fileNameFromUri } from '../-lib/normalize'
-import { useVikingFsList, useDebouncedValue } from '../-hooks/viking-fm'
-import type { VikingFsEntry } from '../-types/viking-fm'
-import { FilePreview } from './file-preview'
-import { ItemColumn } from './item-column'
-
-const VIKING_ROOT_URI = 'viking://'
-
-// Pure controlled view. The browsed directory (currentUri), the item list and
-// the cursor (activeIndex) are all owned by FindPalette; this component only
-// renders and reports intent via callbacks — no internal focus state, no
-// document keyboard listener, no two-way sync ref.
-interface DirBrowserProps {
- currentUri: string
- items: VikingFsEntry[]
- activeIndex: number
- loading?: boolean
- errored?: boolean
- onCursorChange: (index: number) => void
- onEnterDir: (uri: string) => void
- onOpenFile: (uri: string) => void
- onGoBack: () => void
-}
-
-// What the right (detail) pane shows, computed once as an explicit value so the
-// render is a flat switch instead of a 6-deep ternary chain.
-type DetailView =
- | { kind: 'preview'; file: VikingFsEntry }
- | { kind: 'loading' }
- | { kind: 'error' }
- | { kind: 'subdir'; items: VikingFsEntry[]; label: string }
- | { kind: 'empty' }
- | { kind: 'idle' }
-
-export function DirBrowser({
- currentUri,
- items,
- activeIndex,
- loading = false,
- errored = false,
- onCursorChange,
- onEnterDir,
- onOpenFile,
- onGoBack,
-}: DirBrowserProps) {
- const { t } = useTranslation('resources')
-
- // activeIndex can transiently fall out of range while the list reshapes, so
- // the cursor really is nullable (bounds check keeps the union honest).
- const cursorItem =
- activeIndex >= 0 && activeIndex < items.length ? items[activeIndex] : null
-
- // Peek (right pane) is a pure derivation of the cursor item. Debounced so
- // arrow-scanning a long directory doesn't fire a request per row.
- const subdirUri = cursorItem?.isDir ? normalizeDirUri(cursorItem.uri) : null
- const debouncedSubdirUri = useDebouncedValue(subdirUri, 150)
- const subdirQuery = useVikingFsList(
- debouncedSubdirUri || VIKING_ROOT_URI,
- { output: 'agent', showAllHidden: true, nodeLimit: 200 },
- Boolean(debouncedSubdirUri),
- )
- const subdirItems = useMemo(() => {
- if (!debouncedSubdirUri || !subdirQuery.data?.entries) return []
- const entries = subdirQuery.data.entries
- const dirs = entries.filter((e) => e.isDir)
- const files = entries.filter((e) => !e.isDir)
- return [...dirs, ...files]
- }, [debouncedSubdirUri, subdirQuery.data])
- const peekPending = Boolean(subdirUri) && subdirUri !== debouncedSubdirUri
-
- const canGoBack = currentUri !== VIKING_ROOT_URI
-
- const detail = useMemo<DetailView>(() => {
- if (!cursorItem) return { kind: 'idle' }
- if (!cursorItem.isDir) return { kind: 'preview', file: cursorItem }
- if (peekPending || subdirQuery.isLoading) return { kind: 'loading' }
- if (subdirQuery.isError) return { kind: 'error' }
- if (subdirItems.length > 0) {
- return {
- kind: 'subdir',
- items: subdirItems,
- label: fileNameFromUri(cursorItem.uri),
- }
- }
- return { kind: 'empty' }
- }, [
- cursorItem,
- peekPending,
- subdirQuery.isLoading,
- subdirQuery.isError,
- subdirItems,
- ])
-
- return (
- <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
- <div className="flex items-center justify-between border-b bg-background/85 px-3 py-2 backdrop-blur-sm">
- <button
- type="button"
- onClick={() => {
- if (canGoBack) onGoBack()
- }}
- disabled={!canGoBack}
- className={cn(
- 'inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium transition-colors',
- canGoBack
- ? 'text-foreground/75 hover:bg-muted hover:text-foreground'
- : 'cursor-not-allowed text-muted-foreground/45',
- )}
- >
- <ArrowLeft className="size-3.5" />
- <span>{t('dirBrowser.back')}</span>
- </button>
- <div className="max-w-[55%] truncate rounded-md bg-blue-500/10 px-2.5 py-1 text-sm font-semibold text-blue-700 dark:text-blue-300">
- {currentUri}
- </div>
- </div>
- <div className="flex min-h-0 flex-1 min-w-0 justify-start overflow-hidden bg-[linear-gradient(180deg,color-mix(in_oklch,var(--muted)_35%,transparent),transparent_18%)]">
- {loading ? (
- <div className="flex flex-1 items-center justify-center">
- <Loader2 className="size-4 animate-spin text-muted-foreground" />
- </div>
- ) : errored ? (
- <div
- role="alert"
- className="flex flex-1 items-center justify-center px-6 text-sm text-destructive"
- >
- {t('dirBrowser.error')}
- </div>
- ) : (
- <>
- <ItemColumn
- className="w-[clamp(15rem,35vw,22rem)] shrink-0"
- label={fileNameFromUri(currentUri.replace(/\/$/, '')) || '/'}
- items={items}
- activeIndex={activeIndex}
- t={t}
- onSelect={(entry, i) =>
- entry.isDir ? onEnterDir(entry.uri) : onCursorChange(i)
- }
- />
- <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden border-l">
- <DetailPane
- detail={detail}
- t={t}
- onEnterDir={onEnterDir}
- onOpenFile={onOpenFile}
- />
- </div>
- </>
- )}
- </div>
- </div>
- )
-}
-
-function DetailPane({
- detail,
- t,
- onEnterDir,
- onOpenFile,
-}: {
- detail: DetailView
- t: TFunction<'resources'>
- onEnterDir: (uri: string) => void
- onOpenFile: (uri: string) => void
-}) {
- switch (detail.kind) {
- case 'preview':
- return (
- <FilePreview
- file={detail.file}
- onClose={() => {}}
- showCloseButton={false}
- />
- )
- case 'loading':
- return (
- <div className="flex flex-1 items-center justify-center">
- <Loader2 className="size-4 animate-spin text-muted-foreground" />
- </div>
- )
- case 'error':
- return (
- <div
- role="alert"
- className="flex flex-1 items-center justify-center px-6 text-sm text-destructive"
- >
- {t('dirBrowser.error')}
- </div>
- )
- case 'subdir':
- return (
- <ItemColumn
- className="min-w-0 flex-1"
- label={detail.label}
- items={detail.items}
- activeIndex={-1}
- t={t}
- onSelect={(entry) => {
- if (entry.isDir) {
- onEnterDir(entry.uri)
- return
- }
- onOpenFile(entry.uri)
- }}
- />
- )
- case 'empty':
- return (
- <div className="flex flex-1 items-center justify-center px-6">
- <div className="max-w-[13rem] text-center">
- <div className="mx-auto mb-3 flex size-10 items-center justify-center rounded-2xl bg-muted/60 text-muted-foreground/70 shadow-inner">
- <Folder className="size-4" />
- </div>
- <p className="text-sm font-medium text-foreground/70">
- {t('dirBrowser.empty.title')}
- </p>
- <p className="mt-1 text-xs leading-5 text-muted-foreground/75">
- {t('dirBrowser.empty.subtitle')}
- </p>
- </div>
- </div>
- )
- case 'idle':
- return (
- <div className="flex flex-1 items-center justify-center px-6 text-sm text-muted-foreground/60">
- {t('dirBrowser.empty.title')}
- </div>
- )
- }
-}
diff --git a/web-studio/src/routes/resources/-components/file-list.tsx b/web-studio/src/routes/resources/-components/file-list.tsx
deleted file mode 100644
index cd0f9086e..000000000
--- a/web-studio/src/routes/resources/-components/file-list.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import { useMemo } from 'react'
-import { File, Folder } from 'lucide-react'
-import { useTranslation } from 'react-i18next'
-
-import { cn } from '#/lib/utils'
-
-import { formatSize } from '../-lib/normalize'
-import type { VikingFsEntry } from '../-types/viking-fm'
-
-type SortKey = 'name' | 'size' | 'modTime'
-type SortDirection = 'asc' | 'desc'
-
-interface FileListProps {
- entries: Array<VikingFsEntry>
- selectedFileUri: string | null
- onOpenDirectory: (entry: VikingFsEntry) => void
- onOpenFile: (file: VikingFsEntry) => void
-}
-
-function compareEntries(
- left: VikingFsEntry,
- right: VikingFsEntry,
- sortKey: SortKey,
- sortDirection: SortDirection,
-): number {
- if (left.isDir !== right.isDir) {
- return left.isDir ? -1 : 1
- }
-
- let comparison = 0
- if (sortKey === 'name') {
- comparison = left.name.localeCompare(right.name)
- } else if (sortKey === 'size') {
- comparison = (left.sizeBytes ?? -1) - (right.sizeBytes ?? -1)
- } else {
- comparison = (left.modTimestamp ?? 0) - (right.modTimestamp ?? 0)
- }
-
- return sortDirection === 'asc' ? comparison : -comparison
-}
-
-export function FileList({
- entries,
- selectedFileUri,
- onOpenDirectory,
- onOpenFile,
-}: FileListProps) {
- const { t } = useTranslation('resources')
- const sortKey: SortKey = 'name'
- const sortDirection: SortDirection = 'asc'
-
- const sortedEntries = useMemo(
- () =>
- [...entries].sort((left, right) =>
- compareEntries(left, right, sortKey, sortDirection),
- ),
- [entries, sortKey, sortDirection],
- )
-
- return (
- <div>
- {!sortedEntries.length ? (
- <div className="px-4 py-8 text-center text-sm text-muted-foreground">
- {t('fileList.empty')}
- </div>
- ) : null}
-
- {sortedEntries.map((entry) => {
- const isSelected = selectedFileUri === entry.uri
-
- return (
- <button
- key={entry.uri}
- className={cn(
- 'flex w-full items-center gap-2 border-b px-4 py-1.5 text-left text-xs transition-colors hover:bg-muted/50 md:py-2 md:text-sm',
- isSelected && 'bg-muted',
- )}
- type="button"
- onClick={() => {
- if (entry.isDir) {
- onOpenDirectory(entry)
- return
- }
- onOpenFile(entry)
- }}
- >
- {entry.isDir ? (
- <Folder className="size-4 shrink-0 fill-gray-700 text-gray-700 dark:fill-gray-300 dark:text-gray-300" />
- ) : (
- <File className="size-4 shrink-0 text-muted-foreground" />
- )}
- <span className="min-w-0 truncate">{entry.name}</span>
- <span className="ml-auto flex shrink-0 items-center gap-4 text-xs text-muted-foreground">
- <span>
- {entry.isDir ? '-' : formatSize(entry.sizeBytes ?? entry.size)}
- </span>
- <span className="w-20 text-right">{entry.modTime || '-'}</span>
- </span>
- </button>
- )
- })}
- </div>
- )
-}
diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsx
index 9bad5a1f0..c7343941d 100644
--- a/web-studio/src/routes/resources/-components/file-preview.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.tsx
@@ -101,6 +101,7 @@ async function ensureLanguage(lang: string): Promise<void> {
interface FilePreviewProps {
file: VikingFsEntry | null
+ hideDirectoryHeader?: boolean
onClose: () => void
showCloseButton?: boolean
}
@@ -725,7 +726,10 @@ function JsonlToolBody({ text, toolName }: { text: string; toolName: string }) {
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]} components={markdownComponents}>
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ components={markdownComponents}
+ >
{content || 'Empty message'}
</ReactMarkdown>
</div>
@@ -892,6 +896,7 @@ function JsonlPreview({ content }: { content: string }) {
export function FilePreview({
file,
+ hideDirectoryHeader = false,
onClose,
showCloseButton = true,
}: FilePreviewProps) {
@@ -1079,67 +1084,74 @@ export function FilePreview({
const visibleDirectoryLevels = availableDirectoryLevels.filter((level) =>
activeDirectoryLevels.has(level.id),
)
+ const showHeader = !(hideDirectoryHeader && file.isDir)
return (
<div className="flex h-full min-h-0 flex-col overflow-hidden">
- <div className="flex items-center justify-between border-b px-4 py-3">
- <div className="flex min-w-0 items-center gap-2">
- <div className="min-w-0">
- <div className="truncate text-sm font-medium">{file.name}</div>
- <div className="text-xs text-muted-foreground">
- {file.isDir ? 'Folder' : formatSize(file.sizeBytes ?? file.size)}{' '}
- · {file.modTime || '-'}
+ {showHeader ? (
+ <div className="flex min-h-14 items-center justify-between border-b px-4">
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium leading-5">
+ {file.name}
+ </div>
+ {!file.isDir ? (
+ <div className="text-xs leading-5 text-muted-foreground">
+ {formatSize(file.sizeBytes ?? file.size)} ·{' '}
+ {file.modTime || '-'}
+ </div>
+ ) : null}
</div>
+ {editing ? (
+ <div className="flex items-center gap-1">
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={saving}
+ onClick={() => setEditing(false)}
+ >
+ <XCircle className="mr-1 size-3.5" />
+ {t('filePreview.cancel')}
+ </Button>
+ <Button
+ size="sm"
+ className="active:scale-[0.96] transition-transform"
+ disabled={saving}
+ onClick={handleSave}
+ >
+ {saving ? (
+ <Loader2 className="mr-1 size-3.5 animate-spin" />
+ ) : (
+ <Save className="mr-1 size-3.5" />
+ )}
+ {t('filePreview.save')}
+ </Button>
+ </div>
+ ) : (
+ canEdit && (
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => setEditing(true)}
+ >
+ <Pencil className="mr-1 size-3.5" />
+ {t('filePreview.edit')}
+ </Button>
+ )
+ )}
</div>
- {editing ? (
- <div className="flex items-center gap-1">
- <Button
- size="sm"
- variant="ghost"
- disabled={saving}
- onClick={() => setEditing(false)}
- >
- <XCircle className="mr-1 size-3.5" />
- {t('filePreview.cancel')}
- </Button>
- <Button
- size="sm"
- className="active:scale-[0.96] transition-transform"
- disabled={saving}
- onClick={handleSave}
- >
- {saving ? (
- <Loader2 className="mr-1 size-3.5 animate-spin" />
- ) : (
- <Save className="mr-1 size-3.5" />
- )}
- {t('filePreview.save')}
- </Button>
- </div>
- ) : (
- canEdit && (
- <Button
- size="sm"
- variant="ghost"
- onClick={() => setEditing(true)}
- >
- <Pencil className="mr-1 size-3.5" />
- {t('filePreview.edit')}
- </Button>
- )
- )}
+ {showCloseButton ? (
+ <Button
+ size="icon"
+ variant="ghost"
+ className="size-10"
+ onClick={onClose}
+ >
+ <X className="size-4" />
+ </Button>
+ ) : null}
</div>
- {showCloseButton ? (
- <Button
- size="icon"
- variant="ghost"
- className="size-10"
- onClick={onClose}
- >
- <X className="size-4" />
- </Button>
- ) : null}
- </div>
+ ) : null}
{editing && preview?.content != null ? (
<div className="h-full min-h-0 p-2">
diff --git a/web-studio/src/routes/resources/-components/file-tree.tsx b/web-studio/src/routes/resources/-components/file-tree.tsx
deleted file mode 100644
index 1487f635c..000000000
--- a/web-studio/src/routes/resources/-components/file-tree.tsx
+++ /dev/null
@@ -1,279 +0,0 @@
-import { memo, useCallback, useRef } from 'react'
-import { File } from 'lucide-react'
-import { useTranslation } from 'react-i18next'
-
-import { cn } from '#/lib/utils'
-
-import { usePrefetchVikingFsList, useVikingFsList } from '../-hooks/viking-fm'
-import type { VikingFsEntry } from '../-types/viking-fm'
-
-interface FileTreeProps {
- currentUri: string
- selectedFileUri?: string | null
- expandedKeys: Set<string>
- onExpandedKeysChange: (next: Set<string>) => void
- onSelectDirectory: (entry: VikingFsEntry) => void
- onSelectFile?: (entry: VikingFsEntry) => void
-}
-
-interface TreeNodeProps {
- entry: VikingFsEntry
- level: number
- currentUri: string
- selectedFileUri?: string | null
- expandedKeys: Set<string>
- onExpandedKeysChange: (next: Set<string>) => void
- onSelectDirectory: (entry: VikingFsEntry) => void
- onSelectFile?: (entry: VikingFsEntry) => void
- prefetch?: (uri: string) => void
-}
-
-const FolderIcon = ({ isOpen }: { isOpen: boolean }) => (
- <svg
- className="size-4 shrink-0 text-foreground/70"
- viewBox="0 0 24 24"
- fill="currentColor"
- stroke="none"
- >
- {isOpen ? (
- <path d="M5 19a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h4l2 2h4a2 2 0 0 1 2 2v1M5 19h14a2 2 0 0 0 2-2v-5a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2z" />
- ) : (
- <path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z" />
- )}
- </svg>
-)
-
-const ChevronIcon = ({ isOpen }: { isOpen: boolean }) => (
- <svg
- className={cn(
- 'size-4 shrink-0 text-muted-foreground transition-transform',
- isOpen && 'rotate-90',
- )}
- viewBox="0 0 20 20"
- fill="currentColor"
- >
- <path
- fillRule="evenodd"
- d="M7.293 14.707a1 1 0 0 1 0-1.414L10.586 10 7.293 6.707a1 1 0 0 1 1.414-1.414l4 4a1 1 0 0 1 0 1.414l-4 4a1 1 0 0 1-1.414 0z"
- clipRule="evenodd"
- />
- </svg>
-)
-
-const LIST_OPTS = {
- output: 'agent' as const,
- showAllHidden: true,
- nodeLimit: 200,
-}
-
-function isSessionSubtree(parentUri: string): boolean {
- // Children of viking://session and anything nested inside it sort by
- // modTime DESC (most recent first) instead of name.
- return parentUri.startsWith('viking://session/')
-}
-
-function sortEntries(
- entries: VikingFsEntry[],
- parentUri: string,
-): VikingFsEntry[] {
- const byModTime = isSessionSubtree(parentUri)
- return [...entries].sort((a, b) => {
- if (a.isDir !== b.isDir) return a.isDir ? -1 : 1
- if (byModTime) {
- const at = a.modTimestamp ?? 0
- const bt = b.modTimestamp ?? 0
- if (at !== bt) return bt - at
- }
- return a.name.localeCompare(b.name)
- })
-}
-
-function TreeNode({
- entry,
- level,
- currentUri,
- selectedFileUri,
- expandedKeys,
- onExpandedKeysChange,
- onSelectDirectory,
- onSelectFile,
- prefetch,
-}: TreeNodeProps) {
- const { t } = useTranslation('resources')
- const isOpen = expandedKeys.has(entry.uri)
- const isDirSelected =
- entry.isDir && currentUri === entry.uri && !selectedFileUri
- const isFileSelected = !entry.isDir && selectedFileUri === entry.uri
-
- const entryRef = useRef(entry)
- entryRef.current = entry
-
- const { data } = useVikingFsList(entry.uri, LIST_OPTS, entry.isDir)
- const children: VikingFsEntry[] = entry.isDir
- ? sortEntries(data?.entries ?? [], entry.uri)
- : []
-
- const handleToggle = useCallback(() => {
- const next = new Set(expandedKeys)
- if (isOpen) {
- next.delete(entry.uri)
- } else {
- for (const key of next) {
- if (key !== entry.uri && key.startsWith(entry.uri)) {
- next.delete(key)
- }
- }
- next.add(entry.uri)
- }
- onExpandedKeysChange(next)
- }, [expandedKeys, isOpen, entry.uri, onExpandedKeysChange])
-
- const handleSelect = useCallback(() => {
- if (entryRef.current.isDir) {
- onSelectDirectory(entryRef.current)
- } else {
- onSelectFile?.(entryRef.current)
- }
- }, [onSelectDirectory, onSelectFile])
-
- const handleMouseEnter = useCallback(() => {
- if (entry.isDir && !isOpen && prefetch) prefetch(entry.uri)
- }, [entry.isDir, entry.uri, isOpen, prefetch])
-
- if (!entry.isDir) {
- return (
- <div
- className="relative text-foreground"
- style={{ marginLeft: `${level * 16}px` }}
- >
- {level > 0 && (
- <span className="absolute -left-2 top-1/2 h-3 w-2 -translate-y-1/2 rounded-bl-md border-b border-l border-border" />
- )}
- <div
- className={cn(
- 'flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 transition-colors md:py-1.5',
- isFileSelected ? 'bg-muted text-foreground' : 'hover:bg-muted/50',
- )}
- onClick={handleSelect}
- >
- <span aria-hidden className="inline-flex size-4 shrink-0" />
- <File className="size-4 shrink-0 text-muted-foreground" />
- <span className="min-w-0 truncate text-xs md:text-sm">{entry.name}</span>
- </div>
- </div>
- )
- }
-
- return (
- <div className="relative text-foreground">
- <div className="relative" style={{ marginLeft: `${level * 16}px` }}>
- {level > 0 && (
- <span className="absolute -left-2 top-1/2 h-3 w-2 -translate-y-1/2 rounded-bl-md border-b border-l border-border" />
- )}
- <div
- className={cn(
- 'flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 transition-colors md:py-1.5',
- isDirSelected ? 'bg-muted text-foreground' : 'hover:bg-muted/50',
- )}
- onClick={handleSelect}
- onMouseEnter={handleMouseEnter}
- >
- {!data || children.length > 0 ? (
- <button
- type="button"
- className="inline-flex shrink-0"
- onClick={(e) => {
- e.stopPropagation()
- handleToggle()
- }}
- aria-label={
- isOpen ? t('fileTree.collapse') : t('fileTree.expand')
- }
- >
- <ChevronIcon isOpen={isOpen} />
- </button>
- ) : (
- <span aria-hidden className="inline-flex size-4 shrink-0" />
- )}
- <FolderIcon isOpen={isOpen} />
- <span className="min-w-0 truncate text-xs md:text-sm">{entry.name}</span>
- </div>
- </div>
- <div
- className={cn(
- 'grid transition-[grid-template-rows] duration-300 ease-in-out',
- isOpen ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]',
- )}
- >
- <div className="overflow-hidden">
- {isOpen && !data && (
- <div
- className="px-2 py-1 text-xs text-muted-foreground"
- style={{ marginLeft: `${(level + 1) * 16}px` }}
- >
- {t('fileTree.loading')}
- </div>
- )}
- {isOpen &&
- children.map((child) => (
- <TreeNodeMemo
- key={child.uri}
- entry={child}
- level={level + 1}
- currentUri={currentUri}
- selectedFileUri={selectedFileUri}
- expandedKeys={expandedKeys}
- onExpandedKeysChange={onExpandedKeysChange}
- onSelectDirectory={onSelectDirectory}
- onSelectFile={onSelectFile}
- prefetch={prefetch}
- />
- ))}
- </div>
- </div>
- </div>
- )
-}
-
-const TreeNodeMemo = memo(TreeNode)
-
-const ROOT_ENTRY: VikingFsEntry = {
- uri: 'viking://',
- name: 'viking://',
- isDir: true,
- size: '',
- sizeBytes: null,
- modTime: '',
- modTimestamp: null,
- abstract: '',
- overview: '',
-}
-
-export function FileTree({
- currentUri,
- selectedFileUri,
- expandedKeys,
- onExpandedKeysChange,
- onSelectDirectory,
- onSelectFile,
-}: FileTreeProps) {
- const { prefetch } = usePrefetchVikingFsList()
-
- return (
- <div className="h-full overflow-auto font-mono">
- <div className="min-w-0 p-2">
- <TreeNodeMemo
- entry={ROOT_ENTRY}
- level={0}
- currentUri={currentUri}
- selectedFileUri={selectedFileUri}
- expandedKeys={expandedKeys}
- onExpandedKeysChange={onExpandedKeysChange}
- onSelectDirectory={onSelectDirectory}
- onSelectFile={onSelectFile}
- prefetch={prefetch}
- />
- </div>
- </div>
- )
-}
diff --git a/web-studio/src/routes/resources/-components/find-palette.tsx b/web-studio/src/routes/resources/-components/find-palette.tsx
deleted file mode 100644
index 9cfc8dda9..000000000
--- a/web-studio/src/routes/resources/-components/find-palette.tsx
+++ /dev/null
@@ -1,664 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import {
- FileIcon,
- FolderIcon,
- FolderOpen,
- Loader2,
- Search,
- X,
-} from 'lucide-react'
-import { useTranslation } from 'react-i18next'
-
-import { cn } from '#/lib/utils'
-import { useTransientScrollbar } from '#/hooks/use-transient-scrollbar'
-
-import {
- fileNameFromUri,
- normalizeDirUri,
- parentUri as getParentUri,
-} from '../-lib/normalize'
-import {
- filterResourceSearchEntries,
- getResourceSearchSpec,
-} from '../-lib/find-search'
-import {
- PALETTE_ROOT_URI,
- buildDirBrowseQuery,
- isResetGlobalCommand,
- parsePaletteMode,
-} from '../-lib/palette-mode'
-import {
- useVikingFsList,
- useVikingFsStat,
- useVikingFsTree,
- useDebouncedValue,
-} from '../-hooks/viking-fm'
-import { useListNavigation } from '../-hooks/use-list-navigation'
-import type { VikingFsEntry } from '../-types/viking-fm'
-import { FilePreview } from './file-preview'
-import { DirBrowser } from './dir-browser'
-
-interface FindPaletteProps {
- open: boolean
- onClose: () => void
- onNavigate: (uri: string) => void
- onNavigateDir: (uri: string) => void
- scopeUri?: string
-}
-const KEY_ESCAPE_LABEL = 'esc'
-
-function displayName(uri: string): { name: string; parent: string } {
- const name = fileNameFromUri(uri)
- const dir = getParentUri(uri)
- const segments = dir.replace(/\/$/, '').split('/').filter(Boolean)
- const parent = segments.length > 1 ? segments.slice(-1)[0] : dir
- return { name, parent }
-}
-
-export function FindPalette({
- open,
- onClose,
- onNavigate,
- onNavigateDir,
- scopeUri,
-}: FindPaletteProps) {
- const { t } = useTranslation('resources')
- const [query, setQuery] = useState('')
- const [findTargetUri, setFindTargetUri] = useState(() =>
- normalizeDirUri(scopeUri || PALETTE_ROOT_URI),
- )
- const inputRef = useRef<HTMLInputElement>(null)
- const resultsRef = useRef<HTMLDivElement>(null)
- const composingRef = useRef(false)
-
- // Single parse entry point. No component code reads `query` structurally.
- const mode = useMemo(
- () => parsePaletteMode(query, findTargetUri),
- [query, findTargetUri],
- )
- const isRoot = findTargetUri === PALETTE_ROOT_URI
- const showIdleBrowse = mode.kind === 'idle' && !isRoot
-
- const searchSpec = useMemo(
- () =>
- mode.kind === 'search'
- ? getResourceSearchSpec(mode.query, findTargetUri)
- : null,
- [mode, findTargetUri],
- )
-
- const idleBrowseQuery = useVikingFsList(
- findTargetUri,
- { output: 'agent', showAllHidden: true },
- showIdleBrowse,
- )
- const idleEntries = useMemo(
- () => (showIdleBrowse ? idleBrowseQuery.data?.entries || [] : []),
- [showIdleBrowse, idleBrowseQuery.data?.entries],
- )
-
- const treeQuery = useVikingFsTree(
- searchSpec?.rootUri || PALETTE_ROOT_URI,
- { output: 'agent', showAllHidden: true, nodeLimit: 2000, levelLimit: 100 },
- mode.kind === 'search' && Boolean(searchSpec),
- )
- const filteredEntries = useMemo(() => {
- if (mode.kind !== 'search' || !treeQuery.data?.nodes) return []
- return filterResourceSearchEntries(treeQuery.data.nodes, searchSpec)
- }, [mode.kind, treeQuery.data?.nodes, searchSpec])
-
- // Directory listing lifted up from DirBrowser so the cursor (activeIndex) and
- // keyboard handling can live in one place. DirBrowser is now a pure view.
- const dirListQuery = useVikingFsList(
- mode.kind === 'dirBrowse' ? mode.uri : PALETTE_ROOT_URI,
- { output: 'agent', showAllHidden: true, nodeLimit: 200 },
- mode.kind === 'dirBrowse',
- )
- const dirItems = useMemo(() => {
- if (mode.kind !== 'dirBrowse') return []
- const entries = dirListQuery.data?.entries ?? []
- const dirs = entries.filter((e) => e.isDir)
- const files = entries.filter((e) => !e.isDir)
- const all = [...dirs, ...files]
- if (!mode.filter) return all
- const lower = mode.filter.toLowerCase()
- return all.filter((e) => e.name.toLowerCase().includes(lower))
- }, [mode, dirListQuery.data])
- const hasResults = filteredEntries.length > 0
- const visibleEntries = useMemo(() => {
- if (mode.kind === 'dirBrowse') return dirItems
- if (hasResults) return filteredEntries
- return idleEntries
- }, [mode.kind, dirItems, hasResults, filteredEntries, idleEntries])
-
- const { index: activeIndex, setIndex, moveUp, moveDown, reset } =
- useListNavigation(visibleEntries.length)
- const activeEntry = activeIndex >= 0 ? (visibleEntries[activeIndex] ?? null) : null
-
- // Preview stat only for search / idle file cursor. dirBrowse renders its own
- // preview inside DirBrowser. Debounced so arrow-scanning doesn't storm stat.
- const statTargetUri =
- mode.kind !== 'dirBrowse' && activeEntry && !activeEntry.isDir
- ? activeEntry.uri
- : undefined
- const debouncedStatUri = useDebouncedValue(statTargetUri, 150)
- const statQuery = useVikingFsStat(debouncedStatUri)
- const previewEntry = useMemo(() => {
- if (!activeEntry) return null
- if (statQuery.data && debouncedStatUri === activeEntry.uri) {
- return {
- ...activeEntry,
- size: statQuery.data.size,
- sizeBytes: statQuery.data.sizeBytes,
- modTime: statQuery.data.modTime,
- }
- }
- return activeEntry
- }, [activeEntry, statQuery.data, debouncedStatUri])
-
- const focusInput = useCallback(() => {
- requestAnimationFrame(() => {
- inputRef.current?.focus()
- inputRef.current?.select()
- })
- }, [])
-
- useEffect(() => {
- if (open) {
- reset()
- focusInput()
- }
- }, [open, reset, focusInput])
-
- useEffect(() => {
- if (!open) return
-
- const restoreFocus = () => {
- if (document.visibilityState === 'visible') focusInput()
- }
- window.addEventListener('focus', focusInput)
- document.addEventListener('visibilitychange', restoreFocus)
- return () => {
- window.removeEventListener('focus', focusInput)
- document.removeEventListener('visibilitychange', restoreFocus)
- }
- }, [open, focusInput])
-
- // Cursor resets on query change (navigation / filter typing) and whenever the
- // visible list identity changes (new data arrives). Arrow moves don't touch
- // query or the list, so they don't trigger a reset.
- useEffect(() => {
- reset()
- }, [query, visibleEntries, reset])
-
- useEffect(() => {
- if (!resultsRef.current) return
- const el = resultsRef.current.querySelector('[data-active="true"]')
- el?.scrollIntoView({ block: 'nearest' })
- }, [activeIndex])
- // Navigation writes go through buildDirBrowseQuery — the only place that
- // turns a uri back into a query string. setQuery is the single owner.
- const enterDir = useCallback((uri: string) => {
- setQuery(buildDirBrowseQuery(uri))
- }, [])
-
- const goToParent = useCallback(() => {
- if (mode.kind !== 'dirBrowse') return
- const parent = getParentUri(mode.uri)
- if (parent !== mode.uri) {
- setQuery(buildDirBrowseQuery(parent))
- }
- }, [mode])
-
- const confirmDirScope = useCallback((uri: string) => {
- setFindTargetUri(normalizeDirUri(uri))
- setQuery('')
- }, [])
-
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent) => {
- if (composingRef.current) return
-
- // `//` + Enter resets scope to global root, regardless of mode.
- if (isResetGlobalCommand(query) && e.key === 'Enter') {
- e.preventDefault()
- setFindTargetUri(PALETTE_ROOT_URI)
- setQuery('')
- return
- }
-
- if (e.key === 'Escape') {
- e.preventDefault()
- onClose()
- return
- }
-
- if (mode.kind === 'dirBrowse') {
- switch (e.key) {
- case 'ArrowDown':
- e.preventDefault()
- moveDown()
- return
- case 'ArrowUp':
- e.preventDefault()
- moveUp()
- return
- case 'ArrowRight':
- case 'Tab':
- e.preventDefault()
- if (activeEntry?.isDir) {
- enterDir(activeEntry.uri)
- } else if (e.key === 'Tab' && activeEntry) {
- onNavigate(activeEntry.uri)
- onClose()
- }
- return
- case 'ArrowLeft':
- e.preventDefault()
- goToParent()
- return
- case 'Enter':
- e.preventDefault()
- if (activeEntry && !activeEntry.isDir) {
- onNavigate(activeEntry.uri)
- onClose()
- } else if (dirListQuery.isSuccess) {
- confirmDirScope(mode.uri)
- }
- return
- }
- return
- }
-
- // search / idle list navigation
- if (visibleEntries.length === 0) return
- switch (e.key) {
- case 'ArrowDown':
- e.preventDefault()
- moveDown()
- return
- case 'ArrowUp':
- e.preventDefault()
- moveUp()
- return
- case 'Enter':
- e.preventDefault()
- if (!activeEntry) return
- if (mode.kind === 'idle' && activeEntry.isDir) {
- confirmDirScope(activeEntry.uri)
- } else {
- onNavigate(activeEntry.uri)
- onClose()
- }
- return
- }
- },
- [
- query,
- mode,
- activeEntry,
- visibleEntries.length,
- dirListQuery.isSuccess,
- moveUp,
- moveDown,
- enterDir,
- goToParent,
- confirmDirScope,
- onNavigate,
- onClose,
- ],
- )
-
- if (!open) return null
-
- const showPreview =
- mode.kind !== 'dirBrowse' && activeEntry !== null && !activeEntry.isDir
- const paletteWidth = showPreview
- ? 'w-[min(92vw,67rem)]'
- : 'w-[min(90vw,45rem)]'
- return (
- <div
- className="fixed inset-0 z-50 flex items-center justify-center px-4 sm:items-start sm:px-6 sm:pt-[12vh]"
- role="dialog"
- aria-modal="true"
- aria-label={t('searchPalette.ariaLabel')}
- >
- <div
- className="animate-palette-backdrop absolute inset-0 bg-background/60 backdrop-blur-sm"
- role="presentation"
- onClick={onClose}
- />
-
- <div
- className={cn(
- 'animate-palette-in relative flex h-[46rem] max-h-[calc(100svh-2rem)] max-w-full flex-col overflow-hidden rounded-xl border bg-background shadow-2xl shadow-black/20 transition-[width] duration-300 sm:max-h-[84vh]',
- paletteWidth,
- )}
- onKeyDown={handleKeyDown}
- >
- {/* Search input */}
- <div className="flex items-center gap-3 border-b px-4">
- <Search className="size-4 shrink-0 text-muted-foreground" />
- <input
- ref={inputRef}
- type="text"
- placeholder={t('searchPalette.placeholder')}
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- onCompositionStart={() => {
- composingRef.current = true
- }}
- onCompositionEnd={() => {
- composingRef.current = false
- }}
- className="h-12 flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground/70 md:text-sm"
- />
- {query && (
- <button
- type="button"
- className="rounded-md p-1 text-muted-foreground/70 transition-colors hover:text-foreground"
- onClick={() => setQuery('')}
- >
- <X className="size-3.5" />
- </button>
- )}
- <span className="flex items-center gap-1 text-xs text-muted-foreground/70">
- {isRoot ? (
- t('searchPalette.scope.global')
- ) : (
- <button
- type="button"
- className="flex items-center gap-1 rounded px-1 py-0.5 transition-colors hover:bg-muted hover:text-foreground"
- title={t('searchPalette.scope.resetToGlobal')}
- onClick={() => setFindTargetUri(PALETTE_ROOT_URI)}
- >
- <FolderOpen className="size-3" />
- {t('searchPalette.scope.current', {
- name: findTargetUri.split('/').filter(Boolean).pop(),
- })}
- <X className="size-3" />
- </button>
- )}
- </span>
- </div>
-
- {/* Body */}
- <div className="flex min-h-0 flex-1" ref={resultsRef}>
- {mode.kind === 'dirBrowse' ? (
- <DirBrowser
- currentUri={mode.uri}
- items={dirItems}
- activeIndex={activeIndex}
- loading={dirListQuery.isLoading}
- errored={dirListQuery.isError}
- onCursorChange={setIndex}
- onEnterDir={enterDir}
- onOpenFile={(uri) => {
- onNavigate(uri)
- onClose()
- }}
- onGoBack={goToParent}
- />
- ) : (
- <>
- {/* Results area */}
- <div
- className={cn(
- 'min-h-0 flex-1 overflow-hidden',
- showPreview && 'border-r',
- )}
- >
- {mode.kind === 'idle' ? (
- showIdleBrowse && idleBrowseQuery.isError ? (
- <div
- role="alert"
- className="px-4 py-6 text-center text-xs text-destructive"
- >
- {t('dirBrowser.error')}
- </div>
- ) : showIdleBrowse && idleEntries.length > 0 ? (
- <DirResultList
- className="h-full"
- items={idleEntries}
- activeIndex={activeIndex}
- onSelect={(entry) => {
- if (entry.isDir) {
- confirmDirScope(entry.uri)
- } else {
- onNavigate(entry.uri)
- onClose()
- }
- }}
- onOpenDir={(entry) => {
- onNavigateDir(getParentUri(entry.uri))
- onClose()
- }}
- />
- ) : (
- <div className="animate-palette-in flex flex-col items-center gap-3 px-4 py-12 text-center">
- <Search className="size-6 text-muted-foreground/30" />
- <div>
- <p className="text-sm text-muted-foreground/70">
- {t('searchPalette.empty.title')}
- </p>
- <p className="mt-1 text-xs text-muted-foreground/50">
- {t('searchPalette.browseDirHint.before')}{' '}
- <kbd className="rounded border border-border bg-muted/50 px-1 py-0.5 font-mono text-[11px] text-foreground/70">
- /
- </kbd>{' '}
- {t('searchPalette.browseDirHint.after')}
- </p>
- <p className="mt-1 text-xs text-muted-foreground/50">
- {t('searchPalette.globalScopeHint.before')}{' '}
- <kbd className="rounded border border-border bg-muted/50 px-1 py-0.5 font-mono text-[11px] text-foreground/70">
- //
- </kbd>{' '}
- {t('searchPalette.globalScopeHint.after')}
- </p>
- </div>
- </div>
- )
- ) : treeQuery.isLoading ? (
- <div className="flex flex-col items-center gap-3 py-12">
- <Loader2 className="size-5 animate-spin text-muted-foreground/50" />
- <p className="text-xs text-muted-foreground/60">
- {t('searchPalette.scopeState.validatingTitle')}
- </p>
- </div>
- ) : treeQuery.error ? (
- <div
- role="alert"
- className="px-4 py-6 text-center text-xs text-destructive"
- >
- {t('searchPalette.error')}
- </div>
- ) : !hasResults ? (
- <div className="flex flex-col items-center gap-2 px-4 py-12 text-center">
- <Search className="size-5 text-muted-foreground/25" />
- <p className="text-sm text-muted-foreground/60">
- {t('searchPalette.emptyResults.title')}
- </p>
- <p className="text-xs text-muted-foreground/40">
- {t('searchPalette.emptyResults.subtitle')}
- </p>
- </div>
- ) : (
- <DirResultList
- className="h-full"
- items={filteredEntries}
- activeIndex={activeIndex}
- onSelect={(entry) => {
- onNavigate(entry.uri)
- onClose()
- }}
- onOpenDir={(entry) => {
- onNavigateDir(getParentUri(entry.uri))
- onClose()
- }}
- />
- )}
- </div>
-
- {/* Preview pane */}
- {showPreview && (
- <div className="animate-palette-preview flex h-full w-[32rem] flex-col overflow-hidden">
- <FilePreview
- file={previewEntry}
- onClose={() => setIndex(-1)}
- showCloseButton={false}
- />
- </div>
- )}
- </>
- )}
- </div>
-
- {mode.kind === 'dirBrowse' ? (
- <div className="flex items-center gap-3 border-t px-4 py-2 text-xs text-muted-foreground/70">
- <span>
- <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">
- ↑↓
- </kbd>{' '}
- {t('searchPalette.footer.dirMode.select')}
- </span>
- <span>
- <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">
- ←→
- </kbd>{' '}
- {t('searchPalette.footer.dirMode.level')}
- </span>
- <span>
- <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">
- ↵
- </kbd>{' '}
- {t('searchPalette.footer.dirMode.confirm')}
- </span>
- <span>
- <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">
- {KEY_ESCAPE_LABEL}
- </kbd>{' '}
- {t('searchPalette.footer.dirMode.cancel')}
- </span>
- </div>
- ) : (
- hasResults && (
- <div className="flex items-center gap-3 border-t px-4 py-2 text-xs text-muted-foreground/70">
- <span>
- <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">
- ↑↓
- </kbd>{' '}
- {t('searchPalette.footer.resultMode.navigate')}
- </span>
- <span>
- <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">
- ↵
- </kbd>{' '}
- {t('searchPalette.footer.resultMode.open')}
- </span>
- <span>
- <kbd className="rounded border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground/70">
- {KEY_ESCAPE_LABEL}
- </kbd>{' '}
- {t('searchPalette.footer.resultMode.close')}
- </span>
- <span className="ml-auto tabular-nums">
- {t('searchPalette.footer.resultMode.count', {
- count: filteredEntries.length,
- })}
- </span>
- </div>
- )
- )}
- </div>
- </div>
- )
-}
-function DirResultList({
- className,
- items,
- activeIndex,
- onSelect,
- onOpenDir,
-}: {
- className?: string
- items: VikingFsEntry[]
- activeIndex: number
- onSelect: (entry: VikingFsEntry) => void
- onOpenDir: (entry: VikingFsEntry) => void
-}) {
- const { t } = useTranslation('resources')
- const { isScrolling, onScroll } = useTransientScrollbar()
-
- return (
- <div
- className={cn(
- 'scrollbar-fade min-h-0 flex-1 overflow-y-auto overscroll-contain',
- className,
- )}
- data-scrolling={isScrolling || undefined}
- onScroll={onScroll}
- >
- {items.map((entry, i) => {
- const { name, parent } = displayName(entry.uri)
- const isActive = i === activeIndex
- const EntryIcon = entry.isDir ? FolderIcon : FileIcon
-
- return (
- <button
- key={entry.uri}
- type="button"
- data-active={isActive}
- className={cn(
- 'animate-palette-row group relative flex w-full items-start gap-3 border-b border-border/50 px-4 py-3 text-left transition-colors last:border-b-0',
- isActive
- ? 'bg-primary/8 text-foreground'
- : 'text-foreground/80 hover:bg-muted/40',
- )}
- style={{ animationDelay: `${i * 24}ms` }}
- onClick={() => onSelect(entry)}
- >
- {isActive && (
- <span className="absolute inset-y-0 left-0 w-0.5 rounded-r bg-primary" />
- )}
- <EntryIcon
- className={cn(
- 'mt-0.5 size-4 shrink-0',
- entry.isDir ? 'text-blue-500/70' : 'text-muted-foreground/70',
- )}
- />
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-medium">{name}</div>
- <div className="mt-0.5 truncate text-xs text-muted-foreground/80">
- {parent}
- </div>
- </div>
- {entry.size && (
- <span className="shrink-0 text-xs tabular-nums text-muted-foreground/60">
- {entry.size}
- </span>
- )}
- <span
- role="button"
- tabIndex={-1}
- title={t('searchPalette.openContainingDirectory')}
- className="shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover:opacity-100 data-[active=true]:opacity-100"
- data-active={isActive}
- onClick={(e) => {
- e.stopPropagation()
- onOpenDir(entry)
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.stopPropagation()
- onOpenDir(entry)
- }
- }}
- >
- <FolderOpen className="size-3.5" />
- </span>
- </button>
- )
- })}
- </div>
- )
-}
diff --git a/web-studio/src/routes/resources/-components/find-results.tsx b/web-studio/src/routes/resources/-components/find-results.tsx
deleted file mode 100644
index f2329bc42..000000000
--- a/web-studio/src/routes/resources/-components/find-results.tsx
+++ /dev/null
@@ -1,242 +0,0 @@
-import { ChevronDown, Brain, FileText, Wrench, FolderOpen } from 'lucide-react'
-import { useState } from 'react'
-import { useTranslation } from 'react-i18next'
-
-import { cn } from '#/lib/utils'
-
-import type {
- FindContextType,
- FindResultItem,
- GroupedFindResult,
-} from '../-types/viking-fm'
-import { fileNameFromUri, parentUri } from '../-lib/normalize'
-
-interface FindResultsProps {
- data: GroupedFindResult
- onNavigate: (uri: string) => void
-}
-
-const GROUP_CONFIG: Array<{
- key: keyof Pick<GroupedFindResult, 'memories' | 'resources' | 'skills'>
- labelKey: string
- icon: typeof Brain
- type: FindContextType
- accent: string
-}> = [
- {
- key: 'resources',
- labelKey: 'findResults.groups.resources',
- icon: FileText,
- type: 'resource',
- accent: 'bg-blue-500/10 text-blue-600 dark:text-blue-400',
- },
- {
- key: 'memories',
- labelKey: 'findResults.groups.memories',
- icon: Brain,
- type: 'memory',
- accent: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',
- },
- {
- key: 'skills',
- labelKey: 'findResults.groups.skills',
- icon: Wrench,
- type: 'skill',
- accent: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
- },
-]
-
-function formatDisplayUri(uri: string): { name: string; parent: string } {
- const name = fileNameFromUri(uri)
- const dir = parentUri(uri)
- const parent =
- dir === 'viking://'
- ? 'viking://'
- : dir.replace(/\/$/, '').split('/').slice(-2).join('/')
- return { name, parent }
-}
-
-function ScoreIndicator({ score }: { score: number }) {
- const width = Math.max(Math.min(Math.round(score * 100), 100), 8)
- const hue =
- score > 0.7
- ? 'bg-emerald-500/70'
- : score > 0.4
- ? 'bg-amber-500/60'
- : 'bg-zinc-400/50'
- return (
- <div className="flex items-center gap-1.5">
- <div className="h-1 w-12 overflow-hidden rounded-full bg-muted">
- <div
- className={cn('h-full rounded-full transition-all', hue)}
- style={{ width: `${width}%` }}
- />
- </div>
- </div>
- )
-}
-
-export function FindResults({ data, onNavigate }: FindResultsProps) {
- const { t } = useTranslation('resources')
-
- if (data.total === 0) {
- return (
- <div className="flex flex-col items-center gap-2 py-16 text-muted-foreground">
- <FileText className="size-8 opacity-30" />
- <p className="text-sm">{t('findResults.noResults')}</p>
- </div>
- )
- }
-
- return (
- <div className="py-1">
- {GROUP_CONFIG.map((group) => {
- const items = data[group.key]
- if (items.length === 0) return null
- return (
- <FindResultGroup
- key={group.key}
- label={t(group.labelKey)}
- icon={group.icon}
- accent={group.accent}
- items={items}
- onNavigate={onNavigate}
- />
- )
- })}
- </div>
- )
-}
-
-function FindResultGroup({
- label,
- icon: Icon,
- accent,
- items,
- onNavigate,
-}: {
- label: string
- icon: typeof Brain
- accent: string
- items: FindResultItem[]
- onNavigate: (uri: string) => void
-}) {
- const [collapsed, setCollapsed] = useState(false)
-
- return (
- <div className="px-3 py-1">
- <button
- type="button"
- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs font-medium uppercase tracking-wide text-muted-foreground transition-colors hover:text-foreground"
- onClick={() => setCollapsed(!collapsed)}
- >
- <ChevronDown
- className={cn(
- 'size-3 transition-transform',
- collapsed && '-rotate-90',
- )}
- />
- <span
- className={cn(
- 'inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-semibold',
- accent,
- )}
- >
- <Icon className="size-3" />
- {label}
- </span>
- <span className="text-[10px] tabular-nums text-muted-foreground/60">
- {items.length}
- </span>
- </button>
-
- {!collapsed && (
- <div className="mt-0.5 space-y-px">
- {items.map((item, i) => (
- <FindResultRow
- key={`${item.uri}-${i}`}
- item={item}
- onNavigate={onNavigate}
- />
- ))}
- </div>
- )}
- </div>
- )
-}
-
-function FindResultRow({
- item,
- onNavigate,
-}: {
- item: FindResultItem
- onNavigate: (uri: string) => void
-}) {
- const { t } = useTranslation('resources')
- const [expanded, setExpanded] = useState(false)
- const { name, parent } = formatDisplayUri(item.uri)
- const hasDetail = item.abstract || item.overview
-
- return (
- <div
- className={cn(
- 'group rounded-lg transition-colors',
- expanded ? 'bg-muted/50' : 'hover:bg-muted/30',
- )}
- >
- <div className="flex items-start gap-3 px-3 py-2.5">
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <button
- type="button"
- className="truncate text-sm font-medium text-foreground transition-colors hover:text-primary"
- onClick={() => onNavigate(item.uri)}
- title={item.uri}
- >
- {name}
- </button>
- <ScoreIndicator score={item.score} />
- </div>
- <div className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground/70">
- <FolderOpen className="size-3 shrink-0" />
- <span className="truncate" title={item.uri}>
- {parent}
- </span>
- </div>
- {!expanded && item.abstract && (
- <p className="mt-1 line-clamp-1 text-xs text-muted-foreground">
- {item.abstract}
- </p>
- )}
- </div>
- {hasDetail && (
- <button
- type="button"
- className="mt-0.5 shrink-0 rounded p-1 text-muted-foreground/50 transition-colors hover:bg-muted hover:text-foreground"
- onClick={() => setExpanded(!expanded)}
- title={
- expanded
- ? t('findResults.collapse')
- : t('findResults.expandDetails')
- }
- >
- <ChevronDown
- className={cn(
- 'size-3.5 transition-transform',
- expanded && 'rotate-180',
- )}
- />
- </button>
- )}
- </div>
-
- {expanded && hasDetail && (
- <div className="px-3 pb-3">
- <div className="rounded-md bg-background/80 px-3 py-2 text-xs leading-relaxed text-muted-foreground">
- {item.overview || item.abstract}
- </div>
- </div>
- )}
- </div>
- )
-}
diff --git a/web-studio/src/routes/resources/-components/item-column.tsx b/web-studio/src/routes/resources/-components/item-column.tsx
deleted file mode 100644
index 3e741cae1..000000000
--- a/web-studio/src/routes/resources/-components/item-column.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-import { ChevronRight, FileText, Folder } from 'lucide-react'
-import type { TFunction } from 'i18next'
-
-import { cn } from '#/lib/utils'
-import { useTransientScrollbar } from '#/hooks/use-transient-scrollbar'
-import type { VikingFsEntry } from '../-types/viking-fm'
-
-export function ItemColumn({
- className,
- label,
- items,
- activeIndex,
- t,
- onSelect,
-}: {
- className?: string
- label: string
- items: VikingFsEntry[]
- activeIndex: number
- t: TFunction<'resources'>
- onSelect: (entry: VikingFsEntry, index: number) => void
-}) {
- const { isScrolling, onScroll } = useTransientScrollbar()
-
- return (
- <div className={cn('flex min-w-0 flex-col overflow-hidden', className)}>
- <div className="flex min-h-11 items-center gap-1.5 border-b bg-blue-500/8 px-3 py-2 text-xs font-semibold tracking-[0.08em] text-blue-700/80 uppercase backdrop-blur-sm dark:text-blue-300/85">
- <Folder className="size-3.5 text-blue-600/75 dark:text-blue-300/75" />
- <span className="truncate normal-case tracking-normal text-sm font-semibold text-blue-700/90 dark:text-blue-200">
- {label}
- </span>
- </div>
- <div
- className="scrollbar-fade min-h-0 flex-1 overflow-y-auto overscroll-contain"
- data-scrolling={isScrolling || undefined}
- onScroll={onScroll}
- >
- {items.length === 0 ? (
- <div className="flex h-full items-center justify-center px-6 py-10">
- <div className="max-w-[13rem] text-center">
- <div className="mx-auto mb-3 flex size-10 items-center justify-center rounded-2xl bg-muted/60 text-muted-foreground/70 shadow-inner">
- <Folder className="size-4" />
- </div>
- <p className="text-sm font-medium text-foreground/70">
- {t('dirBrowser.empty.title')}
- </p>
- <p className="mt-1 text-xs leading-5 text-muted-foreground/75">
- {t('dirBrowser.empty.subtitle')}
- </p>
- </div>
- </div>
- ) : (
- items.map((entry, i) => {
- const isActive = i === activeIndex
- const isDir = entry.isDir
-
- return (
- <button
- key={entry.uri}
- type="button"
- data-active={isActive}
- className={cn(
- 'group relative flex w-full items-center gap-2.5 border-b border-border/40 px-3 py-2 text-left text-sm transition-colors',
- isActive
- ? 'bg-primary/8 text-foreground'
- : 'text-foreground/80 hover:bg-muted/35',
- )}
- onClick={() => onSelect(entry, i)}
- >
- {isActive && (
- <span className="absolute inset-y-1 left-0 w-0.5 rounded-r bg-primary" />
- )}
- {isDir ? (
- <Folder
- className={cn(
- 'size-3.5 shrink-0 transition-colors',
- isActive ? 'text-primary/80' : 'text-muted-foreground',
- )}
- />
- ) : (
- <FileText
- className={cn(
- 'size-3.5 shrink-0',
- isActive
- ? 'text-blue-600/75 dark:text-blue-300/75'
- : 'text-muted-foreground/65',
- )}
- />
- )}
- <span className="truncate font-medium">{entry.name}</span>
- {isDir && (
- <ChevronRight className="ml-auto size-3 shrink-0 text-muted-foreground/45 transition-transform group-hover:translate-x-0.5" />
- )}
- </button>
- )
- })
- )}
- </div>
- </div>
- )
-}
diff --git a/web-studio/src/routes/resources/-components/viking-file-manager.tsx b/web-studio/src/routes/resources/-components/viking-file-manager.tsx
deleted file mode 100644
index bd686d417..000000000
--- a/web-studio/src/routes/resources/-components/viking-file-manager.tsx
+++ /dev/null
@@ -1,580 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react'
-import {
- ArrowLeft,
- ChevronRight,
- FolderOpen,
- RefreshCcw,
- Search,
- Upload,
-} from 'lucide-react'
-import { toast } from 'sonner'
-import { useTranslation } from 'react-i18next'
-
-import { Button } from '#/components/ui/button'
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
-} from '#/components/ui/dialog'
-
-import { normalizeDirUri, normalizeFileUri, parentUri } from '../-lib/normalize'
-import { useResourceUpload } from '../-hooks/use-resource-upload'
-import { useInvalidateVikingFs, useVikingFsList } from '../-hooks/viking-fm'
-import type { VikingFsEntry } from '../-types/viking-fm'
-import { AddResourceForm } from './add-resource-page'
-import { FileList } from './file-list'
-import { FilePreview } from './file-preview'
-import { FileTree } from './file-tree'
-import { FindPalette } from './find-palette'
-import { UploadTaskDialog } from './upload-task-dialog'
-
-interface VikingFileManagerProps {
- initialUri?: string
- initialFile?: string
- initialUploadOpen?: boolean
- onUriChange?: (uri: string) => void
-}
-
-function getAncestorUris(uri: string): Array<string> {
- const normalized = normalizeDirUri(uri)
- if (normalized === 'viking://') {
- return ['viking://']
- }
-
- const body = normalized.slice('viking://'.length, -1)
- const parts = body.split('/').filter(Boolean)
-
- const ancestors = ['viking://']
- let running = 'viking://'
- for (const part of parts) {
- running = `${running}${part}/`
- ancestors.push(running)
- }
-
- return ancestors
-}
-
-function isDirectoryUri(uri: string): boolean {
- return uri.endsWith('/')
-}
-
-const TREE_WIDTH_STORAGE_KEY = 'openviking.playground.resourceTree.width'
-const TREE_HEIGHT_STORAGE_KEY = 'openviking.playground.resourceTree.height'
-
-function clampNumber(value: number, min: number, max: number): number {
- return Math.min(Math.max(value, min), max)
-}
-
-function readStoredNumber(
- key: string,
- fallback: number,
- min: number,
- max: number,
-): number {
- if (typeof window === 'undefined') {
- return fallback
- }
- const raw = window.localStorage.getItem(key)
- if (raw === null) {
- return fallback
- }
-
- const stored = Number(raw)
- return Number.isFinite(stored) ? clampNumber(stored, min, max) : fallback
-}
-
-export function VikingFileManager({
- initialUri,
- initialFile,
- initialUploadOpen,
- onUriChange,
-}: VikingFileManagerProps) {
- const { t } = useTranslation('resources')
- const { tasks, hasActiveTasks } = useResourceUpload()
- const [currentUri, setCurrentUri] = useState(
- normalizeDirUri(initialUri || 'viking://'),
- )
- const [expandedKeys, setExpandedKeys] = useState<Set<string>>(
- new Set(['viking://']),
- )
- const [selectedFile, setSelectedFile] = useState<VikingFsEntry | null>(null)
- const [paletteOpen, setPaletteOpen] = useState(false)
- const [uploadDialogOpen, setUploadDialogOpen] = useState(
- initialUploadOpen ?? false,
- )
- const [taskDialogOpen, setTaskDialogOpen] = useState(false)
-
- useEffect(() => {
- const normalized = normalizeDirUri(initialUri || 'viking://')
- setCurrentUri(normalized)
- setExpandedKeys(new Set(getAncestorUris(normalized)))
- }, [initialUri])
-
- useEffect(() => {
- if (!initialFile) return
- const fileUri = normalizeFileUri(initialFile)
- const name = fileUri.split('/').pop() || fileUri
- setSelectedFile({
- uri: fileUri,
- name,
- isDir: false,
- size: '',
- sizeBytes: null,
- modTime: '',
- modTimestamp: null,
- abstract: '',
- overview: '',
- })
- }, [initialFile])
-
- useEffect(() => {
- const handler = (e: KeyboardEvent) => {
- if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
- e.preventDefault()
- setPaletteOpen((prev) => !prev)
- }
- }
- document.addEventListener('keydown', handler)
- return () => document.removeEventListener('keydown', handler)
- }, [])
-
- const updateUri = useCallback((uri: string) => {
- const normalized = normalizeDirUri(uri)
- setCurrentUri(normalized)
- setSelectedFile(null)
- setExpandedKeys(new Set(getAncestorUris(normalized)))
- }, [])
-
- const handleOpenDirectory = useCallback((entry: VikingFsEntry) => {
- const normalized = normalizeDirUri(entry.uri)
- setCurrentUri(normalized)
- setSelectedFile({
- ...entry,
- uri: normalized,
- isDir: true,
- })
- setExpandedKeys(new Set(getAncestorUris(normalized)))
- }, [])
-
- const handleNavigateFromSearch = useCallback((uri: string) => {
- if (isDirectoryUri(uri)) {
- const normalized = normalizeDirUri(uri)
- setCurrentUri(normalized)
- setSelectedFile(null)
- setExpandedKeys(new Set(getAncestorUris(normalized)))
- } else {
- const dirUri = parentUri(uri)
- const normalizedDir = normalizeDirUri(dirUri)
- setCurrentUri(normalizedDir)
- const name = uri.split('/').pop() || uri
- setSelectedFile({
- uri: normalizeFileUri(uri),
- name,
- isDir: false,
- size: '',
- sizeBytes: null,
- modTime: '',
- modTimestamp: null,
- abstract: '',
- overview: '',
- })
- setExpandedKeys(new Set(getAncestorUris(normalizedDir)))
- }
- }, [])
-
- const listQuery = useVikingFsList(currentUri, {
- output: 'agent',
- showAllHidden: true,
- nodeLimit: 500,
- })
- const { invalidateList } = useInvalidateVikingFs()
- const completedTaskIdsRef = useRef<Set<string>>(new Set())
- const processingNoticeShownRef = useRef(false)
- const processingToastIdRef = useRef<string | number | null>(null)
-
- const entries = useMemo(
- () => listQuery.data?.entries || [],
- [listQuery.data?.entries],
- )
-
- useEffect(() => {
- const nextCompletedIds = new Set(completedTaskIdsRef.current)
- let hasNewSuccess = false
-
- for (const task of tasks) {
- if (task.status === 'success' && !nextCompletedIds.has(task.id)) {
- nextCompletedIds.add(task.id)
- hasNewSuccess = true
- }
- }
-
- completedTaskIdsRef.current = nextCompletedIds
-
- if (hasNewSuccess) {
- void invalidateList()
- }
- }, [invalidateList, tasks])
-
- useEffect(() => {
- if (!hasActiveTasks) {
- processingNoticeShownRef.current = false
- if (processingToastIdRef.current !== null) {
- toast.dismiss(processingToastIdRef.current)
- processingToastIdRef.current = null
- }
- return
- }
-
- if (processingNoticeShownRef.current) {
- return
- }
-
- processingNoticeShownRef.current = true
- processingToastIdRef.current = toast(
- <div className="max-w-[min(94vw,720px)] text-sm leading-5">
- <span>{`${t('processingNotice.prefix')} `}</span>
- <button
- type="button"
- className="inline p-0 font-medium text-foreground underline underline-offset-4 transition-colors hover:text-primary"
- onClick={() => setTaskDialogOpen(true)}
- >
- {t('processingNotice.action')}
- </button>
- <span>{` ${t('processingNotice.suffix')}`}</span>
- </div>,
- {
- position: 'top-center',
- duration: 2500,
- className: 'w-auto max-w-[min(94vw,720px)]',
- onAutoClose: () => {
- processingToastIdRef.current = null
- },
- onDismiss: () => {
- processingToastIdRef.current = null
- },
- },
- )
- }, [hasActiveTasks])
-
- useEffect(
- () => () => {
- if (processingToastIdRef.current !== null) {
- toast.dismiss(processingToastIdRef.current)
- }
- },
- [],
- )
-
- const handleRefresh = async () => {
- await invalidateList()
- await listQuery.refetch()
- }
-
- const handleUploadSubmitted = () => {
- setUploadDialogOpen(false)
- }
-
- useEffect(() => {
- onUriChange?.(currentUri)
- }, [currentUri, onUriChange])
-
- const breadcrumbs = useMemo(() => {
- const body = currentUri.slice('viking://'.length).replace(/\/$/, '')
- const parts = body ? body.split('/').filter(Boolean) : []
- const crumbs: Array<{ label: string; uri: string }> = [
- { label: 'viking://', uri: 'viking://' },
- ]
- let running = 'viking://'
- for (const part of parts) {
- running = `${running}${part}/`
- crumbs.push({ label: part, uri: running })
- }
- return crumbs
- }, [currentUri])
-
- const showPreview = selectedFile !== null || currentUri === 'viking://'
-
- const layoutRef = useRef<HTMLDivElement>(null)
- const [treeWidth, setTreeWidth] = useState(() =>
- readStoredNumber(TREE_WIDTH_STORAGE_KEY, 450, 180, 640),
- )
- const [treeHeight, setTreeHeight] = useState(() =>
- readStoredNumber(TREE_HEIGHT_STORAGE_KEY, 46, 34, 72),
- )
- const [isResizingTree, setResizingTree] = useState(false)
- const dragging = useRef(false)
- const treeWidthRef = useRef(treeWidth)
- const treeHeightRef = useRef(treeHeight)
- treeWidthRef.current = treeWidth
- treeHeightRef.current = treeHeight
-
- const treePaneStyle = useMemo(
- () =>
- ({
- '--resource-tree-height': `${treeHeight}%`,
- '--resource-tree-width': `${treeWidth}px`,
- }) as CSSProperties,
- [treeHeight, treeWidth],
- )
-
- const handleResizeStart = useCallback(
- (event: ReactPointerEvent<HTMLDivElement>) => {
- event.preventDefault()
- event.currentTarget.setPointerCapture(event.pointerId)
- dragging.current = true
- setResizingTree(true)
-
- const isDesktop = window.matchMedia('(min-width: 768px)').matches
- const startX = event.clientX
- const startY = event.clientY
- const startWidth = treeWidthRef.current
- const startHeight = treeHeightRef.current
- const layoutRect = layoutRef.current?.getBoundingClientRect()
-
- const onMove = (moveEvent: PointerEvent) => {
- if (isDesktop) {
- const nextWidth = clampNumber(
- startWidth + moveEvent.clientX - startX,
- 180,
- 640,
- )
- setTreeWidth(nextWidth)
- window.localStorage.setItem(TREE_WIDTH_STORAGE_KEY, String(nextWidth))
- return
- }
-
- const rect = layoutRef.current?.getBoundingClientRect() ?? layoutRect
- if (!rect) {
- const fallbackHeight = clampNumber(
- startHeight +
- ((moveEvent.clientY - startY) / Math.max(1, window.innerHeight)) *
- 100,
- 34,
- 72,
- )
- setTreeHeight(fallbackHeight)
- window.localStorage.setItem(
- TREE_HEIGHT_STORAGE_KEY,
- String(fallbackHeight),
- )
- return
- }
-
- const y = moveEvent.clientY - rect.top
- const nextHeight = clampNumber(
- (y / Math.max(1, rect.height)) * 100,
- 34,
- 72,
- )
- setTreeHeight(nextHeight)
- window.localStorage.setItem(TREE_HEIGHT_STORAGE_KEY, String(nextHeight))
- }
-
- const onUp = () => {
- dragging.current = false
- setResizingTree(false)
- document.removeEventListener('pointermove', onMove)
- document.removeEventListener('pointerup', onUp)
- document.removeEventListener('pointercancel', onUp)
- document.body.style.cursor = ''
- document.body.style.userSelect = ''
- }
-
- document.body.style.cursor = isDesktop ? 'col-resize' : 'row-resize'
- document.body.style.userSelect = 'none'
- document.addEventListener('pointermove', onMove)
- document.addEventListener('pointerup', onUp)
- document.addEventListener('pointercancel', onUp)
- },
- [],
- )
-
- useEffect(() => {
- return () => {
- if (!dragging.current) return
- document.body.style.cursor = ''
- document.body.style.userSelect = ''
- }
- }, [])
-
- const isRoot = currentUri === 'viking://'
-
- const toolbar = (
- <div className="flex h-10 items-center gap-1 border-b px-3">
- <button
- type="button"
- disabled={isRoot}
- aria-label={t('dirBrowser.back')}
- className="inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40"
- onClick={() => updateUri(parentUri(currentUri))}
- >
- <ArrowLeft className="size-3.5" />
- </button>
- <nav className="flex flex-1 items-center gap-0.5 overflow-x-auto whitespace-nowrap text-xs text-muted-foreground md:text-sm">
- {breadcrumbs.map((crumb, i) => (
- <span key={crumb.uri} className="flex shrink-0 items-center gap-0.5">
- {i > 0 && <ChevronRight className="size-3" />}
- <button
- type="button"
- className={`rounded px-1 py-0.5 hover:bg-muted ${i === breadcrumbs.length - 1 ? 'font-medium text-foreground' : ''}`}
- onClick={() => updateUri(crumb.uri)}
- >
- {crumb.label}
- </button>
- </span>
- ))}
- </nav>
- </div>
- )
-
- return (
- <div className="web-playground-resource-fs -mx-4 -my-6 flex h-[calc(100svh-3rem)] flex-col md:-mx-6">
- <div ref={layoutRef} className="flex min-h-0 flex-1 flex-col md:flex-row">
- <section
- className="flex h-[var(--resource-tree-height)] min-h-[190px] min-w-0 flex-col bg-muted/30 md:h-auto md:min-h-0 md:w-[var(--resource-tree-width)] md:min-w-[var(--resource-tree-width)]"
- style={treePaneStyle}
- >
- <div className="flex h-10 items-center gap-1 overflow-hidden border-b pl-4 pr-2 md:px-2">
- <Button
- variant="ghost"
- size="icon-sm"
- title={t('toolbar.refresh')}
- onClick={() => void handleRefresh()}
- >
- <RefreshCcw className="size-4" />
- </Button>
- <div className="ml-auto flex w-fit items-center gap-1.5">
- <Button
- type="button"
- size="sm"
- variant="secondary"
- className="h-8"
- onClick={() => setTaskDialogOpen(true)}
- >
- {t('toolbar.processingTasks')}
- </Button>
- <Button
- type="button"
- size="sm"
- variant="secondary"
- className="h-8 gap-1.5"
- onClick={() => setUploadDialogOpen(true)}
- >
- <Upload className="size-4" />
- {t('toolbar.upload')}
- </Button>
- <Button
- variant="secondary"
- size="icon"
- className="h-8 w-fit px-2"
- title={t('toolbar.search')}
- onClick={() => setPaletteOpen(true)}
- >
- <Search className="size-4" />
- </Button>
- </div>
- </div>
- <div className="min-h-0 flex-1">
- <FileTree
- currentUri={currentUri}
- selectedFileUri={
- selectedFile && !selectedFile.isDir ? selectedFile.uri : null
- }
- expandedKeys={expandedKeys}
- onExpandedKeysChange={setExpandedKeys}
- onSelectDirectory={handleOpenDirectory}
- onSelectFile={setSelectedFile}
- />
- </div>
- </section>
- <div
- role="separator"
- data-dragging={isResizingTree}
- className="group flex h-2 w-full shrink-0 cursor-row-resize touch-none items-center justify-center bg-transparent transition-colors hover:bg-primary/10 active:bg-primary/20 data-[dragging=true]:bg-primary/20 md:h-auto md:w-1 md:cursor-col-resize"
- onPointerDown={handleResizeStart}
- >
- <span className="h-0.5 w-12 rounded-full bg-border transition-colors group-hover:bg-primary/50 md:h-8 md:w-0.5" />
- </div>
-
- {showPreview ? (
- <section className="relative flex min-h-0 min-w-0 flex-1 flex-col">
- {toolbar}
- <div className="min-h-0 w-full flex-1">
- <FilePreview
- file={selectedFile}
- onClose={() => setSelectedFile(null)}
- showCloseButton={false}
- />
- </div>
- </section>
- ) : (
- <section className="relative flex min-h-0 min-w-0 flex-1 flex-col">
- {toolbar}
- <div className="min-h-0 flex-1 overflow-auto">
- {entries.length === 0 && !listQuery.isLoading ? (
- <div className="flex h-full flex-col items-center justify-center gap-4 p-8 text-center">
- <FolderOpen className="size-16 text-muted-foreground/20" />
- <p className="text-sm text-muted-foreground">
- {t('emptyState.title')}
- </p>
- <Button
- size="sm"
- variant="secondary"
- className="gap-1.5"
- onClick={() => setUploadDialogOpen(true)}
- >
- <Upload className="size-4" />
- {t('emptyState.upload')}
- </Button>
- </div>
- ) : (
- <FileList
- entries={entries}
- selectedFileUri={null}
- onOpenDirectory={handleOpenDirectory}
- onOpenFile={(file) => setSelectedFile(file)}
- />
- )}
- </div>
- </section>
- )}
- </div>
-
- <FindPalette
- open={paletteOpen}
- onClose={() => setPaletteOpen(false)}
- onNavigate={handleNavigateFromSearch}
- onNavigateDir={(uri) => {
- updateUri(uri)
- setPaletteOpen(false)
- }}
- scopeUri={currentUri}
- />
-
- <Dialog open={uploadDialogOpen} onOpenChange={setUploadDialogOpen}>
- <DialogContent className="max-h-[min(86vh,760px)] gap-0 overflow-hidden p-0 sm:max-w-4xl">
- <DialogHeader className="border-b px-6 py-5">
- <DialogTitle className="text-xl">
- {t('uploadDialog.title')}
- </DialogTitle>
- <DialogDescription>
- {t('uploadDialog.description')}
- </DialogDescription>
- </DialogHeader>
- <div className="max-h-[calc(min(86vh,760px)-6rem)] overflow-y-auto px-6 py-5">
- <AddResourceForm onSubmitted={handleUploadSubmitted} />
- </div>
- </DialogContent>
- </Dialog>
-
- <UploadTaskDialog
- open={taskDialogOpen}
- onOpenChange={setTaskDialogOpen}
- tasks={tasks}
- />
- </div>
- )
-}
diff --git a/web-studio/src/routes/resources/-hooks/use-list-navigation.ts b/web-studio/src/routes/resources/-hooks/use-list-navigation.ts
deleted file mode 100644
index e11484019..000000000
--- a/web-studio/src/routes/resources/-hooks/use-list-navigation.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from 'react'
-
-// Cursor movement for keyboard-driven lists. Shared by FindPalette across its
-// idle / search / dirBrowse modes so the up/down/clamp logic lives once.
-// `length` is read through a ref so move handlers stay referentially stable.
-export function useListNavigation(length: number) {
- const [index, setIndex] = useState(0)
- const lengthRef = useRef(length)
- lengthRef.current = length
-
- const moveDown = useCallback(() => {
- setIndex((i) => {
- if (lengthRef.current <= 0) return 0
- return Math.min(i + 1, lengthRef.current - 1)
- })
- }, [])
-
- const moveUp = useCallback(() => {
- setIndex((i) => Math.max(i - 1, 0))
- }, [])
-
- useEffect(() => {
- setIndex((i) => {
- if (length <= 0) return 0
- return Math.min(Math.max(i, 0), length - 1)
- })
- }, [length])
-
- const reset = useCallback(() => {
- setIndex(0)
- }, [])
-
- return { index, setIndex, moveUp, moveDown, reset }
-}
diff --git a/web-studio/src/routes/resources/-lib/find-search.ts b/web-studio/src/routes/resources/-lib/find-search.ts
deleted file mode 100644
index a0d703496..000000000
--- a/web-studio/src/routes/resources/-lib/find-search.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import type { VikingFsEntry } from '../-types/viking-fm'
-import { normalizeDirUri } from './normalize'
-
-const VIKING_URI_PREFIX = 'viking://'
-
-export type ResourceSearchSpec =
- | {
- mode: 'name'
- query: string
- rootUri: string
- }
- | {
- mode: 'path'
- query: string
- rootUri: string
- }
-
-export function isVikingPathSearchQuery(query: string): boolean {
- return query.trimStart().toLowerCase().startsWith(VIKING_URI_PREFIX)
-}
-
-export function normalizeVikingPathSearchQuery(query: string): string {
- const trimmed = query.trim()
- if (!isVikingPathSearchQuery(trimmed)) {
- return ''
- }
-
- const path = trimmed.slice(VIKING_URI_PREFIX.length)
- const hasTrailingSlash = path.endsWith('/')
- const normalizedPath = path.split('/').filter(Boolean).join('/')
-
- if (!normalizedPath) {
- return VIKING_URI_PREFIX
- }
-
- return `${VIKING_URI_PREFIX}${normalizedPath}${hasTrailingSlash ? '/' : ''}`
-}
-
-export function getResourceSearchSpec(
- query: string,
- scopeUri: string,
-): ResourceSearchSpec | null {
- const trimmed = query.trim()
- if (!trimmed) {
- return null
- }
-
- if (isVikingPathSearchQuery(trimmed)) {
- return {
- mode: 'path',
- query: normalizeVikingPathSearchQuery(trimmed),
- rootUri: VIKING_URI_PREFIX,
- }
- }
-
- return {
- mode: 'name',
- query: trimmed.toLowerCase(),
- rootUri: normalizeDirUri(scopeUri),
- }
-}
-
-export function matchesResourceSearch(
- entry: VikingFsEntry,
- spec: ResourceSearchSpec,
-): boolean {
- if (!entry.uri.startsWith(spec.rootUri)) {
- return false
- }
-
- if (spec.mode === 'path') {
- return entry.uri.startsWith(spec.query)
- }
-
- return entry.name.toLowerCase().includes(spec.query)
-}
-
-export function filterResourceSearchEntries(
- entries: Array<VikingFsEntry>,
- spec: ResourceSearchSpec | null,
-): Array<VikingFsEntry> {
- if (!spec) {
- return []
- }
-
- return entries.filter((entry) => matchesResourceSearch(entry, spec))
-}
diff --git a/web-studio/src/routes/resources/-lib/palette-mode.ts b/web-studio/src/routes/resources/-lib/palette-mode.ts
deleted file mode 100644
index 3b377ae03..000000000
--- a/web-studio/src/routes/resources/-lib/palette-mode.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { normalizeDirUri } from './normalize'
-
-// Single source of truth for interpreting the palette query string.
-// Nothing else may structurally parse `query` (no startsWith('/'), === '//',
-// slice, split, etc.) — route every read through parsePaletteMode and every
-// write through buildDirBrowseQuery. This keeps the stringly state machine
-// from spreading back into the components.
-
-export const PALETTE_ROOT_URI = 'viking://'
-
-export const PALETTE_COMMANDS = {
- dir: '/',
- resetGlobal: '//',
-} as const
-
-export type PaletteMode =
- | { kind: 'idle' }
- | { kind: 'search'; query: string }
- | { kind: 'dirBrowse'; uri: string; filter: string }
-
-export function parsePaletteMode(query: string, scopeUri: string): PaletteMode {
- const trimmed = query.trim()
- if (trimmed.length === 0) {
- return { kind: 'idle' }
- }
- if (trimmed.startsWith(PALETTE_COMMANDS.dir)) {
- return { kind: 'dirBrowse', ...parseDirBrowse(trimmed, scopeUri) }
- }
- return { kind: 'search', query: trimmed }
-}
-
-function parseDirBrowse(
- trimmed: string,
- scopeUri: string,
-): { uri: string; filter: string } {
- const raw = trimmed.slice(PALETTE_COMMANDS.dir.length)
- const lastSlash = raw.lastIndexOf('/')
- // No inner slash ("/", "/abc"): browse the current scope, optional filter.
- if (lastSlash === -1) {
- return { uri: normalizeDirUri(scopeUri), filter: raw }
- }
- // Inner/trailing slash: the path is root-absolute so it round-trips with
- // buildDirBrowseQuery (empty path -> root, which makes root representable).
- const pathPart = raw.slice(0, lastSlash)
- const filter = raw.slice(lastSlash + 1)
- const parts = pathPart
- .split('/')
- .map((p) => p.trim())
- .filter(Boolean)
- const uri =
- parts.length > 0
- ? normalizeDirUri(`${PALETTE_ROOT_URI}${parts.join('/')}`)
- : PALETTE_ROOT_URI
- return { uri, filter }
-}
-
-export function isResetGlobalCommand(query: string): boolean {
- return query.trim() === PALETTE_COMMANDS.resetGlobal
-}
-
-// Inverse of parseDirBrowse: the query string that navigates to `uri`.
-// Confines the `viking://` literal to this module; when the URI domain module
-// lands (deferred), only this file changes.
-export function buildDirBrowseQuery(uri: string): string {
- const normalized = normalizeDirUri(uri)
- if (normalized === PALETTE_ROOT_URI) {
- return PALETTE_COMMANDS.resetGlobal
- }
- const path = normalized.slice(PALETTE_ROOT_URI.length)
- return `${PALETTE_COMMANDS.dir}${path}`
-}
diff --git a/web-studio/src/routes/resources/index.tsx b/web-studio/src/routes/resources/index.tsx
deleted file mode 100644
index 08856abdf..000000000
--- a/web-studio/src/routes/resources/index.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { createFileRoute, useNavigate } from '@tanstack/react-router'
-
-import { VikingFileManager } from './-components/viking-file-manager'
-import { normalizeDirUri, parentUri as getParentUri } from './-lib/normalize'
-
-type ResourcesSearch = {
- uri?: string
- file?: string
- upload?: boolean
-}
-
-function shouldPreserveFile(file: unknown, uri: string): file is string {
- return typeof file === 'string' && getParentUri(file) === normalizeDirUri(uri)
-}
-
-export const Route = createFileRoute('/resources/')({
- validateSearch: (search: Record<string, unknown>): ResourcesSearch => ({
- uri: typeof search.uri === 'string' ? search.uri : undefined,
- file: typeof search.file === 'string' ? search.file : undefined,
- upload: search.upload === true || search.upload === 'true',
- }),
- component: ResourcesIndexRoute,
-})
-
-function ResourcesIndexRoute() {
- const search = Route.useSearch()
- const navigate = useNavigate({ from: Route.fullPath })
-
- return (
- <VikingFileManager
- initialUri={search.uri}
- initialFile={search.file}
- initialUploadOpen={search.upload}
- onUriChange={(uri) => {
- navigate({
- search: (prev) => ({
- ...prev,
- uri,
- file: shouldPreserveFile(prev.file, uri) ? prev.file : undefined,
- upload: undefined,
- }),
- replace: true,
- })
- }}
- />
- )
-}
diff --git a/web-studio/src/routes/resources/route.tsx b/web-studio/src/routes/resources/route.tsx
deleted file mode 100644
index 0ea3f379b..000000000
--- a/web-studio/src/routes/resources/route.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { createFileRoute, Outlet } from '@tanstack/react-router'
-
-import { ResourceUploadProvider } from './-hooks/use-resource-upload'
-
-export const Route = createFileRoute('/resources')({
- validateSearch: (search: Record<string, unknown>) => ({
- ...(typeof search.uri === 'string' && { uri: search.uri }),
- ...(typeof search.file === 'string' && { file: search.file }),
- ...((search.upload === true || search.upload === 'true') && {
- upload: true,
- }),
- }),
- component: ResourcesLayout,
-})
-
-function ResourcesLayout() {
- return (
- <ResourceUploadProvider>
- <Outlet />
- </ResourceUploadProvider>
- )
-}
diff --git a/web-studio/src/routes/retrieval/-components/loading-hint.tsx b/web-studio/src/routes/retrieval/-components/loading-hint.tsx
index c89acacac..c8d0a02fb 100644
--- a/web-studio/src/routes/retrieval/-components/loading-hint.tsx
+++ b/web-studio/src/routes/retrieval/-components/loading-hint.tsx
@@ -20,7 +20,7 @@ export function LoadingHint() {
<Loader2 className="size-6 animate-spin text-muted-foreground/50" />
<p
key={hintIndex}
- className="animate-palette-in text-xs text-muted-foreground/60"
+ className="animate-home-panel-in text-xs text-muted-foreground/60"
>
{t(LOADING_HINT_KEYS[hintIndex])}
</p>
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-results.tsx b/web-studio/src/routes/retrieval/-components/retrieval-results.tsx
index aea625a03..b00f702ff 100644
--- a/web-studio/src/routes/retrieval/-components/retrieval-results.tsx
+++ b/web-studio/src/routes/retrieval/-components/retrieval-results.tsx
@@ -224,7 +224,7 @@ function ResultRow({
return (
<Link
- to="/resources"
+ to="/playground"
search={resourceSearch}
target="_blank"
rel="noreferrer noopener"
diff --git a/web-studio/src/routes/retrieval/route.tsx b/web-studio/src/routes/retrieval/route.tsx
index f793fe862..52597b3b4 100644
--- a/web-studio/src/routes/retrieval/route.tsx
+++ b/web-studio/src/routes/retrieval/route.tsx
@@ -111,7 +111,7 @@ function RetrievalPage() {
])
const handleUploadClick = useCallback(() => {
- void navigate({ to: '/resources', search: { upload: true } })
+ void navigate({ to: '/playground', search: { upload: true } })
}, [navigate])
useEffect(() => {
diff --git a/web-studio/src/routes/settings/-lib/admin.ts b/web-studio/src/routes/settings/-lib/admin.ts
index c53458472..bbc59d045 100644
--- a/web-studio/src/routes/settings/-lib/admin.ts
+++ b/web-studio/src/routes/settings/-lib/admin.ts
@@ -48,6 +48,27 @@ export type KeyResult = {
userId?: string
}
+export type ProbeState = 'ok' | 'error' | 'skipped'
+
+export type CapabilityProbeResult = {
+ detail?: string
+ state: ProbeState
+}
+
+export type StudioConnectionProbe = {
+ admin: CapabilityProbeResult
+ data: CapabilityProbeResult
+}
+
+export type ProbeConnectionInput = {
+ accountId: string
+ adminApiKey: string
+ apiKey: string
+ baseUrl: string
+ serverMode: 'api_key' | 'trusted' | 'dev' | 'checking' | 'offline'
+ userId: string
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value)
}
@@ -80,8 +101,6 @@ function createAdminClient(connection: AdminConnection) {
Accept: 'application/json',
}
setOptionalHeader(headers, 'X-API-Key', connection.apiKey)
- setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)
- setOptionalHeader(headers, 'X-OpenViking-User', connection.userId)
return createClient({
axios: axios.create(),
@@ -91,6 +110,167 @@ function createAdminClient(connection: AdminConnection) {
})
}
+function getErrorMessage(error: unknown): string {
+ if (axios.isAxiosError(error)) {
+ const data = error.response?.data
+ if (isRecord(data) && isRecord(data.error)) {
+ const message = asString(data.error.message)
+ if (message) {
+ return message
+ }
+ }
+
+ if (error.response?.status) {
+ return `HTTP ${error.response.status}`
+ }
+ }
+
+ return error instanceof Error ? error.message : String(error)
+}
+
+function createProbeClient(baseUrl: string) {
+ return axios.create({
+ baseURL: normalizeBaseUrl(baseUrl),
+ headers: {
+ Accept: 'application/json',
+ },
+ })
+}
+
+function setApiKeyHeader(
+ headers: Record<string, string>,
+ apiKey: string,
+): void {
+ setOptionalHeader(headers, 'X-API-Key', apiKey)
+}
+
+async function probeAdminAccess(
+ input: ProbeConnectionInput,
+): Promise<CapabilityProbeResult> {
+ if (input.serverMode === 'checking' || input.serverMode === 'offline') {
+ return { state: 'skipped' }
+ }
+ if (input.serverMode === 'dev') {
+ return {
+ detail: 'Admin API requires API-key or trusted mode',
+ state: 'skipped',
+ }
+ }
+
+ const controlKey = input.adminApiKey || input.apiKey
+ if (input.serverMode === 'api_key' && !controlKey) {
+ return {
+ detail: 'A root or account-admin API key is required',
+ state: 'skipped',
+ }
+ }
+
+ const client = createProbeClient(input.baseUrl)
+ const headers: Record<string, string> = {}
+ setApiKeyHeader(headers, controlKey)
+
+ try {
+ await client.get('/api/v1/admin/accounts', { headers })
+ return {
+ detail: 'Root admin control available',
+ state: 'ok',
+ }
+ } catch (accountsError) {
+ if (
+ !axios.isAxiosError(accountsError) ||
+ accountsError.response?.status !== 403 ||
+ !input.accountId
+ ) {
+ return {
+ detail: getErrorMessage(accountsError),
+ state: 'error',
+ }
+ }
+
+ try {
+ const accountId = encodeURIComponent(input.accountId)
+ await client.get(`/api/v1/admin/accounts/${accountId}/users`, {
+ headers,
+ params: {
+ limit: 1,
+ },
+ })
+ return {
+ detail: 'Account admin control available',
+ state: 'ok',
+ }
+ } catch (usersError) {
+ return {
+ detail: getErrorMessage(usersError),
+ state: 'error',
+ }
+ }
+ }
+}
+
+async function probeDataAccess(
+ input: ProbeConnectionInput,
+): Promise<CapabilityProbeResult> {
+ if (input.serverMode === 'checking' || input.serverMode === 'offline') {
+ return { state: 'skipped' }
+ }
+ if (input.serverMode === 'api_key' && !input.apiKey) {
+ return {
+ detail: 'A user or account-admin API key is required',
+ state: 'skipped',
+ }
+ }
+ if (
+ input.serverMode === 'trusted' &&
+ (!input.accountId.trim() || !input.userId.trim())
+ ) {
+ return {
+ detail: 'Trusted mode data access requires account and user',
+ state: 'skipped',
+ }
+ }
+
+ const client = createProbeClient(input.baseUrl)
+ const headers: Record<string, string> = {}
+ setApiKeyHeader(headers, input.apiKey)
+
+ if (input.serverMode === 'trusted') {
+ setOptionalHeader(headers, 'X-OpenViking-Account', input.accountId)
+ setOptionalHeader(headers, 'X-OpenViking-User', input.userId)
+ }
+
+ try {
+ await client.get('/api/v1/fs/ls', {
+ headers,
+ params: {
+ node_limit: 1,
+ output: 'agent',
+ uri: 'viking://',
+ },
+ })
+ return {
+ detail: 'Tenant data access available',
+ state: 'ok',
+ }
+ } catch (error) {
+ return {
+ detail: getErrorMessage(error),
+ state: 'error',
+ }
+ }
+}
+
+export async function probeStudioConnection(
+ input: ProbeConnectionInput,
+): Promise<StudioConnectionProbe> {
+ const [admin, data] = await Promise.all([
+ probeAdminAccess(input),
+ probeDataAccess(input),
+ ])
+
+ return { admin, data }
+}
+
function normalizeAccount(value: unknown): AdminAccount | null {
if (!isRecord(value)) {
return null
diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsx
index be8960a29..f1e5bcee9 100644
--- a/web-studio/src/routes/settings/route.tsx
+++ b/web-studio/src/routes/settings/route.tsx
@@ -2,13 +2,16 @@ import * as React from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router'
import {
+ CircleAlertIcon,
+ CircleDashedIcon,
CopyIcon,
+ DatabaseIcon,
KeyRoundIcon,
PlusIcon,
RefreshCwIcon,
RotateCwIcon,
- SaveIcon,
ServerIcon,
+ ShieldCheckIcon,
UserRoundIcon,
UsersRoundIcon,
} from 'lucide-react'
@@ -68,12 +71,14 @@ import {
createAdminUser,
fetchAdminAccounts,
fetchAdminUsers,
+ probeStudioConnection,
regenerateAdminUserKey,
} from './-lib/admin'
import type {
AdminConnection,
AdminAccount,
AdminUser,
+ CapabilityProbeResult,
CreateAccountInput,
CreateUserInput,
KeyResult,
@@ -90,10 +95,7 @@ const USER_ROLES = ['user', 'admin'] as const
type AddAccountDraft = CreateAccountInput
type AddUserDraft = CreateUserInput
-function uniqueOptions(
- values: readonly string[],
- fallback: string,
-): readonly string[] {
+function uniqueOptions(values: readonly string[], fallback: string): string[] {
const seen = new Set<string>()
const result: string[] = []
@@ -109,6 +111,31 @@ function uniqueOptions(
return result
}
+function compareAccountId(left: string, right: string): number {
+ const normalizedLeft = left.toLowerCase()
+ const normalizedRight = right.toLowerCase()
+ if (normalizedLeft < normalizedRight) {
+ return -1
+ }
+ if (normalizedLeft > normalizedRight) {
+ return 1
+ }
+ return left < right ? -1 : left > right ? 1 : 0
+}
+
+function sortedAccountIds(
+ values: readonly string[],
+ fallback: string,
+): string[] {
+ return uniqueOptions([...values, fallback], '').sort(compareAccountId)
+}
+
+function sortedAccounts(accounts: readonly AdminAccount[]): AdminAccount[] {
+ return [...accounts].sort((left, right) =>
+ compareAccountId(left.accountId, right.accountId),
+ )
+}
+
function getErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
@@ -155,9 +182,11 @@ function StatCard({
function KeyResultCard({
onClear,
+ onUseForData,
result,
}: {
onClear: () => void
+ onUseForData: () => void
result: KeyResult
}) {
const { t } = useTranslation('settings')
@@ -193,12 +222,74 @@ function KeyResultCard({
<CopyIcon />
{t('actions.copy')}
</Button>
+ <Button
+ type="button"
+ variant="default"
+ size="sm"
+ onClick={onUseForData}
+ >
+ <DatabaseIcon />
+ {t('actions.useForData')}
+ </Button>
</div>
</CardContent>
</Card>
)
}
+function getCapabilityIcon(result: CapabilityProbeResult | undefined) {
+ if (!result) {
+ return <CircleDashedIcon className="size-4" />
+ }
+ if (result.state === 'ok') {
+ return <ShieldCheckIcon className="size-4" />
+ }
+ if (result.state === 'error') {
+ return <CircleAlertIcon className="size-4" />
+ }
+ return <CircleDashedIcon className="size-4" />
+}
+
+function CapabilityStatus({
+ isLoading,
+ label,
+ result,
+}: {
+ isLoading: boolean
+ label: string
+ result: CapabilityProbeResult | undefined
+}) {
+ const { t } = useTranslation('settings')
+ const state = isLoading ? 'checking' : result?.state || 'skipped'
+
+ return (
+ <div
+ className={cn(
+ 'flex min-w-0 items-start gap-2 rounded-md border bg-background/70 px-3 py-2 text-sm',
+ state === 'ok' && 'border-emerald-500/35 text-emerald-700',
+ state === 'error' && 'border-destructive/35 text-destructive',
+ )}
+ >
+ <div className={cn('mt-0.5', isLoading && 'animate-spin')}>
+ {getCapabilityIcon(result)}
+ </div>
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="font-medium">{label}</span>
+ <span className="text-xs text-muted-foreground">
+ {t(`health.state.${state}`)}
+ </span>
+ </div>
+ {result?.detail ? (
+ <p className="mt-1 truncate text-xs text-muted-foreground">
+ {result.detail}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ )
+}
+
function AccountSelect({
accounts,
disabled,
@@ -212,7 +303,7 @@ function AccountSelect({
onChange: (value: string) => void
value: string
}) {
- const options = uniqueOptions(
+ const options = sortedAccountIds(
accounts.map((account) => account.accountId),
value || DEFAULT_ACCOUNT_ID,
)
@@ -244,6 +335,69 @@ function AccountSelect({
)
}
+function AccountFilterChips({
+ accounts,
+ disabled,
+ label,
+ onChange,
+ selectedAccountIds,
+}: {
+ accounts: readonly AdminAccount[]
+ disabled?: boolean
+ label: string
+ onChange: (value: string[]) => void
+ selectedAccountIds: readonly string[]
+}) {
+ const options = sortedAccountIds(
+ accounts.map((account) => account.accountId),
+ selectedAccountIds[0] || DEFAULT_ACCOUNT_ID,
+ )
+ const selected = new Set(selectedAccountIds)
+
+ function toggle(accountId: string): void {
+ if (disabled) {
+ return
+ }
+ if (selected.has(accountId)) {
+ const next = selectedAccountIds.filter((item) => item !== accountId)
+ if (next.length > 0) {
+ onChange(next)
+ }
+ return
+ }
+ onChange([...selectedAccountIds, accountId])
+ }
+
+ return (
+ <div className="flex min-w-0 flex-col gap-2">
+ <span className="text-xs font-medium text-muted-foreground">{label}</span>
+ <div className="flex max-w-full flex-wrap gap-2">
+ {options.map((accountId) => {
+ const isSelected = selected.has(accountId)
+
+ return (
+ <button
+ key={accountId}
+ type="button"
+ aria-pressed={isSelected}
+ disabled={disabled}
+ onClick={() => toggle(accountId)}
+ className={cn(
+ 'h-8 rounded-full border px-3 font-mono text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50',
+ isSelected
+ ? 'border-primary bg-primary text-primary-foreground'
+ : 'border-border bg-background text-muted-foreground hover:border-primary/50 hover:text-foreground',
+ )}
+ >
+ {accountId}
+ </button>
+ )
+ })}
+ </div>
+ </div>
+ )
+}
+
function UserSelect({
disabled,
label,
@@ -289,6 +443,48 @@ function UserSelect({
)
}
+function UserApiKeyInput({
+ accountId,
+ disabled,
+ id,
+ onChange,
+ placeholder,
+ userId,
+ value,
+}: {
+ accountId: string
+ disabled?: boolean
+ id: string
+ onChange: (value: string) => void
+ placeholder: string
+ userId: string
+ value: string
+}) {
+ const identity = `${accountId || DEFAULT_ACCOUNT_ID}/${userId || DEFAULT_USER_ID}`
+
+ return (
+ <div
+ className={cn(
+ 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30',
+ disabled && 'cursor-not-allowed opacity-50',
+ )}
+ >
+ <span className="shrink-0 rounded-sm bg-muted px-2 py-1 font-mono text-xs text-muted-foreground">
+ [{identity}]
+ </span>
+ <input
+ id={id}
+ type="password"
+ value={value}
+ disabled={disabled}
+ onChange={(event) => onChange(event.target.value)}
+ placeholder={placeholder}
+ className="h-full min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"
+ />
+ </div>
+ )
+}
+
function AddAccountDialog({
isPending,
onCreate,
@@ -516,9 +712,9 @@ function SettingsRoute() {
const queryClient = useQueryClient()
const { connection, saveConnection, serverMode } = useAppConnection()
const [draft, setDraft] = React.useState<ConnectionDraft>(connection)
- const [managedAccountId, setManagedAccountId] = React.useState(
+ const [managedAccountIds, setManagedAccountIds] = React.useState<string[]>([
connection.accountId || DEFAULT_ACCOUNT_ID,
- )
+ ])
const [addAccountOpen, setAddAccountOpen] = React.useState(false)
const [addUserOpen, setAddUserOpen] = React.useState(false)
const [keyResult, setKeyResult] = React.useState<KeyResult | null>(null)
@@ -529,17 +725,65 @@ function SettingsRoute() {
setDraft(connection)
}, [connection])
- const canQueryAdmin = Boolean(draft.apiKey.trim())
+ const controlApiKey = draft.adminApiKey.trim() || draft.apiKey.trim()
const adminConnection = React.useMemo<AdminConnection>(
() => ({
accountId: draft.accountId || DEFAULT_ACCOUNT_ID,
- apiKey: draft.apiKey,
+ apiKey: controlApiKey,
baseUrl: draft.baseUrl,
userId: draft.userId || DEFAULT_USER_ID,
}),
- [draft.accountId, draft.apiKey, draft.baseUrl, draft.userId],
+ [controlApiKey, draft.accountId, draft.baseUrl, draft.userId],
)
+ const probeQuery = useQuery({
+ enabled: Boolean(draft.baseUrl) && serverMode !== 'checking',
+ queryFn: () =>
+ probeStudioConnection({
+ accountId: draft.accountId || DEFAULT_ACCOUNT_ID,
+ adminApiKey: draft.adminApiKey,
+ apiKey: draft.apiKey,
+ baseUrl: draft.baseUrl,
+ serverMode,
+ userId: draft.userId || DEFAULT_USER_ID,
+ }),
+ queryKey: [
+ 'studio-connection-probe',
+ draft.baseUrl,
+ draft.adminApiKey,
+ draft.apiKey,
+ draft.accountId,
+ draft.userId,
+ serverMode,
+ ],
+ retry: false,
+ staleTime: 15_000,
+ })
+
+ const hasAdminAccess =
+ serverMode !== 'dev' && probeQuery.data?.admin.state === 'ok'
+ const hasSavedAdminApiKey = Boolean(draft.adminApiKey.trim())
+ const showAdminCredentialFields =
+ serverMode !== 'dev' && (hasAdminAccess || hasSavedAdminApiKey)
+ const canQueryAdmin = Boolean(controlApiKey) && hasAdminAccess
+ const showDevApiKeyPlaceholder = serverMode === 'dev'
+ const shouldPromoteApiKeyToAdmin =
+ hasAdminAccess && !draft.adminApiKey.trim() && Boolean(draft.apiKey.trim())
+
+ React.useEffect(() => {
+ if (!hasAdminAccess || draft.adminApiKey.trim() || !draft.apiKey.trim()) {
+ return
+ }
+
+ const next = {
+ ...draft,
+ adminApiKey: draft.apiKey,
+ apiKey: '',
+ }
+ setDraft(next)
+ saveConnection(next)
+ }, [draft, hasAdminAccess, saveConnection])
+
const accountsQuery = useQuery({
enabled: canQueryAdmin,
queryFn: () => fetchAdminAccounts(adminConnection),
@@ -553,8 +797,13 @@ function SettingsRoute() {
retry: false,
})
- const accountOptions = accountsQuery.data ?? []
const selectedAccountId = draft.accountId || DEFAULT_ACCOUNT_ID
+ const selectedManagedAccountIds = React.useMemo(() => {
+ const selected = sortedAccountIds(managedAccountIds, '')
+ return selected.length > 0
+ ? selected
+ : sortedAccountIds([selectedAccountId], '')
+ }, [managedAccountIds, selectedAccountId])
const usersQuery = useQuery({
enabled: canQueryAdmin && Boolean(selectedAccountId),
@@ -571,19 +820,42 @@ function SettingsRoute() {
})
const managedUsersQuery = useQuery({
- enabled: canQueryAdmin && Boolean(managedAccountId),
- queryFn: () => fetchAdminUsers(adminConnection, managedAccountId),
+ enabled: canQueryAdmin && selectedManagedAccountIds.length > 0,
+ queryFn: async () => {
+ const usersByAccount = await Promise.all(
+ selectedManagedAccountIds.map((accountId) =>
+ fetchAdminUsers(adminConnection, accountId),
+ ),
+ )
+ return usersByAccount.flat()
+ },
queryKey: [
'admin-users',
adminConnection.baseUrl,
adminConnection.apiKey,
adminConnection.accountId,
adminConnection.userId,
- managedAccountId,
+ 'managed',
+ selectedManagedAccountIds,
],
retry: false,
})
+ const accountOptions = React.useMemo<AdminAccount[]>(() => {
+ if (accountsQuery.data) {
+ return sortedAccounts(accountsQuery.data)
+ }
+
+ return sortedAccounts(
+ selectedManagedAccountIds.map((accountId) => ({
+ accountId,
+ userCount:
+ managedUsersQuery.data?.filter((user) => user.accountId === accountId)
+ .length ?? 0,
+ })),
+ )
+ }, [accountsQuery.data, managedUsersQuery.data, selectedManagedAccountIds])
+
React.useEffect(() => {
if (!accountOptions.length) {
return
@@ -594,15 +866,20 @@ function SettingsRoute() {
? DEFAULT_ACCOUNT_ID
: accountIds[0]
- setDraft((current) =>
- current.accountId && accountIds.includes(current.accountId)
- ? current
- : { ...current, accountId: preferred },
- )
- setManagedAccountId((current) =>
- current && accountIds.includes(current) ? current : preferred,
- )
- }, [accountOptions])
+ setDraft((current) => {
+ if (current.accountId && accountIds.includes(current.accountId)) {
+ return current
+ }
+
+ const next = { ...current, accountId: preferred }
+ saveConnection(next)
+ return next
+ })
+ setManagedAccountIds((current) => {
+ const next = current.filter((accountId) => accountIds.includes(accountId))
+ return next.length > 0 ? next : [preferred]
+ })
+ }, [accountOptions, saveConnection])
React.useEffect(() => {
const users = usersQuery.data
@@ -614,25 +891,49 @@ function SettingsRoute() {
const preferred = userIds.includes(DEFAULT_USER_ID)
? DEFAULT_USER_ID
: userIds[0]
- setDraft((current) =>
- current.userId && userIds.includes(current.userId)
- ? current
- : { ...current, userId: preferred },
- )
- }, [usersQuery.data])
+ setDraft((current) => {
+ const hasCurrentUser =
+ Boolean(current.userId) && userIds.includes(current.userId)
+ const userId = hasCurrentUser ? current.userId : preferred
+ const selectedUser = users.find((user) => user.userId === userId)
+ const apiKey =
+ selectedUser?.apiKey || (hasCurrentUser ? current.apiKey : '')
+ const next = { ...current, apiKey, userId }
+
+ if (next.apiKey !== current.apiKey || next.userId !== current.userId) {
+ saveConnection(next)
+ return next
+ }
+
+ return current
+ })
+ }, [saveConnection, usersQuery.data])
const createAccountMutation = useMutation({
mutationFn: (input: CreateAccountInput) =>
createAdminAccount(adminConnection, input),
onError: (error) => toast.error(getErrorMessage(error)),
onSuccess: async (result, variables) => {
- setKeyResult(result)
- setManagedAccountId(variables.accountId)
- setDraft((current) => ({
- ...current,
- accountId: variables.accountId,
- userId: variables.adminUserId,
- }))
+ const keyResultWithIdentity = {
+ ...result,
+ accountId: result.accountId || variables.accountId,
+ userId: result.userId || variables.adminUserId,
+ }
+ setKeyResult(keyResultWithIdentity)
+ setManagedAccountIds([variables.accountId])
+ if (keyResultWithIdentity.apiKey) {
+ const next = buildDataKeyConnection(draft, keyResultWithIdentity)
+ setDraft(next)
+ saveConnection(next)
+ } else {
+ const next = {
+ ...draft,
+ accountId: variables.accountId,
+ userId: variables.adminUserId,
+ }
+ setDraft(next)
+ saveConnection(next)
+ }
setAddAccountOpen(false)
toast.success(t('toast.accountCreated'))
await queryClient.invalidateQueries({ queryKey: ['admin-accounts'] })
@@ -645,13 +946,28 @@ function SettingsRoute() {
createAdminUser(adminConnection, input),
onError: (error) => toast.error(getErrorMessage(error)),
onSuccess: async (result, variables) => {
- setKeyResult(result)
- setManagedAccountId(variables.accountId)
- setDraft((current) => ({
- ...current,
- accountId: variables.accountId,
- userId: variables.userId,
- }))
+ const keyResultWithIdentity = {
+ ...result,
+ accountId: result.accountId || variables.accountId,
+ userId: result.userId || variables.userId,
+ }
+ setKeyResult(keyResultWithIdentity)
+ setManagedAccountIds((current) =>
+ sortedAccountIds([...current, variables.accountId], ''),
+ )
+ if (keyResultWithIdentity.apiKey) {
+ const next = buildDataKeyConnection(draft, keyResultWithIdentity)
+ setDraft(next)
+ saveConnection(next)
+ } else {
+ const next = {
+ ...draft,
+ accountId: variables.accountId,
+ userId: variables.userId,
+ }
+ setDraft(next)
+ saveConnection(next)
+ }
setAddUserOpen(false)
toast.success(t('toast.userCreated'))
await queryClient.invalidateQueries({ queryKey: ['admin-accounts'] })
@@ -663,8 +979,17 @@ function SettingsRoute() {
mutationFn: (user: AdminUser) =>
regenerateAdminUserKey(adminConnection, user.accountId, user.userId),
onError: (error) => toast.error(getErrorMessage(error)),
- onSuccess: async (result) => {
+ onSuccess: async (result, user) => {
setKeyResult(result)
+ if (
+ result.apiKey &&
+ user.accountId === draft.accountId &&
+ user.userId === draft.userId
+ ) {
+ const next = buildDataKeyConnection(draft, result)
+ setDraft(next)
+ saveConnection(next)
+ }
setPendingRegenerateUser(null)
toast.success(t('toast.keyRegenerated'))
await queryClient.invalidateQueries({ queryKey: ['admin-users'] })
@@ -680,16 +1005,54 @@ function SettingsRoute() {
const visibleKeys = managedUsers.filter(
(user) => user.apiKey || user.keyPrefix,
).length
- const adminUnavailable =
- !canQueryAdmin || accountsQuery.isError || managedUsersQuery.isError
+ const adminUnavailable = !canQueryAdmin || managedUsersQuery.isError
function updateDraft(next: Partial<ConnectionDraft>): void {
- setDraft((current) => ({ ...current, ...next }))
+ const updated = { ...draft, ...next }
+ setDraft(updated)
+ saveConnection(updated)
+ }
+
+ function updateConnectionAccount(accountId: string): void {
+ updateDraft({
+ accountId,
+ apiKey: '',
+ userId: DEFAULT_USER_ID,
+ })
+ }
+
+ function updateConnectionUser(userId: string): void {
+ const selectedUser = users.find((user) => user.userId === userId)
+ updateDraft({
+ apiKey: selectedUser?.apiKey || '',
+ userId,
+ })
+ }
+
+ function buildDataKeyConnection(
+ current: ConnectionDraft,
+ result: KeyResult,
+ ): ConnectionDraft {
+ const nextApiKey = result.apiKey || current.apiKey
+ return {
+ ...current,
+ accountId: result.accountId || current.accountId || DEFAULT_ACCOUNT_ID,
+ adminApiKey:
+ current.adminApiKey ||
+ (current.apiKey && current.apiKey !== nextApiKey ? current.apiKey : ''),
+ apiKey: nextApiKey,
+ userId: result.userId || current.userId || DEFAULT_USER_ID,
+ }
}
- function handleSave(): void {
- saveConnection(draft)
- toast.success(t('toast.connectionSaved'))
+ function useKeyForData(result: KeyResult): void {
+ if (!result.apiKey) {
+ return
+ }
+ const next = buildDataKeyConnection(draft, result)
+ setDraft(next)
+ saveConnection(next)
+ toast.success(t('toast.dataKeySelected'))
}
async function refreshAdmin(): Promise<void> {
@@ -697,6 +1060,7 @@ function SettingsRoute() {
accountsQuery.refetch(),
usersQuery.refetch(),
managedUsersQuery.refetch(),
+ probeQuery.refetch(),
])
}
@@ -728,39 +1092,19 @@ function SettingsRoute() {
<KeyRoundIcon className="size-4" />
</div>
<CardTitle>{t('connection.title')}</CardTitle>
- <Badge
- variant="outline"
- className="border-primary/25 bg-background/80 text-primary"
- >
- {t(`serverMode.${serverMode}`)}
- </Badge>
</div>
- <CardDescription className="mt-1">
- {t('connection.description')}
- </CardDescription>
- </div>
- <div className="flex flex-wrap gap-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => void refreshAdmin()}
- disabled={!canQueryAdmin || accountsQuery.isFetching}
- >
- <RefreshCwIcon
- className={cn(accountsQuery.isFetching && 'animate-spin')}
- />
- {t('actions.refresh')}
- </Button>
- <Button type="button" size="sm" onClick={handleSave}>
- <SaveIcon />
- {t('actions.save')}
- </Button>
</div>
</div>
</CardHeader>
<CardContent className="grid gap-3 px-5 py-4">
- <div className="grid gap-3 xl:grid-cols-[minmax(16rem,1.2fr)_minmax(12rem,0.8fr)_minmax(12rem,0.8fr)_minmax(11rem,0.8fr)]">
+ <div
+ className={cn(
+ 'grid gap-3',
+ hasAdminAccess
+ ? 'xl:grid-cols-[minmax(16rem,1.2fr)_minmax(12rem,0.8fr)_minmax(12rem,0.8fr)]'
+ : 'xl:grid-cols-[minmax(16rem,1.2fr)_minmax(16rem,1fr)]',
+ )}
+ >
<Field>
<FieldLabel htmlFor="settings-base-url">
{t('fields.baseUrl')}
@@ -776,236 +1120,326 @@ function SettingsRoute() {
/>
</FieldContent>
</Field>
- <Field>
- <FieldLabel>{t('fields.account')}</FieldLabel>
- <FieldContent>
- <AccountSelect
- accounts={accountOptions}
- disabled={!canQueryAdmin || accountsQuery.isLoading}
- label={t('fields.account')}
- value={draft.accountId || DEFAULT_ACCOUNT_ID}
- onChange={(accountId) =>
- updateDraft({
- accountId,
- userId: DEFAULT_USER_ID,
- })
- }
- />
- </FieldContent>
- </Field>
- <Field>
- <FieldLabel>{t('fields.user')}</FieldLabel>
- <FieldContent>
- <UserSelect
- disabled={!canQueryAdmin || usersQuery.isLoading}
- label={t('fields.user')}
- users={users}
- value={draft.userId || DEFAULT_USER_ID}
- onChange={(userId) => updateDraft({ userId })}
- />
- </FieldContent>
- </Field>
+ {hasAdminAccess ? (
+ <>
+ <Field>
+ <FieldLabel>{t('fields.account')}</FieldLabel>
+ <FieldContent>
+ <AccountSelect
+ accounts={accountOptions}
+ disabled={!canQueryAdmin || accountsQuery.isLoading}
+ label={t('fields.account')}
+ value={draft.accountId || DEFAULT_ACCOUNT_ID}
+ onChange={updateConnectionAccount}
+ />
+ </FieldContent>
+ </Field>
+ <Field>
+ <FieldLabel>{t('fields.user')}</FieldLabel>
+ <FieldContent>
+ <UserSelect
+ disabled={!canQueryAdmin || usersQuery.isLoading}
+ label={t('fields.user')}
+ users={users}
+ value={draft.userId || DEFAULT_USER_ID}
+ onChange={updateConnectionUser}
+ />
+ </FieldContent>
+ </Field>
+ </>
+ ) : showDevApiKeyPlaceholder ? (
+ <Field>
+ <FieldLabel htmlFor="settings-api-key-dev">
+ {t('fields.apiKey')}
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ id="settings-api-key-dev"
+ value={t('placeholders.devModeApiKey')}
+ disabled
+ readOnly
+ />
+ </FieldContent>
+ </Field>
+ ) : showAdminCredentialFields ? null : (
+ <Field>
+ <FieldLabel htmlFor="settings-api-key">
+ {t('fields.apiKey')}
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ id="settings-api-key"
+ type="password"
+ value={draft.apiKey}
+ onChange={(event) =>
+ updateDraft({ apiKey: event.target.value })
+ }
+ placeholder={t('placeholders.apiKey')}
+ />
+ </FieldContent>
+ </Field>
+ )}
</div>
- <div className="grid gap-3">
- <Field>
- <FieldLabel htmlFor="settings-api-key">
- {t('fields.apiKey')}
- </FieldLabel>
- <FieldContent>
- <Input
- id="settings-api-key"
- type="password"
- value={draft.apiKey}
- onChange={(event) =>
- updateDraft({ apiKey: event.target.value })
- }
- placeholder={t('placeholders.apiKey')}
+ {showAdminCredentialFields ? (
+ <>
+ <div className="grid gap-3">
+ <Field>
+ <FieldLabel htmlFor="settings-admin-api-key">
+ {t('fields.adminApiKey')}
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ id="settings-admin-api-key"
+ type="password"
+ value={
+ shouldPromoteApiKeyToAdmin
+ ? draft.apiKey
+ : draft.adminApiKey
+ }
+ onChange={(event) =>
+ updateDraft({ adminApiKey: event.target.value })
+ }
+ placeholder={t('placeholders.adminApiKey')}
+ />
+ </FieldContent>
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="settings-user-api-key">
+ {t('fields.userApiKey')}
+ </FieldLabel>
+ <FieldContent>
+ <UserApiKeyInput
+ accountId={draft.accountId || DEFAULT_ACCOUNT_ID}
+ id="settings-user-api-key"
+ userId={draft.userId || DEFAULT_USER_ID}
+ value={shouldPromoteApiKeyToAdmin ? '' : draft.apiKey}
+ onChange={(apiKey) => updateDraft({ apiKey })}
+ placeholder={t('placeholders.userApiKey')}
+ />
+ </FieldContent>
+ </Field>
+ </div>
+ <div className="grid gap-2 md:grid-cols-2">
+ <CapabilityStatus
+ isLoading={probeQuery.isFetching}
+ label={t('health.admin')}
+ result={probeQuery.data?.admin}
/>
- </FieldContent>
- </Field>
- </div>
- {!canQueryAdmin ? (
- <p className="text-sm text-muted-foreground">
- {t('connection.noKey')}
- </p>
- ) : accountsQuery.isError ? (
- <p className="text-sm text-destructive">
- {t('connection.adminError', {
- message: getErrorMessage(accountsQuery.error),
- })}
- </p>
+ <CapabilityStatus
+ isLoading={probeQuery.isFetching}
+ label={t('health.data')}
+ result={probeQuery.data?.data}
+ />
+ </div>
+ {accountsQuery.isError && managedUsersQuery.isError ? (
+ <p className="text-sm text-destructive">
+ {t('connection.adminError', {
+ message: getErrorMessage(accountsQuery.error),
+ })}
+ </p>
+ ) : accountsQuery.isError ? (
+ <p className="text-sm text-muted-foreground">
+ {t('connection.accountListLimited')}
+ </p>
+ ) : null}
+ </>
) : null}
</CardContent>
</Card>
- <div className="grid gap-3 md:grid-cols-3">
- <StatCard
- label={t('stats.accounts')}
- value={totalAccounts || '-'}
- icon={<ServerIcon className="size-4" />}
- />
- <StatCard
- label={t('stats.users')}
- value={totalUsers || '-'}
- icon={<UsersRoundIcon className="size-4" />}
- />
- <StatCard
- label={t('stats.apiKeys')}
- value={visibleKeys || '-'}
- icon={<KeyRoundIcon className="size-4" />}
- />
- </div>
+ {hasAdminAccess ? (
+ <div className="grid gap-3 md:grid-cols-3">
+ <StatCard
+ label={t('stats.accounts')}
+ value={totalAccounts || '-'}
+ icon={<ServerIcon className="size-4" />}
+ />
+ <StatCard
+ label={t('stats.users')}
+ value={totalUsers || '-'}
+ icon={<UsersRoundIcon className="size-4" />}
+ />
+ <StatCard
+ label={t('stats.apiKeys')}
+ value={visibleKeys || '-'}
+ icon={<KeyRoundIcon className="size-4" />}
+ />
+ </div>
+ ) : null}
- {keyResult ? (
- <KeyResultCard result={keyResult} onClear={() => setKeyResult(null)} />
+ {hasAdminAccess && keyResult ? (
+ <KeyResultCard
+ result={keyResult}
+ onClear={() => setKeyResult(null)}
+ onUseForData={() => useKeyForData(keyResult)}
+ />
) : null}
- <Card className="overflow-hidden">
- <CardHeader className="gap-4 border-b bg-muted/20">
- <div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-start">
- <div className="min-w-0">
- <CardTitle>{t('management.title')}</CardTitle>
- <CardDescription>{t('management.description')}</CardDescription>
- </div>
- <div className="flex flex-wrap items-center gap-2 lg:flex-nowrap lg:justify-end">
- <div className="min-w-40">
- <AccountSelect
+ {hasAdminAccess ? (
+ <Card className="overflow-hidden">
+ <CardHeader className="gap-4 border-b bg-muted/20">
+ <div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-start">
+ <div className="min-w-0">
+ <CardTitle>{t('management.title')}</CardTitle>
+ <CardDescription>{t('management.description')}</CardDescription>
+ </div>
+ <div className="flex flex-wrap items-end gap-2 lg:justify-end">
+ <AccountFilterChips
accounts={accountOptions}
disabled={!canQueryAdmin || accountsQuery.isLoading}
label={t('management.accountFilter')}
- value={managedAccountId}
- onChange={setManagedAccountId}
+ selectedAccountIds={selectedManagedAccountIds}
+ onChange={setManagedAccountIds}
/>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => void refreshAdmin()}
+ disabled={!canQueryAdmin || managedUsersQuery.isFetching}
+ >
+ <RefreshCwIcon
+ className={cn(
+ managedUsersQuery.isFetching && 'animate-spin',
+ )}
+ />
+ {t('actions.refresh')}
+ </Button>
+ <Button
+ type="button"
+ onClick={() => setAddAccountOpen(true)}
+ disabled={!canQueryAdmin}
+ >
+ <PlusIcon />
+ {t('actions.addAccount')}
+ </Button>
+ <Button
+ type="button"
+ onClick={() => setAddUserOpen(true)}
+ disabled={!canQueryAdmin}
+ >
+ <PlusIcon />
+ {t('actions.addUser')}
+ </Button>
</div>
- <Button
- type="button"
- variant="outline"
- onClick={() => void refreshAdmin()}
- disabled={!canQueryAdmin || managedUsersQuery.isFetching}
- >
- <RefreshCwIcon
- className={cn(managedUsersQuery.isFetching && 'animate-spin')}
- />
- {t('actions.refresh')}
- </Button>
- <Button
- type="button"
- onClick={() => setAddAccountOpen(true)}
- disabled={!canQueryAdmin}
- >
- <PlusIcon />
- {t('actions.addAccount')}
- </Button>
- <Button
- type="button"
- onClick={() => setAddUserOpen(true)}
- disabled={!canQueryAdmin}
- >
- <PlusIcon />
- {t('actions.addUser')}
- </Button>
</div>
- </div>
- </CardHeader>
- <CardContent className="p-0">
- {adminUnavailable ? (
- <div className="flex min-h-56 flex-col items-center justify-center gap-2 px-6 text-center">
- <div className="flex size-11 items-center justify-center rounded-lg border bg-muted/30 text-muted-foreground">
- <KeyRoundIcon className="size-5" />
+ </CardHeader>
+ <CardContent className="p-0">
+ {adminUnavailable ? (
+ <div className="flex min-h-56 flex-col items-center justify-center gap-2 px-6 text-center">
+ <div className="flex size-11 items-center justify-center rounded-lg border bg-muted/30 text-muted-foreground">
+ <KeyRoundIcon className="size-5" />
+ </div>
+ <p className="font-medium">{t('empty.adminTitle')}</p>
+ <p className="max-w-lg text-sm text-muted-foreground">
+ {t('empty.adminDescription')}
+ </p>
</div>
- <p className="font-medium">{t('empty.adminTitle')}</p>
- <p className="max-w-lg text-sm text-muted-foreground">
- {t('empty.adminDescription')}
- </p>
- </div>
- ) : managedUsersQuery.isLoading ? (
- <div className="flex min-h-56 items-center justify-center text-sm text-muted-foreground">
- {t('loading')}
- </div>
- ) : managedUsers.length === 0 ? (
- <div className="flex min-h-56 flex-col items-center justify-center gap-2 px-6 text-center">
- <div className="flex size-11 items-center justify-center rounded-lg border bg-muted/30 text-muted-foreground">
- <UserRoundIcon className="size-5" />
+ ) : managedUsersQuery.isLoading ? (
+ <div className="flex min-h-56 items-center justify-center text-sm text-muted-foreground">
+ {t('loading')}
</div>
- <p className="font-medium">{t('empty.usersTitle')}</p>
- <p className="text-sm text-muted-foreground">
- {t('empty.usersDescription')}
- </p>
- </div>
- ) : (
- <div className="overflow-x-auto">
- <Table>
- <TableHeader>
- <TableRow className="bg-muted/20 hover:bg-muted/20">
- <TableHead>{t('table.account')}</TableHead>
- <TableHead>{t('table.user')}</TableHead>
- <TableHead>{t('table.role')}</TableHead>
- <TableHead>{t('table.apiKey')}</TableHead>
- <TableHead className="text-right">
- {t('table.actions')}
- </TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {managedUsers.map((user) => (
- <TableRow key={`${user.accountId}:${user.userId}`}>
- <TableCell className="font-mono text-xs text-muted-foreground">
- {user.accountId}
- </TableCell>
- <TableCell className="font-medium">
- {user.userId}
- </TableCell>
- <TableCell>
- <Badge
- variant={
- user.role === 'admin' ? 'secondary' : 'outline'
- }
- >
- {t(`roles.${user.role}`, {
- defaultValue: user.role,
- })}
- </Badge>
- </TableCell>
- <TableCell>
- <div className="flex min-w-0 items-center gap-2">
- <code className="max-w-[20rem] truncate rounded-md border bg-muted/40 px-2 py-1 font-mono text-xs">
- {resolveKeyLabel(user)}
- </code>
- {user.apiKey ? (
+ ) : managedUsers.length === 0 ? (
+ <div className="flex min-h-56 flex-col items-center justify-center gap-2 px-6 text-center">
+ <div className="flex size-11 items-center justify-center rounded-lg border bg-muted/30 text-muted-foreground">
+ <UserRoundIcon className="size-5" />
+ </div>
+ <p className="font-medium">{t('empty.usersTitle')}</p>
+ <p className="text-sm text-muted-foreground">
+ {t('empty.usersDescription')}
+ </p>
+ </div>
+ ) : (
+ <div className="overflow-x-auto">
+ <Table>
+ <TableHeader>
+ <TableRow className="bg-muted/20 hover:bg-muted/20">
+ <TableHead>{t('table.account')}</TableHead>
+ <TableHead>{t('table.user')}</TableHead>
+ <TableHead>{t('table.role')}</TableHead>
+ <TableHead>{t('table.apiKey')}</TableHead>
+ <TableHead className="text-right">
+ {t('table.actions')}
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {managedUsers.map((user) => (
+ <TableRow key={`${user.accountId}:${user.userId}`}>
+ <TableCell className="font-mono text-xs text-muted-foreground">
+ {user.accountId}
+ </TableCell>
+ <TableCell className="font-medium">
+ {user.userId}
+ </TableCell>
+ <TableCell>
+ <Badge
+ variant={
+ user.role === 'admin' ? 'secondary' : 'outline'
+ }
+ >
+ {t(`roles.${user.role}`, {
+ defaultValue: user.role,
+ })}
+ </Badge>
+ </TableCell>
+ <TableCell>
+ <div className="flex min-w-0 items-center gap-2">
+ <code className="max-w-[20rem] truncate rounded-md border bg-muted/40 px-2 py-1 font-mono text-xs">
+ {resolveKeyLabel(user)}
+ </code>
+ {user.apiKey ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t('actions.copy')}
+ onClick={() => void copyKey(user.apiKey)}
+ >
+ <CopyIcon />
+ </Button>
+ ) : null}
+ </div>
+ </TableCell>
+ <TableCell>
+ <div className="flex justify-end gap-2">
+ {user.apiKey ? (
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ onClick={() =>
+ useKeyForData({
+ accountId: user.accountId,
+ apiKey: user.apiKey || '',
+ userId: user.userId,
+ })
+ }
+ >
+ <DatabaseIcon />
+ {t('actions.useForData')}
+ </Button>
+ ) : null}
<Button
type="button"
- variant="ghost"
- size="icon-xs"
- aria-label={t('actions.copy')}
- onClick={() => void copyKey(user.apiKey)}
+ variant="outline"
+ size="sm"
+ onClick={() => setPendingRegenerateUser(user)}
+ disabled={regenerateMutation.isPending}
>
- <CopyIcon />
+ <RotateCwIcon />
+ {t('actions.regenerate')}
</Button>
- ) : null}
- </div>
- </TableCell>
- <TableCell>
- <div className="flex justify-end gap-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => setPendingRegenerateUser(user)}
- disabled={regenerateMutation.isPending}
- >
- <RotateCwIcon />
- {t('actions.regenerate')}
- </Button>
- </div>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </div>
- )}
- </CardContent>
- </Card>
+ </div>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ ) : null}
<AddAccountDialog
open={addAccountOpen}
@@ -1017,7 +1451,7 @@ function SettingsRoute() {
open={addUserOpen}
onOpenChange={setAddUserOpen}
accounts={accountOptions}
- defaultAccountId={managedAccountId}
+ defaultAccountId={selectedManagedAccountIds[0] || selectedAccountId}
isPending={createUserMutation.isPending}
onCreate={(next) => createUserMutation.mutate(next)}
/>
diff --git a/web-studio/src/styles.css b/web-studio/src/styles.css
index 006b6886b..46b77a790 100644
--- a/web-studio/src/styles.css
+++ b/web-studio/src/styles.css
@@ -199,8 +199,6 @@
}
}
-/* ---- FindPalette animations ---- */
-
@keyframes home-panel-in {
from {
opacity: 0;
@@ -216,60 +214,6 @@
animation: home-panel-in 0.32s cubic-bezier(0.16, 1, 0.3, 1) both;
}
-@keyframes palette-backdrop-in {
- from { opacity: 0; }
- to { opacity: 1; }
-}
-
-@keyframes palette-in {
- from {
- opacity: 0;
- transform: translateY(-12px) scale(0.97);
- }
- to {
- opacity: 1;
- transform: translateY(0) scale(1);
- }
-}
-
-@keyframes palette-slide-right {
- from {
- opacity: 0;
- transform: translateX(8px);
- }
- to {
- opacity: 1;
- transform: translateX(0);
- }
-}
-
-@keyframes palette-row-in {
- from {
- opacity: 0;
- transform: translateY(4px);
- }
- to {
- opacity: 1;
- transform: translateY(0);
- }
-}
-
-.animate-palette-backdrop {
- animation: palette-backdrop-in 0.18s cubic-bezier(0.16, 1, 0.3, 1) both;
-}
-
-.animate-palette-in {
- animation: palette-in 0.22s cubic-bezier(0.16, 1, 0.3, 1) both;
-}
-
-.animate-palette-preview {
- animation: palette-slide-right 0.18s cubic-bezier(0.16, 1, 0.3, 1) both;
-}
-
-.animate-palette-row {
- animation: palette-row-in 0.2s cubic-bezier(0.16, 1, 0.3, 1) both;
-}
-
.scrollbar-fade {
scrollbar-width: none;
scrollbar-color: color-mix(in oklch, var(--foreground) 22%, transparent) transparent;