Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

27.5 KB
Raw Blame
import type { SyncMode } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
import { act, cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';

vi.doMock('@lingui/react/macro', () => ({
  ...actualLinguiMacro,
  useLingui: () => ({
    t: (strings: TemplateStringsArray, ...values: unknown[]) =>
      strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
  }),
}));

const toastErrors: string[] = [];
const toastInfos: Array<{ message: string; id: string | number | undefined }> = [];
vi.doMock('sonner', () => ({
  toast: {
    error: (message: string) => toastErrors.push(message),
    info: (message: string, options?: { id?: string | number }) =>
      toastInfos.push({ message, id: options?.id }),
  },
}));

const syncSettingsNotReadyInfo = {
  message: 'Sync settings not yet loaded — try again in a moment',
  id: 'sync-settings-not-ready',
};

function expectRepeatedSyncSettingsNotReadyInfo(): void {
  expect(toastInfos).toEqual([syncSettingsNotReadyInfo, syncSettingsNotReadyInfo]);
  expect(toastErrors).toEqual([]);
}

let projectLocalBinding: null | {
  patch: (patch: unknown) => { ok: true } | { ok: false; error: unknown };
} = null;
let projectLocalSynced = true;
let projectBinding: null | {
  patch: (patch: unknown) => { ok: true } | { ok: false; error: unknown };
} = null;
let projectSynced = true;

vi.doMock('@/lib/config-provider', () => ({
  useConfigContext: () => ({
    projectBinding,
    projectSynced,
    projectLocalBinding,
    projectLocalSynced,
  }),
}));

type Writer = ((enabled: boolean) => { ok: true } | { ok: false; error: string }) | null;
type ConfirmState = {
  confirmOpen: boolean;
  setConfirmOpen: (open: boolean) => void;
  onToggleRequest: (next: boolean) => void;
  onConfirm: () => void;
};
let hooks: Awaited<typeof import('./use-enable-sync-with-confirm')> | null = null;
let latestConfirmState: ConfirmState | null = null;
let latestWriter: Writer | undefined;

async function loadHooks() {
  hooks ??= await import('./use-enable-sync-with-confirm');
  return hooks;
}

function ConfirmProbe({ writer, onEnabled }: { writer: Writer; onEnabled?: () => void }) {
  if (!hooks) throw new Error('hooks not loaded');
  latestConfirmState = hooks.useEnableSyncWithConfirm(
    writer,
    onEnabled ? { onEnabled } : undefined,
  );
  return <div data-testid="confirm-open">{String(latestConfirmState.confirmOpen)}</div>;
}

function WriterProbe({ children: _children }: { children?: ReactNode }) {
  if (!hooks) throw new Error('hooks not loaded');
  latestWriter = hooks.useSyncEnabledWriter();
  return <div data-testid="writer-present">{String(latestWriter !== null)}</div>;
}

type ModeWriter = ((mode: SyncMode) => { ok: true } | { ok: false; error: string }) | null;
let latestModeWriter: ModeWriter | undefined;

function ModeWriterProbe() {
  if (!hooks) throw new Error('hooks not loaded');
  latestModeWriter = hooks.useSyncModeWriter();
  return <div data-testid="mode-writer-present">{String(latestModeWriter !== null)}</div>;
}

type DefaultWriter =
  | ((next: boolean | SyncMode | null) => { ok: true } | { ok: false; error: string })
  | null;
let latestDefaultWriter: DefaultWriter | undefined;

function DefaultWriterProbe() {
  if (!hooks) throw new Error('hooks not loaded');
  latestDefaultWriter = hooks.useSyncDefaultWriter();
  return <div data-testid="default-writer-present">{String(latestDefaultWriter !== null)}</div>;
}

type IntervalWriter =
  | ((next: {
      pullIntervalSeconds: number;
      pushIntervalSeconds: number;
    }) => { ok: true } | { ok: false; error: string })
  | null;
let latestIntervalWriter: IntervalWriter | undefined;

function IntervalWriterProbe() {
  if (!hooks) throw new Error('hooks not loaded');
  latestIntervalWriter = hooks.useSyncIntervalWriter();
  return <div data-testid="interval-writer-present">{String(latestIntervalWriter !== null)}</div>;
}

type AutoSyncPatch = {
  mode?: SyncMode;
  enabled?: null;
  resumeMode?: Exclude<SyncMode, 'off'> | null;
};
type AutoSyncPatchWriter =
  | ((patch: AutoSyncPatch) => { ok: true } | { ok: false; error: string })
  | null;
let latestAutoSyncPatchWriter: AutoSyncPatchWriter | undefined;

function AutoSyncPatchWriterProbe() {
  if (!hooks) throw new Error('hooks not loaded');
  latestAutoSyncPatchWriter = hooks.useAutoSyncPatchWriter();
  return (
    <div data-testid="auto-sync-patch-writer-present">
      {String(latestAutoSyncPatchWriter !== null)}
    </div>
  );
}

type ModeSelectionState = {
  confirmOpen: boolean;
  pendingMode: 'follow' | 'full' | null;
  onModeSelect: (next: SyncMode) => void;
  onTurnOff: () => boolean;
  onConfirm: () => void;
};
let latestModeSelection: ModeSelectionState | null = null;

function ModeSelectionProbe({
  writer,
  currentMode,
  onApplied,
}: {
  writer: ModeWriter;
  currentMode: SyncMode;
  onApplied?: (mode: SyncMode) => void;
}) {
  if (!hooks) throw new Error('hooks not loaded');
  latestModeSelection = hooks.useSyncModeSelection(
    writer,
    currentMode,
    onApplied ? { onApplied } : undefined,
  );
  return (
    <div data-testid="mode-selection">
      {String(latestModeSelection.confirmOpen)}:{String(latestModeSelection.pendingMode)}
    </div>
  );
}

type BadgeControlsState = {
  onModeSelect: (next: SyncMode) => void;
};
let latestBadgeControls: BadgeControlsState | null = null;

function BadgeControlsProbe({ mode }: { mode: SyncMode }) {
  if (!hooks) throw new Error('hooks not loaded');
  latestBadgeControls = hooks.useBadgeSyncControls({ mode }, 'off', 0);
  return null;
}

describe('useEnableSyncWithConfirm runtime behavior', () => {
  let consoleErrorSpy: ReturnType<typeof spyOn>;

  afterEach(() => {
    cleanup();
    latestConfirmState = null;
    latestWriter = undefined;
    latestModeWriter = undefined;
    latestDefaultWriter = undefined;
    latestIntervalWriter = undefined;
    latestAutoSyncPatchWriter = undefined;
    latestModeSelection = null;
    latestBadgeControls = null;
    projectLocalBinding = null;
    projectLocalSynced = true;
    projectBinding = null;
    projectSynced = true;
    toastErrors.length = 0;
    toastInfos.length = 0;
    consoleErrorSpy?.mockRestore();
  });

  test('exports the hook and every writer adapter', async () => {
    const mod = await loadHooks();
    expect(typeof mod.useEnableSyncWithConfirm).toBe('function');
    expect(typeof mod.useSyncEnabledWriter).toBe('function');
    expect(typeof mod.useSyncModeWriter).toBe('function');
    expect(typeof mod.useSyncDefaultWriter).toBe('function');
    expect(typeof mod.useSyncIntervalWriter).toBe('function');
    expect(typeof mod.useAutoSyncPatchWriter).toBe('function');
  });

  test('off to on opens confirmation and writes true only after confirm', async () => {
    await loadHooks();
    const writes: boolean[] = [];
    const writer: Writer = (enabled) => {
      writes.push(enabled);
      return { ok: true };
    };
    render(<ConfirmProbe writer={writer} />);

    await act(async () => {
      latestConfirmState?.onToggleRequest(true);
    });
    expect(screen.getByTestId('confirm-open').textContent).toBe('true');
    expect(writes).toEqual([]);

    await act(async () => {
      latestConfirmState?.onConfirm();
    });
    expect(writes).toEqual([true]);
    expect(screen.getByTestId('confirm-open').textContent).toBe('false');
  });

  test('on to off commits immediately without opening confirmation', async () => {
    await loadHooks();
    const writes: boolean[] = [];
    const writer: Writer = (enabled) => {
      writes.push(enabled);
      return { ok: true };
    };
    render(<ConfirmProbe writer={writer} />);

    await act(async () => {
      latestConfirmState?.onToggleRequest(false);
    });

    expect(writes).toEqual([false]);
    expect(screen.getByTestId('confirm-open').textContent).toBe('false');
  });

  test('confirm keeps the dialog open when enabling fails', async () => {
    await loadHooks();
    consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    const writer: Writer = () => ({ ok: false, error: 'branch is protected' });
    render(<ConfirmProbe writer={writer} />);

    await act(async () => {
      latestConfirmState?.onToggleRequest(true);
      latestConfirmState?.onConfirm();
    });

    expect(screen.getByTestId('confirm-open').textContent).toBe('true');
    expect(toastErrors).toEqual(['Failed to enable sync — branch is protected']);
    expect(toastInfos).toEqual([]);
  });

  test('an unavailable writer reports the loading wait as information', async () => {
    await loadHooks();
    render(<ConfirmProbe writer={null} />);

    await act(async () => {
      latestConfirmState?.onToggleRequest(true);
    });
    await act(async () => {
      latestConfirmState?.onConfirm();
      latestConfirmState?.onConfirm();
    });

    expectRepeatedSyncSettingsNotReadyInfo();
  });

  test('fires opts.onEnabled once, only after a successful confirm', async () => {
    await loadHooks();
    let enabledCalls = 0;
    const writer: Writer = () => ({ ok: true });
    render(<ConfirmProbe writer={writer} onEnabled={() => enabledCalls++} />);

    await act(async () => {
      latestConfirmState?.onToggleRequest(true);
    });
    expect(enabledCalls).toBe(0);

    await act(async () => {
      latestConfirmState?.onConfirm();
    });
    expect(enabledCalls).toBe(1);
  });

  test('does not fire opts.onEnabled when the enable write fails', async () => {
    await loadHooks();
    consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    let enabledCalls = 0;
    const writer: Writer = () => ({ ok: false, error: 'branch is protected' });
    render(<ConfirmProbe writer={writer} onEnabled={() => enabledCalls++} />);

    await act(async () => {
      latestConfirmState?.onToggleRequest(true);
      latestConfirmState?.onConfirm();
    });

    expect(enabledCalls).toBe(0);
    expect(screen.getByTestId('confirm-open').textContent).toBe('true');
  });
});

describe('useSyncEnabledWriter runtime behavior', () => {
  afterEach(() => {
    cleanup();
    latestWriter = undefined;
    projectLocalBinding = null;
    projectLocalSynced = true;
  });

  test('returns null until the project-local binding mounts', async () => {
    await loadHooks();
    projectLocalBinding = null;
    render(<WriterProbe />);

    expect(screen.getByTestId('writer-present').textContent).toBe('false');
    expect(latestWriter).toBeNull();
  });

  test('returns null while the project-local binding awaits its first sync', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectLocalBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectLocalSynced = false;
    render(<WriterProbe />);

    expect(latestWriter).toBeNull();
    latestWriter?.(true);
    expect(patches).toEqual([]);
  });

  test('after first sync, patches both autoSync.mode and the legacy enabled leaf', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectLocalBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectLocalSynced = true;
    render(<WriterProbe />);

    expect(latestWriter?.(true)).toEqual({ ok: true });
    expect(latestWriter?.(false)).toEqual({ ok: true });
    expect(patches).toEqual([
      { autoSync: { mode: 'full', enabled: true } },
      { autoSync: { mode: 'off', enabled: false } },
    ]);
  });

  test('wraps binding errors into a string result for toast rendering', async () => {
    await loadHooks();
    projectLocalBinding = {
      patch: () => ({ ok: false, error: { code: 'WRITE_ERROR', detail: 'disk denied' } }),
    };
    render(<WriterProbe />);

    expect(latestWriter?.(false)).toEqual({
      ok: false,
      error: 'Failed to write config file: disk denied',
    });
  });
});

