diff --git a/packages/app/src/utils/persist-local-storage.ts b/packages/app/src/utils/persist-local-storage.ts new file mode 100644 index 000000000..30c1cf342 --- /dev/null +++ b/packages/app/src/utils/persist-local-storage.ts @@ -0,0 +1,227 @@ +import type { SyncStorage } from "@solid-primitives/storage" + +const LOCAL_PREFIX = "pawwork." +const LEGACY_LOCAL_PREFIX = "opencode." +// The legacy prefix intentionally covers old workspace, global, and settings keys. +const EVICT_PREFIXES = [LOCAL_PREFIX, LEGACY_LOCAL_PREFIX] +const fallback = new Map() + +const CACHE_MAX_ENTRIES = 500 +const CACHE_MAX_BYTES = 8 * 1024 * 1024 + +type CacheEntry = { value: string; bytes: number } +const cache = new Map() +const cacheTotal = { bytes: 0 } + +function cacheDelete(key: string) { + const entry = cache.get(key) + if (!entry) return + cacheTotal.bytes -= entry.bytes + cache.delete(key) +} + +function cachePrune() { + for (;;) { + if (cache.size <= CACHE_MAX_ENTRIES && cacheTotal.bytes <= CACHE_MAX_BYTES) return + const oldest = cache.keys().next().value as string | undefined + if (!oldest) return + cacheDelete(oldest) + } +} + +function cacheSet(key: string, value: string) { + const bytes = value.length * 2 + if (bytes > CACHE_MAX_BYTES) { + cacheDelete(key) + return + } + + const entry = cache.get(key) + if (entry) cacheTotal.bytes -= entry.bytes + cache.delete(key) + cache.set(key, { value, bytes }) + cacheTotal.bytes += bytes + cachePrune() +} + +function cacheGet(key: string) { + const entry = cache.get(key) + if (!entry) return + cache.delete(key) + cache.set(key, entry) + return entry.value +} + +function fallbackDisabled(scope: string) { + return fallback.get(scope) === true +} + +function fallbackSet(scope: string) { + fallback.set(scope, true) +} + +function quota(error: unknown) { + if (error instanceof DOMException) { + if (error.name === "QuotaExceededError") return true + if (error.name === "NS_ERROR_DOM_QUOTA_REACHED") return true + if (error.name === "QUOTA_EXCEEDED_ERR") return true + if (error.code === 22 || error.code === 1014) return true + return false + } + + if (!error || typeof error !== "object") return false + const name = (error as { name?: string }).name + if (name === "QuotaExceededError" || name === "NS_ERROR_DOM_QUOTA_REACHED") return true + if (name && /quota/i.test(name)) return true + + const code = (error as { code?: number }).code + if (code === 22 || code === 1014) return true + + const message = (error as { message?: string }).message + if (typeof message !== "string") return false + if (/quota/i.test(message)) return true + return false +} + +type Evict = { key: string; size: number } + +function evict(storage: Storage, keep: string, value: string) { + const total = storage.length + const items: Evict[] = [] + + for (let index = 0; index < total; index++) { + const name = storage.key(index) + if (!name) continue + if (!EVICT_PREFIXES.some((prefix) => name.startsWith(prefix))) continue + if (name === keep) continue + const stored = storage.getItem(name) + items.push({ key: name, size: stored?.length ?? 0 }) + } + + items.sort((a, b) => b.size - a.size) + + for (const item of items) { + storage.removeItem(item.key) + cacheDelete(item.key) + + try { + storage.setItem(keep, value) + cacheSet(keep, value) + return true + } catch (error) { + if (!quota(error)) throw error + } + } + + return false +} + +function write(storage: Storage, key: string, value: string) { + try { + storage.setItem(key, value) + cacheSet(key, value) + return true + } catch (error) { + if (!quota(error)) throw error + } + + try { + storage.removeItem(key) + cacheDelete(key) + storage.setItem(key, value) + cacheSet(key, value) + return true + } catch (error) { + if (!quota(error)) throw error + } + + const ok = evict(storage, key, value) + return ok +} + +export function localStorageWithPrefix(prefix: string): SyncStorage { + const base = `${prefix}:` + const scope = `prefix:${prefix}` + const item = (key: string) => base + key + return { + getItem: (key) => { + const name = item(key) + const cached = cacheGet(name) + if (fallbackDisabled(scope)) return cached ?? null + + const stored = (() => { + try { + return localStorage.getItem(name) + } catch { + fallbackSet(scope) + return null + } + })() + if (stored === null) return cached ?? null + cacheSet(name, stored) + return stored + }, + setItem: (key, value) => { + const name = item(key) + if (fallbackDisabled(scope)) return + try { + if (write(localStorage, name, value)) return + } catch { + fallbackSet(scope) + return + } + fallbackSet(scope) + }, + removeItem: (key) => { + const name = item(key) + cacheDelete(name) + if (fallbackDisabled(scope)) return + try { + localStorage.removeItem(name) + } catch { + fallbackSet(scope) + } + }, + } +} + +export function localStorageDirect(): SyncStorage { + const scope = "direct" + return { + getItem: (key) => { + const cached = cacheGet(key) + if (fallbackDisabled(scope)) return cached ?? null + + const stored = (() => { + try { + return localStorage.getItem(key) + } catch { + fallbackSet(scope) + return null + } + })() + if (stored === null) return cached ?? null + cacheSet(key, stored) + return stored + }, + setItem: (key, value) => { + if (fallbackDisabled(scope)) return + try { + if (write(localStorage, key, value)) return + } catch { + fallbackSet(scope) + return + } + fallbackSet(scope) + }, + removeItem: (key) => { + cacheDelete(key) + if (fallbackDisabled(scope)) return + try { + localStorage.removeItem(key) + } catch { + fallbackSet(scope) + } + }, + } +} diff --git a/packages/app/src/utils/persist-read.ts b/packages/app/src/utils/persist-read.ts new file mode 100644 index 000000000..a21e6d674 --- /dev/null +++ b/packages/app/src/utils/persist-read.ts @@ -0,0 +1,144 @@ +import type { AsyncStorage, SyncStorage } from "@solid-primitives/storage" + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value) +} + +function merge(defaults: unknown, value: unknown): unknown { + if (value === undefined) return defaults + if (value === null) return value + + if (Array.isArray(defaults)) { + if (Array.isArray(value)) return value + return defaults + } + + if (isRecord(defaults)) { + if (!isRecord(value)) return defaults + + const result: Record = { ...defaults } + for (const key of Object.keys(value)) { + if (key in defaults) { + result[key] = merge((defaults as Record)[key], (value as Record)[key]) + } else { + result[key] = (value as Record)[key] + } + } + return result + } + + return value +} + +function parse(value: string) { + try { + return JSON.parse(value) as unknown + } catch { + return undefined + } +} + +export function normalize(defaults: unknown, raw: string, migrate?: (value: unknown) => unknown) { + const parsed = parse(raw) + if (parsed === undefined) return + const migrated = migrate ? migrate(parsed) : parsed + if (migrate && migrated === undefined) return + const merged = merge(defaults, migrated) + return JSON.stringify(merged) +} + +export function readPersistedSync(input: { + current: SyncStorage + legacyStore: SyncStorage + key: string + defaults: unknown + legacy: string[] + currentLegacy: string[] + migrate?: (value: unknown) => unknown +}) { + const raw = input.current.getItem(input.key) + if (raw !== null) { + const next = normalize(input.defaults, raw, input.migrate) + if (next === undefined) { + input.current.removeItem(input.key) + return null + } + if (raw !== next) input.current.setItem(input.key, next) + return next + } + + for (const legacyKey of input.currentLegacy) { + const legacyRaw = input.current.getItem(legacyKey) + if (legacyRaw === null) continue + + const next = normalize(input.defaults, legacyRaw, input.migrate) + if (next === undefined) continue + input.current.setItem(input.key, next) + return next + } + + for (const legacyKey of input.legacy) { + const legacyRaw = input.legacyStore.getItem(legacyKey) + if (legacyRaw === null) continue + + const next = normalize(input.defaults, legacyRaw, input.migrate) + if (next === undefined) { + input.legacyStore.removeItem(legacyKey) + continue + } + input.current.setItem(input.key, next) + input.legacyStore.removeItem(legacyKey) + return next + } + + return null +} + +export async function readPersistedAsync(input: { + current: AsyncStorage + legacyStore?: AsyncStorage + key: string + defaults: unknown + legacy: string[] + currentLegacy: string[] + migrate?: (value: unknown) => unknown +}) { + const raw = await input.current.getItem(input.key) + if (raw !== null) { + const next = normalize(input.defaults, raw, input.migrate) + if (next === undefined) { + await input.current.removeItem(input.key).catch(() => undefined) + return null + } + if (raw !== next) await input.current.setItem(input.key, next) + return next + } + + for (const legacyKey of input.currentLegacy) { + const legacyRaw = await input.current.getItem(legacyKey) + if (legacyRaw === null) continue + + const next = normalize(input.defaults, legacyRaw, input.migrate) + if (next === undefined) continue + await input.current.setItem(input.key, next) + return next + } + + if (!input.legacyStore) return null + + for (const legacyKey of input.legacy) { + const legacyRaw = await input.legacyStore.getItem(legacyKey) + if (legacyRaw === null) continue + + const next = normalize(input.defaults, legacyRaw, input.migrate) + if (next === undefined) { + await input.legacyStore.removeItem(legacyKey).catch(() => undefined) + continue + } + await input.current.setItem(input.key, next) + await input.legacyStore.removeItem(legacyKey) + return next + } + + return null +} diff --git a/packages/app/src/utils/persist.test.ts b/packages/app/src/utils/persist.test.ts index ba82b62c8..db641b42c 100644 --- a/packages/app/src/utils/persist.test.ts +++ b/packages/app/src/utils/persist.test.ts @@ -1,4 +1,5 @@ import { beforeAll, beforeEach, describe, expect, mock, test } from "bun:test" +import type { AsyncStorage } from "@solid-primitives/storage" type PersistTestingType = typeof import("./persist").PersistTesting type ShouldDebugPersistedTerminalRead = typeof import("./persist").shouldDebugPersistedTerminalRead @@ -56,6 +57,20 @@ class MemoryStorage implements Storage { const storage = new MemoryStorage() +function asyncMemoryStorage(initial: Record = {}) { + const values = new Map(Object.entries(initial)) + const api: AsyncStorage = { + getItem: async (key) => values.get(key) ?? null, + setItem: async (key, value) => { + values.set(key, value) + }, + removeItem: async (key) => { + values.delete(key) + }, + } + return { api, values } +} + let persistTesting: PersistTestingType let shouldDebugPersistedTerminalRead: ShouldDebugPersistedTerminalRead @@ -198,6 +213,24 @@ describe("persist localStorage resilience", () => { expect(legacy.getItem("layout.page.v1")).toBeNull() }) + test("async reader removes malformed current values without legacy fallback", async () => { + const current = asyncMemoryStorage({ "layout-page": "{" }) + const legacy = asyncMemoryStorage({ "layout.page.v1": JSON.stringify({ pinned: ["legacy"] }) }) + + const result = await persistTesting.readPersistedAsync({ + current: current.api, + legacyStore: legacy.api, + key: "layout-page", + defaults: { pinned: [] as string[] }, + currentLegacy: [], + legacy: ["layout.page.v1"], + }) + + expect(result).toBeNull() + expect(current.values.has("layout-page")).toBeFalse() + expect(legacy.values.has("layout.page.v1")).toBeTrue() + }) + test("workspace storage sanitizes Windows filename characters", () => { const result = persistTesting.workspaceStorage("C:\\Users\\foo") diff --git a/packages/app/src/utils/persist.ts b/packages/app/src/utils/persist.ts index 4e04f0273..59c6d3e24 100644 --- a/packages/app/src/utils/persist.ts +++ b/packages/app/src/utils/persist.ts @@ -3,6 +3,8 @@ import { makePersisted, type AsyncStorage, type SyncStorage } from "@solid-primi import { checksum } from "@opencode-ai/util/encode" import { createResource, type Accessor } from "solid-js" import type { SetStoreFunction, Store } from "solid-js/store" +import { localStorageDirect, localStorageWithPrefix } from "./persist-local-storage" +import { normalize, readPersistedAsync, readPersistedSync } from "./persist-read" type InitType = Promise | string | null type PersistedWithReady = [ @@ -22,386 +24,17 @@ type PersistTarget = { const LEGACY_STORAGE = "default.dat" const GLOBAL_STORAGE = "pawwork.global.dat" -const LOCAL_PREFIX = "pawwork." -const LEGACY_LOCAL_PREFIX = "opencode." -// The legacy prefix intentionally covers old workspace, global, and settings keys. -const EVICT_PREFIXES = [LOCAL_PREFIX, LEGACY_LOCAL_PREFIX] -const fallback = new Map() - -const CACHE_MAX_ENTRIES = 500 -const CACHE_MAX_BYTES = 8 * 1024 * 1024 - -type CacheEntry = { value: string; bytes: number } -const cache = new Map() -const cacheTotal = { bytes: 0 } - -function cacheDelete(key: string) { - const entry = cache.get(key) - if (!entry) return - cacheTotal.bytes -= entry.bytes - cache.delete(key) -} - -function cachePrune() { - for (;;) { - if (cache.size <= CACHE_MAX_ENTRIES && cacheTotal.bytes <= CACHE_MAX_BYTES) return - const oldest = cache.keys().next().value as string | undefined - if (!oldest) return - cacheDelete(oldest) - } -} - -function cacheSet(key: string, value: string) { - const bytes = value.length * 2 - if (bytes > CACHE_MAX_BYTES) { - cacheDelete(key) - return - } - - const entry = cache.get(key) - if (entry) cacheTotal.bytes -= entry.bytes - cache.delete(key) - cache.set(key, { value, bytes }) - cacheTotal.bytes += bytes - cachePrune() -} - -function cacheGet(key: string) { - const entry = cache.get(key) - if (!entry) return - cache.delete(key) - cache.set(key, entry) - return entry.value -} - -function fallbackDisabled(scope: string) { - return fallback.get(scope) === true -} - -function fallbackSet(scope: string) { - fallback.set(scope, true) -} - -function quota(error: unknown) { - if (error instanceof DOMException) { - if (error.name === "QuotaExceededError") return true - if (error.name === "NS_ERROR_DOM_QUOTA_REACHED") return true - if (error.name === "QUOTA_EXCEEDED_ERR") return true - if (error.code === 22 || error.code === 1014) return true - return false - } - - if (!error || typeof error !== "object") return false - const name = (error as { name?: string }).name - if (name === "QuotaExceededError" || name === "NS_ERROR_DOM_QUOTA_REACHED") return true - if (name && /quota/i.test(name)) return true - - const code = (error as { code?: number }).code - if (code === 22 || code === 1014) return true - - const message = (error as { message?: string }).message - if (typeof message !== "string") return false - if (/quota/i.test(message)) return true - return false -} - -type Evict = { key: string; size: number } - -function evict(storage: Storage, keep: string, value: string) { - const total = storage.length - const indexes = Array.from({ length: total }, (_, index) => index) - const items: Evict[] = [] - - for (const index of indexes) { - const name = storage.key(index) - if (!name) continue - if (!EVICT_PREFIXES.some((prefix) => name.startsWith(prefix))) continue - if (name === keep) continue - const stored = storage.getItem(name) - items.push({ key: name, size: stored?.length ?? 0 }) - } - - items.sort((a, b) => b.size - a.size) - - for (const item of items) { - storage.removeItem(item.key) - cacheDelete(item.key) - - try { - storage.setItem(keep, value) - cacheSet(keep, value) - return true - } catch (error) { - if (!quota(error)) throw error - } - } - - return false -} - -function write(storage: Storage, key: string, value: string) { - try { - storage.setItem(key, value) - cacheSet(key, value) - return true - } catch (error) { - if (!quota(error)) throw error - } - - try { - storage.removeItem(key) - cacheDelete(key) - storage.setItem(key, value) - cacheSet(key, value) - return true - } catch (error) { - if (!quota(error)) throw error - } - - const ok = evict(storage, key, value) - return ok -} function snapshot(value: unknown) { return JSON.parse(JSON.stringify(value)) as unknown } -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value) -} - -function merge(defaults: unknown, value: unknown): unknown { - if (value === undefined) return defaults - if (value === null) return value - - if (Array.isArray(defaults)) { - if (Array.isArray(value)) return value - return defaults - } - - if (isRecord(defaults)) { - if (!isRecord(value)) return defaults - - const result: Record = { ...defaults } - for (const key of Object.keys(value)) { - if (key in defaults) { - result[key] = merge((defaults as Record)[key], (value as Record)[key]) - } else { - result[key] = (value as Record)[key] - } - } - return result - } - - return value -} - -function parse(value: string) { - try { - return JSON.parse(value) as unknown - } catch { - return undefined - } -} - -function normalize(defaults: unknown, raw: string, migrate?: (value: unknown) => unknown) { - const parsed = parse(raw) - if (parsed === undefined) return - const migrated = migrate ? migrate(parsed) : parsed - if (migrate && migrated === undefined) return - const merged = merge(defaults, migrated) - return JSON.stringify(merged) -} - -function readPersistedSync(input: { - current: SyncStorage - legacyStore: SyncStorage - key: string - defaults: unknown - legacy: string[] - currentLegacy: string[] - migrate?: (value: unknown) => unknown -}) { - const raw = input.current.getItem(input.key) - if (raw !== null) { - const next = normalize(input.defaults, raw, input.migrate) - if (next === undefined) { - input.current.removeItem(input.key) - return null - } - if (raw !== next) input.current.setItem(input.key, next) - return next - } - - for (const legacyKey of input.currentLegacy) { - const legacyRaw = input.current.getItem(legacyKey) - if (legacyRaw === null) continue - - const next = normalize(input.defaults, legacyRaw, input.migrate) - if (next === undefined) continue - input.current.setItem(input.key, next) - return next - } - - for (const legacyKey of input.legacy) { - const legacyRaw = input.legacyStore.getItem(legacyKey) - if (legacyRaw === null) continue - - const next = normalize(input.defaults, legacyRaw, input.migrate) - if (next === undefined) { - input.legacyStore.removeItem(legacyKey) - continue - } - input.current.setItem(input.key, next) - input.legacyStore.removeItem(legacyKey) - return next - } - - return null -} - -async function readPersistedAsync(input: { - current: AsyncStorage - legacyStore?: AsyncStorage - key: string - defaults: unknown - legacy: string[] - currentLegacy: string[] - migrate?: (value: unknown) => unknown -}) { - const raw = await input.current.getItem(input.key) - if (raw !== null) { - const next = normalize(input.defaults, raw, input.migrate) - if (next === undefined) { - await input.current.removeItem(input.key).catch(() => undefined) - return null - } - if (raw !== next) await input.current.setItem(input.key, next) - return next - } - - for (const legacyKey of input.currentLegacy) { - const legacyRaw = await input.current.getItem(legacyKey) - if (legacyRaw === null) continue - - const next = normalize(input.defaults, legacyRaw, input.migrate) - if (next === undefined) continue - await input.current.setItem(input.key, next) - return next - } - - if (!input.legacyStore) return null - - for (const legacyKey of input.legacy) { - const legacyRaw = await input.legacyStore.getItem(legacyKey) - if (legacyRaw === null) continue - - const next = normalize(input.defaults, legacyRaw, input.migrate) - if (next === undefined) { - await input.legacyStore.removeItem(legacyKey).catch(() => undefined) - continue - } - await input.current.setItem(input.key, next) - await input.legacyStore.removeItem(legacyKey) - return next - } - - return null -} - function workspaceStorage(dir: string) { const head = (dir.slice(0, 12) || "workspace").replace(/[^a-zA-Z0-9._-]/g, "-") const sum = checksum(dir) ?? "0" return `pawwork.workspace.${head}.${sum}.dat` } -function localStorageWithPrefix(prefix: string): SyncStorage { - const base = `${prefix}:` - const scope = `prefix:${prefix}` - const item = (key: string) => base + key - return { - getItem: (key) => { - const name = item(key) - const cached = cacheGet(name) - if (fallbackDisabled(scope)) return cached ?? null - - const stored = (() => { - try { - return localStorage.getItem(name) - } catch { - fallbackSet(scope) - return null - } - })() - if (stored === null) return cached ?? null - cacheSet(name, stored) - return stored - }, - setItem: (key, value) => { - const name = item(key) - if (fallbackDisabled(scope)) return - try { - if (write(localStorage, name, value)) return - } catch { - fallbackSet(scope) - return - } - fallbackSet(scope) - }, - removeItem: (key) => { - const name = item(key) - cacheDelete(name) - if (fallbackDisabled(scope)) return - try { - localStorage.removeItem(name) - } catch { - fallbackSet(scope) - } - }, - } -} - -function localStorageDirect(): SyncStorage { - const scope = "direct" - return { - getItem: (key) => { - const cached = cacheGet(key) - if (fallbackDisabled(scope)) return cached ?? null - - const stored = (() => { - try { - return localStorage.getItem(key) - } catch { - fallbackSet(scope) - return null - } - })() - if (stored === null) return cached ?? null - cacheSet(key, stored) - return stored - }, - setItem: (key, value) => { - if (fallbackDisabled(scope)) return - try { - if (write(localStorage, key, value)) return - } catch { - fallbackSet(scope) - return - } - fallbackSet(scope) - }, - removeItem: (key) => { - cacheDelete(key) - if (fallbackDisabled(scope)) return - try { - localStorage.removeItem(key) - } catch { - fallbackSet(scope) - } - }, - } -} - export const PersistTesting = { localStorageDirect, localStorageWithPrefix,