Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(web-studio): share user skills and switch users (#4706)
yufengc25ed5147cd0
diff --git a/web-studio/src/components/current-user-menu.interaction.test.tsx b/web-studio/src/components/current-user-menu.interaction.test.tsxindex 080e6290a..21f24bb75 100644--- a/web-studio/src/components/current-user-menu.interaction.test.tsx+++ b/web-studio/src/components/current-user-menu.interaction.test.tsx@@ -8,6 +8,7 @@ import {screen,waitFor,} from '@testing-library/react'+import userEvent from '@testing-library/user-event'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { CurrentUserMenu } from './current-user-menu'@@ -24,6 +25,8 @@ const connectionMocks = vi.hoisted(() => ({baseUrl: 'http://localhost:1933',userId: 'alice',},+ connectionRole: 'root',+ isConnectionRoleLoading: false,serverMode: 'trusted',switchIdentity: vi.fn(),}))@@ -64,6 +67,8 @@ function renderMenu() {beforeEach(() => {connectionMocks.connection.adminApiKey = 'root-key'+ connectionMocks.connectionRole = 'root'+ connectionMocks.isConnectionRoleLoading = falseconnectionMocks.serverMode = 'trusted'connectionMocks.switchIdentity.mockResolvedValue(undefined)adminMocks.fetchAdminUsers.mockResolvedValue([@@ -93,8 +98,13 @@ describe('CurrentUserMenu', () => {screen.getByRole('button', { name: 'header.currentUser.openMenu' }),)- const bob = await screen.findByRole('button', { name: 'bob' })- fireEvent.click(bob)+ const selector = await screen.findByRole('combobox', {+ name: 'header.currentUser.switchUser',+ })+ expect(screen.queryByRole('option', { name: 'bob' })).toBeNull()+ await userEvent.click(selector)+ const bob = await screen.findByRole('option', { name: 'bob' })+ await userEvent.click(bob)await waitFor(() => {expect(connectionMocks.switchIdentity).toHaveBeenCalledWith({@@ -109,8 +119,49 @@ describe('CurrentUserMenu', () => {)})- it('keeps non-trusted user menus read-only', () => {+ it('switches API-key identities when management access exposes a user key', async () => {connectionMocks.serverMode = 'api_key'+ adminMocks.fetchAdminUsers.mockResolvedValue([+ {+ accountId: 'account-a',+ apiKey: 'alice-key',+ role: 'admin',+ userId: 'alice',+ },+ {+ accountId: 'account-a',+ apiKey: 'bob-key',+ role: 'user',+ userId: 'bob',+ },+ ])+ renderMenu()++ fireEvent.click(+ screen.getByRole('button', { name: 'header.currentUser.openMenu' }),+ )++ const selector = await screen.findByRole('combobox', {+ name: 'header.currentUser.switchUser',+ })+ expect(screen.queryByRole('option', { name: 'bob' })).toBeNull()+ await userEvent.click(selector)+ const bob = await screen.findByRole('option', { name: 'bob' })+ await userEvent.click(bob)++ await waitFor(() => {+ expect(connectionMocks.switchIdentity).toHaveBeenCalledWith({+ accountId: 'account-a',+ allowLegacyIdentityFallback: true,+ apiKey: 'bob-key',+ userId: 'bob',+ })+ })+ })++ it('keeps ordinary API-key user menus read-only', () => {+ connectionMocks.serverMode = 'api_key'+ connectionMocks.connectionRole = 'user'renderMenu()fireEvent.click(@@ -121,6 +172,38 @@ describe('CurrentUserMenu', () => {expect(adminMocks.fetchAdminUsers).not.toHaveBeenCalled()})+ it('disables API-key identities whose secret is unavailable', async () => {+ connectionMocks.serverMode = 'api_key'+ adminMocks.fetchAdminUsers.mockResolvedValue([+ {+ accountId: 'account-a',+ apiKey: 'alice-key',+ role: 'admin',+ userId: 'alice',+ },+ {+ accountId: 'account-a',+ keyPrefix: 'ovk_bob',+ role: 'user',+ userId: 'bob',+ },+ ])+ renderMenu()++ fireEvent.click(+ screen.getByRole('button', { name: 'header.currentUser.openMenu' }),+ )++ const selector = await screen.findByRole('combobox', {+ name: 'header.currentUser.switchUser',+ })+ expect(screen.queryByRole('option', { name: 'bob' })).toBeNull()+ await userEvent.click(selector)+ const bob = await screen.findByRole('option', { name: 'bob' })+ expect(bob.getAttribute('aria-disabled')).toBe('true')+ expect(screen.getByText('header.currentUser.keyUnavailable')).toBeTruthy()+ })+it('accepts a user ID when trusted mode has no user directory', async () => {connectionMocks.connection.adminApiKey = ''renderMenu()diff --git a/web-studio/src/components/current-user-menu.tsx b/web-studio/src/components/current-user-menu.tsxindex 13a3c9857..c3e44887d 100644--- a/web-studio/src/components/current-user-menu.tsx+++ b/web-studio/src/components/current-user-menu.tsx@@ -2,7 +2,6 @@ import * as React from 'react'import { useQuery } from '@tanstack/react-query'import {Building2Icon,- CheckIcon,ChevronDownIcon,LoaderCircleIcon,UserRoundIcon,@@ -15,9 +14,17 @@ import {PopoverContent,PopoverTrigger,} from '#/components/ui/popover'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '#/components/ui/select'import { useAppConnection } from '#/hooks/use-app-connection'import { fetchAdminUsers } from '#/lib/admin'import type { AdminConnection } from '#/lib/admin'+import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'export function getUserInitial(userId: string): string {const normalizedUserId = userId.trim()@@ -26,15 +33,28 @@ export function getUserInitial(userId: string): string {export function CurrentUserMenu() {const { t } = useTranslation('appShell')- const { connection, serverMode, switchIdentity } = useAppConnection()+ const {+ connection,+ connectionRole,+ isConnectionRoleLoading,+ serverMode,+ switchIdentity,+ } = useAppConnection()const [open, setOpen] = React.useState(false)const [manualUserId, setManualUserId] = React.useState('')const [switchingUserId, setSwitchingUserId] = React.useState('')const { accountId, userId } = connectionconst accountLabel = accountId || t('header.currentUser.unset')const userLabel = userId || t('header.currentUser.unset')- const canSwitchUser = serverMode === 'trusted' && Boolean(accountId)- const canListUsers = Boolean(connection.adminApiKey)+ const { canManageUsers } = resolveStudioManagementCapabilities({+ hasControlCredential: Boolean(connection.adminApiKey.trim()),+ isRoleLoading: isConnectionRoleLoading,+ role: connectionRole,+ serverMode,+ })+ const canSwitchUser =+ Boolean(accountId) && (serverMode === 'trusted' || canManageUsers)+ const canListUsers = canManageUsersconst manualTargetUserId = manualUserId.trim()const adminConnection = React.useMemo<AdminConnection>(() => ({@@ -57,7 +77,10 @@ export function CurrentUserMenu() {retry: false,})- async function selectUser(nextUserId: string): Promise<void> {+ async function selectUser(+ nextUserId: string,+ nextApiKey = '',+ ): Promise<void> {const normalizedUserId = nextUserId.trim()if (!normalizedUserId || normalizedUserId === userId) {return@@ -68,7 +91,7 @@ export function CurrentUserMenu() {await switchIdentity({accountId,allowLegacyIdentityFallback: true,- apiKey: '',+ apiKey: serverMode === 'trusted' ? '' : nextApiKey,userId: normalizedUserId,})setManualUserId('')@@ -202,33 +225,49 @@ export function CurrentUserMenu() {</button></div>) : usersQuery.data?.length ? (- usersQuery.data.map((user) => {- const current = user.userId === userId- const switching = switchingUserId === user.userId- return (- <button- key={user.userId}- type="button"- aria-current={current ? 'true' : undefined}- aria-label={user.userId}- disabled={current || Boolean(switchingUserId)}- className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left transition-colors hover:bg-accent disabled:cursor-default disabled:opacity-70"- onClick={() => void selectUser(user.userId)}+ <div className="px-2.5 pb-2">+ <Select+ value={userId}+ onValueChange={(nextUserId) => {+ const user = usersQuery.data.find(+ (item) => item.userId === nextUserId,+ )+ if (user) void selectUser(user.userId, user.apiKey)+ }}+ >+ <SelectTrigger+ aria-label={t('header.currentUser.switchUser')}+ className="w-full"+ disabled={Boolean(switchingUserId)}>- <span className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-background text-xs font-semibold">- {getUserInitial(user.userId)}- </span>- <span className="min-w-0 flex-1 truncate text-sm font-medium">- {user.userId}- </span>- {switching ? (+ {switchingUserId ? (<LoaderCircleIcon className="size-3.5 animate-spin" />- ) : current ? (- <CheckIcon className="size-3.5 text-primary" />) : null}- </button>- )- })+ <SelectValue>{userLabel}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {usersQuery.data.map((user) => {+ const canUseIdentity =+ serverMode === 'trusted' || Boolean(user.apiKey)+ return (+ <SelectItem+ key={user.userId}+ value={user.userId}+ aria-label={user.userId}+ disabled={!canUseIdentity}+ >+ {user.userId}+ {!canUseIdentity ? (+ <span className="text-[10px] text-muted-foreground">+ {t('header.currentUser.keyUnavailable')}+ </span>+ ) : null}+ </SelectItem>+ )+ })}+ </SelectContent>+ </Select>+ </div>) : (<p className="px-2.5 py-4 text-center text-xs text-muted-foreground">{t('header.currentUser.noUsers')}diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.tsindex c50bae058..9441a2aae 100644--- a/web-studio/src/i18n/locales/en/workspace.ts+++ b/web-studio/src/i18n/locales/en/workspace.ts@@ -12,6 +12,7 @@ const workspace = {currentUser: {account: 'Account',accountSummary: 'Account · {{account}}',+ keyUnavailable: 'Key unavailable',loadingUsers: 'Loading users',loadUsersFailed: 'Failed to load users',noUsers: 'No users in this account',@@ -220,6 +221,11 @@ const workspace = {'Could not connect to the OpenViking service. Check the server URL and connection status.',connectionSettings: 'Open connection settings',detail: 'Details',+ share: 'Share',+ sharing: 'Sharing...',+ shareSkill: 'Set {{name}} as a shared skill',+ shareFailed: 'Could not share skill',+ shareSuccess: '{{name}} is now a shared skill',openPlayground: 'Open in Playground',viewDetail: 'View {{name}} details',detailLoading: 'Loading skill details...',diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.tsindex da7df1e16..124e90c96 100644--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts@@ -12,6 +12,7 @@ const workspace = {currentUser: {account: '账号',accountSummary: '账号 · {{account}}',+ keyUnavailable: '密钥不可用',loadingUsers: '正在加载用户',loadUsersFailed: '用户列表加载失败',noUsers: '当前账号暂无用户',@@ -215,6 +216,11 @@ const workspace = {networkError: '无法连接 OpenViking 服务,请检查服务地址和连接状态。',connectionSettings: '打开连接设置',detail: '详情',+ share: '共享',+ sharing: '共享中...',+ shareSkill: '将 {{name}} 设为共享技能',+ shareFailed: '共享技能失败',+ shareSuccess: '已将 {{name}} 设为共享技能',openPlayground: '在工作台中打开',viewDetail: '查看 {{name}} 详情',detailLoading: '正在加载技能详情...',diff --git a/web-studio/src/routes/skills/-components/skill-card.test.tsx b/web-studio/src/routes/skills/-components/skill-card.test.tsxnew file mode 100644index 000000000..08f1a962a--- /dev/null+++ b/web-studio/src/routes/skills/-components/skill-card.test.tsx@@ -0,0 +1,97 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { SkillCard } from './skill-card'++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: { name?: string }) => {+ if (key === 'scopes.user') return '用户技能'+ if (key === 'scopes.agent') return '共享技能'+ if (key === 'share') return '共享'+ if (key === 'sharing') return '共享中...'+ if (key === 'shareSkill') return `将 ${values?.name} 设为共享技能`+ if (key === 'viewDetail') return `查看 ${values?.name} 详情`+ if (key === 'detail') return '详情'+ return key+ },+ }),+}))++afterEach(cleanup)++describe('SkillCard', () => {+ const userSkill = {+ description: 'A private skill',+ name: 'private-reviewer',+ scope: 'user' as const,+ uri: 'viking://user/default/skills/private-reviewer',+ }++ it('opens the skill detail from the full-card action', () => {+ const onOpen = vi.fn()++ render(+ <SkillCard+ isSharing={false}+ skill={userSkill}+ onOpen={onOpen}+ onShare={vi.fn()}+ />,+ )++ fireEvent.click(+ screen.getByRole('button', {+ name: '查看 private-reviewer 详情',+ }),+ )++ expect(onOpen).toHaveBeenCalledOnce()+ })++ it('offers the share action for a user skill', () => {+ const onOpen = vi.fn()+ const onShare = vi.fn()++ render(+ <SkillCard+ isSharing={false}+ skill={userSkill}+ onOpen={onOpen}+ onShare={onShare}+ />,+ )++ fireEvent.click(+ screen.getByRole('button', {+ name: '将 private-reviewer 设为共享技能',+ }),+ )++ expect(onShare).toHaveBeenCalledOnce()+ expect(onOpen).not.toHaveBeenCalled()+ })++ it('does not offer the share action for a shared skill', () => {+ render(+ <SkillCard+ isSharing={false}+ skill={{+ ...userSkill,+ scope: 'agent',+ uri: 'viking://agent/skills/private-reviewer',+ }}+ onOpen={vi.fn()}+ onShare={vi.fn()}+ />,+ )++ expect(+ screen.queryByRole('button', {+ name: '将 private-reviewer 设为共享技能',+ }),+ ).toBeNull()+ })+})diff --git a/web-studio/src/routes/skills/-components/skill-card.tsx b/web-studio/src/routes/skills/-components/skill-card.tsxnew file mode 100644index 000000000..852888da9--- /dev/null+++ b/web-studio/src/routes/skills/-components/skill-card.tsx@@ -0,0 +1,106 @@+import {+ ChevronRightIcon,+ LoaderCircleIcon,+ Share2Icon,+ SparklesIcon,+} 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 { SKILL_SCOPE_ICONS } from './skill-scope-tabs'+import type { SkillScope } from './skill-scope-tabs'++export type SkillCardItem = {+ description: string+ name: string+ scope: SkillScope+ uri: string+}++export function SkillCard({+ isSharing,+ onOpen,+ onShare,+ skill,+}: {+ isSharing: boolean+ onOpen: () => void+ onShare: () => void+ skill: SkillCardItem+}) {+ const { t } = useTranslation('skillsPage')+ const ScopeIcon = SKILL_SCOPE_ICONS[skill.scope]++ return (+ <Card+ size="sm"+ className="relative h-full transition-colors hover:bg-muted/35"+ >+ <button+ type="button"+ className="absolute inset-0 z-0 rounded-xl outline-none focus-visible:ring-3 focus-visible:ring-inset focus-visible:ring-ring/50"+ aria-label={t('viewDetail', { name: skill.name })}+ onClick={onOpen}+ />+ <CardHeader className="pointer-events-none relative z-10">+ <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="pointer-events-none relative z-10 mt-auto">+ <div className="flex items-center justify-between gap-3">+ <code className="min-w-0 flex-1 truncate text-xs text-muted-foreground">+ {skill.uri}+ </code>+ <div className="flex shrink-0 items-center gap-1">+ {skill.scope === 'user' ? (+ <Button+ type="button"+ variant="outline"+ size="xs"+ className="pointer-events-auto"+ disabled={isSharing}+ aria-label={t('shareSkill', { name: skill.name })}+ onClick={onShare}+ >+ {isSharing ? (+ <LoaderCircleIcon className="animate-spin" />+ ) : (+ <Share2Icon />+ )}+ {isSharing ? t('sharing') : t('share')}+ </Button>+ ) : null}+ <span className="flex h-6 items-center gap-1 px-2 text-xs font-medium text-primary">+ {t('detail')}+ <ChevronRightIcon />+ </span>+ </div>+ </div>+ </CardContent>+ </Card>+ )+}diff --git a/web-studio/src/routes/skills/route.tsx b/web-studio/src/routes/skills/route.tsxindex 46b4ac1bf..2970ca6b4 100644--- a/web-studio/src/routes/skills/route.tsx+++ b/web-studio/src/routes/skills/route.tsx@@ -1,8 +1,7 @@import * as React from 'react'-import { useQuery } from '@tanstack/react-query'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { Link, createFileRoute } from '@tanstack/react-router'import {- ChevronRightIcon,ExternalLinkIcon,FileCode2Icon,LoaderCircleIcon,@@ -11,16 +10,11 @@ import {UserRoundIcon,} from 'lucide-react'import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'import { Badge } from '#/components/ui/badge'import { Button } from '#/components/ui/button'-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from '#/components/ui/card'+import { Card } from '#/components/ui/card'import {Sheet,SheetContent,@@ -29,10 +23,15 @@ import {SheetTitle,} from '#/components/ui/sheet'import { useAppConnection } from '#/hooks/use-app-connection'-import { getOvResult, isOvClientError, ovClient } from '#/lib/ov-client'+import {+ getOvResult,+ isOvClientError,+ ovClient,+ postFsMv,+} from '#/lib/ov-client'+import { SkillCard } from './-components/skill-card'import {- SKILL_SCOPE_ICONS,SkillScopeTabs,getSkillsForScope,} from './-components/skill-scope-tabs'@@ -181,9 +180,22 @@ async function fetchSkillDetail(skill: SkillItem): Promise<SkillDetail> {return normalizeSkillDetail(result, skill)}+async function shareSkill(skill: SkillItem): Promise<void> {+ await getOvResult(+ postFsMv({+ body: {+ from_uri: skill.uri,+ to_uri: `viking://agent/skills/${skill.name}`,+ },+ client: ovClient.client,+ }),+ )+}+function SkillsRoute() {const { t } = useTranslation('skillsPage')const { identityScopeKey } = useAppConnection()+ const queryClient = useQueryClient()const [selectedSkill, setSelectedSkill] = React.useState<SkillItem | null>(null,)@@ -206,6 +218,23 @@ function SkillsRoute() {queryFn: () => fetchSkillDetail(selectedSkill as SkillItem),queryKey: ['skill-detail', identityScopeKey, selectedSkill?.uri],})+ const shareMutation = useMutation({+ mutationFn: shareSkill,+ onSuccess: async (_, skill) => {+ if (selectedSkill?.uri === skill.uri) {+ setSelectedSkill(null)+ }+ await queryClient.invalidateQueries({+ queryKey: ['skills', identityScopeKey],+ })+ setActiveScope('agent')+ toast.success(t('shareSuccess', { name: skill.name }))+ },+ onError: (error) =>+ toast.error(t('shareFailed'), {+ description: getErrorMessage(error),+ }),+ })return (<div className="flex w-full min-w-0 flex-col gap-5">@@ -306,57 +335,17 @@ function SkillsRoute() {) : (<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">{visibleSkills.map((skill) => {- const ScopeIcon = SKILL_SCOPE_ICONS[skill.scope]-return (- <button+ <SkillCardkey={`${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>+ skill={skill}+ isSharing={+ shareMutation.isPending &&+ shareMutation.variables.uri === skill.uri+ }+ onOpen={() => setSelectedSkill(skill)}+ onShare={() => shareMutation.mutate(skill)}+ />)})}</div>