Lists Duplicating/Not Syncing [web/iOS]

The lists duplicate and don’t sync from the main account

Triage & Root Cause Analysis

  • Classification: bug (fix(sync): resolve list duplication and cross-device account syncing)
  • Priority: High / Critical
  • Affected Components: packages/hfw_core, packages/hfw_jaspr, packages/hfw_flutter, packages/hfw_server

Root Causes Identified

  1. Premature "Favorites" & Guest List Migration Before Initial Sync Completes (web_app_store_web.dart)

    • In packages/hfw_jaspr/lib/services/web_app_store_web.dart (_migrateGuestListsToAccount, lines 908–980), the check for whether "Favorites" or matching user lists exist in local SQLite (SELECT id FROM user_lists WHERE user_id = ? ...) is triggered immediately at line 204 (_initPowerSync) and line 823 (_persistAuth) before PowerSync completes its initial sync from the server.
    • Because local SQLite is still empty at that moment (existingLists.isEmpty == true), conn.createUserList(targetUserId, 'Favorites', ...) generates a brand-new UUID v4 (packages/hfw_core/lib/src/services/powersync/queries.dart:873) and uploads a duplicate "Favorites" list on every fresh session/login. The same happens in packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart (_migrateGuestListsToAccount, lines 240–281).
  2. user_list_items Missing user_id Column in Client Schema vs. PowerSync Sync Rules

    • In packages/hfw_server/powersync/sync_rules.yaml (lines 26–32), PowerSync filters list items by SELECT * FROM user_list_items WHERE user_id = bucket.user_id.
    • However, the client SQLite schema in packages/hfw_core/lib/src/services/powersync/database.dart (lines 195–204) and addHymnToList in packages/hfw_core/lib/src/services/powersync/queries.dart (lines 942–964) do not include a user_id column on user_list_items.
    • Furthermore, /api/powersync-upload in packages/hfw_server/powersync/setup.go (lines 100–225) does not inject user_id = authRecord.Id into user_list_items on PUT/PATCH, leaving user_id as NULL in PostgreSQL so items fail to replicate back to other devices via PowerSync.
  3. Split-Brain Between PocketBase (data.db) and PowerSync (PostgreSQL)

    • Both Web (web_app_store_web.dart:1446–1488) and iOS (hfw_headless_coordinator.dart:332–446) fall back to reading from the PocketBase REST API (/api/collections/user_lists/records), while all client writes go exclusively to PostgreSQL via /api/powersync-upload (setup.go:100–225).
    • On Web (web_app_store_web.dart:1462), once a single local list (such as the auto-created "Favorites" list) exists in local PowerSync SQLite (rows.isNotEmpty), getHymnLists() skips the PocketBase fallback entirely—making main account lists stored in PocketBase disappear.
    • On iOS (hfw_headless_coordinator.dart:332–359), _mergeUserListsAndCounts() merges both _remoteUserLists (PocketBase) and _localUserLists (PowerSync) by id, causing duplicate entries when IDs differ and resurrecting deleted lists that still exist in PocketBase.

Proposed Fix

  1. Wait for PowerSync initial sync completion (waitForFirstSync / hasSynced) before running _migrateGuestListsToAccount or seeding a default "Favorites" list, and deduplicate "Favorites" by normalized name/deterministic ID.
  2. Add Column.text('user_id') to user_list_items in database.dart and queries.dart, and enforce op.Data["user_id"] = authRecord.Id on server upload (setup.go) so sync_rules.yaml replicates all list items across devices.
  3. Unify user_lists and user_list_items storage so PocketBase and PostgreSQL stay synchronized without split-brain reads/writes.

