Line data Source code
1 : /**
2 : * V2 Storage I/O - localStorage read/write with error handling.
3 : *
4 : * Handles quota management, orphan cleanup, and graceful degradation.
5 : */
6 :
7 : import type {
8 : ActivePathPointer,
9 : DraftIndexV2,
10 : DraftPayloadV2,
11 : OpenPathsPointer
12 : } from './draftTypes'
13 : import { StorageKeys } from './storageKeys'
14 :
15 : type StorageAvailability = 'available' | 'unavailable'
16 : type WorkflowStorageState =
17 : | { status: 'ready'; availability: StorageAvailability }
18 : | {
19 : status: 'transitioning'
20 : reason: 'workspace'
21 : resumeAvailability: StorageAvailability
22 : ownerId: symbol
23 : }
24 : | {
25 : status: 'transitioning'
26 : reason: 'logout'
27 : resumeAvailability: StorageAvailability
28 : }
29 :
30 2356 : let workflowStorageState: WorkflowStorageState = {
31 : status: 'ready',
32 : availability: 'available'
33 : }
34 2356 : const pendingPersistenceFlushes = new Set<() => void>()
35 :
36 2355 : export function registerWorkflowPersistenceFlush(
37 : flush: () => void
38 : ): () => void {
39 2355 : pendingPersistenceFlushes.add(flush)
40 2355 : return () => pendingPersistenceFlushes.delete(flush)
41 : }
42 :
43 0 : function flushPendingWorkflowPersistence(): void {
44 0 : for (const flush of pendingPersistenceFlushes) {
45 0 : try {
46 0 : flush()
47 : } catch (error) {
48 0 : console.warn('Failed to flush pending workflow persistence', error)
49 : }
50 : }
51 : }
52 :
53 26902 : export function isStorageAvailable(): boolean {
54 26902 : return (
55 : workflowStorageState.status === 'ready' &&
56 : workflowStorageState.availability === 'available'
57 : )
58 : }
59 :
60 0 : export function markStorageUnavailable(): void {
61 0 : workflowStorageState =
62 : workflowStorageState.status === 'transitioning'
63 : ? { ...workflowStorageState, resumeAvailability: 'unavailable' }
64 : : { status: 'ready', availability: 'unavailable' }
65 : }
66 :
67 8307 : function isStorageReadable(): boolean {
68 8307 : return workflowStorageState.status === 'transitioning'
69 : ? workflowStorageState.resumeAvailability === 'available'
70 : : workflowStorageState.availability === 'available'
71 : }
72 :
73 : /** @internal Test-only: do not call from production code paths. */
74 : export function resetStorageAvailable(): void {
75 : workflowStorageState = { status: 'ready', availability: 'available' }
76 : }
77 :
78 0 : function isQuotaExceeded(error: unknown): boolean {
79 0 : return (
80 : error instanceof DOMException &&
81 : (error.name === 'QuotaExceededError' ||
82 : error.name === 'NS_ERROR_DOM_QUOTA_REACHED' ||
83 : error.code === 22 ||
84 : error.code === 1014)
85 : )
86 : }
87 :
88 98 : function isValidIndex(value: unknown): value is DraftIndexV2 {
89 98 : if (typeof value !== 'object' || value === null) return false
90 98 : const obj = value as Record<string, unknown>
91 98 : return (
92 : obj.v === 2 &&
93 : typeof obj.updatedAt === 'number' &&
94 : Array.isArray(obj.order) &&
95 : typeof obj.entries === 'object' &&
96 : obj.entries !== null
97 : )
98 : }
99 :
100 : /**
101 : * Reads and parses the draft index from localStorage.
102 : */
103 2354 : export function readIndex(workspaceId: string): DraftIndexV2 | null {
104 2354 : if (!isStorageReadable()) return null
105 :
106 2354 : try {
107 2354 : const key = StorageKeys.draftIndex(workspaceId)
108 2354 : const json = localStorage.getItem(key)
109 2354 : if (!json) return null
110 :
111 98 : const parsed = JSON.parse(json)
112 98 : if (!isValidIndex(parsed)) return null
113 :
114 98 : return parsed
115 : } catch {
116 0 : return null
117 : }
118 : }
119 :
120 : /**
121 : * Writes the draft index to localStorage.
122 : */
123 5869 : export function writeIndex(workspaceId: string, index: DraftIndexV2): boolean {
124 5869 : if (!isStorageAvailable()) return false
125 :
126 5869 : try {
127 5869 : const key = StorageKeys.draftIndex(workspaceId)
128 5869 : localStorage.setItem(key, JSON.stringify(index))
129 5869 : return true
130 : } catch (error) {
131 0 : if (isQuotaExceeded(error)) return false
132 0 : throw error
133 : }
134 : }
135 :
136 : /**
137 : * Reads a draft payload from localStorage.
138 : */
139 5757 : export function readPayload(
140 : workspaceId: string,
141 : draftKey: string
142 : ): DraftPayloadV2 | null {
143 5757 : if (!isStorageReadable()) return null
144 :
145 5757 : try {
146 5757 : const key = `${StorageKeys.prefixes.draftPayload}${workspaceId}:${draftKey}`
147 5757 : const json = localStorage.getItem(key)
148 5757 : if (!json) return null
149 :
150 1913 : return JSON.parse(json) as DraftPayloadV2
151 : } catch {
152 0 : return null
153 : }
154 : }
155 :
156 : /**
157 : * Writes a draft payload to localStorage.
158 : */
159 5525 : export function writePayload(
160 : workspaceId: string,
161 : draftKey: string,
162 : payload: DraftPayloadV2
163 : ): boolean {
164 5525 : if (!isStorageAvailable()) return false
165 :
166 5525 : try {
167 5525 : const key = `${StorageKeys.prefixes.draftPayload}${workspaceId}:${draftKey}`
168 5525 : localStorage.setItem(key, JSON.stringify(payload))
169 5525 : return true
170 : } catch (error) {
171 0 : if (isQuotaExceeded(error)) return false
172 0 : throw error
173 : }
174 : }
175 :
176 : /**
177 : * Deletes a draft payload from localStorage.
178 : */
179 262 : export function deletePayload(workspaceId: string, draftKey: string): void {
180 262 : try {
181 262 : const key = `${StorageKeys.prefixes.draftPayload}${workspaceId}:${draftKey}`
182 262 : localStorage.removeItem(key)
183 : } catch {
184 : // Ignore errors during deletion
185 : }
186 : }
187 :
188 : /**
189 : * Deletes multiple draft payloads from localStorage.
190 : */
191 5524 : export function deletePayloads(workspaceId: string, draftKeys: string[]): void {
192 5524 : for (const draftKey of draftKeys) {
193 0 : deletePayload(workspaceId, draftKey)
194 : }
195 : }
196 :
197 : /**
198 : * Gets all draft payload keys for a workspace from localStorage.
199 : */
200 196 : export function getPayloadKeys(workspaceId: string): string[] {
201 196 : if (!isStorageReadable()) return []
202 :
203 196 : const prefix = `${StorageKeys.prefixes.draftPayload}${workspaceId}:`
204 196 : const keys: string[] = []
205 :
206 196 : try {
207 196 : for (let i = 0; i < localStorage.length; i++) {
208 2918 : const key = localStorage.key(i)
209 2918 : if (key?.startsWith(prefix)) {
210 320 : keys.push(key.slice(prefix.length))
211 : }
212 : }
213 : } catch {
214 0 : return []
215 : }
216 :
217 196 : return keys
218 : }
219 :
220 : /**
221 : * Deletes orphan payloads that are not in the index.
222 : */
223 98 : export function deleteOrphanPayloads(
224 : workspaceId: string,
225 : indexKeys: Set<string>
226 : ): number {
227 98 : const payloadKeys = getPayloadKeys(workspaceId)
228 98 : let deleted = 0
229 :
230 98 : for (const key of payloadKeys) {
231 160 : if (!indexKeys.has(key)) {
232 0 : deletePayload(workspaceId, key)
233 0 : deleted++
234 : }
235 : }
236 :
237 98 : return deleted
238 : }
239 :
240 128 : function findAndMigratePointer<T extends { workspaceId: string }>(
241 : newKey: string,
242 : prefix: string,
243 : targetWorkspaceId: string,
244 : isValid: (value: unknown) => value is T,
245 : previousKey: string | null
246 : ): T | null {
247 128 : const candidateKeys = previousKey ? [previousKey] : []
248 128 : for (let i = 0; i < sessionStorage.length; i++) {
249 176 : const storageKey = sessionStorage.key(i)
250 176 : if (storageKey?.startsWith(prefix) && storageKey !== previousKey) {
251 0 : candidateKeys.push(storageKey)
252 : }
253 : }
254 :
255 128 : for (const storageKey of candidateKeys) {
256 128 : if (storageKey === newKey) continue
257 0 : const pointer = readSessionValue(storageKey, isValid)
258 128 : if (pointer?.workspaceId !== targetWorkspaceId) continue
259 0 : sessionStorage.setItem(newKey, JSON.stringify(pointer))
260 0 : sessionStorage.removeItem(storageKey)
261 0 : return pointer
262 : }
263 128 : return null
264 : }
265 :
266 236 : function readSessionPointer<T extends { workspaceId: string }>(
267 : key: string,
268 : prefix: string,
269 : targetWorkspaceId: string | undefined,
270 : isValid: (value: unknown) => value is T,
271 : previousKey: string | null
272 : ): T | null {
273 236 : try {
274 236 : const json = sessionStorage.getItem(key)
275 236 : if (json) {
276 108 : const pointer: unknown = JSON.parse(json)
277 108 : if (!isValid(pointer)) {
278 0 : sessionStorage.removeItem(key)
279 108 : } else if (
280 : targetWorkspaceId &&
281 : pointer.workspaceId !== targetWorkspaceId
282 : ) {
283 0 : sessionStorage.removeItem(key)
284 : } else {
285 108 : return pointer
286 : }
287 : }
288 :
289 128 : if (targetWorkspaceId) {
290 128 : return findAndMigratePointer(
291 : key,
292 : prefix,
293 : targetWorkspaceId,
294 : isValid,
295 : previousKey
296 : )
297 : }
298 :
299 0 : return null
300 : } catch {
301 0 : return null
302 : }
303 : }
304 :
305 4992 : function writeSessionPointer<T extends { workspaceId: string }>(
306 : key: string,
307 : prefix: string,
308 : pointer: T,
309 : isValid: (value: unknown) => value is T
310 : ): void {
311 4992 : if (!isStorageAvailable()) return
312 :
313 4992 : let saved = true
314 4992 : try {
315 4992 : sessionStorage.setItem(key, JSON.stringify(pointer))
316 : } catch {
317 0 : saved = false
318 : }
319 4992 : removeSessionPointers(
320 : prefix,
321 : pointer.workspaceId,
322 : isValid,
323 : saved ? key : null
324 : )
325 : }
326 :
327 4992 : function removeSessionPointers(
328 : prefix: string,
329 : workspaceId: string,
330 : isValid: (value: unknown) => value is { workspaceId: string },
331 : keepKey: string | null
332 : ): void {
333 4992 : try {
334 4992 : const staleKeys: string[] = []
335 4992 : for (let i = 0; i < sessionStorage.length; i++) {
336 13730 : const storageKey = sessionStorage.key(i)
337 13730 : if (!storageKey?.startsWith(prefix) || storageKey === keepKey) continue
338 13730 : if (readSessionValue(storageKey, isValid)?.workspaceId === workspaceId) {
339 0 : staleKeys.push(storageKey)
340 : }
341 : }
342 4992 : for (const storageKey of staleKeys) sessionStorage.removeItem(storageKey)
343 : } catch {
344 0 : return
345 : }
346 : }
347 :
348 0 : function readSessionValue<T>(
349 : key: string,
350 : isValid: (value: unknown) => value is T
351 : ): T | null {
352 0 : const json = sessionStorage.getItem(key)
353 0 : if (!json) return null
354 0 : try {
355 0 : const value: unknown = JSON.parse(json)
356 0 : return isValid(value) ? value : null
357 : } catch {
358 0 : return null
359 : }
360 : }
361 :
362 : /**
363 : * Reads the active path pointer from sessionStorage.
364 : * Falls back to workspace-based search when clientId changes after reload,
365 : * then to localStorage when sessionStorage is empty (browser restart).
366 : */
367 2299 : export function readActivePath(
368 : clientId: string | null,
369 : targetWorkspaceId?: string,
370 : previousClientId: string | null = null
371 : ): ActivePathPointer | null {
372 2299 : return (
373 : (clientId
374 : ? readSessionPointer<ActivePathPointer>(
375 : StorageKeys.activePath(clientId),
376 : StorageKeys.prefixes.activePath,
377 : targetWorkspaceId,
378 : isValidActivePathPointer,
379 : previousClientId ? StorageKeys.activePath(previousClientId) : null
380 : )
381 : : null) ??
382 : (targetWorkspaceId
383 : ? readLocalPointer<ActivePathPointer>(
384 : StorageKeys.lastActivePath(targetWorkspaceId),
385 : isValidActivePathPointer
386 : )
387 : : null)
388 : )
389 : }
390 :
391 : /**
392 : * Writes the active path pointer to both sessionStorage (tab-scoped)
393 : * and localStorage (survives browser restart).
394 : */
395 1718 : export function writeActivePath(
396 : clientId: string,
397 : pointer: ActivePathPointer
398 : ): void {
399 1718 : const json = JSON.stringify(pointer)
400 1718 : writeSessionPointer(
401 : StorageKeys.activePath(clientId),
402 : StorageKeys.prefixes.activePath,
403 : pointer,
404 : isValidActivePathPointer
405 : )
406 1718 : writeStorage(
407 : localStorage,
408 : StorageKeys.lastActivePath(pointer.workspaceId),
409 : json
410 : )
411 : }
412 :
413 : /** Inverse of {@link writeActivePath}: drops both pointers it writes. */
414 0 : export function clearActivePath(clientId: string, workspaceId: string): void {
415 0 : try {
416 0 : sessionStorage.removeItem(StorageKeys.activePath(clientId))
417 0 : localStorage.removeItem(StorageKeys.lastActivePath(workspaceId))
418 : } catch {
419 0 : return
420 : }
421 0 : removeSessionPointers(
422 : StorageKeys.prefixes.activePath,
423 : workspaceId,
424 : isValidActivePathPointer,
425 : null
426 : )
427 : }
428 :
429 : /**
430 : * Reads the open paths pointer from sessionStorage.
431 : * Falls back to workspace-based search when clientId changes after reload,
432 : * then to localStorage when sessionStorage is empty (browser restart).
433 : */
434 4708 : export function readOpenPaths(
435 : clientId: string | null,
436 : targetWorkspaceId?: string,
437 : previousClientId: string | null = null
438 : ): OpenPathsPointer | null {
439 4708 : return (
440 : (clientId
441 : ? readSessionPointer<OpenPathsPointer>(
442 : StorageKeys.openPaths(clientId),
443 : StorageKeys.prefixes.openPaths,
444 : targetWorkspaceId,
445 : isValidOpenPathsPointer,
446 : previousClientId ? StorageKeys.openPaths(previousClientId) : null
447 : )
448 : : null) ??
449 : (targetWorkspaceId
450 : ? readLocalPointer<OpenPathsPointer>(
451 : StorageKeys.lastOpenPaths(targetWorkspaceId),
452 : isValidOpenPathsPointer
453 : )
454 : : null)
455 : )
456 : }
457 :
458 : /**
459 : * Writes the open paths pointer to both sessionStorage (tab-scoped)
460 : * and localStorage (survives browser restart).
461 : */
462 3274 : export function writeOpenPaths(
463 : clientId: string,
464 : pointer: OpenPathsPointer
465 : ): void {
466 3274 : const json = JSON.stringify(pointer)
467 3274 : writeSessionPointer(
468 : StorageKeys.openPaths(clientId),
469 : StorageKeys.prefixes.openPaths,
470 : pointer,
471 : isValidOpenPathsPointer
472 : )
473 3274 : writeStorage(
474 : localStorage,
475 : StorageKeys.lastOpenPaths(pointer.workspaceId),
476 : json
477 : )
478 : }
479 :
480 114 : function hasWorkspaceId(obj: Record<string, unknown>): boolean {
481 114 : return typeof obj.workspaceId === 'string'
482 : }
483 :
484 4 : function isValidActivePathPointer(value: unknown): value is ActivePathPointer {
485 4 : if (typeof value !== 'object' || value === null) return false
486 4 : const obj = value as Record<string, unknown>
487 4 : return hasWorkspaceId(obj) && typeof obj.path === 'string'
488 : }
489 :
490 110 : function isValidOpenPathsPointer(value: unknown): value is OpenPathsPointer {
491 110 : if (typeof value !== 'object' || value === null) return false
492 110 : const obj = value as Record<string, unknown>
493 110 : return (
494 : hasWorkspaceId(obj) &&
495 : Array.isArray(obj.paths) &&
496 : typeof obj.activeIndex === 'number'
497 : )
498 : }
499 :
500 6899 : function readLocalPointer<T>(
501 : key: string,
502 : validate: (value: unknown) => value is T
503 : ): T | null {
504 6899 : try {
505 6899 : const json = localStorage.getItem(key)
506 6899 : if (!json) return null
507 6 : const parsed = JSON.parse(json)
508 6899 : return validate(parsed) ? parsed : null
509 : } catch {
510 0 : return null
511 : }
512 : }
513 :
514 4992 : function writeStorage(storage: Storage, key: string, value: string): void {
515 4992 : if (!isStorageAvailable()) return
516 :
517 4992 : try {
518 4992 : storage.setItem(key, value)
519 : } catch {
520 : // Best effort — silently degrade when storage is full or unavailable
521 : }
522 : }
523 :
524 2356 : const legacyLocalRestoreKeys = [
525 : 'Comfy.Workflow.Drafts',
526 : 'Comfy.Workflow.DraftOrder',
527 : 'Comfy.OpenWorkflowsPaths',
528 : 'Comfy.ActiveWorkflowIndex',
529 : 'Comfy.PreviousWorkflow',
530 : 'workflow'
531 : ]
532 :
533 2356 : const legacyAgentKeys = [
534 : 'Comfy.Agent.ThreadId',
535 : 'Comfy.Agent.WorkflowTabBindings',
536 : 'Comfy.Agent.WorkflowTabBindings.v2',
537 : 'Comfy.Agent.ChatTitles',
538 : 'Comfy.Agent.DeletedThreads'
539 : ]
540 :
541 2356 : const sessionRestorePrefixes = [
542 : StorageKeys.prefixes.activePath,
543 : StorageKeys.prefixes.openPaths,
544 : 'Comfy.PreviousWorkflow:',
545 : 'Comfy.OpenWorkflowsPaths:',
546 : 'Comfy.ActiveWorkflowIndex:',
547 : 'workflow:'
548 : ]
549 :
550 2356 : const sessionRestoreKeys = [
551 : 'Comfy.PreviousWorkflow',
552 : 'Comfy.OpenWorkflowsPaths',
553 : 'Comfy.ActiveWorkflowIndex'
554 : ]
555 :
556 3 : function removeStorageKeys(
557 : storage: Storage,
558 : keys: string[],
559 : prefixes: string[] = []
560 : ): void {
561 3 : try {
562 3 : for (let i = storage.length - 1; i >= 0; i--) {
563 65 : const key = storage.key(i)
564 65 : if (
565 : key &&
566 : (keys.includes(key) ||
567 : prefixes.some((prefix) => key.startsWith(prefix)))
568 : ) {
569 0 : try {
570 0 : storage.removeItem(key)
571 : } catch {
572 0 : continue
573 : }
574 : }
575 : }
576 : } catch {
577 0 : return
578 : }
579 : }
580 :
581 3 : export function clearLegacyAgentStorage(): void {
582 3 : removeStorageKeys(localStorage, legacyAgentKeys)
583 : }
584 :
585 0 : export function clearWorkflowRestoreState(): void {
586 0 : removeStorageKeys(localStorage, legacyLocalRestoreKeys)
587 0 : removeStorageKeys(sessionStorage, sessionRestoreKeys, sessionRestorePrefixes)
588 : }
589 :
590 0 : export function prepareWorkflowWorkspaceTransition(): () => void {
591 0 : let ownerId: symbol | undefined
592 0 : if (workflowStorageState.status === 'ready') {
593 0 : flushPendingWorkflowPersistence()
594 0 : ownerId = Symbol('workflow-storage-transition')
595 0 : workflowStorageState = {
596 : status: 'transitioning',
597 : reason: 'workspace',
598 : resumeAvailability: workflowStorageState.availability,
599 : ownerId
600 : }
601 : }
602 0 : clearWorkflowRestoreState()
603 :
604 0 : return () => {
605 0 : if (
606 : workflowStorageState.status !== 'transitioning' ||
607 : workflowStorageState.reason !== 'workspace' ||
608 : workflowStorageState.ownerId !== ownerId
609 : )
610 0 : return
611 :
612 0 : workflowStorageState = {
613 : status: 'ready',
614 : availability: workflowStorageState.resumeAvailability
615 : }
616 : }
617 : }
618 :
619 0 : export function prepareWorkflowLogoutTransition(): void {
620 0 : workflowStorageState = {
621 : status: 'transitioning',
622 : reason: 'logout',
623 : resumeAvailability:
624 : workflowStorageState.status === 'transitioning'
625 : ? workflowStorageState.resumeAvailability
626 : : workflowStorageState.availability
627 : }
628 : }
629 :
630 0 : export function completeWorkflowLogoutTransition(): void {
631 0 : if (
632 : workflowStorageState.status !== 'transitioning' ||
633 : workflowStorageState.reason !== 'logout'
634 : )
635 0 : return
636 :
637 0 : workflowStorageState = {
638 : status: 'ready',
639 : availability: workflowStorageState.resumeAvailability
640 : }
641 : }
642 :
643 0 : export function clearAllWorkflowStorage(): void {
644 0 : const localPrefixes = [
645 : StorageKeys.prefixes.draftIndex,
646 : StorageKeys.prefixes.draftPayload,
647 : StorageKeys.prefixes.lastActivePath,
648 : StorageKeys.prefixes.lastOpenPaths,
649 : 'Comfy.Workflow.Drafts:',
650 : 'Comfy.Workflow.DraftOrder:'
651 : ]
652 :
653 0 : removeStorageKeys(localStorage, legacyLocalRestoreKeys, localPrefixes)
654 0 : removeStorageKeys(sessionStorage, sessionRestoreKeys, sessionRestorePrefixes)
655 : }
656 :
657 0 : export function clearAllWorkspaceStorage(): void {
658 0 : clearAllWorkflowStorage()
659 0 : clearLegacyAgentStorage()
660 0 : removeStorageKeys(
661 : localStorage,
662 : [],
663 : [
664 : StorageKeys.prefixes.agentThread,
665 : StorageKeys.prefixes.agentWorkflowTabBindings,
666 : StorageKeys.prefixes.agentChatTitles,
667 : StorageKeys.prefixes.agentDeletedThreads,
668 : StorageKeys.prefixes.agentComposerDraft
669 : ]
670 : )
671 : }
|