describe('useSyncModeWriter runtime behavior', () => {
  afterEach(() => {
    cleanup();
    latestModeWriter = undefined;
    projectLocalBinding = null;
    projectLocalSynced = true;
  });

  test('returns null until the project-local binding mounts', async () => {
    await loadHooks();
    projectLocalBinding = null;
    render(<ModeWriterProbe />);

    expect(screen.getByTestId('mode-writer-present').textContent).toBe('false');
    expect(latestModeWriter).toBeNull();
  });

  test('returns null while the project-local binding awaits its first sync', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectLocalBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectLocalSynced = false;
    render(<ModeWriterProbe />);

    expect(latestModeWriter).toBeNull();
    latestModeWriter?.('full');
    expect(patches).toEqual([]);
  });

  test('after first sync, patches autoSync.mode on the project-local binding', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectLocalBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectLocalSynced = true;
    render(<ModeWriterProbe />);

    expect(latestModeWriter?.('follow')).toEqual({ ok: true });
    expect(patches).toEqual([{ autoSync: { mode: 'follow', enabled: null } }]);
  });

  test('wraps binding errors into a string result for toast rendering', async () => {
    await loadHooks();
    projectLocalBinding = {
      patch: () => ({ ok: false, error: { code: 'WRITE_ERROR', detail: 'disk denied' } }),
    };
    render(<ModeWriterProbe />);

    expect(latestModeWriter?.('full')).toEqual({
      ok: false,
      error: 'Failed to write config file: disk denied',
    });
  });
});

