GitHubBackupSettings.tsx 68 KB

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