Spaces:
Sleeping
Sleeping
File size: 36,417 Bytes
bf8b26e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 |
import { useState, useCallback } from 'react';
import { toast } from 'react-toastify';
import { ImportExportService } from '~/lib/services/importExportService';
import { useIndexedDB } from '~/lib/hooks/useIndexedDB';
import { generateId } from 'ai';
interface UseDataOperationsProps {
/**
* Callback to reload settings after import
*/
onReloadSettings?: () => void;
/**
* Callback to reload chats after import
*/
onReloadChats?: () => void;
/**
* Callback to reset settings to defaults
*/
onResetSettings?: () => void;
/**
* Callback to reset chats
*/
onResetChats?: () => void;
/**
* Custom database instance (optional)
*/
customDb?: IDBDatabase;
}
/**
* Hook for managing data operations in the DataTab
*/
export function useDataOperations({
onReloadSettings,
onReloadChats,
onResetSettings,
onResetChats,
customDb,
}: UseDataOperationsProps = {}) {
const { db: defaultDb } = useIndexedDB();
// Use the custom database if provided, otherwise use the default
const db = customDb || defaultDb;
const [isExporting, setIsExporting] = useState(false);
const [isImporting, setIsImporting] = useState(false);
const [isResetting, setIsResetting] = useState(false);
const [isDownloadingTemplate, setIsDownloadingTemplate] = useState(false);
const [progressMessage, setProgressMessage] = useState<string>('');
const [progressPercent, setProgressPercent] = useState<number>(0);
const [lastOperation, setLastOperation] = useState<{ type: string; data: any } | null>(null);
/**
* Show progress toast with percentage
*/
const showProgress = useCallback((message: string, percent: number) => {
setProgressMessage(message);
setProgressPercent(percent);
// Dismiss any existing progress toast before showing a new one
toast.dismiss('progress-toast');
toast.loading(`${message} (${percent}%)`, {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast', // Use the same ID for all progress messages
});
}, []);
/**
* Export all settings to a JSON file
*/
const handleExportSettings = useCallback(async () => {
setIsExporting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading('Preparing settings export...', {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Export settings
showProgress('Exporting settings', 25);
const settingsData = await ImportExportService.exportSettings();
// Step 2: Create blob
showProgress('Creating file', 50);
const blob = new Blob([JSON.stringify(settingsData, null, 2)], {
type: 'application/json',
});
// Step 3: Download file
showProgress('Downloading file', 75);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'bolt-settings.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Step 4: Complete
showProgress('Completing export', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('Settings exported successfully', {
position: 'bottom-right',
autoClose: 3000,
});
// Save operation for potential undo
setLastOperation({ type: 'export-settings', data: settingsData });
} catch (error) {
console.error('Error exporting settings:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to export settings: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsExporting(false);
setProgressPercent(0);
setProgressMessage('');
}
}, [showProgress]);
/**
* Export selected settings categories to a JSON file
* @param categoryIds Array of category IDs to export
*/
const handleExportSelectedSettings = useCallback(
async (categoryIds: string[]) => {
if (!categoryIds || categoryIds.length === 0) {
toast.error('No settings categories selected', {
position: 'bottom-right',
autoClose: 3000,
});
return;
}
setIsExporting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading(`Preparing export of ${categoryIds.length} settings categories...`, {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Export all settings
showProgress('Exporting settings', 20);
const allSettings = await ImportExportService.exportSettings();
// Step 2: Filter settings by category
showProgress('Filtering selected categories', 40);
const filteredSettings: Record<string, any> = {
exportDate: allSettings.exportDate,
};
// Add selected categories to filtered settings
categoryIds.forEach((category) => {
if (allSettings[category]) {
filteredSettings[category] = allSettings[category];
}
});
// Step 3: Create blob
showProgress('Creating file', 60);
const blob = new Blob([JSON.stringify(filteredSettings, null, 2)], {
type: 'application/json',
});
// Step 4: Download file
showProgress('Downloading file', 80);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `bolt-settings-${categoryIds.join('-')}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Step 5: Complete
showProgress('Completing export', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success(`${categoryIds.length} settings categories exported successfully`, {
position: 'bottom-right',
autoClose: 3000,
});
// Save operation for potential undo
setLastOperation({
type: 'export-selected-settings',
data: { settings: filteredSettings, categories: categoryIds },
});
} catch (error) {
console.error('Error exporting selected settings:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to export settings: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsExporting(false);
setProgressPercent(0);
setProgressMessage('');
}
},
[showProgress],
);
/**
* Export all chats to a JSON file
*/
const handleExportAllChats = useCallback(async () => {
if (!db) {
toast.error('Database not available', {
position: 'bottom-right',
autoClose: 3000,
});
return;
}
console.log('Export: Using database', {
name: db.name,
version: db.version,
objectStoreNames: Array.from(db.objectStoreNames),
});
setIsExporting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading('Preparing chats export...', {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Export chats
showProgress('Retrieving chats from database', 25);
console.log('Database details:', {
name: db.name,
version: db.version,
objectStoreNames: Array.from(db.objectStoreNames),
});
// Direct database query approach for more reliable access
const directChats = await new Promise<any[]>((resolve, reject) => {
try {
console.log(`Creating transaction on '${db.name}' database, objectStore 'chats'`);
const transaction = db.transaction(['chats'], 'readonly');
const store = transaction.objectStore('chats');
const request = store.getAll();
request.onsuccess = () => {
console.log(`Found ${request.result ? request.result.length : 0} chats directly from database`);
resolve(request.result || []);
};
request.onerror = () => {
console.error('Error querying chats store:', request.error);
reject(request.error);
};
} catch (err) {
console.error('Error creating transaction:', err);
reject(err);
}
});
// Export data with direct chats
const exportData = {
chats: directChats,
exportDate: new Date().toISOString(),
};
console.log(`Preparing to export ${exportData.chats.length} chats`);
// Step 2: Create blob
showProgress('Creating file', 50);
const blob = new Blob([JSON.stringify(exportData, null, 2)], {
type: 'application/json',
});
// Step 3: Download file
showProgress('Downloading file', 75);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'bolt-chats.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Step 4: Complete
showProgress('Completing export', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success(`${exportData.chats.length} chats exported successfully`, {
position: 'bottom-right',
autoClose: 3000,
});
// Save operation for potential undo
setLastOperation({ type: 'export-chats', data: exportData });
} catch (error) {
console.error('Error exporting chats:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to export chats: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsExporting(false);
setProgressPercent(0);
setProgressMessage('');
}
}, [db, showProgress]);
/**
* Export selected chats to a JSON file
* @param chatIds Array of chat IDs to export
*/
const handleExportSelectedChats = useCallback(
async (chatIds: string[]) => {
if (!db) {
toast.error('Database not available', {
position: 'bottom-right',
autoClose: 3000,
});
return;
}
if (!chatIds || chatIds.length === 0) {
toast.error('No chats selected', {
position: 'bottom-right',
autoClose: 3000,
});
return;
}
setIsExporting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading(`Preparing export of ${chatIds.length} chats...`, {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Get chats from database
showProgress('Retrieving chats from database', 25);
const transaction = db.transaction(['chats'], 'readonly');
const store = transaction.objectStore('chats');
// Create an array to store the promises for getting each chat
const chatPromises = chatIds.map((chatId) => {
return new Promise<any>((resolve, reject) => {
const request = store.get(chatId);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
});
// Wait for all promises to resolve
const chats = await Promise.all(chatPromises);
const filteredChats = chats.filter(Boolean); // Remove any null/undefined results
console.log(`Retrieved ${filteredChats.length} chats for export`);
// Create export data
const exportData = {
chats: filteredChats,
exportDate: new Date().toISOString(),
};
// Step 2: Create blob
showProgress('Creating file', 50);
const blob = new Blob([JSON.stringify(exportData, null, 2)], {
type: 'application/json',
});
// Step 3: Download file
showProgress('Downloading file', 75);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'bolt-selected-chats.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Step 4: Complete
showProgress('Completing export', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success(`${filteredChats.length} chats exported successfully`, {
position: 'bottom-right',
autoClose: 3000,
});
// Save operation for potential undo
setLastOperation({ type: 'export-selected-chats', data: { chatIds, chats: filteredChats } });
} catch (error) {
console.error('Error exporting selected chats:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to export selected chats: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsExporting(false);
setProgressPercent(0);
setProgressMessage('');
}
},
[db, showProgress],
);
/**
* Import settings from a JSON file
* @param file The file to import
*/
const handleImportSettings = useCallback(
async (file: File) => {
setIsImporting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading(`Importing settings from ${file.name}...`, {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Read file
showProgress('Reading file', 20);
const fileContent = await file.text();
// Step 2: Parse JSON
showProgress('Parsing settings data', 40);
const importedData = JSON.parse(fileContent);
// Step 3: Validate data
showProgress('Validating settings data', 60);
// Save current settings for potential undo
const currentSettings = await ImportExportService.exportSettings();
setLastOperation({ type: 'import-settings', data: { previous: currentSettings } });
// Step 4: Import settings
showProgress('Applying settings', 80);
await ImportExportService.importSettings(importedData);
// Step 5: Complete
showProgress('Completing import', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('Settings imported successfully', {
position: 'bottom-right',
autoClose: 3000,
});
if (onReloadSettings) {
onReloadSettings();
}
} catch (error) {
console.error('Error importing settings:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to import settings: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsImporting(false);
setProgressPercent(0);
setProgressMessage('');
}
},
[onReloadSettings, showProgress],
);
/**
* Import chats from a JSON file
* @param file The file to import
*/
const handleImportChats = useCallback(
async (file: File) => {
if (!db) {
toast.error('Database not available', {
position: 'bottom-right',
autoClose: 3000,
});
return;
}
setIsImporting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading(`Importing chats from ${file.name}...`, {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Read file
showProgress('Reading file', 20);
const fileContent = await file.text();
// Step 2: Parse JSON and validate structure
showProgress('Parsing chat data', 40);
const importedData = JSON.parse(fileContent);
if (!importedData.chats || !Array.isArray(importedData.chats)) {
throw new Error('Invalid chat data format: missing or invalid chats array');
}
// Step 3: Validate each chat object
showProgress('Validating chat data', 60);
const validatedChats = importedData.chats.map((chat: any) => {
if (!chat.id || !Array.isArray(chat.messages)) {
throw new Error('Invalid chat format: missing required fields');
}
// Ensure each message has required fields
const validatedMessages = chat.messages.map((msg: any) => {
if (!msg.role || !msg.content) {
throw new Error('Invalid message format: missing required fields');
}
return {
id: msg.id || generateId(),
role: msg.role,
content: msg.content,
name: msg.name,
function_call: msg.function_call,
timestamp: msg.timestamp || Date.now(),
};
});
return {
id: chat.id,
description: chat.description || '',
messages: validatedMessages,
timestamp: chat.timestamp || new Date().toISOString(),
urlId: chat.urlId || null,
metadata: chat.metadata || null,
};
});
// Step 4: Save current chats for potential undo
showProgress('Preparing database transaction', 70);
const currentChats = await ImportExportService.exportAllChats(db);
setLastOperation({ type: 'import-chats', data: { previous: currentChats } });
// Step 5: Import chats
showProgress(`Importing ${validatedChats.length} chats`, 80);
const transaction = db.transaction(['chats'], 'readwrite');
const store = transaction.objectStore('chats');
let processed = 0;
for (const chat of validatedChats) {
store.put(chat);
processed++;
if (processed % 5 === 0 || processed === validatedChats.length) {
showProgress(
`Imported ${processed} of ${validatedChats.length} chats`,
80 + (processed / validatedChats.length) * 20,
);
}
}
await new Promise((resolve, reject) => {
transaction.oncomplete = resolve;
transaction.onerror = reject;
});
// Step 6: Complete
showProgress('Completing import', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success(`${validatedChats.length} chats imported successfully`, {
position: 'bottom-right',
autoClose: 3000,
});
if (onReloadChats) {
onReloadChats();
}
} catch (error) {
console.error('Error importing chats:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to import chats: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsImporting(false);
setProgressPercent(0);
setProgressMessage('');
}
},
[db, onReloadChats, showProgress],
);
/**
* Import API keys from a JSON file
* @param file The file to import
*/
const handleImportAPIKeys = useCallback(
async (file: File) => {
setIsImporting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading(`Importing API keys from ${file.name}...`, {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Read file
showProgress('Reading file', 20);
const fileContent = await file.text();
// Step 2: Parse JSON
showProgress('Parsing API keys data', 40);
const importedData = JSON.parse(fileContent);
// Step 3: Validate data
showProgress('Validating API keys data', 60);
// Get current API keys from cookies for potential undo
const apiKeysStr = document.cookie.split(';').find((row) => row.trim().startsWith('apiKeys='));
const currentApiKeys = apiKeysStr ? JSON.parse(decodeURIComponent(apiKeysStr.split('=')[1])) : {};
setLastOperation({ type: 'import-api-keys', data: { previous: currentApiKeys } });
// Step 4: Import API keys
showProgress('Applying API keys', 80);
const newKeys = ImportExportService.importAPIKeys(importedData);
const apiKeysJson = JSON.stringify(newKeys);
document.cookie = `apiKeys=${apiKeysJson}; path=/; max-age=31536000`;
// Step 5: Complete
showProgress('Completing import', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
// Count how many keys were imported
const keyCount = Object.keys(newKeys).length;
const newKeyCount = Object.keys(newKeys).filter(
(key) => !currentApiKeys[key] || currentApiKeys[key] !== newKeys[key],
).length;
toast.success(
`${keyCount} API keys imported successfully (${newKeyCount} new/updated)\n` +
'Note: Keys are stored in browser cookies. For server-side usage, add them to your .env.local file.',
{ position: 'bottom-right', autoClose: 5000 },
);
if (onReloadSettings) {
onReloadSettings();
}
} catch (error) {
console.error('Error importing API keys:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to import API keys: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsImporting(false);
setProgressPercent(0);
setProgressMessage('');
}
},
[onReloadSettings, showProgress],
);
/**
* Reset all settings to default values
*/
const handleResetSettings = useCallback(async () => {
setIsResetting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading('Resetting settings...', {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
if (db) {
// Step 1: Save current settings for potential undo
showProgress('Backing up current settings', 25);
const currentSettings = await ImportExportService.exportSettings();
setLastOperation({ type: 'reset-settings', data: { previous: currentSettings } });
// Step 2: Reset settings
showProgress('Resetting settings to defaults', 50);
await ImportExportService.resetAllSettings(db);
// Step 3: Complete
showProgress('Completing reset', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('Settings reset successfully', {
position: 'bottom-right',
autoClose: 3000,
});
if (onResetSettings) {
onResetSettings();
}
} else {
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error('Database not available', {
position: 'bottom-right',
autoClose: 3000,
});
}
} catch (error) {
console.error('Error resetting settings:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to reset settings: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsResetting(false);
setProgressPercent(0);
setProgressMessage('');
}
}, [db, onResetSettings, showProgress]);
/**
* Reset all chats
*/
const handleResetChats = useCallback(async () => {
if (!db) {
toast.error('Database not available', {
position: 'bottom-right',
autoClose: 3000,
});
return;
}
setIsResetting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading('Deleting all chats...', {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Save current chats for potential undo
showProgress('Backing up current chats', 25);
const currentChats = await ImportExportService.exportAllChats(db);
setLastOperation({ type: 'reset-chats', data: { previous: currentChats } });
// Step 2: Delete chats
showProgress('Deleting chats from database', 50);
await ImportExportService.deleteAllChats(db);
// Step 3: Complete
showProgress('Completing deletion', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('All chats deleted successfully', {
position: 'bottom-right',
autoClose: 3000,
});
if (onResetChats) {
onResetChats();
}
} catch (error) {
console.error('Error resetting chats:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to delete chats: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsResetting(false);
setProgressPercent(0);
setProgressMessage('');
}
}, [db, onResetChats, showProgress]);
/**
* Download API keys template
*/
const handleDownloadTemplate = useCallback(async () => {
setIsDownloadingTemplate(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading('Creating API keys template...', {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Create template
showProgress('Creating template', 50);
const templateData = ImportExportService.createAPIKeysTemplate();
// Step 2: Download file
showProgress('Downloading template', 75);
const blob = new Blob([JSON.stringify(templateData, null, 2)], {
type: 'application/json',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'bolt-api-keys-template.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Step 3: Complete
showProgress('Completing download', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('Template downloaded successfully', {
position: 'bottom-right',
autoClose: 3000,
});
} catch (error) {
console.error('Error downloading template:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to download template: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsDownloadingTemplate(false);
setProgressPercent(0);
setProgressMessage('');
}
}, [showProgress]);
/**
* Export API keys to a JSON file
*/
const handleExportAPIKeys = useCallback(async () => {
setIsExporting(true);
setProgressPercent(0);
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading('Exporting API keys...', {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
// Step 1: Get API keys from all sources
showProgress('Retrieving API keys', 25);
// Create a fetch request to get API keys from server
const response = await fetch('/api/export-api-keys');
if (!response.ok) {
throw new Error('Failed to retrieve API keys from server');
}
const apiKeys = await response.json();
// Step 2: Create blob
showProgress('Creating file', 50);
const blob = new Blob([JSON.stringify(apiKeys, null, 2)], {
type: 'application/json',
});
// Step 3: Download file
showProgress('Downloading file', 75);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'bolt-api-keys.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Step 4: Complete
showProgress('Completing export', 100);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('API keys exported successfully', {
position: 'bottom-right',
autoClose: 3000,
});
// Save operation for potential undo
setLastOperation({ type: 'export-api-keys', data: apiKeys });
} catch (error) {
console.error('Error exporting API keys:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to export API keys: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
} finally {
setIsExporting(false);
setProgressPercent(0);
setProgressMessage('');
}
}, [showProgress]);
/**
* Undo the last operation if possible
*/
const handleUndo = useCallback(async () => {
if (!lastOperation || !db) {
toast.error('Nothing to undo', {
position: 'bottom-right',
autoClose: 3000,
});
return;
}
// Dismiss any existing toast first
toast.dismiss('progress-toast');
toast.loading('Processing undo operation...', {
position: 'bottom-right',
autoClose: 3000,
toastId: 'progress-toast',
});
try {
switch (lastOperation.type) {
case 'import-settings': {
// Restore previous settings
await ImportExportService.importSettings(lastOperation.data.previous);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('Operation undone successfully', {
position: 'bottom-right',
autoClose: 3000,
});
if (onReloadSettings) {
onReloadSettings();
}
break;
}
case 'import-chats': {
// Delete imported chats and restore previous state
await ImportExportService.deleteAllChats(db);
// Reimport previous chats
const transaction = db.transaction(['chats'], 'readwrite');
const store = transaction.objectStore('chats');
for (const chat of lastOperation.data.previous.chats) {
store.put(chat);
}
await new Promise((resolve, reject) => {
transaction.oncomplete = resolve;
transaction.onerror = reject;
});
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('Operation undone successfully', {
position: 'bottom-right',
autoClose: 3000,
});
if (onReloadChats) {
onReloadChats();
}
break;
}
case 'reset-settings': {
// Restore previous settings
await ImportExportService.importSettings(lastOperation.data.previous);
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('Operation undone successfully', {
position: 'bottom-right',
autoClose: 3000,
});
if (onReloadSettings) {
onReloadSettings();
}
break;
}
case 'reset-chats': {
// Restore previous chats
const chatTransaction = db.transaction(['chats'], 'readwrite');
const chatStore = chatTransaction.objectStore('chats');
for (const chat of lastOperation.data.previous.chats) {
chatStore.put(chat);
}
await new Promise((resolve, reject) => {
chatTransaction.oncomplete = resolve;
chatTransaction.onerror = reject;
});
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('Operation undone successfully', {
position: 'bottom-right',
autoClose: 3000,
});
if (onReloadChats) {
onReloadChats();
}
break;
}
case 'import-api-keys': {
// Restore previous API keys
const previousAPIKeys = lastOperation.data.previous;
const newKeys = ImportExportService.importAPIKeys(previousAPIKeys);
const apiKeysJson = JSON.stringify(newKeys);
document.cookie = `apiKeys=${apiKeysJson}; path=/; max-age=31536000`;
// Dismiss progress toast before showing success toast
toast.dismiss('progress-toast');
toast.success('Operation undone successfully', {
position: 'bottom-right',
autoClose: 3000,
});
if (onReloadSettings) {
onReloadSettings();
}
break;
}
default:
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error('Cannot undo this operation', {
position: 'bottom-right',
autoClose: 3000,
});
}
// Clear the last operation after undoing
setLastOperation(null);
} catch (error) {
console.error('Error undoing operation:', error);
// Dismiss progress toast before showing error toast
toast.dismiss('progress-toast');
toast.error(`Failed to undo: ${error instanceof Error ? error.message : 'Unknown error'}`, {
position: 'bottom-right',
autoClose: 3000,
});
}
}, [lastOperation, db, onReloadSettings, onReloadChats]);
return {
isExporting,
isImporting,
isResetting,
isDownloadingTemplate,
progressMessage,
progressPercent,
lastOperation,
handleExportSettings,
handleExportSelectedSettings,
handleExportAllChats,
handleExportSelectedChats,
handleImportSettings,
handleImportChats,
handleImportAPIKeys,
handleResetSettings,
handleResetChats,
handleDownloadTemplate,
handleExportAPIKeys,
handleUndo,
};
}
|