π€― 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
π fix(agent): improve prompt save feedback and header layouts (#17071)
AmAzing-fbbedf3a859b
diff --git a/src/features/AgentBreadcrumb/index.tsx b/src/features/AgentBreadcrumb/index.tsxindex fda13ec3523..6669baf9404 100644--- a/src/features/AgentBreadcrumb/index.tsx+++ b/src/features/AgentBreadcrumb/index.tsx@@ -2,6 +2,7 @@import { Icon, Text } from '@lobehub/ui';import { Breadcrumb as AntBreadcrumb } from 'antd';+import { createStaticStyles } from 'antd-style';import { ChevronRight } from 'lucide-react';import { memo, type ReactNode, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -17,6 +18,21 @@ import {import { useAgentStore } from '@/store/agent';import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';+const styles = createStaticStyles(({ css }) => ({+ breadcrumb: css`+ ol {+ align-items: center;+ }++ li,+ .ant-breadcrumb-link,+ .ant-breadcrumb-link > a {+ display: flex;+ align-items: center;+ }+ `,+}));+interface AgentBreadcrumbProps {agentId: string;/**@@ -47,12 +63,13 @@ const AgentBreadcrumb = memo<AgentBreadcrumbProps>(({ agentId, title }) => {return (<AntBreadcrumb+ className={styles.breadcrumb}separator={<Icon icon={ChevronRight} size={14} />}items={[{title: (<Link to={agentHomePath}>- <Text ellipsis color={'inherit'} style={{ maxWidth: 200 }} weight={500}>+ <Text ellipsis as={'span'} color={'inherit'} style={{ maxWidth: 200 }} weight={500}>{displayTitle}</Text></Link>@@ -60,7 +77,7 @@ const AgentBreadcrumb = memo<AgentBreadcrumbProps>(({ agentId, title }) => {},{title: (- <Text color={'inherit'} weight={500}>+ <Text as={'span'} color={'inherit'} weight={500}>{title}</Text>),diff --git a/src/features/AgentTopicManager/Header.tsx b/src/features/AgentTopicManager/Header.tsxindex e46d0579dd8..1be575d2abe 100644--- a/src/features/AgentTopicManager/Header.tsx+++ b/src/features/AgentTopicManager/Header.tsx@@ -22,17 +22,21 @@ const Header = memo<HeaderProps>(({ agentId }) => {return (<NavHeaderleft={<AgentBreadcrumb agentId={agentId} title={t('management.title')} />}- styles={{ center: { maxWidth: 560, paddingInline: 16 }, left: { paddingInlineStart: 24 } }}- >- <Input- placeholder={t('management.searchPlaceholder')}- prefix={<Icon icon={Search} size={'small'} style={{ marginInlineEnd: 4 }} />}- size={'small'}- value={search}- variant={'filled'}- onChange={(e) => setSearch(e.target.value)}- />- </NavHeader>+ right={+ <Input+ placeholder={t('searchPlaceholder')}+ prefix={<Icon icon={Search} size={'small'} style={{ marginInlineEnd: 4 }} />}+ size={'small'}+ value={search}+ variant={'filled'}+ onChange={(e) => setSearch(e.target.value)}+ />+ }+ styles={{+ left: { paddingInlineStart: 16 },+ right: { flex: 1, maxWidth: 400, paddingInline: 16 },+ }}+ />);});diff --git a/src/features/AgentTopicManager/TopicCard.tsx b/src/features/AgentTopicManager/TopicCard.tsxindex 68aac2310ca..a555cbb9ec8 100644--- a/src/features/AgentTopicManager/TopicCard.tsx+++ b/src/features/AgentTopicManager/TopicCard.tsx@@ -72,6 +72,11 @@ const styles = createStaticStyles(({ css }) => ({-webkit-box-orient: vertical;-webkit-line-clamp: 1;`,+ /* Reserve space for the absolutely positioned checkbox (18px + gap)+ so long titles don't run underneath it. */+ titleRow: css`+ padding-inline-end: 28px;+ `,}));interface TopicCardProps {@@ -138,7 +143,7 @@ const TopicCard = memo<TopicCardProps>(({ topic, agentId }) => {/></div>- <Flexbox horizontal align={'center'} gap={6}>+ <Flexbox horizontal align={'center'} className={styles.titleRow} gap={6}>{topic.favorite && (<Icon icon={Star} size={13} style={{ color: cssVar.colorWarning, flexShrink: 0 }} />)}diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsxindex 264d1ac52d1..c3c08ad8953 100644--- a/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx@@ -1,14 +1,19 @@/*** @vitest-environment happy-dom*/-import { act, render, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { type SaveStatus } from '@/types/saveState';+import EditorCanvas from './index';const editorProps = vi.hoisted(() => ({last: undefined as any,}));+const autoSaveHintProps = vi.hoisted(() => ({+ last: undefined as any,+}));const editorDocuments = {json: undefined as unknown,@@ -27,7 +32,9 @@ const editor = {const handleContentChange = vi.fn();const flushSave = vi.fn().mockResolvedValue(undefined);+const retryPromptSave = vi.fn().mockResolvedValue(undefined);const setHasEdited = vi.fn();+const messageError = vi.fn();const permissionState = {allowed: false,};@@ -53,6 +60,17 @@ const agentStoreMock = vi.hoisted(() => {});const { state: agentStoreState } = agentStoreMock;const { updateAgentConfigById } = agentStoreState;+const profileStoreState = {+ editor,+ flushSave,+ handleContentChange,+ hasEdited: false,+ lockState: { holderId: null, lockedByOther: false, pending: false },+ promptLastUpdatedTime: null as Date | null,+ promptSaveStatus: 'idle' as SaveStatus,+ retryPromptSave,+ setHasEdited,+};type UseSyncExternalStore = <Snapshot>(subscribe: (onStoreChange: () => void) => () => void,@@ -76,6 +94,23 @@ vi.mock('@lobehub/editor', () => ({ReactToolbarPlugin: vi.fn(),}));+vi.mock('@/components/Editor/AutoSaveHint', () => ({+ default: vi.fn((props: any) => {+ autoSaveHintProps.last = props;+ return (+ <button data-testid="prompt-save-status" type="button" onClick={props.onRetry}>+ {props.saveStatus}+ </button>+ );+ }),+}));++vi.mock('@/components/AntdStaticMethods', () => ({+ message: {+ error: (...args: unknown[]) => messageError(...args),+ },+}));+vi.mock('@/features/ChatInput/InputEditor/plugins', () => ({createChatInputRichPlugins: () => [],}));@@ -107,15 +142,10 @@ vi.mock('../ProfileEditor/MentionList', () => ({}));vi.mock('../store', () => ({- useProfileStore: (selector: any) =>- selector({- editor,- flushSave,- handleContentChange,- hasEdited: false,- lockState: { holderId: null, lockedByOther: false, pending: false },- setHasEdited,- }),+ useProfileStore: (selector: any) => selector(profileStoreState),+ useStoreApi: () => ({+ getState: () => profileStoreState,+ }),}));vi.mock('./TypoBar', () => ({@@ -134,6 +164,7 @@ describe('Agent profile EditorCanvas', () => {beforeEach(() => {vi.clearAllMocks();editorProps.last = undefined;+ autoSaveHintProps.last = undefined;permissionState.allowed = false;agentStoreMock.listeners.clear();agentStoreState.activeAgentId = 'agent-a';@@ -146,8 +177,11 @@ describe('Agent profile EditorCanvas', () => {agentStoreState.streamingSystemRole = undefined;agentStoreState.streamingSystemRoleAgentId = undefined;agentStoreState.streamingSystemRoleInProgress = false;+ profileStoreState.promptLastUpdatedTime = null;+ profileStoreState.promptSaveStatus = 'idle';editorDocuments.json = undefined;editorDocuments.markdown = '';+ updateAgentConfigById.mockResolvedValue(undefined);});afterEach(() => {@@ -185,7 +219,21 @@ describe('Agent profile EditorCanvas', () => {editorDocuments.json = { root: { children: ['agent-a edited'] } };editorDocuments.markdown = 'agent-a edited';act(() => editorProps.last?.onTextChange(editor));- expect(handleContentChange).toHaveBeenCalledWith('agent-a', updateAgentConfigById, editor);+ expect(handleContentChange).toHaveBeenCalledWith('agent-a', expect.any(Function), editor);++ const savePrompt = handleContentChange.mock.calls.at(-1)?.[1];+ await savePrompt('agent-a', {+ editorData: editorDocuments.json,+ systemRole: editorDocuments.markdown,+ });+ expect(updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-a',+ {+ editorData: editorDocuments.json,+ systemRole: editorDocuments.markdown,+ },+ { rethrow: true, showErrorMessage: false },+ );act(() => {agentStoreState.activeAgentId = 'agent-b';@@ -269,7 +317,50 @@ describe('Agent profile EditorCanvas', () => {});expect(editor.setDocument).not.toHaveBeenCalled();- expect(handleContentChange).toHaveBeenCalledWith('agent-a', updateAgentConfigById, editor);+ expect(handleContentChange).toHaveBeenCalledWith('agent-a', expect.any(Function), editor);+ });++ it('shows failed Prompt save feedback with a local Retry action', () => {+ permissionState.allowed = true;+ profileStoreState.promptSaveStatus = 'failed';++ render(<EditorCanvas />);++ expect(screen.getByTestId('prompt-save-status')).toHaveTextContent('failed');+ fireEvent.click(screen.getByTestId('prompt-save-status'));+ expect(retryPromptSave).toHaveBeenCalledTimes(1);+ });++ it('falls back to a global toast when an unmounted flush fails', async () => {+ permissionState.allowed = true;+ flushSave.mockImplementation(async () => {+ profileStoreState.promptSaveStatus = 'failed';+ });++ const { unmount } = render(<EditorCanvas />);+ unmount();++ await waitFor(() => expect(flushSave).toHaveBeenCalledWith('agent-a'));+ await waitFor(() => expect(messageError).toHaveBeenCalledWith('saveAgentConfigFail'));+ });++ it('does not toast on unmount when the flush succeeds', async () => {+ permissionState.allowed = true;+ flushSave.mockImplementation(async () => {+ profileStoreState.promptSaveStatus = 'saved';+ });++ const { unmount } = render(<EditorCanvas />);+ unmount();++ await waitFor(() => expect(flushSave).toHaveBeenCalledWith('agent-a'));+ expect(messageError).not.toHaveBeenCalled();+ });++ it('hides Prompt save feedback before the first edit', () => {+ render(<EditorCanvas />);++ expect(screen.queryByTestId('prompt-save-status')).not.toBeInTheDocument();});it('ignores a stream inherited from the previously active agent', async () => {diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsxindex 3daf74d04b6..fd47b13930d 100644--- a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx@@ -9,6 +9,8 @@ import isEqual from 'fast-deep-equal';import { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { message } from '@/components/AntdStaticMethods';+import AutoSaveHint from '@/components/Editor/AutoSaveHint';import { createChatInputRichPlugins } from '@/features/ChatInput/InputEditor/plugins';import { EditingIndicator } from '@/features/EditLock';import { usePermission } from '@/hooks/usePermission';@@ -16,7 +18,8 @@ import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';import { useAgentStore } from '@/store/agent';import { useMentionOptions } from '../ProfileEditor/MentionList';-import { useProfileStore } from '../store';+import { useProfileStore, useStoreApi } from '../store';+import { type UpdateConfigById } from '../store/action';import { selectors as profileSelectors } from '../store/selectors';import TypoBar from './TypoBar';import { useSlashItems } from './useSlashItems';@@ -67,6 +70,11 @@ const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {const editorData = config?.editorData;const systemRole = config?.systemRole;const updateConfigById = useAgentStore((s) => s.updateAgentConfigById);+ const updatePromptConfigById = useCallback<UpdateConfigById>(+ (targetAgentId, payload) =>+ updateConfigById(targetAgentId, payload, { rethrow: true, showErrorMessage: false }),+ [updateConfigById],+ );const [initialLoad] = useState(editorData === undefined || editorData?.root === undefined ? EMPTY_EDITOR_STATE : editorData,);@@ -104,6 +112,9 @@ const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {const lockedByOther = useProfileStore(profileSelectors.lockedByOther);const lockHolderId = useProfileStore(profileSelectors.lockHolderId);const lockPending = useProfileStore(profileSelectors.lockPending);+ const promptLastUpdatedTime = useProfileStore(profileSelectors.promptLastUpdatedTime);+ const promptSaveStatus = useProfileStore(profileSelectors.promptSaveStatus);+ const retryPromptSave = useProfileStore((s) => s.retryPromptSave);const setHasEdited = useProfileStore((s) => s.setHasEdited);// Read-only until the lock resolves, so the user can't start typing on an agent// that turns out to be locked and get bounced mid-edit.@@ -152,7 +163,7 @@ const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {// edit. Streaming systemRole writes are programmatic and skipped above.localEditRef.current = true;setHasEdited(true);- handleContentChange(agentId, updateConfigById, sourceEditor);+ handleContentChange(agentId, updatePromptConfigById, sourceEditor);},[agentId,@@ -161,7 +172,7 @@ const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {isProgrammaticChange,setHasEdited,streamingInProgress,- updateConfigById,+ updatePromptConfigById,],);@@ -199,7 +210,7 @@ const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {// Streaming just ended, wait for editor to update its internal state then save// This ensures editorData (json) is properly updated from the markdown contentconst timer = setTimeout(() => {- handleContentChange(agentId, updateConfigById);+ handleContentChange(agentId, updatePromptConfigById);}, 100);return () => clearTimeout(timer);}@@ -212,7 +223,7 @@ const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {handleContentChange,streamingSystemRoleAgentId,streamingInProgress,- updateConfigById,+ updatePromptConfigById,]);useEffect(() => {@@ -300,7 +311,16 @@ const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {return (<Flexbox className={styles.root} gap={16}><Flexbox className={styles.header} gap={4}>- <div className={styles.title}>{t('settingAgent.prompt.title')}</div>+ <Flexbox horizontal align={'center'} distribution={'space-between'} gap={8}>+ <div className={styles.title}>{t('settingAgent.prompt.title')}</div>+ {promptSaveStatus !== 'idle' && (+ <AutoSaveHint+ lastUpdatedTime={promptLastUpdatedTime}+ saveStatus={promptSaveStatus}+ onRetry={editable ? () => void retryPromptSave() : undefined}+ />+ )}+ </Flexbox><div className={styles.desc}>{t('settingAgent.prompt.desc')}</div></Flexbox><div@@ -344,16 +364,29 @@ const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {});const EditorCanvas = memo(() => {+ const { t } = useTranslation();const agentId = useAgentStore((s) => s.activeAgentId);const flushSave = useProfileStore((s) => s.flushSave);+ // Capture the store API in the cleanup closure so the final status check+ // still works after this provider/editor unmounts.+ const storeApi = useStoreApi();// Flush the departing agent's own debouncer before this keyed editor is// replaced. The store keeps the save target and payload isolated by agentId.+ // After unmount AutoSaveHint is gone, so a failed flush must fall back to a+ // global toast. This is reliable because flushSave awaits saveQueue, and+ // enqueueSave writes promptSaveStatus: 'failed' before the queue promise+ // resolves β with no further revision overwrites after unmount.useEffect(() => () => {- if (agentId) void flushSave(agentId);+ if (!agentId) return;+ void flushSave(agentId).then(() => {+ if (storeApi.getState().promptSaveStatus === 'failed') {+ message.error(t('saveAgentConfigFail', { ns: 'common' }));+ }+ });},- [agentId, flushSave],+ [agentId, flushSave, storeApi, t],);if (!agentId) return null;diff --git a/src/routes/(main)/agent/profile/features/Header/index.test.tsx b/src/routes/(main)/agent/profile/features/Header/index.test.tsxindex 18c649c302a..ba3edb12768 100644--- a/src/routes/(main)/agent/profile/features/Header/index.test.tsx+++ b/src/routes/(main)/agent/profile/features/Header/index.test.tsx@@ -1,7 +1,7 @@import type * as LobeChatConst from '@lobechat/const';import { fireEvent, render, screen, waitFor } from '@testing-library/react';import type * as LucideReact from 'lucide-react';-import type { PropsWithChildren, ReactNode } from 'react';+import type { CSSProperties, PropsWithChildren, ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';import Header from './index';@@ -139,6 +139,7 @@ vi.mock('@/components/AntdStaticMethods', () => ({}));vi.mock('@/const/layoutTokens', () => ({+ CONVERSATION_MIN_WIDTH: 960,DESKTOP_HEADER_ICON_SMALL_SIZE: 24,}));@@ -147,9 +148,19 @@ vi.mock('@/features/AgentBreadcrumb', () => ({}));vi.mock('@/features/NavHeader', () => ({- default: ({ left, right }: { left?: ReactNode; right?: ReactNode }) => (+ default: ({+ left,+ right,+ styles,+ }: {+ left?: ReactNode;+ right?: ReactNode;+ styles?: { left?: CSSProperties };+ }) => (<header>- {left}+ <div data-testid="nav-header-left" style={styles?.left}>+ {left}+ </div>{right}</header>),@@ -223,6 +234,14 @@ describe('Agent profile Header', () => {mocks.profileState.editor = undefined;});+ it('aligns the breadcrumb with the responsive profile content column', () => {+ render(<Header />);++ expect(screen.getByTestId('nav-header-left').style.paddingInlineStart).toBe(+ 'max(8px, calc((100% - 960px) / 2 + 16px))',+ );+ });+it('should show the markdown export action', () => {render(<Header />);diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsxindex e913580ae9c..533b6738e9a 100644--- a/src/routes/(main)/agent/profile/features/Header/index.tsx+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx@@ -18,7 +18,7 @@ import { useTranslation } from 'react-i18next';import { useAgentTransferMenuItem } from '@/business/client/hooks/useAgentTransferMenuItem';import { useBusinessAgentImportMenuItem } from '@/business/client/hooks/useBusinessAgentImportMenuItem';import { message } from '@/components/AntdStaticMethods';-import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';+import { CONVERSATION_MIN_WIDTH, DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';import AgentBreadcrumb from '@/features/AgentBreadcrumb';import NavHeader from '@/features/NavHeader';import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';@@ -246,7 +246,6 @@ const Header = memo(() => {return (<NavHeader- styles={{ left: { paddingInlineStart: 24 } }}left={<Flexbox horizontal align={'center'} gap={8}>{activeAgentId && (@@ -272,6 +271,11 @@ const Header = memo(() => {)}</Flexbox>}+ styles={{+ left: {+ paddingInlineStart: `max(8px, calc((100% - ${CONVERSATION_MIN_WIDTH}px) / 2 + 16px))`,+ },+ }}/>);});diff --git a/src/routes/(main)/agent/profile/features/store/action.test.ts b/src/routes/(main)/agent/profile/features/store/action.test.tsindex 1c151545ea5..b94efcdc18c 100644--- a/src/routes/(main)/agent/profile/features/store/action.test.ts+++ b/src/routes/(main)/agent/profile/features/store/action.test.ts@@ -21,6 +21,7 @@ describe('agent profile store actions', () => {});afterEach(() => {+ vi.restoreAllMocks();vi.useRealTimers();});@@ -45,6 +46,8 @@ describe('agent profile store actions', () => {editorData: { root: { children: ['agent-b'] } },systemRole: 'agent-b draft',});+ expect(profileStore.getState().promptSaveStatus).toBe('saved');+ expect(profileStore.getState().promptLastUpdatedTime).toBeInstanceOf(Date);});it('serializes saves emitted by one editor store', async () => {@@ -69,6 +72,11 @@ describe('agent profile store actions', () => {expect(updateConfigById).toHaveBeenLastCalledWith('agent-a', expect.any(Object));resolveAgentA?.();+ await Promise.resolve();++ // Agent A's older completion must not mark the newer Agent B draft as saved.+ expect(profileStore.getState().promptSaveStatus).toBe('saving');+await profileStore.getState().flushSave();expect(updateConfigById).toHaveBeenCalledTimes(2);@@ -96,4 +104,33 @@ describe('agent profile store actions', () => {systemRole: 'agent-a delayed draft',});});++ it('keeps a failed Prompt save visible and retries the same draft', async () => {+ const profileStore = createStore({ editor });+ const updateConfigById = vi+ .fn()+ .mockRejectedValueOnce(new Error('save failed'))+ .mockResolvedValueOnce(undefined);+ vi.spyOn(console, 'error').mockImplementation(() => {});++ profileStore.getState().handleContentChange('agent-a', updateConfigById);++ expect(profileStore.getState().promptSaveStatus).toBe('saving');++ await vi.advanceTimersByTimeAsync(EDITOR_DEBOUNCE_TIME);+ await profileStore.getState().flushSave();++ expect(profileStore.getState().promptSaveStatus).toBe('failed');+ expect(profileStore.getState().promptLastUpdatedTime).toBeNull();++ await profileStore.getState().retryPromptSave();++ expect(updateConfigById).toHaveBeenCalledTimes(2);+ expect(updateConfigById).toHaveBeenLastCalledWith('agent-a', {+ editorData: { root: { children: ['agent-a'] } },+ systemRole: 'agent-a draft',+ });+ expect(profileStore.getState().promptSaveStatus).toBe('saved');+ expect(profileStore.getState().promptLastUpdatedTime).toBeInstanceOf(Date);+ });});diff --git a/src/routes/(main)/agent/profile/features/store/action.ts b/src/routes/(main)/agent/profile/features/store/action.tsindex da22f813e6a..0f0512700d9 100644--- a/src/routes/(main)/agent/profile/features/store/action.ts+++ b/src/routes/(main)/agent/profile/features/store/action.ts@@ -10,11 +10,12 @@ type SaveConfigPayload = {systemRole: string;};-type UpdateConfigById = (agentId: string, payload: SaveConfigPayload) => Promise<void>;+export type UpdateConfigById = (agentId: string, payload: SaveConfigPayload) => Promise<void>;interface PendingSave {agentId: string;payload: SaveConfigPayload;+ revision: number;updateConfigById: UpdateConfigById;}@@ -33,6 +34,8 @@ export interface Action {updateConfigById: UpdateConfigById,sourceEditor?: State['editor'],) => void;+ /** Retry the latest failed Prompt autosave. */+ retryPromptSave: () => Promise<void>;/** Latch edit-intent so the lock driver acquires the lock on first real edit. */setHasEdited: (value: boolean) => void;/** Publish the latest edit-lock state from the always-mounted lock driver. */@@ -51,13 +54,31 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =// save concurrently because AgentStore now owns independent abort signals// per agent.let saveQueue = Promise.resolve();+ let latestSaveRevision = 0;+ let failedSave: PendingSave | undefined;++ const createPendingSave = (pendingSave: Omit<PendingSave, 'revision'>): PendingSave => {+ const nextSave = { ...pendingSave, revision: ++latestSaveRevision };+ failedSave = undefined;+ set({ promptSaveStatus: 'saving' });+ return nextSave;+ };- const enqueueSave = ({ agentId, payload, updateConfigById }: PendingSave) => {+ const enqueueSave = (pendingSave: PendingSave) => {+ const { agentId, payload, revision, updateConfigById } = pendingSave;saveQueue = saveQueue.then(async () => {try {await updateConfigById(agentId, payload);+ if (revision === latestSaveRevision) {+ failedSave = undefined;+ set({ promptLastUpdatedTime: new Date(), promptSaveStatus: 'saved' });+ }} catch (error) {console.error('[ProfileEditor] Failed to save:', error);+ if (revision === latestSaveRevision) {+ failedSave = pendingSave;+ set({ promptSaveStatus: 'failed' });+ }}});@@ -127,14 +148,16 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =// Save to configtry {- await enqueueSave({- agentId,- payload: {- editorData: structuredClone(editorData || {}),- systemRole: finalContent,- },- updateConfigById,- });+ await enqueueSave(+ createPendingSave({+ agentId,+ payload: {+ editorData: structuredClone(editorData || {}),+ systemRole: finalContent,+ },+ updateConfigById,+ }),+ );} catch (error) {console.error('[ProfileEditor] Failed to save streaming content:', error);}@@ -163,18 +186,28 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';const jsonContent = editor.getDocument('json') as unknown as Record<string, unknown>;- getDebouncedSave(agentId)({- agentId,- payload: {- editorData: structuredClone(jsonContent || {}),- systemRole: markdownContent || '',- },- updateConfigById,- });+ getDebouncedSave(agentId)(+ createPendingSave({+ agentId,+ payload: {+ editorData: structuredClone(jsonContent || {}),+ systemRole: markdownContent || '',+ },+ updateConfigById,+ }),+ );} catch (error) {console.error('[ProfileEditor] Failed to read editor content:', error);}},+ retryPromptSave: async () => {+ const pendingSave = failedSave;+ if (!pendingSave) return;++ failedSave = undefined;+ set({ promptSaveStatus: 'saving' });+ await enqueueSave(pendingSave);+ },setHasEdited: (value) => {if (get().hasEdited !== value) set({ hasEdited: value });},diff --git a/src/routes/(main)/agent/profile/features/store/initialState.ts b/src/routes/(main)/agent/profile/features/store/initialState.tsindex 5df8cfe55ea..f3b393063ad 100644--- a/src/routes/(main)/agent/profile/features/store/initialState.ts+++ b/src/routes/(main)/agent/profile/features/store/initialState.ts@@ -1,6 +1,8 @@import { type IEditor } from '@lobehub/editor';import { type EditorState } from '@lobehub/editor/react';+import { type SaveStatus } from '@/types/saveState';+export interface EditLockState {holderId: string | null;lockedByOther: boolean;@@ -23,6 +25,10 @@ export interface State extends PublicState {* is resolved before the (loading-gated) editor renders.*/lockState: EditLockState;+ /** Timestamp of the latest successful Prompt autosave. */+ promptLastUpdatedTime: Date | null;+ /** Save lifecycle owned only by the Prompt editor. */+ promptSaveStatus: SaveStatus;/*** Content being streamed from AI*/@@ -38,6 +44,8 @@ export const initialState: State = {// Start pending (read-only) so the editor never flashes editable before the// lock driver has resolved whether the agent is free.lockState: { holderId: null, lockedByOther: false, pending: true },+ promptLastUpdatedTime: null,+ promptSaveStatus: 'idle',streamingContent: undefined,streamingInProgress: false,};diff --git a/src/routes/(main)/agent/profile/features/store/selectors.ts b/src/routes/(main)/agent/profile/features/store/selectors.tsindex cc745c77f57..4340dcb6325 100644--- a/src/routes/(main)/agent/profile/features/store/selectors.ts+++ b/src/routes/(main)/agent/profile/features/store/selectors.ts@@ -7,4 +7,6 @@ export const selectors = {lockHolderId: (s: Store) => s.lockState.holderId,lockPending: (s: Store) => s.lockState.pending,lockedByOther: (s: Store) => s.lockState.lockedByOther,+ promptLastUpdatedTime: (s: Store) => s.promptLastUpdatedTime,+ promptSaveStatus: (s: Store) => s.promptSaveStatus,};diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex 0f12124ab69..cc3c0d023fa 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -540,6 +540,26 @@ describe('AgentSlice Actions', () => {expect(refreshSpy).toHaveBeenCalledWith('agent-1');expect(result.current.saveStatus).toBe('idle');});++ it('should let a scoped editor own config failure feedback', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockRejectedValue(new Error('save failed'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ await act(async () => {+ await expect(+ result.current.updateAgentConfigById(+ 'agent-1',+ { editorData: {}, systemRole: 'draft' },+ { rethrow: true, showErrorMessage: false },+ ),+ ).rejects.toThrow('save failed');+ });++ expect(message.error).not.toHaveBeenCalled();+ expect(result.current.saveStatus).toBe('idle');+ });});describe('updateAgentMeta', () => {diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex f6482c6baaf..0629c79012b 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -47,6 +47,13 @@ type AgentMetaUpdate = Partial<>;type AgencyConfigPatch = PartialDeep<LobeAgentAgencyConfig>;+interface AgentConfigUpdateOptions {+ /** Propagate the persistence failure so a scoped editor can render failed + Retry. */+ rethrow?: boolean;+ /** Keep generic error messaging for ordinary config controls. @default true */+ showErrorMessage?: boolean;+}+const preserveWorkingDirDeleteMarkers = (merged: LobeAgentAgencyConfig,patch: AgencyConfigPatch,@@ -271,6 +278,7 @@ export class AgentSliceActionImpl {updateAgentConfigById = async (agentId: string,config: PartialDeep<LobeAgentConfig>,+ options?: AgentConfigUpdateOptions,): Promise<void> => {if (!agentId) return;@@ -280,7 +288,7 @@ export class AgentSliceActionImpl {);try {- await this.#get().optimisticUpdateAgentConfig(agentId, config, controller.signal);+ await this.#get().optimisticUpdateAgentConfig(agentId, config, controller.signal, options);} finally {if (this.#updateAgentConfigControllers.get(agentId) === controller) {this.#updateAgentConfigControllers.delete(agentId);@@ -555,6 +563,7 @@ export class AgentSliceActionImpl {id: string,data: PartialDeep<LobeAgentConfig>,signal?: AbortSignal,+ options?: AgentConfigUpdateOptions,): Promise<void> => {const { internal_dispatchAgentMap, updateSaveStatus } = this.#get();const mergedData = this.#mergeLatestAgencyConfigPatch(id, data);@@ -585,7 +594,9 @@ export class AgentSliceActionImpl {// A swallowed failure reads as saved and surfaces later as mysterious// data loss (the next refetch reverts the optimistic value) β tell the// user right away.- message.error(t('saveAgentConfigFail', { ns: 'common' }));+ if (options?.showErrorMessage !== false) {+ message.error(t('saveAgentConfigFail', { ns: 'common' }));+ }// Roll back only agencyConfig patches: those are discrete picks the// server actively validates (e.g. a workspace agent binding a// non-workspace device is rejected), so keeping the optimistic value@@ -594,6 +605,7 @@ export class AgentSliceActionImpl {// form edits on a transient failure (see #16337).if (data.agencyConfig) await this.#get().internal_refreshAgentConfig(id);}+ if (options?.rethrow) throw error;}};