Skip to content

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

fix(studio): redesign connection switching and verify account identities (#6308)

Zayn Jarvis0a2578e7ebb4
diff --git a/web-studio/src/components/account-switcher.gateway.test.tsx b/web-studio/src/components/account-switcher.gateway.test.tsx
index 517ca5aa4..eb29b8183 100644
--- a/web-studio/src/components/account-switcher.gateway.test.tsx
+++ b/web-studio/src/components/account-switcher.gateway.test.tsx
@@ -94,7 +94,8 @@ it('root selects an account through the read-only list without requesting user c
<AccountSwitcher />
</QueryClientProvider>,
)
- fireEvent.click(screen.getByText('default'))
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ fireEvent.click(screen.getByRole('button', { name: 'serverAccountsTitle' }))
await waitFor(() => expect(screen.getByText('team')).toBeTruthy())
expect(screen.queryByText('create')).toBeNull()
expect(fetchAccounts).toHaveBeenCalledWith(
@@ -153,17 +154,29 @@ it('keeps saved connections and server account switching available to a gateway
fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
expect(
- screen.getByRole('button', { name: /Open-source default/ }),
- ).toBeTruthy()
- const hosted = screen.getByRole('button', { name: /Hosted space/ })
+ screen
+ .getByRole('button', { name: 'serverAccountsTitle' })
+ .getAttribute('aria-pressed'),
+ ).toBe('false')
+ expect(
+ screen
+ .getByRole('button', { name: 'identities' })
+ .getAttribute('aria-pressed'),
+ ).toBe('true')
+ fireEvent.click(screen.getByRole('button', { name: 'identities' }))
+ expect(screen.getByTitle('Open-source default')).toBeTruthy()
+ const hostedService = screen.getByRole('button', { name: 'provider.hosted' })
+ fireEvent.click(hostedService)
+ expect(activateProfile).not.toHaveBeenCalled()
expect(
- hosted.querySelector('[role="img"][aria-label="provider.hosted"]'),
- ).toBeTruthy()
- fireEvent.click(hosted)
+ screen.queryByRole('button', { name: 'serverAccountsTitle' }),
+ ).toBeNull()
+ fireEvent.click(screen.getByTitle('Hosted space'))
expect(activateProfile).toHaveBeenCalledWith('hosted')
expect(switchAccount).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ fireEvent.click(screen.getByRole('button', { name: 'serverAccountsTitle' }))
await waitFor(() => expect(screen.getByText('team')).toBeTruthy())
fireEvent.click(screen.getByText('team'))
await waitFor(() => expect(switchAccount).toHaveBeenCalledWith('team'))
diff --git a/web-studio/src/components/account-switcher.hosted.test.tsx b/web-studio/src/components/account-switcher.hosted.test.tsx
index 8ce9a7e78..d0bfd8d3f 100644
--- a/web-studio/src/components/account-switcher.hosted.test.tsx
+++ b/web-studio/src/components/account-switcher.hosted.test.tsx
@@ -204,25 +204,16 @@ it('keeps distinct keys and users selectable while deduplicating identical hoste
await waitFor(() =>
expect(screen.getByRole('button', { name: /study\/alice/ })).toBeTruthy(),
)
- expect(
- screen
- .getAllByRole('button')
- .filter(
- (button) =>
- button.getAttribute('data-slot') !== 'popover-trigger' &&
- button.querySelector('[role="img"][aria-label="provider.hosted"]'),
- ),
- ).toHaveLength(6)
- const otherKey = screen.getByRole('button', { name: /Study copy/ })
+ expect(screen.getByTitle('Study copy')).toBeTruthy()
+ const otherKey = screen.getByTitle('Study copy')
expect(otherKey).toBeTruthy()
- expect(screen.queryByRole('button', { name: /Study identical/ })).toBeNull()
+ expect(screen.queryByTitle('Study identical')).toBeNull()
const selected = screen
.getAllByRole('button')
.find((button) => button.hasAttribute('aria-current'))
expect(selected?.getAttribute('aria-current')).toBe('true')
expect(selected?.textContent).toContain('study/default')
- expect(selected?.textContent).toContain('Study')
- expect(screen.getByRole('button', { name: /Unconfigured/ })).toBeTruthy()
+ expect(screen.getByTitle('Unconfigured')).toBeTruthy()
fireEvent.click(otherKey)
expect(activateProfile).toHaveBeenCalledWith('study-copy')
@@ -232,7 +223,7 @@ it('keeps distinct keys and users selectable while deduplicating identical hoste
client.clear()
})
-it('lists saved open-source connections beside hosted connections without merging providers', async () => {
+it('previews a different service without switching, then activates the chosen identity', async () => {
const client = new QueryClient()
render(
<QueryClientProvider client={client}>
@@ -240,32 +231,20 @@ it('lists saved open-source connections beside hosted connections without mergin
</QueryClientProvider>,
)
fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
-
- const openSource = await screen.findByRole('button', {
- name: /Work memory/,
- })
- expect(openSource).toBeTruthy()
- expect(screen.queryByText('Duplicate work memory')).toBeNull()
- expect(
- screen
- .getByRole('button', { name: /Open-source shared URL/ })
- .querySelector('[role="img"][aria-label="provider.opensource"]'),
- ).toBeNull()
- expect(
- screen.getByRole('button', { name: /Development server/ }),
- ).toBeTruthy()
- expect(screen.getByRole('button', { name: /study\/alice/ })).toBeTruthy()
-
- fireEvent.click(openSource)
+ fireEvent.click(screen.getByRole('button', { name: 'devbox.example:1933' }))
+ expect(activateProfile).not.toHaveBeenCalled()
+ expect(screen.queryByTitle('Duplicate work memory')).toBeNull()
+ expect(screen.queryByRole('button', { name: /study\/alice/ })).toBeNull()
+ fireEvent.click(screen.getByTitle('Work memory'))
expect(activateProfile).toHaveBeenCalledWith('opensource-memory')
-
fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
- fireEvent.click(screen.getByRole('button', { name: /Development server/ }))
- expect(activateProfile).toHaveBeenCalledWith('opensource-development')
+ fireEvent.click(screen.getByRole('button', { name: 'hosted.example' }))
+ fireEvent.click(screen.getByTitle('Open-source shared URL'))
+ expect(activateProfile).toHaveBeenCalledWith('opensource-shared-url')
client.clear()
})
-it('opens the same saved connection list from an open-source profile without admin rights', async () => {
+it('opens the current service and filters identities independently from services', async () => {
activeState.provider = 'opensource'
activeState.profileId = 'opensource-memory'
const client = new QueryClient()
@@ -274,14 +253,19 @@ it('opens the same saved connection list from an open-source profile without adm
<AccountSwitcher />
</QueryClientProvider>,
)
-
fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
- const selected = await screen.findByRole('button', { name: /Work memory/ })
- expect(selected.getAttribute('aria-current')).toBe('true')
- expect(screen.queryByText('Duplicate work memory')).toBeNull()
- expect(screen.getByRole('button', { name: /study\/alice/ })).toBeTruthy()
- fireEvent.click(screen.getByRole('button', { name: /study\/alice/ }))
- expect(activateProfile).toHaveBeenCalledWith('study-alice')
+ expect(screen.getByTitle('Work memory').getAttribute('aria-current')).toBe(
+ 'true',
+ )
+ fireEvent.change(screen.getByRole('textbox', { name: 'identitiesSearch' }), {
+ target: { value: 'not-a-user' },
+ })
+ expect(screen.queryByTitle('Work memory')).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'provider.hosted' }))
+ expect(screen.getByTitle('Study Alice')).toBeTruthy()
+ expect(
+ screen.queryByRole('button', { name: 'serverAccountsTitle' }),
+ ).toBeNull()
client.clear()
})
@@ -295,10 +279,7 @@ it('distinguishes hosted connections with the same identity and profile name', a
fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
const sameNamePattern = (name: string) =>
- name.includes('study/default') &&
- name.includes('Study') &&
- !name.includes('Study copy') &&
- !name.includes('Study identical')
+ name.includes('study/default') && !name.includes('#study-co')
const accessibleNames = new Set<string>()
const sameNameOptions = screen.getAllByRole('button', {
name: (name) => {
@@ -344,3 +325,21 @@ it('shows a single default for personal hosted connections', async () => {
expect(activateProfile).toHaveBeenCalledWith('default')
client.clear()
})
+
+it('keeps the account tab discoverable when the active open-source identity lacks management access', () => {
+ activeState.provider = 'opensource'
+ const client = new QueryClient()
+ render(
+ <QueryClientProvider client={client}>
+ <AccountSwitcher />
+ </QueryClientProvider>,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ expect(screen.getByRole('button', { name: 'identities' })).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'serverAccountsTitle' }))
+ expect(screen.getByText('accountsRootRequired')).toBeTruthy()
+ expect(
+ screen.queryByRole('textbox', { name: 'searchPlaceholder' }),
+ ).toBeNull()
+ client.clear()
+})
diff --git a/web-studio/src/components/account-switcher.stale.test.tsx b/web-studio/src/components/account-switcher.stale.test.tsx
index 9a13f8315..90ff249ca 100644
--- a/web-studio/src/components/account-switcher.stale.test.tsx
+++ b/web-studio/src/components/account-switcher.stale.test.tsx
@@ -97,7 +97,8 @@ function renderSwitcher() {
}
async function selectTeam() {
- fireEvent.click(screen.getByText('default'))
+ fireEvent.click(screen.getByRole('button', { name: 'connections.switch' }))
+ fireEvent.click(screen.getByRole('button', { name: 'serverAccountsTitle' }))
await waitFor(() => expect(screen.getByText('team')).toBeTruthy())
fireEvent.click(screen.getByText('team'))
await waitFor(() => expect(fetchUsers).toHaveBeenCalledTimes(1))
diff --git a/web-studio/src/components/account-switcher.tsx b/web-studio/src/components/account-switcher.tsx
index 272d614b3..de52329f6 100644
--- a/web-studio/src/components/account-switcher.tsx
+++ b/web-studio/src/components/account-switcher.tsx
@@ -3,6 +3,9 @@ import { Link } from '@tanstack/react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
Building2Icon,
+ ArrowLeftIcon,
+ CloudIcon,
+ ServerIcon,
CheckIcon,
ChevronDownIcon,
LoaderCircleIcon,
@@ -42,9 +45,11 @@ import type {
import { DEFAULT_USER_ID } from '#/lib/admin-options'
import { formatHostedIdentity } from '#/lib/connection/identity-label'
import { connectionProfileFingerprint } from '#/lib/connection/profiles'
+import type { ConnectionProfile } from '#/lib/connection/profiles'
import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
import { ovClient } from '#/lib/ov-client'
import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'
+import { resolveConfiguredServiceProvider } from '#/lib/studio-service'
import { cn } from '#/lib/utils'
export function selectAccountUser(
@@ -72,56 +77,37 @@ function currentRuntimeIdentity(): string {
])
}
-function HostedServiceIcon() {
- const { t } = useTranslation('accountSwitcher')
- const label = t('provider.hosted')
+function OpenVikingMark() {
return (
- <span
- title={label}
- role="img"
- aria-label={label}
- className="inline-flex size-4 shrink-0 items-center justify-center text-sidebar-foreground/70"
+ <svg
+ viewBox="0 0 100 100"
+ className="size-7"
+ fill="currentColor"
+ aria-hidden="true"
>
- <svg
- viewBox="0 0 24 24"
- className="size-3.5 opacity-60"
- aria-hidden="true"
- >
- <g transform="translate(0.349 12.857)">
- <path
- d="M0 9.1584H6.34404L3.4718 0.221463C3.41951 0.0533704 3.23825 -0.0376799 3.07094 0.0148491C2.97333 0.0463665 2.89665 0.123409 2.86528 0.221463L0 9.1584Z"
- fill="#00DCFF"
- />
- </g>
- <g transform="translate(15.771 11.277)">
- <path
- d="M0 10.7483H7.36188L3.9842 0.221463C3.93191 0.0533704 3.75065 -0.03768 3.58334 0.0148491C3.48574 0.0463665 3.40905 0.123409 3.37768 0.221463L0 10.7483Z"
- fill="#00DCFF"
- />
- </g>
- <g transform="translate(7.012 1.716)">
- <path
- d="M0 20.3102H13.5804L7.09348 0.219641C7.03771 0.0515485 6.85993 -0.0395018 6.69262 0.0165291C6.59502 0.0480465 6.51833 0.125089 6.48696 0.219641L0 20.3102Z"
- fill="#006AFF"
- />
- </g>
- <g transform="translate(2.882 6.815)">
- <path
- d="M0.00348549 15.2114H10.2829L5.44472 0.219641C5.38895 0.0515482 5.21118 -0.0395018 5.04386 0.0165292C4.94626 0.0480466 4.86958 0.125089 4.83821 0.219641L0 15.2114H0.00348549Z"
- fill="#006AFF"
- />
- </g>
- <g transform="translate(5.736 9.355)">
- <path
- d="M0 12.6725H8.69343L4.64998 0.219641C4.5942 0.0515485 4.41643 -0.0395018 4.24912 0.0165291C4.15152 0.0480465 4.07832 0.125089 4.04694 0.219641L0.00348582 12.6725H0Z"
- fill="#00DCFF"
- />
- </g>
- </svg>
- </span>
+ <path d="M20.5 84H31L70 16.45H67ZM37 84 76 16.45V84Z" />
+ </svg>
)
}
+function serviceKey(connection: ConnectionProfile['connection']): string {
+ return JSON.stringify([
+ resolveConfiguredServiceProvider(
+ connection.baseUrl,
+ connection.serviceSelection,
+ ),
+ connection.baseUrl.trim().replace(/\/+$/, ''),
+ ])
+}
+
+function serviceHost(baseUrl: string): string {
+ try {
+ return new URL(baseUrl).host
+ } catch {
+ return baseUrl
+ }
+}
+
export function AccountSwitcher() {
const { t } = useTranslation('accountSwitcher')
const queryClient = useQueryClient()
@@ -142,6 +128,16 @@ export function AccountSwitcher() {
const [open, setOpen] = React.useState(false)
const [createOpen, setCreateOpen] = React.useState(false)
const [search, setSearch] = React.useState('')
+ const [serviceSearch, setServiceSearch] = React.useState('')
+ const [identitySearch, setIdentitySearch] = React.useState('')
+ const [selectedService, setSelectedService] = React.useState<string | null>(
+ null,
+ )
+ const [view, setView] = React.useState<'identities' | 'accounts'>('accounts')
+ const [mobileDetails, setMobileDetails] = React.useState(false)
+ const currentService = serviceKey(connection)
+ const selectedIsActive =
+ !selectedService || selectedService === currentService
const [switchingAccountId, setSwitchingAccountId] = React.useState('')
const [manualSwitch, setManualSwitch] = React.useState<{
accountId: string
@@ -195,7 +191,8 @@ export function AccountSwitcher() {
)
const accountsQuery = useQuery({
- enabled: canManageAccounts && open,
+ enabled:
+ canManageAccounts && open && selectedIsActive && view === 'accounts',
queryFn: () => fetchAdminAccounts(adminConnection),
queryKey: [
'account-switcher',
@@ -348,7 +345,6 @@ export function AccountSwitcher() {
},
})
- const accountLabel = connection.accountId || t('unset')
const seenProfiles = new Set<string>()
const savedProfiles = [...profiles]
.sort((a, b) =>
@@ -360,143 +356,81 @@ export function AccountSwitcher() {
seenProfiles.add(key)
return true
})
- const identityFor = (profile: (typeof savedProfiles)[number]) =>
- profile.connection.serviceSelection === 'volcengine'
- ? formatHostedIdentity(
- profile.connection.accountId,
- profile.connection.userId,
- )
- : `${profile.connection.accountId}/${profile.connection.userId}`
- const summaryFor = (profile: (typeof savedProfiles)[number]) =>
- JSON.stringify([
- profile.name,
- profile.connection.serviceSelection,
- identityFor(profile),
- profile.connection.baseUrl.trim().replace(/\/+$/, ''),
- ])
- const summaryCounts = new Map<string, number>()
+ const groups = new Map<
+ string,
+ {
+ connection: ConnectionProfile['connection']
+ profiles: ConnectionProfile[]
+ }
+ >()
+ groups.set(currentService, { connection, profiles: [] })
for (const profile of savedProfiles) {
- const summary = summaryFor(profile)
- summaryCounts.set(summary, (summaryCounts.get(summary) ?? 0) + 1)
+ const key = serviceKey(profile.connection)
+ if (!groups.has(key))
+ groups.set(key, { connection: profile.connection, profiles: [] })
+ groups.get(key)!.profiles.push(profile)
}
- const savedConnectionsMenu = (
- <>
- <div className="max-h-60 space-y-0.5 overflow-y-auto p-1.5">
- {savedProfiles.map((profile) => {
- const active = profile.id === activeProfileId
- const identity = identityFor(profile)
- const showProfileId =
- (summaryCounts.get(summaryFor(profile)) ?? 0) > 1
- return (
- <button
- key={profile.id}
- type="button"
- aria-current={active ? 'true' : undefined}
- onClick={() => {
- setOpen(false)
- activateProfile(profile.id)
- }}
- className={cn(
- 'flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
- active && 'bg-accent/70',
- )}
- >
- <span className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-background text-xs font-semibold">
- {profile.name.charAt(0).toUpperCase()}
- </span>
- <span className="min-w-0 flex-1">
- <span className="flex min-w-0 items-center gap-1">
- <span className="min-w-0 truncate text-sm font-medium">
- {profile.name}
- </span>
- {profile.connection.serviceSelection === 'volcengine' ? (
- <HostedServiceIcon />
- ) : null}
- {showProfileId ? (
- <span
- className="shrink-0 font-mono text-[10px] text-muted-foreground"
- title={profile.id}
- >
- #{profile.id.slice(0, 8)}
- </span>
- ) : null}
- </span>
- <span
- className="block truncate text-xs text-muted-foreground"
- title={`${identity ? `[${identity}] · ` : ''}${profile.connection.baseUrl}`}
- >
- {identity ? `[${identity}] · ` : null}
- {profile.connection.baseUrl}
- </span>
- </span>
- {active ? <CheckIcon className="size-3.5 shrink-0" /> : null}
- </button>
- )
- })}
- </div>
- <p className="border-t px-2.5 py-2 text-xs text-muted-foreground">
- {t('connections.savedOnly')}
- </p>
- <Link
- to="/config"
- onClick={() => setOpen(false)}
- className="flex items-center gap-2 rounded-md px-2.5 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- <PlusIcon className="size-4" />
- {t('connections.add')}
- </Link>
- </>
+ const selectedKey =
+ selectedService && groups.has(selectedService)
+ ? selectedService
+ : currentService
+ const selected = groups.get(selectedKey)!
+ const titleFor = (c: ConnectionProfile['connection']) =>
+ c.serviceSelection === 'volcengine'
+ ? t('provider.hosted')
+ : serviceHost(c.baseUrl)
+ const identityFor = (c: ConnectionProfile['connection']) =>
+ c.serviceSelection === 'volcengine'
+ ? formatHostedIdentity(c.accountId, c.userId) || t('unset')
+ : `${c.accountId}/${c.userId}`
+ const visibleGroups = [...groups].filter(([, group]) =>
+ `${titleFor(group.connection)} ${group.connection.baseUrl}`
+ .toLowerCase()
+ .includes(serviceSearch.trim().toLowerCase()),
)
-
- if (provider === 'volcengine' || !canManageAccounts) {
- return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger
- aria-label={t('connections.switch')}
- className="flex h-10 w-full min-w-0 items-center gap-2 rounded-lg px-1 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"
- >
- <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="flex min-w-0 flex-1 items-center gap-1 group-data-[collapsible=icon]:hidden">
- <span className="min-w-0 truncate text-sm font-semibold">
- {(provider === 'volcengine' &&
- formatHostedIdentity(
- connection.accountId,
- connection.userId,
- )) ||
- connection.accountId ||
- t('hosted.currentWorkspace')}
- </span>
- {provider === 'volcengine' ? <HostedServiceIcon /> : null}
- </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-80 gap-0 p-1.5"
- >
- {savedConnectionsMenu}
- </PopoverContent>
- </Popover>
- )
+ const visibleProfiles = selected.profiles.filter((profile) =>
+ `${identityFor(profile.connection)} ${profile.name}`
+ .toLowerCase()
+ .includes(identitySearch.trim().toLowerCase()),
+ )
+ const showAccountsTab =
+ resolveConfiguredServiceProvider(
+ selected.connection.baseUrl,
+ selected.connection.serviceSelection,
+ ) === 'opensource'
+ const accountsVisible = showAccountsTab && view === 'accounts'
+ const accountAccessReady = canManageAccounts && selectedKey === currentService
+ function changeOpen(next: boolean) {
+ setOpen(next)
+ if (next) {
+ setSelectedService(currentService)
+ setServiceSearch('')
+ setIdentitySearch('')
+ setSearch('')
+ setMobileDetails(false)
+ setView('identities')
+ }
}
return (
<>
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover open={open} onOpenChange={changeOpen}>
<PopoverTrigger
aria-label={t('connections.switch')}
- className="flex h-10 w-full min-w-0 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"
+ className="flex min-h-12 w-full min-w-0 items-center gap-2 rounded-lg px-1 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"
>
- <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 className="flex size-8 shrink-0 items-center justify-center text-sidebar-foreground">
+ <OpenVikingMark />
</span>
- <span className="flex min-w-0 flex-1 items-center gap-1 group-data-[collapsible=icon]:hidden">
- <span className="min-w-0 truncate text-sm font-semibold">
- {accountLabel}
+ <span className="min-w-0 flex-1 group-data-[collapsible=icon]:hidden">
+ <span
+ className="block truncate text-sm font-semibold"
+ title={connection.baseUrl}
+ >
+ {titleFor(connection)}
+ </span>
+ <span className="block truncate text-xs text-muted-foreground">
+ [{identityFor(connection)}]
</span>
</span>
<ChevronDownIcon className="size-4 shrink-0 text-muted-foreground group-data-[collapsible=icon]:hidden" />
@@ -505,102 +439,334 @@ export function AccountSwitcher() {
side="bottom"
align="start"
sideOffset={6}
- className="max-h-[min(80vh,44rem)] w-80 gap-0 overflow-y-auto p-0"
+ className="w-[min(40rem,calc(100vw-2rem))] gap-0 overflow-hidden p-0"
>
- <p className="px-4 pt-3 text-xs font-medium text-muted-foreground">
- {t('connections.title')}
- </p>
- {savedConnectionsMenu}
- <p className="border-t px-4 pt-3 text-xs font-medium text-muted-foreground">
- {t('serverAccountsTitle')}
- </p>
- <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 className="grid min-h-80 sm:grid-cols-[12rem_minmax(0,1fr)]">
+ <div
+ className={cn(
+ 'flex min-w-0 flex-col sm:border-r',
+ mobileDetails && 'hidden sm:flex',
+ )}
+ >
+ <div className="p-3">
+ <Input
+ value={serviceSearch}
+ onChange={(event) => setServiceSearch(event.target.value)}
+ aria-label={t('servicesSearch')}
+ placeholder={t('servicesSearch')}
+ className="h-9"
+ />
</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 className="max-h-72 flex-1 overflow-y-auto px-1.5 pb-2">
+ {visibleGroups.map(([key, group]) => {
+ const Icon =
+ group.connection.serviceSelection === 'volcengine'
+ ? CloudIcon
+ : ServerIcon
+ return (
+ <button
+ key={key}
+ type="button"
+ aria-pressed={key === selectedKey}
+ title={group.connection.baseUrl}
+ onClick={() => {
+ setSelectedService(key)
+ setView('identities')
+ setIdentitySearch('')
+ setMobileDetails(true)
+ }}
+ className={cn(
+ 'flex min-h-11 w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-xs hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ key === selectedKey && 'bg-accent',
+ )}
+ >
+ <Icon className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 truncate font-medium">
+ {titleFor(group.connection)}
+ </span>
+ </button>
+ )
+ })}
+ {visibleGroups.length === 0 && (
+ <p className="px-3 py-5 text-xs text-muted-foreground">
+ {t('noConnections')}
+ </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 (
+ <Link
+ to="/config"
+ onClick={() => setOpen(false)}
+ className="mt-auto flex h-11 shrink-0 items-center gap-2 border-t px-3 text-xs hover:bg-accent"
+ >
+ <PlusIcon className="size-3.5" />
+ {t('connections.add')}
+ </Link>
+ </div>
+ <div
+ className={cn(
+ 'flex min-w-0 flex-col',
+ !mobileDetails && 'hidden sm:flex',
+ )}
+ >
+ <div className="flex min-h-14 items-center gap-2 px-4 py-3">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 sm:hidden"
+ aria-label={t('backToServices')}
+ onClick={() => setMobileDetails(false)}
+ >
+ <ArrowLeftIcon className="size-4" />
+ </Button>
+ <span
+ className="min-w-0 truncate text-sm font-semibold"
+ title={selected.connection.baseUrl}
+ >
+ {titleFor(selected.connection)}
+ </span>
+ {selectedKey === currentService && (
+ <span className="ml-auto shrink-0 text-[10px] text-muted-foreground">
+ {t('connected')}
+ </span>
+ )}
+ </div>
+ <div className="flex gap-4 border-b px-4">
+ <button
+ type="button"
+ aria-pressed={!accountsVisible}
+ onClick={() => setView('identities')}
+ className={cn(
+ 'min-h-9 border-b-2 text-xs',
+ !accountsVisible
+ ? 'border-foreground font-medium'
+ : 'border-transparent text-muted-foreground',
+ )}
+ >
+ {t('identities')}
+ </button>
+ {showAccountsTab && (
<button
- key={account.accountId}
type="button"
- disabled={Boolean(switchingAccountId)}
- onClick={() => void selectAccount(account.accountId)}
+ aria-pressed={accountsVisible}
+ onClick={() => setView('accounts')}
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',
+ 'min-h-9 border-b-2 text-xs',
+ accountsVisible
+ ? 'border-foreground font-medium'
+ : 'border-transparent text-muted-foreground',
)}
>
- <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="flex min-w-0 items-center gap-1">
- <span className="min-w-0 truncate text-sm font-medium">
- {account.accountId}
- </span>
- </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}
+ {t('serverAccountsTitle')}
</button>
- )
- })
- )}
- </div>
- {!isGatewayHost && (
- <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)
- }}
+ )}
+ </div>
+ <div className="min-h-0 flex-1">
+ {accountsVisible && !accountAccessReady ? (
+ <div className="space-y-3 p-4 text-xs text-muted-foreground">
+ <p>
+ {t(
+ selectedKey !== currentService
+ ? 'accountsConnectFirst'
+ : isConnectionRoleLoading
+ ? 'accountsChecking'
+ : 'accountsRootRequired',
+ )}
+ </p>
+ {selectedKey === currentService &&
+ !isConnectionRoleLoading && (
+ <Link
+ to="/settings"
+ onClick={() => setOpen(false)}
+ className="text-foreground underline underline-offset-4"
+ >
+ {t('manageConnections')}
+ </Link>
+ )}
+ </div>
+ ) : accountsVisible ? (
+ <>
+ <div className="flex items-center gap-2 p-3">
+ <div className="relative min-w-0 flex-1">
+ <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)}
+ aria-label={t('searchPlaceholder')}
+ placeholder={t('searchPlaceholder')}
+ className="h-9 pl-8 text-xs"
+ />
+ </div>
+ {!isGatewayHost && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-9 shrink-0 text-xs"
+ onClick={() => {
+ setOpen(false)
+ setCreateOpen(true)
+ }}
+ >
+ <PlusIcon className="size-3.5" />
+ {t('create')}
+ </Button>
+ )}
+ </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="flex min-w-0 items-center gap-1">
+ <span className="min-w-0 truncate text-sm font-medium">
+ {account.accountId}
+ </span>
+ </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="p-3">
+ <Input
+ value={identitySearch}
+ onChange={(event) =>
+ setIdentitySearch(event.target.value)
+ }
+ aria-label={t('identitiesSearch')}
+ placeholder={t('identitiesSearch')}
+ className="h-9"
+ />
+ </div>
+ <div className="max-h-60 space-y-1 overflow-y-auto px-2 pb-2">
+ {visibleProfiles.map((profile) => {
+ const identity = identityFor(profile.connection)
+ const duplicateIdentity =
+ selected.profiles.filter(
+ (candidate) =>
+ identityFor(candidate.connection) === identity,
+ ).length > 1
+ return (
+ <button
+ key={profile.id}
+ type="button"
+ aria-current={
+ profile.id === activeProfileId
+ ? 'true'
+ : undefined
+ }
+ title={profile.name}
+ onClick={() => {
+ setOpen(false)
+ activateProfile(profile.id)
+ }}
+ className={cn(
+ 'flex min-h-11 w-full items-center gap-2 rounded-md px-3 py-2 text-left text-xs hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ profile.id === activeProfileId && 'bg-accent',
+ )}
+ >
+ <span className="min-w-0 flex-1">
+ <span className="block truncate font-medium">
+ {profile.name}
+ </span>
+ <span className="block truncate text-[11px] text-muted-foreground">
+ [{identity}]
+ </span>
+ </span>
+ {duplicateIdentity && (
+ <span
+ className="shrink-0 font-mono text-[10px] text-muted-foreground"
+ title={profile.id}
+ >
+ #{profile.id.slice(0, 8)}
+ </span>
+ )}
+ {profile.id === activeProfileId && (
+ <CheckIcon className="size-3.5 shrink-0" />
+ )}
+ </button>
+ )
+ })}
+ {visibleProfiles.length === 0 && (
+ <p className="px-3 py-5 text-xs text-muted-foreground">
+ {t('noIdentities')}
+ </p>
+ )}
+ </div>
+ <p className="px-4 pb-3 text-[11px] text-muted-foreground">
+ {t('connections.savedOnly')}
+ </p>
+ </>
+ )}
+ </div>
+ <Link
+ to={
+ accountsVisible && accountAccessReady ? '/users' : '/settings'
+ }
+ onClick={() => setOpen(false)}
+ className="mt-auto flex h-11 shrink-0 items-center border-t px-4 text-xs hover:bg-accent"
>
- <PlusIcon />
- {t('create')}
- </Button>
+ {t(
+ accountsVisible && accountAccessReady
+ ? 'accountSettings'
+ : 'manageConnections',
+ )}
+ </Link>
</div>
- )}
+ </div>
</PopoverContent>
</Popover>
diff --git a/web-studio/src/components/app-shell-recovery.test.tsx b/web-studio/src/components/app-shell-recovery.test.tsx
index a2f6b5bb5..6218dfa5a 100644
--- a/web-studio/src/components/app-shell-recovery.test.tsx
+++ b/web-studio/src/components/app-shell-recovery.test.tsx
@@ -20,9 +20,6 @@ vi.mock('#/hooks/use-mobile', () => ({ useIsMobile: () => false }))
vi.mock('#/components/account-switcher', () => ({
AccountSwitcher: () => null,
}))
-vi.mock('#/components/current-user-menu', () => ({
- CurrentUserMenu: () => null,
-}))
vi.mock('#/components/generated-credential-dialog', () => ({
GeneratedCredentialDialog: () => null,
}))
diff --git a/web-studio/src/components/app-shell.test.tsx b/web-studio/src/components/app-shell.test.tsx
index e6a4ad321..945689cfa 100644
--- a/web-studio/src/components/app-shell.test.tsx
+++ b/web-studio/src/components/app-shell.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { cleanup, render, screen } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
@@ -9,7 +9,11 @@ import {
shouldShowGatewayNavigation,
} from './app-shell'
-const bootstrap = vi.hoisted(() => ({ health: vi.fn(), pathname: '/' }))
+const bootstrap = vi.hoisted(() => ({
+ health: vi.fn(),
+ pathname: '/',
+ navigate: vi.fn(),
+}))
vi.mock('#/lib/connection/health', async (original) => ({
...(await original<Record<string, unknown>>()),
fetchServerHealth: bootstrap.health,
@@ -22,7 +26,7 @@ vi.mock('#/hooks/use-app-connection', async (original) => ({
vi.mock('@tanstack/react-router', async (original) => ({
...(await original<Record<string, unknown>>()),
Navigate: ({ to }: { to: string }) => <output>{to}</output>,
- useNavigate: () => vi.fn(),
+ useNavigate: () => bootstrap.navigate,
useRouterState: ({
select,
}: {
@@ -133,3 +137,14 @@ it('opens a fresh standalone Gateway Studio without the data-connection wizard',
window.history.replaceState(null, '', '/')
}
})
+
+it('cancels setup back to the existing workspace without changing its marker', () => {
+ localStorage.clear()
+ localStorage.setItem('ov_studio_setup', 'complete')
+ sessionStorage.setItem('ov_studio_workspace_selected', 'selected')
+ bootstrap.pathname = '/config'
+ render(<AppShell>{null}</AppShell>)
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(bootstrap.navigate).toHaveBeenCalledWith({ to: '/', replace: true })
+ expect(localStorage.getItem('ov_studio_setup')).toBe('complete')
+})
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index 31528aa99..f777bafdd 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -46,7 +46,6 @@ import {
} from '#/components/ui/collapsible'
import { CrossDeviceVerifyDialog } from '#/components/cross-device-verify-dialog'
import { AccountSwitcher } from '#/components/account-switcher'
-import { CurrentUserMenu } from '#/components/current-user-menu'
import { GeneratedCredentialDialog } from '#/components/generated-credential-dialog'
import { ScrollArea } from '#/components/ui/scroll-area'
import {
@@ -325,6 +324,14 @@ export function AppShell({ children }: { children: React.ReactNode }) {
if (pathname === '/config')
return (
<StudioSetup
+ canReturnToWorkspace={!needsSetup}
+ onCancel={() => {
+ if (needsSetup) {
+ window.location.assign('https://docs.openviking.ai/')
+ } else {
+ void navigate({ to: '/', replace: true })
+ }
+ }}
onComplete={(connection) => {
setNeedsSetup(false)
void navigate({
@@ -781,9 +788,6 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
<GithubIcon className="size-4" />
</a>
- <div className="h-6 w-px bg-border/80" aria-hidden="true" />
-
- {isGatewayHost ? null : <CurrentUserMenu />}
</div>
</header>
diff --git a/web-studio/src/components/current-user-menu.interaction.test.tsx b/web-studio/src/components/current-user-menu.interaction.test.tsx
deleted file mode 100644
index 21c299300..000000000
--- a/web-studio/src/components/current-user-menu.interaction.test.tsx
+++ /dev/null
@@ -1,253 +0,0 @@
-// @vitest-environment jsdom
-
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import {
- cleanup,
- fireEvent,
- render,
- screen,
- waitFor,
-} from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-import { CurrentUserMenu } from './current-user-menu'
-
-const adminMocks = vi.hoisted(() => ({
- fetchAdminUsers: vi.fn(),
-}))
-
-const connectionMocks = vi.hoisted(() => ({
- connection: {
- accountId: 'account-a',
- adminApiKey: 'root-key',
- apiKey: '',
- baseUrl: 'http://localhost:1933',
- userId: 'alice',
- },
- connectionRole: 'root',
- isConnectionRoleLoading: false,
- serverMode: 'trusted',
- switchIdentity: vi.fn(),
-}))
-
-const toastMocks = vi.hoisted(() => ({
- error: vi.fn(),
- success: vi.fn(),
-}))
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}))
-
-vi.mock('#/hooks/use-studio-service', () => ({
- useStudioService: () => ({ provider: 'opensource' }),
-}))
-
-vi.mock('sonner', () => ({ toast: toastMocks }))
-
-vi.mock('#/hooks/use-app-connection', () => ({
- useAppConnection: () => connectionMocks,
-}))
-
-vi.mock('#/lib/admin', () => adminMocks)
-
-function renderMenu() {
- const queryClient = new QueryClient({
- defaultOptions: {
- mutations: { retry: false },
- queries: { retry: false },
- },
- })
-
- return render(
- <QueryClientProvider client={queryClient}>
- <CurrentUserMenu />
- </QueryClientProvider>,
- )
-}
-
-beforeEach(() => {
- connectionMocks.connection.adminApiKey = 'root-key'
- connectionMocks.connectionRole = 'root'
- connectionMocks.isConnectionRoleLoading = false
- connectionMocks.serverMode = 'trusted'
- connectionMocks.switchIdentity.mockResolvedValue(undefined)
- adminMocks.fetchAdminUsers.mockResolvedValue([
- {
- accountId: 'account-a',
- role: 'admin',
- userId: 'alice',
- },
- {
- accountId: 'account-a',
- role: 'user',
- userId: 'bob',
- },
- ])
-})
-
-afterEach(() => {
- cleanup()
- vi.clearAllMocks()
-})
-
-describe('CurrentUserMenu', () => {
- it('switches trusted identities without requiring a user API key', async () => {
- renderMenu()
-
- fireEvent.click(
- screen.getByRole('button', { name: 'header.currentUser.openMenu' }),
- )
-
- const selector = await screen.findByRole('combobox', {
- name: 'header.currentUser.switchUser',
- })
- expect(screen.queryByRole('option', { name: 'bob' })).toBeNull()
- await userEvent.click(selector)
- const bob = await screen.findByRole('option', { name: 'bob' })
- await userEvent.click(bob)
-
- await waitFor(() => {
- expect(connectionMocks.switchIdentity).toHaveBeenCalledWith({
- accountId: 'account-a',
- allowLegacyIdentityFallback: true,
- apiKey: '',
- userId: 'bob',
- })
- })
- expect(toastMocks.success).toHaveBeenCalledWith(
- 'header.currentUser.switchSuccess',
- )
- })
-
- it('switches API-key identities when management access exposes a user key', async () => {
- connectionMocks.serverMode = 'api_key'
- adminMocks.fetchAdminUsers.mockResolvedValue([
- {
- accountId: 'account-a',
- apiKey: 'alice-key',
- role: 'admin',
- userId: 'alice',
- },
- {
- accountId: 'account-a',
- apiKey: 'bob-key',
- role: 'user',
- userId: 'bob',
- },
- ])
- renderMenu()
-
- fireEvent.click(
- screen.getByRole('button', { name: 'header.currentUser.openMenu' }),
- )
-
- const selector = await screen.findByRole('combobox', {
- name: 'header.currentUser.switchUser',
- })
- expect(screen.queryByRole('option', { name: 'bob' })).toBeNull()
- await userEvent.click(selector)
- const bob = await screen.findByRole('option', { name: 'bob' })
- await userEvent.click(bob)
-
- await waitFor(() => {
- expect(connectionMocks.switchIdentity).toHaveBeenCalledWith({
- accountId: 'account-a',
- allowLegacyIdentityFallback: true,
- apiKey: 'bob-key',
- userId: 'bob',
- })
- })
- })
-
- it('keeps ordinary API-key user menus read-only', () => {
- connectionMocks.serverMode = 'api_key'
- connectionMocks.connectionRole = 'user'
- renderMenu()
-
- fireEvent.click(
- screen.getByRole('button', { name: 'header.currentUser.openMenu' }),
- )
-
- expect(screen.queryByText('header.currentUser.switchUser')).toBeNull()
- expect(adminMocks.fetchAdminUsers).not.toHaveBeenCalled()
- })
-
- it('disables API-key identities whose secret is unavailable', async () => {
- connectionMocks.serverMode = 'api_key'
- adminMocks.fetchAdminUsers.mockResolvedValue([
- {
- accountId: 'account-a',
- apiKey: 'alice-key',
- role: 'admin',
- userId: 'alice',
- },
- {
- accountId: 'account-a',
- keyPrefix: 'ovk_bob',
- role: 'user',
- userId: 'bob',
- },
- ])
- renderMenu()
-
- fireEvent.click(
- screen.getByRole('button', { name: 'header.currentUser.openMenu' }),
- )
-
- const selector = await screen.findByRole('combobox', {
- name: 'header.currentUser.switchUser',
- })
- expect(screen.queryByRole('option', { name: 'bob' })).toBeNull()
- await userEvent.click(selector)
- const bob = await screen.findByRole('option', { name: 'bob' })
- expect(bob.getAttribute('aria-disabled')).toBe('true')
- expect(screen.getByText('header.currentUser.keyUnavailable')).toBeTruthy()
- })
-
- it('accepts a user ID when trusted mode has no user directory', async () => {
- connectionMocks.connection.adminApiKey = ''
- renderMenu()
-
- fireEvent.click(
- screen.getByRole('button', { name: 'header.currentUser.openMenu' }),
- )
- fireEvent.change(
- screen.getByPlaceholderText('header.currentUser.userIdPlaceholder'),
- { target: { value: ' bob ' } },
- )
- fireEvent.click(
- screen.getByRole('button', { name: 'header.currentUser.switchAction' }),
- )
-
- await waitFor(() => {
- expect(connectionMocks.switchIdentity).toHaveBeenCalledWith({
- accountId: 'account-a',
- allowLegacyIdentityFallback: true,
- apiKey: '',
- userId: 'bob',
- })
- })
- expect(adminMocks.fetchAdminUsers).not.toHaveBeenCalled()
- })
-
- it('renders current user identity clearly even when manual switcher is available in trusted mode', () => {
- connectionMocks.connection.adminApiKey = ''
- renderMenu()
-
- fireEvent.click(
- screen.getByRole('button', { name: 'header.currentUser.openMenu' }),
- )
-
- const userTerm = screen.getByText('header.currentUser.user')
- const userRow = userTerm.closest('div')
- expect(userRow).toBeTruthy()
- expect(userRow?.textContent).toContain('alice')
- expect(
- screen.getByPlaceholderText('header.currentUser.userIdPlaceholder'),
- ).toBeTruthy()
- })
-})
diff --git a/web-studio/src/components/current-user-menu.test.ts b/web-studio/src/components/current-user-menu.test.ts
deleted file mode 100644
index 08927fc62..000000000
--- a/web-studio/src/components/current-user-menu.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { getUserInitial } from './current-user-menu'
-
-describe('getUserInitial', () => {
- it('uses the first character of the normalized user id', () => {
- expect(getUserInitial(' yufeng201 ')).toBe('Y')
- })
-
- it('supports non-Latin user ids', () => {
- expect(getUserInitial('用户')).toBe('用')
- })
-
- it('returns a fallback when the user id is empty', () => {
- expect(getUserInitial(' ')).toBe('?')
- })
-})
diff --git a/web-studio/src/components/current-user-menu.tsx b/web-studio/src/components/current-user-menu.tsx
deleted file mode 100644
index e8c6c3a2d..000000000
--- a/web-studio/src/components/current-user-menu.tsx
+++ /dev/null
@@ -1,285 +0,0 @@
-import * as React from 'react'
-import { useQuery } from '@tanstack/react-query'
-import {
- Building2Icon,
- ChevronDownIcon,
- LoaderCircleIcon,
- UserRoundIcon,
-} from 'lucide-react'
-import { useTranslation } from 'react-i18next'
-import { toast } from 'sonner'
-
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from '#/components/ui/popover'
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '#/components/ui/select'
-import { useStudioService } from '#/hooks/use-studio-service'
-import { useAppConnection } from '#/hooks/use-app-connection'
-import { fetchAdminUsers } from '#/lib/admin'
-import type { AdminConnection } from '#/lib/admin'
-import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'
-
-export function getUserInitial(userId: string): string {
- const normalizedUserId = userId.trim()
- return normalizedUserId ? normalizedUserId.slice(0, 1).toUpperCase() : '?'
-}
-
-export function CurrentUserMenu() {
- const { t } = useTranslation('appShell')
- const {
- connection,
- connectionRole,
- isConnectionRoleLoading,
- serverMode,
- switchIdentity,
- } = useAppConnection()
- const [open, setOpen] = React.useState(false)
- const [manualUserId, setManualUserId] = React.useState('')
- const [switchingUserId, setSwitchingUserId] = React.useState('')
- const { accountId, userId } = connection
- const accountLabel = accountId || t('header.currentUser.unset')
- const userLabel = userId || t('header.currentUser.unset')
- const { provider } = useStudioService()
- const { canManageUsers } = resolveStudioManagementCapabilities({
- serviceProvider: provider,
- hasControlCredential: Boolean(connection.adminApiKey.trim()),
- isRoleLoading: isConnectionRoleLoading,
- role: connectionRole,
- serverMode,
- })
- const canSwitchUser =
- Boolean(accountId) && (serverMode === 'trusted' || canManageUsers)
- const canListUsers = canManageUsers
- const manualTargetUserId = manualUserId.trim()
- const adminConnection = React.useMemo<AdminConnection>(
- () => ({
- accountId,
- apiKey: connection.adminApiKey,
- baseUrl: connection.baseUrl,
- userId,
- }),
- [accountId, connection.adminApiKey, connection.baseUrl, userId],
- )
- const usersQuery = useQuery({
- enabled: canSwitchUser && canListUsers && open,
- queryFn: () => fetchAdminUsers(adminConnection, accountId),
- queryKey: [
- 'current-user-menu',
- adminConnection.baseUrl,
- adminConnection.apiKey,
- accountId,
- ],
- retry: false,
- })
-
- async function selectUser(
- nextUserId: string,
- nextApiKey = '',
- ): Promise<void> {
- const normalizedUserId = nextUserId.trim()
- if (!normalizedUserId || normalizedUserId === userId) {
- return
- }
-
- setSwitchingUserId(normalizedUserId)
- try {
- await switchIdentity({
- accountId,
- allowLegacyIdentityFallback: true,
- apiKey: serverMode === 'trusted' ? '' : nextApiKey,
- userId: normalizedUserId,
- })
- setManualUserId('')
- setOpen(false)
- toast.success(t('header.currentUser.switchSuccess'))
- } catch (error) {
- toast.error(error instanceof Error ? error.message : String(error))
- } finally {
- setSwitchingUserId('')
- }
- }
-
- return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger
- aria-label={t('header.currentUser.openMenu', { user: userLabel })}
- className="group flex h-8 max-w-48 items-center gap-2 rounded-lg border border-border/80 bg-muted/60 p-1 pr-2.5 text-left shadow-xs outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
- >
- <span className="flex size-6 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background shadow-sm">
- {getUserInitial(userLabel)}
- </span>
- <span className="hidden min-w-0 flex-1 sm:block">
- <span className="block truncate text-xs font-semibold leading-3 text-foreground">
- {userLabel}
- </span>
- <span className="block truncate text-[10px] leading-3 text-muted-foreground">
- {t('header.currentUser.accountSummary', {
- account: accountLabel,
- })}
- </span>
- </span>
- <ChevronDownIcon className="hidden size-3.5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180 sm:block" />
- </PopoverTrigger>
-
- <PopoverContent
- align="end"
- side="bottom"
- sideOffset={8}
- className="w-72 gap-0 overflow-hidden p-0"
- >
- <div className="flex items-center gap-3 border-b bg-muted/35 px-4 py-3.5">
- <span className="flex size-10 shrink-0 items-center justify-center rounded-2xl bg-foreground text-sm font-semibold text-background shadow-sm">
- {getUserInitial(userLabel)}
- </span>
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-semibold">{userLabel}</div>
- <div className="mt-0.5 text-xs text-muted-foreground">
- {t('header.currentUser.signedInAs')}
- </div>
- </div>
- </div>
-
- <dl className="space-y-1 p-2">
- <div className="flex items-center gap-3 rounded-lg px-2.5 py-2">
- <Building2Icon className="size-4 shrink-0 text-muted-foreground" />
- <dt className="w-16 shrink-0 text-xs text-muted-foreground">
- {t('header.currentUser.account')}
- </dt>
- <dd className="min-w-0 flex-1 truncate text-right text-xs font-medium">
- {accountLabel}
- </dd>
- </div>
- <div className="flex items-center gap-3 rounded-lg px-2.5 py-2">
- <UserRoundIcon className="size-4 shrink-0 text-muted-foreground" />
- <dt className="w-16 shrink-0 text-xs text-muted-foreground">
- {t('header.currentUser.user')}
- </dt>
- <dd className="min-w-0 flex-1 truncate text-right text-xs font-medium">
- {canSwitchUser && canListUsers ? (
- <div>
- {usersQuery.isLoading ? (
- <div className="flex items-center justify-end gap-1.5 text-xs text-muted-foreground">
- <LoaderCircleIcon className="size-3.5 animate-spin" />
- <span className="truncate">{userLabel}</span>
- </div>
- ) : usersQuery.isError ? (
- <div className="flex items-center justify-end gap-1.5 text-xs text-muted-foreground">
- <span className="truncate">{userLabel}</span>
- <button
- type="button"
- className="text-xs font-medium text-primary hover:underline"
- onClick={() => void usersQuery.refetch()}
- >
- {t('header.currentUser.retry')}
- </button>
- </div>
- ) : usersQuery.data?.length ? (
- <div>
- <Select
- value={userId}
- onValueChange={(nextUserId) => {
- const user = usersQuery.data.find(
- (item) => item.userId === nextUserId,
- )
- if (user) void selectUser(user.userId, user.apiKey)
- }}
- >
- <SelectTrigger
- aria-label={t('header.currentUser.switchUser')}
- className="h-8 w-full justify-end border-transparent bg-transparent px-2 text-xs shadow-none hover:bg-accent"
- disabled={Boolean(switchingUserId)}
- >
- {switchingUserId ? (
- <LoaderCircleIcon className="size-3.5 animate-spin" />
- ) : null}
- <SelectValue>{userLabel}</SelectValue>
- </SelectTrigger>
- <SelectContent>
- {usersQuery.data.map((user) => {
- const canUseIdentity =
- serverMode === 'trusted' || Boolean(user.apiKey)
- return (
- <SelectItem
- key={user.userId}
- value={user.userId}
- aria-label={user.userId}
- disabled={!canUseIdentity}
- >
- {user.userId}
- {!canUseIdentity ? (
- <span className="text-[10px] text-muted-foreground">
- {t('header.currentUser.keyUnavailable')}
- </span>
- ) : null}
- </SelectItem>
- )
- })}
- </SelectContent>
- </Select>
- </div>
- ) : (
- <span className="truncate">{userLabel}</span>
- )}
- </div>
- ) : (
- <span className="truncate">{userLabel}</span>
- )}
- </dd>
- </div>
- </dl>
-
- {canSwitchUser && !canListUsers ? (
- <div className="border-t border-border/80 bg-muted/20 p-2.5">
- <form
- className="grid gap-2"
- onSubmit={(event) => {
- event.preventDefault()
- void selectUser(manualTargetUserId)
- }}
- >
- <label
- className="text-xs font-medium text-muted-foreground"
- htmlFor="trusted-user-id"
- >
- {t('header.currentUser.switchUser')}
- </label>
- <div className="flex items-center gap-1.5">
- <input
- id="trusted-user-id"
- type="text"
- autoComplete="off"
- value={manualUserId}
- className="h-8 min-w-0 flex-1 rounded-md border bg-background px-2.5 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"
- placeholder={t('header.currentUser.userIdPlaceholder')}
- onChange={(event) => setManualUserId(event.target.value)}
- />
- <button
- type="submit"
- disabled={
- !manualTargetUserId ||
- manualTargetUserId === userId ||
- Boolean(switchingUserId)
- }
- className="flex h-8 shrink-0 items-center justify-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground transition-opacity disabled:cursor-not-allowed disabled:opacity-50"
- >
- {switchingUserId ? (
- <LoaderCircleIcon className="size-3.5 animate-spin" />
- ) : null}
- {t('header.currentUser.switchAction')}
- </button>
- </div>
- </form>
- </div>
- ) : null}
- </PopoverContent>
- </Popover>
- )
-}
diff --git a/web-studio/src/components/setup-identity-directory.test.tsx b/web-studio/src/components/setup-identity-directory.test.tsx
new file mode 100644
index 000000000..2f04d9d32
--- /dev/null
+++ b/web-studio/src/components/setup-identity-directory.test.tsx
@@ -0,0 +1,251 @@
+// @vitest-environment jsdom
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { SetupIdentityDirectory } from './setup-identity-directory'
+
+const mocks = vi.hoisted(() => ({
+ health: vi.fn(),
+ accounts: vi.fn(),
+ users: vi.fn(),
+}))
+vi.mock('#/lib/connection/health', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ fetchConnectionHealth: mocks.health,
+}))
+vi.mock('#/lib/admin', () => ({
+ fetchAdminAccounts: mocks.accounts,
+ fetchAdminUserDirectory: mocks.users,
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+const connection = {
+ serviceSelection: 'opensource' as const,
+ baseUrl: 'https://service.test',
+ apiKey: 'user-secret',
+ adminApiKey: 'root-secret',
+ accountId: 'team',
+ userId: 'alice',
+}
+beforeEach(() => {
+ vi.resetAllMocks()
+ mocks.accounts.mockResolvedValue([
+ { accountId: 'team', userCount: 1 },
+ { accountId: 'other', userCount: 1 },
+ ])
+ mocks.users.mockResolvedValue([
+ { accountId: 'team', userId: 'alice', role: 'user' },
+ ])
+})
+afterEach(cleanup)
+it('loads root accounts and a credential-free user directory without changing identity on load', async () => {
+ mocks.health.mockResolvedValue({
+ version: 'test',
+ role: 'root',
+ auth_mode: 'api_key',
+ account_id: 'default',
+ user_id: 'default',
+ })
+ const onSelect = vi.fn()
+ render(
+ <SetupIdentityDirectory
+ connection={connection}
+ disabled={false}
+ onSelect={onSelect}
+ />,
+ )
+ await screen.findByRole('combobox', { name: 'directoryAccount' })
+ await waitFor(() => expect(mocks.users).toHaveBeenCalled())
+ expect(mocks.health).toHaveBeenCalledWith(
+ expect.objectContaining({ apiKey: '', adminApiKey: 'root-secret' }),
+ expect.any(AbortSignal),
+ )
+ expect(mocks.users).toHaveBeenCalledWith(
+ expect.objectContaining({ apiKey: 'root-secret' }),
+ 'team',
+ )
+ expect(onSelect).not.toHaveBeenCalled()
+ const user = userEvent.setup()
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole('combobox', { name: 'directoryAccount' })
+ .hasAttribute('disabled'),
+ ).toBe(false),
+ )
+ await user.click(screen.getByRole('combobox', { name: 'directoryAccount' }))
+ await user.click(await screen.findByRole('option', { name: 'other' }))
+ expect(onSelect).toHaveBeenCalledWith({ accountId: 'other', userId: '' })
+})
+it('restricts an admin key to its authoritative account instead of listing all accounts', async () => {
+ mocks.health.mockResolvedValue({
+ version: 'test',
+ role: 'admin',
+ account_id: 'bound-account',
+ user_id: 'default',
+ })
+ const onSelect = vi.fn()
+ render(
+ <SetupIdentityDirectory
+ connection={connection}
+ disabled={false}
+ onSelect={onSelect}
+ />,
+ )
+ await screen.findByRole('combobox', { name: 'directoryAccount' })
+ expect(mocks.accounts).not.toHaveBeenCalled()
+ expect(mocks.users).not.toHaveBeenCalled()
+ const user = userEvent.setup()
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole('combobox', { name: 'directoryAccount' })
+ .hasAttribute('disabled'),
+ ).toBe(false),
+ )
+ await user.click(screen.getByRole('combobox', { name: 'directoryAccount' }))
+ expect(screen.queryByRole('option', { name: 'team' })).toBeNull()
+ await user.click(screen.getByRole('option', { name: 'bound-account' }))
+ expect(mocks.users).toHaveBeenCalledWith(
+ expect.objectContaining({ accountId: 'bound-account' }),
+ 'bound-account',
+ )
+})
+it('discards directory results after the control key changes', async () => {
+ let resolveOld!: (value: unknown) => void
+ mocks.health
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOld = resolve
+ }),
+ )
+ .mockResolvedValueOnce({ version: 'test', role: 'user' })
+ const { rerender } = render(
+ <SetupIdentityDirectory
+ connection={connection}
+ disabled={false}
+ onSelect={vi.fn()}
+ />,
+ )
+ rerender(
+ <SetupIdentityDirectory
+ connection={{ ...connection, adminApiKey: 'new-key' }}
+ disabled={false}
+ onSelect={vi.fn()}
+ />,
+ )
+ await screen.findByText('directoryControlRequired')
+ await act(async () => resolveOld({ version: 'test', role: 'root' }))
+ expect(mocks.accounts).not.toHaveBeenCalled()
+ expect(screen.queryByRole('combobox')).toBeNull()
+})
+
+it.each(['user', 'admin'])(
+ 'loads global accounts for a trusted Root key when the data role is %s',
+ async (role) => {
+ mocks.health.mockResolvedValue({
+ version: 'test',
+ auth_mode: 'trusted',
+ role,
+ account_id: 'team',
+ user_id: 'alice',
+ })
+ const onSelect = vi.fn()
+ render(
+ <SetupIdentityDirectory
+ connection={connection}
+ disabled={false}
+ onSelect={onSelect}
+ />,
+ )
+ await waitFor(() =>
+ expect(mocks.users).toHaveBeenCalledWith(
+ expect.objectContaining({ apiKey: 'root-secret' }),
+ 'team',
+ ),
+ )
+ expect(onSelect).not.toHaveBeenCalled()
+ expect(mocks.accounts).toHaveBeenCalledWith(
+ expect.objectContaining({ apiKey: 'root-secret' }),
+ )
+ const user = userEvent.setup()
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole('combobox', { name: 'directoryAccount' })
+ .hasAttribute('disabled'),
+ ).toBe(false),
+ )
+ await user.click(screen.getByRole('combobox', { name: 'directoryAccount' }))
+ await user.click(await screen.findByRole('option', { name: 'other' }))
+ expect(onSelect).toHaveBeenCalledWith({ accountId: 'other', userId: '' })
+ await waitFor(() =>
+ expect(mocks.users).toHaveBeenLastCalledWith(
+ expect.objectContaining({ apiKey: 'root-secret', accountId: 'other' }),
+ 'other',
+ ),
+ )
+ },
+)
+
+it.each([403, 503])(
+ 'does not infer control permissions from a trusted admin data role when the account probe fails with %s',
+ async (status) => {
+ mocks.health.mockResolvedValue({
+ version: 'test',
+ auth_mode: 'trusted',
+ role: 'admin',
+ account_id: 'team',
+ user_id: 'alice',
+ })
+ mocks.accounts.mockRejectedValue({ response: { status } })
+ const onSelect = vi.fn()
+ render(
+ <SetupIdentityDirectory
+ connection={connection}
+ disabled={false}
+ onSelect={onSelect}
+ />,
+ )
+ await screen.findByText(/directoryLoadFailed/)
+ expect(screen.queryByRole('combobox')).toBeNull()
+ expect(mocks.users).not.toHaveBeenCalled()
+ expect(onSelect).not.toHaveBeenCalled()
+ },
+)
+
+it('shows useful directory failure details without exposing either credential', async () => {
+ mocks.health.mockResolvedValue({
+ version: 'test',
+ auth_mode: 'api_key',
+ role: 'root',
+ })
+ mocks.accounts.mockRejectedValue(
+ new Error('Service unavailable for root-secret and user-secret'),
+ )
+ render(
+ <SetupIdentityDirectory
+ connection={{
+ ...connection,
+ apiKey: ' user-secret ',
+ adminApiKey: ' root-secret ',
+ }}
+ disabled={false}
+ onSelect={vi.fn()}
+ />,
+ )
+ const alert = await screen.findByRole('alert')
+ expect(alert.textContent).toContain('directoryLoadFailed')
+ expect(alert.textContent).toContain('Service unavailable')
+ expect(alert.textContent).not.toContain('root-secret')
+ expect(alert.textContent).not.toContain('user-secret')
+})
diff --git a/web-studio/src/components/setup-identity-directory.tsx b/web-studio/src/components/setup-identity-directory.tsx
new file mode 100644
index 000000000..2785123af
--- /dev/null
+++ b/web-studio/src/components/setup-identity-directory.tsx
@@ -0,0 +1,281 @@
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '#/components/ui/select'
+import { fetchAdminAccounts, fetchAdminUserDirectory } from '#/lib/admin'
+import type { AdminAccount, AdminConnection, AdminUser } from '#/lib/admin'
+import {
+ fetchConnectionHealth,
+ isUsableServerHealth,
+ readServerIdentity,
+} from '#/lib/connection/health'
+import type { ConnectionDraft } from '#/lib/connection/types'
+import { StudioSetupRequestError } from '#/lib/connection/onboarding'
+
+export function SetupIdentityDirectory({
+ connection,
+ disabled,
+ onSelect,
+}: {
+ connection: ConnectionDraft
+ disabled: boolean
+ onSelect: (identity: { accountId: string; userId: string }) => void
+}) {
+ const { t } = useTranslation('onboarding')
+ const [accounts, setAccounts] = useState<AdminAccount[]>([])
+ const [users, setUsers] = useState<AdminUser[]>([])
+ const [role, setRole] = useState<'root' | 'admin' | null>(null)
+ const [loadedAccount, setLoadedAccount] = useState('')
+ const [loading, setLoading] = useState(false)
+ const [error, setError] = useState('')
+ const revision = useRef(0)
+ const controller = useRef<AbortController | null>(null)
+ const scope = `${connection.baseUrl}\n${connection.adminApiKey}`
+ const currentScope = useRef(scope)
+ currentScope.current = scope
+ useEffect(() => {
+ revision.current += 1
+ controller.current?.abort()
+ setAccounts([])
+ setUsers([])
+ setRole(null)
+ setLoadedAccount('')
+ setLoading(false)
+ setError('')
+ return () => {
+ revision.current += 1
+ controller.current?.abort()
+ }
+ }, [scope])
+
+ const adminConnection: AdminConnection = {
+ baseUrl: connection.baseUrl,
+ apiKey: connection.adminApiKey.trim(),
+ accountId: connection.accountId,
+ userId: connection.userId,
+ }
+
+ async function loadDirectory() {
+ const request = ++revision.current
+ const sourceScope = scope
+ controller.current?.abort()
+ controller.current = new AbortController()
+ const signal = controller.current.signal
+ const current = () =>
+ request === revision.current &&
+ sourceScope === currentScope.current &&
+ !signal.aborted
+ setLoading(true)
+ setError('')
+ setRole(null)
+ setAccounts([])
+ setUsers([])
+ try {
+ // The directory is authorized only by the control key, never by a stale
+ // User API Key from a previously selected identity.
+ const health = await fetchConnectionHealth(
+ { ...connection, apiKey: '' },
+ signal,
+ )
+ if (!current()) return
+ if (
+ !isUsableServerHealth(health) ||
+ (health.auth_mode !== 'trusted' &&
+ health.role !== 'root' &&
+ health.role !== 'admin')
+ ) {
+ setError(t('directoryControlRequired'))
+ return
+ }
+ // In trusted mode /health describes the selected data user, not the
+ // control key. Like detectConnectionIdentity, verify Root capability by
+ // actually listing accounts; a failed probe must not fall back to the
+ // data user's admin role and incorrectly pin the directory to one tenant.
+ const listRootAccounts =
+ health.auth_mode === 'trusted' || health.role === 'root'
+ const directoryRole = listRootAccounts ? 'root' : 'admin'
+ const identity = readServerIdentity(health)
+ const scopedConnection = {
+ ...adminConnection,
+ accountId:
+ directoryRole === 'admin' ? identity.accountId : connection.accountId,
+ }
+ if (directoryRole === 'admin' && !scopedConnection.accountId) {
+ setError(t('directoryControlRequired'))
+ return
+ }
+ const nextAccounts = listRootAccounts
+ ? await fetchAdminAccounts(scopedConnection)
+ : [{ accountId: identity.accountId, userCount: 0 }]
+ if (!current()) return
+ setAccounts(nextAccounts)
+ setRole(directoryRole)
+ // Loading a list never silently switches the selected data identity.
+ const account = nextAccounts.find(
+ (item) => item.accountId === connection.accountId,
+ )?.accountId
+ if (account) {
+ const nextUsers = await fetchAdminUserDirectory(
+ scopedConnection,
+ account,
+ )
+ if (!current()) return
+ setUsers(nextUsers)
+ setLoadedAccount(account)
+ } else {
+ setLoadedAccount('')
+ }
+ } catch (cause) {
+ if (current())
+ setError(
+ `${t('directoryLoadFailed')} ${new StudioSetupRequestError('data', cause, connection).message}`,
+ )
+ } finally {
+ if (current()) setLoading(false)
+ }
+ }
+
+ async function selectAccount(accountId: string) {
+ if (!accounts.some((account) => account.accountId === accountId)) return
+ const request = ++revision.current
+ const sourceScope = scope
+ const current = () =>
+ request === revision.current && sourceScope === currentScope.current
+ setUsers([])
+ setLoadedAccount('')
+ setLoading(true)
+ setError('')
+ onSelect({ accountId, userId: '' })
+ try {
+ const nextUsers = await fetchAdminUserDirectory(
+ { ...adminConnection, accountId },
+ accountId,
+ )
+ if (!current()) return
+ setUsers(nextUsers)
+ setLoadedAccount(accountId)
+ } catch (cause) {
+ if (current())
+ setError(
+ `${t('directoryLoadFailed')} ${new StudioSetupRequestError('data', cause, connection).message}`,
+ )
+ } finally {
+ if (current()) setLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ void loadDirectory()
+ // This component mounts only after successful connection verification.
+ // Scope changes invalidate all outstanding requests in the cleanup above.
+ }, [scope])
+
+ return (
+ <div className="space-y-3 rounded-lg border border-border p-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="text-xs text-muted-foreground">{t('directoryHint')}</p>
+ {(loading || error) && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled || loading || !connection.adminApiKey.trim()}
+ onClick={() => void loadDirectory()}
+ >
+ {t(loading ? 'loadingUsers' : 'loadDirectory')}
+ </Button>
+ )}
+ </div>
+ {role && (
+ <div className="grid gap-3 sm:grid-cols-2">
+ <div className="space-y-1">
+ <p className="text-xs font-medium">{t('directoryAccount')}</p>
+ <Select
+ value={
+ accounts.some((a) => a.accountId === connection.accountId)
+ ? connection.accountId
+ : null
+ }
+ onValueChange={(value) => {
+ if (value) void selectAccount(value)
+ }}
+ disabled={disabled || loading}
+ >
+ <SelectTrigger
+ aria-label={t('directoryAccount')}
+ className="h-10 w-full"
+ >
+ <SelectValue placeholder={t('directoryAccount')} />
+ </SelectTrigger>
+ <SelectContent>
+ {accounts.map((account) => (
+ <SelectItem key={account.accountId} value={account.accountId}>
+ {account.accountId}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="space-y-1">
+ <p className="text-xs font-medium">{t('directoryUser')}</p>
+ <Select
+ value={
+ loadedAccount === connection.accountId &&
+ users.some((user) => user.userId === connection.userId)
+ ? connection.userId
+ : null
+ }
+ onValueChange={(value) => {
+ if (
+ value &&
+ loadedAccount === connection.accountId &&
+ users.some((user) => user.userId === value)
+ )
+ onSelect({ accountId: connection.accountId, userId: value })
+ }}
+ disabled={
+ disabled ||
+ loading ||
+ loadedAccount !== connection.accountId ||
+ users.length === 0
+ }
+ >
+ <SelectTrigger
+ aria-label={t('directoryUser')}
+ className="h-10 w-full"
+ >
+ <SelectValue placeholder={t('directoryUser')} />
+ </SelectTrigger>
+ <SelectContent>
+ {users.map((user) => (
+ <SelectItem key={user.userId} value={user.userId}>
+ {user.userId}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <p className="text-xs text-muted-foreground sm:col-span-2">
+ {t(role === 'admin' ? 'directoryAdminHint' : 'directoryKeyHint')}
+ </p>
+ {!loading && loadedAccount && users.length === 0 && (
+ <p className="text-xs text-muted-foreground sm:col-span-2">
+ {t('noUsers')}
+ </p>
+ )}
+ </div>
+ )}
+ {error && (
+ <p role="alert" className="text-xs text-destructive">
+ {error}
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/web-studio/src/components/studio-setup.test.tsx b/web-studio/src/components/studio-setup.test.tsx
index 4b4ec9ef5..1e3a30a4d 100644
--- a/web-studio/src/components/studio-setup.test.tsx
+++ b/web-studio/src/components/studio-setup.test.tsx
@@ -16,6 +16,20 @@ const mocks = vi.hoisted(() => ({
language: vi.fn(),
theme: vi.fn(),
}))
+vi.mock('./setup-identity-directory', () => ({
+ SetupIdentityDirectory: ({
+ onSelect,
+ }: {
+ onSelect: (identity: { accountId: string; userId: string }) => void
+ }) => (
+ <button
+ type="button"
+ onClick={() => onSelect({ accountId: 'team', userId: 'alice' })}
+ >
+ choose-directory-user
+ </button>
+ ),
+}))
vi.mock('next-themes', () => ({
useTheme: () => ({ theme: 'system', setTheme: mocks.theme }),
}))
@@ -45,7 +59,7 @@ beforeEach(() => {
localStorage.clear()
})
-it('deduplicates identical saved connections and keeps the active profile', async () => {
+it('groups workspace choices by endpoint despite different identities and credentials, keeping the active profile', async () => {
const connection = {
serviceSelection: 'opensource',
baseUrl: 'http://127.0.0.1:1933',
@@ -62,7 +76,12 @@ it('deduplicates identical saved connections and keeps the active profile', asyn
{
id: 'first',
name: 'Default',
- connection: { ...connection, userId: '' },
+ connection: {
+ ...connection,
+ baseUrl: connection.baseUrl + '/',
+ userId: 'alice',
+ apiKey: 'alice-key',
+ },
},
{
id: 'second',
@@ -81,7 +100,7 @@ it('deduplicates identical saved connections and keeps the active profile', asyn
const selector = screen.getByRole('combobox', {
name: 'connectionChoice',
})
- expect(selector.textContent).toContain('Open source')
+ expect(selector.textContent).toContain('openSourceConnection · ')
const user = userEvent.setup()
fireEvent.click(screen.getByRole('button', { name: 'next' }))
fireEvent.click(screen.getByRole('button', { name: 'advanced' }))
@@ -91,12 +110,18 @@ it('deduplicates identical saved connections and keeps the active profile', asyn
fireEvent.click(screen.getByRole('button', { name: 'back' }))
await user.click(screen.getByRole('combobox', { name: 'connectionChoice' }))
expect(await screen.findAllByRole('option')).toHaveLength(3)
- expect(screen.getAllByRole('option', { name: 'Open source' })).toHaveLength(1)
+ expect(
+ screen.getAllByRole('option', {
+ name: 'openSourceConnection · 127.0.0.1:1933',
+ }),
+ ).toHaveLength(1)
expect(screen.queryByRole('option', { name: 'Default' })).toBeNull()
- await user.click(screen.getByRole('option', { name: 'Remote' }))
+ await user.click(
+ screen.getByRole('option', { name: 'openSourceConnection · remote.test' }),
+ )
expect(
screen.getByRole('combobox', { name: 'connectionChoice' }).textContent,
- ).toContain('Remote')
+ ).toContain('openSourceConnection · remote.test')
fireEvent.click(screen.getByRole('button', { name: 'next' }))
expect(screen.getAllByText('https://remote.test/ov').length).toBeGreaterThan(
0,
@@ -134,14 +159,11 @@ it('shows the hosted server address on step one and requires a fresh API key eac
)
const first = render(<StudioSetup onComplete={vi.fn()} />)
const endpoint = screen.getByLabelText<HTMLInputElement>('hostedEndpoint')
- expect(endpoint.value).toBe('https://saved.hosted.test/ov')
+ expect(endpoint.textContent).toBe('https://saved.hosted.test/ov')
expect(
screen.queryByRole('combobox', { name: 'connectionChoice' }),
).toBeNull()
- fireEvent.change(endpoint, {
- target: { value: 'https://another.hosted.test/ov' },
- })
- expect(endpoint.value).toBe('https://another.hosted.test/ov')
+ expect(screen.queryByRole('textbox', { name: 'hostedEndpoint' })).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'next' }))
expect(
screen.queryByRole('combobox', { name: 'connectionChoice' }),
@@ -184,7 +206,7 @@ it('reuses an existing hosted profile only after the user reenters its API key',
)
mocks.verify.mockImplementation(async (draft) => draft)
render(<StudioSetup onComplete={vi.fn()} />)
- expect(screen.getByLabelText<HTMLInputElement>('hostedEndpoint').value).toBe(
+ expect(screen.getByLabelText('hostedEndpoint').textContent).toBe(
'https://saved.hosted.test/ov',
)
fireEvent.click(screen.getByRole('button', { name: 'next' }))
@@ -225,7 +247,7 @@ it('accepts an older hosted profile without an API key after manual verification
const done = vi.fn()
mocks.verify.mockImplementation(async (draft) => draft)
render(<StudioSetup onComplete={done} />)
- expect(screen.getByLabelText<HTMLInputElement>('hostedEndpoint').value).toBe(
+ expect(screen.getByLabelText('hostedEndpoint').textContent).toBe(
'https://saved.hosted.test/ov',
)
fireEvent.click(screen.getByRole('button', { name: 'next' }))
@@ -274,7 +296,7 @@ it('selects the configured open-source address when switching from hosted', () =
fireEvent.click(screen.getByLabelText('studio:providers.opensource'))
expect(
screen.getByRole('combobox', { name: 'connectionChoice' }).textContent,
- ).toContain('Open source')
+ ).toContain('openSourceConnection · ')
expect(
screen.getAllByTitle('https://configured.example/ov').length,
).toBeGreaterThan(0)
@@ -306,7 +328,7 @@ it('offers the local development service when only a hosted link is saved', () =
fireEvent.click(screen.getByLabelText('studio:providers.opensource'))
expect(
screen.getByRole('combobox', { name: 'connectionChoice' }).textContent,
- ).toContain('studio:localConnection')
+ ).toContain('openSourceConnection · 127.0.0.1:1933')
expect(screen.getAllByTitle('http://127.0.0.1:1933').length).toBeGreaterThan(
0,
)
@@ -428,72 +450,28 @@ it('keeps the user in setup on verification failure', async () => {
)
expect(done).not.toHaveBeenCalled()
})
-it('edits the hosted endpoint and uses it for connection verification', async () => {
+it('displays the hosted endpoint without offering an editable address', async () => {
render(<StudioSetup onComplete={vi.fn()} />)
fireEvent.click(screen.getByLabelText('studio:providers.volcengine'))
- expect(
- screen.queryByRole('combobox', { name: 'connectionChoice' }),
- ).toBeNull()
- const endpoint = screen.getByRole<HTMLInputElement>('textbox', {
- name: 'hostedEndpoint',
- })
- expect(endpoint.value).toBe(
- 'https://api.vikingdb.cn-beijing.volces.com/openviking',
- )
- fireEvent.change(endpoint, { target: { value: 'invalid-address' } })
- expect(
- screen.getByRole<HTMLButtonElement>('button', { name: 'next' }).disabled,
- ).toBe(true)
- fireEvent.change(endpoint, { target: { value: 'https://hosted.test/ov' } })
- expect(endpoint.value).toBe('https://hosted.test/ov')
- expect(
- screen.getByRole<HTMLButtonElement>('button', { name: 'next' }).disabled,
- ).toBe(false)
+ const endpoint = 'https://api.vikingdb.cn-beijing.volces.com/openviking'
+ expect(screen.getByText(endpoint)).toBeTruthy()
+ expect(screen.queryByRole('textbox', { name: 'hostedEndpoint' })).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'next' }))
- expect(
- screen.queryByRole('combobox', { name: 'connectionChoice' }),
- ).toBeNull()
- expect(screen.queryByLabelText('hostedEndpoint')).toBeNull()
- expect(screen.getByText('hostedKeyHelp')).toBeTruthy()
- fireEvent.click(screen.getByRole('button', { name: 'verify' }))
- expect(screen.getByRole('alert').textContent).toBe('keyRequired')
- expect(document.activeElement).toBe(
- screen.getByLabelText('settings:fields.userApiKey'),
- )
- expect(mocks.verify).not.toHaveBeenCalled()
+ expect(screen.queryByRole('radio')).toBeNull()
+ expect(screen.getByText('studio:providers.volcengine')).toBeTruthy()
+ expect(screen.getByText(endpoint)).toBeTruthy()
fireEvent.change(screen.getByLabelText('settings:fields.userApiKey'), {
target: { value: 'hosted-key' },
})
fireEvent.click(screen.getByRole('button', { name: 'verify' }))
await waitFor(() =>
expect(mocks.verify).toHaveBeenCalledWith(
- expect.objectContaining({
- baseUrl: 'https://hosted.test/ov',
- apiKey: 'hosted-key',
- }),
+ expect.objectContaining({ baseUrl: endpoint, apiKey: 'hosted-key' }),
expect.any(AbortSignal),
),
)
})
-it('clears the hosted API key when its service address changes', () => {
- render(<StudioSetup onComplete={vi.fn()} />)
- fireEvent.click(screen.getByLabelText('studio:providers.volcengine'))
- fireEvent.click(screen.getByRole('button', { name: 'next' }))
- fireEvent.change(screen.getByLabelText('settings:fields.userApiKey'), {
- target: { value: 'old-service-secret' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'back' }))
- fireEvent.change(screen.getByLabelText('hostedEndpoint'), {
- target: { value: 'https://another.hosted.test/ov' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'next' }))
- expect(
- screen.getByLabelText<HTMLInputElement>('settings:fields.userApiKey').value,
- ).toBe('')
- fireEvent.click(screen.getByRole('button', { name: 'verify' }))
- expect(screen.getByRole('alert').textContent).toBe('keyRequired')
- expect(mocks.verify).not.toHaveBeenCalled()
-})
+
it('keeps each workspace draft isolated when switching on the first step', () => {
render(<StudioSetup onComplete={vi.fn()} />)
const url = () =>
@@ -505,12 +483,9 @@ it('keeps each workspace draft isolated when switching on the first step', () =>
fireEvent.change(key(), { target: { value: 'synthetic-oss' } })
fireEvent.click(screen.getByRole('button', { name: 'back' }))
fireEvent.click(screen.getByLabelText('studio:providers.volcengine'))
- expect(screen.getByLabelText<HTMLInputElement>('hostedEndpoint').value).toBe(
+ expect(screen.getByLabelText('hostedEndpoint').textContent).toBe(
'https://api.vikingdb.cn-beijing.volces.com/openviking',
)
- fireEvent.change(screen.getByLabelText('hostedEndpoint'), {
- target: { value: 'https://cloud.test/ov' },
- })
fireEvent.click(screen.getByRole('button', { name: 'next' }))
expect(screen.queryByLabelText('hostedEndpoint')).toBeNull()
expect(key().value).toBe('')
@@ -522,8 +497,8 @@ it('keeps each workspace draft isolated when switching on the first step', () =>
expect(key().value).toBe('synthetic-oss')
fireEvent.click(screen.getByRole('button', { name: 'back' }))
fireEvent.click(screen.getByLabelText('studio:providers.volcengine'))
- expect(screen.getByLabelText<HTMLInputElement>('hostedEndpoint').value).toBe(
- 'https://cloud.test/ov',
+ expect(screen.getByLabelText('hostedEndpoint').textContent).toBe(
+ 'https://api.vikingdb.cn-beijing.volces.com/openviking',
)
fireEvent.click(screen.getByRole('button', { name: 'next' }))
expect(key().value).toBe('synthetic-cloud')
@@ -536,3 +511,72 @@ it('loads the logo from the deployment base path', () => {
'/studio/ov-logo.png',
)
})
+
+it('cancels an in-flight verification without replacing the saved workspace', async () => {
+ const onCancel = vi.fn()
+ const onComplete = vi.fn()
+ localStorage.setItem('ov_studio_setup', 'complete')
+ mocks.verify.mockImplementationOnce(() => new Promise(() => {}))
+ render(
+ <StudioSetup
+ onComplete={onComplete}
+ onCancel={onCancel}
+ canReturnToWorkspace
+ />,
+ )
+ fireEvent.change(screen.getByLabelText('settings:fields.baseUrl'), {
+ target: { value: 'https://other.test' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ await waitFor(() => expect(mocks.verify).toHaveBeenCalled())
+ const signal = mocks.verify.mock.calls[0][1] as AbortSignal
+ fireEvent.click(screen.getByRole('button', { name: 'cancel' }))
+ expect(signal.aborted).toBe(true)
+ expect(onCancel).toHaveBeenCalledOnce()
+ expect(onComplete).not.toHaveBeenCalled()
+ expect(mocks.complete).not.toHaveBeenCalled()
+ expect(localStorage.getItem('ov_studio_setup')).toBe('complete')
+})
+
+it('offers an exit on first use without requiring a valid address', () => {
+ const onCancel = vi.fn()
+ render(<StudioSetup onComplete={vi.fn()} onCancel={onCancel} />)
+ fireEvent.click(screen.getByRole('button', { name: 'exit' }))
+ expect(onCancel).toHaveBeenCalledOnce()
+ expect(mocks.verify).not.toHaveBeenCalled()
+})
+
+it('opens the account/user picker only after Verify and rejects a mismatched user key', async () => {
+ mocks.verify.mockImplementationOnce(async (draft) => draft)
+ render(<StudioSetup onComplete={vi.fn()} />)
+ fireEvent.change(screen.getByLabelText('settings:fields.baseUrl'), {
+ target: { value: 'https://service.test' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'next' }))
+ fireEvent.change(screen.getByLabelText('settings:fields.rootApiKey'), {
+ target: { value: 'root-secret' },
+ })
+ expect(screen.queryByText('choose-directory-user')).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ fireEvent.click(await screen.findByText('choose-directory-user'))
+ expect(
+ screen.getByLabelText<HTMLInputElement>('settings:fields.userApiKey').value,
+ ).toBe('')
+ expect(screen.queryByRole('button', { name: 'enter' })).toBeNull()
+ mocks.verify.mockImplementationOnce(async (draft) => ({
+ ...draft,
+ accountId: 'other',
+ userId: 'bob',
+ }))
+ fireEvent.change(screen.getByLabelText('settings:fields.userApiKey'), {
+ target: { value: 'wrong-user-key' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'verify' }))
+ await waitFor(() =>
+ expect(screen.getByRole('alert').textContent).toContain(
+ 'directoryIdentityMismatch',
+ ),
+ )
+ expect(screen.queryByRole('button', { name: 'enter' })).toBeNull()
+})
diff --git a/web-studio/src/components/studio-setup.tsx b/web-studio/src/components/studio-setup.tsx
index 89c0696b1..3bb0dd410 100644
--- a/web-studio/src/components/studio-setup.tsx
+++ b/web-studio/src/components/studio-setup.tsx
@@ -10,6 +10,7 @@ import {
ServerIcon,
Loader2Icon,
} from 'lucide-react'
+import { SetupIdentityDirectory } from './setup-identity-directory'
import { Button } from '#/components/ui/button'
import { Input } from '#/components/ui/input'
import {
@@ -33,11 +34,13 @@ import {
studioSetupDestination,
CLOUD_SETUP_URL,
completeStudioSetup,
- markStudioSetupPending,
savedSetupConnections,
verifyStudioSetup,
} from '#/lib/connection/onboarding'
-import { isValidConnectionUrl } from '#/lib/connection/profiles'
+import {
+ connectionProfileFingerprint,
+ isValidConnectionUrl,
+} from '#/lib/connection/profiles'
import type { ConnectionDraft } from '#/hooks/use-app-connection'
const LANGUAGES = [
@@ -49,7 +52,7 @@ const PROVIDERS = [
['volcengine', CloudIcon],
] as const
const THEMES = ['light', 'dark', 'system'] as const
-const ADVANCED_FIELDS = ['adminApiKey', 'accountId', 'userId'] as const
+const ADVANCED_FIELDS = ['accountId', 'userId'] as const
const NEW_CONNECTION = 'new'
type SavedConnection = ReturnType<typeof savedSetupConnections>[number]
@@ -57,25 +60,15 @@ function withoutCredentials(connection: ConnectionDraft): ConnectionDraft {
return { ...connection, apiKey: '', adminApiKey: '' }
}
-function savedConnectionTitle(profile: SavedConnection): string {
- const identity = [
- profile.connection.accountId,
- profile.connection.userId,
- ].filter((value) => value && value !== 'default')
- return identity.length
- ? `${profile.name} · ${identity.join('/')}`
- : profile.name
-}
-
function savedConnectionLabel(
profile: SavedConnection,
profiles: SavedConnection[],
+ providerLabel: string,
): string {
- const title = savedConnectionTitle(profile)
+ const domain = new URL(profile.connection.baseUrl).host
+ const title = `${providerLabel} · ${domain}`
const sameLabel = profiles.filter(
- (candidate) =>
- savedConnectionTitle(candidate) === title &&
- candidate.connection.baseUrl === profile.connection.baseUrl,
+ (candidate) => new URL(candidate.connection.baseUrl).host === domain,
)
if (sameLabel.length < 2) return title
return `${title} (${sameLabel.findIndex((candidate) => candidate.id === profile.id) + 1})`
@@ -96,13 +89,20 @@ function newConnectionDraft(
export function StudioSetup({
onComplete,
+ onCancel,
+ canReturnToWorkspace = false,
}: {
onComplete: (connection: ConnectionDraft) => void
+ onCancel?: () => void
+ canReturnToWorkspace?: boolean
}) {
const { t, i18n } = useTranslation(['onboarding', 'studio', 'settings'])
const { theme, setTheme } = useTheme()
const [step, setStep] = useState(0)
const [advancedOpen, setAdvancedOpen] = useState(false)
+ const [controlVerified, setControlVerified] = useState(false)
+ const [selectedDirectoryIdentity, setSelectedDirectoryIdentity] =
+ useState(false)
const [activeProfileId] = useState(() => {
try {
return JSON.parse(
@@ -139,14 +139,7 @@ export function StudioSetup({
.filter((profile) => {
const connection = profile.connection
const address = new URL(connection.baseUrl).href.replace(/\/+$/, '')
- const identity = JSON.stringify([
- connection.serviceSelection,
- address,
- connection.accountId,
- connection.userId,
- connection.apiKey,
- connection.adminApiKey,
- ])
+ const identity = JSON.stringify([connection.serviceSelection, address])
if (seen.has(identity)) return false
seen.add(identity)
return true
@@ -201,7 +194,6 @@ export function StudioSetup({
const cardAnimationRef = useRef<Animation | null>(null)
const previousCardHeightRef = useRef<number | null>(null)
useEffect(() => {
- markStudioSetupPending()
return () => abortRef.current?.abort()
}, [])
useEffect(() => {
@@ -239,6 +231,14 @@ export function StudioSetup({
? 'zh-CN'
: 'en'
function update(next: Partial<ConnectionDraft>) {
+ if ('baseUrl' in next || 'adminApiKey' in next) setControlVerified(false)
+ if (
+ 'baseUrl' in next ||
+ 'adminApiKey' in next ||
+ 'accountId' in next ||
+ 'userId' in next
+ )
+ setSelectedDirectoryIdentity(false)
connectionRevisionRef.current += 1
verifiedSelectionRef.current = null
setDraft((value) => ({ ...value, ...next }))
@@ -253,6 +253,8 @@ export function StudioSetup({
draft.serviceSelection === 'volcengine' ? 'volcengine' : 'opensource'
if (selectedConnectionId === NEW_CONNECTION)
newDraftsRef.current[provider] = draft
+ setControlVerified(false)
+ setSelectedDirectoryIdentity(false)
setSelectedConnectionId(id)
providerSelectionsRef.current[provider] = id
setDraft(
@@ -284,6 +286,8 @@ export function StudioSetup({
(profile) => profile.connection.serviceSelection === provider,
)?.id ??
NEW_CONNECTION)
+ setControlVerified(false)
+ setSelectedDirectoryIdentity(false)
setSelectedConnectionId(nextId)
const savedHostedConnection = savedConnections.find(
(profile) => profile.connection.serviceSelection === 'volcengine',
@@ -313,27 +317,15 @@ export function StudioSetup({
return
}
try {
- const matchingHostedProfile =
- verified.serviceSelection === 'volcengine'
- ? savedSetupConnections().find(
- (profile) =>
- profile.connection.serviceSelection === 'volcengine' &&
- new URL(profile.connection.baseUrl).href.replace(
- /\/+$/,
- '',
- ) === new URL(verified.baseUrl).href.replace(/\/+$/, '') &&
- typeof profile.connection.apiKey === 'string' &&
- profile.connection.apiKey.trim() === verified.apiKey,
- )
- : undefined
+ const matchingProfile = savedSetupConnections().find(
+ (profile) =>
+ connectionProfileFingerprint(profile.connection) ===
+ connectionProfileFingerprint(verified),
+ )
completeStudioSetup(
verified,
t(`studio:providers.${verified.serviceSelection}`),
- verified.serviceSelection === 'volcengine'
- ? matchingHostedProfile?.id
- : selectedConnectionId === NEW_CONNECTION
- ? undefined
- : selectedConnectionId,
+ matchingProfile?.id,
)
onComplete(verified)
} catch {
@@ -360,6 +352,19 @@ export function StudioSetup({
!controller.signal.aborted &&
connectionRevision === connectionRevisionRef.current
) {
+ if (
+ selectedDirectoryIdentity &&
+ draft.apiKey &&
+ (result.accountId !== draft.accountId ||
+ result.userId !== draft.userId)
+ ) {
+ setError(t('directoryIdentityMismatch'))
+ return
+ }
+ setControlVerified(
+ result.serviceSelection === 'opensource' &&
+ Boolean(result.adminApiKey),
+ )
setDraft(result)
verifiedSelectionRef.current = selectedConnectionId
setVerified(result)
@@ -394,6 +399,20 @@ export function StudioSetup({
<span className="text-base font-semibold tracking-tight">
{t('brand')}
</span>
+ {onCancel ? (
+ <Button
+ type="button"
+ variant="ghost"
+ className="ml-auto"
+ onClick={() => {
+ connectionRevisionRef.current += 1
+ abortRef.current?.abort()
+ onCancel()
+ }}
+ >
+ {t(canReturnToWorkspace ? 'cancel' : 'exit')}
+ </Button>
+ ) : null}
</div>
<div className="grid items-start gap-6 lg:grid-cols-[1fr_1.15fr] lg:gap-20">
<header className="lg:pt-5">
@@ -515,6 +534,7 @@ export function StudioSetup({
? savedConnectionLabel(
selectedProfile,
providerConnections,
+ t('openSourceConnection'),
)
: t('newConnection')}
</SelectValue>
@@ -534,6 +554,7 @@ export function StudioSetup({
{savedConnectionLabel(
profile,
providerConnections,
+ t('openSourceConnection'),
)}
</span>
</SelectItem>
@@ -586,32 +607,18 @@ export function StudioSetup({
</div>
) : (
<div className="space-y-2">
- <label
- htmlFor="setup-hosted-url"
+ <p
+ id="setup-hosted-url-label"
className="text-sm font-medium"
>
{t('hostedEndpoint')}
- </label>
- <Input
- id="setup-hosted-url"
- className="h-11 rounded-lg"
- type="url"
- value={draft.baseUrl}
- aria-invalid={Boolean(draft.baseUrl) && !canContinue}
- onChange={(event) =>
- update({
- baseUrl: event.target.value,
- apiKey: '',
- adminApiKey: '',
- })
- }
- {...PLAIN_INPUT_PROPS}
- />
- {draft.baseUrl && !canContinue ? (
- <p className="text-xs text-destructive">
- {t('studio:profiles.invalidUrl')}
- </p>
- ) : null}
+ </p>
+ <p
+ aria-labelledby="setup-hosted-url-label"
+ className="break-all rounded-lg bg-muted/30 px-4 py-3 text-sm text-muted-foreground"
+ >
+ {draft.baseUrl}
+ </p>
</div>
)}
<fieldset className="space-y-3">
@@ -697,8 +704,12 @@ export function StudioSetup({
<fieldset disabled={busy} className="space-y-4">
<div className="grid gap-2 text-sm">
<span className="font-medium">
- {t('settings:fields.baseUrl')}
+ {t('studio:serviceType')}
</span>
+ <p>{t(`studio:providers.${draft.serviceSelection}`)}</p>
+ </div>
+ <div className="grid gap-2 text-sm">
+ <span className="font-medium">{t('hostedEndpoint')}</span>
<p className="break-all rounded-lg border border-border bg-muted/30 px-4 py-3 text-sm">
{draft.baseUrl}
</p>
@@ -744,7 +755,33 @@ export function StudioSetup({
: 'keyHelp',
)}
</p>
- {draft.serviceSelection === 'opensource' ? (
+ {draft.serviceSelection === 'opensource' && (
+ <div className="grid gap-2 text-sm font-medium">
+ <label htmlFor="setup-adminApiKey">
+ {t('settings:fields.rootApiKey')}
+ </label>
+ <Input
+ id="setup-adminApiKey"
+ aria-describedby="setup-control-hint"
+ type="password"
+ value={draft.adminApiKey}
+ onChange={(event) =>
+ update({ adminApiKey: event.target.value })
+ }
+ className="h-11 rounded-lg"
+ {...PLAIN_INPUT_PROPS}
+ autoComplete="new-password"
+ />
+ <p
+ id="setup-control-hint"
+ className="text-xs font-normal text-muted-foreground"
+ >
+ {t('verifyDirectoryHint')}
+ </p>
+ </div>
+ )}
+ {draft.serviceSelection === 'opensource' &&
+ !controlVerified ? (
<div>
<button
type="button"
@@ -774,27 +811,19 @@ export function StudioSetup({
htmlFor={`setup-${key}`}
>
{t(
- `settings:fields.${key === 'accountId' ? 'account' : key === 'userId' ? 'user' : 'rootApiKey'}`,
+ `settings:fields.${key === 'accountId' ? 'account' : 'user'}`,
)}
<Input
id={`setup-${key}`}
className="focus-visible:ring-inset"
name={key}
- type={
- key === 'adminApiKey'
- ? 'password'
- : 'text'
- }
+ type={'text'}
value={draft[key]}
onChange={(event) =>
update({ [key]: event.target.value })
}
{...PLAIN_INPUT_PROPS}
- autoComplete={
- key === 'adminApiKey'
- ? 'new-password'
- : 'off'
- }
+ autoComplete={'off'}
/>
</label>
))}
@@ -804,6 +833,22 @@ export function StudioSetup({
</div>
) : null}
</fieldset>
+ {controlVerified && (
+ <SetupIdentityDirectory
+ connection={draft}
+ disabled={busy}
+ onSelect={(identity) => {
+ const changed =
+ identity.accountId !== draft.accountId ||
+ identity.userId !== draft.userId
+ update({
+ ...identity,
+ ...(changed ? { apiKey: '' } : {}),
+ })
+ setSelectedDirectoryIdentity(true)
+ }}
+ />
+ )}
{error && error !== t('keyRequired') ? (
<p
role="alert"
@@ -866,7 +911,7 @@ function ThemePreview({ appearance }: { appearance: (typeof THEMES)[number] }) {
return (
<div
aria-hidden="true"
- className={`relative h-14 overflow-hidden rounded-md border border-black/10 ${appearance === 'light' ? 'bg-[#f9fafb]' : appearance === 'dark' ? 'bg-[#191b20]' : 'bg-[linear-gradient(110deg,#f9fafb_50%,#191b20_50%)]'}`}
+ className={`relative h-14 overflow-hidden rounded-md border border-black/10 bg-clip-padding ${appearance === 'light' ? 'bg-[#f9fafb]' : appearance === 'dark' ? 'bg-[#191b20]' : 'bg-[linear-gradient(110deg,#f9fafb_calc(50%_-_0.5px),#191b20_calc(50%_+_0.5px))]'}`}
>
<div
className={`flex h-4 items-center gap-1 border-b px-2 ${appearance === 'dark' ? 'border-white/10' : 'border-black/10'}`}
diff --git a/web-studio/src/hooks/use-app-connection.test.ts b/web-studio/src/hooks/use-app-connection.test.ts
index d981cfcd2..570325d2b 100644
--- a/web-studio/src/hooks/use-app-connection.test.ts
+++ b/web-studio/src/hooks/use-app-connection.test.ts
@@ -441,3 +441,19 @@ describe('connection credential planes', () => {
})
})
})
+
+it('does not synchronize a control-key placeholder into the selected data user', () => {
+ expect(
+ synchronizeResolvedDataIdentity(
+ {
+ serviceSelection: 'opensource',
+ baseUrl: 'https://service.test',
+ apiKey: '',
+ adminApiKey: 'admin-key',
+ accountId: 'tenant',
+ userId: 'alice',
+ },
+ { role: 'admin', accountId: 'tenant', userId: 'default' },
+ ),
+ ).toBeNull()
+})
diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsx
index 368f5a25f..7ea13c55a 100644
--- a/web-studio/src/hooks/use-app-connection.tsx
+++ b/web-studio/src/hooks/use-app-connection.tsx
@@ -12,6 +12,7 @@ import { fetchAdminAccounts } from '#/lib/admin'
import { isOvClientError, ovClient } from '#/lib/ov-client'
import {
readConnectionProfiles,
+ activateIdentityProfile,
persistConnectionProfiles,
updateActiveProfile,
normalizeProfileConnection,
@@ -397,6 +398,7 @@ export function synchronizeResolvedDataIdentity(
identity: ConnectionIdentity,
): ConnectionDraft | null {
if (
+ (!connection.apiKey && Boolean(connection.adminApiKey)) ||
(identity.role !== 'admin' && identity.role !== 'user') ||
!identity.accountId ||
!identity.userId ||
@@ -827,12 +829,18 @@ export function AppConnectionProvider({
}
}
- const commitConnection = (next: ConnectionDraft) => {
+ const commitConnection = (
+ next: ConnectionDraft,
+ preserveIdentity = false,
+ ) => {
connectionGenerationRef.current += 1
connectionRevisionRef.current += 1
authPromptSuppressedUntilRef.current =
Date.now() + AUTH_PROMPT_SUPPRESSION_MS
const normalized = synchronizeConnectionRuntime(next, serverMode)
+ if (preserveIdentity) {
+ storeProfiles(activateIdentityProfile(profilesRef.current!, normalized))
+ }
queryClient.clear()
setConnection(normalized)
}
@@ -958,10 +966,13 @@ export function AppConnectionProvider({
})
}
assertCurrentConnection()
- commitConnection({
- ...requested,
- ...resolvedIdentity,
- })
+ commitConnection(
+ {
+ ...requested,
+ ...resolvedIdentity,
+ },
+ true,
+ )
},
switchManagementAccount: async (accountId) => {
assertSourceConnection()
@@ -974,6 +985,7 @@ export function AppConnectionProvider({
accountId,
isGatewayHost,
),
+ true,
)
},
}
diff --git a/web-studio/src/i18n/locales/en/onboarding.ts b/web-studio/src/i18n/locales/en/onboarding.ts
index 70bee3caa..73c42bf08 100644
--- a/web-studio/src/i18n/locales/en/onboarding.ts
+++ b/web-studio/src/i18n/locales/en/onboarding.ts
@@ -1,4 +1,24 @@
export default {
+ verifyDirectoryHint:
+ 'Optional. After Verify Connection, choose an Account and User with this Root or Admin key. A User API Key is still needed for data access.',
+ loadDirectory: 'Load Accounts & Users',
+ directoryHint: 'Use a Root or Admin API Key to browse identities.',
+ directoryControlRequired:
+ 'Enter a valid Root or Admin API Key to load accounts and users.',
+ directoryLoadFailed:
+ 'Could not load identities. Check the management key and service address, then retry.',
+ directoryAccount: 'Select Account',
+ directoryUser: 'Select User',
+ directoryAdminHint:
+ 'An Admin key can select users only in its own account. Enter that user’s API Key to access data.',
+ directoryKeyHint:
+ 'Selecting an identity does not grant data access. Enter its User API Key, or leave it empty to manage accounts only.',
+ directoryIdentityMismatch:
+ 'This User API Key belongs to a different account or user. Enter the key for the selected identity.',
+
+ openSourceConnection: 'OpenSource',
+ cancel: 'Cancel',
+ exit: 'Exit Studio',
connectionTitle: 'Connect your workspace.',
preferencesHint: 'Choose your language and appearance.',
connectionHint: 'Connect and verify an OpenViking service.',
@@ -19,7 +39,7 @@ export default {
savedConnectionUnavailable:
'This saved connection is unavailable. Choose another one or enter a new API Key.',
newAddressHint: 'Enter a valid HTTP or HTTPS address to continue.',
- hostedEndpoint: 'Service address',
+ hostedEndpoint: 'Service Address',
preferences: 'Preferences',
connection: 'Connect a service',
welcome: 'Welcome to\nOpenViking Studio',
diff --git a/web-studio/src/i18n/locales/en/studio.ts b/web-studio/src/i18n/locales/en/studio.ts
index 217b04ace..3597f7093 100644
--- a/web-studio/src/i18n/locales/en/studio.ts
+++ b/web-studio/src/i18n/locales/en/studio.ts
@@ -92,7 +92,7 @@ const studio = {
'Enter a valid HTTP or HTTPS service address without embedded credentials.',
deleteConfirm: 'Delete “{{name}}”? Its saved credentials will be removed.',
fields: {
- baseUrl: 'Service address',
+ baseUrl: 'Service Address',
apiKey: 'User API Key',
adminApiKey: 'Management API Key (optional)',
accountId: 'Account ID',
@@ -132,12 +132,12 @@ const studio = {
management: 'Management',
},
providers: {
- opensource: 'Open source',
- volcengine: 'Volcengine hosted',
+ opensource: 'Open Source',
+ volcengine: 'VolcEngine Hosted',
unknown: 'Service type unconfirmed',
checking: 'Checking connection…',
},
- serviceType: 'Service type',
+ serviceType: 'Service Type',
auto: 'Detect automatically',
serviceHint:
'Automatic detection uses Volcengine for official endpoints and open source for other addresses. For a hosted proxy, select Volcengine hosted. Features appear after connection verification.',
diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.ts
index 1da6c0843..0c893d116 100644
--- a/web-studio/src/i18n/locales/en/workspace.ts
+++ b/web-studio/src/i18n/locales/en/workspace.ts
@@ -4,8 +4,8 @@ const workspace = {
agentIntegrations: 'Agent Integrations',
beta: 'Beta',
connection: 'Connection Settings',
- gateway: 'OpenViking Gateway',
- gatewayBeta: 'OpenViking Gateway · Beta',
+ gateway: 'Gateway',
+ gatewayBeta: 'Gateway · Beta',
docs: 'Documentation',
github: 'GitHub',
sdkApi: 'SDK & API',
@@ -684,16 +684,30 @@ const workspace = {
},
},
accountSwitcher: {
- create: 'Create account',
+ accountsConnectFirst:
+ 'Select a saved identity to connect to this service before browsing its accounts.',
+ accountsChecking: 'Checking account management access…',
+ accountsRootRequired:
+ 'Configure a Root API Key in Connection Settings to browse and switch server accounts. Saved identities remain available in the adjacent tab.',
+ servicesSearch: 'Search services',
+ identitiesSearch: 'Search saved identities',
+ identities: 'Saved Identities',
+ connected: 'Connected',
+ noConnections: 'No matching services',
+ noIdentities: 'No saved identities for this service',
+ backToServices: 'Back to services',
+ accountSettings: 'Account Settings',
+ manageConnections: 'Manage Connections',
+ create: 'Add Account',
connections: {
- add: 'Add connection',
+ add: 'Add Connection',
savedOnly: 'Connections saved in Connection Settings',
switch: 'Switch connection',
title: 'Saved connections',
},
- serverAccountsTitle: 'Server accounts',
+ serverAccountsTitle: 'Accounts',
provider: {
- hosted: 'Volcengine hosted',
+ hosted: 'VolcEngine Hosted',
opensource: 'Open source',
},
hosted: {
diff --git a/web-studio/src/i18n/locales/zh-CN/onboarding.ts b/web-studio/src/i18n/locales/zh-CN/onboarding.ts
index 0e267a4bf..bc885a706 100644
--- a/web-studio/src/i18n/locales/zh-CN/onboarding.ts
+++ b/web-studio/src/i18n/locales/zh-CN/onboarding.ts
@@ -1,4 +1,23 @@
export default {
+ verifyDirectoryHint:
+ '可选。填写 Root 或 Admin Key 并验证连接后,可选择 Account 和 User;访问数据仍需对应的 User API Key。',
+ loadDirectory: '加载 Account 和 User',
+ directoryHint: '使用 Root 或 Admin API Key 浏览可选身份。',
+ directoryControlRequired:
+ '请输入有效的 Root 或 Admin API Key 后加载账号和用户。',
+ directoryLoadFailed: '加载身份失败,请检查管理密钥和服务地址后重试。',
+ directoryAccount: '选择 Account',
+ directoryUser: '选择 User',
+ directoryAdminHint:
+ 'Admin Key 仅可选择所属 Account 中的用户。访问数据还需填写该用户的 API Key。',
+ directoryKeyHint:
+ '选择身份不会自动授予数据权限。请填写对应的 User API Key;留空则仅进入账号管理。',
+ directoryIdentityMismatch:
+ '此 User API Key 属于其他账号或用户,请输入所选身份对应的密钥。',
+
+ openSourceConnection: 'OpenSource',
+ cancel: '取消',
+ exit: '退出 Studio',
connectionTitle: '连接你的工作区。',
preferencesHint: '选择你熟悉的语言与外观。',
connectionHint: '连接并验证你的 OpenViking 服务。',
diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.ts
index 06d32d44a..df7672a74 100644
--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts
+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts
@@ -657,6 +657,19 @@ const workspace = {
},
},
accountSwitcher: {
+ accountsConnectFirst: '请先在已保存身份中连接此服务,再查看服务端账号。',
+ accountsChecking: '正在验证账号管理权限…',
+ accountsRootRequired:
+ '请在连接设置中配置 Root API Key,以浏览和切换服务端账号。已有身份仍可在旁边的页签切换。',
+ servicesSearch: '搜索服务',
+ identitiesSearch: '搜索已保存身份',
+ identities: '已保存身份',
+ connected: '已连接',
+ noConnections: '没有匹配的服务',
+ noIdentities: '此服务没有匹配的已保存身份',
+ backToServices: '返回服务列表',
+ accountSettings: 'Account 设置',
+ manageConnections: '管理连接',
create: '新建账号',
connections: {
add: '添加连接',
diff --git a/web-studio/src/lib/connection/onboarding.test.ts b/web-studio/src/lib/connection/onboarding.test.ts
index fd8da47c3..7f1543445 100644
--- a/web-studio/src/lib/connection/onboarding.test.ts
+++ b/web-studio/src/lib/connection/onboarding.test.ts
@@ -328,3 +328,68 @@ describe('management bootstrap', () => {
).toBe('/filesystem')
})
})
+
+it.each([
+ ['root', 'chosen-account'],
+ ['admin', 'bound-account'],
+])(
+ 'keeps the selected user when verifying a %s control credential',
+ async (role, expectedAccount) => {
+ get
+ .mockResolvedValueOnce({
+ data: {
+ version: 'test',
+ auth_mode: 'api_key',
+ role,
+ account_id: role === 'root' ? 'default' : 'bound-account',
+ user_id: 'default',
+ },
+ })
+ .mockResolvedValueOnce({
+ status: 200,
+ headers: {},
+ data: { status: 'ok', result: [] },
+ })
+ const result = await verifyStudioSetup(
+ {
+ ...draft,
+ apiKey: '',
+ adminApiKey: 'control-key',
+ accountId: 'chosen-account',
+ userId: 'alice',
+ },
+ new AbortController().signal,
+ )
+ expect(result.accountId).toBe(expectedAccount)
+ expect(result.userId).toBe('alice')
+ expect(result.apiKey).toBe('')
+ expect(get.mock.calls[1][0].path.account_id).toBe(expectedAccount)
+ },
+)
+
+it('uses the User API Key identity when a separate control key is also configured', async () => {
+ get
+ .mockResolvedValueOnce({
+ data: {
+ version: 'test',
+ auth_mode: 'api_key',
+ role: 'user',
+ account_id: 'user-account',
+ user_id: 'alice',
+ },
+ })
+ .mockResolvedValueOnce({
+ status: 200,
+ headers: {},
+ data: { status: 'ok', result: [] },
+ })
+ const result = await verifyStudioSetup(
+ { ...draft, adminApiKey: 'control-key' },
+ new AbortController().signal,
+ )
+ expect(result.accountId).toBe('user-account')
+ expect(result.userId).toBe('alice')
+ expect(vi.mocked(createClient).mock.calls[0][0]?.headers?.['X-API-Key']).toBe(
+ 'synthetic-key',
+ )
+})
diff --git a/web-studio/src/lib/connection/onboarding.ts b/web-studio/src/lib/connection/onboarding.ts
index 55b4e4bce..214ec37c3 100644
--- a/web-studio/src/lib/connection/onboarding.ts
+++ b/web-studio/src/lib/connection/onboarding.ts
@@ -36,7 +36,9 @@ export class StudioSetupRequestError extends Error {
) {
const error = normalizeOvClientError(cause)
let message = error.message
- for (const secret of [connection.apiKey, connection.adminApiKey]) {
+ for (const secret of [connection.apiKey, connection.adminApiKey].flatMap(
+ (key) => [key, key.trim()],
+ )) {
if (secret) message = message.replaceAll(secret, '[redacted]')
}
super(`${error.statusCode ? `HTTP ${error.statusCode}: ` : ''}${message}`, {
@@ -167,20 +169,27 @@ export async function verifyStudioSetup(
connection.accountId = ''
connection.userId = ''
}
+ const managementOnly =
+ mode === 'api_key' &&
+ connection.serviceSelection === 'opensource' &&
+ !connection.apiKey &&
+ Boolean(connection.adminApiKey)
const identity = readServerIdentity(health)
- if (identity.accountId) connection.accountId = identity.accountId
- if (identity.userId) connection.userId = identity.userId
+ // Control credentials do not identify a tenant data user. Root's default
+ // identity is only a placeholder; an account-admin key binds the account,
+ // but must not replace the user's selected data identity.
+ if (!managementOnly) {
+ if (identity.accountId) connection.accountId = identity.accountId
+ if (identity.userId) connection.userId = identity.userId
+ } else if (health.role === 'admin' && identity.accountId) {
+ connection.accountId = identity.accountId
+ }
const dataClient = createClient({
baseURL: connection.baseUrl,
headers: createConnectionHealthHeaders(connection, 'data'),
timeout: 10000,
throwOnError: true,
})
- const managementOnly =
- mode === 'api_key' &&
- connection.serviceSelection === 'opensource' &&
- !connection.apiKey &&
- Boolean(connection.adminApiKey)
if (managementOnly) {
// ROOT cannot call tenant data APIs. Verify control access before letting
// a new administrator open Users and mint a separate user credential.
diff --git a/web-studio/src/lib/connection/profiles.test.ts b/web-studio/src/lib/connection/profiles.test.ts
index 8261eb786..e50316053 100644
--- a/web-studio/src/lib/connection/profiles.test.ts
+++ b/web-studio/src/lib/connection/profiles.test.ts
@@ -2,6 +2,7 @@
import { afterEach, expect, it } from 'vitest'
import {
readConnectionProfiles,
+ activateIdentityProfile,
persistConnectionProfiles,
updateActiveProfile,
normalizeProfileConnection,
@@ -92,3 +93,20 @@ it('recovers a missing active ID and ignores malformed records without losing th
'legacy-key',
)
})
+
+it('preserves identities on one endpoint and reuses an exact saved identity', () => {
+ const initial = readConnectionProfiles(fallback)
+ const next = { ...fallback, userId: 'bob', apiKey: 'bob-key' }
+ const switched = activateIdentityProfile(initial, next)
+ expect(switched.profiles).toHaveLength(2)
+ expect(switched.profiles[0]).toEqual(initial.profiles[0])
+ expect(switched.activeId).not.toBe(initial.activeId)
+ const restored = activateIdentityProfile(switched, fallback)
+ expect(restored.activeId).toBe(initial.activeId)
+ expect(restored.profiles).toHaveLength(2)
+ const otherCredential = activateIdentityProfile(switched, {
+ ...next,
+ apiKey: 'other-key',
+ })
+ expect(otherCredential.profiles).toHaveLength(3)
+})
diff --git a/web-studio/src/lib/connection/profiles.ts b/web-studio/src/lib/connection/profiles.ts
index 98e682eab..644bf264b 100644
--- a/web-studio/src/lib/connection/profiles.ts
+++ b/web-studio/src/lib/connection/profiles.ts
@@ -1,3 +1,4 @@
+import { createRandomUuid } from '#/lib/browser-crypto'
import type { ConnectionDraft } from '#/lib/connection/types'
import { resolveConfiguredServiceProvider } from '../studio-service'
@@ -140,3 +141,30 @@ export function updateActiveProfile(
),
}
}
+
+// Explicit identity switches preserve the previous identity and its credentials.
+// Ordinary configuration edits still update the selected profile in place.
+export function activateIdentityProfile(
+ value: ConnectionProfiles,
+ connection: ConnectionDraft,
+): ConnectionProfiles {
+ const normalized = normalizeProfileConnection(connection)
+ const fingerprint = connectionProfileFingerprint(normalized)
+ const existing = value.profiles.find(
+ (profile) =>
+ connectionProfileFingerprint(profile.connection) === fingerprint,
+ )
+ if (existing) return { ...value, activeId: existing.id }
+ const id = createRandomUuid()
+ return {
+ activeId: id,
+ profiles: [
+ ...value.profiles,
+ {
+ id,
+ name: `${normalized.accountId}/${normalized.userId}`,
+ connection: normalized,
+ },
+ ],
+ }
+}
diff --git a/web-studio/src/routes/gateway/-lib/i18n-parity.test.ts b/web-studio/src/routes/gateway/-lib/i18n-parity.test.ts
index 3f2011764..c1526e6d0 100644
--- a/web-studio/src/routes/gateway/-lib/i18n-parity.test.ts
+++ b/web-studio/src/routes/gateway/-lib/i18n-parity.test.ts
@@ -35,7 +35,7 @@ describe('gateway translations', () => {
})
it('label the sidebar entry in both languages', () => {
- expect(en.appShell.footer.gateway).toBe('OpenViking Gateway')
+ expect(en.appShell.footer.gateway).toBe('Gateway')
expect(zhCN.appShell.footer.gateway).toBe('OpenViking 网关')
})
diff --git a/web-studio/src/routes/settings/-components/connection-profiles.test.ts b/web-studio/src/routes/settings/-components/connection-profiles.test.ts
index deef13b93..281644e13 100644
--- a/web-studio/src/routes/settings/-components/connection-profiles.test.ts
+++ b/web-studio/src/routes/settings/-components/connection-profiles.test.ts
@@ -1,11 +1,13 @@
// @vitest-environment jsdom
import * as React from 'react'
import {
+ act,
cleanup,
fireEvent,
render,
screen,
within,
+ waitFor,
} from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { ConnectionProfile } from '#/lib/connection/profiles'
@@ -21,6 +23,37 @@ const connectionState = vi.hoisted(() => ({
activateProfile: vi.fn(),
deleteProfile: vi.fn(),
}))
+const verify = vi.hoisted(() => vi.fn())
+vi.mock('#/lib/connection/onboarding', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ verifyStudioSetup: verify,
+}))
+vi.mock('#/components/setup-identity-directory', () => ({
+ SetupIdentityDirectory: ({
+ onSelect,
+ }: {
+ onSelect: (identity: { accountId: string; userId: string }) => void
+ }) =>
+ React.createElement(
+ 'button',
+ {
+ type: 'button',
+ onClick: () => onSelect({ accountId: 'team', userId: 'bob' }),
+ },
+ 'Select Bob',
+ ),
+}))
+
+vi.mock('@tanstack/react-router', () => ({
+ Link: ({
+ to,
+ children,
+ ...props
+ }: {
+ to: string
+ children: React.ReactNode
+ }) => React.createElement('a', { href: to, ...props }, children),
+}))
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => connectionState,
@@ -49,6 +82,7 @@ const hosted = (
beforeEach(() => {
vi.clearAllMocks()
+ verify.mockReset()
connectionState.profiles = []
connectionState.activeProfileId = 'active'
})
@@ -140,28 +174,124 @@ it('lets every record in an identical connection group be managed', () => {
expect(connectionState.activateProfile).toHaveBeenCalledWith('duplicate')
})
-it('creates a connection on HTTP origins without crypto.randomUUID', () => {
- const getRandomValues = globalThis.crypto.getRandomValues.bind(
- globalThis.crypto,
- )
- vi.stubGlobal('crypto', { getRandomValues })
+it('routes adding a profile to the connection wizard without creating a modal draft', () => {
+ render(React.createElement(ConnectionProfilesList))
+ expect(
+ screen.getByRole('link', { name: 'profiles.add' }).getAttribute('href'),
+ ).toBe('/config')
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(connectionState.saveProfile).not.toHaveBeenCalled()
+})
+it('preserves a saved hosted proxy address when editing its name', () => {
+ const profile = hosted('proxy', 'team', 'alice')
+ profile.connection.baseUrl = 'https://hosted-proxy.example/openviking'
+ connectionState.profiles = [profile]
render(React.createElement(ConnectionProfilesList))
- fireEvent.click(screen.getByRole('button', { name: 'profiles.add' }))
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.edit' }))
+ const address = screen.getByDisplayValue(profile.connection.baseUrl)
+ expect(address.hasAttribute('readonly')).toBe(true)
fireEvent.change(screen.getByLabelText('profiles.name'), {
- target: { value: 'Local' },
+ target: { value: 'Renamed' },
})
- fireEvent.change(screen.getByLabelText('profiles.fields.baseUrl'), {
- target: { value: 'http://192.0.2.1:1933' },
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.save' }))
+ expect(connectionState.saveProfile).toHaveBeenCalledWith({
+ ...profile,
+ name: 'Renamed',
})
+ expect(verify).not.toHaveBeenCalled()
+})
+
+function selectDirectoryUser() {
+ const profile = hosted('active', 'team', 'alice', 'alice-key')
+ profile.connection.serviceSelection = 'opensource'
+ profile.connection.baseUrl = 'https://service.example'
+ profile.connection.adminApiKey = 'root-key'
+ connectionState.profiles = [profile]
+ render(React.createElement(ConnectionProfilesList))
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.edit' }))
+ fireEvent.click(screen.getByRole('button', { name: 'onboarding:verify' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Select Bob' }))
+ return {
+ ...profile,
+ connection: { ...profile.connection, userId: 'bob', apiKey: '' },
+ }
+}
+
+it.each([
+ { accountId: 'other-team', userId: 'bob' },
+ { accountId: 'team', userId: 'alice' },
+])(
+ 'rejects a key for $accountId/$userId and then saves a matching key',
+ async (identity) => {
+ const expected = selectDirectoryUser()
+ const key = screen.getByLabelText('profiles.fields.apiKey')
+ expect((key as HTMLInputElement).value).toBe('')
+ verify.mockResolvedValueOnce({ ...expected.connection, ...identity })
+ fireEvent.change(key, { target: { value: 'alice-key' } })
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.save' }))
+ await screen.findByText('onboarding:directoryIdentityMismatch')
+ expect(connectionState.saveProfile).not.toHaveBeenCalled()
+ expect(screen.getByRole('dialog')).toBeTruthy()
+ verify.mockResolvedValueOnce({ ...expected.connection, apiKey: 'bob-key' })
+ fireEvent.change(key, { target: { value: 'bob-key' } })
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.save' }))
+ await waitFor(() =>
+ expect(connectionState.saveProfile).toHaveBeenCalledWith({
+ ...expected,
+ connection: { ...expected.connection, apiKey: 'bob-key' },
+ }),
+ )
+ },
+)
+
+it('saves a directory selection with no data key for management without probing data access', () => {
+ const expected = selectDirectoryUser()
fireEvent.click(screen.getByRole('button', { name: 'profiles.save' }))
+ expect(connectionState.saveProfile).toHaveBeenCalledWith(expected)
+ expect(verify).not.toHaveBeenCalled()
+})
- expect(connectionState.saveProfile).toHaveBeenCalledWith(
- expect.objectContaining({
- id: expect.stringMatching(
- /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
- ),
- name: 'Local',
- }),
- )
+it.each(['edit', 'cancel'])(
+ 'ignores verification results after %s',
+ async (action) => {
+ const expected = selectDirectoryUser()
+ let resolve!: (value: unknown) => void
+ verify.mockImplementation(
+ () =>
+ new Promise((done) => {
+ resolve = done
+ }),
+ )
+ fireEvent.change(screen.getByLabelText('profiles.fields.apiKey'), {
+ target: { value: 'bob-key' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.save' }))
+ if (action === 'edit') {
+ fireEvent.change(screen.getByLabelText('profiles.name'), {
+ target: { value: 'Changed' },
+ })
+ } else {
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.cancel' }))
+ }
+ await act(async () =>
+ resolve({ ...expected.connection, apiKey: 'bob-key' }),
+ )
+ expect(connectionState.saveProfile).not.toHaveBeenCalled()
+ },
+)
+
+it('retains the draft and redacts keys when verification fails', async () => {
+ selectDirectoryUser()
+ verify.mockRejectedValue(new Error('Denied bob-key using root-key'))
+ fireEvent.change(screen.getByLabelText('profiles.fields.apiKey'), {
+ target: { value: 'bob-key' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'profiles.save' }))
+ const alert = await screen.findByRole('alert')
+ expect(alert.textContent).toContain('Denied')
+ expect(alert.textContent).not.toContain('bob-key')
+ expect(alert.textContent).not.toContain('root-key')
+ expect(connectionState.saveProfile).not.toHaveBeenCalled()
+ expect(screen.getByRole('dialog')).toBeTruthy()
})
diff --git a/web-studio/src/routes/settings/-components/connection-profiles.tsx b/web-studio/src/routes/settings/-components/connection-profiles.tsx
index e287a089b..cf294233d 100644
--- a/web-studio/src/routes/settings/-components/connection-profiles.tsx
+++ b/web-studio/src/routes/settings/-components/connection-profiles.tsx
@@ -1,7 +1,9 @@
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { ChevronDownIcon } from 'lucide-react'
-import { Button } from '#/components/ui/button'
+import { Button, buttonVariants } from '#/components/ui/button'
+import { Link } from '@tanstack/react-router'
+import { SetupIdentityDirectory } from '#/components/setup-identity-directory'
import { Badge } from '#/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '#/components/ui/card'
import {
@@ -21,7 +23,11 @@ import {
} from '#/components/ui/select'
import { Field, FieldLabel } from '#/components/ui/field'
import { useAppConnection } from '#/hooks/use-app-connection'
-import { createRandomUuid } from '#/lib/browser-crypto'
+import {
+ CLOUD_SETUP_URL,
+ StudioSetupRequestError,
+ verifyStudioSetup,
+} from '#/lib/connection/onboarding'
import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
import type { ConnectionProfile } from '#/lib/connection/profiles'
import { formatHostedIdentity } from '#/lib/connection/identity-label'
@@ -69,19 +75,78 @@ export function ConnectionProfilesList() {
} = useAppConnection()
const [draft, setDraft] = React.useState<ConnectionProfile | null>(null)
const [error, setError] = React.useState('')
+ const [directoryIdentitySelected, setDirectoryIdentitySelected] =
+ React.useState(false)
+ const [saving, setSaving] = React.useState(false)
+ const saveController = React.useRef<AbortController | null>(null)
+ const currentDraft = React.useRef(draft)
+ currentDraft.current = draft
+ React.useEffect(() => {
+ saveController.current?.abort()
+ setSaving(false)
+ return () => saveController.current?.abort()
+ }, [draft])
+ const [directoryScope, setDirectoryScope] = React.useState<string | null>(
+ null,
+ )
+ const currentDirectoryScope = draft
+ ? JSON.stringify([
+ draft.id,
+ draft.connection.serviceSelection,
+ draft.connection.baseUrl,
+ draft.connection.adminApiKey,
+ ])
+ : null
+ const hasControlKey =
+ draft?.connection.serviceSelection === 'opensource' &&
+ Boolean(draft.connection.adminApiKey.trim())
const [deleting, setDeleting] = React.useState<ConnectionProfile | null>(null)
+ const openSourceUrlRef = React.useRef('')
const openEditor = (profile: ConnectionProfile) => {
setError('')
+ setDirectoryScope(null)
+ setDirectoryIdentitySelected(false)
+ const hosted = profile.connection.serviceSelection === 'volcengine'
+ openSourceUrlRef.current = hosted ? '' : profile.connection.baseUrl
setDraft(profile)
}
- function save(event: React.FormEvent) {
+ async function save(event: React.FormEvent) {
event.preventDefault()
- if (!draft) return
+ if (!draft || saving) return
if (!isValidConnectionUrl(draft.connection.baseUrl)) {
setError(t('profiles.invalidUrl'))
return
}
const connection = normalizeProfileConnection(draft.connection)
+ if (directoryIdentitySelected && connection.apiKey.trim()) {
+ const controller = new AbortController()
+ saveController.current = controller
+ setSaving(true)
+ setError('')
+ try {
+ const verified = await verifyStudioSetup(connection, controller.signal)
+ if (controller.signal.aborted || currentDraft.current !== draft) return
+ if (
+ verified.accountId !== connection.accountId ||
+ verified.userId !== connection.userId
+ ) {
+ setError(t('onboarding:directoryIdentityMismatch'))
+ return
+ }
+ } catch (cause) {
+ if (!controller.signal.aborted && currentDraft.current === draft) {
+ setError(
+ new StudioSetupRequestError('data', cause, connection).message,
+ )
+ }
+ return
+ } finally {
+ if (saveController.current === controller) {
+ saveController.current = null
+ setSaving(false)
+ }
+ }
+ }
saveProfile({
...draft,
connection: {
@@ -159,24 +224,9 @@ export function ConnectionProfilesList() {
<Card>
<CardHeader className="flex flex-wrap items-center justify-between gap-3">
<CardTitle>{t('profiles.title')}</CardTitle>
- <Button
- onClick={() =>
- openEditor({
- id: createRandomUuid(),
- name: '',
- connection: {
- serviceSelection: 'opensource',
- baseUrl: '',
- apiKey: '',
- adminApiKey: '',
- accountId: 'default',
- userId: 'default',
- },
- })
- }
- >
+ <Link to="/config" className={buttonVariants()}>
{t('profiles.add')}
- </Button>
+ </Link>
</CardHeader>
<CardContent className="grid gap-3">
<p className="text-sm text-muted-foreground">{t('profiles.hint')}</p>
@@ -231,7 +281,7 @@ export function ConnectionProfilesList() {
if (!open) setDraft(null)
}}
>
- <DialogContent className="sm:max-w-lg">
+ <DialogContent className="max-h-[85dvh] overflow-y-auto sm:max-w-lg">
<DialogHeader className="pr-8">
<DialogTitle>
{t(
@@ -271,11 +321,20 @@ export function ConnectionProfilesList() {
]}
onValueChange={(value) => {
if (value !== 'opensource' && value !== 'volcengine') return
+ setDirectoryIdentitySelected(false)
+ if (draft.connection.serviceSelection !== 'volcengine') {
+ openSourceUrlRef.current = draft.connection.baseUrl
+ }
setDraft({
...draft,
connection: {
...draft.connection,
+ baseUrl:
+ value === 'volcengine'
+ ? CLOUD_SETUP_URL
+ : openSourceUrlRef.current,
serviceSelection: value,
+ apiKey: '',
},
})
}}
@@ -298,9 +357,13 @@ export function ConnectionProfilesList() {
</Field>
{PROFILE_FIELDS.filter(
(field) =>
- draft.connection.serviceSelection === 'opensource' ||
- field === 'baseUrl' ||
- field === 'apiKey',
+ (draft.connection.serviceSelection === 'opensource' ||
+ field === 'baseUrl' ||
+ field === 'apiKey') &&
+ !(
+ hasControlKey &&
+ (field === 'accountId' || field === 'userId')
+ ),
).map((key) => {
return (
<Field key={key} className="gap-2">
@@ -311,6 +374,10 @@ export function ConnectionProfilesList() {
id={`profile-${key}`}
className="h-10"
required={key === 'baseUrl'}
+ readOnly={
+ key === 'baseUrl' &&
+ draft.connection.serviceSelection === 'volcengine'
+ }
type={
key === 'apiKey' || key === 'adminApiKey'
? 'password'
@@ -331,6 +398,45 @@ export function ConnectionProfilesList() {
</Field>
)
})}
+ {hasControlKey && (
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setDirectoryScope(currentDirectoryScope)}
+ >
+ {t('onboarding:verify')}
+ </Button>
+ {directoryScope === currentDirectoryScope && (
+ <SetupIdentityDirectory
+ key={currentDirectoryScope}
+ connection={draft.connection}
+ disabled={false}
+ onSelect={({ accountId, userId }) => {
+ setDirectoryIdentitySelected(true)
+ setDraft((current) =>
+ current
+ ? {
+ ...current,
+ connection: {
+ ...current.connection,
+ accountId,
+ userId,
+ apiKey:
+ current.connection.accountId ===
+ accountId &&
+ current.connection.userId === userId
+ ? current.connection.apiKey
+ : '',
+ },
+ }
+ : current,
+ )
+ }}
+ />
+ )}
+ </>
+ )}
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
@@ -344,8 +450,8 @@ export function ConnectionProfilesList() {
>
{t('profiles.cancel')}
</Button>
- <Button type="submit" disabled={!draft.name.trim()}>
- {t('profiles.save')}
+ <Button type="submit" disabled={saving || !draft.name.trim()}>
+ {t(saving ? 'onboarding:verifying' : 'profiles.save')}
</Button>
</div>
</form>
diff --git a/web-studio/src/routes/settings/-components/server-configuration.test.tsx b/web-studio/src/routes/settings/-components/server-configuration.test.tsx
index 5a9615009..4827b3c2f 100644
--- a/web-studio/src/routes/settings/-components/server-configuration.test.tsx
+++ b/web-studio/src/routes/settings/-components/server-configuration.test.tsx
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
+import type { ComponentProps } from 'react'
import {
cleanup,
createEvent,
@@ -18,6 +19,13 @@ import zh from '#/i18n/locales/zh-CN/workspace'
import en from '#/i18n/locales/en/workspace'
import type { ModelConfig } from '../-lib/config-file-api'
+vi.mock('@tanstack/react-router', async (original) => ({
+ ...(await original<Record<string, unknown>>()),
+ Link: ({ to, ...props }: { to: string } & ComponentProps<'a'>) => (
+ <a href={to} {...props} />
+ ),
+}))
+
const state = vi.hoisted(() => ({
role: 'root',
provider: 'opensource',
diff --git a/web-studio/src/routes/settings/route.test.tsx b/web-studio/src/routes/settings/route.test.tsx
index 9769ed8af..72fd9a09f 100644
--- a/web-studio/src/routes/settings/route.test.tsx
+++ b/web-studio/src/routes/settings/route.test.tsx
@@ -1,15 +1,8 @@
// @vitest-environment jsdom
import type { ComponentType } from 'react'
-import {
- cleanup,
- fireEvent,
- render,
- screen,
- waitFor,
-} from '@testing-library/react'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { afterEach, expect, it, vi } from 'vitest'
-import userEvent from '@testing-library/user-event'
import { Route } from './route'
@@ -76,6 +69,9 @@ vi.mock('#/hooks/use-studio-service', () => ({
health: { refetch: vi.fn() },
}),
}))
+vi.mock('./-components/connection-profiles', () => ({
+ ConnectionProfilesList: () => <span data-testid="connection-profiles" />,
+}))
vi.mock('./-components/server-configuration', () => ({
ServerConfigurationEditor: () => <span data-testid="configuration-editor" />,
}))
@@ -86,163 +82,6 @@ afterEach(() => {
reconnect.mockClear()
})
-it('preserves the active connection when an invalid address is saved from the details panel', async () => {
- probe.mockResolvedValue({
- admin: { state: 'skipped' },
- data: { state: 'ok' },
- })
- const client = new QueryClient()
- const Settings = Route.options.component as ComponentType & {
- preload?: () => Promise<unknown>
- }
- await Settings.preload?.()
- render(
- <QueryClientProvider client={client}>
- <Settings />
- </QueryClientProvider>,
- )
- fireEvent.change(document.getElementById('settings-base-url')!, {
- target: { value: 'not-a-url' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'studio:profiles.save' }))
- expect(screen.getByRole('alert').textContent).toBe(
- 'studio:profiles.invalidUrl',
- )
- expect(saveConnection).not.toHaveBeenCalled()
- expect(reconnect).not.toHaveBeenCalled()
- fireEvent.change(document.getElementById('settings-base-url')!, {
- target: { value: 'https://proxy.example/openviking' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'studio:profiles.save' }))
- expect(screen.queryByRole('alert')).toBeNull()
- expect(saveConnection).toHaveBeenCalledWith(
- expect.objectContaining({ baseUrl: 'https://proxy.example/openviking' }),
- )
- expect(reconnect).toHaveBeenCalledTimes(1)
- client.clear()
-})
-
-it('uses the hosted default address when the Base UI service selector changes', async () => {
- const user = userEvent.setup()
- const client = new QueryClient()
- const Settings = Route.options.component as ComponentType
- render(
- <QueryClientProvider client={client}>
- <Settings />
- </QueryClientProvider>,
- )
- const serviceType = screen.getByRole('combobox', {
- name: 'studio:serviceType',
- })
- const url = screen.getByLabelText<HTMLInputElement>('fields.baseUrl')
- fireEvent.change(url, { target: { value: 'https://open-source.example/ov' } })
- await user.click(serviceType)
- await user.click(
- screen.getByRole('option', { name: 'studio:providers.volcengine' }),
- )
- expect(url.value).toBe(
- 'https://api.vikingdb.cn-beijing.volces.com/openviking',
- )
- expect(url.readOnly).toBe(true)
- fireEvent.click(screen.getByRole('button', { name: 'studio:profiles.save' }))
- expect(saveConnection).toHaveBeenCalledWith(
- expect.objectContaining({
- serviceSelection: 'volcengine',
- baseUrl: 'https://api.vikingdb.cn-beijing.volces.com/openviking',
- }),
- )
- client.clear()
-})
-
-it('shows only the server-resolved identity next to the data key', async () => {
- probe.mockResolvedValue({
- admin: { state: 'skipped' },
- data: { state: 'ok' },
- })
- const client = new QueryClient()
- const Settings = Route.options.component as ComponentType & {
- preload?: () => Promise<unknown>
- }
- await Settings.preload?.()
- const content = () => (
- <QueryClientProvider client={client}>
- <Settings />
- </QueryClientProvider>
- )
- const view = render(content())
- expect(
- await screen.findByText('[studio:profiles.identityPending]'),
- ).toBeTruthy()
- expect(screen.queryByText('[account-a/alice]')).toBeNull()
- healthState.value = { account_id: 'server-account', user_id: 'server-user' }
- view.rerender(content())
- expect(await screen.findByText('[server-account/server-user]')).toBeTruthy()
- fireEvent.change(document.getElementById('settings-user-api-key')!, {
- target: { value: 'unverified-key' },
- })
- expect(screen.getByText('[studio:profiles.identityPending]')).toBeTruthy()
- client.clear()
-})
-
-it.each([false, undefined, true])(
- 'requires the Root key in trusted mode regardless of legacy metadata: %s',
- async (required) => {
- probe.mockResolvedValue({
- admin: {
- state: 'error',
- statusCode: 403,
- detail: 'Management unavailable',
- },
- data: { state: 'ok', detailCode: 'tenantDataAvailable' },
- rootApiKeyRequired: required,
- })
- const client = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- })
- const Settings = Route.options.component as ComponentType & {
- preload?: () => Promise<unknown>
- }
- await Settings.preload?.()
- render(
- <QueryClientProvider client={client}>
- <Settings />
- </QueryClientProvider>,
- )
- await waitFor(
- () => expect(screen.getByText('Management unavailable')).toBeTruthy(),
- { timeout: 5000 },
- )
- expect(
- Boolean(screen.queryByText('connection.keyGuide.trusted.title')),
- ).toBe(true)
- client.clear()
- },
-)
-
-it('keeps management credentials editable after authentication fails and retries the connection owner', async () => {
- serviceState.provider = 'unknown'
- config.url = 'https://custom.example'
- config.selection = 'opensource'
- probe.mockResolvedValue({
- admin: { state: 'skipped' },
- data: { state: 'skipped' },
- })
- const client = new QueryClient()
- const Settings = Route.options.component as ComponentType
- render(
- <QueryClientProvider client={client}>
- <Settings />
- </QueryClientProvider>,
- )
- expect(document.getElementById('settings-root-api-key')).toBeTruthy()
- fireEvent.click(screen.getByRole('button', { name: 'studio:retry' }))
- expect(reconnect).toHaveBeenCalledTimes(1)
- client.clear()
- serviceState.provider = 'opensource'
- config.url = 'http://localhost:1933'
- config.selection = 'auto'
-})
-
it('unmounts the configuration editor and resets the active tab when switching to a hosted connection', async () => {
Object.assign(serviceState, {
provider: 'opensource',
@@ -252,7 +91,10 @@ it('unmounts the configuration editor and resets the active tab when switching t
})
probe.mockResolvedValue({ admin: { state: 'ok' }, data: { state: 'ok' } })
const client = new QueryClient()
- const Settings = Route.options.component as ComponentType
+ const Settings = Route.options.component as ComponentType & {
+ preload?: () => Promise<unknown>
+ }
+ await Settings.preload?.()
const content = () => (
<QueryClientProvider client={client}>
<Settings />
@@ -273,42 +115,3 @@ it('unmounts the configuration editor and resets the active tab when switching t
client.clear()
Object.assign(serviceState, { provider: 'opensource', role: 'user', key: '' })
})
-
-it('preserves an edited URL and user key while health fills in identity', async () => {
- const originalIdentity = {
- accountId: connectionState.accountId,
- userId: connectionState.userId,
- }
- const client = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- })
- const Settings = Route.options.component as ComponentType
- const content = () => (
- <QueryClientProvider client={client}>
- <Settings />
- </QueryClientProvider>
- )
- const view = render(content())
- const url = screen.getByLabelText<HTMLInputElement>('fields.baseUrl')
- const key = document.getElementById(
- 'settings-user-api-key',
- ) as HTMLInputElement
- fireEvent.change(url, { target: { value: 'http://recovery.test' } })
- fireEvent.change(key, { target: { value: 'synthetic-draft' } })
- connectionState.accountId = 'resolved-account'
- connectionState.userId = 'resolved-user'
- view.rerender(content())
- expect(url.value).toBe('http://recovery.test')
- expect(key.value).toBe('synthetic-draft')
- fireEvent.click(screen.getByRole('button', { name: 'studio:profiles.save' }))
- expect(saveConnection).toHaveBeenCalledWith(
- expect.objectContaining({
- baseUrl: 'http://recovery.test',
- apiKey: 'synthetic-draft',
- accountId: 'resolved-account',
- userId: 'resolved-user',
- }),
- )
- Object.assign(connectionState, originalIdentity)
- client.clear()
-})
diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsx
index 2ba7d2f3a..4cf7f0761 100644
--- a/web-studio/src/routes/settings/route.tsx
+++ b/web-studio/src/routes/settings/route.tsx
@@ -1,20 +1,9 @@
import { fetchServerHealth } from '#/lib/connection/health'
import * as React from 'react'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import {
- CircleAlertIcon,
- CircleDashedIcon,
- CircleHelpIcon,
- ExternalLinkIcon,
- KeyRoundIcon,
- ShieldCheckIcon,
- TriangleAlertIcon,
-} from 'lucide-react'
import { useTranslation } from 'react-i18next'
-import { Alert, AlertDescription, AlertTitle } from '#/components/ui/alert'
import { Button } from '#/components/ui/button'
-import { Badge } from '#/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '#/components/ui/card'
import {
Field,
@@ -23,25 +12,10 @@ import {
FieldLabel,
} from '#/components/ui/field'
import { Input } from '#/components/ui/input'
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '#/components/ui/select'
import { canEditStudioConfiguration } from '#/lib/studio-permissions'
-import { resolveConfiguredServiceProvider } from '#/lib/studio-service'
-import { isValidConnectionUrl } from '#/lib/connection/profiles'
-import { CLOUD_SETUP_URL } from '#/lib/connection/onboarding'
import { useStudioService } from '#/hooks/use-studio-service'
import { useAppConnection } from '#/hooks/use-app-connection'
-import { useConnectionProbe } from '#/hooks/use-connection-probe'
-import type { CapabilityProbeResult } from '#/lib/admin'
import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
-import { cn } from '#/lib/utils'
-import { localizeCapabilityDetail } from './-lib/localize-capability-probe'
-import type { ConnectionDraft } from '#/hooks/use-app-connection'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '#/components/ui/tabs'
import { ConnectionProfilesList } from './-components/connection-profiles'
import { ServerConfigurationEditor } from './-components/server-configuration'
@@ -55,7 +29,6 @@ function ConnectionSettingsRoute() {
const {
identityScopeKey,
isGatewayHost,
- activeProfileId,
connection,
connectionRole,
isConnectionRoleLoading,
@@ -93,10 +66,7 @@ function ConnectionSettingsRoute() {
) : null}
</TabsList>
<TabsContent value="connection">
- <div className="grid gap-5">
- <ConnectionProfilesList />
- <ConnectionSettingsPanel key={activeProfileId} />
- </div>
+ <ConnectionProfilesList />
</TabsContent>
{canConfigure ? (
<TabsContent value="configuration" keepMounted>
@@ -229,495 +199,3 @@ export function GatewayConnectionSettings() {
</Card>
)
}
-
-function getCapabilityIcon(result: CapabilityProbeResult | undefined) {
- if (!result) {
- return <CircleDashedIcon className="size-4" />
- }
- if (result.state === 'ok') {
- return <ShieldCheckIcon className="size-4" />
- }
- if (result.state === 'error') {
- return <CircleAlertIcon className="size-4" />
- }
- return <CircleDashedIcon className="size-4" />
-}
-
-function CapabilityStatus({
- isLoading,
- label,
- result,
-}: {
- isLoading: boolean
- label: string
- result: CapabilityProbeResult | undefined
-}) {
- const { t } = useTranslation('settings')
- const state = isLoading ? 'checking' : result?.state || 'skipped'
- const detail = localizeCapabilityDetail(result, t)
-
- return (
- <div
- className={cn(
- 'flex min-w-0 items-start gap-2 rounded-md border bg-background/70 px-3 py-2 text-sm',
- state === 'ok' && 'border-emerald-500/35 text-emerald-700',
- state === 'error' && 'border-destructive/35 text-destructive',
- )}
- >
- <div className={cn('mt-0.5', isLoading && 'animate-spin')}>
- {getCapabilityIcon(result)}
- </div>
- <div className="min-w-0">
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
- <span className="font-medium">{label}</span>
- <span className="text-xs text-muted-foreground">
- {t(`health.state.${state}`)}
- </span>
- </div>
- {detail ? (
- <p className="mt-1 truncate text-xs text-muted-foreground">
- {detail}
- </p>
- ) : null}
- </div>
- </div>
- )
-}
-
-function UserApiKeyInput({
- identity,
- id,
- onChange,
- placeholder,
- value,
-}: {
- identity: string
- id: string
- onChange: (value: string) => void
- placeholder: string
- value: string
-}) {
- return (
- <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>
- <input
- id={id}
- type="password"
- value={value}
- 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"
- {...PLAIN_INPUT_PROPS}
- />
- </div>
- )
-}
-
-function ConnectionSettingsPanel() {
- const { i18n, t } = useTranslation(['settings', 'studio'])
- const service = useStudioService()
- const { connection, reconnect, saveConnection, serverMode, serverHealth } =
- useAppConnection()
- const [draft, setDraft] = React.useState<ConnectionDraft>(connection)
- const previousConnectionRef = React.useRef({ ...connection })
- const openSourceUrlRef = React.useRef(
- resolveConfiguredServiceProvider(
- connection.baseUrl,
- connection.serviceSelection,
- ) === 'opensource'
- ? connection.baseUrl
- : '',
- )
- const [saveError, setSaveError] = React.useState(false)
- const canEditControlCredential =
- resolveConfiguredServiceProvider(draft.baseUrl, draft.serviceSelection) ===
- 'opensource'
- React.useEffect(() => {
- const previous = previousConnectionRef.current
- previousConnectionRef.current = { ...connection }
- if (
- previous.baseUrl !== connection.baseUrl ||
- previous.serviceSelection !== connection.serviceSelection ||
- previous.apiKey !== connection.apiKey ||
- previous.adminApiKey !== connection.adminApiKey
- ) {
- if (
- resolveConfiguredServiceProvider(
- connection.baseUrl,
- connection.serviceSelection,
- ) === 'opensource'
- ) {
- openSourceUrlRef.current = connection.baseUrl
- }
- setDraft(connection)
- setSaveError(false)
- } else if (
- previous.accountId !== connection.accountId ||
- previous.userId !== connection.userId
- ) {
- // Health may fill in identity while the user edits a recovery address/key.
- // Update untouched identity fields without replacing the in-progress form.
- setDraft((current) => ({
- ...current,
- accountId:
- current.accountId === previous.accountId
- ? connection.accountId
- : current.accountId,
- userId:
- current.userId === previous.userId
- ? connection.userId
- : current.userId,
- }))
- }
- }, [connection])
-
- function updateDraft(next: Partial<ConnectionDraft>): void {
- setSaveError(false)
- setDraft((current) => ({ ...current, ...next }))
- }
-
- function selectServiceType(selection: 'opensource' | 'volcengine'): void {
- if (
- resolveConfiguredServiceProvider(
- draft.baseUrl,
- draft.serviceSelection,
- ) === 'opensource' &&
- selection === 'volcengine'
- ) {
- openSourceUrlRef.current = draft.baseUrl
- }
- updateDraft({
- serviceSelection: selection,
- baseUrl:
- selection === 'volcengine' ? CLOUD_SETUP_URL : openSourceUrlRef.current,
- })
- }
-
- const resolvedIdentity =
- draft.baseUrl === connection.baseUrl &&
- draft.apiKey === connection.apiKey &&
- draft.serviceSelection === connection.serviceSelection &&
- (draft.apiKey || draft.adminApiKey === connection.adminApiKey) &&
- typeof serverHealth?.account_id === 'string' &&
- serverHealth.account_id &&
- typeof serverHealth.user_id === 'string' &&
- serverHealth.user_id
- ? `${serverHealth.account_id}/${serverHealth.user_id}`
- : t('studio:profiles.identityPending')
-
- const probeQuery = useConnectionProbe()
- const isDevMode = serverMode === 'dev'
- const isUnsupportedAuthMode = serverMode === 'oidc' || serverMode === 'ldap'
- const rootApiKey = connection.adminApiKey.trim()
- const hasControlCredential =
- service.provider === 'opensource' && Boolean(draft.adminApiKey.trim())
- const hasDataCredential = Boolean(draft.apiKey.trim())
- const adminProbe = probeQuery.data?.admin
- const dataProbe = probeQuery.data?.data
- const hasAdminAccess = !isDevMode && adminProbe?.state === 'ok'
- 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
- const keyGuide =
- service.provider !== 'opensource'
- ? null
- : 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'),
- }
- : null
-
- return (
- <div className="flex w-full min-w-0 flex-col gap-5">
- <Card className="gap-0 overflow-hidden border-primary/25 bg-primary/[0.025] py-0 shadow-sm ring-1 ring-primary/10">
- <CardHeader className="gap-2 border-b border-primary/15 bg-primary/[0.07] px-5 py-3.5">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div className="flex min-w-0 items-center gap-2">
- <div className="flex size-7 items-center justify-center rounded-md bg-primary text-primary-foreground">
- <KeyRoundIcon className="size-4" />
- </div>
- <CardTitle>{t('connection.title')}</CardTitle>
- </div>
- <Badge variant="outline" className="shrink-0 font-normal">
- {t(`serverMode.${serverMode}`)}
- </Badge>
- </div>
- </CardHeader>
- <CardContent className="grid gap-4 px-5 py-4">
- <Field>
- <FieldLabel htmlFor="settings-service-type">
- {t('studio:serviceType')}
- </FieldLabel>
- <FieldContent>
- <Select
- value={
- draft.serviceSelection === 'auto'
- ? resolveConfiguredServiceProvider(draft.baseUrl)
- : draft.serviceSelection
- }
- items={[
- {
- value: 'opensource',
- label: t('studio:providers.opensource'),
- },
- {
- value: 'volcengine',
- label: t('studio:providers.volcengine'),
- },
- ]}
- onValueChange={(value) =>
- selectServiceType(value as 'opensource' | 'volcengine')
- }
- >
- <SelectTrigger
- id="settings-service-type"
- className="w-full bg-background"
- >
- <SelectValue />
- </SelectTrigger>
- <SelectContent
- align="start"
- className="w-[var(--anchor-width)]"
- >
- <SelectItem value="opensource">
- {t('studio:providers.opensource')}
- </SelectItem>
- <SelectItem value="volcengine">
- {t('studio:providers.volcengine')}
- </SelectItem>
- </SelectContent>
- </Select>
- <FieldDescription>
- {t('studio:profiles.typeHint')}
- </FieldDescription>
- <Button
- type="button"
- variant="outline"
- disabled={service.isChecking}
- onClick={reconnect}
- >
- {t('studio:retry')}
- </Button>
- <p className="text-sm" aria-live="polite">
- {t(
- `studio:providers.${service.isChecking ? 'checking' : service.provider}`,
- )}{' '}
- {service.version}
- </p>
- <FieldDescription>
- {t(`studio:connectionSummary.${service.provider}`)}
- </FieldDescription>
- </FieldContent>
- </Field>
- <Field>
- <FieldLabel htmlFor="settings-base-url">
- {t('fields.baseUrl')}
- </FieldLabel>
- <FieldContent>
- <Input
- id="settings-base-url"
- value={draft.baseUrl}
- onChange={(event) =>
- updateDraft({ baseUrl: event.target.value })
- }
- readOnly={
- resolveConfiguredServiceProvider(
- draft.baseUrl,
- draft.serviceSelection,
- ) === 'volcengine'
- }
- placeholder={t('placeholders.baseUrl')}
- inputMode="url"
- {...PLAIN_INPUT_PROPS}
- />
- </FieldContent>
- </Field>
-
- {isDevMode ? (
- <p className="rounded-md border border-dashed bg-muted/30 px-3 py-2 text-sm text-muted-foreground">
- {t('connection.devMode')}
- </p>
- ) : isUnsupportedAuthMode ? (
- <Alert variant="destructive" className="border-destructive/50">
- <TriangleAlertIcon className="size-5" />
- <AlertTitle>
- {t('connection.unsupportedAuthMode.title')}
- </AlertTitle>
- <AlertDescription className="grid gap-2">
- <p>
- {t('connection.unsupportedAuthMode.primary', {
- mode: serverMode,
- })}
- </p>
- <p>
- {t('connection.unsupportedAuthMode.description', {
- mode: serverMode,
- ov: 'ov',
- })}
- </p>
- <a
- href={authenticationGuideUrl}
- target="_blank"
- rel="noreferrer"
- className="mt-1 inline-flex w-fit items-center gap-1 font-medium text-foreground underline underline-offset-2"
- >
- {t('connection.keyGuide.learnMore')}
- <ExternalLinkIcon className="size-3.5" />
- </a>
- </AlertDescription>
- </Alert>
- ) : (
- <>
- <div className="grid gap-4 md:grid-cols-2">
- {canEditControlCredential ? (
- <Field>
- <FieldLabel htmlFor="settings-root-api-key">
- {t('fields.rootApiKey')}
- </FieldLabel>
- <FieldContent>
- <Input
- id="settings-root-api-key"
- type="password"
- value={draft.adminApiKey}
- onChange={(event) =>
- updateDraft({ adminApiKey: event.target.value })
- }
- placeholder={t('placeholders.adminApiKey')}
- {...PLAIN_INPUT_PROPS}
- />
- <FieldDescription>
- {t(
- serverMode === 'trusted'
- ? 'connection.trustedRootHint'
- : 'connection.rootHint',
- )}
- </FieldDescription>
- </FieldContent>
- </Field>
- ) : null}
- <Field>
- <FieldLabel htmlFor="settings-user-api-key">
- {t('fields.userApiKey')}
- </FieldLabel>
- <FieldContent>
- <UserApiKeyInput
- identity={resolvedIdentity}
- id="settings-user-api-key"
- value={draft.apiKey}
- onChange={(apiKey) => updateDraft({ apiKey })}
- placeholder={t('placeholders.userApiKey')}
- />
- <FieldDescription>
- {t(
- serverMode === 'trusted'
- ? 'connection.trustedUserHint'
- : 'connection.userHint',
- )}
- </FieldDescription>
- </FieldContent>
- </Field>
- </div>
-
- <div className="grid gap-2 md:grid-cols-2">
- {service.provider === 'opensource' ? (
- <CapabilityStatus
- isLoading={probeQuery.isFetching}
- label={t('health.admin')}
- result={adminProbe}
- />
- ) : null}
- <CapabilityStatus
- isLoading={probeQuery.isFetching}
- label={t('health.data')}
- result={dataProbe}
- />
- </div>
-
- {service.provider === 'volcengine' ? (
- <p className="text-sm text-muted-foreground">
- {t('studio:cloudManagement')}
- </p>
- ) : null}
- {(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 || '',
- })}
- </p>
- ) : null}
- </>
- )}
- {saveError && (
- <p role="alert" className="text-sm text-destructive">
- {t('studio:profiles.invalidUrl')}
- </p>
- )}
- <div className="flex justify-end">
- <Button
- onClick={() => {
- if (!isValidConnectionUrl(draft.baseUrl)) {
- setSaveError(true)
- return
- }
- saveConnection(draft)
- reconnect()
- }}
- disabled={JSON.stringify(draft) === JSON.stringify(connection)}
- >
- {t('studio:profiles.save')}
- </Button>
- </div>
- </CardContent>
- </Card>
- </div>
- )
-}