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.

34.0 KB
Raw Blame
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { cacheScope } from '@/libs/replica';
import { taskService } from '@/services/task';
import { useUserStore } from '@/store/user';

import { useTaskStore } from '../../store';
import { taskDetailResource } from '../detail/projection';
import { taskDetailRefreshes } from '../detail/testUtils';

vi.mock('@/services/task', () => ({
  taskService: {
    find: vi.fn(),
    markBriefRead: vi.fn(),
    resolveBrief: vi.fn(),
    runReview: vi.fn(),
    update: vi.fn(),
    updateCheckpoint: vi.fn(),
    updateConfig: vi.fn(),
    updateReview: vi.fn(),
    updateVerifyConfig: vi.fn(),
  },
}));

vi.mock('@/libs/swr', () => ({
  mutate: vi.fn(),
  useClientDataSWR: vi.fn(),
}));

vi.mock('@lobehub/ui', async (importOriginal) => ({
  ...(await importOriginal<object>()),
  ...(await import('~base-ui-stubs')).baseUiStubs,
}));

const mockDetail = {
  checkpoint: { onAgentRequest: false },
  identifier: 'T-1',
  instruction: 'Test',
  status: 'backlog',
} as any;

beforeEach(() => {
  vi.clearAllMocks();
  vi.mocked(taskService.find).mockImplementation(
    async (id) => ({ data: { id, identifier: id }, success: true }) as never,
  );
  useTaskStore.setState({
    activeTaskId: 'T-1',
    taskRefIndex: {},
    taskDetailMap: { 'T-1': { ...mockDetail } },
  });
});

