import { useCallback, useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNostr } from '@nostrify/react'; import { useAISettings } from '@/hooks/useAISettings'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useFS } from '@/hooks/useFS'; import { useFSPaths } from '@/hooks/useFSPaths'; import { toast } from '@/hooks/useToast'; import { readAISyncMeta, writeAISyncMeta, type AISyncMeta } from '@/lib/configUtils'; import { buildAISettingsEvent, decryptAISettingsEvent, fetchRemoteAISettingsEvent, } from '@/lib/aiSettingsSync'; import type { AISettings } from '@/contexts/AISettingsContext'; const AUTO_SYNC_DEBOUNCE_MS = 2000; const SYNC_TIMEOUT_MS = 5000; const DEFAULT_META: AISyncMeta = { autoSync: false, lastModifiedAt: 0 }; function nowSeconds(): number { return Math.floor(Date.now() / 1000); } function errorMessage(err: unknown): string { return err instanceof Error ? err.message : String(err); } export interface UseAISettingsSyncResult { /** Whether auto-sync is enabled on this device. */ autoSync: boolean; /** Enable/disable auto-sync (persists and reconciles immediately when enabling). */ setAutoSync: (value: boolean) => void; /** Whether the active signer supports NIP-44 encryption (and a user is signed in). */ canSync: boolean; /** Unix seconds of the last successful push/pull, if any. */ lastSyncedAt?: number; isBackingUp: boolean; isRestoring: boolean; /** Manually publish current settings to Nostr. */ backupNow: () => Promise; /** Manually pull settings from Nostr and apply them locally. */ restoreFromNostr: () => Promise; } /** * Orchestrates NIP-78 sync of AI settings: debounced push on local change, * pull-on-login, and manual backup/restore. Newest-wins conflict resolution. */ export function useAISettingsSync(): UseAISettingsSyncResult { const { t } = useTranslation(); const { nostr } = useNostr(); const { user } = useCurrentUser(); const { settings, replaceSettings, isLoading } = useAISettings(); const { fs } = useFS(); const { configPath } = useFSPaths(); const canSync = !!user?.signer?.nip44; const pubkey = user?.pubkey; const [autoSync, setAutoSyncState] = useState(false); const [lastSyncedAt, setLastSyncedAt] = useState(undefined); const [metaLoaded, setMetaLoaded] = useState(false); const [isBackingUp, setIsBackingUp] = useState(false); const [isRestoring, setIsRestoring] = useState(false); // Latest-ref mirrors so stable callbacks/effects can read current values // without re-running on every render. const userRef = useRef(user); userRef.current = user; const settingsRef = useRef(settings); settingsRef.current = settings; const autoSyncRef = useRef(autoSync); autoSyncRef.current = autoSync; const canSyncRef = useRef(canSync); canSyncRef.current = canSync; const replaceSettingsRef = useRef(replaceSettings); replaceSettingsRef.current = replaceSettings; const metaRef = useRef(DEFAULT_META); const applyingRemoteRef = useRef(false); const lastSnapshotRef = useRef(null); const debounceTimerRef = useRef | null>(null); // --- Core operations (stable; read mutable state via refs) --- const persistMeta = useCallback(async (patch: Partial) => { const next: AISyncMeta = { ...metaRef.current, ...patch }; metaRef.current = next; setAutoSyncState(next.autoSync); setLastSyncedAt(next.lastSyncedAt); await writeAISyncMeta(fs, next, configPath); }, [fs, configPath]); const pushSettings = useCallback(async (toPush: AISettings) => { const u = userRef.current; if (!u) return; const event = await buildAISettingsEvent(u.signer, u.pubkey, toPush); await nostr.event(event, { signal: AbortSignal.timeout(SYNC_TIMEOUT_MS) }); await persistMeta({ lastModifiedAt: event.created_at, lastSyncedAt: event.created_at }); }, [nostr, persistMeta]); const scheduleDebouncedPush = useCallback(() => { if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current); debounceTimerRef.current = setTimeout(() => { pushSettings(settingsRef.current).catch((err) => { console.error('AI settings auto-sync push failed:', err); }); }, AUTO_SYNC_DEBOUNCE_MS); }, [pushSettings]); /** Apply a freshly-decrypted remote payload locally without triggering a re-push. */ const applyRemote = useCallback(async (next: AISettings, remoteCreatedAt: number) => { applyingRemoteRef.current = true; replaceSettingsRef.current(next); await persistMeta({ lastModifiedAt: remoteCreatedAt, lastSyncedAt: remoteCreatedAt }); }, [persistMeta]); /** Reconcile local vs remote using newest-wins. Only runs when auto-sync is on. */ const reconcile = useCallback(async (isCancelled: () => boolean) => { const u = userRef.current; if (!u || !canSyncRef.current || !autoSyncRef.current) return; try { const remote = await fetchRemoteAISettingsEvent( nostr, u.pubkey, AbortSignal.timeout(SYNC_TIMEOUT_MS), ); if (isCancelled()) return; if (!remote) { // Nothing stored remotely yet: seed it from local if we have anything. if (settingsRef.current.providers.length > 0) { await pushSettings(settingsRef.current); } return; } const localModifiedAt = metaRef.current.lastModifiedAt; if (remote.created_at > localModifiedAt) { const next = await decryptAISettingsEvent(u.signer, u.pubkey, remote); if (isCancelled()) return; await applyRemote(next, remote.created_at); } else if (localModifiedAt > remote.created_at) { await pushSettings(settingsRef.current); } } catch (err) { console.error('AI settings sync (reconcile) failed:', err); } }, [nostr, pushSettings, applyRemote]); // --- Load local sync metadata once on mount --- useEffect(() => { let cancelled = false; (async () => { const meta = await readAISyncMeta(fs, configPath); if (cancelled) return; metaRef.current = meta; setAutoSyncState(meta.autoSync); setLastSyncedAt(meta.lastSyncedAt); setMetaLoaded(true); })(); return () => { cancelled = true; }; }, [fs, configPath]); // --- Push on local settings change (debounced, loop-guarded) --- useEffect(() => { if (isLoading || !metaLoaded) return; const snap = JSON.stringify(settings); if (applyingRemoteRef.current) { // This change came from a remote pull; adopt it without pushing back. applyingRemoteRef.current = false; lastSnapshotRef.current = snap; return; } if (lastSnapshotRef.current === null) { // First observation after load: establish baseline, don't push. lastSnapshotRef.current = snap; return; } if (lastSnapshotRef.current === snap) return; // Genuine local change. lastSnapshotRef.current = snap; persistMeta({ lastModifiedAt: nowSeconds() }).catch((err) => { console.error('Failed to persist AI sync metadata:', err); }); if (autoSync && canSync) { scheduleDebouncedPush(); } }, [settings, isLoading, metaLoaded, autoSync, canSync, persistMeta, scheduleDebouncedPush]); // --- Pull/reconcile on login & account switch --- useEffect(() => { // Reset per-account guards and cancel any pending push. lastSnapshotRef.current = null; if (debounceTimerRef.current) { clearTimeout(debounceTimerRef.current); debounceTimerRef.current = null; } if (!pubkey || !metaLoaded || isLoading) return; let cancelled = false; reconcile(() => cancelled); return () => { cancelled = true; }; }, [pubkey, metaLoaded, isLoading, reconcile]); // --- Cancel pending push on unmount --- useEffect(() => { return () => { if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current); }; }, []); // --- Public API --- const setAutoSync = useCallback((value: boolean) => { // Update the ref eagerly so reconcile() below sees the new value without // waiting for the state-driven re-render. autoSyncRef.current = value; (async () => { await persistMeta({ autoSync: value }); if (value) { // Enabling: reconcile immediately so the device is in sync right away. await reconcile(() => false); } })().catch((err) => { console.error('Failed to update auto-sync setting:', err); }); }, [persistMeta, reconcile]); const backupNow = useCallback(async () => { if (!userRef.current) return; setIsBackingUp(true); try { await pushSettings(settingsRef.current); toast({ title: t('syncBackupSuccess') }); } catch (err) { toast({ title: t('syncBackupFailed'), description: errorMessage(err), variant: 'destructive', }); } finally { setIsBackingUp(false); } }, [pushSettings, t]); const restoreFromNostr = useCallback(async () => { const u = userRef.current; if (!u) return; setIsRestoring(true); try { const remote = await fetchRemoteAISettingsEvent( nostr, u.pubkey, AbortSignal.timeout(SYNC_TIMEOUT_MS), ); if (!remote) { toast({ title: t('noRemoteBackup'), variant: 'destructive' }); return; } const next = await decryptAISettingsEvent(u.signer, u.pubkey, remote); await applyRemote(next, remote.created_at); toast({ title: t('syncRestoreSuccess') }); } catch (err) { toast({ title: t('syncDecryptFailed'), description: errorMessage(err), variant: 'destructive', }); } finally { setIsRestoring(false); } }, [nostr, applyRemote, t]); return { autoSync, setAutoSync, canSync, lastSyncedAt, isBackingUp, isRestoring, backupNow, restoreFromNostr, }; }