:white_check_mark: Fixed across Server, Web, iOS/iPadOS, and Android:

  • PostgreSQL / PowerSync Backfill (packages/hfw_server/powersync/setup.go): Backfilled missing user_id on user_list_items from parent user_lists during InitDb() so pre-migration list items sync into the user’s PowerSync bucket, and updated PATCH/DELETE handling in /api/powersync-upload to match items whose user_id was previously NULL/empty.
  • Duplicate List Deduplication & Item Merging (packages/hfw_core, packages/hfw_jaspr, packages/hfw_flutter): Deduplicated user_lists by normalized path/name (LOWER(TRIM(name))) per user while preferring the list row that owns items, merged user_list_items across duplicate list IDs sharing the same normalized name, parsed JSON metadata.hymn_id fallbacks, and matched hymns by both id and number.
  • Pure Local PowerSync Queries: Removed all legacy PocketBase HTTP fallback queries so all lists, list items, and history read strictly from the local PowerSync SQLite database.

Comment by dkladd:

I tried this in the web version today and it’s not loading any lists current. Shows no lists on web version. I can see historic lists on iOS but not web for some reason

Pushed another version last night, can you test on web again?

Status Update & Technical Audit (Web vs. iOS List Sync)

Hi @dkladd — following up on your Oct 16 report (“Shows no lists on web version. I can see historic lists on iOS but not web for some reason”). Here is a summary of what was deployed later on Oct 16 after your comment, along with the remaining edge cases we identified in our audit of the Web + iOS list sync pipeline.


1. Fixes Deployed Later on Oct 16 (After Your 10:13 AM Report)

At the time of your test on the morning of Oct 16, Web list sync was still blocked by three issues that were patched later that afternoon/evening:

  1. Web PowerSync Blocked Behind 41.1 MB Library Bucket (f189a4a — Oct 16, 7:23 PM)
    • What happened: Previously, the Web client had to finish downloading and indexing the entire library_data bucket (~41 MB of hymn metadata/assets into browser WASM SQLite) before PowerSync would finish syncing user_data (user_lists and user_list_items). On Web, this frequently stalled or showed 0 lists.
    • Fix: Added a dedicated fast-path endpoint (GET /v1/users/me/lists-sync in packages/hfw_jaspr/lib/main.server.dart) that streams only the authenticated user’s user_data bucket in ~130ms, plus direct HTTP write-through (/api/powersync-upload) and 8-second foreground polling in WebAppStore.
  2. Web Auth User ID & Self-Healing Token Refresh (24174cc — Oct 16, 12:44 PM)
    • What happened: If the cached PocketBase user record in localStorage was missing id or the token expired, Web defaulted to local_guest and filtered out account lists.
    • Fix: Added JWT payload fallback (WebListRecordMapper.resolveUserId), automatic token refresh on 401/403 in HttpPowerSyncConnector, localStorage snapshot caching (hfw_cached_user_lists_v2), and the Repair Sync & Clear Cache action in the account menu.
  3. Guest-to-Account List & CRUD Migration (0079e3d — Oct 16, 1:03 PM)
    • Fix: Preserved custom list item portions/metadata in cache and rewrote pending local_guest entries in ps_crud to the signed-in user_id instead of purging them on sign-in.

2. Why Historic Lists Can Still Appear on iOS While Missing on Web (Open Root Causes)

