Skip to content

Open source personal finance application

fix(sync): preserve offline writes on involuntary session loss

Ilya Komichev5276761b0907
diff --git a/CLAUDE.md b/CLAUDE.md
index 962b0ad5..9a0dc09a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -38,9 +38,9 @@ Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Supab
### Client data layer
-- `app/services/powersync/` - `AppSchema.ts` (client SQLite schema), `db.ts` (lazy `getPowerSyncDb()` singleton - dynamically imports `@powersync/web` to keep it out of the entry chunk - plus `connectPowerSync` / `watchTable` / `waitForFirstSync`), `connector.ts` (`SupabaseConnector`: `fetchCredentials` + `uploadData`; reachable only via the dynamic import in db.ts), `uploadReconcile.ts` + `uploadErrorHandler.ts` (auto-reconcile of fatally rejected uploads), `transforms.ts` (row↔item: booleans 0/1, `parentId` null↔0, `rates` JSON), `mutations.ts` (`upsertRow` / `deleteRow` / `deleteTrnsReferencing` - INSERT/UPDATE, never `ON CONFLICT`, since PowerSync tables are views).
+- `app/services/powersync/` - `AppSchema.ts` (client SQLite schema), `db.ts` (lazy `getPowerSyncDb()` singleton - dynamically imports `@powersync/web` to keep it out of the entry chunk - plus `connectPowerSync` / `pausePowerSync` / `watchTable` / `waitForFirstSync`), `connector.ts` (`SupabaseConnector`: `fetchCredentials` + `uploadData`; reachable only via the dynamic import in db.ts), `uploadReconcile.ts` + `uploadErrorHandler.ts` (auto-reconcile of fatally rejected uploads), `transforms.ts` (row↔item: booleans 0/1, `parentId` null↔0, `rates` JSON), `mutations.ts` (`upsertRow` / `deleteRow` / `deleteTrnsReferencing` - INSERT/UPDATE, never `ON CONFLICT`, since PowerSync tables are views).
- `app/app/composables/useSupabase.ts` - the supabase-js client + `useSupabaseAuth()` (reactive session, `signInWithPassword` / `signUp` / `signInWithGoogle` / `signOut`). `detectSessionInUrl: true` so the Google OAuth PKCE `?code=` is exchanged on return to `/login` (handled in `login.vue`).
-- `app/app/plugins/powersync.client.ts` - eagerly opens local SQLite for an already-logged-in user, then connects/disconnects PowerSync as the auth session (`uid`) resolves. The synchronous route-guard gate is `hasPersistedSession()` (`app/app/composables/useAuthSession.ts`), which reads the persisted Supabase session from localStorage directly - no cookie.
+- `app/app/plugins/powersync.client.ts` - eagerly opens local SQLite for an already-logged-in user, then connects PowerSync when the auth session (`uid`) resolves. On involuntary session loss (token revoked/expired) it pauses sync (`pausePowerSync`: keeps local SQLite + the unsynced queue) rather than wiping, surfacing a re-auth toast when writes are pending; only an explicit sign-out (`useUserStore.signOut`) wipes. The synchronous route-guard gate is `hasPersistedSession()` (`app/app/composables/useAuthSession.ts`), which reads the persisted Supabase session from localStorage directly - no cookie. Local row writes stamp `userId` via `resolveWriteUid` (same file), which falls back to the persisted uid so an offline cold start before the session resolves doesn't write an empty `userId` (which RLS would reject).
- Stores hydrate via `db.watch('SELECT * FROM ...')` (one subscription handles both initial load and realtime, local + synced) and write via `upsertRow`/`deleteRow`. Demo mode bypasses PowerSync and uses in-memory + localforage.
## Documentation
diff --git a/app/app/components/categories/useCategoriesStore.ts b/app/app/components/categories/useCategoriesStore.ts
index 20f720af..2de0e764 100644
--- a/app/app/components/categories/useCategoriesStore.ts
+++ b/app/app/components/categories/useCategoriesStore.ts
@@ -12,6 +12,7 @@ import { useDemo } from '~/components/demo/useDemo'
import { STORAGE_KEYS } from '~/components/offline/storageKeys'
import { TrnType } from '~/components/trns/types'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
+import { resolveWriteUid } from '~/composables/useAuthSession'
import { persistStoreCache } from '~/composables/useStoreCache'
import { createDebouncedPersist, showErrorToast } from '~/composables/useStoreSync'
import { useSupabaseAuth } from '~/composables/useSupabase'
@@ -332,7 +333,7 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
for (const cid of diff.added) touched.add(cid)
for (const cid of diff.removed) touched.add(cid)
- const userId = uid.value ?? ''
+ const userId = resolveWriteUid(uid.value)
const rows: { id: CategoryId, row: Record<string, unknown> }[] = []
for (const cid of touched) {
const item = items.value[cid]
diff --git a/app/app/components/trns/useTrnsStore.test.ts b/app/app/components/trns/useTrnsStore.test.ts
index 1e852c02..e732e9a2 100644
--- a/app/app/components/trns/useTrnsStore.test.ts
+++ b/app/app/components/trns/useTrnsStore.test.ts
@@ -5,6 +5,7 @@ import type { TrnItem } from '~/components/trns/types'
import { TrnType } from '~/components/trns/types'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
+import { AUTH_STORAGE_KEY } from '~/composables/useAuthSession'
import { toastAddMock } from '~/test-utils/setup-store'
// Mock the PowerSync data layer so the store talks to a controllable fake:
@@ -46,6 +47,8 @@ describe('useTrnsStore', () => {
beforeEach(() => {
setActivePinia(createPinia())
h.demo.value = false
+ h.auth.uid.value = 'u1'
+ localStorage.clear()
h.watchCallbacks.length = 0
h.watchTable.mockClear()
h.upsertRow.mockReset().mockResolvedValue(undefined)
@@ -145,6 +148,20 @@ describe('useTrnsStore', () => {
await tick()
expect(h.upsertRow).not.toHaveBeenCalled()
})
+
+ it('stamps the persisted uid when the reactive session uid has not resolved', async () => {
+ // Offline cold start: getSession resolved to null (reactive uid null), but the
+ // session is still in localStorage. The row must carry the real uid, not '' (which
+ // RLS would reject on upload, dropping the offline write).
+ h.auth.uid.value = null
+ localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify({ user: { id: 'persisted-uid' } }))
+
+ const store = useTrnsStore()
+ store.saveTrn({ id: 't1', values: expense() })
+
+ await tick()
+ expect(h.upsertRow).toHaveBeenCalledWith('trns', 't1', expect.objectContaining({ userId: 'persisted-uid' }))
+ })
})
describe('deleteTrn', () => {
diff --git a/app/app/components/trns/useTrnsStore.ts b/app/app/components/trns/useTrnsStore.ts
index b5d7afc5..3893a9e3 100644
--- a/app/app/components/trns/useTrnsStore.ts
+++ b/app/app/components/trns/useTrnsStore.ts
@@ -15,6 +15,7 @@ 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 { resolveWriteUid } from '~/composables/useAuthSession'
import { persistStoreCache } from '~/composables/useStoreCache'
import { createDebouncedPersist, showErrorToast } from '~/composables/useStoreSync'
import { useSupabaseAuth } from '~/composables/useSupabase'
@@ -157,7 +158,7 @@ export const useTrnsStore = defineStore('trns', () => {
if (isDemo.value)
return
- upsertRow('trns', id, trnToRow(valuesWithEditDate, uid.value ?? '')).catch((e) => {
+ upsertRow('trns', id, trnToRow(valuesWithEditDate, resolveWriteUid(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')
diff --git a/app/app/components/wallets/useWalletsStore.ts b/app/app/components/wallets/useWalletsStore.ts
index e8bfab30..df697985 100644
--- a/app/app/components/wallets/useWalletsStore.ts
+++ b/app/app/components/wallets/useWalletsStore.ts
@@ -16,6 +16,7 @@ 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 { resolveWriteUid } from '~/composables/useAuthSession'
import { persistStoreCache } from '~/composables/useStoreCache'
import { createDebouncedPersist, showErrorToast } from '~/composables/useStoreSync'
import { useSupabaseAuth } from '~/composables/useSupabase'
@@ -112,7 +113,7 @@ export const useWalletsStore = defineStore('wallets', () => {
if (isDemo.value)
return
- upsertRow('wallets', id, walletToRow(values, uid.value ?? '')).catch((e) => {
+ upsertRow('wallets', id, walletToRow(values, resolveWriteUid(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')
@@ -138,7 +139,7 @@ export const useWalletsStore = defineStore('wallets', () => {
.filter(walletId => items.value?.[walletId])
.map((walletId, index) => ({
id: walletId,
- row: walletToRow({ ...items.value![walletId]!, order: index }, uid.value ?? ''),
+ row: walletToRow({ ...items.value![walletId]!, order: index }, resolveWriteUid(uid.value)),
})),
).catch((e) => {
setWallets(prev) // restore the previous order if the local write failed
diff --git a/app/app/composables/useAuthSession.test.ts b/app/app/composables/useAuthSession.test.ts
index 1c8bb971..03e0f977 100644
--- a/app/app/composables/useAuthSession.test.ts
+++ b/app/app/composables/useAuthSession.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { AUTH_STORAGE_KEY, getPersistedSession, getPersistedUid, hasPersistedSession } from '~/composables/useAuthSession'
+import { AUTH_STORAGE_KEY, getPersistedSession, getPersistedUid, hasPersistedSession, resolveWriteUid } from '~/composables/useAuthSession'
let store: Record<string, string>
@@ -73,4 +73,21 @@ describe('useAuthSession', () => {
expect(getPersistedSession()).toBeNull()
})
})
+
+ describe('resolveWriteUid', () => {
+ it('prefers the reactive uid when present', () => {
+ store[AUTH_STORAGE_KEY] = makeSession('persisted')
+ expect(resolveWriteUid('reactive')).toBe('reactive')
+ })
+
+ it('falls back to the persisted uid when the reactive uid is null', () => {
+ // The offline-cold-start case: getSession resolved to null, but the session is still in storage.
+ store[AUTH_STORAGE_KEY] = makeSession('persisted')
+ expect(resolveWriteUid(null)).toBe('persisted')
+ })
+
+ it('returns an empty string when neither is available', () => {
+ expect(resolveWriteUid(null)).toBe('')
+ })
+ })
})
diff --git a/app/app/composables/useAuthSession.ts b/app/app/composables/useAuthSession.ts
index 8d6e716a..bde70993 100644
--- a/app/app/composables/useAuthSession.ts
+++ b/app/app/composables/useAuthSession.ts
@@ -55,3 +55,13 @@ export function hasPersistedSession(): boolean {
export function getPersistedUid(): string | null {
return getPersistedSession()?.uid ?? null
}
+
+/**
+ * The uid to stamp on a local row write. Prefers the reactive session uid, but falls
+ * back to the synchronously-persisted uid so writes made before the async session
+ * resolves (e.g. an offline cold start with an expired access token, where getSession
+ * returns null) aren't stamped with an empty userId - which RLS would reject on upload.
+ */
+export function resolveWriteUid(reactiveUid: string | null): string {
+ return reactiveUid ?? getPersistedUid() ?? ''
+}
diff --git a/app/app/plugins/powersync.client.ts b/app/app/plugins/powersync.client.ts
index 5e91ac4a..725f545a 100644
--- a/app/app/plugins/powersync.client.ts
+++ b/app/app/plugins/powersync.client.ts
@@ -1,4 +1,4 @@
-import { connectPowerSync, disconnectPowerSync, forceResync, getPowerSyncDb } from '~~/services/powersync/db'
+import { connectPowerSync, forceResync, getPendingUploadCount, getPowerSyncDb, pausePowerSync } from '~~/services/powersync/db'
import { deleteRow, deleteTrnsReferencing } from '~~/services/powersync/mutations'
import { setUploadErrorHandler } from '~~/services/powersync/uploadErrorHandler'
import { planDivergence } from '~~/services/powersync/uploadReconcile'
@@ -67,10 +67,26 @@ export default defineNuxtPlugin(() => {
if (userId) {
connectPowerSync(client, powerSyncUrl, userId).catch(e => logger.error('connect failed', e))
}
- // Only disconnect+wipe on a genuine sign-out (auth resolved, no user). The initial
- // null on cold start (session not resolved yet) must NOT wipe a returning user's data.
+ // Session lost while resolved (the initial cold-start null is skipped via isAuthReady).
+ // This is NOT the explicit sign-out path - useUserStore.signOut() wipes locally itself
+ // before this fires - so it's an involuntary loss (token revoked/expired). Keep the local
+ // data + unsynced queue and only pause syncing; re-auth as the same user drains the queue.
+ // Wiping here would silently discard offline writes that never reached the server.
else if (isAuthReady.value) {
- disconnectPowerSync().catch(e => logger.error('disconnect failed', e))
+ pausePowerSync()
+ .then(() => getPendingUploadCount())
+ .then((pending) => {
+ if (pending > 0) {
+ showActionToast(
+ 'warning',
+ 'sync.errors.sessionLostPending',
+ 'sync.actions.reauth',
+ () => { void navigateTo('/login') },
+ { count: pending },
+ )
+ }
+ })
+ .catch(e => logger.error('pause failed', e))
}
},
{ immediate: true },
diff --git a/app/i18n/locales/en-US.js b/app/i18n/locales/en-US.js
index 8702c255..d7f20bcc 100644
--- a/app/i18n/locales/en-US.js
+++ b/app/i18n/locales/en-US.js
@@ -393,9 +393,11 @@ export default {
sync: {
actions: {
+ reauth: 'Sign in again',
reloadFromServer: 'Reload from server',
},
errors: {
+ sessionLostPending: 'Your session ended with {count} change(s) not yet synced. Sign in again to upload them.',
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',
diff --git a/app/i18n/locales/ru-RU.js b/app/i18n/locales/ru-RU.js
index 17a4ec29..d174919e 100644
--- a/app/i18n/locales/ru-RU.js
+++ b/app/i18n/locales/ru-RU.js
@@ -393,9 +393,11 @@ export default {
sync: {
actions: {
+ reauth: 'Войти снова',
reloadFromServer: 'Загрузить с сервера',
},
errors: {
+ sessionLostPending: 'Сессия завершилась, а {count} изменений ещё не синхронизированы. Войдите снова, чтобы отправить их.',
uploadDiverged: 'Изменение не удалось синхронизировать - локальные данные могут отличаться от сервера. Загрузите заново, чтобы отменить несинхронизированные локальные изменения и обновить данные с сервера.',
uploadRejected: 'Некоторые изменения не удалось синхронизировать с сервером',
uploadReverted: 'Изменение не удалось сохранить, оно было отменено',
diff --git a/app/services/powersync/db.test.ts b/app/services/powersync/db.test.ts
new file mode 100644
index 00000000..641e0022
--- /dev/null
+++ b/app/services/powersync/db.test.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+// Spies shared across the fake PowerSyncDatabase instances so assertions can reach them.
+const disconnect = vi.fn(async () => {})
+const disconnectAndClear = vi.fn(async () => {})
+const getUploadQueueStats = vi.fn(async () => ({ count: 0, size: null }))
+
+vi.mock('@powersync/web', () => {
+ class PowerSyncDatabase {
+ disconnect = disconnect
+ disconnectAndClear = disconnectAndClear
+ getUploadQueueStats = getUploadQueueStats
+ }
+ class WASQLiteOpenFactory {}
+ return { PowerSyncDatabase, WASQLiteOpenFactory, WASQLiteVFS: { IDBBatchAtomicVFS: 'idb' } }
+})
+vi.mock('~~/services/powersync/AppSchema', () => ({ AppSchema: {} }))
+
+const { getPendingUploadCount, getPowerSyncDb, pausePowerSync } = await import('~~/services/powersync/db')
+
+describe('pausePowerSync', () => {
+ beforeEach(() => {
+ disconnect.mockClear()
+ disconnectAndClear.mockClear()
+ })
+
+ it('disconnects but keeps local data (never disconnectAndClear)', async () => {
+ await getPowerSyncDb() // populate the singleton so pausePowerSync has a db
+ await pausePowerSync()
+ expect(disconnect).toHaveBeenCalledTimes(1)
+ expect(disconnectAndClear).not.toHaveBeenCalled()
+ })
+})
+
+describe('getPendingUploadCount', () => {
+ it('returns the local upload-queue count', async () => {
+ getUploadQueueStats.mockResolvedValueOnce({ count: 3, size: null })
+ expect(await getPendingUploadCount()).toBe(3)
+ })
+})
diff --git a/app/services/powersync/db.ts b/app/services/powersync/db.ts
index 9e0d6129..f3d181f5 100644
--- a/app/services/powersync/db.ts
+++ b/app/services/powersync/db.ts
@@ -144,6 +144,28 @@ export async function disconnectPowerSync(): Promise<boolean> {
}
}
+/**
+ * Stop syncing but KEEP local SQLite and the unsynced upload queue (unlike
+ * disconnectPowerSync, which clears them). Used when the auth session is lost
+ * involuntarily (token revoked/expired) so pending offline writes survive until the
+ * user re-authenticates - re-connecting as the same uid then drains the queue. The
+ * owner marker is intentionally left in place so the same-user reconnect skips the wipe.
+ */
+export async function pausePowerSync(): Promise<void> {
+ if (!_dbPromise)
+ return
+ _connected = false
+ const db = await _dbPromise
+ await db.disconnect()
+ logger.log('paused (local data kept)')
+}
+
+/** Number of not-yet-uploaded operations in the local CRUD queue. */
+export async function getPendingUploadCount(): Promise<number> {
+ const db = await getPowerSyncDb()
+ return (await db.getUploadQueueStats()).count
+}
+
/** Resolves `true` once the first full sync completes; `false` on timeout / not connected. */
export async function waitForFirstSync(timeoutMs = 30000): Promise<boolean> {
const db = await getPowerSyncDb()
diff --git a/docs/content/en/3.reference/03.sync.md b/docs/content/en/3.reference/03.sync.md
index 2634a06f..5a085fcc 100644
--- a/docs/content/en/3.reference/03.sync.md
+++ b/docs/content/en/3.reference/03.sync.md
@@ -107,7 +107,7 @@ PowerSync syncs hard deletes natively - when a row is deleted on the server the
| `app/services/powersync/mutations.ts` | `upsertRow`, `deleteRow`, `upsertRows` |
| `app/app/components/trns/useTrnsStore.ts` | `watchTable` subscription + `reconcileTrns` echo suppression |
| `app/app/components/trns/reconcile.ts` | `reconcileTrns` - dedup and reuse unchanged row objects |
-| `app/app/plugins/powersync.client.ts` | Plugin that connects/disconnects PowerSync on auth state change |
+| `app/app/plugins/powersync.client.ts` | Connects PowerSync on sign-in; pauses it (keeps local data + queue) on involuntary session loss; explicit sign-out wipes separately |
| `app/powersync/config/sync-config.yaml` | Sync Streams rules (per-user + global rates) |
| `app/powersync/config/service.yaml` | PowerSync service config (replication, JWT, port 8080) |
| `app/supabase/powersync_setup.sql` | `powersync_role` + `powersync` publication |
diff --git a/docs/content/en/3.reference/04.offline-first.md b/docs/content/en/3.reference/04.offline-first.md
index 0c6b6ef4..a60fa802 100644
--- a/docs/content/en/3.reference/04.offline-first.md
+++ b/docs/content/en/3.reference/04.offline-first.md
@@ -35,6 +35,13 @@ When the device is offline:
No user action is needed to trigger sync after reconnect.
+## Session Loss While Offline
+
+Going offline does not sign the user out. A failed token refresh while offline is **retryable** - supabase-js keeps the persisted session (localStorage) and emits no `SIGNED_OUT`, so the route guard (`hasPersistedSession()`) keeps the user in the app and the unsynced queue keeps filling. Two cases are handled so offline writes survive:
+
+- **Reactive session not resolved yet (offline cold start).** After the access token expires, a fresh `getSession()` resolves to `null`, so the reactive `uid` is null until reconnect. Writes stamp `userId` via `resolveWriteUid(uid.value)` (`app/app/composables/useAuthSession.ts`), which falls back to the synchronously-persisted uid. Without it the row would carry an empty `userId`, which RLS rejects (`42501`) on upload - silently dropping the offline write.
+- **Session lost involuntarily (token revoked / expired server-side).** Surfaces on reconnect as a genuine `SIGNED_OUT`. The auth watcher then **pauses** sync (`pausePowerSync` - `db.disconnect()`, no clear) instead of wiping, keeping local SQLite **and the unsynced queue**. When pending writes exist, a re-auth toast is shown (`sync.errors.sessionLostPending`); re-authenticating as the same user reconnects and drains the queue. Only an **explicit** sign-out (`useUserStore.signOut()`) wipes local data via `disconnectPowerSync` → `disconnectAndClear`.
+
## Upload Error Handling
`SupabaseConnector.uploadData()` distinguishes fatal errors from retryable ones:
@@ -72,8 +79,9 @@ Client IDs are regular UUIDs (generated client-side via `crypto.randomUUID()` or
|------|------|
| `app/services/powersync/connector.ts` | `SupabaseConnector.uploadData()` - drains queue, fatal/retryable split |
| `app/services/powersync/mutations.ts` | `upsertRow`, `deleteRow` - write to local SQLite |
-| `app/services/powersync/db.ts` | `watchTable` - subscribe to SQLite changes |
-| `app/app/plugins/powersync.client.ts` | Registers upload-error handler (toast) |
+| `app/services/powersync/db.ts` | `watchTable` - subscribe to SQLite changes; `pausePowerSync` - stop sync, keep local data + queue |
+| `app/app/composables/useAuthSession.ts` | `resolveWriteUid` - persisted-uid fallback for row writes; `hasPersistedSession` route gate |
+| `app/app/plugins/powersync.client.ts` | Registers upload-error handler (toast); pauses sync (keeps data) on involuntary session loss |
| `app/app/components/trns/useTrnsStore.ts` | Optimistic write + rollback pattern, cascade delete trns |
| `app/app/components/wallets/useWalletsStore.ts` | Optimistic write + rollback + cascade delete trns |
| `app/app/components/categories/useCategoriesStore.ts` | Optimistic write + rollback + cascade delete trns |
diff --git a/docs/content/ru/3.reference/03.sync.md b/docs/content/ru/3.reference/03.sync.md
index 09840af6..2e8b3f9d 100644
--- a/docs/content/ru/3.reference/03.sync.md
+++ b/docs/content/ru/3.reference/03.sync.md
@@ -107,7 +107,7 @@ PowerSync синхронизирует жёсткие удаления нати
| `app/services/powersync/mutations.ts` | `upsertRow`, `deleteRow`, `upsertRows` |
| `app/app/components/trns/useTrnsStore.ts` | Подписка `watchTable` + подавление эха `reconcileTrns` |
| `app/app/components/trns/reconcile.ts` | `reconcileTrns` - дедупликация и переиспользование неизменённых объектов строк |
-| `app/app/plugins/powersync.client.ts` | Плагин подключения/отключения PowerSync при смене состояния авторизации |
+| `app/app/plugins/powersync.client.ts` | Подключает PowerSync при входе; ставит на паузу (сохраняя локальные данные и очередь) при непроизвольной потере сессии; явный выход стирает отдельно |
| `app/powersync/config/sync-config.yaml` | Правила Sync Streams (per-user + глобальные rates) |
| `app/powersync/config/service.yaml` | Конфиг сервиса PowerSync (репликация, JWT, порт 8080) |
| `app/supabase/powersync_setup.sql` | `powersync_role` + публикация `powersync` |
diff --git a/docs/content/ru/3.reference/04.offline-first.md b/docs/content/ru/3.reference/04.offline-first.md
index ce73719d..df74f96c 100644
--- a/docs/content/ru/3.reference/04.offline-first.md
+++ b/docs/content/ru/3.reference/04.offline-first.md
@@ -35,6 +35,13 @@ seo:
Никаких действий пользователя для запуска синхронизации после переподключения не требуется.
+## Потеря сессии в офлайне
+
+Уход в офлайн не разлогинивает пользователя. Неудачное обновление токена в офлайне считается **повторяемым** - supabase-js сохраняет персистнутую сессию (localStorage) и не шлёт `SIGNED_OUT`, поэтому роут-гард (`hasPersistedSession()`) оставляет пользователя в приложении, а несинхронизированная очередь продолжает наполняться. Два случая обрабатываются так, чтобы офлайн-записи не терялись:
+
+- **Реактивная сессия ещё не зарезолвилась (холодный старт в офлайне).** После протухания access-токена свежий `getSession()` возвращает `null`, поэтому реактивный `uid` равен null до переподключения. Записи проставляют `userId` через `resolveWriteUid(uid.value)` (`app/app/composables/useAuthSession.ts`), который откатывается к синхронно-персистнутому uid. Без этого строка получила бы пустой `userId`, который RLS отклоняет (`42501`) при загрузке - молча теряя офлайн-запись.
+- **Сессия потеряна непроизвольно (токен отозван / истёк на сервере).** Всплывает при переподключении как настоящий `SIGNED_OUT`. Тогда watcher авторизации **ставит синхронизацию на паузу** (`pausePowerSync` - `db.disconnect()`, без очистки), а не стирает, сохраняя локальную SQLite **и несинхронизированную очередь**. При наличии ожидающих записей показывается toast на повторный вход (`sync.errors.sessionLostPending`); повторная авторизация тем же пользователем переподключает и опустошает очередь. Только **явный** выход (`useUserStore.signOut()`) стирает локальные данные через `disconnectPowerSync` → `disconnectAndClear`.
+
## Обработка ошибок загрузки
`SupabaseConnector.uploadData()` разделяет фатальные ошибки и повторяемые:
@@ -72,8 +79,9 @@ seo:
|------|------|
| `app/services/powersync/connector.ts` | `SupabaseConnector.uploadData()` - опустошение очереди, разделение фатальных/повторяемых ошибок |
| `app/services/powersync/mutations.ts` | `upsertRow`, `deleteRow` - запись в локальную SQLite |
-| `app/services/powersync/db.ts` | `watchTable` - подписка на изменения SQLite |
-| `app/app/plugins/powersync.client.ts` | Регистрирует обработчик ошибок загрузки (toast) |
+| `app/services/powersync/db.ts` | `watchTable` - подписка на изменения SQLite; `pausePowerSync` - остановить синк, сохранив локальные данные и очередь |
+| `app/app/composables/useAuthSession.ts` | `resolveWriteUid` - откат на персистнутый uid при записи строк; роут-гард `hasPersistedSession` |
+| `app/app/plugins/powersync.client.ts` | Регистрирует обработчик ошибок загрузки (toast); ставит синк на паузу (сохраняя данные) при непроизвольной потере сессии |
| `app/app/components/trns/useTrnsStore.ts` | Оптимистичная запись + откат, каскадное удаление trns |
| `app/app/components/wallets/useWalletsStore.ts` | Оптимистичная запись + откат + каскадное удаление trns |
| `app/app/components/categories/useCategoriesStore.ts` | Оптимистичная запись + откат + каскадное удаление trns |