describe('TaskConfigSliceAction', () => {
  describe('persisting config-only saves', () => {
    const persisted = async (scope: string) =>
      (await taskDetailResource.storage!.get({ queryKey: 'T-1', scope }))?.data;

    const useScope = () => {
      const scope = `task-config-${crypto.randomUUID()}:personal`;
      vi.spyOn(cacheScope, 'get').mockReturnValue(scope);
      vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
      return scope;
    };

    it('persists a saved model change so a reload paints it', async () => {
      const scope = useScope();
      vi.mocked(taskService.updateConfig).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().updateTaskModelConfig('T-1', { model: 'gpt-x' });

      await vi.waitFor(async () =>
        expect((await persisted(scope))?.config).toMatchObject({ model: 'gpt-x' }),
      );
      vi.restoreAllMocks();
    });

    it('persists the automation mode once the toggle is saved', async () => {
      const scope = useScope();
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().setAutomationMode('T-1', 'heartbeat');

      await vi.waitFor(async () =>
        expect((await persisted(scope))?.automationMode).toBe('heartbeat'),
      );
      vi.restoreAllMocks();
    });
  });

  describe('updateCheckpoint', () => {
    it('should optimistically update and call service', async () => {
      vi.mocked(taskService.updateCheckpoint).mockResolvedValue({ success: true } as any);

      const checkpoint = { onAgentRequest: true };
      await useTaskStore.getState().updateCheckpoint('T-1', checkpoint);

      expect(useTaskStore.getState().taskDetailMap['T-1'].checkpoint).toEqual(checkpoint);
      expect(taskService.updateCheckpoint).toHaveBeenCalledWith('T-1', checkpoint);
    });

    it('keeps config.checkpoint in sync so a later schedule edit does not restore the old one', async () => {
      vi.mocked(taskService.updateCheckpoint).mockResolvedValue({ success: true } as any);
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
      useTaskStore.setState({
        taskDetailMap: {
          'T-1': {
            ...mockDetail,
            config: { checkpoint: { onAgentRequest: false }, schedule: { maxExecutions: null } },
            schedule: { pattern: '0 9 * * *', timezone: 'UTC' },
          },
        },
      });

      await useTaskStore.getState().updateCheckpoint('T-1', { onAgentRequest: true });
      await useTaskStore.getState().updateSchedule('T-1', {
        maxExecutions: null,
        pattern: '0 18 * * *',
        timezone: 'UTC',
      });

      expect(useTaskStore.getState().taskDetailMap['T-1'].config?.checkpoint).toEqual({
        onAgentRequest: true,
      });
      // The schedule save sends only its own key, never a config snapshot that
      // could carry a stale checkpoint back to the server.
      expect(vi.mocked(taskService.update).mock.calls[0][1]).not.toHaveProperty('config');
    });

    it('rolls back and marks the save failed when the PUT rejects', async () => {
      const { toast } = await import('@lobehub/ui');
      vi.mocked(taskService.updateCheckpoint).mockRejectedValue(new Error('fail'));

      await useTaskStore.getState().updateCheckpoint('T-1', { onAgentRequest: true });

      // The optimistic patch is replayed back; a failure must never leave the
      // toggle looking saved, and it must not depend on a refetch to say so.
      expect(useTaskStore.getState().taskDetailMap['T-1'].checkpoint).toEqual({
        onAgentRequest: false,
      });
      expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('failed');
      expect(toast.error).toHaveBeenCalled();
      const refreshes = taskDetailRefreshes('T-1');
      expect(refreshes).toHaveLength(0);
    });
  });

  describe('updateReview', () => {
    it('should call service and refresh detail', async () => {
      vi.mocked(taskService.updateReview).mockResolvedValue({ success: true } as any);

      const review = { enabled: true, rubrics: [] };
      await useTaskStore.getState().updateReview('T-1', review as any);

      expect(taskService.updateReview).toHaveBeenCalledWith({ id: 'T-1', review });
      expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);
    });
  });

  describe('review / verify writes', () => {
    const flush = () => new Promise((r) => setTimeout(r, 0));

    it.each([
      [
        'updateReview',
        () => useTaskStore.getState().updateReview('T-1', { enabled: true } as any),
        () => taskService.updateReview,
      ],
      [
        'updateVerifyConfig',
        () => useTaskStore.getState().updateVerifyConfig('T-1', { enabled: true }),
        () => taskService.updateVerifyConfig,
      ],
    ] as const)(
      '%s queues behind an in-flight run-location write on the same config column',
      async (_name, write, service) => {
        // The server merges `tasks.config` read-modify-write, and this writer's
        // follow-up refetch would otherwise land on top of the run-location
        // chip's optimistic state while its PUT is still in flight.
        let settleExecution!: () => void;
        vi.mocked(taskService.updateConfig).mockImplementation(
          () =>
            new Promise((resolve) => {
              settleExecution = () => resolve({ success: true } as any);
            }),
        );
        vi.mocked(service()).mockResolvedValue({ success: true } as any);

        const store = useTaskStore.getState();
        const p1 = store.updateTaskExecution('T-1', { boundDeviceId: 'device-a' });
        const p2 = write();

        await flush();
        expect(taskService.updateConfig).toHaveBeenCalledTimes(1);
        expect(service()).not.toHaveBeenCalled();

        settleExecution();
        await Promise.all([p1, p2]);
        expect(service()).toHaveBeenCalledTimes(1);
      },
    );

    it('keeps an edit queued behind a review write when the review refetch lands', async () => {
      const { mutate } = await import('@/libs/swr');
      let settleReview!: () => void;
      vi.mocked(taskService.updateReview).mockImplementation(
        () =>
          new Promise((resolve) => {
            settleReview = () => resolve({ success: true } as any);
          }),
      );
      vi.mocked(taskService.updateCheckpoint).mockResolvedValue({ success: true } as any);
      // The refetch returns server data that predates the queued checkpoint edit.
      vi.mocked(mutate).mockImplementation(async () => {
        useTaskStore.setState({
          taskDetailMap: {
            'T-1': { ...mockDetail, checkpoint: { onAgentRequest: false } },
          },
        });
      });

      const store = useTaskStore.getState();
      const review = store.updateReview('T-1', { enabled: true } as any);
      await flush();
      const checkpoint = store.updateCheckpoint('T-1', { onAgentRequest: true });
      settleReview();
      await Promise.all([review, checkpoint]);

      expect(taskService.updateCheckpoint).toHaveBeenCalledOnce();
      expect(useTaskStore.getState().taskDetailMap['T-1'].checkpoint).toEqual({
        onAgentRequest: true,
      });
      vi.mocked(mutate).mockReset();
    });

    it('updateVerifyConfig still rejects so multi-step callers can abort', async () => {
      vi.mocked(taskService.updateVerifyConfig).mockRejectedValue(new Error('fail'));

      await expect(
        useTaskStore.getState().updateVerifyConfig('T-1', { enabled: true }),
      ).rejects.toThrow('fail');
      expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('failed');
    });
  });

  describe('runReview', () => {
    it('should call service and refresh detail', async () => {
      const mockResult = { overallScore: 85, passed: true };
      vi.mocked(taskService.runReview).mockResolvedValue({
        data: mockResult,
        success: true,
      } as any);

      const result = await useTaskStore.getState().runReview('T-1', { content: 'Test output' });

      expect(taskService.runReview).toHaveBeenCalledWith('T-1', { content: 'Test output' });
      expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);
      expect(result).toEqual({ data: mockResult, success: true });
    });

    it('should throw on error', async () => {
      vi.mocked(taskService.runReview).mockRejectedValue(new Error('review failed'));

      await expect(useTaskStore.getState().runReview('T-1', { content: 'Test' })).rejects.toThrow(
        'review failed',
      );
    });
  });

  describe('updateTaskModelConfig', () => {
    it('should call updateConfig with model/provider and never refetch', async () => {
      vi.mocked(taskService.updateConfig).mockResolvedValue({ success: true } as any);

      await useTaskStore
        .getState()
        .updateTaskModelConfig('T-1', { model: 'claude-sonnet-4-6', provider: 'anthropic' });

      expect(taskService.updateConfig).toHaveBeenCalledWith('T-1', {
        model: 'claude-sonnet-4-6',
        provider: 'anthropic',
      });
      expect(useTaskStore.getState().taskDetailMap['T-1'].config).toMatchObject({
        model: 'claude-sonnet-4-6',
        provider: 'anthropic',
      });
      expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('saved');
      // A refresh here is an async write that could land after the user's next
      // run-location pick and replace it.
      const refreshes = taskDetailRefreshes('T-1');
      expect(refreshes).toHaveLength(0);
    });

    it('serializes with the run-location writes they share a config column with', async () => {
      const flush = () => new Promise((r) => setTimeout(r, 0));
      const settlers: Array<() => void> = [];
      vi.mocked(taskService.updateConfig).mockImplementation(
        () =>
          new Promise((resolve) => {
            settlers.push(() => resolve({ success: true } as any));
          }),
      );

      // Both writes merge into `tasks.config` server-side with a
      // read-modify-write, so two in flight let the later one erase the other.
      const store = useTaskStore.getState();
      const p1 = store.updateTaskModelConfig('T-1', { model: 'claude-sonnet-4-6' });
      const p2 = store.updateTaskExecution('T-1', { boundDeviceId: 'device-a' });

      // Both are already visible, and only the first PUT is on the wire.
      expect(useTaskStore.getState().taskDetailMap['T-1'].config).toMatchObject({
        execution: { boundDeviceId: 'device-a' },
        model: 'claude-sonnet-4-6',
      });

      await flush();
      expect(taskService.updateConfig).toHaveBeenCalledTimes(1);

      settlers[0]();
      await flush();
      expect(taskService.updateConfig).toHaveBeenCalledTimes(2);

      settlers[1]();
      await Promise.all([p1, p2]);

      expect(vi.mocked(taskService.updateConfig).mock.calls.map((call) => call[1])).toEqual([
        { model: 'claude-sonnet-4-6' },
        {
          execution: {
            boundDeviceId: 'device-a',
            repos: null,
            workingDirectory: null,
            workingDirectoryConfig: null,
          },
        },
      ]);
    });
  });

  describe('updateTaskExecution', () => {
    // Macrotask flush — enough for OptimisticEngine to resolve the previous PUT,
    // run its post-await steps, and kick off the next mutation's PUT.
    const flush = () => new Promise((r) => setTimeout(r, 0));

    const executionOf = (id = 'T-1') =>
      useTaskStore.getState().taskDetailMap[id].config?.execution as Record<string, unknown>;

    it('serializes rapid device + directory edits, keeps the last one, and never refetches', async () => {
      const settlers: Array<() => void> = [];
      vi.mocked(taskService.updateConfig).mockImplementation(
        () =>
          new Promise((resolve) => {
            settlers.push(() => resolve({ success: true } as any));
          }),
      );

      // Every call writes a COMPLETE four-axis patch, so the older PUT landing
      // last would put the previous selection back — silently moving the run.
      const store = useTaskStore.getState();
      const p1 = store.updateTaskExecution('T-1', { boundDeviceId: 'device-a' });
      const p2 = store.updateTaskExecution('T-1', {
        boundDeviceId: 'device-a',
        workingDirectory: '/srv/app',
      });
      const p3 = store.updateTaskExecution('T-1', {
        boundDeviceId: 'device-b',
        workingDirectory: '/srv/app',
      });

      // The last click is already on screen while the first PUT is in flight.
      expect(executionOf()).toEqual({
        boundDeviceId: 'device-b',
        repos: null,
        workingDirectory: '/srv/app',
        workingDirectoryConfig: null,
      });

      await flush();
      expect(taskService.updateConfig).toHaveBeenCalledTimes(1);

      settlers[0]();
      await flush();
      expect(taskService.updateConfig).toHaveBeenCalledTimes(2);

      settlers[1]();
      await flush();
      expect(taskService.updateConfig).toHaveBeenCalledTimes(3);

      settlers[2]();
      await Promise.all([p1, p2, p3]);

      expect(
        vi
          .mocked(taskService.updateConfig)
          .mock.calls.map((call) => (call[1] as any).execution.boundDeviceId),
      ).toEqual(['device-a', 'device-a', 'device-b']);
      expect(executionOf()).toEqual({
        boundDeviceId: 'device-b',
        repos: null,
        workingDirectory: '/srv/app',
        workingDirectoryConfig: null,
      });

      const refreshes = taskDetailRefreshes('T-1');
      expect(refreshes).toHaveLength(0);
    });

    it('rolls the optimistic patch back, marks the save failed, and offers a retry', async () => {
      const { toast } = await import('@lobehub/ui');
      useTaskStore.setState({
        taskDetailMap: {
          'T-1': {
            ...mockDetail,
            config: { execution: { boundDeviceId: 'device-a' }, model: 'x' },
          },
        },
      });
      vi.mocked(taskService.updateConfig).mockRejectedValue(new Error('boom'));

      await useTaskStore.getState().updateTaskExecution('T-1', { boundDeviceId: 'device-b' });

      // Engine replayed the inverse patch: the stored selection is back, and the
      // other config pockets were never touched.
      expect(useTaskStore.getState().taskDetailMap['T-1'].config).toEqual({
        execution: { boundDeviceId: 'device-a' },
        model: 'x',
      });
      expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('failed');

      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.');
      }
      expect(toastOptions.actions?.[0]).toBeDefined();
    });

    it('marks the save saved when the write lands', async () => {
      vi.mocked(taskService.updateConfig).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().updateTaskExecution('T-1', { boundDeviceId: 'device-a' });

      expect(taskService.updateConfig).toHaveBeenCalledWith('T-1', {
        execution: {
          boundDeviceId: 'device-a',
          repos: null,
          workingDirectory: null,
          workingDirectoryConfig: null,
        },
      });
      expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('saved');
    });
  });

  describe('updatePeriodicInterval', () => {
    it('should call update with heartbeatInterval and refresh detail', async () => {
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().updatePeriodicInterval('T-1', 600);

      expect(taskService.update).toHaveBeenCalledWith('T-1', { heartbeatInterval: 600 });
      expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);
    });

    it('should send 0 when null to disable interval (automationMode untouched)', async () => {
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().updatePeriodicInterval('T-1', null);

      expect(taskService.update).toHaveBeenCalledWith('T-1', { heartbeatInterval: 0 });
    });
  });

  describe('setAutomationMode', () => {
    it('should seed default heartbeat interval when first enabling', async () => {
      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,
      });
    });

    it('should preserve the responsible assignee when enabling automation', async () => {
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      useTaskStore.setState({
        taskDetailMap: {
          'T-1': {
            ...useTaskStore.getState().taskDetailMap['T-1'],
            heartbeat: { interval: 1800 },
            userId: 'user_member_1',
          },
        },
      });

      await useTaskStore.getState().setAutomationMode('T-1', 'heartbeat');

      expect(taskService.update).toHaveBeenCalledWith('T-1', { automationMode: 'heartbeat' });
      expect(useTaskStore.getState().taskDetailMap['T-1'].userId).toBe('user_member_1');
    });

    it('should not touch the assignee when disabling automation', async () => {
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().setAutomationMode('T-1', null);

      expect(taskService.update).toHaveBeenCalledWith('T-1', { automationMode: null });
    });

    it('should preserve existing heartbeat interval when re-entering heartbeat mode', async () => {
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      useTaskStore.setState({
        taskDetailMap: {
          'T-1': {
            ...useTaskStore.getState().taskDetailMap['T-1'],
            heartbeat: { interval: 1800 },
          },
        },
      });

      await useTaskStore.getState().setAutomationMode('T-1', 'heartbeat');

      expect(taskService.update).toHaveBeenCalledWith('T-1', { automationMode: 'heartbeat' });
    });

    it('should seed default cron pattern + local timezone when entering schedule mode', async () => {
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().setAutomationMode('T-1', 'schedule');

      const localTz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
      expect(taskService.update).toHaveBeenCalledWith('T-1', {
        automationMode: 'schedule',
        schedulePattern: '0 9 * * *',
        scheduleTimezone: localTz,
      });
    });

    it('should override DB-default UTC timezone on first-time schedule enable', async () => {
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      // The tasks table has `schedule_timezone TEXT DEFAULT 'UTC'`, so a row that
      // has never had its schedule configured still surfaces timezone='UTC'.
      // First-time enable (no pattern yet) must override with the user's local tz.
      useTaskStore.setState({
        taskDetailMap: {
          'T-1': {
            ...useTaskStore.getState().taskDetailMap['T-1'],
            schedule: { pattern: null, timezone: 'UTC' },
          },
        },
      });

      await useTaskStore.getState().setAutomationMode('T-1', 'schedule');

      const localTz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
      expect(taskService.update).toHaveBeenCalledWith('T-1', {
        automationMode: 'schedule',
        schedulePattern: '0 9 * * *',
        scheduleTimezone: localTz,
      });
    });

    it('should preserve user-chosen timezone when re-entering schedule mode', async () => {
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      useTaskStore.setState({
        taskDetailMap: {
          'T-1': {
            ...useTaskStore.getState().taskDetailMap['T-1'],
            schedule: { pattern: '0 8 * * 1', timezone: 'Asia/Shanghai' },
          },
        },
      });

      await useTaskStore.getState().setAutomationMode('T-1', 'schedule');

      expect(taskService.update).toHaveBeenCalledWith('T-1', { automationMode: 'schedule' });
    });

    it('should accept null to disable automation', async () => {
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().setAutomationMode('T-1', null);

      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 () => {
      // 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 = taskDetailRefreshes('T-1');
      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('activity feed rows', () => {
    const signIn = () =>
      useUserStore.setState({
        isSignedIn: true,
        user: { avatar: null, fullName: 'Me', id: 'user_me' } as any,
      });
    const rows = () =>
      (useTaskStore.getState().taskDetailMap['T-1'].activities ?? []).map((a) => a.propertyChange);

    it('shows an automation row for a schedule edit — this path never refetches', async () => {
      signIn();
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
      useTaskStore.setState({
        taskDetailMap: {
          'T-1': {
            ...mockDetail,
            activities: [],
            automationMode: 'schedule',
            schedule: { pattern: '0 9 * * *', timezone: 'UTC' },
          },
        },
      });

      await useTaskStore.getState().updateSchedule('T-1', {
        maxExecutions: null,
        pattern: '0 18 * * *',
        timezone: 'Asia/Shanghai',
      });

      expect(rows()).toEqual([
        {
          field: 'automation',
          from: {
            heartbeatInterval: null,
            maxExecutions: null,
            mode: 'schedule',
            schedulePattern: '0 9 * * *',
            scheduleTimezone: 'UTC',
          },
          to: {
            heartbeatInterval: null,
            maxExecutions: null,
            mode: 'schedule',
            schedulePattern: '0 18 * * *',
            scheduleTimezone: 'Asia/Shanghai',
          },
        },
      ]);
    });

    it('logs a cap-only edit: the execution cap is part of the schedule', async () => {
      signIn();
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
      useTaskStore.setState({
        taskDetailMap: {
          'T-1': {
            ...mockDetail,
            activities: [],
            automationMode: 'schedule',
            schedule: { maxExecutions: null, pattern: '0 9 * * *', timezone: 'UTC' },
          },
        },
      });

      await useTaskStore.getState().updateSchedule('T-1', {
        maxExecutions: 5,
        pattern: '0 9 * * *',
        timezone: 'UTC',
      });

      expect(rows()).toHaveLength(1);
      expect(rows()[0]).toMatchObject({
        from: expect.objectContaining({ maxExecutions: null }),
        to: expect.objectContaining({ maxExecutions: 5 }),
      });
    });

    it('does not log a schedule edit while automation is off — the server does not either', async () => {
      signIn();
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
      useTaskStore.setState({ taskDetailMap: { 'T-1': { ...mockDetail, activities: [] } } });

      await useTaskStore.getState().updateSchedule('T-1', {
        maxExecutions: null,
        pattern: '0 18 * * *',
        timezone: 'UTC',
      });

      expect(rows()).toEqual([]);
    });

    it('folds a burst of mode toggles the way the server will show it', async () => {
      signIn();
      vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
      // Both modes already configured, so toggling only moves `mode` — the
      // same columns the server snapshots, so it folds the same way there.
      useTaskStore.setState({
        taskDetailMap: {
          'T-1': {
            ...mockDetail,
            activities: [],
            automationMode: 'heartbeat',
            heartbeat: { interval: 600 },
            schedule: { pattern: '0 9 * * *', timezone: 'UTC' },
          },
        },
      });

      const store = useTaskStore.getState();
      await store.setAutomationMode('T-1', 'schedule');
      await store.setAutomationMode('T-1', 'heartbeat');

      // heartbeat → schedule → heartbeat is a net no-op: nothing to tell.
      expect(rows()).toEqual([]);

      await store.setAutomationMode('T-1', null);
      expect(rows()).toEqual([
        {
          field: 'automation',
          from: {
            heartbeatInterval: 600,
            maxExecutions: null,
            mode: 'heartbeat',
            schedulePattern: '0 9 * * *',
            scheduleTimezone: 'UTC',
          },
          to: null,
        },
      ]);
    });
  });

  describe('updateSchedule', () => {
    it('mirrors pattern, timezone, and maxExecutions into the local detail and PUTs the flat shape', async () => {
      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', {
        configPatch: { schedule: { maxExecutions: 5 } },
        schedulePattern: '0 9 * * 1-5',
        scheduleTimezone: 'Asia/Shanghai',
      });
      // No SWR refresh — optimistic patch is the source of truth.
      const refreshCalls = taskDetailRefreshes('T-1');
      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 () => {
      vi.mocked(taskService.resolveBrief).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().resolveBrief('brief_1', { action: 'approve' });

      expect(taskService.resolveBrief).toHaveBeenCalledWith('brief_1', { action: 'approve' });
      expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);
    });
  });

  describe('markBriefRead', () => {
    it('should call service and refresh active detail', async () => {
      vi.mocked(taskService.markBriefRead).mockResolvedValue({ success: true } as any);

      await useTaskStore.getState().markBriefRead('brief_1');

      expect(taskService.markBriefRead).toHaveBeenCalledWith('brief_1');
      expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);
    });
  });
});