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): support trusted user switching (#4426)
yufeng460f57c1a206
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsxindex 05f0b01ad..4d324b3b4 100644--- a/web-studio/src/components/app-shell.tsx+++ b/web-studio/src/components/app-shell.tsx@@ -542,10 +542,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {<div className="h-6 w-px bg-border/80" aria-hidden="true" />- <CurrentUserMenu- accountId={connection.accountId}- userId={connection.userId}- />+ <CurrentUserMenu /></div></header>diff --git a/web-studio/src/components/current-user-menu.interaction.test.tsx b/web-studio/src/components/current-user-menu.interaction.test.tsxnew file mode 100644index 000000000..080e6290a--- /dev/null+++ b/web-studio/src/components/current-user-menu.interaction.test.tsx@@ -0,0 +1,149 @@+// @vitest-environment jsdom++import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { CurrentUserMenu } from './current-user-menu'++const adminMocks = vi.hoisted(() => ({+ fetchAdminUsers: vi.fn(),+}))++const connectionMocks = vi.hoisted(() => ({+ connection: {+ accountId: 'account-a',+ adminApiKey: 'root-key',+ apiKey: '',+ baseUrl: 'http://localhost:1933',+ userId: 'alice',+ },+ serverMode: 'trusted',+ switchIdentity: vi.fn(),+}))++const toastMocks = vi.hoisted(() => ({+ error: vi.fn(),+ success: vi.fn(),+}))++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}))++vi.mock('sonner', () => ({ toast: toastMocks }))++vi.mock('#/hooks/use-app-connection', () => ({+ useAppConnection: () => connectionMocks,+}))++vi.mock('#/lib/admin', () => adminMocks)++function renderMenu() {+ const queryClient = new QueryClient({+ defaultOptions: {+ mutations: { retry: false },+ queries: { retry: false },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ <CurrentUserMenu />+ </QueryClientProvider>,+ )+}++beforeEach(() => {+ connectionMocks.connection.adminApiKey = 'root-key'+ connectionMocks.serverMode = 'trusted'+ connectionMocks.switchIdentity.mockResolvedValue(undefined)+ adminMocks.fetchAdminUsers.mockResolvedValue([+ {+ accountId: 'account-a',+ role: 'admin',+ userId: 'alice',+ },+ {+ accountId: 'account-a',+ role: 'user',+ userId: 'bob',+ },+ ])+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++describe('CurrentUserMenu', () => {+ it('switches trusted identities without requiring a user API key', async () => {+ renderMenu()++ fireEvent.click(+ screen.getByRole('button', { name: 'header.currentUser.openMenu' }),+ )++ const bob = await screen.findByRole('button', { name: 'bob' })+ fireEvent.click(bob)++ await waitFor(() => {+ expect(connectionMocks.switchIdentity).toHaveBeenCalledWith({+ accountId: 'account-a',+ allowLegacyIdentityFallback: true,+ apiKey: '',+ userId: 'bob',+ })+ })+ expect(toastMocks.success).toHaveBeenCalledWith(+ 'header.currentUser.switchSuccess',+ )+ })++ it('keeps non-trusted user menus read-only', () => {+ connectionMocks.serverMode = 'api_key'+ renderMenu()++ fireEvent.click(+ screen.getByRole('button', { name: 'header.currentUser.openMenu' }),+ )++ expect(screen.queryByText('header.currentUser.switchUser')).toBeNull()+ expect(adminMocks.fetchAdminUsers).not.toHaveBeenCalled()+ })++ it('accepts a user ID when trusted mode has no user directory', async () => {+ connectionMocks.connection.adminApiKey = ''+ renderMenu()++ fireEvent.click(+ screen.getByRole('button', { name: 'header.currentUser.openMenu' }),+ )+ fireEvent.change(+ screen.getByPlaceholderText('header.currentUser.userIdPlaceholder'),+ { target: { value: ' bob ' } },+ )+ fireEvent.click(+ screen.getByRole('button', { name: 'header.currentUser.switchAction' }),+ )++ await waitFor(() => {+ expect(connectionMocks.switchIdentity).toHaveBeenCalledWith({+ accountId: 'account-a',+ allowLegacyIdentityFallback: true,+ apiKey: '',+ userId: 'bob',+ })+ })+ expect(adminMocks.fetchAdminUsers).not.toHaveBeenCalled()+ })+})diff --git a/web-studio/src/components/current-user-menu.tsx b/web-studio/src/components/current-user-menu.tsxindex 875b8ee9a..13a3c9857 100644--- a/web-studio/src/components/current-user-menu.tsx+++ b/web-studio/src/components/current-user-menu.tsx@@ -1,29 +1,88 @@-import { Building2Icon, ChevronDownIcon, UserRoundIcon } from 'lucide-react'+import * as React from 'react'+import { useQuery } from '@tanstack/react-query'+import {+ Building2Icon,+ CheckIcon,+ ChevronDownIcon,+ LoaderCircleIcon,+ UserRoundIcon,+} from 'lucide-react'import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'import {Popover,PopoverContent,PopoverTrigger,} from '#/components/ui/popover'--type CurrentUserMenuProps = {- accountId: string- userId: string-}+import { useAppConnection } from '#/hooks/use-app-connection'+import { fetchAdminUsers } from '#/lib/admin'+import type { AdminConnection } from '#/lib/admin'export function getUserInitial(userId: string): string {const normalizedUserId = userId.trim()return normalizedUserId ? normalizedUserId.slice(0, 1).toUpperCase() : '?'}-export function CurrentUserMenu({ accountId, userId }: CurrentUserMenuProps) {+export function CurrentUserMenu() {const { t } = useTranslation('appShell')+ const { connection, 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 manualTargetUserId = manualUserId.trim()+ const adminConnection = React.useMemo<AdminConnection>(+ () => ({+ accountId,+ apiKey: connection.adminApiKey,+ baseUrl: connection.baseUrl,+ userId,+ }),+ [accountId, connection.adminApiKey, connection.baseUrl, userId],+ )+ const usersQuery = useQuery({+ enabled: canSwitchUser && canListUsers && open,+ queryFn: () => fetchAdminUsers(adminConnection, accountId),+ queryKey: [+ 'current-user-menu',+ adminConnection.baseUrl,+ adminConnection.apiKey,+ accountId,+ ],+ retry: false,+ })++ async function selectUser(nextUserId: string): Promise<void> {+ const normalizedUserId = nextUserId.trim()+ if (!normalizedUserId || normalizedUserId === userId) {+ return+ }++ setSwitchingUserId(normalizedUserId)+ try {+ await switchIdentity({+ accountId,+ allowLegacyIdentityFallback: true,+ apiKey: '',+ userId: normalizedUserId,+ })+ setManualUserId('')+ setOpen(false)+ toast.success(t('header.currentUser.switchSuccess'))+ } catch (error) {+ toast.error(error instanceof Error ? error.message : String(error))+ } finally {+ setSwitchingUserId('')+ }+ }return (- <Popover>+ <Popover open={open} onOpenChange={setOpen}><PopoverTriggeraria-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"@@ -82,6 +141,102 @@ export function CurrentUserMenu({ accountId, userId }: CurrentUserMenuProps) {</dd></div></dl>++ {canSwitchUser ? (+ <div className="border-t p-1.5">+ <p className="px-2.5 py-1.5 text-[11px] font-semibold uppercase tracking-[0.1em] text-muted-foreground">+ {t('header.currentUser.switchUser')}+ </p>+ <div className="max-h-56 overflow-y-auto">+ {!canListUsers ? (+ <form+ className="grid gap-2 p-2"+ onSubmit={(event) => {+ event.preventDefault()+ void selectUser(manualTargetUserId)+ }}+ >+ <label className="sr-only" htmlFor="trusted-user-id">+ {t('header.currentUser.userId')}+ </label>+ <input+ id="trusted-user-id"+ type="text"+ autoComplete="off"+ value={manualUserId}+ className="h-9 rounded-md border bg-background px-3 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"+ placeholder={t('header.currentUser.userIdPlaceholder')}+ onChange={(event) => setManualUserId(event.target.value)}+ />+ <button+ type="submit"+ disabled={+ !manualTargetUserId ||+ manualTargetUserId === userId ||+ Boolean(switchingUserId)+ }+ className="flex h-9 items-center justify-center gap-2 rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground transition-opacity disabled:cursor-not-allowed disabled:opacity-50"+ >+ {switchingUserId ? (+ <LoaderCircleIcon className="size-3.5 animate-spin" />+ ) : null}+ {t('header.currentUser.switchAction')}+ </button>+ </form>+ ) : usersQuery.isLoading ? (+ <div className="flex items-center justify-center gap-2 px-3 py-5 text-xs text-muted-foreground">+ <LoaderCircleIcon className="size-3.5 animate-spin" />+ {t('header.currentUser.loadingUsers')}+ </div>+ ) : usersQuery.isError ? (+ <div className="grid gap-2 px-2.5 py-3 text-center">+ <p className="text-xs text-destructive">+ {t('header.currentUser.loadUsersFailed')}+ </p>+ <button+ type="button"+ className="text-xs font-medium text-primary hover:underline"+ onClick={() => void usersQuery.refetch()}+ >+ {t('header.currentUser.retry')}+ </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)}+ >+ <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 ? (+ <LoaderCircleIcon className="size-3.5 animate-spin" />+ ) : current ? (+ <CheckIcon className="size-3.5 text-primary" />+ ) : null}+ </button>+ )+ })+ ) : (+ <p className="px-2.5 py-4 text-center text-xs text-muted-foreground">+ {t('header.currentUser.noUsers')}+ </p>+ )}+ </div>+ </div>+ ) : null}</PopoverContent></Popover>)diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.tsindex 041d20710..c50bae058 100644--- a/web-studio/src/i18n/locales/en/workspace.ts+++ b/web-studio/src/i18n/locales/en/workspace.ts@@ -12,10 +12,19 @@ const workspace = {currentUser: {account: 'Account',accountSummary: 'Account · {{account}}',+ loadingUsers: 'Loading users',+ loadUsersFailed: 'Failed to load users',+ noUsers: 'No users in this account',openMenu: 'View current user {{user}}',+ retry: 'Retry',signedInAs: 'Current data identity',+ switchSuccess: 'User switched',+ switchAction: 'Switch user',+ switchUser: 'Switch user',unset: 'Not set',user: 'User',+ userId: 'User ID',+ userIdPlaceholder: 'Enter a User ID',},defaultTitle: 'OpenViking Studio',},diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.tsindex b8a327694..da7df1e16 100644--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts@@ -12,10 +12,19 @@ const workspace = {currentUser: {account: '账号',accountSummary: '账号 · {{account}}',+ loadingUsers: '正在加载用户',+ loadUsersFailed: '用户列表加载失败',+ noUsers: '当前账号暂无用户',openMenu: '查看当前用户 {{user}}',+ retry: '重试',signedInAs: '当前数据访问身份',+ switchSuccess: '用户切换成功',+ switchAction: '切换用户',+ switchUser: '切换用户',unset: '未设置',user: '用户',+ userId: '用户 ID',+ userIdPlaceholder: '输入用户 ID',},defaultTitle: 'OpenViking Studio',},diff --git a/web-studio/src/lib/ov-client/client.test.ts b/web-studio/src/lib/ov-client/client.test.tsindex 8de0db5f6..d2dbe37a9 100644--- a/web-studio/src/lib/ov-client/client.test.ts+++ b/web-studio/src/lib/ov-client/client.test.ts@@ -114,4 +114,26 @@ describe('createOvClient API key selection', () => {'candidate-user-key',)})++ it('preserves explicit trusted identity headers used to probe a candidate user', async () => {+ const { client, requests } = createRecordingClient()+ client.setConnection({+ accountId: 'account-a',+ adminApiKey: 'root-key',+ identityHeaders: true,+ userId: 'alice',+ })++ await client.instance.get('/health', {+ headers: {+ 'X-OpenViking-Account': 'account-a',+ 'X-OpenViking-User': 'bob',+ },+ })++ expect(readRequestHeader(requests[0], 'X-OpenViking-Account')).toBe(+ 'account-a',+ )+ expect(readRequestHeader(requests[0], 'X-OpenViking-User')).toBe('bob')+ })})diff --git a/web-studio/src/lib/ov-client/client.ts b/web-studio/src/lib/ov-client/client.tsindex de34da5f6..0c9072ee3 100644--- a/web-studio/src/lib/ov-client/client.ts+++ b/web-studio/src/lib/ov-client/client.ts@@ -191,8 +191,12 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {setOptionalHeader(headers, 'X-API-Key', apiKey)}if (connection.identityHeaders) {- setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)- setOptionalHeader(headers, 'X-OpenViking-User', connection.userId)+ if (!readHeader(headers, 'X-OpenViking-Account')?.trim()) {+ setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)+ }+ if (!readHeader(headers, 'X-OpenViking-User')?.trim()) {+ setOptionalHeader(headers, 'X-OpenViking-User', connection.userId)+ }} else {headers.delete('X-OpenViking-Account')headers.delete('X-OpenViking-User')diff --git a/web-studio/src/routes/users/route.tsx b/web-studio/src/routes/users/route.tsxindex f3fdab483..c3535713f 100644--- a/web-studio/src/routes/users/route.tsx+++ b/web-studio/src/routes/users/route.tsx@@ -247,7 +247,7 @@ function UserManagementRoute() {}async function useUserIdentity(user: AdminUser | KeyResult): Promise<void> {- if (!user.apiKey) {+ if (serverMode !== 'trusted' && !user.apiKey) {toast.error(t('management.noUsableKey'))return}@@ -259,7 +259,7 @@ function UserManagementRoute() {await switchIdentity({accountId,allowLegacyIdentityFallback: true,- apiKey: user.apiKey,+ apiKey: user.apiKey || '',userId,})toast.success(t('toast.dataKeySelected'))@@ -434,6 +434,9 @@ function UserManagementRoute() {const isCurrentIdentity =user.accountId === connection.accountId &&user.userId === connection.userId+ const canSwitchIdentity =+ !isCurrentIdentity &&+ (serverMode === 'trusted' || Boolean(user.apiKey))const isSwitching = switchingIdentityKey === identityKeyconst isLastManager =(user.role === 'admin' || user.role === 'root') &&@@ -571,7 +574,7 @@ function UserManagementRoute() {</TableCell><TableCell><div className="flex items-center justify-end gap-1">- {user.apiKey && !isCurrentIdentity ? (+ {canSwitchIdentity ? (<Buttontype="button"variant="secondary"