π€― 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: synchronize task editor and grouped retries (#17585)
YuTengjingb48fbfde0e35
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.tsindex 46777f2c1d0..9a29097acb0 100644--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts@@ -155,6 +155,32 @@ describe('Task Router Integration', () => {}),).rejects.toThrow('Assignee agent not found');});++ it('should clear stale editorData for instruction-only updates', async () => {+ const task = await caller.create({+ editorData: { root: { children: [{ text: 'Old instruction' }] } },+ instruction: 'Old instruction',+ name: 'Editable task',+ });++ const instructionOnlyUpdate = await caller.update({+ id: task.data.id,+ instruction: 'New instruction',+ });++ expect(instructionOnlyUpdate.data.instruction).toBe('New instruction');+ expect(instructionOnlyUpdate.data.editorData).toBeNull();++ const nextEditorData = { root: { children: [{ text: 'Rich instruction' }] } };+ const richTextUpdate = await caller.update({+ editorData: nextEditorData,+ id: task.data.id,+ instruction: 'Rich instruction',+ });++ expect(richTextUpdate.data.instruction).toBe('Rich instruction');+ expect(richTextUpdate.data.editorData).toEqual(nextEditorData);+ });});describe('subtasks + dependencies', () => {@@ -329,6 +355,33 @@ describe('Task Router Integration', () => {const deletedDetail = await caller.detail({ id: task.data.identifier });expect(deletedDetail.data.activities?.some((a) => a.id === added.data.id)).toBe(false);});++ it('should clear stale editorData for content-only comment updates', async () => {+ const task = await caller.create({ instruction: 'Test' });+ const comment = await caller.addComment({+ content: 'Old comment',+ editorData: { root: { children: [{ text: 'Old comment' }] } },+ id: task.data.id,+ });++ const contentOnlyUpdate = await caller.updateComment({+ commentId: comment.data.id,+ content: 'New comment',+ });++ expect(contentOnlyUpdate.data.content).toBe('New comment');+ expect(contentOnlyUpdate.data.editorData).toBeNull();++ const nextEditorData = { root: { children: [{ text: 'Rich comment' }] } };+ const richTextUpdate = await caller.updateComment({+ commentId: comment.data.id,+ content: 'Rich comment',+ editorData: nextEditorData,+ });++ expect(richTextUpdate.data.content).toBe('Rich comment');+ expect(richTextUpdate.data.editorData).toEqual(nextEditorData);+ });});describe('review config', () => {diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex 1a308728286..c92399845c3 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -313,7 +313,7 @@ export const taskRouter = router({.mutation(async ({ input, ctx }) => {try {const comment = await ctx.taskModel.updateComment(input.commentId, input.content, {- editorData: input.editorData,+ editorData: input.editorData === undefined ? null : input.editorData,});if (!comment) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Comment not found' });@@ -1058,7 +1058,16 @@ export const taskRouter = router({const updateData =parentTaskId === undefined ? data : { ...data, parentTaskId: resolvedParentTaskId };- const task = await model.update(resolved.id, updateData);+ // `instruction` is the markdown source of truth while `editorData` is its+ // rich-text mirror. Text-only callers (for example the editTask builtin)+ // cannot produce Lexical JSON, so discard the stale mirror and let the+ // editor rebuild from markdown. Callers that provide both fields keep+ // their explicit editor state.+ const normalizedUpdateData =+ updateData.instruction !== undefined && updateData.editorData === undefined+ ? { ...updateData, editorData: null }+ : updateData;+ const task = await model.update(resolved.id, normalizedUpdateData);if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });return { data: task, message: 'Task updated', success: true };} catch (error) {diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.tsindex f4c37cdae22..3244d695ecb 100644--- a/packages/builtin-tool-task/src/client/executor/index.ts+++ b/packages/builtin-tool-task/src/client/executor/index.ts@@ -422,7 +422,10 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {}if (Object.keys(updateData).length > 0) {- ops.push(store.updateTask(identifier, updateData));+ // `external` is the default, but keep it explicit because editTask must+ // bump the mounted editor's content revision rather than look like an+ // autosave echo.+ ops.push(store.updateTask(identifier, updateData, { source: 'external' }));}if (addDependencies?.length) {diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsxindex 9f450c70a84..bdd862d0bbf 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx@@ -13,7 +13,7 @@ import { lambdaClient } from '@/libs/trpc/client';import { useTaskStore } from '@/store/task';import { taskDetailSelectors } from '@/store/task/selectors';-const DEBOUNCE_MS = 300;+import { useTaskInstructionAutosave } from './useTaskInstructionAutosave';// Stable lock RPC binding for the task resource.const taskLockClient: EditLockClient = {@@ -28,6 +28,7 @@ const TaskInstruction = memo(() => {const { t } = useTranslation('chat');const { allowed: canEditTask } = usePermission('create_content');const instruction = useTaskStore(taskDetailSelectors.activeTaskInstruction);+ const instructionRevision = useTaskStore(taskDetailSelectors.activeTaskInstructionRevision);const persistedEditorData = useTaskStore(taskDetailSelectors.activeTaskEditorData);const taskId = useTaskStore(taskDetailSelectors.activeTaskId);const taskWorkspaceId = useTaskStore(taskDetailSelectors.activeTaskWorkspaceId);@@ -55,11 +56,6 @@ const TaskInstruction = memo(() => {// that turns out to be locked and get bounced mid-edit.const editable = canEditTask && !lock.lockedByOther && !lock.pending;- const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);- // Skip save when the serialized state matches the last persisted snapshot β- // Lexical fires content-change for selection moves and other no-op events.- const lastSavedJsonRef = useRef<string | undefined>(undefined);-const editorData = useMemo(() => ({content: instruction ?? '',@@ -74,32 +70,15 @@ const TaskInstruction = memo(() => {}}, [persistedFiles]);- useEffect(() => {- lastSavedJsonRef.current = undefined;- return () => {- if (debounceRef.current) clearTimeout(debounceRef.current);- };- }, [taskId]);-- const handleContentChange = useCallback(() => {- if (!editable) return;- if (!editor || !taskId) return;-- setEdited(true);-- if (debounceRef.current) clearTimeout(debounceRef.current);- debounceRef.current = setTimeout(() => {- const json = editor.getDocument('json') as unknown;- const jsonSignature = JSON.stringify(json);- if (jsonSignature === lastSavedJsonRef.current) return;- lastSavedJsonRef.current = jsonSignature;-- const markdown = String(editor.getDocument('markdown') ?? '');- updateTask(taskId, { editorData: json, instruction: markdown }).catch((e) => {- console.error('[TaskInstruction] Failed to save:', e);- });- }, DEBOUNCE_MS);- }, [editable, editor, taskId, updateTask]);+ const handleEdit = useCallback(() => setEdited(true), []);+ const handleContentChange = useTaskInstructionAutosave({+ contentRevision: instructionRevision,+ editable,+ editor,+ onEdit: handleEdit,+ taskId,+ updateTask,+ });const handleAttach = useCallback(() => {pickAndInsertAttachments(editor);@@ -111,7 +90,11 @@ const TaskInstruction = memo(() => {holderId={lock.lockedByOther ? lock.holderId : null}pending={canEditTask && lock.pending}/>+ {/* editTask can update this mounted editor. The store revision changes only for external+ snapshots, so local autosave echoes and unchanged polling snapshots do not reload live+ input. */}<EditorCanvas+ contentRevision={instructionRevision}disabled={!canEditTask}editable={!lock.lockedByOther && !lock.pending}editor={editor}diff --git a/src/features/AgentTasks/AgentTaskDetail/useTaskInstructionAutosave.test.ts b/src/features/AgentTasks/AgentTaskDetail/useTaskInstructionAutosave.test.tsnew file mode 100644index 00000000000..f2e8d3c4afa--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/useTaskInstructionAutosave.test.ts@@ -0,0 +1,102 @@+/**+ * @vitest-environment happy-dom+ */+import type { IEditor } from '@lobehub/editor';+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { TaskStore } from '@/store/task';+import { useTaskStore } from '@/store/task';++import { useTaskInstructionAutosave } from './useTaskInstructionAutosave';++describe('useTaskInstructionAutosave', () => {+ const editor = {+ getDocument: vi.fn((type: string) =>+ type === 'json' ? { root: { children: [{ text: 'Local edit' }] } } : 'Local edit',+ ),+ } as unknown as IEditor;+ const onEdit = vi.fn();+ const updateTask = vi.fn().mockResolvedValue(undefined) as TaskStore['updateTask'];++ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ useTaskStore.setState({ taskInstructionRevisionMap: {} });+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('keeps a pending autosave when the external revision stays stable', async () => {+ const { result, rerender } = renderHook(+ ({ contentRevision }) =>+ useTaskInstructionAutosave({+ contentRevision,+ editable: true,+ editor,+ onEdit,+ taskId: 'T-1',+ updateTask,+ }),+ { initialProps: { contentRevision: 0 } },+ );++ act(() => result.current());+ rerender({ contentRevision: 0 });+ await act(async () => vi.advanceTimersByTimeAsync(300));++ expect(updateTask).toHaveBeenCalledWith(+ 'T-1',+ {+ editorData: { root: { children: [{ text: 'Local edit' }] } },+ instruction: 'Local edit',+ },+ { source: 'editor' },+ );+ });++ it('cancels a pending autosave when an external instruction revision arrives', async () => {+ const { result, rerender } = renderHook(+ ({ contentRevision }) =>+ useTaskInstructionAutosave({+ contentRevision,+ editable: true,+ editor,+ onEdit,+ taskId: 'T-1',+ updateTask,+ }),+ { initialProps: { contentRevision: 0 } },+ );++ act(() => result.current());+ rerender({ contentRevision: 1 });+ await act(async () => vi.advanceTimersByTimeAsync(300));++ expect(updateTask).not.toHaveBeenCalled();+ });++ it('drops a queued autosave when the Store revision changes before React rerenders', async () => {+ const { result } = renderHook(() =>+ useTaskInstructionAutosave({+ contentRevision: 0,+ editable: true,+ editor,+ onEdit,+ taskId: 'T-1',+ updateTask,+ }),+ );++ act(() => result.current());+ act(() => {+ useTaskStore.setState({ taskInstructionRevisionMap: { 'T-1': 1 } });+ });+ await act(async () => vi.advanceTimersByTimeAsync(300));++ expect(editor.getDocument).not.toHaveBeenCalled();+ expect(updateTask).not.toHaveBeenCalled();+ });+});diff --git a/src/features/AgentTasks/AgentTaskDetail/useTaskInstructionAutosave.ts b/src/features/AgentTasks/AgentTaskDetail/useTaskInstructionAutosave.tsnew file mode 100644index 00000000000..fb906f81606--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/useTaskInstructionAutosave.ts@@ -0,0 +1,82 @@+import type { IEditor } from '@lobehub/editor';+import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';++import type { TaskStore } from '@/store/task';+import { useTaskStore } from '@/store/task';++const DEBOUNCE_MS = 300;++interface UseTaskInstructionAutosaveOptions {+ contentRevision: number;+ editable: boolean;+ editor: IEditor | undefined;+ onEdit: () => void;+ taskId?: string;+ updateTask: TaskStore['updateTask'];+}++export const useTaskInstructionAutosave = ({+ contentRevision,+ editable,+ editor,+ onEdit,+ taskId,+ updateTask,+}: UseTaskInstructionAutosaveOptions) => {+ const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);+ const lastSavedJsonRef = useRef<string | undefined>(undefined);+ const lastContentRevisionRef = useRef(contentRevision);++ const cancelPendingSave = useCallback(() => {+ if (debounceRef.current) clearTimeout(debounceRef.current);+ debounceRef.current = undefined;+ }, []);++ useEffect(() => {+ lastSavedJsonRef.current = undefined;+ return cancelPendingSave;+ }, [cancelPendingSave, taskId]);++ // Cancel the local debounce before EditorDataMode applies the corresponding+ // external snapshot in its passive effect. Otherwise the stale timer could+ // write the pre-tool document back over the authoritative editTask result.+ useLayoutEffect(() => {+ if (lastContentRevisionRef.current === contentRevision) return;+ lastContentRevisionRef.current = contentRevision;+ cancelPendingSave();+ lastSavedJsonRef.current = undefined;+ }, [cancelPendingSave, contentRevision]);++ return useCallback(() => {+ if (!editable || !editor || !taskId) return;++ onEdit();+ cancelPendingSave();+ const scheduledContentRevision = contentRevision;+ debounceRef.current = setTimeout(() => {+ debounceRef.current = undefined;++ /**+ * editTask updates the Store revision synchronously, but React may not+ * have committed the layout effect that cancels this timer yet. Checking+ * the Store closes that dispatch-to-commit window before reading or+ * persisting the stale editor document.+ */+ const currentContentRevision =+ useTaskStore.getState().taskInstructionRevisionMap[taskId] ?? 0;+ if (currentContentRevision !== scheduledContentRevision) return;++ const json = editor.getDocument('json') as unknown;+ const jsonSignature = JSON.stringify(json);+ if (jsonSignature === lastSavedJsonRef.current) return;+ lastSavedJsonRef.current = jsonSignature;++ const markdown = String(editor.getDocument('markdown') ?? '');+ updateTask(taskId, { editorData: json, instruction: markdown }, { source: 'editor' }).catch(+ (error) => {+ console.error('[TaskInstruction] Failed to save:', error);+ },+ );+ }, DEBOUNCE_MS);+ }, [cancelPendingSave, contentRevision, editable, editor, onEdit, taskId, updateTask]);+};diff --git a/src/features/Conversation/Error/TraceIdError.tsx b/src/features/Conversation/Error/TraceIdError.tsxindex 5748e2c6f5c..9660743ed02 100644--- a/src/features/Conversation/Error/TraceIdError.tsx+++ b/src/features/Conversation/Error/TraceIdError.tsx@@ -14,10 +14,11 @@ import { useRetryParentMessage } from './useRetryParentMessage';interface TraceIdErrorProps {id: string;+ onRetry?: () => Promise<void> | void;traceId?: string;}-const TraceIdError = memo<TraceIdErrorProps>(({ id, traceId }) => {+const TraceIdError = memo<TraceIdErrorProps>(({ id, onRetry, traceId }) => {const { t } = useTranslation('error');const { disabled, loading, retryParentMessage } = useRetryParentMessage(id);@@ -32,18 +33,27 @@ const TraceIdError = memo<TraceIdErrorProps>(({ id, traceId }) => {}}, [t, traceId]);+ const handleRetry = useCallback(() => {+ if (onRetry) {+ void onRetry();+ return;+ }++ void retryParentMessage();+ }, [onRetry, retryParentMessage]);+return (<BaseErrorFormavatar={<Icon icon={AlertTriangle} size={24} />}title={t('unknownError.title')}action={<Button- disabled={disabled}+ disabled={!onRetry && disabled}icon={<Icon icon={RotateCw} />}- loading={loading}+ loading={!onRetry && loading}size={'small'}type={'primary'}- onClick={() => retryParentMessage()}+ onClick={handleRetry}>{t('unknownError.retry')}</Button>diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex ba4daa21054..debc86274de 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -13,6 +13,7 @@ import ErrorMessageExtra, { useErrorContent } from './index';const navigateMock = vi.fn();const updateMessageErrorMock = vi.fn();+const dynamicComponentPropsMock = vi.hoisted(() => vi.fn());const serverConfigMock = vi.hoisted(() => ({ enableBusinessFeatures: false }));const missingTranslationKeys = vi.hoisted(() => new Set<string>());@@ -124,7 +125,16 @@ vi.mock('@/hooks/useProviderName', () => ({}));vi.mock('@/libs/next/dynamic', () => ({- default: () => () => <div>dynamic</div>,+ default: () => (props: { onRetry?: () => void }) => {+ dynamicComponentPropsMock(props);++ return (+ <div>+ dynamic+ {props.onRetry && <button onClick={props.onRetry}>dynamic-retry</button>}+ </div>+ );+ },}));vi.mock('@/store/serverConfig', () => ({@@ -161,6 +171,7 @@ const ErrorMessageWithContent = ({ data }: { data: any }) => {describe('ErrorMessageExtra', () => {beforeEach(() => {+ dynamicComponentPropsMock.mockClear();missingTranslationKeys.clear();serverConfigMock.enableBusinessFeatures = false;businessErrorContentMock.mockReturnValue({@@ -232,6 +243,31 @@ describe('ErrorMessageExtra', () => {expect(screen.queryByText('Sensitive internal configuration error')).not.toBeInTheDocument();});+ it('keeps the group retry callback on the internal server error UI', () => {+ serverConfigMock.enableBusinessFeatures = true;+ const onRegenerate = vi.fn();++ render(+ <ErrorMessageExtra+ error={{ message: 'Sensitive internal configuration error' }}+ retryScopeId="group-parent"+ data={{+ error: {+ body: { name: 'Error' },+ message: 'Sensitive internal configuration error',+ type: ChatErrorType.InternalServerError,+ },+ id: 'group-child-error',+ }}+ onRegenerate={onRegenerate}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'dynamic-retry' }));++ expect(onRegenerate).toHaveBeenCalledTimes(1);+ });+it('shows the trace-id report UI for fallback provider errors', () => {serverConfigMock.enableBusinessFeatures = true;diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 67ef1541ad0..42792b0a472 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -452,7 +452,13 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(const traceId =typeof error?.body?.traceId === 'string' ? (error.body.traceId as string) : undefined;- return <TraceIdError id={data.id} traceId={traceId} />;+ return (+ <TraceIdError+ id={data.id}+ traceId={traceId}+ onRetry={canCreate && onRegenerate ? handleManualRetry : undefined}+ />+ );}return (diff --git a/src/features/EditorCanvas/EditorCanvas.test.tsx b/src/features/EditorCanvas/EditorCanvas.test.tsxindex 410938719e8..ddfe78800c5 100644--- a/src/features/EditorCanvas/EditorCanvas.test.tsx+++ b/src/features/EditorCanvas/EditorCanvas.test.tsx@@ -2,10 +2,12 @@* @vitest-environment happy-dom*/import { type IEditor } from '@lobehub/editor';-import { cleanup, render, screen } from '@testing-library/react';+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import type { ComponentType } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { EditorCanvas } from './EditorCanvas';+import type { EditorDataModeProps } from './EditorDataMode';// Mock DocumentIdModevi.mock('./DocumentIdMode', () => ({@@ -138,6 +140,7 @@ describe('EditorCanvas', () => {render(<EditorCanvas+ contentRevision={3}editor={mockEditor}editorData={editorData}placeholder="Custom placeholder"@@ -150,6 +153,7 @@ describe('EditorCanvas', () => {const lastCall = (EditorDataMode.default as ReturnType<typeof vi.fn>).mock.calls.at(-1);expect(lastCall?.[0]).toMatchObject({+ contentRevision: 3,editor: mockEditor,editorData,onContentChange,@@ -158,6 +162,66 @@ describe('EditorCanvas', () => {});});+ it('should reload same-entity content only when its authoritative revision changes', async () => {+ const editorDataModeModule = (await vi.importActual('./EditorDataMode')) as {+ default: ComponentType<EditorDataModeProps>;+ };+ const ActualEditorDataMode = editorDataModeModule.default;++ const { rerender } = render(+ <ActualEditorDataMode+ contentRevision={0}+ editor={mockEditor}+ editorData={{ content: 'Old instruction' }}+ entityId="T-1"+ />,+ );++ const InternalEditor = await vi.importMock('./InternalEditor');+ const onInit = (InternalEditor.default as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0]+ .onInit;+ act(() => onInit?.(mockEditor));+ vi.mocked(mockEditor.setDocument).mockClear();++ rerender(+ <ActualEditorDataMode+ contentRevision={0}+ editor={mockEditor}+ editorData={{ content: 'Old instruction' }}+ entityId="T-1"+ />,+ );+ expect(mockEditor.setDocument).not.toHaveBeenCalled();++ // A refetch or local autosave can replace the props while the revision+ // stays stable. Never inspect/reload the live document in that case.+ rerender(+ <ActualEditorDataMode+ contentRevision={0}+ editor={mockEditor}+ editorData={{ content: 'New instruction' }}+ entityId="T-1"+ />,+ );+ expect(mockEditor.setDocument).not.toHaveBeenCalled();+ expect(mockEditor.getDocument).not.toHaveBeenCalled();++ rerender(+ <ActualEditorDataMode+ contentRevision={1}+ editor={mockEditor}+ editorData={{ content: 'New instruction' }}+ entityId="T-1"+ />,+ );++ await waitFor(() => {+ expect(mockEditor.setDocument).toHaveBeenCalledWith('markdown', 'New instruction', {+ keepId: true,+ });+ });+ });+it('should forward props to InternalEditor in basic mode', async () => {const onContentChange = vi.fn();const onInit = vi.fn();diff --git a/src/features/EditorCanvas/EditorCanvas.tsx b/src/features/EditorCanvas/EditorCanvas.tsxindex c691cbb56bf..3a2427154ec 100644--- a/src/features/EditorCanvas/EditorCanvas.tsx+++ b/src/features/EditorCanvas/EditorCanvas.tsx@@ -42,6 +42,13 @@ export interface EditorCanvasProps {*/autoSave?: boolean;+ /**+ * Reload an already-mounted editor when an authoritative external content+ * revision changes. Keep this stable for local autosave echoes and unchanged+ * refetches so unsaved input is never replaced by prop identity churn.+ */+ contentRevision?: number;+disabled?: boolean;/**diff --git a/src/features/EditorCanvas/EditorDataMode.tsx b/src/features/EditorCanvas/EditorDataMode.tsxindex 2707a461cb7..f54d8ea0720 100644--- a/src/features/EditorCanvas/EditorDataMode.tsx+++ b/src/features/EditorCanvas/EditorDataMode.tsx@@ -45,18 +45,30 @@ const loadEditorContent = (* EditorCanvas with editorData mode - uses provided data directly*/const EditorDataMode = memo<EditorDataModeProps>(- ({ editor, editorData, entityId, onContentChange, onInit, style, ...editorProps }) => {+ ({+ contentRevision,+ editor,+ editorData,+ entityId,+ onContentChange,+ onInit,+ style,+ ...editorProps+ }) => {const { t } = useTranslation('file');const isEditorReadyRef = useRef(false);const contentChangeLockRef = useRef(false);const lockIdRef = useRef(0);// Track the current entityId to detect entity changesconst currentEntityIdRef = useRef<string | undefined>(undefined);+ const currentContentRevisionRef = useRef<number | undefined>(undefined);// Check if we're editing a different entity// When entityId is undefined, always consider it as "changed" (backward compatibility)// When entityId is provided, check if it actually changedconst isEntityChanged = entityId === undefined || currentEntityIdRef.current !== entityId;+ const isContentRevisionChanged = currentContentRevisionRef.current !== contentRevision;+ const shouldReloadContent = isEntityChanged || isContentRevisionChanged;const loadContentWithLock = useCallback((editorInstance: IEditor) => {@@ -64,6 +76,7 @@ const EditorDataMode = memo<EditorDataModeProps>(contentChangeLockRef.current = true;if (loadEditorContent(editorInstance, editorData)) {currentEntityIdRef.current = entityId;+ currentContentRevisionRef.current = contentRevision;}queueMicrotask(() => {if (lockIdRef.current === lockId) {@@ -71,24 +84,25 @@ const EditorDataMode = memo<EditorDataModeProps>(}});},- [editorData, entityId],+ [contentRevision, editorData, entityId],);const handleInit = useCallback((editorInstance: IEditor) => {isEditorReadyRef.current = true;- if (isEntityChanged) loadContentWithLock(editorInstance);+ if (shouldReloadContent) loadContentWithLock(editorInstance);onInit?.(editorInstance);},- [isEntityChanged, loadContentWithLock, onInit],+ [loadContentWithLock, onInit, shouldReloadContent],);- // Load content when entityId changes (switching to a different entity)- // Ignore editorData changes when entityId hasn't changed to prevent focus loss during auto-save+ // Reload only for an entity switch or an explicit authoritative revision.+ // editorData object churn and local autosave echoes keep the revision stable,+ // so they cannot overwrite live input or reset the cursor.useEffect(() => {- if (!editor || !isEditorReadyRef.current || !isEntityChanged) return;+ if (!editor || !isEditorReadyRef.current || !shouldReloadContent) return;loadContentWithLock(editor);- }, [editor, isEntityChanged, loadContentWithLock]);+ }, [editor, loadContentWithLock, shouldReloadContent]);if (!editor) return null;diff --git a/src/store/task/selectors/detailSelectors.test.ts b/src/store/task/selectors/detailSelectors.test.tsindex 1c85816438b..def2f8118a9 100644--- a/src/store/task/selectors/detailSelectors.test.ts+++ b/src/store/task/selectors/detailSelectors.test.ts@@ -49,6 +49,7 @@ describe('taskDetailSelectors', () => {const state = createState({activeTaskId: 'T-1',taskDetailMap: { 'T-1': mockDetail },+ taskInstructionRevisionMap: { 'T-1': 3 },});it('should return activeTaskName', () => {@@ -71,6 +72,11 @@ describe('taskDetailSelectors', () => {expect(taskDetailSelectors.activeTaskInstruction(state)).toBe('Do something');});+ it('should return the active task instruction revision', () => {+ expect(taskDetailSelectors.activeTaskInstructionRevision(state)).toBe(3);+ expect(taskDetailSelectors.activeTaskInstructionRevision(createState())).toBe(0);+ });+it('should return activeTaskAgentId', () => {expect(taskDetailSelectors.activeTaskAgentId(state)).toBe('agt_1');});diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.tsindex ccd4dfbeb21..d3d7d30b46a 100644--- a/src/store/task/selectors/detailSelectors.ts+++ b/src/store/task/selectors/detailSelectors.ts@@ -27,6 +27,9 @@ const activeTaskCreatedByUserId = (s: TaskStoreState) => activeTaskDetail(s)?.crconst activeTaskInstruction = (s: TaskStoreState) => activeTaskDetail(s)?.instruction;+const activeTaskInstructionRevision = (s: TaskStoreState) =>+ (s.activeTaskId ? s.taskInstructionRevisionMap[s.activeTaskId] : undefined) ?? 0;+const activeTaskEditorData = (s: TaskStoreState) => activeTaskDetail(s)?.editorData;const activeTaskFiles = (s: TaskStoreState) => activeTaskDetail(s)?.files;@@ -131,6 +134,7 @@ export const taskDetailSelectors = {activeTaskFiles,activeTaskId,activeTaskInstruction,+ activeTaskInstructionRevision,activeTaskName,activeTaskParent,activeTaskPeriodicInterval,diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsindex 99fc0f7e588..83dccfd6466 100644--- a/src/store/task/slices/detail/action.test.ts+++ b/src/store/task/slices/detail/action.test.ts@@ -49,6 +49,7 @@ beforeEach(() => {isCreatingTask: false,isDeletingTask: false,taskDetailMap: {},+ taskInstructionRevisionMap: {},taskSaveStatusMap: {},});});@@ -132,6 +133,114 @@ describe('TaskDetailSliceAction', () => {expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('saved');});+ it('should clear stale editorData for instruction-only optimistic updates', async () => {+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: {+ 'T-1': {+ editorData: { root: { children: [{ text: 'Old instruction' }] } },+ identifier: 'T-1',+ instruction: 'Old instruction',+ status: 'backlog',+ },+ },+ });+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().updateTask('T-1', { instruction: 'New instruction' });++ expect(useTaskStore.getState().taskDetailMap['T-1']).toMatchObject({+ editorData: null,+ instruction: 'New instruction',+ });+ expect(useTaskStore.getState().taskInstructionRevisionMap['T-1']).toBe(1);++ const nextEditorData = { root: { children: [{ text: 'Rich instruction' }] } };+ await useTaskStore.getState().updateTask('T-1', {+ editorData: nextEditorData,+ instruction: 'Rich instruction',+ });++ expect(useTaskStore.getState().taskDetailMap['T-1']).toMatchObject({+ editorData: nextEditorData,+ instruction: 'Rich instruction',+ });+ expect(useTaskStore.getState().taskInstructionRevisionMap['T-1']).toBe(2);+ });++ it('should keep the external revision stable for editor autosaves and matching refetches', async () => {+ const editorData = { root: { children: [{ text: 'Old instruction' }] } };+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: {+ 'T-1': {+ editorData,+ identifier: 'T-1',+ instruction: 'Old instruction',+ status: 'backlog',+ },+ },+ });+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);++ await useTaskStore+ .getState()+ .updateTask('T-1', { editorData, instruction: 'Old instruction' }, { source: 'editor' });++ expect(useTaskStore.getState().taskInstructionRevisionMap['T-1']).toBeUndefined();++ vi.mocked(taskService.getDetail).mockResolvedValue({+ data: {+ editorData: { root: { children: [{ text: 'Old instruction' }] } },+ identifier: 'T-1',+ instruction: 'Old instruction',+ status: 'backlog',+ },+ success: true,+ } as any);++ await useTaskStore.getState().fetchTaskDetail('T-1');++ expect(useTaskStore.getState().taskInstructionRevisionMap['T-1']).toBeUndefined();+ });++ it('should atomically bump the revision when a refetch changes the instruction snapshot', async () => {+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: {+ 'T-1': {+ editorData: { root: { children: [{ text: 'Old instruction' }] } },+ identifier: 'T-1',+ instruction: 'Old instruction',+ status: 'running',+ },+ },+ });+ vi.mocked(taskService.getDetail).mockResolvedValue({+ data: {+ editorData: null,+ identifier: 'T-1',+ instruction: 'Tool instruction',+ status: 'running',+ },+ success: true,+ } as any);+ const observedSnapshots: Array<[string | undefined, number | undefined]> = [];+ const unsubscribe = useTaskStore.subscribe((state) => {+ observedSnapshots.push([+ state.taskDetailMap['T-1']?.instruction,+ state.taskInstructionRevisionMap['T-1'],+ ]);+ });++ await useTaskStore.getState().fetchTaskDetail('T-1');+ unsubscribe();++ expect(useTaskStore.getState().taskInstructionRevisionMap['T-1']).toBe(1);+ expect(observedSnapshots).toContainEqual(['Tool instruction', 1]);+ expect(observedSnapshots).not.toContainEqual(['Old instruction', 1]);+ });+it('should propagate error, mark saveStatus failed, refresh, and toast on failure', async () => {const { mutate } = await import('@/libs/swr');const { toast } = await import('@lobehub/ui/base-ui');@@ -154,6 +263,61 @@ describe('TaskDetailSliceAction', () => {expect(toast.error).toHaveBeenCalled();});+ it('should reload retry content after an editor autosave failure rolls back', async () => {+ const { mutate } = await import('@/libs/swr');+ const { toast } = await import('@lobehub/ui/base-ui');+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: {+ 'T-1': {+ editorData: { root: { children: [{ text: 'Persisted' }] } },+ identifier: 'T-1',+ instruction: 'Persisted',+ status: 'backlog',+ },+ },+ });+ vi.mocked(taskService.getDetail).mockResolvedValue({+ data: {+ editorData: { root: { children: [{ text: 'Persisted' }] } },+ identifier: 'T-1',+ instruction: 'Persisted',+ status: 'backlog',+ },+ success: true,+ } as any);+ vi.mocked(mutate).mockImplementation(async () => {+ await useTaskStore.getState().fetchTaskDetail('T-1');+ });+ vi.mocked(taskService.update).mockRejectedValueOnce(new Error('fail'));++ const retryData = {+ editorData: { root: { children: [{ text: 'Retry content' }] } },+ instruction: 'Retry content',+ };+ await expect(+ useTaskStore.getState().updateTask('T-1', retryData, { source: 'editor' }),+ ).rejects.toThrow('fail');++ expect(useTaskStore.getState().taskDetailMap['T-1'].instruction).toBe('Persisted');+ expect(useTaskStore.getState().taskInstructionRevisionMap['T-1']).toBe(1);++ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);+ const toastOptions = vi.mocked(toast.error).mock.calls.at(-1)?.[0];+ if (!toastOptions || typeof toastOptions === 'string') {+ throw new Error('Expected the failed save toast to expose a Retry action.');+ }+ const retryAction = toastOptions.actions?.[0];+ expect(retryAction).toBeDefined();+ retryAction?.onClick?.();++ await vi.waitFor(() => {+ expect(useTaskStore.getState().taskDetailMap['T-1'].instruction).toBe('Retry content');+ expect(useTaskStore.getState().taskInstructionRevisionMap['T-1']).toBe(2);+ expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('saved');+ });+ });+it('should refresh the cached parent on failure when updating from a subtask detail page', async () => {const { mutate } = await import('@/libs/swr');useTaskStore.setState({diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex 0ace6350c03..0839f93e2f3 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -35,6 +35,14 @@ export interface TaskUpdatePayload {priority?: number;}+export interface TaskUpdateOptions {+ /**+ * The mounted editor marks its own autosaves so they do not request an+ * external-content reload. Tool calls and refetches are authoritative by default.+ */+ source?: 'editor' | 'external';+}+const TASK_DETAIL_POLL_INTERVAL = 10_000;const hasInFlightSubtask = (subtasks: TaskDetailSubtask[] | undefined): boolean =>@@ -60,6 +68,15 @@ const hasInFlightActivity = (detail: TaskDetailData | undefined): boolean => {);};+const hasInstructionSnapshotChanged = (+ current: TaskDetailData | undefined,+ next: TaskDetailData | undefined,+): boolean => {+ if (!current || !next) return false;++ return current.instruction !== next.instruction || !isEqual(current.editorData, next.editorData);+};+type Setter = StoreSetter<TaskStore>;export const createTaskDetailSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>@@ -138,20 +155,26 @@ export class TaskDetailSliceActionImpl {throw notFound;}- this.internal_dispatchTaskDetail({- id: detail.identifier,- type: 'setTaskDetail',- value: detail,- });+ this.internal_dispatchTaskDetail(+ {+ id: detail.identifier,+ type: 'setTaskDetail',+ value: detail,+ },+ { instructionSource: 'external' },+ );// When looked up by raw DB id (e.g. `task_xxx`), also store under that key// so `activeTaskId` β `taskDetailMap[activeTaskId]` resolves correctly.if (resolvedId !== detail.identifier) {- this.internal_dispatchTaskDetail({- id: resolvedId,- type: 'setTaskDetail',- value: detail,- });+ this.internal_dispatchTaskDetail(+ {+ id: resolvedId,+ type: 'setTaskDetail',+ value: detail,+ },+ { instructionSource: 'external' },+ );}return detail;@@ -319,10 +342,19 @@ export class TaskDetailSliceActionImpl {}};- updateTask = async (id: string, data: TaskUpdatePayload): Promise<void> => {+ updateTask = async (+ id: string,+ data: TaskUpdatePayload,+ options?: TaskUpdateOptions,+ ): Promise<void> => {const { assigneeAgentId, ...rest } = data;const optimisticRest = { ...rest };delete optimisticRest.parentTaskId;+ // editTask may send only instruction while the detail store still holds old rich editorData.+ // Mirror the server normalization so the optimistic render cannot prefer stale JSON.+ if (optimisticRest.instruction !== undefined && optimisticRest.editorData === undefined) {+ optimisticRest.editorData = null;+ }const optimistic: Partial<TaskDetailData> = {...optimisticRest,...(assigneeAgentId !== undefined ? { agentId: assigneeAgentId } : {}),@@ -343,7 +375,10 @@ export class TaskDetailSliceActionImpl {);};- this.internal_dispatchTaskDetail({ id, type: 'updateTaskDetail', value: optimistic });+ this.internal_dispatchTaskDetail(+ { id, type: 'updateTaskDetail', value: optimistic },+ options?.source === 'editor' ? undefined : { instructionSource: 'external' },+ );await runMutation(this.#set, this.#get, {mutate: () => taskService.update(id, data),@@ -352,7 +387,17 @@ export class TaskDetailSliceActionImpl {// optimistic dispatch above is reconciled from the source of record.onError: async (error) => {await refreshPatchedTargets();- saveToast(error, { retry: () => void this.#get().updateTask(id, data) });+ /**+ * The rollback refetch has already replaced the editor's failed local+ * content. Treating Retry as another editor echo would update only the+ * Store and server, leaving the mounted editor on the rollback snapshot.+ */+ const retry = () =>+ void this.#get().updateTask(id, data, {+ ...options,+ source: 'external',+ });+ saveToast(error, { retry });},setStatus: (status) => this.#get().internal_setTaskSaveStatus(id, status),});@@ -392,11 +437,53 @@ export class TaskDetailSliceActionImpl {);};- internal_dispatchTaskDetail = (payload: TaskDetailDispatch): void => {- const currentMap = this.#get().taskDetailMap;+ internal_dispatchTaskDetail = (+ payload: TaskDetailDispatch,+ options?: { instructionSource?: 'external' },+ ): void => {+ const state = this.#get();+ const currentMap = state.taskDetailMap;const nextMap = taskDetailReducer(currentMap, payload);+ const shouldIncrementInstructionRevision =+ options?.instructionSource === 'external' &&+ hasInstructionSnapshotChanged(currentMap[payload.id], nextMap[payload.id]);+ const shouldDeleteInstructionRevision =+ payload.type === 'deleteTaskDetail' &&+ state.taskInstructionRevisionMap[payload.id] !== undefined;++ if (+ isEqual(nextMap, currentMap) &&+ !shouldIncrementInstructionRevision &&+ !shouldDeleteInstructionRevision+ ) {+ return;+ }++ if (shouldIncrementInstructionRevision) {+ this.#set(+ {+ taskDetailMap: nextMap,+ taskInstructionRevisionMap: {+ ...state.taskInstructionRevisionMap,+ [payload.id]: (state.taskInstructionRevisionMap[payload.id] ?? 0) + 1,+ },+ },+ false,+ `internal_dispatchTaskDetail/${payload.type}`,+ );+ return;+ }- if (isEqual(nextMap, currentMap)) return;+ if (shouldDeleteInstructionRevision) {+ const taskInstructionRevisionMap = { ...state.taskInstructionRevisionMap };+ delete taskInstructionRevisionMap[payload.id];+ this.#set(+ { taskDetailMap: nextMap, taskInstructionRevisionMap },+ false,+ `internal_dispatchTaskDetail/${payload.type}`,+ );+ return;+ }this.#set({ taskDetailMap: nextMap }, false, `internal_dispatchTaskDetail/${payload.type}`);};diff --git a/src/store/task/slices/detail/initialState.ts b/src/store/task/slices/detail/initialState.tsindex 2af168b9a01..19cb05b4558 100644--- a/src/store/task/slices/detail/initialState.ts+++ b/src/store/task/slices/detail/initialState.ts@@ -15,6 +15,12 @@ export interface TaskDetailSliceState {isCreatingTask: boolean;isDeletingTask: boolean;taskDetailMap: Record<string, TaskDetailData>;+ /**+ * Increments only when an authoritative source outside the mounted task editor+ * changes its persisted instruction snapshot. The editor uses this as an+ * explicit reload signal instead of comparing against live, unsaved content.+ */+ taskInstructionRevisionMap: Record<string, number>;// Save status is scoped per task id (mirrors `taskDetailMap`). A store-wide// field would leak one task's `failed` state across navigation, since// `setActiveTaskId` only swaps `activeTaskId` and never clears the status.@@ -25,5 +31,6 @@ export const initialTaskDetailSliceState: TaskDetailSliceState = {isCreatingTask: false,isDeletingTask: false,taskDetailMap: {},+ taskInstructionRevisionMap: {},taskSaveStatusMap: {},};