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.

💄 style(agent-mail): full-page offer to open a mailbox for agents without one (#22722)

Arvin Xufa6fc2befa92
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index af94598ba74..2c1868c7f58 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1037,6 +1037,9 @@
"hotkey.updateSuccess": "Hotkey updated successfully",
"identity.add": "Add mailbox",
"identity.copy": "Copy address",
+ "identity.empty.open": "Open mailbox",
+ "identity.empty.readOnly": "This agent has no mailbox yet",
+ "identity.empty.title": "Give this agent a mailbox",
"identity.hideDetail": "Hide details",
"identity.inbox.detail.attachments": "Attachments",
"identity.inbox.detail.from": "From",
@@ -1057,8 +1060,6 @@
"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",
@@ -1072,7 +1073,6 @@
"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",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index fddfa5fdf92..2b9df968757 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1037,6 +1037,9 @@
"hotkey.updateSuccess": "快捷键更新成功",
"identity.add": "添加邮箱",
"identity.copy": "复制地址",
+ "identity.empty.open": "开通邮箱",
+ "identity.empty.readOnly": "这个 Agent 还没有邮箱",
+ "identity.empty.title": "给 Agent 开通一个邮箱",
"identity.hideDetail": "收起详情",
"identity.inbox.detail.attachments": "附件",
"identity.inbox.detail.from": "发件人",
@@ -1057,8 +1060,6 @@
"identity.mail.title": "邮箱",
"identity.more": "更多操作",
"identity.noAgent": "请选择一个 Agent 以查看它拥有的地址。",
- "identity.prefix.hint": "可选。支持字母、数字、点、下划线和连字符。",
- "identity.prefix.placeholder": "期望的前缀(可选)",
"identity.prefix.required": "邮箱前缀",
"identity.prefix.requiredHint": "可使用字母、数字、点、下划线和短横线。",
"identity.provision": "开通",
@@ -1072,7 +1073,6 @@
"identity.release.title": "释放该地址?",
"identity.retry": "重试",
"identity.showDetail": "查看详情",
- "identity.status.active": "已启用",
"identity.status.provisioning": "开通中",
"identity.status.revoked": "已释放",
"identity.status.suspended": "已暂停",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 7778047ba4f..a7b2ba43156 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -334,6 +334,9 @@ export default {
'agentTab.tts': 'Voice Service',
'identity.add': 'Add mailbox',
'identity.copy': 'Copy address',
+ 'identity.empty.open': 'Open mailbox',
+ 'identity.empty.readOnly': 'This agent has no mailbox yet',
+ 'identity.empty.title': 'Give this agent a mailbox',
'identity.hideDetail': 'Hide details',
'identity.inbox.detail.attachments': 'Attachments',
'identity.inbox.detail.from': 'From',
@@ -354,8 +357,6 @@ export default {
'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',
@@ -370,7 +371,6 @@ export default {
'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',
diff --git a/src/features/AgentMail/MailSplitView.tsx b/src/features/AgentMail/MailSplitView.tsx
index ed19eec29c8..8a1837274f9 100644
--- a/src/features/AgentMail/MailSplitView.tsx
+++ b/src/features/AgentMail/MailSplitView.tsx
@@ -17,6 +17,22 @@ interface MailSplitViewProps {
messageId?: string;
}
+/** The page title a wide screen shows above the mail, or above the offer to open a mailbox. */
+export const MailNavHeader = () => {
+ const { t } = useTranslation('setting');
+
+ return (
+ <NavHeader
+ styles={{ left: { minWidth: 0, paddingInlineStart: 8 } }}
+ left={
+ <Text fontSize={14} weight={500}>
+ {t('identity.mail.title')}
+ </Text>
+ }
+ />
+ );
+};
+
/** 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');
@@ -25,14 +41,7 @@ const MailSplitView = ({ inbox, mailbox, messageId }: MailSplitViewProps) => {
<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 } }}
- />
+ <MailNavHeader />
<Flexbox
flex={1}
gap={16}
diff --git a/src/features/AgentMail/MailboxCard.tsx b/src/features/AgentMail/MailboxCard.tsx
index aabc8b01751..ae8b864ab74 100644
--- a/src/features/AgentMail/MailboxCard.tsx
+++ b/src/features/AgentMail/MailboxCard.tsx
@@ -4,6 +4,7 @@ import {
ActionIcon,
createModal,
DropdownMenu,
+ Empty,
Flexbox,
Icon,
Skeleton,
@@ -16,28 +17,25 @@ 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 { type Mailbox, useOpenableChannel } 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.
+ * Only a state that differs from the working default is worth a label. Released
+ * is 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>;
+} as const satisfies Record<Exclude<AgentAccountView['status'], 'active'>, string>;
const channelOf = (account: AgentAccountView) =>
IDENTITY_CHANNELS.find((channel) => isChannelAccount(account, channel));
@@ -53,14 +51,11 @@ interface MailboxCardProps {
/**
* 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 openable = useOpenableChannel();
const { release } = useAccountActions({
agentId,
onChanged: () => {
@@ -71,9 +66,6 @@ const MailboxCard = memo<MailboxCardProps>(({ agentId, disabled, mailbox, onSwit
},
});
- // 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 ? (
@@ -85,22 +77,7 @@ const MailboxCard = memo<MailboxCardProps>(({ agentId, disabled, mailbox, onSwit
) : 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);
+ if (isLoading && !data) return <Skeleton height={44} width={'100%'} />;
const openAdd = () => {
if (!openable) return;
@@ -109,11 +86,11 @@ const MailboxCard = memo<MailboxCardProps>(({ agentId, disabled, mailbox, onSwit
<AddMailboxForm
agentId={agentId}
channel={openable}
+ onChanged={mutate}
onAdded={(account) => {
onSwitch(account.id);
modal.close();
}}
- onChanged={mutate}
/>
),
footer: null,
@@ -123,6 +100,16 @@ const MailboxCard = memo<MailboxCardProps>(({ agentId, disabled, mailbox, onSwit
});
};
+ // Mail kept from a released address is still listed below; offer a new
+ // address beside it instead of hiding that mail behind the full-page offer.
+ if (!current) {
+ if (failure || !openable || disabled) return failure ?? null;
+
+ return <Empty title={t('identity.empty.open')} variant={'dashed'} onClick={openAdd} />;
+ }
+
+ const channel = channelOf(current);
+
const switchItems = [
...accounts.map((account) => ({
icon:
@@ -174,17 +161,12 @@ const MailboxCard = memo<MailboxCardProps>(({ agentId, disabled, mailbox, onSwit
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>
+ <Text code ellipsis style={{ flex: 1, minWidth: 0 }} weight={500}>
+ {current.identifier}
+ </Text>
+ {current.status !== 'active' && (
+ <Tag style={{ flexShrink: 0 }}>{t(STATUS_KEYS[current.status])}</Tag>
+ )}
<Icon className={identityStyles.icon} icon={ChevronsUpDown} size={14} />
</div>
</DropdownMenu>
diff --git a/src/features/AgentMail/MailboxEmptyState.tsx b/src/features/AgentMail/MailboxEmptyState.tsx
new file mode 100644
index 00000000000..c6614b1cca0
--- /dev/null
+++ b/src/features/AgentMail/MailboxEmptyState.tsx
@@ -0,0 +1,108 @@
+'use client';
+
+import { Button, Empty, Flexbox, Input, Text } from '@lobehub/ui';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { IdentityChannel } from './const';
+import { useAccountActions } from './useIdentityActions';
+
+interface MailboxEmptyStateProps {
+ agentId: string;
+ channel: IdentityChannel;
+ /** Read-only viewer: the absence is stated, but there is nothing to open. */
+ disabled?: boolean;
+ onProvisioned: () => Promise<unknown> | void;
+}
+
+/**
+ * The mail page of an agent with no address: what opening one gives it, the
+ * prefix 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 MailboxEmptyState = memo<MailboxEmptyStateProps>(
+ ({ agentId, channel, disabled, onProvisioned }) => {
+ const { t } = useTranslation('setting');
+ const [prefix, setPrefix] = useState('');
+ const [loading, setLoading] = useState(false);
+ const [failure, setFailure] = useState<string>();
+ const { provision } = useAccountActions({
+ agentId,
+ onChanged: onProvisioned,
+ onProvisionFailed: setFailure,
+ });
+ // Without a prefix the provider would mint an address nobody chose.
+ const empty = channel.prefixable && !prefix.trim();
+
+ const handleProvision = async () => {
+ if (empty || loading) return;
+ setFailure(undefined);
+ setLoading(true);
+ try {
+ await provision(channel, prefix);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const form = (
+ <Flexbox gap={12} style={{ maxWidth: '100%' }} width={360}>
+ {channel.prefixable && (
+ <Flexbox gap={6}>
+ <Input
+ aria-label={t('identity.prefix.required')}
+ disabled={loading}
+ placeholder={t('identity.prefix.required')}
+ size={'large'}
+ suffix={<Text type={'secondary'}>{channel.addressSuffix}</Text>}
+ value={prefix}
+ variant={'filled'}
+ onPressEnter={handleProvision}
+ onChange={(e) => {
+ setPrefix(e.target.value);
+ setFailure(undefined);
+ }}
+ />
+ {failure ? (
+ <Text fontSize={12} role={'alert'} type={'danger'}>
+ {failure}
+ </Text>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ {t('identity.prefix.requiredHint')}
+ </Text>
+ )}
+ </Flexbox>
+ )}
+ <Button
+ block
+ disabled={empty}
+ loading={loading}
+ size={'large'}
+ type={empty ? 'fill' : 'primary'}
+ onClick={handleProvision}
+ >
+ {t('identity.empty.open')}
+ </Button>
+ </Flexbox>
+ );
+
+ return (
+ <Empty
+ action={disabled ? undefined : form}
+ description={t(channel.descKey)}
+ emoji={'📬'}
+ imageSize={72}
+ title={t(disabled ? 'identity.empty.readOnly' : 'identity.empty.title')}
+ titleProps={{ fontSize: 20, weight: 600 }}
+ />
+ );
+ },
+);
+
+MailboxEmptyState.displayName = 'AgentMailboxEmptyState';
+
+export default MailboxEmptyState;
diff --git a/src/features/AgentMail/ProvisionCard.tsx b/src/features/AgentMail/ProvisionCard.tsx
deleted file mode 100644
index 72fa122abd4..00000000000
--- a/src/features/AgentMail/ProvisionCard.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-'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/AgentMail/index.test.tsx b/src/features/AgentMail/index.test.tsx
index fe5d7a473c6..7a67ad621b0 100644
--- a/src/features/AgentMail/index.test.tsx
+++ b/src/features/AgentMail/index.test.tsx
@@ -16,11 +16,15 @@ const service = vi.hoisted(() => ({
vi.mock('@/services/agentAccount', () => ({ agentAccountService: service }));
const surface = vi.hoisted(() => ({ mobile: false }));
+const server = vi.hoisted(() => ({ loaded: true, providers: ['agent-mail'] }));
vi.mock('@/utils/mobileSurface', () => ({ isMobileSurface: () => surface.mobile }));
vi.mock('@/store/serverConfig', () => ({
useServerConfigStore: (selector: (state: unknown) => unknown) =>
- selector({ serverConfig: { agentIdentityProviders: ['agent-mail'] } }),
+ selector({
+ serverConfig: { agentIdentityProviders: server.providers },
+ serverConfigLoaded: server.loaded,
+ }),
}));
vi.mock('@/features/NavHeader', () => ({ default: () => null }));
vi.mock('@/features/AgentBreadcrumb', () => ({ default: () => null }));
@@ -86,12 +90,16 @@ const row = (id: string, subject: string) => ({
subject,
});
-const page = (path = '/agent/agt_1/mail') =>
+const page = (path = '/agent/agt_1/mail', disabled = false) =>
render(
<SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>
<MemoryRouter initialEntries={[path]}>
<Routes>
- <Route element={<AgentMail agentId={'agt_1'} />} path={'/agent/:aid/mail/:messageId?'} />
+ <Route
+ element={<AgentMail agentId={'agt_1'} disabled={disabled} />}
+ path={'/agent/:aid/mail/:messageId?'}
+ />
+ <Route element={<div>profile page</div>} path={'/agent/:aid/profile'} />
</Routes>
</MemoryRouter>
</SWRConfig>,
@@ -100,6 +108,8 @@ const page = (path = '/agent/agt_1/mail') =>
beforeEach(() => {
vi.clearAllMocks();
surface.mobile = false;
+ server.providers = ['agent-mail'];
+ server.loaded = true;
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')],
@@ -212,7 +222,8 @@ describe('AgentMail', () => {
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();
+ // Switching the list and leaving the message are separate updates; wait for both.
+ await waitFor(() => expect(screen.queryByText('Full body of msg_a')).not.toBeInTheDocument());
});
it('adds another mailbox through a dialog', async () => {
@@ -228,10 +239,147 @@ describe('AgentMail', () => {
service.listInbox.mockResolvedValue([]);
page();
- expect(await screen.findByText('identity.provision')).toBeInTheDocument();
+ expect(await screen.findByText('identity.empty.open')).toBeInTheDocument();
expect(screen.queryByText('menu:identity.release')).not.toBeInTheDocument();
});
+ it('gives the whole page to the offer instead of an empty inbox and reader', async () => {
+ service.list.mockResolvedValue([]);
+ service.listInbox.mockResolvedValue([]);
+ page();
+
+ expect(await screen.findByText('identity.empty.title')).toBeInTheDocument();
+ expect(screen.getByText('@lobe.id')).toBeInTheDocument();
+ expect(screen.queryByText('identity.inbox.title')).not.toBeInTheDocument();
+ expect(screen.queryByText('identity.inbox.detail.placeholder')).not.toBeInTheDocument();
+ });
+
+ it('keeps the action unavailable until a prefix is typed', async () => {
+ service.list.mockResolvedValue([]);
+ service.listInbox.mockResolvedValue([]);
+ page();
+
+ await screen.findByText('identity.empty.title');
+ const action = screen.getByRole('button', { name: 'identity.empty.open' });
+ expect(action).toBeDisabled();
+
+ fireEvent.change(screen.getByLabelText('identity.prefix.required'), {
+ target: { value: ' ' },
+ });
+ expect(action).toBeDisabled();
+ expect(service.provision).not.toHaveBeenCalled();
+ });
+
+ it('shows a refused opening inside the form and clears it on the next edit', async () => {
+ service.list.mockResolvedValue([]);
+ service.listInbox.mockResolvedValue([]);
+ service.provision.mockRejectedValue(new Error('prefix is taken'));
+ page();
+
+ const input = await screen.findByLabelText('identity.prefix.required');
+ fireEvent.change(input, { target: { value: 'taken' } });
+ fireEvent.click(screen.getByRole('button', { name: 'identity.empty.open' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('identity.provision.failed');
+ expect(input).toHaveValue('taken');
+
+ fireEvent.change(input, { target: { value: 'other' } });
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('leaves the page when the deployment cannot open a mailbox and the agent has none', async () => {
+ server.providers = [];
+ service.list.mockResolvedValue([]);
+ service.listInbox.mockResolvedValue([]);
+ page();
+
+ expect(await screen.findByText('profile page')).toBeInTheDocument();
+ });
+
+ it('keeps mail from a released address readable instead of the full-page offer', async () => {
+ service.list.mockResolvedValue([]);
+ page('/agent/agt_1/mail/msg_a');
+
+ expect(await screen.findByText('For A')).toBeInTheDocument();
+ expect(await screen.findByText('Full body of msg_a')).toBeInTheDocument();
+ expect(screen.queryByText('identity.empty.title')).not.toBeInTheDocument();
+ expect(screen.getByText('identity.empty.open')).toBeInTheDocument();
+ });
+
+ it('does not leave the page while retained mail exists and no provider is configured', async () => {
+ server.providers = [];
+ service.list.mockResolvedValue([]);
+ page();
+
+ expect(await screen.findByText('For A')).toBeInTheDocument();
+ expect(screen.queryByText('profile page')).not.toBeInTheDocument();
+ });
+
+ it('does not leave the page while the server config is still loading', async () => {
+ server.loaded = false;
+ server.providers = [];
+ service.list.mockResolvedValue([]);
+ service.listInbox.mockResolvedValue([]);
+ page();
+
+ await waitFor(() => expect(service.list).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(screen.queryByText('profile page')).not.toBeInTheDocument();
+ });
+
+ it('keeps an existing mailbox readable after the provider is removed', async () => {
+ server.providers = [];
+ page();
+
+ expect(await screen.findByText('[email protected]')).toBeInTheDocument();
+ expect(screen.queryByText('profile page')).not.toBeInTheDocument();
+ });
+
+ it('shows the address on one row without labelling a working mailbox', async () => {
+ page();
+
+ expect(await screen.findByText('[email protected]')).toBeInTheDocument();
+ expect(screen.queryByText('identity.status.active')).not.toBeInTheDocument();
+ });
+
+ it('opens the first mailbox and moves on to it', async () => {
+ service.list.mockResolvedValueOnce([]);
+ // No mail before the first address; the new address then has its own.
+ service.listInbox.mockImplementation(async ({ accountId }: { accountId?: string }) =>
+ accountId ? [row('msg_a', 'For A')] : [],
+ );
+ service.provision.mockResolvedValue(account('acc_a', '[email protected]'));
+ page();
+
+ fireEvent.change(await screen.findByLabelText('identity.prefix.required'), {
+ target: { value: 'growth' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'identity.empty.open' }));
+
+ expect(await screen.findByText('For A')).toBeInTheDocument();
+ expect(service.provision).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agt_1', prefix: 'growth', provider: 'agent-mail' }),
+ );
+ expect(screen.queryByText('identity.empty.title')).not.toBeInTheDocument();
+ });
+
+ it('states the absence to a read-only viewer without offering to open one', async () => {
+ service.list.mockResolvedValue([]);
+ service.listInbox.mockResolvedValue([]);
+ page('/agent/agt_1/mail', true);
+
+ expect(await screen.findByText('identity.empty.readOnly')).toBeInTheDocument();
+ expect(screen.queryByText('identity.empty.open')).not.toBeInTheDocument();
+ });
+
+ it('does not mistake a failed read for an agent with no mailbox', async () => {
+ service.list.mockRejectedValue(new Error('network down'));
+ page();
+
+ expect(await screen.findByText('identity.loadFailed')).toBeInTheDocument();
+ expect(screen.queryByText('identity.empty.title')).not.toBeInTheDocument();
+ });
+
it('keeps the mailbox on screen when a later refresh fails', async () => {
service.list
.mockResolvedValueOnce([account('acc_user', '[email protected]')])
diff --git a/src/features/AgentMail/index.tsx b/src/features/AgentMail/index.tsx
index fc86dcd39d8..6214b3b3488 100644
--- a/src/features/AgentMail/index.tsx
+++ b/src/features/AgentMail/index.tsx
@@ -1,6 +1,7 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
+import { Center, Flexbox } from '@lobehub/ui';
+import { useEffect } from 'react';
import { useParams } from 'react-router';
import urlJoin from 'url-join';
@@ -9,15 +10,17 @@ import AgentProfileTabs, { AGENT_PROFILE_TABS_CENTER_STYLE } from '@/features/Ag
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useServerConfigStore } from '@/store/serverConfig';
import { isMobileSurface } from '@/utils/mobileSurface';
import { StyleSheet } from '@/utils/styles';
import InboxMessageDetail from './InboxMessageDetail';
import InboxSection from './InboxSection';
import MailboxCard from './MailboxCard';
-import MailSplitView from './MailSplitView';
+import MailboxEmptyState from './MailboxEmptyState';
+import MailSplitView, { MailNavHeader } from './MailSplitView';
import { identityStyles } from './styles';
-import { useMailbox } from './useAgentIdentity';
+import { useAgentInbox, useMailbox, useOpenableChannel } from './useAgentIdentity';
const styles = StyleSheet.create({
body: {
@@ -44,8 +47,25 @@ const MailPage = ({ agentId, disabled }: AgentMailProps) => {
const { messageId } = useParams<{ messageId?: string }>();
const navigate = useWorkspaceAwareNavigate();
const mailbox = useMailbox(agentId, messageId);
+ const openable = useOpenableChannel();
+ const configLoaded = useServerConfigStore((s) => s.serverConfigLoaded);
const mobile = isMobileSurface();
const mailPath = urlJoin('/agent', agentId, 'mail');
+ const noAddress = !!mailbox.data && !mailbox.current;
+ // Releasing an address keeps the mail it received, so "no address" is not
+ // "no mail": only an empty, successfully read inbox counts as nothing to show.
+ // Same key as the inbox list below, so this adds no request of its own.
+ const retained = useAgentInbox(noAddress ? agentId : '');
+ const noMail = noAddress && !retained.error && retained.data?.length === 0;
+ const checkingMail = noAddress && !retained.error && !retained.data;
+ // Nothing to read and nothing this deployment could open, so there is no page.
+ // Until the server config has loaded, an empty provider list is only the
+ // default (a cold desktop start), not the deployment saying it has none.
+ const unavailable = configLoaded && noMail && !openable;
+
+ useEffect(() => {
+ if (unavailable) navigate(urlJoin('/agent', agentId, 'profile'), { replace: true });
+ }, [agentId, navigate, unavailable]);
// Moving between messages replaces the entry, so back leaves the mail page.
const openMessage = (id: string) => {
@@ -59,6 +79,8 @@ const MailPage = ({ agentId, disabled }: AgentMailProps) => {
if (messageId) navigate(mailPath, { replace: true });
};
+ if (unavailable) return null;
+
const mailboxCard = (
<MailboxCard agentId={agentId} disabled={disabled} mailbox={mailbox} onSwitch={switchMailbox} />
);
@@ -72,6 +94,24 @@ const MailPage = ({ agentId, disabled }: AgentMailProps) => {
/>
);
+ // With no address there is nothing to list or read, so the offer takes the
+ // whole page. Waits for a successful read: a failure must not look like "none".
+ const emptyState = checkingMail ? (
+ <Center flex={1} />
+ ) : (
+ noMail &&
+ openable && (
+ <Center flex={1} padding={24} style={{ minHeight: 0 }}>
+ <MailboxEmptyState
+ agentId={agentId}
+ channel={openable}
+ disabled={disabled}
+ onProvisioned={mailbox.mutate}
+ />
+ </Center>
+ )
+ );
+
return (
<Flexbox height={'100%'} style={{ position: 'relative' }} width={'100%'}>
{mobile ? (
@@ -88,14 +128,21 @@ const MailPage = ({ agentId, disabled }: AgentMailProps) => {
>
<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>
+ {emptyState || (
+ <Flexbox flex={1} style={styles.body} width={'100%'}>
+ <WideScreenContainer>
+ <Flexbox gap={24} paddingBlock={16}>
+ {mailboxCard}
+ {inbox}
+ </Flexbox>
+ </WideScreenContainer>
+ </Flexbox>
+ )}
+ </>
+ ) : emptyState ? (
+ <>
+ <MailNavHeader />
+ {emptyState}
</>
) : (
<MailSplitView inbox={inbox} mailbox={mailboxCard} messageId={messageId} />
diff --git a/src/features/AgentMail/useAgentIdentity.ts b/src/features/AgentMail/useAgentIdentity.ts
index 1c25bfb7440..1d357d010a8 100644
--- a/src/features/AgentMail/useAgentIdentity.ts
+++ b/src/features/AgentMail/useAgentIdentity.ts
@@ -5,6 +5,17 @@ import useSWRImmutable from 'swr/immutable';
import useSWRInfinite from 'swr/infinite';
import { agentAccountService } from '@/services/agentAccount';
+import { useServerConfigStore } from '@/store/serverConfig';
+import { serverConfigSelectors } from '@/store/serverConfig/selectors';
+
+import { IDENTITY_CHANNELS } from './const';
+
+/** The channel to offer; one this deployment cannot fulfil would only fail on click. */
+export const useOpenableChannel = () => {
+ const providers = useServerConfigStore(serverConfigSelectors.agentIdentityProviders);
+
+ return IDENTITY_CHANNELS.find((channel) => providers.includes(channel.provider));
+};
const accountsKey = (agentId: string): [string, string] | null =>
agentId ? ['agent-accounts', agentId] : null;
diff --git a/src/features/AgentMail/useIdentityActions.tsx b/src/features/AgentMail/useIdentityActions.tsx
index 6ca1a3b56af..567edb9871f 100644
--- a/src/features/AgentMail/useIdentityActions.tsx
+++ b/src/features/AgentMail/useIdentityActions.tsx
@@ -13,6 +13,8 @@ export interface UseAccountActionsParams {
agentId: string;
/** Revalidate the addresses after opening or releasing one. */
onChanged: () => Promise<unknown> | void;
+ /** Show a refused opening beside the form that asked, instead of in a toast. */
+ onProvisionFailed?: (message: string) => void;
}
/**
@@ -23,7 +25,11 @@ export interface UseAccountActionsParams {
* 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) => {
+export const useAccountActions = ({
+ agentId,
+ onChanged,
+ onProvisionFailed,
+}: UseAccountActionsParams) => {
const { t } = useTranslation('setting');
const provision = useCallback(
@@ -43,15 +49,15 @@ export const useAccountActions = ({ agentId, onChanged }: UseAccountActionsParam
return account;
} catch (error) {
console.error('[AgentIdentity] provision failed', error);
- toast.error(
- t('identity.provision.failed', {
- reason: error instanceof Error ? error.message : String(error),
- }),
- );
+ const message = t('identity.provision.failed', {
+ reason: error instanceof Error ? error.message : String(error),
+ });
+ if (onProvisionFailed) onProvisionFailed(message);
+ else toast.error(message);
return undefined;
}
},
- [agentId, onChanged, t],
+ [agentId, onChanged, onProvisionFailed, t],
);
const release = useCallback(