Open source personal finance application
refactor(stores): migrate stores and app init to powersync offline-first with cold-start cache
Ilya Komichev7def15e081c9
diff --git a/app/app/components/app/useInitApp.ts b/app/app/components/app/useInitApp.tsindex a867fd6d..6dee8da2 100644--- a/app/app/components/app/useInitApp.ts+++ b/app/app/components/app/useInitApp.ts@@ -1,45 +1,85 @@import localforage from 'localforage'+import { connectPowerSync, getLocalDbOwner, waitForFirstSync } from '~~/services/powersync/db'import type { Categories } from '~/components/categories/types'+import type { Rates } from '~/components/currencies/types'import type { Trns } from '~/components/trns/types'-import type { User } from '~/components/user/useUserStore'+import type { User, UserSettingsCache } from '~/components/user/useUserStore'import type { Wallets } from '~/components/wallets/types'import { useCategoriesStore } from '~/components/categories/useCategoriesStore'import { ratesSchema } from '~/components/currencies/types'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'-import { setOfflineQueueUserId } from '~/components/offline/helpers'-import { replayOfflineQueue } from '~/components/offline/replay'+import { useDemo } from '~/components/demo/useDemo'import { STORAGE_KEYS } from '~/components/offline/storageKeys'import { useTrnsStore } from '~/components/trns/useTrnsStore'import { userSettingsSchema } from '~/components/user/types'import { useUserStore } from '~/components/user/useUserStore'import { useWalletsStore } from '~/components/wallets/useWalletsStore'-import { hasAuthCookie } from '~/composables/useAuthCookie'-import { startAllRealtime } from '~/composables/useRealtimeSync'+import { getPersistedUid } from '~/composables/useAuthSession'+import { clearStoreCache, readStoreCache } from '~/composables/useStoreCache'import { blockPersist, unblockPersist } from '~/composables/useStoreSync'+import { useSupabase } from '~/composables/useSupabase'import { createLogger } from '~/utils/logger'+const logger = createLogger('app')++// Module-level singletons: every useInitApp() caller (layout, dashboard, guard) observes the same flags.+const isDbLoading = ref(false)+const isOffline = ref(false)+export function useInitApp() {- const isDbLoading = ref(false)- const isOffline = ref(false)const userStore = useUserStore()const currenciesStore = useCurrenciesStore()const walletsStore = useWalletsStore()const categoriesStore = useCategoriesStore()const trnsStore = useTrnsStore()+ // True once all three data stores have received their first local-SQLite watch emission (even+ // an empty one) - the real "local data is on screen" signal the onboarding gate waits on. Demo+ // mode loads synchronously, so it's always ready.+ const isHydrated = computed(() =>+ useDemo().isDemo.value+ || (walletsStore.isLoaded && categoriesStore.isLoaded && trnsStore.isLoaded))+useEventListener(window, 'online', () => {isOffline.value = false+ // PowerSync reconnects on its own; re-arming watches is cheap and idempotent.if (userStore.uid && !isDbLoading.value)- loadDataFromDB()+ startWatches()})useEventListener(window, 'offline', () => {isOffline.value = true})- async function loadDataFromCache() {+ /**+ * Register reactive watches on local SQLite. Each watch emits current local rows immediately+ * and again on every incoming sync. Idempotent: each store aborts its previous watch first.+ */+ function startWatches() {+ userStore.initUserSettings()+ currenciesStore.initCurrencies()+ categoriesStore.initCategories()+ walletsStore.initWallets()+ trnsStore.initTrns()+ }++ // Instant first paint: seed the stores from the last session's per-user snapshot while+ // PowerSync's db.init + first query scan are still running. The watches then reconcile to truth.+ async function primeStoresFromCache() {+ const snap = await readStoreCache()+ if (!snap)+ return+ trnsStore.primeFromCache((snap.trns as Trns) ?? null)+ categoriesStore.primeFromCache((snap.categories as Categories) ?? null)+ walletsStore.primeFromCache((snap.wallets as Wallets) ?? null)+ userStore.primeFromCache((snap.user as UserSettingsCache) ?? null)+ currenciesStore.primeFromCache((snap.rates as Rates) ?? null)+ }++ // Demo mode keeps its own localforage-backed cache (no backend).+ async function loadDemoFromCache() {const [user, rawUserSettings, rawCurrencies, categories, wallets, trns] = await Promise.all([localforage.getItem<User | null>(STORAGE_KEYS.user),localforage.getItem(STORAGE_KEYS.userSettings),@@ -67,79 +107,73 @@ export function useInitApp() {trnsStore.setTrns(trns ?? null)}- function clearLocalData() {- blockPersist()-- categoriesStore.setCategories(null)- trnsStore.setTrns(null)- walletsStore.setWallets(null)- userStore.setUser(null)+ // Offline-first: local PowerSync SQLite is the only data source the UI reads. This arms the live+ // watches; their first emission fills the stores from disk. The server sync runs in the background.+ async function startLocalData() {+ unblockPersist()- const offlineKeys: Set<string> = new Set([STORAGE_KEYS.offlineQueue, STORAGE_KEYS.offlineQueueUserId])- for (const key of Object.values(STORAGE_KEYS)) {- if (!offlineKeys.has(key))- localforage.removeItem(key)+ if (useDemo().isDemo.value) {+ await loadDemoFromCache()+ return}- }- async function loadDataFromDB() {- unblockPersist()+ // Paint instantly from the last session's snapshot, in parallel with db.init - don't await.+ void primeStoresFromCache()- const { $waitForConvexAuth } = useNuxtApp()- await ($waitForConvexAuth as () => Promise<void>)()-- // Auth cookie exists but session hasn't resolved yet (no cached user from previous login).- // Wait briefly for userStore.uid to appear before giving up.- if (!userStore.uid && hasAuthCookie()) {- await new Promise<void>((resolve) => {- let timer: ReturnType<typeof setTimeout>- const stop = watch(() => userStore.uid, (val) => {- if (val) {- stop()- clearTimeout(timer)- resolve()- }- })- timer = setTimeout(() => {- stop()- resolve()- }, 5000)- })+ // If local SQLite still holds another user's rows, wipe + reconnect before reading so we never+ // surface the previous user's data. Same-user path stays instant (no wait).+ const currentUid = userStore.uid ?? getPersistedUid()+ const owner = getLocalDbOwner()+ if (currentUid && owner && owner !== currentUid) {+ const config = useRuntimeConfig()+ await connectPowerSync(useSupabase(), config.public.powersyncUrl as string, currentUid)}- if (!userStore.uid)+ startWatches()+ }++ // NOT a second data load - just waits for the server's first sync to land in local SQLite. Only+ // matters when local SQLite is empty/stale (fresh login, new device): holds the loading screen so+ // a returning user on a new device doesn't flash onboarding before their data lands.+ async function awaitInitialSync() {+ if (useDemo().isDemo.value)return- setOfflineQueueUserId(userStore.uid)+ if (!userStore.uid)+ returnisDbLoading.value = truetry {- await Promise.all([- userStore.initUserSettings(),- currenciesStore.initCurrencies(),- categoriesStore.initCategories(),- walletsStore.initWallets(),- trnsStore.initTrns(),- ])-- await replayOfflineQueue()- // Subscriptions must start AFTER initial sync so `since` is meaningful- // and AFTER replay so our own replayed ops are in inFlightOps first.- startAllRealtime().catch(e => createLogger('app').error('startAllRealtime failed', e))+ await waitForFirstSync()}catch (e) {- createLogger('app').error('loadDataFromDB failed', e)+ logger.error('awaitInitialSync failed', e)}finally {isDbLoading.value = false}}+ function clearLocalData() {+ blockPersist()++ categoriesStore.setCategories(null)+ trnsStore.setTrns(null)+ walletsStore.setWallets(null)+ userStore.setUser(null)++ for (const key of Object.values(STORAGE_KEYS))+ localforage.removeItem(key)++ void clearStoreCache()+ }+return {+ awaitInitialSync,clearLocalData,isDbLoading,+ isHydrated,isOffline,- loadDataFromCache,- loadDataFromDB,+ startLocalData,}}diff --git a/app/app/components/categories/Form.vue b/app/app/components/categories/Form.vueindex ebdeab9b..99e2a054 100644--- a/app/app/components/categories/Form.vue+++ b/app/app/components/categories/Form.vue@@ -256,13 +256,14 @@ async function onSave() {}}- const result = await categoriesStore.saveCategory({+ await categoriesStore.saveCategory({id: editCategoryId,isUpdateChildCategoriesColor: isUpdateChildCategoriesColor.value,nextChildIds: isAllowManageChildren.value ? [...selectedChildIds.value] : undefined,values: parsed.data,})- emit('afterSave', result?.convexId ?? editCategoryId)+ // With client-generated UUIDs the id is final - no server remap.+ emit('afterSave', editCategoryId)}</script>diff --git a/app/app/components/categories/StatPage.vue b/app/app/components/categories/StatPage.vueindex 655b4d44..8a3936a1 100644--- a/app/app/components/categories/StatPage.vue+++ b/app/app/components/categories/StatPage.vue@@ -24,7 +24,7 @@ const filter = useFilter()provide(filterKey, filter)const categoryId = computed(() => route.params.id) as ComputedRef<CategoryId>-const category = ref(categoriesStore.items[categoryId.value])+const category = computed(() => categoriesStore.items[categoryId.value])const categoriesIdsOrParent = computed(() => categoriesStore.getChildrenIdsOrParent(categoryId.value))const activeTab = useStorage<StatTabSlug>(`stat-${categoryId.value}-tab`, 'summary')@@ -62,8 +62,19 @@ const statDate = useStatDate({})provide(statDateKey, statDate)-if (!category.value)- router.replace('/dashboard')+// On a hard reload of /categories/{id} the store only holds the synthetic+// adjustment/transfer entries for a tick, so redirecting synchronously would+// bounce a valid id to the dashboard (hydration race). `items` is always truthy+// (it carries those synthetic entries), so wait on `hasItems` instead: only+// redirect once real categories have hydrated but this id is genuinely absent.+watch(+ () => categoriesStore.hasItems,+ (hasItems) => {+ if (hasItems && !category.value)+ router.replace('/dashboard')+ },+ { immediate: true },+)onMounted(() => {statConfig.updateConfig('catsList', { isGrouped: false })@@ -73,7 +84,7 @@ onMounted(() => {trnsFormStore.values.categoryId = categoryId.value})-useHead({ title: category.value?.name })+useHead({ title: computed(() => category.value?.name) })</script><template>diff --git a/app/app/components/categories/page/id/Edit.vue b/app/app/components/categories/page/id/Edit.vueindex 8bce2a41..89775fc5 100644--- a/app/app/components/categories/page/id/Edit.vue+++ b/app/app/components/categories/page/id/Edit.vue@@ -12,10 +12,18 @@ const categoriesStore = useCategoriesStore()const categoryId = computed<CategoryId>(() => String(route.params.id))const category = computed(() => categoriesStore.items[categoryId.value])-const categoryForm = ref(categoryFormSchema.parse(category.value))+// On a hard navigation the store hydrates from PowerSync after setup, so+// `category` is undefined initially - parse `?? {}` to avoid throwing, then+// re-seed the form once the category arrives (the template gates on `category`).+const categoryForm = ref(categoryFormSchema.parse(category.value ?? {}))++watch(category, (cat) => {+ if (cat)+ categoryForm.value = categoryFormSchema.parse(cat)+}, { immediate: true })useHead({- title: `${t('base.edit')}: ${categoryForm.value?.name || t('categories.form.name.label')}`,+ title: computed(() => `${t('base.edit')}: ${categoryForm.value?.name || t('categories.form.name.label')}`),})function onAfterSave() {diff --git a/app/app/components/categories/useCategoriesStore.ts b/app/app/components/categories/useCategoriesStore.tsindex 16385a84..9f7e078d 100644--- a/app/app/components/categories/useCategoriesStore.ts+++ b/app/app/components/categories/useCategoriesStore.ts@@ -1,16 +1,20 @@-import { convexCategoriesToMap } from '~~/services/convex/api'+import type { Row } from '~~/services/powersync/transforms'++import { watchTable } from '~~/services/powersync/db'+import { deleteRow, upsertRows } from '~~/services/powersync/mutations'+import { categoryToRow, rowToCategory } from '~~/services/powersync/transforms'import type { AddCategoryParams, Categories, CategoryId, CategoryItem } from '~/components/categories/types'import type { TrnId } from '~/components/trns/types'-import type { RemapInfo } from '~/composables/useStoreSync'import { compareCategoryIds, computeChildrenDiff, getTransactibleCategoriesIds } from '~/components/categories/utils'import { useDemo } from '~/components/demo/useDemo'-import { removeOfflineOps, updateOfflineOpData } from '~/components/offline/helpers'import { STORAGE_KEYS } from '~/components/offline/storageKeys'import { TrnType } from '~/components/trns/types'import { useTrnsStore } from '~/components/trns/useTrnsStore'-import { createDebouncedPersist, handleMutationResult, isInFlight, mergeOfflineOps, pushDeleteOp, pushSaveOp } from '~/composables/useStoreSync'+import { persistStoreCache } from '~/composables/useStoreCache'+import { createDebouncedPersist, showErrorToast } from '~/composables/useStoreSync'+import { useSupabaseAuth } from '~/composables/useSupabase'import { createLogger } from '~/utils/logger'const adjustment: CategoryItem = {@@ -32,11 +36,10 @@ const transfer: CategoryItem = {}type CategoriesStore = {- applyRealtimePatch: (patch: { deletedIds: string[], docs: { [k: string]: unknown, _creationTime: number, _id: string, userId: string }[], serverTime: number, truncated: boolean }) => number | nullcategoriesForBeParent: ComputedRef<CategoryId[]>categoriesIdsForTrnValues: ComputedRef<CategoryId[]>categoriesRootIds: ComputedRef<CategoryId[]>- deleteCategory: (id: CategoryId, trnsIds?: TrnId[]) => Promise<RemapInfo | void> | void+ deleteCategory: (id: CategoryId, trnsIds?: TrnId[]) => Promise<void> | voidfavoriteCategoriesIds: ComputedRef<CategoryId[]>getChildrenIds: (categoryId: CategoryId) => CategoryId[]getChildrenIdsOrParent: (categoryId: CategoryId) => CategoryId[]@@ -44,11 +47,12 @@ type CategoriesStore = {hasChildren: (categoryId: CategoryId) => booleanhasItems: ComputedRef<boolean>initCategories: () => void+ isLoaded: import('vue').Ref<boolean>isTransactible: (categoryId: CategoryId) => booleanitems: import('vue').ShallowRef<Categories>- lastSyncedAt: import('vue').Ref<number>+ primeFromCache: (data: Categories | null) => voidrecentCategoriesIds: ComputedRef<CategoryId[]>- saveCategory: (params: AddCategoryParams) => Promise<RemapInfo | void> | void+ saveCategory: (params: AddCategoryParams) => Promise<void> | voidsetCategories: (values: Categories | null) => void}@@ -57,14 +61,38 @@ const logger = createLogger('categories')export const useCategoriesStore = defineStore('categories', (): CategoriesStore => {const trnsStore = useTrnsStore()const { isDemo } = useDemo()+ const { uid } = useSupabaseAuth()const items = shallowRef<Categories>({ adjustment, transfer })const hasItems = computed(() =>Object.keys(items.value).some(id => id !== 'transfer' && id !== 'adjustment'),)+ // True after the first local-SQLite emission; reset on (re)subscribe so a new user waits for theirs.+ const isLoaded = ref(false)++ let watchController: AbortController | null = nullconst categoriesIds = computed(() => Object.keys(items.value))+ // Child ids grouped by parentId, sorted once per `items` change.+ const childrenMap = computed(() => {+ const all = items.value+ const map = new Map<CategoryId, CategoryId[]>()+ for (const id in all) {+ const parentId = all[id]?.parentId+ if (!parentId) // root (parentId 0) - not a child of any category+ continue+ const group = map.get(parentId)+ if (group)+ group.push(id)+ else+ map.set(parentId, [id])+ }+ for (const group of map.values())+ group.sort((a, b) => compareCategoryIds(a, b, all))+ return map+ })+const categoriesRootIds = computed(() => {if (!hasItems.value)return []@@ -153,78 +181,40 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStoreconst debouncedPersist = createDebouncedPersist<Categories>(STORAGE_KEYS.categories)- const lastSyncedAt = ref(0)-- async function initCategories() {- try {- const { api, client } = useConvexClientWithApi()- const categories = await client.query(api.categories.list, {})- let data: Categories | null = categories?.length ? convexCategoriesToMap(categories) : null-- if (data)- data = await mergeOfflineOps(data, 'categories') as Categories-- setCategories(data)- lastSyncedAt.value = Date.now()- }- catch (e) {- logger.error('init failed', e)- }- }-- type ConvexCategoryDoc = { [key: string]: unknown, _creationTime: number, _id: string, userId: string }-- function applyRealtimePatch(patch: { deletedIds: string[], docs: ConvexCategoryDoc[], serverTime: number, truncated: boolean }): number | null {- if (patch.truncated) {- logger.log('realtime delta truncated — running initCategories')- initCategories()- return null- }-- const current = items.value- const updated: Categories = { ...current }- let changed = false-- for (const doc of patch.docs) {- if (isInFlight(doc._id))- continue- const existing = updated[doc._id]- const existingUpdatedAt = existing?.updatedAt- const docUpdatedAt = typeof doc.updatedAt === 'number' ? doc.updatedAt : 0- if (existing && typeof existingUpdatedAt === 'number' && existingUpdatedAt >= docUpdatedAt)- continue- const { _creationTime: _ct, _id, userId: _u, ...rest } = doc- updated[_id] = rest as unknown as CategoryItem- changed = true- }-- for (const id of patch.deletedIds) {- if (isInFlight(id) || id === 'transfer' || id === 'adjustment')- continue- if (id in updated) {- delete updated[id]- changed = true- }- }-- if (changed) {- // setCategories re-adds synthetic transfer/adjustment entries.- const userItems: Record<CategoryId, CategoryItem> = {}- for (const id of Object.keys(updated)) {- if (id !== 'transfer' && id !== 'adjustment')- userItems[id] = updated[id]!+ /** Real mode: subscribe to local SQLite. setCategories re-adds synthetic entries. */+ function initCategories(): void {+ if (isDemo.value)+ return+ watchController?.abort()+ isLoaded.value = false // re-subscribe (e.g. different user) waits for a fresh emission+ watchController = watchTable<Row>('SELECT * FROM categories', [], (rows) => {+ isLoaded.value = true+ if (!rows.length) {+ setCategories(null)+ return}- setCategories(userItems as Categories)- logger.log(`realtime: ${patch.docs.length} docs, ${patch.deletedIds.length} deletes`)- }- lastSyncedAt.value = patch.serverTime- return patch.serverTime+ const map: Categories = {} as Categories+ for (const row of rows)+ map[row.id] = rowToCategory(row)+ setCategories(map)+ })+ logger.log('watching categories')}function setCategories(values: Categories | null) {const categories = values ? { ...values, adjustment, transfer } : { adjustment, transfer }items.value = categories- debouncedPersist(categories)+ if (isDemo.value)+ debouncedPersist(categories)+ else+ persistStoreCache('categories', categories)+ }++ /** Cold-start paint from the snapshot before the watch emits; re-adds the synthetic entries. */+ function primeFromCache(data: Categories | null): void {+ if (isDemo.value || !data || isLoaded.value)+ return+ items.value = { ...data, adjustment, transfer }}function hasChildren(categoryId: CategoryId) {@@ -235,16 +225,14 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStoreif (!category || category.parentId !== 0)return false- return Object.keys(items.value).some(id => items.value[id]?.parentId === categoryId)+ return (childrenMap.value.get(categoryId)?.length ?? 0) > 0}function getChildrenIds(categoryId: CategoryId) {if (!hasItems.value)return []- return Object.keys(items.value)- .filter(id => items.value[id]?.parentId === categoryId)- .sort((a, b) => compareCategoryIds(a, b, items.value))+ return childrenMap.value.get(categoryId)?.slice() ?? []}function getChildrenIdsOrParent(categoryId: CategoryId) {@@ -305,30 +293,18 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStoreif (id === 'transfer' || id === 'adjustment')return+ const prev = items.valueconst prevChildIds = getChildrenIds(id)const useChildrenDiff = Array.isArray(nextChildIds)const diff = useChildrenDiff? computeChildrenDiff(prevChildIds, nextChildIds!): { added: [] as CategoryId[], removed: [] as CategoryId[] }const hasChildrenDiff = diff.added.length > 0 || diff.removed.length > 0- // Children that stay under this parent — safe color propagation targets+ // Children that stay under this parent - safe color propagation targetsconst keptChildIds = useChildrenDiff? prevChildIds.filter(cid => nextChildIds!.includes(cid)): prevChildIds- // Frontend IDs are always treated as new creates (server generates real ID)- const isExisting = !isLocalId(id) && items.value && id in items.value-- // Capture pre-optimistic snapshot for rollback (only for reparented children)- const reparentRollback = new Map<CategoryId, { color: string, parentId: CategoryId | 0 }>()- if (hasChildrenDiff) {- for (const cid of [...diff.added, ...diff.removed]) {- const prev = items.value[cid]- if (prev)- reparentRollback.set(cid, { color: prev.color, parentId: prev.parentId })- }- }-applyOptimisticUpdate(id,values,@@ -337,219 +313,40 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStorehasChildrenDiff ? diff : undefined,)- if (!pushSaveOp({ entity: 'categories', id, isDemo: !!isDemo.value, isExisting: !!isExisting, values }))+ if (isDemo.value)return- // 3c — Queue per-kept-child color ops so propagation survives updateWithChildren failure.- const useUpdateWithChildren = !!isExisting && isUpdateChildCategoriesColor && keptChildIds.length > 0- if (useUpdateWithChildren) {- const snapshot = items.value- for (const cid of keptChildIds) {- const child = snapshot[cid]- if (!child)- continue- pushSaveOp({- entity: 'categories',- id: cid,- isDemo: !!isDemo.value,- isExisting: true,- values: { ...child, color: values.color } as unknown as Record<string, unknown>,- })- }+ // Persist every category whose row changed during the optimistic update, in one+ // transaction so a partial local-write failure can't leave SQLite half-updated.+ const touched = new Set<CategoryId>([id])+ if (isUpdateChildCategoriesColor) {+ for (const cid of keptChildIds) touched.add(cid)}-- const { api, client } = useConvexClientWithApi()- const action = isExisting ? 'update' : 'create'-- const categoryData = {- color: values.color,- icon: values.icon,- name: values.name,- parentId: values.parentId ? asConvexId<'categories'>(String(values.parentId)) : 0 as const,- showInLastUsed: values.showInLastUsed,- showInQuickSelector: values.showInQuickSelector,+ for (const cid of diff.added) touched.add(cid)+ for (const cid of diff.removed) touched.add(cid)++ const userId = uid.value ?? ''+ const rows: { id: CategoryId, row: Record<string, unknown> }[] = []+ for (const cid of touched) {+ const item = items.value[cid]+ if (item)+ rows.push({ id: cid, row: categoryToRow(item, userId) })}- const mutation = useUpdateWithChildren- ? client.mutation(api.categories.updateWithChildren, {- childIds: keptChildIds.map(cid => asConvexId<'categories'>(cid)),- id: asConvexId<'categories'>(id),- ...categoryData,- })- : isExisting- ? client.mutation(api.categories.update, { id: asConvexId<'categories'>(id), ...categoryData })- : client.mutation(api.categories.create, categoryData)-- const coreResult = handleMutationResult({- action,- entity: 'categories',- errorMessage: 'categories.errors.saveFailed',- // When updateWithChildren is in play, drain kept-child ops on success too.- id: useUpdateWithChildren ? [id, ...keptChildIds] : id,- items,- mutation,- })-- if (hasChildrenDiff) {- const snapshot = items.value- const reparentIds: CategoryId[] = []- for (const addId of diff.added) {- const current = snapshot[addId]- if (!current)- continue- reparentIds.push(addId)- pushSaveOp({- entity: 'categories',- id: addId,- isDemo: !!isDemo.value,- isExisting: true,- values: { ...current, parentId: id } as unknown as Record<string, unknown>,- })- }- for (const removeId of diff.removed) {- const current = snapshot[removeId]- if (!current)- continue- reparentIds.push(removeId)- pushSaveOp({- entity: 'categories',- id: removeId,- isDemo: !!isDemo.value,- isExisting: true,- values: { ...current, parentId: 0 } as unknown as Record<string, unknown>,- })- }-- if (reparentIds.length > 0 && !isLocalId(id)) {- // Filter local-id children out of setChildren — their create op carries- // the new parentId via the collapsed update op, so server picks it up- // when the create eventually replays. Sending local_* to setChildren- // would be rejected as an invalid Convex id.- const serverAddIds = diff.added.filter(cid => !isLocalId(cid))- const serverRemoveIds = diff.removed.filter(cid => !isLocalId(cid))-- if (serverAddIds.length === 0 && serverRemoveIds.length === 0)- return coreResult-- const reparentMutation = client.mutation(api.categories.setChildren, {- addIds: serverAddIds.map(cid => asConvexId<'categories'>(cid)),- childrenColor: isUpdateChildCategoriesColor ? values.color : undefined,- id: asConvexId<'categories'>(id),- removeIds: serverRemoveIds.map(cid => asConvexId<'categories'>(cid)),- })- handleMutationResult({- action: 'update',- entity: 'categories',- errorMessage: 'categories.errors.saveFailed',- id: [...serverAddIds, ...serverRemoveIds],- items,- mutation: reparentMutation,- onError: () => {- // Restore previous parentIds/colors for reparented categories- const restored: Categories = { ...items.value }- for (const [cid, prev] of reparentRollback) {- if (restored[cid])- restored[cid] = { ...restored[cid], color: prev.color, parentId: prev.parentId }- }- setCategories(restored)- // 3d — Drain non-local reparent update ops; for local-id children- // patch their queued create back to pre-optimistic parentId so the- // child is still created server-side, just under the original parent.- const nonLocalIds = reparentIds.filter(cid => !isLocalId(cid))- if (nonLocalIds.length > 0)- void removeOfflineOps('categories', nonLocalIds)- for (const cid of reparentIds) {- if (!isLocalId(cid))- continue- const prev = reparentRollback.get(cid)- if (prev)- void updateOfflineOpData('categories', cid, { parentId: prev.parentId })- }- },- })- }- else if (reparentIds.length > 0 && isLocalId(id)) {- // New parent: wait for create to remap localId → convexId, then- // patch children's parentId locally and call setChildren on server.- // Local-id children stay queued and rely on offline replay.- const serverAddIds = diff.added.filter(cid => !isLocalId(cid))- const serverRemoveIds = diff.removed.filter(cid => !isLocalId(cid))-- Promise.resolve(coreResult).then((remap) => {- if (!remap || remap.localId !== id)- return-- const updated: Categories = { ...items.value }- let changed = false- for (const addId of diff.added) {- const child = updated[addId]- if (child && child.parentId === remap.localId) {- updated[addId] = { ...child, parentId: remap.convexId }- changed = true- }- }- if (changed)- setCategories(updated)-- // 3b — Patch queued child ops so their data.parentId no longer points- // at the remapped local id. Covers both reparented existing children- // (queued as 'update') and local-id children with their own queued- // 'create' op carrying values.parentId = local_parent_id.- for (const addId of diff.added)- void updateOfflineOpData('categories', addId, { parentId: remap.convexId })-- if (serverAddIds.length === 0 && serverRemoveIds.length === 0)- return-- const reparentMutation = client.mutation(api.categories.setChildren, {- addIds: serverAddIds.map(cid => asConvexId<'categories'>(cid)),- childrenColor: isUpdateChildCategoriesColor ? values.color : undefined,- id: asConvexId<'categories'>(remap.convexId),- removeIds: serverRemoveIds.map(cid => asConvexId<'categories'>(cid)),- })- handleMutationResult({- action: 'update',- entity: 'categories',- errorMessage: 'categories.errors.saveFailed',- id: [...serverAddIds, ...serverRemoveIds],- items,- mutation: reparentMutation,- onError: () => {- const restored: Categories = { ...items.value }- for (const [cid, prev] of reparentRollback) {- if (restored[cid])- restored[cid] = { ...restored[cid], color: prev.color, parentId: prev.parentId }- }- setCategories(restored)- // 3d — Drain non-local reparent update ops; for local-id children- // patch their queued create back to pre-optimistic parentId.- const nonLocalIds = [...diff.added, ...diff.removed].filter(cid => !isLocalId(cid))- if (nonLocalIds.length > 0)- void removeOfflineOps('categories', nonLocalIds)- for (const cid of [...diff.added, ...diff.removed]) {- if (!isLocalId(cid))- continue- const prev = reparentRollback.get(cid)- if (prev)- void updateOfflineOpData('categories', cid, { parentId: prev.parentId })- }- },- })- }).catch((e) => {- // coreResult resolves with RemapInfo|void and never rejects (handleMutationResult- // catches mutation rejection internally), but guard against unforeseen throws.- logger.error('reparent post-create flow failed', e)- })- }- }-- return coreResult+ return upsertRows('categories', rows)+ .catch((e) => {+ setCategories(prev) // roll back the optimistic update if the local write failed+ logger.error('saveCategory failed', e)+ showErrorToast('categories.errors.saveFailed')+ })}function deleteCategory(id: CategoryId, trnsIds?: TrnId[]) {if (id === 'transfer' || id === 'adjustment')return+ const prevCategories = items.value+ const prevTrns = trnsStore.itemsconst categories = { ...items.value }delete categories[id]setCategories(categories)@@ -557,23 +354,27 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStoreif (trnsIds?.length)trnsStore.removeTrnsFromStore(trnsIds)- if (!pushDeleteOp({ entity: 'categories', id, isDemo: !!isDemo.value }))+ if (isDemo.value)return- const { api, client } = useConvexClientWithApi()- return handleMutationResult({- action: 'delete',- entity: 'categories',- errorMessage: 'categories.errors.deleteFailed',- id,- items,- mutation: client.action(api.categories.remove, { id: asConvexId<'categories'>(id) }),+ // Cascade: delete the category and its transactions.+ const writes: Promise<void>[] = [deleteRow('categories', id)]+ if (trnsIds?.length) {+ for (const trnId of trnsIds) writes.push(deleteRow('trns', trnId))+ }- })+ return Promise.all(writes)+ .then(() => undefined)+ .catch((e) => {+ // Roll back the category and its cascaded trns if the local write failed.+ setCategories(prevCategories)+ trnsStore.setTrns(prevTrns)+ logger.error('deleteCategory failed', e)+ showErrorToast('categories.errors.deleteFailed')+ })}return {- applyRealtimePatch,categoriesForBeParent,categoriesIdsForTrnValues,categoriesRootIds,@@ -585,9 +386,10 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStorehasChildren,hasItems,initCategories,+ isLoaded,isTransactible,items,- lastSyncedAt,+ primeFromCache,recentCategoriesIds,saveCategory,setCategories,diff --git a/app/app/components/currencies/useCurrenciesStore.ts b/app/app/components/currencies/useCurrenciesStore.tsindex 53e899e3..249cfd40 100644--- a/app/app/components/currencies/useCurrenciesStore.ts+++ b/app/app/components/currencies/useCurrenciesStore.ts@@ -1,11 +1,16 @@+import type { Row } from '~~/services/powersync/transforms'+import localforage from 'localforage'import { defineStore } from 'pinia'+import { watchTable } from '~~/services/powersync/db'+import { rowToRates } from '~~/services/powersync/transforms'import type { Rates } from '~/components/currencies/types'-import { ratesSchema } from '~/components/currencies/types'+import { useDemo } from '~/components/demo/useDemo'import { STORAGE_KEYS } from '~/components/offline/storageKeys'import { useUserStore } from '~/components/user/useUserStore'+import { persistStoreCache } from '~/composables/useStoreCache'import { isPersistBlocked } from '~/composables/useStoreSync'import { createLogger } from '~/utils/logger'@@ -13,29 +18,25 @@ const logger = createLogger('currencies')export const useCurrenciesStore = defineStore('currencies', () => {const userStore = useUserStore()+ const { isDemo } = useDemo()const base = computed(() => userStore.baseCurrency)const rates = ref<Rates>({})- async function initCurrencies() {- try {- const { api, client } = useConvexClientWithApi()-- const latestRates = await client.query(api.rates.getLatest, {})-- if (latestRates?.rates) {- const parsed = ratesSchema.safeParse(latestRates.rates)- if (parsed.success) {- setRates(parsed.data)- }- else {- logger.error('invalid rates from Convex', parsed.error)- }- }- }- catch (e) {- logger.error('init failed', e)- }+ let watchController: AbortController | null = null++ /** Real mode: subscribe to the latest rates row in local SQLite. */+ function initCurrencies(): void {+ if (isDemo.value)+ return++ watchController?.abort()+ watchController = watchTable<Row>('SELECT * FROM rates ORDER BY date DESC LIMIT 1', [], (rows) => {+ const r = rows[0] ? rowToRates(rows[0]) : null+ if (r)+ setRates(r)+ })+ logger.log('watching rates')}function setRates(values: Rates) {@@ -43,15 +44,24 @@ export const useCurrenciesStore = defineStore('currencies', () => {if (isPersistBlocked())return+ // Demo keeps its own localforage key; real mode mirrors rates into the cold-start snapshot.+ if (isDemo.value)+ localforage.setItem(STORAGE_KEYS.currencies, { rates: values })+ else+ persistStoreCache('rates', toRaw(values)) // plain copy - IndexedDB can't clone a Vue proxy+ }- localforage.setItem(STORAGE_KEYS.currencies, {- rates: values,- })+ /** Cold-start paint: seed rates from the per-user snapshot before the rates watch emits. */+ function primeFromCache(data: Rates | null): void {+ if (isDemo.value || !data || Object.keys(rates.value).length)+ return+ rates.value = data}return {base,initCurrencies,+ primeFromCache,rates,setRates,}diff --git a/app/app/components/offline/storageKeys.ts b/app/app/components/offline/storageKeys.tsindex 86481986..a9dc58f5 100644--- a/app/app/components/offline/storageKeys.ts+++ b/app/app/components/offline/storageKeys.ts@@ -1,10 +1,7 @@export const STORAGE_KEYS = {categories: 'finapp.categories',currencies: 'finapp.currencies',- offlineQueue: 'finapp.offline.queue',- offlineQueueUserId: 'finapp.offline.queueUserId',trns: 'finapp.trns',- trnsSyncMeta: 'finapp.trns.syncMeta',user: 'finapp.user',userSettings: 'finapp.userSettings',wallets: 'finapp.wallets',diff --git a/app/app/components/trns/reconcile.ts b/app/app/components/trns/reconcile.tsnew file mode 100644index 00000000..584785d1--- /dev/null+++ b/app/app/components/trns/reconcile.ts@@ -0,0 +1,55 @@+import type { Row } from '~~/services/powersync/transforms'++import { rowToTrn } from '~~/services/powersync/transforms'++import type { Trns } from '~/components/trns/types'++/** Build a fresh trns map from a full row snapshot (initial load). */+export function rowsToTrns(rows: Row[]): Trns | null {+ if (!rows.length)+ return null+ const map: Trns = {}+ for (const row of rows)+ map[row.id] = rowToTrn(row)+ return map+}++/**+ * Reconcile a full row snapshot from the watch against the previous item map.+ *+ * - Returns `prev` unchanged (same reference) when nothing changed, so the+ * caller can skip the update entirely - this suppresses the redundant rebuild+ * the watch fires as an echo of our own optimistic write.+ * - Otherwise returns a new map, reusing the previous object for every unchanged+ * row (matched on `updatedAt`) so the O(N) `rowToTrn` transform runs only for+ * rows that were actually added or changed.+ *+ * `updatedAt` reads deterministically (null -> 0, see transforms.ts), so even+ * rows without a timestamp compare stably and are correctly suppressed.+ */+export function reconcileTrns(prev: Trns, rows: Row[]): Trns | null {+ let dirty = rows.length !== Object.keys(prev).length+ if (!dirty) {+ for (const row of rows) {+ const existing = prev[row.id]+ if (!existing || existing.updatedAt !== Number(row.updatedAt)) {+ dirty = true+ break+ }+ }+ }+ if (!dirty)+ return prev++ if (!rows.length)+ return null++ const next: Trns = {}+ for (const row of rows) {+ const existing = prev[row.id]+ next[row.id] = existing && existing.updatedAt === Number(row.updatedAt)+ ? existing+ : rowToTrn(row)+ }+ return next+}diff --git a/app/app/components/trns/useTrnsStore.ts b/app/app/components/trns/useTrnsStore.tsindex e74ab57e..e824780b 100644--- a/app/app/components/trns/useTrnsStore.ts+++ b/app/app/components/trns/useTrnsStore.ts@@ -1,9 +1,8 @@-import type { ConvexClient } from 'convex/browser'-import type { FunctionReference } from 'convex/server'+import type { Row } from '~~/services/powersync/transforms'-import localforage from 'localforage'-import { convexTrnsToMap } from '~~/services/convex/api'-import { xorIdsHash } from '~~/utils/fnv1a'+import { watchTable } from '~~/services/powersync/db'+import { deleteRow, upsertRow } from '~~/services/powersync/mutations'+import { trnToRow } from '~~/services/powersync/transforms'import type { Range } from '~/components/date/types'import type { TrnId, TrnItem, TrnItemFull, Trns, TrnsGetterProps } from '~/components/trns/types'@@ -13,47 +12,31 @@ import { getEndOf, getStartOf } from '~/components/date/utils'import { useDemo } from '~/components/demo/useDemo'import { STORAGE_KEYS } from '~/components/offline/storageKeys'import { filterTrnsIds } from '~/components/trns/getTrns'+import { reconcileTrns, rowsToTrns } from '~/components/trns/reconcile'import { TrnType } from '~/components/trns/types'import { useWalletsStore } from '~/components/wallets/useWalletsStore'-import { createDebouncedPersist, handleMutationResult, isInFlight, isPersistBlocked, mergeOfflineOps, pushDeleteOp, pushSaveOp } from '~/composables/useStoreSync'+import { persistStoreCache } from '~/composables/useStoreCache'+import { createDebouncedPersist, showErrorToast } from '~/composables/useStoreSync'+import { useSupabaseAuth } from '~/composables/useSupabase'import { createLogger } from '~/utils/logger'-/** Shape returned by Convex paginated queries (has _id, _creationTime, userId + entity fields). */-type ConvexTrnDoc = { [key: string]: unknown, _creationTime: number, _id: string, userId: string }-const logger = createLogger('trns')-async function fetchAllPages<T>(- client: ConvexClient,- queryFn: FunctionReference<'query'>,- args: Record<string, unknown>,- pageSize = 5000,-): Promise<T[]> {- const allItems: T[] = []- let cursor: string | null = null- let isDone = false-- while (!isDone) {- const result: { continueCursor: string, isDone: boolean, page: T[] } | null = await client.query(queryFn, {- ...args,- paginationOpts: { cursor, numItems: pageSize },- })- if (!result)- return allItems- allItems.push(...result.page)- isDone = result.isDone- cursor = result.continueCursor- }-- return allItems-}+// trns is the largest table, so its watch coalesces more aggressively than the 30ms default;+// the optimistic write already updated the UI, so the delayed re-query echo is imperceptible.+const TRNS_WATCH_THROTTLE_MS = 120export const useTrnsStore = defineStore('trns', () => {const categoriesStore = useCategoriesStore()const walletsStore = useWalletsStore()const { isDemo } = useDemo()+ const { uid } = useSupabaseAuth()const items = shallowRef<Trns | null>(null)+ // True after the first local-SQLite emission; reset on (re)subscribe so a new user waits for theirs.+ const isLoaded = ref(false)++ let watchController: AbortController | null = nullfunction getStoreTrnsIds(props: TrnsGetterProps) {return filterTrnsIds({@@ -115,254 +98,77 @@ export const useTrnsStore = defineStore('trns', () => {const lastCreatedTrnItem = computed<TrnItem | undefined>(() => lastCreatedTrnId.value ? items.value?.[lastCreatedTrnId.value] : undefined)- type TrnsSyncMeta = {- idsHash: string- lastSyncedAt: number- }-- async function fullSync(retried = false): Promise<void> {- const { api, client } = useConvexClientWithApi()- const trns = await fetchAllPages<ConvexTrnDoc>(client, api.trns.list, {})- let data: Trns | null = trns.length ? convexTrnsToMap(trns) : null-- // Verify local hash against server + get server timestamp- const hashResult = await client.query(api.trns.idsHash, {}) as { hash: string, serverTime: number } | null- const localHash = xorIdsHash(trns.map(t => t._id))-- if (hashResult && localHash !== hashResult.hash) {- if (!retried) {- logger.log('fullSync hash mismatch, retrying')- return fullSync(true)- }- logger.log('fullSync hash still mismatched after retry, proceeding')- }-- const lastSyncedAt = hashResult?.serverTime ?? Date.now()-- if (data)- data = await mergeOfflineOps(data, 'trns')-- setTrns(data)+ const debouncedPersist = createDebouncedPersist<Trns | null>(STORAGE_KEYS.trns)- const syncMeta: TrnsSyncMeta = {- idsHash: hashResult?.hash ?? localHash,- lastSyncedAt,- }- if (!isPersistBlocked())- await localforage.setItem(STORAGE_KEYS.trnsSyncMeta, syncMeta)- logger.log(`full sync: ${trns.length} trns`)+ function setTrns(values: Trns | null) {+ items.value = values+ // Demo persists to localforage; real mode mirrors into the per-user cold-start blob+ // (PowerSync SQLite stays the source of truth).+ if (isDemo.value)+ debouncedPersist(values)+ else+ persistStoreCache('trns', values)}- async function deltaSync(syncMeta: TrnsSyncMeta, cachedTrns: Trns): Promise<void> {- const { api, client } = useConvexClientWithApi()-- const [changedTrns, hashResult] = await Promise.all([- fetchAllPages<ConvexTrnDoc>(client, api.trns.delta, { since: syncMeta.lastSyncedAt }),- client.query(api.trns.idsHash, {}) as Promise<{ hash: string, serverTime: number } | null>,- ])-- if (hashResult === null) {- setTrns(null)- await localforage.removeItem(STORAGE_KEYS.trnsSyncMeta)+ /** Cold-start paint: seed items from the snapshot before the watch emits (no-op once it has). */+ function primeFromCache(data: Trns | null): void {+ if (isDemo.value || !data || isLoaded.value)return- }-- const { hash: currentHash, serverTime } = hashResult-- let data: Trns = { ...cachedTrns }- if (changedTrns.length > 0) {- const changedMap = convexTrnsToMap(changedTrns)- data = { ...data, ...changedMap }- }-- const localHash = xorIdsHash(Object.keys(data).filter(id => !isLocalId(id)))- if (localHash !== currentHash) {- // Hash mismatch = deletions or missed changes → fallback to fullSync- logger.log('hash mismatch after delta, falling back to fullSync')- throw new Error('hash mismatch')- }-- data = await mergeOfflineOps(data, 'trns')-- setTrns(Object.keys(data).length > 0 ? data : null)-- // Update sync metadata (use server time to avoid client clock skew)- const newSyncMeta: TrnsSyncMeta = {- idsHash: currentHash,- lastSyncedAt: serverTime,- }- if (!isPersistBlocked())- await localforage.setItem(STORAGE_KEYS.trnsSyncMeta, newSyncMeta)- logger.log(`delta sync: ${changedTrns.length} changed`)+ items.value = data}- /**- * Apply a realtime delta patch from a server subscription. Returns the- * new `since` timestamp for the next subscription window, or null when- * caller should fall back to a fullSync (truncated or no items).- */- async function applyRealtimePatch(patch: { deletedIds: string[], docs: ConvexTrnDoc[], serverTime: number, truncated: boolean }): Promise<number | null> {- if (patch.truncated) {- logger.log('realtime delta truncated — running fullSync')- await fullSync()- return null- }-- const current = items.value ?? {}- const updated: Trns = { ...current }- let changed = false-- for (const doc of patch.docs) {- if (isInFlight(doc._id))- continue- const existing = updated[doc._id]- if (existing && typeof existing.updatedAt === 'number' && existing.updatedAt >= (doc.updatedAt as number))- continue- const { _creationTime: _ct, _id, userId: _u, ...rest } = doc- updated[_id] = rest as unknown as Trns[string]- changed = true- }-- for (const id of patch.deletedIds) {- if (isInFlight(id))- continue- if (id in updated) {- delete updated[id]- changed = true- }- }-- if (changed) {- setTrns(Object.keys(updated).length > 0 ? updated : null)- logger.log(`realtime: ${patch.docs.length} docs, ${patch.deletedIds.length} deletes`)- }-- const syncMeta: TrnsSyncMeta = {- idsHash: '',- lastSyncedAt: patch.serverTime,- }- const existingMeta = await localforage.getItem<TrnsSyncMeta>(STORAGE_KEYS.trnsSyncMeta)- if (existingMeta)- syncMeta.idsHash = existingMeta.idsHash- if (!isPersistBlocked())- await localforage.setItem(STORAGE_KEYS.trnsSyncMeta, syncMeta)-- return patch.serverTime- }-- async function initTrns() {- try {- const syncMeta = await localforage.getItem<TrnsSyncMeta>(STORAGE_KEYS.trnsSyncMeta)- const cachedTrns = await localforage.getItem<Trns>(STORAGE_KEYS.trns)-- if (syncMeta && cachedTrns) {- try {- await deltaSync(syncMeta, cachedTrns)- return- }- catch (e) {- logger.log('delta sync failed, falling back to full sync', e)- }- }-- // Ensure syncMeta row exists before fullSync so subsequent idsHash queries are O(1)- // Fire-and-forget: don't block fullSync if auth token isn't ready yet- const { api, client } = useConvexClientWithApi()- client.mutation(api.trns.ensureSyncMeta, {}).catch(() => {})-- await fullSync()- }- catch (e) {- logger.error('init failed', e)- }- }-- const debouncedPersist = createDebouncedPersist<Trns | null>(STORAGE_KEYS.trns)-- function setTrns(values: Trns | null) {- items.value = values- debouncedPersist(values)+ /** Real mode: subscribe to local SQLite. Fires immediately and on every sync/local write. */+ function initTrns(): void {+ if (isDemo.value)+ return+ watchController?.abort()+ isLoaded.value = false // re-subscribe (e.g. different user) waits for a fresh emission+ watchController = watchTable<Row>('SELECT * FROM trns', [], (rows) => {+ isLoaded.value = true+ const prev = items.value+ const next = prev ? reconcileTrns(prev, rows) : rowsToTrns(rows)+ // reconcileTrns returns `prev` (same ref) when nothing changed - skip the rebuild+ // (this is the echo of our own optimistic write).+ if (next !== prev)+ setTrns(next)+ }, TRNS_WATCH_THROTTLE_MS)+ logger.log('watching trns')}function saveTrn({ id, values }: { id: TrnId, values: TrnItem }) {- const valuesWithEditDate = {- ...values,- updatedAt: Date.now(),- }-- // Check before setTrns so the new id isn't already in the store- // Frontend IDs are always treated as new creates (server generates real ID)- const isExisting = !isLocalId(id) && items.value && id in items.value+ const valuesWithEditDate = { ...values, updatedAt: Date.now() }+ const prev = items.value+ // Optimistic update (instant UI). In real mode the watch re-emits the same shape.setTrns({ ...(items.value ?? {}), [id]: valuesWithEditDate })- if (!pushSaveOp({ entity: 'trns', id, isDemo: !!isDemo.value, isExisting: !!isExisting, values }))+ if (isDemo.value)return- const { api, client } = useConvexClientWithApi()- const action = isExisting ? 'update' : 'create'-- const base = {- date: valuesWithEditDate.date,- desc: valuesWithEditDate.desc || undefined,- type: valuesWithEditDate.type,- }-- const trnData = values.type === TrnType.Transfer- ? {- ...base,- categoryId: 'transfer' as const,- expenseAmount: values.expenseAmount,- expenseWalletId: asConvexId<'wallets'>(values.expenseWalletId),- incomeAmount: values.incomeAmount,- incomeWalletId: asConvexId<'wallets'>(values.incomeWalletId),- }- : {- ...base,- amount: values.amount,- categoryId: values.categoryId === 'adjustment'- ? 'adjustment' as const- : asConvexId<'categories'>(values.categoryId),- walletId: asConvexId<'wallets'>(values.walletId),- }-- const mutation = isExisting- ? client.mutation(api.trns.update, { id: asConvexId<'trns'>(id), ...trnData })- : client.mutation(api.trns.create, trnData)-- return handleMutationResult({- action,- entity: 'trns',- errorMessage: 'trns.errors.saveFailed',- id,- items,- mutation,-+ upsertRow('trns', id, trnToRow(valuesWithEditDate, uid.value ?? '')).catch((e) => {+ setTrns(prev) // roll back the optimistic update if the local write failed+ logger.error('saveTrn failed', e)+ showErrorToast('trns.errors.saveFailed')})}function deleteTrn(id: TrnId) {- // Optimistic UI+ const prev = items.valueconst trns = { ...(items.value ?? {}) }delete trns[id]setTrns(trns)- if (!pushDeleteOp({ entity: 'trns', id, isDemo: !!isDemo.value }))+ if (isDemo.value)return- const { api, client } = useConvexClientWithApi()- return handleMutationResult({- action: 'delete',- entity: 'trns',- errorMessage: 'trns.errors.deleteFailed',- id,- items,- mutation: client.mutation(api.trns.remove, { id: asConvexId<'trns'>(id) }),-+ deleteRow('trns', id).catch((e) => {+ setTrns(prev) // restore the deleted trn if the local write failed+ logger.error('deleteTrn failed', e)+ showErrorToast('trns.errors.deleteFailed')})}- /** Remove trns from store only. Does NOT fire mutations or push to offline queue. */+ /** Remove trns from the in-memory store only (used when a wallet/category is deleted). */function removeTrnsFromStore(trnsIds: TrnId[]) {if (!items.value)return@@ -434,15 +240,16 @@ export const useTrnsStore = defineStore('trns', () => {}return {- applyRealtimePatch,computeTrnItem,deleteTrn,getRange,getStoreTrnsIds,hasItems,initTrns,+ isLoaded,items,lastCreatedTrnItem,+ primeFromCache,removeTrnsFromStore,saveTrn,setTrns,diff --git a/app/app/components/ui/ContextMenuMy.vue b/app/app/components/ui/ContextMenuMy.vueindex cc72545d..822d2018 100644--- a/app/app/components/ui/ContextMenuMy.vue+++ b/app/app/components/ui/ContextMenuMy.vue@@ -65,7 +65,7 @@ const appConfig = useAppConfig()const ui = computed(() => tv({extend: tv(theme as any),...(appConfig as any).ui?.contextMenu || {},-})({ size: props.size }))+})({ size: props.size } as any) as any)</script><template>diff --git a/app/app/components/user/useUserStore.ts b/app/app/components/user/useUserStore.tsindex e30d5501..0147bd7d 100644--- a/app/app/components/user/useUserStore.ts+++ b/app/app/components/user/useUserStore.ts@@ -1,20 +1,22 @@+import type { Row } from '~~/services/powersync/transforms'+import localforage from 'localforage'+import { disconnectPowerSync, usePowerSyncDb, watchTable } from '~~/services/powersync/db'+import { upsertRow } from '~~/services/powersync/mutations'import type { CurrencyCode } from '~/components/currencies/types'import type { LocaleSlug } from '~/components/locale/types'import { useCategoriesStore } from '~/components/categories/useCategoriesStore'import { useDemo } from '~/components/demo/useDemo'-import { getOfflineOpsByEntity, pushOfflineOp } from '~/components/offline/helpers'-import { isReplaying } from '~/components/offline/replay'import { STORAGE_KEYS } from '~/components/offline/storageKeys'import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'import { useTrnsStore } from '~/components/trns/useTrnsStore'-import { userSettingsSchema } from '~/components/user/types'import { useWalletsStore } from '~/components/wallets/useWalletsStore'-import { clearAuthCookie, hasAuthCookie, setSessionInitialized } from '~/composables/useAuthCookie'-import { stopAllRealtime } from '~/composables/useRealtimeSync'-import { blockPersist, handleMutationResult, isPersistBlocked } from '~/composables/useStoreSync'+import { hasPersistedSession } from '~/composables/useAuthSession'+import { clearStoreCache, persistStoreCache } from '~/composables/useStoreCache'+import { blockPersist, isPersistBlocked } from '~/composables/useStoreSync'+import { useSupabaseAuth } from '~/composables/useSupabase'import { createLogger } from '~/utils/logger'export type User = {@@ -24,11 +26,17 @@ export type User = {uid: string}+/** The 'user' slice of the cold-start snapshot (identity + settings) - see useStoreCache. */+export type UserSettingsCache = {+ baseCurrency?: CurrencyCode+ locale?: LocaleSlug+ user?: User | null+}+const logger = createLogger('user')export const useUserStore = defineStore('user', () => {- const authClient = useAuth()- const session = authClient.useSession()+ const { session, signOut: supabaseSignOut, user: authUser } = useSupabaseAuth()const walletsStore = useWalletsStore()const categoriesStore = useCategoriesStore()const trnsStore = useTrnsStore()@@ -38,18 +46,18 @@ export const useUserStore = defineStore('user', () => {const baseCurrency = ref<CurrencyCode>('USD')const locale = ref<LocaleSlug>('en')+ let watchController: AbortController | null = null+const currentUser = computed<User | null>(() => {- const s = session.value- const sessionUser = s?.data?.user- if (sessionUser) {+ if (authUser.value) {return {- displayName: sessionUser.name,- email: sessionUser.email,- photoURL: sessionUser.image,- uid: sessionUser.id,+ displayName: authUser.value.email,+ email: authUser.value.email,+ photoURL: null,+ uid: authUser.value.id,}}- if (user.value && !isDemo.value && hasAuthCookie())+ if (user.value && !isDemo.value && hasPersistedSession())return user.valuereturn null})@@ -66,21 +74,26 @@ export const useUserStore = defineStore('user', () => {}: null- if (!isPersistBlocked())- localforage.setItem(STORAGE_KEYS.user, user.value ? { ...user.value } : null)+ // Demo persists the user to its own localforage key; real mode mirrors into the cold-start snapshot.+ if (isDemo.value) {+ if (!isPersistBlocked())+ localforage.setItem(STORAGE_KEYS.user, user.value ? { ...user.value } : null)+ }+ else {+ persistUserCache()+ }}- // Persist session user to cache on resolution so next reload has `user` synchronously.- // Skipped in demo mode to avoid leaking real-auth session into demo's cleared cache.+ // Keep `user.value` in sync with the resolved session (real mode only; demo manages its own user).watch(- () => session.value?.data?.user,+ () => session.value?.user,(sessionUser) => {if (!sessionUser || isSigningOut.value || isDemo.value)returnconst next: User = {- displayName: sessionUser.name,+ displayName: sessionUser.email,email: sessionUser.email,- photoURL: sessionUser.image,+ photoURL: null,uid: sessionUser.id,}if (user.value?.uid === next.uid@@ -97,10 +110,41 @@ export const useUserStore = defineStore('user', () => {function persistUserSettings() {if (isPersistBlocked())return- localforage.setItem(STORAGE_KEYS.userSettings, {+ if (isDemo.value) {+ localforage.setItem(STORAGE_KEYS.userSettings, {+ baseCurrency: baseCurrency.value,+ locale: locale.value,+ })+ return+ }+ // Real mode: mirror settings into the per-user cold-start snapshot.+ persistUserCache()+ }++ /** Write the 'user' snapshot slice (identity + settings) for the next cold start. */+ function persistUserCache() {+ if (isDemo.value)+ return+ // toRaw: IndexedDB can't structure-clone a Vue proxy, so persist the plain target.+ persistStoreCache('user', {baseCurrency: baseCurrency.value,locale: locale.value,- })+ user: toRaw(user.value),+ } satisfies UserSettingsCache)+ }++ /** Cold-start paint: seed identity + settings from the snapshot before the user_settings watch emits. */+ function primeFromCache(data: UserSettingsCache | null): void {+ if (isDemo.value || !data)+ return+ if (data.user && !user.value)+ user.value = data.user+ if (data.baseCurrency)+ baseCurrency.value = data.baseCurrency+ if (data.locale && data.locale !== locale.value) {+ locale.value = data.locale+ useNuxtApp().$i18n.setLocale(data.locale)+ }}function setUserBaseCurrency(value: CurrencyCode) {@@ -114,17 +158,12 @@ export const useUserStore = defineStore('user', () => {if (isDemo.value || !uid.value)return- logger.log(`optimistic update: baseCurrency → ${value}`)- if (!isReplaying())- pushOfflineOp({ data: { baseCurrency: value }, entity: 'userSettings', id: 'settings', type: 'update' })-- const { api, client } = useConvexClientWithApi()- handleMutationResult({- action: 'update',- entity: 'userSettings',- errorMessage: 'settings.errors.saveFailed',- id: 'settings',- mutation: client.mutation(api.user.upsert, { baseCurrency: value }),+ upsertRow('user_settings', uid.value, {+ baseCurrency: value,+ locale: locale.value,+ userId: uid.value,+ }).catch((e) => {+ logger.error('saveUserBaseCurrency failed', e)})}@@ -140,84 +179,42 @@ export const useUserStore = defineStore('user', () => {if (isDemo.value || !uid.value)return- logger.log(`optimistic update: locale → ${value}`)- if (!isReplaying())- pushOfflineOp({ data: { locale: value }, entity: 'userSettings', id: 'settings', type: 'update' })-- const { api, client } = useConvexClientWithApi()- handleMutationResult({- action: 'update',- entity: 'userSettings',- errorMessage: 'settings.errors.saveFailed',- id: 'settings',- mutation: client.mutation(api.user.upsert, { locale: value }),+ upsertRow('user_settings', uid.value, {+ baseCurrency: baseCurrency.value,+ locale: value,+ userId: uid.value,+ }).catch((e) => {+ logger.error('saveUserLocale failed', e)})}- function applyRealtimeSettings(settings: unknown): void {- if (!settings)+ /** Real mode: subscribe to the user's settings row in local SQLite. */+ function initUserSettings(): void {+ if (isDemo.value)return- const parsed = userSettingsSchema.safeParse(settings)- if (!parsed.success)- return- if (parsed.data.baseCurrency !== baseCurrency.value) {- baseCurrency.value = parsed.data.baseCurrency- persistUserSettings()- }- if (parsed.data.locale && parsed.data.locale !== locale.value) {- locale.value = parsed.data.locale- useNuxtApp().$i18n.setLocale(parsed.data.locale)- persistUserSettings()- }- }- async function initUserSettings() {- try {- const { api, client } = useConvexClientWithApi()-- const settings = await client.query(api.user.get, {})- if (!settings)+ watchController?.abort()+ watchController = watchTable<Row>('SELECT * FROM user_settings LIMIT 1', [], (rows) => {+ const s = rows[0]+ if (!s)return-- const parsed = userSettingsSchema.safeParse(settings)- if (parsed.success) {- baseCurrency.value = parsed.data.baseCurrency- if (parsed.data.locale) {- locale.value = parsed.data.locale- useNuxtApp().$i18n.setLocale(parsed.data.locale)- }- }-- const pendingOps = await getOfflineOpsByEntity('userSettings')- const partialSchema = userSettingsSchema.partial()- for (const op of pendingOps) {- const parsedOp = partialSchema.safeParse(op.data)- if (!parsedOp.success)- continue- if (parsedOp.data.baseCurrency)- baseCurrency.value = parsedOp.data.baseCurrency- if (parsedOp.data.locale) {- locale.value = parsedOp.data.locale- useNuxtApp().$i18n.setLocale(parsedOp.data.locale)- }+ if (s.baseCurrency)+ baseCurrency.value = s.baseCurrency+ if (s.locale && s.locale !== locale.value) {+ locale.value = s.locale+ useNuxtApp().$i18n.setLocale(s.locale)}-persistUserSettings()- }- catch (e) {- logger.error('init user settings failed', e)- }+ })+ logger.log('watching user settings')}async function signOut() {isSigningOut.value = true- stopAllRealtime()if (isDemo.value) {await localforage.clear()isDemo.value = undefined- clearAuthCookie()- setSessionInitialized(false)useCookie<boolean>('finapp.isOnboarded').value = falsewindow.location.href = '/login'return@@ -233,18 +230,19 @@ export const useUserStore = defineStore('user', () => {useTrnsFormStore().$reset()setUser(null)- clearAuthCookie()- setSessionInitialized(false)useCookie<boolean>('finapp.isOnboarded').value = false- const offlineKeys: Set<string> = new Set([STORAGE_KEYS.offlineQueue, STORAGE_KEYS.offlineQueueUserId])await Promise.all(- Object.values(STORAGE_KEYS)- .filter(key => !offlineKeys.has(key))- .map(key => localforage.removeItem(key)),+ Object.values(STORAGE_KEYS).map(key => localforage.removeItem(key)),)+ await clearStoreCache() // session still present here, so the uid resolves- await authClient.signOut()+ // Best-effort local wipe; if it fails the owner marker makes the next foreign sign-in wipe first.+ const cleared = await disconnectPowerSync()+ if (!cleared)+ logger.warn('local data not cleared on sign-out; will wipe on next foreign sign-in')++ await supabaseSignOut()}catch (error) {logger.error('signOut failed:', error)@@ -253,8 +251,6 @@ export const useUserStore = defineStore('user', () => {isSigningOut.value = false}- localStorage.removeItem('better-auth_cookie')- localStorage.removeItem('better-auth_session_data')window.location.href = '/login'}@@ -268,24 +264,31 @@ export const useUserStore = defineStore('user', () => {useCookie<boolean>('finapp.isOnboarded').value = false- const { clearOfflineQueue, setOfflineQueueUserId } = await import('~/components/offline/helpers')- await clearOfflineQueue()-- setOfflineQueueUserId(uid.value)+ if (isDemo.value) {+ await localforage.clear()+ return+ }- if (!isDemo.value) {- const { api, client } = useConvexClientWithApi()- await client.action(api.user.removeAllUserData, {})+ try {+ const db = usePowerSyncDb()+ await db.execute('DELETE FROM trns')+ await db.execute('DELETE FROM categories')+ await db.execute('DELETE FROM wallets')+ await db.execute('DELETE FROM user_settings')+ await clearStoreCache()+ }+ catch (e) {+ logger.error('removeAllUserData failed', e)}}return {- applyRealtimeSettings,baseCurrency,currentUser,initUserSettings,isSigningOut,locale,+ primeFromCache,removeAllUserData,saveUserBaseCurrency,saveUserLocale,diff --git a/app/app/components/wallets/EditModal.vue b/app/app/components/wallets/EditModal.vueindex db139224..652f2dc0 100644--- a/app/app/components/wallets/EditModal.vue+++ b/app/app/components/wallets/EditModal.vue@@ -16,7 +16,7 @@ const { t } = useI18n()const walletsStore = useWalletsStore()const wallet = computed(() =>- props.walletId ? walletsStore.items[props.walletId] : undefined,+ props.walletId ? walletsStore.items?.[props.walletId] : undefined,)const walletForm = ref(wallet.valuediff --git a/app/app/components/wallets/page/id/Edit.vue b/app/app/components/wallets/page/id/Edit.vueindex 79f00506..836a0a3a 100644--- a/app/app/components/wallets/page/id/Edit.vue+++ b/app/app/components/wallets/page/id/Edit.vue@@ -13,11 +13,28 @@ const walletsStore = useWalletsStore()const walletId = computed(() => route.params.id) as Ref<WalletId>const wallet = computed(() => walletsStore.items?.[walletId.value])-if (!wallet.value) {- router.replace('/wallets')-}+const walletForm = ref<WalletItem | undefined>(+ wallet.value ? walletItemSchema.parse(wallet.value) : undefined,+)-const walletForm = ref(wallet.value ? walletItemSchema.parse(wallet.value) : undefined)+// On a hard reload of /wallets/{id}/edit the store is still empty for a tick, so+// redirecting synchronously would bounce a valid id to the list (hydration race).+// `items` is null until at least one wallet has loaded, so wait for it: seed the+// form once the wallet appears, and only redirect once the store has hydrated+// (items truthy) but this id is genuinely absent.+watch(+ () => walletsStore.items,+ (items) => {+ if (wallet.value) {+ if (!walletForm.value)+ walletForm.value = walletItemSchema.parse(wallet.value)+ }+ else if (items) {+ router.replace('/wallets')+ }+ },+ { immediate: true },+)function updateField(key: keyof WalletItem, value: WalletItem[keyof WalletItem]) {if (walletForm.value)@@ -31,7 +48,7 @@ function onAfterSave() {navigateAfterSave(router, `/wallets/${walletId.value}`)}-useHead({ title: `${t('base.edit')}: ${walletForm.value?.name || t('wallets.form.name.label')}` })+useHead({ title: computed(() => `${t('base.edit')}: ${walletForm.value?.name || t('wallets.form.name.label')}`) })</script><template>diff --git a/app/app/components/wallets/useWalletsStore.ts b/app/app/components/wallets/useWalletsStore.tsindex 3166eda1..0d33ce6a 100644--- a/app/app/components/wallets/useWalletsStore.ts+++ b/app/app/components/wallets/useWalletsStore.ts@@ -1,4 +1,8 @@-import { convexWalletsToMap } from '~~/services/convex/api'+import type { Row } from '~~/services/powersync/transforms'++import { watchTable } from '~~/services/powersync/db'+import { deleteRow, upsertRow, upsertRows } from '~~/services/powersync/mutations'+import { rowToWallet, walletToRow } from '~~/services/powersync/transforms'import { uniqueElementsBy } from '~~/utils/simple'import type { CurrencyCode } from '~/components/currencies/types'@@ -8,92 +12,70 @@ import type { WalletId, WalletItem, WalletItemComputed, Wallets, WalletsComputedimport { getAmountInRate, getWalletsTotals } from '~/components/amount/getTotal'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'import { useDemo } from '~/components/demo/useDemo'-import { pushOfflineOp } from '~/components/offline/helpers'-import { isReplaying } from '~/components/offline/replay'import { STORAGE_KEYS } from '~/components/offline/storageKeys'import { TrnType } from '~/components/trns/types'import { useTrnsStore } from '~/components/trns/useTrnsStore'import { useUserStore } from '~/components/user/useUserStore'-import { createDebouncedPersist, handleMutationResult, isInFlight, mergeOfflineOps, pushDeleteOp, pushSaveOp } from '~/composables/useStoreSync'+import { persistStoreCache } from '~/composables/useStoreCache'+import { createDebouncedPersist, showErrorToast } from '~/composables/useStoreSync'+import { useSupabaseAuth } from '~/composables/useSupabase'import { createLogger } from '~/utils/logger'const logger = createLogger('wallets')+function rowsToWallets(rows: Row[]): Wallets | null {+ if (!rows.length)+ return null+ const map: Wallets = {}+ for (const row of rows)+ map[row.id] = rowToWallet(row)+ return map+}+export const useWalletsStore = defineStore('wallets', () => {const trnsStore = useTrnsStore()const currenciesStore = useCurrenciesStore()const { isDemo } = useDemo()+ const { uid } = useSupabaseAuth()const items = shallowRef<Wallets | null>(null)const hasItems = computed(() => Object.keys(items.value ?? {}).length > 0)- /** In-memory only — survives for the app session. Reset on each initWallets. */- const lastSyncedAt = ref(0)+ // True after the first local-SQLite emission; drives the onboarding gate. Reset on+ // (re)subscribe so a new user waits for theirs. Demo skips the watch (see useInitApp).+ const isLoaded = ref(false)- async function initWallets() {- try {- const { api, client } = useConvexClientWithApi()- const wallets = await client.query(api.wallets.list, {})- let data: Wallets | null = wallets?.length ? convexWalletsToMap(wallets) : null+ let watchController: AbortController | null = null- if (data)- data = await mergeOfflineOps(data, 'wallets')+ const debouncedPersist = createDebouncedPersist<Wallets | null>(STORAGE_KEYS.wallets)- setWallets(data)- lastSyncedAt.value = Date.now()- }- catch (e) {- logger.error('init failed', e)- }+ function setWallets(values: Wallets | null) {+ items.value = values+ // Demo persists to localforage; real mode mirrors into the per-user cold-start blob+ // (PowerSync SQLite stays the source of truth).+ if (isDemo.value)+ debouncedPersist(values)+ else+ persistStoreCache('wallets', values)}- type ConvexWalletDoc = { [key: string]: unknown, _creationTime: number, _id: string, userId: string }-- function applyRealtimePatch(patch: { deletedIds: string[], docs: ConvexWalletDoc[], serverTime: number, truncated: boolean }): number | null {- if (patch.truncated) {- logger.log('realtime delta truncated — running initWallets')- initWallets()- return null- }-- const current = items.value ?? {}- const updated: Wallets = { ...current }- let changed = false-- for (const doc of patch.docs) {- if (isInFlight(doc._id))- continue- const existing = updated[doc._id]- const existingUpdatedAt = existing?.updatedAt- const docUpdatedAt = typeof doc.updatedAt === 'number' ? doc.updatedAt : 0- if (existing && typeof existingUpdatedAt === 'number' && existingUpdatedAt >= docUpdatedAt)- continue- const { _creationTime: _ct, _id, userId: _u, ...rest } = doc- updated[_id] = rest as unknown as WalletItem- changed = true- }-- for (const id of patch.deletedIds) {- if (isInFlight(id))- continue- if (id in updated) {- delete updated[id]- changed = true- }- }-- if (changed) {- setWallets(updated)- logger.log(`realtime: ${patch.docs.length} docs, ${patch.deletedIds.length} deletes`)- }- lastSyncedAt.value = patch.serverTime- return patch.serverTime+ /** Cold-start paint from the per-user snapshot before the SQLite watch emits. See trns store. */+ function primeFromCache(data: Wallets | null): void {+ if (isDemo.value || !data || isLoaded.value)+ return+ items.value = data}- const debouncedPersist = createDebouncedPersist<Wallets | null>(STORAGE_KEYS.wallets)-- function setWallets(values: Wallets | null) {- items.value = values- debouncedPersist(values)+ /** Real mode: subscribe to local SQLite. Fires immediately and on every sync/local write. */+ function initWallets(): void {+ if (isDemo.value)+ return+ watchController?.abort()+ isLoaded.value = false // re-subscribe (e.g. different user) waits for a fresh emission+ watchController = watchTable<Row>('SELECT * FROM wallets', [], (rows) => {+ setWallets(rowsToWallets(rows))+ isLoaded.value = true+ })+ logger.log('watching wallets')}function saveWallet({ id, values }: { id: WalletId, values: WalletItem }) {@@ -101,11 +83,10 @@ export const useWalletsStore = defineStore('wallets', () => {if (!hasItems.value)useUserStore().saveUserBaseCurrency(values.currency)- // Check before optimistic update so the new id isn't already in the store- // Frontend IDs are always treated as new creates (server generates real ID)- const isExisting = !isLocalId(id) && items.value && id in items.value+ // A new wallet is one whose id isn't already in the store.+ const isNew = !(items.value && id in items.value)- if (!isExisting) {+ if (isNew) {const maxOrder = Object.values(items.value ?? {}).reduce((max, w) => Math.max(max, w.order ?? 0),-1,@@ -113,46 +94,26 @@ export const useWalletsStore = defineStore('wallets', () => {values = { ...values, order: maxOrder + 1 }}+ const prev = items.value++ // Optimistic update (instant UI). In real mode the watch re-emits the same shape.setWallets({...(items.value ?? {}),[id]: values,})- if (!pushSaveOp({ entity: 'wallets', id, isDemo: !!isDemo.value, isExisting: !!isExisting, values }))+ if (isDemo.value)return- const { api, client } = useConvexClientWithApi()- const action = isExisting ? 'update' : 'create'-- const walletData = {- color: values.color,- creditLimit: 'creditLimit' in values ? values.creditLimit : undefined,- currency: values.currency,- desc: values.desc || undefined,- isArchived: values.isArchived,- isExcludeInTotal: values.isExcludeInTotal,- isWithdrawal: values.isWithdrawal,- name: values.name,- order: values.order,- type: values.type,- }-- const mutation = isExisting- ? client.mutation(api.wallets.update, { id: asConvexId<'wallets'>(id), ...walletData })- : client.mutation(api.wallets.create, walletData)-- return handleMutationResult({- action,- entity: 'wallets',- errorMessage: 'wallets.errors.saveFailed',- id,- items,- mutation,-+ upsertRow('wallets', id, walletToRow(values, uid.value ?? '')).catch((e) => {+ setWallets(prev) // roll back the optimistic update if the local write failed+ logger.error('saveWallet failed', e)+ showErrorToast('wallets.errors.saveFailed')})}function saveWalletsOrder(ids: WalletId[]) {+ const prev = items.valueconst updated = { ...(items.value ?? {}) } as Walletsfor (let i = 0; i < ids.length; i++) {const walletId = ids[i]!@@ -164,28 +125,18 @@ export const useWalletsStore = defineStore('wallets', () => {if (isDemo.value)return- // Save to offline queue immediately (skip during replay)- logger.log('optimistic update: order')- if (!isReplaying()) {- for (const id of ids) {- if (updated[id])- pushOfflineOp({ data: updated[id], entity: 'wallets', id, type: 'update' })- }- }-- const { api, client } = useConvexClientWithApi()-- return handleMutationResult({- action: 'update',- entity: 'wallets',- errorMessage: 'wallets.errors.orderFailed',- id: ids,- mutation: client.mutation(api.wallets.updateOrder, {- orders: ids.map((walletId, index) => ({- id: asConvexId<'wallets'>(walletId),- order: index,+ upsertRows(+ 'wallets',+ ids+ .filter(walletId => items.value?.[walletId])+ .map((walletId, index) => ({+ id: walletId,+ row: walletToRow({ ...items.value![walletId]!, order: index }, uid.value ?? ''),})),- }),+ ).catch((e) => {+ setWallets(prev) // restore the previous order if the local write failed+ logger.error('saveWalletsOrder failed', e)+ showErrorToast('wallets.errors.orderFailed')})}@@ -232,7 +183,7 @@ export const useWalletsStore = defineStore('wallets', () => {.filter(id => items.value?.[id])})- // O(N) single pass over all trns — replaces O(W×N) per-wallet getWalletTotal+ // Wallet totals in a single pass over all trns.const walletTotals = computed(() =>getWalletsTotals({trnsItems: trnsStore.items ?? {},@@ -261,7 +212,9 @@ export const useWalletsStore = defineStore('wallets', () => {const currenciesUsed = computed<CurrencyCode[]>(() => uniqueElementsBy(itemsComputed.value, 'currency'))- function deleteWallet(id: WalletId, trnsIds?: TrnId[]) {+ async function deleteWallet(id: WalletId, trnsIds?: TrnId[]) {+ const prevWallets = items.value+ const prevTrns = trnsStore.itemsconst wallets = { ...(items.value ?? {}) }delete wallets[id]setWallets(wallets)@@ -269,30 +222,35 @@ export const useWalletsStore = defineStore('wallets', () => {if (trnsIds?.length)trnsStore.removeTrnsFromStore(trnsIds)- if (!pushDeleteOp({ entity: 'wallets', id, isDemo: !!isDemo.value }))+ if (isDemo.value)return- const { api, client } = useConvexClientWithApi()- return handleMutationResult({- action: 'delete',- entity: 'wallets',- errorMessage: 'wallets.errors.deleteFailed',- id,- items,- mutation: client.action(api.wallets.remove, { id: asConvexId<'wallets'>(id) }),-- })+ // Real mode: the wallet's transactions must also be deleted from the DB,+ // otherwise the trns watch would re-add them after the optimistic removal.+ try {+ await Promise.all([+ deleteRow('wallets', id),+ ...(trnsIds ?? []).map(trnId => deleteRow('trns', trnId)),+ ])+ }+ catch (e) {+ // Roll back the wallet and its cascaded trns if the local write failed.+ setWallets(prevWallets)+ trnsStore.setTrns(prevTrns)+ logger.error('deleteWallet failed', e)+ showErrorToast('wallets.errors.deleteFailed')+ }}return {- applyRealtimePatch,currenciesUsed,deleteWallet,hasItems,initWallets,+ isLoaded,items,itemsComputed,- lastSyncedAt,+ primeFromCache,recentWalletIds,saveWallet,saveWalletsOrder,diff --git a/app/app/composables/useStoreCache.ts b/app/app/composables/useStoreCache.tsnew file mode 100644index 00000000..b90c718c--- /dev/null+++ b/app/app/composables/useStoreCache.ts@@ -0,0 +1,71 @@+import { debounce } from 'es-toolkit'+import localforage from 'localforage'++import { getPersistedUid } from '~/composables/useAuthSession'+import { isPersistBlocked } from '~/composables/useStoreSync'+import { createLogger } from '~/utils/logger'++// Per-user localforage snapshot of the watch-driven stores, read at cold start to paint the+// dashboard from the last session before PowerSync's db.init + first query scan finish; the live+// watches then reconcile to SQLite truth. One blob = a single IndexedDB read of an internally+// consistent snapshot. Stores toRaw() reactive refs first (IndexedDB can't clone a Vue proxy).+// Keyed by uid so users never read each other's snapshot. Demo mode uses its own cache.++const logger = createLogger('cache')++export type CacheSlice = 'categories' | 'rates' | 'trns' | 'user' | 'wallets'++export type StoreSnapshot = Partial<Record<CacheSlice, unknown>>++// In-memory accumulator of this session's latest slice values. The debounced write merges it+// over the on-disk blob (read-modify-write) so a single-slice write never drops other slices.+const snapshot: StoreSnapshot = {}++function cacheKey(uid: string): string {+ return `finapp.cache.${uid}`+}++/** Read the current user's whole snapshot. Null when absent or no session. */+export async function readStoreCache(): Promise<StoreSnapshot | null> {+ const uid = getPersistedUid()+ if (!uid)+ return null+ try {+ return await localforage.getItem<StoreSnapshot>(cacheKey(uid))+ }+ catch (e) {+ logger.error('read err', e)+ return null+ }+}++let persist: (() => void) | null = null++/** Update one slice and persist the snapshot (debounced, per-user). No-op while persist is blocked. */+export function persistStoreCache(slice: CacheSlice, data: unknown): void {+ if (isPersistBlocked() || !getPersistedUid())+ return+ snapshot[slice] = data+ if (!persist) {+ persist = debounce(() => {+ const uid = getPersistedUid()+ if (!uid)+ return+ // Read-modify-write: merge this session's touched slices over what's on disk.+ void localforage.getItem<StoreSnapshot>(cacheKey(uid))+ .then(existing => localforage.setItem(cacheKey(uid), { ...existing, ...snapshot }))+ .catch(e => logger.error('WRITE err', e))+ }, 400)+ }+ persist()+}++/** Remove a user's snapshot (sign-out / wipe). Defaults to the current session uid. */+export async function clearStoreCache(uid?: string | null): Promise<void> {+ for (const key of Object.keys(snapshot))+ delete snapshot[key as CacheSlice]+ const target = uid ?? getPersistedUid()+ if (!target)+ return+ await localforage.removeItem(cacheKey(target)).catch(() => {})+}diff --git a/app/app/composables/useStoreSync.ts b/app/app/composables/useStoreSync.tsindex e7eccdd7..701b1a4e 100644--- a/app/app/composables/useStoreSync.ts+++ b/app/app/composables/useStoreSync.ts@@ -1,18 +1,10 @@-import type { ShallowRef } from 'vue'-import { debounce } from 'es-toolkit'import localforage from 'localforage'-import type { EntityType } from '~/components/offline/types'-import { errorEmo, random, successEmo, warningEmo } from '~/assets/js/emo'-import { getOfflineOpsByEntity, pushOfflineOp, removeOfflineOp, removeOfflineOps } from '~/components/offline/helpers'-import { isReplaying } from '~/components/offline/replay'-import { STORAGE_KEYS } from '~/components/offline/storageKeys'-import { createLogger } from '~/utils/logger'--const logger = createLogger('store-sync')+// Persistence to localforage is only used by demo mode (real mode persists via+// PowerSync's local SQLite). blockPersist guards writes during sign-out cleanup.let _persistBlocked = falseexport function blockPersist(): void {@@ -27,23 +19,6 @@ export function isPersistBlocked(): boolean {return _persistBlocked}-// Tracks ids of mutations currently being confirmed by the server. Used by-// the realtime-sync layer to suppress self-echo: subscription updates whose-// id is in-flight are skipped so the origin device doesn't apply its own change twice.-const _inFlightOps = new Set<string>()--export function trackInFlight(id: string): void {- _inFlightOps.add(id)-}--export function untrackInFlight(id: string): void {- _inFlightOps.delete(id)-}--export function isInFlight(id: string): boolean {- return _inFlightOps.has(id)-}-export function createDebouncedPersist<T>(storageKey: string) {return debounce((values: T) => {if (_persistBlocked)@@ -52,141 +27,6 @@ export function createDebouncedPersist<T>(storageKey: string) {}, 300)}-export function pushSaveOp<T extends Record<string, unknown>>(opts: {- entity: EntityType- id: string- isDemo: boolean- isExisting: boolean- values: T-}): boolean {- if (opts.isDemo)- return false-- const action = opts.isExisting ? 'update' : 'create'- logger.log(`optimistic ${action}: ${opts.id}`)- if (!isReplaying())- pushOfflineOp({ data: opts.values, entity: opts.entity, id: opts.id, type: action })-- return true-}--export function pushDeleteOp(opts: {- entity: EntityType- id: string- isDemo: boolean-}): boolean {- if (opts.isDemo)- return false-- logger.log(`optimistic delete: ${opts.id}`)- if (!isReplaying())- pushOfflineOp({ entity: opts.entity, id: opts.id, type: 'delete' })-- return true-}--export async function mergeOfflineOps<T>(- data: Record<string, T>,- entity: EntityType,-): Promise<Record<string, T>> {- const pendingOps = await getOfflineOpsByEntity(entity)-- const pendingUpdates: Record<string, T> = {}- const pendingDeleteIds: string[] = []-- for (const op of pendingOps) {- if (op.type === 'delete')- pendingDeleteIds.push(op.id)- else if (op.data)- pendingUpdates[op.id] = op.data as unknown as T- }-- const hasUpdates = Object.keys(pendingUpdates).length > 0- const hasDeletes = pendingDeleteIds.length > 0-- if (hasUpdates || hasDeletes) {- const merged = { ...data }- for (const id of Object.keys(pendingUpdates))- merged[id] = pendingUpdates[id]!- for (const id of pendingDeleteIds)- delete merged[id]- data = merged- logger.log(`init: merged ${Object.keys(pendingUpdates).length} updates, ${pendingDeleteIds.length} deletes`)- }-- return cleanupFrontendIds(data, pendingUpdates)-}--export type RemapInfo = { convexId: string, localId: string }--export function handleMutationResult<T>(opts: {- action: 'create' | 'delete' | 'update'- entity: EntityType- errorMessage: string- id: string | string[]- items?: ShallowRef<Record<string, T> | null>- mutation: Promise<unknown>- onError?: (error: unknown) => void-}): Promise<RemapInfo | void> {- const ids = Array.isArray(opts.id) ? opts.id : [opts.id]-- // Track ids as in-flight so that the subscription's own echo (for update/delete- // this is the convex id already; for create the local id won't match, but the- // post-mutation remap handles that path).- for (const id of ids) trackInFlight(id)-- return opts.mutation- .then(async (result): Promise<RemapInfo | void> => {- logger.log(`confirmed ${opts.action}: ${ids.length > 1 ? `${ids.length} items` : ids[0]}`)-- // Track convex id BEFORE any await so a realtime echo arriving during- // removeOfflineOp can't slip past the in-flight gate and overwrite- // our optimistic state with server-side echo data.- let convexIdToUntrack: string | null = null- if (opts.action === 'create' && !Array.isArray(opts.id) && result) {- const convexId = String(result)- if (opts.id !== convexId) {- trackInFlight(convexId)- convexIdToUntrack = convexId- }- }-- if (ids.length === 1)- await removeOfflineOp(opts.entity, ids[0]!)- else- await removeOfflineOps(opts.entity, ids)-- if (opts.action === 'create' && !Array.isArray(opts.id) && result && opts.items) {- const convexId = String(result)- const current = opts.items.value- if (current && opts.id in current && opts.id !== convexId) {- const { [opts.id]: item, ...rest } = current- const remapped = { ...rest, [convexId]: item } as Record<string, T>- opts.items.value = remapped- if (!_persistBlocked)- localforage.setItem(STORAGE_KEYS[opts.entity], remapped)- logger.log(`remapped ID: ${opts.id} → ${convexId}`)- // Extend tracking past the await so a delayed echo is still suppressed.- setTimeout(untrackInFlight, 2000, convexId)- convexIdToUntrack = null- return { convexId, localId: opts.id }- }- }-- // If we tracked but never remapped (e.g., result mismatch), release.- if (convexIdToUntrack)- untrackInFlight(convexIdToUntrack)- })- .catch((e) => {- logger.error(`${opts.action} failed: ${ids.length > 1 ? `${ids.length} items` : ids[0]}`, e)- opts.onError?.(e)- showErrorToast(opts.errorMessage)- })- .finally(() => {- for (const id of ids) untrackInFlight(id)- })-}-let _toast: ReturnType<typeof useToast> | null = nulllet _t: ((key: string, params?: Record<string, unknown>) => string) | null = null@@ -219,6 +59,27 @@ export function showToast(type: ToastType, key: string, params?: Record<string,return toast.add({ color: type, description: t ? t(key, params ?? {}) : key, title: random(emoByType[type]) })}+/**+ * Like showToast but with a single action button (e.g. "Reload from server").+ * `onClick` runs when the user taps the action.+ */+export function showActionToast(+ type: ToastType,+ messageKey: string,+ actionLabelKey: string,+ onClick: () => void,+ params?: Record<string, unknown>,+) {+ const toast = getToast()+ const t = getT()+ return toast.add({+ actions: [{ label: t ? t(actionLabelKey) : actionLabelKey, onClick }],+ color: type,+ description: t ? t(messageKey, params ?? {}) : messageKey,+ title: random(emoByType[type]),+ })+}+export function showErrorToast(key: string, params?: Record<string, unknown>) {return showToast('error', key, params)}diff --git a/app/app/layouts/default.vue b/app/app/layouts/default.vueindex e8a07d10..675af5f2 100644--- a/app/app/layouts/default.vue+++ b/app/app/layouts/default.vue@@ -19,18 +19,26 @@ const trnsStore = useTrnsStore()const { isDemo } = useDemo()const { isMenuOpen } = useMenuData()const { isSearchOpen } = useSearch()-const { loadDataFromCache, loadDataFromDB } = useInitApp()+const { awaitInitialSync, isHydrated, startLocalData } = useInitApp()const { width } = useWindowSize()const isShowSidebar = useCookie('finapp.isShowSidebar', { default: () => true })const isOnboardedHint = useCookie('finapp.isOnboarded', { default: () => false })const isOnboarded = computed(() => walletsStore.hasItems && categoriesStore.hasItems && trnsStore.hasItems)-watch(isOnboarded, val => (isOnboardedHint.value = val))-const hasSidebar = computed(() => isOnboardedHint.value || isOnboarded.value)+// Only sync the hint once local data has hydrated - otherwise the empty stores during the+// load gap would wipe the hint exactly when it's needed.+watch([isOnboarded, isHydrated], () => {+ if (isHydrated.value)+ isOnboardedHint.value = isOnboarded.value+})++// Render the app shell as soon as the user is known onboarded - live data, or the persisted+// hint on a cold start before hydration - so the first frame is the shell, not a splash.+const showShell = computed(() => isOnboarded.value || isOnboardedHint.value)const layoutClasses = computed(() => cn('flex min-h-dvh flex-col transition-all duration-300 ease-in-out',- hasSidebar.value && (isShowSidebar.value ? 'md:pl-72' : 'md:pl-12'),+ showShell.value && (isShowSidebar.value ? 'md:pl-72' : 'md:pl-12'),isOnboarded.value && trnsFormStore.ui.isShow && 'md:pr-[360px]',))@@ -38,20 +46,21 @@ const { error, status } = useAsyncData('app',async () => {if (isDemo.value) {- // Skip cache load if stores already have data (just generated by openDemo)+ // Skip if stores already have data (just generated by openDemo)if (!categoriesStore.hasItems)- await loadDataFromCache()+ await startLocalData()}- else if (userStore.currentUser || hasAuthCookie()) {- await loadDataFromCache()+ else if (userStore.currentUser || hasPersistedSession()) {+ // Read local SQLite (offline-first - this is the data the user sees).+ await startLocalData()if (navigator.onLine) {- // If cache had data, load from DB in background (user sees cached UI).- // If no cache (first login), await so the loading screen stays visible.+ // Have local data: let the first sync land in the background. Empty (first login /+ // new device): await it so the loading screen stays up instead of flashing onboarding.if (isOnboarded.value)- loadDataFromDB()+ awaitInitialSync()else- await loadDataFromDB()+ await awaitInitialSync()}}},@@ -89,19 +98,19 @@ defineShortcuts({<pre>{{ error }}</pre></div>- <template v-else-if="status === 'success'">- <template v-if="isOnboarded">+ <template v-else-if="status === 'success' || isOnboardedHint">+ <template v-if="showShell"><LayoutSidebar:isShowSidebar@toggleSidebar="isShowSidebar = !isShowSidebar"/></template>- <div :class="isOnboarded ? 'flex min-h-dvh flex-col md:py-4 md:pr-4' : 'flex flex-1 items-center justify-center'">- <div :class="isOnboarded ? 'bg-default md:border-accented relative z-10 flex max-w-5xl flex-1 flex-col contain-paint md:rounded-md md:border lg:rounded-2xl' : 'w-full max-w-lg px-4'">+ <div :class="showShell ? 'flex min-h-dvh flex-col md:py-4 md:pr-4' : 'flex flex-1 items-center justify-center'">+ <div :class="showShell ? 'bg-default md:border-accented relative z-10 flex max-w-5xl flex-1 flex-col contain-paint md:rounded-md md:border lg:rounded-2xl' : 'w-full max-w-lg px-4'"><mainid="pageScroll"- :style="isOnboarded ? 'padding-bottom: calc(64px + env(safe-area-inset-bottom))' : ''"+ :style="showShell ? 'padding-bottom: calc(64px + env(safe-area-inset-bottom))' : ''"class="@container/main flex-1 contain-paint md:!pb-0"><slot :keepalive="{ include: keepalive }" />@@ -109,9 +118,9 @@ defineShortcuts({</div></div>- <SearchModal v-if="isOnboarded" />+ <SearchModal v-if="showShell" />- <template v-if="isOnboarded">+ <template v-if="showShell"><TrnFormFloatOpener v-if="width >= 767" /><LayoutMenuBottom />diff --git a/app/app/pages/dashboard.vue b/app/app/pages/dashboard.vueindex 1252804e..67e5b363 100644--- a/app/app/pages/dashboard.vue+++ b/app/app/pages/dashboard.vue@@ -10,10 +10,18 @@ const { t } = useI18n()const trnsStore = useTrnsStore()const walletsStore = useWalletsStore()const categoriesStore = useCategoriesStore()-const { isDbLoading } = useInitApp()+const { isDbLoading, isHydrated } = useInitApp()+const isOnboardedHint = useCookie('finapp.isOnboarded', { default: () => false })const isOnboarded = computed(() => walletsStore.hasItems && categoriesStore.hasItems && trnsStore.hasItems)+// Show the dashboard for a returning onboarded user on the first frame (hint), before local+// SQLite has hydrated - so they never see the onboarding flash.+const showStat = computed(() => isOnboarded.value || (!isHydrated.value && isOnboardedHint.value))+// Only conclude "not onboarded" once hydrated AND the first sync settled: an empty DB mid-sync+// is "unknown", not "new", so showing onboarding there would flash it before data arrives.+const showOnboarding = computed(() => isHydrated.value && !isOnboarded.value && !isDbLoading.value)+useSeoMeta({ogTitle: t('stat.title'),titleTemplate: t('stat.title'),@@ -21,6 +29,6 @@ useSeoMeta({</script><template>- <StatPage v-if="isOnboarded" />- <LazyAppOnboarding v-else-if="!isDbLoading" />+ <StatPage v-if="showStat" />+ <LazyAppOnboarding v-else-if="showOnboarding" /></template>diff --git a/app/i18n/locales/en-US.js b/app/i18n/locales/en-US.jsindex bc0a8fe4..8d632665 100644--- a/app/i18n/locales/en-US.js+++ b/app/i18n/locales/en-US.js@@ -130,9 +130,11 @@ export default {},chart: {+ empty: 'No data for this period',types: {bar: 'Bars',line: 'Lines',+ pie: 'Donut',},},@@ -234,14 +236,18 @@ export default {login: {description: 'Powerful open-source finance application',+ email: 'Email',error: 'Login failed. Please try again.',+ haveAccount: 'Already have an account? Sign in',+ noAccount: 'No account? Sign up',openDemo: 'Open Demo',or: 'or',+ password: 'Password',+ signIn: 'Sign in',+ signUp: 'Sign up',title: 'Login',},- loginWithGoogle: 'Login with Google',-money: {all: 'Total',average: 'Average',@@ -333,6 +339,7 @@ export default {},byCategories: 'By categories',groupByParent: 'Group by parent',+ other: 'Other',type: {label: 'Chart type',},@@ -387,6 +394,17 @@ export default {title: 'Statistics',},+ sync: {+ actions: {+ reloadFromServer: 'Reload from server',+ },+ errors: {+ uploadDiverged: 'A change could not be synced - your local data may differ from the server. Reload to discard unsynced local changes and refresh from the server.',+ uploadRejected: 'Some changes could not be synced to the server',+ uploadReverted: 'A change could not be saved and was reverted',+ },+ },+theme: {color: 'Change theme color',dark: 'Dark',diff --git a/app/i18n/locales/ru-RU.js b/app/i18n/locales/ru-RU.jsindex 1a8b7a21..6eace90e 100644--- a/app/i18n/locales/ru-RU.js+++ b/app/i18n/locales/ru-RU.js@@ -130,9 +130,11 @@ export default {},chart: {+ empty: 'Нет данных за период',types: {bar: 'Колонки',line: 'Линии',+ pie: 'Кольцо',},},@@ -234,14 +236,18 @@ export default {login: {description: 'Персональный финансовый ассистент',+ email: 'Эл. почта',error: 'Ошибка входа. Попробуйте ещё раз.',+ haveAccount: 'Уже есть аккаунт? Войти',+ noAccount: 'Нет аккаунта? Зарегистрироваться',openDemo: 'Открыть демо',or: 'или',+ password: 'Пароль',+ signIn: 'Войти',+ signUp: 'Регистрация',title: 'Вход',},- loginWithGoogle: 'Войти через Google',-money: {all: 'Всего',average: 'Среднее',@@ -333,6 +339,7 @@ export default {},byCategories: 'По категориям',groupByParent: 'Группировать по родителю',+ other: 'Прочее',type: {label: 'Тип графика',},@@ -387,6 +394,17 @@ export default {title: 'Статистика',},+ sync: {+ actions: {+ reloadFromServer: 'Загрузить с сервера',+ },+ errors: {+ uploadDiverged: 'Изменение не удалось синхронизировать - локальные данные могут отличаться от сервера. Загрузите заново, чтобы отменить несинхронизированные локальные изменения и обновить данные с сервера.',+ uploadRejected: 'Некоторые изменения не удалось синхронизировать с сервером',+ uploadReverted: 'Изменение не удалось сохранить, оно было отменено',+ },+ },+theme: {color: 'Сменить цвет оформления',dark: 'Темная',diff --git a/app/utils/generateId.ts b/app/utils/generateId.tsindex fb2be19c..68eee0ff 100644--- a/app/utils/generateId.ts+++ b/app/utils/generateId.ts@@ -1,4 +1,8 @@-export function generateId() {- const random = Math.random().toString(36).substring(2, 8)- return `local_${random}`+/**+ * Client-generated entity id. With PowerSync the client generates the final id+ * (a UUID), so there is no server-side remapping - the id written locally is the+ * same id stored in Postgres.+ */+export function generateId(): string {+ return crypto.randomUUID()}