If you are still seeing historic lists on iOS that do not appear on Web even after refreshing Web (or running Repair Sync & Clear Cache), our codebase audit identified four specific scenarios that explain the discrepancy:

  1. Historic iOS Lists Stored Only in Local SQLite (Never Uploaded to Server)
    • Where: packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart (_initPowerSync lines 993–999, _listsSub lines 1444–1461).
    • Mechanism: iOS renders the Lists tab directly from its local powersync3.db SQLite tables (user_lists / user_list_items). However, PowerSync only uploads local rows to PostgreSQL when they have pending entries in the ps_crud queue.
    • If your iOS token had expired during a previous launch, HfwHeadlessCoordinator._initPowerSync executed DELETE FROM ps_crud when !_authService.isAuthenticated (line 994) or DELETE FROM ps_crud WHERE data LIKE '%local_guest%' (line 997). That leaves the historic lists visible locally in iOS’s user_lists table while wiping the upload queue—so those lists never reach the server or Web.
  2. iOS Destructive Logout on Token Expiry vs. Silent Refresh
    • Where: packages/hfw_flutter/lib/injection.dart (lines 88–93) and packages/hfw_flutter/lib/services/auth/auth_service.dart (lines 225–228).
    • Mechanism: On iOS, HttpPowerSyncConnector.onAuthFailure is wired directly to AuthService.logout(). If the PocketBase token expires while iOS is attempting to upload list changes in uploadData(), it triggers logout(), and on the next launch any un-uploaded ps_crud entries are deleted.
  3. Missing Guest-to-Account List Migration on iOS
    • Where: packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart (lines 996–999) vs. packages/hfw_jaspr/lib/services/web_app_store_web.dart (_migrateGuestListsToUser, lines 1183–1207).
    • Mechanism: Web migrates lists created while signed out (user_id = 'local_guest') to the authenticated user’s ID on login. iOS does not run this migration and currently deletes local_guest ps_crud mutations on startup.
  4. Web /v1/users/me/lists-sync Authoritative Empty Override Risk
    • Where: packages/hfw_jaspr/lib/main.server.dart (lines 300–360) and packages/hfw_jaspr/lib/services/web_app_store_web.dart (lines 830–920).
    • Mechanism: When /v1/users/me/lists-sync returns HTTP 200, Web sets _hasSyncedListsFromServerHttp = true and getHymnLists() stops falling back to local WASM PowerSync SQLite. If the server stream times out at 8 seconds or the bucket checkpoint returns 0 lines before sync-complete, Web will authoritatively display an empty list.

3. Quick Diagnostic Check for @dkladd

Could you check two quick things when you have a moment?

  1. On Web: Do a hard refresh / open the Account menu and click Repair Sync & Clear Cache to ensure your browser is running the post-f189a4a build.
  2. On iOS: Try renaming one of the historic lists (or adding/removing a hymn inside it) while signed in on iOS.
    • If that list immediately appears on Web afterward, it confirms Root Cause #1 (the historic lists exist in iOS local SQLite, and touching the list creates a fresh ps_crud entry that uploads it to the server).

4. Proposed Action Plan to Close This Out Permanently

  • iOS Local-to-Server List Reconciliation: On iOS startup (when authenticated), inspect local user_lists and user_list_items in powersync3.db and enqueue/upload any existing local lists & items to /api/powersync-upload so historic local-only iOS lists automatically sync to the server without requiring manual edits.
  • Non-Destructive iOS Auth Failure Handling: Stop deleting ps_crud on transient auth failures in HfwHeadlessCoordinator._initPowerSync; mirror Web’s WebListRecordMapper.rewriteGuestCrudData migration on iOS so offline/guest lists are migrated to the signed-in user rather than dropped.
  • Harden /v1/users/me/lists-sync: Only mark _hasSyncedListsFromServerHttp = true when the PowerSync stream confirmed completion (or merge with local WASM SQLite rather than replacing non-empty local lists with an incomplete stream).

Cross-Platform Applicability & Audit Matrix (iOS/iPadOS, macOS, Android, Web)

To ensure our fixes for Issue #16 cover every client in the monorepo, we audited how iOS/iPadOS, macOS, Android, and Web manage list storage, deduplication, auth lifecycle, and PowerSync synchronization.

Architecture Overview

  • iOS/iPadOS, macOS, and Android all run the exact same headless Dart engine (packages/hfw_flutter/lib/main.dart → HfwHeadlessCoordinator) and configureDependencies() (packages/hfw_flutter/lib/injection.dart), bridged via Pigeon (HfwHeadlessFlutterApi / HfwNativeHostApi).
    • iOS/iPadOS & macOS share the same SwiftUI HfwStore (packages/hfw_flutter/ios/Runner/HfwStore.swift) and list views (packages/hfw_flutter/ios/Runner/HfwListsAndSettingsViews.swift), with macOS hosting HfwRootView inside packages/hfw_flutter/macos/Runner/MainFlutterWindow.swift.
    • Android uses Jetpack Compose with HfwStore.kt (packages/hfw_flutter/android/app/src/main/kotlin/com/appleeducate/hfw/HfwStore.kt) and HfwListsComposeViews.kt.
    • Neither HfwStore.swift (iOS/macOS) nor HfwStore.kt (Android) persists lists in UserDefaults or SharedPreferences; both hold purely in-memory reactive state (@Published var listsExplorer / MutableStateFlow<NativeListsExplorerStateDto?>) pushed by HfwHeadlessCoordinator.
  • Web (packages/hfw_jaspr/lib/services/web_app_store_web.dart) uses its own store (WebAppStore) combining browser WASM PowerSync SQLite (powersync_web_v3.db), localStorage snapshot caches (hfw_cached_user_lists_v2 / hfw_cached_list_items_v2), direct HTTP write-through (/api/powersync-upload), and the fast-path GET /v1/users/me/lists-sync endpoint.

