forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseMemories.ts
More file actions
549 lines (496 loc) · 16.9 KB
/
Copy pathuseMemories.ts
File metadata and controls
549 lines (496 loc) · 16.9 KB
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
'use client';
import { useState, useEffect, useCallback, useRef } from 'react';
import type { Memory, MemoryCategory, MemoryVisibility } from '@/types/conversation';
import {
getMemories,
createMemory,
updateMemoryContent,
updateMemoryVisibility,
deleteMemory,
deleteMemoriesBatch,
reviewMemory,
} from '@/lib/api';
import {
getCache,
setCache,
updateCache,
onCacheInvalidation,
invalidationPatterns,
CACHE_TTL,
cacheKeys,
} from '@/lib/cache';
import { getCachedMemories, cacheMemories } from '@/lib/indexeddb';
export interface UseMemoriesOptions {
categories?: MemoryCategory[];
limit?: number;
}
/** Outcome of a chunked bulk delete. */
export interface RemoveMemoriesResult {
/** Whether every chunk succeeded. */
success: boolean;
/** IDs confirmed deleted across successful chunks (empty unless chunks ran). */
deletedIds: string[];
}
export interface UseMemoriesReturn {
memories: Memory[];
loading: boolean;
error: string | null;
hasMore: boolean;
loadMore: () => Promise<void>;
refresh: () => Promise<void>;
addMemory: (content: string, visibility?: MemoryVisibility) => Promise<Memory | null>;
editMemory: (id: string, content: string) => Promise<boolean>;
removeMemory: (id: string) => Promise<boolean>;
removeMemories: (ids: string[]) => Promise<RemoveMemoriesResult>;
toggleVisibility: (id: string, visibility: MemoryVisibility) => Promise<boolean>;
acceptMemory: (id: string) => Promise<boolean>;
rejectMemory: (id: string) => Promise<boolean>;
setCategories: (categories: MemoryCategory[]) => void;
activeCategories: MemoryCategory[];
}
// Cache entry structure
interface CacheEntry {
memories: Memory[];
offset: number;
hasMore: boolean;
}
function getCacheKey(categories: MemoryCategory[]): string {
return cacheKeys.memories(categories.length === 0 ? [] : [...categories].sort());
}
function getFromCache(key: string): CacheEntry | null {
const cached = getCache<CacheEntry>(key);
return cached ? cached.data : null;
}
function setToCache(
key: string,
memories: Memory[],
offset: number,
hasMore: boolean,
): void {
setCache<CacheEntry>(key, { memories, offset, hasMore }, CACHE_TTL.MEDIUM);
}
function updateCacheMemories(
key: string,
updater: (memories: Memory[]) => Memory[],
): void {
updateCache<CacheEntry>(key, (entry) => ({
...entry,
memories: updater(entry.memories),
}));
}
function isCacheStale(key: string): boolean {
const cached = getCache<CacheEntry>(key);
return cached ? cached.isStale : true;
}
export function useMemories(options: UseMemoriesOptions = {}): UseMemoriesReturn {
const { limit = 25 } = options;
const [activeCategories, setActiveCategories] = useState<MemoryCategory[]>(
options.categories || [],
);
// Get cache key for current categories
const cacheKey = getCacheKey(activeCategories);
const cachedEntry = getFromCache(cacheKey);
// Initialize state from cache if available
const [memories, setMemories] = useState<Memory[]>(cachedEntry?.memories || []);
const [loading, setLoading] = useState(!cachedEntry); // Only show loading if no cache
const [error, setError] = useState<string | null>(null);
const [hasMore, setHasMore] = useState(cachedEntry?.hasMore ?? true);
// Use ref for offset to avoid dependency issues
const offsetRef = useRef(cachedEntry?.offset || 0);
// Track if a fetch is in progress to prevent concurrent fetches
const fetchingRef = useRef(false);
// Track if initial fetch is done
const initializedRef = useRef(false);
// Core fetch function
const doFetch = useCallback(
async (categories: MemoryCategory[], currentOffset: number): Promise<Memory[]> => {
const result = await getMemories({
limit,
offset: currentOffset,
categories: categories.length > 0 ? categories : undefined,
});
return result;
},
[limit],
);
// Initial load - check cache first (memory → IndexedDB → network)
useEffect(() => {
if (initializedRef.current) return;
initializedRef.current = true;
const key = getCacheKey(activeCategories);
const cached = getFromCache(key);
// If we have fresh in-memory cache, use it and skip fetch
if (cached && !isCacheStale(key)) {
setMemories(cached.memories);
setHasMore(cached.hasMore);
offsetRef.current = cached.offset;
setLoading(false);
return;
}
// If we have stale in-memory cache, show it but refresh in background
if (cached) {
setMemories(cached.memories);
setHasMore(cached.hasMore);
offsetRef.current = cached.offset;
setLoading(false);
// Don't return - continue to background refresh
}
const loadInitial = async () => {
if (fetchingRef.current) return;
fetchingRef.current = true;
// Try IndexedDB first if no in-memory cache
if (!cached) {
const indexedDBMemories = await getCachedMemories();
if (indexedDBMemories && indexedDBMemories.length > 0) {
console.log('[useMemories] Loaded from IndexedDB');
setMemories(indexedDBMemories);
offsetRef.current = indexedDBMemories.length;
setHasMore(indexedDBMemories.length >= limit);
// Also update in-memory cache
setToCache(
key,
indexedDBMemories,
indexedDBMemories.length,
indexedDBMemories.length >= limit,
);
setLoading(false);
// Continue to background refresh to get latest data
} else {
// No cache at all, show loading
setLoading(true);
}
} else {
// Already showing stale in-memory cache, don't show loading
setLoading(false);
}
setError(null);
try {
const result = await doFetch(activeCategories, 0);
setMemories(result);
offsetRef.current = result.length;
setHasMore(result.length >= limit);
// Update both caches
setToCache(key, result, result.length, result.length >= limit);
await cacheMemories(result);
} catch (err) {
// Check if we have any cached data to show
let hasAnyCachedData = !!cached;
if (!hasAnyCachedData) {
try {
const indexedDbMemories = await getCachedMemories();
hasAnyCachedData = !!indexedDbMemories;
} catch {
// If reading from IndexedDB fails, don't mask the original error
}
}
const baseMessage =
err instanceof Error ? err.message : 'Failed to load memories';
if (hasAnyCachedData) {
// Show that refresh failed but cached data is available
setError(`${baseMessage} (showing cached data)`);
} else {
setError(baseMessage);
}
} finally {
setLoading(false);
fetchingRef.current = false;
}
};
loadInitial();
}, [doFetch, activeCategories, limit]);
// Handle category changes (after initial load)
const prevCategoriesRef = useRef<string>(JSON.stringify(activeCategories));
useEffect(() => {
const currentKey = JSON.stringify(activeCategories);
if (prevCategoriesRef.current === currentKey) return;
prevCategoriesRef.current = currentKey;
// Only refetch if already initialized
if (!initializedRef.current) return;
const key = getCacheKey(activeCategories);
const cached = getFromCache(key);
// If we have cache for this category, use it immediately
if (cached) {
setMemories(cached.memories);
setHasMore(cached.hasMore);
offsetRef.current = cached.offset;
// If not stale, we're done
if (!isCacheStale(key)) {
return;
}
// If stale, continue to background refresh
}
const loadForCategories = async () => {
if (fetchingRef.current) return;
fetchingRef.current = true;
// Only show loading if no cache
if (!cached) {
setLoading(true);
}
setError(null);
try {
const result = await doFetch(activeCategories, 0);
setMemories(result);
offsetRef.current = result.length;
setHasMore(result.length >= limit);
// Update cache
setToCache(key, result, result.length, result.length >= limit);
} catch (err) {
if (!cached) {
setError(err instanceof Error ? err.message : 'Failed to load memories');
}
} finally {
setLoading(false);
fetchingRef.current = false;
}
};
loadForCategories();
}, [activeCategories, doFetch, limit]);
// Subscribe to cache invalidation - refetch when memories are modified elsewhere
useEffect(() => {
const unsubscribe = onCacheInvalidation((pattern) => {
if (pattern === invalidationPatterns.memories) {
// Clear local state and refetch
const key = getCacheKey(activeCategories);
const loadFresh = async () => {
if (fetchingRef.current) return;
fetchingRef.current = true;
try {
const result = await doFetch(activeCategories, 0);
setMemories(result);
offsetRef.current = result.length;
setHasMore(result.length >= limit);
setToCache(key, result, result.length, result.length >= limit);
} catch (err) {
// Silent fail on background refresh
console.error('Failed to refresh memories after invalidation:', err);
} finally {
fetchingRef.current = false;
}
};
loadFresh();
}
});
return unsubscribe;
}, [activeCategories, doFetch, limit]);
// Load more (pagination)
const loadMore = useCallback(async () => {
if (fetchingRef.current || !hasMore) return;
fetchingRef.current = true;
setLoading(true);
const key = getCacheKey(activeCategories);
try {
const result = await doFetch(activeCategories, offsetRef.current);
setMemories((prev) => {
// Deduplicate
const existingIds = new Set(prev.map((m) => m.id));
const newMemories = result.filter((m) => !existingIds.has(m.id));
const updated = [...prev, ...newMemories];
// Update cache with new memories
const newOffset = offsetRef.current + result.length;
const newHasMore = result.length >= limit;
setToCache(key, updated, newOffset, newHasMore);
return updated;
});
offsetRef.current += result.length;
setHasMore(result.length >= limit);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load more memories');
} finally {
setLoading(false);
fetchingRef.current = false;
}
}, [activeCategories, doFetch, hasMore, limit]);
// Refresh
const refresh = useCallback(async () => {
if (fetchingRef.current) return;
fetchingRef.current = true;
setLoading(true);
setError(null);
const key = getCacheKey(activeCategories);
try {
const result = await doFetch(activeCategories, 0);
setMemories(result);
offsetRef.current = result.length;
setHasMore(result.length >= limit);
// Update cache
setToCache(key, result, result.length, result.length >= limit);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to refresh memories');
} finally {
setLoading(false);
fetchingRef.current = false;
}
}, [activeCategories, doFetch, limit]);
// Add memory
const addMemory = useCallback(
async (
content: string,
visibility: MemoryVisibility = 'public',
): Promise<Memory | null> => {
const key = getCacheKey(activeCategories);
try {
const newMemory = await createMemory({ content, visibility, category: 'manual' });
setMemories((prev) => {
const updated = [newMemory, ...prev];
// Update cache
updateCacheMemories(key, () => updated);
return updated;
});
return newMemory;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create memory');
return null;
}
},
[activeCategories],
);
// Edit memory
const editMemory = useCallback(
async (id: string, content: string): Promise<boolean> => {
const key = getCacheKey(activeCategories);
try {
await updateMemoryContent(id, content);
const updater = (prev: Memory[]) =>
prev.map((m) =>
m.id === id
? { ...m, content, edited: true, updated_at: new Date().toISOString() }
: m,
);
setMemories(updater);
updateCacheMemories(key, updater);
return true;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update memory');
return false;
}
},
[activeCategories],
);
// Remove memory
const removeMemory = useCallback(
async (id: string): Promise<boolean> => {
const key = getCacheKey(activeCategories);
try {
await deleteMemory(id);
const updater = (prev: Memory[]) => prev.filter((m) => m.id !== id);
setMemories(updater);
updateCacheMemories(key, updater);
return true;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete memory');
return false;
}
},
[activeCategories],
);
// Remove multiple memories via the batch API. IDs are sent in chunks of 100 (the
// server's per-request cap) and each successful chunk is applied to the UI
// immediately, so a later chunk failure can never leave already-deleted items
// visible. Returns success only when every chunk succeeded; on partial failure the
// confirmed-deleted IDs are surfaced via deletedIds so callers can drop them from
// any selection they keep for retry (otherwise a retry would re-send IDs the server
// already removed and trip the all-or-nothing 404).
const removeMemories = useCallback(
async (ids: string[]): Promise<RemoveMemoriesResult> => {
if (ids.length === 0) return { success: true, deletedIds: [] };
const key = getCacheKey(activeCategories);
const CHUNK_SIZE = 100;
const deletedIds: string[] = [];
try {
for (let i = 0; i < ids.length; i += CHUNK_SIZE) {
const chunk = ids.slice(i, i + CHUNK_SIZE);
await deleteMemoriesBatch(chunk);
deletedIds.push(...chunk);
const removed = new Set(chunk);
const updater = (prev: Memory[]) => prev.filter((m) => !removed.has(m.id));
setMemories(updater);
updateCacheMemories(key, updater);
}
return { success: true, deletedIds };
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete memories');
return { success: false, deletedIds };
}
},
[activeCategories],
);
// Toggle visibility
const toggleVisibility = useCallback(
async (id: string, visibility: MemoryVisibility): Promise<boolean> => {
const key = getCacheKey(activeCategories);
try {
await updateMemoryVisibility(id, visibility);
const updater = (prev: Memory[]) =>
prev.map((m) =>
m.id === id ? { ...m, visibility, updated_at: new Date().toISOString() } : m,
);
setMemories(updater);
updateCacheMemories(key, updater);
return true;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update visibility');
return false;
}
},
[activeCategories],
);
// Accept memory
const acceptMemory = useCallback(
async (id: string): Promise<boolean> => {
const key = getCacheKey(activeCategories);
try {
await reviewMemory(id, true);
const updater = (prev: Memory[]) =>
prev.map((m) =>
m.id === id ? { ...m, reviewed: true, user_review: true } : m,
);
setMemories(updater);
updateCacheMemories(key, updater);
return true;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to accept memory');
return false;
}
},
[activeCategories],
);
// Reject memory
const rejectMemory = useCallback(
async (id: string): Promise<boolean> => {
const key = getCacheKey(activeCategories);
try {
await reviewMemory(id, false);
const updater = (prev: Memory[]) => prev.filter((m) => m.id !== id);
setMemories(updater);
updateCacheMemories(key, updater);
return true;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to reject memory');
return false;
}
},
[activeCategories],
);
// Set categories
const setCategories = useCallback((categories: MemoryCategory[]) => {
setActiveCategories(categories);
offsetRef.current = 0;
}, []);
return {
memories,
loading,
error,
hasMore,
loadMore,
refresh,
addMemory,
editMemory,
removeMemory,
removeMemories,
toggleVisibility,
acceptMemory,
rejectMemory,
setCategories,
activeCategories,
};
}