describe('useSyncDefaultWriter runtime behavior', () => {
  afterEach(() => {
    cleanup();
    latestDefaultWriter = undefined;
    projectBinding = null;
    projectSynced = true;
    projectLocalBinding = null;
    projectLocalSynced = true;
  });

  test('returns null until the committed project binding mounts', async () => {
    await loadHooks();
    projectBinding = null;
    render(<DefaultWriterProbe />);

    expect(screen.getByTestId('default-writer-present').textContent).toBe('false');
    expect(latestDefaultWriter).toBeNull();
  });

  test('returns null while the committed project binding awaits its first sync', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectSynced = false;
    render(<DefaultWriterProbe />);

    expect(latestDefaultWriter).toBeNull();
    latestDefaultWriter?.(true);
    expect(patches).toEqual([]);
  });

  test('after first sync, patches autoSync.default on the committed project binding', async () => {
    await loadHooks();
    const committedPatches: unknown[] = [];
    const localPatches: unknown[] = [];
    projectBinding = {
      patch: (patch: unknown) => {
        committedPatches.push(patch);
        return { ok: true };
      },
    };
    projectSynced = true;
    projectLocalBinding = {
      patch: (patch: unknown) => {
        localPatches.push(patch);
        return { ok: true };
      },
    };
    render(<DefaultWriterProbe />);

    expect(latestDefaultWriter?.(false)).toEqual({ ok: true });
    expect(committedPatches).toEqual([{ autoSync: { default: false } }]);
    expect(localPatches).toEqual([]);

    expect(latestDefaultWriter?.(null)).toEqual({ ok: true });
    expect(committedPatches).toEqual([
      { autoSync: { default: false } },
      { autoSync: { default: null } },
    ]);
    expect(localPatches).toEqual([]);
  });

  test('patches a widened mode-string default (committed pull seed)', async () => {
    await loadHooks();
    const committedPatches: unknown[] = [];
    projectBinding = {
      patch: (patch: unknown) => {
        committedPatches.push(patch);
        return { ok: true };
      },
    };
    render(<DefaultWriterProbe />);

    expect(latestDefaultWriter?.('follow')).toEqual({ ok: true });
    expect(committedPatches).toEqual([{ autoSync: { default: 'follow' } }]);
  });

  test('wraps binding errors into a string result for toast rendering', async () => {
    await loadHooks();
    projectBinding = {
      patch: () => ({ ok: false, error: { code: 'WRITE_ERROR', detail: 'disk denied' } }),
    };
    render(<DefaultWriterProbe />);

    expect(latestDefaultWriter?.(true)).toEqual({
      ok: false,
      error: 'Failed to write config file: disk denied',
    });
  });
});

