Skip to content

Open source personal finance application

feat(app): boot-state machine with cache-first paint and sync-error retry

Ilya Komicheve24d341ca52a
diff --git a/app/app/components/app/useInitApp.ts b/app/app/components/app/useInitApp.ts
index 6dee8da2..48303fd8 100644
--- a/app/app/components/app/useInitApp.ts
+++ b/app/app/components/app/useInitApp.ts
@@ -1,5 +1,5 @@
import localforage from 'localforage'
-import { connectPowerSync, getLocalDbOwner, waitForFirstSync } from '~~/services/powersync/db'
+import { connectPowerSync, getLocalDbOwner, hasAnyLocalData, waitForFirstSync } from '~~/services/powersync/db'
import type { Categories } from '~/components/categories/types'
import type { Rates } from '~/components/currencies/types'
@@ -26,7 +26,10 @@ 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)
+const firstSyncComplete = ref(false)
+const syncError = ref(false)
+// Shared cookie ref so every caller reads/writes the same reactive value (per-call useCookie would not).
+let hintRef: Ref<boolean> | null = null
export function useInitApp() {
const userStore = useUserStore()
@@ -42,17 +45,55 @@ export function useInitApp() {
useDemo().isDemo.value
|| (walletsStore.isLoaded && categoriesStore.isLoaded && trnsStore.isLoaded))
+ const isOnboarded = computed(() =>
+ walletsStore.hasItems && categoriesStore.hasItems && trnsStore.hasItems)
+
+ // Persisted hint so a returning user gets the app shell on the first frame, before hydration.
+ hintRef ??= useCookie('finapp.isOnboarded', { default: () => false })
+ const isOnboardedHint = hintRef
+
+ // Single source of truth for the boot screen. Onboarding only once we're certain the user is
+ // new (demo, or the first server sync genuinely completed) - never while data may still arrive.
+ const bootState = computed<'loading' | 'error' | 'onboarding' | 'ready'>(() => {
+ if (isOnboarded.value || isOnboardedHint.value)
+ return 'ready'
+ if (syncError.value)
+ return 'error'
+ const loaded = useDemo().isDemo.value || firstSyncComplete.value
+ if (loaded && isHydrated.value && !isDbLoading.value)
+ return 'onboarding'
+ // TEMP: never show the loading (logo) screen - paint cached/local data immediately.
+ // return 'loading'
+ return 'ready'
+ })
+
+ // Hold the loading screen until the throttled watches push the freshly-synced rows into the
+ // stores, so onboarding never flashes between "sync done" and "stores filled".
+ function waitForStoresToReflectData(maxMs = 2000): Promise<void> {
+ if (isOnboarded.value)
+ return Promise.resolve()
+ return new Promise((resolve) => {
+ let stop = () => {}
+ const timer = setTimeout(() => {
+ stop()
+ resolve()
+ }, maxMs)
+ stop = watch(isOnboarded, (ready) => {
+ if (ready) {
+ clearTimeout(timer)
+ stop()
+ resolve()
+ }
+ })
+ })
+ }
+
useEventListener(window, 'online', () => {
- isOffline.value = false
// PowerSync reconnects on its own; re-arming watches is cheap and idempotent.
if (userStore.uid && !isDbLoading.value)
startWatches()
})
- useEventListener(window, 'offline', () => {
- isOffline.value = true
- })
-
/**
* 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.
@@ -117,8 +158,9 @@ export function useInitApp() {
return
}
- // Paint instantly from the last session's snapshot, in parallel with db.init - don't await.
- void primeStoresFromCache()
+ // TEMP: await the cache snapshot so it's in the stores before the watches arm (otherwise an
+ // empty first SQLite emission marks isLoaded and the cache prime is skipped).
+ await primeStoresFromCache()
// 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).
@@ -132,9 +174,9 @@ export function useInitApp() {
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.
+ // Waits for the server's first sync to land in local SQLite (fresh login / new device), holding
+ // the loading screen. Sets `syncError` instead of flashing onboarding when the sync can't
+ // complete and there's no local data to fall back to.
async function awaitInitialSync() {
if (useDemo().isDemo.value)
return
@@ -143,17 +185,68 @@ export function useInitApp() {
return
isDbLoading.value = true
+ syncError.value = false
try {
- await waitForFirstSync()
+ if (!navigator.onLine) {
+ syncError.value = !(await hasAnyLocalData())
+ return
+ }
+
+ const synced = await waitForFirstSync()
+ if (!synced) {
+ syncError.value = !(await hasAnyLocalData())
+ firstSyncComplete.value = !syncError.value
+ return
+ }
+
+ firstSyncComplete.value = true
+ if (await hasAnyLocalData())
+ await waitForStoresToReflectData()
}
catch (e) {
logger.error('awaitInitialSync failed', e)
+ syncError.value = !(await hasAnyLocalData().catch(() => false))
}
finally {
isDbLoading.value = false
}
}
+ // Boot the app: arm local data, then (clean login) wait for the first sync so onboarding never
+ // flashes; a returning user (hint) gets the shell now and syncs in the background. Re-runnable
+ // as the retry action from the error screen.
+ async function initApp() {
+ try {
+ if (useDemo().isDemo.value) {
+ if (!categoriesStore.hasItems)
+ await startLocalData()
+ return true
+ }
+
+ if (!(userStore.currentUser || hasPersistedSession()))
+ return true
+
+ await startLocalData()
+
+ // TEMP: don't wait for the first real sync - sync in the background so cached/local data
+ // shows immediately without the loading screen.
+ // if (isOnboardedHint.value) {
+ // if (navigator.onLine)
+ // awaitInitialSync()
+ // }
+ // else {
+ // await awaitInitialSync()
+ // }
+ if (navigator.onLine)
+ awaitInitialSync()
+ }
+ catch (e) {
+ logger.error('initApp failed', e)
+ syncError.value = !(await hasAnyLocalData().catch(() => false))
+ }
+ return true
+ }
+
function clearLocalData() {
blockPersist()
@@ -169,11 +262,11 @@ export function useInitApp() {
}
return {
- awaitInitialSync,
+ bootState,
clearLocalData,
- isDbLoading,
+ initApp,
isHydrated,
- isOffline,
- startLocalData,
+ isOnboarded,
+ isOnboardedHint,
}
}
diff --git a/app/app/components/categories/useCategoriesStore.ts b/app/app/components/categories/useCategoriesStore.ts
index 9f7e078d..987b78ec 100644
--- a/app/app/components/categories/useCategoriesStore.ts
+++ b/app/app/components/categories/useCategoriesStore.ts
@@ -190,6 +190,9 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
watchController = watchTable<Row>('SELECT * FROM categories', [], (rows) => {
isLoaded.value = true
if (!rows.length) {
+ // TEMP: keep cached data instead of wiping it with an empty first emission.
+ if (hasItems.value)
+ return
setCategories(null)
return
}
diff --git a/app/app/components/trns/useTrnsStore.ts b/app/app/components/trns/useTrnsStore.ts
index e824780b..ebcd8ebe 100644
--- a/app/app/components/trns/useTrnsStore.ts
+++ b/app/app/components/trns/useTrnsStore.ts
@@ -125,6 +125,9 @@ export const useTrnsStore = defineStore('trns', () => {
isLoaded.value = false // re-subscribe (e.g. different user) waits for a fresh emission
watchController = watchTable<Row>('SELECT * FROM trns', [], (rows) => {
isLoaded.value = true
+ // TEMP: keep cached data instead of wiping it with an empty first emission.
+ if (!rows.length && hasItems.value)
+ return
const prev = items.value
const next = prev ? reconcileTrns(prev, rows) : rowsToTrns(rows)
// reconcileTrns returns `prev` (same ref) when nothing changed - skip the rebuild
diff --git a/app/app/components/wallets/useWalletsStore.ts b/app/app/components/wallets/useWalletsStore.ts
index 0d33ce6a..243ebfd6 100644
--- a/app/app/components/wallets/useWalletsStore.ts
+++ b/app/app/components/wallets/useWalletsStore.ts
@@ -72,8 +72,11 @@ export const useWalletsStore = defineStore('wallets', () => {
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
+ // TEMP: keep cached data instead of wiping it with an empty first SQLite emission.
+ if (!rows.length && hasItems.value)
+ return
+ setWallets(rowsToWallets(rows))
})
logger.log('watching wallets')
}
diff --git a/app/app/layouts/default.vue b/app/app/layouts/default.vue
index 675af5f2..84777d1c 100644
--- a/app/app/layouts/default.vue
+++ b/app/app/layouts/default.vue
@@ -1,30 +1,23 @@
<script setup lang="ts">
import { useInitApp } from '~/components/app/useInitApp'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { useDemo } from '~/components/demo/useDemo'
import { useMenuData } from '~/components/layout/useMenuData'
import { useSearch } from '~/components/search/useSearch'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
-import { useTrnsStore } from '~/components/trns/useTrnsStore'
-import { useUserStore } from '~/components/user/useUserStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
const keepalive = ['Categories', 'CategoriesId', 'Wallets', 'WalletsId', 'Dashboard']
+const { t } = useI18n()
const categoriesStore = useCategoriesStore()
const trnsFormStore = useTrnsFormStore()
-const userStore = useUserStore()
const walletsStore = useWalletsStore()
-const trnsStore = useTrnsStore()
-const { isDemo } = useDemo()
const { isMenuOpen } = useMenuData()
const { isSearchOpen } = useSearch()
-const { awaitInitialSync, isHydrated, startLocalData } = useInitApp()
+const { bootState, initApp, isHydrated, isOnboarded, isOnboardedHint } = 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)
// 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.
@@ -33,38 +26,14 @@ watch([isOnboarded, isHydrated], () => {
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 showShell = computed(() => bootState.value === 'ready')
const layoutClasses = computed(() => cn(
'flex min-h-dvh flex-col transition-all duration-300 ease-in-out',
showShell.value && (isShowSidebar.value ? 'md:pl-72' : 'md:pl-12'),
isOnboarded.value && trnsFormStore.ui.isShow && 'md:pr-[360px]',
))
-const { error, status } = useAsyncData(
- 'app',
- async () => {
- if (isDemo.value) {
- // Skip if stores already have data (just generated by openDemo)
- if (!categoriesStore.hasItems)
- await startLocalData()
- }
- else if (userStore.currentUser || hasPersistedSession()) {
- // Read local SQLite (offline-first - this is the data the user sees).
- await startLocalData()
-
- if (navigator.onLine) {
- // 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)
- awaitInitialSync()
- else
- await awaitInitialSync()
- }
- }
- },
-)
+useAsyncData('app', initApp)
defineShortcuts({
'escape': () => {
@@ -90,15 +59,28 @@ defineShortcuts({
:class="layoutClasses"
style="margin-left: env(safe-area-inset-left)"
>
- <div v-if="status === 'pending' && !isOnboardedHint" class="flex-center h-dvh">
+ <div v-if="bootState === 'loading'" class="flex-center h-dvh">
<UiLogo size="lg" />
</div>
- <div v-else-if="status === 'error'" class="p-4">
- <pre>{{ error }}</pre>
+ <div
+ v-else-if="bootState === 'error'"
+ class="flex-center h-dvh flex-col gap-6 px-4 text-center"
+ >
+ <UiLogo size="lg" />
+ <p class="text-muted">
+ {{ t('app.loadError') }}
+ </p>
+ <UButton
+ size="xl"
+ class="min-w-52 justify-center rounded-full px-8 py-3"
+ @click="initApp"
+ >
+ {{ t('app.retry') }}
+ </UButton>
</div>
- <template v-else-if="status === 'success' || isOnboardedHint">
+ <template v-else>
<template v-if="showShell">
<LayoutSidebar
:isShowSidebar
diff --git a/app/app/pages/dashboard.vue b/app/app/pages/dashboard.vue
index 67e5b363..72580c4a 100644
--- a/app/app/pages/dashboard.vue
+++ b/app/app/pages/dashboard.vue
@@ -1,26 +1,10 @@
<script setup lang="ts">
import { useInitApp } from '~/components/app/useInitApp'
-import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { useTrnsStore } from '~/components/trns/useTrnsStore'
-import { useWalletsStore } from '~/components/wallets/useWalletsStore'
defineOptions({ name: 'Dashboard' })
const { t } = useI18n()
-const trnsStore = useTrnsStore()
-const walletsStore = useWalletsStore()
-const categoriesStore = useCategoriesStore()
-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)
+const { bootState } = useInitApp()
useSeoMeta({
ogTitle: t('stat.title'),
@@ -29,6 +13,6 @@ useSeoMeta({
</script>
<template>
- <StatPage v-if="showStat" />
- <LazyAppOnboarding v-else-if="showOnboarding" />
+ <StatPage v-if="bootState === 'ready'" />
+ <LazyAppOnboarding v-else-if="bootState === 'onboarding'" />
</template>
diff --git a/app/i18n/locales/en-US.js b/app/i18n/locales/en-US.js
index 0c286ec9..db7884d3 100644
--- a/app/i18n/locales/en-US.js
+++ b/app/i18n/locales/en-US.js
@@ -18,10 +18,12 @@ export default {
app: {
about: 'About',
desc: 'Finapp helps you to control personal finances easily and efficiently.',
+ loadError: 'Could not load your data. Check your connection and try again.',
madeBy: {
name: 'by Ilya Komichev',
text: 'Made with',
},
+ retry: 'Try again',
toggleSidebar: 'Toggle sidebar',
version: 'Version',
},
diff --git a/app/i18n/locales/ru-RU.js b/app/i18n/locales/ru-RU.js
index fd6693ee..6eaf3863 100644
--- a/app/i18n/locales/ru-RU.js
+++ b/app/i18n/locales/ru-RU.js
@@ -18,10 +18,12 @@ export default {
app: {
about: 'О приложении',
desc: 'Приложение для учета личных финансов',
+ loadError: 'Не удалось загрузить данные. Проверьте соединение и попробуйте снова.',
madeBy: {
name: 'Илья Комичев',
text: 'Разработал',
},
+ retry: 'Повторить',
toggleSidebar: 'Скрыть/показать боковую панель',
version: 'Версия',
},
diff --git a/app/services/powersync/db.ts b/app/services/powersync/db.ts
index d3e7f27a..8cb82abd 100644
--- a/app/services/powersync/db.ts
+++ b/app/services/powersync/db.ts
@@ -134,24 +134,35 @@ export async function disconnectPowerSync(): Promise<boolean> {
}
}
-/** Resolve once the first sync from the server completes, or after `timeoutMs`. */
-export async function waitForFirstSync(timeoutMs = 10000): Promise<void> {
+/** Resolves `true` once the first full sync completes; `false` on timeout / not connected. */
+export async function waitForFirstSync(timeoutMs = 30000): Promise<boolean> {
const db = usePowerSyncDb()
if (db.currentStatus?.hasSynced)
- return
+ return true
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), timeoutMs)
try {
await db.waitForFirstSync({ signal: controller.signal })
+ return !!db.currentStatus?.hasSynced
}
catch {
- // timeout or not connected - the watch fills data later
+ return false
}
finally {
clearTimeout(timer)
}
}
+export async function hasAnyLocalData(): Promise<boolean> {
+ const db = usePowerSyncDb()
+ for (const table of ['wallets', 'categories', 'trns'] as const) {
+ const row = await db.get<{ c: number }>(`SELECT count(*) as c FROM ${table}`)
+ if ((row?.c ?? 0) > 0)
+ return true
+ }
+ return false
+}
+
/**
* Subscribe to a query. `onRows` fires immediately with current local rows and again
* on every change (local write or incoming sync). Returns an AbortController to stop.