🤯 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
✨ feat(save-state): write-side save-state framework (#16668)
Arvin Xu9fa6e02a0755
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.mdindex db908448990..0e01bd3d172 100644--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md@@ -55,6 +55,28 @@DOES catch TRPC). Needs a raw CDP ws (see C2 for getting the endpoint).- Server-side: temporarily make the one endpoint return 500.+### A6. ✅ WORKS — WRITE-side (mutation) fault injection, same HMR technique++- To test the write-side save-state UI (`AutoSaveHint` failed tag + `saveToast`),+ inject the throw into the client service **mutation** method, not a fetcher:+ ```ts+ // src/services/task.ts — the method the store action calls (updateTask → taskService.update)+ update = async (id, data) => {+ // [AGENT-TEST] REMOVE+ if (true)+ throw Object.assign(new Error('injected save failure'), { data: { httpStatus: 500 } });+ return lambdaClient.task.update.mutate({ id, ...data });+ };+ ```+ Then trigger a save in the UI (edit the title / change the model). `runMutation`+ sets `taskSaveStatus:'failed'` and calls `saveToast`. `httpStatus:500` ⇒ retryable+ ⇒ the toast shows a Retry action; 401/403 would suppress it.+- **Gotcha — reverting the injection triggers a FULL page reload.** `git checkout --`+ on a service file makes Vite do a full reload (not just HMR), so the SPA resets to+ a blank Main Layout (Case 1 trap: a blank shell with only the `Debug ID` tag).+ After reverting, **re-navigate** (`agent-browser open .../task/<id>`) and re-fetch+ element refs before continuing the recovery test.+---## B. Cache / stale state that MASKS the failure@@ -144,6 +166,19 @@- `agent-browser console` and `app-probe.sh errors` returned nothing this run.Prefer the debug-global (C2) over console reading.+### C4. `document.body.innerText` keyword grep false-positives on fixture text++- **Situation**: asserting a state like "保存失败" / "Save failed" via+ `body.innerText.includes('保存失败')`. If the test fixture's own content contains+ that substring (e.g. a task literally named " 验证保存**失败**态的测试任务 "), the grep+ matches the fixture, not the state indicator — a false PASS on the error state+ even when it never rendered (a Case-1 grep trap).+- **Works**: scope the check to the actual UI element, never `body.innerText`:+ - the save hint tag → `[...document.querySelectorAll('[class*=Tag],.ant-tag')].map(t=>t.textContent.trim())`+ - the toast → find the leaf node matching the message, climb while the subtree+ text stays short, then read its `button`s (`[Close, 重试]`).+ Pick fixture names that do NOT contain any state keyword you'll assert on.+---## D. agent-browser / CDP mechanics@@ -159,6 +194,22 @@- **D4. `wait --load networkidle` HANGS during a retry loop** (network neveridles) and can blow the command timeout — use a fixed `wait <ms>` instead whena fetch is stuck retrying.+- **D5. base-ui `toast` lives in a portal, auto-dismisses in \~5s, and can be+ occluded by the dev FPS overlay.** `snapshot -i` does NOT reliably surface the+ portal's action buttons (the `重试`/Retry ref came back empty); read the toast+ via `eval` DOM query instead. The bottom-right dev FPS/debug widget overlaps the+ bottom-right toast, hiding the action row in screenshots — relocate the toast+ region for a clean shot:+ ```js+ [...document.querySelectorAll('[aria-label=Notifications]')].forEach((r) => {+ r.style.cssText +=+ ';position:fixed!important;top:100px!important;left:360px!important;right:auto!important;bottom:auto!important;z-index:2147483647!important;';+ });+ ```+ Because it dismisses in 5s, re-trigger the toast immediately before the+ screenshot/query; a click-the-Retry-then-observe flow is timing-flaky — fire it+ via `button.click()` in `eval` right after re-triggering, or extend the toast+ duration.---diff --git a/locales/en-US/editor.json b/locales/en-US/editor.jsonindex c1a04ee52d2..17de519c5a1 100644--- a/locales/en-US/editor.json+++ b/locales/en-US/editor.json@@ -15,7 +15,9 @@"actions.typobar.off": "Hide formatting toolbar","actions.typobar.on": "Show formatting toolbar","actions.typobar.title": "Formatting Tool",+ "autoSave.failed": "Save failed","autoSave.latest": "Latest version loaded",+ "autoSave.retry": "Retry","autoSave.saved": "Saved","autoSave.saving": "Auto-saving...","cancel": "Cancel",diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex 587d69b3529..e66cf4805a7 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -108,6 +108,8 @@"response.WorkspaceAgentRequiresWorkspaceDevice": "This agent lives in a workspace, so it can only bind devices the whole team can reach. Personal devices stay with the user who registered them — pick a workspace device instead, or enroll this device to the workspace first.","response.WorkspaceFrozenByAdmin": "This workspace is frozen by an admin and cannot run requests. Please contact the workspace owner to resolve the issue.","response.WorkspaceFrozenByRiskControl": "This workspace was auto-frozen by risk control and cannot run requests. Please contact support to review the status.",+ "saveState.retry": "Retry",+ "saveState.saveFailed": "Failed to save your changes. Please try again.","stt.responseError": "Service request failed, please check the configuration or try again","supervisor.decisionFailed": "The group host is unable to function. Please check your host configuration to ensure the correct model, API Key, and API endpoint are set.","testConnectionFailed": "Test connection failed: {{error}}",diff --git a/locales/zh-CN/editor.json b/locales/zh-CN/editor.jsonindex 65d6f73f8f9..af83df7fcb6 100644--- a/locales/zh-CN/editor.json+++ b/locales/zh-CN/editor.json@@ -15,7 +15,9 @@"actions.typobar.off": "隐藏格式工具栏","actions.typobar.on": "显示格式工具栏","actions.typobar.title": "格式工具",+ "autoSave.failed": "保存失败","autoSave.latest": "已加载最新版本",+ "autoSave.retry": "重试","autoSave.saved": "已保存","autoSave.saving": "自动保存中…","cancel": "取消",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex 7474d0490d4..e9c8d3b53da 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -108,6 +108,8 @@"response.WorkspaceAgentRequiresWorkspaceDevice": "这是一个工作区助手,只能绑定全员都能访问的工作区设备。个人设备仅注册者本人可达 —— 请改选工作区设备,或先把这台设备加入工作区。","response.WorkspaceFrozenByAdmin": "工作区已被管理员冻结,暂时无法处理请求。请联系工作区所有者处理","response.WorkspaceFrozenByRiskControl": "工作区已被风控系统自动冻结,暂时无法处理请求。请联系客服处理",+ "saveState.retry": "重试",+ "saveState.saveFailed": "保存失败,请重试。","stt.responseError": "请求失败。请检查配置后重试","supervisor.decisionFailed": "群组主持人运行失败。请检查主持人配置(模型、API Key 与 API 地址)后重试","testConnectionFailed": "测试连接失败:{{error}}",diff --git a/packages/locales/src/default/editor.ts b/packages/locales/src/default/editor.tsindex c6cd36218c1..aeb82f38812 100644--- a/packages/locales/src/default/editor.ts+++ b/packages/locales/src/default/editor.ts@@ -4,7 +4,9 @@ export default {'actions.typobar.off': 'Hide formatting toolbar','actions.typobar.on': 'Show formatting toolbar','actions.typobar.title': 'Formatting Tool',+ 'autoSave.failed': 'Save failed','autoSave.latest': 'Latest version loaded',+ 'autoSave.retry': 'Retry','autoSave.saved': 'Saved','autoSave.saving': 'Auto-saving...','cancel': 'Cancel',diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex b0cd9582690..773f44875df 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -2,6 +2,8 @@ export default {'asyncState.desc': 'Something went wrong while loading. Please try again.','asyncState.metricLabel': 'Failed to load','asyncState.title': 'Failed to load',+ 'saveState.retry': 'Retry',+ 'saveState.saveFailed': 'Failed to save your changes. Please try again.','error.backHome': 'Back to Home','error.desc': 'Give it a try later, or go back to the known world.','error.stack': 'Error Stack',diff --git a/src/components/Editor/AutoSaveHint.tsx b/src/components/Editor/AutoSaveHint.tsxindex add6c25618c..b619ac2e95b 100644--- a/src/components/Editor/AutoSaveHint.tsx+++ b/src/components/Editor/AutoSaveHint.tsx@@ -2,34 +2,51 @@import { Icon, Tag } from '@lobehub/ui';import dayjs from 'dayjs';-import { CloudIcon, Loader2Icon } from 'lucide-react';+import { CloudIcon, Loader2Icon, TriangleAlertIcon } from 'lucide-react';import { type CSSProperties } from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { type SaveStatus } from '@/types/saveState';+interface AutoSaveHintProps {lastUpdatedTime?: string | Date | null;- saveStatus: 'idle' | 'saving' | 'saved';+ /** Called when the user clicks Retry on a failed save. */+ onRetry?: () => void;+ saveStatus: SaveStatus;style?: CSSProperties;}/*** AutoSaveHint - Unified save status indicator for editors*- * Displays real-time save status for document/config changes+ * Displays real-time save status for document/config changes. The `failed`+ * state (LOBE-11078 write-side) renders an error tag with an inline Retry so a+ * silent save failure can never masquerade as "Latest version loaded".*/-const AutoSaveHint = memo<AutoSaveHintProps>(({ style, saveStatus, lastUpdatedTime }) => {+const AutoSaveHint = memo<AutoSaveHintProps>(({ style, saveStatus, lastUpdatedTime, onRetry }) => {const { t } = useTranslation('editor');- const isSaving = saveStatus === 'saving';-- if (isSaving)+ if (saveStatus === 'saving')return (<Tag icon={<Icon spin icon={Loader2Icon} />} style={style}>{t('autoSave.saving')}</Tag>);+ if (saveStatus === 'failed')+ return (+ <Tag+ color={'error'}+ icon={<Icon icon={TriangleAlertIcon} />}+ style={{ cursor: onRetry ? 'pointer' : undefined, ...style }}+ onClick={onRetry}+ >+ {t('autoSave.failed')}+ {onRetry ? ` · ${t('autoSave.retry')}` : ''}+ </Tag>+ );+if (saveStatus === 'saved' && lastUpdatedTime)return (<Tag icon={<Icon icon={CloudIcon} />} style={style}>diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsxindex bfc4797c733..a35f381fc50 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx@@ -82,7 +82,9 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId, showTaskAgentPanelTo<><Breadcrumb taskId={taskId} /><TaskDetailHeaderActions />- {saveStatus === 'saving' ? <AutoSaveHint saveStatus={saveStatus} /> : undefined}+ {saveStatus === 'saving' || saveStatus === 'failed' ? (+ <AutoSaveHint saveStatus={saveStatus} />+ ) : undefined}</>}right={diff --git a/src/hooks/useSaveState.ts b/src/hooks/useSaveState.tsnew file mode 100644index 00000000000..9aba642de09--- /dev/null+++ b/src/hooks/useSaveState.ts@@ -0,0 +1,58 @@+import { useCallback, useRef, useState } from 'react';++import { type SaveStatus } from '@/types/saveState';++export interface SaveStateHandle {+ /** Timestamp of the last successful save, for `AutoSaveHint`'s "Saved {fromNow}". */+ lastSavedAt: Date | null;+ /** Re-run the most recent save task — wire to the Retry affordance of a failed hint. */+ retry: () => Promise<void>;+ /** Run a save task, driving `status` through saving → saved / failed. */+ save: (task: () => Promise<void>) => Promise<void>;+ status: SaveStatus;+}++/**+ * Component-level save-state primitive for surfaces that own their autosave+ * locally (no store save-status map). Pair with `AutoSaveHint`:+ *+ * ```tsx+ * const { status, lastSavedAt, save, retry } = useSaveState();+ * // in the debounced change handler: save(() => service.update(id, value))+ * <AutoSaveHint saveStatus={status} lastUpdatedTime={lastSavedAt} onRetry={retry} />+ * ```+ *+ * The whole point (LOBE-11078 write-side): a failed save resolves to `failed`,+ * never `idle`, so it can't render as a clean "Latest version loaded". Errors+ * are swallowed after being surfaced via `status` so fire-and-forget autosave+ * callers don't produce unhandled rejections; use the store-level `runMutation`+ * when a caller needs the error to propagate (e.g. keep a modal open).+ */+export const useSaveState = (): SaveStateHandle => {+ const [status, setStatus] = useState<SaveStatus>('idle');+ const [lastSavedAt, setLastSavedAt] = useState<Date | null>(null);+ // Keep the latest save task so `retry` re-runs exactly what failed.+ const lastTaskRef = useRef<(() => Promise<void>) | null>(null);++ const save = useCallback(async (task: () => Promise<void>) => {+ lastTaskRef.current = task;+ setStatus('saving');+ try {+ await task();+ setStatus('saved');+ setLastSavedAt(new Date());+ } catch (error) {+ // Never collapse to `idle` on failure — that is the exact bug this+ // primitive exists to kill (a lost edit masquerading as "Latest").+ setStatus('failed');+ console.error('[useSaveState] save failed:', error);+ }+ }, []);++ const retry = useCallback(async () => {+ const task = lastTaskRef.current;+ if (task) await save(task);+ }, [save]);++ return { lastSavedAt, retry, save, status };+};diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.tsindex 7bde2c710e2..37be275aac2 100644--- a/src/store/task/selectors/detailSelectors.ts+++ b/src/store/task/selectors/detailSelectors.ts@@ -1,5 +1,7 @@import type { TaskDetailData, TaskVerifyConfig } from '@lobechat/types';+import type { SaveStatus } from '@/types/saveState';+import type { TaskStoreState } from '../initialState';const activeTaskId = (s: TaskStoreState) => s.activeTaskId;@@ -96,7 +98,10 @@ const canCancelActiveTask = (s: TaskStoreState): boolean => {return ['backlog', 'paused', 'running', 'scheduled'].includes(detail.status);};-const taskSaveStatus = (s: TaskStoreState) => s.taskSaveStatus;+// Save status is keyed per task, so switching tasks reads the target task's own+// status (defaulting to 'idle') instead of a stale 'failed' from a prior task.+const taskSaveStatus = (s: TaskStoreState): SaveStatus =>+ (s.activeTaskId ? s.taskSaveStatusMap[s.activeTaskId] : undefined) ?? 'idle';const activeTopicDrawerTopicId = (s: TaskStoreState) => s.activeTopicDrawerTopicId;diff --git a/src/store/task/slices/config/action.ts b/src/store/task/slices/config/action.tsindex 35c927cc391..cd41425710c 100644--- a/src/store/task/slices/config/action.ts+++ b/src/store/task/slices/config/action.ts@@ -3,6 +3,8 @@ import type { CheckpointConfig, TaskAutomationMode, TaskDetailData } from '@lobeimport { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';import { OptimisticEngine } from '@/store/utils/optimisticEngine';+import { runMutation } from '@/store/utils/runMutation';+import { saveToast } from '@/store/utils/saveToast';import type { TaskStore } from '../../store';@@ -142,17 +144,21 @@ export class TaskConfigSliceActionImpl {type: 'updateTaskDetail',value: { config: { ...this.#get().taskDetailMap[id]?.config, ...modelConfig } },});- this.#set({ taskSaveStatus: 'saving' }, false, 'updateTaskModelConfig/saving');-- try {- await taskService.updateConfig(id, modelConfig);- this.#set({ taskSaveStatus: 'saved' }, false, 'updateTaskModelConfig/saved');- await this.#get().internal_refreshTaskDetail(id);- } catch (error) {- console.error('[TaskStore] Failed to update task model config:', error);- this.#set({ taskSaveStatus: 'idle' }, false, 'updateTaskModelConfig/error');- await this.#get().internal_refreshTaskDetail(id);- }+ await runMutation(this.#set, this.#get, {+ mutate: async () => {+ await taskService.updateConfig(id, modelConfig);+ await this.#get().internal_refreshTaskDetail(id);+ },+ name: 'updateTaskModelConfig',+ onError: async (error) => {+ console.error('[TaskStore] Failed to update task model config:', error);+ await this.#get().internal_refreshTaskDetail(id);+ saveToast(error, { retry: () => void this.#get().updateTaskModelConfig(id, modelConfig) });+ },+ // Best-effort toggle — the toast + refetch surface the failure, callers don't rethrow.+ rethrow: false,+ setStatus: (status) => this.#get().internal_setTaskSaveStatus(id, status),+ });};// Configure periodic execution interval (heartbeatInterval in seconds).diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsindex 91fba92a590..b27f0ea6f7c 100644--- a/src/store/task/slices/detail/action.test.ts+++ b/src/store/task/slices/detail/action.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { taskService } from '@/services/task';+import { taskDetailSelectors } from '@/store/task/selectors';import { useTaskStore } from '../../store';@@ -30,6 +31,10 @@ vi.mock('@/components/AntdStaticMethods', () => ({notification: { error: vi.fn() },}));+vi.mock('@lobehub/ui/base-ui', () => ({+ toast: { error: vi.fn(), success: vi.fn() },+}));+beforeEach(() => {vi.resetAllMocks();useTaskStore.setState({@@ -37,7 +42,7 @@ beforeEach(() => {isCreatingTask: false,isDeletingTask: false,taskDetailMap: {},- taskSaveStatus: 'idle',+ taskSaveStatusMap: {},});});@@ -114,12 +119,12 @@ describe('TaskDetailSliceAction', () => {expect(useTaskStore.getState().taskDetailMap['T-1'].name).toBe('New Name');expect(taskService.update).toHaveBeenCalledWith('T-1', { name: 'New Name' });- expect(useTaskStore.getState().taskSaveStatus).toBe('saved');+ expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('saved');});- it('should propagate error, reset saveStatus, refresh, and toast on failure', async () => {+ it('should propagate error, mark saveStatus failed, refresh, and toast on failure', async () => {const { mutate } = await import('@/libs/swr');- const { message } = await import('@/components/AntdStaticMethods');+ const { toast } = await import('@lobehub/ui/base-ui');useTaskStore.setState({taskDetailMap: {'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },@@ -132,9 +137,11 @@ describe('TaskDetailSliceAction', () => {'fail',);- expect(useTaskStore.getState().taskSaveStatus).toBe('idle');+ // The failure must surface as `failed` (never `idle`) so the save hint+ // shows an error + Retry instead of masquerading as a clean state.+ expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('failed');expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);- expect(message.error).toHaveBeenCalled();+ expect(toast.error).toHaveBeenCalled();});it('should refresh the cached parent on failure when updating from a subtask detail page', async () => {@@ -177,7 +184,7 @@ describe('TaskDetailSliceAction', () => {await useTaskStore.getState().updateTask('T-1', { assigneeAgentId: 'agent-x' });- expect(useTaskStore.getState().taskSaveStatus).toBe('saved');+ expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('saved');expect(message.error).not.toHaveBeenCalled();});@@ -236,6 +243,30 @@ describe('TaskDetailSliceAction', () => {expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-sub']);expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-parent']);});++ it('should scope save status per task so a failure does not leak across navigation', async () => {+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: {+ 'T-1': { identifier: 'T-1', instruction: 'One', status: 'backlog' },+ 'T-2': { identifier: 'T-2', instruction: 'Two', status: 'backlog' },+ },+ });++ vi.mocked(taskService.update).mockRejectedValue(new Error('fail'));++ await expect(useTaskStore.getState().updateTask('T-1', { name: 'New' })).rejects.toThrow(+ 'fail',+ );++ // Opening task T-2 must show a clean state — T-1's `failed` stays with T-1.+ useTaskStore.getState().setActiveTaskId('T-2');+ expect(taskDetailSelectors.taskSaveStatus(useTaskStore.getState())).toBe('idle');++ // Returning to T-1 still reflects its own failed save.+ useTaskStore.getState().setActiveTaskId('T-1');+ expect(taskDetailSelectors.taskSaveStatus(useTaskStore.getState())).toBe('failed');+ });});describe('deleteTask', () => {diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex 2bf68cd6af0..a34947907cd 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -7,6 +7,9 @@ import { mutate, useClientDataSWR } from '@/libs/swr';import { taskKeys } from '@/libs/swr/keys';import { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';+import { runMutation } from '@/store/utils/runMutation';+import { saveToast } from '@/store/utils/saveToast';+import type { SaveStatus } from '@/types/saveState';import type { TaskStore } from '../../store';import { useTaskStore } from '../../store';@@ -309,22 +312,18 @@ export class TaskDetailSliceActionImpl {};this.internal_dispatchTaskDetail({ id, type: 'updateTaskDetail', value: optimistic });- this.#set({ taskSaveStatus: 'saving' }, false, 'updateTask/saving');- try {- await taskService.update(id, data);- this.#set({ taskSaveStatus: 'saved' }, false, 'updateTask/saved');- } catch (error) {- this.#set({ taskSaveStatus: 'idle' }, false, 'updateTask/error');- await refreshPatchedTargets();- message.error(- t('taskDetail.updateFailed', {- defaultValue: 'Failed to update task',- ns: 'chat',- }),- );- throw error;- }+ await runMutation(this.#set, this.#get, {+ mutate: () => taskService.update(id, data),+ name: 'updateTask',+ // Rollback is a server-truth refetch (not a local snapshot), so the+ // optimistic dispatch above is reconciled from the source of record.+ onError: async (error) => {+ await refreshPatchedTargets();+ saveToast(error, { retry: () => void this.#get().updateTask(id, data) });+ },+ setStatus: (status) => this.#get().internal_setTaskSaveStatus(id, status),+ });if (assigneeAgentId !== undefined || data.parentTaskId !== undefined) {await Promise.all([this.#get().refreshTaskList(), refreshPatchedTargets()]).catch(() => {});@@ -350,6 +349,17 @@ export class TaskDetailSliceActionImpl {// ── Internal Actions ──+ // Write the save status for a single task id. Keyed per task so a `failed`+ // status stays with its task and never bleeds into another task's header after+ // navigation. Shared by every runMutation-based write across the task slices.+ internal_setTaskSaveStatus = (id: string, status: SaveStatus): void => {+ this.#set(+ { taskSaveStatusMap: { ...this.#get().taskSaveStatusMap, [id]: status } },+ false,+ `setTaskSaveStatus/${status}`,+ );+ };+internal_dispatchTaskDetail = (payload: TaskDetailDispatch): void => {const currentMap = this.#get().taskDetailMap;const nextMap = taskDetailReducer(currentMap, payload);diff --git a/src/store/task/slices/detail/initialState.ts b/src/store/task/slices/detail/initialState.tsindex 34d9009963c..777ae7edb69 100644--- a/src/store/task/slices/detail/initialState.ts+++ b/src/store/task/slices/detail/initialState.ts@@ -1,17 +1,22 @@import type { TaskDetailData } from '@lobechat/types';+import { type SaveStatus } from '@/types/saveState';+export interface TaskDetailSliceState {activeTaskId?: string;activeTopicDrawerTopicId?: string;isCreatingTask: boolean;isDeletingTask: boolean;taskDetailMap: Record<string, TaskDetailData>;- taskSaveStatus: 'idle' | 'saved' | 'saving';+ // 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.+ taskSaveStatusMap: Record<string, SaveStatus>;}export const initialTaskDetailSliceState: TaskDetailSliceState = {isCreatingTask: false,isDeletingTask: false,taskDetailMap: {},- taskSaveStatus: 'idle',+ taskSaveStatusMap: {},};diff --git a/src/store/task/slices/lifecycle/action.ts b/src/store/task/slices/lifecycle/action.tsindex c64f037e211..f2aa4f566e9 100644--- a/src/store/task/slices/lifecycle/action.ts+++ b/src/store/task/slices/lifecycle/action.ts@@ -2,6 +2,8 @@ import type { TaskDetailData, TaskStatus } from '@lobechat/types';import { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';+import { runMutation } from '@/store/utils/runMutation';+import { saveToast } from '@/store/utils/saveToast';import type { TaskStore } from '../../store';@@ -94,19 +96,22 @@ export class TaskLifecycleSliceActionImpl {type: 'updateTaskDetail',value: { status, ...extraUpdate },});- this.#set({ taskSaveStatus: 'saving' }, false, 'transitionStatus/saving');-- try {- await taskService.updateStatus(id, status, error);- this.#set({ taskSaveStatus: 'saved' }, false, 'transitionStatus/saved');- await this.#get().internal_refreshTaskDetail(id);- await this.#get().refreshTaskList();- } catch (error) {- console.error(`[TaskStore] Failed to transition task to ${status}:`, error);- this.#set({ taskSaveStatus: 'idle' }, false, 'transitionStatus/error');- await this.#get().internal_refreshTaskDetail(id);- throw error;- }+ await runMutation(this.#set, this.#get, {+ mutate: async () => {+ await taskService.updateStatus(id, status, error);+ await this.#get().internal_refreshTaskDetail(id);+ await this.#get().refreshTaskList();+ },+ name: 'transitionStatus',+ onError: async (err) => {+ console.error(`[TaskStore] Failed to transition task to ${status}:`, err);+ await this.#get().internal_refreshTaskDetail(id);+ saveToast(err, {+ retry: () => void this.#transitionStatus(id, status, extraUpdate, error),+ });+ },+ setStatus: (s) => this.#get().internal_setTaskSaveStatus(id, s),+ });};}diff --git a/src/store/utils/runMutation.ts b/src/store/utils/runMutation.tsnew file mode 100644index 00000000000..51f669ec24d--- /dev/null+++ b/src/store/utils/runMutation.ts@@ -0,0 +1,91 @@+import { applyPatches, type Draft, type Patch, produceWithPatches } from 'immer';++import { type StoreSetter } from '@/store/types';+import { type SaveStatus } from '@/types/saveState';++export interface RunMutationConfig<TStore extends object, T> {+ /** The server write. Its resolved value is returned by `runMutation`. */+ mutate: () => Promise<T>;+ /** Debug label for the devtools action names (`<name>/optimistic`, `<name>/rollback`). */+ name?: string;+ /**+ * Surface the failure — typically `saveToast(err, { retry })`. Runs after+ * rollback and is awaited before rethrow, so a refetch-style rollback+ * (`await refreshDetail()`) completes before the caller sees the error.+ */+ onError?: (error: unknown) => void | Promise<void>;+ /**+ * Optimistic update recipe, applied synchronously before `mutate` via immer.+ * `runMutation` records the inverse patches and, on failure, restores exactly+ * the keys this recipe touched — concurrent unrelated updates are preserved.+ */+ optimistic?: (draft: Draft<TStore>) => void;+ /** Rethrow after rollback + `onError` so explicit-submit callers can react. @default true */+ rethrow?: boolean;+ /**+ * Reflect the save lifecycle in the store's own save-state field, whatever its+ * shape (`taskSaveStatus`, `saveStateMap[id]`, …). Called with `'saving'`+ * before the write and `'saved'` / `'failed'` after. This is the enforced+ * invariant: a failed write can never be silently left looking idle.+ */+ setStatus?: (status: SaveStatus) => void;+}++/**+ * Function-style write-mutation helper for zustand class actions — the write-side+ * counterpart to the read-side `AsyncBoundary`. It wraps the recurring+ * saving → optimistic → mutate → (saved | rollback + failed + toast) dance so no+ * action can forget the failure branch, which is the exact bug (`catch → 'idle'`,+ * a lost edit rendering as a clean state) the LOBE-11078 audit found duplicated+ * across the write surfaces.+ *+ * Kept deliberately lightweight vs. the queued `OptimisticEngine` — no cross-action+ * queue or conflict detection, just per-action optimistic + precise patch rollback.+ *+ * @example+ * updateTask = (id, value) =>+ * runMutation(this.#set, this.#get, {+ * name: 'updateTask',+ * setStatus: (s) => this.#set({ taskSaveStatus: s }, false, `updateTask/${s}`),+ * optimistic: (draft) => {+ * draft.taskDetailMap[id] = { ...draft.taskDetailMap[id], ...value };+ * },+ * mutate: async () => {+ * await taskService.updateTask(id, value);+ * await this.#get().refreshTaskList();+ * },+ * onError: (err) => saveToast(err, { retry: () => this.#get().updateTask(id, value) }),+ * });+ */+export async function runMutation<TStore extends object, T = void>(+ set: StoreSetter<TStore>,+ get: () => TStore,+ config: RunMutationConfig<TStore, T>,+): Promise<T> {+ const { mutate, name = 'runMutation', onError, optimistic, rethrow = true, setStatus } = config;++ setStatus?.('saving');++ let inversePatches: Patch[] | undefined;+ if (optimistic) {+ const [next, patches, inverse] = produceWithPatches(get(), optimistic);+ if (patches.length > 0) {+ inversePatches = inverse;+ set(next as TStore, false, `${name}/optimistic`);+ }+ }++ try {+ const result = await mutate();+ setStatus?.('saved');+ return result;+ } catch (error) {+ if (inversePatches) {+ set(applyPatches(get(), inversePatches) as TStore, false, `${name}/rollback`);+ }+ setStatus?.('failed');+ await onError?.(error);+ if (rethrow) throw error;+ return undefined as T;+ }+}diff --git a/src/store/utils/saveToast.ts b/src/store/utils/saveToast.tsnew file mode 100644index 00000000000..6caaddc05b2--- /dev/null+++ b/src/store/utils/saveToast.ts@@ -0,0 +1,35 @@+import { toast } from '@lobehub/ui/base-ui';+import { t } from 'i18next';++import { normalizeAsyncError } from '@/libs/swr/normalizeError';++export interface SaveToastOptions {+ /**+ * Retry handler. A Retry action is shown only when the failure is retryable —+ * `normalizeAsyncError` marks auth / permission failures (401 / 403, or an+ * explicit `meta.shouldRetry === false`) non-retryable, so we never dangle a+ * pointless Retry on a wall the user can't get through.+ */+ retry?: () => void;+ /** Override the default "Failed to save your changes" title. */+ title?: string;+}++/**+ * Standard failure toast for write actions — the write-side counterpart to the+ * read-side `AsyncError`. Works inside zustand class actions (uses the imperative+ * base-ui `toast` + i18next `t`, no React context). Pass it as `runMutation`'s+ * `onError` so every migrated mutation surfaces failures the same way.+ */+export const saveToast = (error: unknown, options: SaveToastOptions = {}) => {+ const { retry, title } = options;+ const { retryable } = normalizeAsyncError(error);++ return toast.error({+ actions:+ retry && retryable+ ? [{ label: t('saveState.retry', { ns: 'error' }), onClick: retry, variant: 'primary' }]+ : undefined,+ title: title ?? t('saveState.saveFailed', { ns: 'error' }),+ });+};diff --git a/src/types/saveState.ts b/src/types/saveState.tsnew file mode 100644index 00000000000..0c3c6f300cb--- /dev/null+++ b/src/types/saveState.ts@@ -0,0 +1,18 @@+/**+ * Canonical save-state contract shared by every write surface (autosave,+ * explicit submit, store save-state maps). The write-side counterpart to the+ * read-side `NormalizedAsyncError` (`libs/swr/normalizeError.ts`).+ *+ * The audit (`ux` feedback.md §4.4) found this union duplicated ~6 times as+ * `'idle' | 'saving' | 'saved'` with **no failure member**, so every `catch`+ * collapsed to `'idle'` and a failed save rendered identically to a clean state+ * ("Latest"). The `failed` member is the fix: the enum can now *represent*+ * failure, so `AutoSaveHint` / `useSaveState` can show an error + Retry and the+ * edited value is never silently lost.+ */+export type SaveStatus = 'idle' | 'saving' | 'saved' | 'failed';++export interface SaveState {+ lastUpdatedTime?: Date | null;+ saveStatus: SaveStatus;+}