describe('useSyncIntervalWriter runtime behavior', () => {
  afterEach(() => {
    cleanup();
    latestIntervalWriter = undefined;
    projectLocalBinding = null;
    projectLocalSynced = true;
  });

  test('returns null while the project-local binding awaits its first sync', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectLocalBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectLocalSynced = false;
    render(<IntervalWriterProbe />);

    expect(latestIntervalWriter).toBeNull();
    latestIntervalWriter?.({ pullIntervalSeconds: 120, pushIntervalSeconds: 45 });
    expect(patches).toEqual([]);
  });

  test('patches both intervals after the project-local binding completes its first sync', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectLocalBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectLocalSynced = true;
    render(<IntervalWriterProbe />);

    expect(latestIntervalWriter?.({ pullIntervalSeconds: 120, pushIntervalSeconds: 45 })).toEqual({
      ok: true,
    });
    expect(patches).toEqual([{ autoSync: { pullIntervalSeconds: 120, pushIntervalSeconds: 45 } }]);
  });
});

describe('useAutoSyncPatchWriter runtime behavior', () => {
  afterEach(() => {
    cleanup();
    latestAutoSyncPatchWriter = undefined;
    projectLocalBinding = null;
    projectLocalSynced = true;
  });

  test('returns null while the project-local binding awaits its first sync', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectLocalBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectLocalSynced = false;
    render(<AutoSyncPatchWriterProbe />);

    expect(latestAutoSyncPatchWriter).toBeNull();
    latestAutoSyncPatchWriter?.({ mode: 'full', enabled: null, resumeMode: null });
    expect(patches).toEqual([]);
  });

  test('patches autoSync after the project-local binding completes its first sync', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectLocalBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectLocalSynced = true;
    render(<AutoSyncPatchWriterProbe />);

    expect(latestAutoSyncPatchWriter?.({ mode: 'full', enabled: null, resumeMode: null })).toEqual({
      ok: true,
    });
    expect(patches).toEqual([{ autoSync: { mode: 'full', enabled: null, resumeMode: null } }]);
  });
});