Cross-Platform Audit Matrix

Mechanism / Edge Case iOS / iPadOS macOS Android Web (hfw_jaspr) Exact File & Line References
1. Un-uploaded local SQLite lists (DELETE FROM ps_crud on startup) Affected Affected Affected Fixed (0079e3d) Native: packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart:993-999
Web: packages/hfw_jaspr/lib/services/web_app_store_web.dart:1126-1180
2. Destructive onAuthFailure -> logout() (deletes saved account & token on 401/403) Affected Affected Affected Not Affected (non-destructive) Native DI: packages/hfw_flutter/lib/injection.dart:88-93
Native Auth: packages/hfw_flutter/lib/services/auth/auth_service.dart:225-228, 283-289
Web: packages/hfw_jaspr/lib/services/web_app_store_web.dart:1022-1046
3. Missing local_guest → Account list migration on sign-in Affected Affected Affected Fixed (24174cc, 0079e3d) Native: packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart:996-999
Web: packages/hfw_jaspr/lib/services/web_app_store_web.dart:1183-1207
4. Unauthenticated importListJson creates orphaned local_guest lists Affected (via Siri/Files/Menu) Affected (via Cmd+Shift+I / Dock / File open) Affected (via ACTION_SEND intent / file open) Not Affected (migrates on sign-in) Native Coordinator: packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator_lists_auth.dart:1113-1156
macOS Menu: packages/hfw_flutter/macos/Runner/AppDelegate.swift:150-152
Android Intent: packages/hfw_flutter/android/app/src/main/kotlin/com/appleeducate/hfw/MainActivity.kt:98-114
5. Fast-path HTTP list sync (GET /v1/users/me/lists-sync) & direct /api/powersync-upload write-through Not Used (waits for full PowerSync checkpoint) Not Used (waits for full PowerSync checkpoint) Not Used (waits for full PowerSync checkpoint) Enabled (f189a4a) Web: packages/hfw_jaspr/lib/services/web_app_store_web.dart:759-1003
Server: packages/hfw_jaspr/lib/main.server.dart:227-395
6. /v1/users/me/lists-sync 8s stream timeout authoritative empty-list override N/A N/A N/A Affected Server: packages/hfw_jaspr/lib/main.server.dart:300-360
Web: packages/hfw_jaspr/lib/services/web_app_store_web_lists.dart:734-743
7. Legacy Documents/powersync3.db → Application Support/powersync3.db file migration iOS-Only (skips if target DB already exists) N/A (always used Application Support) N/A (always used filesDir) N/A (OPFS/IndexedDB) packages/hfw_flutter/lib/injection.dart:104-144
packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart:974-986, 1087-1175
8. Case-insensitive list name deduplication & item merging Implemented Implemented Implemented Implemented Native: packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart:1344-1406
Shared Queries: packages/hfw_core/lib/src/services/powersync/queries.dart:718-761, 910-985
Web: packages/hfw_jaspr/lib/services/web_app_store_web.dart:683-736

Detailed Platform Findings

1. Shared Native Engine Issues (Affecting iOS/iPadOS, macOS, and Android Identically)

