GitHubBackupSettings.tsx 70 KB

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