GitHubBackupSettings.tsx 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  1. import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import {
  5. Github,
  6. Play,
  7. Clock,
  8. CheckCircle,
  9. XCircle,
  10. Loader2,
  11. ExternalLink,
  12. RefreshCw,
  13. Download,
  14. Upload,
  15. Database,
  16. History,
  17. SkipForward,
  18. AlertTriangle,
  19. Trash2,
  20. RotateCcw,
  21. FolderArchive,
  22. } from 'lucide-react';
  23. import { api } from '../api/client';
  24. import type {
  25. GitHubBackupConfig,
  26. GitHubBackupConfigCreate,
  27. GitHubBackupLog,
  28. GitHubBackupStatus,
  29. GitHubBackupTriggerResponse,
  30. GitProviderType,
  31. LocalBackupFile,
  32. LocalBackupPathCheck,
  33. LocalBackupStatus,
  34. ScheduleType,
  35. CloudAccountCounts,
  36. CloudAuthStatus,
  37. Printer,
  38. } from '../api/client';
  39. import { useAuth } from '../contexts/AuthContext';
  40. import { Card, CardContent, CardHeader } from './Card';
  41. import { Button } from './Button';
  42. import { Toggle } from './Toggle';
  43. import { ConfirmModal } from './ConfirmModal';
  44. import { GitHubRestoreModal } from './GitHubRestoreModal';
  45. import { useToast } from '../contexts/ToastContext';
  46. import { formatRelativeTime, parseUTCDate } from '../utils/date';
  47. function formatDateTime(dateStr: string | null): string {
  48. if (!dateStr) return '-';
  49. const date = parseUTCDate(dateStr);
  50. if (!date) return '-';
  51. return date.toLocaleString();
  52. }
  53. interface StatusBadgeProps {
  54. status: string | null;
  55. }
  56. function StatusBadge({ status }: StatusBadgeProps) {
  57. if (!status) return null;
  58. const styles: Record<string, string> = {
  59. success: 'bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400',
  60. failed: 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400',
  61. skipped: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  62. running: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  63. };
  64. const icons: Record<string, React.ReactNode> = {
  65. success: <CheckCircle className="w-3 h-3" />,
  66. failed: <XCircle className="w-3 h-3" />,
  67. skipped: <SkipForward className="w-3 h-3" />,
  68. running: <Loader2 className="w-3 h-3 animate-spin" />,
  69. };
  70. return (
  71. <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium ${styles[status] || 'bg-gray-500/20 text-gray-400'}`}>
  72. {icons[status]}
  73. {status.charAt(0).toUpperCase() + status.slice(1)}
  74. </span>
  75. );
  76. }
  77. const PROVIDER_REPO_URL_I18N_KEY: Record<GitProviderType, string> = {
  78. github: 'backup.repoUrlPlaceholderGitHub',
  79. gitea: 'backup.repoUrlPlaceholderGitea',
  80. forgejo: 'backup.repoUrlPlaceholderForgejo',
  81. gitlab: 'backup.repoUrlPlaceholderGitLab',
  82. };
  83. const PROVIDER_TOKEN_PLACEHOLDER: Record<GitProviderType, string> = {
  84. github: 'ghp_xxxxxxxxxxxx',
  85. gitea: 'your_access_token',
  86. forgejo: 'your_access_token',
  87. gitlab: 'glpat-xxxxxxxxxxxx',
  88. };
  89. interface GitHubBackupAutosaveState {
  90. repository_url: string;
  91. branch: string;
  92. provider: GitProviderType;
  93. allow_insecure_http: boolean;
  94. schedule_enabled: boolean;
  95. schedule_type: ScheduleType;
  96. backup_kprofiles: boolean;
  97. backup_cloud_profiles: boolean;
  98. backup_settings: boolean;
  99. backup_spools: boolean;
  100. backup_archives: boolean;
  101. enabled: boolean;
  102. }
  103. function serializeAutosaveState(state: GitHubBackupAutosaveState): string {
  104. return JSON.stringify(state);
  105. }
  106. function getChangedAutosaveFields(
  107. current: GitHubBackupAutosaveState,
  108. previous: GitHubBackupAutosaveState | null
  109. ): Partial<GitHubBackupAutosaveState> {
  110. if (!previous) {
  111. return current;
  112. }
  113. const changes: Partial<GitHubBackupAutosaveState> = {};
  114. for (const key of Object.keys(current) as Array<keyof GitHubBackupAutosaveState>) {
  115. if (current[key] !== previous[key]) {
  116. changes[key] = current[key] as never;
  117. }
  118. }
  119. return changes;
  120. }
  121. export function GitHubBackupSettings() {
  122. const queryClient = useQueryClient();
  123. const { showToast } = useToast();
  124. const { t } = useTranslation();
  125. const { hasPermission } = useAuth();
  126. // All three restore endpoints are gated on GITHUB_RESTORE server-side, so a
  127. // user without it gets a 403 the moment the modal opens its preview. Hide the
  128. // button rather than offer an action that cannot work. Deliberately scoped to
  129. // the button: the card itself stays visible, since backup configuration is a
  130. // separate permission. hasPermission returns true when auth is off.
  131. const canRestoreFromGit = hasPermission('github:restore');
  132. // Local state for form
  133. const [repoUrl, setRepoUrl] = useState('');
  134. const [accessToken, setAccessToken] = useState('');
  135. const [branch, setBranch] = useState('main');
  136. const [provider, setProvider] = useState<GitProviderType>('github');
  137. const [scheduleEnabled, setScheduleEnabled] = useState(false);
  138. const [scheduleType, setScheduleType] = useState<ScheduleType>('daily');
  139. const [backupKProfiles, setBackupKProfiles] = useState(true);
  140. const [backupCloudProfiles, setBackupCloudProfiles] = useState(true);
  141. const [backupSettings, setBackupSettings] = useState(false);
  142. const [backupSpools, setBackupSpools] = useState(false);
  143. const [backupArchives, setBackupArchives] = useState(false);
  144. const [allowInsecureHttp, setAllowInsecureHttp] = useState(false);
  145. const [enabled, setEnabled] = useState(true);
  146. // Local backup state
  147. const [isExporting, setIsExporting] = useState(false);
  148. const [isRestoring, setIsRestoring] = useState(false);
  149. const [operationStatus, setOperationStatus] = useState<string>('');
  150. const [showRestoreConfirm, setShowRestoreConfirm] = useState(false);
  151. const [restoreFile, setRestoreFile] = useState<File | null>(null);
  152. const [restoreResult, setRestoreResult] = useState<{ success: boolean; message: string } | null>(null);
  153. const fileInputRef = useRef<HTMLInputElement>(null);
  154. // Restore from the Git backup repository (#2656)
  155. const [showGitRestore, setShowGitRestore] = useState(false);
  156. // Scheduled local backup state
  157. const [deleteConfirmFile, setDeleteConfirmFile] = useState<string | null>(null);
  158. const [restoreConfirmFile, setRestoreConfirmFile] = useState<string | null>(null);
  159. const [localBackupPath, setLocalBackupPath] = useState('');
  160. const { data: localBackupStatus, refetch: refetchLocalStatus } = useQuery<LocalBackupStatus>({
  161. queryKey: ['local-backup-status'],
  162. queryFn: api.getLocalBackupStatus,
  163. refetchInterval: (query) => query.state.data?.is_running ? 1000 : 10000,
  164. });
  165. const { data: localBackups, refetch: refetchLocalBackups } = useQuery<LocalBackupFile[]>({
  166. queryKey: ['local-backup-files'],
  167. queryFn: api.getLocalBackups,
  168. refetchInterval: 30000,
  169. });
  170. // Probes the output directory with a real write (#2544). A directory the
  171. // service cannot write to — a NAS share outside the systemd unit's
  172. // ReadWritePaths, typically — otherwise only surfaces as a failed backup at
  173. // 03:00, for however many nights it takes someone to notice. Refetched
  174. // explicitly when the path changes or a backup runs, not polled: it writes.
  175. const { data: localBackupPathCheck, refetch: refetchLocalPathCheck } = useQuery<LocalBackupPathCheck>({
  176. queryKey: ['local-backup-path-check'],
  177. queryFn: api.checkLocalBackupPath,
  178. enabled: localBackupStatus?.enabled === true,
  179. refetchOnWindowFocus: false,
  180. });
  181. // Sync local path state from server
  182. useEffect(() => {
  183. if (localBackupStatus?.path !== undefined) {
  184. setLocalBackupPath(localBackupStatus.path);
  185. }
  186. }, [localBackupStatus?.path]);
  187. const triggerLocalBackupMutation = useMutation({
  188. mutationFn: api.triggerLocalBackup,
  189. onSuccess: (data) => {
  190. if (data.success) {
  191. showToast(t('backup.scheduledBackupComplete'));
  192. } else {
  193. showToast(data.message, 'error');
  194. }
  195. refetchLocalStatus();
  196. refetchLocalBackups();
  197. refetchLocalPathCheck();
  198. },
  199. onError: () => showToast(t('backup.scheduledBackupFailed'), 'error'),
  200. });
  201. const deleteLocalBackupMutation = useMutation({
  202. mutationFn: (filename: string) => api.deleteLocalBackup(filename),
  203. onSuccess: () => {
  204. refetchLocalBackups();
  205. setDeleteConfirmFile(null);
  206. },
  207. });
  208. const restoreLocalBackupMutation = useMutation({
  209. mutationFn: async (filename: string) => {
  210. setRestoreConfirmFile(null);
  211. setIsRestoring(true);
  212. setRestoreResult(null);
  213. setOperationStatus(t('backup.restoring'));
  214. return api.restoreLocalBackup(filename);
  215. },
  216. onSuccess: (data) => {
  217. setIsRestoring(false);
  218. setOperationStatus('');
  219. if (data.success) {
  220. setRestoreResult({ success: true, message: data.message });
  221. showToast(t('backup.backupRestoredRestart'), 'success');
  222. } else {
  223. setRestoreResult({ success: false, message: data.message });
  224. showToast(data.message, 'error');
  225. }
  226. },
  227. onError: (e) => {
  228. setIsRestoring(false);
  229. setOperationStatus('');
  230. const msg = e instanceof Error ? e.message : t('backup.failedToRestore');
  231. setRestoreResult({ success: false, message: msg });
  232. showToast(msg, 'error');
  233. },
  234. });
  235. // Block navigation while backup/restore is in progress
  236. useEffect(() => {
  237. const isOperationInProgress = isExporting || isRestoring;
  238. if (isOperationInProgress) {
  239. const handleBeforeUnload = (e: BeforeUnloadEvent) => {
  240. e.preventDefault();
  241. e.returnValue = 'A backup operation is in progress. Are you sure you want to leave?';
  242. return e.returnValue;
  243. };
  244. window.addEventListener('beforeunload', handleBeforeUnload);
  245. return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  246. }
  247. }, [isExporting, isRestoring]);
  248. // Test connection state
  249. const [testLoading, setTestLoading] = useState(false);
  250. const [testResult, setTestResult] = useState<{
  251. success: boolean;
  252. message: string;
  253. isPrivate: boolean | null;
  254. } | null>(null);
  255. // Inline save-error banner — backend rejection messages (e.g. the
  256. // "repository is not private" guard) are far too long for a toast.
  257. // Cleared on success, on the next save attempt, and when the user starts
  258. // editing the repo URL / token / provider so the banner doesn't persist
  259. // after the user has already addressed the cause.
  260. const [saveError, setSaveError] = useState<string | null>(null);
  261. // Auto-save debounce
  262. const settingsAutoSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  263. const tokenAutoSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  264. const initializationTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  265. const lastSavedAutosaveStateRef = useRef<GitHubBackupAutosaveState | null>(null);
  266. const lastTokenScheduledForSaveRef = useRef('');
  267. const [isInitialized, setIsInitialized] = useState(false);
  268. const autoSaveState = useMemo<GitHubBackupAutosaveState>(() => ({
  269. repository_url: repoUrl,
  270. branch,
  271. provider,
  272. allow_insecure_http: allowInsecureHttp,
  273. schedule_enabled: scheduleEnabled,
  274. schedule_type: scheduleType,
  275. backup_kprofiles: backupKProfiles,
  276. backup_cloud_profiles: backupCloudProfiles,
  277. backup_settings: backupSettings,
  278. backup_spools: backupSpools,
  279. backup_archives: backupArchives,
  280. enabled,
  281. }), [repoUrl, branch, provider, allowInsecureHttp, scheduleEnabled, scheduleType, backupKProfiles, backupCloudProfiles, backupSettings, backupSpools, backupArchives, enabled]);
  282. const autoSaveStateFingerprint = useMemo(
  283. () => serializeAutosaveState(autoSaveState),
  284. [autoSaveState]
  285. );
  286. // Queries
  287. const { data: config, isLoading: configLoading } = useQuery<GitHubBackupConfig | null>({
  288. queryKey: ['github-backup-config'],
  289. queryFn: api.getGitHubBackupConfig,
  290. });
  291. const { data: status } = useQuery<GitHubBackupStatus>({
  292. queryKey: ['github-backup-status'],
  293. queryFn: api.getGitHubBackupStatus,
  294. refetchInterval: (query) => query.state.data?.is_running ? 500 : 10000, // Poll fast during backup
  295. });
  296. const { data: logs } = useQuery<GitHubBackupLog[]>({
  297. queryKey: ['github-backup-logs'],
  298. queryFn: () => api.getGitHubBackupLogs(20),
  299. });
  300. const { data: cloudStatus } = useQuery<CloudAuthStatus>({
  301. queryKey: ['cloud-status'],
  302. queryFn: api.getCloudStatus,
  303. });
  304. // How many cloud accounts the backup would actually collect from, across
  305. // both Bambu Cloud and Orca Cloud. Not the same question as `cloudStatus`,
  306. // which is only *this viewer's* Bambu sign-in: with auth enabled every user
  307. // holds their own credentials and the backup collects from all of them, so
  308. // an admin who never signed in to Bambu Cloud personally would otherwise see
  309. // the category disabled while there is plenty to back up (#2717).
  310. const { data: cloudAccounts } = useQuery<CloudAccountCounts>({
  311. queryKey: ['github-backup-cloud-accounts'],
  312. queryFn: api.getGitHubBackupCloudAccounts,
  313. staleTime: 60_000,
  314. });
  315. const connectedCloudAccounts = (cloudAccounts?.bambu ?? 0) + (cloudAccounts?.orca ?? 0);
  316. // Until the count arrives, fall back to the viewer's own Bambu status rather
  317. // than rendering the toggle as unavailable and making it flicker enabled.
  318. const anyCloudConnected = cloudAccounts
  319. ? connectedCloudAccounts > 0
  320. : !!cloudStatus?.is_authenticated;
  321. // Fetch printers and their statuses for K-profile availability
  322. const { data: printers } = useQuery<Printer[]>({
  323. queryKey: ['printers'],
  324. queryFn: api.getPrinters,
  325. });
  326. // Fetch printer statuses from API (not just cache) to get accurate connection status
  327. const printerStatusQueries = useQueries({
  328. queries: (printers ?? []).map(printer => ({
  329. queryKey: ['printerStatus', printer.id],
  330. queryFn: () => api.getPrinterStatus(printer.id),
  331. staleTime: 10000, // Consider stale after 10s
  332. refetchInterval: 30000, // Refresh every 30s
  333. })),
  334. });
  335. const printerStatuses = (printers ?? []).map((printer, index) => ({
  336. printer,
  337. connected: printerStatusQueries[index]?.data?.connected ?? false,
  338. }));
  339. const totalPrinters = printerStatuses.length;
  340. const connectedPrinters = printerStatuses.filter(p => p.connected).length;
  341. const noPrintersConnected = totalPrinters > 0 && connectedPrinters === 0;
  342. const somePrintersDisconnected = connectedPrinters > 0 && connectedPrinters < totalPrinters;
  343. // Initialize form from config
  344. useEffect(() => {
  345. if (initializationTimerRef.current) {
  346. clearTimeout(initializationTimerRef.current);
  347. }
  348. if (config) {
  349. setIsInitialized(false);
  350. lastSavedAutosaveStateRef.current = {
  351. repository_url: config.repository_url,
  352. branch: config.branch,
  353. provider: config.provider ?? 'github',
  354. allow_insecure_http: config.allow_insecure_http ?? false,
  355. schedule_enabled: config.schedule_enabled,
  356. schedule_type: config.schedule_type,
  357. backup_kprofiles: config.backup_kprofiles,
  358. backup_cloud_profiles: config.backup_cloud_profiles,
  359. backup_settings: config.backup_settings,
  360. backup_spools: config.backup_spools,
  361. backup_archives: config.backup_archives,
  362. enabled: config.enabled,
  363. };
  364. setRepoUrl(config.repository_url);
  365. setBranch(config.branch);
  366. setProvider(config.provider ?? 'github');
  367. setScheduleEnabled(config.schedule_enabled);
  368. setScheduleType(config.schedule_type);
  369. setBackupKProfiles(config.backup_kprofiles);
  370. setBackupCloudProfiles(config.backup_cloud_profiles);
  371. setBackupSettings(config.backup_settings);
  372. setBackupSpools(config.backup_spools);
  373. setBackupArchives(config.backup_archives);
  374. setAllowInsecureHttp(config.allow_insecure_http ?? false);
  375. setEnabled(config.enabled);
  376. setAccessToken(''); // Don't show stored token
  377. // Mark as initialized after a tick to avoid auto-save on initial load
  378. initializationTimerRef.current = setTimeout(() => { setIsInitialized(true); }, 100);
  379. } else {
  380. setIsInitialized(false);
  381. lastSavedAutosaveStateRef.current = null;
  382. setAccessToken('');
  383. }
  384. return () => {
  385. if (initializationTimerRef.current) {
  386. clearTimeout(initializationTimerRef.current);
  387. }
  388. };
  389. }, [config]);
  390. // Auto-save function for existing configs
  391. const autoSave = useCallback(async (includeToken: boolean = false) => {
  392. if (!config) return; // Only auto-save if config already exists
  393. try {
  394. if (includeToken && accessToken) {
  395. // Full save with new token
  396. await api.saveGitHubBackupConfig({
  397. ...autoSaveState,
  398. access_token: accessToken,
  399. });
  400. setAccessToken(''); // Clear after save
  401. setSaveError(null);
  402. showToast(t('backup.tokenUpdated'));
  403. lastTokenScheduledForSaveRef.current = '';
  404. } else {
  405. // Update without token
  406. await api.updateGitHubBackupConfig(getChangedAutosaveFields(
  407. autoSaveState,
  408. lastSavedAutosaveStateRef.current
  409. ));
  410. setSaveError(null);
  411. showToast(t('backup.settingsSaved'));
  412. }
  413. lastSavedAutosaveStateRef.current = autoSaveState;
  414. queryClient.invalidateQueries({ queryKey: ['github-backup-config'] });
  415. queryClient.invalidateQueries({ queryKey: ['github-backup-status'] });
  416. } catch (error) {
  417. setSaveError((error as Error).message);
  418. }
  419. }, [config, accessToken, autoSaveState, queryClient, showToast, t]);
  420. const autoSaveRef = useRef(autoSave);
  421. useEffect(() => {
  422. autoSaveRef.current = autoSave;
  423. }, [autoSave]);
  424. // Auto-save effect for existing configs (debounced)
  425. useEffect(() => {
  426. if (!isInitialized || !config) return;
  427. if (
  428. lastSavedAutosaveStateRef.current
  429. && autoSaveStateFingerprint === serializeAutosaveState(lastSavedAutosaveStateRef.current)
  430. ) return;
  431. if (settingsAutoSaveTimerRef.current) {
  432. clearTimeout(settingsAutoSaveTimerRef.current);
  433. }
  434. settingsAutoSaveTimerRef.current = setTimeout(() => {
  435. autoSave(false);
  436. }, 500);
  437. return () => {
  438. if (settingsAutoSaveTimerRef.current) {
  439. clearTimeout(settingsAutoSaveTimerRef.current);
  440. }
  441. };
  442. }, [isInitialized, config, autoSaveStateFingerprint, autoSave]);
  443. // Auto-save token when it changes (with longer debounce)
  444. useEffect(() => {
  445. if (!isInitialized || !config || !accessToken) return;
  446. if (accessToken === lastTokenScheduledForSaveRef.current) return;
  447. lastTokenScheduledForSaveRef.current = accessToken;
  448. if (tokenAutoSaveTimerRef.current) {
  449. clearTimeout(tokenAutoSaveTimerRef.current);
  450. }
  451. tokenAutoSaveTimerRef.current = setTimeout(() => {
  452. autoSaveRef.current(true);
  453. }, 1000);
  454. return () => {
  455. if (tokenAutoSaveTimerRef.current) {
  456. clearTimeout(tokenAutoSaveTimerRef.current);
  457. }
  458. };
  459. }, [isInitialized, accessToken, config]);
  460. // Mutations
  461. const saveConfigMutation = useMutation({
  462. mutationFn: (data: GitHubBackupConfigCreate) => api.saveGitHubBackupConfig(data),
  463. onMutate: () => {
  464. setSaveError(null);
  465. },
  466. onSuccess: () => {
  467. queryClient.invalidateQueries({ queryKey: ['github-backup-config'] });
  468. queryClient.invalidateQueries({ queryKey: ['github-backup-status'] });
  469. showToast(t('backup.githubBackupEnabled'));
  470. setAccessToken('');
  471. setIsInitialized(true);
  472. },
  473. onError: (error: Error) => {
  474. setSaveError(error.message);
  475. },
  476. });
  477. const triggerBackupMutation = useMutation<GitHubBackupTriggerResponse, Error>({
  478. mutationFn: api.triggerGitHubBackup,
  479. onSuccess: (result) => {
  480. queryClient.invalidateQueries({ queryKey: ['github-backup-status'] });
  481. queryClient.invalidateQueries({ queryKey: ['github-backup-logs'] });
  482. if (result.success) {
  483. if (result.files_changed > 0) {
  484. showToast(t('backup.backupCompleteFiles', { count: result.files_changed }));
  485. } else {
  486. showToast(t('backup.backupSkippedNoChanges'));
  487. }
  488. } else {
  489. showToast(t('backup.backupFailed2', { message: result.message }), 'error');
  490. }
  491. },
  492. onError: (error: Error) => {
  493. showToast(t('backup.backupFailed2', { message: error.message }), 'error');
  494. },
  495. });
  496. const clearLogsMutation = useMutation<{ deleted: number; message: string }, Error>({
  497. mutationFn: () => api.clearGitHubBackupLogs(0),
  498. onSuccess: (result) => {
  499. queryClient.invalidateQueries({ queryKey: ['github-backup-logs'] });
  500. showToast(t('backup.clearedLogs', { count: result.deleted }));
  501. },
  502. onError: (error: Error) => {
  503. showToast(t('backup.failedToClearLogs', { message: error.message }), 'error');
  504. },
  505. });
  506. const handleTestConnection = async () => {
  507. setTestLoading(true);
  508. setTestResult(null);
  509. try {
  510. let result;
  511. // If user entered a new token, test with those credentials
  512. if (accessToken) {
  513. if (!repoUrl) {
  514. showToast(t('backup.enterRepoUrl'), 'error');
  515. setTestLoading(false);
  516. return;
  517. }
  518. result = await api.testGitHubConnection(repoUrl, accessToken, provider);
  519. } else if (config?.has_token) {
  520. // Use stored credentials
  521. result = await api.testGitHubStoredConnection();
  522. } else {
  523. showToast(t('backup.enterRepoAndToken'), 'error');
  524. setTestLoading(false);
  525. return;
  526. }
  527. setTestResult({
  528. success: result.success,
  529. message: result.message,
  530. isPrivate: result.is_private,
  531. });
  532. } catch (error) {
  533. setTestResult({ success: false, message: (error as Error).message, isPrivate: null });
  534. } finally {
  535. setTestLoading(false);
  536. }
  537. };
  538. // Initial setup save (only for new configs)
  539. const handleInitialSetup = () => {
  540. if (!repoUrl) {
  541. showToast(t('backup.repoRequired'), 'error');
  542. return;
  543. }
  544. if (!accessToken) {
  545. showToast(t('backup.tokenRequired'), 'error');
  546. return;
  547. }
  548. saveConfigMutation.mutate({
  549. repository_url: repoUrl,
  550. access_token: accessToken,
  551. branch,
  552. provider,
  553. allow_insecure_http: allowInsecureHttp,
  554. schedule_enabled: scheduleEnabled,
  555. schedule_type: scheduleType,
  556. backup_kprofiles: backupKProfiles,
  557. backup_cloud_profiles: backupCloudProfiles,
  558. backup_settings: backupSettings,
  559. backup_spools: backupSpools,
  560. backup_archives: backupArchives,
  561. enabled,
  562. });
  563. };
  564. if (configLoading) {
  565. return (
  566. <div className="flex items-center justify-center py-12">
  567. <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
  568. </div>
  569. );
  570. }
  571. return (
  572. <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
  573. {/* Left Column - Git Backup */}
  574. <div className="space-y-6">
  575. <Card id="card-backup-github">
  576. <CardHeader>
  577. <div className="flex items-center justify-between">
  578. <div className="flex items-center gap-2">
  579. <Github className="w-5 h-5 text-gray-400" />
  580. <h2 className="text-lg font-semibold text-white">{t('backup.githubBackup')}</h2>
  581. </div>
  582. {config && (
  583. <div className="flex items-center gap-2">
  584. <span className="text-sm text-bambu-gray">{t('backup.enabled')}</span>
  585. <Toggle
  586. checked={enabled}
  587. onChange={setEnabled}
  588. />
  589. </div>
  590. )}
  591. </div>
  592. </CardHeader>
  593. <CardContent className="space-y-4">
  594. <p className="text-sm text-bambu-gray">
  595. {t('backup.githubDescription')}
  596. </p>
  597. {/* Provider Selection */}
  598. <div>
  599. <label htmlFor="git-provider-select" className="block text-sm text-bambu-gray mb-1">{t('backup.provider')}</label>
  600. <select
  601. id="git-provider-select"
  602. value={provider}
  603. onChange={(e) => { setProvider(e.target.value as GitProviderType); setTestResult(null); setSaveError(null); }}
  604. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  605. >
  606. <option value="github">{t('backup.providerGitHub')}</option>
  607. <option value="gitlab">{t('backup.providerGitLab')}</option>
  608. <option value="gitea">{t('backup.providerGitea')}</option>
  609. <option value="forgejo">{t('backup.providerForgejo')}</option>
  610. </select>
  611. </div>
  612. {/* Repository URL */}
  613. <div>
  614. <label className="block text-sm text-bambu-gray mb-1">
  615. {t('backup.repositoryUrl')}
  616. </label>
  617. <input
  618. type="text"
  619. value={repoUrl}
  620. onChange={(e) => { setRepoUrl(e.target.value); setTestResult(null); setSaveError(null); }}
  621. placeholder={t(PROVIDER_REPO_URL_I18N_KEY[provider])}
  622. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  623. />
  624. <label className="flex items-start gap-2 mt-2 cursor-pointer">
  625. <input
  626. type="checkbox"
  627. checked={allowInsecureHttp}
  628. onChange={(e) => { setAllowInsecureHttp(e.target.checked); setTestResult(null); }}
  629. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  630. />
  631. <div>
  632. <span className="text-sm text-white">{t('backup.allowInsecureHttp')}</span>
  633. <p className="text-xs text-bambu-gray">{t('backup.allowInsecureHttpHint')}</p>
  634. </div>
  635. </label>
  636. </div>
  637. {/* Access Token */}
  638. <div>
  639. <label className="block text-sm text-bambu-gray mb-1">
  640. {t('backup.personalAccessToken')} {config?.has_token && <span className="text-green-700 dark:text-green-400">{t('backup.tokenSaved')}</span>}
  641. </label>
  642. <input
  643. type="password"
  644. value={accessToken}
  645. onChange={(e) => { setAccessToken(e.target.value); setTestResult(null); setSaveError(null); }}
  646. placeholder={config?.has_token ? t('backup.enterNewToken') : PROVIDER_TOKEN_PLACEHOLDER[provider]}
  647. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  648. />
  649. <p className="text-xs text-bambu-gray mt-1">
  650. {t('backup.tokenHint')}
  651. </p>
  652. </div>
  653. {/* Branch - inline with schedule */}
  654. <div className="grid grid-cols-2 gap-4">
  655. <div>
  656. <label className="block text-sm text-bambu-gray mb-1">{t('backup.branch')}</label>
  657. <input
  658. type="text"
  659. value={branch}
  660. onChange={(e) => setBranch(e.target.value)}
  661. placeholder="main"
  662. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  663. />
  664. </div>
  665. <div>
  666. <label className="block text-sm text-bambu-gray mb-1">{t('backup.autoBackup')}</label>
  667. <select
  668. value={scheduleEnabled ? scheduleType : 'disabled'}
  669. onChange={(e) => {
  670. if (e.target.value === 'disabled') {
  671. setScheduleEnabled(false);
  672. } else {
  673. setScheduleEnabled(true);
  674. setScheduleType(e.target.value as ScheduleType);
  675. }
  676. }}
  677. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  678. >
  679. <option value="disabled">{t('backup.manualOnly')}</option>
  680. <option value="hourly">{t('backup.hourly')}</option>
  681. <option value="daily">{t('backup.daily')}</option>
  682. <option value="weekly">{t('backup.weekly')}</option>
  683. </select>
  684. </div>
  685. </div>
  686. {/* What to backup */}
  687. <div>
  688. <label className="block text-sm text-bambu-gray mb-2">{t('backup.includeInBackup')}</label>
  689. <div className="space-y-2">
  690. <label className={`flex items-start gap-2 ${noPrintersConnected ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}>
  691. <input
  692. type="checkbox"
  693. checked={backupKProfiles}
  694. onChange={(e) => setBackupKProfiles(e.target.checked)}
  695. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  696. disabled={noPrintersConnected}
  697. />
  698. <div className="flex-1">
  699. <div className="flex items-center gap-2">
  700. <span className={`text-sm ${noPrintersConnected ? 'text-bambu-gray' : 'text-white'}`}>{t('backup.kProfiles')}</span>
  701. {noPrintersConnected && (
  702. <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400">
  703. <AlertTriangle className="w-3 h-3" />
  704. {t('backup.noPrintersConnected')}
  705. </span>
  706. )}
  707. {somePrintersDisconnected && (
  708. <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400">
  709. <AlertTriangle className="w-3 h-3" />
  710. {t('backup.printersConnected', { connected: connectedPrinters, total: totalPrinters })}
  711. </span>
  712. )}
  713. </div>
  714. <p className="text-xs text-bambu-gray">{t('backup.kProfilesDescription')}</p>
  715. </div>
  716. </label>
  717. <label className={`flex items-start gap-2 ${!anyCloudConnected ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}>
  718. <input
  719. type="checkbox"
  720. checked={backupCloudProfiles}
  721. onChange={(e) => setBackupCloudProfiles(e.target.checked)}
  722. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  723. disabled={!anyCloudConnected}
  724. />
  725. <div>
  726. <div className="flex items-center gap-2">
  727. <span className={`text-sm ${anyCloudConnected ? 'text-white' : 'text-bambu-gray'}`}>{t('backup.cloudProfiles')}</span>
  728. {!anyCloudConnected && (
  729. <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400">
  730. <AlertTriangle className="w-3 h-3" />
  731. {t('backup.cloudLoginRequiredShort')}
  732. </span>
  733. )}
  734. </div>
  735. <p className="text-xs text-bambu-gray">{t('backup.cloudProfilesDescription')}</p>
  736. {/* Say how many accounts are in scope. On a multi-user
  737. install the presets being backed up are other people's,
  738. and the count is the only honest way to show that
  739. without naming them. */}
  740. {connectedCloudAccounts > 0 && (
  741. <p className="text-xs text-bambu-gray mt-0.5">
  742. {t('backup.cloudProfilesAccounts', {
  743. bambu: cloudAccounts?.bambu ?? 0,
  744. orca: cloudAccounts?.orca ?? 0,
  745. })}
  746. </p>
  747. )}
  748. </div>
  749. </label>
  750. <label className="flex items-start gap-2 cursor-pointer">
  751. <input
  752. type="checkbox"
  753. checked={backupSettings}
  754. onChange={(e) => setBackupSettings(e.target.checked)}
  755. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  756. />
  757. <div>
  758. <span className="text-white text-sm">{t('backup.appSettings')}</span>
  759. <p className="text-xs text-bambu-gray">{t('backup.appSettingsDescription')}</p>
  760. </div>
  761. </label>
  762. <label className="flex items-start gap-2 cursor-pointer">
  763. <input
  764. type="checkbox"
  765. checked={backupSpools}
  766. onChange={(e) => setBackupSpools(e.target.checked)}
  767. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  768. />
  769. <div>
  770. <span className="text-white text-sm">{t('backup.spoolInventory')}</span>
  771. <p className="text-xs text-bambu-gray">{t('backup.spoolInventoryDescription')}</p>
  772. </div>
  773. </label>
  774. <label className="flex items-start gap-2 cursor-pointer">
  775. <input
  776. type="checkbox"
  777. checked={backupArchives}
  778. onChange={(e) => setBackupArchives(e.target.checked)}
  779. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  780. />
  781. <div>
  782. <span className="text-white text-sm">{t('backup.printArchives')}</span>
  783. <p className="text-xs text-bambu-gray">{t('backup.printArchivesDescription')}</p>
  784. </div>
  785. </label>
  786. </div>
  787. </div>
  788. {/* Test + Status + Actions */}
  789. <div className="border-t border-bambu-dark-tertiary pt-4 space-y-3">
  790. {/* Status line */}
  791. {status?.configured && (
  792. <div className="flex items-center justify-between text-sm">
  793. <div className="flex items-center gap-2 text-bambu-gray">
  794. {status.last_backup_at ? (
  795. <>
  796. <span>{t('backup.lastBackupAt')} {formatRelativeTime(status.last_backup_at, 'system', t)}</span>
  797. <StatusBadge status={status.last_backup_status} />
  798. </>
  799. ) : (
  800. <span>{t('backup.noBackupsYet')}</span>
  801. )}
  802. </div>
  803. {status.next_scheduled_run && (
  804. <span className="text-bambu-gray">
  805. <Clock className="w-3 h-3 inline mr-1" />
  806. {t('backup.next')} {formatRelativeTime(status.next_scheduled_run, 'system', t)}
  807. </span>
  808. )}
  809. </div>
  810. )}
  811. {/* Save error — inline banner. Keeps long backend rejection
  812. messages (e.g. the "repository is not private" guard)
  813. readable instead of clipped to a toast. */}
  814. {saveError && (
  815. <div className="text-sm text-red-700 dark:text-red-400 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded p-3 flex items-start gap-2">
  816. <XCircle className="w-4 h-4 mt-0.5 shrink-0" />
  817. <div className="flex-1 leading-relaxed whitespace-pre-wrap break-words">{saveError}</div>
  818. <button
  819. type="button"
  820. onClick={() => setSaveError(null)}
  821. className="text-bambu-gray hover:text-white shrink-0"
  822. aria-label={t('common.dismiss', 'Dismiss')}
  823. >
  824. <XCircle className="w-4 h-4" />
  825. </button>
  826. </div>
  827. )}
  828. {/* Test result */}
  829. {testResult && (
  830. <div className="space-y-1.5">
  831. <div className={`text-sm flex items-center gap-1 ${testResult.success ? 'text-green-700 dark:text-green-400' : 'text-red-700 dark:text-red-400'}`}>
  832. {testResult.success ? <CheckCircle className="w-4 h-4" /> : <XCircle className="w-4 h-4" />}
  833. {testResult.message}
  834. </div>
  835. {testResult.success && testResult.isPrivate === true && (
  836. <div className="text-xs flex items-center gap-1 text-green-700 dark:text-green-400">
  837. <CheckCircle className="w-3.5 h-3.5" />
  838. {t('backup.repoIsPrivate', 'Repository is private — safe to back up to.')}
  839. </div>
  840. )}
  841. {testResult.success && testResult.isPrivate === false && (
  842. <div className="text-xs text-red-700 dark:text-red-400 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded p-2 flex items-start gap-1.5">
  843. <XCircle className="w-4 h-4 mt-0.5 shrink-0" />
  844. <span>
  845. {t(
  846. 'backup.repoIsPublicWarning',
  847. 'Repository is PUBLIC. Bambuddy backups include MQTT credentials, Home Assistant tokens, Prometheus tokens, your Bambu Cloud email, and printer access codes via K-profiles. Saving is blocked until you make the repository private in your provider\'s settings.',
  848. )}
  849. </span>
  850. </div>
  851. )}
  852. {testResult.success && testResult.isPrivate === null && (
  853. <div className="text-xs text-yellow-700 dark:text-yellow-400 bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded p-2 flex items-start gap-1.5">
  854. <XCircle className="w-4 h-4 mt-0.5 shrink-0" />
  855. <span>
  856. {t(
  857. 'backup.repoVisibilityUnknown',
  858. 'Could not determine repository visibility. Bambuddy refuses to back up to anything not confirmed private; saving will be blocked.',
  859. )}
  860. </span>
  861. </div>
  862. )}
  863. </div>
  864. )}
  865. {/* Action buttons */}
  866. <div className="flex flex-wrap items-center gap-2">
  867. {status?.configured ? (
  868. <>
  869. {(triggerBackupMutation.isPending || status.is_running) ? (
  870. <div className="flex items-center gap-2 text-bambu-green">
  871. <Loader2 className="w-4 h-4 animate-spin" />
  872. <span className="text-sm">{status.progress || t('backup.startingBackup')}</span>
  873. </div>
  874. ) : (
  875. <>
  876. <Button
  877. variant="primary"
  878. size="sm"
  879. onClick={() => triggerBackupMutation.mutate()}
  880. disabled={!config?.enabled}
  881. >
  882. <Play className="w-4 h-4" />
  883. {t('backup.backupNow')}
  884. </Button>
  885. <Button
  886. variant="secondary"
  887. size="sm"
  888. onClick={handleTestConnection}
  889. disabled={testLoading}
  890. >
  891. {testLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
  892. {t('backup.test')}
  893. </Button>
  894. {/* Restore from the backup repo (#2656) */}
  895. {canRestoreFromGit && (
  896. <Button
  897. variant="secondary"
  898. size="sm"
  899. onClick={() => setShowGitRestore(true)}
  900. disabled={status.restore_running}
  901. >
  902. <RotateCcw className="w-4 h-4" />
  903. {t('backup.restoreFromGit.button')}
  904. </Button>
  905. )}
  906. </>
  907. )}
  908. </>
  909. ) : (
  910. <>
  911. <Button
  912. variant="primary"
  913. size="sm"
  914. onClick={handleInitialSetup}
  915. disabled={saveConfigMutation.isPending || !repoUrl || !accessToken}
  916. >
  917. {saveConfigMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle className="w-4 h-4" />}
  918. {t('backup.enableBackup')}
  919. </Button>
  920. <Button
  921. variant="secondary"
  922. size="sm"
  923. onClick={handleTestConnection}
  924. disabled={testLoading || !repoUrl || !accessToken}
  925. >
  926. {testLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
  927. {t('backup.testConnection')}
  928. </Button>
  929. </>
  930. )}
  931. </div>
  932. </div>
  933. </CardContent>
  934. </Card>
  935. {/* Backup History - only show if configured and has logs */}
  936. {logs && logs.length > 0 && (
  937. <Card id="card-backup-history">
  938. <CardHeader>
  939. <div className="flex items-center justify-between">
  940. <div className="flex items-center gap-2">
  941. <History className="w-5 h-5 text-gray-400" />
  942. <h2 className="text-lg font-semibold text-white">{t('backup.history')}</h2>
  943. </div>
  944. <Button
  945. variant="ghost"
  946. size="sm"
  947. onClick={() => clearLogsMutation.mutate()}
  948. disabled={clearLogsMutation.isPending}
  949. >
  950. <Trash2 className="w-4 h-4" />
  951. {t('backup.clear')}
  952. </Button>
  953. </div>
  954. </CardHeader>
  955. <CardContent>
  956. <div className="overflow-x-auto">
  957. <table className="w-full text-sm">
  958. <thead>
  959. <tr className="text-bambu-gray border-b border-bambu-dark-tertiary">
  960. <th className="text-left py-2 px-2">{t('backup.date')}</th>
  961. <th className="text-left py-2 px-2">{t('backup.status')}</th>
  962. <th className="text-left py-2 px-2">{t('backup.commit')}</th>
  963. </tr>
  964. </thead>
  965. <tbody>
  966. {logs.slice(0, 10).map((log) => (
  967. <tr key={log.id} className="border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary">
  968. <td className="py-2 px-2 text-white">{formatDateTime(log.started_at)}</td>
  969. <td className="py-2 px-2"><StatusBadge status={log.status} /></td>
  970. <td className="py-2 px-2">
  971. {log.commit_sha ? (
  972. <a
  973. href={`${config?.repository_url}/commit/${log.commit_sha}`}
  974. target="_blank"
  975. rel="noopener noreferrer"
  976. className="text-bambu-green hover:underline inline-flex items-center gap-1"
  977. >
  978. {log.commit_sha.substring(0, 7)}
  979. <ExternalLink className="w-3 h-3" />
  980. </a>
  981. ) : (
  982. <span className="text-bambu-gray">-</span>
  983. )}
  984. </td>
  985. </tr>
  986. ))}
  987. </tbody>
  988. </table>
  989. </div>
  990. </CardContent>
  991. </Card>
  992. )}
  993. </div>
  994. {/* Right Column - Local Backup */}
  995. <div className="space-y-6">
  996. <Card id="card-backup-local">
  997. <CardHeader>
  998. <div className="flex items-center gap-2">
  999. <Database className="w-5 h-5 text-gray-400" />
  1000. <h2 className="text-lg font-semibold text-white">{t('backup.localBackup')}</h2>
  1001. </div>
  1002. </CardHeader>
  1003. <CardContent className="space-y-4">
  1004. <p className="text-sm text-bambu-gray">
  1005. {t('backup.localBackupDescription')}
  1006. </p>
  1007. {/* Export */}
  1008. <div className="flex items-center justify-between py-3 border-b border-bambu-dark-tertiary">
  1009. <div>
  1010. <p className="text-white">{t('backup.downloadBackupLabel')}</p>
  1011. <p className="text-sm text-bambu-gray">
  1012. {t('backup.completeBackupZip')}
  1013. </p>
  1014. </div>
  1015. <Button
  1016. variant="secondary"
  1017. size="sm"
  1018. disabled={isExporting || isRestoring}
  1019. onClick={async () => {
  1020. setIsExporting(true);
  1021. setOperationStatus(t('backup.preparingBackup'));
  1022. try {
  1023. setOperationStatus(t('backup.creatingArchive'));
  1024. const { blob, filename } = await api.exportBackup();
  1025. setOperationStatus(t('backup.downloadingFile'));
  1026. const url = URL.createObjectURL(blob);
  1027. const a = document.createElement('a');
  1028. a.href = url;
  1029. a.download = filename;
  1030. a.click();
  1031. URL.revokeObjectURL(url);
  1032. showToast(t('backup.backupDownloaded'));
  1033. } catch (e) {
  1034. showToast(t('backup.failedToCreateBackup', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1035. } finally {
  1036. setIsExporting(false);
  1037. setOperationStatus('');
  1038. }
  1039. }}
  1040. >
  1041. <Download className="w-4 h-4" />
  1042. {t('backup.download')}
  1043. </Button>
  1044. </div>
  1045. {/* Import */}
  1046. <div className="flex items-center justify-between py-3 border-b border-bambu-dark-tertiary">
  1047. <div>
  1048. <p className="text-white">{t('backup.restoreBackup')}</p>
  1049. <p className="text-sm text-bambu-gray">
  1050. {t('backup.restoreDescription')}
  1051. </p>
  1052. <p className="text-xs text-bambu-gray-light mt-1">
  1053. {t('backup.restoreNote')}
  1054. </p>
  1055. </div>
  1056. <input
  1057. ref={fileInputRef}
  1058. type="file"
  1059. accept=".zip"
  1060. className="hidden"
  1061. onChange={(e) => {
  1062. const file = e.target.files?.[0];
  1063. if (file) {
  1064. setRestoreFile(file);
  1065. setShowRestoreConfirm(true);
  1066. }
  1067. e.target.value = '';
  1068. }}
  1069. />
  1070. <Button
  1071. variant="secondary"
  1072. size="sm"
  1073. disabled={isRestoring || isExporting}
  1074. onClick={() => fileInputRef.current?.click()}
  1075. >
  1076. <Upload className="w-4 h-4" />
  1077. {t('backup.restore')}
  1078. </Button>
  1079. </div>
  1080. {/* Restore result message */}
  1081. {restoreResult && (
  1082. <div className={`p-3 rounded-lg ${restoreResult.success ? 'bg-green-50 dark:bg-green-500/10 border border-green-300 dark:border-green-500/30' : 'bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30'}`}>
  1083. <div className="flex items-start gap-2 text-sm">
  1084. {restoreResult.success ? (
  1085. <CheckCircle className="w-4 h-4 text-green-600 dark:text-green-400 mt-0.5 flex-shrink-0" />
  1086. ) : (
  1087. <XCircle className="w-4 h-4 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
  1088. )}
  1089. <div className={restoreResult.success ? 'text-green-800 dark:text-green-200' : 'text-red-800 dark:text-red-200'}>
  1090. {restoreResult.message}
  1091. {restoreResult.success && (
  1092. <div className="mt-2">
  1093. <Button
  1094. size="sm"
  1095. onClick={() => window.location.reload()}
  1096. >
  1097. <RotateCcw className="w-3 h-3" />
  1098. {t('backup.reloadNow')}
  1099. </Button>
  1100. </div>
  1101. )}
  1102. </div>
  1103. </div>
  1104. </div>
  1105. )}
  1106. {/* Warning */}
  1107. <div className="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30">
  1108. <div className="flex items-start gap-2 text-sm">
  1109. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  1110. <div className="text-yellow-800 dark:text-yellow-200">
  1111. <span className="font-medium">{t('backup.restoreReplacesAll')}</span>{' '}
  1112. <span className="text-yellow-800/80 dark:text-yellow-200/70">{t('backup.restoreReplacesAllDetail')}</span>
  1113. </div>
  1114. </div>
  1115. </div>
  1116. </CardContent>
  1117. </Card>
  1118. {/* Scheduled Local Backups */}
  1119. <Card id="card-backup-scheduled">
  1120. <CardHeader>
  1121. <div className="flex items-center justify-between">
  1122. <div className="flex items-center gap-2">
  1123. <FolderArchive className="w-5 h-5 text-gray-400" />
  1124. <h2 className="text-lg font-semibold text-white">{t('backup.scheduledBackup')}</h2>
  1125. </div>
  1126. <Toggle
  1127. checked={localBackupStatus?.enabled ?? false}
  1128. onChange={async (checked) => {
  1129. try {
  1130. await api.updateSettings({ local_backup_enabled: checked });
  1131. queryClient.invalidateQueries({ queryKey: ['settings'] });
  1132. showToast(t('backup.settingsSaved'));
  1133. } catch (e) {
  1134. showToast(t('backup.failedToSave', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1135. }
  1136. refetchLocalStatus();
  1137. }}
  1138. />
  1139. </div>
  1140. </CardHeader>
  1141. <CardContent className="space-y-4">
  1142. <p className="text-sm text-bambu-gray">
  1143. {t('backup.scheduledBackupDescription')}
  1144. </p>
  1145. {localBackupStatus?.enabled && (
  1146. <>
  1147. {/* Schedule + Time + Retention */}
  1148. <div className="grid grid-cols-3 gap-4">
  1149. <div>
  1150. <label className="block text-sm text-bambu-gray mb-1">{t('backup.frequency')}</label>
  1151. <select
  1152. value={localBackupStatus?.schedule ?? 'daily'}
  1153. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  1154. onChange={async (e) => {
  1155. try {
  1156. await api.updateSettings({ local_backup_schedule: e.target.value });
  1157. showToast(t('backup.settingsSaved'));
  1158. } catch (e) {
  1159. showToast(t('backup.failedToSave', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1160. }
  1161. refetchLocalStatus();
  1162. }}
  1163. >
  1164. <option value="hourly">{t('backup.hourly')}</option>
  1165. <option value="daily">{t('backup.daily')}</option>
  1166. <option value="weekly">{t('backup.weekly')}</option>
  1167. </select>
  1168. </div>
  1169. {(localBackupStatus?.schedule ?? 'daily') !== 'hourly' && (
  1170. <div>
  1171. <label className="block text-sm text-bambu-gray mb-1">{t('backup.backupTime')}</label>
  1172. <input
  1173. type="time"
  1174. value={localBackupStatus?.time ?? '03:00'}
  1175. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none [color-scheme:dark]"
  1176. onChange={async (e) => {
  1177. try {
  1178. await api.updateSettings({ local_backup_time: e.target.value });
  1179. showToast(t('backup.settingsSaved'));
  1180. } catch (err) {
  1181. showToast(t('backup.failedToSave', { message: err instanceof Error ? err.message : 'Unknown error' }), 'error');
  1182. }
  1183. refetchLocalStatus();
  1184. }}
  1185. />
  1186. <p className="text-xs text-bambu-gray-light mt-1">
  1187. {t('backup.localTimeHint', { tz: localBackupStatus?.timezone || 'UTC' })}
  1188. </p>
  1189. </div>
  1190. )}
  1191. <div>
  1192. <label className="block text-sm text-bambu-gray mb-1">{t('backup.retention')}</label>
  1193. <input
  1194. type="number"
  1195. min={1}
  1196. max={100}
  1197. value={localBackupStatus?.retention ?? 5}
  1198. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  1199. onChange={async (e) => {
  1200. const val = Math.max(1, Math.min(100, parseInt(e.target.value) || 5));
  1201. try {
  1202. await api.updateSettings({ local_backup_retention: val });
  1203. showToast(t('backup.settingsSaved'));
  1204. } catch (e) {
  1205. showToast(t('backup.failedToSave', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1206. }
  1207. refetchLocalStatus();
  1208. }}
  1209. />
  1210. <p className="text-xs text-bambu-gray-light mt-1">{t('backup.retentionDescription')}</p>
  1211. </div>
  1212. </div>
  1213. {/* Output Path */}
  1214. <div>
  1215. <label className="block text-sm text-bambu-gray mb-1">{t('backup.outputPath')}</label>
  1216. <input
  1217. type="text"
  1218. value={localBackupPath}
  1219. onChange={(e) => setLocalBackupPath(e.target.value)}
  1220. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  1221. onBlur={async () => {
  1222. try {
  1223. await api.updateSettings({ local_backup_path: localBackupPath });
  1224. showToast(t('backup.settingsSaved'));
  1225. } catch (err) {
  1226. showToast(t('backup.failedToSave', { message: err instanceof Error ? err.message : 'Unknown error' }), 'error');
  1227. }
  1228. refetchLocalStatus();
  1229. refetchLocalBackups();
  1230. refetchLocalPathCheck();
  1231. }}
  1232. onKeyDown={(e) => {
  1233. if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
  1234. }}
  1235. />
  1236. <p className="text-xs text-bambu-gray-light mt-1">
  1237. {localBackupPath
  1238. ? t('backup.outputPathDescription')
  1239. : <>{t('backup.defaultPathLabel')} <code className="text-bambu-gray">{localBackupStatus?.default_path || '...'}</code></>
  1240. }
  1241. </p>
  1242. {/* The directory cannot be written to — say why, and how to fix it (#2544) */}
  1243. {localBackupPathCheck && !localBackupPathCheck.writable && (
  1244. <div className="mt-2 p-3 rounded-lg bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30">
  1245. <div className="flex items-start gap-2 text-sm">
  1246. <AlertTriangle className="w-4 h-4 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
  1247. <div className="min-w-0 text-red-800 dark:text-red-200">
  1248. <p className="font-medium">{t('backup.pathCheck.title')}</p>
  1249. <p className="mt-1 text-red-800/80 dark:text-red-200/80">
  1250. {t(`backup.pathCheck.${localBackupPathCheck.code}`, {
  1251. path: localBackupPathCheck.path,
  1252. defaultValue: localBackupPathCheck.message,
  1253. })}
  1254. </p>
  1255. {localBackupPathCheck.remedy && (
  1256. <>
  1257. <p className="mt-2 font-medium">{t('backup.pathCheck.howToFix')}</p>
  1258. <pre className="mt-1 p-2 rounded bg-black/10 dark:bg-black/40 text-xs whitespace-pre-wrap break-words">
  1259. {localBackupPathCheck.remedy}
  1260. </pre>
  1261. </>
  1262. )}
  1263. {localBackupPathCheck.detail && (
  1264. <p className="mt-2 text-xs text-red-800/60 dark:text-red-200/60 break-words">
  1265. {localBackupPathCheck.detail}
  1266. </p>
  1267. )}
  1268. </div>
  1269. </div>
  1270. </div>
  1271. )}
  1272. {/* Writable, but only inside the container — the backups die with it */}
  1273. {localBackupPathCheck?.writable && localBackupPathCheck.warning === 'container_ephemeral' && (
  1274. <div className="mt-2 p-3 rounded-lg bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30">
  1275. <div className="flex items-start gap-2 text-sm">
  1276. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  1277. <div className="min-w-0 text-yellow-800 dark:text-yellow-200">
  1278. <p className="font-medium">{t('backup.pathCheck.ephemeralTitle')}</p>
  1279. <p className="mt-1 text-yellow-800/80 dark:text-yellow-200/80">
  1280. {t('backup.pathCheck.container_ephemeral', { path: localBackupPathCheck.path })}
  1281. </p>
  1282. {localBackupPathCheck.remedy && (
  1283. <pre className="mt-1 p-2 rounded bg-black/10 dark:bg-black/40 text-xs whitespace-pre-wrap break-words">
  1284. {localBackupPathCheck.remedy}
  1285. </pre>
  1286. )}
  1287. </div>
  1288. </div>
  1289. </div>
  1290. )}
  1291. </div>
  1292. {/* Status + Run Now */}
  1293. <div className="flex items-center justify-between py-3 border-t border-bambu-dark-tertiary">
  1294. <div className="text-sm">
  1295. {localBackupStatus?.last_backup_at && (
  1296. <div className="flex items-center gap-2 text-bambu-gray">
  1297. <span>{t('backup.lastBackup')}:</span>
  1298. <StatusBadge status={localBackupStatus.last_status} />
  1299. <span>{formatRelativeTime(localBackupStatus.last_backup_at)}</span>
  1300. </div>
  1301. )}
  1302. {localBackupStatus?.next_run && (
  1303. <div className="text-bambu-gray mt-1">
  1304. <span>{t('backup.nextBackup')}: </span>
  1305. <span>{formatDateTime(localBackupStatus.next_run)}</span>
  1306. </div>
  1307. )}
  1308. </div>
  1309. <Button
  1310. variant="secondary"
  1311. size="sm"
  1312. disabled={localBackupStatus?.is_running || triggerLocalBackupMutation.isPending}
  1313. onClick={() => triggerLocalBackupMutation.mutate()}
  1314. >
  1315. {localBackupStatus?.is_running || triggerLocalBackupMutation.isPending ? (
  1316. <Loader2 className="w-4 h-4 animate-spin" />
  1317. ) : (
  1318. <Play className="w-4 h-4" />
  1319. )}
  1320. {localBackupStatus?.is_running ? t('backup.backupRunning') : t('backup.runNow')}
  1321. </Button>
  1322. </div>
  1323. {/* Backup Files List */}
  1324. {localBackups && localBackups.length > 0 && (
  1325. <div className="border-t border-bambu-dark-tertiary pt-3">
  1326. <h3 className="text-sm font-medium text-white mb-2">{t('backup.backupFiles')}</h3>
  1327. <div className="space-y-1">
  1328. {localBackups.map((file) => (
  1329. <div key={file.filename} className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-bambu-dark-tertiary/50 text-sm">
  1330. <div className="flex-1 min-w-0">
  1331. <span className="text-white truncate block">{file.filename}</span>
  1332. <span className="text-bambu-gray text-xs">
  1333. {(file.size / 1024 / 1024).toFixed(1)} MB &middot; {formatDateTime(file.created_at)}
  1334. </span>
  1335. </div>
  1336. <div className="flex items-center gap-1 flex-shrink-0">
  1337. <button
  1338. className="text-bambu-gray hover:text-bambu-green p-1"
  1339. title={t('backup.download')}
  1340. onClick={async () => {
  1341. try {
  1342. const { blob, filename: fname } = await api.downloadLocalBackup(file.filename);
  1343. const url = URL.createObjectURL(blob);
  1344. const a = document.createElement('a');
  1345. a.href = url;
  1346. a.download = fname;
  1347. a.click();
  1348. URL.revokeObjectURL(url);
  1349. } catch {
  1350. showToast(t('backup.scheduledBackupFailed'), 'error');
  1351. }
  1352. }}
  1353. >
  1354. <Download className="w-3.5 h-3.5" />
  1355. </button>
  1356. <button
  1357. className="text-bambu-gray hover:text-yellow-600 dark:hover:text-yellow-400 p-1"
  1358. title={t('backup.restore')}
  1359. onClick={() => setRestoreConfirmFile(file.filename)}
  1360. >
  1361. <RotateCcw className="w-3.5 h-3.5" />
  1362. </button>
  1363. <button
  1364. className="text-bambu-gray hover:text-red-600 dark:hover:text-red-400 p-1"
  1365. onClick={() => setDeleteConfirmFile(file.filename)}
  1366. title={t('backup.deleteBackup')}
  1367. >
  1368. <Trash2 className="w-3.5 h-3.5" />
  1369. </button>
  1370. </div>
  1371. </div>
  1372. ))}
  1373. </div>
  1374. </div>
  1375. )}
  1376. {localBackups && localBackups.length === 0 && (
  1377. <p className="text-sm text-bambu-gray text-center py-3 border-t border-bambu-dark-tertiary">
  1378. {t('backup.noScheduledBackups')}
  1379. </p>
  1380. )}
  1381. </>
  1382. )}
  1383. </CardContent>
  1384. </Card>
  1385. </div>
  1386. {/* Restore from the Git backup repository (#2656) */}
  1387. {showGitRestore && <GitHubRestoreModal onClose={() => setShowGitRestore(false)} />}
  1388. {/* Delete Backup Confirmation Modal */}
  1389. {deleteConfirmFile && (
  1390. <ConfirmModal
  1391. title={t('backup.deleteBackup')}
  1392. message={t('backup.deleteBackupConfirm')}
  1393. confirmText={t('backup.deleteBackup')}
  1394. variant="danger"
  1395. onConfirm={() => deleteLocalBackupMutation.mutate(deleteConfirmFile)}
  1396. onCancel={() => setDeleteConfirmFile(null)}
  1397. />
  1398. )}
  1399. {/* Restore from Scheduled Backup Confirmation Modal */}
  1400. {restoreConfirmFile && (
  1401. <ConfirmModal
  1402. title={t('backup.restoreConfirmTitle')}
  1403. message={t('backup.restoreConfirmMessage', { filename: restoreConfirmFile })}
  1404. confirmText={t('backup.restoreConfirmButton')}
  1405. variant="danger"
  1406. onConfirm={() => restoreLocalBackupMutation.mutate(restoreConfirmFile)}
  1407. onCancel={() => setRestoreConfirmFile(null)}
  1408. />
  1409. )}
  1410. {/* Restore Confirmation Modal */}
  1411. {showRestoreConfirm && restoreFile && (
  1412. <ConfirmModal
  1413. title={t('backup.restoreConfirmTitle')}
  1414. message={t('backup.restoreConfirmMessage', { filename: restoreFile.name })}
  1415. confirmText={t('backup.restoreConfirmButton')}
  1416. variant="danger"
  1417. onConfirm={async () => {
  1418. setShowRestoreConfirm(false);
  1419. setIsRestoring(true);
  1420. setRestoreResult(null);
  1421. try {
  1422. setOperationStatus(t('backup.uploadingFile'));
  1423. const result = await api.importBackup(restoreFile);
  1424. setRestoreResult(result);
  1425. if (result.success) {
  1426. showToast(t('backup.backupRestoredRestart'), 'success');
  1427. } else {
  1428. showToast(result.message, 'error');
  1429. }
  1430. } catch (e) {
  1431. const message = e instanceof Error ? e.message : t('backup.failedToRestore');
  1432. setRestoreResult({ success: false, message });
  1433. showToast(message, 'error');
  1434. } finally {
  1435. setIsRestoring(false);
  1436. setOperationStatus('');
  1437. setRestoreFile(null);
  1438. }
  1439. }}
  1440. onCancel={() => {
  1441. setShowRestoreConfirm(false);
  1442. setRestoreFile(null);
  1443. }}
  1444. />
  1445. )}
  1446. {/* Blocking overlay during backup/restore operations */}
  1447. {(isExporting || isRestoring) && (
  1448. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-[100]">
  1449. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center">
  1450. <div className="flex justify-center mb-4">
  1451. <div className="relative">
  1452. <div className="w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"></div>
  1453. <div className="w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"></div>
  1454. </div>
  1455. </div>
  1456. <h3 className="text-xl font-semibold text-white mb-2">
  1457. {isExporting ? t('backup.creatingBackup') : t('backup.restoringBackup')}
  1458. </h3>
  1459. <p className="text-bambu-gray mb-4">
  1460. {operationStatus || (isExporting ? t('backup.preparing') : t('backup.processing'))}
  1461. </p>
  1462. <div className="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30">
  1463. <div className="flex items-start gap-2 text-sm">
  1464. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  1465. <p className="text-yellow-800 dark:text-yellow-200 text-left">
  1466. {t('backup.doNotClosePage')}
  1467. </p>
  1468. </div>
  1469. </div>
  1470. </div>
  1471. </div>
  1472. )}
  1473. </div>
  1474. );
  1475. }