describe('useSyncModeSelection runtime behavior', () => {
  let consoleErrorSpy: ReturnType<typeof spyOn> | undefined;

  afterEach(() => {
    cleanup();
    latestModeSelection = null;
    projectLocalBinding = null;
    toastErrors.length = 0;
    toastInfos.length = 0;
    consoleErrorSpy?.mockRestore();
    consoleErrorSpy = undefined;
  });

  test('selecting off commits immediately without a confirmation', async () => {
    await loadHooks();
    const writes: SyncMode[] = [];
    const writer: ModeWriter = (mode) => {
      writes.push(mode);
      return { ok: true };
    };
    render(<ModeSelectionProbe writer={writer} currentMode="full" />);

    await act(async () => {
      latestModeSelection?.onModeSelect('off');
    });

    expect(writes).toEqual(['off']);
    expect(screen.getByTestId('mode-selection').textContent).toBe('false:null');
  });

  test('turning off writes an explicit off even when the current mode already reads off', async () => {
    await loadHooks();
    const writes: SyncMode[] = [];
    const writer: ModeWriter = (mode) => {
      writes.push(mode);
      return { ok: true };
    };
    render(<ModeSelectionProbe writer={writer} currentMode="off" />);

    await act(async () => {
      latestModeSelection?.onTurnOff();
    });

    expect(writes).toEqual(['off']);
    expect(screen.getByTestId('mode-selection').textContent).toBe('false:null');
  });

  test('turning off reports whether the write landed', async () => {
    await loadHooks();
    let accept = true;
    const writer: ModeWriter = () =>
      accept ? { ok: true } : { ok: false, error: 'branch is protected' };
    render(<ModeSelectionProbe writer={writer} currentMode="full" />);

    const results: boolean[] = [];
    await act(async () => {
      results.push(latestModeSelection?.onTurnOff() ?? true);
      accept = false;
      results.push(latestModeSelection?.onTurnOff() ?? true);
    });

    expect(results).toEqual([true, false]);
    expect(toastErrors).toEqual(['Failed to update sync mode — branch is protected']);
  });

  test('selecting pull opens the confirmation and writes only after confirm', async () => {
    await loadHooks();
    const writes: SyncMode[] = [];
    const writer: ModeWriter = (mode) => {
      writes.push(mode);
      return { ok: true };
    };
    render(<ModeSelectionProbe writer={writer} currentMode="off" />);

    await act(async () => {
      latestModeSelection?.onModeSelect('follow');
    });
    expect(screen.getByTestId('mode-selection').textContent).toBe('true:follow');
    expect(writes).toEqual([]);

    await act(async () => {
      latestModeSelection?.onConfirm();
    });
    expect(writes).toEqual(['follow']);
    expect(screen.getByTestId('mode-selection').textContent).toBe('false:follow');
  });

  test('escalating pull to full confirms with the full variant', async () => {
    await loadHooks();
    const writes: SyncMode[] = [];
    const writer: ModeWriter = (mode) => {
      writes.push(mode);
      return { ok: true };
    };
    render(<ModeSelectionProbe writer={writer} currentMode="follow" />);

    await act(async () => {
      latestModeSelection?.onModeSelect('full');
    });
    expect(screen.getByTestId('mode-selection').textContent).toBe('true:full');

    await act(async () => {
      latestModeSelection?.onConfirm();
    });
    expect(writes).toEqual(['full']);
  });

  test('re-selecting the current mode is a no-op', async () => {
    await loadHooks();
    const writes: SyncMode[] = [];
    const writer: ModeWriter = (mode) => {
      writes.push(mode);
      return { ok: true };
    };
    render(<ModeSelectionProbe writer={writer} currentMode="follow" />);

    await act(async () => {
      latestModeSelection?.onModeSelect('follow');
    });

    expect(writes).toEqual([]);
    expect(screen.getByTestId('mode-selection').textContent).toBe('false:null');
  });

  test('a failed confirm keeps the dialog open and toasts', async () => {
    await loadHooks();
    consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    const writer: ModeWriter = () => ({ ok: false, error: 'branch is protected' });
    render(<ModeSelectionProbe writer={writer} currentMode="off" />);

    await act(async () => {
      latestModeSelection?.onModeSelect('full');
    });
    await act(async () => {
      latestModeSelection?.onConfirm();
    });

    expect(screen.getByTestId('mode-selection').textContent).toBe('true:full');
    expect(toastErrors).toEqual(['Failed to update sync mode — branch is protected']);
    expect(toastInfos).toEqual([]);
  });

  test('fires opts.onApplied with the confirmed mode after a successful write', async () => {
    await loadHooks();
    const applied: SyncMode[] = [];
    const writer: ModeWriter = () => ({ ok: true });
    render(
      <ModeSelectionProbe
        writer={writer}
        currentMode="off"
        onApplied={(mode) => applied.push(mode)}
      />,
    );

    await act(async () => {
      latestModeSelection?.onModeSelect('follow');
    });
    expect(applied).toEqual([]);

    await act(async () => {
      latestModeSelection?.onConfirm();
    });
    expect(applied).toEqual(['follow']);
  });

  test('fires opts.onApplied for the unconfirmed off direction too', async () => {
    await loadHooks();
    const applied: SyncMode[] = [];
    const writer: ModeWriter = () => ({ ok: true });
    render(
      <ModeSelectionProbe
        writer={writer}
        currentMode="full"
        onApplied={(mode) => applied.push(mode)}
      />,
    );

    await act(async () => {
      latestModeSelection?.onModeSelect('off');
    });

    expect(applied).toEqual(['off']);
  });

  test('does not fire opts.onApplied when the mode write fails', async () => {
    await loadHooks();
    consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    const applied: SyncMode[] = [];
    const writer: ModeWriter = () => ({ ok: false, error: 'branch is protected' });
    render(
      <ModeSelectionProbe
        writer={writer}
        currentMode="off"
        onApplied={(mode) => applied.push(mode)}
      />,
    );

    await act(async () => {
      latestModeSelection?.onModeSelect('follow');
    });
    await act(async () => {
      latestModeSelection?.onConfirm();
    });

    expect(applied).toEqual([]);
    expect(toastErrors).toEqual(['Failed to update sync mode — branch is protected']);
  });

  test('does not fire opts.onApplied when no writer has mounted yet', async () => {
    await loadHooks();
    const applied: SyncMode[] = [];
    render(
      <ModeSelectionProbe
        writer={null}
        currentMode="off"
        onApplied={(mode) => applied.push(mode)}
      />,
    );

    await act(async () => {
      latestModeSelection?.onModeSelect('full');
    });
    await act(async () => {
      latestModeSelection?.onConfirm();
      latestModeSelection?.onConfirm();
    });

    expect(applied).toEqual([]);
    expectRepeatedSyncSettingsNotReadyInfo();
  });
});

