GitHubBackupSettings.tsx 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  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 } = 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. </div>
  1032. <Button
  1033. variant="secondary"
  1034. size="sm"
  1035. disabled={isExporting || isRestoring}
  1036. onClick={async () => {
  1037. setIsExporting(true);
  1038. setOperationStatus(t('backup.preparingBackup'));
  1039. try {
  1040. setOperationStatus(t('backup.creatingArchive'));
  1041. const { blob, filename } = await api.exportBackup();
  1042. setOperationStatus(t('backup.downloadingFile'));
  1043. const url = URL.createObjectURL(blob);
  1044. const a = document.createElement('a');
  1045. a.href = url;
  1046. a.download = filename;
  1047. a.click();
  1048. URL.revokeObjectURL(url);
  1049. showToast(t('backup.backupDownloaded'));
  1050. } catch (e) {
  1051. showToast(t('backup.failedToCreateBackup', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1052. } finally {
  1053. setIsExporting(false);
  1054. setOperationStatus('');
  1055. }
  1056. }}
  1057. >
  1058. <Download className="w-4 h-4" />
  1059. {t('backup.download')}
  1060. </Button>
  1061. </div>
  1062. {/* Import */}
  1063. <div className="flex items-center justify-between py-3 border-b border-bambu-dark-tertiary">
  1064. <div>
  1065. <p className="text-white">{t('backup.restoreBackup')}</p>
  1066. <p className="text-sm text-bambu-gray">
  1067. {t('backup.restoreDescription')}
  1068. </p>
  1069. <p className="text-xs text-bambu-gray-light mt-1">
  1070. {t('backup.restoreNote')}
  1071. </p>
  1072. </div>
  1073. <input
  1074. ref={fileInputRef}
  1075. type="file"
  1076. accept=".zip"
  1077. className="hidden"
  1078. onChange={(e) => {
  1079. const file = e.target.files?.[0];
  1080. if (file) {
  1081. setRestoreFile(file);
  1082. setShowRestoreConfirm(true);
  1083. }
  1084. e.target.value = '';
  1085. }}
  1086. />
  1087. <Button
  1088. variant="secondary"
  1089. size="sm"
  1090. disabled={isRestoring || isExporting}
  1091. onClick={() => fileInputRef.current?.click()}
  1092. >
  1093. <Upload className="w-4 h-4" />
  1094. {t('backup.restore')}
  1095. </Button>
  1096. </div>
  1097. {/* Restore result message */}
  1098. {restoreResult && (
  1099. <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'}`}>
  1100. <div className="flex items-start gap-2 text-sm">
  1101. {restoreResult.success ? (
  1102. <CheckCircle className="w-4 h-4 text-green-600 dark:text-green-400 mt-0.5 flex-shrink-0" />
  1103. ) : (
  1104. <XCircle className="w-4 h-4 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
  1105. )}
  1106. <div className={restoreResult.success ? 'text-green-800 dark:text-green-200' : 'text-red-800 dark:text-red-200'}>
  1107. {restoreResult.message}
  1108. {restoreResult.success && (
  1109. <div className="mt-2">
  1110. <Button
  1111. size="sm"
  1112. onClick={() => window.location.reload()}
  1113. >
  1114. <RotateCcw className="w-3 h-3" />
  1115. {t('backup.reloadNow')}
  1116. </Button>
  1117. </div>
  1118. )}
  1119. </div>
  1120. </div>
  1121. </div>
  1122. )}
  1123. {/* Warning */}
  1124. <div className="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30">
  1125. <div className="flex items-start gap-2 text-sm">
  1126. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  1127. <div className="text-yellow-800 dark:text-yellow-200">
  1128. <span className="font-medium">{t('backup.restoreReplacesAll')}</span>{' '}
  1129. <span className="text-yellow-800/80 dark:text-yellow-200/70">{t('backup.restoreReplacesAllDetail')}</span>
  1130. </div>
  1131. </div>
  1132. </div>
  1133. </CardContent>
  1134. </Card>
  1135. {/* Scheduled Local Backups */}
  1136. <Card id="card-backup-scheduled">
  1137. <CardHeader>
  1138. <div className="flex items-center justify-between">
  1139. <div className="flex items-center gap-2">
  1140. <FolderArchive className="w-5 h-5 text-gray-400" />
  1141. <h2 className="text-lg font-semibold text-white">{t('backup.scheduledBackup')}</h2>
  1142. </div>
  1143. <Toggle
  1144. checked={localBackupStatus?.enabled ?? false}
  1145. onChange={async (checked) => {
  1146. try {
  1147. await api.updateSettings({ local_backup_enabled: checked });
  1148. queryClient.invalidateQueries({ queryKey: ['settings'] });
  1149. showToast(t('backup.settingsSaved'));
  1150. } catch (e) {
  1151. showToast(t('backup.failedToSave', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1152. }
  1153. refetchLocalStatus();
  1154. }}
  1155. />
  1156. </div>
  1157. </CardHeader>
  1158. <CardContent className="space-y-4">
  1159. <p className="text-sm text-bambu-gray">
  1160. {t('backup.scheduledBackupDescription')}
  1161. </p>
  1162. {localBackupStatus?.enabled && (
  1163. <>
  1164. {/* Schedule + Time + Retention */}
  1165. <div className="grid grid-cols-3 gap-4">
  1166. <div>
  1167. <label className="block text-sm text-bambu-gray mb-1">{t('backup.frequency')}</label>
  1168. <select
  1169. value={localBackupStatus?.schedule ?? 'daily'}
  1170. 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"
  1171. onChange={async (e) => {
  1172. try {
  1173. await api.updateSettings({ local_backup_schedule: e.target.value });
  1174. showToast(t('backup.settingsSaved'));
  1175. } catch (e) {
  1176. showToast(t('backup.failedToSave', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1177. }
  1178. refetchLocalStatus();
  1179. }}
  1180. >
  1181. <option value="hourly">{t('backup.hourly')}</option>
  1182. <option value="daily">{t('backup.daily')}</option>
  1183. <option value="weekly">{t('backup.weekly')}</option>
  1184. </select>
  1185. </div>
  1186. {(localBackupStatus?.schedule ?? 'daily') !== 'hourly' && (
  1187. <div>
  1188. <label className="block text-sm text-bambu-gray mb-1">{t('backup.backupTime')}</label>
  1189. <input
  1190. type="time"
  1191. value={localBackupStatus?.time ?? '03:00'}
  1192. 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"
  1193. onChange={async (e) => {
  1194. try {
  1195. await api.updateSettings({ local_backup_time: e.target.value });
  1196. showToast(t('backup.settingsSaved'));
  1197. } catch (err) {
  1198. showToast(t('backup.failedToSave', { message: err instanceof Error ? err.message : 'Unknown error' }), 'error');
  1199. }
  1200. refetchLocalStatus();
  1201. }}
  1202. />
  1203. <p className="text-xs text-bambu-gray-light mt-1">
  1204. {t('backup.localTimeHint', { tz: localBackupStatus?.timezone || 'UTC' })}
  1205. </p>
  1206. </div>
  1207. )}
  1208. <div>
  1209. <label className="block text-sm text-bambu-gray mb-1">{t('backup.retention')}</label>
  1210. <NumberInput
  1211. min={1}
  1212. max={100}
  1213. value={localBackupStatus?.retention ?? 5}
  1214. 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"
  1215. onChange={async (val) => {
  1216. try {
  1217. await api.updateSettings({ local_backup_retention: val });
  1218. showToast(t('backup.settingsSaved'));
  1219. } catch (e) {
  1220. showToast(t('backup.failedToSave', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1221. }
  1222. refetchLocalStatus();
  1223. }}
  1224. fallback={5}
  1225. />
  1226. <p className="text-xs text-bambu-gray-light mt-1">{t('backup.retentionDescription')}</p>
  1227. </div>
  1228. </div>
  1229. {/* Output Path */}
  1230. <div>
  1231. <label className="block text-sm text-bambu-gray mb-1">{t('backup.outputPath')}</label>
  1232. <input
  1233. type="text"
  1234. value={localBackupPath}
  1235. onChange={(e) => setLocalBackupPath(e.target.value)}
  1236. 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"
  1237. onBlur={async () => {
  1238. try {
  1239. await api.updateSettings({ local_backup_path: localBackupPath });
  1240. showToast(t('backup.settingsSaved'));
  1241. } catch (err) {
  1242. showToast(t('backup.failedToSave', { message: err instanceof Error ? err.message : 'Unknown error' }), 'error');
  1243. }
  1244. refetchLocalStatus();
  1245. refetchLocalBackups();
  1246. refetchLocalPathCheck();
  1247. }}
  1248. onKeyDown={(e) => {
  1249. if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
  1250. }}
  1251. />
  1252. <p className="text-xs text-bambu-gray-light mt-1">
  1253. {localBackupPath
  1254. ? t('backup.outputPathDescription')
  1255. : <>{t('backup.defaultPathLabel')} <code className="text-bambu-gray">{localBackupStatus?.default_path || '...'}</code></>
  1256. }
  1257. </p>
  1258. {/* The directory cannot be written to — say why, and how to fix it (#2544) */}
  1259. {localBackupPathCheck && !localBackupPathCheck.writable && (
  1260. <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">
  1261. <div className="flex items-start gap-2 text-sm">
  1262. <AlertTriangle className="w-4 h-4 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
  1263. <div className="min-w-0 text-red-800 dark:text-red-200">
  1264. <p className="font-medium">{t('backup.pathCheck.title')}</p>
  1265. <p className="mt-1 text-red-800/80 dark:text-red-200/80">
  1266. {t(`backup.pathCheck.${localBackupPathCheck.code}`, {
  1267. path: localBackupPathCheck.path,
  1268. defaultValue: localBackupPathCheck.message,
  1269. })}
  1270. </p>
  1271. {localBackupPathCheck.remedy && (
  1272. <>
  1273. <p className="mt-2 font-medium">{t('backup.pathCheck.howToFix')}</p>
  1274. <pre className="mt-1 p-2 rounded bg-black/10 dark:bg-black/40 text-xs whitespace-pre-wrap break-words">
  1275. {localBackupPathCheck.remedy}
  1276. </pre>
  1277. </>
  1278. )}
  1279. {localBackupPathCheck.detail && (
  1280. <p className="mt-2 text-xs text-red-800/60 dark:text-red-200/60 break-words">
  1281. {localBackupPathCheck.detail}
  1282. </p>
  1283. )}
  1284. </div>
  1285. </div>
  1286. </div>
  1287. )}
  1288. {/* Writable, but only inside the container — the backups die with it */}
  1289. {localBackupPathCheck?.writable && localBackupPathCheck.warning === 'container_ephemeral' && (
  1290. <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">
  1291. <div className="flex items-start gap-2 text-sm">
  1292. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  1293. <div className="min-w-0 text-yellow-800 dark:text-yellow-200">
  1294. <p className="font-medium">{t('backup.pathCheck.ephemeralTitle')}</p>
  1295. <p className="mt-1 text-yellow-800/80 dark:text-yellow-200/80">
  1296. {t('backup.pathCheck.container_ephemeral', { path: localBackupPathCheck.path })}
  1297. </p>
  1298. {localBackupPathCheck.remedy && (
  1299. <pre className="mt-1 p-2 rounded bg-black/10 dark:bg-black/40 text-xs whitespace-pre-wrap break-words">
  1300. {localBackupPathCheck.remedy}
  1301. </pre>
  1302. )}
  1303. </div>
  1304. </div>
  1305. </div>
  1306. )}
  1307. </div>
  1308. {/* Status + Run Now */}
  1309. <div className="flex items-center justify-between py-3 border-t border-bambu-dark-tertiary">
  1310. <div className="text-sm">
  1311. {localBackupStatus?.last_backup_at && (
  1312. <div className="flex items-center gap-2 text-bambu-gray">
  1313. <span>{t('backup.lastBackup')}:</span>
  1314. <StatusBadge status={localBackupStatus.last_status} />
  1315. <span>{formatRelativeTime(localBackupStatus.last_backup_at)}</span>
  1316. </div>
  1317. )}
  1318. {localBackupStatus?.next_run && (
  1319. <div className="text-bambu-gray mt-1">
  1320. <span>{t('backup.nextBackup')}: </span>
  1321. <span>{formatDateTime(localBackupStatus.next_run)}</span>
  1322. </div>
  1323. )}
  1324. </div>
  1325. <Button
  1326. variant="secondary"
  1327. size="sm"
  1328. disabled={localBackupStatus?.is_running || triggerLocalBackupMutation.isPending}
  1329. onClick={() => triggerLocalBackupMutation.mutate()}
  1330. >
  1331. {localBackupStatus?.is_running || triggerLocalBackupMutation.isPending ? (
  1332. <Loader2 className="w-4 h-4 animate-spin" />
  1333. ) : (
  1334. <Play className="w-4 h-4" />
  1335. )}
  1336. {localBackupStatus?.is_running ? t('backup.backupRunning') : t('backup.runNow')}
  1337. </Button>
  1338. </div>
  1339. {/* Backup Files List */}
  1340. {localBackups && localBackups.length > 0 && (
  1341. <div className="border-t border-bambu-dark-tertiary pt-3">
  1342. <h3 className="text-sm font-medium text-white mb-2">{t('backup.backupFiles')}</h3>
  1343. <div className="space-y-1">
  1344. {localBackups.map((file) => (
  1345. <div key={file.filename} className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-bambu-dark-tertiary/50 text-sm">
  1346. <div className="flex-1 min-w-0">
  1347. <span className="text-white truncate block">{file.filename}</span>
  1348. <span className="text-bambu-gray text-xs">
  1349. {(file.size / 1024 / 1024).toFixed(1)} MB &middot; {formatDateTime(file.created_at)}
  1350. </span>
  1351. </div>
  1352. <div className="flex items-center gap-1 flex-shrink-0">
  1353. <button
  1354. className="text-bambu-gray hover:text-bambu-green p-1"
  1355. title={t('backup.download')}
  1356. onClick={async () => {
  1357. try {
  1358. const { blob, filename: fname } = await api.downloadLocalBackup(file.filename);
  1359. const url = URL.createObjectURL(blob);
  1360. const a = document.createElement('a');
  1361. a.href = url;
  1362. a.download = fname;
  1363. a.click();
  1364. URL.revokeObjectURL(url);
  1365. } catch {
  1366. showToast(t('backup.scheduledBackupFailed'), 'error');
  1367. }
  1368. }}
  1369. >
  1370. <Download className="w-3.5 h-3.5" />
  1371. </button>
  1372. <button
  1373. className="text-bambu-gray hover:text-yellow-600 dark:hover:text-yellow-400 p-1"
  1374. title={t('backup.restore')}
  1375. onClick={() => setRestoreConfirmFile(file.filename)}
  1376. >
  1377. <RotateCcw className="w-3.5 h-3.5" />
  1378. </button>
  1379. <button
  1380. className="text-bambu-gray hover:text-red-600 dark:hover:text-red-400 p-1"
  1381. onClick={() => setDeleteConfirmFile(file.filename)}
  1382. title={t('backup.deleteBackup')}
  1383. >
  1384. <Trash2 className="w-3.5 h-3.5" />
  1385. </button>
  1386. </div>
  1387. </div>
  1388. ))}
  1389. </div>
  1390. </div>
  1391. )}
  1392. {localBackups && localBackups.length === 0 && (
  1393. <p className="text-sm text-bambu-gray text-center py-3 border-t border-bambu-dark-tertiary">
  1394. {t('backup.noScheduledBackups')}
  1395. </p>
  1396. )}
  1397. </>
  1398. )}
  1399. </CardContent>
  1400. </Card>
  1401. </div>
  1402. {/* Restore from the Git backup repository (#2656) */}
  1403. {showGitRestore && <GitHubRestoreModal onClose={() => setShowGitRestore(false)} />}
  1404. {/* Delete Backup Confirmation Modal */}
  1405. {deleteConfirmFile && (
  1406. <ConfirmModal
  1407. title={t('backup.deleteBackup')}
  1408. message={t('backup.deleteBackupConfirm')}
  1409. confirmText={t('backup.deleteBackup')}
  1410. variant="danger"
  1411. onConfirm={() => deleteLocalBackupMutation.mutate(deleteConfirmFile)}
  1412. onCancel={() => setDeleteConfirmFile(null)}
  1413. />
  1414. )}
  1415. {/* Restore from Scheduled Backup Confirmation Modal */}
  1416. {restoreConfirmFile && (
  1417. <ConfirmModal
  1418. title={t('backup.restoreConfirmTitle')}
  1419. message={t('backup.restoreConfirmMessage', { filename: restoreConfirmFile })}
  1420. confirmText={t('backup.restoreConfirmButton')}
  1421. variant="danger"
  1422. onConfirm={() => restoreLocalBackupMutation.mutate(restoreConfirmFile)}
  1423. onCancel={() => setRestoreConfirmFile(null)}
  1424. />
  1425. )}
  1426. {/* Restore Confirmation Modal */}
  1427. {showRestoreConfirm && restoreFile && (
  1428. <ConfirmModal
  1429. title={t('backup.restoreConfirmTitle')}
  1430. message={t('backup.restoreConfirmMessage', { filename: restoreFile.name })}
  1431. confirmText={t('backup.restoreConfirmButton')}
  1432. variant="danger"
  1433. onConfirm={async () => {
  1434. setShowRestoreConfirm(false);
  1435. setIsRestoring(true);
  1436. setRestoreResult(null);
  1437. try {
  1438. setOperationStatus(t('backup.uploadingFile'));
  1439. const result = await api.importBackup(restoreFile);
  1440. setRestoreResult(result);
  1441. if (result.success) {
  1442. showToast(t('backup.backupRestoredRestart'), 'success');
  1443. } else {
  1444. showToast(result.message || t('backup.failedToRestore'), 'error');
  1445. }
  1446. } catch (e) {
  1447. const message = e instanceof Error ? e.message : t('backup.failedToRestore');
  1448. setRestoreResult({ success: false, message });
  1449. showToast(message, 'error');
  1450. } finally {
  1451. setIsRestoring(false);
  1452. setOperationStatus('');
  1453. setRestoreFile(null);
  1454. }
  1455. }}
  1456. onCancel={() => {
  1457. setShowRestoreConfirm(false);
  1458. setRestoreFile(null);
  1459. }}
  1460. />
  1461. )}
  1462. {/* Blocking overlay during backup/restore operations */}
  1463. {(isExporting || isRestoring) && (
  1464. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-[100]">
  1465. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center">
  1466. <div className="flex justify-center mb-4">
  1467. <div className="relative">
  1468. <div className="w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"></div>
  1469. <div className="w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"></div>
  1470. </div>
  1471. </div>
  1472. <h3 className="text-xl font-semibold text-white mb-2">
  1473. {isExporting ? t('backup.creatingBackup') : t('backup.restoringBackup')}
  1474. </h3>
  1475. <p className="text-bambu-gray mb-4">
  1476. {operationStatus || (isExporting ? t('backup.preparing') : t('backup.processing'))}
  1477. </p>
  1478. <div className="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30">
  1479. <div className="flex items-start gap-2 text-sm">
  1480. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  1481. <p className="text-yellow-800 dark:text-yellow-200 text-left">
  1482. {t('backup.doNotClosePage')}
  1483. </p>
  1484. </div>
  1485. </div>
  1486. </div>
  1487. </div>
  1488. )}
  1489. </div>
  1490. );
  1491. }