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 SchedulerForm race + drop stale-refresh CLS (#14853)

Tsukib8a03bdc08d9
diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx b/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx
index 551bb9f8ea4..2c701dfcef0 100644
--- a/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx
@@ -99,10 +99,8 @@ interface SchedulerFormProps {
const SchedulerForm = memo<SchedulerFormProps>(({ maxExecutions, onChange, pattern, timezone }) => {
const { t } = useTranslation('chat');
- // Optimistic local state: seed once from props at mount, then own the values
- // locally. Don't re-sync from props on every change β€” otherwise the async
- // server roundtrip (updateSchedule β†’ refreshTaskDetail) bounces stale prop
- // values back into the form during rapid edits and clobbers the user input.
+ // Local state seeded once from props at mount; never re-synced. Keeps the
+ // form in user control even if an unrelated detail refresh runs concurrently.
// Parent should `key={taskId}` this component to remount cleanly across tasks.
const [initial] = useState(() => {
const parsed = parseCronPattern(pattern || DEFAULT_PATTERN);
diff --git a/src/features/AgentTasks/features/TaskTriggerTag.tsx b/src/features/AgentTasks/features/TaskTriggerTag.tsx
index a6d53e6e1f4..96a591fb1d7 100644
--- a/src/features/AgentTasks/features/TaskTriggerTag.tsx
+++ b/src/features/AgentTasks/features/TaskTriggerTag.tsx
@@ -57,15 +57,20 @@ 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.
+ // Single-line row regardless of mode/content length β€” long primaries
+ // (e.g. "Every Mon/Tue/Wed/Thu/Fri/Sat at HH:MM") used to wrap to two
+ // lines and shift the rows below. Tooltip still surfaces the full text
+ // plus timezone on hover, so no information is lost.
return (
<Tooltip title={data?.tooltip}>
- <Flexbox horizontal align="center" gap={10}>
+ <Flexbox horizontal align="center" gap={10} style={{ minWidth: 0 }}>
<Icon color={cssVar.colorTextDescription} icon={ClockIcon} size={16} />
- <Text type={data ? undefined : 'secondary'} weight={data ? 500 : undefined}>
+ <Text
+ ellipsis
+ style={{ minWidth: 0 }}
+ type={data ? undefined : 'secondary'}
+ weight={data ? 500 : undefined}
+ >
{data?.primary ?? t('taskSchedule.tag.add')}
</Text>
</Flexbox>
diff --git a/src/store/task/slices/config/action.test.ts b/src/store/task/slices/config/action.test.ts
index c084c5583f4..006d5dc076d 100644
--- a/src/store/task/slices/config/action.test.ts
+++ b/src/store/task/slices/config/action.test.ts
@@ -307,6 +307,127 @@ describe('TaskConfigSliceAction', () => {
});
});
+ describe('updateSchedule', () => {
+ it('mirrors pattern, timezone, and maxExecutions into the local detail and PUTs the flat shape', async () => {
+ const { mutate } = await import('@/libs/swr');
+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
+
+ await useTaskStore.getState().updateSchedule('T-1', {
+ maxExecutions: 5,
+ pattern: '0 9 * * 1-5',
+ timezone: 'Asia/Shanghai',
+ });
+
+ const detail = useTaskStore.getState().taskDetailMap['T-1'];
+ expect(detail.schedule).toEqual({
+ maxExecutions: 5,
+ pattern: '0 9 * * 1-5',
+ timezone: 'Asia/Shanghai',
+ });
+ expect((detail.config as any).schedule.maxExecutions).toBe(5);
+ expect(taskService.update).toHaveBeenCalledWith('T-1', {
+ config: { schedule: { maxExecutions: 5 } },
+ schedulePattern: '0 9 * * 1-5',
+ scheduleTimezone: 'Asia/Shanghai',
+ });
+ // No SWR refresh β€” optimistic patch is the source of truth.
+ const refreshCalls = vi
+ .mocked(mutate)
+ .mock.calls.filter((c) => Array.isArray(c[0]) && c[0][0] === 'fetchTaskDetail');
+ expect(refreshCalls).toHaveLength(0);
+ });
+
+ it('serializes rapid weekday-toggle edits and keeps the user’s final input', async () => {
+ const flush = () => new Promise((r) => setTimeout(r, 0));
+
+ const settlers: Array<() => void> = [];
+ vi.mocked(taskService.update).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settlers.push(() => resolve({ success: true } as any));
+ }),
+ );
+
+ const store = useTaskStore.getState();
+ const args = (pattern: string) => ({ maxExecutions: null, pattern, timezone: 'UTC' });
+ const p1 = store.updateSchedule('T-1', args('0 9 * * 1'));
+ const p2 = store.updateSchedule('T-1', args('0 9 * * 1,2'));
+ const p3 = store.updateSchedule('T-1', args('0 9 * * 1,2,3'));
+
+ // Store reflects the most recent click immediately.
+ expect(useTaskStore.getState().taskDetailMap['T-1'].schedule?.pattern).toBe('0 9 * * 1,2,3');
+
+ await flush();
+ expect(taskService.update).toHaveBeenCalledTimes(1);
+ 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 patterns = vi.mocked(taskService.update).mock.calls.map((c) => c[1].schedulePattern);
+ expect(patterns).toEqual(['0 9 * * 1', '0 9 * * 1,2', '0 9 * * 1,2,3']);
+ expect(useTaskStore.getState().taskDetailMap['T-1'].schedule?.pattern).toBe('0 9 * * 1,2,3');
+ });
+
+ it('shares the engine path with setAutomationMode, so a mode toggle and a schedule edit serialize', async () => {
+ const flush = () => new Promise((r) => setTimeout(r, 0));
+
+ const settlers: Array<() => void> = [];
+ vi.mocked(taskService.update).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settlers.push(() => resolve({ success: true } as any));
+ }),
+ );
+
+ const store = useTaskStore.getState();
+ const pA = store.setAutomationMode('T-1', 'schedule');
+ const pB = store.updateSchedule('T-1', {
+ maxExecutions: null,
+ pattern: '0 10 * * *',
+ timezone: 'UTC',
+ });
+
+ // First PUT runs; the second is queued on the conflicting path.
+ await flush();
+ expect(taskService.update).toHaveBeenCalledTimes(1);
+
+ settlers[0]();
+ await flush();
+ expect(taskService.update).toHaveBeenCalledTimes(2);
+
+ settlers[1]();
+ await Promise.all([pA, pB]);
+ });
+
+ it('rolls back the schedule patch when the PUT fails', async () => {
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': {
+ ...useTaskStore.getState().taskDetailMap['T-1'],
+ schedule: { pattern: '0 9 * * *', timezone: 'UTC' },
+ },
+ },
+ });
+
+ vi.mocked(taskService.update).mockRejectedValue(new Error('boom'));
+
+ await useTaskStore.getState().updateSchedule('T-1', {
+ maxExecutions: 10,
+ pattern: '0 11 * * 1',
+ timezone: 'Asia/Shanghai',
+ });
+
+ const detail = useTaskStore.getState().taskDetailMap['T-1'];
+ expect(detail.schedule?.pattern).toBe('0 9 * * *');
+ expect(detail.schedule?.timezone).toBe('UTC');
+ });
+ });
+
describe('resolveBrief', () => {
it('should call service and refresh active detail', async () => {
const { mutate } = await import('@/libs/swr');
diff --git a/src/store/task/slices/config/action.ts b/src/store/task/slices/config/action.ts
index 7c3d8d75038..a0286af1db9 100644
--- a/src/store/task/slices/config/action.ts
+++ b/src/store/task/slices/config/action.ts
@@ -35,14 +35,10 @@ export const createTaskConfigSlice = (set: Setter, get: () => TaskStore, _api?:
export class TaskConfigSliceActionImpl {
readonly #get: () => TaskStore;
readonly #set: Setter;
- // Counts in-flight writes per task so we can coalesce the post-write
- // `internal_refreshTaskDetail` into a single fetch after the last response.
- // 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.
+ // Lazily-initialized engine shared by every action that mutates a task's
+ // `taskDetailMap` entry (setAutomationMode, updateSchedule). Per-task path
+ // conflicts serialize rapid edits for the same task while different tasks
+ // stay parallel.
#automationEngine?: OptimisticEngine<AutomationModeOptimisticState>;
constructor(set: Setter, get: () => TaskStore, _api?: unknown) {
@@ -67,24 +63,6 @@ export class TaskConfigSliceActionImpl {
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.
- async #withCoalescedRefresh(id: string, write: () => Promise<void>): Promise<void> {
- this.#pendingWrites.set(id, (this.#pendingWrites.get(id) ?? 0) + 1);
- try {
- await write();
- } finally {
- const remaining = (this.#pendingWrites.get(id) ?? 1) - 1;
- if (remaining <= 0) {
- this.#pendingWrites.delete(id);
- await this.#get().internal_refreshTaskDetail(id);
- } else {
- this.#pendingWrites.set(id, remaining);
- }
- }
- }
-
markBriefRead = async (briefId: string): Promise<void> => {
await taskService.markBriefRead(briefId);
const { activeTaskId, internal_refreshTaskDetail } = this.#get();
@@ -260,35 +238,43 @@ export class TaskConfigSliceActionImpl {
schedule: { ...existingScheduleConfig, maxExecutions: schedule.maxExecutions },
};
- // Optimistic dispatch so TaskTriggerTag / summary text reflect the change
- // immediately, without waiting for the server roundtrip. `taskService.update`
- // wants the flat DB shape (`schedulePattern` / `scheduleTimezone` columns +
- // `config.schedule.maxExecutions` JSONB), but the store reads from the
- // normalized nested `schedule` object β€” populate both for the in-memory copy.
- this.#get().internal_dispatchTaskDetail({
- id,
- type: 'updateTaskDetail',
- value: {
- config: nextConfig,
- schedule: {
- maxExecutions: schedule.maxExecutions,
- pattern: schedule.pattern,
- timezone: schedule.timezone,
- },
- },
+ // Share the engine + path (taskDetailMap.<id>) with setAutomationMode, so
+ // rapid SchedulerForm edits (weekday toggles, frequency switches, time
+ // picks) serialize against each other AND against mode toggles. No PUT
+ // reordering on the wire; no stale post-write refresh that could land
+ // after the user's next click.
+ //
+ // The optimistic patch mirrors every field this call sends to the server
+ // (`config` JSONB shape + flat `schedule.{pattern,timezone}` for the
+ // normalized store copy), so we don't need a follow-up refresh β€” that
+ // refresh used to be the race source: an async SWR write that could
+ // arrive after the user's next click and overwrite their input.
+ const engine = this.#getAutomationEngine();
+ const tx = engine.createTransaction(`updateSchedule(${id})`);
+ tx.set((draft) => {
+ const target = draft.taskDetailMap[id];
+ if (!target) return;
+ target.config = nextConfig;
+ target.schedule = {
+ maxExecutions: schedule.maxExecutions,
+ pattern: schedule.pattern,
+ timezone: schedule.timezone,
+ };
});
+ tx.mutation = async () => {
+ await taskService.update(id, {
+ config: nextConfig,
+ schedulePattern: schedule.pattern,
+ scheduleTimezone: schedule.timezone,
+ });
+ };
- await this.#withCoalescedRefresh(id, async () => {
- try {
- await taskService.update(id, {
- config: nextConfig,
- schedulePattern: schedule.pattern,
- scheduleTimezone: schedule.timezone,
- });
- } catch (error) {
- console.error('[TaskStore] Failed to update schedule:', error);
- }
- });
+ try {
+ await tx.commit();
+ } catch (error) {
+ // engine already rolled the optimistic patches back; just log.
+ console.error('[TaskStore] Failed to update schedule:', error);
+ }
};
}