describe('useBadgeSyncControls loading feedback', () => {
  let consoleErrorSpy: ReturnType<typeof spyOn> | undefined;

  afterEach(() => {
    cleanup();
    latestBadgeControls = null;
    projectLocalBinding = null;
    projectLocalSynced = true;
    toastErrors.length = 0;
    toastInfos.length = 0;
    consoleErrorSpy?.mockRestore();
    consoleErrorSpy = undefined;
  });

  test('an unavailable writer reports the loading wait as information', async () => {
    await loadHooks();
    const patches: unknown[] = [];
    projectLocalBinding = {
      patch: (patch: unknown) => {
        patches.push(patch);
        return { ok: true };
      },
    };
    projectLocalSynced = false;
    render(<BadgeControlsProbe mode="full" />);

    await act(async () => {
      latestBadgeControls?.onModeSelect('off');
      latestBadgeControls?.onModeSelect('off');
    });

    expect(patches).toEqual([]);
    expectRepeatedSyncSettingsNotReadyInfo();
  });

  test('an actual patch failure remains an error', async () => {
    await loadHooks();
    consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    projectLocalBinding = {
      patch: () => ({ ok: false, error: { code: 'WRITE_ERROR', detail: 'disk denied' } }),
    };
    projectLocalSynced = true;
    render(<BadgeControlsProbe mode="full" />);

    await act(async () => {
      latestBadgeControls?.onModeSelect('off');
    });

    expect(toastErrors).toEqual([
      'Failed to update sync — Failed to write config file: disk denied',
    ]);
    expect(toastInfos).toEqual([]);
  });
});