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): add account switching and user management (#3500)
yufengfeba7e78a2ac
diff --git a/web-studio/src/components/account-switcher.test.ts b/web-studio/src/components/account-switcher.test.tsnew file mode 100644index 000000000..fdcf07956--- /dev/null+++ b/web-studio/src/components/account-switcher.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest'++import { selectAccountUser } from './account-switcher'+import type { AdminUser } from '#/lib/admin'++const users: AdminUser[] = [+ {+ accountId: 'workspace',+ apiKey: 'alice-key',+ role: 'user',+ userId: 'alice',+ },+ {+ accountId: 'workspace',+ apiKey: 'default-key',+ role: 'admin',+ userId: 'default',+ },+]++describe('selectAccountUser', () => {+ it('selects the first user returned by the target account', () => {+ expect(selectAccountUser(users, 'default', true)?.userId).toBe('alice')+ })++ it('falls back to the first user for a new account', () => {+ expect(selectAccountUser(users, 'missing', true)?.userId).toBe('alice')+ })++ it('rejects prefix-only users in API-key mode', () => {+ expect(+ selectAccountUser(+ [+ {+ accountId: 'workspace',+ keyPrefix: 'ovk_123',+ role: 'admin',+ userId: 'default',+ },+ ],+ 'default',+ true,+ ),+ ).toBeUndefined()+ })+})diff --git a/web-studio/src/components/account-switcher.tsx b/web-studio/src/components/account-switcher.tsxnew file mode 100644index 000000000..b7da8ee7d--- /dev/null+++ b/web-studio/src/components/account-switcher.tsx@@ -0,0 +1,538 @@+import * as React from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import {+ Building2Icon,+ CheckIcon,+ ChevronDownIcon,+ LoaderCircleIcon,+ PlusIcon,+ SearchIcon,+} from 'lucide-react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'++import { Button } from '#/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '#/components/ui/dialog'+import { Input } from '#/components/ui/input'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '#/components/ui/popover'+import { useAppConnection } from '#/hooks/use-app-connection'+import {+ createAdminAccount,+ fetchAdminAccounts,+ fetchAdminUsers,+} from '#/lib/admin'+import type {+ AdminConnection,+ AdminUser,+ CreateAccountInput,+} from '#/lib/admin'+import { DEFAULT_USER_ID } from '#/lib/admin-options'+import { PLAIN_INPUT_PROPS } from '#/lib/form-input'+import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'+import { cn } from '#/lib/utils'++export function selectAccountUser(+ users: readonly AdminUser[],+ _currentUserId: string,+ requireApiKey: boolean,+): AdminUser | undefined {+ const candidates = requireApiKey+ ? users.filter((user) => Boolean(user.apiKey))+ : [...users]+ return candidates[0]+}++export function AccountSwitcher() {+ const { t } = useTranslation('accountSwitcher')+ const queryClient = useQueryClient()+ const {+ connection,+ connectionRole,+ isConnectionRoleLoading,+ setGeneratedCredential,+ serverMode,+ switchIdentity,+ switchManagementAccount,+ } = useAppConnection()+ const [open, setOpen] = React.useState(false)+ const [createOpen, setCreateOpen] = React.useState(false)+ const [search, setSearch] = React.useState('')+ const [switchingAccountId, setSwitchingAccountId] = React.useState('')+ const [manualSwitch, setManualSwitch] = React.useState<{+ accountId: string+ apiKey: string+ userId: string+ } | null>(null)+ const [createDraft, setCreateDraft] = React.useState<CreateAccountInput>({+ accountId: '',+ adminUserId: DEFAULT_USER_ID,+ })++ const { canManageAccounts } = resolveStudioManagementCapabilities({+ hasControlCredential: Boolean(connection.adminApiKey.trim()),+ isRoleLoading: isConnectionRoleLoading,+ role: connectionRole,+ serverMode,+ })++ const adminConnection = React.useMemo<AdminConnection>(+ () => ({+ accountId: connection.accountId,+ apiKey: connection.adminApiKey,+ baseUrl: connection.baseUrl,+ userId: connection.userId,+ }),+ [+ connection.accountId,+ connection.adminApiKey,+ connection.baseUrl,+ connection.userId,+ ],+ )++ const accountsQuery = useQuery({+ enabled: canManageAccounts && open,+ queryFn: () => fetchAdminAccounts(adminConnection),+ queryKey: [+ 'account-switcher',+ adminConnection.baseUrl,+ adminConnection.apiKey,+ ],+ retry: false,+ })++ const filteredAccounts = React.useMemo(() => {+ const normalizedSearch = search.trim().toLowerCase()+ const accounts = accountsQuery.data ?? []+ if (!normalizedSearch) {+ return accounts+ }+ return accounts.filter((account) =>+ account.accountId.toLowerCase().includes(normalizedSearch),+ )+ }, [accountsQuery.data, search])++ async function selectAccount(accountId: string): Promise<void> {+ if (accountId === connection.accountId) {+ setOpen(false)+ return+ }++ setSwitchingAccountId(accountId)+ try {+ const users = await fetchAdminUsers(adminConnection, accountId)+ const firstUser = selectAccountUser(users, connection.userId, false)+ if (!firstUser) {+ throw new Error(t('errors.noUsers'))+ }++ const candidates =+ serverMode === 'api_key'+ ? users.filter((user) => Boolean(user.apiKey))+ : [firstUser]+ let switchError: unknown+ for (const user of candidates) {+ try {+ await switchIdentity({+ accountId,+ allowLegacyIdentityFallback: true,+ apiKey: user.apiKey || '',+ userId: user.userId,+ })+ setOpen(false)+ toast.success(+ t('toast.switched', {+ account: accountId,+ }),+ )+ return+ } catch (error) {+ switchError = error+ }+ }++ if (serverMode === 'api_key') {+ setOpen(false)+ setManualSwitch({+ accountId,+ apiKey: '',+ userId: firstUser.userId,+ })+ return+ }+ throw switchError+ } catch (error) {+ toast.error(error instanceof Error ? error.message : String(error))+ } finally {+ setSwitchingAccountId('')+ }+ }++ const createAccount = useMutation({+ mutationFn: (input: CreateAccountInput) =>+ createAdminAccount(adminConnection, input),+ onError: (error) =>+ toast.error(error instanceof Error ? error.message : String(error)),+ onSuccess: async (result, input) => {+ const accountId = result.accountId || input.accountId+ const userId = result.userId || input.adminUserId+ if (result.apiKey) {+ setGeneratedCredential({+ accountId,+ apiKey: result.apiKey,+ userId,+ })+ }+ setCreateOpen(false)+ setOpen(false)+ setCreateDraft({ accountId: '', adminUserId: DEFAULT_USER_ID })+ void queryClient.invalidateQueries({ queryKey: ['account-switcher'] })++ if (!result.apiKey && serverMode === 'api_key') {+ await switchManagementAccount(accountId)+ toast.warning(t('errors.noCreatedKey'))+ return+ }++ try {+ await switchIdentity({+ accountId,+ allowLegacyIdentityFallback: true,+ apiKey: result.apiKey,+ userId,+ })+ toast.success(t('toast.created', { account: input.accountId }))+ } catch (error) {+ await switchManagementAccount(accountId)+ toast.error(+ t('toast.createdSwitchFailed', {+ account: input.accountId,+ error: error instanceof Error ? error.message : String(error),+ }),+ )+ }+ },+ })++ const accountLabel = connection.accountId || t('unset')++ if (!canManageAccounts) {+ return (+ <div+ className="flex h-10 min-w-0 flex-1 items-center gap-2 rounded-lg px-2 text-left group-data-[collapsible=icon]:size-9 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0"+ title={accountLabel}+ >+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-sidebar-border bg-sidebar-accent/50">+ <Building2Icon className="size-4" />+ </span>+ <span className="min-w-0 flex-1 truncate text-sm font-semibold group-data-[collapsible=icon]:hidden">+ {accountLabel}+ </span>+ </div>+ )+ }++ return (+ <>+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger className="flex h-10 min-w-0 flex-1 items-center gap-2 rounded-lg px-2 text-left outline-none transition-colors hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-sidebar-ring group-data-[collapsible=icon]:size-9 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0">+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-sidebar-border bg-sidebar-accent/50">+ <Building2Icon className="size-4" />+ </span>+ <span className="min-w-0 flex-1 truncate text-sm font-semibold group-data-[collapsible=icon]:hidden">+ {accountLabel}+ </span>+ <ChevronDownIcon className="size-4 shrink-0 text-muted-foreground group-data-[collapsible=icon]:hidden" />+ </PopoverTrigger>+ <PopoverContent+ side="bottom"+ align="start"+ sideOffset={6}+ className="w-64 gap-0 p-0"+ >+ <div className="border-b p-2">+ <div className="relative">+ <SearchIcon className="absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={search}+ onChange={(event) => setSearch(event.target.value)}+ placeholder={t('searchPlaceholder')}+ className="h-8 pl-8 text-sm"+ />+ </div>+ </div>+ <div className="max-h-60 overflow-y-auto p-1.5">+ {accountsQuery.isLoading ? (+ <div className="flex items-center justify-center gap-2 px-2.5 py-6 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-3.5 animate-spin" />+ {t('loading')}+ </div>+ ) : accountsQuery.isError ? (+ <div className="grid gap-1 px-2.5 py-5 text-center">+ <p className="text-sm font-medium text-destructive">+ {t('errors.loadAccounts')}+ </p>+ <p className="line-clamp-2 text-xs text-muted-foreground">+ {accountsQuery.error instanceof Error+ ? accountsQuery.error.message+ : String(accountsQuery.error)}+ </p>+ </div>+ ) : filteredAccounts.length === 0 ? (+ <p className="px-2.5 py-6 text-center text-sm text-muted-foreground">+ {t('empty')}+ </p>+ ) : (+ filteredAccounts.map((account) => {+ const active = account.accountId === connection.accountId+ const switching = switchingAccountId === account.accountId+ return (+ <button+ key={account.accountId}+ type="button"+ disabled={Boolean(switchingAccountId)}+ onClick={() => void selectAccount(account.accountId)}+ className={cn(+ 'flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left transition-colors hover:bg-accent disabled:cursor-wait disabled:opacity-60',+ active && 'bg-accent/70',+ )}+ >+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-background">+ <Building2Icon className="size-3.5" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium">+ {account.accountId}+ </span>+ <span className="block text-xs text-muted-foreground">+ {t('memberCount', { count: account.userCount })}+ </span>+ </span>+ {switching ? (+ <LoaderCircleIcon className="size-3.5 animate-spin" />+ ) : active ? (+ <CheckIcon className="size-3.5 text-primary" />+ ) : null}+ </button>+ )+ })+ )}+ </div>+ <div className="border-t p-1.5">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="w-full justify-start px-2.5"+ onClick={() => {+ setOpen(false)+ setCreateOpen(true)+ }}+ >+ <PlusIcon />+ {t('create')}+ </Button>+ </div>+ </PopoverContent>+ </Popover>++ <Dialog+ open={Boolean(manualSwitch)}+ onOpenChange={(nextOpen) => {+ if (!nextOpen && !switchingAccountId) {+ setManualSwitch(null)+ }+ }}+ >+ <DialogContent>+ <form+ onSubmit={(event) => {+ event.preventDefault()+ if (!manualSwitch?.apiKey.trim()) {+ return+ }+ const target = manualSwitch+ setSwitchingAccountId(target.accountId)+ void switchIdentity({+ accountId: target.accountId,+ apiKey: target.apiKey,+ userId: target.userId,+ })+ .then(() => {+ toast.success(+ t('toast.switched', { account: target.accountId }),+ )+ setManualSwitch(null)+ })+ .catch((error: unknown) => {+ toast.error(+ error instanceof Error ? error.message : String(error),+ )+ })+ .finally(() => setSwitchingAccountId(''))+ }}+ >+ <DialogHeader>+ <DialogTitle>{t('manualSwitch.title')}</DialogTitle>+ <DialogDescription>+ {t('manualSwitch.description', {+ account: manualSwitch?.accountId,+ })}+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-2 py-5">+ <label className="grid gap-2 text-sm font-medium">+ {t('manualSwitch.keyLabel')}+ <Input+ required+ type="password"+ value={manualSwitch?.apiKey ?? ''}+ onChange={(event) =>+ setManualSwitch((current) =>+ current+ ? { ...current, apiKey: event.target.value }+ : current,+ )+ }+ placeholder={t('manualSwitch.keyPlaceholder')}+ {...PLAIN_INPUT_PROPS}+ />+ </label>+ <p className="text-xs leading-5 text-muted-foreground">+ {t('manualSwitch.hint')}+ </p>+ </div>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ disabled={Boolean(switchingAccountId)}+ onClick={() => {+ const targetAccountId = manualSwitch?.accountId+ if (!targetAccountId) {+ return+ }+ setSwitchingAccountId(targetAccountId)+ void switchManagementAccount(targetAccountId)+ .then(() => {+ setManualSwitch(null)+ toast.success(+ t('toast.managementSwitched', {+ account: targetAccountId,+ }),+ )+ })+ .catch((error: unknown) => {+ toast.error(+ error instanceof Error ? error.message : String(error),+ )+ })+ .finally(() => setSwitchingAccountId(''))+ }}+ >+ {t('manualSwitch.manageOnly')}+ </Button>+ <Button+ type="button"+ variant="ghost"+ disabled={Boolean(switchingAccountId)}+ onClick={() => setManualSwitch(null)}+ >+ {t('dialog.cancel')}+ </Button>+ <Button+ type="submit"+ disabled={+ Boolean(switchingAccountId) || !manualSwitch?.apiKey.trim()+ }+ >+ {switchingAccountId ? (+ <LoaderCircleIcon className="animate-spin" />+ ) : (+ <CheckIcon />+ )}+ {t('manualSwitch.submit')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <DialogContent>+ <form+ onSubmit={(event) => {+ event.preventDefault()+ createAccount.mutate(createDraft)+ }}+ >+ <DialogHeader>+ <DialogTitle>{t('dialog.title')}</DialogTitle>+ <DialogDescription>{t('dialog.description')}</DialogDescription>+ </DialogHeader>+ <div className="grid gap-4 py-5">+ <label className="grid gap-2 text-sm font-medium">+ {t('dialog.accountLabel')}+ <Input+ required+ value={createDraft.accountId}+ onChange={(event) =>+ setCreateDraft((current) => ({+ ...current,+ accountId: event.target.value,+ }))+ }+ placeholder={t('dialog.accountPlaceholder')}+ {...PLAIN_INPUT_PROPS}+ />+ </label>+ <label className="grid gap-2 text-sm font-medium">+ {t('dialog.adminLabel')}+ <Input+ required+ value={createDraft.adminUserId}+ onChange={(event) =>+ setCreateDraft((current) => ({+ ...current,+ adminUserId: event.target.value,+ }))+ }+ placeholder={DEFAULT_USER_ID}+ {...PLAIN_INPUT_PROPS}+ />+ </label>+ </div>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => setCreateOpen(false)}+ >+ {t('dialog.cancel')}+ </Button>+ <Button type="submit" disabled={createAccount.isPending}>+ {createAccount.isPending ? (+ <LoaderCircleIcon className="animate-spin" />+ ) : (+ <PlusIcon />+ )}+ {t('dialog.submit')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </>+ )+}diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsxindex 7fabcff54..ef7ae9e51 100644--- a/web-studio/src/components/app-shell.tsx+++ b/web-studio/src/components/app-shell.tsx@@ -16,6 +16,7 @@ import {SearchIcon,SunIcon,TrashIcon,+ UsersRoundIcon,} from 'lucide-react'import { useTranslation } from 'react-i18next'import { useTheme } from 'next-themes'@@ -26,6 +27,8 @@ import {CollapsibleTrigger,} from '#/components/ui/collapsible'import { CrossDeviceVerifyDialog } from '#/components/cross-device-verify-dialog'+import { AccountSwitcher } from '#/components/account-switcher'+import { GeneratedCredentialDialog } from '#/components/generated-credential-dialog'import { ScrollArea } from '#/components/ui/scroll-area'import {Sidebar,@@ -50,16 +53,13 @@ import {useAppConnection,} 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,- setSessionTitle,- removeSessionTitle,-} from '#/lib/sessions/use-session-titles'+import { useSessionTitles } from '#/lib/sessions/use-session-titles'type NavItem = {icon: React.ComponentType@@ -205,12 +205,13 @@ function NavSessionsItem({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 } = useSessionTitles()+ const { getTitle, removeTitle, setTitle } = useSessionTitles(identityScopeKey)const createSession = useCreateSession()const deleteSession = useDeleteSession()@@ -227,19 +228,16 @@ function NavSessionsItem({const handleNewSession = React.useCallback(async () => {const result = await createSession.mutateAsync(undefined)- setSessionTitle(- result.session_id,- t('threadList.newSession', { ns: 'sessions' }),- )+ setTitle(result.session_id, t('threadList.newSession', { ns: 'sessions' }))void navigate({ to: '/sessions', search: { s: result.session_id } })- }, [createSession, navigate, t])+ }, [createSession, navigate, setTitle, t])const handleDeleteSession = React.useCallback(async (e: React.MouseEvent, id: string) => {e.stopPropagation()e.preventDefault()await deleteSession.mutateAsync(id)- removeSessionTitle(id)+ removeTitle(id)if (activeSessionId === id) {void navigate({to: '/sessions',@@ -247,7 +245,7 @@ function NavSessionsItem({})}},- [deleteSession, activeSessionId, navigate],+ [activeSessionId, deleteSession, navigate, removeTitle],)return (@@ -329,11 +327,16 @@ function NavSessionsItem({export function AppShell({ children }: { children: React.ReactNode }) {return (<AppConnectionProvider>- <AppShellInner>{children}</AppShellInner>+ <IdentityScopedAppShell>{children}</IdentityScopedAppShell></AppConnectionProvider>)}+function IdentityScopedAppShell({ children }: { children: React.ReactNode }) {+ const { identityScopeKey } = useAppConnection()+ return <AppShellInner key={identityScopeKey}>{children}</AppShellInner>+}+function AppShellInner({ children }: { children: React.ReactNode }) {const { i18n, t } = useTranslation(['appShell', 'common'])const navigate = useNavigate()@@ -346,7 +349,16 @@ function AppShellInner({ children }: { children: React.ReactNode }) {)const [crossDeviceVerifyOpen, setCrossDeviceVerifyOpen] =React.useState(false)+ const { connection, connectionRole, isConnectionRoleLoading, serverMode } =+ useAppConnection()const settingsActive = pathname === '/settings'+ const usersActive = pathname === '/users'+ const { canManageUsers } = resolveStudioManagementCapabilities({+ hasControlCredential: Boolean(connection.adminApiKey.trim()),+ isRoleLoading: isConnectionRoleLoading,+ role: connectionRole,+ serverMode,+ })const crossDeviceVerifyActive =pathname === '/oauth/verify' || pathname.startsWith('/oauth/verify/')const visibleNavItems = NAV_ITEMS@@ -377,9 +389,9 @@ function AppShellInner({ children }: { children: React.ReactNode }) {<Sidebar variant="sidebar" collapsible="icon" className="!border-r-0"><SidebarHeader className="h-12 border-b border-sidebar-border/70 px-2 py-0"><div className="flex h-full items-center justify-between gap-2 group-data-[collapsible=icon]:justify-center">- <span className="flex h-8 min-w-0 items-center truncate px-2 text-base font-semibold leading-none group-data-[collapsible=icon]:hidden">- {t('sidebar.workspaceGroupLabel', { ns: 'appShell' })}- </span>+ <div className="min-w-0 flex-1 group-data-[collapsible=icon]:hidden">+ <AccountSwitcher />+ </div><SidebarTrigger className="hidden shrink-0 md:inline-flex" /></div></SidebarHeader>@@ -451,6 +463,19 @@ function AppShellInner({ children }: { children: React.ReactNode }) {<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><SidebarMenuButtononClick={openCrossDeviceVerify}@@ -576,6 +601,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {open={crossDeviceVerifyOpen}onOpenChange={setCrossDeviceVerifyOpen}/>+ <GeneratedCredentialDialog /></SidebarProvider>)}diff --git a/web-studio/src/components/generated-credential-dialog.tsx b/web-studio/src/components/generated-credential-dialog.tsxnew file mode 100644index 000000000..77dc9939e--- /dev/null+++ b/web-studio/src/components/generated-credential-dialog.tsx@@ -0,0 +1,135 @@+import * as React from 'react'+import {+ CheckIcon,+ CopyIcon,+ KeyRoundIcon,+ LoaderCircleIcon,+} 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 {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '#/components/ui/dialog'+import { useAppConnection } from '#/hooks/use-app-connection'+import { copyTextToClipboard } from '#/lib/clipboard'++export function GeneratedCredentialDialog() {+ const { t } = useTranslation('settings')+ const {+ clearGeneratedCredential,+ connection,+ generatedCredential,+ switchIdentity,+ } = useAppConnection()+ const [isSwitching, setIsSwitching] = React.useState(false)++ if (!generatedCredential?.apiKey) {+ return null+ }++ const accountId = generatedCredential.accountId || connection.accountId+ const userId = generatedCredential.userId || connection.userId+ const isCurrentIdentity =+ accountId === connection.accountId &&+ userId === connection.userId &&+ generatedCredential.apiKey === connection.apiKey++ async function copyKey(): Promise<void> {+ try {+ await copyTextToClipboard(generatedCredential.apiKey)+ toast.success(t('toast.copied'))+ } catch {+ toast.error(t('toast.copyFailed'))+ }+ }++ async function useIdentity(): Promise<void> {+ setIsSwitching(true)+ try {+ await switchIdentity({+ accountId,+ allowLegacyIdentityFallback: true,+ apiKey: generatedCredential.apiKey,+ userId,+ })+ toast.success(t('toast.dataKeySelected'))+ } catch (error) {+ toast.error(error instanceof Error ? error.message : String(error))+ } finally {+ setIsSwitching(false)+ }+ }++ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !isSwitching) {+ clearGeneratedCredential()+ }+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('keyResult.title')}</DialogTitle>+ <DialogDescription>+ {t('keyResult.description', { account: accountId, user: userId })}+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-3 py-4">+ <div className="rounded-md border bg-muted/30 px-3 py-2 text-sm text-muted-foreground">+ {accountId} / {userId}+ </div>+ <code className="break-all rounded-md border bg-background p-3 font-mono text-sm">+ {generatedCredential.apiKey}+ </code>+ </div>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => void copyKey()}+ >+ <CopyIcon />+ {t('actions.copy')}+ </Button>+ {isCurrentIdentity ? (+ <Badge variant="secondary" className="h-9 gap-1.5 px-3 font-normal">+ <CheckIcon />+ {t('actions.currentIdentity')}+ </Badge>+ ) : (+ <Button+ type="button"+ disabled={isSwitching}+ onClick={() => void useIdentity()}+ >+ {isSwitching ? (+ <LoaderCircleIcon className="animate-spin" />+ ) : (+ <KeyRoundIcon />+ )}+ {t('actions.switchIdentity')}+ </Button>+ )}+ <Button+ type="button"+ variant="ghost"+ disabled={isSwitching}+ onClick={clearGeneratedCredential}+ >+ {t('keyResult.dismiss')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web-studio/src/hooks/use-app-connection.test.ts b/web-studio/src/hooks/use-app-connection.test.tsindex cdd40ee09..5866ad4d2 100644--- a/web-studio/src/hooks/use-app-connection.test.ts+++ b/web-studio/src/hooks/use-app-connection.test.ts@@ -1,10 +1,16 @@import { describe, expect, it } from 'vitest'import {+ createManagementAccountConnection,+ createIdentityScopeKey,+ resolveSwitchedIdentity,resolveConnectionRoleProbeState,resolveInitialApiKey,shouldRedirectToLoginOnApiError,+ synchronizeConnectionRuntime,+ synchronizeResolvedDataIdentity,} from './use-app-connection'+import { ovClient } from '#/lib/ov-client'const acceptClientError = () => true@@ -40,6 +46,168 @@ describe('resolveInitialApiKey', () => {})})+describe('createIdentityScopeKey', () => {+ it('changes when the active account changes', () => {+ const connection = {+ accountId: 'account-a',+ adminApiKey: 'root-key',+ apiKey: 'user-key',+ baseUrl: 'http://localhost:1933',+ userId: 'default',+ }++ expect(createIdentityScopeKey(connection, 'api_key')).not.toBe(+ createIdentityScopeKey(+ {+ ...connection,+ accountId: 'account-b',+ },+ 'api_key',+ ),+ )+ })++ it('does not expose the raw data credential', () => {+ const scope = createIdentityScopeKey(+ {+ accountId: 'default',+ adminApiKey: 'root-key',+ apiKey: 'secret-user-key',+ baseUrl: 'http://localhost:1933',+ userId: 'default',+ },+ 'api_key',+ )++ expect(scope).not.toContain('secret-user-key')+ })+})++describe('synchronizeResolvedDataIdentity', () => {+ it('updates the active account and user even when a Root control key is configured', () => {+ const connection = {+ accountId: 'account-a',+ adminApiKey: 'root-key',+ apiKey: 'account-b-user-key',+ baseUrl: 'http://localhost:1933',+ userId: 'alice',+ }++ expect(+ synchronizeResolvedDataIdentity(connection, {+ accountId: 'account-b',+ role: 'user',+ userId: 'bob',+ }),+ ).toEqual({+ ...connection,+ accountId: 'account-b',+ userId: 'bob',+ })+ })++ it('does not rewrite an already synchronized identity', () => {+ const connection = {+ accountId: 'account-b',+ adminApiKey: 'root-key',+ apiKey: 'account-b-user-key',+ baseUrl: 'http://localhost:1933',+ userId: 'bob',+ }++ expect(+ synchronizeResolvedDataIdentity(connection, {+ accountId: 'account-b',+ role: 'user',+ userId: 'bob',+ }),+ ).toBeNull()+ })+})++describe('resolveSwitchedIdentity', () => {+ it('uses the requested account and user for legacy health responses', () => {+ expect(+ resolveSwitchedIdentity(+ { accountId: 'account-b', userId: 'bob' },+ { accountId: '', role: 'user', userId: '' },+ ),+ ).toEqual({ accountId: 'account-b', userId: 'bob' })+ })++ it('rejects a credential that resolves to another identity', () => {+ expect(+ resolveSwitchedIdentity(+ { accountId: 'account-b', userId: 'bob' },+ { accountId: 'account-a', role: 'user', userId: 'alice' },+ ),+ ).toBeNull()+ })++ it('uses an Admin API credential association with legacy health endpoints', () => {+ expect(+ resolveSwitchedIdentity(+ { accountId: 'account-b', userId: 'bob' },+ { accountId: '', role: 'unknown', userId: '' },+ true,+ ),+ ).toEqual({ accountId: 'account-b', userId: 'bob' })+ })+})++describe('createManagementAccountConnection', () => {+ it('keeps the Root credential while clearing stale tenant data credentials', () => {+ expect(+ createManagementAccountConnection(+ {+ accountId: 'account-a',+ adminApiKey: 'root-key',+ apiKey: 'account-a-user-key',+ baseUrl: 'http://localhost:1933',+ userId: 'alice',+ },+ ' account-b ',+ ),+ ).toEqual({+ accountId: 'account-b',+ adminApiKey: 'root-key',+ apiKey: '',+ baseUrl: 'http://localhost:1933',+ userId: '',+ })+ })+})++describe('synchronizeConnectionRuntime', () => {+ it('updates the imperative client before React state consumers remount', () => {+ const next = synchronizeConnectionRuntime(+ {+ accountId: 'account-b',+ adminApiKey: 'root-key',+ apiKey: 'account-b-user-key',+ baseUrl: 'http://localhost:1933/',+ userId: 'bob',+ },+ 'api_key',+ )++ expect(next).toEqual({+ accountId: 'account-b',+ adminApiKey: 'root-key',+ apiKey: 'account-b-user-key',+ baseUrl: 'http://localhost:1933/',+ userId: 'bob',+ })+ expect(ovClient.getConnection()).toMatchObject({+ accountId: 'account-b',+ adminApiKey: 'root-key',+ apiKey: 'account-b-user-key',+ identityHeaders: false,+ userId: 'bob',+ })+ })+})+describe('resolveConnectionRoleProbeState', () => {it('treats dev mode as root without requiring an API key', () => {expect(diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsxindex 4232b532c..811d49a82 100644--- a/web-studio/src/hooks/use-app-connection.tsx+++ b/web-studio/src/hooks/use-app-connection.tsx@@ -1,8 +1,11 @@import * as React from 'react'import { useQueryClient } from '@tanstack/react-query'import { useNavigate, useRouterState } from '@tanstack/react-router'+import axios from 'axios'-import { isOvClientError, ovClient } from '#/lib/ov-client'+import { createClient } from '#/gen/ov-client/client'+import { fetchAdminAccounts } from '#/lib/admin'+import { getHealth, isOvClientError, ovClient } from '#/lib/ov-client'import { detectServerMode, normalizeBaseUrl } from './use-server-mode'import type { ServerMode } from './use-server-mode'@@ -24,13 +27,30 @@ export type ConnectionIdentitySummary = {}}+export type GeneratedCredential = {+ accountId?: string+ apiKey: string+ userId?: string+}+type AppConnectionContextValue = {+ clearGeneratedCredential: () => voidconnection: ConnectionDraftconnectionRole: ConnectionRole+ generatedCredential: GeneratedCredential | null+ identityScopeKey: stringisConnectionRoleLoading: booleanopenConnectionSettings: () => voidsaveConnection: (next: ConnectionDraft) => void+ setGeneratedCredential: (credential: GeneratedCredential) => voidserverMode: ServerMode+ switchIdentity: (identity: {+ accountId: string+ allowLegacyIdentityFallback?: boolean+ apiKey: string+ userId: string+ }) => Promise<void>+ switchManagementAccount: (accountId: string) => Promise<void>}const CONNECTION_STORAGE_KEY = 'ov_console_connection'@@ -132,6 +152,29 @@ function normalizeConnectionDraft(}}+function hashSecret(value: string): string {+ let hash = 0x811c9dc5+ for (let index = 0; index < value.length; index += 1) {+ hash ^= value.charCodeAt(index)+ hash = Math.imul(hash, 0x01000193)+ }+ return (hash >>> 0).toString(36)+}++export function createIdentityScopeKey(+ connection: ConnectionDraft,+ serverMode: ServerMode,+): string {+ const dataKey = connection.apiKey || connection.adminApiKey+ return [+ normalizeBaseUrl(connection.baseUrl),+ serverMode,+ connection.accountId,+ connection.userId,+ dataKey ? hashSecret(dataKey) : 'none',+ ].join('\u0000')+}+function resolveIdentityField(envValue: string,storedValue: string | undefined,@@ -210,16 +253,52 @@ function applyConnection(})}+export function synchronizeConnectionRuntime(+ connection: ConnectionDraft,+ serverMode: ServerMode,+): ConnectionDraft {+ const normalized = normalizeConnectionDraft(connection)+ // Keep the imperative request client ahead of the React tree. Identity+ // changes remount route content, whose child effects may start requests+ // before this provider's passive effects run.+ applyConnection(normalized, serverMode)+ persistConnection(normalized)+ return normalized+}+type ConnectionIdentity = {accountId: stringrole: ConnectionRole+ userId: string+}++async function canListAccounts(connection: ConnectionDraft): Promise<boolean> {+ if (!connection.adminApiKey) {+ return false+ }++ try {+ await fetchAdminAccounts({+ accountId: connection.accountId,+ apiKey: connection.adminApiKey,+ baseUrl: connection.baseUrl,+ userId: connection.userId,+ })+ return true+ } catch {+ return false+ }}async function detectConnectionIdentity(connection: ConnectionDraft,+ credential: 'control' | 'data' = 'control',): Promise<ConnectionIdentity> {const headers: Record<string, string> = {}- const apiKey = connection.adminApiKey || connection.apiKey+ const apiKey =+ credential === 'data'+ ? connection.apiKey || connection.adminApiKey+ : connection.adminApiKey || connection.apiKeyif (apiKey) {headers['X-API-Key'] = apiKey}@@ -232,24 +311,92 @@ async function detectConnectionIdentity(headers['X-OpenViking-User'] = connection.userId}- const response = await fetch(- `${normalizeBaseUrl(connection.baseUrl)}/health`,- { headers },- )- if (!response.ok) {- return { accountId: '', role: 'unknown' }- }+ const client = createClient({+ axios: axios.create(),+ baseURL: normalizeBaseUrl(connection.baseUrl),+ headers,+ throwOnError: true,+ })+ const response = await getHealth({ client })// /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 = (await response.json().catch(() => null)) as {+ const data = response.data as {account_id?: unknownrole?: unknown- } | null+ 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+ // the actual control-plane endpoint so Root capabilities reflect what the+ // browser can really do.+ const role =+ credential === 'control' &&+ connection.adminApiKey &&+ (await canListAccounts(connection))+ ? 'root'+ : healthRole+return {- accountId: typeof data?.account_id === 'string' ? data.account_id : '',- role: isConnectionRole(data?.role) ? data.role : 'unknown',+ accountId: typeof data.account_id === 'string' ? data.account_id : '',+ role,+ userId: typeof data.user_id === 'string' ? data.user_id : '',+ }+}++export function synchronizeResolvedDataIdentity(+ connection: ConnectionDraft,+ identity: ConnectionIdentity,+): ConnectionDraft | null {+ if (+ (identity.role !== 'admin' && identity.role !== 'user') ||+ !identity.accountId ||+ !identity.userId ||+ (connection.accountId === identity.accountId &&+ connection.userId === identity.userId)+ ) {+ return null+ }++ return {+ ...connection,+ accountId: identity.accountId,+ userId: identity.userId,+ }+}++export function resolveSwitchedIdentity(+ requested: Pick<ConnectionDraft, 'accountId' | 'userId'>,+ identity: ConnectionIdentity,+ allowLegacyIdentityFallback = false,+): Pick<ConnectionDraft, 'accountId' | 'userId'> | null {+ if (+ (identity.role === 'unknown' && !allowLegacyIdentityFallback) ||+ (identity.accountId && identity.accountId !== requested.accountId) ||+ (identity.userId &&+ requested.userId &&+ identity.userId !== requested.userId)+ ) {+ return null+ }++ return {+ accountId: identity.accountId || requested.accountId,+ userId: identity.userId || requested.userId,+ }+}++export function createManagementAccountConnection(+ connection: ConnectionDraft,+ accountId: string,+): ConnectionDraft {+ return {+ ...connection,+ accountId: accountId.trim(),+ apiKey: '',+ userId: '',}}@@ -347,6 +494,8 @@ export function AppConnectionProvider({),)const [serverMode, setServerMode] = React.useState<ServerMode>('checking')+ const [generatedCredential, setGeneratedCredential] =+ React.useState<GeneratedCredential | null>(null)const openConnectionSettings = React.useCallback(() => {if (pathname !== '/settings') {@@ -357,8 +506,7 @@ export function AppConnectionProvider({React.useEffect(() => {applyConnection(connection, serverMode)persistConnection(connection)- void queryClient.invalidateQueries()- }, [connection, queryClient, serverMode])+ }, [connection, serverMode])React.useEffect(() => {let cancelled = false@@ -377,6 +525,7 @@ export function AppConnectionProvider({React.useEffect(() => {let cancelled = false+ const isCancelled = () => cancelledconst apiKey = connection.adminApiKey || connection.apiKeyconst roleProbe = resolveConnectionRoleProbeState({apiKey,@@ -393,21 +542,52 @@ export function AppConnectionProvider({}void detectConnectionIdentity(connection)- .then(({ accountId, role }) => {- if (cancelled) {+ .then(async (controlIdentity) => {+ if (isCancelled()) {return}+ const dataIdentity =+ connection.apiKey &&+ (controlIdentity.role === 'root' ||+ (controlIdentity.role === 'admin' &&+ controlIdentity.accountId === connection.accountId))+ ? await detectConnectionIdentity(connection, 'data')+ : !connection.adminApiKey+ ? controlIdentity+ : null+ if (isCancelled()) {+ return+ }++ const { accountId, role } = controlIdentitysetConnectionRole(role)setConnectionRoleLoading(false)+ const dataConnection = dataIdentity+ ? synchronizeResolvedDataIdentity(connection, dataIdentity)+ : null+ if (dataConnection) {+ const next = synchronizeConnectionRuntime(dataConnection, serverMode)+ queryClient.clear()+ setConnection(next)+ return+ }// An account-admin Root key is scoped to its own account. Pin that// account as the assumed identity so admin and data calls target the// right tenant instead of failing with a mismatch (the server rejects// a foreign account with "ADMIN can only manage account: <x>"). A root// key is not account-scoped, so its account selection is left intact.- if (role === 'admin' && accountId) {- setConnection((prev) =>- prev.accountId === accountId ? prev : { ...prev, accountId },+ if (+ role === 'admin' &&+ accountId &&+ connection.accountId !== accountId+ ) {+ const next = synchronizeConnectionRuntime(+ { ...connection, accountId },+ serverMode,)+ queryClient.clear()+ setConnection(next)+ return}}).catch(() => {@@ -426,6 +606,7 @@ export function AppConnectionProvider({connection.apiKey,connection.baseUrl,connection.userId,+ queryClient,serverMode,])@@ -448,29 +629,90 @@ export function AppConnectionProvider({}}, [openConnectionSettings])- const value = React.useMemo<AppConnectionContextValue>(- () => ({- connection,- connectionRole,- isConnectionRoleLoading,- openConnectionSettings,- saveConnection: (next) => {- authPromptSuppressedUntilRef.current =- Date.now() + AUTH_PROMPT_SUPPRESSION_MS- void queryClient.cancelQueries()- setConnection(normalizeConnectionDraft(next))- },- serverMode,- }),- [+ const value = React.useMemo<AppConnectionContextValue>(() => {+ const commitConnection = (next: ConnectionDraft) => {+ authPromptSuppressedUntilRef.current =+ Date.now() + AUTH_PROMPT_SUPPRESSION_MS+ const normalized = synchronizeConnectionRuntime(next, serverMode)+ queryClient.clear()+ setConnection(normalized)+ }++ return {+ clearGeneratedCredential: () => setGeneratedCredential(null),connection,connectionRole,+ generatedCredential,+ identityScopeKey: createIdentityScopeKey(connection, serverMode),isConnectionRoleLoading,openConnectionSettings,- queryClient,+ saveConnection: commitConnection,+ setGeneratedCredential,serverMode,- ],- )+ switchIdentity: async ({+ accountId,+ allowLegacyIdentityFallback,+ apiKey,+ userId,+ }) => {+ if (serverMode === 'dev' || serverMode === 'checking') {+ throw new Error(+ 'The current server mode does not support identity switching.',+ )+ }++ const requested = normalizeConnectionDraft({+ ...connection,+ accountId,+ apiKey: serverMode === 'trusted' ? '' : apiKey,+ userId,+ })+ const identity = await detectConnectionIdentity(requested, 'data')+ const resolvedIdentity = resolveSwitchedIdentity(+ requested,+ identity,+ allowLegacyIdentityFallback,+ )+ if (!resolvedIdentity) {+ throw new Error(+ 'The selected credential does not match the target account and user.',+ )+ }++ if (pathname === '/playground') {+ await navigate({+ replace: true,+ search: { upload: false },+ to: '/playground',+ })+ }+ commitConnection({+ ...requested,+ ...resolvedIdentity,+ })+ },+ switchManagementAccount: async (accountId) => {+ if (connectionRole !== 'root') {+ throw new Error(+ 'Only a validated Root credential can switch management accounts.',+ )+ }+ commitConnection(+ createManagementAccountConnection(connection, accountId),+ )+ },+ }+ }, [+ connection,+ connectionRole,+ generatedCredential,+ isConnectionRoleLoading,+ navigate,+ openConnectionSettings,+ pathname,+ queryClient,+ serverMode,+ ])return (<AppConnectionContext.Provider value={value}>diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.tsindex fc2cc6061..097f7a68b 100644--- a/web-studio/src/i18n/locales/en.ts+++ b/web-studio/src/i18n/locales/en.ts@@ -1,9 +1,10 @@const en = {appShell: {footer: {- connection: 'Connection & Identity',+ connection: 'Connection Settings',docs: 'Documentation',github: 'GitHub',+ users: 'User Management',},header: {defaultTitle: 'OpenViking Studio',@@ -37,6 +38,50 @@ const en = {workspaceGroupLabel: 'OpenViking Studio',},},+ accountSwitcher: {+ create: 'Create account',+ dialog: {+ accountLabel: 'Account',+ accountPlaceholder: 'team-account',+ adminLabel: 'Initial admin user',+ cancel: 'Cancel',+ description:+ 'Create a workspace and its first administrator. Studio switches to it after creation.',+ submit: 'Create and switch',+ title: 'Create account',+ },+ empty: 'No matching accounts',+ errors: {+ loadAccounts: 'Could not load accounts',+ noCreatedKey:+ 'The account was created, but the server did not return a data credential.',+ noUsableKey:+ 'This account has no plaintext user API key available for data access.',+ noUsers: 'This account has no available users.',+ },+ loading: 'Loading accounts...',+ manualSwitch: {+ description:+ 'The server did not expose a plaintext credential for {{account}}. Enter a User API Key from that account.',+ hint: 'Studio only verifies the key and switches the active data identity. It will not modify or rotate the server credential.',+ keyLabel: 'User API Key',+ keyPlaceholder: 'Paste a User API Key for the target account',+ manageOnly: 'Manage without a User Key',+ submit: 'Verify and switch',+ title: 'Enter a User API Key',+ },+ memberCount: '{{count}} users',+ searchPlaceholder: 'Search accounts',+ toast: {+ created: 'Created and switched to {{account}}',+ createdSwitchFailed:+ 'Created {{account}}, but data identity switching failed: {{error}}. The Account remains available for management.',+ managementSwitched:+ 'Switched management to {{account}}. Select or create a User Key before opening tenant data.',+ switched: 'Switched to {{account}}',+ },+ unset: 'No account selected',+ },common: {action: {cancel: 'Cancel',@@ -106,12 +151,15 @@ const en = {addAccount: 'Add account',addUser: 'Add user',cancel: 'Cancel',+ changeRole: 'Change the role for {{user}}',+ confirmRoleChange: 'Confirm change',copy: 'Copy',+ currentIdentity: 'Current identity',refresh: 'Refresh',regenerate: 'Regenerate',save: 'Save',+ switchIdentity: 'Switch identity',use: 'Use',- useForData: 'Use as User API Key',},connection: {accountListLimited:@@ -121,12 +169,46 @@ const en = {'Use a User API Key for tenant data APIs and an optional Root or account-admin key for control APIs.',devMode:'Development mode is active — identity is automatic and no API key is required.',- noKey:- 'Add a Root API Key to manage accounts and mint user keys. The User API Key alone powers the Playground and data APIs.',+ keyGuide: {+ control: {+ primary:+ 'Your User API Key already enables the Playground and data access. Regular users do not need a control credential.',+ secondary:+ 'To switch Accounts or manage users, request a Root Key from the deployment admin or an Admin Key from the current Account admin. The Root Key is stored at server.root_api_key in the server-side ov.conf.',+ title: 'Need to manage Accounts or users?',+ },+ data: {+ primary:+ 'The Root/Admin API Key is mainly for management. The Playground and tenant data APIs require a User API Key bound to a user identity.',+ secondary:+ 'Select or create a user in User Management, or regenerate its key, then use it as the User API Key.',+ title: 'A User API Key is still required',+ },+ empty: {+ primary:+ 'Regular users should request a User API Key from their Account admin.',+ secondary:+ 'Deployment admins can find the Root API Key at server.root_api_key in the server-side ov.conf. Add it here, then create or regenerate a User Key in User Management.',+ title: 'No OpenViking API Key yet?',+ },+ learnMore: 'Learn how to get an API Key',+ trusted: {+ primary:+ 'This trusted server enforces Root Key validation. The browser needs the same Root API Key for management and tenant data requests.',+ secondary:+ 'Request the Root Key from the deployment admin; it is stored at server.root_api_key in the server-side ov.conf. Trusted-mode data identity comes from Account/User assertions and does not need a User API Key.',+ title: 'This trusted server requires a Root API Key',+ },+ },rootHint: 'Lists accounts and users, and mints or rotates keys.',title: 'Connection settings',userHint: 'Used by the Playground and tenant data APIs.',},+ connectionPage: {+ description:+ 'Configure the OpenViking server connection, control credential, and active data credential.',+ title: 'Connection settings',+ },dialogs: {addAccount: {description:@@ -134,10 +216,17 @@ const en = {title: 'Add account',},addUser: {+ currentAccountDescription:+ 'Create a user in {{accountId}}. The generated key is shown only once.',description:'Register a user under an existing account. The generated key will be shown once.',title: 'Add user',},+ changeRole: {+ description:+ 'Change the role for {{account}} / {{user}} to {{role}}. The new permissions take effect immediately.',+ title: 'Change user role?',+ },regenerate: {description:'Regenerate the API key for {{account}} / {{user}}. The current key stops working immediately.',@@ -182,8 +271,21 @@ const en = {loading: 'Loading identities...',management: {accountFilter: 'Accounts',+ accessDeniedDescription:+ 'User management requires a validated Root or Account Admin API key.',+ accessDeniedTitle: 'User management unavailable',+ currentAccountDescription:+ 'Manage users and access credentials in the {{account}} workspace.',description:'Review users and credentials for selected accounts, then add users or rotate keys from the web UI.',+ memberListDescription:+ '"Switch identity" uses that user for data pages such as Playground and Retrieval without changing the active Root/Admin management credential.',+ 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',+ noUsableKey:+ 'This user has no plaintext API key available for data access.',+ openConnection: 'Open connection settings',title: 'User management',},page: {@@ -204,6 +306,7 @@ const en = {},roles: {admin: 'Admin',+ root: 'Root',user: 'User',},serverMode: {@@ -230,8 +333,9 @@ const en = {connectionSaved: 'Connection saved',copyFailed: 'Copy failed',copied: 'Copied',- dataKeySelected: 'User API key selected',+ dataKeySelected: 'Data access identity switched',keyRegenerated: 'API key regenerated',+ roleUpdated: "{{user}}'s role changed to {{role}}",userCreated: 'User created',},},diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.tsindex 33f3b116b..052a86a7d 100644--- a/web-studio/src/i18n/locales/zh-CN.ts+++ b/web-studio/src/i18n/locales/zh-CN.ts@@ -1,9 +1,10 @@const zhCN = {appShell: {footer: {- connection: '连接与身份',+ connection: '连接设置',docs: '文档站',github: 'GitHub',+ users: '用户管理',},header: {defaultTitle: 'OpenViking Studio',@@ -37,6 +38,48 @@ const zhCN = {workspaceGroupLabel: 'OpenViking Studio',},},+ accountSwitcher: {+ create: '新建 Account',+ dialog: {+ accountLabel: 'Account',+ accountPlaceholder: 'team-account',+ adminLabel: '初始 Admin user',+ cancel: '取消',+ description:+ '创建一个新的空间和首个管理员。创建完成后将自动切换到该空间。',+ submit: '创建并切换',+ title: '新建 Account',+ },+ empty: '没有匹配的 Account',+ errors: {+ loadAccounts: '加载 Account 失败',+ noCreatedKey: 'Account 已创建,但服务端没有返回可用于切换的数据凭证。',+ noUsableKey: '该 Account 没有可用于数据访问的明文 User API Key。',+ noUsers: '该 Account 下没有可用用户。',+ },+ loading: '正在加载 Accounts...',+ manualSwitch: {+ description:+ '服务端没有返回 {{account}} 下的明文凭证。请输入该 Account 中任意用户的 User API Key。',+ hint: 'API Key 只用于校验并切换当前数据身份,不会修改或重新生成服务端凭证。',+ keyLabel: 'User API Key',+ keyPlaceholder: '粘贴目标 Account 的 User API Key',+ manageOnly: '仅管理该 Account',+ submit: '验证并切换',+ title: '输入 User API Key',+ },+ memberCount: '{{count}} 个用户',+ searchPlaceholder: '搜索 Account',+ toast: {+ created: '已创建并切换到 {{account}}',+ createdSwitchFailed:+ '{{account}} 已创建,但数据身份切换失败:{{error}}。仍可进入该 Account 管理用户。',+ managementSwitched:+ '管理空间已切换到 {{account}}。访问租户数据前,请先选择或创建 User Key。',+ switched: '已切换到 {{account}}',+ },+ unset: '未选择 Account',+ },common: {action: {cancel: '取消',@@ -106,12 +149,15 @@ const zhCN = {addAccount: '新增 account',addUser: '新增 user',cancel: '取消',+ changeRole: '修改 {{user}} 的角色',+ confirmRoleChange: '确认修改',copy: '复制',+ currentIdentity: '当前身份',refresh: '刷新',regenerate: '重新生成',save: '保存',+ switchIdentity: '切换身份',use: '使用',- useForData: '用作 User API Key',},connection: {accountListLimited:@@ -120,12 +166,44 @@ const zhCN = {description:'租户数据 API 使用 User API Key;控制 API 可单独使用 Root 或 account-admin key。',devMode: '当前为开发模式 — 身份自动确定,无需 API key。',- noKey:- '填入 Root API Key 即可管理 account / user 并生成 user key。仅凭 User API Key 即可使用 Playground 和数据 API。',+ keyGuide: {+ control: {+ primary:+ '当前 User API Key 已可用于 Playground 和数据访问,普通用户无需配置控制凭证。',+ secondary:+ '如需切换 Account 或管理用户,请向部署管理员索取 Root Key,或向当前 Account 管理员索取 Admin Key。Root Key 位于服务端 ov.conf 的 server.root_api_key。',+ title: '需要管理 Account 或用户?',+ },+ data: {+ primary:+ 'Root/Admin API Key 主要用于管理操作,Playground 和租户数据访问需要绑定用户身份的 User API Key。',+ secondary:+ '请在「用户管理」中选择、创建用户或重新生成 User Key,然后将它用作 User API Key。',+ title: '还缺少 User API Key',+ },+ empty: {+ primary: '普通用户:请向当前 Account 管理员索取 User API Key。',+ secondary:+ '部署管理员:Root API Key 位于服务端 ov.conf 的 server.root_api_key;填入后可在「用户管理」中创建或重新生成 User Key。',+ title: '还没有 OpenViking API Key?',+ },+ learnMore: '查看 API Key 获取方式',+ trusted: {+ primary:+ '当前 Trusted 服务启用了 Root Key 校验,浏览器需要配置同一 Root API Key 才能访问管理和租户数据接口。',+ secondary:+ '请向部署管理员索取 Root Key;它位于服务端 ov.conf 的 server.root_api_key。Trusted 模式的数据身份由 Account/User 断言确定,不需要 User API Key。',+ title: 'Trusted 服务需要 Root API Key',+ },+ },rootHint: '用于列出 account / user,以及生成或轮换 key。',title: '连接设置',userHint: '供 Playground 和租户数据 API 使用。',},+ connectionPage: {+ description: '配置 OpenViking 服务连接、控制面凭证和当前数据访问凭证。',+ title: '连接设置',+ },dialogs: {addAccount: {description:@@ -133,10 +211,17 @@ const zhCN = {title: '新增 account',},addUser: {+ currentAccountDescription:+ '在 {{accountId}} 空间下创建用户。生成的 key 只会在创建后展示一次。',description:'在已有 account 下注册 user。生成的 key 只会在创建后展示一次。',title: '新增 user',},+ changeRole: {+ description:+ '将 {{account}} / {{user}} 的角色修改为 {{role}}。新的权限会立即生效。',+ title: '修改用户角色?',+ },regenerate: {description:'要重新生成 {{account}} / {{user}} 的 API key 吗?当前 key 会立即失效。',@@ -181,8 +266,19 @@ const zhCN = {loading: '正在加载身份...',management: {accountFilter: 'Accounts',+ accessDeniedDescription:+ '只有配置并通过校验的 Root 或 Account Admin API Key 才能管理用户。',+ accessDeniedTitle: '无用户管理权限',+ currentAccountDescription: '管理 {{account}} 空间下的用户和访问凭证。',description:'查看选中 accounts 下的 users 和凭证,并在网页端新增 user 或轮换 key。',+ memberListDescription:+ '“切换身份”会将该用户设为 Playground、检索等数据页面的访问身份,不会改变当前 Root/Admin 管理凭证。',+ memberListDescriptionRoot:+ '可直接修改成员角色;“切换身份”只会改变 Playground、检索等数据页面的访问身份,不会改变当前 Root 管理凭证。',+ memberListTitle: '空间成员',+ noUsableKey: '该用户没有可用于数据访问的明文 API Key。',+ openConnection: '打开连接设置',title: '用户管理',},page: {@@ -203,6 +299,7 @@ const zhCN = {},roles: {admin: 'Admin',+ root: 'Root',user: 'User',},serverMode: {@@ -229,8 +326,9 @@ const zhCN = {connectionSaved: '连接已保存',copyFailed: '复制失败',copied: '已复制',- dataKeySelected: '已选择 User API key',+ dataKeySelected: '已切换数据访问身份',keyRegenerated: 'API key 已重新生成',+ roleUpdated: '{{user}} 的角色已修改为 {{role}}',userCreated: 'User 已创建',},},diff --git a/web-studio/src/lib/admin.ts b/web-studio/src/lib/admin.tsindex bdb139fba..d2edfecaa 100644--- a/web-studio/src/lib/admin.ts+++ b/web-studio/src/lib/admin.ts@@ -8,8 +8,11 @@ import {postAdminAccountIdUserIdKey,postAdminAccountIdUsers,postAdminAccounts,+ putAdminAccountIdUserIdRole,} from '#/lib/ov-client'+export type AdminUserRole = 'admin' | 'root' | 'user'+export type AdminConnection = {accountId: stringapiKey: string@@ -48,6 +51,12 @@ export type KeyResult = {userId?: string}+export type UpdateUserRoleInput = {+ accountId: string+ role: AdminUserRole+ userId: string+}+export type ProbeState = 'ok' | 'error' | 'skipped'export type CapabilityProbeResult = {@@ -410,3 +419,21 @@ export async function regenerateAdminUserKey(user_id: userId,})}++export async function updateAdminUserRole(+ connection: AdminConnection,+ input: UpdateUserRoleInput,+): Promise<void> {+ await getOvResult<unknown>(+ putAdminAccountIdUserIdRole({+ body: {+ role: input.role,+ },+ client: createAdminClient(connection),+ path: {+ account_id: input.accountId,+ user_id: input.userId,+ },+ }),+ )+}diff --git a/web-studio/src/lib/form-input.ts b/web-studio/src/lib/form-input.tsnew file mode 100644index 000000000..233beb693--- /dev/null+++ b/web-studio/src/lib/form-input.ts@@ -0,0 +1,6 @@+export const PLAIN_INPUT_PROPS = {+ autoCapitalize: 'none',+ autoComplete: 'off',+ autoCorrect: 'off',+ spellCheck: false,+} as constdiff --git a/web-studio/src/lib/sessions/use-chat.ts b/web-studio/src/lib/sessions/use-chat.tsindex e8b31d6ca..1eee8f973 100644--- a/web-studio/src/lib/sessions/use-chat.ts+++ b/web-studio/src/lib/sessions/use-chat.ts@@ -131,6 +131,7 @@ function buildAssistantMessage(}export interface UseChatOptions {+ identityScopeKey: stringsessionId: string/** Initial messages to populate the chat. */initialMessages?: Message[]@@ -154,7 +155,12 @@ export interface UseChatReturn {}export function useChat(options: UseChatOptions): UseChatReturn {- const { sessionId, initialMessages, persistMessages = true } = options+ const {+ identityScopeKey,+ sessionId,+ initialMessages,+ persistMessages = true,+ } = optionsconst [messages, setMessages] = useState<Message[]>(initialMessages ?? [])const [status, setStatus] = useState<ChatStatus>('idle')@@ -408,7 +414,10 @@ export function useChat(options: UseChatOptions): UseChatReturn {tool_status: 'running',}try {- toolPart.tool_input = JSON.parse(args) as Record<string, unknown>+ toolPart.tool_input = JSON.parse(args) as Record<+ string,+ unknown+ >} catch {if (args) toolPart.tool_input = { raw: args }}@@ -426,7 +435,8 @@ export function useChat(options: UseChatOptions): UseChatReturn {const pendingToolPart = accParts.find((part): part is ToolPart =>part.type === 'tool' &&- (part.tool_status === 'running' || part.tool_status === 'pending'),+ (part.tool_status === 'running' ||+ part.tool_status === 'pending'),)if (pendingToolCall) {const result = streamEventDataToText(event.data)@@ -486,7 +496,11 @@ export function useChat(options: UseChatOptions): UseChatReturn {// Generate session title on first exchangeif (sessionId && isFirstExchange) {// Immediate: use first user message as temp title- setSessionTitle(sessionId, displayMessage.slice(0, 20))+ setSessionTitle(+ identityScopeKey,+ sessionId,+ displayMessage.slice(0, 20),+ )}} catch (err) {if (controller.signal.aborted) {@@ -513,7 +527,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {abortRef.current = null}},- [status, sessionId, persistMessages],+ [identityScopeKey, persistMessages, sessionId, status],)return {diff --git a/web-studio/src/lib/sessions/use-session-titles.test.ts b/web-studio/src/lib/sessions/use-session-titles.test.tsnew file mode 100644index 000000000..592199b02--- /dev/null+++ b/web-studio/src/lib/sessions/use-session-titles.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest'++import { createSessionTitleStorageKey } from './use-session-titles'++describe('createSessionTitleStorageKey', () => {+ it('partitions session titles by active identity', () => {+ expect(createSessionTitleStorageKey('account-a\u0000alice')).not.toBe(+ createSessionTitleStorageKey('account-b\u0000alice'),+ )+ })++ it('does not expose unescaped identity separators in the storage key', () => {+ expect(createSessionTitleStorageKey('account-a\u0000alice')).not.toContain(+ '\u0000',+ )+ })+})diff --git a/web-studio/src/lib/sessions/use-session-titles.ts b/web-studio/src/lib/sessions/use-session-titles.tsindex 90cce305e..55f5b3917 100644--- a/web-studio/src/lib/sessions/use-session-titles.ts+++ b/web-studio/src/lib/sessions/use-session-titles.ts@@ -1,29 +1,59 @@-import { useSyncExternalStore, useCallback } from 'react'+import { useCallback, useSyncExternalStore } from 'react'const STORAGE_KEY = 'ov-session-titles'+const snapshots = new Map<string, Record<string, string>>()-function readTitles(): Record<string, string> {+export function createSessionTitleStorageKey(identityScopeKey: string): string {+ return `${STORAGE_KEY}.${encodeURIComponent(identityScopeKey)}`+}++function readTitles(storageKey: string): Record<string, string> {try {- const raw = localStorage.getItem(STORAGE_KEY)+ const raw = localStorage.getItem(storageKey)return raw ? (JSON.parse(raw) as Record<string, string>) : {}} catch {return {}}}-function writeTitles(titles: Record<string, string>) {- localStorage.setItem(STORAGE_KEY, JSON.stringify(titles))- // Notify all subscribers within the same tab- window.dispatchEvent(new StorageEvent('storage', { key: STORAGE_KEY }))+function getTitlesSnapshot(storageKey: string): Record<string, string> {+ const current = snapshots.get(storageKey)+ if (current) {+ return current+ }+ const initial = readTitles(storageKey)+ snapshots.set(storageKey, initial)+ return initial}-// Shared snapshot reference — updated on every storage event-let snapshot = readTitles()+function writeTitles(storageKey: string, titles: Record<string, string>) {+ const serialized = JSON.stringify(titles)+ try {+ localStorage.setItem(storageKey, serialized)+ } catch {+ // Keep the in-memory snapshot usable in restricted browser environments.+ }+ snapshots.set(storageKey, titles)+ window.dispatchEvent(+ new StorageEvent('storage', { key: storageKey, newValue: serialized }),+ )+}-function subscribe(onStoreChange: () => void) {- const handler = (e: StorageEvent) => {- if (e.key === STORAGE_KEY || e.key === null) {- snapshot = readTitles()+function subscribe(storageKey: string, onStoreChange: () => void) {+ const handler = (event: StorageEvent) => {+ if (event.key === storageKey || event.key === null) {+ if (event.key === storageKey && event.newValue !== null) {+ try {+ snapshots.set(+ storageKey,+ JSON.parse(event.newValue) as Record<string, string>,+ )+ } catch {+ snapshots.set(storageKey, readTitles(storageKey))+ }+ } else {+ snapshots.set(storageKey, readTitles(storageKey))+ }onStoreChange()}}@@ -31,31 +61,55 @@ function subscribe(onStoreChange: () => void) {return () => window.removeEventListener('storage', handler)}-function getSnapshot() {- return snapshot+export function setSessionTitle(+ identityScopeKey: string,+ sessionId: string,+ title: string,+) {+ const storageKey = createSessionTitleStorageKey(identityScopeKey)+ const titles = { ...getTitlesSnapshot(storageKey), [sessionId]: title }+ writeTitles(storageKey, titles)}-export function setSessionTitle(sessionId: string, title: string) {- const titles = readTitles()- titles[sessionId] = title- writeTitles(titles)- snapshot = titles-}--export function removeSessionTitle(sessionId: string) {- const titles = readTitles()+export function removeSessionTitle(+ identityScopeKey: string,+ sessionId: string,+) {+ const storageKey = createSessionTitleStorageKey(identityScopeKey)+ const titles = { ...getTitlesSnapshot(storageKey) }delete titles[sessionId]- writeTitles(titles)- snapshot = titles+ writeTitles(storageKey, titles)}-export function useSessionTitles() {- const titles = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)+export function useSessionTitles(identityScopeKey: string) {+ const storageKey = createSessionTitleStorageKey(identityScopeKey)+ const subscribeToScope = useCallback(+ (onStoreChange: () => void) => subscribe(storageKey, onStoreChange),+ [storageKey],+ )+ const getSnapshot = useCallback(+ () => getTitlesSnapshot(storageKey),+ [storageKey],+ )+ const titles = useSyncExternalStore(+ subscribeToScope,+ getSnapshot,+ getSnapshot,+ )const getTitle = useCallback((sessionId: string) => titles[sessionId] ?? sessionId,[titles],)+ const setTitle = useCallback(+ (sessionId: string, title: string) =>+ setSessionTitle(identityScopeKey, sessionId, title),+ [identityScopeKey],+ )+ const removeTitle = useCallback(+ (sessionId: string) => removeSessionTitle(identityScopeKey, sessionId),+ [identityScopeKey],+ )- return { titles, getTitle }+ return { getTitle, removeTitle, setTitle, titles }}diff --git a/web-studio/src/lib/studio-permissions.test.ts b/web-studio/src/lib/studio-permissions.test.tsnew file mode 100644index 000000000..5ca42a35b--- /dev/null+++ b/web-studio/src/lib/studio-permissions.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from 'vitest'++import { resolveStudioManagementCapabilities } from './studio-permissions'++describe('resolveStudioManagementCapabilities', () => {+ it('allows a validated root control credential to manage accounts and users', () => {+ expect(+ resolveStudioManagementCapabilities({+ hasControlCredential: true,+ isRoleLoading: false,+ role: 'root',+ serverMode: 'api_key',+ }),+ ).toEqual({+ canManageAccounts: true,+ canManageUsers: true,+ })+ })++ it('allows a verified trusted Root key to manage accounts and users', () => {+ expect(+ resolveStudioManagementCapabilities({+ hasControlCredential: true,+ isRoleLoading: false,+ role: 'root',+ serverMode: 'trusted',+ }),+ ).toEqual({+ canManageAccounts: true,+ canManageUsers: true,+ })+ })++ it('limits account admins to user management', () => {+ expect(+ resolveStudioManagementCapabilities({+ hasControlCredential: true,+ isRoleLoading: false,+ role: 'admin',+ serverMode: 'api_key',+ }),+ ).toEqual({+ canManageAccounts: false,+ canManageUsers: true,+ })+ })++ it('does not expose management to ordinary users', () => {+ expect(+ resolveStudioManagementCapabilities({+ hasControlCredential: true,+ isRoleLoading: false,+ role: 'user',+ serverMode: 'api_key',+ }),+ ).toEqual({+ canManageAccounts: false,+ canManageUsers: false,+ })+ })++ it('does not infer permissions from an unverified input value', () => {+ expect(+ resolveStudioManagementCapabilities({+ hasControlCredential: true,+ isRoleLoading: true,+ role: 'unknown',+ serverMode: 'api_key',+ }),+ ).toEqual({+ canManageAccounts: false,+ canManageUsers: false,+ })+ })+})diff --git a/web-studio/src/lib/studio-permissions.ts b/web-studio/src/lib/studio-permissions.tsnew file mode 100644index 000000000..802d5f4bf--- /dev/null+++ b/web-studio/src/lib/studio-permissions.ts@@ -0,0 +1,31 @@+import type { ConnectionRole } from '#/hooks/use-app-connection'+import type { ServerMode } from '#/hooks/use-server-mode'++export type StudioManagementCapabilities = {+ canManageAccounts: boolean+ canManageUsers: boolean+}++export function resolveStudioManagementCapabilities({+ hasControlCredential,+ isRoleLoading,+ role,+ serverMode,+}: {+ hasControlCredential: boolean+ isRoleLoading: boolean+ role: ConnectionRole+ serverMode: ServerMode+}): StudioManagementCapabilities {+ if (isRoleLoading || serverMode === 'dev' || !hasControlCredential) {+ return {+ canManageAccounts: false,+ canManageUsers: false,+ }+ }++ return {+ canManageAccounts: role === 'root',+ canManageUsers: role === 'root' || role === 'admin',+ }+}diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.tsindex 4f8c425b2..62b41adea 100644--- a/web-studio/src/routeTree.gen.ts+++ b/web-studio/src/routeTree.gen.ts@@ -9,6 +9,7 @@// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.import { Route as rootRouteImport } from './routes/__root'+import { Route as UsersRouteRouteImport } from './routes/users/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'@@ -20,6 +21,11 @@ import { Route as SessionsIndexRouteImport } from './routes/sessions/index'import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'import { Route as OauthConsentRouteImport } from './routes/oauth/consent'+const UsersRouteRoute = UsersRouteRouteImport.update({+ id: '/users',+ path: '/users',+ getParentRoute: () => rootRouteImport,+} as any)const SettingsRouteRoute = SettingsRouteRouteImport.update({id: '/settings',path: '/settings',@@ -79,6 +85,7 @@ export interface FileRoutesByFullPath {'/retrieval': typeof RetrievalRouteRoute'/sessions': typeof SessionsRouteRouteWithChildren'/settings': typeof SettingsRouteRoute+ '/users': typeof UsersRouteRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/verify': typeof OauthVerifyRoute'/sessions/': typeof SessionsIndexRoute@@ -90,6 +97,7 @@ export interface FileRoutesByTo {'/request-logs': typeof RequestLogsRouteRoute'/retrieval': typeof RetrievalRouteRoute'/settings': typeof SettingsRouteRoute+ '/users': typeof UsersRouteRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/verify': typeof OauthVerifyRoute'/sessions': typeof SessionsIndexRoute@@ -103,6 +111,7 @@ export interface FileRoutesById {'/retrieval': typeof RetrievalRouteRoute'/sessions': typeof SessionsRouteRouteWithChildren'/settings': typeof SettingsRouteRoute+ '/users': typeof UsersRouteRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/verify': typeof OauthVerifyRoute'/sessions/': typeof SessionsIndexRoute@@ -117,6 +126,7 @@ export interface FileRouteTypes {| '/retrieval'| '/sessions'| '/settings'+ | '/users'| '/oauth/consent'| '/oauth/verify'| '/sessions/'@@ -128,6 +138,7 @@ export interface FileRouteTypes {| '/request-logs'| '/retrieval'| '/settings'+ | '/users'| '/oauth/consent'| '/oauth/verify'| '/sessions'@@ -140,6 +151,7 @@ export interface FileRouteTypes {| '/retrieval'| '/sessions'| '/settings'+ | '/users'| '/oauth/consent'| '/oauth/verify'| '/sessions/'@@ -153,12 +165,20 @@ export interface RootRouteChildren {RetrievalRouteRoute: typeof RetrievalRouteRouteSessionsRouteRoute: typeof SessionsRouteRouteWithChildrenSettingsRouteRoute: typeof SettingsRouteRoute+ UsersRouteRoute: typeof UsersRouteRouteOauthConsentRoute: typeof OauthConsentRouteOauthVerifyRoute: typeof OauthVerifyRoute}declare module '@tanstack/react-router' {interface FileRoutesByPath {+ '/users': {+ id: '/users'+ path: '/users'+ fullPath: '/users'+ preLoaderRoute: typeof UsersRouteRouteImport+ parentRoute: typeof rootRouteImport+ }'/settings': {id: '/settings'path: '/settings'@@ -252,6 +272,7 @@ const rootRouteChildren: RootRouteChildren = {RetrievalRouteRoute: RetrievalRouteRoute,SessionsRouteRoute: SessionsRouteRouteWithChildren,SettingsRouteRoute: SettingsRouteRoute,+ UsersRouteRoute: UsersRouteRoute,OauthConsentRoute: OauthConsentRoute,OauthVerifyRoute: OauthVerifyRoute,}diff --git a/web-studio/src/routes/playground/-components/agent-panel.tsx b/web-studio/src/routes/playground/-components/agent-panel.tsxindex d0fc46981..63052a167 100644--- a/web-studio/src/routes/playground/-components/agent-panel.tsx+++ b/web-studio/src/routes/playground/-components/agent-panel.tsx@@ -19,6 +19,7 @@ import {DialogTitle,} from '#/components/ui/dialog'import { cn } from '#/lib/utils'+import { useAppConnection } from '#/hooks/use-app-connection'import { createRandomUuid } from '#/lib/browser-crypto'import { useChat } from '#/lib/sessions/use-chat'import {@@ -27,10 +28,7 @@ import {useSessionListByRecency,useSessionMessages,} from '#/lib/sessions/use-sessions'-import {- setSessionTitle,- useSessionTitles,-} from '#/lib/sessions/use-session-titles'+import { useSessionTitles } from '#/lib/sessions/use-session-titles'import { Composer } from '#/routes/sessions/-components/composer'import { MessageList } from '#/routes/sessions/-components/message-list'@@ -52,6 +50,7 @@ export function AgentPanel({onSessionChange: (sessionId: string) => void}) {const { t } = useTranslation('playground')+ const { identityScopeKey } = useAppConnection()const [sessionId, setSessionId] = useState(initialSessionId ?? createRandomUuid(),)@@ -63,12 +62,13 @@ export function AgentPanel({const createSession = useCreateSession()const { data: sessions, isLoading: isLoadingSessions } =useSessionListByRecency()- const { getTitle } = useSessionTitles()+ const { getTitle, setTitle } = useSessionTitles(identityScopeKey)const [playgroundSessionIds, setPlaygroundSessionIds] = useState<string[]>(- () => readPlaygroundAgentSessionIds(),+ () => readPlaygroundAgentSessionIds(identityScopeKey),)const { data: historyMessages } = useSessionMessages(sessionId)const chat = useChat({+ identityScopeKey,initialMessages: historyMessages,persistMessages: true,sessionId,@@ -92,9 +92,9 @@ export function AgentPanel({t('agent.createTimeout'),)setPlaygroundSessionIds(- registerPlaygroundAgentSessionId(result.session_id),+ registerPlaygroundAgentSessionId(result.session_id, identityScopeKey),)- setSessionTitle(result.session_id, t('agent.newSessionTitle'))+ setTitle(result.session_id, t('agent.newSessionTitle'))setSessionId(result.session_id)onSessionChange(result.session_id)setHistoryOpen(false)@@ -104,7 +104,15 @@ export function AgentPanel({} finally {setIsCreatingSession(false)}- }, [chat, createSession, isCreatingSession, onSessionChange, t])+ }, [+ chat,+ createSession,+ identityScopeKey,+ isCreatingSession,+ onSessionChange,+ setTitle,+ t,+ ])const handleSwitchSession = useCallback((nextSessionId: string) => {@@ -112,12 +120,14 @@ export function AgentPanel({creationStartedRef.current = truesetSessionError(null)setIsCreatingSession(false)- setPlaygroundSessionIds(registerPlaygroundAgentSessionId(nextSessionId))+ setPlaygroundSessionIds(+ registerPlaygroundAgentSessionId(nextSessionId, identityScopeKey),+ )setSessionId(nextSessionId)onSessionChange(nextSessionId)setHistoryOpen(false)},- [chat, onSessionChange],+ [chat, identityScopeKey, onSessionChange],)// Notify parent of the initial sessionId so the URL stays in sync.@@ -130,9 +140,11 @@ export function AgentPanel({useEffect(() => {if (sessionId) {- setPlaygroundSessionIds(registerPlaygroundAgentSessionId(sessionId))+ setPlaygroundSessionIds(+ registerPlaygroundAgentSessionId(sessionId, identityScopeKey),+ )}- }, [sessionId])+ }, [identityScopeKey, sessionId])useEffect(() => {bottomRef.current?.scrollIntoView({ behavior: 'smooth' })@@ -156,7 +168,7 @@ export function AgentPanel({// `sessions` is already sorted by recency (newest first). Filter to// sessions that were opened in this playground, preserving recency order.const sessionById = new Map(- (sessions ?? []).map((session) => [session.session_id, session]),+ sessions.map((session) => [session.session_id, session]),)return playgroundSessionIdsdiff --git a/web-studio/src/routes/playground/-components/terminal-panel.tsx b/web-studio/src/routes/playground/-components/terminal-panel.tsxindex 336f8e8e0..9991b67fb 100644--- a/web-studio/src/routes/playground/-components/terminal-panel.tsx+++ b/web-studio/src/routes/playground/-components/terminal-panel.tsx@@ -67,6 +67,7 @@ import type {} from '../-lib/types'import {cleanVikingUri,+ createIdentityStorageKey,entryToRef,getErrorMessage,readStoredJsonArray,@@ -249,9 +250,9 @@ type ParsedOptions = {positional: string[]}-function loadCommandHistory(): string[] {+function loadCommandHistory(storageKey: string): string[] {return readStoredJsonArray(- TERMINAL_COMMAND_HISTORY_STORAGE_KEY,+ storageKey,(item) => {if (typeof item !== 'string') return undefinedconst trimmed = item.trim()@@ -261,11 +262,8 @@ function loadCommandHistory(): string[] {)}-function persistCommandHistory(history: string[]): void {- writeStoredJson(- TERMINAL_COMMAND_HISTORY_STORAGE_KEY,- history.slice(0, TERMINAL_COMMAND_HISTORY_LIMIT),- )+function persistCommandHistory(storageKey: string, history: string[]): void {+ writeStoredJson(storageKey, history.slice(0, TERMINAL_COMMAND_HISTORY_LIMIT))}function normalizeRefs(value: unknown): ResourceRef[] | undefined {@@ -285,9 +283,9 @@ function normalizeRefs(value: unknown): ResourceRef[] | undefined {return refs.length > 0 ? refs : undefined}-function loadTerminalHistory(): TerminalEntry[] {+function loadTerminalHistory(storageKey: string): TerminalEntry[] {return readStoredJsonArray(- TERMINAL_ENTRY_HISTORY_STORAGE_KEY,+ storageKey,(item): TerminalEntry | undefined => {if (typeof item !== 'object' || item === null) return undefinedconst record = item as Record<string, unknown>@@ -314,15 +312,15 @@ function loadTerminalHistory(): TerminalEntry[] {)}-function persistTerminalHistory(history: TerminalEntry[]): void {- writeStoredJson(- TERMINAL_ENTRY_HISTORY_STORAGE_KEY,- history.slice(-TERMINAL_ENTRY_HISTORY_LIMIT),- )+function persistTerminalHistory(+ storageKey: string,+ history: TerminalEntry[],+): void {+ writeStoredJson(storageKey, history.slice(-TERMINAL_ENTRY_HISTORY_LIMIT))}-function clearPersistedTerminalHistory(): void {- removeStoredValue(TERMINAL_ENTRY_HISTORY_STORAGE_KEY)+function clearPersistedTerminalHistory(storageKey: string): void {+ removeStoredValue(storageKey)}function extractVikingUris(text: string): string[] {@@ -462,13 +460,25 @@ export function TerminalPanel({sessionId?: string}) {const { t } = useTranslation('playground')- const { connectionRole } = useAppConnection()+ const { connectionRole, identityScopeKey } = useAppConnection()+ const commandHistoryStorageKey = createIdentityStorageKey(+ TERMINAL_COMMAND_HISTORY_STORAGE_KEY,+ identityScopeKey,+ )+ const terminalHistoryStorageKey = createIdentityStorageKey(+ TERMINAL_ENTRY_HISTORY_STORAGE_KEY,+ identityScopeKey,+ )const [command, setCommand] = useState('')const [running, setRunning] = useState(false)const [suggestionsOpen, setSuggestionsOpen] = useState(false)const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(0)- const [commandHistory, setCommandHistory] = useState(loadCommandHistory)- const [history, setHistory] = useState(loadTerminalHistory)+ const [commandHistory, setCommandHistory] = useState(() =>+ loadCommandHistory(commandHistoryStorageKey),+ )+ const [history, setHistory] = useState(() =>+ loadTerminalHistory(terminalHistoryStorageKey),+ )const [historyOpen, setHistoryOpen] = useState(false)const [inputFocused, setInputFocused] = useState(false)const inputRef = useRef<HTMLInputElement>(null)@@ -592,18 +602,16 @@ export function TerminalPanel({if (!isChoosingSubcommand) return []- return SESSION_SUBCOMMANDS.filter(- (item) => {- const description = t(- `terminal.commandExamples.${item.examples[0]}.description`,- )- return (- !partial ||- item.key.toLowerCase().startsWith(partial.toLowerCase()) ||- description.toLowerCase().includes(partial.toLowerCase())- )- },- ).map((item) => {+ return SESSION_SUBCOMMANDS.filter((item) => {+ const description = t(+ `terminal.commandExamples.${item.examples[0]}.description`,+ )+ return (+ !partial ||+ item.key.toLowerCase().startsWith(partial.toLowerCase()) ||+ description.toLowerCase().includes(partial.toLowerCase())+ )+ }).map((item) => {return {...activeCommand,command: item.key,@@ -735,10 +743,7 @@ export function TerminalPanel({}, [suggestions.length])useEffect(() => {- suggestionRefs.current = suggestionRefs.current.slice(- 0,- suggestions.length,- )+ suggestionRefs.current = suggestionRefs.current.slice(0, suggestions.length)}, [suggestions.length])useEffect(() => {@@ -755,37 +760,45 @@ export function TerminalPanel({})}, [history.length, running])- const append = useCallback((entry: Omit<TerminalEntry, 'id'>) => {- setHistory((prev) => {- const next = [- ...prev,- {- ...entry,- id: `${Date.now()}-${prev.length}`,- },- ].slice(-TERMINAL_ENTRY_HISTORY_LIMIT)- persistTerminalHistory(next)- return next- })- }, [])+ const append = useCallback(+ (entry: Omit<TerminalEntry, 'id'>) => {+ setHistory((prev) => {+ const next = [+ ...prev,+ {+ ...entry,+ id: `${Date.now()}-${prev.length}`,+ },+ ].slice(-TERMINAL_ENTRY_HISTORY_LIMIT)+ persistTerminalHistory(terminalHistoryStorageKey, next)+ return next+ })+ },+ [terminalHistoryStorageKey],+ )const clearHistory = useCallback(() => {setHistory([])- clearPersistedTerminalHistory()- }, [])+ clearPersistedTerminalHistory(terminalHistoryStorageKey)+ }, [terminalHistoryStorageKey])- const rememberCommand = useCallback((raw: string) => {- const trimmed = raw.trim()- if (!trimmed) return- setCommandHistory((prev) => {- const next = [- trimmed,- ...prev.filter((item) => item.toLowerCase() !== trimmed.toLowerCase()),- ].slice(0, TERMINAL_COMMAND_HISTORY_LIMIT)- persistCommandHistory(next)- return next- })- }, [])+ const rememberCommand = useCallback(+ (raw: string) => {+ const trimmed = raw.trim()+ if (!trimmed) return+ setCommandHistory((prev) => {+ const next = [+ trimmed,+ ...prev.filter(+ (item) => item.toLowerCase() !== trimmed.toLowerCase(),+ ),+ ].slice(0, TERMINAL_COMMAND_HISTORY_LIMIT)+ persistCommandHistory(commandHistoryStorageKey, next)+ return next+ })+ },+ [commandHistoryStorageKey],+ )const runCommand = useCallback(async (raw: string) => {@@ -1017,7 +1030,10 @@ export function TerminalPanel({case 'create': {const requestedId = positional.shift()const result = await createSession(requestedId)- registerPlaygroundAgentSessionId(result.session_id)+ registerPlaygroundAgentSessionId(+ result.session_id,+ identityScopeKey,+ )onSessionChange(result.session_id)append({body: joinBodyLines([@@ -1035,7 +1051,7 @@ export function TerminalPanel({case 'switch': {const id = positional.shift()if (!id) throw new Error(t('terminal.sessionUsage'))- registerPlaygroundAgentSessionId(id)+ registerPlaygroundAgentSessionId(id, identityScopeKey)onSessionChange(id)append({body: t('terminal.sessionSwitchedBody', { id }),@@ -1138,7 +1154,10 @@ export function TerminalPanel({? positional.slice(0, roleIndex).join(' '): requireCurrentSession()const role = positional[roleIndex] as 'user' | 'assistant'- const content = positional.slice(roleIndex + 1).join(' ').trim()+ const content = positional+ .slice(roleIndex + 1)+ .join(' ')+ .trim()if (!content) throw new Error(t('terminal.sessionUsage'))const result = await addMessage(id, role, content)append({@@ -1277,6 +1296,7 @@ export function TerminalPanel({currentUri,entries,groupLabels,+ identityScopeKey,onOpenAddResource,onOpenResource,onSessionChange,diff --git a/web-studio/src/routes/playground/-lib/utils.test.ts b/web-studio/src/routes/playground/-lib/utils.test.tsnew file mode 100644index 000000000..915558b99--- /dev/null+++ b/web-studio/src/routes/playground/-lib/utils.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest'++import { createIdentityStorageKey } from './utils'++describe('createIdentityStorageKey', () => {+ it('isolates persisted Playground state by identity scope', () => {+ const baseKey = 'openviking.playground.terminalEntryHistory'++ expect(createIdentityStorageKey(baseKey, 'account-a\u0000alice')).not.toBe(+ createIdentityStorageKey(baseKey, 'account-b\u0000bob'),+ )+ })++ it('keeps the storage key browser-safe', () => {+ const key = createIdentityStorageKey(+ 'openviking.playground.agentSessions',+ 'http://localhost:1933\u0000api_key\u0000account-a\u0000alice',+ )++ expect(key).not.toContain('\u0000')+ })+})diff --git a/web-studio/src/routes/playground/-lib/utils.ts b/web-studio/src/routes/playground/-lib/utils.tsindex da1189ab0..f7dd45765 100644--- a/web-studio/src/routes/playground/-lib/utils.ts+++ b/web-studio/src/routes/playground/-lib/utils.ts@@ -98,9 +98,21 @@ export function removeStoredValue(key: string): void {}}-export function readPlaygroundAgentSessionIds(): string[] {+export function createIdentityStorageKey(+ key: string,+ identityScopeKey: string,+): string {+ return `${key}.${encodeURIComponent(identityScopeKey)}`+}++export function readPlaygroundAgentSessionIds(+ identityScopeKey: string,+): string[] {return readStoredJsonArray(- PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY,+ createIdentityStorageKey(+ PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY,+ identityScopeKey,+ ),(sessionId) =>typeof sessionId === 'string' && sessionId.length > 0? sessionId@@ -108,17 +120,28 @@ export function readPlaygroundAgentSessionIds(): string[] {)}-export function registerPlaygroundAgentSessionId(sessionId: string): string[] {+export function registerPlaygroundAgentSessionId(+ sessionId: string,+ identityScopeKey: string,+): string[] {const trimmed = sessionId.trim()if (typeof window === 'undefined') return trimmed ? [trimmed] : []- if (!trimmed) return readPlaygroundAgentSessionIds()+ if (!trimmed) return readPlaygroundAgentSessionIds(identityScopeKey)const next = [trimmed,- ...readPlaygroundAgentSessionIds().filter((item) => item !== trimmed),+ ...readPlaygroundAgentSessionIds(identityScopeKey).filter(+ (item) => item !== trimmed,+ ),].slice(0, 50)- writeStoredJson(PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY, next)+ writeStoredJson(+ createIdentityStorageKey(+ PLAYGROUND_AGENT_SESSIONS_STORAGE_KEY,+ identityScopeKey,+ ),+ next,+ )return next}diff --git a/web-studio/src/routes/sessions/-components/thread.tsx b/web-studio/src/routes/sessions/-components/thread.tsxindex 6baf956f4..6f93ac8d4 100644--- a/web-studio/src/routes/sessions/-components/thread.tsx+++ b/web-studio/src/routes/sessions/-components/thread.tsx@@ -2,6 +2,7 @@ import { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'import { CompassIcon } from 'lucide-react'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 { useSessionTitles } from '#/lib/sessions/use-session-titles'@@ -16,12 +17,14 @@ interface ThreadProps {}export function Thread({ sessionId }: ThreadProps) {- const { getTitle } = useSessionTitles()+ const { identityScopeKey } = useAppConnection()+ const { getTitle } = useSessionTitles(identityScopeKey)const title = getTitle(sessionId)const { data: historyMessages } = useSessionMessages(sessionId)const chat = useChat({+ identityScopeKey,sessionId,initialMessages: historyMessages,persistMessages: true,@@ -55,10 +58,7 @@ export function Thread({ sessionId }: ThreadProps) {scrollRafRef.current = requestAnimationFrame(() => {bottomRef.current?.scrollIntoView({ behavior: 'smooth' })})- }, [- chat.messages.length,- chat.streamingParts,- ])+ }, [chat.messages.length, chat.streamingParts])const [showBackground, setShowBackground] = useState(false)diff --git a/web-studio/src/routes/sessions/index.tsx b/web-studio/src/routes/sessions/index.tsxindex 76243093f..5f932a87f 100644--- a/web-studio/src/routes/sessions/index.tsx+++ b/web-studio/src/routes/sessions/index.tsx@@ -3,8 +3,9 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'import { CompassIcon } from 'lucide-react'import { useTranslation } from 'react-i18next'+import { useAppConnection } from '#/hooks/use-app-connection'import { useCreateSession } from '#/lib/sessions/use-sessions'-import { setSessionTitle } from '#/lib/sessions/use-session-titles'+import { useSessionTitles } from '#/lib/sessions/use-session-titles'import { Thread } from './-components/thread'const COMMAND_KEY_LABEL = '⌘'@@ -21,14 +22,16 @@ export const Route = createFileRoute('/sessions/')({function SessionsPage() {const { t } = useTranslation('sessions')const { s: activeSessionId } = Route.useSearch()+ const { identityScopeKey } = useAppConnection()const navigate = useNavigate()const createSession = useCreateSession()+ const { setTitle } = useSessionTitles(identityScopeKey)const handleNewSession = useCallback(async () => {const result = await createSession.mutateAsync(undefined)- setSessionTitle(result.session_id, t('threadList.newSession'))+ setTitle(result.session_id, t('threadList.newSession'))void navigate({ to: '/sessions', search: { s: result.session_id } })- }, [createSession, navigate, t])+ }, [createSession, navigate, setTitle, t])// Cmd+N to create new sessionuseEffect(() => {diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsxindex 3ccb5493c..b77a5471b 100644--- a/web-studio/src/routes/settings/route.tsx+++ b/web-studio/src/routes/settings/route.tsx@@ -1,44 +1,19 @@import * as React from 'react'-import {- keepPreviousData,- useMutation,- useQuery,- useQueryClient,-} from '@tanstack/react-query'+import { keepPreviousData, useQuery } from '@tanstack/react-query'import { createFileRoute } from '@tanstack/react-router'import {CircleAlertIcon,CircleDashedIcon,- CopyIcon,+ CircleHelpIcon,+ ExternalLinkIcon,KeyRoundIcon,- PlusIcon,- RefreshCwIcon,- RotateCwIcon,- ServerIcon,ShieldCheckIcon,- UserRoundIcon,- UsersRoundIcon,} from 'lucide-react'-import { toast } from 'sonner'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,- CardDescription,- CardHeader,- CardTitle,-} from '#/components/ui/card'-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '#/components/ui/dialog'+import { Card, CardContent, CardHeader, CardTitle } from '#/components/ui/card'import {Field,FieldContent,@@ -46,186 +21,18 @@ import {FieldLabel,} from '#/components/ui/field'import { Input } from '#/components/ui/input'-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '#/components/ui/select'-import {- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,-} from '#/components/ui/table'-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from '#/components/ui/alert-dialog'import { useAppConnection } from '#/hooks/use-app-connection'-import { copyTextToClipboard } from '#/lib/clipboard'+import { probeStudioConnection } from '#/lib/admin'+import type { CapabilityProbeResult } from '#/lib/admin'+import { DEFAULT_ACCOUNT_ID, DEFAULT_USER_ID } from '#/lib/admin-options'+import { PLAIN_INPUT_PROPS } from '#/lib/form-input'import { cn } from '#/lib/utils'import type { ConnectionDraft } from '#/hooks/use-app-connection'-import { AccountSelect } from '#/components/identity-select'-import {- DEFAULT_ACCOUNT_ID,- DEFAULT_USER_ID,- sortedAccountIds,- sortedAccounts,-} from '#/lib/admin-options'-import {- createAdminAccount,- createAdminUser,- fetchAdminAccounts,- fetchAdminUsers,- probeStudioConnection,- regenerateAdminUserKey,-} from '#/lib/admin'-import type {- AdminConnection,- AdminAccount,- AdminUser,- CapabilityProbeResult,- CreateAccountInput,- CreateUserInput,- KeyResult,-} from '#/lib/admin'-export const Route = createFileRoute('/settings')({- component: SettingsRoute,+ component: ConnectionSettingsRoute,})-const USER_ROLES = ['user', 'admin'] as const--type AddAccountDraft = CreateAccountInput-type AddUserDraft = CreateUserInput--// Server URLs, API keys, and account/user ids are case-sensitive freeform-// values. Browsers (and mobile keyboards) otherwise auto-capitalize the first-// letter — turning "http://" into "Http://" — and run autocorrect/spellcheck.-// Disable all of it on these inputs.-const PLAIN_INPUT_PROPS = {- autoCapitalize: 'none',- autoComplete: 'off',- autoCorrect: 'off',- spellCheck: false,-} as const--function getErrorMessage(error: unknown): string {- return error instanceof Error ? error.message : String(error)-}--function maskApiKey(value: string | undefined): string {- if (!value) {- return '-'- }-- if (value.length <= 16) {- return value- }-- return `${value.slice(0, 10)}...${value.slice(-6)}`-}--function resolveKeyLabel(user: AdminUser): string {- return user.apiKey ? maskApiKey(user.apiKey) : user.keyPrefix || '-'-}--function StatCard({- icon,- label,- value,-}: {- icon: React.ReactNode- label: string- value: React.ReactNode-}) {- return (- <Card className="bg-card/70 py-4">- <CardContent className="flex items-center justify-between gap-4 px-5">- <div>- <p className="text-sm text-muted-foreground">{label}</p>- <p className="mt-1 text-2xl font-semibold tabular-nums">{value}</p>- </div>- <div className="flex size-10 items-center justify-center rounded-md border bg-background/70 text-primary">- {icon}- </div>- </CardContent>- </Card>- )-}--function KeyResultCard({- onClear,- onUseAsUserKey,- result,-}: {- onClear: () => void- onUseAsUserKey: () => void- result: KeyResult-}) {- const { t } = useTranslation('settings')-- if (!result.apiKey) {- return null- }-- async function copyKey(): Promise<void> {- try {- await copyTextToClipboard(result.apiKey)- toast.success(t('toast.copied'))- } catch {- toast.error(t('toast.copyFailed'))- }- }-- return (- <Card className="border-primary/20 bg-primary/5 py-4">- <CardContent className="grid gap-3 px-5">- <div className="flex flex-wrap items-start justify-between gap-3">- <div>- <p className="font-medium">{t('keyResult.title')}</p>- <p className="mt-1 text-sm text-muted-foreground">- {t('keyResult.description')}- </p>- </div>- <Button type="button" variant="ghost" size="sm" onClick={onClear}>- {t('keyResult.dismiss')}- </Button>- </div>- <div className="flex min-w-0 flex-col gap-2 rounded-md border bg-background/80 p-3 sm:flex-row sm:items-center">- <code className="min-w-0 flex-1 truncate font-mono text-sm">- {result.apiKey}- </code>- <Button type="button" variant="outline" size="sm" onClick={copyKey}>- <CopyIcon />- {t('actions.copy')}- </Button>- <Button- type="button"- variant="default"- size="sm"- onClick={onUseAsUserKey}- >- <KeyRoundIcon />- {t('actions.useForData')}- </Button>- </div>- </CardContent>- </Card>- )-}-function getCapabilityIcon(result: CapabilityProbeResult | undefined) {if (!result) {return <CircleDashedIcon className="size-4" />@@ -279,73 +86,8 @@ function CapabilityStatus({)}-function AccountFilterChips({- accounts,- disabled,- label,- onChange,- selectedAccountIds,-}: {- accounts: readonly AdminAccount[]- disabled?: boolean- label: string- onChange: (value: string[]) => void- selectedAccountIds: readonly string[]-}) {- const options = sortedAccountIds(- accounts.map((account) => account.accountId),- selectedAccountIds[0] || DEFAULT_ACCOUNT_ID,- )- const selected = new Set(selectedAccountIds)-- function toggle(accountId: string): void {- if (disabled) {- return- }- if (selected.has(accountId)) {- const next = selectedAccountIds.filter((item) => item !== accountId)- if (next.length > 0) {- onChange(next)- }- return- }- onChange([...selectedAccountIds, accountId])- }-- return (- <div className="flex min-w-0 flex-col gap-2">- <span className="text-xs font-medium text-muted-foreground">{label}</span>- <div className="flex max-w-full min-w-0 flex-wrap gap-2">- {options.map((accountId) => {- const isSelected = selected.has(accountId)-- return (- <button- key={accountId}- type="button"- aria-pressed={isSelected}- disabled={disabled}- onClick={() => toggle(accountId)}- title={accountId}- className={cn(- 'h-8 max-w-full truncate rounded-full border px-3 font-mono text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50 sm:max-w-72',- isSelected- ? 'border-primary bg-primary text-primary-foreground'- : 'border-border bg-background text-muted-foreground hover:border-primary/50 hover:text-foreground',- )}- >- {accountId}- </button>- )- })}- </div>- </div>- )-}-function UserApiKeyInput({accountId,- disabled,id,onChange,placeholder,@@ -353,7 +95,6 @@ function UserApiKeyInput({value,}: {accountId: string- disabled?: booleanid: stringonChange: (value: string) => voidplaceholder: string@@ -363,12 +104,7 @@ function UserApiKeyInput({const identity = `${accountId || DEFAULT_ACCOUNT_ID}/${userId || DEFAULT_USER_ID}`return (- <div- className={cn(- 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30',- disabled && 'cursor-not-allowed opacity-50',- )}- >+ <div className="flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30"><span className="shrink-0 rounded-sm bg-muted px-2 py-1 font-mono text-xs text-muted-foreground">[{identity}]</span>@@ -376,340 +112,64 @@ function UserApiKeyInput({id={id}type="password"value={value}- disabled={disabled}onChange={(event) => onChange(event.target.value)}placeholder={placeholder}- className="h-full min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"+ className="h-full min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"{...PLAIN_INPUT_PROPS}/></div>)}-function AddAccountDialog({- isPending,- onCreate,- onOpenChange,- open,-}: {- isPending: boolean- onCreate: (draft: AddAccountDraft) => void- onOpenChange: (open: boolean) => void- open: boolean-}) {- const { t } = useTranslation('settings')- const [draft, setDraft] = React.useState<AddAccountDraft>({- accountId: '',- adminUserId: DEFAULT_USER_ID,- })-- React.useEffect(() => {- if (open) {- setDraft({ accountId: '', adminUserId: DEFAULT_USER_ID })- }- }, [open])-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>{t('dialogs.addAccount.title')}</DialogTitle>- <DialogDescription>- {t('dialogs.addAccount.description')}- </DialogDescription>- </DialogHeader>- <form- className="grid gap-4"- onSubmit={(event) => {- event.preventDefault()- onCreate(draft)- }}- >- <Field>- <FieldLabel htmlFor="settings-add-account-id">- {t('fields.account')}- </FieldLabel>- <FieldContent>- <Input- id="settings-add-account-id"- value={draft.accountId}- onChange={(event) =>- setDraft((current) => ({- ...current,- accountId: event.target.value,- }))- }- placeholder={t('placeholders.account')}- required- {...PLAIN_INPUT_PROPS}- />- </FieldContent>- </Field>- <Field>- <FieldLabel htmlFor="settings-add-account-admin">- {t('fields.adminUser')}- </FieldLabel>- <FieldContent>- <Input- id="settings-add-account-admin"- value={draft.adminUserId}- onChange={(event) =>- setDraft((current) => ({- ...current,- adminUserId: event.target.value,- }))- }- placeholder={DEFAULT_USER_ID}- required- {...PLAIN_INPUT_PROPS}- />- </FieldContent>- </Field>- <DialogFooter>- <Button- type="button"- variant="outline"- onClick={() => onOpenChange(false)}- >- {t('actions.cancel')}- </Button>- <Button type="submit" disabled={isPending}>- <PlusIcon />- {t('actions.addAccount')}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}--function AddUserDialog({- accounts,- defaultAccountId,- isPending,- onCreate,- onOpenChange,- open,-}: {- accounts: readonly AdminAccount[]- defaultAccountId: string- isPending: boolean- onCreate: (draft: AddUserDraft) => void- onOpenChange: (open: boolean) => void- open: boolean-}) {- const { t } = useTranslation('settings')- const [draft, setDraft] = React.useState<AddUserDraft>({- accountId: defaultAccountId || DEFAULT_ACCOUNT_ID,- role: 'user',- userId: '',- })-- React.useEffect(() => {- if (open) {- setDraft({- accountId: defaultAccountId || DEFAULT_ACCOUNT_ID,- role: 'user',- userId: '',- })- }- }, [defaultAccountId, open])-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>{t('dialogs.addUser.title')}</DialogTitle>- <DialogDescription>- {t('dialogs.addUser.description')}- </DialogDescription>- </DialogHeader>- <form- className="grid gap-4"- onSubmit={(event) => {- event.preventDefault()- onCreate(draft)- }}- >- <Field>- <FieldLabel>{t('fields.account')}</FieldLabel>- <FieldContent>- <AccountSelect- accounts={accounts}- label={t('fields.account')}- value={draft.accountId}- onChange={(accountId) =>- setDraft((current) => ({ ...current, accountId }))- }- />- </FieldContent>- </Field>- <Field>- <FieldLabel htmlFor="settings-add-user-id">- {t('fields.user')}- </FieldLabel>- <FieldContent>- <Input- id="settings-add-user-id"- value={draft.userId}- onChange={(event) =>- setDraft((current) => ({- ...current,- userId: event.target.value,- }))- }- placeholder={t('placeholders.user')}- required- {...PLAIN_INPUT_PROPS}- />- </FieldContent>- </Field>- <Field>- <FieldLabel>{t('fields.role')}</FieldLabel>- <FieldContent>- <Select- value={draft.role}- onValueChange={(role) => {- if (role) {- setDraft((current) => ({ ...current, role }))- }- }}- >- <SelectTrigger- aria-label={t('fields.role')}- className="h-9 w-full"- >- <SelectValue>{t(`roles.${draft.role}`)}</SelectValue>- </SelectTrigger>- <SelectContent alignItemWithTrigger>- {USER_ROLES.map((role) => (- <SelectItem key={role} value={role}>- {t(`roles.${role}`)}- </SelectItem>- ))}- </SelectContent>- </Select>- </FieldContent>- </Field>- <DialogFooter>- <Button- type="button"- variant="outline"- onClick={() => onOpenChange(false)}- >- {t('actions.cancel')}- </Button>- <Button type="submit" disabled={isPending}>- <PlusIcon />- {t('actions.addUser')}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}--function SettingsRoute() {- const { t } = useTranslation('settings')- const queryClient = useQueryClient()- const { connection, connectionRole, saveConnection, serverMode } =- useAppConnection()+function ConnectionSettingsRoute() {+ const { i18n, t } = useTranslation('settings')+ const { connection, saveConnection, serverMode } = useAppConnection()const [draft, setDraft] = React.useState<ConnectionDraft>(connection)- const [managedAccountIds, setManagedAccountIds] = React.useState<string[]>([- connection.accountId || DEFAULT_ACCOUNT_ID,- ])- const [addAccountOpen, setAddAccountOpen] = React.useState(false)- const [addUserOpen, setAddUserOpen] = React.useState(false)- const [keyResult, setKeyResult] = React.useState<KeyResult | null>(null)- const [pendingRegenerateUser, setPendingRegenerateUser] =- React.useState<AdminUser | null>(null)-- // Debounced persistence. `draft` is the live, editable buffer behind the- // inputs; `connection` is the committed value everything else keys off (the- // probe, the admin queries, applyConnection, server-mode detection). Typing- // only updates draft and schedules a commit, so we don't re-probe / re-detect- // / refetch on every keystroke. Programmatic changes (adopting or rotating a- // key) commit immediately.+ const pendingDraftRef = React.useRef<ConnectionDraft | null>(null)+ const saveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)const saveConnectionRef = React.useRef(saveConnection)+React.useEffect(() => {saveConnectionRef.current = saveConnection}, [saveConnection])- const pendingDraftRef = React.useRef<ConnectionDraft | null>(null)- const saveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)- const commitConnection = React.useCallback((next: ConnectionDraft) => {- if (saveTimerRef.current) {- clearTimeout(saveTimerRef.current)- saveTimerRef.current = null+ React.useEffect(() => {+ if (!pendingDraftRef.current) {+ setDraft(connection)}- pendingDraftRef.current = null- saveConnectionRef.current(next)- }, [])-- const commitConnectionDebounced = React.useCallback(- (next: ConnectionDraft) => {- pendingDraftRef.current = next- if (saveTimerRef.current) {- clearTimeout(saveTimerRef.current)- }- saveTimerRef.current = setTimeout(() => {- saveTimerRef.current = null- const pending = pendingDraftRef.current- pendingDraftRef.current = null- if (pending) {- saveConnectionRef.current(pending)- }- }, 350)- },- [],- )+ }, [connection])- // Flush a still-pending edit when leaving the page so the last keystrokes are- // not lost. Empty deps -> the cleanup runs only on unmount.React.useEffect(() => {return () => {if (saveTimerRef.current) {clearTimeout(saveTimerRef.current)- saveTimerRef.current = null}- const pending = pendingDraftRef.current- pendingDraftRef.current = null- if (pending) {- saveConnectionRef.current(pending)+ if (pendingDraftRef.current) {+ saveConnectionRef.current(pendingDraftRef.current)}}}, [])- // Mirror committed connection changes back into the buffer, but never while an- // edit is still pending (that would clobber what the user is typing).- React.useEffect(() => {- if (pendingDraftRef.current) {- return+ function updateDraft(next: Partial<ConnectionDraft>): void {+ const updated = { ...draft, ...next }+ setDraft(updated)+ pendingDraftRef.current = updated+ if (saveTimerRef.current) {+ clearTimeout(saveTimerRef.current)}- setDraft(connection)- }, [connection])-- const isDevMode = serverMode === 'dev'- // The Root API key is the only control-plane credential and drives every- // admin call below. The User API key powers tenant data APIs (Playground,- // retrieval, ...). Keeping the two keys cleanly separated is the whole point- // of this screen. These derive from the committed connection (not the live- // draft) so the heavy work waits until typing settles.- const rootApiKey = connection.adminApiKey.trim()- const adminConnection = React.useMemo<AdminConnection>(- () => ({- accountId: connection.accountId || DEFAULT_ACCOUNT_ID,- apiKey: rootApiKey,- baseUrl: connection.baseUrl,- userId: connection.userId || DEFAULT_USER_ID,- }),- [rootApiKey, connection.accountId, connection.baseUrl, connection.userId],- )+ saveTimerRef.current = setTimeout(() => {+ saveTimerRef.current = null+ const pending = pendingDraftRef.current+ pendingDraftRef.current = null+ if (pending) {+ saveConnectionRef.current(pending)+ }+ }, 350)+ }const probeQuery = useQuery({enabled: Boolean(connection.baseUrl) && serverMode !== 'checking',+ placeholderData: keepPreviousData,queryFn: () =>probeStudioConnection({accountId: connection.accountId || DEFAULT_ACCOUNT_ID,@@ -728,234 +188,62 @@ function SettingsRoute() {connection.userId,serverMode,],- // Keep showing the last probe result while a new identity/key is being- // checked, so adopting a user key (or editing a key) does not blank out the- // Admin/Data status and the whole User Management panel mid-refetch.- placeholderData: keepPreviousData,retry: false,staleTime: 15_000,})+ const isDevMode = serverMode === 'dev'+ const rootApiKey = connection.adminApiKey.trim()+ const hasControlCredential = Boolean(draft.adminApiKey.trim())+ const hasDataCredential = Boolean(draft.apiKey.trim())const adminProbe = probeQuery.data?.admin+ const dataProbe = probeQuery.data?.dataconst hasAdminAccess = !isDevMode && adminProbe?.state === 'ok'- const showAdminDescription =- hasAdminAccess || connectionRole === 'admin' || connectionRole === 'root'- const canQueryAdmin = Boolean(rootApiKey) && hasAdminAccess-- const accountsQuery = useQuery({- enabled: canQueryAdmin,- queryFn: () => fetchAdminAccounts(adminConnection),- queryKey: [- 'admin-accounts',- adminConnection.baseUrl,- adminConnection.apiKey,- adminConnection.accountId,- adminConnection.userId,- ],- retry: false,- })-- const selectedAccountId = connection.accountId || DEFAULT_ACCOUNT_ID- const selectedManagedAccountIds = React.useMemo(() => {- const selected = sortedAccountIds(managedAccountIds, '')- return selected.length > 0- ? selected- : sortedAccountIds([selectedAccountId], '')- }, [managedAccountIds, selectedAccountId])-- const managedUsersQuery = useQuery({- enabled: canQueryAdmin && selectedManagedAccountIds.length > 0,- queryFn: async () => {- const usersByAccount = await Promise.all(- selectedManagedAccountIds.map((accountId) =>- fetchAdminUsers(adminConnection, accountId),- ),- )- return usersByAccount.flat()- },- queryKey: [- 'admin-users',- adminConnection.baseUrl,- adminConnection.apiKey,- adminConnection.accountId,- adminConnection.userId,- 'managed',- selectedManagedAccountIds,- ],- retry: false,- })-- const accountOptions = React.useMemo<AdminAccount[]>(() => {- if (accountsQuery.data) {- return sortedAccounts(accountsQuery.data)- }-- return sortedAccounts(- selectedManagedAccountIds.map((accountId) => ({- accountId,- userCount:- managedUsersQuery.data?.filter((user) => user.accountId === accountId)- .length ?? 0,- })),- )- }, [accountsQuery.data, managedUsersQuery.data, selectedManagedAccountIds])-- // Keep the management account filter pointed at an account that still exists.- // This never mutates the active identity — that only changes when the user- // explicitly adopts a key via "Use as User API Key".- React.useEffect(() => {- if (!accountOptions.length) {- return- }- const accountIds = accountOptions.map((account) => account.accountId)- const preferred = accountIds.includes(DEFAULT_ACCOUNT_ID)- ? DEFAULT_ACCOUNT_ID- : accountIds[0]- setManagedAccountIds((current) => {- const next = current.filter((accountId) => accountIds.includes(accountId))- const resolved = next.length > 0 ? next : [preferred]- // Return the SAME reference when nothing actually changed. filter() always- // builds a fresh array, and handing a new reference back would re-key the- // selectedManagedAccountIds -> accountOptions memos and re-fire this- // effect on every render — an unbounded loop.- const unchanged =- resolved.length === current.length &&- resolved.every((accountId, index) => accountId === current[index])- return unchanged ? current : resolved- })- }, [accountOptions])-- function buildUserKeyConnection(- current: ConnectionDraft,- result: KeyResult,- ): ConnectionDraft {- return {- ...current,- accountId: result.accountId || current.accountId || DEFAULT_ACCOUNT_ID,- apiKey: result.apiKey || current.apiKey,- userId: result.userId || current.userId || DEFAULT_USER_ID,- }- }-- // Field edits debounce the commit (no probe/refetch per keystroke).- function updateDraft(next: Partial<ConnectionDraft>): void {- const updated = { ...draft, ...next }- setDraft(updated)- commitConnectionDebounced(updated)- }-- function useUserKey(result: KeyResult): void {- if (!result.apiKey) {- return- }- // Adopting a key is an explicit action — commit it right away.- const next = buildUserKeyConnection(draft, result)- setDraft(next)- commitConnection(next)- toast.success(t('toast.dataKeySelected'))- }-- const createAccountMutation = useMutation({- mutationFn: (input: CreateAccountInput) =>- createAdminAccount(adminConnection, input),- onError: (error) => toast.error(getErrorMessage(error)),- onSuccess: async (result, variables) => {- setKeyResult({- ...result,- accountId: result.accountId || variables.accountId,- userId: result.userId || variables.adminUserId,- })- setManagedAccountIds([variables.accountId])- setAddAccountOpen(false)- toast.success(t('toast.accountCreated'))- await queryClient.invalidateQueries({ queryKey: ['admin-accounts'] })- await queryClient.invalidateQueries({ queryKey: ['admin-users'] })- },- })-- const createUserMutation = useMutation({- mutationFn: (input: CreateUserInput) =>- createAdminUser(adminConnection, input),- onError: (error) => toast.error(getErrorMessage(error)),- onSuccess: async (result, variables) => {- setKeyResult({- ...result,- accountId: result.accountId || variables.accountId,- userId: result.userId || variables.userId,- })- setManagedAccountIds((current) =>- sortedAccountIds([...current, variables.accountId], ''),- )- setAddUserOpen(false)- toast.success(t('toast.userCreated'))- await queryClient.invalidateQueries({ queryKey: ['admin-accounts'] })- await queryClient.invalidateQueries({ queryKey: ['admin-users'] })- },- })-- const regenerateMutation = useMutation({- mutationFn: (user: AdminUser) =>- regenerateAdminUserKey(adminConnection, user.accountId, user.userId),- onError: (error) => toast.error(getErrorMessage(error)),- onSuccess: async (result, user) => {- setKeyResult(result)- // If the rotated user is the one currently powering data APIs, keep the- // active User API key in sync so the session does not silently break.- if (- result.apiKey &&- user.accountId === draft.accountId &&- user.userId === draft.userId- ) {- const next = buildUserKeyConnection(draft, result)- setDraft(next)- commitConnection(next)- }- setPendingRegenerateUser(null)- toast.success(t('toast.keyRegenerated'))- await queryClient.invalidateQueries({ queryKey: ['admin-users'] })- },- })-- const managedUsers = managedUsersQuery.data ?? []- const totalAccounts = accountOptions.length- const totalUsers =- accountOptions.reduce((sum, account) => sum + account.userCount, 0) ||- managedUsers.length- const visibleKeys = managedUsers.filter(- (user) => user.apiKey || user.keyPrefix,- ).length- const adminUnavailable = !canQueryAdmin || managedUsersQuery.isError-- async function refreshAdmin(): Promise<void> {- await Promise.all([- accountsQuery.refetch(),- managedUsersQuery.refetch(),- probeQuery.refetch(),- ])- }-- async function copyKey(value: string | undefined): Promise<void> {- if (!value) {- return- }- try {- await copyTextToClipboard(value)- toast.success(t('toast.copied'))- } catch {- toast.error(t('toast.copyFailed'))- }- }+ const authenticationGuideUrl = i18n.resolvedLanguage?.startsWith('zh')+ ? 'https://docs.openviking.ai/zh/guides/04-authentication'+ : 'https://docs.openviking.ai/en/guides/04-authentication'+ const trustedCredentialRequired =+ serverMode === 'trusted' &&+ !probeQuery.isFetching &&+ !hasControlCredential &&+ (adminProbe?.state === 'error' || dataProbe?.state === 'error')+ const keyGuide =+ serverMode === 'trusted'+ ? trustedCredentialRequired+ ? {+ primary: t('connection.keyGuide.trusted.primary'),+ secondary: t('connection.keyGuide.trusted.secondary'),+ title: t('connection.keyGuide.trusted.title'),+ }+ : null+ : !hasControlCredential && !hasDataCredential+ ? {+ primary: t('connection.keyGuide.empty.primary'),+ secondary: t('connection.keyGuide.empty.secondary'),+ title: t('connection.keyGuide.empty.title'),+ }+ : !hasControlCredential+ ? {+ primary: t('connection.keyGuide.control.primary'),+ secondary: t('connection.keyGuide.control.secondary'),+ title: t('connection.keyGuide.control.title'),+ }+ : !hasDataCredential+ ? {+ primary: t('connection.keyGuide.data.primary'),+ secondary: t('connection.keyGuide.data.secondary'),+ title: t('connection.keyGuide.data.title'),+ }+ : nullreturn (<div className="flex w-full min-w-0 flex-col gap-5"><header className="flex flex-col gap-2"><h1 className="text-2xl font-semibold tracking-tight">- {t('page.title')}+ {t('connectionPage.title')}</h1><p className="max-w-3xl text-sm leading-6 text-muted-foreground">- {showAdminDescription- ? t('page.adminDescription')- : t('page.description')}+ {t('connectionPage.description')}</p></header>@@ -1025,9 +313,9 @@ function SettingsRoute() {</FieldLabel><FieldContent><UserApiKeyInput- accountId={draft.accountId || DEFAULT_ACCOUNT_ID}+ accountId={draft.accountId}id="settings-user-api-key"- userId={draft.userId || DEFAULT_USER_ID}+ userId={draft.userId}value={draft.apiKey}onChange={(apiKey) => updateDraft({ apiKey })}placeholder={t('placeholders.userApiKey')}@@ -1048,17 +336,34 @@ function SettingsRoute() {<CapabilityStatusisLoading={probeQuery.isFetching}label={t('health.data')}- result={probeQuery.data?.data}+ result={dataProbe}/></div>- {!hasAdminAccess && !rootApiKey ? (- <p className="text-sm text-muted-foreground">- {t('connection.noKey')}- </p>- ) : !hasAdminAccess &&- rootApiKey &&- adminProbe?.state === 'error' ? (+ {(serverMode === 'api_key' || serverMode === 'trusted') &&+ keyGuide ? (+ <Alert className="border-primary/25 bg-primary/[0.045]">+ <CircleHelpIcon className="text-primary" />+ <AlertTitle>{keyGuide.title}</AlertTitle>+ <AlertDescription className="grid gap-1.5 text-pretty [&_p:not(:last-child)]:mb-0">+ <p>{keyGuide.primary}</p>+ <p>{keyGuide.secondary}</p>+ <a+ href={authenticationGuideUrl}+ target="_blank"+ rel="noreferrer"+ className="mt-1 inline-flex w-fit items-center gap-1 font-medium text-foreground"+ >+ {t('connection.keyGuide.learnMore')}+ <ExternalLinkIcon className="size-3.5" />+ </a>+ </AlertDescription>+ </Alert>+ ) : null}++ {!hasAdminAccess &&+ rootApiKey &&+ adminProbe?.state === 'error' ? (<p className="text-sm text-destructive">{t('connection.adminError', {message: adminProbe.detail || '',@@ -1069,255 +374,6 @@ function SettingsRoute() {)}</CardContent></Card>-- {hasAdminAccess ? (- <div className="grid gap-3 md:grid-cols-3">- <StatCard- label={t('stats.accounts')}- value={totalAccounts || '-'}- icon={<ServerIcon className="size-4" />}- />- <StatCard- label={t('stats.users')}- value={totalUsers || '-'}- icon={<UsersRoundIcon className="size-4" />}- />- <StatCard- label={t('stats.apiKeys')}- value={visibleKeys || '-'}- icon={<KeyRoundIcon className="size-4" />}- />- </div>- ) : null}-- {hasAdminAccess && keyResult ? (- <KeyResultCard- result={keyResult}- onClear={() => setKeyResult(null)}- onUseAsUserKey={() => useUserKey(keyResult)}- />- ) : null}-- {hasAdminAccess ? (- <Card className="overflow-hidden">- <CardHeader className="gap-4 border-b bg-muted/20">- <div className="flex min-w-0 flex-col gap-4">- <div className="min-w-0">- <CardTitle>{t('management.title')}</CardTitle>- <CardDescription className="max-w-3xl">- {t('management.description')}- </CardDescription>- </div>- <div className="flex min-w-0 flex-col gap-3 xl:flex-row xl:items-end xl:justify-between">- <div className="min-w-0 flex-1">- <AccountFilterChips- accounts={accountOptions}- disabled={!canQueryAdmin || accountsQuery.isLoading}- label={t('management.accountFilter')}- selectedAccountIds={selectedManagedAccountIds}- onChange={setManagedAccountIds}- />- </div>- <div className="flex shrink-0 flex-wrap gap-2 xl:justify-end">- <Button- type="button"- variant="outline"- onClick={() => void refreshAdmin()}- disabled={!canQueryAdmin || managedUsersQuery.isFetching}- >- <RefreshCwIcon- className={cn(- managedUsersQuery.isFetching && 'animate-spin',- )}- />- {t('actions.refresh')}- </Button>- <Button- type="button"- onClick={() => setAddAccountOpen(true)}- disabled={!canQueryAdmin}- >- <PlusIcon />- {t('actions.addAccount')}- </Button>- <Button- type="button"- onClick={() => setAddUserOpen(true)}- disabled={!canQueryAdmin}- >- <PlusIcon />- {t('actions.addUser')}- </Button>- </div>- </div>- </div>- </CardHeader>- <CardContent className="p-0">- {adminUnavailable ? (- <div className="flex min-h-56 flex-col items-center justify-center gap-2 px-6 text-center">- <div className="flex size-11 items-center justify-center rounded-lg border bg-muted/30 text-muted-foreground">- <KeyRoundIcon className="size-5" />- </div>- <p className="font-medium">{t('empty.adminTitle')}</p>- <p className="max-w-lg text-sm text-muted-foreground">- {t('empty.adminDescription')}- </p>- </div>- ) : managedUsersQuery.isLoading ? (- <div className="flex min-h-56 items-center justify-center text-sm text-muted-foreground">- {t('loading')}- </div>- ) : managedUsers.length === 0 ? (- <div className="flex min-h-56 flex-col items-center justify-center gap-2 px-6 text-center">- <div className="flex size-11 items-center justify-center rounded-lg border bg-muted/30 text-muted-foreground">- <UserRoundIcon className="size-5" />- </div>- <p className="font-medium">{t('empty.usersTitle')}</p>- <p className="text-sm text-muted-foreground">- {t('empty.usersDescription')}- </p>- </div>- ) : (- <div className="overflow-x-auto">- <Table>- <TableHeader>- <TableRow className="bg-muted/20 hover:bg-muted/20">- <TableHead>{t('table.account')}</TableHead>- <TableHead>{t('table.user')}</TableHead>- <TableHead>{t('table.role')}</TableHead>- <TableHead>{t('table.apiKey')}</TableHead>- <TableHead className="text-right">- {t('table.actions')}- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {managedUsers.map((user) => (- <TableRow key={`${user.accountId}:${user.userId}`}>- <TableCell className="font-mono text-xs text-muted-foreground">- {user.accountId}- </TableCell>- <TableCell className="font-medium">- {user.userId}- </TableCell>- <TableCell>- <Badge- variant={- user.role === 'admin' ? 'secondary' : 'outline'- }- >- {t(`roles.${user.role}`, {- defaultValue: user.role,- })}- </Badge>- </TableCell>- <TableCell>- <div className="flex min-w-0 items-center gap-2">- <code className="max-w-[20rem] truncate rounded-md border bg-muted/40 px-2 py-1 font-mono text-xs">- {resolveKeyLabel(user)}- </code>- {user.apiKey ? (- <Button- type="button"- variant="ghost"- size="icon-xs"- aria-label={t('actions.copy')}- onClick={() => void copyKey(user.apiKey)}- >- <CopyIcon />- </Button>- ) : null}- </div>- </TableCell>- <TableCell>- <div className="flex justify-end gap-2">- {user.apiKey ? (- <Button- type="button"- variant="secondary"- size="sm"- onClick={() =>- useUserKey({- accountId: user.accountId,- apiKey: user.apiKey || '',- userId: user.userId,- })- }- >- <KeyRoundIcon />- {t('actions.useForData')}- </Button>- ) : null}- <Button- type="button"- variant="outline"- size="sm"- onClick={() => setPendingRegenerateUser(user)}- disabled={regenerateMutation.isPending}- >- <RotateCwIcon />- {t('actions.regenerate')}- </Button>- </div>- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </div>- )}- </CardContent>- </Card>- ) : null}-- <AddAccountDialog- open={addAccountOpen}- onOpenChange={setAddAccountOpen}- isPending={createAccountMutation.isPending}- onCreate={(next) => createAccountMutation.mutate(next)}- />- <AddUserDialog- open={addUserOpen}- onOpenChange={setAddUserOpen}- accounts={accountOptions}- defaultAccountId={selectedManagedAccountIds[0] || selectedAccountId}- isPending={createUserMutation.isPending}- onCreate={(next) => createUserMutation.mutate(next)}- />- <AlertDialog- open={Boolean(pendingRegenerateUser)}- onOpenChange={(open) => {- if (!open) {- setPendingRegenerateUser(null)- }- }}- >- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>{t('dialogs.regenerate.title')}</AlertDialogTitle>- <AlertDialogDescription>- {t('dialogs.regenerate.description', {- account: pendingRegenerateUser?.accountId,- user: pendingRegenerateUser?.userId,- })}- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>{t('actions.cancel')}</AlertDialogCancel>- <AlertDialogAction- onClick={() => {- if (pendingRegenerateUser) {- regenerateMutation.mutate(pendingRegenerateUser)- }- }}- disabled={regenerateMutation.isPending}- >- <RotateCwIcon />- {t('actions.regenerate')}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog></div>)}diff --git a/web-studio/src/routes/users/route.tsx b/web-studio/src/routes/users/route.tsxnew file mode 100644index 000000000..1b12f525f--- /dev/null+++ b/web-studio/src/routes/users/route.tsx@@ -0,0 +1,738 @@+import * as React from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { Link, createFileRoute } from '@tanstack/react-router'+import {+ CheckIcon,+ CopyIcon,+ KeyRoundIcon,+ LoaderCircleIcon,+ PlusIcon,+ RefreshCwIcon,+ RotateCwIcon,+ ShieldAlertIcon,+ UsersRoundIcon,+} 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 {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '#/components/ui/dialog'+import { Input } from '#/components/ui/input'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '#/components/ui/select'+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '#/components/ui/table'+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from '#/components/ui/alert-dialog'+import { useAppConnection } from '#/hooks/use-app-connection'+import {+ createAdminUser,+ fetchAdminUsers,+ regenerateAdminUserKey,+ updateAdminUserRole,+} from '#/lib/admin'+import type {+ AdminConnection,+ AdminUser,+ AdminUserRole,+ CreateUserInput,+ KeyResult,+ UpdateUserRoleInput,+} from '#/lib/admin'+import { copyTextToClipboard } from '#/lib/clipboard'+import { PLAIN_INPUT_PROPS } from '#/lib/form-input'+import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'++export const Route = createFileRoute('/users')({+ component: UserManagementRoute,+})++const USER_ROLE_OPTIONS: AdminUserRole[] = ['user', 'admin', 'root']++function getErrorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++function isAdminUserRole(role: string): role is AdminUserRole {+ return USER_ROLE_OPTIONS.includes(role as AdminUserRole)+}++function maskApiKey(value: string | undefined): string {+ if (!value) {+ return '-'+ }+ if (value.length <= 16) {+ return value+ }+ return `${value.slice(0, 10)}...${value.slice(-6)}`+}++function resolveKeyLabel(user: AdminUser): string {+ return user.apiKey ? maskApiKey(user.apiKey) : user.keyPrefix || '-'+}++function UserManagementRoute() {+ const { t } = useTranslation('settings')+ const queryClient = useQueryClient()+ const {+ connection,+ connectionRole,+ isConnectionRoleLoading,+ setGeneratedCredential,+ serverMode,+ switchIdentity,+ } = useAppConnection()+ const [addUserOpen, setAddUserOpen] = React.useState(false)+ const [pendingRegenerateUser, setPendingRegenerateUser] =+ React.useState<AdminUser | null>(null)+ const [pendingRoleChange, setPendingRoleChange] =+ React.useState<UpdateUserRoleInput | null>(null)+ const [switchingIdentityKey, setSwitchingIdentityKey] = React.useState('')++ const { canManageAccounts, canManageUsers } =+ resolveStudioManagementCapabilities({+ hasControlCredential: Boolean(connection.adminApiKey.trim()),+ isRoleLoading: isConnectionRoleLoading,+ role: connectionRole,+ serverMode,+ })++ const adminConnection = React.useMemo<AdminConnection>(+ () => ({+ accountId: connection.accountId,+ apiKey: connection.adminApiKey,+ baseUrl: connection.baseUrl,+ userId: connection.userId,+ }),+ [+ connection.accountId,+ connection.adminApiKey,+ connection.baseUrl,+ connection.userId,+ ],+ )++ const usersQuery = useQuery({+ enabled: canManageUsers && Boolean(connection.accountId),+ queryFn: () => fetchAdminUsers(adminConnection, connection.accountId),+ queryKey: [+ 'managed-users',+ adminConnection.baseUrl,+ adminConnection.apiKey,+ connection.accountId,+ ],+ retry: false,+ })++ const createUser = useMutation({+ mutationFn: (input: CreateUserInput) =>+ createAdminUser(adminConnection, input),+ onError: (error) => toast.error(getErrorMessage(error)),+ onSuccess: async (result, input) => {+ setGeneratedCredential(result)+ setAddUserOpen(false)+ if (result.apiKey) {+ try {+ await switchIdentity({+ accountId: result.accountId || input.accountId,+ allowLegacyIdentityFallback: true,+ apiKey: result.apiKey,+ userId: result.userId || input.userId,+ })+ } catch (error) {+ toast.error(getErrorMessage(error))+ }+ }+ toast.success(t('toast.userCreated'))+ await queryClient.invalidateQueries({ queryKey: ['managed-users'] })+ await queryClient.invalidateQueries({ queryKey: ['account-switcher'] })+ },+ })++ const regenerateKey = useMutation({+ mutationFn: (user: AdminUser) =>+ regenerateAdminUserKey(adminConnection, user.accountId, user.userId),+ onError: (error) => toast.error(getErrorMessage(error)),+ onSuccess: async (result, user) => {+ setGeneratedCredential(result)+ setPendingRegenerateUser(null)+ if (+ user.accountId === connection.accountId &&+ user.userId === connection.userId &&+ result.apiKey+ ) {+ await switchIdentity({+ accountId: user.accountId,+ allowLegacyIdentityFallback: true,+ apiKey: result.apiKey,+ userId: user.userId,+ })+ }+ toast.success(t('toast.keyRegenerated'))+ await queryClient.invalidateQueries({ queryKey: ['managed-users'] })+ },+ })++ const updateRole = useMutation({+ mutationFn: (input: UpdateUserRoleInput) =>+ updateAdminUserRole(adminConnection, input),+ onError: (error) => toast.error(getErrorMessage(error)),+ onSuccess: async (_, input) => {+ setPendingRoleChange(null)+ toast.success(+ t('toast.roleUpdated', {+ role: t(`roles.${input.role}`),+ user: input.userId,+ }),+ )+ await queryClient.invalidateQueries({ queryKey: ['managed-users'] })+ },+ })++ async function copyKey(value: string | undefined): Promise<void> {+ if (!value) {+ return+ }+ try {+ await copyTextToClipboard(value)+ toast.success(t('toast.copied'))+ } catch {+ toast.error(t('toast.copyFailed'))+ }+ }++ async function useUserIdentity(user: AdminUser | KeyResult): Promise<void> {+ if (!user.apiKey) {+ toast.error(t('management.noUsableKey'))+ return+ }+ const accountId = user.accountId || connection.accountId+ const userId = user.userId || connection.userId+ const identityKey = `${accountId}:${userId}`+ setSwitchingIdentityKey(identityKey)+ try {+ await switchIdentity({+ accountId,+ allowLegacyIdentityFallback: true,+ apiKey: user.apiKey,+ userId,+ })+ toast.success(t('toast.dataKeySelected'))+ } catch (error) {+ toast.error(getErrorMessage(error))+ } finally {+ setSwitchingIdentityKey('')+ }+ }++ if (isConnectionRoleLoading) {+ return (+ <div className="flex min-h-64 items-center justify-center gap-2 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-4 animate-spin" />+ {t('loading')}+ </div>+ )+ }++ if (!canManageUsers) {+ return (+ <Card className="mx-auto mt-10 w-full max-w-xl">+ <CardHeader className="items-center text-center">+ <div className="mb-2 flex size-12 items-center justify-center rounded-xl border bg-muted/40 text-muted-foreground">+ <ShieldAlertIcon className="size-5" />+ </div>+ <CardTitle>{t('management.accessDeniedTitle')}</CardTitle>+ <CardDescription>+ {t('management.accessDeniedDescription')}+ </CardDescription>+ </CardHeader>+ <CardContent className="flex justify-center">+ <Button nativeButton={false} render={<Link to="/settings" />}>+ <KeyRoundIcon />+ {t('management.openConnection')}+ </Button>+ </CardContent>+ </Card>+ )+ }++ const users = usersQuery.data ?? []+ const visibleKeys = users.filter(+ (user) => user.apiKey || user.keyPrefix,+ ).length+ return (+ <div className="flex w-full min-w-0 flex-col gap-5">+ <header className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">+ <div className="flex min-w-0 flex-col gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <h1 className="text-2xl font-semibold tracking-tight">+ {t('management.title')}+ </h1>+ <Badge variant="secondary" className="max-w-72 truncate font-mono">+ {connection.accountId}+ </Badge>+ </div>+ <p className="max-w-3xl text-sm leading-6 text-muted-foreground">+ {t('management.currentAccountDescription', {+ account: connection.accountId,+ })}+ </p>+ </div>+ <div className="flex shrink-0 flex-wrap gap-2">+ <Button+ type="button"+ variant="outline"+ onClick={() => void usersQuery.refetch()}+ disabled={usersQuery.isFetching}+ >+ <RefreshCwIcon+ className={usersQuery.isFetching ? 'animate-spin' : undefined}+ />+ {t('actions.refresh')}+ </Button>+ <Button type="button" onClick={() => setAddUserOpen(true)}>+ <PlusIcon />+ {t('actions.addUser')}+ </Button>+ </div>+ </header>++ <div className="grid gap-3 sm:grid-cols-2">+ <Card className="bg-card/70 py-4">+ <CardContent className="flex items-center justify-between gap-4 px-5">+ <div>+ <p className="text-sm text-muted-foreground">+ {t('stats.users')}+ </p>+ <p className="mt-1 text-2xl font-semibold tabular-nums">+ {users.length || '-'}+ </p>+ </div>+ <div className="flex size-10 items-center justify-center rounded-md border bg-background/70 text-primary">+ <UsersRoundIcon className="size-4" />+ </div>+ </CardContent>+ </Card>+ <Card className="bg-card/70 py-4">+ <CardContent className="flex items-center justify-between gap-4 px-5">+ <div>+ <p className="text-sm text-muted-foreground">+ {t('stats.apiKeys')}+ </p>+ <p className="mt-1 text-2xl font-semibold tabular-nums">+ {visibleKeys || '-'}+ </p>+ </div>+ <div className="flex size-10 items-center justify-center rounded-md border bg-background/70 text-primary">+ <KeyRoundIcon className="size-4" />+ </div>+ </CardContent>+ </Card>+ </div>++ <Card className="overflow-hidden">+ <CardHeader className="border-b bg-muted/20">+ <CardTitle>{t('management.memberListTitle')}</CardTitle>+ <CardDescription>+ {t(+ canManageAccounts+ ? 'management.memberListDescriptionRoot'+ : 'management.memberListDescription',+ )}+ </CardDescription>+ </CardHeader>+ <CardContent className="p-0">+ {usersQuery.isLoading ? (+ <div className="flex min-h-56 items-center justify-center gap-2 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-4 animate-spin" />+ {t('loading')}+ </div>+ ) : usersQuery.isError ? (+ <div className="flex min-h-56 flex-col items-center justify-center gap-2 px-6 text-center">+ <p className="font-medium">{t('empty.adminTitle')}</p>+ <p className="max-w-lg text-sm text-muted-foreground">+ {getErrorMessage(usersQuery.error)}+ </p>+ </div>+ ) : users.length === 0 ? (+ <div className="flex min-h-56 flex-col items-center justify-center gap-2 px-6 text-center">+ <p className="font-medium">{t('empty.usersTitle')}</p>+ <p className="text-sm text-muted-foreground">+ {t('empty.usersDescription')}+ </p>+ </div>+ ) : (+ <div className="overflow-x-auto">+ <Table>+ <TableHeader>+ <TableRow className="bg-muted/20 hover:bg-muted/20">+ <TableHead>{t('table.user')}</TableHead>+ <TableHead>{t('table.role')}</TableHead>+ <TableHead>{t('table.apiKey')}</TableHead>+ <TableHead className="text-right">+ {t('table.actions')}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {users.map((user) => {+ const identityKey = `${user.accountId}:${user.userId}`+ const isCurrentIdentity =+ user.accountId === connection.accountId &&+ user.userId === connection.userId+ const isSwitching = switchingIdentityKey === identityKey++ return (+ <TableRow+ key={identityKey}+ className={+ isCurrentIdentity ? 'bg-primary/[0.025]' : ''+ }+ >+ <TableCell className="font-medium">+ <div className="flex items-center gap-2">+ {user.userId}+ {isCurrentIdentity ? (+ <Badge+ variant="secondary"+ className="gap-1 font-normal"+ >+ <CheckIcon />+ {t('actions.currentIdentity')}+ </Badge>+ ) : null}+ </div>+ </TableCell>+ <TableCell>+ {canManageAccounts && isAdminUserRole(user.role) ? (+ <Select+ value={user.role}+ disabled={updateRole.isPending}+ onValueChange={(role) => {+ if (+ role &&+ isAdminUserRole(role) &&+ role !== user.role+ ) {+ setPendingRoleChange({+ accountId: user.accountId,+ role,+ userId: user.userId,+ })+ }+ }}+ >+ <SelectTrigger+ className="h-8 w-28"+ aria-label={t('actions.changeRole', {+ user: user.userId,+ })}+ >+ <SelectValue>+ {t(`roles.${user.role}`)}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {USER_ROLE_OPTIONS.map((role) => (+ <SelectItem key={role} value={role}>+ {t(`roles.${role}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <Badge+ variant={+ user.role === 'admin' ? 'secondary' : 'outline'+ }+ >+ {t(`roles.${user.role}`, {+ defaultValue: user.role,+ })}+ </Badge>+ )}+ </TableCell>+ <TableCell>+ <div className="flex min-w-0 items-center gap-2">+ <code className="max-w-[20rem] truncate rounded-md border bg-muted/40 px-2 py-1 font-mono text-xs">+ {resolveKeyLabel(user)}+ </code>+ {user.apiKey ? (+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label={t('actions.copy')}+ onClick={() => void copyKey(user.apiKey)}+ >+ <CopyIcon />+ </Button>+ ) : null}+ </div>+ </TableCell>+ <TableCell>+ <div className="flex justify-end gap-2">+ {user.apiKey && !isCurrentIdentity ? (+ <Button+ type="button"+ variant="secondary"+ size="sm"+ disabled={Boolean(switchingIdentityKey)}+ onClick={() => void useUserIdentity(user)}+ >+ {isSwitching ? (+ <LoaderCircleIcon className="animate-spin" />+ ) : (+ <KeyRoundIcon />+ )}+ {t('actions.switchIdentity')}+ </Button>+ ) : null}+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => setPendingRegenerateUser(user)}+ disabled={+ regenerateKey.isPending ||+ Boolean(switchingIdentityKey)+ }+ >+ <RotateCwIcon />+ {t('actions.regenerate')}+ </Button>+ </div>+ </TableCell>+ </TableRow>+ )+ })}+ </TableBody>+ </Table>+ </div>+ )}+ </CardContent>+ </Card>++ <AddUserDialog+ open={addUserOpen}+ onOpenChange={setAddUserOpen}+ accountId={connection.accountId}+ isPending={createUser.isPending}+ onCreate={(input) => createUser.mutate(input)}+ />++ <AlertDialog+ open={Boolean(pendingRegenerateUser)}+ onOpenChange={(open) => {+ if (!open) {+ setPendingRegenerateUser(null)+ }+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t('dialogs.regenerate.title')}</AlertDialogTitle>+ <AlertDialogDescription>+ {t('dialogs.regenerate.description', {+ account: pendingRegenerateUser?.accountId,+ user: pendingRegenerateUser?.userId,+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t('actions.cancel')}</AlertDialogCancel>+ <AlertDialogAction+ onClick={() => {+ if (pendingRegenerateUser) {+ regenerateKey.mutate(pendingRegenerateUser)+ }+ }}+ disabled={regenerateKey.isPending}+ >+ <RotateCwIcon />+ {t('actions.regenerate')}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ <AlertDialog+ open={Boolean(pendingRoleChange)}+ onOpenChange={(open) => {+ if (!open && !updateRole.isPending) {+ setPendingRoleChange(null)+ }+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t('dialogs.changeRole.title')}</AlertDialogTitle>+ <AlertDialogDescription>+ {t('dialogs.changeRole.description', {+ account: pendingRoleChange?.accountId,+ role: pendingRoleChange+ ? t(`roles.${pendingRoleChange.role}`)+ : '',+ user: pendingRoleChange?.userId,+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={updateRole.isPending}>+ {t('actions.cancel')}+ </AlertDialogCancel>+ <AlertDialogAction+ disabled={updateRole.isPending}+ onClick={(event) => {+ event.preventDefault()+ if (pendingRoleChange) {+ updateRole.mutate(pendingRoleChange)+ }+ }}+ >+ {updateRole.isPending ? (+ <LoaderCircleIcon className="animate-spin" />+ ) : null}+ {t('actions.confirmRoleChange')}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ )+}++function AddUserDialog({+ accountId,+ isPending,+ onCreate,+ onOpenChange,+ open,+}: {+ accountId: string+ isPending: boolean+ onCreate: (draft: CreateUserInput) => void+ onOpenChange: (open: boolean) => void+ open: boolean+}) {+ const { t } = useTranslation('settings')+ const [draft, setDraft] = React.useState<CreateUserInput>({+ accountId,+ role: 'user',+ userId: '',+ })++ React.useEffect(() => {+ if (open) {+ setDraft({ accountId, role: 'user', userId: '' })+ }+ }, [accountId, open])++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <form+ onSubmit={(event) => {+ event.preventDefault()+ onCreate(draft)+ }}+ >+ <DialogHeader>+ <DialogTitle>{t('dialogs.addUser.title')}</DialogTitle>+ <DialogDescription>+ {t('dialogs.addUser.currentAccountDescription', { accountId })}+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4 py-5">+ <label className="grid gap-2 text-sm font-medium">+ {t('fields.user')}+ <Input+ required+ value={draft.userId}+ onChange={(event) =>+ setDraft((current) => ({+ ...current,+ userId: event.target.value,+ }))+ }+ placeholder={t('placeholders.user')}+ {...PLAIN_INPUT_PROPS}+ />+ </label>+ <label className="grid gap-2 text-sm font-medium">+ {t('fields.role')}+ <Select+ value={draft.role}+ onValueChange={(role) =>+ setDraft((current) => ({+ ...current,+ role: role || 'user',+ }))+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="user">{t('roles.user')}</SelectItem>+ <SelectItem value="admin">{t('roles.admin')}</SelectItem>+ </SelectContent>+ </Select>+ </label>+ </div>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ {t('actions.cancel')}+ </Button>+ <Button type="submit" disabled={isPending}>+ {isPending ? (+ <LoaderCircleIcon className="animate-spin" />+ ) : (+ <PlusIcon />+ )}+ {t('actions.addUser')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}