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): create agents from the identity form (#21987)

Arvin Xu4172c0e524c9
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index c75a22d7c1f..2c17417a046 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1356,6 +1356,8 @@
"settingAgent.export.tags": "Tags",
"settingAgent.export.untitled": "Untitled Agent",
"settingAgent.export.untitledFileName": "agent-profile",
+ "settingAgent.identity.create": "Create",
+ "settingAgent.identity.createFailed": "Could not create the agent, please try again",
"settingAgent.identity.done": "Done",
"settingAgent.identity.edit": "Edit identity",
"settingAgent.identity.saveFailed": "Could not save the identity, please try again",
@@ -1385,6 +1387,7 @@
"settingAgent.selectionPolicy.membersCanSwitchWhenShared": "Can switch when shared",
"settingAgent.selectionPolicy.membersCannotSwitch": "Locked",
"settingAgent.selectionPolicy.membersCannotSwitchWhenShared": "Locked when shared",
+ "settingAgent.slug.autoPlaceholder": "Leave empty to generate one",
"settingAgent.slug.error.builtin": "A builtin agent’s identifier can’t be changed",
"settingAgent.slug.error.invalid": "Use lowercase letters, numbers and hyphens only",
"settingAgent.slug.error.reserved": "This identifier is reserved",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 3ee91c9c63c..f0823a634d2 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1356,6 +1356,8 @@
"settingAgent.export.tags": "标签",
"settingAgent.export.untitled": "未命名助理",
"settingAgent.export.untitledFileName": "助理档案",
+ "settingAgent.identity.create": "创建",
+ "settingAgent.identity.createFailed": "创建助理失败,请重试",
"settingAgent.identity.done": "完成",
"settingAgent.identity.edit": "编辑身份信息",
"settingAgent.identity.saveFailed": "身份信息保存失败,请重试",
@@ -1385,6 +1387,7 @@
"settingAgent.selectionPolicy.membersCanSwitchWhenShared": "公开后可切换",
"settingAgent.selectionPolicy.membersCannotSwitch": "锁定",
"settingAgent.selectionPolicy.membersCannotSwitchWhenShared": "公开后锁定",
+ "settingAgent.slug.autoPlaceholder": "留空则自动生成",
"settingAgent.slug.error.builtin": "内置助理的标识不可修改",
"settingAgent.slug.error.invalid": "只能使用小写字母、数字和连字符",
"settingAgent.slug.error.reserved": "该标识为系统保留",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 734a8f72510..611f903c3e4 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1190,6 +1190,8 @@ export default {
'settingAgent.personalName.pickForMe': 'Name it for me',
'settingAgent.personalName.pickFailed': 'Could not save the name, please try again',
'settingAgent.personalName.roll': 'Roll a random name',
+ 'settingAgent.identity.create': 'Create',
+ 'settingAgent.identity.createFailed': 'Could not create the agent, please try again',
'settingAgent.identity.done': 'Done',
'settingAgent.identity.edit': 'Edit identity',
'settingAgent.identity.saveFailed': 'Could not save the identity, please try again',
@@ -1202,6 +1204,7 @@ export default {
'settingAgent.slug.error.invalid': 'Use lowercase letters, numbers and hyphens only',
'settingAgent.slug.error.reserved': 'This identifier is reserved',
'settingAgent.slug.error.taken': 'This identifier is already in use',
+ 'settingAgent.slug.autoPlaceholder': 'Leave empty to generate one',
'settingAgent.slug.placeholder': 'url-identifier',
'settingAgent.slug.openWith': 'Open it directly with /agent/{{slug}}',
'settingAgent.slug.tooltip': 'The agent’s url identifier — open it with /agent/<slug>',
diff --git a/src/features/AgentIdentityModal/BlindBoxAvatar.tsx b/src/features/AgentIdentityModal/BlindBoxAvatar.tsx
new file mode 100644
index 00000000000..f2bf0feac87
--- /dev/null
+++ b/src/features/AgentIdentityModal/BlindBoxAvatar.tsx
@@ -0,0 +1,91 @@
+'use client';
+
+import * as stylex from '@stylexjs/stylex';
+import { memo, type Ref } from 'react';
+
+import AgentAvatar from '@/components/AgentAvatar';
+import { pickDomProps } from '@/components/AgentAvatar/resolve';
+
+import { useBlindBoxSeed } from './useBlindBoxSeed';
+
+const fadeIn = stylex.keyframes({
+ from: { opacity: 0 },
+ to: { opacity: 1 },
+});
+
+const fadeOut = stylex.keyframes({
+ from: { opacity: 1 },
+ to: { opacity: 0 },
+});
+
+const styles = stylex.create({
+ stack: {
+ position: 'relative',
+ display: 'inline-flex',
+ flexShrink: 0,
+ },
+ // The outgoing character sits on top of the incoming one in the same box.
+ outgoing: {
+ position: 'absolute',
+ insetBlockStart: 0,
+ insetInlineStart: 0,
+ display: 'inline-flex',
+ pointerEvents: 'none',
+ animationName: fadeOut,
+ animationDuration: {
+ 'default': '600ms',
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
+ animationTimingFunction: 'ease-in-out',
+ animationFillMode: 'forwards',
+ },
+ incoming: {
+ display: 'inline-flex',
+ animationName: fadeIn,
+ animationDuration: {
+ 'default': '600ms',
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
+ animationTimingFunction: 'ease-in-out',
+ animationFillMode: 'both',
+ },
+});
+
+interface BlindBoxAvatarProps {
+ [key: string]: unknown;
+ className?: string;
+ name?: string;
+ ref?: Ref<HTMLSpanElement>;
+ size: number;
+}
+
+/**
+ * The generated agent character, cross-fading to a new one every couple of
+ * seconds: the agent's real character is decided by an id it does not have yet.
+ */
+const BlindBoxAvatar = memo<BlindBoxAvatarProps>(({ className, name, ref, size, ...rest }) => {
+ const { seed, previousSeed } = useBlindBoxSeed(true);
+
+ // It renders as the emoji picker's trigger, so the handlers, aria and anchor
+ // ref the picker injects must reach the DOM — dropping them leaves the picker
+ // unopenable. Same forwarding as AgentAvatar's generated branch.
+ return (
+ <span
+ {...pickDomProps(rest)}
+ className={[stylex.props(styles.stack).className, className].filter(Boolean).join(' ')}
+ ref={ref}
+ >
+ {/* Keyed by seed so each swap remounts both layers and replays the fades. */}
+ <span {...stylex.props(styles.incoming)} key={seed}>
+ <AgentAvatar agentId={seed} name={name} size={size} />
+ </span>
+ {previousSeed && (
+ <span {...stylex.props(styles.outgoing)} key={previousSeed}>
+ <AgentAvatar agentId={previousSeed} name={name} size={size} />
+ </span>
+ )}
+ </span>
+ );
+});
+
+export default BlindBoxAvatar;
diff --git a/src/features/AgentIdentityModal/Content.tsx b/src/features/AgentIdentityModal/Content.tsx
index 6924db3dd8f..1fb941c594b 100644
--- a/src/features/AgentIdentityModal/Content.tsx
+++ b/src/features/AgentIdentityModal/Content.tsx
@@ -1,160 +1,32 @@
'use client';
-import { randomAgentName } from '@lobechat/const';
-import {
- ActionIcon,
- Button,
- cssVar,
- Flexbox,
- Input,
- Text,
- TextArea,
- useModalContext,
-} from '@lobehub/ui';
-import { DicesIcon } from 'lucide-react';
-import { memo, type ReactNode, useCallback } from 'react';
+import { Button, Flexbox, useModalContext } from '@lobehub/ui';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useGlobalStore } from '@/store/global';
-import { globalGeneralSelectors } from '@/store/global/selectors';
-import { useHomeStore } from '@/store/home';
-import { homeAgentListSelectors } from '@/store/home/selectors';
-
+import IdentityFields from './IdentityFields';
import { useAgentIdentityForm } from './useAgentIdentityForm';
-interface FieldProps {
- children: ReactNode;
- hint?: ReactNode;
- label: string;
-}
-
-const Field = memo<FieldProps>(({ label, hint, children }) => (
- <Flexbox gap={6}>
- <Text type={'secondary'}>{label}</Text>
- {children}
- {hint}
- </Flexbox>
-));
-
interface AgentIdentityContentProps {
agentId: string;
}
-/** Matches the `agents.description` column width. */
-const DESCRIPTION_MAX_LENGTH = 1000;
-
/**
* The identity fields as a real form. They used to be inline inputs in the
* profile header, which crowded it and left no room for a per-field label or
* error. All behaviour lives in {@link useAgentIdentityForm}.
*/
const AgentIdentityContent = memo<AgentIdentityContentProps>(({ agentId }) => {
- const { t } = useTranslation(['setting', 'common']);
+ const { t } = useTranslation('common');
const { close } = useModalContext();
- const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
const form = useAgentIdentityForm({ agentId, onSaved: close });
- const { setName } = form;
-
- // Same draw as the header's "name it for me" button: the pool matches the
- // user's language, and names already visible in the sidebar are excluded so
- // the dice never suggests a second "佳宁". Read at click time — the list only
- // matters at the moment of the roll.
- const rollName = useCallback(() => {
- const takenNames = homeAgentListSelectors
- .allAgents(useHomeStore.getState())
- .filter((agent) => agent.id !== agentId)
- .map((agent) => agent.name)
- .filter((name): name is string => !!name);
-
- setName(randomAgentName(locale, takenNames));
- }, [agentId, locale, setName]);
return (
<Flexbox gap={20} padding={20}>
- <Field label={t('settingAgent.personalName.label', { ns: 'setting' })}>
- <Input
- autoFocus
- placeholder={t('settingAgent.personalName.placeholder', { ns: 'setting' })}
- value={form.name}
- suffix={
- <ActionIcon
- icon={DicesIcon}
- size={'small'}
- title={t('settingAgent.personalName.roll', { ns: 'setting' })}
- onClick={rollName}
- />
- }
- onChange={(e) => form.setName(e.target.value)}
- />
- </Field>
- <Field label={t('settingAgent.role.label', { ns: 'setting' })}>
- <Input
- placeholder={t('settingAgent.role.placeholder', { ns: 'setting' })}
- value={form.title}
- onChange={(e) => form.setTitle(e.target.value)}
- />
- </Field>
- {/* Other agents read this when they list agents to pick a teammate, so
- the hint says who the text is for. */}
- <Field
- label={t('settingAgent.description.label', { ns: 'setting' })}
- hint={
- <Text style={{ fontSize: 12 }} type={'secondary'}>
- {t('settingAgent.description.hint', { ns: 'setting' })}
- </Text>
- }
- >
- <TextArea
- autoSize={{ maxRows: 6, minRows: 2 }}
- maxLength={DESCRIPTION_MAX_LENGTH}
- placeholder={t('settingAgent.description.inputPlaceholder', { ns: 'setting' })}
- value={form.description}
- onChange={(e) => form.setDescription(e.target.value)}
- />
- </Field>
- {/* A builtin agent's identifier is not an editable field at all, so it is
- not dressed as one: a disabled input still reads as "a control you
- can't use right now" and needs a sentence explaining itself. Rendering
- the bare marker states the fact and needs no caption. */}
- {form.slugLocked ? (
- <Field label={t('settingAgent.slug.label', { ns: 'setting' })}>
- <Text code style={{ alignSelf: 'flex-start', color: cssVar.colorTextSecondary }}>
- <span style={{ color: cssVar.colorTextTertiary }}>@</span>
- {form.slug}
- </Text>
- </Field>
- ) : (
- <Field
- label={t('settingAgent.slug.label', { ns: 'setting' })}
- hint={
- <Text style={{ fontSize: 12 }} type={form.error ? 'danger' : 'secondary'}>
- {/* Show the url the current input actually produces — a literal
- `<slug>` leaves the reader to do the substitution themselves,
- and it updates as they type. Only an empty field falls back to
- describing the field in the abstract. */}
- {form.error ??
- (form.slug.trim()
- ? t('settingAgent.slug.openWith', {
- ns: 'setting',
- slug: form.slug.trim().toLowerCase(),
- })
- : t('settingAgent.slug.tooltip', { ns: 'setting' }))}
- </Text>
- }
- >
- <Input
- aria-invalid={!!form.error}
- data-invalid={form.error ? '' : undefined}
- placeholder={t('settingAgent.slug.placeholder', { ns: 'setting' })}
- prefix={'@'}
- value={form.slug}
- onChange={(e) => form.setSlug(e.target.value)}
- />
- </Field>
- )}
+ <IdentityFields agentId={agentId} form={form} />
<Flexbox horizontal gap={8} justify={'flex-end'}>
<Button disabled={form.saving} onClick={() => close()}>
- {t('cancel', { ns: 'common' })}
+ {t('cancel')}
</Button>
<Button
disabled={form.saving}
@@ -164,7 +36,7 @@ const AgentIdentityContent = memo<AgentIdentityContentProps>(({ agentId }) => {
void form.save();
}}
>
- {t('save', { ns: 'common' })}
+ {t('save')}
</Button>
</Flexbox>
</Flexbox>
diff --git a/src/features/AgentIdentityModal/CreateContent.tsx b/src/features/AgentIdentityModal/CreateContent.tsx
new file mode 100644
index 00000000000..58c48bb26b4
--- /dev/null
+++ b/src/features/AgentIdentityModal/CreateContent.tsx
@@ -0,0 +1,100 @@
+'use client';
+
+import { Button, Center, Flexbox, toast, useModalContext } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AgentAvatar from '@/components/AgentAvatar';
+import EmojiPicker from '@/components/EmojiPicker';
+import { useGlobalStore } from '@/store/global';
+import { globalGeneralSelectors } from '@/store/global/selectors';
+
+import BlindBoxAvatar from './BlindBoxAvatar';
+import IdentityFields from './IdentityFields';
+import {
+ useCreateAgentIdentityForm,
+ type UseCreateAgentIdentityFormOptions,
+} from './useCreateAgentIdentityForm';
+
+export type CreateAgentIdentityContentProps = UseCreateAgentIdentityFormOptions;
+
+/**
+ * Creating an agent is filling in who it is: avatar on top, then the same
+ * identity fields the edit form has. Everything else (prompt, model, skills) is
+ * configured on the profile page the new agent opens on.
+ */
+const CreateAgentIdentityContent = memo<CreateAgentIdentityContentProps>(
+ ({ groupId, onCreated, visibility }) => {
+ const { t } = useTranslation(['setting', 'common']);
+ const { close } = useModalContext();
+ const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
+ const form = useCreateAgentIdentityForm({
+ groupId,
+ onCreated: (agentId) => {
+ close();
+ onCreated(agentId);
+ },
+ visibility,
+ });
+
+ return (
+ <Flexbox gap={20} padding={20}>
+ <Center>
+ <EmojiPicker
+ allowUpload
+ allowDelete={!!form.avatar}
+ loading={form.uploading}
+ locale={locale}
+ popupProps={{ placement: 'bottom' }}
+ shape={'square'}
+ size={72}
+ value={form.avatar}
+ // Same avatar the agent wears everywhere else. Without an emoji or
+ // image it is the generated character — which the agent's future id
+ // decides, so the preview cross-fades as a blind box rather than
+ // promising one character.
+ customRender={() =>
+ form.avatar ? (
+ <AgentAvatar
+ avatar={form.avatar}
+ className={'lobe-emoji-picker-avatar'}
+ name={form.name}
+ size={72}
+ />
+ ) : (
+ <BlindBoxAvatar className={'lobe-emoji-picker-avatar'} name={form.name} size={72} />
+ )
+ }
+ onChange={(avatar) => form.setAvatar(avatar)}
+ onDelete={() => form.setAvatar(undefined)}
+ onUpload={async (file) => {
+ if ((await form.uploadAvatar(file)) === 'tooLarge')
+ toast.error(t('settingAgent.avatar.sizeExceeded', { ns: 'setting' }));
+ }}
+ />
+ </Center>
+ <IdentityFields
+ form={form}
+ slugPlaceholder={t('settingAgent.slug.autoPlaceholder', { ns: 'setting' })}
+ />
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button disabled={form.saving} onClick={() => close()}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ disabled={form.saving || form.uploading}
+ loading={form.saving}
+ type={'primary'}
+ onClick={() => {
+ void form.submit();
+ }}
+ >
+ {t('settingAgent.identity.create', { ns: 'setting' })}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+export default CreateAgentIdentityContent;
diff --git a/src/features/AgentIdentityModal/IdentityFields.tsx b/src/features/AgentIdentityModal/IdentityFields.tsx
new file mode 100644
index 00000000000..73b1f9ea4ee
--- /dev/null
+++ b/src/features/AgentIdentityModal/IdentityFields.tsx
@@ -0,0 +1,157 @@
+'use client';
+
+import { randomAgentName } from '@lobechat/const';
+import { ActionIcon, cssVar, Flexbox, Input, Text, TextArea } from '@lobehub/ui';
+import { DicesIcon } from 'lucide-react';
+import { memo, type ReactNode, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useGlobalStore } from '@/store/global';
+import { globalGeneralSelectors } from '@/store/global/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+
+interface FieldProps {
+ children: ReactNode;
+ hint?: ReactNode;
+ label: string;
+}
+
+const Field = memo<FieldProps>(({ label, hint, children }) => (
+ <Flexbox gap={6}>
+ <Text type={'secondary'}>{label}</Text>
+ {children}
+ {hint}
+ </Flexbox>
+));
+
+/** The field values and setters both the edit and the create form expose. */
+export interface IdentityFieldsForm {
+ description: string;
+ error?: string;
+ name: string;
+ setDescription: (value: string) => void;
+ setName: (value: string) => void;
+ setSlug: (value: string) => void;
+ setTitle: (value: string) => void;
+ slug: string;
+ slugLocked: boolean;
+ title: string;
+}
+
+interface IdentityFieldsProps {
+ /** The agent being edited, so the dice never suggests its own current name back. */
+ agentId?: string;
+ form: IdentityFieldsForm;
+ /** Overrides the slug placeholder, e.g. to say an empty slug is generated. */
+ slugPlaceholder?: string;
+}
+
+/** Matches the `agents.description` column width. */
+const DESCRIPTION_MAX_LENGTH = 1000;
+
+/** Name / role / description / slug, shared by the edit and the create form. */
+const IdentityFields = memo<IdentityFieldsProps>(({ agentId, form, slugPlaceholder }) => {
+ const { t } = useTranslation('setting');
+ const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
+ const { setName } = form;
+
+ // Same draw as the header's "name it for me" button: the pool matches the
+ // user's language, and names already visible in the sidebar are excluded so
+ // the dice never suggests a second "佳宁". Read at click time — the list only
+ // matters at the moment of the roll.
+ const rollName = useCallback(() => {
+ const takenNames = homeAgentListSelectors
+ .allAgents(useHomeStore.getState())
+ .filter((agent) => agent.id !== agentId)
+ .map((agent) => agent.name)
+ .filter((name): name is string => !!name);
+
+ setName(randomAgentName(locale, takenNames));
+ }, [agentId, locale, setName]);
+
+ return (
+ <>
+ <Field label={t('settingAgent.personalName.label')}>
+ <Input
+ autoFocus
+ placeholder={t('settingAgent.personalName.placeholder')}
+ value={form.name}
+ suffix={
+ <ActionIcon
+ icon={DicesIcon}
+ size={'small'}
+ title={t('settingAgent.personalName.roll')}
+ onClick={rollName}
+ />
+ }
+ onChange={(e) => form.setName(e.target.value)}
+ />
+ </Field>
+ <Field label={t('settingAgent.role.label')}>
+ <Input
+ placeholder={t('settingAgent.role.placeholder')}
+ value={form.title}
+ onChange={(e) => form.setTitle(e.target.value)}
+ />
+ </Field>
+ {/* Other agents read this when they list agents to pick a teammate, so
+ the hint says who the text is for. */}
+ <Field
+ label={t('settingAgent.description.label')}
+ hint={
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ {t('settingAgent.description.hint')}
+ </Text>
+ }
+ >
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ maxLength={DESCRIPTION_MAX_LENGTH}
+ placeholder={t('settingAgent.description.inputPlaceholder')}
+ value={form.description}
+ onChange={(e) => form.setDescription(e.target.value)}
+ />
+ </Field>
+ {/* A builtin agent's identifier is not an editable field at all, so it is
+ not dressed as one: a disabled input still reads as "a control you
+ can't use right now" and needs a sentence explaining itself. Rendering
+ the bare marker states the fact and needs no caption. */}
+ {form.slugLocked ? (
+ <Field label={t('settingAgent.slug.label')}>
+ <Text code style={{ alignSelf: 'flex-start', color: cssVar.colorTextSecondary }}>
+ <span style={{ color: cssVar.colorTextTertiary }}>@</span>
+ {form.slug}
+ </Text>
+ </Field>
+ ) : (
+ <Field
+ label={t('settingAgent.slug.label')}
+ hint={
+ <Text style={{ fontSize: 12 }} type={form.error ? 'danger' : 'secondary'}>
+ {/* Show the url the current input actually produces — a literal
+ `<slug>` leaves the reader to do the substitution themselves,
+ and it updates as they type. Only an empty field falls back to
+ describing the field in the abstract. */}
+ {form.error ??
+ (form.slug.trim()
+ ? t('settingAgent.slug.openWith', { slug: form.slug.trim().toLowerCase() })
+ : t('settingAgent.slug.tooltip'))}
+ </Text>
+ }
+ >
+ <Input
+ aria-invalid={!!form.error}
+ data-invalid={form.error ? '' : undefined}
+ placeholder={slugPlaceholder ?? t('settingAgent.slug.placeholder')}
+ prefix={'@'}
+ value={form.slug}
+ onChange={(e) => form.setSlug(e.target.value)}
+ />
+ </Field>
+ )}
+ </>
+ );
+});
+
+export default IdentityFields;
diff --git a/src/features/AgentIdentityModal/index.tsx b/src/features/AgentIdentityModal/index.tsx
index 3c5feb5b51e..c755ef8ec50 100644
--- a/src/features/AgentIdentityModal/index.tsx
+++ b/src/features/AgentIdentityModal/index.tsx
@@ -4,6 +4,9 @@ import { createModal } from '@lobehub/ui';
import { t } from 'i18next';
import AgentIdentityContent from './Content';
+import CreateAgentIdentityContent, { type CreateAgentIdentityContentProps } from './CreateContent';
+
+const MODAL_WIDTH = 'min(90%, 460px)';
/** Open the identity form (name / role / description / slug) for a specific agent. */
export const createAgentIdentityModal = (agentId: string) =>
@@ -12,5 +15,28 @@ export const createAgentIdentityModal = (agentId: string) =>
footer: null,
styles: { content: { padding: 0 } },
title: t('settingAgent.identity.edit', { ns: 'setting' }),
- width: 'min(90%, 460px)',
+ width: MODAL_WIDTH,
+ });
+
+export interface OpenCreateAgentIdentityModalOptions extends CreateAgentIdentityContentProps {
+ /** Runs once the modal has been dismissed, for whatever reason. */
+ onClosed?: () => void;
+}
+
+/** Open the create-agent form: avatar plus the identity fields. */
+export const openCreateAgentIdentityModal = ({
+ onClosed,
+ ...contentProps
+}: OpenCreateAgentIdentityModalOptions) =>
+ createModal({
+ content: <CreateAgentIdentityContent {...contentProps} />,
+ footer: null,
+ // `onOpenChange` only fires for user dismissal; the in-content close goes
+ // through `instance.close()`, which only `onOpenChangeComplete` observes.
+ onOpenChangeComplete: (open) => {
+ if (!open) onClosed?.();
+ },
+ styles: { content: { padding: 0 } },
+ title: t('newAgent', { ns: 'chat' }),
+ width: MODAL_WIDTH,
});
diff --git a/src/features/AgentIdentityModal/useBlindBoxSeed.test.ts b/src/features/AgentIdentityModal/useBlindBoxSeed.test.ts
new file mode 100644
index 00000000000..bf8b3ff2c87
--- /dev/null
+++ b/src/features/AgentIdentityModal/useBlindBoxSeed.test.ts
@@ -0,0 +1,52 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BLIND_BOX_INTERVAL, useBlindBoxSeed } from './useBlindBoxSeed';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('useBlindBoxSeed', () => {
+ it('changes the seed every interval while active', () => {
+ const { result } = renderHook(() => useBlindBoxSeed(true));
+ const first = result.current.seed;
+
+ act(() => vi.advanceTimersByTime(BLIND_BOX_INTERVAL - 1));
+ expect(result.current.seed).toBe(first);
+
+ act(() => vi.advanceTimersByTime(1));
+ const second = result.current.seed;
+ expect(second).not.toBe(first);
+
+ act(() => vi.advanceTimersByTime(BLIND_BOX_INTERVAL));
+ expect(result.current.seed).not.toBe(second);
+ });
+
+ // The outgoing character stays mounted for the cross-fade.
+ it('keeps the replaced seed as the previous one', () => {
+ const { result } = renderHook(() => useBlindBoxSeed(true));
+ const first = result.current.seed;
+ expect(result.current.previousSeed).toBeUndefined();
+
+ act(() => vi.advanceTimersByTime(BLIND_BOX_INTERVAL));
+
+ expect(result.current.previousSeed).toBe(first);
+ });
+
+ it('holds still while inactive, e.g. once the user picked an avatar', () => {
+ const { result, rerender } = renderHook(({ active }) => useBlindBoxSeed(active), {
+ initialProps: { active: true },
+ });
+
+ rerender({ active: false });
+ const held = result.current;
+ act(() => vi.advanceTimersByTime(BLIND_BOX_INTERVAL * 3));
+
+ expect(result.current).toBe(held);
+ });
+});
diff --git a/src/features/AgentIdentityModal/useBlindBoxSeed.ts b/src/features/AgentIdentityModal/useBlindBoxSeed.ts
new file mode 100644
index 00000000000..1b4cef7eb6b
--- /dev/null
+++ b/src/features/AgentIdentityModal/useBlindBoxSeed.ts
@@ -0,0 +1,36 @@
+import { useEffect, useState } from 'react';
+
+export const BLIND_BOX_INTERVAL = 2000;
+
+const randomSeed = () => Math.random().toString(36).slice(2, 10);
+
+interface BlindBoxSeeds {
+ /** The character fading out; absent until the first swap. */
+ previousSeed?: string;
+ seed: string;
+}
+
+/**
+ * A seed for the generated agent character that changes every
+ * {@link BLIND_BOX_INTERVAL} ms while `active`, plus the one it replaced so
+ * the two can cross-fade.
+ *
+ * Before the agent exists it has no id, and the character it finally wears is
+ * seeded by that id — so no single preview can be the real one. Cycling makes
+ * the preview read as a blind box instead of a promise.
+ */
+export const useBlindBoxSeed = (active: boolean): BlindBoxSeeds => {
+ const [seeds, setSeeds] = useState<BlindBoxSeeds>(() => ({ seed: randomSeed() }));
+
+ useEffect(() => {
+ if (!active) return;
+
+ const timer = setInterval(
+ () => setSeeds(({ seed }) => ({ previousSeed: seed, seed: randomSeed() })),
+ BLIND_BOX_INTERVAL,
+ );
+ return () => clearInterval(timer);
+ }, [active]);
+
+ return seeds;
+};
diff --git a/src/features/AgentIdentityModal/useCreateAgentIdentityForm.test.ts b/src/features/AgentIdentityModal/useCreateAgentIdentityForm.test.ts
new file mode 100644
index 00000000000..1de897a6415
--- /dev/null
+++ b/src/features/AgentIdentityModal/useCreateAgentIdentityForm.test.ts
@@ -0,0 +1,194 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MAX_AVATAR_SIZE, useCreateAgentIdentityForm } from './useCreateAgentIdentityForm';
+
+const mocks = vi.hoisted(() => ({
+ confirmAgentSlug: vi.fn(),
+ createAgent: vi.fn(),
+ refreshAgentConfig: vi.fn(),
+ refreshAgentList: vi.fn(),
+ updateAgentMeta: vi.fn(),
+ updateAgentSlug: vi.fn(),
+ uploadWithProgress: vi.fn(),
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ randomAgentName: () => '小朵',
+}));
+
+vi.mock('@/store/home', () => {
+ const state = () => ({
+ refreshAgentList: mocks.refreshAgentList,
+ updateAgentMeta: mocks.updateAgentMeta,
+ });
+ const useHomeStore = (selector: (s: unknown) => unknown) => selector(state());
+ useHomeStore.getState = state;
+ return { useHomeStore };
+});
+
+vi.mock('@/store/home/selectors', () => ({
+ homeAgentListSelectors: { allAgents: () => [] },
+}));
+
+vi.mock('@/store/global', () => ({ useGlobalStore: { getState: () => ({}) } }));
+vi.mock('@/store/global/selectors', () => ({
+ globalGeneralSelectors: { currentLanguage: () => 'zh-CN' },
+}));
+
+vi.mock('@/store/file', () => ({
+ useFileStore: (selector: (s: unknown) => unknown) =>
+ selector({ uploadWithProgress: mocks.uploadWithProgress }),
+}));
+
+vi.mock('@/services/agent', () => ({
+ agentService: {
+ updateAgentSlug: (...args: unknown[]) => mocks.updateAgentSlug(...args),
+ },
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: unknown) => unknown) =>
+ selector({
+ createAgent: mocks.createAgent,
+ internal_confirmAgentSlug: mocks.confirmAgentSlug,
+ internal_refreshAgentConfig: mocks.refreshAgentConfig,
+ }),
+}));
+
+const setup = (options: { groupId?: string; visibility?: 'private' | 'public' } = {}) => {
+ const onCreated = vi.fn();
+ const view = renderHook(() => useCreateAgentIdentityForm({ ...options, onCreated }));
+ return { onCreated, ...view };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createAgent.mockResolvedValue({ agentId: 'agent-new' });
+ mocks.updateAgentSlug.mockResolvedValue({ success: true });
+});
+
+describe('useCreateAgentIdentityForm', () => {
+ it('starts with a drawn name so the agent never lands nameless', () => {
+ const { result } = setup();
+
+ expect(result.current.name).toBe('小朵');
+ expect(result.current.slug).toBe('');
+ });
+
+ it('creates the agent with the whole identity and hands back its id', async () => {
+ const { result, onCreated } = setup({ groupId: 'grp', visibility: 'private' });
+
+ act(() => {
+ result.current.setAvatar('🦊');
+ result.current.setTitle(' Health Assistant ');
+ result.current.setDescription('Tracks sleep\n');
+ });
+ await act(async () => {
+ await result.current.submit();
+ });
+
+ expect(mocks.createAgent).toHaveBeenCalledExactlyOnceWith({
+ config: {
+ avatar: '🦊',
+ description: 'Tracks sleep',
+ name: '小朵',
+ title: 'Health Assistant',
+ },
+ groupId: 'grp',
+ visibility: 'private',
+ });
+ // An empty slug is left to the server to generate.
+ expect(mocks.updateAgentSlug).not.toHaveBeenCalled();
+ expect(mocks.refreshAgentList).toHaveBeenCalled();
+ expect(onCreated).toHaveBeenCalledExactlyOnceWith('agent-new');
+ });
+
+ it('applies a custom slug to the created agent, normalized to lowercase', async () => {
+ const { result, onCreated } = setup();
+
+ act(() => result.current.setSlug('My-Agent'));
+ await act(async () => {
+ await result.current.submit();
+ });
+
+ expect(mocks.updateAgentSlug).toHaveBeenCalledExactlyOnceWith('agent-new', 'my-agent');
+ expect(mocks.confirmAgentSlug).toHaveBeenCalledWith('agent-new', 'my-agent', {
+ scope: expect.any(String),
+ });
+ expect(mocks.refreshAgentConfig).toHaveBeenCalledWith('agent-new');
+ expect(onCreated).toHaveBeenCalledWith('agent-new');
+ });
+
+ it('keeps the form open on a rejected slug and does not create a second agent on retry', async () => {
+ mocks.updateAgentSlug.mockResolvedValueOnce({ reason: 'taken', success: false });
+ const { result, onCreated } = setup();
+
+ act(() => result.current.setSlug('taken'));
+ await act(async () => {
+ await result.current.submit();
+ });
+
+ expect(result.current.error).toBe('settingAgent.slug.error.taken');
+ expect(onCreated).not.toHaveBeenCalled();
+
+ act(() => {
+ result.current.setSlug('free');
+ result.current.setName('小艾');
+ });
+ expect(result.current.error).toBeUndefined();
+ await act(async () => {
+ await result.current.submit();
+ });
+
+ expect(mocks.createAgent).toHaveBeenCalledOnce();
+ expect(mocks.updateAgentMeta).toHaveBeenCalledExactlyOnceWith('agent-new', {
+ avatar: null,
+ description: '',
+ name: '小艾',
+ title: '',
+ });
+ expect(mocks.updateAgentSlug).toHaveBeenLastCalledWith('agent-new', 'free');
+ expect(onCreated).toHaveBeenCalledExactlyOnceWith('agent-new');
+ });
+
+ it('shows a reason instead of closing when the create fails', async () => {
+ mocks.createAgent.mockRejectedValueOnce(new Error('boom'));
+ const { result, onCreated } = setup();
+
+ await act(async () => {
+ await result.current.submit();
+ });
+
+ expect(result.current.error).toBe('settingAgent.identity.createFailed');
+ expect(result.current.saving).toBe(false);
+ expect(onCreated).not.toHaveBeenCalled();
+ });
+
+ it('uses the uploaded image as the avatar', async () => {
+ mocks.uploadWithProgress.mockResolvedValue({ url: 'https://cdn/avatar.png' });
+ const { result } = setup();
+
+ await act(async () => {
+ await result.current.uploadAvatar(new File(['x'], 'a.png', { type: 'image/png' }));
+ });
+
+ expect(result.current.avatar).toBe('https://cdn/avatar.png');
+ expect(result.current.uploading).toBe(false);
+ });
+
+ it('refuses an image over the upload limit without uploading it', async () => {
+ const { result } = setup();
+ const file = new File([new Uint8Array(MAX_AVATAR_SIZE + 1)], 'big.png');
+
+ let outcome: unknown;
+ await act(async () => {
+ outcome = await result.current.uploadAvatar(file);
+ });
+
+ expect(outcome).toBe('tooLarge');
+ expect(mocks.uploadWithProgress).not.toHaveBeenCalled();
+ expect(result.current.avatar).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentIdentityModal/useCreateAgentIdentityForm.ts b/src/features/AgentIdentityModal/useCreateAgentIdentityForm.ts
new file mode 100644
index 00000000000..7a0093aac9a
--- /dev/null
+++ b/src/features/AgentIdentityModal/useCreateAgentIdentityForm.ts
@@ -0,0 +1,142 @@
+import { randomAgentName } from '@lobechat/const';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { cacheScope } from '@/libs/replica';
+import { agentService } from '@/services/agent';
+import { useAgentStore } from '@/store/agent';
+import { useFileStore } from '@/store/file';
+import { useGlobalStore } from '@/store/global';
+import { globalGeneralSelectors } from '@/store/global/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+
+/** Uploaded avatars go through a server action, which caps the body at 1MB. */
+export const MAX_AVATAR_SIZE = 1024 * 1024;
+
+export interface UseCreateAgentIdentityFormOptions {
+ groupId?: string;
+ onCreated: (agentId: string) => void;
+ visibility?: 'private' | 'public';
+}
+
+const drawInitialName = () => {
+ const locale = globalGeneralSelectors.currentLanguage(useGlobalStore.getState());
+ const takenNames = homeAgentListSelectors
+ .allAgents(useHomeStore.getState())
+ .map((agent) => agent.name)
+ .filter((name): name is string => !!name);
+
+ return randomAgentName(locale, takenNames);
+};
+
+/**
+ * Drives the create-agent form: avatar plus the same identity fields the edit
+ * form has.
+ *
+ * The slug is optional — left empty, the server generates one. A custom slug
+ * can only be validated against an existing agent (`updateAgentSlug`), so it is
+ * applied right after the create. When it is rejected the form stays open with
+ * the reason, and the next submit updates the agent already created instead of
+ * creating a second one.
+ */
+export const useCreateAgentIdentityForm = ({
+ groupId,
+ onCreated,
+ visibility,
+}: UseCreateAgentIdentityFormOptions) => {
+ const { t } = useTranslation('setting');
+
+ const createAgent = useAgentStore((s) => s.createAgent);
+ const refreshAgentConfig = useAgentStore((s) => s.internal_refreshAgentConfig);
+ const confirmAgentSlug = useAgentStore((s) => s.internal_confirmAgentSlug);
+ const updateAgentMeta = useHomeStore((s) => s.updateAgentMeta);
+ const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+
+ const [avatar, setAvatar] = useState<string | undefined>();
+ const [name, setName] = useState(drawInitialName);
+ const [title, setTitle] = useState('');
+ const [description, setDescription] = useState('');
+ const [slug, setSlug] = useState('');
+ const [createdAgentId, setCreatedAgentId] = useState<string>();
+ const [error, setError] = useState<string | undefined>();
+ const [saving, setSaving] = useState(false);
+ const [uploading, setUploading] = useState(false);
+
+ const uploadAvatar = async (file: File): Promise<'tooLarge' | void> => {
+ if (file.size > MAX_AVATAR_SIZE) return 'tooLarge';
+
+ setUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ if (result?.url) setAvatar(result.url);
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ const submit = async () => {
+ if (saving || uploading) return;
+ setSaving(true);
+ try {
+ const meta = {
+ avatar: avatar ?? null,
+ description: description.trim(),
+ name: name.trim(),
+ title: title.trim(),
+ };
+
+ let agentId = createdAgentId;
+ if (agentId) {
+ await updateAgentMeta(agentId, meta);
+ } else {
+ ({ agentId } = await createAgent({ config: meta, groupId, visibility }));
+ setCreatedAgentId(agentId);
+ }
+
+ const nextSlug = slug.trim().toLowerCase();
+ if (nextSlug) {
+ const scope = cacheScope.get();
+ const result = await agentService.updateAgentSlug(agentId, nextSlug);
+ if (!result.success) {
+ setError(t(`settingAgent.slug.error.${result.reason ?? 'invalid'}`));
+ // The agent exists already; keep the sidebar honest while the user fixes the slug.
+ void refreshAgentList();
+ return;
+ }
+ confirmAgentSlug(agentId, nextSlug, { scope });
+ await refreshAgentConfig(agentId);
+ }
+
+ await refreshAgentList();
+ onCreated(agentId);
+ } catch {
+ setError(t('settingAgent.identity.createFailed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return {
+ avatar,
+ description,
+ error,
+ name,
+ saving,
+ setAvatar,
+ setDescription,
+ setName,
+ setSlug: (value: string) => {
+ setSlug(value);
+ setError(undefined);
+ },
+ setTitle,
+ slug,
+ slugLocked: false,
+ submit,
+ title,
+ uploadAvatar,
+ uploading,
+ };
+};
diff --git a/src/features/AgentIdentityModal/useOpenCreateAgentModal.test.ts b/src/features/AgentIdentityModal/useOpenCreateAgentModal.test.ts
new file mode 100644
index 00000000000..f3d8452078f
--- /dev/null
+++ b/src/features/AgentIdentityModal/useOpenCreateAgentModal.test.ts
@@ -0,0 +1,51 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useOpenCreateAgentModal } from './useOpenCreateAgentModal';
+
+const mocks = vi.hoisted(() => ({
+ canCreate: true,
+ navigate: vi.fn(),
+ openCreateAgentIdentityModal: vi.fn(),
+}));
+
+vi.mock('./index', () => ({
+ openCreateAgentIdentityModal: mocks.openCreateAgentIdentityModal,
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: mocks.canCreate }),
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.canCreate = true;
+});
+
+describe('useOpenCreateAgentModal', () => {
+ it('opens the identity form and lands the new agent on its profile', () => {
+ const { result } = renderHook(() => useOpenCreateAgentModal());
+
+ result.current({ groupId: 'grp', visibility: 'private' });
+
+ expect(mocks.openCreateAgentIdentityModal).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ groupId: 'grp', visibility: 'private' }),
+ );
+ const { onCreated } = mocks.openCreateAgentIdentityModal.mock.calls[0][0];
+ onCreated('agent-new');
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-new/profile');
+ });
+
+ it('does nothing without create permission', () => {
+ mocks.canCreate = false;
+ const { result } = renderHook(() => useOpenCreateAgentModal());
+
+ result.current();
+
+ expect(mocks.openCreateAgentIdentityModal).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentIdentityModal/useOpenCreateAgentModal.ts b/src/features/AgentIdentityModal/useOpenCreateAgentModal.ts
new file mode 100644
index 00000000000..5324e773ce0
--- /dev/null
+++ b/src/features/AgentIdentityModal/useOpenCreateAgentModal.ts
@@ -0,0 +1,34 @@
+import { useCallback } from 'react';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
+
+import { openCreateAgentIdentityModal, type OpenCreateAgentIdentityModalOptions } from './index';
+
+export type OpenCreateAgentModalParams = Pick<
+ OpenCreateAgentIdentityModalOptions,
+ 'groupId' | 'onClosed' | 'visibility'
+>;
+
+/**
+ * Opens the create-agent form from anywhere — the command menu, the desktop
+ * File menu, or a surface outside `AgentModalProvider`. The modal renders in the
+ * global ModalHost, so the caller may unmount (the command menu closes) while
+ * it stays open; the new agent lands on its profile page.
+ */
+export const useOpenCreateAgentModal = () => {
+ const navigate = useWorkspaceAwareNavigate();
+ const { allowed: canCreate } = usePermission('create_content');
+
+ return useCallback(
+ (params?: OpenCreateAgentModalParams) => {
+ if (!canCreate) return;
+
+ return openCreateAgentIdentityModal({
+ ...params,
+ onCreated: (agentId) => navigate(`/agent/${agentId}/profile`),
+ });
+ },
+ [canCreate, navigate],
+ );
+};
diff --git a/src/features/AgentViewAll/AgentViewAllPage.tsx b/src/features/AgentViewAll/AgentViewAllPage.tsx
index 1e2b6e7af79..79b72caa19c 100644
--- a/src/features/AgentViewAll/AgentViewAllPage.tsx
+++ b/src/features/AgentViewAll/AgentViewAllPage.tsx
@@ -484,7 +484,6 @@ const AgentViewAllPage = memo(() => {
createConnectAgentMenuItem,
createGroupChatMenuItem,
createMarketAgentMenuItem,
- isMutatingAgent,
} = useCreateMenuItems();
// Creating from the Private tab lands the item in the private bucket, so
@@ -594,7 +593,7 @@ const AgentViewAllPage = memo(() => {
)}
{canCreate ? (
<DropdownMenu items={createMenuItems}>
- <Button icon={PlusIcon} loading={isMutatingAgent}>
+ <Button icon={PlusIcon}>
<Icon icon={ChevronDownIcon} size={14} />
</Button>
</DropdownMenu>
diff --git a/src/features/CommandMenu/useCommandMenu.ts b/src/features/CommandMenu/useCommandMenu.ts
index 2d6c46f7444..7f3d2db7ad2 100644
--- a/src/features/CommandMenu/useCommandMenu.ts
+++ b/src/features/CommandMenu/useCommandMenu.ts
@@ -4,6 +4,7 @@ import { useCallback, useEffect } from 'react';
import useSWR from 'swr';
import type { FtsSearchResult } from '@/database/repositories/ftsSearch';
+import { useOpenCreateAgentModal } from '@/features/AgentIdentityModal/useOpenCreateAgentModal';
import { createTaskModal } from '@/features/AgentTasks/CreateTaskModal';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import { useCreateMenuItems } from '@/features/HomeSidebar/hooks';
@@ -18,7 +19,6 @@ import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { globalHelpers } from '@/store/global/helpers';
-import { useHomeStore } from '@/store/home';
import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import { useCommandMenuContext } from './CommandMenuContext';
@@ -48,8 +48,7 @@ export const useCommandMenu = () => {
const navigate = useWorkspaceAwareNavigate();
const { allowed: canCreate } = usePermission('create_content');
const { setTheme } = useNextThemesTheme();
- const createAgent = useAgentStore((s) => s.createAgent);
- const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
+ const openCreateAgentModal = useOpenCreateAgentModal();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const { openGroupWizard } = useGroupWizard();
const { createGroupWithMembers, createGroupFromTemplate, createPage } = useCreateMenuItems();
@@ -160,19 +159,13 @@ export const useCommandMenu = () => {
}
}, [selectedAgent, search, navigate, setSelectedAgent, onClose]);
- const handleCreateSession = useCallback(async () => {
+ // Hands off to the create-agent form; the menu closes so the form isn't stacked under it.
+ const handleCreateSession = useCallback(() => {
if (!canCreate) return;
- const result = await createAgent({});
- await refreshAgentList();
-
- // Navigate to the newly created agent
- if (result.agentId) {
- navigate(`/agent/${result.agentId}`);
- }
-
onClose();
- }, [canCreate, createAgent, refreshAgentList, navigate, onClose]);
+ openCreateAgentModal();
+ }, [canCreate, onClose, openCreateAgentModal]);
const openNewTopicOrSaveTopic = useChatStore((s) => s.openNewTopicOrSaveTopic);
diff --git a/src/features/DesktopFileMenuBridge/index.tsx b/src/features/DesktopFileMenuBridge/index.tsx
index b416065d0f3..ccc484aa70b 100644
--- a/src/features/DesktopFileMenuBridge/index.tsx
+++ b/src/features/DesktopFileMenuBridge/index.tsx
@@ -4,6 +4,7 @@ import { AGENT_CHAT_URL } from '@lobechat/const';
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
import { useCallback } from 'react';
+import { useOpenCreateAgentModal } from '@/features/AgentIdentityModal/useOpenCreateAgentModal';
import { useCreateMenuItems } from '@/features/HomeSidebar/hooks/useCreateMenuItems';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
@@ -17,7 +18,8 @@ import { openCurrentWorkspaceInNewWindow } from './openCurrentWorkspaceInNewWind
* Listens to broadcast events for creating new topics, agents, agent groups, pages and windows
*/
const DesktopFileMenuBridge = () => {
- const { createAgent, createEmptyGroup, createPage } = useCreateMenuItems();
+ const { createEmptyGroup, createPage } = useCreateMenuItems();
+ const openCreateAgentModal = useOpenCreateAgentModal();
const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
@@ -35,10 +37,10 @@ const DesktopFileMenuBridge = () => {
navigate(AGENT_CHAT_URL(inboxAgentId, false));
}, [activeAgentId, inboxAgentId, navigate]);
- // Handle create new agent from File menu
- const handleCreateNewAgent = useCallback(async () => {
- await createAgent();
- }, [createAgent]);
+ // Handle create new agent from File menu — same identity form as the sidebar
+ const handleCreateNewAgent = useCallback(() => {
+ openCreateAgentModal();
+ }, [openCreateAgentModal]);
// Handle create new agent group from File menu
const handleCreateNewAgentGroup = useCallback(async () => {
diff --git a/src/features/HomeSidebar/Body/Agent/CreateAgentButton.tsx b/src/features/HomeSidebar/Body/Agent/CreateAgentButton.tsx
index b09f5848d41..da8a9a43d4b 100644
--- a/src/features/HomeSidebar/Body/Agent/CreateAgentButton.tsx
+++ b/src/features/HomeSidebar/Body/Agent/CreateAgentButton.tsx
@@ -10,7 +10,6 @@ import {
DropdownMenu,
Flexbox,
Icon,
- Spin,
Text,
Tooltip,
} from '@lobehub/ui';
@@ -58,14 +57,12 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className, vi
const { t } = useTranslation('chat');
const { allowed: canCreate, reason } = usePermission('create_content');
const {
- createAgent,
createAgentListMenuItem,
createAgentMenuItem,
createConnectAgentMenuItem,
createGroupChatMenuItem,
createMarketAgentMenuItem,
- isMutatingAgent,
- openCreateModal,
+ openCreateAgentModal,
} = useCreateMenuItems();
const isCustomGroup = Boolean(groupId) && groupId !== SessionDefaultGroup.Default;
@@ -111,12 +108,7 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className, vi
]);
const handleClick = () => {
- if (!canCreate) return;
- if (openCreateModal) {
- openCreateModal('agent', menuOptions);
- } else {
- createAgent(menuOptions);
- }
+ openCreateAgentModal(menuOptions);
};
const content = (
@@ -133,11 +125,7 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className, vi
onClick={handleClick}
>
<Center flex={'none'} height={28} width={28}>
- {isMutatingAgent ? (
- <Spin size="small" variant="network" />
- ) : (
- <Icon icon={PlusIcon} size={'small'} />
- )}
+ <Icon icon={PlusIcon} size={'small'} />
</Center>
<Text style={{ flex: 1 }} type={'secondary'}>
{t('addAgent')}
diff --git a/src/features/HomeSidebar/Body/Agent/ModalProvider.test.tsx b/src/features/HomeSidebar/Body/Agent/ModalProvider.test.tsx
index 61aaf9207f6..d2da7566267 100644
--- a/src/features/HomeSidebar/Body/Agent/ModalProvider.test.tsx
+++ b/src/features/HomeSidebar/Body/Agent/ModalProvider.test.tsx
@@ -5,18 +5,22 @@ import { AgentModalProvider, useAgentModal } from './ModalProvider';
const mocks = vi.hoisted(() => ({
closeCreateAgentModal: vi.fn(),
- createAgent: vi.fn(),
createAgentModalProps: undefined as
| {
onCreateBlank: () => Promise<void> | void;
- onOpenSkills?: (identifier: string) => void;
+ onSubmit: (prompt: string) => Promise<void> | void;
+ type: 'agent' | 'group';
+ }
+ | undefined,
+ identityModalProps: undefined as
+ | {
+ groupId?: string;
+ onCreated: (agentId: string) => void;
+ visibility?: 'private' | 'public';
}
| undefined,
navigate: vi.fn(),
- refreshAgentList: vi.fn(),
- sendAsAgent: vi.fn(),
sendAsGroup: vi.fn(),
- toggleAgentBuilderPanel: vi.fn(),
}));
vi.mock('react-router', () => ({
@@ -46,27 +50,26 @@ vi.mock('@/features/EditingPopover', () => ({
}));
vi.mock('@/features/HomeSidebar/hooks/useCreateModal', () => ({
- openCreateAgentModal: (props: {
- onCreateBlank: () => Promise<void> | void;
- onOpenSkills?: (identifier: string) => void;
- }) => {
+ openCreateAgentModal: (props: NonNullable<typeof mocks.createAgentModalProps>) => {
mocks.createAgentModalProps = props;
return { close: mocks.closeCreateAgentModal };
},
}));
+vi.mock('@/features/AgentIdentityModal', () => ({
+ openCreateAgentIdentityModal: (props: NonNullable<typeof mocks.identityModalProps>) => {
+ mocks.identityModalProps = props;
+ return { close: vi.fn() };
+ },
+}));
+
vi.mock('@/features/WorkspaceSetting/Labels/LabelFormModal', () => ({
openLabelFormModal: vi.fn(),
}));
vi.mock('@/store/agent', () => ({
- useAgentStore: (
- selector: (state: { createAgent: typeof mocks.createAgent; inboxAgentId: string }) => unknown,
- ) =>
- selector({
- createAgent: mocks.createAgent,
- inboxAgentId: 'inbox-agent',
- }),
+ useAgentStore: (selector: (state: { inboxAgentId: string }) => unknown) =>
+ selector({ inboxAgentId: 'inbox-agent' }),
}));
vi.mock('@/store/agent/selectors', () => ({
@@ -75,27 +78,9 @@ vi.mock('@/store/agent/selectors', () => ({
},
}));
-vi.mock('@/store/global', () => ({
- useGlobalStore: {
- getState: () => ({
- toggleAgentBuilderPanel: mocks.toggleAgentBuilderPanel,
- }),
- },
-}));
-
vi.mock('@/store/home', () => ({
- useHomeStore: (
- selector: (state: {
- refreshAgentList: typeof mocks.refreshAgentList;
- sendAsAgent: typeof mocks.sendAsAgent;
- sendAsGroup: typeof mocks.sendAsGroup;
- }) => unknown,
- ) =>
- selector({
- refreshAgentList: mocks.refreshAgentList,
- sendAsAgent: mocks.sendAsAgent,
- sendAsGroup: mocks.sendAsGroup,
- }),
+ useHomeStore: (selector: (state: { sendAsGroup: typeof mocks.sendAsGroup }) => unknown) =>
+ selector({ sendAsGroup: mocks.sendAsGroup }),
}));
vi.mock('./Modals/ConfigGroupModal', () => ({
@@ -111,9 +96,15 @@ const OpenCreateAgentModalButton = () => {
return (
<>
- <button type="button" onClick={() => openCreateModal('agent')}>
+ <button
+ type="button"
+ onClick={() => openCreateModal('agent', { groupId: 'grp', visibility: 'private' })}
+ >
Open create agent modal
</button>
+ <button type="button" onClick={() => openCreateModal('group')}>
+ Open create group modal
+ </button>
<button type="button" onClick={() => openGroupWizardModal({})}>
Open group wizard
</button>
@@ -135,38 +126,42 @@ describe('AgentModalProvider', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.createAgentModalProps = undefined;
- mocks.createAgent.mockResolvedValue({ agentId: 'agent-new' });
+ mocks.identityModalProps = undefined;
});
afterEach(() => {
cleanup();
});
- it('opens the Agent Builder panel after creating a blank agent', async () => {
+ it('creates an agent from the identity form and opens its profile', async () => {
renderProvider();
fireEvent.click(screen.getByText('Open create agent modal'));
- await waitFor(() => expect(mocks.createAgentModalProps).toBeDefined());
- await mocks.createAgentModalProps!.onCreateBlank();
+ await waitFor(() => expect(mocks.identityModalProps).toBeDefined());
- await waitFor(() => {
- expect(mocks.createAgent).toHaveBeenCalledWith({ groupId: undefined });
- expect(mocks.toggleAgentBuilderPanel).toHaveBeenCalledWith(true);
- expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-new/profile');
- expect(mocks.refreshAgentList).toHaveBeenCalled();
- });
+ expect(mocks.identityModalProps).toMatchObject({ groupId: 'grp', visibility: 'private' });
+ // The prompt-based modal is no longer part of agent creation.
+ expect(mocks.createAgentModalProps).toBeUndefined();
+
+ mocks.identityModalProps!.onCreated('agent-new');
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-new/profile');
});
- it('opens the Skills tab from the create modal skill completion state', async () => {
+ it('keeps the prompt modal for groups', async () => {
renderProvider();
- fireEvent.click(screen.getByText('Open create agent modal'));
+ fireEvent.click(screen.getByText('Open create group modal'));
await waitFor(() => expect(mocks.createAgentModalProps).toBeDefined());
- mocks.createAgentModalProps!.onOpenSkills?.('product-requirements-writer');
- expect(mocks.navigate).toHaveBeenCalledWith(
- '/settings/skill?skill=product-requirements-writer',
- );
+ expect(mocks.createAgentModalProps!.type).toBe('group');
+ expect(mocks.identityModalProps).toBeUndefined();
+
+ await mocks.createAgentModalProps!.onSubmit('Plan a launch');
+ expect(mocks.sendAsGroup).toHaveBeenCalledWith({
+ groupId: undefined,
+ message: 'Plan a launch',
+ visibility: undefined,
+ });
});
it('loads deferred selection modals when their interactions request them', async () => {
diff --git a/src/features/HomeSidebar/Body/Agent/ModalProvider.tsx b/src/features/HomeSidebar/Body/Agent/ModalProvider.tsx
index c180b8e6728..ad48679de04 100644
--- a/src/features/HomeSidebar/Body/Agent/ModalProvider.tsx
+++ b/src/features/HomeSidebar/Body/Agent/ModalProvider.tsx
@@ -1,6 +1,5 @@
'use client';
-import { AGENT_CHAT_URL } from '@lobechat/const';
import { type ModalInstance } from '@lobehub/ui';
import {
createContext,
@@ -16,13 +15,13 @@ import {
useState,
} from 'react';
+import type { OpenCreateAgentIdentityModalOptions } from '@/features/AgentIdentityModal';
import EditingPopover from '@/features/EditingPopover';
import type { OpenCreateAgentModalOptions } from '@/features/HomeSidebar/hooks/useCreateModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { openLabelFormModal } from '@/features/WorkspaceSetting/Labels/LabelFormModal';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
-import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
import ConfigGroupModal from './Modals/ConfigGroupModal';
@@ -45,9 +44,8 @@ interface OpenCreateModalOptions {
/**
* Threaded into the create flow so the resulting agent / group lands in the
* Private bucket of the sidebar. Omitted means "public" — the existing
- * default. Honored by the inner CreateModalRenderer when it calls
- * `storeCreateAgent` (the chat-group path defers to its own
- * publish-to-workspace toggle inside the profile page).
+ * default. The agent form passes it to `createAgent`; the group path
+ * forwards it to `sendAsGroup`.
*/
visibility?: 'private' | 'public';
}
@@ -97,74 +95,43 @@ export const useOptionalAgentModal = () => {
return use(AgentModalContext);
};
-interface CreateModalRendererProps {
+interface CreateGroupModalRendererProps {
groupId?: string;
onClose: () => void;
- type: 'agent' | 'group';
visibility?: 'private' | 'public';
}
-const CreateModalRenderer = memo<CreateModalRendererProps>(
- ({ type, groupId, onClose, visibility }) => {
- const navigate = useWorkspaceAwareNavigate();
+/** Groups still start from a prompt: describe the group and the builder assembles it. */
+const CreateGroupModalRenderer = memo<CreateGroupModalRendererProps>(
+ ({ groupId, onClose, visibility }) => {
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
- const storeCreateAgent = useAgentStore((s) => s.createAgent);
- const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
- const sendAsAgent = useHomeStore((s) => s.sendAsAgent);
const sendAsGroup = useHomeStore((s) => s.sendAsGroup);
const handleSubmit = useCallback(
async (prompt: string) => {
- if (type === 'agent') {
- await sendAsAgent({ groupId, message: prompt, visibility });
- } else {
- await sendAsGroup({ groupId, message: prompt, visibility });
- }
+ await sendAsGroup({ groupId, message: prompt, visibility });
},
- [type, sendAsAgent, sendAsGroup, groupId, visibility],
+ [sendAsGroup, groupId, visibility],
);
const handleCreateBlank = useCallback(async () => {
- if (type === 'agent') {
- const result = await storeCreateAgent({ groupId, visibility });
- useGlobalStore.getState().toggleAgentBuilderPanel(true);
- navigate(`/agent/${result.agentId}/profile`);
- await refreshAgentList();
- } else {
- await sendAsGroup({ groupId, message: '', visibility });
- }
- }, [type, storeCreateAgent, navigate, refreshAgentList, sendAsGroup, groupId, visibility]);
-
- const handleOpenSkills = useCallback(
- (identifier: string) => {
- onClose();
- navigate(`/settings/skill?skill=${encodeURIComponent(identifier)}`);
- },
- [navigate, onClose],
- );
-
- const handleTryInLobeAI = useCallback(() => {
- if (!inboxAgentId) return;
-
- navigate(AGENT_CHAT_URL(inboxAgentId, false));
- }, [inboxAgentId, navigate]);
+ await sendAsGroup({ groupId, message: '', visibility });
+ }, [sendAsGroup, groupId, visibility]);
// Mounted only while the modal should be open, so the open/close bridge is
// just this component's lifetime — the panel itself lives in the ModalHost.
const openArgsRef = useRef<OpenCreateAgentModalOptions>(undefined);
openArgsRef.current = {
agentId: inboxAgentId,
- type,
+ type: 'group',
onClosed: onClose,
onCreateBlank: handleCreateBlank,
- onOpenSkills: handleOpenSkills,
onSubmit: handleSubmit,
- onTryInLobeAI: handleTryInLobeAI,
};
useEffect(() => {
- // Imported here rather than at module scope so the create-agent chunk (it
- // pulls in the whole ChatInput stack) still loads only when the modal opens.
+ // Imported here rather than at module scope so the create chunk (it pulls
+ // in the whole ChatInput stack) still loads only when the modal opens.
let cancelled = false;
let instance: ModalInstance | undefined;
@@ -185,6 +152,47 @@ const CreateModalRenderer = memo<CreateModalRendererProps>(
},
);
+interface CreateAgentIdentityRendererProps {
+ groupId?: string;
+ onClose: () => void;
+ visibility?: 'private' | 'public';
+}
+
+/**
+ * New agents start from the identity form (avatar, name, role, description,
+ * slug) and land on their profile page, where the rest is configured.
+ */
+const CreateAgentIdentityRenderer = memo<CreateAgentIdentityRendererProps>(
+ ({ groupId, onClose, visibility }) => {
+ const navigate = useWorkspaceAwareNavigate();
+
+ const openArgsRef = useRef<OpenCreateAgentIdentityModalOptions>(undefined);
+ openArgsRef.current = {
+ groupId,
+ onClosed: onClose,
+ onCreated: (agentId) => navigate(`/agent/${agentId}/profile`),
+ visibility,
+ };
+
+ useEffect(() => {
+ let cancelled = false;
+ let instance: ModalInstance | undefined;
+
+ void import('@/features/AgentIdentityModal').then(({ openCreateAgentIdentityModal }) => {
+ if (cancelled) return;
+ instance = openCreateAgentIdentityModal(openArgsRef.current!);
+ });
+
+ return () => {
+ cancelled = true;
+ instance?.close();
+ };
+ }, []);
+
+ return null;
+ },
+);
+
interface AgentModalProviderProps {
children: ReactNode;
}
@@ -260,10 +268,16 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
return (
<AgentModalContext value={contextValue}>
- {createModalOpen && (
- <CreateModalRenderer
+ {createModalOpen && createModalType === 'agent' && (
+ <CreateAgentIdentityRenderer
+ groupId={createModalGroupId}
+ visibility={createModalVisibility}
+ onClose={() => setCreateModalOpen(false)}
+ />
+ )}
+ {createModalOpen && createModalType === 'group' && (
+ <CreateGroupModalRenderer
groupId={createModalGroupId}
- type={createModalType}
visibility={createModalVisibility}
onClose={() => setCreateModalOpen(false)}
/>
diff --git a/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx b/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx
index 7ed56207133..b0ce5fa41fc 100644
--- a/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx
+++ b/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx
@@ -6,7 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useCreateMenuItems } from './useCreateMenuItems';
-const createAgentMock = vi.hoisted(() => vi.fn().mockResolvedValue({ agentId: 'agent-codex' }));
+const openIdentityModalMock = vi.hoisted(() => vi.fn());
const refreshAgentListMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
const addGroupMock = vi.hoisted(() => vi.fn());
const switchToGroupMock = vi.hoisted(() => vi.fn());
@@ -18,7 +18,12 @@ const navigateMock = vi.hoisted(() => vi.fn());
const openConnectAgentModalMock = vi.hoisted(() => vi.fn());
const openCreateGroupModalMock = vi.hoisted(() => vi.fn());
const agentModalMock = vi.hoisted(() => ({
- current: undefined as { openCreateGroupModal: (id?: string, v?: string) => void } | undefined,
+ current: undefined as
+ | {
+ openCreateGroupModal?: (id?: string, v?: string) => void;
+ openCreateModal?: (type: 'agent' | 'group', options?: object) => void;
+ }
+ | undefined,
}));
vi.mock('@lobechat/const', () => ({
@@ -50,6 +55,10 @@ vi.mock('@/components/ChatGroupWizard/templates', () => ({
useGroupTemplates: () => [],
}));
+vi.mock('@/features/AgentIdentityModal/useOpenCreateAgentModal', () => ({
+ useOpenCreateAgentModal: () => openIdentityModalMock,
+}));
+
vi.mock('@/features/ConnectAgent', () => ({
openConnectAgentModal: openConnectAgentModalMock,
}));
@@ -64,13 +73,6 @@ vi.mock('@/services/chatGroup', () => ({
},
}));
-vi.mock('@/store/agent', () => ({
- useAgentStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({
- createAgent: createAgentMock,
- }),
-}));
-
vi.mock('@/store/agentGroup', () => ({
useAgentGroupStore: (selector: (state: Record<string, unknown>) => unknown) =>
selector({
@@ -106,6 +108,33 @@ describe('useCreateMenuItems', () => {
agentModalMock.current = undefined;
});
+ it('opens the identity form through the provider when one is mounted', () => {
+ const openCreateModal = vi.fn();
+ agentModalMock.current = { openCreateModal };
+ const { result } = renderHook(() => useCreateMenuItems());
+
+ const item = result.current.createAgentMenuItem({ groupId: 'grp', visibility: 'private' });
+ act(() => {
+ void (item as any).onClick({ domEvent: { stopPropagation: vi.fn() } });
+ });
+
+ expect(openCreateModal).toHaveBeenCalledWith('agent', {
+ groupId: 'grp',
+ visibility: 'private',
+ });
+ expect(openIdentityModalMock).not.toHaveBeenCalled();
+ });
+
+ // Surfaces outside the provider (desktop File menu, ⌘K) used to create a
+ // blank agent here; every entry now goes through the form.
+ it('opens the identity form directly without a provider instead of creating a blank agent', () => {
+ const { result } = renderHook(() => useCreateMenuItems());
+
+ result.current.openCreateAgentModal({ visibility: 'private' });
+
+ expect(openIdentityModalMock).toHaveBeenCalledWith({ visibility: 'private' });
+ });
+
it('adds Agent-list and Market entries while omitting Page creation', async () => {
const { result } = renderHook(() => useCreateMenuItems());
diff --git a/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx b/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx
index 52004ecfb0e..04c1ad7a634 100644
--- a/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx
+++ b/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx
@@ -17,15 +17,14 @@ import useSWRMutation from 'swr/mutation';
import { useGroupTemplates } from '@/components/ChatGroupWizard/templates';
import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';
+import { useOpenCreateAgentModal } from '@/features/AgentIdentityModal/useOpenCreateAgentModal';
import { openConnectAgentModal } from '@/features/ConnectAgent';
import { useOptionalAgentModal } from '@/features/HomeSidebar/Body/Agent/ModalProvider';
import { docsPagePath } from '@/features/ResourceHome/paths';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
-import type { CreateAgentParams } from '@/services/agent';
import type { GroupMemberConfig } from '@/services/chatGroup';
import { chatGroupService } from '@/services/chatGroup';
-import { useAgentStore } from '@/store/agent';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useHomeStore } from '@/store/home';
import { pageActions } from '@/store/page';
@@ -56,7 +55,6 @@ export const useCreateMenuItems = () => {
const groupTemplates = useGroupTemplates();
const { allowed: canCreate } = usePermission('create_content');
- const [storeCreateAgent] = useAgentStore((s) => [s.createAgent]);
const [addGroup, refreshAgentList, switchToGroup] = useHomeStore((s) => [
s.addGroup,
s.refreshAgentList,
@@ -67,21 +65,6 @@ export const useCreateMenuItems = () => {
const [isCreatingGroup, setIsCreatingGroup] = useState(false);
const [isCreatingSessionGroup, setIsCreatingSessionGroup] = useState(false);
- // SWR-based agent creation with auto navigation to profile
- const { trigger: mutateAgent, isMutating: isMutatingAgent } = useSWRMutation(
- 'agent.createAgent',
- async (_key: string, { arg }: { arg?: CreateAgentParams }) => {
- const result = await storeCreateAgent(arg ?? {});
- return result;
- },
- {
- onSuccess: async (result) => {
- navigate(`/agent/${result.agentId}/profile`);
- await refreshAgentList();
- },
- },
- );
-
// SWR-based group creation with auto navigation to profile
const { trigger: mutateGroup, isMutating: isMutatingGroup } = useSWRMutation(
'group.createGroup',
@@ -109,24 +92,6 @@ export const useCreateMenuItems = () => {
},
);
- /**
- * Create agent action (optionally with a prompt as systemRole)
- */
- const createAgent = useCallback(
- async (options?: CreateAgentOptions & { prompt?: string }) => {
- if (!canCreate) return;
-
- const config = options?.prompt ? { systemRole: options.prompt } : undefined;
- await mutateAgent({
- config,
- groupId: options?.groupId,
- visibility: options?.visibility,
- });
- options?.onSuccess?.();
- },
- [canCreate, mutateAgent],
- );
-
/**
* Create group from template
* Uses backend batch creation for better performance and consistency
@@ -229,6 +194,24 @@ export const useCreateMenuItems = () => {
const agentModal = useOptionalAgentModal();
const openCreateModal = agentModal?.openCreateModal;
const openCreateGroupModal = agentModal?.openCreateGroupModal;
+ const openCreateAgentIdentityModal = useOpenCreateAgentModal();
+
+ /**
+ * Every "new agent" entry opens the identity form — through the provider when
+ * one is mounted, otherwise directly in the global ModalHost.
+ */
+ const openCreateAgentModal = useCallback(
+ (options?: Pick<CreateAgentOptions, 'groupId' | 'visibility'>) => {
+ if (!canCreate) return;
+ const params = {
+ ...(options?.groupId ? { groupId: options.groupId } : {}),
+ ...(options?.visibility ? { visibility: options.visibility } : {}),
+ };
+ if (openCreateModal) openCreateModal('agent', params);
+ else openCreateAgentIdentityModal(params);
+ },
+ [canCreate, openCreateAgentIdentityModal, openCreateModal],
+ );
/**
* Create agent menu item
@@ -242,21 +225,12 @@ export const useCreateMenuItems = () => {
key: options?.visibility === 'private' ? 'newPrivateAgent' : 'newAgent',
label: t('newAgent'),
sfSymbol: 'plus.bubble',
- onClick: async (info) => {
+ onClick: (info) => {
info.domEvent?.stopPropagation();
- if (!canCreate) return;
-
- if (openCreateModal) {
- openCreateModal('agent', {
- ...(options?.groupId ? { groupId: options.groupId } : {}),
- ...(options?.visibility ? { visibility: options.visibility } : {}),
- });
- } else {
- await createAgent(options);
- }
+ openCreateAgentModal(options);
},
}),
- [canCreate, t, createAgent, openCreateModal],
+ [canCreate, t, openCreateAgentModal],
);
/**
@@ -467,7 +441,6 @@ export const useCreateMenuItems = () => {
return {
configMenuItem,
- createAgent,
createAgentListMenuItem,
createAgentMenuItem,
createConnectAgentMenuItem,
@@ -480,12 +453,12 @@ export const useCreateMenuItems = () => {
createPageMenuItem,
createSessionGroupMenuItem,
createTopLevelMenuItems,
+ openCreateAgentModal,
openCreateModal,
// Loading states
isCreatingGroup,
isCreatingSessionGroup,
- isLoading: isMutatingAgent || isMutatingGroup || isCreatingGroup || isCreatingSessionGroup,
- isMutatingAgent,
+ isLoading: isMutatingGroup || isCreatingGroup || isCreatingSessionGroup,
};
};