Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent-identity): identity settings tab and inbox UI (frontend) (#22010)

Arvin Xubbea25c29852
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.json
index 1ea6f743580..b17455d09f9 100644
--- a/locales/en-US/auth.json
+++ b/locales/en-US/auth.json
@@ -61,6 +61,7 @@
"apikey.list.restrictedEmpty.desc": "Only workspace admins can create API Keys. Contact a workspace admin if you need one.",
"apikey.list.restrictedEmpty.title": "API Key creation is restricted",
"apikey.list.title": "API Key List",
+ "apikey.scopes.agentCredential": "Write account credentials",
"apikey.scopes.count": "{{count}} scopes",
"apikey.scopes.fullAccess": "Full access",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/en-US/labs.json b/locales/en-US/labs.json
index 5e0a3fee8b7..ae23778754c 100644
--- a/locales/en-US/labs.json
+++ b/locales/en-US/labs.json
@@ -2,6 +2,8 @@
"description": "These features are experimental. We might remove them, and they might have bugs. We'd love your feedback while using them.",
"features.agentGraphConfig.desc": "Show graph runtime configuration in an agent profile advanced settings.",
"features.agentGraphConfig.title": "Agent Graph Runtime Configuration",
+ "features.agentIdentity.desc": "Give an agent its own email address, and read what arrives in its inbox from the agent settings.",
+ "features.agentIdentity.title": "Agent Identity",
"features.agentSelfIteration.desc": "Allow the agent to reflect, build self-awareness, and continuously iterate through ongoing attempts and interactions.",
"features.agentSelfIteration.title": "Agent Self-iteration",
"features.artifactDeployment.desc": "Publish artifacts to a hosted URL and manage releases from the conversation sidebar",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index caf1d24254e..d5353b76db4 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -216,6 +216,7 @@
"agentSkillModal.url.urlPlaceholder": "https://example.com/path/to/SKILL.md",
"agentSkillTag": "Agent Skill",
"agentTab.graph": "Graph Runtime",
+ "agentTab.identity": "Identity",
"agentTab.opening": "Opening Settings",
"agentTab.plugin": "Skill Settings",
"agentTab.prompt": "Agent Profile",
@@ -1033,6 +1034,45 @@
"hotkey.title": "Hotkeys",
"hotkey.updateError": "Failed to update hotkey: Network or system error",
"hotkey.updateSuccess": "Hotkey updated successfully",
+ "identity.copy": "Copy address",
+ "identity.desc": "Addresses this agent owns and can be reached at. Opening one is an explicit action; releasing it hands the address back.",
+ "identity.hideDetail": "Hide details",
+ "identity.inbox.desc": "Messages delivered to the addresses above.",
+ "identity.inbox.detail.attachments": "Attachments",
+ "identity.inbox.detail.from": "From",
+ "identity.inbox.detail.loadFailed": "Could not open this message",
+ "identity.inbox.detail.receivedAt": "Received",
+ "identity.inbox.detail.to": "To",
+ "identity.inbox.empty": "Nothing here yet. Mail sent to the addresses above lands here.",
+ "identity.inbox.loadFailed": "Couldn't load the inbox.",
+ "identity.inbox.loadMore": "Load older messages",
+ "identity.inbox.markAllRead": "Mark all read",
+ "identity.inbox.markAllReadFailed": "Could not mark messages as read",
+ "identity.inbox.noSubject": "(no subject)",
+ "identity.inbox.title": "Inbox",
+ "identity.inbox.unread": "{{count}} unread",
+ "identity.loadFailed": "Couldn't load the addresses.",
+ "identity.mail.desc": "A @lobe.id inbox the agent can receive mail at and reply from.",
+ "identity.mail.title": "Email",
+ "identity.noAgent": "Select an agent to see the addresses it owns.",
+ "identity.prefix.hint": "Optional. Letters, numbers, dot, underscore and dash.",
+ "identity.prefix.placeholder": "Preferred prefix (optional)",
+ "identity.provision": "Open",
+ "identity.provision.failed": "Could not open the address: {{reason}}",
+ "identity.provision.success": "Opened {{identifier}}",
+ "identity.release": "Release",
+ "identity.release.confirm": "Release",
+ "identity.release.content": "“{{identifier}}” will stop receiving new messages. This cannot be undone.",
+ "identity.release.failed": "Could not release the address",
+ "identity.release.success": "Address released",
+ "identity.release.title": "Release this address?",
+ "identity.retry": "Retry",
+ "identity.showDetail": "Show details",
+ "identity.status.active": "Active",
+ "identity.status.provisioning": "Opening",
+ "identity.status.revoked": "Released",
+ "identity.status.suspended": "Suspended",
+ "identity.title": "Identity",
"llm.aesGcm": "Your keys and proxy address will be encrypted using the <1>AES-GCM</1> encryption algorithm",
"llm.apiKey.desc": "Please enter your {{name}} API Key",
"llm.apiKey.placeholder": "{{name}} API Key",
diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.json
index daf97495a16..51f3035824c 100644
--- a/locales/zh-CN/auth.json
+++ b/locales/zh-CN/auth.json
@@ -61,6 +61,7 @@
"apikey.list.restrictedEmpty.desc": "仅工作区管理员可以创建 API Key。如有需要,请联系工作区管理员。",
"apikey.list.restrictedEmpty.title": "API Key 创建权限已受限",
"apikey.list.title": "API Key 列表",
+ "apikey.scopes.agentCredential": "写入账号凭据",
"apikey.scopes.count": "{{count}} 项权限",
"apikey.scopes.fullAccess": "完全访问",
"apikey.scopes.grantJoin": ":",
diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.json
index f70057d602a..87977b36ee4 100644
--- a/locales/zh-CN/labs.json
+++ b/locales/zh-CN/labs.json
@@ -2,6 +2,8 @@
"description": "这些功能仍处于实验阶段,可能会被移除,也可能存在问题。欢迎在使用过程中向我们提供反馈。",
"features.agentGraphConfig.desc": "在助理档案的进阶设置中显示 Graph 运行时配置。",
"features.agentGraphConfig.title": "Agent Graph 运行时配置",
+ "features.agentIdentity.desc": "为助理开通专属邮箱地址,并在助理设置中查看它收到的消息。",
+ "features.agentIdentity.title": "助理身份",
"features.agentSelfIteration.desc": "允许助理自我反思、自我感知,并在持续的尝试与交互中不断自我迭代。",
"features.agentSelfIteration.title": "Agent 自我迭代",
"features.artifactDeployment.desc": "将 Artifact 发布为可访问的托管链接,并在会话侧边栏管理发布版本",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index eb755a4537a..e6f34d705b7 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -216,6 +216,7 @@
"agentSkillModal.url.urlPlaceholder": "https://example.com/path/to/SKILL.md",
"agentSkillTag": "Agent 技能",
"agentTab.graph": "Graph 运行时",
+ "agentTab.identity": "身份",
"agentTab.opening": "开场设置",
"agentTab.plugin": "技能设置",
"agentTab.prompt": "助理档案",
@@ -1033,6 +1034,45 @@
"hotkey.title": "快捷键",
"hotkey.updateError": "快捷键更新失败:网络或系统错误",
"hotkey.updateSuccess": "快捷键更新成功",
+ "identity.copy": "复制地址",
+ "identity.desc": "该 Agent 拥有的地址,外界可通过这些地址联系它。开通是明确的主动操作;释放会把地址交还。",
+ "identity.hideDetail": "收起详情",
+ "identity.inbox.desc": "投递到上述地址的消息。",
+ "identity.inbox.detail.attachments": "附件",
+ "identity.inbox.detail.from": "发件人",
+ "identity.inbox.detail.loadFailed": "无法打开这封消息",
+ "identity.inbox.detail.receivedAt": "接收时间",
+ "identity.inbox.detail.to": "收件人",
+ "identity.inbox.empty": "暂无消息。发往上列地址的邮件会出现在这里。",
+ "identity.inbox.loadFailed": "收件箱加载失败。",
+ "identity.inbox.loadMore": "加载更早的消息",
+ "identity.inbox.markAllRead": "全部标记为已读",
+ "identity.inbox.markAllReadFailed": "标记已读失败",
+ "identity.inbox.noSubject": "(无主题)",
+ "identity.inbox.title": "收件箱",
+ "identity.inbox.unread": "{{count}} 条未读",
+ "identity.loadFailed": "地址加载失败。",
+ "identity.mail.desc": "一个 @lobe.id 邮箱,Agent 可收发邮件。",
+ "identity.mail.title": "邮箱",
+ "identity.noAgent": "请选择一个 Agent 以查看它拥有的地址。",
+ "identity.prefix.hint": "可选。支持字母、数字、点、下划线和连字符。",
+ "identity.prefix.placeholder": "期望的前缀(可选)",
+ "identity.provision": "开通",
+ "identity.provision.failed": "开通失败:{{reason}}",
+ "identity.provision.success": "已开通 {{identifier}}",
+ "identity.release": "释放",
+ "identity.release.confirm": "释放",
+ "identity.release.content": "“{{identifier}}” 将不再接收新消息。此操作无法撤销。",
+ "identity.release.failed": "释放失败",
+ "identity.release.success": "已释放地址",
+ "identity.release.title": "释放该地址?",
+ "identity.retry": "重试",
+ "identity.showDetail": "查看详情",
+ "identity.status.active": "已启用",
+ "identity.status.provisioning": "开通中",
+ "identity.status.revoked": "已释放",
+ "identity.status.suspended": "已暂停",
+ "identity.title": "身份",
"llm.aesGcm": "你的密钥与代理地址等将使用 <1>AES-GCM</1> 加密算法进行加密",
"llm.apiKey.desc": "请填写你的 {{name}} API Key",
"llm.apiKey.placeholder": "{{name}} API Key",
diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.ts
index be7fbc11f77..170f1699b87 100644
--- a/packages/locales/src/default/auth.ts
+++ b/packages/locales/src/default/auth.ts
@@ -67,6 +67,7 @@ export default {
'Only workspace admins can create API Keys. Contact a workspace admin if you need one.',
'apikey.list.restrictedEmpty.title': 'API Key creation is restricted',
'apikey.list.title': 'API Key List',
+ 'apikey.scopes.agentCredential': 'Write account credentials',
'apikey.scopes.count': '{{count}} scopes',
'apikey.scopes.fullAccess': 'Full access',
'apikey.scopes.grantJoin': ': ',
diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.ts
index cb58b4f3a03..ab4e2a6834a 100644
--- a/packages/locales/src/default/labs.ts
+++ b/packages/locales/src/default/labs.ts
@@ -4,6 +4,9 @@ export default {
'features.agentGraphConfig.desc':
'Show graph runtime configuration in an agent profile advanced settings.',
'features.agentGraphConfig.title': 'Agent Graph Runtime Configuration',
+ 'features.agentIdentity.desc':
+ 'Give an agent its own email address, and read what arrives in its inbox from the agent settings.',
+ 'features.agentIdentity.title': 'Agent Identity',
'features.agentSelfIteration.desc':
'Allow the agent to reflect, build self-awareness, and continuously iterate through ongoing attempts and interactions.',
'features.agentSelfIteration.title': 'Agent Self-iteration',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 60cf1699f32..f4b94d2bba3 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -328,10 +328,52 @@ export default {
'agentSkillModal.url.urlPlaceholder': 'https://example.com/path/to/SKILL.md',
'agentSkillTag': 'Agent Skill',
'agentTab.graph': 'Graph Runtime',
+ 'agentTab.identity': 'Identity',
'agentTab.opening': 'Opening Settings',
'agentTab.plugin': 'Skill Settings',
'agentTab.prompt': 'Agent Profile',
'agentTab.tts': 'Voice Service',
+ 'identity.copy': 'Copy address',
+ 'identity.desc':
+ 'Addresses this agent owns and can be reached at. Opening one is an explicit action; releasing it hands the address back.',
+ 'identity.hideDetail': 'Hide details',
+ 'identity.inbox.desc': 'Messages delivered to the addresses above.',
+ 'identity.inbox.detail.attachments': 'Attachments',
+ 'identity.inbox.detail.from': 'From',
+ 'identity.inbox.detail.loadFailed': 'Could not open this message',
+ 'identity.inbox.detail.receivedAt': 'Received',
+ 'identity.inbox.detail.to': 'To',
+ 'identity.inbox.empty': 'Nothing here yet. Mail sent to the addresses above lands here.',
+ 'identity.inbox.loadFailed': "Couldn't load the inbox.",
+ 'identity.inbox.loadMore': 'Load older messages',
+ 'identity.inbox.markAllRead': 'Mark all read',
+ 'identity.inbox.markAllReadFailed': 'Could not mark messages as read',
+ 'identity.inbox.noSubject': '(no subject)',
+ 'identity.inbox.title': 'Inbox',
+ 'identity.inbox.unread': '{{count}} unread',
+ 'identity.loadFailed': "Couldn't load the addresses.",
+ 'identity.mail.desc': 'A @lobe.id inbox the agent can receive mail at and reply from.',
+ 'identity.mail.title': 'Email',
+ 'identity.noAgent': 'Select an agent to see the addresses it owns.',
+ 'identity.prefix.hint': 'Optional. Letters, numbers, dot, underscore and dash.',
+ 'identity.prefix.placeholder': 'Preferred prefix (optional)',
+ 'identity.provision': 'Open',
+ 'identity.provision.failed': 'Could not open the address: {{reason}}',
+ 'identity.provision.success': 'Opened {{identifier}}',
+ 'identity.release': 'Release',
+ 'identity.release.confirm': 'Release',
+ 'identity.release.content':
+ '“{{identifier}}” will stop receiving new messages. This cannot be undone.',
+ 'identity.release.failed': 'Could not release the address',
+ 'identity.release.success': 'Address released',
+ 'identity.release.title': 'Release this address?',
+ 'identity.retry': 'Retry',
+ 'identity.showDetail': 'Show details',
+ 'identity.status.active': 'Active',
+ 'identity.status.provisioning': 'Opening',
+ 'identity.status.revoked': 'Released',
+ 'identity.status.suspended': 'Suspended',
+ 'identity.title': 'Identity',
'permission.accessTag.useOnlyTip':
'Your member permission here is "Can use" — you can view and use it, but not edit. Ask the creator or a workspace owner for edit access.',
'permission.accessTag.viewOnlyTip':
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index fa2b28cae90..fe1d3769438 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -166,6 +166,10 @@ export const UserGuideSchema = z.object({
export type UserGuide = z.infer<typeof UserGuideSchema>;
export const UserLabSchema = z.object({
+ /**
+ * enable agent identity: give an agent its own mail address
+ */
+ enableAgentIdentity: z.boolean().optional(),
/**
* enable graph runtime configuration for agents
*/
diff --git a/src/features/AgentSetting/AgentIdentity/AccountCard.tsx b/src/features/AgentSetting/AgentIdentity/AccountCard.tsx
new file mode 100644
index 00000000000..8cff8c8a63d
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/AccountCard.tsx
@@ -0,0 +1,83 @@
+'use client';
+
+import { ActionIcon, CopyButton, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { Trash2 } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { AgentAccountView } from '@/services/agentAccount';
+
+import type { IdentityChannel } from './const';
+import { KIND_ICONS } from './const';
+import { identityStyles } from './styles';
+import { useAccountActions } from './useIdentityActions';
+
+/**
+ * Every lifecycle state gets a label, released included: the list filters
+ * revoked accounts out today, but a tag that silently renders nothing would
+ * turn a future filter change into a blank chip rather than a wrong-looking one.
+ */
+const STATUS_KEYS = {
+ active: 'identity.status.active',
+ provisioning: 'identity.status.provisioning',
+ revoked: 'identity.status.revoked',
+ suspended: 'identity.status.suspended',
+} as const satisfies Record<AgentAccountView['status'], string>;
+
+interface AccountCardProps {
+ account: AgentAccountView;
+ agentId: string;
+ /**
+ * The built-in channel the account belongs to. Absent for a mounted account
+ * (e.g. provider `user`); the card then falls back to the account's kind and
+ * provider so the address can still be read, copied and released.
+ */
+ channel?: IdentityChannel;
+ /** Read-only viewer: the address stays copyable, but cannot be released. */
+ disabled?: boolean;
+ onChanged: () => Promise<unknown> | void;
+}
+
+/**
+ * One owned address: what it is, whether it is live, and the two things a
+ * person does with it — copy it out, or give it back.
+ */
+const AccountCard = memo<AccountCardProps>(({ account, channel, agentId, disabled, onChanged }) => {
+ const { t } = useTranslation('setting');
+ const { release } = useAccountActions({ agentId, onChanged });
+
+ return (
+ <Flexbox horizontal align={'center'} className={identityStyles.card} gap={12}>
+ <Icon
+ className={identityStyles.icon}
+ icon={channel?.icon ?? KIND_ICONS[account.kind]}
+ size={18}
+ />
+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text code ellipsis weight={500}>
+ {account.identifier}
+ </Text>
+ <Tag>{t(STATUS_KEYS[account.status])}</Tag>
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {account.displayName || (channel ? t(channel.titleKey) : account.provider)}
+ </Text>
+ </Flexbox>
+ <CopyButton content={account.identifier} title={t('identity.copy')} />
+ <ActionIcon
+ disabled={disabled}
+ icon={Trash2}
+ title={t('identity.release')}
+ onClick={() => {
+ if (disabled) return;
+ void release(account);
+ }}
+ />
+ </Flexbox>
+ );
+});
+
+AccountCard.displayName = 'AgentIdentityAccountCard';
+
+export default AccountCard;
diff --git a/src/features/AgentSetting/AgentIdentity/IdentityAccounts.tsx b/src/features/AgentSetting/AgentIdentity/IdentityAccounts.tsx
new file mode 100644
index 00000000000..6b5cfc5a90d
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/IdentityAccounts.tsx
@@ -0,0 +1,119 @@
+'use client';
+
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useServerConfigStore } from '@/store/serverConfig';
+import { serverConfigSelectors } from '@/store/serverConfig/selectors';
+
+import AccountCard from './AccountCard';
+import { IDENTITY_CHANNELS, isChannelAccount, isUnchanneledAccount } from './const';
+import InlineError from './InlineError';
+import ProvisionCard from './ProvisionCard';
+import SectionHeader from './SectionHeader';
+import { useAgentAccounts } from './useAgentIdentity';
+
+interface IdentityAccountsProps {
+ agentId: string;
+ disabled?: boolean;
+}
+
+/**
+ * The addresses the agent owns.
+ *
+ * Every channel is rendered either as the address that exists or as the offer
+ * to open one — never as a plain list that silently omits a channel, so "the
+ * agent has no mail address" is visible rather than inferred from absence.
+ */
+const IdentityAccounts = memo<IdentityAccountsProps>(({ agentId, disabled }) => {
+ const { t } = useTranslation('setting');
+ const { data, error, isLoading, mutate } = useAgentAccounts(agentId);
+ const providers = useServerConfigStore(serverConfigSelectors.agentIdentityProviders);
+
+ const header = <SectionHeader desc={t('identity.desc')} title={t('identity.title')} />;
+
+ // Only a read that never succeeded replaces the list. A later revalidation
+ // that fails keeps the addresses on screen, with the failure beside them.
+ if (error && !data) {
+ return (
+ <Flexbox gap={10}>
+ {header}
+ <InlineError
+ detail={error instanceof Error ? error.message : String(error)}
+ summary={t('identity.loadFailed')}
+ onRetry={() => void mutate()}
+ />
+ </Flexbox>
+ );
+ }
+
+ if (isLoading && !data) {
+ return (
+ <Flexbox gap={10}>
+ {header}
+ <Skeleton height={56} width={'100%'} />
+ <Skeleton height={88} width={'100%'} />
+ </Flexbox>
+ );
+ }
+
+ const accounts = (data ?? []).filter((account) => account.status !== 'revoked');
+
+ return (
+ <Flexbox gap={10}>
+ {header}
+ {error && (
+ <InlineError
+ detail={error instanceof Error ? error.message : String(error)}
+ summary={t('identity.loadFailed')}
+ onRetry={() => void mutate()}
+ />
+ )}
+ {IDENTITY_CHANNELS.map((channel) => {
+ const owned = accounts.filter((account) => isChannelAccount(account, channel));
+
+ if (owned.length === 0) {
+ // An offer this deployment cannot fulfil would only fail on click.
+ if (!providers.includes(channel.provider)) return null;
+
+ return (
+ <ProvisionCard
+ agentId={agentId}
+ channel={channel}
+ disabled={disabled}
+ key={channel.provider}
+ onProvisioned={mutate}
+ />
+ );
+ }
+
+ return owned.map((account) => (
+ <AccountCard
+ account={account}
+ agentId={agentId}
+ channel={channel}
+ disabled={disabled}
+ key={account.id}
+ onChanged={mutate}
+ />
+ ));
+ })}
+ {/* Mounted addresses (and providers this tab does not offer) still belong
+ to the agent: show them so they can be read, copied and released. */}
+ {accounts.filter(isUnchanneledAccount).map((account) => (
+ <AccountCard
+ account={account}
+ agentId={agentId}
+ disabled={disabled}
+ key={account.id}
+ onChanged={mutate}
+ />
+ ))}
+ </Flexbox>
+ );
+});
+
+IdentityAccounts.displayName = 'AgentIdentityAccounts';
+
+export default IdentityAccounts;
diff --git a/src/features/AgentSetting/AgentIdentity/InboxMessageModal.tsx b/src/features/AgentSetting/AgentIdentity/InboxMessageModal.tsx
new file mode 100644
index 00000000000..ff661e17763
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/InboxMessageModal.tsx
@@ -0,0 +1,129 @@
+'use client';
+
+import { Flexbox, Skeleton, Text } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
+
+import { agentAccountService } from '@/services/agentAccount';
+
+import InlineError from './InlineError';
+
+dayjs.extend(relativeTime);
+
+export interface InboxMessageModalProps {
+ id: string;
+}
+
+const MetaRow = memo<{ label: string; value: string }>(({ label, value }) => (
+ <Flexbox horizontal gap={12}>
+ <Text fontSize={12} style={{ flexShrink: 0, width: 68 }} type={'secondary'}>
+ {label}
+ </Text>
+ <Text fontSize={13} style={{ wordBreak: 'break-all' }}>
+ {value}
+ </Text>
+ </Flexbox>
+));
+
+MetaRow.displayName = 'InboxMessageMetaRow';
+
+/**
+ * One delivered message, fetched by id rather than taken from the list row.
+ *
+ * The list is a summary and may be stale; opening a message reads the stored
+ * row, so the body shown is the body that was persisted.
+ */
+/** `2.4 MB`, `512 KB` — enough to tell a photo from a document at a glance. */
+const formatAttachmentSize = (bytes?: number): string | undefined => {
+ if (!bytes) return undefined;
+ if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;
+};
+
+const InboxMessageModal = memo<InboxMessageModalProps>(({ id }) => {
+ const { t } = useTranslation('setting');
+ const { data, error, isLoading, mutate } = useSWR(['agent-inbox-message', id], ([, messageId]) =>
+ agentAccountService.getInboxMessage(messageId),
+ );
+
+ // A failed read must say so: a skeleton that never resolves reads as "still
+ // loading" forever.
+ if (error && !data) {
+ return (
+ <Flexbox padding={4}>
+ <InlineError
+ detail={error instanceof Error ? error.message : String(error)}
+ summary={t('identity.inbox.detail.loadFailed')}
+ onRetry={() => void mutate()}
+ />
+ </Flexbox>
+ );
+ }
+
+ if (isLoading || !data) {
+ return (
+ <Flexbox gap={12} padding={4}>
+ <Skeleton height={20} width={'60%'} />
+ <Skeleton height={14} width={'40%'} />
+ <Skeleton height={120} width={'100%'} />
+ </Flexbox>
+ );
+ }
+
+ // An older server may omit `attachments` entirely; the guard above only covers
+ // the payload root, so normalize the field once instead of trusting it.
+ const attachments = data.attachments ?? [];
+
+ return (
+ <Flexbox gap={14} padding={4}>
+ <Text fontSize={16} weight={600}>
+ {data.subject || t('identity.inbox.noSubject')}
+ </Text>
+ <Flexbox gap={6}>
+ <MetaRow label={t('identity.inbox.detail.from')} value={data.from} />
+ <MetaRow label={t('identity.inbox.detail.to')} value={data.to} />
+ <MetaRow
+ label={t('identity.inbox.detail.receivedAt')}
+ value={dayjs(data.receivedAt).format('YYYY-MM-DD HH:mm')}
+ />
+ </Flexbox>
+ <Text
+ fontSize={13}
+ style={{ lineHeight: 1.7, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}
+ >
+ {data.text}
+ </Text>
+ {attachments.length > 0 && (
+ <Flexbox gap={6}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('identity.inbox.detail.attachments')}
+ </Text>
+ {/* Descriptors, not links: the bytes stay with the mail provider, so the
+ list says what was sent without fetching any of it. */}
+ {attachments.map((attachment) => (
+ <Text
+ fontSize={13}
+ key={attachment.index}
+ style={{ wordBreak: 'break-all' }}
+ type={'secondary'}
+ >
+ {[
+ attachment.filename || attachment.contentType,
+ formatAttachmentSize(attachment.size),
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </Text>
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+InboxMessageModal.displayName = 'AgentInboxMessageModal';
+
+export default InboxMessageModal;
diff --git a/src/features/AgentSetting/AgentIdentity/InboxSection.tsx b/src/features/AgentSetting/AgentIdentity/InboxSection.tsx
new file mode 100644
index 00000000000..604f4e6a9de
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/InboxSection.tsx
@@ -0,0 +1,161 @@
+'use client';
+
+import { Button, Flexbox, Skeleton, Text } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import InlineError from './InlineError';
+import SectionHeader from './SectionHeader';
+import { identityStyles } from './styles';
+import { useAgentInbox, useAgentInboxUnreadCount } from './useAgentIdentity';
+import { useInboxActions } from './useIdentityActions';
+
+dayjs.extend(relativeTime);
+
+interface InboxSectionProps {
+ agentId: string;
+}
+
+/**
+ * What has arrived at the agent's addresses.
+ *
+ * The list is the inbox: sender, subject and when it landed, newest first. A
+ * row is the way in — opening one reads the stored message and clears its
+ * unread mark, which is the only state the inbox keeps.
+ */
+const InboxSection = memo<InboxSectionProps>(({ agentId }) => {
+ const { t } = useTranslation('setting');
+ const { data, error, hasMore, isLoading, loadMore, mutate } = useAgentInbox(agentId);
+ const { data: unreadCount = 0, mutate: mutateUnread } = useAgentInboxUnreadCount(agentId);
+ const refresh = useCallback(
+ () => Promise.all([mutate(), mutateUnread()]),
+ [mutate, mutateUnread],
+ );
+ const { markAllRead, openMessage } = useInboxActions({ agentId, onChanged: refresh });
+
+ const messages = data ?? [];
+
+ const extra =
+ unreadCount > 0 ? (
+ <Flexbox horizontal align={'center'} gap={12}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('identity.inbox.unread', { count: unreadCount })}
+ </Text>
+ <Button size={'small'} type={'text'} onClick={() => void markAllRead()}>
+ {t('identity.inbox.markAllRead')}
+ </Button>
+ </Flexbox>
+ ) : undefined;
+
+ const header = (
+ <SectionHeader
+ desc={t('identity.inbox.desc')}
+ extra={extra}
+ title={t('identity.inbox.title')}
+ />
+ );
+
+ // A later fetch can fail while SWR still holds the last good result, and an
+ // empty inbox is a legitimate result. Show the failure next to whatever is
+ // cached instead of returning early, or an unreachable inbox reads as empty.
+ const refreshError = error ? (
+ <InlineError
+ detail={error instanceof Error ? error.message : String(error)}
+ summary={t('identity.inbox.loadFailed')}
+ onRetry={() => void mutate()}
+ />
+ ) : undefined;
+
+ // Only a first page that never loaded replaces the list. A failed refresh or
+ // older page keeps every message already on screen, with a retry below it.
+ if (error && !data) {
+ return (
+ <Flexbox gap={10}>
+ {header}
+ {refreshError}
+ </Flexbox>
+ );
+ }
+
+ if (isLoading && !data) {
+ return (
+ <Flexbox gap={10}>
+ {header}
+ <Skeleton height={54} width={'100%'} />
+ <Skeleton height={54} width={'100%'} />
+ </Flexbox>
+ );
+ }
+
+ if (messages.length === 0) {
+ return (
+ <Flexbox gap={10}>
+ {header}
+ <div className={identityStyles.empty}>{t('identity.inbox.empty')}</div>
+ {refreshError}
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox gap={10}>
+ {header}
+ <Flexbox gap={8}>
+ {messages.map((message) => {
+ const unread = !message.readAt;
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ aria-label={`${message.from} — ${message.subject || t('identity.inbox.noSubject')}`}
+ className={identityStyles.inboxRow}
+ gap={10}
+ key={message.id}
+ role={'button'}
+ tabIndex={0}
+ onClick={() => {
+ void openMessage(message);
+ }}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ void openMessage(message);
+ }}
+ >
+ <span
+ className={identityStyles.unreadDot}
+ style={{ visibility: unread ? 'visible' : 'hidden' }}
+ />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <Text ellipsis fontSize={13} weight={unread ? 500 : 400}>
+ {message.from}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {dayjs(message.receivedAt).fromNow()}
+ </Text>
+ </Flexbox>
+ <Text ellipsis className={identityStyles.subject}>
+ {message.subject || t('identity.inbox.noSubject')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ {refreshError ??
+ (hasMore && (
+ <Button block size={'small'} type={'text'} onClick={loadMore}>
+ {t('identity.inbox.loadMore')}
+ </Button>
+ ))}
+ </Flexbox>
+ );
+});
+
+InboxSection.displayName = 'AgentInboxSection';
+
+export default InboxSection;
diff --git a/src/features/AgentSetting/AgentIdentity/InlineError.tsx b/src/features/AgentSetting/AgentIdentity/InlineError.tsx
new file mode 100644
index 00000000000..469a5069be5
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/InlineError.tsx
@@ -0,0 +1,58 @@
+'use client';
+
+import { Button, Flexbox, Icon, Text } from '@lobehub/ui';
+import { TriangleAlert } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface InlineErrorProps {
+ /** Raw failure, folded behind the details toggle. */
+ detail?: string;
+ /** Retry entry, when the read can simply be repeated. */
+ onRetry?: () => void;
+ /** One readable sentence: what failed, in the user's terms. */
+ summary: string;
+}
+
+/**
+ * A feature-level failure as one readable line — icon, sentence, retry — with
+ * the raw message folded behind a toggle.
+ *
+ * A section inside agent settings is not a page: wrapping a failed read in a
+ * full alert panel makes a recoverable hiccup look like the tab broke, and
+ * dumps a transport string where a person expects a sentence.
+ */
+const InlineError = memo<InlineErrorProps>(({ summary, detail, onRetry }) => {
+ const { t } = useTranslation('setting');
+ const [open, setOpen] = useState(false);
+
+ return (
+ <Flexbox gap={4} paddingBlock={4}>
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Icon icon={TriangleAlert} size={14} />
+ <Text fontSize={13} type={'secondary'}>
+ {summary}
+ </Text>
+ {onRetry && (
+ <Button size={'small'} type={'text'} onClick={onRetry}>
+ {t('identity.retry')}
+ </Button>
+ )}
+ {detail && (
+ <Button size={'small'} type={'text'} onClick={() => setOpen(!open)}>
+ {open ? t('identity.hideDetail') : t('identity.showDetail')}
+ </Button>
+ )}
+ </Flexbox>
+ {open && detail && (
+ <Text fontSize={12} style={{ wordBreak: 'break-all' }} type={'secondary'}>
+ {detail}
+ </Text>
+ )}
+ </Flexbox>
+ );
+});
+
+InlineError.displayName = 'AgentIdentityInlineError';
+
+export default InlineError;
diff --git a/src/features/AgentSetting/AgentIdentity/ProvisionCard.tsx b/src/features/AgentSetting/AgentIdentity/ProvisionCard.tsx
new file mode 100644
index 00000000000..72fa122abd4
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/ProvisionCard.tsx
@@ -0,0 +1,79 @@
+'use client';
+
+import { Button, Flexbox, Icon, Input, Text } from '@lobehub/ui';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { IdentityChannel } from './const';
+import { identityStyles } from './styles';
+import { useAccountActions } from './useIdentityActions';
+
+interface ProvisionCardProps {
+ agentId: string;
+ channel: IdentityChannel;
+ disabled?: boolean;
+ onProvisioned: () => Promise<unknown> | void;
+}
+
+/**
+ * A channel the agent does not have yet: what opening one gives it, an
+ * optional handle to ask for, and the one action that opens it.
+ *
+ * Opening is an explicit, user-initiated act — nothing here provisions on
+ * mount, because an address is a commitment (it starts accepting mail) and not
+ * a default.
+ */
+const ProvisionCard = memo<ProvisionCardProps>(({ agentId, channel, disabled, onProvisioned }) => {
+ const { t } = useTranslation('setting');
+ const [prefix, setPrefix] = useState('');
+ const [loading, setLoading] = useState(false);
+ const { provision } = useAccountActions({ agentId, onChanged: onProvisioned });
+
+ const handleProvision = async () => {
+ setLoading(true);
+ try {
+ const account = await provision(channel, prefix);
+ if (account) setPrefix('');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Flexbox className={identityStyles.card} gap={10}>
+ <Flexbox horizontal align={'flex-start'} gap={12}>
+ <Icon className={identityStyles.icon} icon={channel.icon} size={18} />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Text weight={500}>{t(channel.titleKey)}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t(channel.descKey)}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal gap={8}>
+ {channel.prefixable && (
+ <Input
+ disabled={disabled || loading}
+ placeholder={t('identity.prefix.placeholder')}
+ value={prefix}
+ variant={'filled'}
+ onChange={(e) => setPrefix(e.target.value)}
+ onPressEnter={handleProvision}
+ />
+ )}
+ <Button disabled={disabled} loading={loading} type={'fill'} onClick={handleProvision}>
+ {t('identity.provision')}
+ </Button>
+ </Flexbox>
+ {channel.prefixable && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('identity.prefix.hint')}
+ </Text>
+ )}
+ </Flexbox>
+ );
+});
+
+ProvisionCard.displayName = 'AgentIdentityProvisionCard';
+
+export default ProvisionCard;
diff --git a/src/features/AgentSetting/AgentIdentity/SectionHeader.tsx b/src/features/AgentSetting/AgentIdentity/SectionHeader.tsx
new file mode 100644
index 00000000000..e4df5f54f46
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/SectionHeader.tsx
@@ -0,0 +1,29 @@
+'use client';
+
+import { Flexbox, Text } from '@lobehub/ui';
+import { memo, type ReactNode } from 'react';
+
+interface SectionHeaderProps {
+ desc: string;
+ /** Status or the action that belongs to this section, kept on the title row. */
+ extra?: ReactNode;
+ title: string;
+}
+
+const SectionHeader = memo<SectionHeaderProps>(({ title, desc, extra }) => (
+ <Flexbox gap={2}>
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <Text fontSize={14} weight={600}>
+ {title}
+ </Text>
+ {extra}
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {desc}
+ </Text>
+ </Flexbox>
+));
+
+SectionHeader.displayName = 'AgentIdentitySectionHeader';
+
+export default SectionHeader;
diff --git a/src/features/AgentSetting/AgentIdentity/const.test.ts b/src/features/AgentSetting/AgentIdentity/const.test.ts
new file mode 100644
index 00000000000..88242d2d7b2
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/const.test.ts
@@ -0,0 +1,32 @@
+import { AGENT_ACCOUNT_PERSISTED_KINDS } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { IDENTITY_CHANNELS, isChannelAccount, isUnchanneledAccount,KIND_ICONS } from './const';
+
+const mailChannel = IDENTITY_CHANNELS.find((channel) => channel.provider === 'agent-mail')!;
+
+describe('isChannelAccount', () => {
+ it('claims an Agent Mail account for the Agent Mail channel', () => {
+ expect(isChannelAccount({ kind: 'mail', provider: 'agent-mail' }, mailChannel)).toBe(true);
+ });
+
+ it('does not treat a mailbox mounted through another provider as Agent Mail', () => {
+ expect(isChannelAccount({ kind: 'mail', provider: 'user' }, mailChannel)).toBe(false);
+ });
+});
+
+describe('KIND_ICONS', () => {
+ it('covers every persisted kind, retired ones included', () => {
+ // An unfiltered list still returns retired-kind rows so their owner can
+ // release them; a missing entry would hand `undefined` to `Icon`'s
+ // required prop and blank the row out.
+ expect(Object.keys(KIND_ICONS).sort()).toEqual([...AGENT_ACCOUNT_PERSISTED_KINDS].sort());
+ expect(KIND_ICONS.phone).toBeDefined();
+ });
+});
+
+describe('isUnchanneledAccount', () => {
+ it('leaves a retired-kind account unchanneled instead of claiming a channel', () => {
+ expect(isUnchanneledAccount({ kind: 'phone', provider: 'linq' })).toBe(true);
+ });
+});
diff --git a/src/features/AgentSetting/AgentIdentity/const.tsx b/src/features/AgentSetting/AgentIdentity/const.tsx
new file mode 100644
index 00000000000..2211c6959e4
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/const.tsx
@@ -0,0 +1,61 @@
+import type { AgentAccountKind, AgentAccountPersistedKind } from '@lobechat/types';
+import type { LucideIcon } from 'lucide-react';
+import { KeyRound, Mail, Phone, Wallet } from 'lucide-react';
+
+/**
+ * One address channel the identity tab can open.
+ *
+ * The pair (kind, provider) is what the control plane is asked for; the icon
+ * and copy are presentation. `prefixable` marks the channels where the caller
+ * may ask for a specific handle (a mailbox local part, for example); a channel
+ * whose handles the provider mints on its own leaves it off.
+ */
+export interface IdentityChannel {
+ descKey: 'identity.mail.desc';
+ icon: LucideIcon;
+ kind: AgentAccountKind;
+ prefixable: boolean;
+ provider: string;
+ titleKey: 'identity.mail.title';
+}
+
+export const IDENTITY_CHANNELS: IdentityChannel[] = [
+ {
+ descKey: 'identity.mail.desc',
+ icon: Mail,
+ kind: 'mail',
+ prefixable: true,
+ provider: 'agent-mail',
+ titleKey: 'identity.mail.title',
+ },
+];
+
+/**
+ * Whether an account belongs to a channel. A channel is the (kind, provider)
+ * pair, so a mailbox mounted through another provider (say `user`) is not the
+ * Agent Mail channel and must not hide its provisioning card.
+ */
+export const isChannelAccount = (
+ account: { kind: AgentAccountPersistedKind; provider: string },
+ channel: Pick<IdentityChannel, 'kind' | 'provider'>,
+): boolean => account.kind === channel.kind && account.provider === channel.provider;
+
+/**
+ * Icon for an account that belongs to no built-in channel (a mounted address).
+ *
+ * Keyed by every *persisted* kind, not just the creatable ones: an unfiltered
+ * list still shows the retired `phone` accounts so they can be released, and a
+ * missing entry would hand `undefined` to `Icon`'s required prop.
+ */
+export const KIND_ICONS: Record<AgentAccountPersistedKind, LucideIcon> = {
+ mail: Mail,
+ phone: Phone,
+ service: KeyRound,
+ wallet: Wallet,
+};
+
+/** Accounts no built-in channel claims — mounted ones, or providers this tab does not offer. */
+export const isUnchanneledAccount = (account: {
+ kind: AgentAccountPersistedKind;
+ provider: string;
+}): boolean => !IDENTITY_CHANNELS.some((channel) => isChannelAccount(account, channel));
diff --git a/src/features/AgentSetting/AgentIdentity/identityUi.test.tsx b/src/features/AgentSetting/AgentIdentity/identityUi.test.tsx
new file mode 100644
index 00000000000..45807ccebeb
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/identityUi.test.tsx
@@ -0,0 +1,296 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { SWRConfig } from 'swr';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const service = vi.hoisted(() => ({
+ getInboxMessage: vi.fn(),
+ getInboxUnreadCount: vi.fn(),
+ list: vi.fn(),
+ listInbox: vi.fn(),
+ markAllInboxRead: vi.fn(),
+ markInboxRead: vi.fn(),
+ revoke: vi.fn(),
+}));
+vi.mock('@/services/agentAccount', () => ({ agentAccountService: service }));
+
+// No provider configured: only already-owned addresses render.
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (selector: (state: unknown) => unknown) =>
+ selector({ serverConfig: { agentIdentityProviders: [] } }),
+}));
+
+const ui = vi.hoisted(() => ({ confirmModal: vi.fn(), createModal: vi.fn() }));
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ confirmModal: ui.confirmModal,
+ createModal: ui.createModal,
+}));
+
+const { IDENTITY_CHANNELS } = await import('./const');
+const { default: AccountCard } = await import('./AccountCard');
+const { default: InboxMessageModal } = await import('./InboxMessageModal');
+const { default: InboxSection } = await import('./InboxSection');
+const { default: IdentityAccounts } = await import('./IdentityAccounts');
+const { INBOX_REFRESH_INTERVAL_MS, useAgentAccounts } = await import('./useAgentIdentity');
+
+const fresh = (node: React.ReactNode) =>
+ render(<SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>{node}</SWRConfig>);
+
+const mailChannel = IDENTITY_CHANNELS.find((channel) => channel.kind === 'mail')!;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('InboxMessageModal', () => {
+ it('shows a retryable error instead of a skeleton that never resolves', async () => {
+ service.getInboxMessage.mockRejectedValueOnce(new Error('network down'));
+
+ fresh(<InboxMessageModal id={'msg_1'} />);
+
+ expect(await screen.findByText('identity.inbox.detail.loadFailed')).toBeInTheDocument();
+ });
+});
+
+describe('IdentityAccounts', () => {
+ it('shows a mounted address that no built-in channel claims, so it can be released', async () => {
+ service.list.mockResolvedValue([
+ {
+ agentId: 'agt_1',
+ capabilities: { receive: true, send: true },
+ displayName: null,
+ id: 'acc_user',
+ identifier: '[email protected]',
+ kind: 'mail',
+ provider: 'user',
+ status: 'active',
+ },
+ ]);
+
+ fresh(<IdentityAccounts agentId={'agt_1'} />);
+
+ expect(await screen.findByText('[email protected]')).toBeInTheDocument();
+ // Its provider stands in for the channel title, and it is releasable.
+ expect(screen.getByText('user')).toBeInTheDocument();
+ fireEvent.click(screen.getAllByRole('button').at(-1)!);
+ expect(ui.confirmModal).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('IdentityAccounts — revalidation failure', () => {
+ it('keeps the addresses on screen when a later refresh fails', async () => {
+ service.list
+ .mockResolvedValueOnce([
+ {
+ agentId: 'agt_1',
+ capabilities: { receive: true, send: true },
+ displayName: null,
+ id: 'acc_user',
+ identifier: '[email protected]',
+ kind: 'mail',
+ provider: 'user',
+ status: 'active',
+ },
+ ])
+ .mockRejectedValue(new Error('network down'));
+ let revalidate: () => Promise<unknown> = async () => {};
+ const Probe = () => {
+ const { mutate } = (useAgentAccounts as any)('agt_1');
+ revalidate = mutate;
+ return null;
+ };
+
+ fresh(
+ <>
+ <IdentityAccounts agentId={'agt_1'} />
+ <Probe />
+ </>,
+ );
+ expect(await screen.findByText('[email protected]')).toBeInTheDocument();
+
+ await revalidate().catch(() => {});
+
+ expect(await screen.findByText('identity.loadFailed')).toBeInTheDocument();
+ expect(screen.getByText('[email protected]')).toBeInTheDocument();
+ });
+});
+
+describe('InboxMessageModal attachments', () => {
+ it('lists what an attachment-only message carried instead of a blank body', async () => {
+ service.getInboxMessage.mockResolvedValue({
+ attachments: [
+ { contentType: 'image/jpeg', filename: 'photo.jpg', index: 0, size: 2_516_582 },
+ { contentType: 'application/pdf', index: 1 },
+ ],
+ from: '+15550001111',
+ id: 'msg_photo',
+ receivedAt: new Date('2026-10-02T00:00:00Z'),
+ subject: null,
+ text: '',
+ });
+
+ fresh(<InboxMessageModal id={'msg_photo'} />);
+
+ // Named by file (or type) and size; nothing is fetched from the provider,
+ // so the list neither links nor previews what an outside sender sent.
+ expect(await screen.findByText('photo.jpg · 2.4 MB')).toBeInTheDocument();
+ expect(screen.getByText('application/pdf')).toBeInTheDocument();
+ expect(screen.queryByRole('link')).toBeNull();
+ expect(screen.queryByRole('img')).toBeNull();
+ });
+});
+
+describe('AccountCard', () => {
+ it('cannot release an address from a read-only view', () => {
+ fresh(
+ <AccountCard
+ disabled
+ account={{ id: 'acc_1', identifier: '[email protected]', status: 'active' } as any}
+ agentId={'agt_1'}
+ channel={mailChannel}
+ onChanged={vi.fn()}
+ />,
+ );
+
+ // Copy comes first; the release action is the card's last control.
+ const release = screen.getAllByRole('button').at(-1)!;
+ fireEvent.click(release);
+
+ expect(ui.confirmModal).not.toHaveBeenCalled();
+ expect(service.revoke).not.toHaveBeenCalled();
+ });
+});
+
+describe('InboxSection', () => {
+ const rows = [
+ {
+ id: 'msg_1',
+ readAt: null,
+ receivedAt: new Date('2026-10-02T00:00:00Z'),
+ subject: 'Lunch?',
+ },
+ ];
+
+ it('reports the server unread count, not the dots on the loaded page', async () => {
+ service.listInbox.mockResolvedValue(rows);
+ service.getInboxUnreadCount.mockResolvedValue(73);
+
+ fresh(<InboxSection agentId={'agt_1'} />);
+
+ await waitFor(() => expect(service.getInboxUnreadCount).toHaveBeenCalledWith('agt_1'));
+ expect(await screen.findByText('identity.inbox.unread')).toBeInTheDocument();
+ });
+
+ it('opens a message from the keyboard', async () => {
+ service.listInbox.mockResolvedValue(rows);
+ service.getInboxUnreadCount.mockResolvedValue(1);
+ service.markInboxRead.mockResolvedValue({ count: 1 });
+
+ fresh(<InboxSection agentId={'agt_1'} />);
+
+ const row = await screen.findByRole('button', { name: /[email protected]/ });
+ expect(row).toHaveAttribute('tabindex', '0');
+
+ fireEvent.keyDown(row, { key: 'Enter' });
+
+ await waitFor(() => expect(ui.createModal).toHaveBeenCalledTimes(1));
+ expect(service.markInboxRead).toHaveBeenCalledWith(['msg_1']);
+ });
+
+ it('pages older mail with a cursor instead of an ever-growing limit', async () => {
+ const page = (offset: number, size: number) =>
+ Array.from({ length: size }, (_, i) => ({
+ from: `sender${offset + i}@example.com`,
+ id: `msg_${offset + i}`,
+ readAt: new Date('2026-10-02T00:00:00Z'),
+ receivedAt: new Date(Date.UTC(2026, 9, 2, 0, 0, 0) - (offset + i) * 1000),
+ subject: `Mail ${offset + i}`,
+ }));
+ const first = page(0, 50);
+ const second = page(50, 50);
+ service.listInbox.mockImplementation(async ({ before }: { before?: unknown }) =>
+ before ? ((before as any).id === 'msg_49' ? second : page(100, 3)) : first,
+ );
+ service.getInboxUnreadCount.mockResolvedValue(0);
+
+ fresh(<InboxSection agentId={'agt_1'} />);
+
+ // Two clicks: beyond the server's 100-row cap if the window just grew.
+ fireEvent.click(await screen.findByRole('button', { name: 'identity.inbox.loadMore' }));
+ await screen.findByRole('button', { name: /[email protected]/ });
+ fireEvent.click(screen.getByRole('button', { name: 'identity.inbox.loadMore' }));
+ await screen.findByRole('button', { name: /[email protected]/ });
+
+ const limits = service.listInbox.mock.calls.map(([params]) => params.limit);
+ expect(Math.max(...limits)).toBe(50);
+ expect(service.listInbox).toHaveBeenCalledWith(
+ expect.objectContaining({ before: { id: 'msg_49', receivedAt: first[49].receivedAt } }),
+ );
+ // The short third page ends the list.
+ expect(screen.queryByRole('button', { name: 'identity.inbox.loadMore' })).toBeNull();
+ });
+
+ it('keeps the loaded messages when an older page fails, with a retry below them', async () => {
+ const first = Array.from({ length: 50 }, (_, i) => ({
+ from: `sender${i}@example.com`,
+ id: `msg_${i}`,
+ readAt: new Date('2026-10-02T00:00:00Z'),
+ receivedAt: new Date(Date.UTC(2026, 9, 2) - i * 1000),
+ subject: `Mail ${i}`,
+ }));
+ service.listInbox.mockImplementation(async ({ before }: { before?: unknown }) => {
+ if (before) throw new Error('older page failed');
+ return first;
+ });
+ service.getInboxUnreadCount.mockResolvedValue(0);
+
+ fresh(<InboxSection agentId={'agt_1'} />);
+
+ fireEvent.click(await screen.findByRole('button', { name: 'identity.inbox.loadMore' }));
+
+ expect(await screen.findByText('identity.inbox.loadFailed')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /[email protected]/ })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /[email protected]/ })).toBeInTheDocument();
+ });
+
+ it('reports a failed refresh when the cached inbox is empty', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ service.listInbox.mockResolvedValueOnce([]).mockRejectedValue(new Error('inbox unavailable'));
+ service.getInboxUnreadCount.mockResolvedValue(0);
+
+ fresh(<InboxSection agentId={'agt_1'} />);
+ await screen.findByText('identity.inbox.empty');
+
+ await vi.advanceTimersByTimeAsync(INBOX_REFRESH_INTERVAL_MS + 100);
+
+ // An unreachable inbox must not read as an empty one.
+ expect(await screen.findByText('identity.inbox.loadFailed')).toBeInTheDocument();
+ expect(screen.getByText('identity.inbox.empty')).toBeInTheDocument();
+ vi.useRealTimers();
+ });
+
+ it('picks up a delivery that lands while the tab stays open', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ service.listInbox.mockResolvedValueOnce(rows).mockResolvedValue([
+ {
+ id: 'msg_2',
+ readAt: null,
+ receivedAt: new Date('2026-10-02T00:01:00Z'),
+ subject: 'Your code',
+ },
+ ...rows,
+ ]);
+ service.getInboxUnreadCount.mockResolvedValue(1);
+
+ fresh(<InboxSection agentId={'agt_1'} />);
+ await screen.findByRole('button', { name: /[email protected]/ });
+
+ await vi.advanceTimersByTimeAsync(INBOX_REFRESH_INTERVAL_MS + 100);
+
+ expect(await screen.findByRole('button', { name: /[email protected]/ })).toBeInTheDocument();
+ vi.useRealTimers();
+ });
+});
diff --git a/src/features/AgentSetting/AgentIdentity/index.tsx b/src/features/AgentSetting/AgentIdentity/index.tsx
new file mode 100644
index 00000000000..86d3bb2b257
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/index.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useStore } from '../store';
+import IdentityAccounts from './IdentityAccounts';
+import InboxSection from './InboxSection';
+
+/**
+ * The identity tab: which addresses this agent owns, and what has arrived.
+ *
+ * Two sections rather than two tabs, because they answer one question — "is
+ * anyone reaching this agent, and through what?" — and the inbox is only
+ * meaningful next to the addresses that received it.
+ */
+const AgentIdentity = memo(() => {
+ const { t } = useTranslation('setting');
+ const [id, disabled] = useStore((s) => [s.id, s.disabled]);
+
+ if (!id) {
+ return (
+ <Flexbox flex={1} style={{ color: 'var(--lobe-colors-text-tertiary)', fontSize: 13 }}>
+ {t('identity.noAgent')}
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox gap={24} paddingBlock={16}>
+ <IdentityAccounts agentId={id} disabled={disabled} />
+ <InboxSection agentId={id} />
+ </Flexbox>
+ );
+});
+
+AgentIdentity.displayName = 'AgentIdentity';
+
+export default AgentIdentity;
diff --git a/src/features/AgentSetting/AgentIdentity/styles.ts b/src/features/AgentSetting/AgentIdentity/styles.ts
new file mode 100644
index 00000000000..7f238e594a4
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/styles.ts
@@ -0,0 +1,58 @@
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * Shared surfaces for the identity tab.
+ *
+ * Filled-and-rounded rather than outlined: a border here would read as a
+ * card-inside-a-card boundary (the settings panel is already the container),
+ * and the accounts are a list of peers, not separate panels.
+ */
+const definitions = stylex.create({
+ card: {
+ paddingBlock: '12px',
+ paddingInline: '14px',
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+ empty: {
+ fontSize: '13px',
+ lineHeight: 1.6,
+ color: cssVar.colorTextTertiary,
+ textAlign: 'center',
+ },
+ icon: {
+ flexShrink: 0,
+ color: cssVar.colorTextSecondary,
+ },
+ inboxRow: {
+ cursor: 'pointer',
+ paddingBlock: '10px',
+ paddingInline: '14px',
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: {
+ 'default': cssVar.colorFillQuaternary,
+ ':hover': cssVar.colorFillTertiary,
+ },
+ },
+ subject: {
+ fontSize: '13px',
+ color: cssVar.colorTextSecondary,
+ },
+ unreadDot: {
+ flexShrink: 0,
+ width: '7px',
+ height: '7px',
+ borderRadius: '50%',
+ backgroundColor: cssVar.colorPrimary,
+ },
+});
+
+export const identityStyles = {
+ card: stylex.props(definitions.card).className ?? '',
+ empty: stylex.props(definitions.empty).className ?? '',
+ icon: stylex.props(definitions.icon).className ?? '',
+ inboxRow: stylex.props(definitions.inboxRow).className ?? '',
+ subject: stylex.props(definitions.subject).className ?? '',
+ unreadDot: stylex.props(definitions.unreadDot).className ?? '',
+};
diff --git a/src/features/AgentSetting/AgentIdentity/useAgentIdentity.test.ts b/src/features/AgentSetting/AgentIdentity/useAgentIdentity.test.ts
new file mode 100644
index 00000000000..3e40a288f11
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/useAgentIdentity.test.ts
@@ -0,0 +1,72 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type ReactNode } from 'react';
+import { SWRConfig } from 'swr';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const service = vi.hoisted(() => ({ listInbox: vi.fn() }));
+vi.mock('@/services/agentAccount', () => ({ agentAccountService: service }));
+
+const { INBOX_PAGE_SIZE, useAgentInbox } = await import('./useAgentIdentity');
+
+const page = (count: number) =>
+ Array.from({ length: count }, (_, i) => ({ from: `sender${i}@example.com`, id: `msg_${i}` }));
+
+/** A fresh cache per test, so one case cannot answer another's read. */
+const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('useAgentInbox', () => {
+ it('reads the newest page first', async () => {
+ service.listInbox.mockResolvedValue(page(3));
+
+ const { result } = renderHook(() => useAgentInbox('agt_1'), { wrapper });
+
+ await waitFor(() => expect(result.current.data).toHaveLength(3));
+ expect(service.listInbox).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ before: undefined,
+ limit: INBOX_PAGE_SIZE,
+ });
+ });
+
+ it('asks for the next page after the last row it has, never more than one page', async () => {
+ const first = page(INBOX_PAGE_SIZE).map((row, i) => ({
+ ...row,
+ receivedAt: new Date(Date.UTC(2026, 9, 2) - i * 1000),
+ }));
+ service.listInbox.mockImplementation(async ({ before }: { before?: unknown }) =>
+ before ? page(INBOX_PAGE_SIZE) : first,
+ );
+
+ const { result } = renderHook(() => useAgentInbox('agt_1'), { wrapper });
+
+ // A page that came back full means the inbox may hold older mail, so the
+ // reader is offered a way to reach it instead of a silent cut-off.
+ await waitFor(() => expect(result.current.hasMore).toBe(true));
+
+ act(() => result.current.loadMore());
+
+ const last = first.at(-1)!;
+ await waitFor(() =>
+ expect(service.listInbox).toHaveBeenLastCalledWith({
+ agentId: 'agt_1',
+ before: { id: last.id, receivedAt: last.receivedAt },
+ limit: INBOX_PAGE_SIZE,
+ }),
+ );
+ expect(result.current.data).toHaveLength(INBOX_PAGE_SIZE * 2);
+ });
+
+ it('reports nothing more when the window came back short', async () => {
+ service.listInbox.mockResolvedValue(page(INBOX_PAGE_SIZE - 1));
+
+ const { result } = renderHook(() => useAgentInbox('agt_1'), { wrapper });
+
+ await waitFor(() => expect(result.current.data).toHaveLength(INBOX_PAGE_SIZE - 1));
+ expect(result.current.hasMore).toBe(false);
+ });
+});
diff --git a/src/features/AgentSetting/AgentIdentity/useAgentIdentity.ts b/src/features/AgentSetting/AgentIdentity/useAgentIdentity.ts
new file mode 100644
index 00000000000..1323a98f68c
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/useAgentIdentity.ts
@@ -0,0 +1,74 @@
+import type { AgentInboxMessageSummary } from '@lobechat/types';
+import useSWR from 'swr';
+import useSWRInfinite from 'swr/infinite';
+
+import { agentAccountService } from '@/services/agentAccount';
+
+const accountsKey = (agentId: string): [string, string] | null =>
+ agentId ? ['agent-accounts', agentId] : null;
+
+/** One page of the inbox. Stays under the server's per-request cap (100). */
+export const INBOX_PAGE_SIZE = 50;
+
+/**
+ * Deliveries land from outside — a webhook, not this tab — so a person
+ * watching for a verification email must see it without refocusing the
+ * window. SWR pauses the poll while the tab is hidden.
+ */
+export const INBOX_REFRESH_INTERVAL_MS = 30_000;
+
+/** The addresses this agent owns. */
+export const useAgentAccounts = (agentId: string) =>
+ useSWR(accountsKey(agentId), ([, id]) => agentAccountService.list({ agentId: id }));
+
+/**
+ * What has arrived at those addresses, newest first.
+ *
+ * Paged by a keyset cursor (the last row of the previous page), so every
+ * request asks for one fixed-size page however far back the user scrolls,
+ * and rows already on screen stay where they are.
+ */
+export const useAgentInbox = (agentId: string) => {
+ const inbox = useSWRInfinite(
+ (pageIndex, previous: AgentInboxMessageSummary[] | null) => {
+ if (!agentId) return null;
+ if (pageIndex === 0) return ['agent-inbox', agentId, null] as const;
+ const last = previous?.at(-1);
+ // The previous page came back short: there is nothing older to ask for.
+ if (!last || previous!.length < INBOX_PAGE_SIZE) return null;
+ return ['agent-inbox', agentId, { id: last.id, receivedAt: last.receivedAt }] as const;
+ },
+ ([, id, before]) =>
+ agentAccountService.listInbox({
+ agentId: id,
+ before: before ?? undefined,
+ limit: INBOX_PAGE_SIZE,
+ }),
+ { refreshInterval: INBOX_REFRESH_INTERVAL_MS },
+ );
+
+ const pages = inbox.data;
+ const lastPage = pages?.at(-1);
+
+ return {
+ data: pages?.flat(),
+ error: inbox.error,
+ /** The last page came back full, so the inbox may hold older mail. */
+ hasMore: (lastPage?.length ?? 0) >= INBOX_PAGE_SIZE,
+ isLoading: inbox.isLoading,
+ /** Fetch the next page without disturbing what is already on screen. */
+ loadMore: () => void inbox.setSize((size) => size + 1),
+ mutate: inbox.mutate,
+ };
+};
+
+/**
+ * The server's unread count. The list above stops at its current window, so
+ * counting its unread dots would under-report a busy inbox.
+ */
+export const useAgentInboxUnreadCount = (agentId: string) =>
+ useSWR(
+ agentId ? ['agent-inbox-unread', agentId] : null,
+ ([, id]) => agentAccountService.getInboxUnreadCount(id),
+ { refreshInterval: INBOX_REFRESH_INTERVAL_MS },
+ );
diff --git a/src/features/AgentSetting/AgentIdentity/useIdentityActions.test.ts b/src/features/AgentSetting/AgentIdentity/useIdentityActions.test.ts
new file mode 100644
index 00000000000..2c3063bb551
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/useIdentityActions.test.ts
@@ -0,0 +1,138 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const service = vi.hoisted(() => ({
+ markAllInboxRead: vi.fn(),
+ markInboxRead: vi.fn(),
+ provision: vi.fn(),
+ revoke: vi.fn(),
+}));
+
+const ui = vi.hoisted(() => ({
+ confirmModal: vi.fn(),
+ createModal: vi.fn(),
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock('@/services/agentAccount', () => ({ agentAccountService: service }));
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ confirmModal: ui.confirmModal,
+ createModal: ui.createModal,
+ toast: ui.toast,
+}));
+
+const { IDENTITY_CHANNELS } = await import('./const');
+const { useAccountActions, useInboxActions } = await import('./useIdentityActions');
+
+const mailChannel = IDENTITY_CHANNELS.find((channel) => channel.kind === 'mail')!;
+/** The mail channel with the prefix preference switched off. */
+const unprefixableChannel = { ...mailChannel, prefixable: false };
+
+const mailAccount = { id: 'acc_mail', identifier: '[email protected]' } as any;
+const unreadMessage = { id: 'msg_1', readAt: null } as any;
+const readMessage = { id: 'msg_2', readAt: new Date('2026-10-02T02:00:00Z') } as any;
+
+const lastConfirm = () => ui.confirmModal.mock.calls.at(-1)![0] as { onOk: () => Promise<void> };
+
+describe('useAccountActions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ service.provision.mockResolvedValue({ id: 'acc_new', identifier: '[email protected]' });
+ service.revoke.mockResolvedValue({ id: 'acc_mail' });
+ });
+
+ it('forwards the trimmed prefix and revalidates the addresses', async () => {
+ const onChanged = vi.fn();
+ const { result } = renderHook(() => useAccountActions({ agentId: 'agt_1', onChanged }));
+
+ await result.current.provision(mailChannel, ' support ');
+
+ expect(service.provision).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ prefix: 'support',
+ provider: 'agent-mail',
+ });
+ expect(onChanged).toHaveBeenCalledTimes(1);
+ expect(ui.toast.success).toHaveBeenCalledTimes(1);
+ });
+
+ it('never sends a prefix down a channel that cannot honour one', async () => {
+ const { result } = renderHook(() =>
+ useAccountActions({ agentId: 'agt_1', onChanged: vi.fn() }),
+ );
+
+ await result.current.provision(unprefixableChannel, 'support');
+
+ expect(service.provision).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ prefix: undefined,
+ provider: 'agent-mail',
+ });
+ });
+
+ it("surfaces the provider's own reason and does not revalidate on failure", async () => {
+ service.provision.mockRejectedValueOnce(new Error('prefix "support" is taken'));
+ const onChanged = vi.fn();
+ const { result } = renderHook(() => useAccountActions({ agentId: 'agt_1', onChanged }));
+
+ await expect(result.current.provision(mailChannel, 'support')).resolves.toBeUndefined();
+
+ expect(onChanged).not.toHaveBeenCalled();
+ expect(ui.toast.error).toHaveBeenCalledTimes(1);
+ });
+
+ it('releases only after the confirmation is accepted', async () => {
+ const onChanged = vi.fn();
+ const { result } = renderHook(() => useAccountActions({ agentId: 'agt_1', onChanged }));
+
+ result.current.release(mailAccount);
+ expect(service.revoke).not.toHaveBeenCalled();
+
+ await lastConfirm().onOk();
+
+ expect(service.revoke).toHaveBeenCalledWith('acc_mail');
+ expect(onChanged).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('useInboxActions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ service.markAllInboxRead.mockResolvedValue({ count: 1 });
+ service.markInboxRead.mockResolvedValue({ count: 1 });
+ });
+
+ it('opens an unread message and clears its unread mark', async () => {
+ const onChanged = vi.fn();
+ const { result } = renderHook(() => useInboxActions({ agentId: 'agt_1', onChanged }));
+
+ await result.current.openMessage(unreadMessage);
+
+ expect(ui.createModal).toHaveBeenCalledTimes(1);
+ expect(service.markInboxRead).toHaveBeenCalledWith(['msg_1']);
+ expect(onChanged).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not re-stamp a message that was already read', async () => {
+ const onChanged = vi.fn();
+ const { result } = renderHook(() => useInboxActions({ agentId: 'agt_1', onChanged }));
+
+ await result.current.openMessage(readMessage);
+
+ expect(ui.createModal).toHaveBeenCalledTimes(1);
+ expect(service.markInboxRead).not.toHaveBeenCalled();
+ expect(onChanged).not.toHaveBeenCalled();
+ });
+
+ it('clears the whole inbox and revalidates', async () => {
+ const onChanged = vi.fn();
+ const { result } = renderHook(() => useInboxActions({ agentId: 'agt_1', onChanged }));
+
+ await result.current.markAllRead();
+
+ expect(service.markAllInboxRead).toHaveBeenCalledWith('agt_1');
+ expect(onChanged).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/AgentSetting/AgentIdentity/useIdentityActions.tsx b/src/features/AgentSetting/AgentIdentity/useIdentityActions.tsx
new file mode 100644
index 00000000000..90f793942bd
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/useIdentityActions.tsx
@@ -0,0 +1,135 @@
+'use client';
+
+import type { AgentInboxMessageSummary } from '@lobechat/types';
+import { confirmModal, createModal, toast } from '@lobehub/ui';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { agentAccountService, type AgentAccountView } from '@/services/agentAccount';
+
+import type { IdentityChannel } from './const';
+import InboxMessageModal from './InboxMessageModal';
+
+/** Open one stored message. Imperative because the trigger is a list row. */
+const openMessageModal = (id: string) =>
+ createModal({
+ content: <InboxMessageModal id={id} />,
+ footer: null,
+ maskClosable: true,
+ styles: {
+ content: { padding: 20 },
+ header: { display: 'none' },
+ },
+ width: 640,
+ });
+
+export interface UseAccountActionsParams {
+ agentId: string;
+ /** Revalidate the addresses after opening or releasing one. */
+ onChanged: () => Promise<unknown> | void;
+}
+
+/**
+ * Opening and releasing an address.
+ *
+ * Both end the same way — revalidate the list they changed — and both degrade
+ * the same way: a provider refusal is surfaced with the provider's own reason,
+ * never a generic failure, because "that prefix is taken" and "this deployment
+ * has no mailbox service" are different things for the user to act on.
+ */
+export const useAccountActions = ({ agentId, onChanged }: UseAccountActionsParams) => {
+ const { t } = useTranslation('setting');
+
+ const provision = useCallback(
+ async (channel: IdentityChannel, prefix: string) => {
+ // A provider that cannot honour a prefix must not be sent a meaningless
+ // one, so the preference is only forwarded down a prefixable channel.
+ const requested = channel.prefixable ? prefix.trim() : '';
+
+ try {
+ const account = await agentAccountService.provision({
+ agentId,
+ prefix: requested || undefined,
+ provider: channel.provider,
+ });
+ toast.success(t('identity.provision.success', { identifier: account.identifier }));
+ await onChanged();
+ return account;
+ } catch (error) {
+ console.error('[AgentIdentity] provision failed', error);
+ toast.error(
+ t('identity.provision.failed', {
+ reason: error instanceof Error ? error.message : String(error),
+ }),
+ );
+ return undefined;
+ }
+ },
+ [agentId, onChanged, t],
+ );
+
+ const release = useCallback(
+ (account: AgentAccountView) =>
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('identity.release.content', { identifier: account.identifier }),
+ okButtonProps: { danger: true },
+ okText: t('identity.release.confirm'),
+ onOk: async () => {
+ try {
+ await agentAccountService.revoke(account.id);
+ toast.success(t('identity.release.success'));
+ await onChanged();
+ } catch (error) {
+ console.error('[AgentIdentity] release failed', error);
+ toast.error(t('identity.release.failed'));
+ }
+ },
+ title: t('identity.release.title'),
+ }),
+ [onChanged, t],
+ );
+
+ return { provision, release };
+};
+
+export interface UseInboxActionsParams {
+ agentId: string;
+ /** Revalidate the inbox after its read state changes. */
+ onChanged: () => Promise<unknown> | void;
+}
+
+/** Reading the inbox: open one message, or clear the unread marks. */
+export const useInboxActions = ({ agentId, onChanged }: UseInboxActionsParams) => {
+ const { t } = useTranslation('setting');
+
+ const openMessage = useCallback(
+ async (message: Pick<AgentInboxMessageSummary, 'id' | 'readAt'>) => {
+ openMessageModal(message.id);
+
+ // Already read: opening it again must not re-stamp `readAt`.
+ if (message.readAt) return;
+
+ try {
+ await agentAccountService.markInboxRead([message.id]);
+ await onChanged();
+ } catch (error) {
+ // The message is already open; a failed read-mark only affects the dot.
+ console.error('[AgentIdentity] mark read failed', error);
+ }
+ },
+ [onChanged],
+ );
+
+ const markAllRead = useCallback(async () => {
+ try {
+ await agentAccountService.markAllInboxRead(agentId);
+ await onChanged();
+ } catch (error) {
+ console.error('[AgentIdentity] mark all read failed', error);
+ toast.error(t('identity.inbox.markAllReadFailed'));
+ }
+ }, [agentId, onChanged, t]);
+
+ return { markAllRead, openMessage };
+};
diff --git a/src/features/AgentSetting/AgentIdentity/useShowAgentIdentity.ts b/src/features/AgentSetting/AgentIdentity/useShowAgentIdentity.ts
new file mode 100644
index 00000000000..9502603a95a
--- /dev/null
+++ b/src/features/AgentSetting/AgentIdentity/useShowAgentIdentity.ts
@@ -0,0 +1,34 @@
+import { useAgentStore } from '@/store/agent';
+import { useServerConfigStore } from '@/store/serverConfig';
+import { serverConfigSelectors } from '@/store/serverConfig/selectors';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+import { useAgentAccounts } from './useAgentIdentity';
+
+/**
+ * Whether the identity tab has anything to offer: the user opted into the Labs
+ * experiment, and either this deployment can open an address (a provider is
+ * configured) or the agent already owns one.
+ *
+ * Provider availability only decides whether new addresses can be opened. An
+ * address that already exists must stay reachable after its provider's
+ * credentials are removed, so it can still be read, copied and released.
+ */
+export const useShowAgentIdentity = (): boolean => {
+ const enabled = useUserStore(labPreferSelectors.enableAgentIdentity);
+ const providers = useServerConfigStore(serverConfigSelectors.agentIdentityProviders);
+ const agentId = useAgentStore((s) => s.activeAgentId);
+
+ // Only ask for the agent's accounts when they are what decides it.
+ const needsAccounts = enabled && providers.length === 0 && !!agentId;
+ const { data: accounts, error } = useAgentAccounts(needsAccounts ? agentId! : '');
+
+ if (!enabled) return false;
+ if (providers.length > 0) return true;
+ // The read that decides it failed: the agent may own an address, so keep the
+ // tab — it shows the failure and a retry — rather than hide it on a guess.
+ if (error && !accounts) return true;
+
+ return (accounts ?? []).some((account) => account.status !== 'revoked');
+};
diff --git a/src/features/AgentSetting/AgentSettingsContent.tsx b/src/features/AgentSetting/AgentSettingsContent.tsx
index 01bcb34765e..410024e0f89 100644
--- a/src/features/AgentSetting/AgentSettingsContent.tsx
+++ b/src/features/AgentSetting/AgentSettingsContent.tsx
@@ -9,6 +9,8 @@ import { labPreferSelectors } from '@/store/user/selectors';
import AgentConnectors from './AgentConnectors';
import AgentGraphRuntime from './AgentGraphRuntime';
+import AgentIdentity from './AgentIdentity';
+import { useShowAgentIdentity } from './AgentIdentity/useShowAgentIdentity';
import AgentOpening from './AgentOpening';
export interface AgentSettingsContentProps {
@@ -19,12 +21,14 @@ export interface AgentSettingsContentProps {
const AgentSettingsContent = memo<AgentSettingsContentProps>(({ tab, loadingSkeleton }) => {
const loading = useAgentStore(agentSelectors.isAgentConfigLoading);
const enableAgentGraphConfigLab = useUserStore(labPreferSelectors.enableAgentGraphConfig);
+ const showIdentity = useShowAgentIdentity();
if (loading) return loadingSkeleton;
return (
<>
{tab === ChatSettingsTabs.Opening && <AgentOpening />}
+ {showIdentity && tab === ChatSettingsTabs.Identity && <AgentIdentity />}
{enableAgentGraphConfigLab && tab === ChatSettingsTabs.Graph && <AgentGraphRuntime />}
{tab === ChatSettingsTabs.Connector && <AgentConnectors />}
</>
diff --git a/src/features/Settings/apikey/features/ApiKey.test.tsx b/src/features/Settings/apikey/features/ApiKey.test.tsx
index 2c136b2fa84..8d93a003f99 100644
--- a/src/features/Settings/apikey/features/ApiKey.test.tsx
+++ b/src/features/Settings/apikey/features/ApiKey.test.tsx
@@ -177,6 +177,32 @@ describe('ApiKey', () => {
expect(onSelectedChange).toHaveBeenCalledWith(['mcp:write', 'mcp:read']);
});
+ it('offers the account-credential scope with the agent scopes it relies on, without inventing a read twin', () => {
+ const onSelectedChange = vi.fn();
+ render(
+ <ScopeSelector
+ fullAccess={false}
+ selected={[]}
+ onFullAccessChange={vi.fn()}
+ onSelectedChange={onSelectedChange}
+ />,
+ );
+
+ const agentGroup = screen.getByText('apikey.scopes.groups.agent').parentElement!;
+ // read + write + the separate high-risk credential tier
+ expect(within(agentGroup).getAllByRole('checkbox')).toHaveLength(3);
+
+ fireEvent.click(
+ within(agentGroup).getByRole('checkbox', { name: 'apikey.scopes.agentCredential' }),
+ );
+
+ // A credential write is still an agent write, so ticking it brings
+ // `agent:write` (and its read) along — but it must NOT derive the
+ // non-existent `agent:credential:read`, which the API would reject.
+ const [selected] = onSelectedChange.mock.calls.at(-1)!;
+ expect([...selected].sort()).toEqual(['agent:credential:write', 'agent:read', 'agent:write']);
+ });
+
it('shows loading, then empty state when the first fetch returns no keys', async () => {
let resolveList!: (items: ApiKeyItem[]) => void;
hoisted.trpc.getApiKeys.mockImplementation(
diff --git a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.test.ts b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.test.ts
new file mode 100644
index 00000000000..3420c1494e7
--- /dev/null
+++ b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+
+import { toggleScopeSelection } from './ScopeSelector';
+
+const sorted = (scopes: string[]) => [...scopes].sort();
+
+describe('toggleScopeSelection', () => {
+ it('adds the agent write and read scopes a credential write cannot work without', () => {
+ expect(sorted(toggleScopeSelection([], 'agent:credential:write', true))).toEqual([
+ 'agent:credential:write',
+ 'agent:read',
+ 'agent:write',
+ ]);
+ });
+
+ it('drops the credential write when the agent write or read it relies on is removed', () => {
+ const granted = toggleScopeSelection(['chat:read'], 'agent:credential:write', true);
+
+ expect(sorted(toggleScopeSelection(granted, 'agent:write', false))).toEqual([
+ 'agent:read',
+ 'chat:read',
+ ]);
+ expect(toggleScopeSelection(granted, 'agent:read', false)).toEqual(['chat:read']);
+ });
+
+ it('keeps write implying read, and a standalone scope standalone', () => {
+ expect(sorted(toggleScopeSelection([], 'chat:write', true))).toEqual([
+ 'chat:read',
+ 'chat:write',
+ ]);
+ expect(toggleScopeSelection([], 'model:invoke', true)).toEqual(['model:invoke']);
+ expect(toggleScopeSelection(['agent:read', 'agent:write'], 'agent:write', false)).toEqual([
+ 'agent:read',
+ ]);
+ });
+});
diff --git a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx
index 33f67bb3e21..ebfbd8fed26 100644
--- a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx
@@ -8,6 +8,7 @@ import type { FC } from 'react';
import { useTranslation } from 'react-i18next';
import type { ApiKeyScope } from '@/const/apiKeyScope';
+import { isValidApiKeyScope } from '@/const/apiKeyScope';
const styles = stylex.create({
disabled: { pointerEvents: 'none', opacity: 0.45 },
@@ -58,13 +59,35 @@ const styles = stylex.create({
/**
* Scope groups shown to the user. Most domains carry read and write scopes;
- * usage is intentionally read-only, while the model group additionally
- * carries the money-burning `model:invoke` tier.
+ * usage is intentionally read-only, while two domains carry an additional
+ * high-risk tier that is separate from plain write:
+ *
+ * - `model:invoke` burns money;
+ * - `agent:credential:write` installs a secret into one of an agent's
+ * accounts — managing the agent's accounts must not imply that.
*/
type ScopeGroupKey =
'agent' | 'chat' | 'file' | 'knowledge' | 'mcp' | 'model' | 'usage' | 'user' | 'workspace';
+/**
+ * Labels an extra scope can carry. Kept as literals (not `string`) so the
+ * `t()` calls stay inside the generated key union.
+ */
+type ScopeExtraLabel =
+ 'apikey.scopes.agentCredential' | 'apikey.scopes.invoke' | 'apikey.scopes.modelInvoke';
+
interface ScopeGroup {
+ /**
+ * A higher-risk scope in the same domain. It gets its own checkbox in the
+ * creation grid and its own entry in the granted-scopes overview; the two
+ * labels differ because the grid spells the act out while the overview lists
+ * grants next to "Read" / "Write".
+ */
+ readonly extra?: {
+ readonly createLabel: ScopeExtraLabel;
+ readonly overviewLabel: ScopeExtraLabel;
+ readonly scope: ApiKeyScope;
+ };
readonly key: ScopeGroupKey;
readonly label: `apikey.scopes.groups.${ScopeGroupKey}`;
readonly read: ApiKeyScope;
@@ -72,9 +95,29 @@ interface ScopeGroup {
}
const SCOPE_GROUPS: readonly ScopeGroup[] = [
- { key: 'agent', label: 'apikey.scopes.groups.agent', read: 'agent:read', write: 'agent:write' },
+ {
+ key: 'agent',
+ label: 'apikey.scopes.groups.agent',
+ read: 'agent:read',
+ write: 'agent:write',
+ extra: {
+ createLabel: 'apikey.scopes.agentCredential',
+ overviewLabel: 'apikey.scopes.agentCredential',
+ scope: 'agent:credential:write',
+ },
+ },
{ key: 'chat', label: 'apikey.scopes.groups.chat', read: 'chat:read', write: 'chat:write' },
- { key: 'model', label: 'apikey.scopes.groups.model', read: 'model:read', write: 'model:write' },
+ {
+ key: 'model',
+ label: 'apikey.scopes.groups.model',
+ read: 'model:read',
+ write: 'model:write',
+ extra: {
+ createLabel: 'apikey.scopes.modelInvoke',
+ overviewLabel: 'apikey.scopes.invoke',
+ scope: 'model:invoke',
+ },
+ },
{ key: 'file', label: 'apikey.scopes.groups.file', read: 'file:read', write: 'file:write' },
{
key: 'knowledge',
@@ -115,7 +158,7 @@ export const ScopeOverview: FC<ScopeOverviewProps> = ({ scopes }) => {
const actions = [
scopeSet.has(group.read) && t('apikey.scopes.read'),
group.write && scopeSet.has(group.write) && t('apikey.scopes.write'),
- group.key === 'model' && scopeSet.has('model:invoke') && t('apikey.scopes.invoke'),
+ group.extra && scopeSet.has(group.extra.scope) && t(group.extra.overviewLabel),
].filter(Boolean) as string[];
return actions.length > 0 ? [{ actions, key: group.key, label: t(group.label) }] : [];
@@ -147,6 +190,59 @@ export const ScopeOverview: FC<ScopeOverviewProps> = ({ scopes }) => {
);
};
+/**
+ * Scopes a scope cannot work without. The server enforces these pairs — a
+ * credential write is still an agent write — so a key holding the dependent
+ * scope alone would be refused on every call it advertises.
+ */
+const SCOPE_PREREQUISITES: Partial<Record<ApiKeyScope, readonly ApiKeyScope[]>> = {
+ 'agent:credential:write': ['agent:write'],
+};
+
+/** Each scope's prerequisites, with every `:write` needing its `:read` twin when one exists. */
+const prerequisitesOf = (scope: ApiKeyScope): ApiKeyScope[] => {
+ const required = [...(SCOPE_PREREQUISITES[scope] ?? [])];
+ if (scope.endsWith(':write')) {
+ const twin = scope.replace(/:write$/, ':read') as ApiKeyScope;
+ if (isValidApiKeyScope(twin)) required.push(twin);
+ }
+ return required;
+};
+
+/**
+ * The selection after toggling one scope. Checking adds everything it needs;
+ * unchecking drops everything that needed it, so the grid never shows a scope
+ * the key could not actually use.
+ */
+export const toggleScopeSelection = (
+ selected: readonly ApiKeyScope[],
+ scope: ApiKeyScope,
+ checked: boolean,
+): ApiKeyScope[] => {
+ const next = new Set(selected);
+
+ if (checked) {
+ const pending = [scope];
+ while (pending.length > 0) {
+ const current = pending.pop()!;
+ if (next.has(current) && current !== scope) continue;
+ next.add(current);
+ pending.push(...prerequisitesOf(current));
+ }
+ } else {
+ const pending = [scope];
+ while (pending.length > 0) {
+ const current = pending.pop()!;
+ next.delete(current);
+ for (const candidate of next) {
+ if (prerequisitesOf(candidate).includes(current)) pending.push(candidate);
+ }
+ }
+ }
+
+ return [...next];
+};
+
export interface ScopeSelectorProps {
fullAccess: boolean;
onFullAccessChange: (fullAccess: boolean) => void;
@@ -162,21 +258,8 @@ const ScopeSelector: FC<ScopeSelectorProps> = ({
}) => {
const { t } = useTranslation('auth');
const selectedSet = new Set(selected);
-
- const toggle = (scope: ApiKeyScope, checked: boolean) => {
- const next = new Set(selectedSet);
- if (checked) {
- next.add(scope);
- // write implies read — keep the UI honest about what the key can do
- if (scope.endsWith(':write')) next.add(scope.replace(/:write$/, ':read') as ApiKeyScope);
- } else {
- next.delete(scope);
- // dropping read also drops the write that implied it
- if (scope.endsWith(':read')) next.delete(scope.replace(/:read$/, ':write') as ApiKeyScope);
- }
-
- onSelectedChange([...next]);
- };
+ const toggle = (scope: ApiKeyScope, checked: boolean) =>
+ onSelectedChange(toggleScopeSelection(selected, scope, checked));
return (
<Flexbox gap={12}>
@@ -213,13 +296,13 @@ const ScopeSelector: FC<ScopeSelectorProps> = ({
{t('apikey.scopes.write')}
</Checkbox>
)}
- {group.key === 'model' && (
+ {group.extra && (
<Checkbox
- checked={selectedSet.has('model:invoke')}
+ checked={selectedSet.has(group.extra.scope)}
disabled={fullAccess}
- onChange={(checked) => toggle('model:invoke', checked)}
+ onChange={(checked) => group.extra && toggle(group.extra.scope, checked)}
>
- {t('apikey.scopes.modelInvoke')}
+ {t(group.extra.createLabel)}
</Checkbox>
)}
</Flexbox>
diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.ts
index 388d07c313c..ed3b46ffa17 100644
--- a/src/features/Settings/labs/features.ts
+++ b/src/features/Settings/labs/features.ts
@@ -15,6 +15,7 @@ export type LabStage = 'alpha' | 'beta';
*/
type LabFeatureI18nKey =
| 'agentGraphConfig'
+ | 'agentIdentity'
| 'artifactDeployment'
| 'claudeCodeSdk'
| 'codexAppServer'
@@ -64,6 +65,12 @@ const ALL_LAB_FEATURES: LabFeatureItem[] = [
searchKeywords: ['agent graph', 'graph runtime'],
stage: 'alpha',
},
+ {
+ flag: 'enableAgentIdentity',
+ i18nKey: 'agentIdentity',
+ searchKeywords: ['agent identity', 'agent mail', 'inbox', 'address'],
+ stage: 'alpha',
+ },
{
flag: 'enableMessageTextSelectionActions',
i18nKey: 'messageTextSelectionActions',
diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx
index 62ba73a7c13..54b11ee4beb 100644
--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx
+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx
@@ -1,5 +1,6 @@
-import { render, screen } from '@testing-library/react';
+import { render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { SWRConfig } from 'swr';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ChatSettingsTabs } from '@/store/global/initialState';
@@ -16,7 +17,8 @@ const mocks = vi.hoisted(() => ({
optimisticUpdateAgentConfig: vi.fn(),
optimisticUpdateAgentMeta: vi.fn(),
},
- userState: { preference: { lab: { enableAgentGraphConfig: false } } },
+ serverState: { serverConfig: { agentIdentityProviders: [] as string[] } },
+ userState: { preference: { lab: { enableAgentGraphConfig: false, enableAgentIdentity: false } } },
}));
vi.mock('@/features/AgentSetting', () => ({
@@ -42,6 +44,9 @@ vi.mock('@/features/AgentSetting', () => ({
),
}));
+const accountService = vi.hoisted(() => ({ list: vi.fn(async () => [] as unknown[]) }));
+vi.mock('@/services/agentAccount', () => ({ agentAccountService: accountService }));
+
vi.mock('@/store/agent', () => {
const useAgentStore = (selector: (state: typeof mocks.agentState) => unknown) =>
selector(mocks.agentState);
@@ -62,6 +67,18 @@ vi.mock('@/store/agent/selectors', () => ({
},
}));
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (selector: (state: typeof mocks.serverState) => unknown) =>
+ selector(mocks.serverState),
+}));
+
+vi.mock('@/store/serverConfig/selectors', () => ({
+ serverConfigSelectors: {
+ agentIdentityProviders: (state: typeof mocks.serverState) =>
+ state.serverConfig.agentIdentityProviders,
+ },
+}));
+
vi.mock('@/store/user', () => ({
useUserStore: (selector: (state: typeof mocks.userState) => unknown) => selector(mocks.userState),
}));
@@ -70,6 +87,8 @@ vi.mock('@/store/user/selectors', () => ({
labPreferSelectors: {
enableAgentGraphConfig: (state: typeof mocks.userState) =>
state.preference.lab.enableAgentGraphConfig,
+ enableAgentIdentity: (state: typeof mocks.userState) =>
+ state.preference.lab.enableAgentIdentity,
},
}));
@@ -78,6 +97,8 @@ describe('AgentSettings Content', () => {
mocks.agentState.isInbox = true;
mocks.agentState.isCurrentAgentHeterogeneous = false;
mocks.userState.preference.lab.enableAgentGraphConfig = false;
+ mocks.userState.preference.lab.enableAgentIdentity = false;
+ mocks.serverState.serverConfig.agentIdentityProviders = [];
});
it('opens on the opening tab', () => {
@@ -111,4 +132,49 @@ describe('AgentSettings Content', () => {
expect(screen.getByTestId('layout')).toHaveAttribute('data-tabs', ChatSettingsTabs.Opening);
});
+
+ it('shows identity only with the Labs toggle on and a provider configured', () => {
+ mocks.serverState.serverConfig.agentIdentityProviders = ['agent-mail'];
+
+ const { unmount } = render(<Content />);
+ // A configured provider alone does not surface the experiment.
+ expect(screen.getByTestId('layout')).toHaveAttribute('data-tabs', ChatSettingsTabs.Opening);
+ unmount();
+
+ mocks.userState.preference.lab.enableAgentIdentity = true;
+ render(<Content />);
+ expect(screen.getByTestId('layout')).toHaveAttribute(
+ 'data-tabs',
+ `${ChatSettingsTabs.Opening},${ChatSettingsTabs.Identity}`,
+ );
+ });
+
+ it('hides identity when the deployment has no identity provider, even in Labs', () => {
+ mocks.userState.preference.lab.enableAgentIdentity = true;
+
+ render(<Content />);
+
+ expect(screen.getByTestId('layout')).toHaveAttribute('data-tabs', ChatSettingsTabs.Opening);
+ });
+
+ it('keeps identity reachable for an agent that already owns an address, even with no provider', async () => {
+ mocks.userState.preference.lab.enableAgentIdentity = true;
+ accountService.list.mockResolvedValueOnce([
+ { id: 'acc_1', identifier: '[email protected]', status: 'active' },
+ ]);
+
+ render(
+ <SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>
+ <Content />
+ </SWRConfig>,
+ );
+
+ await waitFor(() =>
+ expect(screen.getByTestId('layout')).toHaveAttribute(
+ 'data-tabs',
+ `${ChatSettingsTabs.Opening},${ChatSettingsTabs.Identity}`,
+ ),
+ );
+ expect(accountService.list).toHaveBeenCalledWith({ agentId: 'inbox-agent' });
+ });
});
diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
index 23c9fffc891..46d6d2cc300 100644
--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
@@ -2,7 +2,7 @@
import { DEFAULT_INBOX_TITLE } from '@lobechat/const';
import isEqual from 'fast-deep-equal';
-import { GitBranchIcon, MessageSquareHeartIcon } from 'lucide-react';
+import { GitBranchIcon, IdCardIcon, MessageSquareHeartIcon } from 'lucide-react';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { shallow } from 'zustand/shallow';
@@ -13,6 +13,7 @@ import {
SettingsModalLayout,
type SettingsModalTabItem,
} from '@/features/AgentSetting';
+import { useShowAgentIdentity } from '@/features/AgentSetting/AgentIdentity/useShowAgentIdentity';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
@@ -22,6 +23,7 @@ import { labPreferSelectors } from '@/store/user/selectors';
const TAB_META = {
[ChatSettingsTabs.Graph]: { icon: GitBranchIcon, labelKey: 'agentTab.graph' },
+ [ChatSettingsTabs.Identity]: { icon: IdCardIcon, labelKey: 'agentTab.identity' },
[ChatSettingsTabs.Opening]: { icon: MessageSquareHeartIcon, labelKey: 'agentTab.opening' },
} as const;
@@ -38,13 +40,16 @@ const Content = memo(() => {
const enableAgentGraphConfigLab = useUserStore(labPreferSelectors.enableAgentGraphConfig);
const [tab, setTab] = useState(ChatSettingsTabs.Opening);
const showGraphTab = enableAgentGraphConfigLab && !isInbox && !isHeterogeneous;
+ const showIdentityTab = useShowAgentIdentity();
const availableTabs = useMemo(
() =>
- [ChatSettingsTabs.Opening, showGraphTab ? ChatSettingsTabs.Graph : null].filter(
- Boolean,
- ) as ChatSettingsTabs[],
- [showGraphTab],
+ [
+ ChatSettingsTabs.Opening,
+ showIdentityTab ? ChatSettingsTabs.Identity : null,
+ showGraphTab ? ChatSettingsTabs.Graph : null,
+ ].filter(Boolean) as ChatSettingsTabs[],
+ [showGraphTab, showIdentityTab],
);
const activeTab = availableTabs.includes(tab) ? tab : availableTabs[0];
diff --git a/src/services/agentAccount.ts b/src/services/agentAccount.ts
new file mode 100644
index 00000000000..23f7f300f72
--- /dev/null
+++ b/src/services/agentAccount.ts
@@ -0,0 +1,112 @@
+import type {
+ AgentAccountKind,
+ AgentInboxMessage,
+ AgentInboxMessageSummary,
+} from '@lobechat/types';
+import type { inferRouterOutputs } from '@trpc/server';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import type { LambdaRouter } from '@/server/routers/lambda';
+
+type AgentAccountRouterOutputs = inferRouterOutputs<LambdaRouter>['agentAccount'];
+type InboxRow = AgentAccountRouterOutputs['inbox']['get'];
+
+/**
+ * One identity account as the control plane returns it. Derived from the router
+ * rather than restated, so the client can never drift from the contract; the
+ * credential is structurally absent, and `hasCredential` is all a read knows.
+ */
+export type AgentAccountView = AgentAccountRouterOutputs['list'][number];
+
+export interface ListAgentAccountsParams {
+ agentId?: string;
+ kind?: AgentAccountKind;
+ provider?: string;
+}
+
+export interface ProvisionAgentAccountParams {
+ agentId: string;
+ displayName?: string;
+ /** Preferred local part for a mail address; the provider may ignore it. */
+ prefix?: string;
+ provider: string;
+}
+
+export interface ListAgentInboxParams {
+ accountId?: string;
+ agentId: string;
+ /** Keyset cursor: the last row of the previous page. */
+ before?: { id: string; receivedAt: Date };
+ limit?: number;
+ unreadOnly?: boolean;
+}
+
+/** The detail read, normalized at the boundary into the client's read model. */
+const toInboxMessage = (row: InboxRow): AgentInboxMessage => ({
+ accountId: row.accountId,
+ agentId: row.agentId,
+ // An attachment-only message would otherwise open with a blank body and no
+ // trace of what was sent.
+ attachments: row.attachments ?? [],
+ codes: row.codes ?? [],
+ createdAt: row.createdAt,
+ from: row.from,
+ id: row.id,
+ preview: row.preview,
+ readAt: row.readAt,
+ receivedAt: row.receivedAt,
+ sourceType: row.sourceType,
+ subject: row.subject,
+ text: row.text,
+ threadKey: row.threadKey,
+ to: row.to,
+});
+
+/**
+ * Client for the agent-account control plane.
+ *
+ * Everything here maps 1:1 onto `agentAccount` tRPC procedures — no client-side
+ * orchestration, no cached identity: the accounts and the inbox both change
+ * outside this tab (a webhook delivers, another device releases), so a stale
+ * local copy would be a lie rather than a convenience.
+ */
+class AgentAccountService {
+ list = (params?: ListAgentAccountsParams): Promise<AgentAccountView[]> =>
+ lambdaClient.agentAccount.list.query(params);
+
+ provision = async (params: ProvisionAgentAccountParams): Promise<AgentAccountView> => {
+ const account = await lambdaClient.agentAccount.provision.mutate(params);
+ // The router answers either an account or an error; a silent `undefined`
+ // would leave the tab showing success for an address it never received.
+ if (!account) throw new Error('Provisioning returned no account');
+
+ return account;
+ };
+
+ revoke = (id: string, options?: { purgeCredential?: boolean; release?: boolean }) =>
+ lambdaClient.agentAccount.revoke.mutate({
+ id,
+ purgeCredential: options?.purgeCredential,
+ release: options?.release,
+ });
+
+ // --------------- Inbox ---------------
+
+ /** A page of summaries; the body and attachments come from {@link getInboxMessage}. */
+ listInbox = (params: ListAgentInboxParams): Promise<AgentInboxMessageSummary[]> =>
+ lambdaClient.agentAccount.inbox.list.query(params);
+
+ /** Unread across the whole inbox, not just the page a list happened to load. */
+ getInboxUnreadCount = async (agentId: string): Promise<number> =>
+ (await lambdaClient.agentAccount.inbox.unreadCount.query({ agentId })).unreadCount;
+
+ getInboxMessage = async (id: string): Promise<AgentInboxMessage> =>
+ toInboxMessage(await lambdaClient.agentAccount.inbox.get.query({ id }));
+
+ markInboxRead = (ids: string[]) => lambdaClient.agentAccount.inbox.markRead.mutate({ ids });
+
+ markAllInboxRead = (agentId: string) =>
+ lambdaClient.agentAccount.inbox.markAllRead.mutate({ agentId });
+}
+
+export const agentAccountService = new AgentAccountService();
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 1a473769a24..6952e46b49a 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -26,6 +26,7 @@ export enum SidebarTabKey {
export enum ChatSettingsTabs {
Connector = 'connector',
Graph = 'graph',
+ Identity = 'identity',
Opening = 'opening',
Plugin = 'plugin',
Prompt = 'prompt',
diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.ts
index 0aa30fedd4c..c09f7e7a26d 100644
--- a/src/store/serverConfig/selectors.ts
+++ b/src/store/serverConfig/selectors.ts
@@ -2,7 +2,11 @@ import { type ServerConfigStore } from './store';
export const featureFlagsSelectors = (s: ServerConfigStore) => s.featureFlags;
+const EMPTY_PROVIDERS: string[] = [];
+
export const serverConfigSelectors = {
+ agentIdentityProviders: (s: ServerConfigStore) =>
+ s.serverConfig.agentIdentityProviders ?? EMPTY_PROVIDERS,
disableEmailPassword: (s: ServerConfigStore) => s.serverConfig.disableEmailPassword || false,
enableBusinessFeatures: (s: ServerConfigStore) => s.serverConfig.enableBusinessFeatures || false,
enableEmailVerification: (s: ServerConfigStore) =>
diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.ts
index 26b964830f5..98e2784dbea 100644
--- a/src/store/user/slices/preference/selectors/labPrefer.ts
+++ b/src/store/user/slices/preference/selectors/labPrefer.ts
@@ -7,6 +7,7 @@ export const labPreferSelectors = {
s.preference.lab?.enableAgentGraphConfig ??
DEFAULT_PREFERENCE.lab?.enableAgentGraphConfig ??
false,
+ enableAgentIdentity: (s: UserState): boolean => s.preference.lab?.enableAgentIdentity ?? false,
enableArtifactDeployment: (s: UserState): boolean =>
s.preference.lab?.enableArtifactDeployment ?? false,
enableClaudeCodeSdk: (s: UserState): boolean => s.preference.lab?.enableClaudeCodeSdk ?? false,