🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(ui): migrate destroyOnHidden modals to imperative createModal (#17941)
Inneid39252def405
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 20d1d0c97b0..4a54559554b 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -913,6 +913,69 @@ Gate on a real authenticated TRPC call rather than on the page rendering: a 200`apps/desktop` are standalone installs (PROJECT.md §1), so each also needs its own`pnpm install` in a fresh worktree.+### The dev Electron instance may be a thin client on PRODUCTION — read `dataSyncConfig` before any write++**Situation:** starting `electron-dev.sh` to verify a frontend change, then driving flows that+create or mutate product objects (labels, groups, agents, forwarded topics, saved edits).++**Doesn't work:** assuming the instance talks to a local backend because the run also started one.+The seeded login snapshot carries its own target, and `{"storageMode":"cloud","active":true}` means+the renderer runs your working-tree code while every request goes to `app.lobehub.com` with the+user's real account. `app-probe.sh server-auth` returns 200, which reads as "the local stack is+wired up" and encourages exactly the writes that then land in production. The local dev server the+run started sits unused.++**Works:** read the target first and let it decide the test's write budget.++```bash+agent-browser --cdp 9222 eval '(() => JSON.stringify(window.__LOBE_STORES.electron().dataSyncConfig))()'+# {"storageMode":"cloud","active":true} -> production account; keep the run read-only+# {"storageMode":"selfHost","remoteServerUrl":"http://localhost:3111", ...} -> local backend+```++On `cloud`, verify open / render / close only, treat every submit as a user-owned decision, and+prove afterwards that nothing was written (re-read the relevant store count). Note this also makes+the whole local-server bring-up unnecessary — check the target before spending minutes on it.++### Asserting a modal's exit window: `data-ending-style` is never set, and `record-gif.sh` is far too slow++**Situation:** proving what a base-ui modal does during its \~120ms exit — typically that the body+stays mounted while the panel fades, rather than blanking at the start of the animation.++**Doesn't work:** three separate traps.++- Gating on `panel.hasAttribute("data-ending-style")`. `base-ui/Modal/style.mjs` does carry a+ `[data-ending-style]` rule, but the imperative host animates through motion/react, so the+ attribute stays absent for the whole exit. Filtering samples on it yields an empty set and reads+ as "the exit never happened".+- Polling the state from the driver. A `Runtime.evaluate` round trip is the same order of magnitude+ as the window itself, so the driver only ever observes before and after.+- `scripts/record-gif.sh`. Its own header caps effective rate at 1–2 fps; a 120ms window gets at+ most one frame.++**Works:** sample inside the page and capture frames from the compositor.++```js+// exit-window signal = opacity decay on popupInner ([role=dialog] > :first-child)+const tick = () =>+ samples.push({+ t: performance.now() - t0,+ connected: panel.isConnected,+ opacity: getComputedStyle(panel).opacity,+ panelH: panel.getBoundingClientRect().height,+ contentKids: content.children.length,+ contentTextLen: content.innerText.length,+ });+setInterval(tick, 8);+```++A body that survives the exit holds `contentTextLen` / `contentKids` constant while opacity decays,+and the panel shrinks only \~1.5% (the `scale(0.98)` exit transform) instead of collapsing to the+56px header. For the visual half, drive raw CDP `Page.startScreencast` (frames land only when the+compositor paints, so they cluster inside the animation — \~9 frames in the 120ms window) and replay+those unmodified frames slowly with ffmpeg. Do not slow the product's own transition: the exit is a+JS animation, so a CSS `transition-duration` override does nothing anyway.+## Detailed references- [Probe field notes](./references/probe-field-notes.md) — all historicaldiff --git a/.agents/skills/modal/SKILL.md b/.agents/skills/modal/SKILL.mdindex 067237d090d..994ed7aa34f 100644--- a/.agents/skills/modal/SKILL.md+++ b/.agents/skills/modal/SKILL.md@@ -99,6 +99,33 @@ return <Button onClick={handleOpen}>Open</Button>;const { close, setCanDismissByClickOutside } = useModalContext();```+### Closing: which callback actually fires++`close()` — from `useModalContext()` inside the content, or from the returned+`ModalInstance` — only flips the stack entry to `open: false`. It does **not** go+through base-ui's dismissal path, so:++| callback | user dismissal (Esc / backdrop / header ✕) | `close()` from content or instance |+| ---------------------- | ------------------------------------------ | ---------------------------------- |+| `onOpenChange` | fires | **does not fire** |+| `onOpenChangeComplete` | fires with `false` | fires with `false` |++Put caller-side cleanup (clearing an editing flag, resetting the provider's+`open` state) on **`onOpenChangeComplete`**. Wiring it to `onOpenChange` looks+correct until a footer button closes the modal, and then the caller never learns+it went away — typically leaving a flag set so the modal cannot be reopened.++`createModal` only ever completes with `false` (the imperative renderer supplies+the argument itself and never forwards the prop to base-ui), but still guard on+it — other base-ui primitives such as `DropdownMenu` do report both directions,+and the guard keeps the call site from depending on that difference:++```tsx+onOpenChangeComplete: (open) => {+ if (!open) onClosed?.();+},+```+### Common options (base-ui)`ImperativeModalProps` builds on `BaseModalProps`: `title`, `width`, `maskClosable`, `open`, `onOpenChange`, `footer`, `styles` / `classNames` (keys: `backdrop`, `popup`, `header`, `title`, `close`, `content`, …).diff --git a/src/components/ImperativeModal/index.test.tsx b/src/components/ImperativeModal/index.test.tsxindex 9945327d0d8..6a304b6e5fd 100644--- a/src/components/ImperativeModal/index.test.tsx+++ b/src/components/ImperativeModal/index.test.tsx@@ -1,6 +1,6 @@import { Input, MotionProvider } from '@lobehub/ui';import { ModalHost } from '@lobehub/ui/base-ui';-import { render, screen } from '@testing-library/react';+import { act, render, screen } from '@testing-library/react';import { motion } from 'motion/react';import { useState } from 'react';import { describe, expect, it } from 'vitest';@@ -8,11 +8,11 @@ import { describe, expect, it } from 'vitest';import ImperativeModal from '.';/** A modal whose input is controlled by state living in the CALLER's tree. */-const Harness = () => {+const Harness = ({ open = true }: { open?: boolean }) => {const [value, setValue] = useState('');return (<MotionProvider motion={motion}>- <ImperativeModal destroyOnHidden open title={'title'}>+ <ImperativeModal open={open} title={'title'}><InputautoFocusdata-testid={'field'}@@ -79,4 +79,19 @@ describe('ImperativeModal', () => {expect(writes).toEqual([]);expect(field.value).toBe('lala');});++ it('keeps the body mounted while the modal plays its exit animation', async () => {+ // Regression: children used to unmount in the same commit that flipped+ // `open` to false, so the panel went blank and snapped to header height for+ // the whole exit transition.+ const { rerender } = render(<Harness />);++ await screen.findByTestId('field');++ await act(async () => {+ rerender(<Harness open={false} />);+ });++ expect(screen.queryByTestId('field')).not.toBeNull();+ });});diff --git a/src/components/ImperativeModal/index.tsx b/src/components/ImperativeModal/index.tsxindex d53038c5983..9e6f3827eba 100644--- a/src/components/ImperativeModal/index.tsx+++ b/src/components/ImperativeModal/index.tsx@@ -51,7 +51,6 @@ export interface ImperativeModalProps extends Omit<classNames?: LegacyModalClassNames;closable?: boolean;confirmLoading?: boolean;- destroyOnHidden?: boolean;footer?: ReactNode;height?: number | string;keyboard?: boolean;@@ -85,7 +84,6 @@ const ImperativeModal = ({className,classNames,confirmLoading,- destroyOnHidden,footer,loading,okButtonProps,@@ -98,7 +96,6 @@ const ImperativeModal = ({}: ImperativeModalProps) => {const { t } = useTranslation('common');const modalRef = useRef<ModalInstance>(undefined);- const canRenderContent = open || !destroyOnHidden;// `createModal` renders into its own host tree, so handing `children` over as// modal content would put them in a tree that only learns about caller state@@ -159,7 +156,7 @@ const ImperativeModal = ({const modalProps = {...rest,classNames: normalizeClassNames(className, classNames),- content: canRenderContent ? contentSlot : null,+ content: contentSlot,footer: modalFooter,loading,onOpenChange: (nextOpen: boolean) => {@@ -179,7 +176,6 @@ const ImperativeModal = ({afterOpenChange?.(true);}, [afterOpenChange,- canRenderContent,contentSlot,className,classNames,@@ -198,7 +194,10 @@ const ImperativeModal = ({};}, []);- if (!contentHost || !canRenderContent) return null;+ // The slot unmounts only after the exit animation completes, so the children+ // stay mounted through it — unmounting on `open: false` would blank the panel+ // mid-animation and read as the body collapsing.+ if (!contentHost) return null;return createPortal(children, contentHost);};diff --git a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx b/src/features/Conversation/ChatItem/components/MessageContent/index.tsxindex 5c18506d89c..26f19163111 100644--- a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx+++ b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx@@ -1,7 +1,8 @@import { Flexbox } from '@lobehub/ui';+import { type ModalInstance } from '@lobehub/ui/base-ui';import { createStaticStyles, cx } from 'antd-style';import { type ReactNode } from 'react';-import { memo, Suspense, useCallback } from 'react';+import { memo, useCallback, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';import {@@ -9,16 +10,11 @@ import {messageStateSelectors,useConversationStore,} from '@/features/Conversation/store';+import { openEditorModal } from '@/features/EditorModal';import { usePermission } from '@/hooks/usePermission';-import dynamic from '@/libs/next/dynamic';import { type ChatItemProps } from '../../type';-const EditorModal = dynamic(- () => import('@/features/EditorModal').then((mode) => mode.EditorModal),- { ssr: false },-);-export const MSG_CONTENT_CLASSNAME = 'msg_content_flag';export const styles = createStaticStyles(({ css, cssVar }) => {@@ -101,48 +97,53 @@ const MessageContent = memo<MessageContentProps>([canEdit, id, toggleMessageEditing],);+ // Held in a ref rather than in the effect's deps: the editor snapshots the+ // message when it opens, so a re-render (a streaming token, a permission+ // refresh) must not tear down and reopen a modal the user is typing in.+ const openEditorRef = useRef<() => ModalInstance>(undefined);+ openEditorRef.current = () =>+ openEditorModal({+ editorData,+ okText: shouldSendOnConfirm ? t('send') : t('save'),+ value: message ? String(message) : '',+ onClose: () => onEditingChange(false),+ onConfirm: async (value, newEditorData) => {+ if (!canEdit) return;+ onEditingChange(false);+ // updateMessageContent does an optimistic state update synchronously before+ // awaiting the DB round trip. Kick off regenerate in parallel so the old+ // assistant reply is replaced by switchMessageBranch without waiting for persistence.+ const save = updateMessageContent(id, value, {+ editorData: newEditorData as Record<string, any> | undefined,+ });+ if (canCreate && shouldSendOnConfirm) {+ await regenerateUserMessage(id);+ }+ await save;+ },+ });++ useEffect(() => {+ if (!editing) return;+ const instance = openEditorRef.current!();+ return () => instance.close();+ }, [editing]);+return (- <>- <Flexbox- gap={16}- className={cx(- MSG_CONTENT_CLASSNAME,- styles.message,- variant === 'bubble' && styles.bubble,- disabled && styles.disabled,- className,- )}- onDoubleClick={onDoubleClick}- >- {children || message}- {messageExtra}- </Flexbox>- <Suspense fallback={null}>- {editing && (- <EditorModal- editorData={editorData}- okText={shouldSendOnConfirm ? t('send') : t('save')}- open={editing}- value={message ? String(message) : ''}- onCancel={() => onEditingChange(false)}- onConfirm={async (value, newEditorData) => {- if (!canEdit) return;- onEditingChange(false);- // updateMessageContent does an optimistic state update synchronously before- // awaiting the DB round trip. Kick off regenerate in parallel so the old- // assistant reply is replaced by switchMessageBranch without waiting for persistence.- const save = updateMessageContent(id, value, {- editorData: newEditorData as Record<string, any> | undefined,- });- if (canCreate && shouldSendOnConfirm) {- await regenerateUserMessage(id);- }- await save;- }}- />- )}- </Suspense>- </>+ <Flexbox+ gap={16}+ className={cx(+ MSG_CONTENT_CLASSNAME,+ styles.message,+ variant === 'bubble' && styles.bubble,+ disabled && styles.disabled,+ className,+ )}+ onDoubleClick={onDoubleClick}+ >+ {children || message}+ {messageExtra}+ </Flexbox>);},);diff --git a/src/features/Conversation/MessageForward/ForwardModal.tsx b/src/features/Conversation/MessageForward/ForwardModal.tsxindex 59a975e26b7..7bc8cbe2950 100644--- a/src/features/Conversation/MessageForward/ForwardModal.tsx+++ b/src/features/Conversation/MessageForward/ForwardModal.tsx@@ -1,20 +1,20 @@'use client';-import { agentDisplayName } from '@lobechat/types';+import { agentDisplayName, type StoreApiWithSelector } from '@lobechat/types';import { Flexbox, SearchBar, Text, TextArea } from '@lobehub/ui';-import { Button } from '@lobehub/ui/base-ui';+import { Button, createModal, useModalContext } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import isEqual from 'fast-deep-equal';+import { t as translate } from 'i18next';import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import { useFetchAgentList } from '@/hooks/useFetchAgentList';import AgentAvatar from '@/routes/(main)/home/_layout/Body/Agent/List/AgentItem/Avatar';import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/selectors';-import { contextSelectors, useConversationStore } from '../store';+import { contextSelectors, type ConversationStore, Provider, useConversationStore } from '../store';import SelectCircle from './SelectCircle';import { type ForwardTarget, useForwardMessages } from './useForwardMessages';@@ -86,13 +86,9 @@ const styles = createStaticStyles(({ css }) => ({`,}));-interface ForwardModalProps {- onClose: () => void;- open: boolean;-}--const ForwardModal = memo<ForwardModalProps>(({ open, onClose }) => {+const ForwardModalContent = memo(() => {const { t } = useTranslation('chat');+ const { close } = useModalContext();const [keyword, setKeyword] = useState('');const [selectedIds, setSelectedIds] = useState<string[]>([]);const [note, setNote] = useState('');@@ -135,120 +131,129 @@ const ForwardModal = memo<ForwardModalProps>(({ open, onClose }) => {const toggle = (id: string) =>setSelectedIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));- const handleClose = () => {- setSelectedIds([]);- setKeyword('');- setNote('');- onClose();- };-const handleForward = () => {const targets: ForwardTarget[] = selectedAgents.map((a) => ({ id: a.id, title: a.title }));if (targets.length === 0) return;forwardMessages(targets, note);- handleClose();+ close();};const avatarOf = (avatar: unknown) => (typeof avatar === 'string' ? avatar : undefined);return (- <ImperativeModal- destroyOnHidden- footer={null}- open={open}- title={t('messageForward.modal.title')}- width={760}- onCancel={handleClose}- >- <Flexbox horizontal className={styles.body} gap={16}>- {/* Left: searchable multi-select agent list */}- <Flexbox flex={1} gap={8} style={{ minWidth: 0 }}>- <SearchBar- allowClear- placeholder={t('messageForward.modal.searchPlaceholder')}- value={keyword}- onChange={(e) => setKeyword(e.target.value)}- />- <Flexbox className={styles.list} gap={4}>- {candidates.length === 0 ? (- <Flexbox align={'center'} justify={'center'} padding={24}>- <Text type={'secondary'}>{t('messageForward.modal.empty')}</Text>- </Flexbox>- ) : (- candidates.map((agent) => {- const checked = selectedIds.includes(agent.id);- return (- <Flexbox- horizontal- align={'center'}- className={cx(styles.row, checked && styles.rowSelected)}- gap={8}- key={agent.id}- onClick={() => toggle(agent.id)}- >- <SelectCircle checked={checked} />- <AgentAvatar avatar={avatarOf(agent.avatar)} />- <Text ellipsis style={{ flex: 1 }}>- {agentDisplayName(agent, t('untitledAgent'))}- </Text>- </Flexbox>- );- })- )}- </Flexbox>+ <Flexbox horizontal className={styles.body} gap={16}>+ {/* Left: searchable multi-select agent list */}+ <Flexbox flex={1} gap={8} style={{ minWidth: 0 }}>+ <SearchBar+ allowClear+ placeholder={t('messageForward.modal.searchPlaceholder')}+ value={keyword}+ onChange={(e) => setKeyword(e.target.value)}+ />+ <Flexbox className={styles.list} gap={4}>+ {candidates.length === 0 ? (+ <Flexbox align={'center'} justify={'center'} padding={24}>+ <Text type={'secondary'}>{t('messageForward.modal.empty')}</Text>+ </Flexbox>+ ) : (+ candidates.map((agent) => {+ const checked = selectedIds.includes(agent.id);+ return (+ <Flexbox+ horizontal+ align={'center'}+ className={cx(styles.row, checked && styles.rowSelected)}+ gap={8}+ key={agent.id}+ onClick={() => toggle(agent.id)}+ >+ <SelectCircle checked={checked} />+ <AgentAvatar avatar={avatarOf(agent.avatar)} />+ <Text ellipsis style={{ flex: 1 }}>+ {agentDisplayName(agent, t('untitledAgent'))}+ </Text>+ </Flexbox>+ );+ })+ )}</Flexbox>+ </Flexbox>- <div className={styles.divider} />-- {/* Right: forwarded content preview + note */}- <Flexbox flex={1} gap={8} style={{ minWidth: 0 }}>- <Text style={{ fontSize: 12 }} type={'secondary'}>- {t('messageForward.transcript.header', { count: preview.count })}- </Text>- <Flexbox className={styles.preview} flex={1}>- <Flexbox className={styles.previewLines} flex={1} gap={4}>- {preview.lines.map((line, i) => (- <div className={styles.previewLine} key={i}>- <Text strong style={{ fontSize: 12 }}>- {line.role}:- </Text>{' '}- {line.text}- </div>- ))}- {preview.count > preview.lines.length && (- <div className={styles.previewMore}>- {t('messageForward.modal.moreMessages', {- count: preview.count - preview.lines.length,- })}- </div>- )}- </Flexbox>- <div className={styles.noteDivider} />- <TextArea- autoSize={{ maxRows: 4, minRows: 2 }}- className={styles.note}- placeholder={t('messageForward.modal.notePlaceholder')}- resize={false}- value={note}- variant={'borderless'}- onChange={(e) => setNote(e.target.value)}- />- </Flexbox>+ <div className={styles.divider} />- <Flexbox horizontal gap={8} justify={'flex-end'}>- <Button onClick={handleClose}>{t('messageForward.bar.cancel')}</Button>- <Button disabled={selectedIds.length === 0} type={'primary'} onClick={handleForward}>- {selectedIds.length > 0- ? t('messageForward.modal.sendCount', { count: selectedIds.length })- : t('messageForward.bar.forward')}- </Button>+ {/* Right: forwarded content preview + note */}+ <Flexbox flex={1} gap={8} style={{ minWidth: 0 }}>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('messageForward.transcript.header', { count: preview.count })}+ </Text>+ <Flexbox className={styles.preview} flex={1}>+ <Flexbox className={styles.previewLines} flex={1} gap={4}>+ {preview.lines.map((line, i) => (+ <div className={styles.previewLine} key={i}>+ <Text strong style={{ fontSize: 12 }}>+ {line.role}:+ </Text>{' '}+ {line.text}+ </div>+ ))}+ {preview.count > preview.lines.length && (+ <div className={styles.previewMore}>+ {t('messageForward.modal.moreMessages', {+ count: preview.count - preview.lines.length,+ })}+ </div>+ )}</Flexbox>+ <div className={styles.noteDivider} />+ <TextArea+ autoSize={{ maxRows: 4, minRows: 2 }}+ className={styles.note}+ placeholder={t('messageForward.modal.notePlaceholder')}+ resize={false}+ value={note}+ variant={'borderless'}+ onChange={(e) => setNote(e.target.value)}+ />+ </Flexbox>++ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button onClick={close}>{t('messageForward.bar.cancel')}</Button>+ <Button disabled={selectedIds.length === 0} type={'primary'} onClick={handleForward}>+ {selectedIds.length > 0+ ? t('messageForward.modal.sendCount', { count: selectedIds.length })+ : t('messageForward.bar.forward')}+ </Button></Flexbox></Flexbox>- </ImperativeModal>+ </Flexbox>);});-ForwardModal.displayName = 'ForwardModal';+ForwardModalContent.displayName = 'ForwardModalContent';++interface OpenForwardModalOptions {+ /**+ * The conversation store is context-scoped, and the modal renders in the+ * global `ModalHost` tree — hand the live store api back so selection state+ * and `exitSelectionMode` stay wired to the conversation that opened it.+ */+ createConversationStore: () => StoreApiWithSelector<ConversationStore>;+ onClosed?: () => void;+}-export default ForwardModal;+export const openForwardModal = ({ createConversationStore, onClosed }: OpenForwardModalOptions) =>+ createModal({+ content: (+ <Provider createStore={createConversationStore}>+ <ForwardModalContent />+ </Provider>+ ),+ footer: null,+ // NOT `onOpenChange`: that skips `instance.close()`, which is how the+ // in-content Cancel and Forward buttons close this modal.+ onOpenChangeComplete: (open) => {+ if (!open) onClosed?.();+ },+ title: translate('messageForward.modal.title', { ns: 'chat' }),+ width: 760,+ });diff --git a/src/features/Conversation/MessageForward/SelectionFooterBar.tsx b/src/features/Conversation/MessageForward/SelectionFooterBar.tsxindex 92113f5828f..6f3862097c5 100644--- a/src/features/Conversation/MessageForward/SelectionFooterBar.tsx+++ b/src/features/Conversation/MessageForward/SelectionFooterBar.tsx@@ -7,8 +7,8 @@ import { Forward, Trash2, X } from 'lucide-react';import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import { messageStateSelectors, useConversationStore } from '../store';-import ForwardModal from './ForwardModal';+import { messageStateSelectors, useConversationStore, useConversationStoreApi } from '../store';+import { openForwardModal } from './ForwardModal';const styles = createStaticStyles(({ css }) => ({// Full-width bar docked at the bottom in place of the composer (hidden by@@ -42,6 +42,7 @@ const SelectionFooterBar = memo(() => {const { t } = useTranslation('chat');const [forwardOpen, setForwardOpen] = useState(false);+ const storeApi = useConversationStoreApi();const selectedCount = useConversationStore(messageStateSelectors.selectedMessageCount);const selectedMessageIds = useConversationStore((s) => s.selectedMessageIds);const exitSelectionMode = useConversationStore((s) => s.exitSelectionMode);@@ -75,37 +76,42 @@ const SelectionFooterBar = memo(() => {});};+ const handleForward = () => {+ setForwardOpen(true);+ openForwardModal({+ createConversationStore: () => storeApi,+ onClosed: () => setForwardOpen(false),+ });+ };+return (- <>- <Flexbox horizontal align={'center'} className={styles.bar} justify={'center'}>- <Text className={styles.count} type={'secondary'}>- {t('messageForward.bar.selected', { count: selectedCount })}- </Text>- <Flexbox horizontal align={'center'} gap={4}>- <Button icon={<Icon icon={X} />} type={'text'} onClick={exitSelectionMode}>- {t('messageForward.bar.cancel')}- </Button>- <Button- danger- disabled={disabled}- icon={<Icon icon={Trash2} />}- type={'text'}- onClick={handleDelete}- >- {t('messageForward.bar.delete')}- </Button>- <Button- disabled={disabled}- icon={<Icon icon={Forward} />}- type={'text'}- onClick={() => setForwardOpen(true)}- >- {t('messageForward.bar.forward')}- </Button>- </Flexbox>+ <Flexbox horizontal align={'center'} className={styles.bar} justify={'center'}>+ <Text className={styles.count} type={'secondary'}>+ {t('messageForward.bar.selected', { count: selectedCount })}+ </Text>+ <Flexbox horizontal align={'center'} gap={4}>+ <Button icon={<Icon icon={X} />} type={'text'} onClick={exitSelectionMode}>+ {t('messageForward.bar.cancel')}+ </Button>+ <Button+ danger+ disabled={disabled}+ icon={<Icon icon={Trash2} />}+ type={'text'}+ onClick={handleDelete}+ >+ {t('messageForward.bar.delete')}+ </Button>+ <Button+ disabled={disabled}+ icon={<Icon icon={Forward} />}+ type={'text'}+ onClick={handleForward}+ >+ {t('messageForward.bar.forward')}+ </Button></Flexbox>- <ForwardModal open={forwardOpen} onClose={() => setForwardOpen(false)} />- </>+ </Flexbox>);});diff --git a/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx b/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsxindex 60416b6a20c..849ec8783cd 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx@@ -1,6 +1,6 @@-import { memo } from 'react';+import { memo, useEffect, useRef } from 'react';-import { EditorModal } from '@/features/EditorModal';+import { openEditorModal } from '@/features/EditorModal';import { useConversationStore } from '../../../store';@@ -16,21 +16,29 @@ const EditState = memo<EditStateProps>(({ id, content, editorData }) => {s.modifyMessageContent,]);- return (- <EditorModal- editorData={editorData}- open={!!id}- value={content ? String(content) : ''}- onCancel={() => {- toggleMessageEditing(id, false);- }}- onConfirm={async (value, newEditorData) => {+ // Held in a ref rather than in the effect's deps: the editor snapshots the+ // message when it opens, so a re-render of the streaming group must not tear+ // down and reopen a modal the user is typing in.+ const openEditorRef = useRef<() => ReturnType<typeof openEditorModal>>(undefined);+ openEditorRef.current = () =>+ openEditorModal({+ editorData,+ value: content ? String(content) : '',+ onClose: () => toggleMessageEditing(id, false),+ onConfirm: async (value, newEditorData) => {if (!id) return;await updateMessageContent(id, value, newEditorData as Record<string, any> | undefined);toggleMessageEditing(id, false);- }}- />- );+ },+ });++ useEffect(() => {+ if (!id) return;+ const instance = openEditorRef.current!();+ return () => instance.close();+ }, [id]);++ return null;});export default EditState;diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsxindex 37f237303cb..68ffbef05fc 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx@@ -1,10 +1,10 @@-import { confirmModal, toast } from '@lobehub/ui/base-ui';+import { confirmModal, createModal, toast } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';+import { t as translate } from 'i18next';import { EyeIcon, PencilIcon, Trash2Icon } from 'lucide-react';-import { lazy, memo, Suspense, useMemo, useState } from 'react';+import { lazy, memo, Suspense, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';import {openRenameSkillModal,@@ -19,6 +19,19 @@ import { agentSkillsSelectors } from '@/store/tool/selectors';const AgentSkillDetail = lazy(() => import('@/features/AgentSkillDetail'));+const openSkillDetailModal = (skillId: string) =>+ createModal({+ content: (+ <Suspense fallback={<div style={{ height: '100%' }} />}>+ <AgentSkillDetail skillId={skillId} />+ </Suspense>+ ),+ footer: null,+ styles: { content: { height: 'calc(100dvh - 200px)', overflow: 'hidden', padding: 0 } },+ title: translate('workingPanel.skills.detail.title', { ns: 'chat' }),+ width: 960,+ });+/*** Reads user-installed skills (entries in the `agent_skill` table — market* imports plus user-created customs) into the `SkillsList` row shape. Builtin@@ -67,7 +80,6 @@ const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader }) => {const updateAgentSkill = useToolStore((s) => s.updateAgentSkill);const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);const { allowed: canEdit } = usePermission('edit_own_content');- const [detailSkillId, setDetailSkillId] = useState<string>();const getRowActions = (item: SkillListItem): SkillRowAction[] => {const skill = agentSkills.find((s) => s.identifier === item.id);@@ -78,7 +90,7 @@ const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader }) => {icon: EyeIcon,key: 'view',label: t('workingPanel.skills.actions.view'),- onClick: () => setDetailSkillId(skill.id),+ onClick: () => openSkillDetailModal(skill.id),sfSymbol: 'eye',},];@@ -149,7 +161,7 @@ const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader }) => {items={items}onOpenSkill={(item) => {const skill = agentSkills.find((s) => s.identifier === item.id);- if (skill) setDetailSkillId(skill.id);+ if (skill) openSkillDetailModal(skill.id);}}onSkillDragStart={(item, event) => {startSkillDrag(event, {@@ -161,42 +173,17 @@ const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader }) => {/>);- const detailModal = (- <ImperativeModal- destroyOnHidden- footer={null}- open={!!detailSkillId}- styles={{ body: { height: 'calc(100dvh - 200px)', overflow: 'hidden', padding: 0 } }}- title={t('workingPanel.skills.detail.title')}- width={960}- onCancel={() => setDetailSkillId(undefined)}- >- <Suspense fallback={<div style={{ height: '100%' }} />}>- {detailSkillId && <AgentSkillDetail skillId={detailSkillId} />}- </Suspense>- </ImperativeModal>- );-- if (hideHeader)- return (- <>- {list}- {detailModal}- </>- );+ if (hideHeader) return list;return (- <>- <SkillSection- sectionHeader={{- count: items.length,- title: t('workingPanel.skills.section.user'),- }}- >- {list}- </SkillSection>- {detailModal}- </>+ <SkillSection+ sectionHeader={{+ count: items.length,+ title: t('workingPanel.skills.section.user'),+ }}+ >+ {list}+ </SkillSection>);});diff --git a/src/features/EditorModal/EditorModalContent.tsx b/src/features/EditorModal/EditorModalContent.tsxnew file mode 100644index 00000000000..63b60ae67ef--- /dev/null+++ b/src/features/EditorModal/EditorModalContent.tsx@@ -0,0 +1,26 @@+import { useEditor } from '@lobehub/editor/react';+import { memo, useEffect } from 'react';++import EditorCanvas from './EditorCanvas';+import type { EditorBridge } from './type';++interface EditorModalContentProps {+ editorBridge: EditorBridge;+ editorData?: unknown;+ value?: string;+}++const EditorModalContent = memo<EditorModalContentProps>(({ editorBridge, editorData, value }) => {+ const editor = useEditor();++ useEffect(() => {+ editorBridge.current = editor;+ editorBridge.notifyReady?.();+ }, [editor, editorBridge]);++ return <EditorCanvas defaultValue={value} editor={editor} editorData={editorData} />;+});++EditorModalContent.displayName = 'EditorModalContent';++export default EditorModalContent;diff --git a/src/features/EditorModal/index.test.ts b/src/features/EditorModal/index.test.tsnew file mode 100644index 00000000000..a1022c0324b--- /dev/null+++ b/src/features/EditorModal/index.test.ts@@ -0,0 +1,46 @@+import { createModal } from '@lobehub/ui/base-ui';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { openEditorModal } from '.';++vi.mock('@lobehub/ui/base-ui', () => ({+ Button: () => null,+ createModal: vi.fn(() => ({ close: vi.fn(), destroy: vi.fn(), update: vi.fn() })),+ ModalFooter: () => null,+ useModalContext: () => ({ close: vi.fn() }),+}));++vi.mock('./EditorModalContent', () => ({ default: () => null }));++const lastModalProps = () => vi.mocked(createModal).mock.calls.at(-1)![0] as Record<string, any>;++describe('openEditorModal', () => {+ beforeEach(() => {+ vi.mocked(createModal).mockClear();+ });++ it('runs the caller cleanup on any close, not only user dismissal', () => {+ // Regression: `onOpenChange` fires only for Escape / backdrop / the header+ // close button. The footer's Cancel goes through the instance's `close()`,+ // which just flips the stack entry — so wiring cleanup to `onOpenChange`+ // left the caller's editing flag set and the editor could never reopen.+ const onClose = vi.fn();+ openEditorModal({ onClose, value: 'original' });++ const props = lastModalProps();+ expect(props.onOpenChange).toBeUndefined();+ expect(typeof props.onOpenChangeComplete).toBe('function');++ props.onOpenChangeComplete(true);+ expect(onClose).not.toHaveBeenCalled();++ props.onOpenChangeComplete(false);+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('tolerates a caller that passes no cleanup', () => {+ openEditorModal({ value: 'original' });++ expect(() => lastModalProps().onOpenChangeComplete(false)).not.toThrow();+ });+});diff --git a/src/features/EditorModal/index.tsx b/src/features/EditorModal/index.tsxindex c58551a0778..3385ca66cd5 100644--- a/src/features/EditorModal/index.tsx+++ b/src/features/EditorModal/index.tsx@@ -1,49 +1,89 @@-import { useEditor } from '@lobehub/editor/react';-import { memo, useState } from 'react';+import { Button, createModal, ModalFooter, useModalContext } from '@lobehub/ui/base-ui';+import { lazy, memo, type ReactNode, Suspense, useState } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal, { type ImperativeModalProps } from '@/components/ImperativeModal';+import type { EditorBridge } from './type';+import { useEditorBridgeReady } from './useEditorBridgeReady';-import EditorCanvas from './EditorCanvas';+// The editor package is heavy and this module is imported statically by hot+// paths (every chat message row), so the half that pulls it in stays lazy.+const EditorModalContent = lazy(() => import('./EditorModalContent'));-interface EditorModalProps extends ImperativeModalProps {+interface EditorModalFooterProps {+ editorBridge: EditorBridge;+ okText?: ReactNode;+ onConfirm?: (value: string, editorData?: unknown) => Promise<void>;+}++const EditorModalFooter = memo<EditorModalFooterProps>(({ editorBridge, okText, onConfirm }) => {+ const { t } = useTranslation('common');+ const { close } = useModalContext();+ const [confirmLoading, setConfirmLoading] = useState(false);+ const ready = useEditorBridgeReady(editorBridge);++ const handleConfirm = async () => {+ const editor = editorBridge.current;+ // Saving before the lazy content mounted would read an empty document and+ // overwrite the caller's value with ''.+ if (!editor) return;++ setConfirmLoading(true);+ try {+ const finalValue = (editor.getDocument('markdown') as unknown as string) || '';+ const editorData = editor.getDocument('json');+ await onConfirm?.(finalValue, editorData);+ close();+ } finally {+ setConfirmLoading(false);+ }+ };++ return (+ <ModalFooter>+ <Button onClick={close}>{t('cancel')}</Button>+ <Button disabled={!ready} loading={confirmLoading} type={'primary'} onClick={handleConfirm}>+ {okText ?? t('ok', { defaultValue: 'OK' })}+ </Button>+ </ModalFooter>+ );+});++EditorModalFooter.displayName = 'EditorModalFooter';++export interface OpenEditorModalOptions {editorData?: unknown;+ okText?: ReactNode;+ /** Runs whenever the modal closes, including confirm — clear caller-side editing flags here. */+ onClose?: () => void;onConfirm?: (value: string, editorData?: unknown) => Promise<void>;value?: string;}-export const EditorModal = memo<EditorModalProps>(- ({ value, editorData: initialEditorData, onConfirm, ...rest }) => {- const [confirmLoading, setConfirmLoading] = useState(false);- const { t } = useTranslation('common');- const editor = useEditor();-- return (- <ImperativeModal- destroyOnHidden- cancelText={t('cancel')}- closable={false}- confirmLoading={confirmLoading}- okText={t('ok')}- title={null}- width={'min(90vw, 920px)'}- styles={{- body: {- overflow: 'hidden',- padding: 0,- },- }}- onOk={async () => {- setConfirmLoading(true);- const finalValue = (editor?.getDocument('markdown') as unknown as string) || '';- const editorData = editor?.getDocument('json');- await onConfirm?.(finalValue, editorData);- setConfirmLoading(false);- }}- {...rest}- >- <EditorCanvas defaultValue={value} editor={editor} editorData={initialEditorData} />- </ImperativeModal>- );- },-);+export const openEditorModal = ({+ editorData,+ okText,+ onClose,+ onConfirm,+ value,+}: OpenEditorModalOptions) => {+ const editorBridge: EditorBridge = {};++ return createModal({+ content: (+ <Suspense fallback={<div style={{ minHeight: '50vh' }} />}>+ <EditorModalContent editorBridge={editorBridge} editorData={editorData} value={value} />+ </Suspense>+ ),+ footer: <EditorModalFooter editorBridge={editorBridge} okText={okText} onConfirm={onConfirm} />,+ // NOT `onOpenChange`: that only fires for user dismissal, while the footer's+ // Cancel goes through `instance.close()`. Cancelling would then leave the+ // caller's editing flag set and the editor could never be reopened.+ // `createModal` only ever completes with `false`, but the open flag is+ // honored so this does not depend on that renderer detail.+ onOpenChangeComplete: (open) => {+ if (!open) onClose?.();+ },+ styles: { content: { overflow: 'hidden', padding: 0 } },+ width: 'min(90vw, 920px)',+ });+};diff --git a/src/features/EditorModal/type.ts b/src/features/EditorModal/type.tsnew file mode 100644index 00000000000..5af8a8ffa98--- /dev/null+++ b/src/features/EditorModal/type.ts@@ -0,0 +1,13 @@+import type { IEditor } from '@lobehub/editor';++/**+ * The editor instance is created by the lazily-loaded content half but read by+ * the footer, and the two are siblings in the modal tree — hence a plain object+ * rather than context. `notifyReady` lets the footer keep Save disabled until+ * the document exists; without it a click during the chunk load would read an+ * empty document and save it over the caller's content.+ */+export interface EditorBridge {+ current?: IEditor;+ notifyReady?: () => void;+}diff --git a/src/features/EditorModal/useEditorBridgeReady.test.ts b/src/features/EditorModal/useEditorBridgeReady.test.tsnew file mode 100644index 00000000000..1514762faa4--- /dev/null+++ b/src/features/EditorModal/useEditorBridgeReady.test.ts@@ -0,0 +1,45 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import type { EditorBridge } from './type';+import { useEditorBridgeReady } from './useEditorBridgeReady';++describe('useEditorBridgeReady', () => {+ it('reports not ready while the lazy content has not produced an editor', () => {+ // Regression: the footer stayed interactive during the content chunk load,+ // so a quick Save read a missing editor, fell back to '' and overwrote the+ // caller's value.+ const bridge: EditorBridge = {};+ const { result } = renderHook(() => useEditorBridgeReady(bridge));++ expect(result.current).toBe(false);+ });++ it('flips to ready when the content notifies', () => {+ const bridge: EditorBridge = {};+ const { result } = renderHook(() => useEditorBridgeReady(bridge));++ act(() => {+ bridge.current = {} as EditorBridge['current'];+ bridge.notifyReady?.();+ });++ expect(result.current).toBe(true);+ });++ it('is ready immediately when the editor already exists', () => {+ const bridge: EditorBridge = { current: {} as EditorBridge['current'] };+ const { result } = renderHook(() => useEditorBridgeReady(bridge));++ expect(result.current).toBe(true);+ });++ it('detaches its notifier on unmount so a stale footer cannot be revived', () => {+ const bridge: EditorBridge = {};+ const { unmount } = renderHook(() => useEditorBridgeReady(bridge));++ expect(typeof bridge.notifyReady).toBe('function');+ unmount();+ expect(bridge.notifyReady).toBeUndefined();+ });+});diff --git a/src/features/EditorModal/useEditorBridgeReady.ts b/src/features/EditorModal/useEditorBridgeReady.tsnew file mode 100644index 00000000000..97ac980da34--- /dev/null+++ b/src/features/EditorModal/useEditorBridgeReady.ts@@ -0,0 +1,25 @@+import { useEffect, useState } from 'react';++import type { EditorBridge } from './type';++/**+ * The footer must not act before the lazily-loaded content half has produced an+ * editor: reading a missing one yields an empty document, which the caller then+ * saves over its own value.+ */+export const useEditorBridgeReady = (bridge: EditorBridge) => {+ const [ready, setReady] = useState(() => Boolean(bridge.current));++ useEffect(() => {+ if (bridge.current) {+ setReady(true);+ return;+ }+ bridge.notifyReady = () => setReady(true);+ return () => {+ bridge.notifyReady = undefined;+ };+ }, [bridge]);++ return ready;+};diff --git a/src/features/Portal/Mobile.tsx b/src/features/Portal/Mobile.tsxindex d4e8af89069..2881368458e 100644--- a/src/features/Portal/Mobile.tsx+++ b/src/features/Portal/Mobile.tsx@@ -1,11 +1,11 @@'use client';import { Flexbox } from '@lobehub/ui';+import { Modal } from '@lobehub/ui/base-ui';import { createStaticStyles, cx } from 'antd-style';import { type ReactNode } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import { useChatStore } from '@/store/chat';import { portalThreadSelectors } from '@/store/chat/selectors';@@ -38,10 +38,13 @@ const MobilePortal = () => {);return (- <ImperativeModal+ // Declarative rather than `createModal`: the portal body reaches for route+ // params (`useParams` in its header), and an imperative modal renders in the+ // global ModalHost — above every route match, where those params are empty.+ <ModalallowFullscreen- destroyOnHiddenclassName={cx(isPortalThread && styles.container)}+ draggable={false}footer={null}height={'95%'}open={showMobilePortal}@@ -53,7 +56,7 @@ const MobilePortal = () => {onCancel={() => clearPortalStack()}><PortalContent renderBody={renderBody} />- </ImperativeModal>+ </Modal>);};diff --git a/src/features/SkillStore/SkillList/Community/Item.tsx b/src/features/SkillStore/SkillList/Community/Item.tsxindex 3a5e152f770..805ab3d3715 100644--- a/src/features/SkillStore/SkillList/Community/Item.tsx+++ b/src/features/SkillStore/SkillList/Community/Item.tsx@@ -1,13 +1,13 @@'use client';import { ActionIcon, Block, DropdownMenu, Flexbox, Icon, stopPropagation } from '@lobehub/ui';-import { Button, confirmModal } from '@lobehub/ui/base-ui';+import { Button, confirmModal, createModal } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';+import { t as translate } from 'i18next';import { MoreVerticalIcon, Plus, Trash2 } from 'lucide-react';-import React, { memo, Suspense, useState } from 'react';+import React, { memo, Suspense } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import MCPTag from '@/components/Plugins/MCPTag';import PluginAvatar from '@/components/Plugins/PluginAvatar';import McpDetail from '@/features/MCP/MCPDetail';@@ -23,10 +23,21 @@ import { type DiscoverMcpItem } from '@/types/discover';import { itemStyles } from '../style';+const openSkillDetailModal = (identifier: string) =>+ createModal({+ content: (+ <Suspense fallback={<McpDetailLoading />}>+ <McpDetail noSettings identifier={identifier} />+ </Suspense>+ ),+ footer: null,+ title: translate('dev.title.skillDetails', { ns: 'plugin' }),+ width: 800,+ });+const Item = memo<DiscoverMcpItem>(({ name, description, icon, identifier }) => {const styles = itemStyles;const { t } = useTranslation('plugin');- const [detailOpen, setDetailOpen] = useState(false);const { allowed: canCreate } = usePermission('create_content');const { allowed: canEdit } = usePermission('edit_own_content');@@ -127,49 +138,35 @@ const Item = memo<DiscoverMcpItem>(({ name, description, icon, identifier }) =>};return (- <>- <Flexbox className={styles.container} gap={0}>- <Block- clickable- horizontal- align={'center'}- gap={12}- paddingBlock={12}- paddingInline={12}- style={{ cursor: 'pointer' }}- variant={'outlined'}- onClick={() => setDetailOpen(true)}- >- <PluginAvatar avatar={icon} size={40} />- <Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>- <Flexbox horizontal align="center" gap={8}>- <span className={styles.title}>{name}</span>- <MCPTag showText={false} />- </Flexbox>- {description && <span className={styles.description}>{description}</span>}- </Flexbox>- <div onClick={stopPropagation}>{renderAction()}</div>- </Block>-- {!!installProgress && (- <Flexbox paddingInline={12}>- <MCPInstallProgress identifier={identifier} />- </Flexbox>- )}- </Flexbox>- <ImperativeModal- destroyOnHidden- footer={null}- open={detailOpen}- title={t('dev.title.skillDetails')}- width={800}- onCancel={() => setDetailOpen(false)}+ <Flexbox className={styles.container} gap={0}>+ <Block+ clickable+ horizontal+ align={'center'}+ gap={12}+ paddingBlock={12}+ paddingInline={12}+ style={{ cursor: 'pointer' }}+ variant={'outlined'}+ onClick={() => openSkillDetailModal(identifier)}>- <Suspense fallback={<McpDetailLoading />}>- <McpDetail noSettings identifier={identifier} />- </Suspense>- </ImperativeModal>- </>+ <PluginAvatar avatar={icon} size={40} />+ <Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>+ <Flexbox horizontal align="center" gap={8}>+ <span className={styles.title}>{name}</span>+ <MCPTag showText={false} />+ </Flexbox>+ {description && <span className={styles.description}>{description}</span>}+ </Flexbox>+ <div onClick={stopPropagation}>{renderAction()}</div>+ </Block>++ {!!installProgress && (+ <Flexbox paddingInline={12}>+ <MCPInstallProgress identifier={identifier} />+ </Flexbox>+ )}+ </Flexbox>);});diff --git a/src/features/SkillStore/SkillList/Community/MarketSkillItem.tsx b/src/features/SkillStore/SkillList/Community/MarketSkillItem.tsxindex 7bc86937f3f..9a589121182 100644--- a/src/features/SkillStore/SkillList/Community/MarketSkillItem.tsx+++ b/src/features/SkillStore/SkillList/Community/MarketSkillItem.tsx@@ -1,14 +1,14 @@'use client';import { ActionIcon, Avatar, Block, DropdownMenu, Flexbox, Icon, Tag } from '@lobehub/ui';-import { confirmModal } from '@lobehub/ui/base-ui';+import { confirmModal, createModal } from '@lobehub/ui/base-ui';import { SkillsIcon } from '@lobehub/ui/icons';import { createStaticStyles, cssVar } from 'antd-style';+import { t as translate } from 'i18next';import { DownloadIcon, Loader2, MoreVerticalIcon, Plus, Trash2 } from 'lucide-react';import { lazy, memo, Suspense, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import { usePermission } from '@/hooks/usePermission';import { agentSkillService } from '@/services/skill';import { useToolStore } from '@/store/tool';@@ -38,10 +38,22 @@ const styles = createStaticStyles(({ css }) => ({`,}));+const openMarketSkillDetailModal = (identifier: string) =>+ createModal({+ content: (+ <Suspense fallback={<div style={{ height: '100%' }} />}>+ <MarketSkillDetail identifier={identifier} />+ </Suspense>+ ),+ footer: null,+ styles: { content: { height: 'calc(100dvh - 200px)', overflow: 'hidden', padding: 0 } },+ title: translate('dev.title.skillDetails', { ns: 'plugin' }),+ width: 960,+ });+const MarketSkillItem = memo<DiscoverSkillItem>(({ name, icon, description, identifier }) => {const { t } = useTranslation('plugin');const { t: tc } = useTranslation('common');- const [detailOpen, setDetailOpen] = useState(false);const [installing, setInstalling] = useState(false);const [loading, setLoading] = useState(false);const { allowed: canCreate } = usePermission('create_content');@@ -140,43 +152,28 @@ const MarketSkillItem = memo<DiscoverSkillItem>(({ name, icon, description, iden};return (- <>- <Flexbox className={itemStyles.container} gap={0}>- <Block- horizontal- align={'center'}- gap={12}- paddingBlock={12}- paddingInline={12}- variant={'outlined'}- >- <Avatar avatar={icon || name} shape={'square'} size={40} style={{ flex: 'none' }} />- <Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>- <Flexbox horizontal align="center" gap={8}>- <span className={styles.title} onClick={() => setDetailOpen(true)}>- {name}- </span>- <Tag icon={<Icon icon={SkillsIcon} />} size={'small'} />- </Flexbox>- {description && <span className={itemStyles.description}>{description}</span>}- </Flexbox>- {renderAction()}- </Block>- </Flexbox>- <ImperativeModal- destroyOnHidden- footer={null}- open={detailOpen}- styles={{ body: { height: 'calc(100dvh - 200px)', overflow: 'hidden', padding: 0 } }}- title={t('dev.title.skillDetails')}- width={960}- onCancel={() => setDetailOpen(false)}+ <Flexbox className={itemStyles.container} gap={0}>+ <Block+ horizontal+ align={'center'}+ gap={12}+ paddingBlock={12}+ paddingInline={12}+ variant={'outlined'}>- <Suspense fallback={<div style={{ height: '100%' }} />}>- <MarketSkillDetail identifier={identifier} />- </Suspense>- </ImperativeModal>- </>+ <Avatar avatar={icon || name} shape={'square'} size={40} style={{ flex: 'none' }} />+ <Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>+ <Flexbox horizontal align="center" gap={8}>+ <span className={styles.title} onClick={() => openMarketSkillDetailModal(identifier)}>+ {name}+ </span>+ <Tag icon={<Icon icon={SkillsIcon} />} size={'small'} />+ </Flexbox>+ {description && <span className={itemStyles.description}>{description}</span>}+ </Flexbox>+ {renderAction()}+ </Block>+ </Flexbox>);});diff --git a/src/features/WorkspaceSetting/Labels/DeleteLabelModal.tsx b/src/features/WorkspaceSetting/Labels/DeleteLabelModal.tsxindex 0425e5b3a53..2d273308ff2 100644--- a/src/features/WorkspaceSetting/Labels/DeleteLabelModal.tsx+++ b/src/features/WorkspaceSetting/Labels/DeleteLabelModal.tsx@@ -1,19 +1,17 @@import { type AgentLabelListItem } from '@lobechat/types';-import { type ModalProps } from '@lobehub/ui';-import { Flexbox, Input, stopPropagation, Text } from '@lobehub/ui';-import { Button, toast } from '@lobehub/ui/base-ui';-import { memo, useEffect, useState } from 'react';+import { Flexbox, Input, Text } from '@lobehub/ui';+import { Button, createModal, ModalFooter, toast, useModalContext } from '@lobehub/ui/base-ui';+import { t as translate } from 'i18next';+import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import { useHomeStore } from '@/store/home';/** The word the user must type to arm the Delete button (mirrors Linear). */const DELETE_CONFIRM_WORD = 'delete';-interface DeleteLabelModalProps extends Pick<ModalProps, 'open'> {- label?: AgentLabelListItem;- onClose: () => void;+interface DeleteLabelContentProps {+ label: AgentLabelListItem;}/**@@ -21,8 +19,9 @@ interface DeleteLabelModalProps extends Pick<ModalProps, 'open'> {* cannot be undone, so the modal requires typing `delete` and offers Archive* as the reversible alternative (mirrors the Linear flow in the issue spec).*/-const DeleteLabelModal = memo<DeleteLabelModalProps>(({ label, open, onClose }) => {+const DeleteLabelContent = memo<DeleteLabelContentProps>(({ label }) => {const { t } = useTranslation(['setting', 'common']);+ const { close } = useModalContext();const [removeAgentLabel, updateAgentLabel] = useHomeStore((s) => [s.removeAgentLabel,s.updateAgentLabel,@@ -32,21 +31,15 @@ const DeleteLabelModal = memo<DeleteLabelModalProps>(({ label, open, onClose })const [loading, setLoading] = useState(false);const [archiving, setArchiving] = useState(false);- useEffect(() => {- if (open) setConfirmText('');- }, [open]);-- if (!label) return null;-const armed = confirmText.trim().toLowerCase() === DELETE_CONFIRM_WORD;const handleDelete = async () => {- if (!armed) return;+ if (!armed || loading || archiving) return;setLoading(true);try {await removeAgentLabel(label.id);toast.success(t('workspaceSetting.labels.delete.success'));- onClose();+ close();} catch (error) {console.error('Failed to delete label:', error);toast.error(t('operationFailed', { ns: 'common' }));@@ -56,11 +49,12 @@ const DeleteLabelModal = memo<DeleteLabelModalProps>(({ label, open, onClose })};const handleArchive = async () => {+ if (loading || archiving) return;setArchiving(true);try {await updateAgentLabel(label.id, { archived: true });toast.success(t('workspaceSetting.labels.archive.success'));- onClose();+ close();} catch (error) {console.error('Failed to archive label:', error);toast.error(t('operationFailed', { ns: 'common' }));@@ -70,48 +64,48 @@ const DeleteLabelModal = memo<DeleteLabelModalProps>(({ label, open, onClose })};return (- <div onClick={stopPropagation}>- <ImperativeModal- destroyOnHidden- open={open}- title={t('workspaceSetting.labels.delete.title', { name: label.name })}- width={460}- footer={- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} width={'100%'}>- <Button loading={archiving} onClick={handleArchive}>- {t('workspaceSetting.labels.actions.archive')}- </Button>- <Flexbox horizontal gap={8}>- <Button onClick={onClose}>{t('cancel', { ns: 'common' })}</Button>- <Button danger disabled={!armed} loading={loading} onClick={handleDelete}>- {t('delete', { ns: 'common' })}- </Button>- </Flexbox>- </Flexbox>- }- onCancel={onClose}- >- <Flexbox gap={12} paddingBlock={8}>- <Text>- {label.usageCount > 0- ? t('workspaceSetting.labels.delete.descUsed', { count: label.usageCount })- : t('workspaceSetting.labels.delete.desc')}- </Text>- <Text type={'secondary'}>{t('workspaceSetting.labels.delete.archiveHint')}</Text>- <Text>{t('workspaceSetting.labels.delete.confirmHint')}</Text>- <Input- autoFocus- placeholder={DELETE_CONFIRM_WORD}- value={confirmText}- onChange={(e) => setConfirmText(e.target.value)}- onPressEnter={handleDelete}- />+ <>+ <Flexbox gap={12} paddingBlock={8} paddingInline={16}>+ <Text>+ {label.usageCount > 0+ ? t('workspaceSetting.labels.delete.descUsed', { count: label.usageCount })+ : t('workspaceSetting.labels.delete.desc')}+ </Text>+ <Text type={'secondary'}>{t('workspaceSetting.labels.delete.archiveHint')}</Text>+ <Text>{t('workspaceSetting.labels.delete.confirmHint')}</Text>+ <Input+ autoFocus+ disabled={loading || archiving}+ placeholder={DELETE_CONFIRM_WORD}+ value={confirmText}+ onChange={(e) => setConfirmText(e.target.value)}+ onPressEnter={handleDelete}+ />+ </Flexbox>+ {/* Archive and Delete both mutate the same label, so each locks the other+ out — `loading` alone only disables the button that owns it. */}+ <ModalFooter style={{ justifyContent: 'space-between' }}>+ <Button disabled={loading} loading={archiving} onClick={handleArchive}>+ {t('workspaceSetting.labels.actions.archive')}+ </Button>+ <Flexbox horizontal gap={8}>+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>+ <Button danger disabled={!armed || archiving} loading={loading} onClick={handleDelete}>+ {t('delete', { ns: 'common' })}+ </Button></Flexbox>- </ImperativeModal>- </div>+ </ModalFooter>+ </>);});-DeleteLabelModal.displayName = 'DeleteLabelModal';+DeleteLabelContent.displayName = 'DeleteLabelContent';-export default DeleteLabelModal;+export const openDeleteLabelModal = (label: AgentLabelListItem) =>+ createModal({+ content: <DeleteLabelContent label={label} />,+ footer: null,+ styles: { content: { padding: 0 } },+ title: translate('workspaceSetting.labels.delete.title', { name: label.name, ns: 'setting' }),+ width: 460,+ });diff --git a/src/features/WorkspaceSetting/Labels/LabelFormModal.tsx b/src/features/WorkspaceSetting/Labels/LabelFormModal.tsxindex d5a13434db5..ae5eeed0bb2 100644--- a/src/features/WorkspaceSetting/Labels/LabelFormModal.tsx+++ b/src/features/WorkspaceSetting/Labels/LabelFormModal.tsx@@ -1,12 +1,11 @@import { type AgentLabelListItem } from '@lobechat/types';-import { type ModalProps } from '@lobehub/ui';-import { Flexbox, Input, stopPropagation } from '@lobehub/ui';-import { toast } from '@lobehub/ui/base-ui';+import { Flexbox, Input } from '@lobehub/ui';+import { Button, createModal, ModalFooter, toast, useModalContext } from '@lobehub/ui/base-ui';import { createStaticStyles, cx } from 'antd-style';-import { memo, useEffect, useState } from 'react';+import { t as translate } from 'i18next';+import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import { useHomeStore } from '@/store/home';import { DEFAULT_LABEL_COLOR, isValidLabelColor, LABEL_COLOR_PRESETS } from './constants';@@ -32,14 +31,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-interface LabelFormModalProps extends Pick<ModalProps, 'open' | 'onCancel'> {- /** Present when editing; absent when creating. */+export interface LabelFormModalOptions {/*** When creating from an agent's Labels submenu, apply the new label to that* agent right away — creating "for" an agent and then having to reopen the* picker would be surprising.*/assignTo?: { agentId: string; currentLabelIds: string[] };+ /** Present when editing; absent when creating. */label?: AgentLabelListItem;/*** Opened from a failed restore: the label is archived and its old name is@@ -49,133 +48,134 @@ interface LabelFormModalProps extends Pick<ModalProps, 'open' | 'onCancel'> {restoreOnSave?: boolean;}-const LabelFormModal = memo<LabelFormModalProps>(- ({ assignTo, label, open, onCancel, restoreOnSave }) => {- const { t } = useTranslation(['setting', 'common']);- const [createAgentLabel, toggleAgentLabel, updateAgentLabel] = useHomeStore((s) => [- s.createAgentLabel,- s.toggleAgentLabel,- s.updateAgentLabel,- ]);+const LabelFormContent = memo<LabelFormModalOptions>(({ assignTo, label, restoreOnSave }) => {+ const { t } = useTranslation(['setting', 'common']);+ const { close } = useModalContext();+ const [createAgentLabel, toggleAgentLabel, updateAgentLabel] = useHomeStore((s) => [+ s.createAgentLabel,+ s.toggleAgentLabel,+ s.updateAgentLabel,+ ]);- const [name, setName] = useState('');- const [description, setDescription] = useState('');- const [color, setColor] = useState<string>(DEFAULT_LABEL_COLOR);- const [loading, setLoading] = useState(false);+ const [name, setName] = useState(label?.name ?? '');+ const [description, setDescription] = useState(label?.description ?? '');+ const [color, setColor] = useState<string>(label?.color ?? DEFAULT_LABEL_COLOR);+ const [loading, setLoading] = useState(false);- // Reset per open so the form reflects the target label (or a blank create).- useEffect(() => {- if (!open) return;- setName(label?.name ?? '');- setDescription(label?.description ?? '');- setColor(label?.color ?? DEFAULT_LABEL_COLOR);- }, [open, label]);+ const handleSave = async () => {+ const trimmed = name.trim();+ if (!trimmed || loading) return;- return (- <div onClick={stopPropagation}>- <ImperativeModal- destroyOnHidden- okButtonProps={{ disabled: !name.trim() || !isValidLabelColor(color), loading }}- open={open}- width={420}- title={- restoreOnSave- ? t('workspaceSetting.labels.form.restoreTitle')- : label- ? t('workspaceSetting.labels.form.editTitle')- : t('workspaceSetting.labels.form.createTitle')- }- onCancel={onCancel}- onOk={async (e) => {- const trimmed = name.trim();- if (!trimmed) return;+ setLoading(true);+ try {+ if (label) {+ await updateAgentLabel(label.id, {+ ...(restoreOnSave ? { archived: false } : {}),+ color,+ description: description.trim() || null,+ name: trimmed,+ });+ } else {+ const id = await createAgentLabel({+ color,+ description: description.trim() || undefined,+ name: trimmed,+ });+ if (assignTo && id) {+ // Delta, not `[...currentLabelIds, id]`: those ids were captured when+ // the modal opened, so replaying them as a full set would delete+ // anything another editor applied while the user was typing.+ await toggleAgentLabel(assignTo.agentId, id, true);+ }+ }+ close();+ } catch (error) {+ // Keep the modal open on a name clash — the user's next move is to edit+ // the name they already typed, not to start over.+ if (isDuplicateLabelNameError(error)) {+ toast.error(t('workspaceSetting.labels.form.duplicateName'));+ return;+ }+ console.error('Failed to save label:', error);+ toast.error(t('operationFailed', { ns: 'common' }));+ } finally {+ setLoading(false);+ }+ };- setLoading(true);- try {- if (label) {- await updateAgentLabel(label.id, {- ...(restoreOnSave ? { archived: false } : {}),- color,- description: description.trim() || null,- name: trimmed,- });- } else {- const id = await createAgentLabel({- color,- description: description.trim() || undefined,- name: trimmed,- });- if (assignTo && id) {- // Delta, not `[...currentLabelIds, id]`: those ids were- // captured when the modal opened, so replaying them as a full- // set would delete anything another editor applied while the- // user was typing.- await toggleAgentLabel(assignTo.agentId, id, true);- }- }- onCancel?.(e as any);- } catch (error) {- // Keep the modal open on a name clash — the user's next move is to- // edit the name they already typed, not to start over.- if (isDuplicateLabelNameError(error)) {- toast.error(t('workspaceSetting.labels.form.duplicateName'));- return;- }- console.error('Failed to save label:', error);- toast.error(t('operationFailed', { ns: 'common' }));- } finally {- setLoading(false);- }- }}- >- <Flexbox gap={16} paddingBlock={8}>- <Flexbox gap={8}>- <span>{t('workspaceSetting.labels.form.name')}</span>- <Input- autoFocus- maxLength={40}- placeholder={t('workspaceSetting.labels.form.namePlaceholder')}- value={name}- onChange={(e) => setName(e.target.value)}- />- </Flexbox>- <Flexbox gap={8}>- <span>{t('workspaceSetting.labels.form.description')}</span>- <Input- maxLength={200}- placeholder={t('workspaceSetting.labels.form.descriptionPlaceholder')}- value={description}- onChange={(e) => setDescription(e.target.value)}+ return (+ <>+ <Flexbox gap={16} paddingBlock={8} paddingInline={16}>+ <Flexbox gap={8}>+ <span>{t('workspaceSetting.labels.form.name')}</span>+ <Input+ autoFocus+ maxLength={40}+ placeholder={t('workspaceSetting.labels.form.namePlaceholder')}+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ </Flexbox>+ <Flexbox gap={8}>+ <span>{t('workspaceSetting.labels.form.description')}</span>+ <Input+ maxLength={200}+ placeholder={t('workspaceSetting.labels.form.descriptionPlaceholder')}+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ />+ </Flexbox>+ <Flexbox gap={8}>+ <span>{t('workspaceSetting.labels.form.color')}</span>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ {LABEL_COLOR_PRESETS.map((preset) => (+ <span+ aria-label={preset}+ className={cx(styles.swatch, color === preset && styles.swatchActive)}+ key={preset}+ role={'button'}+ style={{ background: preset }}+ onClick={() => setColor(preset)}/>- </Flexbox>- <Flexbox gap={8}>- <span>{t('workspaceSetting.labels.form.color')}</span>- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>- {LABEL_COLOR_PRESETS.map((preset) => (- <span- aria-label={preset}- className={cx(styles.swatch, color === preset && styles.swatchActive)}- key={preset}- role={'button'}- style={{ background: preset }}- onClick={() => setColor(preset)}- />- ))}- <Input- placeholder={'#RRGGBB'}- style={{ width: 100 }}- value={color}- onChange={(e) => setColor(e.target.value)}- />- </Flexbox>- </Flexbox>+ ))}+ <Input+ placeholder={'#RRGGBB'}+ style={{ width: 100 }}+ value={color}+ onChange={(e) => setColor(e.target.value)}+ /></Flexbox>- </ImperativeModal>- </div>- );- },-);+ </Flexbox>+ </Flexbox>+ <ModalFooter>+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>+ <Button+ disabled={!name.trim() || !isValidLabelColor(color)}+ loading={loading}+ type={'primary'}+ onClick={handleSave}+ >+ {t('ok', { defaultValue: 'OK', ns: 'common' })}+ </Button>+ </ModalFooter>+ </>+ );+});-LabelFormModal.displayName = 'LabelFormModal';+LabelFormContent.displayName = 'LabelFormContent';-export default LabelFormModal;+export const openLabelFormModal = (options: LabelFormModalOptions = {}) =>+ createModal({+ content: <LabelFormContent {...options} />,+ footer: null,+ styles: { content: { padding: 0 } },+ title: translate(+ options.restoreOnSave+ ? 'workspaceSetting.labels.form.restoreTitle'+ : options.label+ ? 'workspaceSetting.labels.form.editTitle'+ : 'workspaceSetting.labels.form.createTitle',+ { ns: 'setting' },+ ),+ width: 420,+ });diff --git a/src/features/WorkspaceSetting/Labels/index.tsx b/src/features/WorkspaceSetting/Labels/index.tsxindex 603a09d7315..57df74839ae 100644--- a/src/features/WorkspaceSetting/Labels/index.tsx+++ b/src/features/WorkspaceSetting/Labels/index.tsx@@ -26,9 +26,9 @@ import { usePermission } from '@/hooks/usePermission';import { useHomeStore } from '@/store/home';import { agentLabelSelectors } from '@/store/home/selectors';-import DeleteLabelModal from './DeleteLabelModal';+import { openDeleteLabelModal } from './DeleteLabelModal';import { isDuplicateLabelNameError } from './errors';-import LabelFormModal from './LabelFormModal';+import { openLabelFormModal } from './LabelFormModal';const styles = createStaticStyles(({ css, cssVar }) => ({dot: css`@@ -255,15 +255,6 @@ const WorkspaceLabelsContent = memo(() => {// Linear-style scope filter: the default "workspace" scope lists active// labels; "archived" surfaces archived ones so they can be restored.const [scope, setScope] = useState<'archived' | 'workspace'>('workspace');- const [formModal, setFormModal] = useState<{- label?: AgentLabelListItem;- open: boolean;- restoreOnSave?: boolean;- }>({- open: false,- });- const [deleteTarget, setDeleteTarget] = useState<AgentLabelListItem | undefined>();-const visibleLabels = useMemo(() => {const query = keyword.trim().toLowerCase();const matched = query@@ -278,11 +269,9 @@ const WorkspaceLabelsContent = memo(() => {key={label.id}label={label}manageBlockedReason={manageBlockedReason}- onDelete={setDeleteTarget}- onEdit={(target) => setFormModal({ label: target, open: true })}- onRestoreConflict={(target) =>- setFormModal({ label: target, open: true, restoreOnSave: true })- }+ onDelete={(target) => openDeleteLabelModal(target)}+ onEdit={(target) => openLabelFormModal({ label: target })}+ onRestoreConflict={(target) => openLabelFormModal({ label: target, restoreOnSave: true })}/>);@@ -291,7 +280,7 @@ const WorkspaceLabelsContent = memo(() => {disabled={!canManage}icon={PlusIcon}type={'primary'}- onClick={() => setFormModal({ open: true })}+ onClick={() => openLabelFormModal()}>{t('workspaceSetting.labels.actions.create')}</Button>@@ -364,17 +353,6 @@ const WorkspaceLabelsContent = memo(() => {{visibleLabels.map(renderRow)}</Flexbox>)}- <LabelFormModal- label={formModal.label}- open={formModal.open}- restoreOnSave={formModal.restoreOnSave}- onCancel={() => setFormModal({ open: false })}- />- <DeleteLabelModal- label={deleteTarget}- open={!!deleteTarget}- onClose={() => setDeleteTarget(undefined)}- /></Flexbox>);});diff --git a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.test.tsx b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.test.tsxindex 059c3a86515..7c85d6d406f 100644--- a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.test.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.test.tsx@@ -4,7 +4,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AgentModalProvider, useAgentModal } from './ModalProvider';const mocks = vi.hoisted(() => ({+ closeCreateAgentModal: vi.fn(),createAgent: vi.fn(),+ createAgentModalProps: undefined as+ | {+ onCreateBlank: () => Promise<void> | void;+ onOpenSkills?: (identifier: string) => void;+ }+ | undefined,navigate: vi.fn(),refreshAgentList: vi.fn(),sendAsAgent: vi.fn(),@@ -39,25 +46,17 @@ vi.mock('@/features/EditingPopover', () => ({}));vi.mock('@/routes/(main)/home/_layout/hooks/useCreateModal', () => ({- CreateAgentModal: ({- open,- onCreateBlank,- onOpenSkills,- }: {+ openCreateAgentModal: (props: {onCreateBlank: () => Promise<void> | void;onOpenSkills?: (identifier: string) => void;- open: boolean;- }) =>- open ? (- <>- <button type="button" onClick={() => void onCreateBlank()}>- Start Blank- </button>- <button type="button" onClick={() => onOpenSkills?.('product-requirements-writer')}>- View in Skills- </button>- </>- ) : null,+ }) => {+ mocks.createAgentModalProps = props;+ return { close: mocks.closeCreateAgentModal };+ },+}));++vi.mock('@/features/WorkspaceSetting/Labels/LabelFormModal', () => ({+ openLabelFormModal: vi.fn(),}));vi.mock('@/store/agent', () => ({@@ -104,7 +103,7 @@ vi.mock('./Modals/ConfigGroupModal', () => ({}));vi.mock('./Modals/CreateGroupModal', () => ({- default: () => null,+ openCreateGroupModal: vi.fn(),}));const OpenCreateAgentModalButton = () => {@@ -135,6 +134,7 @@ const renderProvider = () =>describe('AgentModalProvider', () => {beforeEach(() => {vi.clearAllMocks();+ mocks.createAgentModalProps = undefined;mocks.createAgent.mockResolvedValue({ agentId: 'agent-new' });});@@ -146,7 +146,8 @@ describe('AgentModalProvider', () => {renderProvider();fireEvent.click(screen.getByText('Open create agent modal'));- fireEvent.click(await screen.findByText('Start Blank'));+ await waitFor(() => expect(mocks.createAgentModalProps).toBeDefined());+ await mocks.createAgentModalProps!.onCreateBlank();await waitFor(() => {expect(mocks.createAgent).toHaveBeenCalledWith({ groupId: undefined });@@ -160,7 +161,8 @@ describe('AgentModalProvider', () => {renderProvider();fireEvent.click(screen.getByText('Open create agent modal'));- fireEvent.click(await screen.findByText('View in Skills'));+ await waitFor(() => expect(mocks.createAgentModalProps).toBeDefined());+ mocks.createAgentModalProps!.onOpenSkills?.('product-requirements-writer');expect(mocks.navigate).toHaveBeenCalledWith('/settings/skill?skill=product-requirements-writer',diff --git a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsxindex 669b243e5ad..12f31734441 100644--- a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx@@ -1,6 +1,7 @@'use client';import { AGENT_CHAT_URL } from '@lobechat/const';+import { type ModalInstance } from '@lobehub/ui/base-ui';import {createContext,lazy,@@ -9,26 +10,23 @@ import {Suspense,use,useCallback,+ useEffect,useMemo,+ useRef,useState,} from 'react';import EditingPopover from '@/features/EditingPopover';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import LabelFormModal from '@/features/WorkspaceSetting/Labels/LabelFormModal';+import { openLabelFormModal } from '@/features/WorkspaceSetting/Labels/LabelFormModal';+import type { OpenCreateAgentModalOptions } from '@/routes/(main)/home/_layout/hooks/useCreateModal';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useGlobalStore } from '@/store/global';import { useHomeStore } from '@/store/home';import ConfigGroupModal from './Modals/ConfigGroupModal';-import CreateGroupModal from './Modals/CreateGroupModal';--const CreateAgentModal = lazy(() =>- import('@/routes/(main)/home/_layout/hooks/useCreateModal').then((module) => ({- default: module.CreateAgentModal,- })),-);+import { openCreateGroupModal } from './Modals/CreateGroupModal';const ChatGroupWizard = lazy(() =>import('@/components/ChatGroupWizard').then((module) => ({@@ -102,13 +100,12 @@ export const useOptionalAgentModal = () => {interface CreateModalRendererProps {groupId?: string;onClose: () => void;- open: boolean;type: 'agent' | 'group';visibility?: 'private' | 'public';}const CreateModalRenderer = memo<CreateModalRendererProps>(- ({ open, type, groupId, onClose, visibility }) => {+ ({ type, groupId, onClose, visibility }) => {const navigate = useWorkspaceAwareNavigate();const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);const storeCreateAgent = useAgentStore((s) => s.createAgent);@@ -152,18 +149,39 @@ const CreateModalRenderer = memo<CreateModalRendererProps>(navigate(AGENT_CHAT_URL(inboxAgentId, false));}, [inboxAgentId, navigate]);- return (- <CreateAgentModal- agentId={inboxAgentId}- open={open}- type={type}- onClose={onClose}- onCreateBlank={handleCreateBlank}- onOpenSkills={handleOpenSkills}- onSubmit={handleSubmit}- onTryInLobeAI={handleTryInLobeAI}- />- );+ // Mounted only while the modal should be open, so the open/close bridge is+ // just this component's lifetime — the panel itself lives in the ModalHost.+ const openArgsRef = useRef<OpenCreateAgentModalOptions>(undefined);+ openArgsRef.current = {+ agentId: inboxAgentId,+ type,+ onClosed: onClose,+ onCreateBlank: handleCreateBlank,+ onOpenSkills: handleOpenSkills,+ onSubmit: handleSubmit,+ onTryInLobeAI: handleTryInLobeAI,+ };++ useEffect(() => {+ // Imported here rather than at module scope so the create-agent chunk (it+ // pulls in the whole ChatInput stack) still loads only when the modal opens.+ let cancelled = false;+ let instance: ModalInstance | undefined;++ void import('@/routes/(main)/home/_layout/hooks/useCreateModal').then(+ ({ openCreateAgentModal }) => {+ if (cancelled) return;+ instance = openCreateAgentModal(openArgsRef.current!);+ },+ );++ return () => {+ cancelled = true;+ instance?.close();+ };+ }, []);++ return null;},);@@ -172,12 +190,7 @@ interface AgentModalProviderProps {}export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) => {- // CreateGroupModal state- const [createGroupModalOpen, setCreateGroupModalOpen] = useState(false);- const [createGroupSessionId, setCreateGroupSessionId] = useState<string | undefined>(undefined);- const [createGroupVisibility, setCreateGroupVisibility] = useState<- 'private' | 'public' | undefined- >(undefined);+ const createGroupModalRef = useRef<ModalInstance>(undefined);// ConfigGroupModal stateconst [configGroupModalOpen, setConfigGroupModalOpen] = useState(false);@@ -195,12 +208,6 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =const [memberSelectionCallbacks, setMemberSelectionCallbacks] =useState<MemberSelectionCallbacks>({});- // Create-label modal state- const [createLabelModalOpen, setCreateLabelModalOpen] = useState(false);- const [createLabelAssignTo, setCreateLabelAssignTo] = useState<- { agentId: string; currentLabelIds: string[] } | undefined- >(undefined);-// CreateAgentModal stateconst [createModalOpen, setCreateModalOpen] = useState(false);const [createModalType, setCreateModalType] = useState<'agent' | 'group'>('agent');@@ -212,14 +219,14 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =const contextValue = useMemo<AgentModalContextValue>(() => ({closeAllModals: () => {- setCreateGroupModalOpen(false);+ createGroupModalRef.current?.close();setConfigGroupModalOpen(false);setGroupWizardOpen(false);setMemberSelectionOpen(false);setCreateModalOpen(false);},closeConfigGroupModal: () => setConfigGroupModalOpen(false),- closeCreateGroupModal: () => setCreateGroupModalOpen(false),+ closeCreateGroupModal: () => createGroupModalRef.current?.close(),closeGroupWizardModal: () => setGroupWizardOpen(false),closeMemberSelectionModal: () => setMemberSelectionOpen(false),openConfigGroupModal: (scope?: 'private' | 'public') => {@@ -227,13 +234,10 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =setConfigGroupModalOpen(true);},openCreateGroupModal: (sessionId?: string, visibility?: 'private' | 'public') => {- setCreateGroupSessionId(sessionId);- setCreateGroupVisibility(visibility);- setCreateGroupModalOpen(true);+ createGroupModalRef.current = openCreateGroupModal({ id: sessionId, visibility });},openCreateLabelModal: (assignTo?: { agentId: string; currentLabelIds: string[] }) => {- setCreateLabelAssignTo(assignTo);- setCreateLabelModalOpen(true);+ openLabelFormModal({ assignTo });},openCreateModal: (type: 'agent' | 'group', options?: OpenCreateModalOptions) => {setCreateModalType(type);@@ -257,34 +261,14 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =return (<AgentModalContext value={contextValue}>{createModalOpen && (- <Suspense fallback={null}>- <CreateModalRenderer- open- groupId={createModalGroupId}- type={createModalType}- visibility={createModalVisibility}- onClose={() => setCreateModalOpen(false)}- />- </Suspense>- )}- {children}-- {/* All modals rendered at top level */}- {createLabelModalOpen && (- <LabelFormModal- open- assignTo={createLabelAssignTo}- onCancel={() => setCreateLabelModalOpen(false)}- />- )}- {createGroupModalOpen && (- <CreateGroupModal- id={createGroupSessionId}- open={createGroupModalOpen}- visibility={createGroupVisibility}- onCancel={() => setCreateGroupModalOpen(false)}+ <CreateModalRenderer+ groupId={createModalGroupId}+ type={createModalType}+ visibility={createModalVisibility}+ onClose={() => setCreateModalOpen(false)}/>)}+ {children}<ConfigGroupModalopen={configGroupModalOpen}diff --git a/src/routes/(main)/home/_layout/Body/Agent/Modals/CreateGroupModal.tsx b/src/routes/(main)/home/_layout/Body/Agent/Modals/CreateGroupModal.tsxindex 5dc6e333eb2..46336e58213 100644--- a/src/routes/(main)/home/_layout/Body/Agent/Modals/CreateGroupModal.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/Modals/CreateGroupModal.tsx@@ -1,17 +1,14 @@-import { type ModalProps } from '@lobehub/ui';-import { Flexbox, Input, stopPropagation } from '@lobehub/ui';-import { toast } from '@lobehub/ui/base-ui';-import { type InputRef } from 'antd';-import { type MouseEvent } from 'react';-import { memo, useRef, useState } from 'react';+import { Flexbox, Input } from '@lobehub/ui';+import { Button, createModal, ModalFooter, toast, useModalContext } from '@lobehub/ui/base-ui';+import { t as translate } from 'i18next';+import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import { usePermission } from '@/hooks/usePermission';import { useGlobalStore } from '@/store/global';import { useHomeStore } from '@/store/home';-interface CreateGroupModalProps extends ModalProps {+interface CreateGroupModalOptions {/*** Agent to move into the newly created group. Omitted when the modal is* opened from the sidebar "create group" entry, which only creates the group.@@ -20,60 +17,66 @@ interface CreateGroupModalProps extends ModalProps {visibility?: 'private' | 'public';}-const CreateGroupModal = memo<CreateGroupModalProps>(- ({ id, open, onCancel, visibility }: CreateGroupModalProps) => {- const { t } = useTranslation('chat');- const { allowed: canCreate } = usePermission('create_content');+const CreateGroupContent = memo<CreateGroupModalOptions>(({ id, visibility }) => {+ const { t } = useTranslation(['chat', 'common']);+ const { close } = useModalContext();+ const { allowed: canCreate } = usePermission('create_content');- const toggleExpandSessionGroup = useGlobalStore((s) => s.toggleExpandSessionGroup);+ const toggleExpandSessionGroup = useGlobalStore((s) => s.toggleExpandSessionGroup);+ const [updateAgentGroup, addGroup] = useHomeStore((s) => [s.updateAgentGroup, s.addGroup]);- const [updateAgentGroup, addGroup] = useHomeStore((s) => [s.updateAgentGroup, s.addGroup]);- // The input stays uncontrolled: ImperativeModal renders this content through- // the global ModalHost, so a controlled value living in this component only- // reaches the DOM after an effect-driven update — the lag makes React reset- // the field mid-IME-composition and CJK input becomes impossible.- const inputRef = useRef<InputRef>(null);- const [loading, setLoading] = useState(false);+ const [input, setInput] = useState('');+ const [loading, setLoading] = useState(false);- return (- <div onClick={stopPropagation}>- <ImperativeModal- allowFullscreen- destroyOnHidden- okButtonProps={{ disabled: !canCreate, loading }}- open={open}- title={t('sessionGroup.createGroup')}- width={400}- onCancel={onCancel}- onOk={async (e: MouseEvent<HTMLButtonElement>) => {- if (!canCreate) return;+ const handleCreate = async () => {+ // Enter fires as fast as the user repeats it — a second pass while `addGroup`+ // is in flight would create a second group and move the agent into whichever+ // request settles last.+ if (!canCreate || loading) return;+ if (input.length === 0 || input.length > 20 || input.trim() === '')+ return toast.warning(t('sessionGroup.tooLong'));- const input = inputRef.current?.input?.value ?? '';- if (input.length === 0 || input.length > 20 || input.trim() === '')- return toast.warning(t('sessionGroup.tooLong'));+ setLoading(true);+ try {+ const groupId = await addGroup(input, visibility);+ if (id) await updateAgentGroup(id, groupId);+ toggleExpandSessionGroup(groupId, true);+ toast.success(t('sessionGroup.createSuccess'));+ close();+ } finally {+ setLoading(false);+ }+ };- setLoading(true);- const groupId = await addGroup(input, visibility);- if (id) await updateAgentGroup(id, groupId);- toggleExpandSessionGroup(groupId, true);- setLoading(false);+ return (+ <>+ <Flexbox paddingBlock={16} paddingInline={16}>+ <Input+ autoFocus+ disabled={!canCreate || loading}+ placeholder={t('sessionGroup.inputPlaceholder')}+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onPressEnter={handleCreate}+ />+ </Flexbox>+ <ModalFooter>+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>+ <Button disabled={!canCreate} loading={loading} type={'primary'} onClick={handleCreate}>+ {t('ok', { defaultValue: 'OK', ns: 'common' })}+ </Button>+ </ModalFooter>+ </>+ );+});- toast.success(t('sessionGroup.createSuccess'));- onCancel?.(e);- }}- >- <Flexbox paddingBlock={16}>- <Input- autoFocus- disabled={!canCreate}- placeholder={t('sessionGroup.inputPlaceholder')}- ref={inputRef}- />- </Flexbox>- </ImperativeModal>- </div>- );- },-);+CreateGroupContent.displayName = 'HomeCreateGroupContent';-export default CreateGroupModal;+export const openCreateGroupModal = (options: CreateGroupModalOptions = {}) =>+ createModal({+ content: <CreateGroupContent {...options} />,+ footer: null,+ styles: { content: { padding: 0 } },+ title: translate('sessionGroup.createGroup', { ns: 'chat' }),+ width: 400,+ });diff --git a/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsx b/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsxindex 43cac3f8e5f..aff91652071 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsx@@ -1,8 +1,9 @@+import { createModal, type ModalInstance } from '@lobehub/ui/base-ui';import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { CreateAgentModal } from './useCreateModal';+import { CreateAgentModal, openCreateAgentModal } from './useCreateModal';const analyticsTrack = vi.hoisted(() => vi.fn());const telemetryState = vi.hoisted(() => ({ enabled: true }));@@ -86,15 +87,6 @@ vi.mock('@lobehub/ui', () => ({Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,}));-vi.mock('@/components/ImperativeModal', () => ({- default: ({ children, open, width }: { children?: ReactNode; open?: boolean; width?: string }) =>- open ? (- <div data-modal-width={width} role="dialog">- {children}- </div>- ) : null,-}));-vi.mock('@/services/marketApi', () => ({marketApiService: {searchSkill: marketApiMocks.searchSkill,@@ -131,12 +123,7 @@ vi.mock('@lobehub/ui/base-ui', () => ({{children}</button>),- Modal: ({ children, open, width }: { children?: ReactNode; open?: boolean; width?: string }) =>- open ? (- <div data-modal-width={width} role="dialog">- {children}- </div>- ) : null,+ createModal: vi.fn(),}));vi.mock('antd-style', () => ({@@ -261,11 +248,13 @@ const renderModal = (type: 'agent' | 'group' = 'agent') => {const onOpenSkills = vi.fn();const onSubmit = vi.fn().mockResolvedValue(undefined);const onTryInLobeAI = vi.fn();+ const update = vi.fn();+ const modalRef = { current: { update } as unknown as ModalInstance };render(<CreateAgentModal- openagentId="inbox-agent"+ modalRef={modalRef}type={type}onClose={onClose}onCreateBlank={onCreateBlank}@@ -275,7 +264,7 @@ const renderModal = (type: 'agent' | 'group' = 'agent') => {/>,);- return { onClose, onCreateBlank, onOpenSkills, onSubmit, onTryInLobeAI };+ return { onClose, onCreateBlank, onOpenSkills, onSubmit, onTryInLobeAI, update };};const expectTrackedSkillSuggestionAction = async (@@ -654,7 +643,7 @@ describe('CreateAgentModal analytics', () => {totalCount: 1,totalPages: 1,});- const { onClose, onOpenSkills, onSubmit, onTryInLobeAI } = renderModal();+ const { onClose, onOpenSkills, onSubmit, onTryInLobeAI, update } = renderModal();fireEvent.change(screen.getByLabelText('chat input'), {target: { value: '帮我做一个简历优化检查清单' },@@ -680,7 +669,7 @@ describe('CreateAgentModal analytics', () => {expect(screen.getByText('Resume Reviewer')).toBeInTheDocument();expect(screen.getByText('Ready in LobeAI')).toBeInTheDocument();expect(screen.queryByText('resume-reviewer')).not.toBeInTheDocument();- expect(screen.getByRole('dialog')).toHaveAttribute('data-modal-width', 'min(90vw, 560px)');+ expect(update).toHaveBeenCalledWith({ width: 'min(90vw, 560px)' });expect(screen.queryByText('Skill not a fit?')).not.toBeInTheDocument();expect(screen.queryByText('Create Agent Anyway')).not.toBeInTheDocument();@@ -744,3 +733,37 @@ describe('CreateAgentModal analytics', () => {).toBeInTheDocument();});});++describe('openCreateAgentModal', () => {+ it('reports the close through onOpenChangeComplete, not onOpenChange', () => {+ // Regression: the in-content close and the post-create path both call the+ // instance's `close()`, which never fires `onOpenChange`. Wiring the+ // provider's `createModalOpen` reset to that callback left it stuck true,+ // after which the dialog could not be opened a second time.+ vi.mocked(createModal).mockClear();+ vi.mocked(createModal).mockReturnValue({+ close: vi.fn(),+ destroy: vi.fn(),+ setCanDismissByClickOutside: vi.fn(),+ update: vi.fn(),+ } as unknown as ModalInstance);++ const onClosed = vi.fn();+ openCreateAgentModal({+ onClosed,+ onCreateBlank: vi.fn(),+ onSubmit: vi.fn(),+ type: 'agent',+ });++ const props = vi.mocked(createModal).mock.calls.at(-1)![0] as Record<string, any>;+ expect(props.onOpenChange).toBeUndefined();+ expect(typeof props.onOpenChangeComplete).toBe('function');++ props.onOpenChangeComplete(true);+ expect(onClosed).not.toHaveBeenCalled();++ props.onOpenChangeComplete(false);+ expect(onClosed).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx b/src/routes/(main)/home/_layout/hooks/useCreateModal.tsxindex d0e7caaedbd..e3ddd237d20 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx@@ -1,11 +1,10 @@import { ActionIcon, Block, Flexbox, Text } from '@lobehub/ui';-import { Button } from '@lobehub/ui/base-ui';+import { Button, createModal, type ModalInstance } from '@lobehub/ui/base-ui';import { cssVar } from 'antd-style';import { Blocks, CheckCircle2, Lightbulb, PencilLineIcon, RefreshCw, X } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import {type ActionKeys,type ChatInputEditor,@@ -308,17 +307,22 @@ const Examples = memo<ExamplesProps>(({ suggestMode, onExampleClick }) => {export interface CreateAgentModalProps {agentId?: string;+ /**+ * The panel narrows once a skill has been installed, and imperative modals+ * take their width at creation — hand the instance back so the content can+ * resize the panel it lives in.+ */+ modalRef?: { current?: ModalInstance };onClose: () => void;onCreateBlank: () => Promise<void> | void;onOpenSkills?: (identifier: string) => void;onSubmit: (prompt: string) => Promise<void> | void;onTryInLobeAI?: () => Promise<void> | void;- open: boolean;type: 'agent' | 'group';}export const CreateAgentModal = memo<CreateAgentModalProps>(- ({ open, type, agentId, onClose, onOpenSkills, onSubmit, onCreateBlank, onTryInLobeAI }) => {+ ({ type, agentId, modalRef, onClose, onOpenSkills, onSubmit, onCreateBlank, onTryInLobeAI }) => {const { t } = useTranslation('chat');const editorRef = useRef<ChatInputEditor | null>(null);const contentRef = useRef('');@@ -345,13 +349,10 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(}, []);useEffect(() => {- if (!open) return;- resetInputTracking();- setInstalledSkill(undefined);- setInstallingSkillIdentifier(undefined);- setSkillInstallError(false);- setSkillSuggestion(undefined);- }, [open, resetInputTracking]);+ modalRef?.current?.update({+ width: installedSkill ? INSTALLED_SKILL_MODAL_WIDTH : CREATE_MODAL_WIDTH,+ });+ }, [installedSkill, modalRef]);const handleClose = useCallback(() => {resetInputTracking();@@ -532,19 +533,7 @@ export const CreateAgentModal = memo<CreateAgentModalProps>();return (- <ImperativeModal- centered- destroyOnHidden- closable={false}- footer={null}- open={open}- title={false}- width={installedSkill ? INSTALLED_SKILL_MODAL_WIDTH : CREATE_MODAL_WIDTH}- styles={{- body: { padding: 0 },- }}- onCancel={handleClose}- >+ <>{installedSkill ? (<Flexbox gap={12} paddingBlock={'12px 24px'} paddingInline={24}><Flexbox horizontal align="center" justify="flex-end">@@ -621,7 +610,50 @@ export const CreateAgentModal = memo<CreateAgentModalProps>()}</Flexbox>)}- </ImperativeModal>+ </>);},);++CreateAgentModal.displayName = 'CreateAgentModal';++export interface OpenCreateAgentModalOptions extends Omit<+ CreateAgentModalProps,+ 'modalRef' | 'onClose'+> {+ /** Runs once the modal has been dismissed, for whatever reason. */+ onClosed?: () => void;+}++export const openCreateAgentModal = ({+ onClosed,+ ...contentProps+}: OpenCreateAgentModalOptions) => {+ const modalRef: { current?: ModalInstance } = {};++ const instance = createModal({+ content: (+ <CreateAgentModal+ {...contentProps}+ modalRef={modalRef}+ onClose={() => modalRef.current?.close()}+ />+ ),+ footer: null,+ // NOT `onOpenChange`: that only fires for user dismissal (Escape, backdrop,+ // the header close button). `instance.close()` — which the in-content close+ // and the post-create path both call — just flips the stack entry, so the+ // provider would never learn the modal went away and could not reopen it.+ // `createModal` only ever completes with `false`, but the open flag is+ // honored so this does not depend on that renderer detail.+ onOpenChangeComplete: (open) => {+ if (!open) onClosed?.();+ },+ styles: { content: { padding: 0 } },+ width: CREATE_MODAL_WIDTH,+ });++ modalRef.current = instance;++ return instance;+};diff --git a/src/routes/(main)/memory/(home)/features/Persona/index.tsx b/src/routes/(main)/memory/(home)/features/Persona/index.tsxindex 784b91cfe7f..322105e5a92 100644--- a/src/routes/(main)/memory/(home)/features/Persona/index.tsx+++ b/src/routes/(main)/memory/(home)/features/Persona/index.tsx@@ -1,8 +1,8 @@import { Flexbox } from '@lobehub/ui';import { cx } from 'antd-style';-import { memo, useState } from 'react';+import { memo } from 'react';-import { EditorModal } from '@/features/EditorModal';+import { openEditorModal } from '@/features/EditorModal';import { useUserMemoryStore } from '@/store/userMemory';import PersonaDetail from './PersonaDetail';@@ -14,24 +14,14 @@ interface PersonaProps {}export const usePersonaEditor = () => {- const [editOpen, setEditOpen] = useState(false);const persona = useUserMemoryStore((s) => s.persona);- const openEditor = () => setEditOpen(true);- const closeEditor = () => setEditOpen(false);-- const EditorModalElement = persona ? (- <EditorModal- open={editOpen}- value={persona.content}- onCancel={closeEditor}- onConfirm={async () => {- closeEditor();- }}- />- ) : null;-- return { EditorModalElement, openEditor };+ const openEditor = () => {+ if (!persona) return;+ openEditorModal({ value: persona.content });+ };++ return { openEditor };};const Persona = memo<PersonaProps>(({ className }) => {diff --git a/src/routes/(main)/memory/features/EditableModal/index.tsx b/src/routes/(main)/memory/features/EditableModal/index.tsxindex bd595207564..cd7b02a7291 100644--- a/src/routes/(main)/memory/features/EditableModal/index.tsx+++ b/src/routes/(main)/memory/features/EditableModal/index.tsx@@ -1,9 +1,17 @@-import { memo } from 'react';+import { memo, useEffect, useRef } from 'react';-import { EditorModal } from '@/features/EditorModal';+import { openEditorModal } from '@/features/EditorModal';import { useUserMemoryStore } from '@/store/userMemory';import { LayersEnum } from '@/types/userMemory';+const LAYER_MAP = {+ activity: LayersEnum.Activity,+ context: LayersEnum.Context,+ experience: LayersEnum.Experience,+ identity: LayersEnum.Identity,+ preference: LayersEnum.Preference,+};+const EditableModal = memo(() => {const editingMemoryId = useUserMemoryStore((s) => s.editingMemoryId);const editingMemoryContent = useUserMemoryStore((s) => s.editingMemoryContent);@@ -11,25 +19,27 @@ const EditableModal = memo(() => {const clearEditingMemory = useUserMemoryStore((s) => s.clearEditingMemory);const updateMemory = useUserMemoryStore((s) => s.updateMemory);- const layerMap = {- activity: LayersEnum.Activity,- context: LayersEnum.Context,- experience: LayersEnum.Experience,- identity: LayersEnum.Identity,- preference: LayersEnum.Preference,- };-- return (- <EditorModal- open={!!editingMemoryId}- value={editingMemoryContent}- onCancel={clearEditingMemory}- onConfirm={async (value) => {+ // Held in a ref rather than in the effect's deps: the editor snapshots the+ // memory when it opens, so an unrelated store update must not tear down and+ // reopen a modal the user is typing in.+ const openEditorRef = useRef<() => ReturnType<typeof openEditorModal>>(undefined);+ openEditorRef.current = () =>+ openEditorModal({+ value: editingMemoryContent,+ onClose: clearEditingMemory,+ onConfirm: async (value) => {if (!editingMemoryId || !editingMemoryLayer) return;- await updateMemory(editingMemoryId, value, layerMap[editingMemoryLayer]);- }}- />- );+ await updateMemory(editingMemoryId, value, LAYER_MAP[editingMemoryLayer]);+ },+ });++ useEffect(() => {+ if (!editingMemoryId) return;+ const instance = openEditorRef.current!();+ return () => instance.close();+ }, [editingMemoryId]);++ return null;});export default EditableModal;diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/DefaultMode.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/DefaultMode.tsxindex 9b48001297a..34d8bb7fd29 100644--- a/src/routes/(mobile)/(home)/features/SessionListContent/DefaultMode.tsx+++ b/src/routes/(mobile)/(home)/features/SessionListContent/DefaultMode.tsx@@ -19,13 +19,11 @@ import Actions from './CollapseGroup/Actions';import Inbox from './Inbox';import SessionList from './List';import ConfigGroupModal from './Modals/ConfigGroupModal';-import RenameGroupModal from './Modals/RenameGroupModal';+import { openRenameGroupModal } from './Modals/RenameGroupModal';const DefaultMode = memo(() => {const { t } = useTranslation('chat');- const [activeGroupId, setActiveGroupId] = useState<string>();- const [renameGroupModalOpen, setRenameGroupModalOpen] = useState(false);const [configGroupModalOpen, setConfigGroupModalOpen] = useState(false);useFetchSessions();@@ -81,10 +79,7 @@ const DefaultMode = memo(() => {isCustomGroupid={id}openConfigModal={() => setConfigGroupModalOpen(true)}- openRenameModal={() => setRenameGroupModalOpen(true)}- onOpenChange={(isOpen) => {- if (isOpen) setActiveGroupId(id);- }}+ openRenameModal={() => openRenameGroupModal(id)}/>),key: id,@@ -111,13 +106,6 @@ const DefaultMode = memo(() => {updateSystemStatus({ expandSessionGroupKeys });}}/>- {activeGroupId && (- <RenameGroupModal- id={activeGroupId}- open={renameGroupModalOpen}- onCancel={() => setRenameGroupModalOpen(false)}- />- )}<ConfigGroupModalopen={configGroupModalOpen}onCancel={() => setConfigGroupModalOpen(false)}diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/index.tsxindex 51a73cb3cb0..3ad6a3e2e31 100644--- a/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx+++ b/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx@@ -17,7 +17,7 @@ import { userProfileSelectors } from '@/store/user/selectors';import { type LobeGroupSession } from '@/types/session';import ListItem from '../../ListItem';-import CreateGroupModal from '../../Modals/CreateGroupModal';+import { openCreateGroupModal } from '../../Modals/CreateGroupModal';import Actions from './Actions';interface SessionItemProps {@@ -26,7 +26,6 @@ interface SessionItemProps {const SessionItem = memo<SessionItemProps>(({ id }) => {const [open, setOpen] = useState(false);- const [createGroupModalOpen, setCreateGroupModalOpen] = useState(false);const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);@@ -79,7 +78,7 @@ const SessionItem = memo<SessionItemProps>(({ id }) => {<Actionsgroup={group}id={id}- openCreateGroupModal={() => setCreateGroupModalOpen(true)}+ openCreateGroupModal={() => openCreateGroupModal(id)}parentType={sessionType}setOpen={setOpen}/>@@ -117,40 +116,33 @@ const SessionItem = memo<SessionItemProps>(({ id }) => {: avatar;return (- <>- <ListItem- actions={actions}- active={active}- addon={addon}- avatar={sessionAvatar as any} // Fix: Bypass complex intersection type ReactNode & avatar type- avatarBackground={avatarBackground}- date={updateAt?.valueOf()}- draggable={isDesktop}- key={id}- loading={loading}- pin={pin}- showAction={open}- title={title}- type={sessionType}- styles={{- container: {- gap: 12,- },- content: {- gap: 6,- maskImage: `linear-gradient(90deg, #000 90%, transparent)`,- },- }}- onDoubleClick={handleDoubleClick}- onDragEnd={handleDragEnd}- onDragStart={handleDragStart}- />- <CreateGroupModal- id={id}- open={createGroupModalOpen}- onCancel={() => setCreateGroupModalOpen(false)}- />- </>+ <ListItem+ actions={actions}+ active={active}+ addon={addon}+ avatar={sessionAvatar as any} // Fix: Bypass complex intersection type ReactNode & avatar type+ avatarBackground={avatarBackground}+ date={updateAt?.valueOf()}+ draggable={isDesktop}+ key={id}+ loading={loading}+ pin={pin}+ showAction={open}+ title={title}+ type={sessionType}+ styles={{+ container: {+ gap: 12,+ },+ content: {+ gap: 6,+ maskImage: `linear-gradient(90deg, #000 90%, transparent)`,+ },+ }}+ onDoubleClick={handleDoubleClick}+ onDragEnd={handleDragEnd}+ onDragStart={handleDragStart}+ />);}, shallow);diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/CreateGroupModal.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/CreateGroupModal.tsxindex 7fe8b6d5141..28b021ebd32 100644--- a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/CreateGroupModal.tsx+++ b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/CreateGroupModal.tsx@@ -1,74 +1,80 @@-import { type ModalProps } from '@lobehub/ui';-import { Flexbox, Input, stopPropagation } from '@lobehub/ui';-import { toast } from '@lobehub/ui/base-ui';-import { type MouseEvent } from 'react';+import { Flexbox, Input } from '@lobehub/ui';+import { Button, createModal, ModalFooter, toast, useModalContext } from '@lobehub/ui/base-ui';+import { t as translate } from 'i18next';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import { usePermission } from '@/hooks/usePermission';import { useGlobalStore } from '@/store/global';import { useSessionStore } from '@/store/session';-interface CreateGroupModalProps extends ModalProps {+interface CreateGroupContentProps {id: string;}-const CreateGroupModal = memo<CreateGroupModalProps>(- ({ id, open, onCancel }: CreateGroupModalProps) => {- const { t } = useTranslation('chat');- const { allowed: canCreate } = usePermission('create_content');+const CreateGroupContent = memo<CreateGroupContentProps>(({ id }) => {+ const { t } = useTranslation(['chat', 'common']);+ const { close } = useModalContext();+ const { allowed: canCreate } = usePermission('create_content');- const toggleExpandSessionGroup = useGlobalStore((s) => s.toggleExpandSessionGroup);+ const toggleExpandSessionGroup = useGlobalStore((s) => s.toggleExpandSessionGroup);+ const [updateSessionGroup, addCustomGroup] = useSessionStore((s) => [+ s.updateSessionGroupId,+ s.addSessionGroup,+ ]);- const [updateSessionGroup, addCustomGroup] = useSessionStore((s) => [- s.updateSessionGroupId,- s.addSessionGroup,- ]);- const [input, setInput] = useState('');- const [loading, setLoading] = useState(false);+ const [input, setInput] = useState('');+ const [loading, setLoading] = useState(false);- return (- <div onClick={stopPropagation}>- <ImperativeModal- allowFullscreen- destroyOnHidden- okButtonProps={{ disabled: !canCreate, loading }}- open={open}- title={t('sessionGroup.createGroup')}- width={400}- onCancel={(e) => {- setInput('');- onCancel?.(e);- }}- onOk={async (e: MouseEvent<HTMLButtonElement>) => {- if (!canCreate) return;- if (input.length === 0 || input.length > 20 || input.trim() === '')- return toast.warning(t('sessionGroup.tooLong'));+ const handleCreate = async () => {+ // Enter fires as fast as the user repeats it — a second pass while+ // `addCustomGroup` is in flight would create a second group and move the+ // session into whichever request settles last.+ if (!canCreate || loading) return;+ if (input.length === 0 || input.length > 20 || input.trim() === '')+ return toast.warning(t('sessionGroup.tooLong'));- setLoading(true);- const groupId = await addCustomGroup(input);- await updateSessionGroup(id, groupId);- toggleExpandSessionGroup(groupId, true);- setLoading(false);+ setLoading(true);+ try {+ const groupId = await addCustomGroup(input);+ await updateSessionGroup(id, groupId);+ toggleExpandSessionGroup(groupId, true);+ toast.success(t('sessionGroup.createSuccess'));+ close();+ } finally {+ setLoading(false);+ }+ };- toast.success(t('sessionGroup.createSuccess'));- onCancel?.(e);- }}- >- <Flexbox paddingBlock={16}>- <Input- autoFocus- disabled={!canCreate}- placeholder={t('sessionGroup.inputPlaceholder')}- value={input}- onChange={(e) => setInput(e.target.value)}- />- </Flexbox>- </ImperativeModal>- </div>- );- },-);+ return (+ <>+ <Flexbox paddingBlock={16} paddingInline={16}>+ <Input+ autoFocus+ disabled={!canCreate || loading}+ placeholder={t('sessionGroup.inputPlaceholder')}+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onPressEnter={handleCreate}+ />+ </Flexbox>+ <ModalFooter>+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>+ <Button disabled={!canCreate} loading={loading} type={'primary'} onClick={handleCreate}>+ {t('ok', { defaultValue: 'OK', ns: 'common' })}+ </Button>+ </ModalFooter>+ </>+ );+});-export default CreateGroupModal;+CreateGroupContent.displayName = 'MobileCreateGroupContent';++export const openCreateGroupModal = (id: string) =>+ createModal({+ content: <CreateGroupContent id={id} />,+ footer: null,+ styles: { content: { padding: 0 } },+ title: translate('sessionGroup.createGroup', { ns: 'chat' }),+ width: 400,+ });diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/RenameGroupModal.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/RenameGroupModal.tsxindex 4733f0e623a..8a4a683ef88 100644--- a/src/routes/(mobile)/(home)/features/SessionListContent/Modals/RenameGroupModal.tsx+++ b/src/routes/(mobile)/(home)/features/SessionListContent/Modals/RenameGroupModal.tsx@@ -1,63 +1,70 @@-import { type ModalProps } from '@lobehub/ui';-import { Input } from '@lobehub/ui';-import { toast } from '@lobehub/ui/base-ui';+import { Flexbox, Input } from '@lobehub/ui';+import { Button, createModal, ModalFooter, toast, useModalContext } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';-import { memo, useEffect, useState } from 'react';+import { t as translate } from 'i18next';+import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import ImperativeModal from '@/components/ImperativeModal';import { useSessionStore } from '@/store/session';import { sessionGroupSelectors } from '@/store/session/selectors';-interface RenameGroupModalProps extends ModalProps {+interface RenameGroupContentProps {id: string;}-const RenameGroupModal = memo<RenameGroupModalProps>(({ id, open, onCancel }) => {- const { t } = useTranslation('chat');+const RenameGroupContent = memo<RenameGroupContentProps>(({ id }) => {+ const { t } = useTranslation(['chat', 'common']);+ const { close } = useModalContext();const updateSessionGroupName = useSessionStore((s) => s.updateSessionGroupName);const group = useSessionStore((s) => sessionGroupSelectors.getGroupById(id)(s), isEqual);- const [input, setInput] = useState<string>('');+ const [input, setInput] = useState<string>(group?.name ?? '');const [loading, setLoading] = useState(false);- useEffect(() => {- setInput(group?.name ?? '');- }, [group]);+ const handleRename = async () => {+ if (loading) return;+ if (input.length === 0 || input.length > 20) return toast.warning(t('sessionGroup.tooLong'));++ setLoading(true);+ try {+ await updateSessionGroupName(id, input);+ toast.success(t('sessionGroup.renameSuccess'));+ close();+ } finally {+ setLoading(false);+ }+ };return (- <ImperativeModal- allowFullscreen- destroyOnHidden- okButtonProps={{ loading }}- open={open}- title={t('sessionGroup.rename')}- width={400}- onCancel={(e) => {- setInput(group?.name ?? '');- onCancel?.(e);- }}- onOk={async (e) => {- if (input.length === 0 || input.length > 20)- return toast.warning(t('sessionGroup.tooLong'));- setLoading(true);- await updateSessionGroupName(id, input);- toast.success(t('sessionGroup.renameSuccess'));- setLoading(false);-- onCancel?.(e);- }}- >- <Input- autoFocus- defaultValue={group?.name}- placeholder={t('sessionGroup.inputPlaceholder')}- value={input}- onChange={(e) => setInput(e.target.value)}- />- </ImperativeModal>+ <>+ <Flexbox paddingBlock={16} paddingInline={16}>+ <Input+ autoFocus+ disabled={loading}+ placeholder={t('sessionGroup.inputPlaceholder')}+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onPressEnter={handleRename}+ />+ </Flexbox>+ <ModalFooter>+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>+ <Button loading={loading} type={'primary'} onClick={handleRename}>+ {t('ok', { defaultValue: 'OK', ns: 'common' })}+ </Button>+ </ModalFooter>+ </>);});-export default RenameGroupModal;+RenameGroupContent.displayName = 'MobileRenameGroupContent';++export const openRenameGroupModal = (id: string) =>+ createModal({+ content: <RenameGroupContent id={id} />,+ footer: null,+ styles: { content: { padding: 0 } },+ title: translate('sessionGroup.rename', { ns: 'chat' }),+ width: 400,+ });