Skip to content

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

feat(web-studio): add account deletion workflow (#3912)

yufeng668637f3447a
diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.ts
index 07a03bf5f..810a1da4b 100644
--- a/web-studio/src/i18n/locales/en/workspace.ts
+++ b/web-studio/src/i18n/locales/en/workspace.ts
@@ -432,10 +432,12 @@ const workspace = {
addUser: 'Add user',
cancel: 'Cancel',
changeRole: 'Change the role for {{user}}',
+ confirmDeleteAccount: 'Delete account permanently',
confirmRemoveUser: 'Delete user',
confirmRoleChange: 'Confirm change',
copy: 'Copy',
currentIdentity: 'Current identity',
+ deleteAccount: 'Delete account',
refresh: 'Refresh',
regenerate: 'Regenerate',
removeUser: 'Delete {{user}}',
@@ -515,6 +517,13 @@ const workspace = {
'Change the role for {{account}} / {{user}} to {{role}}. The new permissions take effect immediately.',
title: 'Change user role?',
},
+ deleteAccount: {
+ confirmHint: 'The account name must match exactly.',
+ confirmLabel: 'Enter {{account}} to confirm',
+ description:
+ 'This permanently deletes {{account}} and removes access to it. This action cannot be undone.',
+ title: 'Delete this account?',
+ },
regenerate: {
description:
'Regenerate the API key for {{account}} / {{user}}. The current key stops working immediately.',
@@ -628,6 +637,9 @@ const workspace = {
},
toast: {
accountCreated: 'Account created',
+ accountDeleted: '{{account}} deleted',
+ accountDeletedRecoveryFailed:
+ 'The account was deleted, but the remaining account list could not be loaded: {{error}}',
connectionSaved: 'Connection saved',
copyFailed: 'Copy failed',
copied: 'Copied',
diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.ts
index fc44d380f..ab48e0be0 100644
--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts
+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts
@@ -413,10 +413,12 @@ const workspace = {
addUser: '新增 user',
cancel: '取消',
changeRole: '修改 {{user}} 的角色',
+ confirmDeleteAccount: '永久删除 Account',
confirmRemoveUser: '删除用户',
confirmRoleChange: '确认修改',
copy: '复制',
currentIdentity: '当前身份',
+ deleteAccount: '删除 Account',
refresh: '刷新',
regenerate: '重新生成',
removeUser: '删除 {{user}}',
@@ -493,6 +495,13 @@ const workspace = {
'将 {{account}} / {{user}} 的角色修改为 {{role}}。新的权限会立即生效。',
title: '修改用户角色?',
},
+ deleteAccount: {
+ confirmHint: 'Account 名称必须完全一致。',
+ confirmLabel: '请输入 {{account}} 以确认',
+ description:
+ '此操作将永久删除 {{account}},之后将无法再访问该 Account,且无法撤销。',
+ title: '删除这个 Account?',
+ },
regenerate: {
description:
'要重新生成 {{account}} / {{user}} 的 API key 吗?当前 key 会立即失效。',
@@ -603,6 +612,9 @@ const workspace = {
},
toast: {
accountCreated: 'Account 已创建',
+ accountDeleted: '{{account}} 已删除',
+ accountDeletedRecoveryFailed:
+ 'Account 已删除,但无法加载剩余 Account 列表:{{error}}',
connectionSaved: '连接已保存',
copyFailed: '复制失败',
copied: '已复制',
diff --git a/web-studio/src/lib/admin.ts b/web-studio/src/lib/admin.ts
index 67c645883..6385ddc00 100644
--- a/web-studio/src/lib/admin.ts
+++ b/web-studio/src/lib/admin.ts
@@ -2,6 +2,7 @@ import axios from 'axios'
import { createClient } from '#/gen/ov-client/client'
import {
+ deleteAdminAccountByAccountId,
deleteAdminAccountIdUserByUserId,
getAdminAccountIdUsers,
getAdminAccounts,
@@ -381,6 +382,20 @@ export async function createAdminAccount(
return normalizeKeyResult(result)
}
+export async function deleteAdminAccount(
+ connection: AdminConnection,
+ accountId: string,
+): Promise<void> {
+ await getOvResult<unknown>(
+ deleteAdminAccountByAccountId({
+ client: createAdminClient(connection),
+ path: {
+ account_id: accountId,
+ },
+ }),
+ )
+}
+
export async function createAdminUser(
connection: AdminConnection,
input: CreateUserInput,
diff --git a/web-studio/src/routes/users/-components/add-user-dialog.tsx b/web-studio/src/routes/users/-components/add-user-dialog.tsx
new file mode 100644
index 000000000..5dcf4fd98
--- /dev/null
+++ b/web-studio/src/routes/users/-components/add-user-dialog.tsx
@@ -0,0 +1,124 @@
+import * as React from 'react'
+import { LoaderCircleIcon, PlusIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import { Button } from '#/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '#/components/ui/dialog'
+import { Input } from '#/components/ui/input'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '#/components/ui/select'
+import type { CreateUserInput } from '#/lib/admin'
+import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
+
+export function AddUserDialog({
+ accountId,
+ isPending,
+ onCreate,
+ onOpenChange,
+ open,
+}: {
+ accountId: string
+ isPending: boolean
+ onCreate: (draft: CreateUserInput) => void
+ onOpenChange: (open: boolean) => void
+ open: boolean
+}) {
+ const { t } = useTranslation('settings')
+ const [draft, setDraft] = React.useState<CreateUserInput>({
+ accountId,
+ role: 'user',
+ userId: '',
+ })
+
+ React.useEffect(() => {
+ if (open) {
+ setDraft({ accountId, role: 'user', userId: '' })
+ }
+ }, [accountId, open])
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ onCreate(draft)
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>{t('dialogs.addUser.title')}</DialogTitle>
+ <DialogDescription>
+ {t('dialogs.addUser.currentAccountDescription', { accountId })}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4 py-5">
+ <label className="grid gap-2 text-sm font-medium">
+ {t('fields.user')}
+ <Input
+ required
+ value={draft.userId}
+ onChange={(event) =>
+ setDraft((current) => ({
+ ...current,
+ userId: event.target.value,
+ }))
+ }
+ placeholder={t('placeholders.user')}
+ {...PLAIN_INPUT_PROPS}
+ />
+ </label>
+ <label className="grid gap-2 text-sm font-medium">
+ {t('fields.role')}
+ <Select
+ value={draft.role}
+ onValueChange={(role) =>
+ setDraft((current) => ({
+ ...current,
+ role: role || 'user',
+ }))
+ }
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="user">{t('roles.user')}</SelectItem>
+ <SelectItem value="admin">{t('roles.admin')}</SelectItem>
+ </SelectContent>
+ </Select>
+ </label>
+ </div>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ >
+ {t('actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={isPending}>
+ {isPending ? (
+ <LoaderCircleIcon className="animate-spin" />
+ ) : (
+ <PlusIcon />
+ )}
+ {t('actions.addUser')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web-studio/src/routes/users/-components/delete-account-button.test.tsx b/web-studio/src/routes/users/-components/delete-account-button.test.tsx
new file mode 100644
index 000000000..2acc9dd8e
--- /dev/null
+++ b/web-studio/src/routes/users/-components/delete-account-button.test.tsx
@@ -0,0 +1,133 @@
+// @vitest-environment jsdom
+
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { DeleteAccountButton } from './delete-account-button'
+
+const adminMocks = vi.hoisted(() => ({
+ deleteAdminAccount: vi.fn(),
+ fetchAdminAccounts: vi.fn(),
+}))
+
+const connectionMocks = vi.hoisted(() => ({
+ openConnectionSettings: vi.fn(),
+ switchManagementAccount: vi.fn(),
+}))
+
+const toastMocks = vi.hoisted(() => ({
+ error: vi.fn(),
+ success: vi.fn(),
+ warning: vi.fn(),
+}))
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+vi.mock('sonner', () => ({ toast: toastMocks }))
+
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => connectionMocks,
+}))
+
+vi.mock('#/lib/admin', () => adminMocks)
+
+const adminConnection = {
+ accountId: 'account-a',
+ apiKey: 'root-key',
+ baseUrl: 'http://localhost:1933',
+ userId: 'root',
+}
+
+function renderButton() {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ mutations: { retry: false },
+ queries: { retry: false },
+ },
+ })
+
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <DeleteAccountButton
+ accountId="account-a"
+ adminConnection={adminConnection}
+ />
+ </QueryClientProvider>,
+ )
+}
+
+beforeEach(() => {
+ adminMocks.deleteAdminAccount.mockResolvedValue(undefined)
+ adminMocks.fetchAdminAccounts.mockResolvedValue([
+ { accountId: 'account-b', userCount: 1 },
+ ])
+ connectionMocks.switchManagementAccount.mockResolvedValue(undefined)
+})
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+describe('DeleteAccountButton', () => {
+ it('requires the exact account name before deleting', async () => {
+ renderButton()
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'actions.deleteAccount' }),
+ )
+
+ const confirmButton = screen.getByRole<HTMLButtonElement>('button', {
+ name: 'actions.confirmDeleteAccount',
+ })
+ const confirmationInput = screen.getByPlaceholderText('account-a')
+
+ expect(confirmButton.disabled).toBe(true)
+ fireEvent.change(confirmationInput, { target: { value: 'account-b' } })
+ expect(confirmButton.disabled).toBe(true)
+
+ fireEvent.change(confirmationInput, { target: { value: 'account-a' } })
+ expect(confirmButton.disabled).toBe(false)
+ fireEvent.click(confirmButton)
+
+ await waitFor(() => {
+ expect(adminMocks.deleteAdminAccount).toHaveBeenCalledWith(
+ adminConnection,
+ 'account-a',
+ )
+ })
+ expect(connectionMocks.switchManagementAccount).toHaveBeenCalledWith(
+ 'account-b',
+ )
+ expect(toastMocks.success).toHaveBeenCalledWith('toast.accountDeleted')
+ })
+
+ it('clears the deleted identity and opens settings when no account remains', async () => {
+ adminMocks.fetchAdminAccounts.mockResolvedValue([])
+ renderButton()
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'actions.deleteAccount' }),
+ )
+ fireEvent.change(screen.getByPlaceholderText('account-a'), {
+ target: { value: 'account-a' },
+ })
+ fireEvent.click(
+ screen.getByRole('button', { name: 'actions.confirmDeleteAccount' }),
+ )
+
+ await waitFor(() => {
+ expect(connectionMocks.switchManagementAccount).toHaveBeenCalledWith('')
+ })
+ expect(connectionMocks.openConnectionSettings).toHaveBeenCalledOnce()
+ })
+})
diff --git a/web-studio/src/routes/users/-components/delete-account-button.tsx b/web-studio/src/routes/users/-components/delete-account-button.tsx
new file mode 100644
index 000000000..eb83c6f09
--- /dev/null
+++ b/web-studio/src/routes/users/-components/delete-account-button.tsx
@@ -0,0 +1,151 @@
+import * as React from 'react'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { LoaderCircleIcon, Trash2Icon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+
+import { Button } from '#/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '#/components/ui/dialog'
+import { Input } from '#/components/ui/input'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { deleteAdminAccount, fetchAdminAccounts } from '#/lib/admin'
+import type { AdminConnection } from '#/lib/admin'
+import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
+
+import { getErrorMessage } from '../-lib/error'
+
+export function DeleteAccountButton({
+ accountId,
+ adminConnection,
+}: {
+ accountId: string
+ adminConnection: AdminConnection
+}) {
+ const { t } = useTranslation('settings')
+ const queryClient = useQueryClient()
+ const { openConnectionSettings, switchManagementAccount } = useAppConnection()
+ const [open, setOpen] = React.useState(false)
+ const [confirmation, setConfirmation] = React.useState('')
+
+ const deleteAccount = useMutation({
+ mutationFn: () => deleteAdminAccount(adminConnection, accountId),
+ onError: (error) => toast.error(getErrorMessage(error)),
+ onSuccess: async () => {
+ let nextAccountId = ''
+ try {
+ const remainingAccounts = await fetchAdminAccounts(adminConnection)
+ nextAccountId = remainingAccounts[0]?.accountId ?? ''
+ } catch (error) {
+ toast.warning(
+ t('toast.accountDeletedRecoveryFailed', {
+ error: getErrorMessage(error),
+ }),
+ )
+ }
+
+ await switchManagementAccount(nextAccountId)
+ queryClient.removeQueries({ queryKey: ['managed-users'] })
+ await queryClient.invalidateQueries({ queryKey: ['account-switcher'] })
+ setOpen(false)
+ setConfirmation('')
+ toast.success(t('toast.accountDeleted', { account: accountId }))
+
+ if (!nextAccountId) {
+ openConnectionSettings()
+ }
+ },
+ })
+
+ const confirmationMatches = confirmation === accountId
+
+ return (
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={!accountId}
+ className="border-destructive/50 text-destructive hover:bg-destructive/10 hover:text-destructive"
+ onClick={() => setOpen(true)}
+ >
+ <Trash2Icon />
+ {t('actions.deleteAccount')}
+ </Button>
+
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (!deleteAccount.isPending) {
+ setOpen(nextOpen)
+ if (!nextOpen) {
+ setConfirmation('')
+ }
+ }
+ }}
+ >
+ <DialogContent>
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (confirmationMatches) {
+ deleteAccount.mutate()
+ }
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>{t('dialogs.deleteAccount.title')}</DialogTitle>
+ <DialogDescription>
+ {t('dialogs.deleteAccount.description', { account: accountId })}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-2 py-5">
+ <label className="grid gap-2 text-sm font-medium">
+ {t('dialogs.deleteAccount.confirmLabel', {
+ account: accountId,
+ })}
+ <Input
+ value={confirmation}
+ disabled={deleteAccount.isPending}
+ onChange={(event) => setConfirmation(event.target.value)}
+ placeholder={accountId}
+ {...PLAIN_INPUT_PROPS}
+ />
+ </label>
+ <p className="text-xs leading-5 text-muted-foreground">
+ {t('dialogs.deleteAccount.confirmHint')}
+ </p>
+ </div>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={deleteAccount.isPending}
+ onClick={() => setOpen(false)}
+ >
+ {t('actions.cancel')}
+ </Button>
+ <Button
+ type="submit"
+ variant="destructive"
+ disabled={!confirmationMatches || deleteAccount.isPending}
+ >
+ {deleteAccount.isPending ? (
+ <LoaderCircleIcon className="animate-spin" />
+ ) : (
+ <Trash2Icon />
+ )}
+ {t('actions.confirmDeleteAccount')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
+}
diff --git a/web-studio/src/routes/users/-lib/error.ts b/web-studio/src/routes/users/-lib/error.ts
new file mode 100644
index 000000000..bc1e2ce07
--- /dev/null
+++ b/web-studio/src/routes/users/-lib/error.ts
@@ -0,0 +1,3 @@
+export function getErrorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
diff --git a/web-studio/src/routes/users/route.tsx b/web-studio/src/routes/users/route.tsx
index dfd4e5bcd..f3fdab483 100644
--- a/web-studio/src/routes/users/route.tsx
+++ b/web-studio/src/routes/users/route.tsx
@@ -25,15 +25,6 @@ import {
CardHeader,
CardTitle,
} from '#/components/ui/card'
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '#/components/ui/dialog'
-import { Input } from '#/components/ui/input'
import {
Select,
SelectContent,
@@ -81,19 +72,18 @@ import type {
UpdateUserRoleInput,
} from '#/lib/admin'
import { copyTextToClipboard } from '#/lib/clipboard'
-import { PLAIN_INPUT_PROPS } from '#/lib/form-input'
import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'
+import { AddUserDialog } from './-components/add-user-dialog'
+import { DeleteAccountButton } from './-components/delete-account-button'
+import { getErrorMessage } from './-lib/error'
+
export const Route = createFileRoute('/users')({
component: UserManagementRoute,
})
const USER_ROLE_OPTIONS: AdminUserRole[] = ['user', 'admin', 'root']
-function getErrorMessage(error: unknown): string {
- return error instanceof Error ? error.message : String(error)
-}
-
function isAdminUserRole(role: string): role is AdminUserRole {
return USER_ROLE_OPTIONS.includes(role as AdminUserRole)
}
@@ -337,6 +327,12 @@ function UserManagementRoute() {
</p>
</div>
<div className="flex shrink-0 flex-wrap gap-2">
+ {canManageAccounts ? (
+ <DeleteAccountButton
+ accountId={connection.accountId}
+ adminConnection={adminConnection}
+ />
+ ) : null}
<Button
type="button"
variant="outline"
@@ -768,104 +764,3 @@ function UserManagementRoute() {
</div>
)
}
-
-function AddUserDialog({
- accountId,
- isPending,
- onCreate,
- onOpenChange,
- open,
-}: {
- accountId: string
- isPending: boolean
- onCreate: (draft: CreateUserInput) => void
- onOpenChange: (open: boolean) => void
- open: boolean
-}) {
- const { t } = useTranslation('settings')
- const [draft, setDraft] = React.useState<CreateUserInput>({
- accountId,
- role: 'user',
- userId: '',
- })
-
- React.useEffect(() => {
- if (open) {
- setDraft({ accountId, role: 'user', userId: '' })
- }
- }, [accountId, open])
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <form
- onSubmit={(event) => {
- event.preventDefault()
- onCreate(draft)
- }}
- >
- <DialogHeader>
- <DialogTitle>{t('dialogs.addUser.title')}</DialogTitle>
- <DialogDescription>
- {t('dialogs.addUser.currentAccountDescription', { accountId })}
- </DialogDescription>
- </DialogHeader>
- <div className="grid gap-4 py-5">
- <label className="grid gap-2 text-sm font-medium">
- {t('fields.user')}
- <Input
- required
- value={draft.userId}
- onChange={(event) =>
- setDraft((current) => ({
- ...current,
- userId: event.target.value,
- }))
- }
- placeholder={t('placeholders.user')}
- {...PLAIN_INPUT_PROPS}
- />
- </label>
- <label className="grid gap-2 text-sm font-medium">
- {t('fields.role')}
- <Select
- value={draft.role}
- onValueChange={(role) =>
- setDraft((current) => ({
- ...current,
- role: role || 'user',
- }))
- }
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="user">{t('roles.user')}</SelectItem>
- <SelectItem value="admin">{t('roles.admin')}</SelectItem>
- </SelectContent>
- </Select>
- </label>
- </div>
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- >
- {t('actions.cancel')}
- </Button>
- <Button type="submit" disabled={isPending}>
- {isPending ? (
- <LoaderCircleIcon className="animate-spin" />
- ) : (
- <PlusIcon />
- )}
- {t('actions.addUser')}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- )
-}