Because all three native platforms initialize HfwHeadlessCoordinator (packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart) and configureDependencies() (packages/hfw_flutter/lib/injection.dart), they share four identical list-sync vulnerabilities:

  1. Startup ps_crud Wipe (hfw_headless_coordinator.dart:993-999):
    • On every app launch across iOS, macOS, and Android, _performInitialization() executes:
      • if (!_authService.isAuthenticated) await _database.db.execute('DELETE FROM ps_crud');
      • else await _database.db.execute("DELETE FROM ps_crud WHERE data LIKE '%local_guest%' OR data LIKE '%user_hymn_history%'");
    • Any un-uploaded list mutations remain in the local user_lists / user_list_items SQLite tables (so they render locally on that device via _listsSub at hfw_headless_coordinator.dart:1444-1461), but their ps_crud upload entries are permanently deleted—so they never upload to PostgreSQL or appear on other devices.
  2. Destructive onAuthFailure -> logout() (injection.dart:88-93 & auth_service.dart:225-228, 283-289):
    • On iOS, macOS, and Android, onAuthFailure calls getIt<AuthService>().logout(), which calls removeAccount(_userId!)—removing the account from _savedAccounts (or switching to another saved account) and clearing _token. If a device’s token fails refresh during fetchCredentials() or uploadData(), the user is logged out and the next launch wipes ps_crud.
  3. Unauthenticated importListJson Bypass (hfw_headless_coordinator_lists_auth.dart:1113-1156):
    • While the Lists tab UI on SwiftUI (HfwListsAndSettingsViews.swift:94) and Compose (HfwListsComposeViews.kt:172) shows a sign-in prompt when logged out, importListJson does not check _authService.isAuthenticated (unlike createList at line 549).
    • Users can trigger importListJson while signed out via:
      • macOS: Menu bar File -> Import Hymn List (JSON)… (Cmd+Shift+I, macos/Runner/AppDelegate.swift:150-152) or opening a .json file from Finder (AppDelegate.swift:56-68).
      • iOS/iPadOS: OpenHymnFileIntent Siri Shortcut (HfwStoreSystemIntegration.swift:1458-1497), hardware keyboard Cmd+Shift+I (ios/Runner/AppDelegate.swift:181-187), or opening a .json file from Files/AirDrop.
      • Android: Sharing a JSON list via Intent.ACTION_SEND (MainActivity.kt:98-114) or opening a .json file URI (MainActivity.kt:142-146).
    • When invoked while signed out, importListJson writes the list into SQLite with _effectiveUserId == 'local_guest', which is then stripped from ps_crud (powersync_connector.dart:149-151 and hfw_headless_coordinator.dart:997) and never migrated when the user signs in.
  4. No Fast-Path List Sync or Direct Write-Through on Native:
    • Unlike Web (_performSyncListsFromServerHttp + _uploadCrudDirect), iOS, macOS, and Android rely exclusively on the PowerSync streaming WebSocket/HTTP sync loop (Database._doConnect in packages/hfw_core/lib/src/services/powersync/database.dart:267-317). On a fresh install on Android, macOS, or iOS, user_lists may wait behind the initial library_data sync checkpoint unless fast-path list sync is also enabled in HfwHeadlessCoordinator.

2. iOS-Specific Legacy Database Migration Edge Case (injection.dart:110-143)

  • On iOS/iPadOS only, configureDependencies() migrates Documents/powersync3.db to Application Support/powersync3.db:
    • if (!await targetDb.exists() && await legacyDb.exists()) { ... rename ... } else { ... delete legacyDb ... } (injection.dart:116-140).
    • If Application Support/powersync3.db was ever created first (for example, during an unauthenticated launch before migration), the else branch deletes Documents/powersync3.db. Neither macOS nor Android ever stored powersync3.db in Documents.

