Skip to content

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

feat(web-studio): select account/user in OAuth consent when permitted (#2528)

t0sakia4f43c97702d
diff --git a/web-studio/src/components/identity-picker.tsx b/web-studio/src/components/identity-picker.tsx
index ddda480be..8673f6659 100644
--- a/web-studio/src/components/identity-picker.tsx
+++ b/web-studio/src/components/identity-picker.tsx
@@ -1,13 +1,34 @@
-import * as React from 'react'
import { useTranslation } from 'react-i18next'
+import { AccountSelect, UserSelect } from '#/components/identity-select'
import { Field, FieldContent, FieldLabel } from '#/components/ui/field'
import { Input } from '#/components/ui/input'
import { RadioGroup, RadioGroupItem } from '#/components/ui/radio-group'
+import type { AdminAccount, AdminUser } from '#/lib/admin'
export type IdentityPickerValue =
| { mode: 'current' }
| { mode: 'custom'; apiKey: string }
+ | { mode: 'select'; accountId: string; userId: string; apiKey: string }
+
+/**
+ * Account/user directory used by the optional "select a specific identity"
+ * mode. Presentational: the parent (via {@link useIdentityDirectory}) owns the
+ * selected account/user state and the underlying admin queries; the picker only
+ * renders the dropdowns and forwards selection changes.
+ */
+export type IdentityDirectory = {
+ available: boolean
+ isRoot: boolean
+ accounts: AdminAccount[]
+ users: AdminUser[]
+ selectedAccountId: string
+ selectedUserId: string
+ onSelectAccount: (accountId: string) => void
+ onSelectUser: (userId: string) => void
+ accountsLoading: boolean
+ usersLoading: boolean
+}
type IdentityPickerProps = {
value: IdentityPickerValue
@@ -16,12 +37,15 @@ type IdentityPickerProps = {
currentIdentityLabel: string
customKeyId?: string
disabled?: boolean
+ directory?: IdentityDirectory
}
export function resolveEffectiveApiKey(
value: IdentityPickerValue,
currentApiKey: string,
): string {
+ // 'custom' and 'select' both carry a concrete key; 'current' resolves to the
+ // Studio session key.
return value.mode === 'current' ? currentApiKey : value.apiKey
}
@@ -32,15 +56,11 @@ export function IdentityPicker({
currentIdentityLabel,
customKeyId = 'identity-picker-custom-key',
disabled = false,
+ directory,
}: IdentityPickerProps) {
const { t } = useTranslation(['oauth', 'common'])
const hasCurrentKey = Boolean(currentApiKey)
-
- React.useEffect(() => {
- if (!hasCurrentKey && value.mode === 'current') {
- onChange({ mode: 'custom', apiKey: '' })
- }
- }, [hasCurrentKey, value, onChange])
+ const canSelect = Boolean(directory?.available)
return (
<RadioGroup
@@ -48,6 +68,13 @@ export function IdentityPicker({
onValueChange={(next) => {
if (next === 'current') {
onChange({ mode: 'current' })
+ } else if (next === 'select') {
+ onChange({
+ mode: 'select',
+ accountId: directory?.selectedAccountId ?? '',
+ userId: directory?.selectedUserId ?? '',
+ apiKey: value.mode === 'select' ? value.apiKey : '',
+ })
} else {
onChange({
mode: 'custom',
@@ -75,6 +102,65 @@ export function IdentityPicker({
</div>
</label>
+ {canSelect && directory ? (
+ <label className="flex items-start gap-3 cursor-pointer">
+ <RadioGroupItem
+ value="select"
+ disabled={disabled}
+ className="mt-0.5"
+ />
+ <div className="flex flex-1 flex-col gap-2">
+ <span className="text-sm font-medium leading-none">
+ {t('identityPicker.useSelect', { ns: 'oauth' })}
+ </span>
+ {value.mode === 'select' ? (
+ <div className="flex flex-col gap-2">
+ <div className="grid gap-1">
+ <span className="text-xs font-medium text-muted-foreground">
+ {t('identityPicker.selectAccountLabel', { ns: 'oauth' })}
+ </span>
+ <AccountSelect
+ accounts={directory.accounts}
+ value={directory.selectedAccountId}
+ label={t('identityPicker.selectAccountLabel', {
+ ns: 'oauth',
+ })}
+ disabled={
+ disabled || !directory.isRoot || directory.accountsLoading
+ }
+ onChange={directory.onSelectAccount}
+ />
+ </div>
+ <div className="grid gap-1">
+ <span className="text-xs font-medium text-muted-foreground">
+ {t('identityPicker.selectUserLabel', { ns: 'oauth' })}
+ </span>
+ <UserSelect
+ users={directory.users}
+ value={directory.selectedUserId}
+ label={t('identityPicker.selectUserLabel', { ns: 'oauth' })}
+ disabled={disabled || directory.usersLoading}
+ onChange={directory.onSelectUser}
+ />
+ </div>
+ {!directory.isRoot ? (
+ <span className="text-xs text-muted-foreground">
+ {t('identityPicker.selectAccountAdminHint', {
+ ns: 'oauth',
+ })}
+ </span>
+ ) : null}
+ {!value.apiKey && !directory.usersLoading ? (
+ <span className="text-xs text-destructive">
+ {t('identityPicker.selectNoKey', { ns: 'oauth' })}
+ </span>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ </label>
+ ) : null}
+
<label className="flex items-start gap-3 cursor-pointer">
<RadioGroupItem value="custom" disabled={disabled} className="mt-0.5" />
<div className="flex flex-1 flex-col gap-2">
diff --git a/web-studio/src/components/identity-select.tsx b/web-studio/src/components/identity-select.tsx
new file mode 100644
index 000000000..65517ec1d
--- /dev/null
+++ b/web-studio/src/components/identity-select.tsx
@@ -0,0 +1,104 @@
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '#/components/ui/select'
+import {
+ DEFAULT_ACCOUNT_ID,
+ DEFAULT_USER_ID,
+ sortedAccountIds,
+ uniqueOptions,
+} from '#/lib/admin-options'
+import type { AdminAccount, AdminUser } from '#/lib/admin'
+
+export function AccountSelect({
+ accounts,
+ disabled,
+ label,
+ onChange,
+ value,
+}: {
+ accounts: readonly AdminAccount[]
+ disabled?: boolean
+ label: string
+ onChange: (value: string) => void
+ value: string
+}) {
+ const options = sortedAccountIds(
+ accounts.map((account) => account.accountId),
+ value || DEFAULT_ACCOUNT_ID,
+ )
+
+ return (
+ <Select
+ value={value || DEFAULT_ACCOUNT_ID}
+ onValueChange={(next) => {
+ if (next) {
+ onChange(next)
+ }
+ }}
+ >
+ <SelectTrigger
+ aria-label={label}
+ className="h-9 w-full"
+ disabled={disabled}
+ >
+ <SelectValue>{value || DEFAULT_ACCOUNT_ID}</SelectValue>
+ </SelectTrigger>
+ <SelectContent alignItemWithTrigger>
+ {options.map((item) => (
+ <SelectItem key={item} value={item}>
+ {item}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )
+}
+
+export function UserSelect({
+ disabled,
+ label,
+ onChange,
+ users,
+ value,
+}: {
+ disabled?: boolean
+ label: string
+ onChange: (value: string) => void
+ users: readonly AdminUser[]
+ value: string
+}) {
+ const options = uniqueOptions(
+ users.map((user) => user.userId),
+ value || DEFAULT_USER_ID,
+ )
+
+ return (
+ <Select
+ value={value || DEFAULT_USER_ID}
+ onValueChange={(next) => {
+ if (next) {
+ onChange(next)
+ }
+ }}
+ >
+ <SelectTrigger
+ aria-label={label}
+ className="h-9 w-full"
+ disabled={disabled}
+ >
+ <SelectValue>{value || DEFAULT_USER_ID}</SelectValue>
+ </SelectTrigger>
+ <SelectContent alignItemWithTrigger>
+ {options.map((item) => (
+ <SelectItem key={item} value={item}>
+ {item}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )
+}
diff --git a/web-studio/src/hooks/use-identity-directory.ts b/web-studio/src/hooks/use-identity-directory.ts
new file mode 100644
index 000000000..a37205a4c
--- /dev/null
+++ b/web-studio/src/hooks/use-identity-directory.ts
@@ -0,0 +1,141 @@
+import * as React from 'react'
+import { useQuery } from '@tanstack/react-query'
+
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { fetchAdminAccounts, fetchAdminUsers } from '#/lib/admin'
+import { DEFAULT_ACCOUNT_ID, DEFAULT_USER_ID } from '#/lib/admin-options'
+import type { AdminAccount, AdminConnection, AdminUser } from '#/lib/admin'
+import type { IdentityDirectory } from '#/components/identity-picker'
+
+export type UseIdentityDirectory = IdentityDirectory & {
+ resolveUserKey: (accountId: string, userId: string) => string | undefined
+}
+
+/**
+ * Builds the account/user directory backing the OAuth consent "select a
+ * specific identity" mode, mirroring the Studio Connection & Identity page.
+ *
+ * Availability is gated on `api_key` server mode (trusted/dev modes never
+ * expose per-user keys, and the backend rejects those identities for OAuth)
+ * plus a root/admin caller. ROOT lists every account; an account-admin gets a
+ * 403 on `GET /admin/accounts` and is therefore pinned to their own account.
+ */
+export function useIdentityDirectory(): UseIdentityDirectory {
+ const { connection, connectionRole, isConnectionRoleLoading, serverMode } =
+ useAppConnection()
+
+ const controlApiKey =
+ connection.adminApiKey.trim() || connection.apiKey.trim()
+ const baseAccountId = connection.accountId || DEFAULT_ACCOUNT_ID
+ const baseUserId = connection.userId || DEFAULT_USER_ID
+
+ const available =
+ serverMode === 'api_key' &&
+ !isConnectionRoleLoading &&
+ (connectionRole === 'root' || connectionRole === 'admin') &&
+ Boolean(controlApiKey)
+
+ const adminConnection = React.useMemo<AdminConnection>(
+ () => ({
+ accountId: baseAccountId,
+ apiKey: controlApiKey,
+ baseUrl: connection.baseUrl,
+ userId: baseUserId,
+ }),
+ [baseAccountId, baseUserId, controlApiKey, connection.baseUrl],
+ )
+
+ // ROOT can enumerate every account; account-admins get 403 here. Query keys
+ // mirror the settings page so navigating between the two reuses cache.
+ const accountsQuery = useQuery({
+ enabled: available,
+ queryFn: () => fetchAdminAccounts(adminConnection),
+ queryKey: [
+ 'admin-accounts',
+ adminConnection.baseUrl,
+ adminConnection.apiKey,
+ adminConnection.accountId,
+ adminConnection.userId,
+ ],
+ retry: false,
+ })
+
+ const isRoot = accountsQuery.isSuccess
+ const accounts: AdminAccount[] = accountsQuery.data ?? [
+ { accountId: baseAccountId, userCount: 0 },
+ ]
+
+ const [selectedAccountId, setSelectedAccountId] =
+ React.useState(baseAccountId)
+ const [selectedUserId, setSelectedUserId] = React.useState(baseUserId)
+
+ // Account-admins cannot switch accounts: keep selection pinned to their own.
+ const effectiveAccountId = isRoot ? selectedAccountId : baseAccountId
+
+ const usersQuery = useQuery({
+ enabled: available && Boolean(effectiveAccountId),
+ queryFn: () => fetchAdminUsers(adminConnection, effectiveAccountId),
+ queryKey: [
+ 'admin-users',
+ adminConnection.baseUrl,
+ adminConnection.apiKey,
+ adminConnection.accountId,
+ adminConnection.userId,
+ effectiveAccountId,
+ ],
+ retry: false,
+ })
+
+ const users: AdminUser[] = usersQuery.data ?? []
+
+ // Once the user list for the selected account arrives, ensure the selected
+ // user is valid; otherwise fall back to a sensible default.
+ React.useEffect(() => {
+ if (!users.length) {
+ return
+ }
+ const ids = users.map((user) => user.userId)
+ if (ids.includes(selectedUserId)) {
+ return
+ }
+ const preferred = ids.includes(baseUserId)
+ ? baseUserId
+ : ids.includes(DEFAULT_USER_ID)
+ ? DEFAULT_USER_ID
+ : ids[0]
+ setSelectedUserId(preferred)
+ }, [users, selectedUserId, baseUserId])
+
+ const onSelectAccount = React.useCallback((accountId: string) => {
+ setSelectedAccountId(accountId)
+ // Reset to default; the reconciliation effect picks a valid user once the
+ // new account's user list loads.
+ setSelectedUserId(DEFAULT_USER_ID)
+ }, [])
+
+ const onSelectUser = React.useCallback((userId: string) => {
+ setSelectedUserId(userId)
+ }, [])
+
+ const resolveUserKey = React.useCallback(
+ (accountId: string, userId: string) =>
+ users.find(
+ (user) => user.accountId === accountId && user.userId === userId,
+ )?.apiKey,
+ [users],
+ )
+
+ return {
+ available,
+ isRoot,
+ accounts,
+ users,
+ selectedAccountId: effectiveAccountId,
+ selectedUserId,
+ onSelectAccount,
+ onSelectUser,
+ accountsLoading: accountsQuery.isLoading,
+ usersLoading: usersQuery.isLoading,
+ resolveUserKey,
+ }
+}
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index 62a0942e7..c4123ea6a 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -603,6 +603,13 @@ const en = {
useCurrent: 'Authorize as the current identity',
noCurrent:
'No identity set. Open Connection & Identity to sign in first, or use a different API key below.',
+ useSelect: 'Authorize a specific account / user',
+ selectAccountLabel: 'Account',
+ selectUserLabel: 'User',
+ selectNoKey:
+ 'This user has no API key. Pick another user or regenerate a key in Connection & Identity.',
+ selectAccountAdminHint:
+ 'You can authorize users in your own account only.',
useCustom: 'Use a different API key',
customKeyLabel: 'API key',
customKeyPlaceholder: 'Paste an API key (not persisted)',
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index 6e1db02f3..2d4bca519 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -592,6 +592,12 @@ const zhCN = {
useCurrent: '以当前身份授权',
noCurrent:
'尚未配置身份。请先在“连接与身份”中登录,或在下方临时粘贴一个 API key。',
+ useSelect: '授权指定的账号 / 用户',
+ selectAccountLabel: '账号',
+ selectUserLabel: '用户',
+ selectNoKey:
+ '该用户没有 API key,请选择其他用户,或在“连接与身份”中重新生成。',
+ selectAccountAdminHint: '你只能为本账号下的用户授权。',
useCustom: '使用其他 API key',
customKeyLabel: 'API key',
customKeyPlaceholder: '粘贴一个 API key(不会持久化)',
diff --git a/web-studio/src/lib/admin-options.ts b/web-studio/src/lib/admin-options.ts
new file mode 100644
index 000000000..4bb666978
--- /dev/null
+++ b/web-studio/src/lib/admin-options.ts
@@ -0,0 +1,50 @@
+import type { AdminAccount } from '#/lib/admin'
+
+export const DEFAULT_ACCOUNT_ID = 'default'
+export const DEFAULT_USER_ID = 'default'
+
+export function uniqueOptions(
+ values: readonly string[],
+ fallback: string,
+): string[] {
+ const seen = new Set<string>()
+ const result: string[] = []
+
+ for (const rawValue of [fallback, ...values]) {
+ const value = rawValue.trim()
+ if (!value || seen.has(value)) {
+ continue
+ }
+ seen.add(value)
+ result.push(value)
+ }
+
+ return result
+}
+
+export function compareAccountId(left: string, right: string): number {
+ const normalizedLeft = left.toLowerCase()
+ const normalizedRight = right.toLowerCase()
+ if (normalizedLeft < normalizedRight) {
+ return -1
+ }
+ if (normalizedLeft > normalizedRight) {
+ return 1
+ }
+ return left < right ? -1 : left > right ? 1 : 0
+}
+
+export function sortedAccountIds(
+ values: readonly string[],
+ fallback: string,
+): string[] {
+ return uniqueOptions([...values, fallback], '').sort(compareAccountId)
+}
+
+export function sortedAccounts(
+ accounts: readonly AdminAccount[],
+): AdminAccount[] {
+ return [...accounts].sort((left, right) =>
+ compareAccountId(left.accountId, right.accountId),
+ )
+}
diff --git a/web-studio/src/routes/settings/-lib/admin.ts b/web-studio/src/lib/admin.ts
similarity index 100%
rename from web-studio/src/routes/settings/-lib/admin.ts
rename to web-studio/src/lib/admin.ts
diff --git a/web-studio/src/routes/oauth/consent.tsx b/web-studio/src/routes/oauth/consent.tsx
index b52d3c305..01016274d 100644
--- a/web-studio/src/routes/oauth/consent.tsx
+++ b/web-studio/src/routes/oauth/consent.tsx
@@ -20,6 +20,7 @@ import {
summarizeConnectionIdentity,
useAppConnection,
} from '#/hooks/use-app-connection'
+import { useIdentityDirectory } from '#/hooks/use-identity-directory'
type ConsentSearch = {
pending: string
@@ -52,7 +53,13 @@ export const Route = createFileRoute('/oauth/consent')({
function ConsentPage() {
const { t } = useTranslation(['oauth', 'common'])
const { pending } = Route.useSearch()
- const { connection, openConnectionSettings, serverMode } = useAppConnection()
+ const {
+ connection,
+ isConnectionRoleLoading,
+ openConnectionSettings,
+ serverMode,
+ } = useAppConnection()
+ const directory = useIdentityDirectory()
const currentIdentity = React.useMemo(() => {
const summary = summarizeConnectionIdentity(connection, serverMode)
@@ -65,6 +72,74 @@ function ConsentPage() {
() =>
connection.apiKey ? { mode: 'current' } : { mode: 'custom', apiKey: '' },
)
+ // Set once the user manually picks a mode, so the default-mode effect stops
+ // overriding their choice.
+ const userTouchedRef = React.useRef(false)
+ const handleIdentityChange = React.useCallback(
+ (next: IdentityPickerValue) => {
+ userTouchedRef.current = true
+ setIdentityValue(next)
+ },
+ [],
+ )
+
+ // Default-mode selection. Runs until the user touches the picker. Critical
+ // for root (whose `connection.apiKey` is empty and who cannot authorize as
+ // "current") — once the directory is available, default to selecting a
+ // concrete account/user. Falls back to custom when no path is available.
+ React.useEffect(() => {
+ if (userTouchedRef.current || isConnectionRoleLoading) {
+ return
+ }
+ const desiredMode = connection.apiKey
+ ? 'current'
+ : directory.available
+ ? 'select'
+ : 'custom'
+ setIdentityValue((prev) => {
+ if (prev.mode === desiredMode) {
+ return prev
+ }
+ if (desiredMode === 'current') {
+ return { mode: 'current' }
+ }
+ if (desiredMode === 'select') {
+ return {
+ mode: 'select',
+ accountId: directory.selectedAccountId,
+ userId: directory.selectedUserId,
+ apiKey:
+ directory.resolveUserKey(
+ directory.selectedAccountId,
+ directory.selectedUserId,
+ ) ?? '',
+ }
+ }
+ return { mode: 'custom', apiKey: '' }
+ })
+ }, [connection.apiKey, directory, isConnectionRoleLoading])
+
+ // Keep the select payload (account/user/key) in sync with the directory
+ // whenever we are in select mode — including after the user changes the
+ // dropdowns or fresh user keys arrive.
+ React.useEffect(() => {
+ setIdentityValue((prev) => {
+ if (prev.mode !== 'select') {
+ return prev
+ }
+ const accountId = directory.selectedAccountId
+ const userId = directory.selectedUserId
+ const apiKey = directory.resolveUserKey(accountId, userId) ?? ''
+ if (
+ prev.accountId === accountId &&
+ prev.userId === userId &&
+ prev.apiKey === apiKey
+ ) {
+ return prev
+ }
+ return { mode: 'select', accountId, userId, apiKey }
+ })
+ }, [directory])
React.useEffect(() => {
if (!pending) {
@@ -236,7 +311,7 @@ function ConsentPage() {
</div>
</dl>
- {!connection.apiKey ? (
+ {!connection.apiKey && !directory.available ? (
<div className="grid gap-2 rounded-md border border-dashed p-3 text-sm">
<p>{t('consent.signInRequired')}</p>
<Button
@@ -255,9 +330,10 @@ function ConsentPage() {
<IdentityPicker
value={identityValue}
- onChange={setIdentityValue}
+ onChange={handleIdentityChange}
currentApiKey={connection.apiKey}
currentIdentityLabel={currentIdentity}
+ directory={directory}
disabled={
phase.kind === 'verifying' ||
phase.kind === 'denying' ||
diff --git a/web-studio/src/routes/oauth/verify.tsx b/web-studio/src/routes/oauth/verify.tsx
index b8aaaeb84..29f179982 100644
--- a/web-studio/src/routes/oauth/verify.tsx
+++ b/web-studio/src/routes/oauth/verify.tsx
@@ -22,6 +22,7 @@ import {
summarizeConnectionIdentity,
useAppConnection,
} from '#/hooks/use-app-connection'
+import { useIdentityDirectory } from '#/hooks/use-identity-directory'
type Phase =
| { kind: 'idle' }
@@ -35,7 +36,13 @@ export const Route = createFileRoute('/oauth/verify')({
function VerifyPage() {
const { t } = useTranslation(['oauth', 'common'])
- const { connection, openConnectionSettings, serverMode } = useAppConnection()
+ const {
+ connection,
+ isConnectionRoleLoading,
+ openConnectionSettings,
+ serverMode,
+ } = useAppConnection()
+ const directory = useIdentityDirectory()
const currentIdentity = React.useMemo(() => {
const summary = summarizeConnectionIdentity(connection, serverMode)
@@ -46,6 +53,72 @@ function VerifyPage() {
() =>
connection.apiKey ? { mode: 'current' } : { mode: 'custom', apiKey: '' },
)
+ // Set once the user manually picks a mode, so the default-mode effect stops
+ // overriding their choice.
+ const userTouchedRef = React.useRef(false)
+ const handleIdentityChange = React.useCallback(
+ (next: IdentityPickerValue) => {
+ userTouchedRef.current = true
+ setIdentityValue(next)
+ },
+ [],
+ )
+
+ // Default-mode selection (see consent.tsx for the rationale): root has no
+ // usable "current" identity, so default to selecting a concrete account/user
+ // once the directory is available.
+ React.useEffect(() => {
+ if (userTouchedRef.current || isConnectionRoleLoading) {
+ return
+ }
+ const desiredMode = connection.apiKey
+ ? 'current'
+ : directory.available
+ ? 'select'
+ : 'custom'
+ setIdentityValue((prev) => {
+ if (prev.mode === desiredMode) {
+ return prev
+ }
+ if (desiredMode === 'current') {
+ return { mode: 'current' }
+ }
+ if (desiredMode === 'select') {
+ return {
+ mode: 'select',
+ accountId: directory.selectedAccountId,
+ userId: directory.selectedUserId,
+ apiKey:
+ directory.resolveUserKey(
+ directory.selectedAccountId,
+ directory.selectedUserId,
+ ) ?? '',
+ }
+ }
+ return { mode: 'custom', apiKey: '' }
+ })
+ }, [connection.apiKey, directory, isConnectionRoleLoading])
+
+ // Keep the select payload in sync with the directory while in select mode.
+ React.useEffect(() => {
+ setIdentityValue((prev) => {
+ if (prev.mode !== 'select') {
+ return prev
+ }
+ const accountId = directory.selectedAccountId
+ const userId = directory.selectedUserId
+ const apiKey = directory.resolveUserKey(accountId, userId) ?? ''
+ if (
+ prev.accountId === accountId &&
+ prev.userId === userId &&
+ prev.apiKey === apiKey
+ ) {
+ return prev
+ }
+ return { mode: 'select', accountId, userId, apiKey }
+ })
+ }, [directory])
+
const [code, setCode] = React.useState('')
const [phase, setPhase] = React.useState<Phase>({ kind: 'idle' })
@@ -116,7 +189,7 @@ function VerifyPage() {
</p>
) : (
<>
- {!connection.apiKey ? (
+ {!connection.apiKey && !directory.available ? (
<div className="grid gap-2 rounded-md border border-dashed p-3 text-sm">
<p>{t('verify.signInRequired')}</p>
<Button
@@ -134,9 +207,10 @@ function VerifyPage() {
<IdentityPicker
value={identityValue}
- onChange={setIdentityValue}
+ onChange={handleIdentityChange}
currentApiKey={connection.apiKey}
currentIdentityLabel={currentIdentity}
+ directory={directory}
disabled={phase.kind === 'verifying'}
/>
diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsx
index 41039db90..6c5505ecb 100644
--- a/web-studio/src/routes/settings/route.tsx
+++ b/web-studio/src/routes/settings/route.tsx
@@ -66,6 +66,13 @@ import { useAppConnection } from '#/hooks/use-app-connection'
import { cn } from '#/lib/utils'
import type { ConnectionDraft } from '#/hooks/use-app-connection'
+import { AccountSelect, UserSelect } from '#/components/identity-select'
+import {
+ DEFAULT_ACCOUNT_ID,
+ DEFAULT_USER_ID,
+ sortedAccountIds,
+ sortedAccounts,
+} from '#/lib/admin-options'
import {
createAdminAccount,
createAdminUser,
@@ -73,7 +80,7 @@ import {
fetchAdminUsers,
probeStudioConnection,
regenerateAdminUserKey,
-} from './-lib/admin'
+} from '#/lib/admin'
import type {
AdminConnection,
AdminAccount,
@@ -82,60 +89,17 @@ import type {
CreateAccountInput,
CreateUserInput,
KeyResult,
-} from './-lib/admin'
+} from '#/lib/admin'
export const Route = createFileRoute('/settings')({
component: SettingsRoute,
})
-const DEFAULT_ACCOUNT_ID = 'default'
-const DEFAULT_USER_ID = 'default'
const USER_ROLES = ['user', 'admin'] as const
type AddAccountDraft = CreateAccountInput
type AddUserDraft = CreateUserInput
-function uniqueOptions(values: readonly string[], fallback: string): string[] {
- const seen = new Set<string>()
- const result: string[] = []
-
- for (const rawValue of [fallback, ...values]) {
- const value = rawValue.trim()
- if (!value || seen.has(value)) {
- continue
- }
- seen.add(value)
- result.push(value)
- }
-
- return result
-}
-
-function compareAccountId(left: string, right: string): number {
- const normalizedLeft = left.toLowerCase()
- const normalizedRight = right.toLowerCase()
- if (normalizedLeft < normalizedRight) {
- return -1
- }
- if (normalizedLeft > normalizedRight) {
- return 1
- }
- return left < right ? -1 : left > right ? 1 : 0
-}
-
-function sortedAccountIds(
- values: readonly string[],
- fallback: string,
-): string[] {
- return uniqueOptions([...values, fallback], '').sort(compareAccountId)
-}
-
-function sortedAccounts(accounts: readonly AdminAccount[]): AdminAccount[] {
- return [...accounts].sort((left, right) =>
- compareAccountId(left.accountId, right.accountId),
- )
-}
-
function getErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
@@ -326,51 +290,6 @@ function CapabilityStatus({
)
}
-function AccountSelect({
- accounts,
- disabled,
- label,
- onChange,
- value,
-}: {
- accounts: readonly AdminAccount[]
- disabled?: boolean
- label: string
- onChange: (value: string) => void
- value: string
-}) {
- const options = sortedAccountIds(
- accounts.map((account) => account.accountId),
- value || DEFAULT_ACCOUNT_ID,
- )
-
- return (
- <Select
- value={value || DEFAULT_ACCOUNT_ID}
- onValueChange={(next) => {
- if (next) {
- onChange(next)
- }
- }}
- >
- <SelectTrigger
- aria-label={label}
- className="h-9 w-full"
- disabled={disabled}
- >
- <SelectValue>{value || DEFAULT_ACCOUNT_ID}</SelectValue>
- </SelectTrigger>
- <SelectContent alignItemWithTrigger>
- {options.map((item) => (
- <SelectItem key={item} value={item}>
- {item}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )
-}
-
function AccountFilterChips({
accounts,
disabled,
@@ -434,51 +353,6 @@ function AccountFilterChips({
)
}
-function UserSelect({
- disabled,
- label,
- onChange,
- users,
- value,
-}: {
- disabled?: boolean
- label: string
- onChange: (value: string) => void
- users: readonly AdminUser[]
- value: string
-}) {
- const options = uniqueOptions(
- users.map((user) => user.userId),
- value || DEFAULT_USER_ID,
- )
-
- return (
- <Select
- value={value || DEFAULT_USER_ID}
- onValueChange={(next) => {
- if (next) {
- onChange(next)
- }
- }}
- >
- <SelectTrigger
- aria-label={label}
- className="h-9 w-full"
- disabled={disabled}
- >
- <SelectValue>{value || DEFAULT_USER_ID}</SelectValue>
- </SelectTrigger>
- <SelectContent alignItemWithTrigger>
- {options.map((item) => (
- <SelectItem key={item} value={item}>
- {item}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )
-}
-
function UserApiKeyInput({
accountId,
disabled,