mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Merge branch 'sync-ai-settings' into 'main'
Sync AI settings to Nostr via NIP-78 See merge request soapbox-pub/shakespeare!116
This commit is contained in:
commit
5d43767c96
19 files changed
+756
-19
No files matched your search
+20
-17
@@ -16,6 +16,7 @@ import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { SentryProvider } from '@/components/SentryProvider';
|
||||
import { PlausibleProvider } from '@/components/PlausibleProvider';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { AISettingsSyncProvider } from '@/components/AISettingsSyncProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
@@ -144,23 +145,25 @@ export function App() {
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<GitSyncProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<LockdownModeDetector />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSyncProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
<AISettingsSyncProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<GitSyncProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<LockdownModeDetector />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSyncProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsSyncProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
|
||||
@@ -64,6 +64,12 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const replaceSettings = (next: AISettings) => {
|
||||
setSettings(next);
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const setProvider = (provider: AIProvider) => {
|
||||
setSettings(prev => {
|
||||
const existingIndex = prev.providers.findIndex(p => p.id === provider.id);
|
||||
@@ -156,6 +162,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
const contextValue: AISettingsContextType = {
|
||||
settings,
|
||||
updateSettings,
|
||||
replaceSettings,
|
||||
setProvider,
|
||||
removeProvider,
|
||||
setProviders,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { AISettingsSyncContext } from '@/contexts/AISettingsSyncContext';
|
||||
import { useAISettingsSync } from '@/hooks/useAISettingsSync';
|
||||
|
||||
interface AISettingsSyncProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs NIP-78 AI-settings sync once for the whole app and exposes its state to
|
||||
* descendants (e.g. the AI settings page). Must live below NostrProvider and
|
||||
* AISettingsProvider so it can read the active account and current settings.
|
||||
*/
|
||||
export function AISettingsSyncProvider({ children }: AISettingsSyncProviderProps) {
|
||||
const sync = useAISettingsSync();
|
||||
return (
|
||||
<AISettingsSyncContext.Provider value={sync}>
|
||||
{children}
|
||||
</AISettingsSyncContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -50,6 +50,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
@@ -97,6 +98,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
@@ -161,6 +163,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
@@ -221,6 +224,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
@@ -275,6 +279,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ export interface AISettings {
|
||||
export interface AISettingsContextType {
|
||||
settings: AISettings;
|
||||
updateSettings: (settings: Partial<AISettings>) => void;
|
||||
replaceSettings: (settings: AISettings) => void;
|
||||
setProvider: (provider: AIProvider) => void;
|
||||
removeProvider: (id: string) => void;
|
||||
setProviders: (providers: AIProvider[]) => void;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createContext } from 'react';
|
||||
import type { UseAISettingsSyncResult } from '@/hooks/useAISettingsSync';
|
||||
|
||||
export type AISettingsSyncContextType = UseAISettingsSyncResult;
|
||||
|
||||
export const AISettingsSyncContext = createContext<AISettingsSyncContextType | undefined>(undefined);
|
||||
@@ -0,0 +1,289 @@
|
||||
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<void>;
|
||||
/** Manually pull settings from Nostr and apply them locally. */
|
||||
restoreFromNostr: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<number | undefined>(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<AISyncMeta>(DEFAULT_META);
|
||||
const applyingRemoteRef = useRef(false);
|
||||
const lastSnapshotRef = useRef<string | null>(null);
|
||||
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// --- Core operations (stable; read mutable state via refs) ---
|
||||
|
||||
const persistMeta = useCallback(async (patch: Partial<AISyncMeta>) => {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useContext } from 'react';
|
||||
import { AISettingsSyncContext, type AISettingsSyncContextType } from '@/contexts/AISettingsSyncContext';
|
||||
|
||||
/**
|
||||
* Access the app-wide AI-settings sync state (auto-sync toggle, manual
|
||||
* backup/restore, status). Must be used within an AISettingsSyncProvider.
|
||||
*/
|
||||
export function useAISettingsSyncContext(): AISettingsSyncContextType {
|
||||
const context = useContext(AISettingsSyncContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useAISettingsSyncContext must be used within an AISettingsSyncProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -138,6 +138,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
@@ -158,6 +159,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
@@ -185,6 +187,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
@@ -212,6 +215,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
@@ -275,6 +279,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
@@ -317,6 +322,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
@@ -371,6 +377,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
@@ -408,6 +415,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
@@ -447,6 +455,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
@@ -480,6 +489,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
replaceSettings: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import type { NostrEvent, NostrSigner, NPool } from '@nostrify/nostrify';
|
||||
import {
|
||||
AI_SETTINGS_KIND,
|
||||
AI_SETTINGS_D_TAG,
|
||||
Nip44UnsupportedError,
|
||||
buildAISettingsEvent,
|
||||
decryptAISettingsEvent,
|
||||
fetchRemoteAISettingsEvent,
|
||||
} from './aiSettingsSync';
|
||||
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||
|
||||
const PUBKEY = '0'.repeat(64);
|
||||
|
||||
const SETTINGS: AISettings = {
|
||||
providers: [
|
||||
{ id: 'openai', name: 'OpenAI', baseURL: 'https://api.openai.com/v1', apiKey: 'sk-secret-123' },
|
||||
],
|
||||
recentlyUsedModels: ['openai/gpt-4o'],
|
||||
imageModel: 'openai/dall-e-3',
|
||||
mcpServers: {
|
||||
example: { type: 'streamable-http', url: 'https://mcp.example.com', headers: { Authorization: 'Bearer x' } },
|
||||
},
|
||||
};
|
||||
|
||||
/** Mock signer with a reversible NIP-44 implementation (round-trips, not real crypto). */
|
||||
function createSigner(withNip44 = true): NostrSigner {
|
||||
const signer: NostrSigner = {
|
||||
getPublicKey: vi.fn(async () => PUBKEY),
|
||||
signEvent: vi.fn(async (event) => ({
|
||||
...event,
|
||||
id: 'id-' + JSON.stringify(event.tags),
|
||||
pubkey: PUBKEY,
|
||||
sig: 'sig',
|
||||
})),
|
||||
};
|
||||
if (withNip44) {
|
||||
signer.nip44 = {
|
||||
encrypt: vi.fn(async (_pk: string, plaintext: string) =>
|
||||
'enc:' + Buffer.from(plaintext, 'utf8').toString('base64'),
|
||||
),
|
||||
decrypt: vi.fn(async (_pk: string, ciphertext: string) =>
|
||||
Buffer.from(ciphertext.replace(/^enc:/, ''), 'base64').toString('utf8'),
|
||||
),
|
||||
};
|
||||
}
|
||||
return signer;
|
||||
}
|
||||
|
||||
function createNostr(events: NostrEvent[]): NPool {
|
||||
return { query: vi.fn(async () => events) } as unknown as NPool;
|
||||
}
|
||||
|
||||
describe('aiSettingsSync', () => {
|
||||
it('round-trips settings through build + decrypt', async () => {
|
||||
const signer = createSigner();
|
||||
const event = await buildAISettingsEvent(signer, PUBKEY, SETTINGS);
|
||||
|
||||
expect(event.kind).toBe(AI_SETTINGS_KIND);
|
||||
expect(event.tags).toContainEqual(['d', AI_SETTINGS_D_TAG]);
|
||||
expect(event.content).not.toContain('sk-secret-123'); // encrypted
|
||||
|
||||
const decrypted = await decryptAISettingsEvent(signer, PUBKEY, event);
|
||||
expect(decrypted).toEqual(SETTINGS);
|
||||
});
|
||||
|
||||
it('throws Nip44UnsupportedError when the signer lacks nip44', async () => {
|
||||
const signer = createSigner(false);
|
||||
await expect(buildAISettingsEvent(signer, PUBKEY, SETTINGS)).rejects.toBeInstanceOf(
|
||||
Nip44UnsupportedError,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects malformed decrypted JSON', async () => {
|
||||
const signer = createSigner();
|
||||
const badEvent = {
|
||||
kind: AI_SETTINGS_KIND,
|
||||
content: 'enc:' + Buffer.from('not json', 'utf8').toString('base64'),
|
||||
tags: [['d', AI_SETTINGS_D_TAG]],
|
||||
created_at: 1,
|
||||
id: 'x',
|
||||
pubkey: PUBKEY,
|
||||
sig: 's',
|
||||
} as NostrEvent;
|
||||
await expect(decryptAISettingsEvent(signer, PUBKEY, badEvent)).rejects.toBeTruthy();
|
||||
});
|
||||
|
||||
it('returns the newest event and null when none exist', async () => {
|
||||
const mk = (created_at: number): NostrEvent => ({
|
||||
kind: AI_SETTINGS_KIND, content: '', tags: [['d', AI_SETTINGS_D_TAG]],
|
||||
created_at, id: 'id' + created_at, pubkey: PUBKEY, sig: 's',
|
||||
});
|
||||
|
||||
const newest = await fetchRemoteAISettingsEvent(
|
||||
createNostr([mk(100), mk(300), mk(200)]), PUBKEY, AbortSignal.timeout(1000),
|
||||
);
|
||||
expect(newest?.created_at).toBe(300);
|
||||
|
||||
const none = await fetchRemoteAISettingsEvent(createNostr([]), PUBKEY, AbortSignal.timeout(1000));
|
||||
expect(none).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { NostrEvent, NostrSigner, NPool } from '@nostrify/nostrify';
|
||||
import { aiSettingsSchema } from '@/lib/configUtils';
|
||||
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||
|
||||
/** NIP-78 addressable event kind for arbitrary app data. */
|
||||
export const AI_SETTINGS_KIND = 30078;
|
||||
|
||||
/** `d` tag identifying Shakespeare's AI settings within the user's app data. */
|
||||
export const AI_SETTINGS_D_TAG = 'shakespeare-ai-settings';
|
||||
|
||||
/** Thrown when the active signer does not support NIP-44 encryption. */
|
||||
export class Nip44UnsupportedError extends Error {
|
||||
constructor() {
|
||||
super('The current signer does not support NIP-44 encryption');
|
||||
this.name = 'Nip44UnsupportedError';
|
||||
}
|
||||
}
|
||||
|
||||
function requireNip44(signer: NostrSigner): NonNullable<NostrSigner['nip44']> {
|
||||
if (!signer.nip44) {
|
||||
throw new Nip44UnsupportedError();
|
||||
}
|
||||
return signer.nip44;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and sign a kind 30078 event carrying the AI settings, encrypted to the
|
||||
* user's own pubkey via NIP-44.
|
||||
*/
|
||||
export async function buildAISettingsEvent(
|
||||
signer: NostrSigner,
|
||||
pubkey: string,
|
||||
settings: AISettings,
|
||||
): Promise<NostrEvent> {
|
||||
const nip44 = requireNip44(signer);
|
||||
const content = await nip44.encrypt(pubkey, JSON.stringify(settings));
|
||||
return signer.signEvent({
|
||||
kind: AI_SETTINGS_KIND,
|
||||
content,
|
||||
tags: [['d', AI_SETTINGS_D_TAG]],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the latest remote AI settings event for a pubkey, or null if none exists.
|
||||
* Relays may return multiple addressable events; the newest by created_at wins.
|
||||
*/
|
||||
export async function fetchRemoteAISettingsEvent(
|
||||
nostr: NPool,
|
||||
pubkey: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<NostrEvent | null> {
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [AI_SETTINGS_KIND], authors: [pubkey], '#d': [AI_SETTINGS_D_TAG], limit: 1 }],
|
||||
{ signal },
|
||||
);
|
||||
if (events.length === 0) return null;
|
||||
return events.reduce((newest, event) =>
|
||||
event.created_at > newest.created_at ? event : newest,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt and validate a remote AI settings event. Throws if the signer lacks
|
||||
* NIP-44, the content can't be decrypted, or the payload fails schema validation.
|
||||
*/
|
||||
export async function decryptAISettingsEvent(
|
||||
signer: NostrSigner,
|
||||
pubkey: string,
|
||||
event: NostrEvent,
|
||||
): Promise<AISettings> {
|
||||
const nip44 = requireNip44(signer);
|
||||
const plaintext = await nip44.decrypt(pubkey, event.content);
|
||||
const data = JSON.parse(plaintext);
|
||||
return aiSettingsSchema.parse(data) as AISettings;
|
||||
}
|
||||
+59
-1
@@ -14,6 +14,15 @@ function getAIConfigPath(configPath = '/config'): string {
|
||||
return `${configPath}/ai.json`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get AI sync metadata file path. This is local-only state used to coordinate
|
||||
* NIP-78 sync and is never published to Nostr.
|
||||
* @param configPath - Custom config path (default: /config)
|
||||
*/
|
||||
function getAISyncConfigPath(configPath = '/config'): string {
|
||||
return `${configPath}/ai-sync.json`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Git config file path
|
||||
* @param configPath - Custom config path (default: /config)
|
||||
@@ -51,7 +60,7 @@ const mcpServerSchema: z.ZodType<MCPServer> = z.object({
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
});
|
||||
|
||||
const aiSettingsSchema = z.object({
|
||||
export const aiSettingsSchema = z.object({
|
||||
providers: filteredArray(aiProviderSchema),
|
||||
recentlyUsedModels: filteredArray(providerModelSchema),
|
||||
imageModel: providerModelSchema.optional(),
|
||||
@@ -226,6 +235,55 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings, con
|
||||
await fs.writeFile(aiConfigPath, JSON.stringify(settings, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Local-only metadata used to coordinate NIP-78 sync of AI settings.
|
||||
* Never published to Nostr.
|
||||
*/
|
||||
export interface AISyncMeta {
|
||||
/** Whether auto-sync (push on change, pull on login) is enabled on this device. */
|
||||
autoSync: boolean;
|
||||
/** Unix seconds of the last local settings change (or the applied remote's created_at). */
|
||||
lastModifiedAt: number;
|
||||
/** Unix seconds of the last successful push or pull. */
|
||||
lastSyncedAt?: number;
|
||||
}
|
||||
|
||||
const aiSyncMetaSchema = z.object({
|
||||
autoSync: z.boolean(),
|
||||
lastModifiedAt: z.number(),
|
||||
lastSyncedAt: z.number().optional(),
|
||||
});
|
||||
|
||||
const DEFAULT_AI_SYNC_META: AISyncMeta = {
|
||||
autoSync: false,
|
||||
lastModifiedAt: 0,
|
||||
};
|
||||
|
||||
/**
|
||||
* Read AI sync metadata from VFS
|
||||
* @param fs - Filesystem instance
|
||||
* @param configPath - Custom config path (default: /config)
|
||||
*/
|
||||
export async function readAISyncMeta(fs: JSRuntimeFS, configPath = '/config'): Promise<AISyncMeta> {
|
||||
try {
|
||||
const content = await fs.readFile(getAISyncConfigPath(configPath), 'utf8');
|
||||
return aiSyncMetaSchema.parse(JSON.parse(content));
|
||||
} catch {
|
||||
return { ...DEFAULT_AI_SYNC_META };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write AI sync metadata to VFS
|
||||
* @param fs - Filesystem instance
|
||||
* @param meta - Sync metadata to write
|
||||
* @param configPath - Custom config path (default: /config)
|
||||
*/
|
||||
export async function writeAISyncMeta(fs: JSRuntimeFS, meta: AISyncMeta, configPath = '/config'): Promise<void> {
|
||||
await ensureConfigDir(fs, configPath);
|
||||
await fs.writeFile(getAISyncConfigPath(configPath), JSON.stringify(meta, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a display name for a credential based on its hostname
|
||||
*/
|
||||
|
||||
@@ -106,6 +106,19 @@
|
||||
"examplePrompt": "Describe what you'd like to build...",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "Configure AI providers and API keys",
|
||||
"aiSettingsSync": "Sync to Nostr",
|
||||
"autoSyncAiSettings": "Auto-sync settings",
|
||||
"autoSyncAiSettingsDescription": "Encrypt your AI settings to your Nostr account and keep them in sync across devices.",
|
||||
"syncUnsupportedDescription": "Your current signer doesn't support NIP-44 encryption, so syncing is unavailable.",
|
||||
"backUpNow": "Back up now",
|
||||
"restoreFromNostr": "Restore from Nostr",
|
||||
"lastSynced": "Last synced: {{time}}",
|
||||
"neverSynced": "Never synced",
|
||||
"noRemoteBackup": "No backup found on Nostr",
|
||||
"syncBackupSuccess": "Settings backed up to Nostr",
|
||||
"syncBackupFailed": "Failed to back up settings",
|
||||
"syncRestoreSuccess": "Settings restored from Nostr",
|
||||
"syncDecryptFailed": "Failed to restore settings",
|
||||
"gitSettings": "Git",
|
||||
"gitSettingsDescription": "Configure Git credentials for HTTP authentication",
|
||||
"deploySettings": "Deployment",
|
||||
|
||||
@@ -99,6 +99,19 @@
|
||||
"settingsDescription": "Sarrafa saitunan aikace-aikacenku da zaɓuɓɓuka.",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "Saita masu samar da AI da maɓallan API",
|
||||
"aiSettingsSync": "Daidaita zuwa Nostr",
|
||||
"autoSyncAiSettings": "Daidaitawa ta atomatik",
|
||||
"autoSyncAiSettingsDescription": "Ɓoye saitunan AI ɗinka zuwa asusun Nostr ɗinka kuma ka kiyaye su a daidaice tsakanin na'urori.",
|
||||
"syncUnsupportedDescription": "Mai sa hannu naka na yanzu bai goyi bayan ɓoyayyen NIP-44 ba, saboda haka daidaitawa ba ta samuwa.",
|
||||
"backUpNow": "Yi ajiya yanzu",
|
||||
"restoreFromNostr": "Maido daga Nostr",
|
||||
"lastSynced": "Daidaitawa ta ƙarshe: {{time}}",
|
||||
"neverSynced": "Ba a taɓa daidaitawa ba",
|
||||
"noRemoteBackup": "Ba a sami ajiya a Nostr ba",
|
||||
"syncBackupSuccess": "An ajiye saitunan zuwa Nostr",
|
||||
"syncBackupFailed": "An kasa ajiye saitunan",
|
||||
"syncRestoreSuccess": "An maido saitunan daga Nostr",
|
||||
"syncDecryptFailed": "An kasa maido saitunan",
|
||||
"gitSettings": "Git",
|
||||
"gitSettingsDescription": "Saita bayanan shaidar Git don tabbatar da HTTP",
|
||||
"nostrSettings": "Nostr",
|
||||
|
||||
@@ -99,6 +99,19 @@
|
||||
"settingsDescription": "Jikwaa ntọala ngwa gị na nhọrọ.",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "Hazie ndị na-enye AI na igodo API",
|
||||
"aiSettingsSync": "Mekọrịta na Nostr",
|
||||
"autoSyncAiSettings": "Mmekọrịta akpaaka",
|
||||
"autoSyncAiSettingsDescription": "Zoo ntọala AI gị n'akaụntụ Nostr gị ma mee ka ha na-emekọrịta n'ọtụtụ ngwaọrụ.",
|
||||
"syncUnsupportedDescription": "Onye mbinye aka gị ugbu a anaghị akwado nzuzo NIP-44, ya mere mmekọrịta adịghị.",
|
||||
"backUpNow": "Mee nchekwa ugbu a",
|
||||
"restoreFromNostr": "Weghachite site na Nostr",
|
||||
"lastSynced": "Mmekọrịta ikpeazụ: {{time}}",
|
||||
"neverSynced": "Emekọrịtabeghị mgbe ọ bụla",
|
||||
"noRemoteBackup": "Achọtaghị nchekwa na Nostr",
|
||||
"syncBackupSuccess": "Echekwala ntọala na Nostr",
|
||||
"syncBackupFailed": "Nchekwa ntọala dara",
|
||||
"syncRestoreSuccess": "Eweghachitela ntọala site na Nostr",
|
||||
"syncDecryptFailed": "Iweghachi ntọala dara",
|
||||
"gitSettings": "Git",
|
||||
"gitSettingsDescription": "Hazie nzere Git maka nkwenye HTTP",
|
||||
"nostrSettings": "Nostr",
|
||||
|
||||
@@ -99,6 +99,19 @@
|
||||
"settingsDescription": "Gerencie as configurações e preferências da aplicação.",
|
||||
"aiSettings": "IA",
|
||||
"aiSettingsDescription": "Configure provedores de IA e chaves de API",
|
||||
"aiSettingsSync": "Sincronizar com Nostr",
|
||||
"autoSyncAiSettings": "Sincronização automática",
|
||||
"autoSyncAiSettingsDescription": "Criptografe suas configurações de IA na sua conta Nostr e mantenha-as sincronizadas entre dispositivos.",
|
||||
"syncUnsupportedDescription": "Seu assinante atual não suporta criptografia NIP-44, portanto a sincronização não está disponível.",
|
||||
"backUpNow": "Fazer backup agora",
|
||||
"restoreFromNostr": "Restaurar do Nostr",
|
||||
"lastSynced": "Última sincronização: {{time}}",
|
||||
"neverSynced": "Nunca sincronizado",
|
||||
"noRemoteBackup": "Nenhum backup encontrado no Nostr",
|
||||
"syncBackupSuccess": "Configurações salvas no Nostr",
|
||||
"syncBackupFailed": "Falha ao fazer backup das configurações",
|
||||
"syncRestoreSuccess": "Configurações restauradas do Nostr",
|
||||
"syncDecryptFailed": "Falha ao restaurar as configurações",
|
||||
"gitSettings": "Git",
|
||||
"gitSettingsDescription": "Configure credenciais do Git para autenticação HTTP",
|
||||
"deploySettings": "Implantação",
|
||||
|
||||
@@ -99,6 +99,19 @@
|
||||
"settingsDescription": "Ṣakoso awọn eto ohun elo rẹ ati awọn ayanfẹ.",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "Tunto awọn olupese AI ati awọn bọtini API",
|
||||
"aiSettingsSync": "Mu ṣiṣẹpọ pẹlu Nostr",
|
||||
"autoSyncAiSettings": "Ìmúṣiṣẹpọ aládàáṣe",
|
||||
"autoSyncAiSettingsDescription": "Fi àbáwọlé pa àwọn eto AI rẹ sí àkàǹtì Nostr rẹ, kí o sì jẹ́ kí wọ́n máa ṣiṣẹpọ kọjá àwọn ẹrọ.",
|
||||
"syncUnsupportedDescription": "Olùfọwọ́sí rẹ lọ́wọ́lọ́wọ́ kò ṣe àtìlẹyìn fún ìpamọ́ NIP-44, nítorí náà ṣiṣẹpọ kò sí.",
|
||||
"backUpNow": "Ṣe afẹyinti báyìí",
|
||||
"restoreFromNostr": "Mú padà láti Nostr",
|
||||
"lastSynced": "Ìṣiṣẹpọ ìkẹyìn: {{time}}",
|
||||
"neverSynced": "Kò ṣiṣẹpọ rí",
|
||||
"noRemoteBackup": "Kò sí afẹyinti lórí Nostr",
|
||||
"syncBackupSuccess": "Àwọn eto ti fi pamọ sí Nostr",
|
||||
"syncBackupFailed": "Ìfẹyinti àwọn eto kùnà",
|
||||
"syncRestoreSuccess": "Àwọn eto ti padà láti Nostr",
|
||||
"syncDecryptFailed": "Mímú àwọn eto padà kùnà",
|
||||
"gitSettings": "Git",
|
||||
"gitSettingsDescription": "Tunto awọn ẹri Git fun ijẹrisi HTTP",
|
||||
"nostrSettings": "Nostr",
|
||||
|
||||
@@ -99,6 +99,19 @@
|
||||
"settingsDescription": "管理您的应用程序设置和偏好。",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "配置AI提供商和API密钥",
|
||||
"aiSettingsSync": "同步到 Nostr",
|
||||
"autoSyncAiSettings": "自动同步设置",
|
||||
"autoSyncAiSettingsDescription": "将您的 AI 设置加密到您的 Nostr 账户,并在各设备间保持同步。",
|
||||
"syncUnsupportedDescription": "您当前的签名器不支持 NIP-44 加密,因此无法同步。",
|
||||
"backUpNow": "立即备份",
|
||||
"restoreFromNostr": "从 Nostr 恢复",
|
||||
"lastSynced": "上次同步:{{time}}",
|
||||
"neverSynced": "从未同步",
|
||||
"noRemoteBackup": "在 Nostr 上未找到备份",
|
||||
"syncBackupSuccess": "设置已备份到 Nostr",
|
||||
"syncBackupFailed": "备份设置失败",
|
||||
"syncRestoreSuccess": "设置已从 Nostr 恢复",
|
||||
"syncDecryptFailed": "恢复设置失败",
|
||||
"gitSettings": "Git",
|
||||
"gitSettingsDescription": "配置HTTP身份验证的Git凭据",
|
||||
"deploySettings": "部署",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot, ChevronDown, RotateCcw, FileText, Edit, X } from 'lucide-react';
|
||||
import { Bot, ChevronDown, RotateCcw, FileText, Edit, X, Cloud, CloudUpload, Download, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
@@ -14,6 +16,7 @@ import { AddAIProviderDialog } from '@/components/AddAIProviderDialog';
|
||||
import { AddCustomAIProviderDialog } from '@/components/AddCustomAIProviderDialog';
|
||||
import { CreditsBadge } from '@/components/CreditsBadge';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useAISettingsSyncContext } from '@/hooks/useAISettingsSyncContext';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
|
||||
@@ -44,6 +47,7 @@ import {
|
||||
export function AISettings() {
|
||||
const { t } = useTranslation();
|
||||
const { settings, updateSettings, setProvider, removeProvider, setProviders, isLoading } = useAISettings();
|
||||
const sync = useAISettingsSyncContext();
|
||||
const { user } = useCurrentUser();
|
||||
const { config, defaultConfig, updateConfig } = useAppContext();
|
||||
const openRouterOAuth = useOpenRouterOAuth();
|
||||
@@ -400,6 +404,68 @@ export function AISettings() {
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
|
||||
{/* Nostr Sync */}
|
||||
{user && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Cloud className="h-5 w-5 text-primary" />
|
||||
<h3 className="text-lg font-semibold">{t('aiSettingsSync')}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{sync.canSync
|
||||
? t('autoSyncAiSettingsDescription')
|
||||
: t('syncUnsupportedDescription')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<Label htmlFor="ai-auto-sync">{t('autoSyncAiSettings')}</Label>
|
||||
<Switch
|
||||
id="ai-auto-sync"
|
||||
checked={sync.autoSync}
|
||||
onCheckedChange={sync.setAutoSync}
|
||||
disabled={!sync.canSync}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => sync.backupNow()}
|
||||
disabled={!sync.canSync || sync.isBackingUp}
|
||||
>
|
||||
{sync.isBackingUp ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<CloudUpload className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{t('backUpNow')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => sync.restoreFromNostr()}
|
||||
disabled={!sync.canSync || sync.isRestoring}
|
||||
>
|
||||
{sync.isRestoring ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{t('restoreFromNostr')}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{sync.lastSyncedAt
|
||||
? t('lastSynced', { time: new Date(sync.lastSyncedAt * 1000).toLocaleString() })
|
||||
: t('neverSynced')}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user