Skip to content

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

feat(web-studio): improve operational navigation and workflows (#3506)

yufeng0ac4b87b03b0
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index ef7ae9e51..db547e4bf 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -3,19 +3,19 @@ import { Link, useNavigate, useRouterState } from '@tanstack/react-router'
import {
BlocksIcon,
BookOpenIcon,
+ BracesIcon,
ChevronRightIcon,
+ ClipboardListIcon,
HomeIcon,
GithubIcon,
KeyRoundIcon,
- LoaderIcon,
- MessageSquareIcon,
MoonIcon,
- PlusIcon,
+ MonitorUpIcon,
PlugZapIcon,
ScrollTextIcon,
SearchIcon,
+ SparklesIcon,
SunIcon,
- TrashIcon,
UsersRoundIcon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
@@ -28,18 +28,18 @@ import {
} from '#/components/ui/collapsible'
import { CrossDeviceVerifyDialog } from '#/components/cross-device-verify-dialog'
import { AccountSwitcher } from '#/components/account-switcher'
+import { CurrentUserMenu } from '#/components/current-user-menu'
import { GeneratedCredentialDialog } from '#/components/generated-credential-dialog'
import { ScrollArea } from '#/components/ui/scroll-area'
import {
Sidebar,
SidebarContent,
- SidebarFooter,
SidebarGroup,
SidebarGroupContent,
+ SidebarGroupLabel,
SidebarHeader,
SidebarInset,
SidebarMenu,
- SidebarMenuAction,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSub,
@@ -54,16 +54,11 @@ import {
} from '#/hooks/use-app-connection'
import { cn } from '#/lib/utils'
import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'
-import {
- useSessionListByRecency,
- useCreateSession,
- useDeleteSession,
-} from '#/lib/sessions/use-sessions'
-import { useSessionTitles } from '#/lib/sessions/use-session-titles'
type NavItem = {
icon: React.ComponentType
id: string
+ section: 'workspace' | 'operations'
titleKey: string
to: string
children?: readonly NavSubItem[]
@@ -87,33 +82,70 @@ const NAV_ITEMS: readonly NavItem[] = [
{
icon: HomeIcon,
id: 'home',
+ section: 'workspace',
titleKey: 'navigation.home.title',
to: '/home',
},
{
icon: PlugZapIcon,
id: 'playground',
+ section: 'workspace',
titleKey: 'navigation.playground.title',
to: '/playground',
},
{
icon: SearchIcon,
id: 'retrieval',
+ section: 'workspace',
titleKey: 'navigation.retrieval.title',
to: '/retrieval',
},
{
- icon: ScrollTextIcon,
- id: 'requestLogs',
- titleKey: 'navigation.requestLogs.title',
- to: '/request-logs',
+ icon: SparklesIcon,
+ id: 'skills',
+ section: 'workspace',
+ titleKey: 'navigation.skills.title',
+ to: '/skills',
},
{
icon: BlocksIcon,
id: 'sessions',
+ section: 'operations',
titleKey: 'navigation.sessions.title',
to: '/sessions',
},
+ {
+ icon: ScrollTextIcon,
+ id: 'requestLogs',
+ section: 'operations',
+ titleKey: 'navigation.requestLogs.title',
+ to: '/request-logs',
+ },
+ {
+ icon: ClipboardListIcon,
+ id: 'tasks',
+ section: 'operations',
+ titleKey: 'navigation.tasks.title',
+ to: '/tasks',
+ },
+ {
+ icon: MonitorUpIcon,
+ id: 'monitoring',
+ section: 'operations',
+ titleKey: 'navigation.monitoring.title',
+ to: '/monitoring',
+ },
+] as const
+
+const NAV_SECTIONS = [
+ {
+ id: 'workspace',
+ titleKey: 'sidebar.groups.workspace',
+ },
+ {
+ id: 'operations',
+ titleKey: 'sidebar.groups.operations',
+ },
] as const
const LANGUAGE_OPTIONS = [
@@ -197,133 +229,6 @@ function NavGroupItem({ item, pathname, title, t }: NavGroupItemProps) {
)
}
-function NavSessionsItem({
- pathname,
- title,
-}: {
- pathname: string
- title: string
-}) {
- const { t } = useTranslation(['appShell', 'sessions'])
- const { identityScopeKey } = useAppConnection()
- const navigate = useNavigate()
- const isActive = pathname === '/sessions' || pathname.startsWith('/sessions/')
- const [open, setOpen] = React.useState(isActive)
-
- const { data: sessions, isLoading } = useSessionListByRecency()
- const { getTitle, removeTitle, setTitle } = useSessionTitles(identityScopeKey)
- const createSession = useCreateSession()
- const deleteSession = useDeleteSession()
-
- const activeSessionId = useRouterState({
- select: (s) => {
- const search = s.location.search as { s?: string }
- return search.s ?? null
- },
- })
-
- React.useEffect(() => {
- if (isActive) setOpen(true)
- }, [isActive])
-
- const handleNewSession = React.useCallback(async () => {
- const result = await createSession.mutateAsync(undefined)
- setTitle(result.session_id, t('threadList.newSession', { ns: 'sessions' }))
- void navigate({ to: '/sessions', search: { s: result.session_id } })
- }, [createSession, navigate, setTitle, t])
-
- const handleDeleteSession = React.useCallback(
- async (e: React.MouseEvent, id: string) => {
- e.stopPropagation()
- e.preventDefault()
- await deleteSession.mutateAsync(id)
- removeTitle(id)
- if (activeSessionId === id) {
- void navigate({
- to: '/sessions',
- search: { s: undefined } as { s?: string },
- })
- }
- },
- [activeSessionId, deleteSession, navigate, removeTitle],
- )
-
- return (
- <Collapsible
- open={open}
- onOpenChange={setOpen}
- className="group/collapsible"
- >
- <SidebarMenuItem>
- <CollapsibleTrigger
- render={
- <SidebarMenuButton tooltip={title} className="text-base">
- <BlocksIcon />
- <span>{title}</span>
- <ChevronRightIcon className="ml-auto transition-transform duration-200 group-data-[open]/collapsible:rotate-90" />
- </SidebarMenuButton>
- }
- />
- <SidebarMenuAction
- onClick={handleNewSession}
- title={t('threadList.newSession', { ns: 'sessions' })}
- >
- <PlusIcon className="size-4" />
- </SidebarMenuAction>
- <CollapsibleContent>
- <SidebarMenuSub>
- {isLoading ? (
- <SidebarMenuSubItem>
- <div className="flex items-center gap-2 px-2 py-1.5 text-xs text-muted-foreground">
- <LoaderIcon className="size-3 animate-spin" />
- <span>
- {t('sidebar.loadingSessions', { ns: 'appShell' })}
- </span>
- </div>
- </SidebarMenuSubItem>
- ) : sessions.length === 0 ? (
- <SidebarMenuSubItem>
- <div className="px-2 py-1.5 text-xs text-muted-foreground">
- {t('sidebar.noSessions', { ns: 'appShell' })}
- </div>
- </SidebarMenuSubItem>
- ) : (
- sessions.map((s) => {
- const sessionTitle = getTitle(s.session_id)
- const isSessionActive = activeSessionId === s.session_id
-
- return (
- <SidebarMenuSubItem
- key={s.session_id}
- className="group/session"
- >
- <SidebarMenuSubButton
- render={
- <Link to="/sessions" search={{ s: s.session_id }} />
- }
- isActive={isSessionActive}
- >
- <MessageSquareIcon className="size-3.5 shrink-0 opacity-60" />
- <span className="truncate">{sessionTitle}</span>
- </SidebarMenuSubButton>
- <button
- type="button"
- onClick={(e) => handleDeleteSession(e, s.session_id)}
- className="absolute right-1 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/session:opacity-100"
- >
- <TrashIcon className="size-3" />
- </button>
- </SidebarMenuSubItem>
- )
- })
- )}
- </SidebarMenuSub>
- </CollapsibleContent>
- </SidebarMenuItem>
- </Collapsible>
- )
-}
-
export function AppShell({ children }: { children: React.ReactNode }) {
return (
<AppConnectionProvider>
@@ -347,6 +252,12 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
const currentLanguage = resolveLanguage(
i18n.resolvedLanguage ?? i18n.language,
)
+ const agentIntegrationsHref = `https://docs.openviking.ai/${
+ currentLanguage === 'zh-CN' ? 'zh' : 'en'
+ }/agent-integrations/01-overview`
+ const sdkApiHref = `https://docs.openviking.ai/${
+ currentLanguage === 'zh-CN' ? 'zh' : 'en'
+ }/api/01-overview`
const [crossDeviceVerifyOpen, setCrossDeviceVerifyOpen] =
React.useState(false)
const { connection, connectionRole, isConnectionRoleLoading, serverMode } =
@@ -396,135 +307,168 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
</div>
</SidebarHeader>
- <SidebarContent>
- <SidebarGroup>
+ <SidebarContent className="gap-0 py-1">
+ {NAV_SECTIONS.map((section) => (
+ <SidebarGroup key={section.id} className="pb-1">
+ <SidebarGroupLabel className="h-7 px-2 pt-2 text-[11px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/45">
+ {t(section.titleKey, { ns: 'appShell' })}
+ </SidebarGroupLabel>
+ <SidebarGroupContent>
+ <SidebarMenu>
+ {visibleNavItems
+ .filter((item) => item.section === section.id)
+ .map((item) => {
+ const isActive =
+ pathname === item.to ||
+ pathname.startsWith(`${item.to}/`)
+ const title = t(item.titleKey, { ns: 'appShell' })
+
+ if (item.children) {
+ return (
+ <NavGroupItem
+ key={item.id}
+ item={
+ item as NavItem & {
+ children: readonly NavSubItem[]
+ }
+ }
+ pathname={pathname}
+ title={title}
+ t={t}
+ />
+ )
+ }
+
+ const Icon = item.icon
+
+ return (
+ <SidebarMenuItem key={item.id}>
+ <SidebarMenuButton
+ render={<Link to={item.to} />}
+ isActive={isActive}
+ tooltip={title}
+ className="h-9"
+ >
+ <Icon />
+ <span>{title}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ )
+ })}
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </SidebarGroup>
+ ))}
+
+ <SidebarGroup className="pb-1">
+ <SidebarGroupLabel className="h-7 px-2 pt-2 text-[11px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/45">
+ {t('sidebar.groups.settings', { ns: 'appShell' })}
+ </SidebarGroupLabel>
+ <SidebarGroupContent>
+ <SidebarMenu>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ render={<Link to="/settings" />}
+ isActive={settingsActive}
+ tooltip={t('footer.connection', { ns: 'appShell' })}
+ className="h-9"
+ >
+ <PlugZapIcon />
+ <span>{t('footer.connection', { ns: 'appShell' })}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ {canManageUsers ? (
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ render={<Link to="/users" />}
+ isActive={usersActive}
+ tooltip={t('footer.users', { ns: 'appShell' })}
+ className="h-9"
+ >
+ <UsersRoundIcon />
+ <span>{t('footer.users', { ns: 'appShell' })}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ ) : null}
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ onClick={openCrossDeviceVerify}
+ isActive={crossDeviceVerifyActive}
+ tooltip={t('navigation.crossDeviceVerify.title', {
+ ns: 'appShell',
+ })}
+ className="h-9"
+ >
+ <KeyRoundIcon />
+ <span>
+ {t('navigation.crossDeviceVerify.title', {
+ ns: 'appShell',
+ })}
+ </span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </SidebarGroup>
+
+ <SidebarGroup className="pb-1">
+ <SidebarGroupLabel className="h-7 px-2 pt-2 text-[11px] font-semibold uppercase tracking-[0.12em] text-sidebar-foreground/45">
+ {t('sidebar.groups.resources', { ns: 'appShell' })}
+ </SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
- {visibleNavItems.map((item) => {
- const isActive =
- pathname === item.to || pathname.startsWith(`${item.to}/`)
- const title = t(item.titleKey, { ns: 'appShell' })
-
- if (item.id === 'sessions') {
- return (
- <NavSessionsItem
- key={item.id}
- pathname={pathname}
- title={title}
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ render={
+ <a
+ href="https://docs.openviking.ai/"
+ target="_blank"
+ rel="noreferrer"
/>
- )
- }
-
- if (item.children) {
- return (
- <NavGroupItem
- key={item.id}
- item={
- item as NavItem & { children: readonly NavSubItem[] }
- }
- pathname={pathname}
- title={title}
- t={t}
+ }
+ tooltip={t('footer.docs', { ns: 'appShell' })}
+ className="h-9"
+ >
+ <BookOpenIcon />
+ <span>{t('footer.docs', { ns: 'appShell' })}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ render={
+ <a href={sdkApiHref} target="_blank" rel="noreferrer" />
+ }
+ tooltip={t('footer.sdkApi', { ns: 'appShell' })}
+ className="h-9"
+ >
+ <BracesIcon />
+ <span>{t('footer.sdkApi', { ns: 'appShell' })}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ render={
+ <a
+ href={agentIntegrationsHref}
+ target="_blank"
+ rel="noreferrer"
/>
- )
- }
-
- const Icon = item.icon
-
- return (
- <SidebarMenuItem key={item.id}>
- <SidebarMenuButton
- render={<Link to={item.to} />}
- isActive={isActive}
- tooltip={title}
- className="text-base"
- >
- <Icon />
- <span>{title}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- )
- })}
+ }
+ tooltip={t('footer.agentIntegrations', {
+ ns: 'appShell',
+ })}
+ className="h-9"
+ >
+ <PlugZapIcon />
+ <span>
+ {t('footer.agentIntegrations', { ns: 'appShell' })}
+ </span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
-
- <SidebarFooter>
- <SidebarMenu>
- <SidebarMenuItem>
- <SidebarMenuButton
- render={<Link to="/settings" />}
- isActive={settingsActive}
- tooltip={t('footer.connection', { ns: 'appShell' })}
- className="text-base"
- >
- <PlugZapIcon className="size-5" />
- <span>{t('footer.connection', { ns: 'appShell' })}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- {canManageUsers ? (
- <SidebarMenuItem>
- <SidebarMenuButton
- render={<Link to="/users" />}
- isActive={usersActive}
- tooltip={t('footer.users', { ns: 'appShell' })}
- className="text-base"
- >
- <UsersRoundIcon className="size-5" />
- <span>{t('footer.users', { ns: 'appShell' })}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- ) : null}
- <SidebarMenuItem>
- <SidebarMenuButton
- onClick={openCrossDeviceVerify}
- isActive={crossDeviceVerifyActive}
- tooltip={t('navigation.crossDeviceVerify.title', {
- ns: 'appShell',
- })}
- className="text-base"
- >
- <KeyRoundIcon className="size-5" />
- <span>
- {t('navigation.crossDeviceVerify.title', { ns: 'appShell' })}
- </span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- <SidebarMenuItem>
- <SidebarMenuButton
- render={
- <a
- href="https://github.com/volcengine/OpenViking"
- target="_blank"
- rel="noreferrer"
- />
- }
- tooltip={t('footer.github', { ns: 'appShell' })}
- className="text-base"
- >
- <GithubIcon className="size-5" />
- <span>{t('footer.github', { ns: 'appShell' })}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- <SidebarMenuItem>
- <SidebarMenuButton
- render={
- <a
- href="https://docs.openviking.ai/"
- target="_blank"
- rel="noreferrer"
- />
- }
- tooltip={t('footer.docs', { ns: 'appShell' })}
- className="text-base"
- >
- <BookOpenIcon className="size-5" />
- <span>{t('footer.docs', { ns: 'appShell' })}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- </SidebarMenu>
- </SidebarFooter>
</Sidebar>
<SidebarInset className="min-h-0 flex-1 overflow-hidden rounded-none border-0 bg-background shadow-none ring-0 md:m-0 md:ml-0">
@@ -587,6 +531,13 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
>
<GithubIcon className="size-5" />
</a>
+
+ <div className="h-6 w-px bg-border/80" aria-hidden="true" />
+
+ <CurrentUserMenu
+ accountId={connection.accountId}
+ userId={connection.userId}
+ />
</div>
</header>
diff --git a/web-studio/src/components/cross-device-verify-dialog.tsx b/web-studio/src/components/cross-device-verify-dialog.tsx
index c98b054a1..5edd25cce 100644
--- a/web-studio/src/components/cross-device-verify-dialog.tsx
+++ b/web-studio/src/components/cross-device-verify-dialog.tsx
@@ -5,7 +5,6 @@ import {
Dialog,
DialogContent,
DialogDescription,
- DialogFooter,
DialogHeader,
DialogTitle,
} from '#/components/ui/dialog'
@@ -28,12 +27,17 @@ export function CrossDeviceVerifyDialog({
{t('verify.description', { ns: 'oauth' })}
</DialogDescription>
</DialogHeader>
- <CrossDeviceVerifyForm />
- <DialogFooter>
- <Button variant="outline" onClick={() => onOpenChange(false)}>
- {t('action.cancel', { ns: 'common' })}
- </Button>
- </DialogFooter>
+ <CrossDeviceVerifyForm
+ secondaryAction={
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ >
+ {t('action.cancel', { ns: 'common' })}
+ </Button>
+ }
+ />
</DialogContent>
</Dialog>
)
diff --git a/web-studio/src/components/cross-device-verify-form.tsx b/web-studio/src/components/cross-device-verify-form.tsx
index ad9d6a506..64c705a43 100644
--- a/web-studio/src/components/cross-device-verify-form.tsx
+++ b/web-studio/src/components/cross-device-verify-form.tsx
@@ -29,7 +29,11 @@ type Phase =
* footer's verify dialog, so it carries its own chrome-free layout and the host
* (Card or Dialog) supplies the title/footer.
*/
-export function CrossDeviceVerifyForm() {
+export function CrossDeviceVerifyForm({
+ secondaryAction,
+}: {
+ secondaryAction?: React.ReactNode
+} = {}) {
const { t } = useTranslation(['oauth', 'common'])
const {
connection,
@@ -229,7 +233,8 @@ export function CrossDeviceVerifyForm() {
</p>
) : null}
- <div className="flex justify-end">
+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
+ {secondaryAction}
<Button
type="submit"
disabled={
diff --git a/web-studio/src/components/current-user-menu.test.ts b/web-studio/src/components/current-user-menu.test.ts
new file mode 100644
index 000000000..08927fc62
--- /dev/null
+++ b/web-studio/src/components/current-user-menu.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest'
+
+import { getUserInitial } from './current-user-menu'
+
+describe('getUserInitial', () => {
+ it('uses the first character of the normalized user id', () => {
+ expect(getUserInitial(' yufeng201 ')).toBe('Y')
+ })
+
+ it('supports non-Latin user ids', () => {
+ expect(getUserInitial('用户')).toBe('用')
+ })
+
+ it('returns a fallback when the user id is empty', () => {
+ expect(getUserInitial(' ')).toBe('?')
+ })
+})
diff --git a/web-studio/src/components/current-user-menu.tsx b/web-studio/src/components/current-user-menu.tsx
new file mode 100644
index 000000000..875b8ee9a
--- /dev/null
+++ b/web-studio/src/components/current-user-menu.tsx
@@ -0,0 +1,88 @@
+import { Building2Icon, ChevronDownIcon, UserRoundIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '#/components/ui/popover'
+
+type CurrentUserMenuProps = {
+ accountId: string
+ userId: string
+}
+
+export function getUserInitial(userId: string): string {
+ const normalizedUserId = userId.trim()
+ return normalizedUserId ? normalizedUserId.slice(0, 1).toUpperCase() : '?'
+}
+
+export function CurrentUserMenu({ accountId, userId }: CurrentUserMenuProps) {
+ const { t } = useTranslation('appShell')
+ const accountLabel = accountId || t('header.currentUser.unset')
+ const userLabel = userId || t('header.currentUser.unset')
+
+ return (
+ <Popover>
+ <PopoverTrigger
+ aria-label={t('header.currentUser.openMenu', { user: userLabel })}
+ className="group flex h-10 max-w-52 items-center gap-2 rounded-2xl border border-border/80 bg-muted/60 p-1 pr-2.5 text-left shadow-xs outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
+ >
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-xl bg-foreground text-xs font-semibold text-background shadow-sm">
+ {getUserInitial(userLabel)}
+ </span>
+ <span className="hidden min-w-0 flex-1 sm:block">
+ <span className="block truncate text-xs font-semibold leading-4 text-foreground">
+ {userLabel}
+ </span>
+ <span className="block truncate text-[10px] leading-3 text-muted-foreground">
+ {t('header.currentUser.accountSummary', {
+ account: accountLabel,
+ })}
+ </span>
+ </span>
+ <ChevronDownIcon className="hidden size-3.5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180 sm:block" />
+ </PopoverTrigger>
+
+ <PopoverContent
+ align="end"
+ side="bottom"
+ sideOffset={8}
+ className="w-72 gap-0 overflow-hidden p-0"
+ >
+ <div className="flex items-center gap-3 border-b bg-muted/35 px-4 py-3.5">
+ <span className="flex size-10 shrink-0 items-center justify-center rounded-2xl bg-foreground text-sm font-semibold text-background shadow-sm">
+ {getUserInitial(userLabel)}
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-semibold">{userLabel}</div>
+ <div className="mt-0.5 text-xs text-muted-foreground">
+ {t('header.currentUser.signedInAs')}
+ </div>
+ </div>
+ </div>
+
+ <dl className="space-y-1 p-2">
+ <div className="flex items-center gap-3 rounded-lg px-2.5 py-2">
+ <Building2Icon className="size-4 shrink-0 text-muted-foreground" />
+ <dt className="w-16 shrink-0 text-xs text-muted-foreground">
+ {t('header.currentUser.account')}
+ </dt>
+ <dd className="min-w-0 flex-1 truncate text-right text-xs font-medium">
+ {accountLabel}
+ </dd>
+ </div>
+ <div className="flex items-center gap-3 rounded-lg px-2.5 py-2">
+ <UserRoundIcon className="size-4 shrink-0 text-muted-foreground" />
+ <dt className="w-16 shrink-0 text-xs text-muted-foreground">
+ {t('header.currentUser.user')}
+ </dt>
+ <dd className="min-w-0 flex-1 truncate text-right text-xs font-medium">
+ {userLabel}
+ </dd>
+ </div>
+ </dl>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/web-studio/src/components/ui/sidebar.tsx b/web-studio/src/components/ui/sidebar.tsx
index e8df3972d..2159805ed 100644
--- a/web-studio/src/components/ui/sidebar.tsx
+++ b/web-studio/src/components/ui/sidebar.tsx
@@ -25,7 +25,7 @@ import { PanelLeftIcon } from "lucide-react"
const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
-const SIDEBAR_WIDTH = "16rem"
+const SIDEBAR_WIDTH = "220px"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
diff --git a/web-studio/src/hooks/use-app-connection.test.ts b/web-studio/src/hooks/use-app-connection.test.ts
index 5866ad4d2..3ac000911 100644
--- a/web-studio/src/hooks/use-app-connection.test.ts
+++ b/web-studio/src/hooks/use-app-connection.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'
import {
createManagementAccountConnection,
createIdentityScopeKey,
+ createConnectionRoleProbeKey,
resolveSwitchedIdentity,
resolveConnectionRoleProbeState,
resolveInitialApiKey,
@@ -14,6 +15,56 @@ import { ovClient } from '#/lib/ov-client'
const acceptClientError = () => true
+describe('createConnectionRoleProbeKey', () => {
+ it('matches the connection produced by an internal identity synchronization', () => {
+ const connection = {
+ accountId: 'default',
+ adminApiKey: 'root-key',
+ apiKey: 'selected-user-key',
+ baseUrl: 'http://localhost:1933/',
+ userId: 'default',
+ }
+ const synchronized = {
+ ...connection,
+ accountId: 'workspace-a',
+ userId: 'alice',
+ }
+
+ expect(createConnectionRoleProbeKey(synchronized, 'api_key')).toBe(
+ createConnectionRoleProbeKey(
+ {
+ ...connection,
+ accountId: 'workspace-a',
+ baseUrl: 'http://localhost:1933',
+ userId: 'alice',
+ },
+ 'api_key',
+ ),
+ )
+ })
+
+ it('changes when a credential or asserted identity changes', () => {
+ const connection = {
+ accountId: 'workspace-a',
+ adminApiKey: 'root-key',
+ apiKey: 'selected-user-key',
+ baseUrl: 'http://localhost:1933',
+ userId: 'alice',
+ }
+ const key = createConnectionRoleProbeKey(connection, 'api_key')
+
+ expect(
+ createConnectionRoleProbeKey(
+ { ...connection, apiKey: 'another-user-key' },
+ 'api_key',
+ ),
+ ).not.toBe(key)
+ expect(
+ createConnectionRoleProbeKey({ ...connection, userId: 'bob' }, 'api_key'),
+ ).not.toBe(key)
+ })
+})
+
describe('resolveInitialApiKey', () => {
it('keeps the stored connection key paired with the stored account and user', () => {
expect(
diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsx
index 811d49a82..483f1b7e8 100644
--- a/web-studio/src/hooks/use-app-connection.tsx
+++ b/web-studio/src/hooks/use-app-connection.tsx
@@ -1,13 +1,15 @@
import * as React from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useNavigate, useRouterState } from '@tanstack/react-router'
-import axios from 'axios'
-import { createClient } from '#/gen/ov-client/client'
import { fetchAdminAccounts } from '#/lib/admin'
-import { getHealth, isOvClientError, ovClient } from '#/lib/ov-client'
+import { isOvClientError, ovClient } from '#/lib/ov-client'
-import { detectServerMode, normalizeBaseUrl } from './use-server-mode'
+import {
+ detectServerMode,
+ fetchServerHealth,
+ normalizeBaseUrl,
+} from './use-server-mode'
import type { ServerMode } from './use-server-mode'
export type ConnectionRole = 'admin' | 'root' | 'unknown' | 'user'
@@ -175,6 +177,20 @@ export function createIdentityScopeKey(
].join('\u0000')
}
+export function createConnectionRoleProbeKey(
+ connection: ConnectionDraft,
+ serverMode: ServerMode,
+): string {
+ return [
+ normalizeBaseUrl(connection.baseUrl),
+ serverMode,
+ connection.accountId,
+ connection.userId,
+ connection.adminApiKey ? hashSecret(connection.adminApiKey) : 'none',
+ connection.apiKey ? hashSecret(connection.apiKey) : 'none',
+ ].join('\u0000')
+}
+
function resolveIdentityField(
envValue: string,
storedValue: string | undefined,
@@ -272,6 +288,27 @@ type ConnectionIdentity = {
userId: string
}
+function createConnectionHealthHeaders(
+ connection: ConnectionDraft,
+ credential: 'control' | 'data' = 'control',
+): Record<string, string> {
+ const headers: Record<string, string> = {}
+ const apiKey =
+ credential === 'data'
+ ? connection.apiKey || connection.adminApiKey
+ : connection.adminApiKey || connection.apiKey
+ if (apiKey) {
+ headers['X-API-Key'] = apiKey
+ }
+ if (connection.accountId) {
+ headers['X-OpenViking-Account'] = connection.accountId
+ }
+ if (connection.userId) {
+ headers['X-OpenViking-User'] = connection.userId
+ }
+ return headers
+}
+
async function canListAccounts(connection: ConnectionDraft): Promise<boolean> {
if (!connection.adminApiKey) {
return false
@@ -294,39 +331,14 @@ async function detectConnectionIdentity(
connection: ConnectionDraft,
credential: 'control' | 'data' = 'control',
): Promise<ConnectionIdentity> {
- const headers: Record<string, string> = {}
- const apiKey =
- credential === 'data'
- ? connection.apiKey || connection.adminApiKey
- : connection.adminApiKey || connection.apiKey
- if (apiKey) {
- headers['X-API-Key'] = apiKey
- }
- // Identity headers are required for trusted-mode identity resolution.
- // In api_key mode the server strips them, so they are always safe to send.
- if (connection.accountId) {
- headers['X-OpenViking-Account'] = connection.accountId
- }
- if (connection.userId) {
- headers['X-OpenViking-User'] = connection.userId
- }
-
- const client = createClient({
- axios: axios.create(),
- baseURL: normalizeBaseUrl(connection.baseUrl),
- headers,
- throwOnError: true,
- })
- const response = await getHealth({ client })
+ const data = await fetchServerHealth(
+ connection.baseUrl,
+ createConnectionHealthHeaders(connection, credential),
+ )
// /health resolves the presented key and echoes back its identity:
// { role, account_id, user_id }. We use role to gate the admin UI and
// account_id to pin the assumed account for an account-admin key.
- const data = response.data as {
- account_id?: unknown
- role?: unknown
- user_id?: unknown
- }
const healthRole = isConnectionRole(data.role) ? data.role : 'unknown'
// In trusted mode /health resolves the asserted tenant user, even when the
// configured Root key is the credential authorizing Admin API calls. Probe
@@ -475,6 +487,10 @@ export function AppConnectionProvider({
select: (state) => state.location.pathname,
})
const initialConnectionRef = React.useRef<ConnectionDraft | null>(null)
+ const synchronizedRoleProbeRef = React.useRef<{
+ key: string
+ role: ConnectionRole
+ } | null>(null)
if (initialConnectionRef.current === null) {
initialConnectionRef.current = readInitialConnection()
applyConnection(initialConnectionRef.current, 'checking')
@@ -512,7 +528,10 @@ export function AppConnectionProvider({
let cancelled = false
setServerMode('checking')
- void detectServerMode(connection.baseUrl).then((mode) => {
+ void detectServerMode(
+ connection.baseUrl,
+ createConnectionHealthHeaders(connection),
+ ).then((mode) => {
if (!cancelled) {
setServerMode(mode)
}
@@ -521,7 +540,13 @@ export function AppConnectionProvider({
return () => {
cancelled = true
}
- }, [connection.baseUrl])
+ }, [
+ connection.accountId,
+ connection.adminApiKey,
+ connection.apiKey,
+ connection.baseUrl,
+ connection.userId,
+ ])
React.useEffect(() => {
let cancelled = false
@@ -532,6 +557,17 @@ export function AppConnectionProvider({
baseUrl: connection.baseUrl,
serverMode,
})
+ const probeKey = createConnectionRoleProbeKey(connection, serverMode)
+ const synchronizedProbe = synchronizedRoleProbeRef.current
+
+ if (synchronizedProbe?.key === probeKey) {
+ synchronizedRoleProbeRef.current = null
+ setConnectionRole(synchronizedProbe.role)
+ setConnectionRoleLoading(false)
+ return () => {
+ cancelled = true
+ }
+ }
setConnectionRole(roleProbe.role)
setConnectionRoleLoading(roleProbe.isLoading)
@@ -560,13 +596,15 @@ export function AppConnectionProvider({
}
const { accountId, role } = controlIdentity
- setConnectionRole(role)
- setConnectionRoleLoading(false)
const dataConnection = dataIdentity
? synchronizeResolvedDataIdentity(connection, dataIdentity)
: null
if (dataConnection) {
const next = synchronizeConnectionRuntime(dataConnection, serverMode)
+ synchronizedRoleProbeRef.current = {
+ key: createConnectionRoleProbeKey(next, serverMode),
+ role,
+ }
queryClient.clear()
setConnection(next)
return
@@ -585,10 +623,16 @@ export function AppConnectionProvider({
{ ...connection, accountId },
serverMode,
)
+ synchronizedRoleProbeRef.current = {
+ key: createConnectionRoleProbeKey(next, serverMode),
+ role,
+ }
queryClient.clear()
setConnection(next)
return
}
+ setConnectionRole(role)
+ setConnectionRoleLoading(false)
})
.catch(() => {
if (!cancelled) {
diff --git a/web-studio/src/hooks/use-server-mode.test.ts b/web-studio/src/hooks/use-server-mode.test.ts
new file mode 100644
index 000000000..c3f8261ee
--- /dev/null
+++ b/web-studio/src/hooks/use-server-mode.test.ts
@@ -0,0 +1,50 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { fetchServerHealth } from './use-server-mode'
+
+const { getHealthMock } = vi.hoisted(() => ({
+ getHealthMock: vi.fn(),
+}))
+
+vi.mock('#/lib/ov-client', () => ({
+ getHealth: getHealthMock,
+}))
+
+describe('fetchServerHealth', () => {
+ beforeEach(() => {
+ getHealthMock.mockReset()
+ getHealthMock.mockResolvedValue({
+ data: { auth_mode: 'api_key', role: 'user' },
+ })
+ })
+
+ it('reuses an identical health probe during connection initialization', async () => {
+ const headers = {
+ 'X-API-Key': 'user-key',
+ 'X-OpenViking-Account': 'default',
+ 'X-OpenViking-User': 'alice',
+ }
+
+ const first = fetchServerHealth('http://localhost:1933/', headers)
+ const second = fetchServerHealth('http://localhost:1933', headers)
+
+ await expect(Promise.all([first, second])).resolves.toEqual([
+ { auth_mode: 'api_key', role: 'user' },
+ { auth_mode: 'api_key', role: 'user' },
+ ])
+ expect(getHealthMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not share health probes across credentials', async () => {
+ await Promise.all([
+ fetchServerHealth('http://localhost:1934', {
+ 'X-API-Key': 'first-key',
+ }),
+ fetchServerHealth('http://localhost:1934', {
+ 'X-API-Key': 'second-key',
+ }),
+ ])
+
+ expect(getHealthMock).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/web-studio/src/hooks/use-server-mode.ts b/web-studio/src/hooks/use-server-mode.ts
index d9e2cdacf..5ab1bcbd0 100644
--- a/web-studio/src/hooks/use-server-mode.ts
+++ b/web-studio/src/hooks/use-server-mode.ts
@@ -4,31 +4,82 @@ export type ServerAuthMode = 'api_key' | 'trusted' | 'dev'
export type ServerMode = ServerAuthMode | 'checking' | 'offline'
const SERVER_AUTH_MODES = new Set<ServerAuthMode>(['api_key', 'trusted', 'dev'])
+const HEALTH_REQUEST_REUSE_MS = 1_000
+
+let recentHealthRequest:
+ | {
+ expiresAt: number
+ key: string
+ promise: Promise<Record<string, unknown>>
+ }
+ | undefined
export function normalizeBaseUrl(baseUrl: string): string {
return baseUrl.trim().replace(/\/+$/, '')
}
function isServerAuthMode(value: unknown): value is ServerAuthMode {
- return typeof value === 'string' && SERVER_AUTH_MODES.has(value as ServerAuthMode)
+ return (
+ typeof value === 'string' && SERVER_AUTH_MODES.has(value as ServerAuthMode)
+ )
}
-export async function detectServerMode(baseUrl: string): Promise<ServerMode> {
+export async function fetchServerHealth(
+ baseUrl: string,
+ headers: Record<string, string> = {},
+): Promise<Record<string, unknown>> {
const normalizedBaseUrl = normalizeBaseUrl(baseUrl)
if (!normalizedBaseUrl) {
- return 'offline'
+ throw new Error('Missing server URL')
+ }
+
+ const key = JSON.stringify([
+ normalizedBaseUrl,
+ Object.entries(headers).sort(([left], [right]) =>
+ left.localeCompare(right),
+ ),
+ ])
+ const now = Date.now()
+ if (recentHealthRequest?.key === key && recentHealthRequest.expiresAt > now) {
+ return recentHealthRequest.promise
}
+ const promise = getHealth({
+ baseURL: normalizedBaseUrl,
+ headers: {
+ Accept: 'application/json',
+ ...headers,
+ },
+ throwOnError: true,
+ }).then((response) => {
+ const data = response.data
+ return data && typeof data === 'object'
+ ? (data as Record<string, unknown>)
+ : {}
+ })
+
+ recentHealthRequest = {
+ expiresAt: now + HEALTH_REQUEST_REUSE_MS,
+ key,
+ promise,
+ }
+
+ try {
+ return await promise
+ } catch (error) {
+ if (recentHealthRequest.promise === promise) {
+ recentHealthRequest = undefined
+ }
+ throw error
+ }
+}
+
+export async function detectServerMode(
+ baseUrl: string,
+ headers?: Record<string, string>,
+): Promise<ServerMode> {
try {
- const response = await getHealth({
- baseURL: normalizedBaseUrl,
- headers: {
- Accept: 'application/json',
- },
- throwOnError: true,
- })
-
- const data = response.data as { auth_mode?: string }
+ const data = await fetchServerHealth(baseUrl, headers)
return isServerAuthMode(data.auth_mode) ? data.auth_mode : 'api_key'
} catch {
return 'offline'
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index 097f7a68b..1cacce22e 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -1,12 +1,22 @@
const en = {
appShell: {
footer: {
+ agentIntegrations: 'Agent Integrations',
connection: 'Connection Settings',
docs: 'Documentation',
github: 'GitHub',
+ sdkApi: 'SDK & API',
users: 'User Management',
},
header: {
+ currentUser: {
+ account: 'Account',
+ accountSummary: 'Account · {{account}}',
+ openMenu: 'View current user {{user}}',
+ signedInAs: 'Current data identity',
+ unset: 'Not set',
+ user: 'User',
+ },
defaultTitle: 'OpenViking Studio',
},
navigation: {
@@ -22,6 +32,15 @@ const en = {
requestLogs: {
title: 'Request Logs',
},
+ monitoring: {
+ title: 'Monitoring',
+ },
+ skills: {
+ title: 'Skills',
+ },
+ tasks: {
+ title: 'Task Center',
+ },
retrieval: {
title: 'Retrieval',
},
@@ -33,11 +52,174 @@ const en = {
},
},
sidebar: {
+ groups: {
+ operations: 'Activity',
+ resources: 'Resources',
+ settings: 'Settings',
+ workspace: 'Workspace',
+ },
loadingSessions: 'Loading...',
noSessions: 'No sessions',
workspaceGroupLabel: 'OpenViking Studio',
},
},
+ monitoringPage: {
+ title: 'Monitoring',
+ description: 'View real-time health for OpenViking components.',
+ version: 'v{{version}}',
+ refresh: 'Refresh',
+ updatedAt: 'Updated at {{time}}',
+ loading: 'Loading monitoring data...',
+ loadFailed: 'Could not load monitoring data',
+ health: {
+ healthy: 'Healthy',
+ unhealthy: 'Unhealthy',
+ },
+ summary: {
+ healthy: 'All components are healthy',
+ unhealthy: 'Some components need attention',
+ components: '{{healthy}} of {{total}} components healthy',
+ },
+ tabs: {
+ label: 'Monitoring type',
+ overview: 'Overview',
+ queue: 'Task queue',
+ vikingdb: 'VectorDB',
+ models: 'Models',
+ filesystem: 'Filesystem',
+ lock: 'Locks',
+ retrieval: 'Retrieval',
+ },
+ detail: {
+ noData: 'No monitoring data',
+ descriptions: {
+ queue: 'Resource processing, semantic generation, and session queues.',
+ vikingdb: 'Vector storage and indexing service.',
+ models: 'VLM, embedding, and rerank model services.',
+ filesystem: 'OpenViking filesystem and mount services.',
+ lock: 'Transaction locks and concurrency control.',
+ retrieval: 'Context retrieval and recall service.',
+ },
+ },
+ offline: {
+ title: 'OpenViking is not connected',
+ description:
+ 'Configure the server URL and credentials to view monitoring data.',
+ action: 'Open connection settings',
+ },
+ },
+ skillsPage: {
+ title: 'Skills',
+ description:
+ 'View Agent skills available to the current user and workspace.',
+ refresh: 'Refresh',
+ loading: 'Loading skills...',
+ empty: 'No skills available',
+ emptyDescription:
+ 'User and shared skills will appear here after they are added.',
+ loadFailed: 'Could not load skills',
+ networkError:
+ 'Could not connect to the OpenViking service. Check the server URL and connection status.',
+ connectionSettings: 'Open connection settings',
+ detail: 'Details',
+ viewDetail: 'View {{name}} details',
+ detailLoading: 'Loading skill details...',
+ detailLoadFailed: 'Could not load skill details',
+ directory: 'Directory',
+ none: 'None',
+ metrics: {
+ files: 'Files',
+ scope: 'Scope',
+ },
+ sections: {
+ allowedTools: 'Allowed tools',
+ content: 'SKILL.md',
+ description: 'Description',
+ files: 'Files',
+ overview: 'Overview',
+ tags: 'Tags',
+ },
+ scopes: {
+ user: 'User skill',
+ agent: 'Shared skill',
+ },
+ },
+ tasksPage: {
+ title: 'Task Center',
+ description:
+ 'Track background work such as resource processing, session commits, and reindexing.',
+ refresh: 'Refresh',
+ loading: 'Loading tasks...',
+ empty: 'No background tasks',
+ emptyDescription:
+ 'Asynchronous work will appear here with its status and update time.',
+ emptyFiltered: 'No matching tasks',
+ emptyFilteredDescription: 'Adjust or clear the filters to see other tasks.',
+ loadFailed: 'Could not load tasks',
+ detail: {
+ title: 'Task details',
+ loading: 'Loading task details...',
+ loadFailed: 'Could not load task details',
+ retry: 'Retry',
+ openLabel: 'View details for task {{taskId}}',
+ fields: {
+ status: 'Task status',
+ type: 'Task type',
+ stage: 'Current stage',
+ resource: 'Resource',
+ createdAt: 'Created',
+ updatedAt: 'Updated',
+ },
+ error: 'Failure reason',
+ result: 'Result',
+ noResult: 'No result yet',
+ noResultDescription:
+ 'Results returned by the API will appear here when the task completes.',
+ noResultFailedDescription:
+ 'This task did not return a result. See the failure reason above.',
+ },
+ filters: {
+ label: 'Filter',
+ type: 'Task type',
+ status: 'Task status',
+ allTypes: 'All types',
+ allStatuses: 'All statuses',
+ clear: 'Clear filters',
+ },
+ pagination: {
+ next: 'Next',
+ page: 'Page {{page}}',
+ pageSize: 'Rows per page',
+ pageSizeValue: '{{count}} per page',
+ previous: 'Previous',
+ scope:
+ 'Showing the latest {{count}} tasks (the API returns at most {{limit}})',
+ },
+ table: {
+ task: 'Task',
+ type: 'Type',
+ resource: 'Resource',
+ createdAt: 'Created',
+ status: 'Status',
+ },
+ status: {
+ completed: 'Completed',
+ failed: 'Failed',
+ pending: 'Pending',
+ running: 'Running',
+ unknown: 'Unknown',
+ },
+ types: {
+ session_commit: 'Session commit',
+ add_resource: 'Resource processing',
+ add_skill: 'Skill import',
+ connector_import: 'Connector import',
+ admin_reindex: 'Reindex',
+ snapshot_restore_reindex: 'Snapshot reindex',
+ legacy_migration: 'Legacy migration',
+ legacy_cleanup: 'Legacy cleanup',
+ },
+ },
accountSwitcher: {
create: 'Create account',
dialog: {
@@ -152,11 +334,13 @@ const en = {
addUser: 'Add user',
cancel: 'Cancel',
changeRole: 'Change the role for {{user}}',
+ confirmRemoveUser: 'Delete user',
confirmRoleChange: 'Confirm change',
copy: 'Copy',
currentIdentity: 'Current identity',
refresh: 'Refresh',
regenerate: 'Regenerate',
+ removeUser: 'Delete {{user}}',
save: 'Save',
switchIdentity: 'Switch identity',
use: 'Use',
@@ -232,6 +416,11 @@ const en = {
'Regenerate the API key for {{account}} / {{user}}. The current key stops working immediately.',
title: 'Regenerate API key?',
},
+ removeUser: {
+ description:
+ 'Remove {{user}} from {{account}}? Their API key stops working immediately. This action cannot be undone.',
+ title: 'Delete user?',
+ },
},
empty: {
adminDescription:
@@ -283,6 +472,9 @@ const en = {
memberListDescriptionRoot:
'You can change member roles here. "Switch identity" only changes the user used by data pages such as Playground and Retrieval; it does not change the active Root management credential.',
memberListTitle: 'Workspace members',
+ cannotRemoveCurrentIdentity: 'The active identity cannot be deleted.',
+ cannotRemoveLastManager:
+ 'The last workspace administrator cannot be deleted.',
noUsableKey:
'This user has no plaintext API key available for data access.',
openConnection: 'Open connection settings',
@@ -337,6 +529,7 @@ const en = {
keyRegenerated: 'API key regenerated',
roleUpdated: "{{user}}'s role changed to {{role}}",
userCreated: 'User created',
+ userRemoved: '{{user}} deleted',
},
},
home: {
@@ -681,13 +874,22 @@ const en = {
retrieval: {
title: 'Retrieval',
searchPlaceholder: 'Search context',
+ placeholders: {
+ find: 'Enter a semantic query',
+ search: 'Enter a question to interpret with session context',
+ grep: 'Enter a regular expression or exact text',
+ glob: 'Enter a file pattern, for example **/*.md',
+ },
send: 'Search',
controls: {
function: 'Retrieval Function',
modes: {
find: 'find',
search: 'search',
+ grep: 'grep',
+ glob: 'glob',
},
+ ignoreCase: 'Ignore case',
resultCount: 'Results',
path: 'Path',
pathPlaceholder: '/',
@@ -713,6 +915,7 @@ const en = {
results: {
title: 'Search Results',
topN: 'Search Results (Top{{count}})',
+ line: 'Line {{line}}',
},
types: {
resource: 'Resources',
@@ -750,6 +953,21 @@ const en = {
threadList: {
title: 'Sessions',
newSession: 'New Session',
+ count: '{{count}} session',
+ count_other: '{{count}} sessions',
+ loading: 'Loading sessions...',
+ emptyTitle: 'No sessions yet',
+ emptyDescription: 'Select the plus button to start a new conversation.',
+ deleteSession: 'Delete “{{title}}”',
+ deleteConfirmTitle: 'Delete session?',
+ deleteConfirmDescription:
+ '“{{title}}” and its conversation history will be permanently deleted. This action cannot be undone.',
+ cancel: 'Cancel',
+ confirmDelete: 'Delete',
+ deleting: 'Deleting...',
+ deleteSuccess: 'Session deleted',
+ deleteFailed: 'Could not delete session: {{error}}',
+ shortcut: '⌘ N to create a new session',
},
chat: {
copy: 'Copy',
@@ -780,8 +998,27 @@ const en = {
send: 'Send',
cancel: 'Stop',
},
+ impact: {
+ title: 'Memory impact',
+ open: 'View memory changes caused by this session',
+ description: '{{changes}} memory changes across {{commits}} commits',
+ kinds: {
+ add: 'Added',
+ update: 'Updated',
+ delete: 'Deleted',
+ },
+ before: 'Before',
+ after: 'After',
+ addedContent: 'Added content',
+ deletedContent: 'Deleted content',
+ emptyContent: 'No content to display',
+ loading: 'Loading memory changes...',
+ loadFailed: 'Could not load memory changes',
+ retry: 'Retry',
+ empty: 'This session commit did not produce any memory changes.',
+ },
empty: {
- description: 'Select a session from the sidebar or create a new one.',
+ description: 'Select a session from the list or create a new one.',
title: 'No session selected',
},
},
@@ -870,8 +1107,8 @@ const en = {
search: 'Search context',
refresh: 'Refresh tree',
namespaces: {
+ agent: 'Agent capabilities, tools, and experience',
user: 'Personalized user memories',
- session: 'Raw sessions between the user and the Agent',
resources: 'External resources the Agent can reference',
},
},
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index 052a86a7d..25203867b 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -1,12 +1,22 @@
const zhCN = {
appShell: {
footer: {
+ agentIntegrations: 'Agent 接入',
connection: '连接设置',
docs: '文档站',
github: 'GitHub',
+ sdkApi: 'SDK 与 API',
users: '用户管理',
},
header: {
+ currentUser: {
+ account: 'Account',
+ accountSummary: 'Account · {{account}}',
+ openMenu: '查看当前用户 {{user}}',
+ signedInAs: '当前数据访问身份',
+ unset: '未设置',
+ user: 'User',
+ },
defaultTitle: 'OpenViking Studio',
},
navigation: {
@@ -22,6 +32,15 @@ const zhCN = {
requestLogs: {
title: '请求日志',
},
+ monitoring: {
+ title: '监控',
+ },
+ skills: {
+ title: '技能',
+ },
+ tasks: {
+ title: '任务中心',
+ },
retrieval: {
title: '检索',
},
@@ -33,11 +52,165 @@ const zhCN = {
},
},
sidebar: {
+ groups: {
+ operations: '活动',
+ resources: '资源',
+ settings: '设置',
+ workspace: '工作区',
+ },
loadingSessions: '加载中...',
noSessions: '暂无会话',
workspaceGroupLabel: 'OpenViking Studio',
},
},
+ monitoringPage: {
+ title: '监控',
+ description: '查看 OpenViking 各组件的实时健康状态。',
+ version: 'v{{version}}',
+ refresh: '刷新',
+ updatedAt: '更新于 {{time}}',
+ loading: '正在加载监控数据...',
+ loadFailed: '监控数据加载失败',
+ health: {
+ healthy: '正常',
+ unhealthy: '异常',
+ },
+ summary: {
+ healthy: '所有组件运行正常',
+ unhealthy: '部分组件需要关注',
+ components: '{{healthy}} / {{total}} 个组件正常',
+ },
+ tabs: {
+ label: '监控类型',
+ overview: '总览',
+ queue: '任务队列',
+ vikingdb: 'VectorDB',
+ models: '模型',
+ filesystem: '文件系统',
+ lock: '锁',
+ retrieval: '检索',
+ },
+ detail: {
+ noData: '暂无监控数据',
+ descriptions: {
+ queue: '资源处理、语义生成和会话提交队列。',
+ vikingdb: '向量数据存储与索引服务。',
+ models: 'VLM、Embedding 和 Rerank 模型服务。',
+ filesystem: 'OpenViking 文件系统与挂载点。',
+ lock: '事务锁与并发控制服务。',
+ retrieval: '上下文检索与召回服务。',
+ },
+ },
+ offline: {
+ title: '尚未连接 OpenViking 服务',
+ description: '配置服务地址和访问凭证后即可查看监控数据。',
+ action: '打开连接设置',
+ },
+ },
+ skillsPage: {
+ title: '技能',
+ description: '查看当前用户和当前空间可用的 Agent 技能。',
+ refresh: '刷新',
+ loading: '正在加载技能...',
+ empty: '暂无可用技能',
+ emptyDescription: '添加技能后,会在这里按用户技能和共享技能统一展示。',
+ loadFailed: '技能加载失败',
+ networkError: '无法连接 OpenViking 服务,请检查服务地址和连接状态。',
+ connectionSettings: '打开连接设置',
+ detail: '详情',
+ viewDetail: '查看 {{name}} 详情',
+ detailLoading: '正在加载技能详情...',
+ detailLoadFailed: '技能详情加载失败',
+ directory: '目录',
+ none: '无',
+ metrics: {
+ files: '文件',
+ scope: '作用域',
+ },
+ sections: {
+ allowedTools: '允许工具',
+ content: 'SKILL.md',
+ description: '简介',
+ files: '文件',
+ overview: 'Overview',
+ tags: '标签',
+ },
+ scopes: {
+ user: '用户技能',
+ agent: '共享技能',
+ },
+ },
+ tasksPage: {
+ title: '任务中心',
+ description: '集中查看资源处理、会话提交和 Reindex 等后台任务。',
+ refresh: '刷新',
+ loading: '正在加载任务...',
+ empty: '暂无后台任务',
+ emptyDescription: '异步任务启动后,会在这里显示执行状态和更新时间。',
+ emptyFiltered: '没有匹配的任务',
+ emptyFilteredDescription: '可以调整或清除筛选条件后重新查看。',
+ loadFailed: '任务加载失败',
+ detail: {
+ title: '任务详情',
+ loading: '正在加载任务详情...',
+ loadFailed: '任务详情加载失败',
+ retry: '重试',
+ openLabel: '查看任务 {{taskId}} 的详情',
+ fields: {
+ status: '任务状态',
+ type: '任务类型',
+ stage: '当前阶段',
+ resource: '关联资源',
+ createdAt: '创建时间',
+ updatedAt: '更新时间',
+ },
+ error: '失败原因',
+ result: '执行结果',
+ noResult: '暂无执行结果',
+ noResultDescription: '任务完成后,接口返回的结果会显示在这里。',
+ noResultFailedDescription: '该任务未返回结果,请查看上方失败原因。',
+ },
+ filters: {
+ label: '筛选',
+ type: '任务类型',
+ status: '任务状态',
+ allTypes: '全部类型',
+ allStatuses: '全部状态',
+ clear: '清除筛选',
+ },
+ pagination: {
+ next: '下一页',
+ page: '第 {{page}} 页',
+ pageSize: '每页条数',
+ pageSizeValue: '每页 {{count}} 条',
+ previous: '上一页',
+ scope: '当前展示最近 {{count}} 条任务(接口最多返回 {{limit}} 条)',
+ },
+ table: {
+ task: '任务',
+ type: '类型',
+ resource: '关联资源',
+ createdAt: '创建时间',
+ status: '状态',
+ },
+ status: {
+ completed: '已完成',
+ failed: '失败',
+ pending: '等待中',
+ running: '进行中',
+ unknown: '未知',
+ },
+ types: {
+ session_commit: '会话提交',
+ add_resource: '资源处理',
+ add_skill: '技能导入',
+ connector_import: '连接器导入',
+ admin_reindex: 'Reindex',
+ snapshot_restore_reindex: '快照恢复索引',
+ legacy_migration: '旧数据迁移',
+ legacy_cleanup: '旧数据清理',
+ },
+ },
accountSwitcher: {
create: '新建 Account',
dialog: {
@@ -150,11 +323,13 @@ const zhCN = {
addUser: '新增 user',
cancel: '取消',
changeRole: '修改 {{user}} 的角色',
+ confirmRemoveUser: '删除用户',
confirmRoleChange: '确认修改',
copy: '复制',
currentIdentity: '当前身份',
refresh: '刷新',
regenerate: '重新生成',
+ removeUser: '删除 {{user}}',
save: '保存',
switchIdentity: '切换身份',
use: '使用',
@@ -227,6 +402,11 @@ const zhCN = {
'要重新生成 {{account}} / {{user}} 的 API key 吗?当前 key 会立即失效。',
title: '重新生成 API key?',
},
+ removeUser: {
+ description:
+ '确定从 {{account}} 空间移除 {{user}} 吗?该用户的 API Key 会立即失效,此操作不可撤销。',
+ title: '删除用户?',
+ },
},
empty: {
adminDescription:
@@ -277,6 +457,8 @@ const zhCN = {
memberListDescriptionRoot:
'可直接修改成员角色;“切换身份”只会改变 Playground、检索等数据页面的访问身份,不会改变当前 Root 管理凭证。',
memberListTitle: '空间成员',
+ cannotRemoveCurrentIdentity: '不能删除当前正在使用的身份。',
+ cannotRemoveLastManager: '不能删除空间内最后一个管理员。',
noUsableKey: '该用户没有可用于数据访问的明文 API Key。',
openConnection: '打开连接设置',
title: '用户管理',
@@ -330,6 +512,7 @@ const zhCN = {
keyRegenerated: 'API key 已重新生成',
roleUpdated: '{{user}} 的角色已修改为 {{role}}',
userCreated: 'User 已创建',
+ userRemoved: '{{user}} 已删除',
},
},
home: {
@@ -661,13 +844,22 @@ const zhCN = {
retrieval: {
title: '检索',
searchPlaceholder: '输入检索内容',
+ placeholders: {
+ find: '输入语义检索内容',
+ search: '输入需要结合会话理解的问题',
+ grep: '输入正则表达式或精确文本',
+ glob: '输入文件模式,例如 **/*.md',
+ },
send: '检索',
controls: {
function: '检索函数',
modes: {
find: 'find',
search: 'search',
+ grep: 'grep',
+ glob: 'glob',
},
+ ignoreCase: '忽略大小写',
resultCount: '返回数量',
path: '路径',
pathPlaceholder: '/',
@@ -693,6 +885,7 @@ const zhCN = {
results: {
title: '检索结果',
topN: '检索结果(Top{{count}})',
+ line: '第 {{line}} 行',
},
types: {
resource: 'Resources',
@@ -730,6 +923,20 @@ const zhCN = {
threadList: {
title: '会话',
newSession: '新建会话',
+ count: '{{count}} 个会话',
+ loading: '正在加载会话...',
+ emptyTitle: '还没有会话',
+ emptyDescription: '点击右上角的加号开始一段新对话。',
+ deleteSession: '删除“{{title}}”',
+ deleteConfirmTitle: '删除会话?',
+ deleteConfirmDescription:
+ '“{{title}}”及其对话记录将被永久删除,此操作无法撤销。',
+ cancel: '取消',
+ confirmDelete: '删除',
+ deleting: '正在删除...',
+ deleteSuccess: '会话已删除',
+ deleteFailed: '会话删除失败:{{error}}',
+ shortcut: '⌘ N 新建会话',
},
chat: {
copy: '复制',
@@ -757,8 +964,27 @@ const zhCN = {
send: '发送',
cancel: '停止',
},
+ impact: {
+ title: '记忆影响',
+ open: '查看本次会话造成的记忆影响',
+ description: '由 {{commits}} 次提交产生 {{changes}} 项记忆变更',
+ kinds: {
+ add: '新增',
+ update: '更新',
+ delete: '删除',
+ },
+ before: '变更前',
+ after: '变更后',
+ addedContent: '新增内容',
+ deletedContent: '删除内容',
+ emptyContent: '没有可展示的内容',
+ loading: '正在加载记忆变更...',
+ loadFailed: '记忆变更加载失败',
+ retry: '重试',
+ empty: '本次会话提交没有产生记忆变更。',
+ },
empty: {
- description: '从侧边栏选择一个会话,或创建新会话。',
+ description: '从左侧选择一个会话,或创建新会话。',
title: '未选择会话',
},
},
@@ -840,8 +1066,8 @@ const zhCN = {
search: '搜索上下文',
refresh: '刷新目录',
namespaces: {
+ agent: 'Agent 的能力、工具和经验',
user: '用户个性化记忆',
- session: '用户与 Agent 的原始会话',
resources: 'Agent 可引用的外部资源',
},
},
diff --git a/web-studio/src/lib/admin.ts b/web-studio/src/lib/admin.ts
index d2edfecaa..67c645883 100644
--- a/web-studio/src/lib/admin.ts
+++ b/web-studio/src/lib/admin.ts
@@ -2,6 +2,7 @@ import axios from 'axios'
import { createClient } from '#/gen/ov-client/client'
import {
+ deleteAdminAccountIdUserByUserId,
getAdminAccountIdUsers,
getAdminAccounts,
getOvResult,
@@ -420,6 +421,22 @@ export async function regenerateAdminUserKey(
})
}
+export async function removeAdminUser(
+ connection: AdminConnection,
+ accountId: string,
+ userId: string,
+): Promise<void> {
+ await getOvResult<unknown>(
+ deleteAdminAccountIdUserByUserId({
+ client: createAdminClient(connection),
+ path: {
+ account_id: accountId,
+ user_id: userId,
+ },
+ }),
+ )
+}
+
export async function updateAdminUserRole(
connection: AdminConnection,
input: UpdateUserRoleInput,
diff --git a/web-studio/src/lib/retrieval.test.ts b/web-studio/src/lib/retrieval.test.ts
new file mode 100644
index 000000000..8002e4e32
--- /dev/null
+++ b/web-studio/src/lib/retrieval.test.ts
@@ -0,0 +1,139 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { fetchFindAllTypes, fetchGlob, fetchGrep } from './retrieval'
+
+const { postSearchFindMock, postSearchGlobMock, postSearchGrepMock } =
+ vi.hoisted(() => ({
+ postSearchFindMock: vi.fn(),
+ postSearchGlobMock: vi.fn(),
+ postSearchGrepMock: vi.fn(),
+ }))
+
+vi.mock('#/lib/ov-client', () => ({
+ getOvResult: async (request: Promise<unknown>) => {
+ const rawResponse = (await request) as {
+ data: { result: unknown }
+ }
+ return rawResponse.data.result
+ },
+ normalizeOvClientError: (error: unknown) => error,
+ postSearchFind: postSearchFindMock,
+ postSearchGlob: postSearchGlobMock,
+ postSearchGrep: postSearchGrepMock,
+ postSearchSearch: vi.fn(),
+}))
+
+function response(result: unknown) {
+ return Promise.resolve({
+ data: { result, status: 'ok' },
+ headers: {},
+ status: 200,
+ })
+}
+
+describe('pattern retrieval', () => {
+ beforeEach(() => {
+ postSearchFindMock.mockReset()
+ postSearchGlobMock.mockReset()
+ postSearchGrepMock.mockReset()
+ })
+
+ it('uses one find request for the server-grouped result types', async () => {
+ postSearchFindMock.mockReturnValue(
+ response({
+ memories: [{ uri: 'viking://user/default/memories/profile.md' }],
+ resources: [{ uri: 'viking://resources/guide.md' }],
+ skills: [{ uri: 'viking://user/default/skills/reviewer' }],
+ total: 3,
+ }),
+ )
+
+ const result = await fetchFindAllTypes('OpenViking', { limit: 10 })
+
+ expect(postSearchFindMock).toHaveBeenCalledTimes(1)
+ expect(postSearchFindMock).toHaveBeenCalledWith({
+ body: {
+ filter: undefined,
+ limit: 10,
+ query: 'OpenViking',
+ score_threshold: undefined,
+ target_uri: undefined,
+ },
+ })
+ expect(result).toMatchObject({
+ total: 3,
+ memories: [{ context_type: 'memory' }],
+ resources: [{ context_type: 'resource' }],
+ skills: [{ context_type: 'skill' }],
+ })
+ })
+
+ it('maps grep line matches into retrieval result rows', async () => {
+ postSearchGrepMock.mockReturnValue(
+ response({
+ count: 1,
+ matches: [
+ {
+ content: 'OpenViking authentication',
+ line: 15,
+ uri: 'viking://resources/docs/auth.md',
+ },
+ ],
+ }),
+ )
+
+ const result = await fetchGrep('authentication', {
+ caseInsensitive: true,
+ limit: 20,
+ uri: 'viking://resources/',
+ })
+
+ expect(postSearchGrepMock).toHaveBeenCalledWith({
+ body: {
+ case_insensitive: true,
+ node_limit: 20,
+ pattern: 'authentication',
+ uri: 'viking://resources/',
+ },
+ })
+ expect(result.resources[0]).toMatchObject({
+ abstract: 'OpenViking authentication',
+ line: 15,
+ result_kind: 'grep',
+ uri: 'viking://resources/docs/auth.md',
+ })
+ expect(result.total).toBe(1)
+ })
+
+ it('maps glob URI matches into retrieval result rows', async () => {
+ postSearchGlobMock.mockReturnValue(
+ response({
+ count: 2,
+ matches: [
+ 'viking://resources/docs/api.md',
+ 'viking://resources/docs/guide.md',
+ ],
+ }),
+ )
+
+ const result = await fetchGlob('**/*.md', {
+ limit: 50,
+ uri: 'viking://',
+ })
+
+ expect(postSearchGlobMock).toHaveBeenCalledWith({
+ body: {
+ node_limit: 50,
+ pattern: '**/*.md',
+ uri: 'viking://',
+ },
+ })
+ expect(
+ result.resources.map(({ result_kind, uri }) => [result_kind, uri]),
+ ).toEqual([
+ ['glob', 'viking://resources/docs/api.md'],
+ ['glob', 'viking://resources/docs/guide.md'],
+ ])
+ expect(result.total).toBe(2)
+ })
+})
diff --git a/web-studio/src/lib/retrieval.ts b/web-studio/src/lib/retrieval.ts
index 48beea7ab..677051ebb 100644
--- a/web-studio/src/lib/retrieval.ts
+++ b/web-studio/src/lib/retrieval.ts
@@ -2,6 +2,8 @@ import {
getOvResult,
normalizeOvClientError,
postSearchFind,
+ postSearchGlob,
+ postSearchGrep,
postSearchSearch,
} from '#/lib/ov-client'
import type { FindContextType, SearchResult } from '@ov-server/api/v1/search'
@@ -18,6 +20,8 @@ export interface FindResultItem {
category: string
match_reason: string
relations: Array<{ uri: string; abstract: string }>
+ result_kind?: 'semantic' | 'grep' | 'glob'
+ line?: number
}
export interface FindQueryPlanItem {
@@ -59,6 +63,17 @@ export interface FetchSearchOptions extends FetchFindOptions {
sessionId?: string
}
+export interface FetchGrepOptions {
+ caseInsensitive?: boolean
+ limit?: number
+ uri: string
+}
+
+export interface FetchGlobOptions {
+ limit?: number
+ uri?: string
+}
+
const FIND_CONTEXT_TYPES = ['resource', 'memory', 'skill'] as const
function toVikingApiError(error: unknown): VikingApiError {
@@ -222,35 +237,115 @@ export async function fetchSearch(
}
}
-export async function fetchFindAllTypes(
+/**
+ * Fetch all context types in one request.
+ *
+ * The server already groups resources, memories, and skills in its response,
+ * so issuing one request per type only duplicates work and can exceed the
+ * requested global limit.
+ */
+export function fetchFindAllTypes(
query: string,
options: Omit<FetchFindOptions, 'targetUri' | 'filter'> = {},
): Promise<GroupedFindResult> {
- const results = await Promise.allSettled(
- FIND_CONTEXT_TYPES.map((ct) =>
- fetchFind(query, {
- ...options,
- filter: { op: 'must', field: 'context_type', conds: [ct] },
- }),
- ),
- )
+ return fetchFind(query, options)
+}
- const merged: GroupedFindResult = {
+function emptyPatternResult(resources: FindResultItem[]): GroupedFindResult {
+ return {
memories: [],
- resources: [],
+ resources,
skills: [],
- total: 0,
+ total: resources.length,
}
+}
- const [resourceResult, memoryResult, skillResult] = results
- if (resourceResult.status === 'fulfilled')
- merged.resources = resourceResult.value.resources
- if (memoryResult.status === 'fulfilled')
- merged.memories = memoryResult.value.memories
- if (skillResult.status === 'fulfilled')
- merged.skills = skillResult.value.skills
+function patternResultItem(
+ uri: string,
+ kind: 'grep' | 'glob',
+ options: { content?: string; line?: number } = {},
+): FindResultItem {
+ return {
+ abstract: options.content ?? '',
+ category: '',
+ context_type: 'resource',
+ level: 2,
+ line: options.line,
+ match_reason: '',
+ relations: [],
+ result_kind: kind,
+ score: 0,
+ uri,
+ }
+}
- merged.total =
- merged.memories.length + merged.resources.length + merged.skills.length
- return merged
+export async function fetchGrep(
+ pattern: string,
+ options: FetchGrepOptions,
+): Promise<GroupedFindResult> {
+ try {
+ const result = await getOvResult<unknown>(
+ postSearchGrep({
+ body: {
+ case_insensitive: options.caseInsensitive,
+ node_limit: options.limit ?? 10,
+ pattern,
+ uri: options.uri,
+ },
+ }),
+ )
+ const matches =
+ result && typeof result === 'object' && 'matches' in result
+ ? (result as { matches?: unknown }).matches
+ : undefined
+ const resources = Array.isArray(matches)
+ ? matches
+ .filter(
+ (match): match is Record<string, unknown> =>
+ match !== null &&
+ typeof match === 'object' &&
+ !Array.isArray(match) &&
+ typeof match.uri === 'string',
+ )
+ .map((match) =>
+ patternResultItem(match.uri as string, 'grep', {
+ content:
+ typeof match.content === 'string' ? match.content : undefined,
+ line: typeof match.line === 'number' ? match.line : undefined,
+ }),
+ )
+ : []
+ return emptyPatternResult(resources)
+ } catch (error) {
+ throw toVikingApiError(error)
+ }
+}
+
+export async function fetchGlob(
+ pattern: string,
+ options: FetchGlobOptions = {},
+): Promise<GroupedFindResult> {
+ try {
+ const result = await getOvResult<unknown>(
+ postSearchGlob({
+ body: {
+ node_limit: options.limit ?? 10,
+ pattern,
+ uri: options.uri ?? 'viking://',
+ },
+ }),
+ )
+ const matches =
+ result && typeof result === 'object' && 'matches' in result
+ ? (result as { matches?: unknown }).matches
+ : undefined
+ const resources = Array.isArray(matches)
+ ? matches
+ .filter((uri): uri is string => typeof uri === 'string')
+ .map((uri) => patternResultItem(uri, 'glob'))
+ : []
+ return emptyPatternResult(resources)
+ } catch (error) {
+ throw toVikingApiError(error)
+ }
}
diff --git a/web-studio/src/lib/sessions/api.test.ts b/web-studio/src/lib/sessions/api.test.ts
new file mode 100644
index 000000000..7f634e3a6
--- /dev/null
+++ b/web-studio/src/lib/sessions/api.test.ts
@@ -0,0 +1,123 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { OvClientError } from '#/lib/ov-client'
+
+import { fetchSessionMessages } from './api'
+
+const {
+ getSessionBySessionIdMock,
+ getSessionIdArchiveByArchiveIdMock,
+ getSessionIdContextMock,
+} = vi.hoisted(() => ({
+ getSessionBySessionIdMock: vi.fn(),
+ getSessionIdArchiveByArchiveIdMock: vi.fn(),
+ getSessionIdContextMock: vi.fn(),
+}))
+
+vi.mock('#/gen/ov-client/sdk.gen', () => ({
+ deleteSessionBySessionId: vi.fn(),
+ getSessionBySessionId: getSessionBySessionIdMock,
+ getSessionIdArchiveByArchiveId: getSessionIdArchiveByArchiveIdMock,
+ getSessionIdContext: getSessionIdContextMock,
+ getSessions: vi.fn(),
+ postBotV1Chat: vi.fn(),
+ postSessions: vi.fn(),
+ postSessionIdCommit: vi.fn(),
+ postSessionIdExtract: vi.fn(),
+ postSessionIdMessages: vi.fn(),
+ postSessionIdUsed: vi.fn(),
+}))
+
+function response(result: unknown) {
+ return Promise.resolve({
+ data: { result, status: 'ok' },
+ headers: {},
+ status: 200,
+ })
+}
+
+function message(id: string, text: string) {
+ return {
+ created_at: '2026-07-24T08:00:00Z',
+ id,
+ parts: [{ text, type: 'text' }],
+ role: 'user',
+ }
+}
+
+describe('fetchSessionMessages', () => {
+ beforeEach(() => {
+ getSessionBySessionIdMock.mockReset()
+ getSessionIdArchiveByArchiveIdMock.mockReset()
+ getSessionIdContextMock.mockReset()
+ })
+
+ it('combines completed archives with current context in chronological order', async () => {
+ getSessionBySessionIdMock.mockReturnValue(response({ commit_count: 2 }))
+ getSessionIdArchiveByArchiveIdMock
+ .mockReturnValueOnce(
+ response({
+ archive_id: 'archive_001',
+ messages: [message('1', 'one')],
+ }),
+ )
+ .mockReturnValueOnce(
+ response({
+ archive_id: 'archive_002',
+ messages: [message('2', 'two')],
+ }),
+ )
+ getSessionIdContextMock.mockReturnValue(
+ response({ messages: [message('3', 'three')] }),
+ )
+
+ const result = await fetchSessionMessages('session-1')
+
+ expect(result.map(({ id }) => id)).toEqual(['1', '2', '3'])
+ expect(getSessionIdArchiveByArchiveIdMock).toHaveBeenNthCalledWith(1, {
+ path: { archive_id: 'archive_001', session_id: 'session-1' },
+ })
+ expect(getSessionIdArchiveByArchiveIdMock).toHaveBeenNthCalledWith(2, {
+ path: { archive_id: 'archive_002', session_id: 'session-1' },
+ })
+ })
+
+ it('keeps readable history when an unfinished archive is unavailable', async () => {
+ getSessionBySessionIdMock.mockReturnValue(response({ commit_count: 2 }))
+ getSessionIdArchiveByArchiveIdMock
+ .mockRejectedValueOnce(
+ new OvClientError({
+ code: 'NOT_FOUND',
+ message: 'archive not found',
+ statusCode: 404,
+ }),
+ )
+ .mockReturnValueOnce(
+ response({
+ archive_id: 'archive_002',
+ messages: [message('2', 'two')],
+ }),
+ )
+ getSessionIdContextMock.mockReturnValue(
+ response({ messages: [message('3', 'three')] }),
+ )
+
+ const result = await fetchSessionMessages('session-1')
+
+ expect(result.map(({ id }) => id)).toEqual(['2', '3'])
+ })
+
+ it('propagates archive failures that are not missing archives', async () => {
+ getSessionBySessionIdMock.mockReturnValue(response({ commit_count: 1 }))
+ getSessionIdArchiveByArchiveIdMock.mockRejectedValueOnce(
+ new Error('connection reset'),
+ )
+ getSessionIdContextMock.mockReturnValue(
+ response({ messages: [message('1', 'one')] }),
+ )
+
+ await expect(fetchSessionMessages('session-1')).rejects.toThrow(
+ 'connection reset',
+ )
+ })
+})
diff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.ts
index 7d38bf95a..b84cbae79 100644
--- a/web-studio/src/lib/sessions/api.ts
+++ b/web-studio/src/lib/sessions/api.ts
@@ -1,5 +1,6 @@
import {
deleteSessionBySessionId,
+ getContentRead,
getSessionIdArchiveByArchiveId,
getSessions,
getSessionBySessionId,
@@ -18,13 +19,16 @@ import {
ovClient,
} from '#/lib/ov-client'
+import { parseSessionMemoryDiff } from './memory-diff'
import type { BotChatRequest, BotChatResponse } from '@ov-server/bot/v1/chat'
+import type { SessionMemoryDiff } from './memory-diff'
import type { Message, MessagePart } from './types/message'
import type {
AddMessageResult,
CommitSessionResult,
CreateSessionResult,
DeleteSessionResult,
+ SessionArchiveResult,
SessionContextResult,
SessionListItem,
SessionMeta,
@@ -74,8 +78,8 @@ export async function fetchSessionContext(
export async function fetchSessionArchive(
sessionId: string,
archiveId: string,
-): Promise<unknown> {
- return getOvResult<unknown>(
+): Promise<SessionArchiveResult> {
+ return getOvResult<SessionArchiveResult>(
getSessionIdArchiveByArchiveId({
path: { archive_id: archiveId, session_id: sessionId },
}),
@@ -96,26 +100,150 @@ export async function deleteSession(
// Session Messages
// ---------------------------------------------------------------------------
-/** Fetch message history for a session via the /context endpoint. */
+function isMessage(value: unknown): value is Message {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'id' in value &&
+ 'role' in value &&
+ 'parts' in value
+ )
+}
+
+function getMessages(value: unknown): Message[] {
+ return Array.isArray(value) ? value.filter(isMessage) : []
+}
+
+function deduplicateMessages(messages: Message[]): Message[] {
+ const seen = new Set<string>()
+ return messages.filter((message) => {
+ if (seen.has(message.id)) return false
+ seen.add(message.id)
+ return true
+ })
+}
+
+const SESSION_ARCHIVE_CONCURRENCY = 4
+
+async function mapWithConcurrency<T, TResult>(
+ items: T[],
+ concurrency: number,
+ mapper: (item: T, index: number) => Promise<TResult>,
+): Promise<TResult[]> {
+ const results = new Array<TResult>(items.length)
+ let nextIndex = 0
+
+ async function worker() {
+ while (nextIndex < items.length) {
+ const index = nextIndex
+ nextIndex += 1
+ results[index] = await mapper(items[index], index)
+ }
+ }
+
+ await Promise.all(
+ Array.from({ length: Math.min(concurrency, items.length) }, () => worker()),
+ )
+ return results
+}
+
+function isMissingArchive(error: unknown): boolean {
+ const normalized = normalizeOvClientError(error)
+ return normalized.statusCode === 404 || normalized.code === 'NOT_FOUND'
+}
+
+/**
+ * Fetch the complete message history.
+ *
+ * `/context` only contains messages after the latest completed archive, so
+ * archived messages must be loaded separately and prepended in archive order.
+ */
export async function fetchSessionMessages(
sessionId: string,
+ sessionMeta?: SessionMeta,
): Promise<Message[]> {
- const result = await getOvResult<SessionContextResult>(
+ const context = await getOvResult<SessionContextResult>(
getSessionIdContext({
path: { session_id: sessionId },
}),
)
- const raw = result.messages
- if (!Array.isArray(raw)) return []
- // Each item is Message.to_dict() — { id, role, parts, created_at }
- return raw.filter(
- (m): m is Message =>
- typeof m === 'object' &&
- m !== null &&
- 'id' in m &&
- 'role' in m &&
- 'parts' in m,
+
+ let commitCount = 0
+ try {
+ const session = sessionMeta ?? (await fetchSession(sessionId))
+ commitCount = Math.max(0, Math.floor(session.commit_count || 0))
+ } catch {
+ // Older servers may not expose session details. Current context is still
+ // useful, so preserve the previous behavior as a fallback.
+ }
+
+ const archiveIds = Array.from(
+ { length: commitCount },
+ (_, index) => `archive_${String(index + 1).padStart(3, '0')}`,
+ )
+ const archives = await mapWithConcurrency(
+ archiveIds,
+ SESSION_ARCHIVE_CONCURRENCY,
+ async (archiveId) => {
+ try {
+ return await fetchSessionArchive(sessionId, archiveId)
+ } catch (error) {
+ if (isMissingArchive(error)) return null
+ throw error
+ }
+ },
+ )
+ const archivedMessages = archives.flatMap((archive) =>
+ archive ? getMessages(archive.messages) : [],
+ )
+
+ return deduplicateMessages([
+ ...archivedMessages,
+ ...getMessages(context.messages),
+ ])
+}
+
+export async function fetchSessionMemoryDiffs(
+ session: SessionMeta,
+): Promise<SessionMemoryDiff[]> {
+ const commitCount = Math.max(0, Math.floor(session.commit_count || 0))
+ if (commitCount === 0) return []
+
+ const sessionUri =
+ session.uri?.replace(/\/+$/, '') ||
+ `viking://user/${session.user.user_id}/sessions/${session.session_id}`
+ const archiveIds = Array.from(
+ { length: commitCount },
+ (_, index) => `archive_${String(index + 1).padStart(3, '0')}`,
)
+ const results = await mapWithConcurrency(
+ archiveIds,
+ SESSION_ARCHIVE_CONCURRENCY,
+ async (archiveId) => {
+ try {
+ const result = await getOvResult<unknown>(
+ getContentRead({
+ query: {
+ limit: -1,
+ offset: 0,
+ raw: true,
+ uri: `${sessionUri}/history/${archiveId}/memory_diff.json`,
+ } as Parameters<typeof getContentRead>[0]['query'] & {
+ raw?: boolean
+ },
+ }),
+ )
+ return parseSessionMemoryDiff(result, archiveId)
+ } catch (error) {
+ if (isMissingArchive(error)) return null
+ throw error
+ }
+ },
+ )
+
+ return results
+ .flatMap((result) => (result ? [result] : []))
+ .sort((left, right) => right.archiveId.localeCompare(left.archiveId))
}
export async function addMessage(
diff --git a/web-studio/src/lib/sessions/memory-diff.test.ts b/web-studio/src/lib/sessions/memory-diff.test.ts
new file mode 100644
index 000000000..99b97ca3c
--- /dev/null
+++ b/web-studio/src/lib/sessions/memory-diff.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest'
+
+import { parseSessionMemoryDiff } from './memory-diff'
+
+describe('parseSessionMemoryDiff', () => {
+ it('normalizes real memory operations and derives the summary from them', () => {
+ expect(
+ parseSessionMemoryDiff(
+ JSON.stringify({
+ archive_uri:
+ 'viking://user/alice/sessions/session-1/history/archive_002',
+ extracted_at: '2026-07-24T08:00:00Z',
+ operations: {
+ adds: [
+ {
+ after: 'new preference',
+ memory_type: 'preferences',
+ uri: 'viking://user/alice/memories/preferences/editor.md',
+ },
+ ],
+ updates: [
+ {
+ after: 'new profile',
+ before: 'old profile',
+ memory_type: 'profile',
+ uri: 'viking://user/alice/memories/profile.md',
+ },
+ ],
+ deletes: [],
+ },
+ summary: {
+ total_adds: 99,
+ total_deletes: 99,
+ total_updates: 99,
+ },
+ }),
+ 'archive_002',
+ ),
+ ).toMatchObject({
+ archiveId: 'archive_002',
+ extractedAt: '2026-07-24T08:00:00Z',
+ summary: { adds: 1, deletes: 0, updates: 1 },
+ })
+ })
+
+ it('returns null for an empty or invalid diff', () => {
+ expect(
+ parseSessionMemoryDiff(
+ {
+ operations: { adds: [], deletes: [], updates: [] },
+ },
+ 'archive_001',
+ ),
+ ).toBeNull()
+ expect(parseSessionMemoryDiff('not-json', 'archive_001')).toBeNull()
+ })
+})
diff --git a/web-studio/src/lib/sessions/memory-diff.ts b/web-studio/src/lib/sessions/memory-diff.ts
new file mode 100644
index 000000000..88ab07197
--- /dev/null
+++ b/web-studio/src/lib/sessions/memory-diff.ts
@@ -0,0 +1,94 @@
+export type MemoryDiffKind = 'add' | 'delete' | 'update'
+
+export type SessionMemoryDiffOperation = {
+ after?: string
+ before?: string
+ kind: MemoryDiffKind
+ memoryType: string
+ uri: string
+}
+
+export type SessionMemoryDiff = {
+ archiveId: string
+ archiveUri: string
+ extractedAt: string
+ operations: SessionMemoryDiffOperation[]
+ summary: {
+ adds: number
+ deletes: number
+ updates: number
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function readString(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function parseOperation(
+ value: unknown,
+ kind: MemoryDiffKind,
+): SessionMemoryDiffOperation | null {
+ if (!isRecord(value)) return null
+ const uri = readString(value.uri)
+ if (!uri) return null
+
+ return {
+ after:
+ kind === 'delete'
+ ? readString(value.deleted_content)
+ : readString(value.after),
+ before: kind === 'update' ? readString(value.before) : undefined,
+ kind,
+ memoryType: readString(value.memory_type) || 'unknown',
+ uri,
+ }
+}
+
+function parseOperationList(
+ value: unknown,
+ kind: MemoryDiffKind,
+): SessionMemoryDiffOperation[] {
+ if (!Array.isArray(value)) return []
+ return value.flatMap((item) => {
+ const operation = parseOperation(item, kind)
+ return operation ? [operation] : []
+ })
+}
+
+export function parseSessionMemoryDiff(
+ value: unknown,
+ archiveId: string,
+): SessionMemoryDiff | null {
+ let parsed = value
+ if (typeof value === 'string') {
+ try {
+ parsed = JSON.parse(value) as unknown
+ } catch {
+ return null
+ }
+ }
+ if (!isRecord(parsed)) return null
+
+ const rawOperations = isRecord(parsed.operations) ? parsed.operations : {}
+ const adds = parseOperationList(rawOperations.adds, 'add')
+ const updates = parseOperationList(rawOperations.updates, 'update')
+ const deletes = parseOperationList(rawOperations.deletes, 'delete')
+ const operations = [...adds, ...updates, ...deletes]
+ if (operations.length === 0) return null
+
+ return {
+ archiveId,
+ archiveUri: readString(parsed.archive_uri),
+ extractedAt: readString(parsed.extracted_at),
+ operations,
+ summary: {
+ adds: adds.length,
+ deletes: deletes.length,
+ updates: updates.length,
+ },
+ }
+}
diff --git a/web-studio/src/lib/sessions/use-sessions.ts b/web-studio/src/lib/sessions/use-sessions.ts
index bcbf1b309..fe15e0945 100644
--- a/web-studio/src/lib/sessions/use-sessions.ts
+++ b/web-studio/src/lib/sessions/use-sessions.ts
@@ -5,11 +5,13 @@ import {
deleteSession,
fetchBotHealth,
fetchSession,
+ fetchSessionMemoryDiffs,
fetchSessionMessages,
fetchSessions,
} from './api'
import type { Message } from './types/message'
-import type { SessionListItem } from '@ov-server/api/v1/sessions'
+import type { SessionMemoryDiff } from './memory-diff'
+import type { SessionListItem, SessionMeta } from '@ov-server/api/v1/sessions'
const SESSIONS_KEY = ['sessions'] as const
const BOT_HEALTH_KEY = ['bot', 'health'] as const
@@ -68,14 +70,41 @@ export function useSession(sessionId: string | undefined) {
/** Fetch message history for a session. */
export function useSessionMessages(sessionId: string | undefined) {
+ const queryClient = useQueryClient()
+
return useQuery<Message[]>({
queryKey: [...SESSIONS_KEY, sessionId, 'messages'],
- queryFn: () => fetchSessionMessages(sessionId!),
+ queryFn: async () => {
+ const session = await queryClient.fetchQuery({
+ queryFn: () => fetchSession(sessionId!),
+ queryKey: [...SESSIONS_KEY, sessionId],
+ staleTime: 15_000,
+ })
+ return fetchSessionMessages(sessionId!, session)
+ },
enabled: Boolean(sessionId),
staleTime: 30_000, // cache for 30s to avoid flash on session switch
})
}
+export function useSessionMemoryDiffs(
+ session: SessionMeta | undefined,
+ enabled = true,
+) {
+ return useQuery<SessionMemoryDiff[]>({
+ queryKey: [
+ ...SESSIONS_KEY,
+ session?.session_id,
+ 'memory-diffs',
+ session?.commit_count,
+ session?.last_commit_at,
+ ],
+ queryFn: () => fetchSessionMemoryDiffs(session!),
+ enabled: Boolean(enabled && session && session.commit_count > 0),
+ staleTime: 30_000,
+ })
+}
+
export function useCreateSession() {
const queryClient = useQueryClient()
diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.ts
index 62b41adea..d9e68fc49 100644
--- a/web-studio/src/routeTree.gen.ts
+++ b/web-studio/src/routeTree.gen.ts
@@ -10,11 +10,14 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as UsersRouteRouteImport } from './routes/users/route'
+import { Route as TasksRouteRouteImport } from './routes/tasks/route'
+import { Route as SkillsRouteRouteImport } from './routes/skills/route'
import { Route as SettingsRouteRouteImport } from './routes/settings/route'
import { Route as SessionsRouteRouteImport } from './routes/sessions/route'
import { Route as RetrievalRouteRouteImport } from './routes/retrieval/route'
import { Route as RequestLogsRouteRouteImport } from './routes/request-logs/route'
import { Route as PlaygroundRouteRouteImport } from './routes/playground/route'
+import { Route as MonitoringRouteRouteImport } from './routes/monitoring/route'
import { Route as HomeRouteRouteImport } from './routes/home/route'
import { Route as IndexRouteImport } from './routes/index'
import { Route as SessionsIndexRouteImport } from './routes/sessions/index'
@@ -26,6 +29,16 @@ const UsersRouteRoute = UsersRouteRouteImport.update({
path: '/users',
getParentRoute: () => rootRouteImport,
} as any)
+const TasksRouteRoute = TasksRouteRouteImport.update({
+ id: '/tasks',
+ path: '/tasks',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const SkillsRouteRoute = SkillsRouteRouteImport.update({
+ id: '/skills',
+ path: '/skills',
+ getParentRoute: () => rootRouteImport,
+} as any)
const SettingsRouteRoute = SettingsRouteRouteImport.update({
id: '/settings',
path: '/settings',
@@ -51,6 +64,11 @@ const PlaygroundRouteRoute = PlaygroundRouteRouteImport.update({
path: '/playground',
getParentRoute: () => rootRouteImport,
} as any)
+const MonitoringRouteRoute = MonitoringRouteRouteImport.update({
+ id: '/monitoring',
+ path: '/monitoring',
+ getParentRoute: () => rootRouteImport,
+} as any)
const HomeRouteRoute = HomeRouteRouteImport.update({
id: '/home',
path: '/home',
@@ -80,11 +98,14 @@ const OauthConsentRoute = OauthConsentRouteImport.update({
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/home': typeof HomeRouteRoute
+ '/monitoring': typeof MonitoringRouteRoute
'/playground': typeof PlaygroundRouteRoute
'/request-logs': typeof RequestLogsRouteRoute
'/retrieval': typeof RetrievalRouteRoute
'/sessions': typeof SessionsRouteRouteWithChildren
'/settings': typeof SettingsRouteRoute
+ '/skills': typeof SkillsRouteRoute
+ '/tasks': typeof TasksRouteRoute
'/users': typeof UsersRouteRoute
'/oauth/consent': typeof OauthConsentRoute
'/oauth/verify': typeof OauthVerifyRoute
@@ -93,10 +114,13 @@ export interface FileRoutesByFullPath {
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/home': typeof HomeRouteRoute
+ '/monitoring': typeof MonitoringRouteRoute
'/playground': typeof PlaygroundRouteRoute
'/request-logs': typeof RequestLogsRouteRoute
'/retrieval': typeof RetrievalRouteRoute
'/settings': typeof SettingsRouteRoute
+ '/skills': typeof SkillsRouteRoute
+ '/tasks': typeof TasksRouteRoute
'/users': typeof UsersRouteRoute
'/oauth/consent': typeof OauthConsentRoute
'/oauth/verify': typeof OauthVerifyRoute
@@ -106,11 +130,14 @@ export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
'/home': typeof HomeRouteRoute
+ '/monitoring': typeof MonitoringRouteRoute
'/playground': typeof PlaygroundRouteRoute
'/request-logs': typeof RequestLogsRouteRoute
'/retrieval': typeof RetrievalRouteRoute
'/sessions': typeof SessionsRouteRouteWithChildren
'/settings': typeof SettingsRouteRoute
+ '/skills': typeof SkillsRouteRoute
+ '/tasks': typeof TasksRouteRoute
'/users': typeof UsersRouteRoute
'/oauth/consent': typeof OauthConsentRoute
'/oauth/verify': typeof OauthVerifyRoute
@@ -121,11 +148,14 @@ export interface FileRouteTypes {
fullPaths:
| '/'
| '/home'
+ | '/monitoring'
| '/playground'
| '/request-logs'
| '/retrieval'
| '/sessions'
| '/settings'
+ | '/skills'
+ | '/tasks'
| '/users'
| '/oauth/consent'
| '/oauth/verify'
@@ -134,10 +164,13 @@ export interface FileRouteTypes {
to:
| '/'
| '/home'
+ | '/monitoring'
| '/playground'
| '/request-logs'
| '/retrieval'
| '/settings'
+ | '/skills'
+ | '/tasks'
| '/users'
| '/oauth/consent'
| '/oauth/verify'
@@ -146,11 +179,14 @@ export interface FileRouteTypes {
| '__root__'
| '/'
| '/home'
+ | '/monitoring'
| '/playground'
| '/request-logs'
| '/retrieval'
| '/sessions'
| '/settings'
+ | '/skills'
+ | '/tasks'
| '/users'
| '/oauth/consent'
| '/oauth/verify'
@@ -160,11 +196,14 @@ export interface FileRouteTypes {
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
HomeRouteRoute: typeof HomeRouteRoute
+ MonitoringRouteRoute: typeof MonitoringRouteRoute
PlaygroundRouteRoute: typeof PlaygroundRouteRoute
RequestLogsRouteRoute: typeof RequestLogsRouteRoute
RetrievalRouteRoute: typeof RetrievalRouteRoute
SessionsRouteRoute: typeof SessionsRouteRouteWithChildren
SettingsRouteRoute: typeof SettingsRouteRoute
+ SkillsRouteRoute: typeof SkillsRouteRoute
+ TasksRouteRoute: typeof TasksRouteRoute
UsersRouteRoute: typeof UsersRouteRoute
OauthConsentRoute: typeof OauthConsentRoute
OauthVerifyRoute: typeof OauthVerifyRoute
@@ -179,6 +218,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof UsersRouteRouteImport
parentRoute: typeof rootRouteImport
}
+ '/tasks': {
+ id: '/tasks'
+ path: '/tasks'
+ fullPath: '/tasks'
+ preLoaderRoute: typeof TasksRouteRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/skills': {
+ id: '/skills'
+ path: '/skills'
+ fullPath: '/skills'
+ preLoaderRoute: typeof SkillsRouteRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/settings': {
id: '/settings'
path: '/settings'
@@ -214,6 +267,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof PlaygroundRouteRouteImport
parentRoute: typeof rootRouteImport
}
+ '/monitoring': {
+ id: '/monitoring'
+ path: '/monitoring'
+ fullPath: '/monitoring'
+ preLoaderRoute: typeof MonitoringRouteRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/home': {
id: '/home'
path: '/home'
@@ -267,11 +327,14 @@ const SessionsRouteRouteWithChildren = SessionsRouteRoute._addFileChildren(
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
HomeRouteRoute: HomeRouteRoute,
+ MonitoringRouteRoute: MonitoringRouteRoute,
PlaygroundRouteRoute: PlaygroundRouteRoute,
RequestLogsRouteRoute: RequestLogsRouteRoute,
RetrievalRouteRoute: RetrievalRouteRoute,
SessionsRouteRoute: SessionsRouteRouteWithChildren,
SettingsRouteRoute: SettingsRouteRoute,
+ SkillsRouteRoute: SkillsRouteRoute,
+ TasksRouteRoute: TasksRouteRoute,
UsersRouteRoute: UsersRouteRoute,
OauthConsentRoute: OauthConsentRoute,
OauthVerifyRoute: OauthVerifyRoute,
diff --git a/web-studio/src/routes/monitoring/-lib/parse-status.test.ts b/web-studio/src/routes/monitoring/-lib/parse-status.test.ts
new file mode 100644
index 000000000..02d284c2c
--- /dev/null
+++ b/web-studio/src/routes/monitoring/-lib/parse-status.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest'
+
+import { parseObserverStatus } from './parse-status'
+
+describe('parseObserverStatus', () => {
+ it('converts an ASCII table into structured rows', () => {
+ expect(
+ parseObserverStatus(`
++-------+---------+
+| Queue | Pending |
++-------+---------+
+| Embed | 2 |
++-------+---------+
+`),
+ ).toEqual([
+ {
+ headers: ['Queue', 'Pending'],
+ kind: 'table',
+ rows: [['Embed', '2']],
+ },
+ ])
+ })
+
+ it('keeps plain status messages as text', () => {
+ expect(parseObserverStatus('No active locks.')).toEqual([
+ {
+ kind: 'text',
+ value: 'No active locks.',
+ },
+ ])
+ })
+})
diff --git a/web-studio/src/routes/monitoring/-lib/parse-status.ts b/web-studio/src/routes/monitoring/-lib/parse-status.ts
new file mode 100644
index 000000000..4ab37d596
--- /dev/null
+++ b/web-studio/src/routes/monitoring/-lib/parse-status.ts
@@ -0,0 +1,64 @@
+export type ObserverStatusBlock =
+ | {
+ kind: 'table'
+ headers: string[]
+ rows: string[][]
+ }
+ | {
+ kind: 'text'
+ value: string
+ }
+
+function parseRow(line: string): string[] {
+ return line
+ .slice(1, -1)
+ .split('|')
+ .map((cell) => cell.trim())
+}
+
+export function parseObserverStatus(status: string): ObserverStatusBlock[] {
+ const lines = status
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ const blocks: ObserverStatusBlock[] = []
+
+ for (let index = 0; index < lines.length; ) {
+ if (lines[index].startsWith('+') && lines[index + 1]?.startsWith('|')) {
+ const rows: string[][] = []
+ index += 1
+
+ while (index < lines.length) {
+ const line = lines[index]
+ if (line.startsWith('|')) {
+ rows.push(parseRow(line))
+ }
+ index += 1
+ if (
+ line.startsWith('+') &&
+ !lines[index]?.startsWith('|') &&
+ !lines[index]?.startsWith('+')
+ ) {
+ break
+ }
+ }
+
+ if (rows.length > 0) {
+ blocks.push({
+ headers: rows[0],
+ kind: 'table',
+ rows: rows.slice(1),
+ })
+ }
+ continue
+ }
+
+ blocks.push({
+ kind: 'text',
+ value: lines[index],
+ })
+ index += 1
+ }
+
+ return blocks
+}
diff --git a/web-studio/src/routes/monitoring/route.tsx b/web-studio/src/routes/monitoring/route.tsx
new file mode 100644
index 000000000..7343c8bad
--- /dev/null
+++ b/web-studio/src/routes/monitoring/route.tsx
@@ -0,0 +1,443 @@
+import * as React from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { createFileRoute, Link } from '@tanstack/react-router'
+import {
+ ActivityIcon,
+ CheckCircle2Icon,
+ CircleAlertIcon,
+ CpuIcon,
+ DatabaseIcon,
+ HardDriveIcon,
+ LayoutDashboardIcon,
+ ListTodoIcon,
+ LockKeyholeIcon,
+ RefreshCwIcon,
+ SearchIcon,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import { Alert, AlertDescription, AlertTitle } from '#/components/ui/alert'
+import { Badge } from '#/components/ui/badge'
+import { Button } from '#/components/ui/button'
+import { Card, CardContent, CardHeader, CardTitle } from '#/components/ui/card'
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '#/components/ui/table'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { getHealth, getObserverSystem, getOvResult } from '#/lib/ov-client'
+import { cn } from '#/lib/utils'
+import { parseObserverStatus } from './-lib/parse-status'
+
+export const Route = createFileRoute('/monitoring')({
+ component: MonitoringRoute,
+})
+
+type ObserverComponent = {
+ has_errors: boolean
+ is_healthy: boolean
+ name: string
+ status: string
+}
+
+type MonitoringOverview = {
+ components: Record<string, ObserverComponent>
+ errors: string[]
+ healthy: boolean
+ version?: string
+}
+
+const MONITOR_TYPES = [
+ ['overview', LayoutDashboardIcon],
+ ['queue', ListTodoIcon],
+ ['vikingdb', DatabaseIcon],
+ ['models', CpuIcon],
+ ['filesystem', HardDriveIcon],
+ ['lock', LockKeyholeIcon],
+ ['retrieval', SearchIcon],
+] as const
+
+type MonitorType = (typeof MONITOR_TYPES)[number][0]
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
+}
+
+function normalizeComponent(
+ name: string,
+ value: unknown,
+): ObserverComponent | undefined {
+ if (!isRecord(value)) return undefined
+
+ return {
+ has_errors: value.has_errors === true,
+ is_healthy: value.is_healthy === true,
+ name: typeof value.name === 'string' ? value.name : name,
+ status: typeof value.status === 'string' ? value.status : '',
+ }
+}
+
+async function fetchMonitoringOverview(): Promise<MonitoringOverview> {
+ const [health, observer] = await Promise.all([
+ getOvResult<Record<string, unknown>>(getHealth()),
+ getOvResult<Record<string, unknown>>(getObserverSystem()),
+ ])
+ const rawComponents = isRecord(observer.components)
+ ? observer.components
+ : {}
+ const components: Record<string, ObserverComponent> = {}
+
+ for (const [name] of MONITOR_TYPES) {
+ if (name === 'overview') continue
+ const component = normalizeComponent(name, rawComponents[name])
+ if (component) components[name] = component
+ }
+
+ return {
+ components,
+ errors: Array.isArray(observer.errors)
+ ? observer.errors.filter(
+ (error): error is string => typeof error === 'string',
+ )
+ : [],
+ healthy: observer.is_healthy === true,
+ version: typeof health.version === 'string' ? health.version : undefined,
+ }
+}
+
+function HealthBadge({
+ healthy,
+ label,
+}: {
+ healthy: boolean
+ label: string
+}) {
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ 'gap-1.5 font-normal',
+ healthy
+ ? 'border-emerald-500/30 text-emerald-600'
+ : 'border-destructive/30 text-destructive',
+ )}
+ >
+ <span
+ className={cn(
+ 'size-1.5 rounded-full',
+ healthy ? 'bg-emerald-500' : 'bg-destructive',
+ )}
+ />
+ {label}
+ </Badge>
+ )
+}
+
+function ObserverStatusContent({ status }: { status: string }) {
+ const { t } = useTranslation('monitoringPage')
+ const blocks = React.useMemo(() => parseObserverStatus(status), [status])
+
+ if (blocks.length === 0) {
+ return (
+ <p className="text-sm text-muted-foreground">{t('detail.noData')}</p>
+ )
+ }
+
+ return (
+ <div className="grid gap-4">
+ {blocks.map((block, blockIndex) =>
+ block.kind === 'text' ? (
+ <p
+ key={`${block.value}-${blockIndex}`}
+ className="rounded-lg border bg-muted/20 px-3 py-2 text-sm text-muted-foreground"
+ >
+ {block.value}
+ </p>
+ ) : (
+ <div
+ key={`table-${blockIndex}`}
+ className="overflow-x-auto rounded-lg border"
+ >
+ <Table>
+ <TableHeader>
+ <TableRow className="bg-muted/20 hover:bg-muted/20">
+ {block.headers.map((header, headerIndex) => (
+ <TableHead
+ key={`${header}-${headerIndex}`}
+ className="whitespace-nowrap"
+ >
+ {header}
+ </TableHead>
+ ))}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {block.rows.map((row, rowIndex) => (
+ <TableRow key={`row-${rowIndex}`}>
+ {row.map((cell, cellIndex) => (
+ <TableCell
+ key={`${cell}-${cellIndex}`}
+ className="whitespace-nowrap font-mono text-xs"
+ >
+ {cell}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ ),
+ )}
+ </div>
+ )
+}
+
+function MonitoringRoute() {
+ const { i18n, t } = useTranslation('monitoringPage')
+ const { identityScopeKey, serverMode } = useAppConnection()
+ const [activeType, setActiveType] = React.useState<MonitorType>('overview')
+ const monitoringQuery = useQuery({
+ enabled: serverMode !== 'offline',
+ queryFn: fetchMonitoringOverview,
+ queryKey: ['monitoring-overview', identityScopeKey],
+ refetchInterval: 10_000,
+ retry: false,
+ staleTime: 5_000,
+ })
+ const overview = monitoringQuery.data
+ const selectedComponent =
+ activeType === 'overview' ? undefined : overview?.components[activeType]
+ const SelectedMonitorIcon =
+ MONITOR_TYPES.find(([name]) => name === activeType)?.[1] ?? ActivityIcon
+ const healthyCount = Object.values(overview?.components ?? {}).filter(
+ (component) => component.is_healthy && !component.has_errors,
+ ).length
+ const totalCount = Object.keys(overview?.components ?? {}).length
+ const updatedAt = monitoringQuery.dataUpdatedAt
+ ? new Intl.DateTimeFormat(i18n.resolvedLanguage, {
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ }).format(monitoringQuery.dataUpdatedAt)
+ : undefined
+
+ return (
+ <div className="flex w-full min-w-0 flex-col gap-5">
+ <header className="flex flex-wrap items-start justify-between gap-3">
+ <div className="grid gap-1.5">
+ <div className="flex flex-wrap items-center gap-2">
+ <h1 className="text-2xl font-semibold tracking-tight">
+ {t('title')}
+ </h1>
+ {overview?.version ? (
+ <Badge variant="outline" className="font-mono font-normal">
+ {t('version', { version: overview.version })}
+ </Badge>
+ ) : null}
+ </div>
+ <p className="max-w-3xl text-sm leading-6 text-muted-foreground">
+ {t('description')}
+ </p>
+ </div>
+ <div className="flex items-center gap-3">
+ {updatedAt ? (
+ <span className="text-xs text-muted-foreground">
+ {t('updatedAt', { time: updatedAt })}
+ </span>
+ ) : null}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={monitoringQuery.isFetching}
+ onClick={() => void monitoringQuery.refetch()}
+ >
+ <RefreshCwIcon
+ className={cn(
+ 'size-4',
+ monitoringQuery.isFetching && 'animate-spin',
+ )}
+ />
+ {t('refresh')}
+ </Button>
+ </div>
+ </header>
+
+ {serverMode === 'offline' ? (
+ <Alert>
+ <CircleAlertIcon />
+ <AlertTitle>{t('offline.title')}</AlertTitle>
+ <AlertDescription>
+ {t('offline.description')}{' '}
+ <Link to="/settings" className="font-medium text-primary underline">
+ {t('offline.action')}
+ </Link>
+ </AlertDescription>
+ </Alert>
+ ) : monitoringQuery.isLoading ? (
+ <Card className="min-h-64 items-center justify-center">
+ <RefreshCwIcon className="size-5 animate-spin text-muted-foreground" />
+ <p className="text-sm text-muted-foreground">{t('loading')}</p>
+ </Card>
+ ) : monitoringQuery.isError ? (
+ <Alert variant="destructive">
+ <CircleAlertIcon />
+ <AlertTitle>{t('loadFailed')}</AlertTitle>
+ <AlertDescription>
+ {monitoringQuery.error instanceof Error
+ ? monitoringQuery.error.message
+ : String(monitoringQuery.error)}
+ </AlertDescription>
+ </Alert>
+ ) : (
+ <>
+ <Card className="gap-0 overflow-hidden py-0">
+ <CardContent className="flex flex-wrap items-center justify-between gap-4 px-5 py-4">
+ <div className="flex items-center gap-3">
+ <div
+ className={cn(
+ 'flex size-10 items-center justify-center rounded-xl',
+ overview?.healthy
+ ? 'bg-emerald-500/10 text-emerald-600'
+ : 'bg-destructive/10 text-destructive',
+ )}
+ >
+ {overview?.healthy ? (
+ <CheckCircle2Icon className="size-5" />
+ ) : (
+ <CircleAlertIcon className="size-5" />
+ )}
+ </div>
+ <div>
+ <p className="font-medium">
+ {overview?.healthy
+ ? t('summary.healthy')
+ : t('summary.unhealthy')}
+ </p>
+ <p className="text-sm text-muted-foreground">
+ {t('summary.components', {
+ healthy: healthyCount,
+ total: totalCount,
+ })}
+ </p>
+ </div>
+ </div>
+ <HealthBadge
+ healthy={overview?.healthy === true}
+ label={
+ overview?.healthy
+ ? t('health.healthy')
+ : t('health.unhealthy')
+ }
+ />
+ </CardContent>
+ </Card>
+
+ <div
+ role="tablist"
+ aria-label={t('tabs.label')}
+ className="flex max-w-full gap-1 overflow-x-auto rounded-xl border bg-muted/20 p-1"
+ >
+ {MONITOR_TYPES.map(([name, Icon]) => (
+ <button
+ key={name}
+ type="button"
+ role="tab"
+ aria-selected={activeType === name}
+ className={cn(
+ 'flex h-9 shrink-0 items-center gap-2 rounded-lg px-3 text-sm text-muted-foreground transition-colors',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ activeType === name
+ ? 'bg-background font-medium text-foreground shadow-xs'
+ : 'hover:bg-background/60 hover:text-foreground',
+ )}
+ onClick={() => setActiveType(name)}
+ >
+ <Icon className="size-4" />
+ {t(`tabs.${name}`)}
+ </button>
+ ))}
+ </div>
+
+ {activeType === 'overview' ? (
+ <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
+ {MONITOR_TYPES.slice(1).map(([name, Icon]) => {
+ const component = overview?.components[name]
+ const healthy =
+ component?.is_healthy === true && !component.has_errors
+ return (
+ <button
+ key={name}
+ type="button"
+ className="group rounded-xl text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => setActiveType(name)}
+ >
+ <Card className="h-full gap-3 p-4 transition-colors group-hover:border-primary/35 group-hover:bg-muted/15">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <div className="flex size-8 items-center justify-center rounded-lg bg-muted text-muted-foreground">
+ <Icon className="size-4" />
+ </div>
+ <CardTitle>{t(`tabs.${name}`)}</CardTitle>
+ </div>
+ <HealthBadge
+ healthy={healthy}
+ label={
+ healthy
+ ? t('health.healthy')
+ : t('health.unhealthy')
+ }
+ />
+ </div>
+ <p className="text-sm leading-6 text-muted-foreground">
+ {t(`detail.descriptions.${name}`)}
+ </p>
+ </Card>
+ </button>
+ )
+ })}
+ </div>
+ ) : (
+ <Card className="gap-0 overflow-hidden py-0">
+ <CardHeader className="border-b px-5 py-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-3">
+ <SelectedMonitorIcon className="size-5 text-muted-foreground" />
+ <div>
+ <CardTitle>{t(`tabs.${activeType}`)}</CardTitle>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {t(`detail.descriptions.${activeType}`)}
+ </p>
+ </div>
+ </div>
+ <HealthBadge
+ healthy={
+ selectedComponent?.is_healthy === true &&
+ !selectedComponent.has_errors
+ }
+ label={
+ selectedComponent?.is_healthy &&
+ !selectedComponent.has_errors
+ ? t('health.healthy')
+ : t('health.unhealthy')
+ }
+ />
+ </div>
+ </CardHeader>
+ <CardContent className="px-5 py-5">
+ <ObserverStatusContent
+ status={selectedComponent?.status ?? ''}
+ />
+ </CardContent>
+ </Card>
+ )}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/playground/-components/context-explorer.tsx b/web-studio/src/routes/playground/-components/context-explorer.tsx
index 00173d4a6..2cd243912 100644
--- a/web-studio/src/routes/playground/-components/context-explorer.tsx
+++ b/web-studio/src/routes/playground/-components/context-explorer.tsx
@@ -4,7 +4,6 @@ import { useTranslation } from 'react-i18next'
import {
ChevronRightIcon,
ClipboardListIcon,
- CommandIcon,
FileTextIcon,
FolderIcon,
FolderTreeIcon,
@@ -19,11 +18,8 @@ import { cn } from '#/lib/utils'
import { useVikingFsList } from '#/routes/resources/-hooks/viking-fm'
import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'
-import {
- createEntryFromUri,
- sortTreeEntries,
- visibleContextEntries,
-} from '../-lib/utils'
+import { sortTreeEntries, visibleContextEntries } from '../-lib/utils'
+import { ROOT_URI } from '../-lib/constants'
const TREE_INDENT_WIDTH = 16
const TREE_ROW_PADDING = 6
@@ -119,31 +115,24 @@ export function ContextExplorerHeader({
)
}
-const NAMESPACES: Array<{
- descriptionKey: 'resources' | 'session' | 'user'
- icon: typeof FolderIcon
- label: string
- uri: string
-}> = [
- {
- descriptionKey: 'user',
- icon: FolderIcon,
- label: 'User',
- uri: 'viking://user/',
- },
- {
- descriptionKey: 'session',
- icon: CommandIcon,
- label: 'Session',
- uri: 'viking://session/',
- },
- {
- descriptionKey: 'resources',
- icon: FolderTreeIcon,
- label: 'Resources',
- uri: 'viking://resources/',
- },
-]
+const NAMESPACE_DESCRIPTION_KEYS: Partial<
+ Record<
+ string,
+ | 'explorer.namespaces.agent'
+ | 'explorer.namespaces.resources'
+ | 'explorer.namespaces.user'
+ >
+> = {
+ agent: 'explorer.namespaces.agent',
+ resources: 'explorer.namespaces.resources',
+ user: 'explorer.namespaces.user',
+} as const
+
+const NAMESPACE_ORDER: Partial<Record<string, number>> = {
+ user: 0,
+ resources: 1,
+ agent: 2,
+}
export function ContextTree({
currentUri,
@@ -161,28 +150,67 @@ export function ContextTree({
selectedFileUri?: string | null
}) {
const { t } = useTranslation('playground')
+ const rootQuery = useVikingFsList(ROOT_URI, {
+ output: 'agent',
+ showAllHidden: true,
+ nodeLimit: 200,
+ sortBy: 'name',
+ sortOrder: 'asc',
+ })
+ const namespaces = useMemo(
+ () =>
+ [...visibleContextEntries(rootQuery.data?.entries ?? [])].sort(
+ (left, right) => {
+ const leftOrder =
+ NAMESPACE_ORDER[left.name.toLowerCase()] ?? Number.POSITIVE_INFINITY
+ const rightOrder =
+ NAMESPACE_ORDER[right.name.toLowerCase()] ??
+ Number.POSITIVE_INFINITY
+ return leftOrder - rightOrder || left.name.localeCompare(right.name)
+ },
+ ),
+ [rootQuery.data?.entries],
+ )
+
return (
<div className="h-full overflow-auto px-2 py-2 font-mono">
- {NAMESPACES.map((item) => {
- const entry = createEntryFromUri(item.uri, true)
- return (
- <ContextTreeNode
- key={item.uri}
- currentUri={currentUri}
- entry={{
- ...entry,
- name: item.label,
- abstract: t(`explorer.namespaces.${item.descriptionKey}`),
- }}
- expandedKeys={expandedKeys}
- level={0}
- onExpandedKeysChange={onExpandedKeysChange}
- onSelectDirectory={onSelectDirectory}
- onSelectFile={onSelectFile}
- selectedFileUri={selectedFileUri}
- />
- )
- })}
+ {rootQuery.isLoading ? (
+ <div className="flex h-7 items-center gap-2 px-1.5 text-xs text-muted-foreground">
+ <Loader2Icon className="size-3 animate-spin" />
+ {t('explorer.loading')}
+ </div>
+ ) : rootQuery.isError ? (
+ <div className="px-1.5 text-xs leading-7 text-destructive">
+ {t('dirBrowser.error')}
+ </div>
+ ) : namespaces.length === 0 ? (
+ <div className="px-1.5 text-xs leading-7 text-muted-foreground/60">
+ {t('explorer.empty')}
+ </div>
+ ) : (
+ namespaces.map((entry) => {
+ const normalizedName = entry.name.toLowerCase()
+ const descriptionKey = NAMESPACE_DESCRIPTION_KEYS[normalizedName]
+
+ return (
+ <ContextTreeNode
+ key={entry.uri}
+ currentUri={currentUri}
+ entry={{
+ ...entry,
+ name: entry.name,
+ abstract: descriptionKey ? t(descriptionKey) : entry.abstract,
+ }}
+ expandedKeys={expandedKeys}
+ level={0}
+ onExpandedKeysChange={onExpandedKeysChange}
+ onSelectDirectory={onSelectDirectory}
+ onSelectFile={onSelectFile}
+ selectedFileUri={selectedFileUri}
+ />
+ )
+ })
+ )}
</div>
)
}
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx b/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx
index fc8cfef3c..02995483d 100644
--- a/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx
+++ b/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx
@@ -1,6 +1,7 @@
import { FolderOpen } from 'lucide-react'
import type { TFunction } from 'i18next'
+import { Checkbox } from '#/components/ui/checkbox'
import { Input } from '#/components/ui/input'
import {
Select,
@@ -19,8 +20,10 @@ import type { RetrievalMode, RetrievalScope } from '../-types/retrieval'
export function RetrievalControls({
customPathInput,
+ ignoreCase,
mode,
onCustomPathInputChange,
+ onIgnoreCaseChange,
onModeChange,
onResultCountChange,
onScopeChange,
@@ -32,8 +35,10 @@ export function RetrievalControls({
targetUri,
}: {
customPathInput: string
+ ignoreCase: boolean
mode: RetrievalMode
onCustomPathInputChange: (value: string) => void
+ onIgnoreCaseChange: (value: boolean) => void
onModeChange: (value: RetrievalMode) => void
onResultCountChange: (value: number) => void
onScopeChange: (value: RetrievalScope) => void
@@ -123,6 +128,13 @@ export function RetrievalControls({
className="h-8 w-52 font-mono text-sm"
/>
)}
+
+ {mode === 'grep' && (
+ <label className="inline-flex h-8 cursor-pointer items-center gap-2 rounded-md border bg-muted/20 px-2.5 text-xs text-foreground">
+ <Checkbox checked={ignoreCase} onCheckedChange={onIgnoreCaseChange} />
+ {t('controls.ignoreCase')}
+ </label>
+ )}
</div>
)
}
diff --git a/web-studio/src/routes/retrieval/-components/retrieval-results.tsx b/web-studio/src/routes/retrieval/-components/retrieval-results.tsx
index b00f702ff..66aaa47ae 100644
--- a/web-studio/src/routes/retrieval/-components/retrieval-results.tsx
+++ b/web-studio/src/routes/retrieval/-components/retrieval-results.tsx
@@ -252,9 +252,15 @@ function ResultRow({
</p>
)}
</div>
- <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] tabular-nums text-muted-foreground">
- {item.item.score.toFixed(3)}
- </span>
+ {item.item.result_kind === 'grep' && item.item.line !== undefined ? (
+ <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">
+ {t('results.line', { line: item.item.line })}
+ </span>
+ ) : item.item.result_kind !== 'glob' ? (
+ <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] tabular-nums text-muted-foreground">
+ {item.item.score.toFixed(3)}
+ </span>
+ ) : null}
</Link>
)
}
diff --git a/web-studio/src/routes/retrieval/-constants/retrieval.ts b/web-studio/src/routes/retrieval/-constants/retrieval.ts
index 30f0f7ada..6607cff79 100644
--- a/web-studio/src/routes/retrieval/-constants/retrieval.ts
+++ b/web-studio/src/routes/retrieval/-constants/retrieval.ts
@@ -1,7 +1,7 @@
export const RESULT_COUNT_OPTIONS = [5, 10, 20, 50] as const
export const DEFAULT_RESULT_COUNT = 10
-export const RETRIEVAL_MODES = ['find', 'search'] as const
+export const RETRIEVAL_MODES = ['find', 'search', 'grep', 'glob'] as const
export const DEFAULT_RETRIEVAL_MODE = 'find'
export const RETRIEVAL_SCOPES = ['all', 'resources', 'custom'] as const
diff --git a/web-studio/src/routes/retrieval/-hooks/use-retrieval-query.ts b/web-studio/src/routes/retrieval/-hooks/use-retrieval-query.ts
index 5d0192bc6..2e503b54e 100644
--- a/web-studio/src/routes/retrieval/-hooks/use-retrieval-query.ts
+++ b/web-studio/src/routes/retrieval/-hooks/use-retrieval-query.ts
@@ -1,12 +1,13 @@
import { useQuery } from '@tanstack/react-query'
-import { fetchFind, fetchFindAllTypes, fetchSearch } from '#/lib/retrieval'
+import { fetchFind, fetchGlob, fetchGrep, fetchSearch } from '#/lib/retrieval'
import type { GroupedFindResult } from '#/lib/retrieval'
import type { RetrievalMode } from '../-types/retrieval'
export function useRetrievalQuery({
enabled,
+ ignoreCase,
mode,
query,
resultCount,
@@ -14,6 +15,7 @@ export function useRetrievalQuery({
targetUri,
}: {
enabled: boolean
+ ignoreCase: boolean
mode: RetrievalMode
query: string
resultCount: number
@@ -29,11 +31,32 @@ export function useRetrievalQuery({
return fetchSearch(query, { limit: resultCount, sessionId, targetUri })
}
- return targetUri
- ? fetchFind(query, { limit: resultCount, targetUri })
- : fetchFindAllTypes(query, { limit: resultCount })
+ if (mode === 'grep') {
+ return fetchGrep(query, {
+ caseInsensitive: ignoreCase,
+ limit: resultCount,
+ uri: targetUri ?? 'viking://',
+ })
+ }
+
+ if (mode === 'glob') {
+ return fetchGlob(query, {
+ limit: resultCount,
+ uri: targetUri ?? 'viking://',
+ })
+ }
+
+ return fetchFind(query, { limit: resultCount, targetUri })
},
- queryKey: ['retrieval', mode, query, targetUri, resultCount, sessionId],
+ queryKey: [
+ 'retrieval',
+ mode,
+ query,
+ targetUri,
+ resultCount,
+ sessionId,
+ ignoreCase,
+ ],
staleTime: 60_000,
})
}
diff --git a/web-studio/src/routes/retrieval/-lib/search-state.ts b/web-studio/src/routes/retrieval/-lib/search-state.ts
index e28063658..e740eecae 100644
--- a/web-studio/src/routes/retrieval/-lib/search-state.ts
+++ b/web-studio/src/routes/retrieval/-lib/search-state.ts
@@ -48,6 +48,8 @@ export function validateRetrievalSearch(
const path = typeof search.path === 'string' ? search.path.trim() : undefined
const session =
typeof search.session === 'string' ? search.session.trim() : undefined
+ const ignoreCase =
+ search.ignoreCase === true || search.ignoreCase === 'true' || undefined
return {
...(q && { q }),
@@ -56,6 +58,7 @@ export function validateRetrievalSearch(
...(isRetrievalScope(search.scope) && { scope: search.scope }),
...(path && { path }),
...(session && { session }),
+ ...(ignoreCase && { ignoreCase }),
}
}
@@ -66,7 +69,8 @@ export function hasRetrievalSearch(search: RetrievalSearch): boolean {
search.count ||
search.scope ||
search.path ||
- search.session,
+ search.session ||
+ search.ignoreCase,
)
}
@@ -115,6 +119,7 @@ export function buildSubmittedSearch(params: {
scope: RetrievalScope
path: string
session: string
+ ignoreCase: boolean
}): RetrievalSearch {
const q = params.q.trim()
const path = params.path.trim()
@@ -127,5 +132,6 @@ export function buildSubmittedSearch(params: {
...(params.scope !== DEFAULT_RETRIEVAL_SCOPE && { scope: params.scope }),
...(params.scope === 'custom' && path && { path }),
...(params.mode === 'search' && session && { session }),
+ ...(params.mode === 'grep' && params.ignoreCase && { ignoreCase: true }),
}
}
diff --git a/web-studio/src/routes/retrieval/-types/retrieval.ts b/web-studio/src/routes/retrieval/-types/retrieval.ts
index 625080cd0..61deceb2e 100644
--- a/web-studio/src/routes/retrieval/-types/retrieval.ts
+++ b/web-studio/src/routes/retrieval/-types/retrieval.ts
@@ -16,6 +16,7 @@ export type RetrievalSearch = {
scope?: RetrievalScope
path?: string
session?: string
+ ignoreCase?: boolean
}
export interface FlatRetrievalItem {
diff --git a/web-studio/src/routes/retrieval/route.tsx b/web-studio/src/routes/retrieval/route.tsx
index 52597b3b4..2b8ce5ed3 100644
--- a/web-studio/src/routes/retrieval/route.tsx
+++ b/web-studio/src/routes/retrieval/route.tsx
@@ -46,6 +46,7 @@ function RetrievalPage() {
const initialScope = activeSearch.scope ?? DEFAULT_RETRIEVAL_SCOPE
const initialCustomPath = activeSearch.path ?? DEFAULT_CUSTOM_PATH_INPUT
const initialSessionId = activeSearch.session ?? ''
+ const initialIgnoreCase = activeSearch.ignoreCase ?? false
const [retrievalMode, setRetrievalMode] = useState<RetrievalMode>(initialMode)
const [query, setQuery] = useState(initialQuery)
@@ -55,6 +56,7 @@ function RetrievalPage() {
useState<RetrievalScope>(initialScope)
const [customPathInput, setCustomPathInput] = useState(initialCustomPath)
const [sessionIdInput, setSessionIdInput] = useState(initialSessionId)
+ const [ignoreCase, setIgnoreCase] = useState(initialIgnoreCase)
const inputRef = useRef<HTMLInputElement>(null)
const targetUri = useMemo(() => {
@@ -65,6 +67,7 @@ function RetrievalPage() {
const sessionId = sessionIdInput.trim() || undefined
const retrievalQuery = useRetrievalQuery({
enabled: hasSubmitted,
+ ignoreCase,
mode: retrievalMode,
query: submittedQuery,
resultCount,
@@ -87,6 +90,7 @@ function RetrievalPage() {
const nextSearch = buildSubmittedSearch({
count: resultCount,
+ ignoreCase,
mode: retrievalMode,
path: customPathInput,
q: trimmed,
@@ -102,6 +106,7 @@ function RetrievalPage() {
})
}, [
customPathInput,
+ ignoreCase,
navigate,
query,
resultCount,
@@ -128,6 +133,7 @@ function RetrievalPage() {
const nextScope = activeSearch.scope ?? DEFAULT_RETRIEVAL_SCOPE
const nextCustomPath = activeSearch.path ?? DEFAULT_CUSTOM_PATH_INPUT
const nextSessionId = activeSearch.session ?? ''
+ const nextIgnoreCase = activeSearch.ignoreCase ?? false
setRetrievalMode(nextMode)
setQuery(activeSearch.q)
@@ -136,9 +142,11 @@ function RetrievalPage() {
setRetrievalScope(nextScope)
setCustomPathInput(nextCustomPath)
setSessionIdInput(nextSessionId)
+ setIgnoreCase(nextIgnoreCase)
const nextSearch = buildSubmittedSearch({
count: nextResultCount,
+ ignoreCase: nextIgnoreCase,
mode: nextMode,
path: nextCustomPath,
q: activeSearch.q,
@@ -156,6 +164,7 @@ function RetrievalPage() {
}
}, [
activeSearch.count,
+ activeSearch.ignoreCase,
activeSearch.mode,
activeSearch.path,
activeSearch.q,
@@ -171,14 +180,16 @@ function RetrievalPage() {
inputRef={inputRef}
onChange={setQuery}
onSubmit={handleSubmit}
- placeholder={t('searchPlaceholder')}
+ placeholder={t(`placeholders.${retrievalMode}`)}
query={query}
/>
<RetrievalControls
customPathInput={customPathInput}
+ ignoreCase={ignoreCase}
mode={retrievalMode}
onCustomPathInputChange={setCustomPathInput}
+ onIgnoreCaseChange={setIgnoreCase}
onModeChange={setRetrievalMode}
onResultCountChange={setResultCount}
onScopeChange={setRetrievalScope}
diff --git a/web-studio/src/routes/sessions/-components/memory-impact.tsx b/web-studio/src/routes/sessions/-components/memory-impact.tsx
new file mode 100644
index 000000000..05e8471e8
--- /dev/null
+++ b/web-studio/src/routes/sessions/-components/memory-impact.tsx
@@ -0,0 +1,323 @@
+import { useMemo, useState } from 'react'
+import {
+ BrainCircuitIcon,
+ FilePenLineIcon,
+ FilePlus2Icon,
+ FileX2Icon,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import { Badge } from '#/components/ui/badge'
+import { Button } from '#/components/ui/button'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '#/components/ui/sheet'
+import { useSessionMemoryDiffs } from '#/lib/sessions/use-sessions'
+import type {
+ MemoryDiffKind,
+ SessionMemoryDiffOperation,
+} from '#/lib/sessions/memory-diff'
+import type { SessionMeta } from '@ov-server/api/v1/sessions'
+
+interface MemoryImpactProps {
+ session?: SessionMeta
+}
+
+const KIND_STYLES: Record<
+ MemoryDiffKind,
+ { icon: typeof FilePlus2Icon; text: string }
+> = {
+ add: {
+ icon: FilePlus2Icon,
+ text: 'text-emerald-600 dark:text-emerald-400',
+ },
+ update: {
+ icon: FilePenLineIcon,
+ text: 'text-amber-600 dark:text-amber-400',
+ },
+ delete: {
+ icon: FileX2Icon,
+ text: 'text-rose-600 dark:text-rose-400',
+ },
+}
+
+export function MemoryImpact({ session }: MemoryImpactProps) {
+ const { i18n, t } = useTranslation('sessions')
+ const [open, setOpen] = useState(false)
+ const diffsQuery = useSessionMemoryDiffs(session, open)
+ const diffs = diffsQuery.data ?? []
+ const totals = useMemo(
+ () =>
+ diffs.reduce(
+ (result, diff) => ({
+ adds: result.adds + diff.summary.adds,
+ deletes: result.deletes + diff.summary.deletes,
+ updates: result.updates + diff.summary.updates,
+ }),
+ { adds: 0, deletes: 0, updates: 0 },
+ ),
+ [diffs],
+ )
+ const totalChanges = totals.adds + totals.updates + totals.deletes
+
+ if (!session || session.commit_count <= 0) return null
+
+ return (
+ <>
+ <Button
+ aria-label={t('impact.open')}
+ className="h-7 gap-1.5 rounded-full border-primary/20 bg-primary/5 px-2.5 text-xs text-primary hover:bg-primary/10"
+ onClick={() => setOpen(true)}
+ size="xs"
+ variant="outline"
+ >
+ <BrainCircuitIcon className="size-3.5" />
+ <span>{t('impact.title')}</span>
+ {totalChanges > 0 ? <ImpactCounts totals={totals} /> : null}
+ </Button>
+
+ <Sheet open={open} onOpenChange={setOpen}>
+ <SheetContent className="gap-0 sm:max-w-2xl">
+ <SheetHeader className="border-b px-6 py-5">
+ <div className="flex items-center gap-3 pr-10">
+ <div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary ring-1 ring-primary/15">
+ <BrainCircuitIcon className="size-4.5" />
+ </div>
+ <div className="min-w-0">
+ <SheetTitle className="text-lg">{t('impact.title')}</SheetTitle>
+ <SheetDescription>
+ {t('impact.description', {
+ changes: totalChanges,
+ commits: diffs.length,
+ })}
+ </SheetDescription>
+ </div>
+ </div>
+ </SheetHeader>
+
+ {diffsQuery.isLoading ? (
+ <div className="flex min-h-48 items-center justify-center text-sm text-muted-foreground">
+ {t('impact.loading')}
+ </div>
+ ) : diffsQuery.isError ? (
+ <div className="flex min-h-48 flex-col items-center justify-center gap-3 px-6 text-center">
+ <p className="text-sm text-destructive">
+ {t('impact.loadFailed')}
+ </p>
+ <Button
+ onClick={() => void diffsQuery.refetch()}
+ size="sm"
+ variant="outline"
+ >
+ {t('impact.retry')}
+ </Button>
+ </div>
+ ) : totalChanges === 0 ? (
+ <div className="flex min-h-48 items-center justify-center px-6 text-center text-sm text-muted-foreground">
+ {t('impact.empty')}
+ </div>
+ ) : (
+ <>
+ <div className="grid grid-cols-3 gap-2 border-b bg-muted/20 px-6 py-4">
+ <SummaryMetric
+ kind="add"
+ label={t('impact.kinds.add')}
+ value={totals.adds}
+ />
+ <SummaryMetric
+ kind="update"
+ label={t('impact.kinds.update')}
+ value={totals.updates}
+ />
+ <SummaryMetric
+ kind="delete"
+ label={t('impact.kinds.delete')}
+ value={totals.deletes}
+ />
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
+ <div className="space-y-6">
+ {diffs.map((diff) => (
+ <section key={diff.archiveId} className="space-y-2.5">
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-2">
+ <code className="text-xs font-medium text-foreground">
+ {diff.archiveId}
+ </code>
+ <ImpactCounts totals={diff.summary} />
+ </div>
+ {diff.extractedAt ? (
+ <time className="shrink-0 text-xs text-muted-foreground">
+ {formatDate(
+ diff.extractedAt,
+ i18n.resolvedLanguage,
+ )}
+ </time>
+ ) : null}
+ </div>
+
+ <div className="overflow-hidden rounded-xl border bg-background">
+ {diff.operations.map((operation, index) => (
+ <OperationRow
+ key={`${operation.kind}-${operation.uri}-${index}`}
+ operation={operation}
+ />
+ ))}
+ </div>
+ </section>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+ </SheetContent>
+ </Sheet>
+ </>
+ )
+}
+
+function ImpactCounts({
+ totals,
+}: {
+ totals: { adds: number; deletes: number; updates: number }
+}) {
+ return (
+ <span className="flex items-center gap-1 font-mono text-[10px]">
+ {totals.adds > 0 ? (
+ <span className="text-emerald-600 dark:text-emerald-400">
+ +{totals.adds}
+ </span>
+ ) : null}
+ {totals.updates > 0 ? (
+ <span className="text-amber-600 dark:text-amber-400">
+ ~{totals.updates}
+ </span>
+ ) : null}
+ {totals.deletes > 0 ? (
+ <span className="text-rose-600 dark:text-rose-400">
+ −{totals.deletes}
+ </span>
+ ) : null}
+ </span>
+ )
+}
+
+function SummaryMetric({
+ kind,
+ label,
+ value,
+}: {
+ kind: MemoryDiffKind
+ label: string
+ value: number
+}) {
+ const { icon: Icon, text } = KIND_STYLES[kind]
+
+ return (
+ <div className="rounded-xl border bg-background px-3 py-2.5">
+ <div className={`flex items-center gap-1.5 text-xs ${text}`}>
+ <Icon className="size-3.5" />
+ {label}
+ </div>
+ <div className="mt-1 font-mono text-xl font-medium text-foreground">
+ {value}
+ </div>
+ </div>
+ )
+}
+
+function OperationRow({
+ operation,
+}: {
+ operation: SessionMemoryDiffOperation
+}) {
+ const { t } = useTranslation('sessions')
+ const { icon: Icon, text } = KIND_STYLES[operation.kind]
+
+ return (
+ <details className="group border-b last:border-b-0">
+ <summary className="flex cursor-pointer list-none items-center gap-3 px-3.5 py-3 transition-colors hover:bg-muted/40">
+ <Icon className={`size-4 shrink-0 ${text}`} />
+ <code className="min-w-0 flex-1 truncate text-xs text-foreground">
+ {operation.uri}
+ </code>
+ <Badge className="max-w-28" variant="outline">
+ <span className="truncate">{operation.memoryType}</span>
+ </Badge>
+ <span className="text-[10px] text-muted-foreground transition-transform group-open:rotate-90">
+ ›
+ </span>
+ </summary>
+
+ <div className="border-t bg-muted/15 px-3.5 py-3">
+ {operation.kind === 'update' ? (
+ <div className="grid gap-3 sm:grid-cols-2">
+ <ContentBlock
+ content={operation.before}
+ label={t('impact.before')}
+ tone="delete"
+ />
+ <ContentBlock
+ content={operation.after}
+ label={t('impact.after')}
+ tone="add"
+ />
+ </div>
+ ) : (
+ <ContentBlock
+ content={operation.after}
+ label={t(
+ operation.kind === 'add'
+ ? 'impact.addedContent'
+ : 'impact.deletedContent',
+ )}
+ tone={operation.kind}
+ />
+ )}
+ </div>
+ </details>
+ )
+}
+
+function ContentBlock({
+ content,
+ label,
+ tone,
+}: {
+ content?: string
+ label: string
+ tone: 'add' | 'delete'
+}) {
+ const { t } = useTranslation('sessions')
+
+ return (
+ <div className="min-w-0">
+ <div
+ className={`mb-1.5 text-[11px] font-medium ${
+ tone === 'add'
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : 'text-rose-600 dark:text-rose-400'
+ }`}
+ >
+ {label}
+ </div>
+ <pre className="max-h-64 overflow-auto whitespace-pre-wrap rounded-lg border bg-background/80 p-3 font-mono text-[11px] leading-5 text-muted-foreground">
+ {content || t('impact.emptyContent')}
+ </pre>
+ </div>
+ )
+}
+
+function formatDate(value: string, language?: string): string {
+ const date = new Date(value)
+ if (Number.isNaN(date.getTime())) return value
+ return new Intl.DateTimeFormat(language, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ }).format(date)
+}
diff --git a/web-studio/src/routes/sessions/-components/thread-list.tsx b/web-studio/src/routes/sessions/-components/thread-list.tsx
new file mode 100644
index 000000000..96700b96e
--- /dev/null
+++ b/web-studio/src/routes/sessions/-components/thread-list.tsx
@@ -0,0 +1,255 @@
+import { useCallback, useState } from 'react'
+import { Link, useNavigate } from '@tanstack/react-router'
+import {
+ LoaderCircleIcon,
+ MessageSquareIcon,
+ PlusIcon,
+ Trash2Icon,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '#/components/ui/alert-dialog'
+import { Button } from '#/components/ui/button'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import {
+ useCreateSession,
+ useDeleteSession,
+ useSessionListByRecency,
+} from '#/lib/sessions/use-sessions'
+import { useSessionTitles } from '#/lib/sessions/use-session-titles'
+import { cn } from '#/lib/utils'
+
+interface ThreadListProps {
+ activeSessionId?: string
+}
+
+export function ThreadList({ activeSessionId }: ThreadListProps) {
+ const { i18n, t } = useTranslation('sessions')
+ const { identityScopeKey } = useAppConnection()
+ const navigate = useNavigate()
+ const { data: sessions, isLoading } = useSessionListByRecency()
+ const { getTitle, removeTitle, setTitle } = useSessionTitles(identityScopeKey)
+ const createSession = useCreateSession()
+ const deleteSession = useDeleteSession()
+ const [sessionToDelete, setSessionToDelete] = useState<{
+ id: string
+ title: string
+ } | null>(null)
+
+ const handleNewSession = useCallback(async () => {
+ const result = await createSession.mutateAsync(undefined)
+ setTitle(result.session_id, t('threadList.newSession'))
+ void navigate({ to: '/sessions', search: { s: result.session_id } })
+ }, [createSession, navigate, setTitle, t])
+
+ const handleDeleteSession = useCallback(async () => {
+ if (!sessionToDelete) return
+
+ try {
+ await deleteSession.mutateAsync(sessionToDelete.id)
+ removeTitle(sessionToDelete.id)
+
+ if (activeSessionId === sessionToDelete.id) {
+ const nextSession = sessions.find(
+ (session) => session.session_id !== sessionToDelete.id,
+ )
+ void navigate({
+ to: '/sessions',
+ search: { s: nextSession?.session_id },
+ })
+ }
+ toast.success(t('threadList.deleteSuccess'))
+ setSessionToDelete(null)
+ } catch (error) {
+ toast.error(
+ t('threadList.deleteFailed', {
+ error: error instanceof Error ? error.message : String(error),
+ }),
+ )
+ }
+ }, [
+ activeSessionId,
+ deleteSession,
+ navigate,
+ removeTitle,
+ sessionToDelete,
+ sessions,
+ t,
+ ])
+
+ return (
+ <aside className="flex h-full w-72 shrink-0 flex-col border-r border-border/70 bg-muted/20">
+ <div className="flex h-16 shrink-0 items-center justify-between border-b border-border/70 px-4">
+ <div className="min-w-0">
+ <h1 className="text-sm font-semibold text-foreground">
+ {t('threadList.title')}
+ </h1>
+ {!isLoading ? (
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {t('threadList.count', { count: sessions.length })}
+ </p>
+ ) : null}
+ </div>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="outline"
+ disabled={createSession.isPending}
+ onClick={handleNewSession}
+ aria-label={t('threadList.newSession')}
+ title={t('threadList.newSession')}
+ >
+ {createSession.isPending ? (
+ <LoaderCircleIcon className="animate-spin" />
+ ) : (
+ <PlusIcon />
+ )}
+ </Button>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto p-2">
+ {isLoading ? (
+ <div className="flex h-28 items-center justify-center gap-2 text-sm text-muted-foreground">
+ <LoaderCircleIcon className="size-4 animate-spin" />
+ <span>{t('threadList.loading')}</span>
+ </div>
+ ) : sessions.length === 0 ? (
+ <div className="flex h-40 flex-col items-center justify-center px-6 text-center">
+ <div className="flex size-9 items-center justify-center rounded-xl bg-muted">
+ <MessageSquareIcon className="size-4 text-muted-foreground" />
+ </div>
+ <p className="mt-3 text-sm font-medium text-foreground">
+ {t('threadList.emptyTitle')}
+ </p>
+ <p className="mt-1 text-xs leading-5 text-muted-foreground">
+ {t('threadList.emptyDescription')}
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-1">
+ {sessions.map((session) => {
+ const isActive = activeSessionId === session.session_id
+ const title = getTitle(session.session_id)
+
+ return (
+ <div
+ key={session.session_id}
+ className={cn(
+ 'group/session relative rounded-xl transition-colors',
+ isActive
+ ? 'bg-accent text-accent-foreground shadow-sm ring-1 ring-border/60'
+ : 'hover:bg-muted/80',
+ )}
+ >
+ <Link
+ to="/sessions"
+ search={{ s: session.session_id }}
+ className="flex min-w-0 items-start gap-2.5 px-3 py-2.5 pr-9 outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <MessageSquareIcon
+ className={cn(
+ 'mt-0.5 size-4 shrink-0',
+ isActive ? 'text-primary' : 'text-muted-foreground',
+ )}
+ />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm font-medium">
+ {title}
+ </span>
+ <span className="mt-1 block truncate font-mono text-[11px] text-muted-foreground">
+ {formatSessionTime(
+ session.mod_time,
+ i18n.resolvedLanguage,
+ )}
+ </span>
+ </span>
+ </Link>
+ <button
+ type="button"
+ onClick={(event) => {
+ event.preventDefault()
+ event.stopPropagation()
+ setSessionToDelete({
+ id: session.session_id,
+ title,
+ })
+ }}
+ disabled={deleteSession.isPending}
+ className="absolute right-2 top-2.5 flex size-6 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-[opacity,color,background-color] hover:bg-destructive/10 hover:text-destructive focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/session:opacity-100"
+ aria-label={t('threadList.deleteSession', { title })}
+ title={t('threadList.deleteSession', { title })}
+ >
+ <Trash2Icon className="size-3.5" />
+ </button>
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+
+ <AlertDialog
+ open={Boolean(sessionToDelete)}
+ onOpenChange={(open) => {
+ if (!open && !deleteSession.isPending) setSessionToDelete(null)
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t('threadList.deleteConfirmTitle')}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t('threadList.deleteConfirmDescription', {
+ title: sessionToDelete?.title,
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={deleteSession.isPending}>
+ {t('threadList.cancel')}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ disabled={deleteSession.isPending}
+ onClick={(event) => {
+ event.preventDefault()
+ void handleDeleteSession()
+ }}
+ >
+ {deleteSession.isPending
+ ? t('threadList.deleting')
+ : t('threadList.confirmDelete')}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ <div className="shrink-0 border-t border-border/70 px-4 py-3 text-[11px] text-muted-foreground">
+ {t('threadList.shortcut')}
+ </div>
+ </aside>
+ )
+}
+
+function formatSessionTime(value: string, locale?: string): string {
+ if (!value) return ''
+
+ const date = new Date(value)
+ if (Number.isNaN(date.getTime())) return ''
+
+ return new Intl.DateTimeFormat(locale, {
+ dateStyle: 'short',
+ timeStyle: 'short',
+ }).format(date)
+}
diff --git a/web-studio/src/routes/sessions/-components/thread.tsx b/web-studio/src/routes/sessions/-components/thread.tsx
index 6f93ac8d4..ec62930ee 100644
--- a/web-studio/src/routes/sessions/-components/thread.tsx
+++ b/web-studio/src/routes/sessions/-components/thread.tsx
@@ -4,9 +4,10 @@ import { useTranslation } from 'react-i18next'
import { useAppConnection } from '#/hooks/use-app-connection'
import { useChat } from '#/lib/sessions/use-chat'
-import { useSessionMessages } from '#/lib/sessions/use-sessions'
+import { useSession, useSessionMessages } from '#/lib/sessions/use-sessions'
import { useSessionTitles } from '#/lib/sessions/use-session-titles'
import { MessageList } from './message-list'
+import { MemoryImpact } from './memory-impact'
import { Composer } from './composer'
const PixelBlast = lazy(() => import('#/components/ui/pixel-blast'))
@@ -21,6 +22,7 @@ export function Thread({ sessionId }: ThreadProps) {
const { getTitle } = useSessionTitles(identityScopeKey)
const title = getTitle(sessionId)
+ const { data: session } = useSession(sessionId)
const { data: historyMessages } = useSessionMessages(sessionId)
const chat = useChat({
@@ -93,13 +95,12 @@ export function Thread({ sessionId }: ThreadProps) {
</div>
)}
- {title && (
- <div className="relative z-10 flex h-12 items-center border-b border-border/50 bg-background/95 px-6">
- <h2 className="text-sm font-medium truncate text-foreground">
- {title}
- </h2>
- </div>
- )}
+ <div className="relative z-10 flex h-12 items-center justify-between gap-4 border-b border-border/50 bg-background/95 px-6">
+ <h2 className="truncate text-sm font-medium text-foreground">
+ {title || sessionId}
+ </h2>
+ <MemoryImpact session={session} />
+ </div>
<div
ref={scrollRef}
diff --git a/web-studio/src/routes/sessions/index.tsx b/web-studio/src/routes/sessions/index.tsx
index 5f932a87f..721273a55 100644
--- a/web-studio/src/routes/sessions/index.tsx
+++ b/web-studio/src/routes/sessions/index.tsx
@@ -7,6 +7,7 @@ import { useAppConnection } from '#/hooks/use-app-connection'
import { useCreateSession } from '#/lib/sessions/use-sessions'
import { useSessionTitles } from '#/lib/sessions/use-session-titles'
import { Thread } from './-components/thread'
+import { ThreadList } from './-components/thread-list'
const COMMAND_KEY_LABEL = '⌘'
const NEW_SESSION_KEY_LABEL = 'N'
@@ -47,14 +48,15 @@ function SessionsPage() {
}, [handleNewSession])
return (
- <div className="-mx-4 -my-6 md:-mx-6 flex h-[calc(100svh-3rem)]">
- <div className="flex-1 min-w-0 bg-background">
+ <div className="-mx-4 -my-6 flex h-[calc(100svh-3rem)] min-w-0 overflow-hidden md:-mx-6">
+ <ThreadList activeSessionId={activeSessionId} />
+ <section className="min-w-0 flex-1 bg-background">
{activeSessionId ? (
<Thread sessionId={activeSessionId} />
) : (
<SessionsEmpty />
)}
- </div>
+ </section>
</div>
)
}
diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsx
index b77a5471b..95453aa66 100644
--- a/web-studio/src/routes/settings/route.tsx
+++ b/web-studio/src/routes/settings/route.tsx
@@ -191,7 +191,6 @@ function ConnectionSettingsRoute() {
retry: false,
staleTime: 15_000,
})
-
const isDevMode = serverMode === 'dev'
const rootApiKey = connection.adminApiKey.trim()
const hasControlCredential = Boolean(draft.adminApiKey.trim())
diff --git a/web-studio/src/routes/skills/route.tsx b/web-studio/src/routes/skills/route.tsx
new file mode 100644
index 000000000..24bc720f6
--- /dev/null
+++ b/web-studio/src/routes/skills/route.tsx
@@ -0,0 +1,498 @@
+import * as React from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { Link, createFileRoute } from '@tanstack/react-router'
+import {
+ ChevronRightIcon,
+ FileCode2Icon,
+ LoaderCircleIcon,
+ RefreshCwIcon,
+ SparklesIcon,
+ UserRoundIcon,
+ UsersRoundIcon,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import { Badge } from '#/components/ui/badge'
+import { Button } from '#/components/ui/button'
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from '#/components/ui/card'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '#/components/ui/sheet'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { getOvResult, isOvClientError, ovClient } from '#/lib/ov-client'
+
+export const Route = createFileRoute('/skills')({
+ component: SkillsRoute,
+})
+
+type SkillScope = 'agent' | 'user'
+
+type SkillItem = {
+ description: string
+ name: string
+ scope: SkillScope
+ uri: string
+}
+
+type SkillListResult = {
+ skills?: unknown[]
+}
+
+type SkillFile = {
+ isDir: boolean
+ name: string
+ path: string
+}
+
+type SkillDetail = SkillItem & {
+ allowedTools: string[]
+ content: string
+ files: SkillFile[]
+ overview: string
+ tags: string[]
+}
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object'
+ ? (value as Record<string, unknown>)
+ : null
+}
+
+function normalizeSkills(value: unknown): SkillItem[] {
+ const result = asRecord(value)
+ const skills = Array.isArray(result?.skills) ? result.skills : []
+
+ return skills.flatMap((rawSkill) => {
+ const skill = asRecord(rawSkill)
+ const name = typeof skill?.name === 'string' ? skill.name : ''
+ const uri =
+ typeof skill?.uri === 'string'
+ ? skill.uri
+ : typeof skill?.root_uri === 'string'
+ ? skill.root_uri
+ : ''
+
+ if (!name || !uri) {
+ return []
+ }
+
+ return [
+ {
+ description:
+ typeof skill?.description === 'string' ? skill.description : '',
+ name,
+ scope: uri.startsWith('viking://agent/') ? 'agent' : 'user',
+ uri,
+ } satisfies SkillItem,
+ ]
+ })
+}
+
+function stringArray(value: unknown): string[] {
+ return Array.isArray(value)
+ ? value.filter((item): item is string => typeof item === 'string')
+ : []
+}
+
+function normalizeSkillDetail(value: unknown, fallback: SkillItem): SkillDetail {
+ const detail = asRecord(value)
+ const files = Array.isArray(detail?.files) ? detail.files : []
+
+ return {
+ allowedTools: stringArray(detail?.allowed_tools),
+ content: typeof detail?.content === 'string' ? detail.content : '',
+ description:
+ typeof detail?.description === 'string'
+ ? detail.description
+ : fallback.description,
+ files: files.flatMap((rawFile) => {
+ const file = asRecord(rawFile)
+ const name = typeof file?.name === 'string' ? file.name : ''
+ if (!name) return []
+ return [
+ {
+ isDir: Boolean(file?.is_dir),
+ name,
+ path: typeof file?.path === 'string' ? file.path : name,
+ },
+ ]
+ }),
+ name: typeof detail?.name === 'string' ? detail.name : fallback.name,
+ overview: typeof detail?.overview === 'string' ? detail.overview : '',
+ scope: fallback.scope,
+ tags: stringArray(detail?.tags),
+ uri: typeof detail?.uri === 'string' ? detail.uri : fallback.uri,
+ }
+}
+
+function getErrorMessage(error: unknown): string {
+ if (isOvClientError(error) || error instanceof Error) {
+ return error.message
+ }
+ const record = asRecord(error)
+ if (typeof record?.message === 'string') {
+ return record.message
+ }
+ return JSON.stringify(error) || String(error)
+}
+
+async function fetchSkills(): Promise<SkillItem[]> {
+ const result = await getOvResult<SkillListResult>(
+ ovClient.client.get({
+ query: {
+ node_limit: 1000,
+ },
+ url: '/api/v1/skills',
+ }),
+ )
+ return normalizeSkills(result)
+}
+
+async function fetchSkillDetail(skill: SkillItem): Promise<SkillDetail> {
+ const targetUri = skill.uri.slice(0, skill.uri.lastIndexOf('/'))
+ const result = await getOvResult<unknown>(
+ ovClient.client.get({
+ query: {
+ include_content: true,
+ include_files: true,
+ target_uri: targetUri,
+ },
+ url: `/api/v1/skills/${encodeURIComponent(skill.name)}`,
+ }),
+ )
+ return normalizeSkillDetail(result, skill)
+}
+
+function SkillsRoute() {
+ const { t } = useTranslation('skillsPage')
+ const { identityScopeKey } = useAppConnection()
+ const [selectedSkill, setSelectedSkill] = React.useState<SkillItem | null>(
+ null,
+ )
+ const skillsQuery = useQuery({
+ queryFn: fetchSkills,
+ queryKey: ['skills', identityScopeKey],
+ staleTime: 30_000,
+ })
+ const skills = skillsQuery.data ?? []
+ const connectionUnavailable =
+ isOvClientError(skillsQuery.error) &&
+ skillsQuery.error.code === 'NETWORK_ERROR'
+ const detailQuery = useQuery({
+ enabled: Boolean(selectedSkill),
+ queryFn: () => fetchSkillDetail(selectedSkill as SkillItem),
+ queryKey: ['skill-detail', identityScopeKey, selectedSkill?.uri],
+ })
+
+ return (
+ <div className="flex w-full min-w-0 flex-col gap-5">
+ <header className="flex flex-wrap items-start justify-between gap-3">
+ <div className="grid gap-1.5">
+ <h1 className="text-2xl font-semibold tracking-tight">
+ {t('title')}
+ </h1>
+ <p className="max-w-3xl text-sm leading-6 text-muted-foreground">
+ {t('description')}
+ </p>
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={skillsQuery.isFetching}
+ onClick={() => void skillsQuery.refetch()}
+ >
+ <RefreshCwIcon
+ className={skillsQuery.isFetching ? 'animate-spin' : undefined}
+ />
+ {t('refresh')}
+ </Button>
+ </header>
+
+ {skillsQuery.isLoading ? (
+ <Card className="min-h-56 items-center justify-center">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <LoaderCircleIcon className="size-4 animate-spin" />
+ {t('loading')}
+ </div>
+ </Card>
+ ) : skillsQuery.isError ? (
+ <Card className="min-h-56 items-center justify-center px-6 text-center">
+ <SparklesIcon className="size-8 text-destructive/70" />
+ <div className="grid gap-1">
+ <p className="font-medium">{t('loadFailed')}</p>
+ <p className="max-w-xl text-sm text-muted-foreground">
+ {connectionUnavailable
+ ? t('networkError')
+ : getErrorMessage(skillsQuery.error)}
+ </p>
+ {connectionUnavailable ? (
+ <Button
+ render={<Link to="/settings" />}
+ nativeButton={false}
+ variant="outline"
+ size="sm"
+ className="mx-auto mt-2"
+ >
+ {t('connectionSettings')}
+ </Button>
+ ) : null}
+ </div>
+ </Card>
+ ) : skills.length === 0 ? (
+ <Card className="min-h-56 items-center justify-center px-6 text-center">
+ <div className="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
+ <SparklesIcon className="size-5" />
+ </div>
+ <div className="grid max-w-md gap-1">
+ <p className="font-medium">{t('empty')}</p>
+ <p className="text-sm text-muted-foreground">
+ {t('emptyDescription')}
+ </p>
+ </div>
+ </Card>
+ ) : (
+ <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
+ {skills.map((skill) => {
+ const ScopeIcon =
+ skill.scope === 'user' ? UserRoundIcon : UsersRoundIcon
+
+ return (
+ <button
+ key={`${skill.scope}:${skill.uri}`}
+ type="button"
+ className="min-w-0 rounded-xl text-left outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
+ aria-label={t('viewDetail', { name: skill.name })}
+ onClick={() => setSelectedSkill(skill)}
+ >
+ <Card
+ size="sm"
+ className="h-full transition-colors hover:bg-muted/35"
+ >
+ <CardHeader>
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
+ <SparklesIcon className="size-4" />
+ </div>
+ <CardTitle className="truncate">{skill.name}</CardTitle>
+ </div>
+ <Badge variant="outline" className="gap-1 font-normal">
+ <ScopeIcon />
+ {t(`scopes.${skill.scope}`)}
+ </Badge>
+ </div>
+ {skill.description ? (
+ <CardDescription className="line-clamp-2 pt-1 leading-5">
+ {skill.description}
+ </CardDescription>
+ ) : null}
+ </CardHeader>
+ <CardContent className="mt-auto">
+ <div className="flex items-center justify-between gap-3">
+ <code className="min-w-0 truncate text-xs text-muted-foreground">
+ {skill.uri}
+ </code>
+ <span className="flex shrink-0 items-center gap-0.5 text-xs font-medium text-primary">
+ {t('detail')}
+ <ChevronRightIcon className="size-3.5" />
+ </span>
+ </div>
+ </CardContent>
+ </Card>
+ </button>
+ )
+ })}
+ </div>
+ )}
+
+ <Sheet
+ open={Boolean(selectedSkill)}
+ onOpenChange={(open) => {
+ if (!open) setSelectedSkill(null)
+ }}
+ >
+ <SheetContent className="gap-0 sm:max-w-2xl">
+ <SheetHeader className="border-b px-6 py-5">
+ <div className="flex items-center gap-2 pr-10">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
+ <SparklesIcon className="size-4" />
+ </div>
+ <SheetTitle className="truncate text-lg">
+ {selectedSkill?.name}
+ </SheetTitle>
+ </div>
+ <SheetDescription className="truncate font-mono text-xs">
+ {selectedSkill?.uri}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
+ {detailQuery.isLoading ? (
+ <div className="flex min-h-48 items-center justify-center gap-2 text-muted-foreground">
+ <LoaderCircleIcon className="size-4 animate-spin" />
+ {t('detailLoading')}
+ </div>
+ ) : detailQuery.isError ? (
+ <div className="flex min-h-48 flex-col items-center justify-center gap-1 text-center">
+ <p className="font-medium">{t('detailLoadFailed')}</p>
+ <p className="max-w-md text-sm text-muted-foreground">
+ {getErrorMessage(detailQuery.error)}
+ </p>
+ </div>
+ ) : detailQuery.data ? (
+ <div className="grid gap-6">
+ <div className="grid grid-cols-2 gap-2">
+ <DetailMetric
+ icon={<UserRoundIcon />}
+ label={t('metrics.scope')}
+ value={t(`scopes.${detailQuery.data.scope}`)}
+ />
+ <DetailMetric
+ icon={<FileCode2Icon />}
+ label={t('metrics.files')}
+ value={String(detailQuery.data.files.length)}
+ />
+ </div>
+
+ {detailQuery.data.description ? (
+ <DetailSection title={t('sections.description')}>
+ <p className="leading-6 text-muted-foreground">
+ {detailQuery.data.description}
+ </p>
+ </DetailSection>
+ ) : null}
+
+ {detailQuery.data.overview ? (
+ <DetailSection title={t('sections.overview')}>
+ <pre className="whitespace-pre-wrap font-sans text-sm leading-6 text-muted-foreground">
+ {detailQuery.data.overview}
+ </pre>
+ </DetailSection>
+ ) : null}
+
+ {detailQuery.data.tags.length > 0 ||
+ detailQuery.data.allowedTools.length > 0 ? (
+ <div className="grid gap-4 sm:grid-cols-2">
+ <DetailTagList
+ title={t('sections.tags')}
+ values={detailQuery.data.tags}
+ empty={t('none')}
+ />
+ <DetailTagList
+ title={t('sections.allowedTools')}
+ values={detailQuery.data.allowedTools}
+ empty={t('none')}
+ />
+ </div>
+ ) : null}
+
+ <DetailSection title={t('sections.files')}>
+ {detailQuery.data.files.length > 0 ? (
+ <div className="overflow-hidden rounded-lg border">
+ {detailQuery.data.files.map((file) => (
+ <div
+ key={file.path}
+ className="flex items-center gap-2 border-b px-3 py-2 last:border-b-0"
+ >
+ <FileCode2Icon className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate">
+ {file.path}
+ </span>
+ {file.isDir ? (
+ <Badge variant="outline">{t('directory')}</Badge>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground">{t('none')}</p>
+ )}
+ </DetailSection>
+
+ {detailQuery.data.content ? (
+ <DetailSection title={t('sections.content')}>
+ <pre className="overflow-x-auto whitespace-pre-wrap rounded-lg border bg-muted/30 p-4 font-mono text-xs leading-5">
+ {detailQuery.data.content}
+ </pre>
+ </DetailSection>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ </SheetContent>
+ </Sheet>
+ </div>
+ )
+}
+
+function DetailMetric({
+ icon,
+ label,
+ value,
+}: {
+ icon: React.ReactNode
+ label: string
+ value: string
+}) {
+ return (
+ <div className="min-w-0 rounded-lg border bg-muted/20 p-3">
+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground [&_svg]:size-3.5">
+ {icon}
+ {label}
+ </div>
+ <p className="mt-1 truncate font-medium">{value}</p>
+ </div>
+ )
+}
+
+function DetailSection({
+ children,
+ title,
+}: {
+ children: React.ReactNode
+ title: string
+}) {
+ return (
+ <section className="grid gap-2">
+ <h3 className="text-sm font-semibold">{title}</h3>
+ {children}
+ </section>
+ )
+}
+
+function DetailTagList({
+ empty,
+ title,
+ values,
+}: {
+ empty: string
+ title: string
+ values: string[]
+}) {
+ return (
+ <DetailSection title={title}>
+ {values.length > 0 ? (
+ <div className="flex flex-wrap gap-1.5">
+ {values.map((value) => (
+ <Badge key={value} variant="secondary" className="font-normal">
+ {value}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground">{empty}</p>
+ )}
+ </DetailSection>
+ )
+}
diff --git a/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx b/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx
new file mode 100644
index 000000000..be6b5e707
--- /dev/null
+++ b/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx
@@ -0,0 +1,268 @@
+import * as React from 'react'
+import { useQuery } from '@tanstack/react-query'
+import {
+ ActivityIcon,
+ CalendarClockIcon,
+ CircleXIcon,
+ ClipboardListIcon,
+ FileJson2Icon,
+ FolderSearch2Icon,
+ Layers3Icon,
+ LoaderCircleIcon,
+ RefreshCwIcon,
+ TimerResetIcon,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import { Button } from '#/components/ui/button'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '#/components/ui/sheet'
+import { getOvResult, getTaskByTaskId } from '#/lib/ov-client'
+import { getTaskDate } from '#/routes/tasks/-lib/task-time'
+
+import {
+ hasTaskResult,
+ normalizeTaskRecord,
+ normalizeTaskStatus,
+} from '../-lib/task-record'
+import type { TaskRecord } from '../-lib/task-record'
+
+type TaskDetailSheetProps = {
+ identityScopeKey: string
+ onOpenChange: (open: boolean) => void
+ open: boolean
+ taskId: string | null
+}
+
+async function fetchTask(taskId: string): Promise<TaskRecord> {
+ const result = await getOvResult<unknown>(
+ getTaskByTaskId({
+ path: { task_id: taskId },
+ }),
+ )
+ const task = normalizeTaskRecord(result)
+ if (!task) {
+ throw new Error('Invalid task detail response')
+ }
+ return task
+}
+
+export function TaskDetailSheet({
+ identityScopeKey,
+ onOpenChange,
+ open,
+ taskId,
+}: TaskDetailSheetProps) {
+ const { i18n, t } = useTranslation('tasksPage')
+ const detailQuery = useQuery({
+ enabled: open && Boolean(taskId),
+ queryFn: () => fetchTask(taskId || ''),
+ queryKey: ['task-detail', identityScopeKey, taskId],
+ refetchInterval: (query) => {
+ const status = normalizeTaskStatus(query.state.data?.status)
+ return status === 'pending' || status === 'running' ? 3_000 : false
+ },
+ })
+ const task = detailQuery.data
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent className="gap-0 sm:max-w-xl">
+ <SheetHeader className="border-b px-6 py-5">
+ <div className="flex items-center gap-3 pr-10">
+ <div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary ring-1 ring-primary/15">
+ <ClipboardListIcon className="size-4.5" />
+ </div>
+ <div className="min-w-0">
+ <SheetTitle className="text-lg">{t('detail.title')}</SheetTitle>
+ <SheetDescription className="truncate font-mono text-xs">
+ {taskId}
+ </SheetDescription>
+ </div>
+ </div>
+ </SheetHeader>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
+ {detailQuery.isLoading ? (
+ <div className="flex min-h-48 items-center justify-center gap-2 text-muted-foreground">
+ <LoaderCircleIcon className="size-4 animate-spin" />
+ {t('detail.loading')}
+ </div>
+ ) : detailQuery.isError ? (
+ <div className="flex min-h-48 flex-col items-center justify-center gap-3 text-center">
+ <CircleXIcon className="size-8 text-destructive/70" />
+ <div className="grid gap-1">
+ <p className="font-medium">{t('detail.loadFailed')}</p>
+ <p className="max-w-md text-sm text-muted-foreground">
+ {detailQuery.error instanceof Error
+ ? detailQuery.error.message
+ : String(detailQuery.error)}
+ </p>
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => void detailQuery.refetch()}
+ >
+ <RefreshCwIcon />
+ {t('detail.retry')}
+ </Button>
+ </div>
+ ) : task ? (
+ <div className="grid gap-6">
+ <div className="grid grid-cols-2 gap-2">
+ <DetailField
+ icon={<ActivityIcon />}
+ label={t('detail.fields.status')}
+ value={t(`status.${normalizeTaskStatus(task.status)}`)}
+ />
+ <DetailField
+ icon={<Layers3Icon />}
+ label={t('detail.fields.type')}
+ value={task.task_type || '-'}
+ />
+ <DetailField
+ className="col-span-2"
+ icon={<TimerResetIcon />}
+ label={t('detail.fields.stage')}
+ value={task.stage || '-'}
+ />
+ <DetailField
+ className="col-span-2"
+ icon={<FolderSearch2Icon />}
+ label={t('detail.fields.resource')}
+ value={task.resource_id || '-'}
+ mono
+ />
+ <DetailField
+ icon={<CalendarClockIcon />}
+ label={t('detail.fields.createdAt')}
+ value={formatTaskTime(task, i18n.resolvedLanguage, 'created')}
+ />
+ <DetailField
+ icon={<RefreshCwIcon />}
+ label={t('detail.fields.updatedAt')}
+ value={formatTaskTime(task, i18n.resolvedLanguage, 'updated')}
+ />
+ </div>
+
+ {task.error ? (
+ <DetailSection title={t('detail.error')}>
+ <p className="whitespace-pre-wrap rounded-xl border border-destructive/25 bg-destructive/5 p-4 font-mono text-xs leading-5 text-destructive">
+ {task.error}
+ </p>
+ </DetailSection>
+ ) : null}
+
+ {hasTaskResult(task.result) ? (
+ <DetailSection title={t('detail.result')}>
+ <pre className="max-h-96 overflow-auto rounded-xl border bg-muted/30 p-4 font-mono text-xs leading-5">
+ {formatTaskResult(task.result)}
+ </pre>
+ </DetailSection>
+ ) : (
+ <div className="flex items-start gap-3 rounded-xl border border-dashed bg-muted/10 p-4">
+ <FileJson2Icon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <div className="grid gap-0.5">
+ <p className="text-sm font-medium">
+ {t('detail.noResult')}
+ </p>
+ <p className="text-xs leading-5 text-muted-foreground">
+ {t(
+ normalizeTaskStatus(task.status) === 'failed'
+ ? 'detail.noResultFailedDescription'
+ : 'detail.noResultDescription',
+ )}
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ ) : null}
+ </div>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function DetailField({
+ className,
+ icon,
+ label,
+ mono = false,
+ value,
+}: {
+ className?: string
+ icon: React.ReactNode
+ label: string
+ mono?: boolean
+ value: string
+}) {
+ return (
+ <div
+ className={`min-w-0 rounded-xl border bg-muted/15 p-3 ${className || ''}`}
+ >
+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground [&_svg]:size-3.5">
+ {icon}
+ {label}
+ </div>
+ <p
+ className={`mt-1.5 truncate text-sm font-medium ${mono ? 'font-mono text-xs' : ''}`}
+ title={value}
+ >
+ {value}
+ </p>
+ </div>
+ )
+}
+
+function DetailSection({
+ children,
+ title,
+}: {
+ children: React.ReactNode
+ title: string
+}) {
+ return (
+ <section className="grid gap-2.5">
+ <h3 className="text-sm font-semibold">{title}</h3>
+ {children}
+ </section>
+ )
+}
+
+function formatTaskTime(
+ task: TaskRecord,
+ language: string | undefined,
+ kind: 'created' | 'updated',
+): string {
+ const date =
+ kind === 'created'
+ ? getTaskDate(task)
+ : getTaskDate({
+ created_at: task.updated_at,
+ created_at_iso: task.updated_at_iso,
+ })
+ if (!date) return '-'
+ return new Intl.DateTimeFormat(language, {
+ dateStyle: 'medium',
+ timeStyle: 'medium',
+ }).format(date)
+}
+
+function formatTaskResult(result: unknown): string {
+ if (typeof result === 'string') {
+ return result
+ }
+ try {
+ return JSON.stringify(result, null, 2)
+ } catch {
+ return String(result)
+ }
+}
diff --git a/web-studio/src/routes/tasks/-lib/task-record.test.ts b/web-studio/src/routes/tasks/-lib/task-record.test.ts
new file mode 100644
index 000000000..9134fc8c9
--- /dev/null
+++ b/web-studio/src/routes/tasks/-lib/task-record.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ hasTaskResult,
+ normalizeTaskRecord,
+ normalizeTasks,
+} from './task-record'
+
+describe('task record helpers', () => {
+ it('normalizes task records from API payloads', () => {
+ expect(
+ normalizeTaskRecord({
+ stage: 'processing_queue',
+ status: 'running',
+ task_id: 'task-1',
+ }),
+ ).toMatchObject({
+ stage: 'processing_queue',
+ status: 'running',
+ task_id: 'task-1',
+ })
+ })
+
+ it('drops invalid list entries', () => {
+ expect(normalizeTasks([null, 'invalid', { task_id: 'task-1' }])).toEqual([
+ { task_id: 'task-1' },
+ ])
+ })
+
+ it('only reports meaningful results', () => {
+ expect(hasTaskResult(undefined)).toBe(false)
+ expect(hasTaskResult({})).toBe(false)
+ expect(hasTaskResult([])).toBe(false)
+ expect(hasTaskResult({ archive_uri: 'viking://archive' })).toBe(true)
+ })
+})
diff --git a/web-studio/src/routes/tasks/-lib/task-record.ts b/web-studio/src/routes/tasks/-lib/task-record.ts
new file mode 100644
index 000000000..86d5d42ad
--- /dev/null
+++ b/web-studio/src/routes/tasks/-lib/task-record.ts
@@ -0,0 +1,61 @@
+import type { TaskTimestamp } from './task-time'
+
+export type TaskStatus =
+ | 'completed'
+ | 'failed'
+ | 'pending'
+ | 'running'
+ | 'unknown'
+
+export type TaskRecord = TaskTimestamp & {
+ error?: string | null
+ resource_id?: string | null
+ result?: unknown
+ stage?: string | null
+ status?: string
+ task_id?: string
+ task_type?: string
+ updated_at?: number | string
+ updated_at_iso?: string
+}
+
+export function normalizeTaskRecord(value: unknown): TaskRecord | undefined {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ return undefined
+ }
+ return value as TaskRecord
+}
+
+export function normalizeTasks(value: unknown): TaskRecord[] {
+ if (!Array.isArray(value)) {
+ return []
+ }
+ return value
+ .map(normalizeTaskRecord)
+ .filter((item): item is TaskRecord => Boolean(item))
+}
+
+export function normalizeTaskStatus(status: string | undefined): TaskStatus {
+ if (
+ status === 'completed' ||
+ status === 'failed' ||
+ status === 'pending' ||
+ status === 'running'
+ ) {
+ return status
+ }
+ return 'unknown'
+}
+
+export function hasTaskResult(result: unknown): boolean {
+ if (result === null || result === undefined) {
+ return false
+ }
+ if (Array.isArray(result)) {
+ return result.length > 0
+ }
+ if (typeof result === 'object') {
+ return Object.keys(result).length > 0
+ }
+ return true
+}
diff --git a/web-studio/src/routes/tasks/-lib/task-time.test.ts b/web-studio/src/routes/tasks/-lib/task-time.test.ts
new file mode 100644
index 000000000..aadd49c79
--- /dev/null
+++ b/web-studio/src/routes/tasks/-lib/task-time.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest'
+
+import { getTaskDate } from './task-time'
+
+describe('getTaskDate', () => {
+ it('prefers the ISO timestamp returned by the task API', () => {
+ const date = getTaskDate({
+ created_at: 1_774_516_075,
+ created_at_iso: '2026-03-26T07:47:55+00:00',
+ })
+
+ expect(date?.toISOString()).toBe('2026-03-26T07:47:55.000Z')
+ })
+
+ it('converts legacy epoch seconds to milliseconds', () => {
+ const date = getTaskDate({
+ created_at: 1_774_516_075,
+ })
+
+ expect(date?.getUTCFullYear()).toBe(2026)
+ })
+})
diff --git a/web-studio/src/routes/tasks/-lib/task-time.ts b/web-studio/src/routes/tasks/-lib/task-time.ts
new file mode 100644
index 000000000..b948ab193
--- /dev/null
+++ b/web-studio/src/routes/tasks/-lib/task-time.ts
@@ -0,0 +1,30 @@
+export type TaskTimestamp = {
+ created_at?: number | string
+ created_at_iso?: string
+ updated_at?: number | string
+ updated_at_iso?: string
+}
+
+export function getTaskDate(task: TaskTimestamp): Date | undefined {
+ const value =
+ task.created_at_iso ??
+ task.updated_at_iso ??
+ task.created_at ??
+ task.updated_at
+ if (value === undefined) return undefined
+
+ const numericValue =
+ typeof value === 'number'
+ ? value
+ : value.trim() !== '' && Number.isFinite(Number(value))
+ ? Number(value)
+ : undefined
+ const normalizedValue =
+ numericValue === undefined
+ ? value
+ : Math.abs(numericValue) < 1_000_000_000_000
+ ? numericValue * 1_000
+ : numericValue
+ const date = new Date(normalizedValue)
+ return Number.isNaN(date.getTime()) ? undefined : date
+}
diff --git a/web-studio/src/routes/tasks/route.tsx b/web-studio/src/routes/tasks/route.tsx
new file mode 100644
index 000000000..6f26b5d23
--- /dev/null
+++ b/web-studio/src/routes/tasks/route.tsx
@@ -0,0 +1,457 @@
+import * as React from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { createFileRoute } from '@tanstack/react-router'
+import {
+ CheckCircle2Icon,
+ CircleDashedIcon,
+ CircleXIcon,
+ ChevronRightIcon,
+ ClipboardListIcon,
+ LoaderCircleIcon,
+ RefreshCwIcon,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import { Badge } from '#/components/ui/badge'
+import { Button } from '#/components/ui/button'
+import { Card } from '#/components/ui/card'
+import {
+ Pagination,
+ PaginationContent,
+ PaginationItem,
+ PaginationNext,
+ PaginationPrevious,
+} from '#/components/ui/pagination'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '#/components/ui/select'
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '#/components/ui/table'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { getOvResult, getTasks } from '#/lib/ov-client'
+import { cn } from '#/lib/utils'
+import { TaskDetailSheet } from '#/routes/tasks/-components/task-detail-sheet'
+import {
+ normalizeTasks,
+ normalizeTaskStatus,
+} from '#/routes/tasks/-lib/task-record'
+import type { TaskRecord, TaskStatus } from '#/routes/tasks/-lib/task-record'
+import { getTaskDate } from '#/routes/tasks/-lib/task-time'
+
+export const Route = createFileRoute('/tasks')({
+ component: TasksRoute,
+})
+
+type TaskStatusFilter = Exclude<TaskStatus, 'unknown'> | 'all'
+
+type TaskTypeFilter =
+ | 'add_resource'
+ | 'add_skill'
+ | 'admin_reindex'
+ | 'connector_import'
+ | 'legacy_cleanup'
+ | 'legacy_migration'
+ | 'session_commit'
+ | 'snapshot_restore_reindex'
+ | 'all'
+
+const DEFAULT_PAGE_SIZE = 20
+const MAX_TASKS = 200
+const PAGE_SIZE_OPTIONS = [20, 50, 100] as const
+const TASK_TYPE_OPTIONS: Exclude<TaskTypeFilter, 'all'>[] = [
+ 'session_commit',
+ 'add_resource',
+ 'add_skill',
+ 'connector_import',
+ 'admin_reindex',
+ 'snapshot_restore_reindex',
+ 'legacy_migration',
+ 'legacy_cleanup',
+]
+const TASK_STATUS_OPTIONS: Exclude<TaskStatusFilter, 'all'>[] = [
+ 'pending',
+ 'running',
+ 'completed',
+ 'failed',
+]
+
+async function fetchTasks(
+ taskType: TaskTypeFilter,
+ status: TaskStatusFilter,
+): Promise<TaskRecord[]> {
+ const query = {
+ limit: MAX_TASKS,
+ status: status === 'all' ? undefined : status,
+ task_type: taskType === 'all' ? undefined : taskType,
+ }
+ const result = await getOvResult<unknown>(
+ getTasks({
+ query,
+ }),
+ )
+ return normalizeTasks(result)
+}
+
+function TasksRoute() {
+ const { i18n, t } = useTranslation('tasksPage')
+ const { identityScopeKey } = useAppConnection()
+ const [page, setPage] = React.useState(1)
+ const [pageSize, setPageSize] = React.useState(DEFAULT_PAGE_SIZE)
+ const [taskType, setTaskType] = React.useState<TaskTypeFilter>('all')
+ const [statusFilter, setStatusFilter] =
+ React.useState<TaskStatusFilter>('all')
+ const [selectedTaskId, setSelectedTaskId] = React.useState<string | null>(
+ null,
+ )
+ const tasksQuery = useQuery({
+ queryFn: () => fetchTasks(taskType, statusFilter),
+ queryKey: ['tasks', identityScopeKey, taskType, statusFilter],
+ refetchInterval: 10_000,
+ })
+ const allTasks = tasksQuery.data ?? []
+ const pageOffset = (page - 1) * pageSize
+ const tasks = allTasks.slice(pageOffset, pageOffset + pageSize)
+ const totalPages = Math.max(1, Math.ceil(allTasks.length / pageSize))
+ const hasNext = page < totalPages
+ const hasActiveFilters = taskType !== 'all' || statusFilter !== 'all'
+
+ React.useEffect(() => {
+ if (page > totalPages) {
+ setPage(totalPages)
+ }
+ }, [page, totalPages])
+
+ const formatTime = (task: TaskRecord) => {
+ const date = getTaskDate(task)
+ if (!date) return '-'
+ return new Intl.DateTimeFormat(i18n.resolvedLanguage, {
+ dateStyle: 'medium',
+ timeStyle: 'medium',
+ }).format(date)
+ }
+
+ const renderStatus = (rawStatus: string | undefined) => {
+ const status = normalizeTaskStatus(rawStatus)
+ const Icon =
+ status === 'completed'
+ ? CheckCircle2Icon
+ : status === 'failed'
+ ? CircleXIcon
+ : status === 'running'
+ ? LoaderCircleIcon
+ : CircleDashedIcon
+
+ return (
+ <Badge
+ variant={
+ status === 'failed'
+ ? 'destructive'
+ : status === 'completed'
+ ? 'secondary'
+ : 'outline'
+ }
+ className="gap-1 font-normal"
+ >
+ <Icon className={status === 'running' ? 'animate-spin' : undefined} />
+ {t(`status.${status}`)}
+ </Badge>
+ )
+ }
+
+ return (
+ <div className="flex w-full min-w-0 flex-col gap-5">
+ <header className="flex flex-wrap items-start justify-between gap-3">
+ <div className="grid gap-1.5">
+ <h1 className="text-2xl font-semibold tracking-tight">
+ {t('title')}
+ </h1>
+ <p className="max-w-3xl text-sm leading-6 text-muted-foreground">
+ {t('description')}
+ </p>
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={tasksQuery.isFetching}
+ onClick={() => void tasksQuery.refetch()}
+ >
+ <RefreshCwIcon
+ className={tasksQuery.isFetching ? 'animate-spin' : undefined}
+ />
+ {t('refresh')}
+ </Button>
+ </header>
+
+ <div className="flex flex-wrap items-center gap-2 rounded-xl border bg-card/60 p-2 shadow-xs">
+ <span className="px-1 text-xs font-medium text-muted-foreground">
+ {t('filters.label')}
+ </span>
+ <Select
+ value={taskType}
+ onValueChange={(value) => {
+ setTaskType(value as TaskTypeFilter)
+ setPage(1)
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ className="min-w-40 bg-background"
+ aria-label={t('filters.type')}
+ >
+ <SelectValue>
+ {taskType === 'all'
+ ? t('filters.allTypes')
+ : t(`types.${taskType}`)}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{t('filters.allTypes')}</SelectItem>
+ {TASK_TYPE_OPTIONS.map((option) => (
+ <SelectItem key={option} value={option}>
+ {t(`types.${option}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select
+ value={statusFilter}
+ onValueChange={(value) => {
+ setStatusFilter(value as TaskStatusFilter)
+ setPage(1)
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ className="min-w-32 bg-background"
+ aria-label={t('filters.status')}
+ >
+ <SelectValue>
+ {statusFilter === 'all'
+ ? t('filters.allStatuses')
+ : t(`status.${statusFilter}`)}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{t('filters.allStatuses')}</SelectItem>
+ {TASK_STATUS_OPTIONS.map((option) => (
+ <SelectItem key={option} value={option}>
+ {t(`status.${option}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {hasActiveFilters ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={() => {
+ setTaskType('all')
+ setStatusFilter('all')
+ setPage(1)
+ }}
+ >
+ {t('filters.clear')}
+ </Button>
+ ) : null}
+ </div>
+
+ {tasksQuery.isLoading ? (
+ <Card className="min-h-56 items-center justify-center">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <LoaderCircleIcon className="size-4 animate-spin" />
+ {t('loading')}
+ </div>
+ </Card>
+ ) : tasksQuery.isError ? (
+ <Card className="min-h-56 items-center justify-center px-6 text-center">
+ <CircleXIcon className="size-8 text-destructive/70" />
+ <div className="grid gap-1">
+ <p className="font-medium">{t('loadFailed')}</p>
+ <p className="max-w-xl text-sm text-muted-foreground">
+ {tasksQuery.error instanceof Error
+ ? tasksQuery.error.message
+ : String(tasksQuery.error)}
+ </p>
+ </div>
+ </Card>
+ ) : tasks.length === 0 ? (
+ <Card className="min-h-56 items-center justify-center px-6 text-center">
+ <div className="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
+ <ClipboardListIcon className="size-5" />
+ </div>
+ <div className="grid max-w-md gap-1">
+ <p className="font-medium">
+ {t(hasActiveFilters ? 'emptyFiltered' : 'empty')}
+ </p>
+ <p className="text-sm text-muted-foreground">
+ {t(
+ hasActiveFilters
+ ? 'emptyFilteredDescription'
+ : 'emptyDescription',
+ )}
+ </p>
+ </div>
+ </Card>
+ ) : (
+ <Card className="gap-0 overflow-hidden py-0">
+ <div className="overflow-x-auto">
+ <Table>
+ <TableHeader>
+ <TableRow className="bg-muted/20 hover:bg-muted/20">
+ <TableHead>{t('table.task')}</TableHead>
+ <TableHead>{t('table.type')}</TableHead>
+ <TableHead>{t('table.resource')}</TableHead>
+ <TableHead>{t('table.status')}</TableHead>
+ <TableHead className="text-right">
+ {t('table.createdAt')}
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {tasks.map((task, index) => {
+ const taskId = task.task_id
+ return (
+ <TableRow
+ key={taskId || String(index)}
+ tabIndex={taskId ? 0 : undefined}
+ aria-label={
+ taskId ? t('detail.openLabel', { taskId }) : undefined
+ }
+ className={cn(
+ taskId &&
+ 'cursor-pointer outline-none hover:bg-muted/35 focus-visible:bg-muted/35 focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-inset',
+ )}
+ onClick={() => {
+ if (taskId) setSelectedTaskId(taskId)
+ }}
+ onKeyDown={(event) => {
+ if (
+ taskId &&
+ (event.key === 'Enter' || event.key === ' ')
+ ) {
+ event.preventDefault()
+ setSelectedTaskId(taskId)
+ }
+ }}
+ >
+ <TableCell>
+ <span className="flex items-center gap-2">
+ <code className="min-w-0 truncate text-xs">
+ {taskId || `#${pageOffset + index + 1}`}
+ </code>
+ {taskId ? (
+ <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" />
+ ) : null}
+ </span>
+ </TableCell>
+ <TableCell className="font-medium">
+ {task.task_type || '-'}
+ </TableCell>
+ <TableCell className="max-w-72 truncate text-muted-foreground">
+ {task.resource_id || '-'}
+ </TableCell>
+ <TableCell>{renderStatus(task.status)}</TableCell>
+ <TableCell className="whitespace-nowrap text-right text-muted-foreground">
+ {formatTime(task)}
+ </TableCell>
+ </TableRow>
+ )
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ <div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex flex-col items-center gap-1.5 sm:items-start">
+ <div className="flex items-center justify-center gap-3 sm:justify-start">
+ <p className="text-sm text-muted-foreground">
+ {t('pagination.page', { page })}
+ </p>
+ <Select
+ value={String(pageSize)}
+ onValueChange={(value) => {
+ setPageSize(Number(value))
+ setPage(1)
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ aria-label={t('pagination.pageSize')}
+ >
+ <SelectValue>
+ {t('pagination.pageSizeValue', { count: pageSize })}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {PAGE_SIZE_OPTIONS.map((option) => (
+ <SelectItem key={option} value={String(option)}>
+ {t('pagination.pageSizeValue', { count: option })}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t('pagination.scope', {
+ count: allTasks.length,
+ limit: MAX_TASKS,
+ })}
+ </p>
+ </div>
+ <Pagination className="mx-0 w-auto justify-center sm:justify-end">
+ <PaginationContent>
+ <PaginationItem>
+ <PaginationPrevious
+ href="#"
+ text={t('pagination.previous')}
+ aria-disabled={page <= 1}
+ className={cn(
+ page <= 1 && 'pointer-events-none opacity-50',
+ )}
+ onClick={(event) => {
+ event.preventDefault()
+ if (page > 1) setPage((current) => current - 1)
+ }}
+ />
+ </PaginationItem>
+ <PaginationItem>
+ <PaginationNext
+ href="#"
+ text={t('pagination.next')}
+ aria-disabled={!hasNext}
+ className={cn(!hasNext && 'pointer-events-none opacity-50')}
+ onClick={(event) => {
+ event.preventDefault()
+ if (hasNext) setPage((current) => current + 1)
+ }}
+ />
+ </PaginationItem>
+ </PaginationContent>
+ </Pagination>
+ </div>
+ </Card>
+ )}
+
+ <TaskDetailSheet
+ identityScopeKey={identityScopeKey}
+ open={Boolean(selectedTaskId)}
+ taskId={selectedTaskId}
+ onOpenChange={(open) => {
+ if (!open) setSelectedTaskId(null)
+ }}
+ />
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/users/route.tsx b/web-studio/src/routes/users/route.tsx
index 1b12f525f..dfd4e5bcd 100644
--- a/web-studio/src/routes/users/route.tsx
+++ b/web-studio/src/routes/users/route.tsx
@@ -10,6 +10,7 @@ import {
RefreshCwIcon,
RotateCwIcon,
ShieldAlertIcon,
+ Trash2Icon,
UsersRoundIcon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
@@ -48,6 +49,11 @@ import {
TableHeader,
TableRow,
} from '#/components/ui/table'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '#/components/ui/tooltip'
import {
AlertDialog,
AlertDialogAction,
@@ -63,6 +69,7 @@ import {
createAdminUser,
fetchAdminUsers,
regenerateAdminUserKey,
+ removeAdminUser,
updateAdminUserRole,
} from '#/lib/admin'
import type {
@@ -119,6 +126,8 @@ function UserManagementRoute() {
const [addUserOpen, setAddUserOpen] = React.useState(false)
const [pendingRegenerateUser, setPendingRegenerateUser] =
React.useState<AdminUser | null>(null)
+ const [pendingRemoveUser, setPendingRemoveUser] =
+ React.useState<AdminUser | null>(null)
const [pendingRoleChange, setPendingRoleChange] =
React.useState<UpdateUserRoleInput | null>(null)
const [switchingIdentityKey, setSwitchingIdentityKey] = React.useState('')
@@ -223,6 +232,18 @@ function UserManagementRoute() {
},
})
+ const removeUser = useMutation({
+ mutationFn: (user: AdminUser) =>
+ removeAdminUser(adminConnection, user.accountId, user.userId),
+ onError: (error) => toast.error(getErrorMessage(error)),
+ onSuccess: async (_, user) => {
+ setPendingRemoveUser(null)
+ toast.success(t('toast.userRemoved', { user: user.userId }))
+ await queryClient.invalidateQueries({ queryKey: ['managed-users'] })
+ await queryClient.invalidateQueries({ queryKey: ['account-switcher'] })
+ },
+ })
+
async function copyKey(value: string | undefined): Promise<void> {
if (!value) {
return
@@ -291,6 +312,9 @@ function UserManagementRoute() {
}
const users = usersQuery.data ?? []
+ const managerCount = users.filter(
+ (user) => user.role === 'admin' || user.role === 'root',
+ ).length
const visibleKeys = users.filter(
(user) => user.apiKey || user.keyPrefix,
).length
@@ -415,6 +439,16 @@ function UserManagementRoute() {
user.accountId === connection.accountId &&
user.userId === connection.userId
const isSwitching = switchingIdentityKey === identityKey
+ const isLastManager =
+ (user.role === 'admin' || user.role === 'root') &&
+ managerCount <= 1
+ const removeDisabled =
+ isCurrentIdentity || isLastManager || removeUser.isPending
+ const removeDisabledReason = isCurrentIdentity
+ ? t('management.cannotRemoveCurrentIdentity')
+ : isLastManager
+ ? t('management.cannotRemoveLastManager')
+ : t('actions.removeUser', { user: user.userId })
return (
<TableRow
@@ -487,25 +521,60 @@ function UserManagementRoute() {
)}
</TableCell>
<TableCell>
- <div className="flex min-w-0 items-center gap-2">
+ <div className="flex min-w-0 items-center gap-1">
<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>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t('actions.copy')}
+ onClick={() => void copyKey(user.apiKey)}
+ />
+ }
+ >
+ <CopyIcon />
+ </TooltipTrigger>
+ <TooltipContent>
+ {t('actions.copy')}
+ </TooltipContent>
+ </Tooltip>
) : null}
+ <div className="ml-1 flex items-center border-l border-border/70 pl-1.5">
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t('actions.regenerate')}
+ onClick={() =>
+ setPendingRegenerateUser(user)
+ }
+ disabled={
+ regenerateKey.isPending ||
+ Boolean(switchingIdentityKey)
+ }
+ />
+ }
+ >
+ <RotateCwIcon />
+ </TooltipTrigger>
+ <TooltipContent>
+ {t('actions.regenerate')}
+ </TooltipContent>
+ </Tooltip>
+ </div>
</div>
</TableCell>
<TableCell>
- <div className="flex justify-end gap-2">
+ <div className="flex items-center justify-end gap-1">
{user.apiKey && !isCurrentIdentity ? (
<Button
type="button"
@@ -521,20 +590,41 @@ function UserManagementRoute() {
)}
{t('actions.switchIdentity')}
</Button>
+ ) : isCurrentIdentity ? (
+ <span
+ aria-hidden="true"
+ className="px-3 text-muted-foreground/45"
+ >
+ —
+ </span>
) : null}
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => setPendingRegenerateUser(user)}
- disabled={
- regenerateKey.isPending ||
- Boolean(switchingIdentityKey)
- }
- >
- <RotateCwIcon />
- {t('actions.regenerate')}
- </Button>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ className="inline-flex"
+ title={removeDisabledReason}
+ />
+ }
+ >
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ disabled={removeDisabled}
+ className="text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
+ aria-label={t('actions.removeUser', {
+ user: user.userId,
+ })}
+ onClick={() => setPendingRemoveUser(user)}
+ >
+ <Trash2Icon />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {removeDisabledReason}
+ </TooltipContent>
+ </Tooltip>
</div>
</TableCell>
</TableRow>
@@ -632,6 +722,49 @@ function UserManagementRoute() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
+
+ <AlertDialog
+ open={Boolean(pendingRemoveUser)}
+ onOpenChange={(open) => {
+ if (!open && !removeUser.isPending) {
+ setPendingRemoveUser(null)
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t('dialogs.removeUser.title')}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t('dialogs.removeUser.description', {
+ account: pendingRemoveUser?.accountId,
+ user: pendingRemoveUser?.userId,
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={removeUser.isPending}>
+ {t('actions.cancel')}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ disabled={removeUser.isPending}
+ onClick={(event) => {
+ event.preventDefault()
+ if (pendingRemoveUser) {
+ removeUser.mutate(pendingRemoveUser)
+ }
+ }}
+ >
+ {removeUser.isPending ? (
+ <LoaderCircleIcon className="animate-spin" />
+ ) : (
+ <Trash2Icon />
+ )}
+ {t('actions.confirmRemoveUser')}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
)
}
diff --git a/web-studio/types/ov-server/api/v1/sessions.ts b/web-studio/types/ov-server/api/v1/sessions.ts
index 8518e8766..59090149e 100644
--- a/web-studio/types/ov-server/api/v1/sessions.ts
+++ b/web-studio/types/ov-server/api/v1/sessions.ts
@@ -29,7 +29,9 @@ export type SessionDetail = {
message_count: number
pending_tokens: number
session_id: string
+ total_message_count?: number
updated_at: string
+ uri?: string
user: UserIdentifier
}
@@ -37,6 +39,13 @@ export type SessionContextResult = {
messages?: unknown[]
}
+export type SessionArchiveResult = {
+ abstract?: string
+ archive_id: string
+ messages?: unknown[]
+ overview?: string
+}
+
export type SessionCreatedResult = {
session_id: string
user: UserIdentifier