@@ -46,8 +46,50 @@ export const combinedGenerations = derived(
46
46
)
47
47
48
48
combinedGenerations . subscribe ( ( value ) => {
49
+ const setItemDeletingOldIfNeeded = ( value : GenerationWithSource [ ] , attempts = 0 ) => {
50
+ // Safeguard: Prevent infinite recursion
51
+ if ( attempts > 1000 ) {
52
+ console . error ( 'Too many attempts to store generations, giving up' )
53
+ localStorage . removeItem ( PERSIST_KEY_GENERATIONS )
54
+ return
55
+ }
56
+
57
+ // Safeguard: If we have no generations left, just clear the storage
58
+ if ( value . length === 0 ) {
59
+ console . warn ( 'No generations left to store, clearing localStorage' )
60
+ localStorage . removeItem ( PERSIST_KEY_GENERATIONS )
61
+ return
62
+ }
63
+
64
+ try {
65
+ localStorage . setItem ( PERSIST_KEY_GENERATIONS , JSON . stringify ( value ) )
66
+
67
+ // Log successful storage if we had to reduce items
68
+ if ( attempts > 0 ) {
69
+ console . log (
70
+ `Successfully stored ${ value . length } generations after ${ attempts + 1 } attempts`
71
+ )
72
+ }
73
+ } catch ( e ) {
74
+ if ( e instanceof DOMException && e . name === 'QuotaExceededError' ) {
75
+ // Log the reduction attempt
76
+ if ( attempts === 0 ) {
77
+ console . warn ( `localStorage quota exceeded with ${ value . length } generations, reducing...` )
78
+ }
79
+
80
+ // If we hit the quota, delete the oldest generation and try again
81
+ const smallerGenerations = value . slice ( 0 , - 1 )
82
+ setItemDeletingOldIfNeeded ( smallerGenerations , attempts + 1 )
83
+ } else {
84
+ // Handle other storage errors
85
+ console . error ( 'Non-quota localStorage error:' , e )
86
+ localStorage . removeItem ( PERSIST_KEY_GENERATIONS )
87
+ }
88
+ }
89
+ }
90
+
49
91
if ( browser ) {
50
- localStorage . setItem ( PERSIST_KEY_GENERATIONS , JSON . stringify ( value ) )
92
+ setItemDeletingOldIfNeeded ( value )
51
93
}
52
94
} )
53
95
0 commit comments