Updated Cross-Platform Action Plan

  1. Shared Native + Core (iOS/iPadOS, macOS, Android):
    • In HfwHeadlessCoordinator._performInitialization (hfw_headless_coordinator.dart:990-1000), replace DELETE FROM ps_crud with non-destructive WebListRecordMapper.rewriteGuestCrudData / shouldPurgeCrudEntry and migrate any user_lists / user_list_items with user_id = 'local_guest' to the authenticated userId on sign-in (matching Web).
    • Add a Local-to-Server List Reconciliation pass in HfwHeadlessCoordinator when authenticated (and direct HTTP write-through /v1/users/me/lists-sync + /api/powersync-upload) so existing local SQLite lists on iOS, macOS, and Android immediately upload to PostgreSQL and sync down without waiting for the 41 MB library_data bucket.
    • Make onAuthFailure in packages/hfw_flutter/lib/injection.dart:88-93 non-destructive so transient auth failures do not wipe saved accounts or pending ps_crud list mutations.
  2. Web (hfw_jaspr):
    • Include a complete status flag in GET /v1/users/me/lists-sync (main.server.dart:300-385) so WebAppStore only marks _hasSyncedListsFromServerHttp = true when the PowerSync bucket stream finished (sync-complete), preventing an 8s stream timeout from hiding local lists.

Cross-Platform Implementation Summary (Issue #16)

Implemented the cross-platform fixes for Lists Duplicating/Not Syncing [web/iOS] across Shared Native Coordinator (iOS/iPadOS/macOS/Android) and Web (hfw_jaspr):

  1. Non-Destructive ps_crud & Guest List Migration (packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart)

    • Replaced the destructive startup DELETE FROM ps_crud / DELETE FROM ps_crud WHERE data LIKE '%local_guest%' with _sanitizePsCrudQueue(preserveUserListsAndItems: true) and _migrateGuestListsToUser(targetUid) using WebListRecordMapper.rewriteGuestCrudData(...) and WebListRecordMapper.shouldPurgeCrudEntry(..., preserveUserListsAndItems: true).
    • Deduplicates any guest lists (local_guest / empty user_id) whose normalized name matches an existing user list (such as "Favorites"), reassigning their user_list_items to the canonical list ID before removing the duplicate guest list row.
    • Hooked _migrateGuestListsToUser and _reconcileLocalListsToServer into both startup (_performInitialization) and session auth changes (_rebindUserScopedStreams).
  2. Historic Local-to-Server List Reconciliation (packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart)

    • Added _reconcileLocalListsToServer(String userId) and _uploadRecordToServerHttp(...) to push local user_lists and user_list_items from powersync3.db to /api/powersync-upload (normalizing type: 'custom' -> 'hymns'), recovering historic lists on iOS/macOS/Android whose ps_crud rows were previously cleared.
  3. Resilient PowerSync Auth Failure Handling (packages/hfw_flutter/lib/injection.dart, packages/hfw_flutter/lib/services/auth/auth_service.dart)

    • Updated onAuthFailure to invoke AuthService.handlePowerSyncAuthFailure(statusCode, responseBody) rather than immediately calling logout().
    • Guarded refreshSession() and handlePowerSyncAuthFailure() with WebListRecordMapper.isJwtExpiredOrInvalid(...) so transient 401/403 responses from PowerSync do not wipe valid user sessions.
  4. Web /api/user-lists Checkpoint Completeness Guard (packages/hfw_jaspr/lib/main.server.dart, packages/hfw_jaspr/lib/services/web_app_store_web.dart)

    • Added 'complete': isComplete alongside 'checkpoint_completed' in /api/user-lists (main.server.dart).
    • Updated _performSyncListsFromServerHttp (web_app_store_web.dart) to inspect isComplete and preserve local/cached lists when an 8-second stream timeout returns an incomplete empty snapshot, only setting _hasSyncedListsFromServerHttp = true when isComplete || nextListsSnapshot.isNotEmpty.
  5. Universal Search scope == 'lists' Sorting (packages/hfw_flutter/lib/src/native_bridge/hfw_headless_coordinator.dart)

    • Updated matchingLists.sort in _runSearchAndPush to honor 'updatedDesc' and 'updatedAsc' in addition to 'titleDesc'/'nameDesc' and 'titleAsc'/'nameAsc' with naturalCompare.