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-mail): split the mail page into list and detail panes (#22690)

Arvin Xu884e28ecbb83
diff --git a/apps/server/src/routers/lambda/__tests__/agentAccount.test.ts b/apps/server/src/routers/lambda/__tests__/agentAccount.test.ts
index b820addc860..000d06c79e8 100644
--- a/apps/server/src/routers/lambda/__tests__/agentAccount.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentAccount.test.ts
@@ -396,7 +396,7 @@ describe('agentAccountRouter', () => {
await caller.inbox.markAllRead({ agentId: 'agt_1' });
expect(assertAgentUsableBy).toHaveBeenCalledWith({}, 'agt_1', expect.anything());
- expect(inbox.markAllRead).toHaveBeenCalledWith('agt_1');
+ expect(inbox.markAllRead).toHaveBeenCalledWith('agt_1', undefined);
});
});
});
diff --git a/apps/server/src/routers/lambda/agentAccount.ts b/apps/server/src/routers/lambda/agentAccount.ts
index e0099ba99a8..7f670a95ce5 100644
--- a/apps/server/src/routers/lambda/agentAccount.ts
+++ b/apps/server/src/routers/lambda/agentAccount.ts
@@ -363,14 +363,16 @@ export const agentAccountRouter = router({
}),
unreadCount: agentAccountProcedure
- .input(z.object({ agentId: z.string().min(1) }))
+ .input(z.object({ accountId: z.string().min(1).optional(), agentId: z.string().min(1) }))
.query(async ({ ctx, input }) => {
await assertAgentUsableBy(ctx.serverDB, input.agentId, {
userId: ctx.userId,
workspaceId: ctx.workspaceId ?? undefined,
});
- return { unreadCount: await ctx.agentInboxModel.unreadCount(input.agentId) };
+ return {
+ unreadCount: await ctx.agentInboxModel.unreadCount(input.agentId, input.accountId),
+ };
}),
get: agentAccountProcedure.input(idInput).query(async ({ ctx, input }) => {
@@ -388,14 +390,14 @@ export const agentAccountRouter = router({
})),
markAllRead: agentAccountProcedure
- .input(z.object({ agentId: z.string().min(1) }))
+ .input(z.object({ accountId: z.string().min(1).optional(), agentId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
await assertAgentUsableBy(ctx.serverDB, input.agentId, {
userId: ctx.userId,
workspaceId: ctx.workspaceId ?? undefined,
});
- return { count: await ctx.agentInboxModel.markAllRead(input.agentId) };
+ return { count: await ctx.agentInboxModel.markAllRead(input.agentId, input.accountId) };
}),
}),
});
diff --git a/apps/server/src/services/agentIdentity/__tests__/agentMailProvider.test.ts b/apps/server/src/services/agentIdentity/__tests__/agentMailProvider.test.ts
index a21d8a526bb..e9065c1c092 100644
--- a/apps/server/src/services/agentIdentity/__tests__/agentMailProvider.test.ts
+++ b/apps/server/src/services/agentIdentity/__tests__/agentMailProvider.test.ts
@@ -226,6 +226,18 @@ describe('agent-mail provider — provisioning', () => {
});
});
+ it('opens a further mailbox for a different prefix instead of returning the first', async () => {
+ const { calls, fetchImpl } = createMailFetch();
+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });
+
+ await provider.provision({ agentId: 'agent_7', prefix: 'sales', userId: 'user_1' });
+
+ expect(calls.find((c) => c.method === 'POST' && c.path === '/v1/inboxes')?.body).toMatchObject({
+ clientId: 'agent_7-sales',
+ username: 'sales',
+ });
+ });
+
it('does not register a second webhook for an inbox a live account already holds', async () => {
const { calls, fetchImpl } = createMailFetch();
const provider = createAgentMailProvider({
diff --git a/apps/server/src/services/agentIdentity/providers/agentMail.ts b/apps/server/src/services/agentIdentity/providers/agentMail.ts
index ea156f520a5..f3dfbbb7bd4 100644
--- a/apps/server/src/services/agentIdentity/providers/agentMail.ts
+++ b/apps/server/src/services/agentIdentity/providers/agentMail.ts
@@ -145,9 +145,10 @@ export const createAgentMailProvider = (
provision: async (input: AgentAccountProvisionInput): Promise<AgentAccountProvisionResult> => {
// `clientId` is the mail API's idempotency key: a retry for the same agent
- // gets the inbox it already opened instead of a second, billable one.
+ // and prefix gets the inbox it already opened instead of a second, billable
+ // one, while a different prefix is a further mailbox the agent asked for.
const inbox = await client.createInbox({
- clientId: input.agentId,
+ clientId: input.prefix ? `${input.agentId}-${input.prefix}` : input.agentId,
displayName: input.displayName,
endUserId: input.agentId,
// The caller's preferred local part. The provider either honours it or
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 443dad63cf1..af94598ba74 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1035,13 +1035,13 @@
"hotkey.title": "Hotkeys",
"hotkey.updateError": "Failed to update hotkey: Network or system error",
"hotkey.updateSuccess": "Hotkey updated successfully",
+ "identity.add": "Add mailbox",
"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.placeholder": "Select a message to read it here.",
"identity.inbox.detail.receivedAt": "Received",
"identity.inbox.detail.to": "To",
"identity.inbox.empty": "Nothing here yet. Mail sent to the addresses above lands here.",
@@ -1055,9 +1055,12 @@
"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.more": "More actions",
"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.prefix.required": "Mailbox prefix",
+ "identity.prefix.requiredHint": "Letters, numbers, dot, underscore and dash.",
"identity.provision": "Open",
"identity.provision.failed": "Could not open the address: {{reason}}",
"identity.provision.success": "Opened {{identifier}}",
@@ -1073,7 +1076,7 @@
"identity.status.provisioning": "Opening",
"identity.status.revoked": "Released",
"identity.status.suspended": "Suspended",
- "identity.title": "Addresses",
+ "identity.switch": "Switch mailbox",
"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/setting.json b/locales/zh-CN/setting.json
index 8140658c56b..fddfa5fdf92 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1035,13 +1035,13 @@
"hotkey.title": "快捷键",
"hotkey.updateError": "快捷键更新失败:网络或系统错误",
"hotkey.updateSuccess": "快捷键更新成功",
+ "identity.add": "添加邮箱",
"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.placeholder": "选择一封邮件,在这里阅读",
"identity.inbox.detail.receivedAt": "接收时间",
"identity.inbox.detail.to": "收件人",
"identity.inbox.empty": "暂无消息。发往上列地址的邮件会出现在这里。",
@@ -1055,9 +1055,12 @@
"identity.loadFailed": "地址加载失败。",
"identity.mail.desc": "一个 @lobe.id 邮箱,Agent 可收发邮件。",
"identity.mail.title": "邮箱",
+ "identity.more": "更多操作",
"identity.noAgent": "请选择一个 Agent 以查看它拥有的地址。",
"identity.prefix.hint": "可选。支持字母、数字、点、下划线和连字符。",
"identity.prefix.placeholder": "期望的前缀(可选)",
+ "identity.prefix.required": "邮箱前缀",
+ "identity.prefix.requiredHint": "可使用字母、数字、点、下划线和短横线。",
"identity.provision": "开通",
"identity.provision.failed": "开通失败:{{reason}}",
"identity.provision.success": "已开通 {{identifier}}",
@@ -1073,7 +1076,7 @@
"identity.status.provisioning": "开通中",
"identity.status.revoked": "已释放",
"identity.status.suspended": "已暂停",
- "identity.title": "邮箱地址",
+ "identity.switch": "切换邮箱",
"llm.aesGcm": "你的密钥与代理地址等将使用 <1>AES-GCM</1> 加密算法进行加密",
"llm.apiKey.desc": "请填写你的 {{name}} API Key",
"llm.apiKey.placeholder": "{{name}} API Key",
diff --git a/packages/database/src/models/__tests__/agentInbox.test.ts b/packages/database/src/models/__tests__/agentInbox.test.ts
index c30fcee2d69..9977a8cca30 100644
--- a/packages/database/src/models/__tests__/agentInbox.test.ts
+++ b/packages/database/src/models/__tests__/agentInbox.test.ts
@@ -115,6 +115,22 @@ describe('AgentInboxModel workspace isolation by agent visibility', () => {
});
});
+describe('AgentInboxModel read state per mailbox', () => {
+ it('counts and clears one mailbox without touching the agent\'s other mailbox', async () => {
+ const first = await deliver(publicAgentId, '[email protected]', 'msg_first');
+ const second = await deliver(publicAgentId, '[email protected]', 'msg_second');
+ const owner = new AgentInboxModel(serverDB, ownerId, workspaceId);
+
+ expect(await owner.unreadCount(publicAgentId)).toBe(2);
+ expect(await owner.unreadCount(publicAgentId, first.accountId!)).toBe(1);
+
+ expect(await owner.markAllRead(publicAgentId, first.accountId!)).toBe(1);
+
+ expect(await owner.unreadCount(publicAgentId, first.accountId!)).toBe(0);
+ expect(await owner.unreadCount(publicAgentId, second.accountId!)).toBe(1);
+ });
+});
+
describe('AgentInboxModel.listSummaries', () => {
it('pages like list but leaves out what the sender wrote', async () => {
const message = await deliver(publicAgentId, '[email protected]', 'msg_summary');
diff --git a/packages/database/src/models/agentInbox.ts b/packages/database/src/models/agentInbox.ts
index a7731db8775..6e1e59c0de1 100644
--- a/packages/database/src/models/agentInbox.ts
+++ b/packages/database/src/models/agentInbox.ts
@@ -468,13 +468,14 @@ export class AgentInboxModel {
.where(and(eq(agentInboxMessages.id, id), this.ownership()));
};
- markAllRead = async (agentId: string): Promise<number> => {
+ markAllRead = async (agentId: string, accountId?: string): Promise<number> => {
const rows = await this.db
.update(agentInboxMessages)
.set({ readAt: new Date(), updatedAt: new Date() })
.where(
and(
eq(agentInboxMessages.agentId, agentId),
+ accountId ? eq(agentInboxMessages.accountId, accountId) : undefined,
isNull(agentInboxMessages.readAt),
this.ownership(),
),
@@ -582,13 +583,14 @@ export class AgentInboxModel {
return row;
};
- unreadCount = async (agentId: string): Promise<number> => {
+ unreadCount = async (agentId: string, accountId?: string): Promise<number> => {
const [row] = await this.db
.select({ value: count() })
.from(agentInboxMessages)
.where(
and(
eq(agentInboxMessages.agentId, agentId),
+ accountId ? eq(agentInboxMessages.accountId, accountId) : undefined,
isNull(agentInboxMessages.readAt),
this.ownership(),
),
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 05b5a5e6577..7778047ba4f 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -332,14 +332,13 @@ export default {
'agentTab.plugin': 'Skill Settings',
'agentTab.prompt': 'Agent Profile',
'agentTab.tts': 'Voice Service',
+ 'identity.add': 'Add mailbox',
'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.placeholder': 'Select a message to read it here.',
'identity.inbox.detail.receivedAt': 'Received',
'identity.inbox.detail.to': 'To',
'identity.inbox.empty': 'Nothing here yet. Mail sent to the addresses above lands here.',
@@ -353,9 +352,12 @@ export default {
'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.more': 'More actions',
'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.prefix.required': 'Mailbox prefix',
+ 'identity.prefix.requiredHint': 'Letters, numbers, dot, underscore and dash.',
'identity.provision': 'Open',
'identity.provision.failed': 'Could not open the address: {{reason}}',
'identity.provision.success': 'Opened {{identifier}}',
@@ -372,7 +374,7 @@ export default {
'identity.status.provisioning': 'Opening',
'identity.status.revoked': 'Released',
'identity.status.suspended': 'Suspended',
- 'identity.title': 'Addresses',
+ 'identity.switch': 'Switch mailbox',
'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/src/features/AgentMail/AccountCard.tsx b/src/features/AgentMail/AccountCard.tsx
deleted file mode 100644
index 8cff8c8a63d..00000000000
--- a/src/features/AgentMail/AccountCard.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-'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/AgentMail/AddMailboxForm.tsx b/src/features/AgentMail/AddMailboxForm.tsx
new file mode 100644
index 00000000000..76031f21466
--- /dev/null
+++ b/src/features/AgentMail/AddMailboxForm.tsx
@@ -0,0 +1,67 @@
+'use client';
+
+import { Button, Flexbox, Input, Text } from '@lobehub/ui';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { AgentAccountView } from '@/services/agentAccount';
+
+import type { IdentityChannel } from './const';
+import { useAccountActions } from './useIdentityActions';
+
+interface AddMailboxFormProps {
+ agentId: string;
+ channel: IdentityChannel;
+ onAdded: (account: AgentAccountView) => void;
+ onChanged: () => Promise<unknown> | void;
+}
+
+/**
+ * Open one more address: only the part the user chooses is asked for. The
+ * prefix is required, because without one the provider hands back the first
+ * mailbox instead of opening another.
+ */
+const AddMailboxForm = ({ agentId, channel, onAdded, onChanged }: AddMailboxFormProps) => {
+ const { t } = useTranslation('setting');
+ const [prefix, setPrefix] = useState('');
+ const [loading, setLoading] = useState(false);
+ const { provision } = useAccountActions({ agentId, onChanged });
+ const empty = !prefix.trim();
+
+ const submit = async () => {
+ if (empty || loading) return;
+ setLoading(true);
+ try {
+ const account = await provision(channel, prefix);
+ if (account) onAdded(account);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={8}>
+ <Input
+ autoFocus
+ disabled={loading}
+ placeholder={t('identity.prefix.required')}
+ size={'large'}
+ suffix={<Text type={'secondary'}>{channel.addressSuffix}</Text>}
+ value={prefix}
+ variant={'filled'}
+ onChange={(event) => setPrefix(event.target.value)}
+ onPressEnter={submit}
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {t('identity.prefix.requiredHint')}
+ </Text>
+ <Flexbox horizontal justify={'flex-end'} paddingBlock={'8px 0'}>
+ <Button disabled={empty} loading={loading} type={'primary'} onClick={submit}>
+ {t('identity.provision')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+export default AddMailboxForm;
diff --git a/src/features/AgentMail/IdentityAccounts.tsx b/src/features/AgentMail/IdentityAccounts.tsx
deleted file mode 100644
index 6b5cfc5a90d..00000000000
--- a/src/features/AgentMail/IdentityAccounts.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-'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/AgentMail/InboxMessageModal.tsx b/src/features/AgentMail/InboxMessageDetail.tsx
similarity index 89%
rename from src/features/AgentMail/InboxMessageModal.tsx
rename to src/features/AgentMail/InboxMessageDetail.tsx
index ff661e17763..7653dbed16b 100644
--- a/src/features/AgentMail/InboxMessageModal.tsx
+++ b/src/features/AgentMail/InboxMessageDetail.tsx
@@ -5,15 +5,13 @@ 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';
+import { useInboxMessage } from './useAgentIdentity';
dayjs.extend(relativeTime);
-export interface InboxMessageModalProps {
+export interface InboxMessageDetailProps {
id: string;
}
@@ -43,11 +41,9 @@ const formatAttachmentSize = (bytes?: number): string | undefined => {
return `${Math.max(1, Math.round(bytes / 1024))} KB`;
};
-const InboxMessageModal = memo<InboxMessageModalProps>(({ id }) => {
+const InboxMessageDetail = memo<InboxMessageDetailProps>(({ id }) => {
const { t } = useTranslation('setting');
- const { data, error, isLoading, mutate } = useSWR(['agent-inbox-message', id], ([, messageId]) =>
- agentAccountService.getInboxMessage(messageId),
- );
+ const { data, error, isLoading, mutate } = useInboxMessage(id);
// A failed read must say so: a skeleton that never resolves reads as "still
// loading" forever.
@@ -124,6 +120,6 @@ const InboxMessageModal = memo<InboxMessageModalProps>(({ id }) => {
);
});
-InboxMessageModal.displayName = 'AgentInboxMessageModal';
+InboxMessageDetail.displayName = 'AgentInboxMessageDetail';
-export default InboxMessageModal;
+export default InboxMessageDetail;
diff --git a/src/features/AgentMail/InboxSection.tsx b/src/features/AgentMail/InboxSection.tsx
index 604f4e6a9de..81245b809d3 100644
--- a/src/features/AgentMail/InboxSection.tsx
+++ b/src/features/AgentMail/InboxSection.tsx
@@ -15,7 +15,12 @@ import { useInboxActions } from './useIdentityActions';
dayjs.extend(relativeTime);
interface InboxSectionProps {
+ /** The mailbox on screen; the list, the count and "mark all read" stay within it. */
+ accountId?: string;
agentId: string;
+ onOpen: (id: string) => void;
+ /** The message showing beside the list; its row stays highlighted. */
+ selectedId?: string;
}
/**
@@ -25,15 +30,23 @@ interface InboxSectionProps {
* 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 InboxSection = memo<InboxSectionProps>(({ accountId, agentId, onOpen, selectedId }) => {
const { t } = useTranslation('setting');
- const { data, error, hasMore, isLoading, loadMore, mutate } = useAgentInbox(agentId);
- const { data: unreadCount = 0, mutate: mutateUnread } = useAgentInboxUnreadCount(agentId);
+ const { data, error, hasMore, isLoading, loadMore, mutate } = useAgentInbox(agentId, accountId);
+ const { data: unreadCount = 0, mutate: mutateUnread } = useAgentInboxUnreadCount(
+ agentId,
+ accountId,
+ );
const refresh = useCallback(
() => Promise.all([mutate(), mutateUnread()]),
[mutate, mutateUnread],
);
- const { markAllRead, openMessage } = useInboxActions({ agentId, onChanged: refresh });
+ const { markAllRead, openMessage } = useInboxActions({
+ accountId,
+ agentId,
+ onChanged: refresh,
+ onOpen,
+ });
const messages = data ?? [];
@@ -49,13 +62,7 @@ const InboxSection = memo<InboxSectionProps>(({ agentId }) => {
</Flexbox>
) : undefined;
- const header = (
- <SectionHeader
- desc={t('identity.inbox.desc')}
- extra={extra}
- title={t('identity.inbox.title')}
- />
- );
+ const header = <SectionHeader 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
@@ -100,21 +107,25 @@ const InboxSection = memo<InboxSectionProps>(({ agentId }) => {
}
return (
- <Flexbox gap={10}>
+ <Flexbox flex={1} gap={10} style={{ minHeight: 0 }}>
{header}
- <Flexbox gap={8}>
+ {/* The list scrolls on its own so the header and addresses stay in view. */}
+ <Flexbox flex={1} gap={2} style={{ minHeight: 0, overflowY: 'auto' }}>
{messages.map((message) => {
const unread = !message.readAt;
+ const selected = message.id === selectedId;
return (
<Flexbox
horizontal
- align={'center'}
+ align={'flex-start'}
+ aria-current={selected ? 'true' : undefined}
aria-label={`${message.from} — ${message.subject || t('identity.inbox.noSubject')}`}
- className={identityStyles.inboxRow}
+ className={selected ? identityStyles.inboxRowSelected : identityStyles.inboxRow}
gap={10}
key={message.id}
role={'button'}
+ style={{ flexShrink: 0 }}
tabIndex={0}
onClick={() => {
void openMessage(message);
@@ -127,31 +138,36 @@ const InboxSection = memo<InboxSectionProps>(({ agentId }) => {
>
<span
className={identityStyles.unreadDot}
- style={{ visibility: unread ? 'visible' : 'hidden' }}
+ style={{ marginBlockStart: 7, 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}>
+ <Text ellipsis fontSize={13} style={{ minWidth: 0 }} weight={unread ? 500 : 400}>
{message.from}
</Text>
- <Text fontSize={12} type={'secondary'}>
+ <Text fontSize={12} style={{ flexShrink: 0 }} type={'secondary'}>
{dayjs(message.receivedAt).fromNow()}
</Text>
</Flexbox>
<Text ellipsis className={identityStyles.subject}>
{message.subject || t('identity.inbox.noSubject')}
</Text>
+ {message.preview && (
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {message.preview}
+ </Text>
+ )}
</Flexbox>
</Flexbox>
);
})}
+ {refreshError ??
+ (hasMore && (
+ <Button block size={'small'} style={{ flexShrink: 0 }} type={'text'} onClick={loadMore}>
+ {t('identity.inbox.loadMore')}
+ </Button>
+ ))}
</Flexbox>
- {refreshError ??
- (hasMore && (
- <Button block size={'small'} type={'text'} onClick={loadMore}>
- {t('identity.inbox.loadMore')}
- </Button>
- ))}
</Flexbox>
);
});
diff --git a/src/features/AgentMail/MailSplitView.tsx b/src/features/AgentMail/MailSplitView.tsx
new file mode 100644
index 00000000000..ed19eec29c8
--- /dev/null
+++ b/src/features/AgentMail/MailSplitView.tsx
@@ -0,0 +1,69 @@
+'use client';
+
+import { Center, Empty, Flexbox, Text } from '@lobehub/ui';
+import { Mail } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NavHeader from '@/features/NavHeader';
+
+import InboxMessageDetail from './InboxMessageDetail';
+import { identityStyles } from './styles';
+
+interface MailSplitViewProps {
+ inbox: ReactNode;
+ mailbox: ReactNode;
+ /** The open message; nothing is opened on arrival, because opening clears its unread mark. */
+ messageId?: string;
+}
+
+/** The mail page on a wide screen: mailbox and list on the left, the open message on the right. */
+const MailSplitView = ({ inbox, mailbox, messageId }: MailSplitViewProps) => {
+ const { t } = useTranslation('setting');
+
+ return (
+ <Flexbox horizontal flex={1} style={{ minHeight: 0 }} width={'100%'}>
+ {/* The header belongs to the list column, so the message runs to the top of the page. */}
+ <div className={identityStyles.listPane}>
+ <NavHeader
+ left={
+ <Text fontSize={14} weight={500}>
+ {t('identity.mail.title')}
+ </Text>
+ }
+ styles={{ left: { minWidth: 0, paddingInlineStart: 8 } }}
+ />
+ <Flexbox
+ flex={1}
+ gap={16}
+ paddingBlock={'0 12px'}
+ paddingInline={12}
+ style={{ minHeight: 0 }}
+ >
+ <div className={identityStyles.accounts}>{mailbox}</div>
+ {inbox}
+ </Flexbox>
+ </div>
+ {/* Keyed so the next message starts at its top, not at the last scroll offset. */}
+ <Flexbox className={identityStyles.detailPane} flex={1} key={messageId}>
+ {messageId ? (
+ // The top keeps clear of what floats over the page header.
+ <Flexbox
+ paddingBlock={'44px 16px'}
+ paddingInline={16}
+ style={{ marginInline: 'auto', maxWidth: 800 }}
+ width={'100%'}
+ >
+ <InboxMessageDetail id={messageId} />
+ </Flexbox>
+ ) : (
+ <Center height={'100%'}>
+ <Empty description={t('identity.inbox.detail.placeholder')} icon={Mail} />
+ </Center>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+export default MailSplitView;
diff --git a/src/features/AgentMail/MailboxCard.tsx b/src/features/AgentMail/MailboxCard.tsx
new file mode 100644
index 00000000000..aabc8b01751
--- /dev/null
+++ b/src/features/AgentMail/MailboxCard.tsx
@@ -0,0 +1,202 @@
+'use client';
+
+import {
+ ActionIcon,
+ createModal,
+ DropdownMenu,
+ Flexbox,
+ Icon,
+ Skeleton,
+ Tag,
+ Text,
+ toast,
+} from '@lobehub/ui';
+import { Check, ChevronsUpDown, Copy, MoreHorizontal, Plus, Trash2 } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { AgentAccountView } from '@/services/agentAccount';
+import { useServerConfigStore } from '@/store/serverConfig';
+import { serverConfigSelectors } from '@/store/serverConfig/selectors';
+
+import AddMailboxForm from './AddMailboxForm';
+import { IDENTITY_CHANNELS, isChannelAccount, KIND_ICONS } from './const';
+import InlineError from './InlineError';
+import ProvisionCard from './ProvisionCard';
+import { identityStyles } from './styles';
+import type { Mailbox } from './useAgentIdentity';
+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>;
+
+const channelOf = (account: AgentAccountView) =>
+ IDENTITY_CHANNELS.find((channel) => isChannelAccount(account, channel));
+
+interface MailboxCardProps {
+ agentId: string;
+ /** Read-only viewer: mailboxes stay readable, nothing can be added or released. */
+ disabled?: boolean;
+ mailbox: Mailbox;
+ onSwitch: (accountId: string) => void;
+}
+
+/**
+ * The mailbox being read: one card that switches between the agent's addresses
+ * and keeps what is done to an address behind its menu.
+ *
+ * An agent with no address gets the offer to open one instead, because opening
+ * is an explicit act and the absence should be visible.
+ */
+const MailboxCard = memo<MailboxCardProps>(({ agentId, disabled, mailbox, onSwitch }) => {
+ const { t } = useTranslation(['setting', 'common']);
+ const { accounts, current, data, error, isLoading, mutate } = mailbox;
+ const providers = useServerConfigStore(serverConfigSelectors.agentIdentityProviders);
+ const { release } = useAccountActions({
+ agentId,
+ onChanged: () => {
+ // The open message belonged to the released mailbox, so move off it too.
+ const next = accounts.find((account) => account.id !== current?.id);
+ if (next) onSwitch(next.id);
+ return mutate();
+ },
+ });
+
+ // An offer this deployment cannot fulfil would only fail on click.
+ const openable = IDENTITY_CHANNELS.find((channel) => providers.includes(channel.provider));
+
+ // Only a read that never succeeded replaces the card. A later revalidation
+ // that fails keeps the mailbox on screen, with the failure beside it.
+ const failure = error ? (
+ <InlineError
+ detail={error instanceof Error ? error.message : String(error)}
+ summary={t('identity.loadFailed')}
+ onRetry={() => void mutate()}
+ />
+ ) : undefined;
+
+ if (error && !data) return failure;
+ if (isLoading && !data) return <Skeleton height={56} width={'100%'} />;
+
+ if (!current) {
+ if (!openable) return failure ?? null;
+
+ return (
+ <ProvisionCard
+ agentId={agentId}
+ channel={openable}
+ disabled={disabled}
+ onProvisioned={mutate}
+ />
+ );
+ }
+
+ const channel = channelOf(current);
+
+ const openAdd = () => {
+ if (!openable) return;
+ const modal = createModal({
+ content: (
+ <AddMailboxForm
+ agentId={agentId}
+ channel={openable}
+ onAdded={(account) => {
+ onSwitch(account.id);
+ modal.close();
+ }}
+ onChanged={mutate}
+ />
+ ),
+ footer: null,
+ maskClosable: true,
+ title: t('identity.add'),
+ width: 400,
+ });
+ };
+
+ const switchItems = [
+ ...accounts.map((account) => ({
+ icon:
+ account.id === current.id ? Check : (channelOf(account)?.icon ?? KIND_ICONS[account.kind]),
+ key: account.id,
+ label: account.identifier,
+ onClick: () => onSwitch(account.id),
+ })),
+ ...(openable && !disabled
+ ? [
+ { type: 'divider' as const },
+ { icon: Plus, key: 'add', label: t('identity.add'), onClick: openAdd },
+ ]
+ : []),
+ ];
+
+ const moreItems = [
+ {
+ icon: Copy,
+ key: 'copy',
+ label: t('identity.copy'),
+ onClick: async () => {
+ await navigator.clipboard.writeText(current.identifier);
+ toast.success(t('copySuccess', { ns: 'common' }));
+ },
+ },
+ {
+ danger: true,
+ disabled,
+ icon: Trash2,
+ key: 'release',
+ label: t('identity.release'),
+ onClick: () => void release(current),
+ },
+ ];
+
+ return (
+ <Flexbox gap={8}>
+ <Flexbox horizontal align={'center'} className={identityStyles.card} gap={4}>
+ <DropdownMenu items={switchItems}>
+ <div
+ aria-label={t('identity.switch')}
+ className={identityStyles.mailboxTrigger}
+ role={'button'}
+ tabIndex={0}
+ >
+ <Icon
+ className={identityStyles.icon}
+ icon={channel?.icon ?? KIND_ICONS[current.kind]}
+ size={18}
+ />
+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
+ <Text code ellipsis weight={500}>
+ {current.identifier}
+ </Text>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text ellipsis fontSize={12} style={{ minWidth: 0 }} type={'secondary'}>
+ {current.displayName || (channel ? t(channel.titleKey) : current.provider)}
+ </Text>
+ <Tag style={{ flexShrink: 0 }}>{t(STATUS_KEYS[current.status])}</Tag>
+ </Flexbox>
+ </Flexbox>
+ <Icon className={identityStyles.icon} icon={ChevronsUpDown} size={14} />
+ </div>
+ </DropdownMenu>
+ <DropdownMenu items={moreItems}>
+ <ActionIcon icon={MoreHorizontal} size={'small'} title={t('identity.more')} />
+ </DropdownMenu>
+ </Flexbox>
+ {failure}
+ </Flexbox>
+ );
+});
+
+MailboxCard.displayName = 'AgentMailboxCard';
+
+export default MailboxCard;
diff --git a/src/features/AgentMail/SectionHeader.tsx b/src/features/AgentMail/SectionHeader.tsx
index e4df5f54f46..25ed93d7cd5 100644
--- a/src/features/AgentMail/SectionHeader.tsx
+++ b/src/features/AgentMail/SectionHeader.tsx
@@ -4,23 +4,17 @@ 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}
+const SectionHeader = memo<SectionHeaderProps>(({ title, extra }) => (
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <Text fontSize={14} weight={600}>
+ {title}
</Text>
+ {extra}
</Flexbox>
));
diff --git a/src/features/AgentMail/const.tsx b/src/features/AgentMail/const.tsx
index 88025318a84..090fb9eace1 100644
--- a/src/features/AgentMail/const.tsx
+++ b/src/features/AgentMail/const.tsx
@@ -11,6 +11,8 @@ import { KeyRound, Mail, Phone, Wallet } from 'lucide-react';
* whose handles the provider mints on its own leaves it off.
*/
export interface IdentityChannel {
+ /** What follows the chosen prefix in an address on this channel. */
+ addressSuffix: string;
descKey: 'identity.mail.desc';
icon: LucideIcon;
kind: AgentAccountKind;
@@ -21,6 +23,7 @@ export interface IdentityChannel {
export const IDENTITY_CHANNELS: IdentityChannel[] = [
{
+ addressSuffix: '@lobe.id',
descKey: 'identity.mail.desc',
icon: Mail,
kind: 'mail',
diff --git a/src/features/AgentMail/identityUi.test.tsx b/src/features/AgentMail/identityUi.test.tsx
index 45807ccebeb..bf1e92105f2 100644
--- a/src/features/AgentMail/identityUi.test.tsx
+++ b/src/features/AgentMail/identityUi.test.tsx
@@ -27,10 +27,8 @@ vi.mock('@lobehub/ui', async (importOriginal) => ({
}));
const { IDENTITY_CHANNELS } = await import('./const');
-const { default: AccountCard } = await import('./AccountCard');
-const { default: InboxMessageModal } = await import('./InboxMessageModal');
+const { default: InboxMessageDetail } = await import('./InboxMessageDetail');
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) =>
@@ -42,80 +40,17 @@ beforeEach(() => {
vi.clearAllMocks();
});
-describe('InboxMessageModal', () => {
+describe('InboxMessageDetail', () => {
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'} />);
+ fresh(<InboxMessageDetail 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', () => {
+describe('InboxMessageDetail attachments', () => {
it('lists what an attachment-only message carried instead of a blank body', async () => {
service.getInboxMessage.mockResolvedValue({
attachments: [
@@ -130,7 +65,7 @@ describe('InboxMessageModal attachments', () => {
});
- fresh(<InboxMessageModal id={'msg_photo'} />);
+ fresh(<InboxMessageDetail 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.
@@ -141,27 +76,6 @@ describe('InboxMessageModal attachments', () => {
});
});
-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 = [
{
@@ -177,9 +91,11 @@ describe('InboxSection', () => {
service.listInbox.mockResolvedValue(rows);
service.getInboxUnreadCount.mockResolvedValue(73);
- fresh(<InboxSection agentId={'agt_1'} />);
+ fresh(<InboxSection agentId={'agt_1'} onOpen={vi.fn()} />);
- await waitFor(() => expect(service.getInboxUnreadCount).toHaveBeenCalledWith('agt_1'));
+ await waitFor(() =>
+ expect(service.getInboxUnreadCount).toHaveBeenCalledWith('agt_1', undefined),
+ );
expect(await screen.findByText('identity.inbox.unread')).toBeInTheDocument();
});
@@ -188,14 +104,15 @@ describe('InboxSection', () => {
service.getInboxUnreadCount.mockResolvedValue(1);
service.markInboxRead.mockResolvedValue({ count: 1 });
- fresh(<InboxSection agentId={'agt_1'} />);
+ const onOpen = vi.fn();
+ fresh(<InboxSection agentId={'agt_1'} onOpen={onOpen} />);
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));
+ await waitFor(() => expect(onOpen).toHaveBeenCalledTimes(1));
expect(service.markInboxRead).toHaveBeenCalledWith(['msg_1']);
});
@@ -215,7 +132,7 @@ describe('InboxSection', () => {
);
service.getInboxUnreadCount.mockResolvedValue(0);
- fresh(<InboxSection agentId={'agt_1'} />);
+ fresh(<InboxSection agentId={'agt_1'} onOpen={vi.fn()} />);
// Two clicks: beyond the server's 100-row cap if the window just grew.
fireEvent.click(await screen.findByRole('button', { name: 'identity.inbox.loadMore' }));
@@ -246,7 +163,7 @@ describe('InboxSection', () => {
});
service.getInboxUnreadCount.mockResolvedValue(0);
- fresh(<InboxSection agentId={'agt_1'} />);
+ fresh(<InboxSection agentId={'agt_1'} onOpen={vi.fn()} />);
fireEvent.click(await screen.findByRole('button', { name: 'identity.inbox.loadMore' }));
@@ -260,7 +177,7 @@ describe('InboxSection', () => {
service.listInbox.mockResolvedValueOnce([]).mockRejectedValue(new Error('inbox unavailable'));
service.getInboxUnreadCount.mockResolvedValue(0);
- fresh(<InboxSection agentId={'agt_1'} />);
+ fresh(<InboxSection agentId={'agt_1'} onOpen={vi.fn()} />);
await screen.findByText('identity.inbox.empty');
await vi.advanceTimersByTimeAsync(INBOX_REFRESH_INTERVAL_MS + 100);
@@ -285,7 +202,7 @@ describe('InboxSection', () => {
]);
service.getInboxUnreadCount.mockResolvedValue(1);
- fresh(<InboxSection agentId={'agt_1'} />);
+ fresh(<InboxSection agentId={'agt_1'} onOpen={vi.fn()} />);
await screen.findByRole('button', { name: /[email protected]/ });
await vi.advanceTimersByTimeAsync(INBOX_REFRESH_INTERVAL_MS + 100);
diff --git a/src/features/AgentMail/index.test.tsx b/src/features/AgentMail/index.test.tsx
new file mode 100644
index 00000000000..fe5d7a473c6
--- /dev/null
+++ b/src/features/AgentMail/index.test.tsx
@@ -0,0 +1,304 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter, Route, Routes } from 'react-router';
+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(),
+ provision: vi.fn(),
+ revoke: vi.fn(),
+}));
+vi.mock('@/services/agentAccount', () => ({ agentAccountService: service }));
+
+const surface = vi.hoisted(() => ({ mobile: false }));
+vi.mock('@/utils/mobileSurface', () => ({ isMobileSurface: () => surface.mobile }));
+
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (selector: (state: unknown) => unknown) =>
+ selector({ serverConfig: { agentIdentityProviders: ['agent-mail'] } }),
+}));
+vi.mock('@/features/NavHeader', () => ({ default: () => null }));
+vi.mock('@/features/AgentBreadcrumb', () => ({ default: () => null }));
+vi.mock('@/features/AgentProfileTabs', () => ({
+ AGENT_PROFILE_TABS_CENTER_STYLE: {},
+ default: () => null,
+}));
+vi.mock('@/features/WideScreenContainer', () => ({
+ default: ({ children }: { children: React.ReactNode }) => children,
+}));
+
+const ui = vi.hoisted(() => ({
+ confirmModal: vi.fn(),
+ createModal: vi.fn(() => ({ close: vi.fn() })),
+}));
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ confirmModal: ui.confirmModal,
+ createModal: ui.createModal,
+ DropdownMenu: ({
+ children,
+ items,
+ }: {
+ children: React.ReactNode;
+ items: { key?: string; label?: string; onClick?: () => void }[];
+ }) => (
+ <div>
+ {children}
+ {items
+ .filter((item) => item.key)
+ .map((item) => (
+ <button key={item.key} onClick={item.onClick}>
+ {`menu:${item.label}`}
+ </button>
+ ))}
+ </div>
+ ),
+}));
+
+const { default: AgentMail } = await import('./index');
+const { default: AddMailboxForm } = await import('./AddMailboxForm');
+const { IDENTITY_CHANNELS } = await import('./const');
+
+const account = (id: string, identifier: string) => ({
+ agentId: 'agt_1',
+ capabilities: { receive: true, send: true },
+ displayName: null,
+ id,
+ identifier,
+ kind: 'mail',
+ provider: 'agent-mail',
+ status: 'active',
+});
+
+const row = (id: string, subject: string) => ({
+ agentId: 'agt_1',
+ createdAt: new Date(),
+ from: `${id}@x.com`,
+ id,
+ preview: `preview of ${subject}`,
+ readAt: null,
+ receivedAt: new Date(),
+ subject,
+});
+
+const page = (path = '/agent/agt_1/mail') =>
+ render(
+ <SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>
+ <MemoryRouter initialEntries={[path]}>
+ <Routes>
+ <Route element={<AgentMail agentId={'agt_1'} />} path={'/agent/:aid/mail/:messageId?'} />
+ </Routes>
+ </MemoryRouter>
+ </SWRConfig>,
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ surface.mobile = false;
+ service.list.mockResolvedValue([account('acc_a', '[email protected]'), account('acc_b', '[email protected]')]);
+ service.listInbox.mockImplementation(async ({ accountId }: { accountId?: string }) =>
+ accountId === 'acc_b' ? [row('msg_b', 'For B')] : [row('msg_a', 'For A')],
+ );
+ service.getInboxUnreadCount.mockResolvedValue(1);
+ service.markInboxRead.mockResolvedValue({ count: 1 });
+ service.getInboxMessage.mockImplementation(async (id: string) => ({
+ ...row(id, 'Opened'),
+ attachments: [],
+ text: `Full body of ${id}`,
+ }));
+});
+
+describe('AgentMail', () => {
+ it('leaves mail unread until the reader picks a message', async () => {
+ page();
+
+ await screen.findByText('preview of For A');
+
+ expect(service.getInboxMessage).not.toHaveBeenCalled();
+ expect(service.markInboxRead).not.toHaveBeenCalled();
+ });
+
+ it('reads a picked message beside the list, without a modal', async () => {
+ page();
+
+ fireEvent.click(await screen.findByRole('button', { name: '[email protected] — For A' }));
+
+ expect(await screen.findByText('Full body of msg_a')).toBeInTheDocument();
+ expect(ui.createModal).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: '[email protected] — For A' })).toHaveAttribute(
+ 'aria-current',
+ 'true',
+ );
+ expect(service.markInboxRead).toHaveBeenCalledWith(['msg_a']);
+ });
+
+ it('switches the list, the count and the open message to the chosen mailbox', async () => {
+ page('/agent/agt_1/mail/msg_a');
+ expect(await screen.findByText('Full body of msg_a')).toBeInTheDocument();
+
+ fireEvent.click(await screen.findByText('menu:[email protected]'));
+
+ expect(await screen.findByText('preview of For B')).toBeInTheDocument();
+ expect(screen.queryByText('preview of For A')).not.toBeInTheDocument();
+ expect(screen.queryByText('Full body of msg_a')).not.toBeInTheDocument();
+ expect(service.getInboxUnreadCount).toHaveBeenCalledWith('agt_1', 'acc_b');
+ });
+
+ it('restores the mailbox of a message opened straight from its URL', async () => {
+ service.getInboxMessage.mockResolvedValue({
+ ...row('msg_b', 'For B'),
+ accountId: 'acc_b',
+ attachments: [],
+ text: 'Full body of msg_b',
+ });
+ page('/agent/agt_1/mail/msg_b');
+
+ expect(await screen.findByText('preview of For B')).toBeInTheDocument();
+ expect(screen.queryByText('preview of For A')).not.toBeInTheDocument();
+ expect(service.listInbox).not.toHaveBeenCalledWith(
+ expect.objectContaining({ accountId: 'acc_a' }),
+ );
+ });
+
+ it('marks a message read when it is opened straight from its URL', async () => {
+ page('/agent/agt_1/mail/msg_a');
+
+ expect(await screen.findByText('Full body of msg_a')).toBeInTheDocument();
+ await waitFor(() => expect(service.markInboxRead).toHaveBeenCalledWith(['msg_a']));
+ expect(service.markInboxRead).toHaveBeenCalledTimes(1);
+ // The list and count load after the mark, so neither shows it as unread.
+ expect(service.markInboxRead.mock.invocationCallOrder[0]).toBeLessThan(
+ service.listInbox.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('does not re-stamp a read message opened from its URL', async () => {
+ service.getInboxMessage.mockResolvedValue({
+ ...row('msg_a', 'For A'),
+ attachments: [],
+ readAt: new Date(),
+ text: 'Full body of msg_a',
+ });
+ page('/agent/agt_1/mail/msg_a');
+
+ expect(await screen.findByText('Full body of msg_a')).toBeInTheDocument();
+ expect(service.markInboxRead).not.toHaveBeenCalled();
+ });
+
+ it('asks for confirmation before releasing the mailbox on screen', async () => {
+ page();
+
+ fireEvent.click(await screen.findByText('menu:identity.release'));
+
+ expect(ui.confirmModal).toHaveBeenCalledTimes(1);
+ });
+
+ it('moves off the open message once its mailbox is released', async () => {
+ service.revoke.mockResolvedValue({});
+ page('/agent/agt_1/mail/msg_a');
+ expect(await screen.findByText('Full body of msg_a')).toBeInTheDocument();
+
+ fireEvent.click(await screen.findByText('menu:identity.release'));
+ const [{ onOk }] = ui.confirmModal.mock.calls[0] as unknown as [{ onOk: () => Promise<void> }];
+ await onOk();
+
+ expect(service.revoke).toHaveBeenCalledWith('acc_a');
+ expect(await screen.findByText('preview of For B')).toBeInTheDocument();
+ expect(screen.queryByText('Full body of msg_a')).not.toBeInTheDocument();
+ });
+
+ it('adds another mailbox through a dialog', async () => {
+ page();
+
+ fireEvent.click(await screen.findByText('menu:identity.add'));
+
+ expect(ui.createModal).toHaveBeenCalledTimes(1);
+ });
+
+ it('offers to open an address when the agent has none', async () => {
+ service.list.mockResolvedValue([]);
+ service.listInbox.mockResolvedValue([]);
+ page();
+
+ expect(await screen.findByText('identity.provision')).toBeInTheDocument();
+ expect(screen.queryByText('menu:identity.release')).not.toBeInTheDocument();
+ });
+
+ it('keeps the mailbox on screen when a later refresh fails', async () => {
+ service.list
+ .mockResolvedValueOnce([account('acc_user', '[email protected]')])
+ .mockRejectedValue(new Error('network down'));
+ render(
+ <SWRConfig value={{ dedupingInterval: 0, provider: () => new Map(), refreshInterval: 20 }}>
+ <MemoryRouter initialEntries={['/agent/agt_1/mail']}>
+ <Routes>
+ <Route
+ element={<AgentMail agentId={'agt_1'} />}
+ path={'/agent/:aid/mail/:messageId?'}
+ />
+ </Routes>
+ </MemoryRouter>
+ </SWRConfig>,
+ );
+
+ expect(await screen.findByText('[email protected]')).toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText('identity.loadFailed')).toBeInTheDocument());
+ expect(screen.getByText('[email protected]')).toBeInTheDocument();
+ });
+
+ it('gives a message its own page on a phone, and no modal', async () => {
+ surface.mobile = true;
+ page();
+
+ fireEvent.click(await screen.findByRole('button', { name: '[email protected] — For A' }));
+
+ expect(await screen.findByText('Full body of msg_a')).toBeInTheDocument();
+ expect(ui.createModal).not.toHaveBeenCalled();
+ });
+});
+
+describe('AddMailboxForm', () => {
+ const setup = () => {
+ const onAdded = vi.fn();
+ render(
+ <AddMailboxForm
+ agentId={'agt_1'}
+ channel={IDENTITY_CHANNELS[0]}
+ onAdded={onAdded}
+ onChanged={vi.fn()}
+ />,
+ );
+ return onAdded;
+ };
+
+ it('shows the fixed domain and waits for a prefix', () => {
+ setup();
+
+ expect(screen.getByText('@lobe.id')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'identity.provision' })).toBeDisabled();
+ });
+
+ it('opens the mailbox for the typed prefix and reports it', async () => {
+ const issued = account('acc_new', '[email protected]');
+ service.provision.mockResolvedValue(issued);
+ const onAdded = setup();
+
+ fireEvent.change(screen.getByPlaceholderText('identity.prefix.required'), {
+ target: { value: 'growth' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'identity.provision' }));
+
+ await waitFor(() => expect(onAdded).toHaveBeenCalledWith(issued));
+ expect(service.provision).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agt_1', prefix: 'growth', provider: 'agent-mail' }),
+ );
+ });
+});
diff --git a/src/features/AgentMail/index.tsx b/src/features/AgentMail/index.tsx
index bc3aa24eae0..fc86dcd39d8 100644
--- a/src/features/AgentMail/index.tsx
+++ b/src/features/AgentMail/index.tsx
@@ -1,15 +1,23 @@
'use client';
import { Flexbox } from '@lobehub/ui';
+import { useParams } from 'react-router';
+import urlJoin from 'url-join';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
import AgentProfileTabs, { AGENT_PROFILE_TABS_CENTER_STYLE } from '@/features/AgentProfileTabs';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { isMobileSurface } from '@/utils/mobileSurface';
import { StyleSheet } from '@/utils/styles';
-import IdentityAccounts from './IdentityAccounts';
+import InboxMessageDetail from './InboxMessageDetail';
import InboxSection from './InboxSection';
+import MailboxCard from './MailboxCard';
+import MailSplitView from './MailSplitView';
+import { identityStyles } from './styles';
+import { useMailbox } from './useAgentIdentity';
const styles = StyleSheet.create({
body: {
@@ -26,35 +34,86 @@ interface AgentMailProps {
}
/**
- * The agent's mail page: which addresses it owns, and what has arrived.
+ * The agent's mail page: which mailbox is being read, 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.
+ * The open message lives in the URL, so a phone's back gesture leaves it and a
+ * reload keeps it. A wide screen shows it beside the list; a phone gives it the
+ * whole page.
*/
-const AgentMail = ({ agentId, disabled }: AgentMailProps) => (
- <Flexbox height={'100%'} width={'100%'}>
- <NavHeader
- left={<AgentBreadcrumb agentId={agentId} />}
- // `relative` anchors the absolutely-centered switcher below.
- style={{ position: 'relative' }}
- styles={{
- // Center on the header midpoint (equal gaps), not the leftover track.
- center: AGENT_PROFILE_TABS_CENTER_STYLE,
- left: { minWidth: 0, paddingInlineStart: 8 },
- }}
- >
- <AgentProfileTabs active={'mail'} agentId={agentId} />
- </NavHeader>
- <Flexbox flex={1} style={styles.body} width={'100%'}>
- <WideScreenContainer>
- <Flexbox gap={24} paddingBlock={16}>
- <IdentityAccounts agentId={agentId} disabled={disabled} />
- <InboxSection agentId={agentId} />
+const MailPage = ({ agentId, disabled }: AgentMailProps) => {
+ const { messageId } = useParams<{ messageId?: string }>();
+ const navigate = useWorkspaceAwareNavigate();
+ const mailbox = useMailbox(agentId, messageId);
+ const mobile = isMobileSurface();
+ const mailPath = urlJoin('/agent', agentId, 'mail');
+
+ // Moving between messages replaces the entry, so back leaves the mail page.
+ const openMessage = (id: string) => {
+ // Pinned so the opened message does not have to be read to know its mailbox.
+ mailbox.select(mailbox.current?.id);
+ navigate(urlJoin(mailPath, id), { replace: Boolean(messageId) });
+ };
+
+ const switchMailbox = (accountId: string) => {
+ mailbox.select(accountId);
+ if (messageId) navigate(mailPath, { replace: true });
+ };
+
+ const mailboxCard = (
+ <MailboxCard agentId={agentId} disabled={disabled} mailbox={mailbox} onSwitch={switchMailbox} />
+ );
+ // Waits for the mailbox so the list never flashes every address's mail first.
+ const inbox = !(mailbox.isLoading && !mailbox.data) && (
+ <InboxSection
+ accountId={mailbox.current?.id}
+ agentId={agentId}
+ selectedId={mobile ? undefined : messageId}
+ onOpen={openMessage}
+ />
+ );
+
+ return (
+ <Flexbox height={'100%'} style={{ position: 'relative' }} width={'100%'}>
+ {mobile ? (
+ <>
+ <NavHeader
+ left={<AgentBreadcrumb agentId={agentId} />}
+ // `relative` anchors the absolutely-centered switcher below.
+ style={{ position: 'relative' }}
+ styles={{
+ // Center on the header midpoint (equal gaps), not the leftover track.
+ center: AGENT_PROFILE_TABS_CENTER_STYLE,
+ left: { minWidth: 0, paddingInlineStart: 8 },
+ }}
+ >
+ <AgentProfileTabs active={'mail'} agentId={agentId} />
+ </NavHeader>
+ <Flexbox flex={1} style={styles.body} width={'100%'}>
+ <WideScreenContainer>
+ <Flexbox gap={24} paddingBlock={16}>
+ {mailboxCard}
+ {inbox}
+ </Flexbox>
+ </WideScreenContainer>
+ </Flexbox>
+ </>
+ ) : (
+ <MailSplitView inbox={inbox} mailbox={mailboxCard} messageId={messageId} />
+ )}
+ {/* Laid over the list instead of replacing it, so back returns to the same scroll. */}
+ {mobile && messageId && (
+ <Flexbox className={identityStyles.mobileDetail}>
+ <NavHeader />
+ <Flexbox flex={1} padding={16} style={styles.body} width={'100%'}>
+ <InboxMessageDetail id={messageId} />
+ </Flexbox>
</Flexbox>
- </WideScreenContainer>
+ )}
</Flexbox>
- </Flexbox>
-);
+ );
+};
+
+/** Keyed so a selected mailbox never carries over to another agent. */
+const AgentMail = (props: AgentMailProps) => <MailPage key={props.agentId} {...props} />;
export default AgentMail;
diff --git a/src/features/AgentMail/styles.ts b/src/features/AgentMail/styles.ts
index 05b0639a012..b3f988c957e 100644
--- a/src/features/AgentMail/styles.ts
+++ b/src/features/AgentMail/styles.ts
@@ -9,12 +9,21 @@ import * as stylex from '@stylexjs/stylex';
* and the accounts are a list of peers, not separate panels.
*/
const definitions = stylex.create({
+ accounts: {
+ flexShrink: 0,
+ overflowY: 'auto',
+ maxHeight: '40%',
+ },
card: {
paddingBlock: '12px',
paddingInline: '14px',
borderRadius: cssVar.borderRadiusLG,
backgroundColor: cssVar.colorFillQuaternary,
},
+ detailPane: {
+ overflowY: 'auto',
+ minWidth: 0,
+ },
empty: {
fontSize: '13px',
lineHeight: 1.6,
@@ -31,10 +40,42 @@ const definitions = stylex.create({
paddingInline: '14px',
borderRadius: cssVar.borderRadiusLG,
backgroundColor: {
- 'default': cssVar.colorFillQuaternary,
+ 'default': 'transparent',
':hover': cssVar.colorFillTertiary,
},
},
+ inboxRowSelected: {
+ backgroundColor: {
+ 'default': cssVar.colorFillSecondary,
+ ':hover': cssVar.colorFillSecondary,
+ },
+ },
+ listPane: {
+ display: 'flex',
+ flexDirection: 'column',
+ flexShrink: 0,
+ width: '384px',
+ minHeight: 0,
+ borderInlineEndWidth: '1px',
+ borderInlineEndStyle: 'solid',
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ },
+ mailboxTrigger: {
+ // The dropdown tints an open trigger; on a card that reads as a stray box.
+ backgroundColor: 'transparent',
+ display: 'flex',
+ flex: '1',
+ gap: '8px',
+ alignItems: 'center',
+ cursor: 'pointer',
+ minWidth: 0,
+ },
+ mobileDetail: {
+ position: 'absolute',
+ inset: 0,
+ zIndex: 1,
+ backgroundColor: cssVar.colorBgContainer,
+ },
subject: {
fontSize: '13px',
color: cssVar.colorTextSecondary,
@@ -49,10 +90,17 @@ const definitions = stylex.create({
});
export const identityStyles = {
+ accounts: stylex.props(definitions.accounts).className ?? '',
card: stylex.props(definitions.card).className ?? '',
+ detailPane: stylex.props(definitions.detailPane).className ?? '',
empty: stylex.props(definitions.empty).className ?? '',
icon: stylex.props(definitions.icon).className ?? '',
inboxRow: stylex.props(definitions.inboxRow).className ?? '',
+ inboxRowSelected:
+ stylex.props(definitions.inboxRow, definitions.inboxRowSelected).className ?? '',
+ listPane: stylex.props(definitions.listPane).className ?? '',
+ mailboxTrigger: stylex.props(definitions.mailboxTrigger).className ?? '',
+ mobileDetail: stylex.props(definitions.mobileDetail).className ?? '',
subject: stylex.props(definitions.subject).className ?? '',
unreadDot: stylex.props(definitions.unreadDot).className ?? '',
};
diff --git a/src/features/AgentMail/useAgentIdentity.ts b/src/features/AgentMail/useAgentIdentity.ts
index 1323a98f68c..1c25bfb7440 100644
--- a/src/features/AgentMail/useAgentIdentity.ts
+++ b/src/features/AgentMail/useAgentIdentity.ts
@@ -1,5 +1,7 @@
import type { AgentInboxMessageSummary } from '@lobechat/types';
+import { useState } from 'react';
import useSWR from 'swr';
+import useSWRImmutable from 'swr/immutable';
import useSWRInfinite from 'swr/infinite';
import { agentAccountService } from '@/services/agentAccount';
@@ -21,25 +23,86 @@ export const INBOX_REFRESH_INTERVAL_MS = 30_000;
export const useAgentAccounts = (agentId: string) =>
useSWR(accountsKey(agentId), ([, id]) => agentAccountService.list({ agentId: id }));
+/** One stored message, read by id rather than taken from a possibly stale list row. */
+export const useInboxMessage = (id?: string) =>
+ useSWR(id ? ['agent-inbox-message', id] : null, ([, messageId]) =>
+ agentAccountService.getInboxMessage(messageId),
+ );
+
+/**
+ * A message reached through its URL rather than a list row: read it and clear
+ * its unread mark before the list and count load, so neither shows it as unread.
+ */
+const openMessageFromUrl = async (id: string) => {
+ const message = await agentAccountService.getInboxMessage(id);
+ if (message.readAt) return message;
+
+ try {
+ await agentAccountService.markInboxRead([id]);
+ } catch (error) {
+ // The message still opens; a failed read-mark only affects the dot.
+ console.error('[AgentIdentity] mark read failed', error);
+ }
+
+ return message;
+};
+
+/**
+ * The mailbox being read, out of the addresses the agent still holds.
+ *
+ * Derived rather than stored as a fallback, so releasing the selected address
+ * lands on the next one without any bookkeeping. Until the reader picks one, a
+ * message opened from its URL decides, so both panes show the same mailbox.
+ */
+export const useMailbox = (agentId: string, messageId?: string) => {
+ const { data, error, isLoading, mutate } = useAgentAccounts(agentId);
+ const [selectedId, select] = useState<string>();
+ // Immutable: one open is one read, so a focus refetch must not stamp it again.
+ const openMessage = useSWRImmutable(
+ !selectedId && messageId ? ['agent-inbox-open-message', messageId] : null,
+ ([, id]) => openMessageFromUrl(id),
+ );
+ const accounts = (data ?? []).filter((account) => account.status !== 'revoked');
+ const preferredId = selectedId ?? openMessage.data?.accountId;
+
+ return {
+ accounts,
+ current: accounts.find((account) => account.id === preferredId) ?? accounts[0],
+ data: openMessage.isLoading ? undefined : data,
+ error,
+ isLoading: isLoading || openMessage.isLoading,
+ mutate,
+ select,
+ };
+};
+
+export type Mailbox = ReturnType<typeof useMailbox>;
+
/**
- * What has arrived at those addresses, newest first.
+ * What has arrived at one address, newest first (every address when none is given).
*
* 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) => {
+export const useAgentInbox = (agentId: string, accountId?: string) => {
const inbox = useSWRInfinite(
(pageIndex, previous: AgentInboxMessageSummary[] | null) => {
if (!agentId) return null;
- if (pageIndex === 0) return ['agent-inbox', agentId, null] as const;
+ if (pageIndex === 0) return ['agent-inbox', agentId, accountId, 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;
+ return [
+ 'agent-inbox',
+ agentId,
+ accountId,
+ { id: last.id, receivedAt: last.receivedAt },
+ ] as const;
},
- ([, id, before]) =>
+ ([, id, account, before]) =>
agentAccountService.listInbox({
+ accountId: account,
agentId: id,
before: before ?? undefined,
limit: INBOX_PAGE_SIZE,
@@ -66,9 +129,9 @@ export const useAgentInbox = (agentId: string) => {
* 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) =>
+export const useAgentInboxUnreadCount = (agentId: string, accountId?: string) =>
useSWR(
- agentId ? ['agent-inbox-unread', agentId] : null,
- ([, id]) => agentAccountService.getInboxUnreadCount(id),
+ agentId ? ['agent-inbox-unread', agentId, accountId] : null,
+ ([, id, account]) => agentAccountService.getInboxUnreadCount(id, account),
{ refreshInterval: INBOX_REFRESH_INTERVAL_MS },
);
diff --git a/src/features/AgentMail/useIdentityActions.test.ts b/src/features/AgentMail/useIdentityActions.test.ts
index 2c3063bb551..b4edc722077 100644
--- a/src/features/AgentMail/useIdentityActions.test.ts
+++ b/src/features/AgentMail/useIdentityActions.test.ts
@@ -98,6 +98,8 @@ describe('useAccountActions', () => {
});
describe('useInboxActions', () => {
+ const onOpen = vi.fn();
+
beforeEach(() => {
vi.clearAllMocks();
service.markAllInboxRead.mockResolvedValue({ count: 1 });
@@ -106,33 +108,33 @@ describe('useInboxActions', () => {
it('opens an unread message and clears its unread mark', async () => {
const onChanged = vi.fn();
- const { result } = renderHook(() => useInboxActions({ agentId: 'agt_1', onChanged }));
+ const { result } = renderHook(() => useInboxActions({ agentId: 'agt_1', onChanged, onOpen }));
await result.current.openMessage(unreadMessage);
- expect(ui.createModal).toHaveBeenCalledTimes(1);
+ expect(onOpen).toHaveBeenCalledWith('msg_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 }));
+ const { result } = renderHook(() => useInboxActions({ agentId: 'agt_1', onChanged, onOpen }));
await result.current.openMessage(readMessage);
- expect(ui.createModal).toHaveBeenCalledTimes(1);
+ expect(onOpen).toHaveBeenCalledWith('msg_2');
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 }));
+ const { result } = renderHook(() => useInboxActions({ agentId: 'agt_1', onChanged, onOpen }));
await result.current.markAllRead();
- expect(service.markAllInboxRead).toHaveBeenCalledWith('agt_1');
+ expect(service.markAllInboxRead).toHaveBeenCalledWith('agt_1', undefined);
expect(onChanged).toHaveBeenCalledTimes(1);
});
});
diff --git a/src/features/AgentMail/useIdentityActions.tsx b/src/features/AgentMail/useIdentityActions.tsx
index 90f793942bd..6ca1a3b56af 100644
--- a/src/features/AgentMail/useIdentityActions.tsx
+++ b/src/features/AgentMail/useIdentityActions.tsx
@@ -1,27 +1,13 @@
'use client';
import type { AgentInboxMessageSummary } from '@lobechat/types';
-import { confirmModal, createModal, toast } from '@lobehub/ui';
+import { confirmModal, 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;
@@ -94,18 +80,26 @@ export const useAccountActions = ({ agentId, onChanged }: UseAccountActionsParam
};
export interface UseInboxActionsParams {
+ /** Keep "mark all read" to the mailbox on screen. */
+ accountId?: string;
agentId: string;
/** Revalidate the inbox after its read state changes. */
onChanged: () => Promise<unknown> | void;
+ onOpen: (id: string) => void;
}
/** Reading the inbox: open one message, or clear the unread marks. */
-export const useInboxActions = ({ agentId, onChanged }: UseInboxActionsParams) => {
+export const useInboxActions = ({
+ accountId,
+ agentId,
+ onChanged,
+ onOpen,
+}: UseInboxActionsParams) => {
const { t } = useTranslation('setting');
const openMessage = useCallback(
async (message: Pick<AgentInboxMessageSummary, 'id' | 'readAt'>) => {
- openMessageModal(message.id);
+ onOpen(message.id);
// Already read: opening it again must not re-stamp `readAt`.
if (message.readAt) return;
@@ -118,18 +112,18 @@ export const useInboxActions = ({ agentId, onChanged }: UseInboxActionsParams) =
console.error('[AgentIdentity] mark read failed', error);
}
},
- [onChanged],
+ [onChanged, onOpen],
);
const markAllRead = useCallback(async () => {
try {
- await agentAccountService.markAllInboxRead(agentId);
+ await agentAccountService.markAllInboxRead(agentId, accountId);
await onChanged();
} catch (error) {
console.error('[AgentIdentity] mark all read failed', error);
toast.error(t('identity.inbox.markAllReadFailed'));
}
- }, [agentId, onChanged, t]);
+ }, [accountId, agentId, onChanged, t]);
return { markAllRead, openMessage };
};
diff --git a/src/features/AgentProfileTabs/tabOptions.test.ts b/src/features/AgentProfileTabs/tabOptions.test.ts
index 053c768de21..7f7a4a40d9b 100644
--- a/src/features/AgentProfileTabs/tabOptions.test.ts
+++ b/src/features/AgentProfileTabs/tabOptions.test.ts
@@ -24,6 +24,10 @@ describe('buildAgentProfileTabPath', () => {
});
describe('getAgentProfileTab', () => {
+ it('keeps the mail tab active on an opened message', () => {
+ expect(getAgentProfileTab('/agent/agt_1/mail/msg_1')).toBe('mail');
+ });
+
it.each([
['/agent/agt_1/profile', 'profile'],
['/agent/agt_1/mail', 'mail'],
diff --git a/src/features/AgentProfileTabs/tabOptions.ts b/src/features/AgentProfileTabs/tabOptions.ts
index d2312c9dd1f..7d8f919d900 100644
--- a/src/features/AgentProfileTabs/tabOptions.ts
+++ b/src/features/AgentProfileTabs/tabOptions.ts
@@ -19,7 +19,7 @@ export const buildAgentProfileTabPath = (agentId: string, tab: AgentProfileTab)
urlJoin('/agent', agentId, tab);
const AGENT_PROFILE_ROUTE =
- /^(?:\/[^/]+)?\/agent\/[^/]+\/(profile|mail|channel(?:\/[^/]+)?|self-evolving(?:\/[^/]+)*|statistics|share)\/?$/;
+ /^(?:\/[^/]+)?\/agent\/[^/]+\/(profile|mail(?:\/[^/]+)?|channel(?:\/[^/]+)?|self-evolving(?:\/[^/]+)*|statistics|share)\/?$/;
/**
* The profile-group tab a URL belongs to, if any. Anchored on Agent subroutes,
diff --git a/src/services/agentAccount.ts b/src/services/agentAccount.ts
index 23f7f300f72..39f8bacccce 100644
--- a/src/services/agentAccount.ts
+++ b/src/services/agentAccount.ts
@@ -97,16 +97,16 @@ class AgentAccountService {
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;
+ getInboxUnreadCount = async (agentId: string, accountId?: string): Promise<number> =>
+ (await lambdaClient.agentAccount.inbox.unreadCount.query({ accountId, 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 });
+ markAllInboxRead = (agentId: string, accountId?: string) =>
+ lambdaClient.agentAccount.inbox.markAllRead.mutate({ accountId, agentId });
}
export const agentAccountService = new AgentAccountService();
diff --git a/src/spa/router/agentPageRoutes.tsx b/src/spa/router/agentPageRoutes.tsx
index 67a23c1cc90..4588bf343f9 100644
--- a/src/spa/router/agentPageRoutes.tsx
+++ b/src/spa/router/agentPageRoutes.tsx
@@ -85,7 +85,7 @@ export const agentPageChildren: RouteObject[] = [
{
element: dynamicElement(() => import('@/routes/(main)/agent/mail'), 'Desktop > Chat > Mail'),
handle: { meta: agentMailRouteMeta },
- path: 'mail',
+ path: 'mail/:messageId?',
},
{
element: dynamicElement(