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.

♻️ refactor(modal): migrate antd Modal to base-ui imperative API (#16212)

Inneia00a627b6ec6
diff --git a/src/components/GuideModal/index.tsx b/src/components/GuideModal/index.tsx
index e251abbfbf7..fa9de77de7a 100644
--- a/src/components/GuideModal/index.tsx
+++ b/src/components/GuideModal/index.tsx
@@ -1,81 +1,117 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { type ModalProps } from 'antd';
-import { ConfigProvider, Modal } from 'antd';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
import { type ReactNode } from 'react';
-import { memo, useMemo } from 'react';
+import { memo } from 'react';
-const prefixCls = 'ant';
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ h3 {
+ margin: 0;
+ font-weight: bold;
+ }
-const styles = createStaticStyles(({ css }) => {
- return {
- content: css`
- .${prefixCls}-modal-footer {
- margin: 0;
- padding: 16px;
- }
- .${prefixCls}-modal-header {
- display: flex;
- gap: 4px;
- align-items: center;
- justify-content: center;
+ p {
+ margin: 0;
+ }
+ `,
+}));
- height: 56px;
- margin-block-end: 0;
- padding: 16px;
- }
- .${prefixCls}-modal-container {
- overflow: hidden;
- padding: 0;
- border: 1px solid ${cssVar.colorSplit};
- border-radius: ${cssVar.borderRadiusLG};
- }
- `,
- wrap: css`
- overflow: hidden auto;
- `,
- };
-});
-
-interface GuideModalProps extends ModalProps {
+interface GuideModalContentProps {
+ cancelText?: ReactNode;
cover: ReactNode;
desc: ReactNode;
+ okText?: ReactNode;
+ onCancel?: () => void;
+ onOk?: () => void;
title: ReactNode;
}
-const GuideModal = memo<GuideModalProps>(
- ({ className, title, desc, cover, width = 360, ...rest }) => {
- const configTheme = useMemo(
- () => ({
- token: {
- colorBgElevated: `color-mix(in srgb, ${cssVar.colorBgContainer} 99.5%, white)`,
- },
- }),
- [],
- );
+const GuideModalContent = memo<GuideModalContentProps>(
+ ({ cover, title, desc, okText, cancelText, onOk, onCancel }) => {
+ const { close } = useModalContext();
+
+ const handleOk = () => {
+ onOk?.();
+ close();
+ };
+
+ const handleCancel = () => {
+ onCancel?.();
+ close();
+ };
return (
- <ConfigProvider theme={configTheme}>
- <Modal
- centered
- maskClosable
- className={cx(styles.content, className)}
- closable={false}
- width={width}
- wrapClassName={styles.wrap}
- {...rest}
- >
- {cover}
- <Flexbox padding={16}>
- <h3 style={{ fontWeight: 'bold' }}>{title}</h3>
- <p style={{ marginBottom: 0 }}>{desc}</p>
+ <Flexbox className={styles.body}>
+ {cover}
+ <Flexbox gap={4} padding={16}>
+ <h3>{title}</h3>
+ <p>{desc}</p>
+ </Flexbox>
+ {(okText || cancelText) && (
+ <Flexbox
+ horizontal
+ gap={8}
+ justify={'flex-end'}
+ paddingBlock={16}
+ paddingInline={16}
+ style={{ paddingTop: 0 }}
+ >
+ {cancelText ? <Button onClick={handleCancel}>{cancelText}</Button> : null}
+ {okText ? (
+ <Button type={'primary'} onClick={handleOk}>
+ {okText}
+ </Button>
+ ) : null}
</Flexbox>
- </Modal>
- </ConfigProvider>
+ )}
+ </Flexbox>
);
},
);
-export default GuideModal;
+GuideModalContent.displayName = 'GuideModalContent';
+
+export interface CreateGuideModalOptions {
+ cancelText?: ReactNode;
+ cover: ReactNode;
+ desc: ReactNode;
+ okText?: ReactNode;
+ onCancel?: () => void;
+ onOk?: () => void;
+ title: ReactNode;
+ width?: number;
+}
+
+export const createGuideModal = ({
+ cancelText,
+ cover,
+ desc,
+ okText,
+ onCancel,
+ onOk,
+ title,
+ width = 360,
+}: CreateGuideModalOptions): ModalInstance =>
+ createModal({
+ content: (
+ <GuideModalContent
+ cancelText={cancelText}
+ cover={cover}
+ desc={desc}
+ okText={okText}
+ title={title}
+ onCancel={onCancel}
+ onOk={onOk}
+ />
+ ),
+ footer: null,
+ maskClosable: true,
+ styles: {
+ content: { padding: 0 },
+ header: { display: 'none' },
+ },
+ width,
+ });
diff --git a/src/features/AgentSetting/AgentOpening/index.tsx b/src/features/AgentSetting/AgentOpening/index.tsx
index 1b0be506144..ff8a52b5fea 100644
--- a/src/features/AgentSetting/AgentOpening/index.tsx
+++ b/src/features/AgentSetting/AgentOpening/index.tsx
@@ -19,27 +19,22 @@ const AgentOpening = memo(() => {
return (
<Form
- itemsType={'group'}
+ itemsType={'flat'}
variant={'borderless'}
items={[
{
- children: [
- {
- children: <OpeningMessage />,
- desc: t('settingOpening.openingMessage.desc'),
- label: t('settingOpening.openingMessage.title'),
- layout: 'vertical',
- wrapperCol,
- },
- {
- children: <OpeningQuestions />,
- desc: t('settingOpening.openingQuestions.desc'),
- label: t('settingOpening.openingQuestions.title'),
- layout: 'vertical',
- wrapperCol,
- },
- ],
- title: t('settingOpening.title'),
+ children: <OpeningMessage />,
+ desc: t('settingOpening.openingMessage.desc'),
+ label: t('settingOpening.openingMessage.title'),
+ layout: 'vertical',
+ wrapperCol,
+ },
+ {
+ children: <OpeningQuestions />,
+ desc: t('settingOpening.openingQuestions.desc'),
+ label: t('settingOpening.openingQuestions.title'),
+ layout: 'vertical',
+ wrapperCol,
},
]}
/>
diff --git a/src/features/AgentSetting/AgentSelfIteration/index.tsx b/src/features/AgentSetting/AgentSelfIteration/index.tsx
index db64b2a6115..439b292338f 100644
--- a/src/features/AgentSetting/AgentSelfIteration/index.tsx
+++ b/src/features/AgentSetting/AgentSelfIteration/index.tsx
@@ -1,6 +1,5 @@
'use client';
-import type { FormGroupItemType } from '@lobehub/ui';
import { Form } from '@lobehub/ui';
import { Switch } from 'antd';
import isEqual from 'fast-deep-equal';
@@ -38,19 +37,14 @@ const AgentSelfIteration = memo(() => {
valuePropName: 'checked',
};
- const selfIteration: FormGroupItemType = {
- children: [selfIterationItem],
- title: t('settingSelfIteration.title'),
- };
-
return (
<Form
disabled={disabled}
footer={isInbox ? undefined : <Form.SubmitFooter />}
form={form}
initialValues={config}
- items={[selfIteration]}
- itemsType={'group'}
+ items={[selfIterationItem]}
+ itemsType={'flat'}
variant={'borderless'}
onFinish={(values) => {
if (disabled) return;
diff --git a/src/features/AgentSetting/SettingsModalLayout.tsx b/src/features/AgentSetting/SettingsModalLayout.tsx
new file mode 100644
index 00000000000..14e6066e6ae
--- /dev/null
+++ b/src/features/AgentSetting/SettingsModalLayout.tsx
@@ -0,0 +1,77 @@
+'use client';
+
+import { ActionIcon, Avatar, Flexbox, Icon, Tabs, Text } from '@lobehub/ui';
+import { useModalContext } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { type LucideIcon, XIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+export interface SettingsModalTabItem {
+ icon?: LucideIcon;
+ key: string;
+ label: ReactNode;
+}
+
+export interface SettingsModalLayoutProps {
+ activeTab?: string;
+ avatar: string;
+ background?: string;
+ children: ReactNode;
+ onTabChange?: (key: string) => void;
+ tabs?: SettingsModalTabItem[];
+ title: ReactNode;
+}
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ header: css`
+ flex-shrink: 0;
+ padding-block: 10px;
+ padding-inline: 16px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ tabsBar: css`
+ flex-shrink: 0;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+}));
+
+const SettingsModalLayout = memo<SettingsModalLayoutProps>(
+ ({ avatar, background, title, tabs, activeTab, onTabChange, children }) => {
+ const { t } = useTranslation('common');
+ const { close } = useModalContext();
+
+ const tabItems = tabs?.map(({ icon, key, label }) => ({
+ icon: icon ? <Icon icon={icon} size={16} /> : undefined,
+ key,
+ label,
+ }));
+
+ return (
+ <Flexbox height={'100%'} style={{ overflow: 'hidden' }}>
+ <Flexbox horizontal align={'center'} className={styles.header} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Avatar avatar={avatar} background={background} shape={'square'} size={24} />
+ <Text ellipsis weight={600}>
+ {title}
+ </Text>
+ </Flexbox>
+ <ActionIcon icon={XIcon} title={t('cancel')} onClick={close} />
+ </Flexbox>
+
+ {tabItems && tabItems.length >= 2 && (
+ <Flexbox className={styles.tabsBar}>
+ <Tabs activeKey={activeTab} items={tabItems} onChange={onTabChange} />
+ </Flexbox>
+ )}
+
+ <Flexbox flex={1} paddingInline={16} style={{ minHeight: 0, overflow: 'auto' }}>
+ {children}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+export default SettingsModalLayout;
diff --git a/src/features/AgentSetting/index.tsx b/src/features/AgentSetting/index.tsx
index d8424f23040..1d5ccb030ce 100644
--- a/src/features/AgentSetting/index.tsx
+++ b/src/features/AgentSetting/index.tsx
@@ -2,3 +2,5 @@ export { default as AgentCategory } from './AgentCategory';
export { default as AgentSettings } from './AgentSettings';
export { AgentSettingsProvider } from './AgentSettingsProvider';
export type { AgentSettingsInstance } from './hooks/useAgentSettings';
+export type { SettingsModalLayoutProps, SettingsModalTabItem } from './SettingsModalLayout';
+export { default as SettingsModalLayout } from './SettingsModalLayout';
diff --git a/src/features/CreatePlatformAgent/index.tsx b/src/features/CreatePlatformAgent/index.tsx
index c19358bc37c..e5a1dce6e0d 100644
--- a/src/features/CreatePlatformAgent/index.tsx
+++ b/src/features/CreatePlatformAgent/index.tsx
@@ -5,9 +5,16 @@ import {
type RemoteHeterogeneousAgentType,
} from '@lobechat/heterogeneous-agents';
import { Button, Flexbox, Icon } from '@lobehub/ui';
-import { Select } from '@lobehub/ui/base-ui';
-import { Alert, Input, Modal, Steps, Tag, Typography } from 'antd';
+import {
+ Button as BaseButton,
+ createModal,
+ type ModalInstance,
+ Select,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { Alert, Input, Steps, Tag, Typography } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
+import { t as i18nT } from 'i18next';
import {
BotIcon,
CheckCircle2,
@@ -98,463 +105,440 @@ interface AgentProfile {
title?: string;
}
-interface CreatePlatformAgentModalProps {
+interface CreatePlatformAgentContentProps {
groupId?: string;
- onClose: () => void;
- open: boolean;
}
-const CreatePlatformAgentModal = memo<CreatePlatformAgentModalProps>(
- ({ open, onClose, groupId }) => {
- const { t } = useTranslation('chat');
- const navigate = useNavigate();
- const storeCreateAgent = useAgentStore((s) => s.createAgent);
- const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
-
- // Creating from a workspace context: the new agent inherits the active
- // workspace's scope (server-side), so the device picker must restrict to
- // workspace devices — a workspace agent bound to a personal device is
- // unreachable to other members and the server rejects the write.
- const activeWorkspaceId = useActiveWorkspaceId();
- const restrictToWorkspaceDevices = Boolean(activeWorkspaceId);
-
- const [step, setStep] = useState(0);
- const [platform, setPlatform] = useState<RemoteHeterogeneousAgentType>('openclaw');
- const [deviceId, setDeviceId] = useState<string | undefined>(undefined);
- const [agentName, setAgentName] = useState('');
- const [agentDescription, setAgentDescription] = useState('');
- const [agentProfile, setAgentProfile] = useState<AgentProfile | null>(null);
- const [fetchingProfile, setFetchingProfile] = useState(false);
- const [creating, setCreating] = useState(false);
- const [capabilityResult, setCapabilityResult] = useState<
- { available: boolean; reason?: string; version?: string } | undefined
- >(undefined);
- const [checkingCapability, setCheckingCapability] = useState(false);
-
- // Platforms that are not yet ready for production use.
- // Remove a type from this set when the platform is fully supported.
- const COMING_SOON_PLATFORMS = new Set<RemoteHeterogeneousAgentType>(['amp', 'opencode']);
-
- // Derive platform display list from the registry — adding a new platform to
- // REMOTE_HETEROGENEOUS_AGENT_CONFIGS automatically includes it here.
- const platformDefs = REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((c) => ({
- comingSoon: COMING_SOON_PLATFORMS.has(c.type),
- desc: t(`platformAgent.create.desc.${c.type}`),
- name: c.title,
- type: c.type,
- }));
-
- // Fetch device list when the modal opens; expose refetch for the refresh button
- const {
- data: devices,
- isLoading: loadingDevices,
- isFetching: fetchingDevices,
- refetch: refetchDevices,
- } = lambdaQuery.device.listDevices.useQuery(undefined, {
- enabled: open,
- staleTime: 0, // always re-fetch when explicitly called
- });
-
- const selectedPlatformDef = platformDefs.find((p) => p.type === platform)!;
-
- // Reset state when modal opens
- useEffect(() => {
- if (open) {
- setStep(0);
- setPlatform('openclaw');
- setDeviceId(undefined);
- setAgentName('');
- setAgentDescription('');
- setAgentProfile(null);
- setCapabilityResult(undefined);
- }
- }, [open]);
-
- // Pre-fill name and description from fetched profile when entering step 2
- useEffect(() => {
- if (step !== 2) return;
- if (agentProfile !== null) {
- if (!agentName) setAgentName(agentProfile.title ?? selectedPlatformDef.name);
- if (!agentDescription) setAgentDescription(agentProfile.description ?? '');
- } else if (!fetchingProfile && !agentName) {
- // Profile fetch failed or no profile — fall back to platform name
- setAgentName(selectedPlatformDef.name);
- }
- }, [step, agentProfile, fetchingProfile]);
-
- const handlePlatformChange = useCallback((type: RemoteHeterogeneousAgentType) => {
- setPlatform(type);
- // Reset device + capability state — capability is platform-specific;
- // stale results from the previous platform must not carry over.
- setDeviceId(undefined);
+const COMING_SOON_PLATFORMS = new Set<RemoteHeterogeneousAgentType>(['amp', 'opencode']);
+
+const CreatePlatformAgentContent = memo<CreatePlatformAgentContentProps>(({ groupId }) => {
+ const { t } = useTranslation('chat');
+ const { close } = useModalContext();
+ const navigate = useNavigate();
+ const storeCreateAgent = useAgentStore((s) => s.createAgent);
+ const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
+
+ // Creating from a workspace context: the new agent inherits the active
+ // workspace's scope (server-side), so the device picker must restrict to
+ // workspace devices — a workspace agent bound to a personal device is
+ // unreachable to other members and the server rejects the write.
+ const activeWorkspaceId = useActiveWorkspaceId();
+ const restrictToWorkspaceDevices = Boolean(activeWorkspaceId);
+
+ const [step, setStep] = useState(0);
+ const [platform, setPlatform] = useState<RemoteHeterogeneousAgentType>('openclaw');
+ const [deviceId, setDeviceId] = useState<string | undefined>(undefined);
+ const [agentName, setAgentName] = useState('');
+ const [agentDescription, setAgentDescription] = useState('');
+ const [agentProfile, setAgentProfile] = useState<AgentProfile | null>(null);
+ const [fetchingProfile, setFetchingProfile] = useState(false);
+ const [creating, setCreating] = useState(false);
+ const [capabilityResult, setCapabilityResult] = useState<
+ { available: boolean; reason?: string; version?: string } | undefined
+ >(undefined);
+ const [checkingCapability, setCheckingCapability] = useState(false);
+
+ const platformDefs = REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((c) => ({
+ comingSoon: COMING_SOON_PLATFORMS.has(c.type),
+ desc: t(`platformAgent.create.desc.${c.type}`),
+ name: c.title,
+ type: c.type,
+ }));
+
+ const {
+ data: devices,
+ isLoading: loadingDevices,
+ isFetching: fetchingDevices,
+ refetch: refetchDevices,
+ } = lambdaQuery.device.listDevices.useQuery(undefined, {
+ staleTime: 0,
+ });
+
+ const selectedPlatformDef = platformDefs.find((p) => p.type === platform)!;
+
+ useEffect(() => {
+ if (step !== 2) return;
+ if (agentProfile !== null) {
+ if (!agentName) setAgentName(agentProfile.title ?? selectedPlatformDef.name);
+ if (!agentDescription) setAgentDescription(agentProfile.description ?? '');
+ } else if (!fetchingProfile && !agentName) {
+ setAgentName(selectedPlatformDef.name);
+ }
+ }, [step, agentProfile, fetchingProfile]);
+
+ const handlePlatformChange = useCallback((type: RemoteHeterogeneousAgentType) => {
+ setPlatform(type);
+ // Reset device + capability state — capability is platform-specific;
+ // stale results from the previous platform must not carry over.
+ setDeviceId(undefined);
+ setCapabilityResult(undefined);
+ setAgentProfile(null);
+ }, []);
+
+ const checkCapability = useCallback(
+ async (dId: string) => {
+ setCheckingCapability(true);
setCapabilityResult(undefined);
- setAgentProfile(null);
- }, []);
-
- const checkCapability = useCallback(
- async (dId: string) => {
- setCheckingCapability(true);
- setCapabilityResult(undefined);
- try {
- const result = await deviceService.checkCapability({
- deviceId: dId,
- platform,
- });
- setCapabilityResult(result);
- } catch {
- setCapabilityResult({ available: false, reason: t('platformAgent.create.checkFailed') });
- } finally {
- setCheckingCapability(false);
- }
- },
- [platform, t],
- );
-
- const fetchProfile = useCallback(
- async (dId: string) => {
- setFetchingProfile(true);
- setAgentProfile(null);
- try {
- const profile = await deviceService.getAgentProfile({
- deviceId: dId,
- platform,
- });
- setAgentProfile(profile);
- } catch {
- setAgentProfile({});
- } finally {
- setFetchingProfile(false);
- }
- },
- [platform],
- );
-
- const handleDeviceChange = useCallback(
- (dId: string) => {
- setDeviceId(dId);
- void checkCapability(dId);
- void fetchProfile(dId);
- },
- [checkCapability, fetchProfile],
- );
-
- const handleNext = useCallback(() => {
- setStep((s) => s + 1);
- }, []);
-
- const handleBack = useCallback(() => {
- setStep((s) => s - 1);
- }, []);
-
- const handleCreate = useCallback(async () => {
- if (!deviceId) return;
- setCreating(true);
try {
- const title = agentName.trim() || selectedPlatformDef.name;
- const result = await storeCreateAgent({
- config: {
- agencyConfig: {
- boundDeviceId: deviceId,
- heterogeneousProvider: {
- type: platform,
- },
- },
- avatar: agentProfile?.avatar || undefined,
- description: agentDescription.trim() || undefined,
- title,
- },
- groupId,
+ const result = await deviceService.checkCapability({
+ deviceId: dId,
+ platform,
});
- await refreshAgentList();
- onClose();
- navigate(`/agent/${result.agentId}`);
+ setCapabilityResult(result);
+ } catch {
+ setCapabilityResult({ available: false, reason: t('platformAgent.create.checkFailed') });
} finally {
- setCreating(false);
- }
- }, [
- deviceId,
- agentName,
- agentDescription,
- agentProfile,
- platform,
- groupId,
- storeCreateAgent,
- refreshAgentList,
- onClose,
- navigate,
- selectedPlatformDef.name,
- ]);
-
- const renderCapabilityStatus = () => {
- if (!deviceId) return null;
- if (checkingCapability)
- return <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgent.create.checking')}</Tag>;
- if (!capabilityResult) return null;
- if (capabilityResult.available) {
- return (
- <Flexbox horizontal align="flex-start" gap={4} style={{ flexWrap: 'wrap' }}>
- <Icon
- color="var(--ant-color-success)"
- icon={CheckCircle2}
- size={14}
- style={{ marginTop: 2, flexShrink: 0 }}
- />
- <Tag
- color="success"
- style={{ marginInlineEnd: 0, whiteSpace: 'normal', wordBreak: 'break-word' }}
- >
- {capabilityResult.version ?? t('platformAgent.create.available')}
- </Tag>
- </Flexbox>
- );
+ setCheckingCapability(false);
}
+ },
+ [platform, t],
+ );
- // Detect outdated lh desktop version — the gateway returns this pattern when the
- // tool is unknown to the running desktop build.
- const isVersionTooLow = capabilityResult.reason?.includes('is not available on this device');
- if (isVersionTooLow) {
- return (
- <Alert
- showIcon
- message={t('platformAgent.create.versionTooLow')}
- type="warning"
- description={
- <Flexbox gap={4}>
- <span>{t('platformAgent.create.versionTooLowHint')}</span>
- <Typography.Text code copyable>
- {t('platformAgent.create.upgradeCmd')}
- </Typography.Text>
- </Flexbox>
- }
- />
- );
+ const fetchProfile = useCallback(
+ async (dId: string) => {
+ setFetchingProfile(true);
+ setAgentProfile(null);
+ try {
+ const profile = await deviceService.getAgentProfile({
+ deviceId: dId,
+ platform,
+ });
+ setAgentProfile(profile);
+ } catch {
+ setAgentProfile({});
+ } finally {
+ setFetchingProfile(false);
}
-
+ },
+ [platform],
+ );
+
+ const handleDeviceChange = useCallback(
+ (dId: string) => {
+ setDeviceId(dId);
+ void checkCapability(dId);
+ void fetchProfile(dId);
+ },
+ [checkCapability, fetchProfile],
+ );
+
+ const handleNext = useCallback(() => {
+ setStep((s) => s + 1);
+ }, []);
+
+ const handleBack = useCallback(() => {
+ setStep((s) => s - 1);
+ }, []);
+
+ const handleCreate = useCallback(async () => {
+ if (!deviceId) return;
+ setCreating(true);
+ try {
+ const title = agentName.trim() || selectedPlatformDef.name;
+ const result = await storeCreateAgent({
+ config: {
+ agencyConfig: {
+ boundDeviceId: deviceId,
+ heterogeneousProvider: {
+ type: platform,
+ },
+ },
+ avatar: agentProfile?.avatar || undefined,
+ description: agentDescription.trim() || undefined,
+ title,
+ },
+ groupId,
+ });
+ await refreshAgentList();
+ close();
+ navigate(`/agent/${result.agentId}`);
+ } finally {
+ setCreating(false);
+ }
+ }, [
+ deviceId,
+ agentName,
+ agentDescription,
+ agentProfile,
+ platform,
+ groupId,
+ storeCreateAgent,
+ refreshAgentList,
+ close,
+ navigate,
+ selectedPlatformDef.name,
+ ]);
+
+ const renderCapabilityStatus = () => {
+ if (!deviceId) return null;
+ if (checkingCapability)
+ return <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgent.create.checking')}</Tag>;
+ if (!capabilityResult) return null;
+ if (capabilityResult.available) {
return (
- <Flexbox horizontal align="center" gap={4}>
- <Icon color="var(--ant-color-error)" icon={XCircle} size={14} />
- <Tag color="error" style={{ marginInlineEnd: 0 }}>
- {capabilityResult.reason ??
- t('platformAgent.create.notInstalled', { name: selectedPlatformDef.name })}
+ <Flexbox horizontal align="flex-start" gap={4} style={{ flexWrap: 'wrap' }}>
+ <Icon
+ color="var(--ant-color-success)"
+ icon={CheckCircle2}
+ size={14}
+ style={{ marginTop: 2, flexShrink: 0 }}
+ />
+ <Tag
+ color="success"
+ style={{ marginInlineEnd: 0, whiteSpace: 'normal', wordBreak: 'break-word' }}
+ >
+ {capabilityResult.version ?? t('platformAgent.create.available')}
</Tag>
</Flexbox>
);
- };
+ }
- const step2NextDisabled =
- !deviceId || checkingCapability || capabilityResult?.available === false;
+ const isVersionTooLow = capabilityResult.reason?.includes('is not available on this device');
+ if (isVersionTooLow) {
+ return (
+ <Alert
+ showIcon
+ message={t('platformAgent.create.versionTooLow')}
+ type="warning"
+ description={
+ <Flexbox gap={4}>
+ <span>{t('platformAgent.create.versionTooLowHint')}</span>
+ <Typography.Text code copyable>
+ {t('platformAgent.create.upgradeCmd')}
+ </Typography.Text>
+ </Flexbox>
+ }
+ />
+ );
+ }
- const renderStepContent = () => {
- if (step === 0) {
- return (
- <Flexbox gap={12}>
- {platformDefs.map((def) => (
- <div
- className={styles.platformCard}
- data-disabled={def.comingSoon}
- data-selected={!def.comingSoon && platform === def.type}
- key={def.type}
- role="button"
- tabIndex={def.comingSoon ? -1 : 0}
- onClick={() => !def.comingSoon && handlePlatformChange(def.type)}
- onKeyDown={(e) => {
- if (!def.comingSoon && (e.key === 'Enter' || e.key === ' '))
- handlePlatformChange(def.type);
- }}
- >
- <Flexbox horizontal align="center" gap={8}>
- <Icon icon={MonitorSmartphone} size={18} />
- <span className={styles.platformName}>{def.name}</span>
- {def.comingSoon && (
- <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgent.create.comingSoon')}</Tag>
- )}
- </Flexbox>
- <span className={styles.platformDesc}>{def.desc}</span>
- </div>
- ))}
- </Flexbox>
- );
- }
+ return (
+ <Flexbox horizontal align="center" gap={4}>
+ <Icon color="var(--ant-color-error)" icon={XCircle} size={14} />
+ <Tag color="error" style={{ marginInlineEnd: 0 }}>
+ {capabilityResult.reason ??
+ t('platformAgent.create.notInstalled', { name: selectedPlatformDef.name })}
+ </Tag>
+ </Flexbox>
+ );
+ };
- if (step === 1) {
- const onlineDevices = (devices ?? []).filter(
- (d) => d.online && (!restrictToWorkspaceDevices || d.scope === 'workspace'),
- );
- const isRefreshing = loadingDevices || fetchingDevices;
-
- const refreshButton = (
- <Button
- icon={<Icon icon={RefreshCw} size={13} />}
- loading={isRefreshing}
- size="small"
- type="text"
- onClick={() => void refetchDevices()}
- >
- {t('platformAgent.create.refresh')}
- </Button>
- );
+ const step2NextDisabled =
+ !deviceId || checkingCapability || capabilityResult?.available === false;
- if (!isRefreshing && onlineDevices.length === 0) {
- return (
- <Flexbox gap={12}>
- <Alert
- showIcon
- message={t('platformAgent.create.noDevices')}
- type="info"
- description={
- <Flexbox gap={12}>
- <Flexbox gap={6}>
- <span>{t('platformAgent.create.noDevicesDesktopHint')}</span>
- <a href="https://lobehub.com/downloads" rel="noreferrer" target="_blank">
- <Button
- icon={<Icon icon={Download} size={13} />}
- size="small"
- type="primary"
- >
- {t('platformAgent.create.downloadDesktop')}
- </Button>
- </a>
- </Flexbox>
- <Flexbox gap={4}>
- <span>{t('platformAgent.create.noDevicesCliHint')}</span>
- <Typography.Text code copyable>
- {t('platformAgent.create.noDevicesCmd')}
- </Typography.Text>
- </Flexbox>
- </Flexbox>
- }
- />
- {refreshButton}
- </Flexbox>
- );
- }
+ const renderStepContent = () => {
+ if (step === 0) {
+ return (
+ <Flexbox gap={12}>
+ {platformDefs.map((def) => (
+ <div
+ className={styles.platformCard}
+ data-disabled={def.comingSoon}
+ data-selected={!def.comingSoon && platform === def.type}
+ key={def.type}
+ role="button"
+ tabIndex={def.comingSoon ? -1 : 0}
+ onClick={() => !def.comingSoon && handlePlatformChange(def.type)}
+ onKeyDown={(e) => {
+ if (!def.comingSoon && (e.key === 'Enter' || e.key === ' '))
+ handlePlatformChange(def.type);
+ }}
+ >
+ <Flexbox horizontal align="center" gap={8}>
+ <Icon icon={MonitorSmartphone} size={18} />
+ <span className={styles.platformName}>{def.name}</span>
+ {def.comingSoon && (
+ <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgent.create.comingSoon')}</Tag>
+ )}
+ </Flexbox>
+ <span className={styles.platformDesc}>{def.desc}</span>
+ </div>
+ ))}
+ </Flexbox>
+ );
+ }
- return (
- <Flexbox gap={12}>
- <Flexbox horizontal align="center" gap={8}>
- <Select
- loading={isRefreshing}
- placeholder={t('platformAgent.create.selectDevice')}
- style={{ flex: 1 }}
- value={deviceId}
- options={onlineDevices.map((d) => ({
- label: (
- <div className={styles.deviceItem}>
- <Icon icon={BotIcon} size={14} />
- <span>{d.hostname}</span>
- <Tag color="success" style={{ marginInlineEnd: 0 }}>
- {t('platformAgent.device.online')}
- </Tag>
- </div>
- ),
- value: d.deviceId,
- }))}
- onChange={handleDeviceChange}
- />
- {refreshButton}
- </Flexbox>
- {renderCapabilityStatus()}
- </Flexbox>
- );
- }
+ if (step === 1) {
+ const onlineDevices = (devices ?? []).filter(
+ (d) => d.online && (!restrictToWorkspaceDevices || d.scope === 'workspace'),
+ );
+ const isRefreshing = loadingDevices || fetchingDevices;
+
+ const refreshButton = (
+ <Button
+ icon={<Icon icon={RefreshCw} size={13} />}
+ loading={isRefreshing}
+ size="small"
+ type="text"
+ onClick={() => void refetchDevices()}
+ >
+ {t('platformAgent.create.refresh')}
+ </Button>
+ );
- if (step === 2) {
- const avatar = agentProfile?.avatar;
+ if (!isRefreshing && onlineDevices.length === 0) {
return (
<Flexbox gap={12}>
- {avatar && (
- <Flexbox horizontal align="center" gap={12}>
- <div className={styles.avatarPreview}>{avatar}</div>
- </Flexbox>
- )}
- <Input
- maxLength={60}
- value={agentName}
- placeholder={
- fetchingProfile
- ? t('platformAgent.create.fetchingProfile')
- : t('platformAgent.create.namePlaceholder')
+ <Alert
+ showIcon
+ message={t('platformAgent.create.noDevices')}
+ type="info"
+ description={
+ <Flexbox gap={12}>
+ <Flexbox gap={6}>
+ <span>{t('platformAgent.create.noDevicesDesktopHint')}</span>
+ <a href="https://lobehub.com/downloads" rel="noreferrer" target="_blank">
+ <Button icon={<Icon icon={Download} size={13} />} size="small" type="primary">
+ {t('platformAgent.create.downloadDesktop')}
+ </Button>
+ </a>
+ </Flexbox>
+ <Flexbox gap={4}>
+ <span>{t('platformAgent.create.noDevicesCliHint')}</span>
+ <Typography.Text code copyable>
+ {t('platformAgent.create.noDevicesCmd')}
+ </Typography.Text>
+ </Flexbox>
+ </Flexbox>
}
- onChange={(e) => setAgentName(e.target.value)}
- onPressEnter={() => void handleCreate()}
- />
- <Input.TextArea
- autoSize={{ maxRows: 4, minRows: 2 }}
- maxLength={200}
- placeholder={t('platformAgent.create.descriptionPlaceholder')}
- value={agentDescription}
- onChange={(e) => setAgentDescription(e.target.value)}
/>
+ {refreshButton}
</Flexbox>
);
}
- return null;
- };
+ return (
+ <Flexbox gap={12}>
+ <Flexbox horizontal align="center" gap={8}>
+ <Select
+ loading={isRefreshing}
+ placeholder={t('platformAgent.create.selectDevice')}
+ style={{ flex: 1 }}
+ value={deviceId}
+ options={onlineDevices.map((d) => ({
+ label: (
+ <div className={styles.deviceItem}>
+ <Icon icon={BotIcon} size={14} />
+ <span>{d.hostname}</span>
+ <Tag color="success" style={{ marginInlineEnd: 0 }}>
+ {t('platformAgent.device.online')}
+ </Tag>
+ </div>
+ ),
+ value: d.deviceId,
+ }))}
+ onChange={handleDeviceChange}
+ />
+ {refreshButton}
+ </Flexbox>
+ {renderCapabilityStatus()}
+ </Flexbox>
+ );
+ }
- const renderFooter = () => {
- const buttons = [];
+ if (step === 2) {
+ const avatar = agentProfile?.avatar;
+ return (
+ <Flexbox gap={12}>
+ {avatar && (
+ <Flexbox horizontal align="center" gap={12}>
+ <div className={styles.avatarPreview}>{avatar}</div>
+ </Flexbox>
+ )}
+ <Input
+ maxLength={60}
+ value={agentName}
+ placeholder={
+ fetchingProfile
+ ? t('platformAgent.create.fetchingProfile')
+ : t('platformAgent.create.namePlaceholder')
+ }
+ onChange={(e) => setAgentName(e.target.value)}
+ onPressEnter={() => void handleCreate()}
+ />
+ <Input.TextArea
+ autoSize={{ maxRows: 4, minRows: 2 }}
+ maxLength={200}
+ placeholder={t('platformAgent.create.descriptionPlaceholder')}
+ value={agentDescription}
+ onChange={(e) => setAgentDescription(e.target.value)}
+ />
+ </Flexbox>
+ );
+ }
- if (step > 0) {
- buttons.push(
- <Button key="back" onClick={handleBack}>
- {t('platformAgent.create.back')}
- </Button>,
- );
- }
+ return null;
+ };
- if (step < 2) {
- const nextDisabled = step === 1 && step2NextDisabled;
- buttons.push(
- <Button disabled={nextDisabled} key="next" type="primary" onClick={handleNext}>
- {t('platformAgent.create.next')}
- </Button>,
- );
- }
+ const renderFooter = () => {
+ const buttons = [];
- if (step === 2) {
- buttons.push(
- <Button
- disabled={!agentName.trim() && !selectedPlatformDef.name}
- key="create"
- loading={creating}
- type="primary"
- onClick={() => void handleCreate()}
- >
- {creating ? t('platformAgent.create.creating') : t('platformAgent.create.create')}
- </Button>,
- );
- }
+ if (step > 0) {
+ buttons.push(
+ <BaseButton key="back" onClick={handleBack}>
+ {t('platformAgent.create.back')}
+ </BaseButton>,
+ );
+ }
- return buttons;
- };
+ if (step < 2) {
+ const nextDisabled = step === 1 && step2NextDisabled;
+ buttons.push(
+ <BaseButton disabled={nextDisabled} key="next" type="primary" onClick={handleNext}>
+ {t('platformAgent.create.next')}
+ </BaseButton>,
+ );
+ }
- return (
- <Modal
- destroyOnClose
- footer={renderFooter()}
- open={open}
- title={t('platformAgent.create.title')}
- width={480}
- onCancel={onClose}
- >
- <Flexbox gap={24} paddingBlock={'16px 8px'}>
- <Steps
- current={step}
- size="small"
- items={[
- { title: t('platformAgent.create.step1') },
- { title: t('platformAgent.create.step2') },
- { title: t('platformAgent.create.step3') },
- ]}
- />
- {renderStepContent()}
- </Flexbox>
- </Modal>
- );
- },
-);
+ if (step === 2) {
+ buttons.push(
+ <BaseButton
+ disabled={!agentName.trim() && !selectedPlatformDef.name}
+ key="create"
+ loading={creating}
+ type="primary"
+ onClick={() => void handleCreate()}
+ >
+ {creating ? t('platformAgent.create.creating') : t('platformAgent.create.create')}
+ </BaseButton>,
+ );
+ }
-CreatePlatformAgentModal.displayName = 'CreatePlatformAgentModal';
+ return buttons;
+ };
+
+ return (
+ <Flexbox gap={24} paddingBlock={'16px 8px'}>
+ <Steps
+ current={step}
+ size="small"
+ items={[
+ { title: t('platformAgent.create.step1') },
+ { title: t('platformAgent.create.step2') },
+ { title: t('platformAgent.create.step3') },
+ ]}
+ />
+ {renderStepContent()}
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ {renderFooter()}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+CreatePlatformAgentContent.displayName = 'CreatePlatformAgentContent';
+
+interface OpenCreatePlatformAgentModalOptions {
+ groupId?: string;
+}
-export default CreatePlatformAgentModal;
+export const openCreatePlatformAgentModal = (
+ options?: OpenCreatePlatformAgentModalOptions,
+): ModalInstance =>
+ createModal({
+ content: <CreatePlatformAgentContent groupId={options?.groupId} />,
+ footer: null,
+ maskClosable: true,
+ title: i18nT('platformAgent.create.title', { ns: 'chat' }),
+ width: 480,
+ });
diff --git a/src/features/Electron/updater/UpdateNotification.tsx b/src/features/Electron/updater/UpdateNotification.tsx
index d3fbeecc4ca..455b132f6a8 100644
--- a/src/features/Electron/updater/UpdateNotification.tsx
+++ b/src/features/Electron/updater/UpdateNotification.tsx
@@ -1,10 +1,11 @@
import { type UpdateInfo } from '@lobechat/electron-client-ipc';
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
import { Button, Flexbox, Icon, Markdown } from '@lobehub/ui';
-import { Modal } from 'antd';
+import { Button as BaseButton, createModal, useModalContext } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
+import { t } from 'i18next';
import { CircleFadingArrowUp } from 'lucide-react';
-import React, { useState } from 'react';
+import React, { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { autoUpdateService } from '@/services/electron/autoUpdate';
@@ -28,15 +29,75 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
+interface UpdateDetailContentProps {
+ updateInfo: UpdateInfo;
+}
+
+const UpdateDetailContent = memo<UpdateDetailContentProps>(({ updateInfo }) => {
+ const { t: tElectron } = useTranslation('electron');
+ const { close } = useModalContext();
+ const [isInstalling, setIsInstalling] = useState(false);
+
+ return (
+ <Flexbox gap={12} style={{ maxWidth: 480 }}>
+ <div style={{ color: cssVar.colorTextSecondary, fontSize: 12 }}>{updateInfo.version}</div>
+ {updateInfo.releaseNotes &&
+ (typeof updateInfo.releaseNotes === 'string' ? (
+ <div className={styles.releaseNote}>
+ <Markdown>{updateInfo.releaseNotes}</Markdown>
+ </div>
+ ) : (
+ <div className={styles.releaseNote}>
+ {updateInfo.releaseNotes.map((note) => (
+ <Markdown key={note.version}>{note.note ?? ''}</Markdown>
+ ))}
+ </div>
+ ))}
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <BaseButton
+ size={'small'}
+ onClick={() => {
+ autoUpdateService.installLater();
+ close();
+ }}
+ >
+ {tElectron('updater.installLater')}
+ </BaseButton>
+ <BaseButton
+ loading={isInstalling}
+ size={'small'}
+ type={'primary'}
+ onClick={() => {
+ setIsInstalling(true);
+ autoUpdateService.installNow();
+ }}
+ >
+ {tElectron('updater.restartAndInstall')}
+ </BaseButton>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+UpdateDetailContent.displayName = 'UpdateDetailContent';
+
+const openUpdateDetailModal = (updateInfo: UpdateInfo) =>
+ createModal({
+ content: <UpdateDetailContent updateInfo={updateInfo} />,
+ footer: null,
+ maskClosable: true,
+ title: t('updater.updateReady', { ns: 'electron' }),
+ width: 520,
+ });
+
export const UpdateNotification: React.FC = () => {
- const { t } = useTranslation('electron');
+ const { t: tElectron } = useTranslation('electron');
const [updateAvailable, setUpdateAvailable] = useState(false);
const [updateDownloaded, setUpdateDownloaded] = useState(false);
const [updateInfo, setUpdateInfo] = useState<UpdateInfo | null>(null);
const [installConfirmMode, setInstallConfirmMode] = useState<
'unconfirm' | 'installLater' | 'installNow' | null
>('unconfirm');
- const [detailVisible, setDetailVisible] = useState(false);
const [isInstalling, setIsInstalling] = useState(false);
useWatchBroadcast('updateDownloaded', (info: UpdateInfo) => {
@@ -44,16 +105,14 @@ export const UpdateNotification: React.FC = () => {
setUpdateDownloaded(true);
setUpdateAvailable(false);
setInstallConfirmMode('unconfirm');
- setDetailVisible(false);
});
useWatchBroadcast('updateWillInstallLater', () => {
setInstallConfirmMode('installLater');
- setTimeout(() => setInstallConfirmMode(null), 5000); // Auto-hide the notification after 5 seconds
+ setTimeout(() => setInstallConfirmMode(null), 5000);
});
- // Do not display anything when there's no update or it's currently downloading
if (!updateDownloaded && !updateAvailable) return null;
if (installConfirmMode === 'installLater') {
@@ -71,100 +130,61 @@ export const UpdateNotification: React.FC = () => {
zIndex: 1000,
}}
>
- {t('updater.willInstallLater')}
+ {tElectron('updater.willInstallLater')}
</div>
);
}
if (installConfirmMode === 'unconfirm')
return (
- <>
- <div className={styles.container}>
+ <div className={styles.container}>
+ <div
+ style={{
+ alignItems: 'center',
+ background: cssVar.colorBgElevated,
+ border: `1px solid ${cssVar.colorBorderSecondary}`,
+ borderRadius: 12,
+ boxShadow: cssVar.boxShadow,
+ color: cssVar.colorText,
+ display: 'flex',
+ gap: 8,
+ padding: '8px 10px',
+ }}
+ >
+ <Icon icon={CircleFadingArrowUp} style={{ fontSize: 16 }} />
<div
- style={{
- alignItems: 'center',
- background: cssVar.colorBgElevated,
- border: `1px solid ${cssVar.colorBorderSecondary}`,
- borderRadius: 12,
- boxShadow: cssVar.boxShadow,
- color: cssVar.colorText,
- display: 'flex',
- gap: 8,
- padding: '8px 10px',
+ style={{ cursor: 'pointer', fontSize: 12 }}
+ onClick={() => {
+ if (updateInfo) openUpdateDetailModal(updateInfo);
}}
>
- <Icon icon={CircleFadingArrowUp} style={{ fontSize: 16 }} />
- <div style={{ cursor: 'pointer', fontSize: 12 }} onClick={() => setDetailVisible(true)}>
- {t('updater.updateReady')}
- {updateInfo?.version ? ` · ${updateInfo.version}` : ''}
- </div>
- <div style={{ flex: 1 }} />
- <Button
- size="small"
- type="text"
- onClick={() => {
- autoUpdateService.installLater();
- }}
- >
- {t('updater.later')}
- </Button>
-
- <Button
- loading={isInstalling}
- size="small"
- type="primary"
- onClick={() => {
- setIsInstalling(true);
- autoUpdateService.installNow();
- }}
- >
- {t('updater.upgradeNow')}
- </Button>
+ {tElectron('updater.updateReady')}
+ {updateInfo?.version ? ` · ${updateInfo.version}` : ''}
</div>
- </div>
+ <div style={{ flex: 1 }} />
+ <Button
+ size="small"
+ type="text"
+ onClick={() => {
+ autoUpdateService.installLater();
+ }}
+ >
+ {tElectron('updater.later')}
+ </Button>
- <Modal
- footer={null}
- open={detailVisible}
- title={t('updater.updateReady')}
- width={520}
- onCancel={() => setDetailVisible(false)}
- >
- <Flexbox gap={12} style={{ maxWidth: 480 }}>
- <div style={{ color: cssVar.colorTextSecondary, fontSize: 12 }}>
- {updateInfo?.version}
- </div>
- {updateInfo?.releaseNotes &&
- (typeof updateInfo.releaseNotes === 'string' ? (
- <div className={styles.releaseNote}>
- <Markdown>{updateInfo.releaseNotes}</Markdown>
- </div>
- ) : (
- <div className={styles.releaseNote}>
- {updateInfo.releaseNotes.map((note) => (
- <Markdown key={note.version}>{note.note ?? ''}</Markdown>
- ))}
- </div>
- ))}
- <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
- <Button size="small" onClick={() => autoUpdateService.installLater()}>
- {t('updater.installLater')}
- </Button>
- <Button
- loading={isInstalling}
- size="small"
- type="primary"
- onClick={() => {
- setIsInstalling(true);
- autoUpdateService.installNow();
- }}
- >
- {t('updater.restartAndInstall')}
- </Button>
- </div>
- </Flexbox>
- </Modal>
- </>
+ <Button
+ loading={isInstalling}
+ size="small"
+ type="primary"
+ onClick={() => {
+ setIsInstalling(true);
+ autoUpdateService.installNow();
+ }}
+ >
+ {tElectron('updater.upgradeNow')}
+ </Button>
+ </div>
+ </div>
);
return null;
diff --git a/src/features/PageExplorer/PageExplorerPlaceholder.tsx b/src/features/PageExplorer/PageExplorerPlaceholder.tsx
index 140ce4c3767..73a3e88fb99 100644
--- a/src/features/PageExplorer/PageExplorerPlaceholder.tsx
+++ b/src/features/PageExplorer/PageExplorerPlaceholder.tsx
@@ -1,4 +1,3 @@
-import { FILE_URL } from '@lobechat/business-const';
import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { Notion } from '@lobehub/icons';
import { Center, FileTypeIcon, Flexbox, Icon, Text } from '@lobehub/ui';
@@ -8,8 +7,6 @@ import { ArrowUpIcon, PlusIcon } from 'lucide-react';
import React, { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import GuideModal from '@/components/GuideModal';
-import GuideVideo from '@/components/GuideVideo';
import NavHeader from '@/features/NavHeader';
import useNotionImport from '@/features/ResourceManager/components/Header/hooks/useNotionImport';
import { usePermission } from '@/hooks/usePermission';
@@ -334,16 +331,6 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(
</Flexbox>
</Flexbox>
</Center>
- <GuideModal
- cancelText={t('header.actions.notionGuide.cancel')}
- cover={<GuideVideo height={269} src={FILE_URL.importFromNotionGuide} width={358} />}
- desc={t('header.actions.notionGuide.desc')}
- okText={t('header.actions.notionGuide.ok')}
- open={notionImport.notionGuideOpen}
- title={t('header.actions.notionGuide.title')}
- onCancel={notionImport.handleCloseNotionGuide}
- onOk={notionImport.handleStartNotionImport}
- />
<input
accept=".zip"
ref={notionImport.notionInputRef}
diff --git a/src/features/ResourceManager/components/Editor/index.tsx b/src/features/ResourceManager/components/Editor/index.tsx
index 5caa25f04c8..485ec9d205f 100644
--- a/src/features/ResourceManager/components/Editor/index.tsx
+++ b/src/features/ResourceManager/components/Editor/index.tsx
@@ -1,14 +1,16 @@
'use client';
-import { ActionIcon, Flexbox } from '@lobehub/ui';
-import { Modal } from 'antd';
+import { ActionIcon, Flexbox, Skeleton } from '@lobehub/ui';
+import { createModal } from '@lobehub/ui/base-ui';
import { cssVar, useTheme } from 'antd-style';
+import { t as i18nT } from 'i18next';
import { ArrowLeftIcon, DownloadIcon, InfoIcon } from 'lucide-react';
-import { memo, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import NavHeader from '@/features/NavHeader';
import { PageAgentProvider } from '@/features/PageEditor/PageAgentProvider';
+import { lambdaQuery } from '@/libs/trpc/client';
import FileDetailComponent from '@/routes/(main)/resource/features/FileDetail';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { fileManagerSelectors, useFileStore } from '@/store/file';
@@ -20,86 +22,110 @@ interface FileEditorProps {
onBack?: () => void;
}
+const FileDetailSkeleton = () => (
+ <Flexbox gap={16}>
+ <Skeleton
+ active
+ paragraph={{ rows: 5, width: ['80%', '60%', '40%', '70%', '70%'] }}
+ title={false}
+ />
+ <Skeleton active paragraph={{ rows: 2, width: ['50%', '60%'] }} title={false} />
+ </Flexbox>
+);
+
+const FileDetailModalContent = memo(() => {
+ const currentViewItemId = useResourceManagerStore((s) => s.currentViewItemId);
+ const fromStore = useFileStore(fileManagerSelectors.getFileById(currentViewItemId));
+ const { data: fromQuery } = lambdaQuery.file.getFileItemById.useQuery(
+ { id: currentViewItemId ?? '' },
+ { enabled: !fromStore && !!currentViewItemId },
+ );
+ const fileDetail = fromStore ?? fromQuery;
+ return (
+ <Flexbox style={{ minHeight: 260 }}>
+ {fileDetail ? (
+ <FileDetailComponent {...fileDetail} showDownloadButton={false} showTitle={false} />
+ ) : (
+ <FileDetailSkeleton />
+ )}
+ </Flexbox>
+ );
+});
+
+FileDetailModalContent.displayName = 'FileDetailModalContent';
+
+const openFileDetailModal = () =>
+ createModal({
+ content: <FileDetailModalContent />,
+ footer: null,
+ maskClosable: true,
+ title: i18nT('detail.basic.title', { ns: 'file' }),
+ width: 400,
+ });
+
const FileEditorCanvas = memo<FileEditorProps>(({ onBack }) => {
const { t } = useTranslation(['common', 'file']);
const theme = useTheme();
- const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
const currentViewItemId = useResourceManagerStore((s) => s.currentViewItemId);
const fileDetail = useFileStore(fileManagerSelectors.getFileById(currentViewItemId));
return (
- <>
- <Flexbox horizontal height={'100%'} width={'100%'}>
- <Flexbox flex={1} height={'100%'}>
- <NavHeader
- left={
- <Flexbox
- horizontal
- align={'center'}
- gap={12}
- style={{ minHeight: 32, minWidth: 0, overflow: 'hidden' }}
+ <Flexbox horizontal height={'100%'} width={'100%'}>
+ <Flexbox flex={1} height={'100%'}>
+ <NavHeader
+ left={
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ style={{ minHeight: 32, minWidth: 0, overflow: 'hidden' }}
+ >
+ <ActionIcon icon={ArrowLeftIcon} title={t('back')} onClick={onBack} />
+ <span
+ title={fileDetail?.name}
+ style={{
+ color: theme.colorText,
+ fontSize: 14,
+ fontWeight: 500,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ }}
>
- <ActionIcon icon={ArrowLeftIcon} title={t('back')} onClick={onBack} />
- <span
- title={fileDetail?.name}
- style={{
- color: theme.colorText,
- fontSize: 14,
- fontWeight: 500,
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
+ {fileDetail?.name}
+ </span>
+ </Flexbox>
+ }
+ right={
+ <Flexbox horizontal gap={8}>
+ {fileDetail?.url && (
+ <ActionIcon
+ icon={DownloadIcon}
+ title={t('download', { ns: 'common' })}
+ onClick={() => {
+ if (fileDetail?.url && fileDetail?.name) {
+ downloadFile(fileDetail.url, fileDetail.name);
+ }
}}
- >
- {fileDetail?.name}
- </span>
- </Flexbox>
- }
- right={
- <Flexbox horizontal gap={8}>
- {/* <ToggleRightPanelButton icon={BotMessageSquareIcon} showActive={true} size={20} /> */}
- {fileDetail?.url && (
- <ActionIcon
- icon={DownloadIcon}
- title={t('download', { ns: 'common' })}
- onClick={() => {
- if (fileDetail?.url && fileDetail?.name) {
- downloadFile(fileDetail.url, fileDetail.name);
- }
- }}
- />
- )}
- <ActionIcon icon={InfoIcon} onClick={() => setIsDetailModalOpen(true)} />
- </Flexbox>
- }
- style={{
- borderBottom: `1px solid ${cssVar.colorBorderSecondary}`,
- }}
- styles={{
- left: { flex: 1, minWidth: 0, overflow: 'hidden', padding: 0 },
- }}
- />
- <Flexbox flex={1} style={{ overflow: 'hidden' }}>
- <FileContent fileId={currentViewItemId} />
- </Flexbox>
+ />
+ )}
+ <ActionIcon icon={InfoIcon} onClick={openFileDetailModal} />
+ </Flexbox>
+ }
+ style={{
+ borderBottom: `1px solid ${cssVar.colorBorderSecondary}`,
+ }}
+ styles={{
+ left: { flex: 1, minWidth: 0, overflow: 'hidden', padding: 0 },
+ }}
+ />
+ <Flexbox flex={1} style={{ overflow: 'hidden' }}>
+ <FileContent fileId={currentViewItemId} />
</Flexbox>
- {/* <FileCopilot /> */}
</Flexbox>
-
- <Modal
- footer={null}
- open={isDetailModalOpen}
- title={t('detail.basic.title', { ns: 'file' })}
- width={400}
- onCancel={() => setIsDetailModalOpen(false)}
- >
- {fileDetail && (
- <FileDetailComponent {...fileDetail} showDownloadButton={false} showTitle={false} />
- )}
- </Modal>
- </>
+ </Flexbox>
);
});
diff --git a/src/features/ResourceManager/components/Header/AddButton.tsx b/src/features/ResourceManager/components/Header/AddButton.tsx
index 44c30149514..f370da85782 100644
--- a/src/features/ResourceManager/components/Header/AddButton.tsx
+++ b/src/features/ResourceManager/components/Header/AddButton.tsx
@@ -1,13 +1,12 @@
'use client';
-import { FILE_URL } from '@lobechat/business-const';
import {
CUSTOM_DOCUMENT_FILE_TYPE,
CUSTOM_FOLDER_FILE_TYPE,
DERIVED_DOCUMENT_SOURCE_TYPE,
} from '@lobechat/const';
import { Notion } from '@lobehub/icons';
-import { type MenuProps } from '@lobehub/ui';
+import { type DropdownItem } from '@lobehub/ui';
import { Button, DropdownMenu, Icon, Tooltip } from '@lobehub/ui';
import { Upload } from 'antd';
import { FilePenLine, FileUp, FolderIcon, FolderUp, Link, Plus } from 'lucide-react';
@@ -16,8 +15,6 @@ import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { message } from '@/components/AntdStaticMethods';
-import GuideModal from '@/components/GuideModal';
-import GuideVideo from '@/components/GuideVideo';
import { usePermission } from '@/hooks/usePermission';
import { useCurrentFolderId } from '@/routes/(main)/resource/features/hooks/useCurrentFolderId';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
@@ -157,14 +154,7 @@ const AddButton = () => {
t,
]);
- const {
- handleCloseNotionGuide,
- handleNotionImport,
- handleOpenNotionGuide,
- handleStartNotionImport,
- notionGuideOpen,
- notionInputRef,
- } = useNotionImport({
+ const { handleNotionImport, handleOpenNotionGuide, notionInputRef } = useNotionImport({
createDocument,
currentFolderId,
libraryId,
@@ -185,7 +175,7 @@ const AddButton = () => {
[handleFolderUpload],
);
- const items = useMemo<MenuProps['items']>(
+ const items = useMemo<DropdownItem[]>(
() => [
{
icon: <Icon icon={FilePenLine} />,
@@ -247,6 +237,7 @@ const AddButton = () => {
icon: <Icon icon={Link} />,
key: 'connect',
label: t('header.actions.connect'),
+ type: 'submenu',
},
],
[
@@ -263,32 +254,21 @@ const AddButton = () => {
return (
<>
- <DropdownMenu
- items={canCreate ? items : []}
- open={menuOpen}
- placement="bottomRight"
- trigger="both"
- onOpenChange={(open) => {
- if (!canCreate) return;
- setMenuOpen(open);
- }}
- >
- <Tooltip title={reason}>
+ <Tooltip title={canCreate ? undefined : reason}>
+ <DropdownMenu
+ items={canCreate ? items : []}
+ open={menuOpen}
+ placement="bottomRight"
+ onOpenChange={(open) => {
+ if (!canCreate) return;
+ setMenuOpen(open);
+ }}
+ >
<Button data-no-highlight disabled={!canCreate} icon={Plus} type="primary">
{t('addLibrary')}
</Button>
- </Tooltip>
- </DropdownMenu>
- <GuideModal
- cancelText={t('header.actions.notionGuide.cancel')}
- cover={<GuideVideo height={269} src={FILE_URL.importFromNotionGuide} width={358} />}
- desc={t('header.actions.notionGuide.desc')}
- okText={t('header.actions.notionGuide.ok')}
- open={notionGuideOpen}
- title={t('header.actions.notionGuide.title')}
- onCancel={handleCloseNotionGuide}
- onOk={handleStartNotionImport}
- />
+ </DropdownMenu>
+ </Tooltip>
<input
multiple
id="folder-upload-input"
diff --git a/src/features/ResourceManager/components/Header/hooks/useNotionImport.ts b/src/features/ResourceManager/components/Header/hooks/useNotionImport.tsx
similarity index 80%
rename from src/features/ResourceManager/components/Header/hooks/useNotionImport.ts
rename to src/features/ResourceManager/components/Header/hooks/useNotionImport.tsx
index 499d86efa4c..73f7f887b5f 100644
--- a/src/features/ResourceManager/components/Header/hooks/useNotionImport.ts
+++ b/src/features/ResourceManager/components/Header/hooks/useNotionImport.tsx
@@ -1,8 +1,11 @@
+import { FILE_URL } from '@lobechat/business-const';
import debug from 'debug';
import { type TFunction } from 'i18next';
import { type ChangeEvent } from 'react';
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useRef } from 'react';
+import { createGuideModal } from '@/components/GuideModal';
+import GuideVideo from '@/components/GuideVideo';
import { type DocumentAction } from '@/store/file/slices/document/action';
import { unzipFile } from '@/utils/unzipFile';
@@ -24,20 +27,19 @@ const useNotionImport = ({
t,
}: UseNotionImportOptions) => {
const notionInputRef = useRef<HTMLInputElement>(null);
- const [notionGuideOpen, setNotionGuideOpen] = useState(false);
const handleOpenNotionGuide = useCallback(() => {
- setNotionGuideOpen(true);
- }, []);
-
- const handleCloseNotionGuide = useCallback(() => {
- setNotionGuideOpen(false);
- }, []);
-
- const handleStartNotionImport = useCallback(() => {
- notionInputRef.current?.click();
- setNotionGuideOpen(false);
- }, []);
+ createGuideModal({
+ cancelText: t('header.actions.notionGuide.cancel'),
+ cover: <GuideVideo height={269} src={FILE_URL.importFromNotionGuide} width={358} />,
+ desc: t('header.actions.notionGuide.desc'),
+ okText: t('header.actions.notionGuide.ok'),
+ onOk: () => {
+ notionInputRef.current?.click();
+ },
+ title: t('header.actions.notionGuide.title'),
+ });
+ }, [t]);
const handleNotionImport = useCallback(
async (event: ChangeEvent<HTMLInputElement>) => {
@@ -47,7 +49,6 @@ const useNotionImport = ({
try {
const { message } = await import('antd');
- // Show loading message
const loadingKey = 'notion-import';
message.loading({
content: t('header.actions.notion.importing'),
@@ -55,7 +56,6 @@ const useNotionImport = ({
key: loadingKey,
});
- // Unzip the file
let files = await unzipFile(file);
log(
@@ -63,7 +63,6 @@ const useNotionImport = ({
files.map((f) => ({ name: f.name, type: f.type })),
);
- // Check if there are nested ZIP files (common in Notion exports)
const nestedZips = files.filter((f) => f.name.toLowerCase().endsWith('.zip'));
if (nestedZips.length > 0) {
@@ -86,7 +85,6 @@ const useNotionImport = ({
}
}
- // Replace files with nested content
files = allNestedFiles;
}
@@ -95,7 +93,6 @@ const useNotionImport = ({
files.map((f) => ({ name: f.name, type: f.type })),
);
- // Filter for markdown files (case-insensitive, support both .md and .markdown)
const mdFiles = files.filter((f) => {
const name = f.name.toLowerCase();
return name.endsWith('.md') || name.endsWith('.markdown');
@@ -114,32 +111,25 @@ const useNotionImport = ({
return;
}
- // Process each markdown file
let successCount = 0;
let failedCount = 0;
for (const mdFile of mdFiles) {
try {
- // Read file content
let content = await mdFile.text();
let title = '';
- // Check if first line is a heading (# Title)
const lines = content.split('\n');
const firstLine = lines[0]?.trim() || '';
if (firstLine.startsWith('#')) {
- // Extract title from heading (remove # symbols and trim)
title = firstLine.replace(/^#+\s*/, '').trim();
- // Remove the first line from content
content = lines.slice(1).join('\n').trim();
} else {
- // Fallback to filename without extension
const filename = mdFile.name.split('/').pop() || 'Untitled';
title = filename.replace(/\.md$/, '');
}
- // Create document
await createDocument({
content,
knowledgeBaseId: libraryId ?? undefined,
@@ -154,7 +144,6 @@ const useNotionImport = ({
}
}
- // Show completion message
message.destroy(loadingKey);
if (failedCount === 0) {
@@ -179,18 +168,14 @@ const useNotionImport = ({
message.error(t('header.actions.notion.error'));
}
- // Reset input to allow re-uploading
event.target.value = '';
},
[createDocument, currentFolderId, libraryId, refetchResources, t],
);
return {
- handleCloseNotionGuide,
handleNotionImport,
handleOpenNotionGuide,
- handleStartNotionImport,
- notionGuideOpen,
notionInputRef,
};
};
diff --git a/src/features/Setting/Footer.tsx b/src/features/Setting/Footer.tsx
index 379b79ff647..1803bb87c9a 100644
--- a/src/features/Setting/Footer.tsx
+++ b/src/features/Setting/Footer.tsx
@@ -5,10 +5,10 @@ import { Center, Flexbox, Icon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { MessageSquareHeart } from 'lucide-react';
import { type PropsWithChildren } from 'react';
-import { memo, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import GuideModal from '@/components/GuideModal';
+import { createGuideModal } from '@/components/GuideModal';
import GuideVideo from '@/components/GuideVideo';
import { GITHUB, GITHUB_ISSUES } from '@/const/url';
import { useServerConfigStore } from '@/store/serverConfig';
@@ -25,90 +25,79 @@ export const LayoutSettingsFooterClassName = 'settings-layout-footer';
const Footer = memo<PropsWithChildren>(() => {
const { t } = useTranslation('common');
- const [openStar, setOpenStar] = useState(false);
- const [openFeedback, setOpenFeedback] = useState(false);
const hideGitHubEngagementFooter = useServerConfigStore((s) =>
Boolean(s.featureFlags.hideGitHub || s.serverConfig.enableBusinessFeatures),
);
+ const handleOpenStar = () =>
+ createGuideModal({
+ cancelText: t('footer.later'),
+ cover: (
+ <GuideVideo
+ height={269}
+ src={`https://hub-apac-1.lobeobjects.space/assets/star.mp4`}
+ width={358}
+ />
+ ),
+ desc: t('footer.star.desc'),
+ okText: t('footer.star.action'),
+ onOk: () => {
+ if (isOnServerSide) return;
+ window.open(GITHUB, '__blank');
+ },
+ title: t('footer.star.title'),
+ });
+
+ const handleOpenFeedback = () =>
+ createGuideModal({
+ cancelText: t('footer.later'),
+ cover: (
+ <GuideVideo
+ height={269}
+ src={'<@985522149420855317> https://hub-apac-1.lobeobjects.space/assets/feedback.mp4'}
+ width={358}
+ />
+ ),
+ desc: t('footer.feedback.desc', { appName: BRANDING_NAME }),
+ okText: t('footer.feedback.action'),
+ onOk: () => {
+ if (isOnServerSide) return;
+ window.open(GITHUB_ISSUES, '__blank');
+ },
+ title: t('footer.feedback.title'),
+ });
+
return hideGitHubEngagementFooter ? null : (
- <>
- <Flexbox className={LayoutSettingsFooterClassName} justify={'flex-end'}>
- <Center
- horizontal
- as={'footer'}
- className={styles}
- flex={'none'}
- padding={16}
- width={'100%'}
- >
- <div style={{ textAlign: 'center' }}>
- <Icon icon={MessageSquareHeart} /> {`${t('footer.title')} `}
- <a
- aria-label={'star'}
- href={GITHUB}
- onClick={(e) => {
- e.preventDefault();
- setOpenStar(true);
- }}
- >
- {t('footer.action.star')}
- </a>
- {` ${t('footer.and')} `}
- <a
- aria-label={'feedback'}
- href={GITHUB_ISSUES}
- onClick={(e) => {
- e.preventDefault();
- setOpenFeedback(true);
- }}
- >
- {t('footer.action.feedback')}
- </a>
- {' !'}
- </div>
- </Center>
- </Flexbox>
- <GuideModal
- cancelText={t('footer.later')}
- desc={t('footer.star.desc')}
- okText={t('footer.star.action')}
- open={openStar}
- title={t('footer.star.title')}
- cover={
- <GuideVideo
- height={269}
- src={`https://hub-apac-1.lobeobjects.space/assets/star.mp4`}
- width={358}
- />
- }
- onCancel={() => setOpenStar(false)}
- onOk={() => {
- if (isOnServerSide) return;
- window.open(GITHUB, '__blank');
- }}
- />
- <GuideModal
- cancelText={t('footer.later')}
- desc={t('footer.feedback.desc', { appName: BRANDING_NAME })}
- okText={t('footer.feedback.action')}
- open={openFeedback}
- title={t('footer.feedback.title')}
- cover={
- <GuideVideo
- height={269}
- src={'<@985522149420855317> https://hub-apac-1.lobeobjects.space/assets/feedback.mp4'}
- width={358}
- />
- }
- onCancel={() => setOpenFeedback(false)}
- onOk={() => {
- if (isOnServerSide) return;
- window.open(GITHUB_ISSUES, '__blank');
- }}
- />
- </>
+ <Flexbox className={LayoutSettingsFooterClassName} justify={'flex-end'}>
+ <Center horizontal as={'footer'} className={styles} flex={'none'} padding={16} width={'100%'}>
+ <div style={{ textAlign: 'center' }}>
+ <Icon icon={MessageSquareHeart} /> {`${t('footer.title')} `}
+ <a
+ aria-label={'star'}
+ href={GITHUB}
+ onClick={(e) => {
+ e.preventDefault();
+ handleOpenStar();
+ }}
+ >
+ {t('footer.action.star')}
+ </a>
+ {` ${t('footer.and')} `}
+ <a
+ aria-label={'feedback'}
+ href={GITHUB_ISSUES}
+ onClick={(e) => {
+ e.preventDefault();
+ handleOpenFeedback();
+ }}
+ >
+ {t('footer.action.feedback')}
+ </a>
+ {' !'}
+ </div>
+ </Center>
+ </Flexbox>
);
});
diff --git a/src/features/ShareModal/SharePdf/PdfPreview.tsx b/src/features/ShareModal/SharePdf/PdfPreview.tsx
index d386993aefa..61ad6912776 100644
--- a/src/features/ShareModal/SharePdf/PdfPreview.tsx
+++ b/src/features/ShareModal/SharePdf/PdfPreview.tsx
@@ -2,7 +2,8 @@
import { LoadingOutlined } from '@ant-design/icons';
import { Button, Flexbox } from '@lobehub/ui';
-import { Input, Modal, Spin } from 'antd';
+import { createModal } from '@lobehub/ui/base-ui';
+import { Input, Spin } from 'antd';
import { createStaticStyles, cx } from 'antd-style';
import { ChevronLeft, ChevronRight, Expand, FileText } from 'lucide-react';
import { memo, useState } from 'react';
@@ -123,6 +124,98 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
+interface FullscreenContentProps {
+ initialPage: number;
+ pdfDataUri: string;
+}
+
+const FullscreenContent = memo<FullscreenContentProps>(({ pdfDataUri, initialPage }) => {
+ const [numPages, setNumPages] = useState<number>(0);
+ const [pageNumber, setPageNumber] = useState<number>(initialPage);
+
+ const goToPrev = () => {
+ if (pageNumber > 1) setPageNumber(pageNumber - 1);
+ };
+
+ const goToNext = () => {
+ if (pageNumber < numPages) setPageNumber(pageNumber + 1);
+ };
+
+ const goToPage = (page: number) => {
+ if (page >= 1 && page <= numPages) setPageNumber(page);
+ };
+
+ return (
+ <div className={styles.fullscreenModal}>
+ <div className={styles.fullscreenContent}>
+ <Document
+ file={pdfDataUri}
+ onLoadSuccess={({ numPages: total }: { numPages: number }) => setNumPages(total)}
+ >
+ <Page
+ pageNumber={pageNumber}
+ renderAnnotationLayer={false}
+ renderTextLayer={false}
+ width={Math.min(window.innerWidth * 0.8, 1000)}
+ />
+ </Document>
+ </div>
+
+ {numPages > 1 && (
+ <div className={styles.fullscreenNavigation}>
+ <Flexbox horizontal align="center" gap={12}>
+ <Button
+ className={styles.fullscreenButton}
+ disabled={pageNumber <= 1}
+ icon={<ChevronLeft size={16} />}
+ size="small"
+ type="text"
+ onClick={goToPrev}
+ />
+ <Flexbox horizontal align="center" gap={8}>
+ <Input
+ className={styles.fullscreenPageInput}
+ max={numPages}
+ min={1}
+ size="small"
+ type="number"
+ value={pageNumber}
+ onChange={(e) => {
+ const value = parseInt(e.target.value);
+ if (!isNaN(value)) goToPage(value);
+ }}
+ />
+ <span className={styles.fullscreenPageText}>/ {numPages}</span>
+ </Flexbox>
+ <Button
+ className={styles.fullscreenButton}
+ disabled={pageNumber >= numPages}
+ icon={<ChevronRight size={16} />}
+ size="small"
+ type="text"
+ onClick={goToNext}
+ />
+ </Flexbox>
+ </div>
+ )}
+ </div>
+ );
+});
+
+FullscreenContent.displayName = 'PdfFullscreenContent';
+
+const openPdfFullscreenModal = (pdfDataUri: string, initialPage: number) =>
+ createModal({
+ content: <FullscreenContent initialPage={initialPage} pdfDataUri={pdfDataUri} />,
+ footer: null,
+ maskClosable: true,
+ styles: {
+ content: { padding: 0 },
+ header: { display: 'none' },
+ },
+ width: '95vw',
+ });
+
interface PdfPreviewProps {
loading: boolean;
onGeneratePdf?: () => void;
@@ -134,11 +227,8 @@ const PdfPreview = memo<PdfPreviewProps>(({ loading, pdfData, onGeneratePdf }) =
const { t } = useTranslation('chat');
const isMobile = useIsMobile();
- // Page navigation state
const [numPages, setNumPages] = useState<number>(0);
const [pageNumber, setPageNumber] = useState<number>(1);
- const [fullscreenOpen, setFullscreenOpen] = useState(false);
- const [fullscreenPageNumber, setFullscreenPageNumber] = useState<number>(1);
const onDocumentLoadSuccess = ({ numPages }: { numPages: number }) => {
setNumPages(numPages);
@@ -163,31 +253,6 @@ const PdfPreview = memo<PdfPreviewProps>(({ loading, pdfData, onGeneratePdf }) =
}
};
- const handleFullscreen = () => {
- if (pdfData) {
- setFullscreenPageNumber(pageNumber);
- setFullscreenOpen(true);
- }
- };
-
- const goToFullscreenPrevPage = () => {
- if (fullscreenPageNumber > 1) {
- setFullscreenPageNumber(fullscreenPageNumber - 1);
- }
- };
-
- const goToFullscreenNextPage = () => {
- if (fullscreenPageNumber < numPages) {
- setFullscreenPageNumber(fullscreenPageNumber + 1);
- }
- };
-
- const goToFullscreenPage = (page: number) => {
- if (page >= 1 && page <= numPages) {
- setFullscreenPageNumber(page);
- }
- };
-
if (loading) {
return (
<div
@@ -217,150 +282,86 @@ const PdfPreview = memo<PdfPreviewProps>(({ loading, pdfData, onGeneratePdf }) =
);
}
- // Convert base64 to data URI
const pdfDataUri = `data:application/pdf;base64,${pdfData}`;
+ const handleFullscreen = () => {
+ if (pdfData) openPdfFullscreenModal(pdfDataUri, pageNumber);
+ };
+
return (
- <>
- <div className={localStyles.containerWrapper}>
- {pdfData && (
- <Button
- className={localStyles.expandButton}
- icon={<Expand size={16} />}
- size="small"
- type="text"
- onClick={handleFullscreen}
- />
- )}
+ <div className={localStyles.containerWrapper}>
+ {pdfData && (
+ <Button
+ className={localStyles.expandButton}
+ icon={<Expand size={16} />}
+ size="small"
+ type="text"
+ onClick={handleFullscreen}
+ />
+ )}
- <div
- className={cx(
- containerStyles.preview,
- containerStyles.previewWide,
- localStyles.previewContainer,
- )}
+ <div
+ className={cx(
+ containerStyles.preview,
+ containerStyles.previewWide,
+ localStyles.previewContainer,
+ )}
+ >
+ <Document
+ file={pdfDataUri}
+ loading={
+ <div className={localStyles.documentLoading}>
+ <Spin />
+ <div className={localStyles.loadingText}>{t('shareModal.loadingPdf')}</div>
+ </div>
+ }
+ onLoadSuccess={onDocumentLoadSuccess}
>
- <Document
- file={pdfDataUri}
- loading={
- <div className={localStyles.documentLoading}>
- <Spin />
- <div className={localStyles.loadingText}>{t('shareModal.loadingPdf')}</div>
- </div>
- }
- onLoadSuccess={onDocumentLoadSuccess}
- >
- <Page
- pageNumber={pageNumber}
- renderAnnotationLayer={false}
- renderTextLayer={false}
- width={isMobile ? 300 : 400}
- />
- </Document>
- </div>
+ <Page
+ pageNumber={pageNumber}
+ renderAnnotationLayer={false}
+ renderTextLayer={false}
+ width={isMobile ? 300 : 400}
+ />
+ </Document>
+ </div>
- {/* Footer navigation */}
- {pdfData && numPages > 1 && (
- <div className={localStyles.footerNavigation}>
- <Flexbox horizontal align="center" gap={8} justify="center">
- <Button
- disabled={pageNumber <= 1}
- icon={<ChevronLeft size={16} />}
- size="small"
- type="text"
- onClick={goToPrevPage}
- />
- <Flexbox horizontal align="center" gap={4}>
- <Input
- className={localStyles.pageInput}
- max={numPages}
- min={1}
- size="small"
- type="number"
- value={pageNumber}
- onChange={(e) => {
- const value = parseInt(e.target.value);
- if (!isNaN(value)) goToPage(value);
- }}
- />
- <span className={localStyles.pageNumberText}>/ {numPages}</span>
- </Flexbox>
- <Button
- disabled={pageNumber >= numPages}
- icon={<ChevronRight size={16} />}
+ {pdfData && numPages > 1 && (
+ <div className={localStyles.footerNavigation}>
+ <Flexbox horizontal align="center" gap={8} justify="center">
+ <Button
+ disabled={pageNumber <= 1}
+ icon={<ChevronLeft size={16} />}
+ size="small"
+ type="text"
+ onClick={goToPrevPage}
+ />
+ <Flexbox horizontal align="center" gap={4}>
+ <Input
+ className={localStyles.pageInput}
+ max={numPages}
+ min={1}
size="small"
- type="text"
- onClick={goToNextPage}
+ type="number"
+ value={pageNumber}
+ onChange={(e) => {
+ const value = parseInt(e.target.value);
+ if (!isNaN(value)) goToPage(value);
+ }}
/>
+ <span className={localStyles.pageNumberText}>/ {numPages}</span>
</Flexbox>
- </div>
- )}
- </div>
-
- {/* Fullscreen modal */}
- <Modal
- centered
- footer={null}
- open={fullscreenOpen}
- width="95vw"
- styles={{
- body: { padding: 0 },
- }}
- onCancel={() => setFullscreenOpen(false)}
- >
- <div className={localStyles.fullscreenModal}>
- <div className={localStyles.fullscreenContent}>
- <Document file={pdfDataUri} onLoadSuccess={onDocumentLoadSuccess}>
- <Page
- pageNumber={fullscreenPageNumber}
- renderAnnotationLayer={false}
- renderTextLayer={false}
- width={Math.min(window.innerWidth * 0.8, 1000)}
- />
- </Document>
- </div>
-
- {/* Navigation in fullscreen mode */}
- {numPages > 1 && (
- <div className={localStyles.fullscreenNavigation}>
- <Flexbox horizontal align="center" gap={12}>
- <Button
- className={localStyles.fullscreenButton}
- disabled={fullscreenPageNumber <= 1}
- icon={<ChevronLeft size={16} />}
- size="small"
- type="text"
- onClick={goToFullscreenPrevPage}
- />
- <Flexbox horizontal align="center" gap={8}>
- <Input
- className={localStyles.fullscreenPageInput}
- max={numPages}
- min={1}
- size="small"
- type="number"
- value={fullscreenPageNumber}
- onChange={(e) => {
- const value = parseInt(e.target.value);
- if (!isNaN(value)) goToFullscreenPage(value);
- }}
- />
- <span className={localStyles.fullscreenPageText}>/ {numPages}</span>
- </Flexbox>
- <Button
- className={localStyles.fullscreenButton}
- disabled={fullscreenPageNumber >= numPages}
- icon={<ChevronRight size={16} />}
- size="small"
- type="text"
- onClick={goToFullscreenNextPage}
- />
- </Flexbox>
- </div>
- )}
+ <Button
+ disabled={pageNumber >= numPages}
+ icon={<ChevronRight size={16} />}
+ size="small"
+ type="text"
+ onClick={goToNextPage}
+ />
+ </Flexbox>
</div>
- </Modal>
- </>
+ )}
+ </div>
);
});
diff --git a/src/features/SkillStore/SkillList/AddSkillButton.tsx b/src/features/SkillStore/SkillList/AddSkillButton.tsx
index 76766dbf5e5..f958d407d9e 100644
--- a/src/features/SkillStore/SkillList/AddSkillButton.tsx
+++ b/src/features/SkillStore/SkillList/AddSkillButton.tsx
@@ -7,9 +7,9 @@ import { useTranslation } from 'react-i18next';
import { CustomConnectorModal } from '@/features/Connectors';
import { usePermission } from '@/hooks/usePermission';
-import ImportFromGithubModal from './ImportFromGithubModal';
-import ImportFromUrlModal from './ImportFromUrlModal';
-import UploadSkillModal from './UploadSkillModal';
+import { openImportFromGithubModal } from './ImportFromGithubModal';
+import { openImportFromUrlModal } from './ImportFromUrlModal';
+import { openUploadSkillModal } from './UploadSkillModal';
const MenuLabel = ({ desc, title }: { desc: string; title: ReactNode }) => (
<Flexbox gap={2}>
@@ -23,9 +23,6 @@ const MenuLabel = ({ desc, title }: { desc: string; title: ReactNode }) => (
const AddSkillButton = () => {
const { t } = useTranslation('setting');
const [showMcpModal, setMcpModal] = useState(false);
- const [showUrlModal, setUrlModal] = useState(false);
- const [showGithubModal, setGithubModal] = useState(false);
- const [showUploadModal, setUploadModal] = useState(false);
const { allowed: canCreate } = usePermission('create_content');
const { allowed: canEdit } = usePermission('edit_own_content');
@@ -36,9 +33,6 @@ const AddSkillButton = () => {
}}
>
<CustomConnectorModal open={showMcpModal} onClose={() => setMcpModal(false)} />
- <ImportFromUrlModal open={showUrlModal} onOpenChange={setUrlModal} />
- <ImportFromGithubModal open={showGithubModal} onOpenChange={setGithubModal} />
- <UploadSkillModal open={showUploadModal} onOpenChange={setUploadModal} />
<DropdownMenu
nativeButton={false}
placement="bottomRight"
@@ -50,7 +44,7 @@ const AddSkillButton = () => {
label: <MenuLabel desc={t('tab.importFromUrl.desc')} title={t('tab.importFromUrl')} />,
onClick: () => {
if (!canCreate) return;
- setUrlModal(true);
+ openImportFromUrlModal();
},
},
{
@@ -62,7 +56,7 @@ const AddSkillButton = () => {
),
onClick: () => {
if (!canCreate) return;
- setGithubModal(true);
+ openImportFromGithubModal();
},
},
{
@@ -72,7 +66,7 @@ const AddSkillButton = () => {
label: <MenuLabel desc={t('tab.uploadZip.desc')} title={t('tab.uploadZip')} />,
onClick: () => {
if (!canCreate) return;
- setUploadModal(true);
+ openUploadSkillModal();
},
},
{ type: 'divider' as const },
diff --git a/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx b/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx
index 747d5bda6ce..01d241e9169 100644
--- a/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx
+++ b/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx
@@ -1,8 +1,9 @@
'use client';
import { Alert, Flexbox, Icon, Input } from '@lobehub/ui';
+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';
import { GithubIcon } from '@lobehub/ui/icons';
-import { App, Button, Modal, Typography } from 'antd';
+import { App, Typography } from 'antd';
import { ArrowLeftRight, Sparkles } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,13 +11,9 @@ import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
-interface ImportFromGithubModalProps {
- onOpenChange: (open: boolean) => void;
- open: boolean;
-}
-
-const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenChange }) => {
+const ImportFromGithubContent = memo(() => {
const { t } = useTranslation(['setting', 'common']);
+ const { close } = useModalContext();
const { message } = App.useApp();
const importAgentSkillFromGitHub = useToolStore((s) => s.importAgentSkillFromGitHub);
const [loading, setLoading] = useState(false);
@@ -24,12 +21,6 @@ const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenCh
const [url, setUrl] = useState('');
const { allowed: canCreate } = usePermission('create_content');
- const handleClose = () => {
- onOpenChange(false);
- setError(null);
- setUrl('');
- };
-
const handleImport = async () => {
const trimmed = url.trim();
if (!canCreate || !trimmed) return;
@@ -40,7 +31,7 @@ const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenCh
try {
await importAgentSkillFromGitHub({ gitUrl: trimmed });
message.success(t('agentSkillModal.importSuccess'));
- handleClose();
+ close();
} catch (err: any) {
setError(err?.message || String(err));
} finally {
@@ -49,7 +40,7 @@ const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenCh
};
return (
- <Modal destroyOnClose footer={null} open={open} title={null} width={480} onCancel={handleClose}>
+ <Flexbox gap={16}>
<Flexbox align="center" gap={16} padding={'16px 0'}>
<Flexbox horizontal align="center" gap={8}>
<Icon icon={GithubIcon} size={28} />
@@ -71,33 +62,36 @@ const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenCh
</Flexbox>
</Flexbox>
- <Flexbox gap={16}>
- {error && (
- <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />
- )}
+ {error && <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />}
- <Flexbox gap={8}>
- <Typography.Text strong>URL</Typography.Text>
- <Input
- disabled={!canCreate}
- placeholder={t('agentSkillModal.github.urlPlaceholder')}
- value={url}
- onPressEnter={handleImport}
- onChange={(e) => {
- setUrl(e.target.value);
- if (error) setError(null);
- }}
- />
- </Flexbox>
-
- <Button block disabled={!canCreate} loading={loading} type="primary" onClick={handleImport}>
- {t('common:import')}
- </Button>
+ <Flexbox gap={8}>
+ <Typography.Text strong>URL</Typography.Text>
+ <Input
+ disabled={!canCreate}
+ placeholder={t('agentSkillModal.github.urlPlaceholder')}
+ value={url}
+ onPressEnter={handleImport}
+ onChange={(e) => {
+ setUrl(e.target.value);
+ if (error) setError(null);
+ }}
+ />
</Flexbox>
- </Modal>
+
+ <Button block disabled={!canCreate} loading={loading} type="primary" onClick={handleImport}>
+ {t('common:import')}
+ </Button>
+ </Flexbox>
);
});
-ImportFromGithubModal.displayName = 'ImportFromGithubModal';
+ImportFromGithubContent.displayName = 'ImportFromGithubContent';
-export default ImportFromGithubModal;
+export const openImportFromGithubModal = (): ModalInstance =>
+ createModal({
+ content: <ImportFromGithubContent />,
+ footer: null,
+ maskClosable: true,
+ styles: { header: { display: 'none' } },
+ width: 480,
+ });
diff --git a/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx b/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx
index 1cdbc4cbb72..af536db7a3c 100644
--- a/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx
+++ b/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx
@@ -1,7 +1,8 @@
'use client';
import { Alert, Flexbox, Icon, Input } from '@lobehub/ui';
-import { App, Button, Modal, Typography } from 'antd';
+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';
+import { App, Typography } from 'antd';
import { ArrowLeftRight, Link, Sparkles } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,13 +10,9 @@ import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
import { useToolStore } from '@/store/tool';
-interface ImportFromUrlModalProps {
- onOpenChange: (open: boolean) => void;
- open: boolean;
-}
-
-const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }) => {
+const ImportFromUrlContent = memo(() => {
const { t } = useTranslation(['setting', 'common']);
+ const { close } = useModalContext();
const { message } = App.useApp();
const importAgentSkillFromUrl = useToolStore((s) => s.importAgentSkillFromUrl);
const [loading, setLoading] = useState(false);
@@ -23,12 +20,6 @@ const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }
const [url, setUrl] = useState('');
const { allowed: canCreate } = usePermission('create_content');
- const handleClose = () => {
- onOpenChange(false);
- setError(null);
- setUrl('');
- };
-
const handleImport = async () => {
const trimmed = url.trim();
if (!canCreate || !trimmed) return;
@@ -39,7 +30,7 @@ const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }
try {
await importAgentSkillFromUrl({ url: trimmed });
message.success(t('agentSkillModal.importSuccess'));
- handleClose();
+ close();
} catch (err: any) {
setError(err?.message || String(err));
} finally {
@@ -48,7 +39,7 @@ const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }
};
return (
- <Modal destroyOnClose footer={null} open={open} title={null} width={480} onCancel={handleClose}>
+ <Flexbox gap={16}>
<Flexbox align="center" gap={16} padding={'16px 0'}>
<Flexbox horizontal align="center" gap={8}>
<Icon icon={Link} size={28} />
@@ -68,33 +59,36 @@ const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }
</Flexbox>
</Flexbox>
- <Flexbox gap={16}>
- {error && (
- <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />
- )}
+ {error && <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />}
- <Flexbox gap={8}>
- <Typography.Text strong>URL</Typography.Text>
- <Input
- disabled={!canCreate}
- placeholder={t('agentSkillModal.url.urlPlaceholder')}
- value={url}
- onPressEnter={handleImport}
- onChange={(e) => {
- setUrl(e.target.value);
- if (error) setError(null);
- }}
- />
- </Flexbox>
-
- <Button block disabled={!canCreate} loading={loading} type="primary" onClick={handleImport}>
- {t('common:import')}
- </Button>
+ <Flexbox gap={8}>
+ <Typography.Text strong>URL</Typography.Text>
+ <Input
+ disabled={!canCreate}
+ placeholder={t('agentSkillModal.url.urlPlaceholder')}
+ value={url}
+ onPressEnter={handleImport}
+ onChange={(e) => {
+ setUrl(e.target.value);
+ if (error) setError(null);
+ }}
+ />
</Flexbox>
- </Modal>
+
+ <Button block disabled={!canCreate} loading={loading} type="primary" onClick={handleImport}>
+ {t('common:import')}
+ </Button>
+ </Flexbox>
);
});
-ImportFromUrlModal.displayName = 'ImportFromUrlModal';
+ImportFromUrlContent.displayName = 'ImportFromUrlContent';
-export default ImportFromUrlModal;
+export const openImportFromUrlModal = (): ModalInstance =>
+ createModal({
+ content: <ImportFromUrlContent />,
+ footer: null,
+ maskClosable: true,
+ styles: { header: { display: 'none' } },
+ width: 480,
+ });
diff --git a/src/features/SkillStore/SkillList/UploadSkillModal.tsx b/src/features/SkillStore/SkillList/UploadSkillModal.tsx
index d60a692d602..1aab0e30f3b 100644
--- a/src/features/SkillStore/SkillList/UploadSkillModal.tsx
+++ b/src/features/SkillStore/SkillList/UploadSkillModal.tsx
@@ -2,10 +2,11 @@
import { LoadingOutlined } from '@ant-design/icons';
import { Alert, Flexbox, Icon } from '@lobehub/ui';
-import { App, Modal, Spin, Typography, Upload } from 'antd';
+import { createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';
+import { App, Spin, Typography, Upload } from 'antd';
import { sha256 } from 'js-sha256';
import { ArrowLeftRight, InboxIcon, Sparkles, Upload as UploadIcon } from 'lucide-react';
-import { memo, useState } from 'react';
+import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
@@ -13,23 +14,18 @@ import { lambdaClient } from '@/libs/trpc/client/lambda';
import { uploadService } from '@/services/upload';
import { useToolStore } from '@/store/tool';
-interface UploadSkillModalProps {
- onOpenChange: (open: boolean) => void;
- open: boolean;
-}
-
-const UploadSkillModal = memo<UploadSkillModalProps>(({ open, onOpenChange }) => {
+const UploadSkillContent = memo(() => {
const { t } = useTranslation(['setting', 'common']);
+ const { close, setCanDismissByClickOutside } = useModalContext();
const { message } = App.useApp();
const importAgentSkillFromZip = useToolStore((s) => s.importAgentSkillFromZip);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const { allowed: canCreate } = usePermission('create_content');
- const handleClose = () => {
- onOpenChange(false);
- setError(null);
- };
+ useEffect(() => {
+ setCanDismissByClickOutside(!loading);
+ }, [loading, setCanDismissByClickOutside]);
const handleUploadFile = async (file: File) => {
if (!canCreate) return;
@@ -54,7 +50,7 @@ const UploadSkillModal = memo<UploadSkillModalProps>(({ open, onOpenChange }) =>
await importAgentSkillFromZip({ zipFileId: result.id });
message.success(t('agentSkillModal.importSuccess'));
- handleClose();
+ close();
} catch (err: any) {
setError(err?.message || String(err));
} finally {
@@ -63,16 +59,7 @@ const UploadSkillModal = memo<UploadSkillModalProps>(({ open, onOpenChange }) =>
};
return (
- <Modal
- destroyOnClose
- closable={!loading}
- footer={null}
- maskClosable={!loading}
- open={open}
- title={null}
- width={480}
- onCancel={handleClose}
- >
+ <Flexbox gap={16}>
<Flexbox align="center" gap={16} padding={'16px 0'}>
<Flexbox horizontal align="center" gap={8}>
<Icon icon={UploadIcon} size={28} />
@@ -92,64 +79,67 @@ const UploadSkillModal = memo<UploadSkillModalProps>(({ open, onOpenChange }) =>
</Flexbox>
</Flexbox>
- <Flexbox gap={16}>
- {error && (
- <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />
- )}
-
- <Upload.Dragger
- accept=".zip,.skill"
- disabled={loading || !canCreate}
- showUploadList={false}
- beforeUpload={(file) => {
- if (!canCreate) return false;
- handleUploadFile(file);
- return false;
- }}
- >
- <Flexbox align="center" gap={8} padding={24}>
- {loading ? (
- <>
- <Spin indicator={<LoadingOutlined spin />} />
- <Typography.Text type="secondary">
- {t('agentSkillModal.upload.uploading')}
- </Typography.Text>
- </>
- ) : (
- <>
- <Icon
- icon={InboxIcon}
- size={48}
- style={{ color: 'var(--ant-color-text-quaternary)' }}
- />
- <Typography.Text type="secondary">
- {t('agentSkillModal.upload.dragText')}
- </Typography.Text>
- </>
- )}
- </Flexbox>
- </Upload.Dragger>
-
- <Flexbox gap={8}>
- <Typography.Text strong>{t('agentSkillModal.upload.requirements')}</Typography.Text>
- <ul style={{ margin: 0, paddingLeft: 20 }}>
- <li>
+ {error && <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />}
+
+ <Upload.Dragger
+ accept=".zip,.skill"
+ disabled={loading || !canCreate}
+ showUploadList={false}
+ beforeUpload={(file) => {
+ if (!canCreate) return false;
+ handleUploadFile(file);
+ return false;
+ }}
+ >
+ <Flexbox align="center" gap={8} padding={24}>
+ {loading ? (
+ <>
+ <Spin indicator={<LoadingOutlined spin />} />
<Typography.Text type="secondary">
- {t('agentSkillModal.upload.requirementZip')}
+ {t('agentSkillModal.upload.uploading')}
</Typography.Text>
- </li>
- <li>
+ </>
+ ) : (
+ <>
+ <Icon
+ icon={InboxIcon}
+ size={48}
+ style={{ color: 'var(--ant-color-text-quaternary)' }}
+ />
<Typography.Text type="secondary">
- {t('agentSkillModal.upload.requirementSkillMd')}
+ {t('agentSkillModal.upload.dragText')}
</Typography.Text>
- </li>
- </ul>
+ </>
+ )}
</Flexbox>
+ </Upload.Dragger>
+
+ <Flexbox gap={8}>
+ <Typography.Text strong>{t('agentSkillModal.upload.requirements')}</Typography.Text>
+ <ul style={{ margin: 0, paddingLeft: 20 }}>
+ <li>
+ <Typography.Text type="secondary">
+ {t('agentSkillModal.upload.requirementZip')}
+ </Typography.Text>
+ </li>
+ <li>
+ <Typography.Text type="secondary">
+ {t('agentSkillModal.upload.requirementSkillMd')}
+ </Typography.Text>
+ </li>
+ </ul>
</Flexbox>
- </Modal>
+ </Flexbox>
);
});
-UploadSkillModal.displayName = 'UploadSkillModal';
+UploadSkillContent.displayName = 'UploadSkillContent';
-export default UploadSkillModal;
+export const openUploadSkillModal = (): ModalInstance =>
+ createModal({
+ content: <UploadSkillContent />,
+ footer: null,
+ maskClosable: true,
+ styles: { header: { display: 'none' } },
+ width: 480,
+ });
diff --git a/src/hooks/useInterceptingRoutes.test.ts b/src/hooks/useInterceptingRoutes.test.ts
index f978dd0c531..0c04d4a5b41 100644
--- a/src/hooks/useInterceptingRoutes.test.ts
+++ b/src/hooks/useInterceptingRoutes.test.ts
@@ -2,6 +2,7 @@ import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { openAgentSettingsModal } from '@/routes/(main)/agent/profile/features/AgentSettings';
import { useAgentStore } from '@/store/agent';
import { ChatSettingsTabs } from '@/store/global/initialState';
@@ -22,10 +23,13 @@ vi.mock('@/store/global', () => ({
setState: vi.fn(),
},
}));
+vi.mock('@/routes/(main)/agent/profile/features/AgentSettings', () => ({
+ openAgentSettingsModal: vi.fn(),
+}));
describe('useOpenChatSettings', () => {
beforeEach(() => {
vi.clearAllMocks();
- useAgentStore.setState({ showAgentSetting: false, activeAgentId: undefined });
+ useAgentStore.setState({ activeAgentId: undefined });
});
it('navigates to mobile chat settings with session info', () => {
@@ -52,7 +56,7 @@ describe('useOpenChatSettings', () => {
result.current();
});
- expect(useAgentStore.getState().showAgentSetting).toBeTruthy();
+ expect(openAgentSettingsModal).toHaveBeenCalled();
expect(mockNavigate).not.toHaveBeenCalled();
});
});
diff --git a/src/hooks/useInterceptingRoutes.ts b/src/hooks/useInterceptingRoutes.ts
index 99b2ef23c26..e102d1b1f43 100644
--- a/src/hooks/useInterceptingRoutes.ts
+++ b/src/hooks/useInterceptingRoutes.ts
@@ -3,6 +3,7 @@ import { useLocation } from 'react-router';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { openAgentSettingsModal } from '@/routes/(main)/agent/profile/features/AgentSettings';
import { useAgentStore } from '@/store/agent';
import { ChatSettingsTabs } from '@/store/global/initialState';
@@ -18,7 +19,7 @@ export const useOpenChatSettings = (tab: ChatSettingsTabs = ChatSettingsTabs.Ope
return () => navigate(`/chat/settings?session=${activeAgentId}&showMobileWorkspace=true`);
return () => {
- useAgentStore.setState({ showAgentSetting: true });
+ openAgentSettingsModal();
};
}, [activeAgentId, navigate, location.pathname, tab, isMobile]);
};
diff --git a/src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx b/src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx
index e2440d842b3..04ddee1d25b 100644
--- a/src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx
+++ b/src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx
@@ -1,15 +1,147 @@
'use client';
import { InfoCircleOutlined } from '@ant-design/icons';
-import { Alert, Button, type ButtonProps, Modal, QRCode, Spin, Typography } from 'antd';
+import { createModal, useModalContext } from '@lobehub/ui/base-ui';
+import { Alert, Button, type ButtonProps, QRCode, Spin, Typography } from 'antd';
+import { t as i18nT } from 'i18next';
import { QrCode, RefreshCw } from 'lucide-react';
-import { memo, useCallback, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { agentBotProviderService } from '@/services/agentBotProvider';
const QR_POLL_INTERVAL_MS = 2000;
+interface QrCodeContentProps {
+ onAuthenticated: (credentials: { botId: string; botToken: string; userId: string }) => void;
+}
+
+const QrCodeContent = memo<QrCodeContentProps>(({ onAuthenticated }) => {
+ const { t } = useTranslation('agent');
+ const { close } = useModalContext();
+ const [qrImgUrl, setQrImgUrl] = useState<string>();
+ const [status, setStatus] = useState<string>('');
+ const [error, setError] = useState<string>();
+ const [loading, setLoading] = useState(false);
+ const pollingRef = useRef(false);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const stopPolling = useCallback(() => {
+ pollingRef.current = false;
+ if (timerRef.current) {
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ }, []);
+
+ const startQrFlow = useCallback(async () => {
+ setLoading(true);
+ setError(undefined);
+ setStatus('');
+ setQrImgUrl(undefined);
+ stopPolling();
+
+ try {
+ const qr = await agentBotProviderService.wechatGetQrCode();
+ setQrImgUrl(qr.qrcode_img_content);
+ setStatus('wait');
+ setLoading(false);
+
+ pollingRef.current = true;
+ const poll = async () => {
+ if (!pollingRef.current) return;
+
+ try {
+ const res = await agentBotProviderService.wechatPollQrStatus(qr.qrcode);
+ if (!pollingRef.current) return;
+
+ setStatus(res.status);
+
+ if (res.status === 'confirmed' && res.bot_token) {
+ stopPolling();
+ onAuthenticated({
+ botId: res.ilink_bot_id || '',
+ botToken: res.bot_token,
+ userId: res.ilink_user_id || '',
+ });
+ close();
+ return;
+ }
+
+ if (res.status === 'expired') {
+ stopPolling();
+ setError(t('channel.wechatQrExpired'));
+ return;
+ }
+
+ timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);
+ } catch {
+ if (pollingRef.current) {
+ timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);
+ }
+ }
+ };
+
+ timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);
+ } catch (err: any) {
+ setError(err?.message || 'Failed to get QR code');
+ setLoading(false);
+ }
+ }, [close, onAuthenticated, stopPolling, t]);
+
+ useEffect(() => {
+ startQrFlow();
+ return () => stopPolling();
+ }, [startQrFlow, stopPolling]);
+
+ const statusText =
+ status === 'wait'
+ ? t('channel.wechatQrWait')
+ : status === 'scaned'
+ ? t('channel.wechatQrScaned')
+ : '';
+
+ return (
+ <div
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 16,
+ padding: '16px 0',
+ }}
+ >
+ {loading && <Spin size="large" />}
+
+ {qrImgUrl && !error && <QRCode size={240} value={qrImgUrl} />}
+
+ {statusText && !error && <Typography.Text type="secondary">{statusText}</Typography.Text>}
+
+ {error && (
+ <>
+ <Alert showIcon message={error} type="warning" />
+ <Button icon={<RefreshCw size={14} />} onClick={startQrFlow}>
+ {t('channel.wechatQrRefresh')}
+ </Button>
+ </>
+ )}
+ </div>
+ );
+});
+
+QrCodeContent.displayName = 'QrCodeContent';
+
+const openQrCodeAuthModal = (
+ onAuthenticated: (credentials: { botId: string; botToken: string; userId: string }) => void,
+) =>
+ createModal({
+ content: <QrCodeContent onAuthenticated={onAuthenticated} />,
+ footer: null,
+ maskClosable: true,
+ title: i18nT('channel.wechatScanTitle', { ns: 'agent' }),
+ width: 460,
+ });
+
interface QrCodeAuthProps {
buttonLabel?: string;
buttonType?: ButtonProps['type'];
@@ -21,151 +153,29 @@ interface QrCodeAuthProps {
const QrCodeAuth = memo<QrCodeAuthProps>(
({ buttonLabel, buttonType = 'primary', disabled, onAuthenticated, showTips = true }) => {
const { t } = useTranslation('agent');
- const [open, setOpen] = useState(false);
- const [qrImgUrl, setQrImgUrl] = useState<string>();
- const [status, setStatus] = useState<string>('');
- const [error, setError] = useState<string>();
- const [loading, setLoading] = useState(false);
- const pollingRef = useRef(false);
- const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
-
- const stopPolling = useCallback(() => {
- pollingRef.current = false;
- if (timerRef.current) {
- clearTimeout(timerRef.current);
- timerRef.current = null;
- }
- }, []);
-
- const startQrFlow = useCallback(async () => {
- setLoading(true);
- setError(undefined);
- setStatus('');
- setQrImgUrl(undefined);
- stopPolling();
-
- try {
- const qr = await agentBotProviderService.wechatGetQrCode();
- setQrImgUrl(qr.qrcode_img_content);
- setStatus('wait');
- setLoading(false);
-
- // Start polling
- pollingRef.current = true;
- const poll = async () => {
- if (!pollingRef.current) return;
-
- try {
- const res = await agentBotProviderService.wechatPollQrStatus(qr.qrcode);
- if (!pollingRef.current) return;
-
- setStatus(res.status);
-
- if (res.status === 'confirmed' && res.bot_token) {
- stopPolling();
- onAuthenticated({
- botId: res.ilink_bot_id || '',
- botToken: res.bot_token,
- userId: res.ilink_user_id || '',
- });
- setOpen(false);
- return;
- }
-
- if (res.status === 'expired') {
- stopPolling();
- setError(t('channel.wechatQrExpired'));
- return;
- }
- timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);
- } catch {
- if (pollingRef.current) {
- timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);
- }
- }
- };
-
- timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);
- } catch (err: any) {
- setError(err?.message || 'Failed to get QR code');
- setLoading(false);
- }
- }, [onAuthenticated, stopPolling, t]);
-
- const handleOpen = useCallback(() => {
+ const handleOpen = () => {
if (disabled) return;
- setOpen(true);
- startQrFlow();
- }, [disabled, startQrFlow]);
-
- const handleClose = useCallback(() => {
- stopPolling();
- setOpen(false);
- }, [stopPolling]);
-
- const statusText =
- status === 'wait'
- ? t('channel.wechatQrWait')
- : status === 'scaned'
- ? t('channel.wechatQrScaned')
- : '';
+ openQrCodeAuthModal(onAuthenticated);
+ };
return (
- <>
- <div style={{ alignItems: 'center', display: 'flex', flexDirection: 'column', gap: 12 }}>
- <Button
- disabled={disabled}
- icon={<QrCode size={16} />}
- type={buttonType}
- onClick={handleOpen}
- >
- {buttonLabel || t('channel.wechatScanToConnect')}
- </Button>
- {showTips && (
- <Typography.Text style={{ maxWidth: 480, textAlign: 'center' }} type="secondary">
- <InfoCircleOutlined style={{ marginInlineEnd: 4 }} />
- {t('channel.wechatTips')}
- </Typography.Text>
- )}
- </div>
-
- <Modal
- centered
- footer={null}
- open={open}
- title={t('channel.wechatScanTitle')}
- width={460}
- onCancel={handleClose}
+ <div style={{ alignItems: 'center', display: 'flex', flexDirection: 'column', gap: 12 }}>
+ <Button
+ disabled={disabled}
+ icon={<QrCode size={16} />}
+ type={buttonType}
+ onClick={handleOpen}
>
- <div
- style={{
- alignItems: 'center',
- display: 'flex',
- flexDirection: 'column',
- gap: 16,
- padding: '16px 0',
- }}
- >
- {loading && <Spin size="large" />}
-
- {qrImgUrl && !error && <QRCode size={240} value={qrImgUrl} />}
-
- {statusText && !error && (
- <Typography.Text type="secondary">{statusText}</Typography.Text>
- )}
-
- {error && (
- <>
- <Alert showIcon message={error} type="warning" />
- <Button icon={<RefreshCw size={14} />} onClick={startQrFlow}>
- {t('channel.wechatQrRefresh')}
- </Button>
- </>
- )}
- </div>
- </Modal>
- </>
+ {buttonLabel || t('channel.wechatScanToConnect')}
+ </Button>
+ {showTips && (
+ <Typography.Text style={{ maxWidth: 480, textAlign: 'center' }} type="secondary">
+ <InfoCircleOutlined style={{ marginInlineEnd: 4 }} />
+ {t('channel.wechatTips')}
+ </Typography.Text>
+ )}
+ </div>
);
},
);
diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx
index b9d49465805..34a356b6182 100644
--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx
+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx
@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react';
-import type { PropsWithChildren, ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ChatSettingsTabs } from '@/store/global/initialState';
@@ -22,42 +22,31 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock('@lobehub/ui', () => ({
- Avatar: () => <div data-testid="avatar" />,
- Block: ({ children }: PropsWithChildren) => <div>{children}</div>,
- Flexbox: ({ children }: PropsWithChildren) => <div>{children}</div>,
- Icon: () => <span />,
- Text: ({ children }: PropsWithChildren) => <span>{children}</span>,
-}));
-
-vi.mock('@/components/Menu', () => ({
- default: ({
- items = [],
- onClick,
- selectedKeys = [],
+vi.mock('@/features/AgentSetting', () => ({
+ AgentSettings: ({ tab }: { tab: ChatSettingsTabs }) => (
+ <div data-tab={tab} data-testid="agent-settings-content" />
+ ),
+ SettingsModalLayout: ({
+ activeTab,
+ tabs = [],
+ children,
}: {
- items?: { key?: string; label?: ReactNode }[];
- onClick?: ({ key }: { key: string }) => void;
- selectedKeys?: string[];
+ activeTab?: string;
+ children?: ReactNode;
+ tabs?: { key: string }[];
}) => (
- <div data-selected={selectedKeys.join(',')} data-testid="agent-settings-menu">
- {items.map((item) => (
- <button
- key={item.key}
- type="button"
- onClick={() => item.key && onClick?.({ key: item.key })}
- >
- {item.label}
- </button>
- ))}
+ <div
+ data-active={activeTab}
+ data-tabs={tabs.map((tab) => tab.key).join(',')}
+ data-testid="layout"
+ >
+ {children}
</div>
),
}));
-vi.mock('@/features/AgentSetting', () => ({
- AgentSettings: ({ tab }: { tab: ChatSettingsTabs }) => (
- <div data-tab={tab} data-testid="agent-settings-content" />
- ),
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: true }),
}));
vi.mock('@/store/agent', () => {
@@ -84,13 +73,6 @@ vi.mock('@/store/serverConfig', () => ({
selector(mocks.serverState),
}));
-vi.mock('antd-style', () => ({
- useTheme: () => ({
- colorBgLayout: '#fff',
- colorBorderSecondary: '#eee',
- }),
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
@@ -103,18 +85,38 @@ describe('AgentSettings Content', () => {
mocks.serverState.featureFlags.enableAgentSelfIteration = true;
});
- it('should select self iteration when inbox hides opening settings', () => {
+ it('falls back to self iteration when inbox hides opening', () => {
render(<Content />);
- expect(screen.queryByRole('button', { name: 'agentTab.opening' })).not.toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'agentTab.selfIteration' })).toBeInTheDocument();
- expect(screen.getByTestId('agent-settings-menu')).toHaveAttribute(
- 'data-selected',
- ChatSettingsTabs.SelfIteration,
- );
+ const layout = screen.getByTestId('layout');
+ expect(layout).toHaveAttribute('data-active', ChatSettingsTabs.SelfIteration);
+ expect(layout).toHaveAttribute('data-tabs', ChatSettingsTabs.SelfIteration);
expect(screen.getByTestId('agent-settings-content')).toHaveAttribute(
'data-tab',
ChatSettingsTabs.SelfIteration,
);
});
+
+ it('exposes both tabs when not inbox and feature is on', () => {
+ mocks.agentState.isInbox = false;
+
+ render(<Content />);
+
+ const layout = screen.getByTestId('layout');
+ expect(layout).toHaveAttribute('data-active', ChatSettingsTabs.Opening);
+ expect(layout).toHaveAttribute(
+ 'data-tabs',
+ `${ChatSettingsTabs.Opening},${ChatSettingsTabs.SelfIteration}`,
+ );
+ });
+
+ it('exposes only opening when feature flag is off', () => {
+ mocks.agentState.isInbox = false;
+ mocks.serverState.featureFlags.enableAgentSelfIteration = false;
+
+ render(<Content />);
+
+ const layout = screen.getByTestId('layout');
+ expect(layout).toHaveAttribute('data-tabs', ChatSettingsTabs.Opening);
+ });
});
diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
index 9bb4ac63357..89110efdb1b 100644
--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
@@ -1,26 +1,33 @@
'use client';
-import { Avatar, Block, Flexbox, Icon, Text } from '@lobehub/ui';
-import { type ItemType } from 'antd/es/menu/interface';
-import { useTheme } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { ActivityIcon, MessageSquareHeartIcon } from 'lucide-react';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { shallow } from 'zustand/shallow';
-import Menu from '@/components/Menu';
import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
-import { AgentSettings as Settings } from '@/features/AgentSetting';
+import {
+ AgentSettings as Settings,
+ SettingsModalLayout,
+ type SettingsModalTabItem,
+} from '@/features/AgentSetting';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
+const TAB_META = {
+ [ChatSettingsTabs.Opening]: { icon: MessageSquareHeartIcon, labelKey: 'agentTab.opening' },
+ [ChatSettingsTabs.SelfIteration]: {
+ icon: ActivityIcon,
+ labelKey: 'agentTab.selfIteration',
+ },
+} as const;
+
const Content = memo(() => {
const { t } = useTranslation('setting');
- const theme = useTheme();
const { allowed: canEdit } = usePermission('edit_own_content');
const [agentId, isInbox] = useAgentStore(
(s) => [s.activeAgentId, builtinAgentSelectors.isInboxAgent(s)],
@@ -58,104 +65,39 @@ const Content = memo(() => {
await useAgentStore.getState().optimisticUpdateAgentMeta(agentId, meta);
};
- const menuItems: ItemType[] = useMemo(
+ const tabs: SettingsModalTabItem[] = useMemo(
() =>
- availableTabs
- .map((tab) => {
- switch (tab) {
- case ChatSettingsTabs.Opening: {
- return {
- icon: <Icon icon={MessageSquareHeartIcon} />,
- key: ChatSettingsTabs.Opening,
- label: t('agentTab.opening'),
- };
- }
- case ChatSettingsTabs.SelfIteration: {
- return {
- icon: <Icon icon={ActivityIcon} />,
- key: ChatSettingsTabs.SelfIteration,
- label: t('agentTab.selfIteration'),
- };
- }
- default: {
- return null;
- }
- }
- })
- .filter(Boolean) as ItemType[],
+ availableTabs.map((key) => {
+ const entry = TAB_META[key as keyof typeof TAB_META];
+ return { icon: entry.icon, key, label: t(entry.labelKey) };
+ }),
[availableTabs, t],
);
const displayTitle = isInbox ? 'Lobe AI' : meta.title || t('defaultSession', { ns: 'common' });
return (
- <Flexbox
- direction="horizontal"
- height="100%"
- style={{
- padding: 0,
- position: 'relative',
- }}
+ <SettingsModalLayout
+ activeTab={activeTab}
+ avatar={isInbox ? DEFAULT_INBOX_AVATAR : meta.avatar || DEFAULT_AVATAR}
+ background={meta.backgroundColor || undefined}
+ tabs={tabs}
+ title={displayTitle}
+ onTabChange={(key) => setTab(key as ChatSettingsTabs)}
>
- <Flexbox
- height={'100%'}
- paddingBlock={24}
- paddingInline={8}
- width={200}
- style={{
- background: theme.colorBgLayout,
- borderRight: `1px solid ${theme.colorBorderSecondary}`,
- }}
- >
- <Block
- horizontal
- align={'center'}
- gap={8}
- paddingBlock={'14px 16px'}
- paddingInline={4}
- variant={'borderless'}
- style={{
- overflow: 'hidden',
- }}
- >
- <Avatar
- avatar={isInbox ? DEFAULT_INBOX_AVATAR : meta.avatar || DEFAULT_AVATAR}
- background={meta.backgroundColor || undefined}
- shape={'square'}
- size={28}
- />
- <Text ellipsis weight={500}>
- {displayTitle}
- </Text>
- </Block>
- <Menu
- selectable
- items={menuItems}
- selectedKeys={activeTab ? [activeTab] : []}
- style={{ width: '100%' }}
- onClick={({ key }) => setTab(key as ChatSettingsTabs)}
+ {activeTab && (
+ <Settings
+ config={config}
+ disabled={!canEdit}
+ id={agentId}
+ loading={false}
+ meta={meta}
+ tab={activeTab}
+ onConfigChange={updateAgentConfig}
+ onMetaChange={updateAgentMeta}
/>
- </Flexbox>
- <Flexbox
- flex={1}
- paddingBlock={24}
- paddingInline={64}
- style={{ overflow: 'scroll', width: '100%' }}
- >
- {activeTab && (
- <Settings
- config={config}
- disabled={!canEdit}
- id={agentId}
- loading={false}
- meta={meta}
- tab={activeTab}
- onConfigChange={updateAgentConfig}
- onMetaChange={updateAgentMeta}
- />
- )}
- </Flexbox>
- </Flexbox>
+ )}
+ </SettingsModalLayout>
);
});
diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/index.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/index.tsx
index 53fe1aa75c4..cbcf413bce4 100644
--- a/src/routes/(main)/agent/profile/features/AgentSettings/index.tsx
+++ b/src/routes/(main)/agent/profile/features/AgentSettings/index.tsx
@@ -1,35 +1,22 @@
'use client';
-import { Modal } from '@lobehub/ui';
-import { memo } from 'react';
-
-import { useAgentStore } from '@/store/agent';
+import { createModal, type ModalInstance } from '@lobehub/ui/base-ui';
import Content from './Content';
-const AgentSettings = memo(() => {
- const showAgentSetting = useAgentStore((s) => s.showAgentSetting);
-
- return (
- <Modal
- centered
- footer={null}
- open={showAgentSetting}
- title={null}
- width={960}
- styles={{
- body: {
- height: '60vh',
- overflow: 'scroll',
- padding: 0,
- position: 'relative',
- },
- }}
- onCancel={() => useAgentStore.setState({ showAgentSetting: false })}
- >
- <Content />
- </Modal>
- );
-});
-
-export default AgentSettings;
+export const openAgentSettingsModal = (): ModalInstance =>
+ createModal({
+ content: <Content />,
+ footer: null,
+ maskClosable: true,
+ styles: {
+ content: {
+ height: '60vh',
+ overflow: 'scroll',
+ padding: 0,
+ position: 'relative',
+ },
+ header: { display: 'none' },
+ },
+ width: 960,
+ });
diff --git a/src/routes/(main)/agent/profile/features/Header/index.test.tsx b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
index 3de1db43bd0..96c2fd1d4de 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.test.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
@@ -1,4 +1,7 @@
+import type * as LobeChatConst from '@lobechat/const';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type * as Antd from 'antd';
+import type * as LucideReact from 'lucide-react';
import type { PropsWithChildren, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -35,7 +38,8 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock('@lobechat/const', () => ({
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<typeof LobeChatConst>()),
isDesktop: false,
}));
@@ -82,21 +86,30 @@ vi.mock('@lobehub/ui/base-ui', () => ({
confirmModal: vi.fn(),
}));
-vi.mock('antd', () => ({
- App: {
- useApp: () => ({
- modal: {
- confirm: vi.fn(),
- },
- }),
- },
- Modal: {
- confirm: vi.fn(),
- },
-}));
+vi.mock('antd', async (importOriginal) => {
+ const actual = await importOriginal<typeof Antd>();
+
+ return {
+ ...actual,
+ App: {
+ ...actual.App,
+ useApp: () => ({
+ modal: {
+ confirm: vi.fn(),
+ },
+ }),
+ },
+ Modal: {
+ ...actual.Modal,
+ confirm: vi.fn(),
+ },
+ };
+});
-vi.mock('lucide-react', () => ({
+vi.mock('lucide-react', async (importOriginal) => ({
+ ...(await importOriginal<typeof LucideReact>()),
BotMessageSquareIcon: () => null,
+ Circle: () => null,
Download: () => null,
MoreHorizontal: () => null,
Settings2Icon: () => null,
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index 792c718692d..6531ddaec6f 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -22,6 +22,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { useHomeStore } from '@/store/home';
import { sanitizeFileName } from '@/utils/sanitizeFileName';
+import { openAgentSettingsModal } from '../AgentSettings';
import { selectors as profileSelectors, useProfileStore } from '../store';
import AgentForkTag from './AgentForkTag';
import AgentStatusTag from './AgentStatusTag';
@@ -170,7 +171,7 @@ const Header = memo(() => {
icon: <Icon icon={Settings2Icon} />,
key: 'advanced-settings',
label: t('advancedSettings', { ns: 'setting' }),
- onClick: () => useAgentStore.setState({ showAgentSetting: true }),
+ onClick: () => openAgentSettingsModal(),
},
{ type: 'divider' as const },
{
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
index e698be6ebf2..931f176719b 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
@@ -6,9 +6,10 @@ import {
} from '@lobechat/heterogeneous-agents';
import type { HeterogeneousProviderConfig } from '@lobechat/types';
import { ActionIcon, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
-import { Select } from '@lobehub/ui/base-ui';
-import { Button, Modal, Tag } from 'antd';
+import { Button as BaseButton, createModal, Select, useModalContext } from '@lobehub/ui/base-ui';
+import { Button, Tag } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
+import { t as i18nT } from 'i18next';
import { BotIcon, CheckCircle2, MonitorSmartphone, RefreshCw, XCircle } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -79,6 +80,162 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
+interface ChangeDeviceContentProps {
+ currentDeviceId?: string;
+ isWorkspaceAgent: boolean;
+ onConfirm: (deviceId: string) => Promise<void> | void;
+ platform: RemoteHeterogeneousAgentType;
+}
+
+const ChangeDeviceContent = memo<ChangeDeviceContentProps>(
+ ({ currentDeviceId, isWorkspaceAgent, onConfirm, platform }) => {
+ const { t } = useTranslation('setting');
+ const { close } = useModalContext();
+
+ const [selectedDeviceId, setSelectedDeviceId] = useState<string | undefined>(currentDeviceId);
+ const [capabilityResult, setCapabilityResult] = useState<
+ { available: boolean; reason?: string; version?: string } | undefined
+ >(undefined);
+ const [checkingCapability, setCheckingCapability] = useState(false);
+ const [saving, setSaving] = useState(false);
+
+ const { data: devices, isLoading: loadingDevices } = lambdaQuery.device.listDevices.useQuery(
+ undefined,
+ { staleTime: 30_000 },
+ );
+
+ const onlineDevices = (devices ?? []).filter(
+ (d) => d.online && (!isWorkspaceAgent || d.scope === 'workspace'),
+ );
+
+ const checkCapability = useCallback(
+ async (deviceId: string) => {
+ setCheckingCapability(true);
+ setCapabilityResult(undefined);
+ try {
+ const result = await deviceService.checkCapability({
+ deviceId,
+ platform,
+ });
+ setCapabilityResult(result);
+ } catch {
+ setCapabilityResult({ available: false, reason: 'Check failed' });
+ } finally {
+ setCheckingCapability(false);
+ }
+ },
+ [platform],
+ );
+
+ const handleDeviceSelect = useCallback(
+ (dId: string) => {
+ setSelectedDeviceId(dId);
+ void checkCapability(dId);
+ },
+ [checkCapability],
+ );
+
+ const handleSave = async () => {
+ if (!selectedDeviceId) return;
+ setSaving(true);
+ try {
+ await onConfirm(selectedDeviceId);
+ close();
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const capabilityOk = capabilityResult?.available === true;
+ const capabilityBad = capabilityResult?.available === false;
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={12} paddingBlock={'12px 4px'}>
+ <Select
+ loading={loadingDevices}
+ placeholder={t('platformAgentConfig.selectDevice')}
+ style={{ width: '100%' }}
+ value={selectedDeviceId}
+ options={onlineDevices.map((d) => ({
+ label: (
+ <div className={styles.deviceItem}>
+ <Icon icon={BotIcon} size={14} />
+ <span>{d.hostname}</span>
+ <Tag color="success" style={{ marginInlineEnd: 0 }}>
+ {t('platformAgentConfig.device.online')}
+ </Tag>
+ </div>
+ ),
+ value: d.deviceId,
+ }))}
+ onChange={handleDeviceSelect}
+ />
+ {checkingCapability && (
+ <Tag style={{ marginInlineEnd: 0 }}>
+ {t('platformAgentConfig.availability.checking')}
+ </Tag>
+ )}
+ {capabilityOk && (
+ <Flexbox horizontal align="center" gap={4}>
+ <Icon color="var(--ant-color-success)" icon={CheckCircle2} size={14} />
+ <Tag color="success" style={{ marginInlineEnd: 0 }}>
+ {capabilityResult?.version ?? t('platformAgentConfig.availability.available')}
+ </Tag>
+ </Flexbox>
+ )}
+ {capabilityBad && (
+ <Flexbox horizontal align="center" gap={4}>
+ <Icon color="var(--ant-color-error)" icon={XCircle} size={14} />
+ <Tag color="error" style={{ marginInlineEnd: 0 }}>
+ {t('platformAgentConfig.availability.notInstalled')}
+ </Tag>
+ </Flexbox>
+ )}
+ </Flexbox>
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <BaseButton disabled={saving} onClick={close}>
+ {t('cancel', { ns: 'common' })}
+ </BaseButton>
+ <BaseButton
+ disabled={!selectedDeviceId || checkingCapability || capabilityBad}
+ loading={saving}
+ type={'primary'}
+ onClick={handleSave}
+ >
+ {t('platformAgentConfig.changeDevice')}
+ </BaseButton>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+ChangeDeviceContent.displayName = 'ChangeDeviceContent';
+
+interface OpenChangeDeviceModalOptions {
+ currentDeviceId?: string;
+ isWorkspaceAgent: boolean;
+ onConfirm: (deviceId: string) => Promise<void> | void;
+ platform: RemoteHeterogeneousAgentType;
+}
+
+const openChangeDeviceModal = (options: OpenChangeDeviceModalOptions) =>
+ createModal({
+ content: (
+ <ChangeDeviceContent
+ currentDeviceId={options.currentDeviceId}
+ isWorkspaceAgent={options.isWorkspaceAgent}
+ platform={options.platform}
+ onConfirm={options.onConfirm}
+ />
+ ),
+ footer: null,
+ maskClosable: true,
+ title: i18nT('platformAgentConfig.changeDevice', { ns: 'setting' }),
+ width: 400,
+ });
+
interface RemoteAgentConfigCardProps {
onBoundDeviceChange?: (deviceId: string) => Promise<void> | void;
provider: HeterogeneousProviderConfig;
@@ -100,20 +257,16 @@ const RemoteAgentConfigCard = memo<RemoteAgentConfigCardProps>(
);
const isWorkspaceAgent = Boolean(agentWorkspaceId);
- const [changeDeviceOpen, setChangeDeviceOpen] = useState(false);
- const [selectedDeviceId, setSelectedDeviceId] = useState<string | undefined>(undefined);
const [capabilityResult, setCapabilityResult] = useState<
{ available: boolean; reason?: string; version?: string } | undefined
>(undefined);
const [checkingCapability, setCheckingCapability] = useState(false);
- const [saving, setSaving] = useState(false);
const platformName = HETEROGENEOUS_TYPE_LABELS[provider.type] ?? provider.type;
- const { data: devices, isLoading: loadingDevices } = lambdaQuery.device.listDevices.useQuery(
- undefined,
- { staleTime: 30_000 },
- );
+ const { data: devices } = lambdaQuery.device.listDevices.useQuery(undefined, {
+ staleTime: 30_000,
+ });
const boundDevice = devices?.find((d) => d.deviceId === boundDeviceId);
@@ -136,7 +289,6 @@ const RemoteAgentConfigCard = memo<RemoteAgentConfigCardProps>(
[provider.type],
);
- // Check capability on mount when bound device is online
useEffect(() => {
if (boundDeviceId && boundDevice?.online) {
void checkCapability(boundDeviceId);
@@ -144,29 +296,15 @@ const RemoteAgentConfigCard = memo<RemoteAgentConfigCardProps>(
}, [boundDeviceId, boundDevice?.online, checkCapability]);
const handleOpenChangeDevice = useCallback(() => {
- setSelectedDeviceId(boundDeviceId);
- setCapabilityResult(undefined);
- setChangeDeviceOpen(true);
- }, [boundDeviceId]);
-
- const handleDeviceSelect = useCallback(
- (dId: string) => {
- setSelectedDeviceId(dId);
- void checkCapability(dId);
- },
- [checkCapability],
- );
-
- const handleSaveDevice = useCallback(async () => {
- if (!selectedDeviceId) return;
- setSaving(true);
- try {
- await onBoundDeviceChange?.(selectedDeviceId);
- setChangeDeviceOpen(false);
- } finally {
- setSaving(false);
- }
- }, [selectedDeviceId, onBoundDeviceChange]);
+ openChangeDeviceModal({
+ currentDeviceId: boundDeviceId,
+ isWorkspaceAgent,
+ onConfirm: async (deviceId) => {
+ await onBoundDeviceChange?.(deviceId);
+ },
+ platform: provider.type as RemoteHeterogeneousAgentType,
+ });
+ }, [boundDeviceId, isWorkspaceAgent, onBoundDeviceChange, provider.type]);
const renderAvailability = () => {
if (!boundDeviceId) {
@@ -207,137 +345,71 @@ const RemoteAgentConfigCard = memo<RemoteAgentConfigCardProps>(
);
};
- const onlineDevices = (devices ?? []).filter(
- (d) => d.online && (!isWorkspaceAgent || d.scope === 'workspace'),
- );
- const capabilityOk = capabilityResult?.available === true;
- const capabilityBad = capabilityResult?.available === false;
-
return (
- <>
- <Flexbox className={styles.card} gap={0}>
- <div className={styles.cardHeader}>
- <Flexbox horizontal align="center" gap={8}>
- <Icon icon={MonitorSmartphone} size={16} />
- <Text strong className={styles.title}>
- {t('platformAgentConfig.title')}
- </Text>
- </Flexbox>
- <Tooltip title={t('platformAgentConfig.redetect')}>
- <ActionIcon
- aria-label={t('platformAgentConfig.redetect')}
- disabled={!boundDeviceId || checkingCapability}
- icon={RefreshCw}
- loading={checkingCapability}
- size="small"
- onClick={() => boundDeviceId && void checkCapability(boundDeviceId)}
- />
- </Tooltip>
- </div>
- <div className={styles.detailList}>
- <div className={styles.detailRow}>
- <Text className={styles.detailLabel}>{t('platformAgentConfig.platform.label')}</Text>
- <div className={styles.detailContent}>
- <Tag style={{ marginInlineEnd: 0 }}>{platformName}</Tag>
- </div>
- </div>
- <div className={styles.detailRow}>
- <Text className={styles.detailLabel}>{t('platformAgentConfig.device.label')}</Text>
- <div className={styles.detailContent}>
- {boundDevice ? (
- <Flexbox horizontal align="center" gap={6}>
- <Text ellipsis style={{ fontSize: 14 }}>
- {boundDevice.hostname}
- </Text>
- <Tag
- color={boundDevice.online ? 'success' : 'default'}
- style={{ marginInlineEnd: 0 }}
- >
- {boundDevice.online
- ? t('platformAgentConfig.device.online')
- : t('platformAgentConfig.device.offline')}
- </Tag>
- </Flexbox>
- ) : (
- <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgentConfig.device.none')}</Tag>
- )}
- </div>
+ <Flexbox className={styles.card} gap={0}>
+ <div className={styles.cardHeader}>
+ <Flexbox horizontal align="center" gap={8}>
+ <Icon icon={MonitorSmartphone} size={16} />
+ <Text strong className={styles.title}>
+ {t('platformAgentConfig.title')}
+ </Text>
+ </Flexbox>
+ <Tooltip title={t('platformAgentConfig.redetect')}>
+ <ActionIcon
+ aria-label={t('platformAgentConfig.redetect')}
+ disabled={!boundDeviceId || checkingCapability}
+ icon={RefreshCw}
+ loading={checkingCapability}
+ size="small"
+ onClick={() => boundDeviceId && void checkCapability(boundDeviceId)}
+ />
+ </Tooltip>
+ </div>
+ <div className={styles.detailList}>
+ <div className={styles.detailRow}>
+ <Text className={styles.detailLabel}>{t('platformAgentConfig.platform.label')}</Text>
+ <div className={styles.detailContent}>
+ <Tag style={{ marginInlineEnd: 0 }}>{platformName}</Tag>
</div>
- <div className={styles.detailRow}>
- <Text className={styles.detailLabel}>
- {t('platformAgentConfig.availability.label')}
- </Text>
- <div className={styles.detailContent}>{renderAvailability()}</div>
+ </div>
+ <div className={styles.detailRow}>
+ <Text className={styles.detailLabel}>{t('platformAgentConfig.device.label')}</Text>
+ <div className={styles.detailContent}>
+ {boundDevice ? (
+ <Flexbox horizontal align="center" gap={6}>
+ <Text ellipsis style={{ fontSize: 14 }}>
+ {boundDevice.hostname}
+ </Text>
+ <Tag
+ color={boundDevice.online ? 'success' : 'default'}
+ style={{ marginInlineEnd: 0 }}
+ >
+ {boundDevice.online
+ ? t('platformAgentConfig.device.online')
+ : t('platformAgentConfig.device.offline')}
+ </Tag>
+ </Flexbox>
+ ) : (
+ <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgentConfig.device.none')}</Tag>
+ )}
</div>
- <div className={styles.detailRow}>
- <div className={styles.detailLabel} />
- <div className={styles.detailContent}>
- <Button size="small" onClick={handleOpenChangeDevice}>
- {t('platformAgentConfig.changeDevice')}
- </Button>
- </div>
+ </div>
+ <div className={styles.detailRow}>
+ <Text className={styles.detailLabel}>
+ {t('platformAgentConfig.availability.label')}
+ </Text>
+ <div className={styles.detailContent}>{renderAvailability()}</div>
+ </div>
+ <div className={styles.detailRow}>
+ <div className={styles.detailLabel} />
+ <div className={styles.detailContent}>
+ <Button size="small" onClick={handleOpenChangeDevice}>
+ {t('platformAgentConfig.changeDevice')}
+ </Button>
</div>
</div>
- </Flexbox>
-
- {/* Change Device Modal */}
- <Modal
- destroyOnClose
- okText={t('platformAgentConfig.changeDevice')}
- open={changeDeviceOpen}
- title={t('platformAgentConfig.changeDevice')}
- width={400}
- okButtonProps={{
- disabled: !selectedDeviceId || checkingCapability || capabilityBad,
- loading: saving,
- }}
- onCancel={() => setChangeDeviceOpen(false)}
- onOk={() => void handleSaveDevice()}
- >
- <Flexbox gap={12} paddingBlock={'12px 4px'}>
- <Select
- loading={loadingDevices}
- placeholder={t('platformAgentConfig.selectDevice')}
- style={{ width: '100%' }}
- value={selectedDeviceId}
- options={onlineDevices.map((d) => ({
- label: (
- <div className={styles.deviceItem}>
- <Icon icon={BotIcon} size={14} />
- <span>{d.hostname}</span>
- <Tag color="success" style={{ marginInlineEnd: 0 }}>
- {t('platformAgentConfig.device.online')}
- </Tag>
- </div>
- ),
- value: d.deviceId,
- }))}
- onChange={handleDeviceSelect}
- />
- {checkingCapability && (
- <Tag style={{ marginInlineEnd: 0 }}>
- {t('platformAgentConfig.availability.checking')}
- </Tag>
- )}
- {capabilityOk && (
- <Flexbox horizontal align="center" gap={4}>
- <Icon color="var(--ant-color-success)" icon={CheckCircle2} size={14} />
- <Tag color="success" style={{ marginInlineEnd: 0 }}>
- {capabilityResult?.version ?? t('platformAgentConfig.availability.available')}
- </Tag>
- </Flexbox>
- )}
- {capabilityBad && (
- <Flexbox horizontal align="center" gap={4}>
- <Icon color="var(--ant-color-error)" icon={XCircle} size={14} />
- <Tag color="error" style={{ marginInlineEnd: 0 }}>
- {t('platformAgentConfig.availability.notInstalled')}
- </Tag>
- </Flexbox>
- )}
- </Flexbox>
- </Modal>
- </>
+ </div>
+ </Flexbox>
);
},
);
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
index 379c3636801..82b915901bc 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
@@ -14,7 +14,6 @@ import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
-import AgentSettings from '../AgentSettings';
import EditorCanvas from '../EditorCanvas';
import AgentHeader from './AgentHeader';
import AgentTool from './AgentTool';
@@ -165,8 +164,6 @@ const ProfileEditor = memo(() => {
editor here to avoid a control that looks effective but isn't (mirrors the
ModelSelect hiding above). */}
{!isHeterogeneous && <EditorCanvas />}
- {/* Advanced Settings Modal */}
- <AgentSettings />
</>
);
});
diff --git a/src/routes/(main)/group/profile/features/AgentSettings/Content.tsx b/src/routes/(main)/group/profile/features/AgentSettings/Content.tsx
index 64b47917046..8c9c309e03a 100644
--- a/src/routes/(main)/group/profile/features/AgentSettings/Content.tsx
+++ b/src/routes/(main)/group/profile/features/AgentSettings/Content.tsx
@@ -1,16 +1,11 @@
'use client';
-import { Avatar, Block, Flexbox, Icon, Text } from '@lobehub/ui';
-import { type ItemType } from 'antd/es/menu/interface';
-import { useTheme } from 'antd-style';
-import { MessageSquareHeartIcon } from 'lucide-react';
-import { memo, useMemo, useState } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
-import Menu from '@/components/Menu';
import { DEFAULT_AVATAR } from '@/const/meta';
-import { AgentSettings as Settings } from '@/features/AgentSetting';
+import { AgentSettings as Settings, SettingsModalLayout } from '@/features/AgentSetting';
import { usePermission } from '@/hooks/usePermission';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
@@ -18,17 +13,14 @@ import { ChatSettingsTabs } from '@/store/global/initialState';
const Content = memo(() => {
const { t } = useTranslation('setting');
- const theme = useTheme();
const { allowed: canEdit } = usePermission('edit_own_content');
const { gid } = useParams<{ gid: string }>();
const groupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
const currentGroup = useAgentGroupStore((s) => agentGroupSelectors.getGroupById(gid ?? '')(s));
- const [tab] = useState(ChatSettingsTabs.Opening);
const updateGroupConfig = async (config: any) => {
if (!canEdit) return;
if (!groupId) return;
- // Only update openingMessage and openingQuestions
const groupConfig = {
openingMessage: config.openingMessage,
openingQuestions: config.openingQuestions,
@@ -42,7 +34,6 @@ const Content = memo(() => {
await useAgentGroupStore.getState().updateGroup(groupId, meta);
};
- // Convert group config to agent config format for AgentSettings component
const agentConfig = useMemo(
() =>
({
@@ -68,79 +59,25 @@ const Content = memo(() => {
[currentGroup],
);
- const menuItems: ItemType[] = useMemo(
- () => [
- {
- icon: <Icon icon={MessageSquareHeartIcon} />,
- key: ChatSettingsTabs.Opening,
- label: t('agentTab.opening'),
- },
- ],
- [t],
- );
-
const displayTitle = currentGroup?.title || t('defaultSession', { ns: 'common' });
return (
- <Flexbox
- direction="horizontal"
- height="100%"
- style={{
- padding: 0,
- position: 'relative',
- }}
+ <SettingsModalLayout
+ avatar={currentGroup?.avatar || DEFAULT_AVATAR}
+ background={currentGroup?.backgroundColor || undefined}
+ title={displayTitle}
>
- <Flexbox
- height={'100%'}
- paddingBlock={24}
- paddingInline={8}
- width={200}
- style={{
- background: theme.colorBgLayout,
- borderRight: `1px solid ${theme.colorBorderSecondary}`,
- }}
- >
- <Block
- horizontal
- align={'center'}
- gap={8}
- paddingBlock={'14px 16px'}
- paddingInline={4}
- variant={'borderless'}
- style={{
- overflow: 'hidden',
- }}
- >
- <Avatar
- avatar={currentGroup?.avatar || DEFAULT_AVATAR}
- background={currentGroup?.backgroundColor || undefined}
- shape={'square'}
- size={28}
- />
- <Text ellipsis weight={500}>
- {displayTitle}
- </Text>
- </Block>
- <Menu selectable items={menuItems} selectedKeys={[tab]} style={{ width: '100%' }} />
- </Flexbox>
- <Flexbox
- flex={1}
- paddingBlock={24}
- paddingInline={64}
- style={{ overflow: 'scroll', width: '100%' }}
- >
- <Settings
- config={agentConfig}
- disabled={!canEdit}
- id={groupId}
- loading={false}
- meta={agentMeta}
- tab={tab}
- onConfigChange={updateGroupConfig}
- onMetaChange={updateGroupMeta}
- />
- </Flexbox>
- </Flexbox>
+ <Settings
+ config={agentConfig}
+ disabled={!canEdit}
+ id={groupId}
+ loading={false}
+ meta={agentMeta}
+ tab={ChatSettingsTabs.Opening}
+ onConfigChange={updateGroupConfig}
+ onMetaChange={updateGroupMeta}
+ />
+ </SettingsModalLayout>
);
});
diff --git a/src/routes/(main)/group/profile/features/AgentSettings/index.tsx b/src/routes/(main)/group/profile/features/AgentSettings/index.tsx
index fce7d37c140..634ff34426c 100644
--- a/src/routes/(main)/group/profile/features/AgentSettings/index.tsx
+++ b/src/routes/(main)/group/profile/features/AgentSettings/index.tsx
@@ -1,36 +1,22 @@
'use client';
-import { Modal } from '@lobehub/ui';
-import { memo } from 'react';
+import { createModal, type ModalInstance } from '@lobehub/ui/base-ui';
import Content from './Content';
-interface AgentSettingsProps {
- onCancel: () => void;
- open: boolean;
-}
-
-const AgentSettings = memo<AgentSettingsProps>(({ open, onCancel }) => {
- return (
- <Modal
- centered
- footer={null}
- open={open}
- title={null}
- width={960}
- styles={{
- body: {
- height: '60vh',
- overflow: 'scroll',
- padding: 0,
- position: 'relative',
- },
- }}
- onCancel={onCancel}
- >
- <Content />
- </Modal>
- );
-});
-
-export default AgentSettings;
+export const openGroupAgentSettingsModal = (): ModalInstance =>
+ createModal({
+ content: <Content />,
+ footer: null,
+ maskClosable: true,
+ styles: {
+ content: {
+ height: '60vh',
+ overflow: 'scroll',
+ padding: 0,
+ position: 'relative',
+ },
+ header: { display: 'none' },
+ },
+ width: 960,
+ });
diff --git a/src/routes/(main)/group/profile/features/GroupProfile/index.tsx b/src/routes/(main)/group/profile/features/GroupProfile/index.tsx
index b26bb67b00b..66f1be35321 100644
--- a/src/routes/(main)/group/profile/features/GroupProfile/index.tsx
+++ b/src/routes/(main)/group/profile/features/GroupProfile/index.tsx
@@ -19,7 +19,7 @@ import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { useGroupProfileStore } from '@/store/groupProfile';
-import AgentSettings from '../AgentSettings';
+import { openGroupAgentSettingsModal } from '../AgentSettings';
import AutoSaveHint from '../Header/AutoSaveHint';
import GroupForkTag from './GroupForkTag';
import GroupHeader from './GroupHeader';
@@ -39,7 +39,6 @@ const GroupProfile = memo(() => {
const { t } = useTranslation(['setting', 'chat']);
const { allowed: canEdit } = usePermission('edit_own_content');
const theme = useTheme();
- const [showAgentSetting, setShowAgentSetting] = useState(false);
const { gid } = useParams<{ gid: string }>();
const groupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
const currentGroup = useAgentGroupStore((s) => agentGroupSelectors.getGroupById(gid ?? '')(s));
@@ -167,7 +166,7 @@ const GroupProfile = memo(() => {
onClick={() => {
if (!canEdit) return;
- setShowAgentSetting(true);
+ openGroupAgentSettingsModal();
}}
>
{t('advancedSettings')}
@@ -189,8 +188,6 @@ const GroupProfile = memo(() => {
placeholder={t('group.profile.contentPlaceholder', { ns: 'chat' })}
onContentChange={onContentChange}
/>
- {/* Advanced Settings Modal */}
- <AgentSettings open={showAgentSetting} onCancel={() => setShowAgentSetting(false)} />
</>
);
});
diff --git a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
index 70352b612ba..519bb31536c 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
@@ -6,7 +6,7 @@ import { createContext, memo, use, useMemo, useState } from 'react';
import { ChatGroupWizard } from '@/components/ChatGroupWizard';
import { MemberSelectionModal } from '@/components/MemberSelectionModal';
-import CreatePlatformAgentModal from '@/features/CreatePlatformAgent';
+import { openCreatePlatformAgentModal } from '@/features/CreatePlatformAgent';
import EditingPopover from '@/features/EditingPopover';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { CreateAgentModal } from '@/routes/(main)/home/_layout/hooks/useCreateModal';
@@ -26,7 +26,6 @@ interface AgentModalContextValue {
closeAllModals: () => void;
closeConfigGroupModal: () => void;
closeCreateGroupModal: () => void;
- closeCreatePlatformAgentModal: () => void;
closeGroupWizardModal: () => void;
closeMemberSelectionModal: () => void;
openConfigGroupModal: () => void;
@@ -158,12 +157,6 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
const [createModalType, setCreateModalType] = useState<'agent' | 'group'>('agent');
const [createModalGroupId, setCreateModalGroupId] = useState<string | undefined>(undefined);
- // CreatePlatformAgentModal state
- const [createPlatformAgentOpen, setCreatePlatformAgentOpen] = useState(false);
- const [createPlatformAgentGroupId, setCreatePlatformAgentGroupId] = useState<string | undefined>(
- undefined,
- );
-
const contextValue = useMemo<AgentModalContextValue>(
() => ({
closeAllModals: () => {
@@ -172,11 +165,9 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
setGroupWizardOpen(false);
setMemberSelectionOpen(false);
setCreateModalOpen(false);
- setCreatePlatformAgentOpen(false);
},
closeConfigGroupModal: () => setConfigGroupModalOpen(false),
closeCreateGroupModal: () => setCreateGroupModalOpen(false),
- closeCreatePlatformAgentModal: () => setCreatePlatformAgentOpen(false),
closeGroupWizardModal: () => setGroupWizardOpen(false),
closeMemberSelectionModal: () => setMemberSelectionOpen(false),
openConfigGroupModal: () => setConfigGroupModalOpen(true),
@@ -190,8 +181,7 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
setCreateModalOpen(true);
},
openCreatePlatformAgentModal: (options?: OpenCreateModalOptions) => {
- setCreatePlatformAgentGroupId(options?.groupId);
- setCreatePlatformAgentOpen(true);
+ openCreatePlatformAgentModal({ groupId: options?.groupId });
},
openGroupWizardModal: (callbacks: GroupWizardCallbacks) => {
setGroupWizardCallbacks(callbacks);
@@ -214,11 +204,6 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
type={createModalType}
onClose={() => setCreateModalOpen(false)}
/>
- <CreatePlatformAgentModal
- groupId={createPlatformAgentGroupId}
- open={createPlatformAgentOpen}
- onClose={() => setCreatePlatformAgentOpen(false)}
- />
{children}
{/* All modals rendered at top level */}
diff --git a/src/routes/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx b/src/routes/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx
index 79d5599edc4..f538d88bdcf 100644
--- a/src/routes/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx
+++ b/src/routes/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx
@@ -267,12 +267,12 @@ const ConnectionLine = memo<ConnectionLineProps>(
},
);
-// Center avatar component
const CenterAvatar = memo(() => {
return (
<Html
center
position={[0, 0, 0]}
+ zIndexRange={[10, 0]}
style={{
pointerEvents: 'none',
}}
diff --git a/src/routes/(main)/memory/features/MemoryAnalysis/Action.tsx b/src/routes/(main)/memory/features/MemoryAnalysis/Action.tsx
index c5168c8fd7d..26528ede353 100644
--- a/src/routes/(main)/memory/features/MemoryAnalysis/Action.tsx
+++ b/src/routes/(main)/memory/features/MemoryAnalysis/Action.tsx
@@ -1,7 +1,6 @@
'use client';
-import { memo, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
+import { memo } from 'react';
import AnalysisTrigger from './AnalysisTrigger';
@@ -10,31 +9,7 @@ interface Props {
}
const AnalysisAction = memo<Props>(({ iconOnly }) => {
- const { t } = useTranslation('memory');
- const [range, setRange] = useState<[Date | null, Date | null]>([null, null]);
-
- const footerNote = useMemo(
- () =>
- range[0] || range[1]
- ? t('analysis.modal.rangeSelected', {
- end: range[1]?.toISOString().slice(0, 10)?.replaceAll('-', '/') ||
- t('analysis.range.end'),
- start:
- range[0]?.toISOString().slice(0, 10)?.replaceAll('-', '/') ||
- t('analysis.range.start'),
- })
- : t('analysis.modal.rangePlaceholder'),
- [range, t],
- );
-
- return (
- <AnalysisTrigger
- footerNote={footerNote}
- iconOnly={iconOnly}
- range={range}
- onRangeChange={setRange}
- />
- );
+ return <AnalysisTrigger iconOnly={iconOnly} />;
});
AnalysisAction.displayName = 'AnalysisAction';
diff --git a/src/routes/(main)/memory/features/MemoryAnalysis/AnalysisTrigger.tsx b/src/routes/(main)/memory/features/MemoryAnalysis/AnalysisTrigger.tsx
index 9cc5f5122b5..c4019e75f64 100644
--- a/src/routes/(main)/memory/features/MemoryAnalysis/AnalysisTrigger.tsx
+++ b/src/routes/(main)/memory/features/MemoryAnalysis/AnalysisTrigger.tsx
@@ -1,89 +1,48 @@
'use client';
import { ActionIcon, Button, Tooltip } from '@lobehub/ui';
-import { App } from 'antd';
import { CalendarClockIcon } from 'lucide-react';
-import { memo, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { useMemoryAnalysisAsyncTask } from '@/routes/(main)/memory/features/MemoryAnalysis/useTask';
-import { memoryExtractionService } from '@/services/userMemory/extraction';
-import DateRangeModal from './DateRangeModal';
+import { createDateRangeModal } from './DateRangeModal';
interface Props {
- footerNote: string;
iconOnly?: boolean;
- onRangeChange: (range: [Date | null, Date | null]) => void;
- range: [Date | null, Date | null];
}
-const AnalysisTrigger = memo<Props>(({ footerNote, range, onRangeChange, iconOnly }) => {
+const AnalysisTrigger = memo<Props>(({ iconOnly }) => {
const { t } = useTranslation('memory');
- const { message } = App.useApp();
- const { isValidating, refresh } = useMemoryAnalysisAsyncTask();
- const [open, setOpen] = useState(false);
- const [submitting, setSubmitting] = useState(false);
+ const { isValidating } = useMemoryAnalysisAsyncTask();
- const handleSubmit = async () => {
- setSubmitting(true);
- try {
- const [from, to] = range;
- const result = await memoryExtractionService.requestFromChatTopics({
- fromDate: from ?? undefined,
- toDate: to ?? undefined,
- });
-
- await refresh();
- message.success(result.deduped ? t('analysis.toast.deduped') : t('analysis.toast.started'));
-
- setOpen(false);
- } catch (error) {
- console.error(error);
- message.error(t('analysis.toast.failed'));
- } finally {
- setSubmitting(false);
- }
+ const handleClick = () => {
+ createDateRangeModal();
};
- const loading = submitting || isValidating;
-
- return (
- <>
- {iconOnly ? (
- <Tooltip title={t('analysis.action.button')}>
- <ActionIcon
- icon={CalendarClockIcon}
- size={DESKTOP_HEADER_ICON_SMALL_SIZE}
- tooltipProps={{ placement: 'bottom' }}
- onClick={() => setOpen(true)}
- />
- </Tooltip>
- ) : (
- <Button
- className="test"
- icon={CalendarClockIcon}
- loading={loading}
- size={'small'}
- style={{ maxWidth: 300 }}
- type={'primary'}
- onClick={() => setOpen(true)}
- >
- {t('analysis.action.button')}
- </Button>
- )}
-
- <DateRangeModal
- footerNote={footerNote}
- open={open}
- range={range}
- submitting={submitting}
- onCancel={() => setOpen(false)}
- onChange={onRangeChange}
- onSubmit={handleSubmit}
+ return iconOnly ? (
+ <Tooltip title={t('analysis.action.button')}>
+ <ActionIcon
+ icon={CalendarClockIcon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ tooltipProps={{ placement: 'bottom' }}
+ onClick={handleClick}
/>
- </>
+ </Tooltip>
+ ) : (
+ <Button
+ className="test"
+ icon={CalendarClockIcon}
+ loading={isValidating}
+ size={'small'}
+ style={{ maxWidth: 300 }}
+ type={'primary'}
+ onClick={handleClick}
+ >
+ {t('analysis.action.button')}
+ </Button>
);
});
diff --git a/src/routes/(main)/memory/features/MemoryAnalysis/DateRangeModal.tsx b/src/routes/(main)/memory/features/MemoryAnalysis/DateRangeModal.tsx
index 3027d539ac6..4325cca0e86 100644
--- a/src/routes/(main)/memory/features/MemoryAnalysis/DateRangeModal.tsx
+++ b/src/routes/(main)/memory/features/MemoryAnalysis/DateRangeModal.tsx
@@ -1,62 +1,100 @@
'use client';
import { Flexbox, Text } from '@lobehub/ui';
-import { DatePicker, Modal } from 'antd';
+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';
+import { App, DatePicker } from 'antd';
import { type RangePickerProps } from 'antd/es/date-picker';
import dayjs from 'dayjs';
-import { memo, useCallback } from 'react';
+import { t as i18nT } from 'i18next';
+import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-interface Props {
- footerNote: string;
- onCancel: () => void;
- onChange: (range: [Date | null, Date | null]) => void;
- onSubmit: () => void;
- open: boolean;
- range: [Date | null, Date | null];
- submitting: boolean;
-}
-
-const DateRangeModal = memo<Props>(
- ({ footerNote, onCancel, onChange, onSubmit, open, range, submitting }) => {
- const { t } = useTranslation('memory');
-
- const disabledDate = useCallback<NonNullable<RangePickerProps['disabledDate']>>(
- (current) => current.isAfter(dayjs(), 'day'),
- [],
- );
-
- return (
- <Modal
- cancelText={t('analysis.modal.cancel')}
- okButtonProps={{ loading: submitting }}
- okText={t('analysis.modal.submit')}
- open={open}
- title={t('analysis.modal.title')}
- onCancel={onCancel}
- onOk={onSubmit}
- >
- <Flexbox gap={12}>
- <Text type={'secondary'}>{t('analysis.modal.helper')}</Text>
- <DatePicker.RangePicker
- allowClear
- disabledDate={disabledDate}
- format={'YYYY/MM/DD'}
- style={{ width: '100%' }}
- value={[range[0] ? dayjs(range[0]) : null, range[1] ? dayjs(range[1]) : null]}
- onChange={(values) =>
- onChange([values?.[0]?.toDate() ?? null, values?.[1]?.toDate() ?? null])
- }
- />
- <Text fontSize={12} type={'secondary'}>
- {footerNote}
- </Text>
- </Flexbox>
- </Modal>
- );
- },
-);
-
-DateRangeModal.displayName = 'DateRangeModal';
-
-export default DateRangeModal;
+import { useMemoryAnalysisAsyncTask } from '@/routes/(main)/memory/features/MemoryAnalysis/useTask';
+import { memoryExtractionService } from '@/services/userMemory/extraction';
+
+const DateRangeContent = memo(() => {
+ const { t } = useTranslation('memory');
+ const { close } = useModalContext();
+ const { message } = App.useApp();
+ const { refresh } = useMemoryAnalysisAsyncTask();
+ const [range, setRange] = useState<[Date | null, Date | null]>([null, null]);
+ const [submitting, setSubmitting] = useState(false);
+
+ const disabledDate = useCallback<NonNullable<RangePickerProps['disabledDate']>>(
+ (current) => current.isAfter(dayjs(), 'day'),
+ [],
+ );
+
+ const footerNote = useMemo(
+ () =>
+ range[0] || range[1]
+ ? t('analysis.modal.rangeSelected', {
+ end:
+ range[1]?.toISOString().slice(0, 10)?.replaceAll('-', '/') || t('analysis.range.end'),
+ start:
+ range[0]?.toISOString().slice(0, 10)?.replaceAll('-', '/') ||
+ t('analysis.range.start'),
+ })
+ : t('analysis.modal.rangePlaceholder'),
+ [range, t],
+ );
+
+ const handleSubmit = async () => {
+ setSubmitting(true);
+ try {
+ const [from, to] = range;
+ const result = await memoryExtractionService.requestFromChatTopics({
+ fromDate: from ?? undefined,
+ toDate: to ?? undefined,
+ });
+
+ await refresh();
+ message.success(result.deduped ? t('analysis.toast.deduped') : t('analysis.toast.started'));
+ close();
+ } catch (error) {
+ console.error(error);
+ message.error(t('analysis.toast.failed'));
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={12}>
+ <Text type={'secondary'}>{t('analysis.modal.helper')}</Text>
+ <DatePicker.RangePicker
+ allowClear
+ disabledDate={disabledDate}
+ format={'YYYY/MM/DD'}
+ style={{ width: '100%' }}
+ value={[range[0] ? dayjs(range[0]) : null, range[1] ? dayjs(range[1]) : null]}
+ onChange={(values) =>
+ setRange([values?.[0]?.toDate() ?? null, values?.[1]?.toDate() ?? null])
+ }
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {footerNote}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button disabled={submitting} onClick={close}>
+ {t('analysis.modal.cancel')}
+ </Button>
+ <Button loading={submitting} type={'primary'} onClick={handleSubmit}>
+ {t('analysis.modal.submit')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+DateRangeContent.displayName = 'DateRangeContent';
+
+export const createDateRangeModal = (): ModalInstance =>
+ createModal({
+ content: <DateRangeContent />,
+ footer: null,
+ maskClosable: true,
+ title: i18nT('analysis.modal.title', { ns: 'memory' }),
+ });
diff --git a/src/routes/(main)/settings/skill/index.tsx b/src/routes/(main)/settings/skill/index.tsx
index 1713c6ec41f..3133b53e99e 100644
--- a/src/routes/(main)/settings/skill/index.tsx
+++ b/src/routes/(main)/settings/skill/index.tsx
@@ -12,9 +12,9 @@ import { useSearchParams } from 'react-router';
import { CustomConnectorModal } from '@/features/Connectors';
import NavHeader from '@/features/NavHeader';
import { createSkillStoreModal } from '@/features/SkillStore';
-import ImportFromGithubModal from '@/features/SkillStore/SkillList/ImportFromGithubModal';
-import ImportFromUrlModal from '@/features/SkillStore/SkillList/ImportFromUrlModal';
-import UploadSkillModal from '@/features/SkillStore/SkillList/UploadSkillModal';
+import { openImportFromGithubModal } from '@/features/SkillStore/SkillList/ImportFromGithubModal';
+import { openImportFromUrlModal } from '@/features/SkillStore/SkillList/ImportFromUrlModal';
+import { openUploadSkillModal } from '@/features/SkillStore/SkillList/UploadSkillModal';
import { useToolStore } from '@/store/tool';
import { agentSkillsSelectors, builtinToolSelectors } from '@/store/tool/selectors';
@@ -96,9 +96,6 @@ const Page = memo(() => {
const [selected, setSelected] = useState<SelectedTool | null>(null);
const [viewMode, setViewMode] = useState<SkillViewMode>(queryViewMode);
const [showAddConnector, setShowAddConnector] = useState(false);
- const [showUrlModal, setUrlModal] = useState(false);
- const [showGithubModal, setGithubModal] = useState(false);
- const [showUploadModal, setUploadModal] = useState(false);
// Data sources for auto-select
const builtinTools = useToolStore((s) => s.builtinTools, isEqual);
@@ -192,7 +189,7 @@ const Page = memo(() => {
</Text>
</Flexbox>
),
- onClick: () => setUrlModal(true),
+ onClick: () => openImportFromUrlModal(),
},
{
icon: <Icon icon={GithubIcon} />,
@@ -205,7 +202,7 @@ const Page = memo(() => {
</Text>
</Flexbox>
),
- onClick: () => setGithubModal(true),
+ onClick: () => openImportFromGithubModal(),
},
{
icon: <Icon icon={FileArchive} />,
@@ -218,7 +215,7 @@ const Page = memo(() => {
</Text>
</Flexbox>
),
- onClick: () => setUploadModal(true),
+ onClick: () => openUploadSkillModal(),
},
{ type: 'divider' as const },
{
@@ -265,9 +262,6 @@ const Page = memo(() => {
</div>
)}
</div>
- <ImportFromUrlModal open={showUrlModal} onOpenChange={setUrlModal} />
- <ImportFromGithubModal open={showGithubModal} onOpenChange={setGithubModal} />
- <UploadSkillModal open={showUploadModal} onOpenChange={setUploadModal} />
<CustomConnectorModal open={showAddConnector} onClose={() => setShowAddConnector(false)} />
</>
);
diff --git a/src/store/agent/slices/agent/initialState.ts b/src/store/agent/slices/agent/initialState.ts
index cf3f359e2df..2f9b80e2b24 100644
--- a/src/store/agent/slices/agent/initialState.ts
+++ b/src/store/agent/slices/agent/initialState.ts
@@ -44,7 +44,6 @@ export interface AgentSliceState {
* Save status for showing auto-save hint
*/
saveStatus: SaveStatus;
- showAgentSetting: boolean;
/**
* Content being streamed for system role update
*/
@@ -74,7 +73,6 @@ export const initialAgentSliceState: AgentSliceState = {
title: false,
},
saveStatus: 'idle',
- showAgentSetting: false,
streamingSystemRole: undefined,
streamingSystemRoleInProgress: false,
};