Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(task-schedule): stop UI flip-flop on rapid automation-mode toggles (#14801)

Tsukid9eba30519da
diff --git a/src/features/AgentTasks/features/TaskTriggerTag.tsx b/src/features/AgentTasks/features/TaskTriggerTag.tsx
index 6dbe0713b29..a6d53e6e1f4 100644
--- a/src/features/AgentTasks/features/TaskTriggerTag.tsx
+++ b/src/features/AgentTasks/features/TaskTriggerTag.tsx
@@ -57,25 +57,17 @@ const TaskTriggerTag = memo<TaskTriggerTagProps>(
}, [automationMode, heartbeatInterval, schedulePattern, scheduleTimezone, t, i18n.language]);
if (mode === 'inline') {
+ // Keep the inline row to a single line regardless of mode so toggling
+ // schedule ↔ heartbeat from the popover above doesn't reflow the rows
+ // below. The timezone (if any) is still surfaced β€” just via the hover
+ // tooltip β€” so we don't lose information.
return (
<Tooltip title={data?.tooltip}>
- <Flexbox horizontal align="flex-start" gap={10}>
- <Icon
- color={cssVar.colorTextDescription}
- icon={ClockIcon}
- size={16}
- style={{ marginTop: 2 }}
- />
- <Flexbox gap={2}>
- <Text type={data ? undefined : 'secondary'} weight={data ? 500 : undefined}>
- {data?.primary ?? t('taskSchedule.tag.add')}
- </Text>
- {data?.secondary && (
- <Text style={{ color: cssVar.colorTextDescription, fontSize: 11 }}>
- {data.secondary}
- </Text>
- )}
- </Flexbox>
+ <Flexbox horizontal align="center" gap={10}>
+ <Icon color={cssVar.colorTextDescription} icon={ClockIcon} size={16} />
+ <Text type={data ? undefined : 'secondary'} weight={data ? 500 : undefined}>
+ {data?.primary ?? t('taskSchedule.tag.add')}
+ </Text>
</Flexbox>
</Tooltip>
);
diff --git a/src/store/task/slices/config/action.test.ts b/src/store/task/slices/config/action.test.ts
index 17ea59d7cbb..c084c5583f4 100644
--- a/src/store/task/slices/config/action.test.ts
+++ b/src/store/task/slices/config/action.test.ts
@@ -135,17 +135,18 @@ describe('TaskConfigSliceAction', () => {
describe('setAutomationMode', () => {
it('should seed default heartbeat interval when first enabling', async () => {
- const { mutate } = await import('@/libs/swr');
vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
await useTaskStore.getState().setAutomationMode('T-1', 'heartbeat');
expect(useTaskStore.getState().taskDetailMap['T-1'].automationMode).toBe('heartbeat');
+ // Default heartbeat interval is mirrored into the local detail in the
+ // same optimistic patch so we don't need to refresh from the server.
+ expect(useTaskStore.getState().taskDetailMap['T-1'].heartbeat?.interval).toBe(600);
expect(taskService.update).toHaveBeenCalledWith('T-1', {
automationMode: 'heartbeat',
heartbeatInterval: 600,
});
- expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);
});
it('should preserve existing heartbeat interval when re-entering heartbeat mode', async () => {
@@ -228,6 +229,82 @@ describe('TaskConfigSliceAction', () => {
expect(useTaskStore.getState().taskDetailMap['T-1'].automationMode).toBeNull();
expect(taskService.update).toHaveBeenCalledWith('T-1', { automationMode: null });
});
+
+ it('serializes rapid toggles, applies optimistic state immediately, and never refreshes', async () => {
+ const { mutate } = await import('@/libs/swr');
+ // Macrotask flush β€” drains the microtask queue, enough for
+ // OptimisticEngine to resolve the previous PUT, run its post-await
+ // steps, and synchronously kick off the next mutation's PUT.
+ const flush = () => new Promise((r) => setTimeout(r, 0));
+
+ // Resolvers we can flip in click order to prove PUTs don't reorder.
+ const settlers: Array<() => void> = [];
+ vi.mocked(taskService.update).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settlers.push(() => resolve({ success: true } as any));
+ }),
+ );
+
+ // Fire three toggles back-to-back (schedule β†’ heartbeat β†’ schedule)
+ // without awaiting β€” mirrors a rapid Segmented click stream.
+ const store = useTaskStore.getState();
+ const p1 = store.setAutomationMode('T-1', 'schedule');
+ const p2 = store.setAutomationMode('T-1', 'heartbeat');
+ const p3 = store.setAutomationMode('T-1', 'schedule');
+
+ expect(useTaskStore.getState().taskDetailMap['T-1'].automationMode).toBe('schedule');
+
+ // Engine has started only the first PUT; the other two are queued on
+ // the conflicting `taskDetailMap.T-1` path.
+ await flush();
+ expect(taskService.update).toHaveBeenCalledTimes(1);
+
+ // Resolve in order; each release unblocks exactly the next PUT.
+ settlers[0]();
+ await flush();
+ expect(taskService.update).toHaveBeenCalledTimes(2);
+
+ settlers[1]();
+ await flush();
+ expect(taskService.update).toHaveBeenCalledTimes(3);
+
+ settlers[2]();
+ await Promise.all([p1, p2, p3]);
+
+ const calls = vi.mocked(taskService.update).mock.calls.map((c) => c[1].automationMode);
+ expect(calls).toEqual(['schedule', 'heartbeat', 'schedule']);
+
+ // Final store still matches the last click β€” no stale SWR refresh can
+ // race-overwrite it back to schedule/heartbeat mid-stream.
+ expect(useTaskStore.getState().taskDetailMap['T-1'].automationMode).toBe('schedule');
+ const refreshCalls = vi
+ .mocked(mutate)
+ .mock.calls.filter((c) => Array.isArray(c[0]) && c[0][0] === 'fetchTaskDetail');
+ expect(refreshCalls).toHaveLength(0);
+ });
+
+ it('rolls back the optimistic store update when the PUT fails', async () => {
+ // Seed an existing schedule mode so we can verify the rollback target.
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': {
+ ...useTaskStore.getState().taskDetailMap['T-1'],
+ automationMode: 'schedule',
+ schedule: { pattern: '0 9 * * *', timezone: 'Asia/Shanghai' },
+ },
+ },
+ });
+
+ vi.mocked(taskService.update).mockRejectedValue(new Error('boom'));
+
+ await useTaskStore.getState().setAutomationMode('T-1', 'heartbeat');
+
+ // Engine replayed inverse patches β†’ store back to pre-call snapshot.
+ const detail = useTaskStore.getState().taskDetailMap['T-1'];
+ expect(detail.automationMode).toBe('schedule');
+ expect(detail.heartbeat?.interval).toBeUndefined();
+ });
});
describe('resolveBrief', () => {
diff --git a/src/store/task/slices/config/action.ts b/src/store/task/slices/config/action.ts
index 922136f7870..7c3d8d75038 100644
--- a/src/store/task/slices/config/action.ts
+++ b/src/store/task/slices/config/action.ts
@@ -1,10 +1,19 @@
-import type { CheckpointConfig, TaskAutomationMode } from '@lobechat/types';
+import type { CheckpointConfig, TaskAutomationMode, TaskDetailData } from '@lobechat/types';
import { taskService } from '@/services/task';
import type { StoreSetter } from '@/store/types';
+import { OptimisticEngine } from '@/store/utils/optimisticEngine';
import type { TaskStore } from '../../store';
+// Slice of TaskStore that the OptimisticEngine for setAutomationMode reads/writes.
+// Keeping it narrow ensures `extractAffectedPaths` produces `taskDetailMap.<id>`
+// keys so concurrent toggles for the same task serialize, while toggles for
+// different tasks stay parallel.
+interface AutomationModeOptimisticState {
+ taskDetailMap: Record<string, TaskDetailData>;
+}
+
// Default values applied when a task is switched into a mode for the first time
// β€” keeps the popover summary, the cron runtime and the persisted record in
// sync rather than leaving the task in a "mode enabled but unconfigured" state.
@@ -31,6 +40,10 @@ export class TaskConfigSliceActionImpl {
// Without this, rapid edits trigger overlapping refreshes that surface stale
// intermediate server state to readers like TaskTriggerTag / summary text.
readonly #pendingWrites = new Map<string, number>();
+ // Lazily-initialized engine that owns serialization + rollback for
+ // setAutomationMode. Scoped to `taskDetailMap` so per-task path conflicts
+ // queue rapid toggles for the same task while different tasks stay parallel.
+ #automationEngine?: OptimisticEngine<AutomationModeOptimisticState>;
constructor(set: Setter, get: () => TaskStore, _api?: unknown) {
void _api;
@@ -38,6 +51,22 @@ export class TaskConfigSliceActionImpl {
this.#get = get;
}
+ // `getState` exposes only the taskDetailMap slice so the engine's patches
+ // refer to keys under it β€” needed for `extractAffectedPaths` to produce
+ // `taskDetailMap.<id>` conflict keys.
+ #getAutomationEngine = (): OptimisticEngine<AutomationModeOptimisticState> => {
+ if (this.#automationEngine) return this.#automationEngine;
+ this.#automationEngine = new OptimisticEngine(
+ {
+ getState: () => ({ taskDetailMap: this.#get().taskDetailMap }),
+ setState: (next) =>
+ this.#set(next as Partial<TaskStore>, false, 'taskConfig/automationEngine'),
+ },
+ { maxRetries: 0 },
+ );
+ return this.#automationEngine;
+ };
+
// Run a write; refresh task detail only after the LAST concurrent write for
// this task settles. Optimistic dispatches by the caller should already have
// updated the store before invoking this, so the UI stays steady.
@@ -175,20 +204,44 @@ export class TaskConfigSliceActionImpl {
}
}
- // Optimistic update so the Segmented reflects the new tab immediately
- this.#get().internal_dispatchTaskDetail({
- id,
- type: 'updateTaskDetail',
- value: { automationMode: mode },
- });
-
- await this.#withCoalescedRefresh(id, async () => {
- try {
- await taskService.update(id, update);
- } catch (error) {
- console.error('[TaskStore] Failed to update automation mode:', error);
+ // Run through OptimisticEngine so concurrent toggles for the same task
+ // serialize on the shared `taskDetailMap.<id>` patch path (preventing PUT
+ // reordering on the wire) and a failure replays inverse patches to roll
+ // the store back. Toggles on different tasks have disjoint paths and stay
+ // parallel.
+ //
+ // The patch also mirrors every server-bound field locally, so no post-PUT
+ // refresh is needed β€” refresh would be an async SWR write that could land
+ // after the user's next click and clobber their latest state.
+ const engine = this.#getAutomationEngine();
+ const tx = engine.createTransaction(`setAutomationMode(${id})`);
+ tx.set((draft) => {
+ const target = draft.taskDetailMap[id];
+ if (!target) return;
+ target.automationMode = mode;
+ if (update.heartbeatInterval !== undefined) {
+ target.heartbeat ??= {};
+ target.heartbeat.interval = update.heartbeatInterval;
+ }
+ if (update.schedulePattern !== undefined) {
+ target.schedule ??= {};
+ target.schedule.pattern = update.schedulePattern;
+ }
+ if (update.scheduleTimezone !== undefined) {
+ target.schedule ??= {};
+ target.schedule.timezone = update.scheduleTimezone;
}
});
+ tx.mutation = async () => {
+ await taskService.update(id, update);
+ };
+
+ try {
+ await tx.commit();
+ } catch (error) {
+ // engine already rolled the optimistic patches back; just log.
+ console.error('[TaskStore] Failed to update automation mode:', error);
+ }
};
// Configure schedule mode: cron pattern + IANA timezone are columns; maxExecutions