diff --git a/CHANGELOG.md b/CHANGELOG.md index 81de85dfa..7e81d9c22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ - Every practice is optional: Practice shows only installed ones. Wim Hof comes installed and can be removed; Meditation and Breathing Patterns come with the app and are added without a download. - Manage practices lists every practice with its size and one button: Install, Buy for a paid practice, Cancel while it downloads, or Uninstall once it is on Practice. Uninstalling a downloaded practice asks once, then frees the space; one that comes with the app just leaves Practice. Drag a practice by its handle onto another to change the order Practice shows them in. Your progress stays either way. - Lumi asks to download or unlock a practice before starting one that isn't on your device. +- A new install comes with Lumi, Habits and Practice, in that order; add Lists, Diary and Leaderboard from More apps. The apps you install or remove and the order of your pinned apps follow your account to your other devices, and a newly signed-in device takes your account's apps instead of replacing them. ### Removed - Donations: the reminder, About's Donate button and Lumi's donation links. Dew is how you pay in Inner Breeze. ### Fixed diff --git a/docs/cells.md b/docs/cells.md index 132cd42f4..23ea8e553 100644 --- a/docs/cells.md +++ b/docs/cells.md @@ -381,12 +381,29 @@ configuration above; a checked build does not establish that configuration. ## Account app choices +A new profile comes with Lumi, Habits and Practice installed and pinned, in +that order; Lists, Diary and Leaderboard are added from More apps. Existing +profiles keep their apps. + Sync v6 uses `private.inbe.v1.app-preferences`. Each of the six `app_used_*` keys is a separate timestamped record, including explicit zero values for removals. Independent changes merge without overwriting unrelated selections. Pending local choices win equal timestamps; newer remote choices win. -Invalid keys, values and timestamps cannot alter preferences. Versions, package -paths, release sequence floors and the automatic-update preference stay local. +Invalid keys, values and timestamps cannot alter preferences. Released +versions reject an unknown key in this collection and stop syncing, so a new +app's choice needs its own collection. A choice nobody made, such as a new +profile's apps, is stored at time 1 (`AppDefaultTime`) and never uploaded, so +a new device takes the account's apps instead of replacing them. + +The pinned apps and their order are one record, `app_order`, in +`private.inbe.v1.app-order`: package names separated by commas, such as +`lumi,habits,practices`, at most 255 bytes. It is sent only when the owner +pins, moves or unpins an app. The newest order wins and a pending local order +wins a tie; versions that don't know the collection skip it, and a record this +version can't read changes nothing without stopping the sync. An arriving +order sets `app_order_received`, and the pins take it once. An app removed on +another device is unpinned here too. Versions, package paths, release +sequence floors and the automatic-update preference stay local. All apps share the existing account, SQLite database and outbox. Diary entries and photos use the owner-only encrypted cell collection on that same sync account. Per-account files provide a local cache; they are not the only copy. diff --git a/src/app/app_launcher.zi b/src/app/app_launcher.zi index 3911e9f54..60aa01987 100644 --- a/src/app/app_launcher.zi +++ b/src/app/app_launcher.zi @@ -384,7 +384,7 @@ app_draw_launcher :: (app: *InnerBreeze) { app.launcher_favorite_count = LauncherPlaceFavorite( app.launcher_favorites[:], app.launcher_favorite_count, app.launcher_drag_route, target) - save_settings(app) + app_launcher_pins_changed(app) } } else if query.count == 0 && scrolled.opened && PointInBounds(point.x, point.y, scrolled.viewport) && @@ -393,7 +393,7 @@ app_draw_launcher :: (app: *InnerBreeze) { app.launcher_favorite_count = LauncherToggleFavorite( app.launcher_favorites[:], app.launcher_favorite_count, app.launcher_drag_route) - save_settings(app) + app_launcher_pins_changed(app) } app.launcher_drag_key = 0 app.launcher_drag_moving = false diff --git a/src/app/app_launcher_state.zi b/src/app/app_launcher_state.zi index 590abc03e..fd3b6fa19 100644 --- a/src/app/app_launcher_state.zi +++ b/src/app/app_launcher_state.zi @@ -20,20 +20,32 @@ app_launcher_is_favorite :: (app: *InnerBreeze, route: s32) -> bool { app.launcher_favorite_count, route) } +// The owner pinned, moved or unpinned an app. The pins and their order go +// to the account's other devices with the next sync. +app_launcher_pins_changed :: (app: *InnerBreeze) { + app_save_app_order(app) + save_settings(app) +} + app_launcher_uninstall :: (app: *InnerBreeze, route: s32) { bit := app_nav_route_bit(route) if bit == 0 { return } mask := app.enabled_apps & ~bit if !CellsSetEnabled(mask) { return } app.enabled_apps = mask - if app_launcher_is_favorite(app, route) { + pinned := app_launcher_is_favorite(app, route) + if pinned { app.launcher_favorite_count = LauncherToggleFavorite( app.launcher_favorites[:], app.launcher_favorite_count, route) } app.launcher_drag_key = 0 app.launcher_drag_moving = false app_update_app_navigation(app) - save_settings(app) + if pinned { + app_launcher_pins_changed(app) + } else { + save_settings(app) + } app_block_current_click(app) } diff --git a/src/app/app_nav_state.zi b/src/app/app_nav_state.zi index 76f6191f3..8c909073d 100644 --- a/src/app/app_nav_state.zi +++ b/src/app/app_nav_state.zi @@ -16,6 +16,7 @@ #import, file "../platform/environment.zi"; #import, file "route_list.zi"; #import, file "bottom_nav_policy.zi"; +#import, file "launcher_policy.zi"; #import, file "app_route_state.zi"; #import, file "locale.zi"; #import, file "text_buffers.zi"; @@ -67,6 +68,7 @@ app_nav_route_available :: (app: *InnerBreeze, route: s32) -> bool { c :: #system_library "c"; app_leave_practice_config :: (app: *InnerBreeze) #foreign c; save_settings :: (app: *InnerBreeze) #foreign c; +app_take_app_order :: (app: *InnerBreeze, order: string) -> bool #foreign c; sync_account_load :: (account: *AccountKeys) -> s32 #foreign c; storage_get_setting_text :: (key: string) -> string #foreign c; @@ -797,6 +799,7 @@ app_update_app_navigation :: (app: *InnerBreeze, add_cells: s32 = 0) { app_sanitize_bottom_nav_routes(app) } +// After a sync, the apps and pins the account's other devices changed. #program_export app_reload_app_choices :: (app: *InnerBreeze) { previous_mask := app.enabled_apps @@ -810,7 +813,27 @@ app_reload_app_choices :: (app: *InnerBreeze) { mask &= ~bit } } + pins_changed := false + if SettingsReadInt(AppOrderReceivedKey, 0) != 0 { + pins_changed = app_take_app_order(app, storage_get_setting_text(AppOrderKey)) + } + // An app removed on another device is unpinned here too, as when it + // is removed on this one. + removed := previous_mask & ~mask + routes := LauncherRoutes() + for index: cast(s32)0..cast(s32)routes.count - 1 { + route := routes[index] + if (app_nav_route_bit(route) & removed) != 0 && + RouteListContains(app.launcher_favorites[:], app.launcher_favorite_count, route) { + app.launcher_favorite_count = LauncherToggleFavorite( + app.launcher_favorites[:], app.launcher_favorite_count, route) + pins_changed = true + } + } if mask == app.enabled_apps { + if pins_changed { + save_settings(app) + } return } app.enabled_apps = mask @@ -826,4 +849,5 @@ app_reload_app_choices :: (app: *InnerBreeze) { app.breathing.screen = ScreenAppSelection } } + save_settings(app) } diff --git a/src/app/app_settings.zi b/src/app/app_settings.zi index 6f3739718..b75f09f65 100644 --- a/src/app/app_settings.zi +++ b/src/app/app_settings.zi @@ -75,10 +75,11 @@ load_bottom_nav_routes :: (app: *InnerBreeze) { if app == null { return } + // A new profile's apps, Lumi, Habits and Practice, in their order. app.bottom_nav_route_count = SettingsCacheInt("bottom_nav_route_count", 4) app.bottom_nav_routes[0] = - SettingsCacheInt("bottom_nav_route_0", APP_NAV_ROUTE_ELIST) + SettingsCacheInt("bottom_nav_route_0", APP_NAV_ROUTE_LUMI) app.bottom_nav_routes[1] = SettingsCacheInt("bottom_nav_route_1", APP_NAV_ROUTE_HABITS) app.bottom_nav_routes[2] = @@ -112,10 +113,60 @@ load_bottom_nav_routes :: (app: *InnerBreeze) { app.launcher_favorites[:], app.launcher_favorite_count, route) } } else { - app.launcher_favorite_count = LauncherDefaults(app.launcher_favorites[:], - DesktopPlatform() != 0) + app.launcher_favorite_count = LauncherDefaults(app.launcher_favorites[:]) } } + // Pins another device of the account changed arrived before this device + // took them, for example when it closed during a practice. + if SettingsCacheInt(AppOrderReceivedKey, 0) != 0 { + order: [LAUNCHER_ORDER_TEXT_MAX + 1]u8 + unused SettingsCacheCopyText(AppOrderKey, order[:]) + unused app_take_app_order(app, AppTextFromCString(*order[0], LAUNCHER_ORDER_TEXT_MAX + 1)) + } +} + +// The pinned apps another device of the account sent replace this device's +// pins, once: a later change here stays here until the owner changes pins. +#program_export +app_take_app_order :: (app: *InnerBreeze, order: string) -> bool { + routes: [LAUNCHER_APP_COUNT]s32 + count := LauncherOrderRoutes(order, routes[:]) + changed := count != app.launcher_favorite_count + for index: cast(s32)0..count - 1 { + if routes[index] != app.launcher_favorites[index] { + changed = true + } + } + for index: cast(s32)0..count - 1 { + app.launcher_favorites[index] = routes[index] + } + app.launcher_favorite_count = count + if changed { + save_launcher_favorites(app) + } + unused SettingsStoreInt(AppOrderReceivedKey, 0) + return changed +} + +// The owner changed the pins: their order goes to the account's other +// devices. A default or an order from another device is never sent back. +app_save_app_order :: (app: *InnerBreeze) { + if app == null || TelegramHostPresent() { + return + } + order: [LAUNCHER_ORDER_TEXT_MAX + 1]u8 + unused LauncherOrderText(app.launcher_favorites[:], app.launcher_favorite_count, order[:]) + unused SettingsStoreText(AppOrderKey, order[:]) +} + +save_launcher_favorites :: (app: *InnerBreeze) { + save_setting_int("launcher_favorite_count", app.launcher_favorite_count) + save_setting_int("launcher_favorite_0", app.launcher_favorites[0]) + save_setting_int("launcher_favorite_1", app.launcher_favorites[1]) + for index: cast(s32)2..cast(s32)app.launcher_favorites.count - 1 { + key := SettingsKeyIndexed("launcher_favorite_", index, "") + unused SettingsStoreInt(AppTextFromCString(*key.bytes[0], 48), app.launcher_favorites[index]) + } } default_theme_source :: () -> s32 { @@ -209,13 +260,7 @@ save_settings :: (app: *InnerBreeze) { save_setting_int("navigation_mode", app.navigation_mode) save_setting_int("navigation_placement", app.navigation_placement) save_setting_int("navigation_collapsed", app.nav_rail_collapsed) - save_setting_int("launcher_favorite_count", app.launcher_favorite_count) - save_setting_int("launcher_favorite_0", app.launcher_favorites[0]) - save_setting_int("launcher_favorite_1", app.launcher_favorites[1]) - for index: cast(s32)2..cast(s32)app.launcher_favorites.count - 1 { - key := SettingsKeyIndexed("launcher_favorite_", index, "") - unused SettingsStoreInt(AppTextFromCString(*key.bytes[0], 48), app.launcher_favorites[index]) - } + save_launcher_favorites(app) save_setting_int("profile_picture_icon", app.profile_picture_icon) save_setting_int("bottom_nav_route_count", app.bottom_nav_route_count) save_setting_int("bottom_nav_route_0", app.bottom_nav_routes[0]) @@ -754,10 +799,10 @@ app_load_settings :: (app: *InnerBreeze) -> s32 { app.exercise_manual_seen_mask = manual_seen_mask & ((1 << EXERCISE_COUNT) - 1) load_language_setting(app, settings_missing) - // Existing profiles retain their app choices. Fresh profiles open the Apps - // library with every bundled app available, without an install chooser. + // Existing profiles retain their app choices. A new profile comes with + // Lumi, Habits and Practice; the other apps are added from More apps. app.enabled_apps = SettingsCacheInt("enabled_apps", - ifx settings_missing != 0 then APP_ALL else APP_LISTS | APP_RECOMMENDED) & APP_ALL + ifx settings_missing != 0 then APP_RECOMMENDED else APP_LISTS | APP_RECOMMENDED) & APP_ALL for index: cast(s32)1..cast(s32)(PackageCount - 1) { key := PackagePreferenceKey(index) if SettingsCacheContains(key) { @@ -772,17 +817,18 @@ app_load_settings :: (app: *InnerBreeze) -> s32 { } // Ordinary profiles migrate their saved app choices. A hosted delegate // reads those choices without creating owner preference outbox rows. + // A new profile already has Lumi among its default apps. if !TelegramHostPresent() && !SettingsCacheContains("lumi_introduced") { - if !SettingsCacheContains("app_used_lumi") { + if settings_missing == 0 && !SettingsCacheContains("app_used_lumi") { app.enabled_apps |= APP_LUMI save_setting_int("app_used_lumi", 1) } save_setting_int("enabled_apps", app.enabled_apps) save_setting_int("lumi_introduced", 1) } - // Leaderboard moved from Profile into its own app. Fresh profiles start - // with every app; existing ones get it installed once. Removing it later - // is respected. + // Leaderboard moved from Profile into its own app. Existing profiles get + // it installed once, and removing it later is respected. New profiles + // add it from More apps. if !TelegramHostPresent() && !SettingsCacheContains("leaderboard_introduced") { if settings_missing == 0 && !SettingsCacheContains("app_used_leaderboard") { app.enabled_apps |= APP_LEADERBOARD @@ -791,6 +837,17 @@ app_load_settings :: (app: *InnerBreeze) -> s32 { } save_setting_int("leaderboard_introduced", 1) } + // Apps nobody chose, such as a new profile's, are stored as defaults: a + // choice from the account's other devices replaces them, and they are + // never sent, so a new device cannot remove the account's apps. + if !TelegramHostPresent() { + for index: cast(s32)1..cast(s32)(PackageCount - 1) { + key := PackagePreferenceKey(index) + if !SettingsCacheContains(key) { + unused SettingsStoreDefaultBool(key, (app.enabled_apps & PackageBit(index)) != 0) + } + } + } app.apps_selected = SettingsCacheInt("apps_setup_done", ifx settings_missing != 0 then 0 else 1) diff --git a/src/app/bottom_nav_policy.zi b/src/app/bottom_nav_policy.zi index 35dc1dd99..5fd4bb43a 100644 --- a/src/app/bottom_nav_policy.zi +++ b/src/app/bottom_nav_policy.zi @@ -5,16 +5,16 @@ using AppNavRoute; BOTTOM_NAV_MAX_ROUTES :: 7 +// The apps a new profile comes with, in their order, then Settings. BottomNavDefaults :: (routes: []s32) -> s32 { if routes.count < 5 { return 0 } routes[0] = APP_NAV_ROUTE_LUMI - routes[1] = APP_NAV_ROUTE_ELIST - routes[2] = APP_NAV_ROUTE_HABITS - routes[3] = APP_NAV_ROUTE_PRACTICE - routes[4] = APP_NAV_ROUTE_SETTINGS - return 5 + routes[1] = APP_NAV_ROUTE_HABITS + routes[2] = APP_NAV_ROUTE_PRACTICE + routes[3] = APP_NAV_ROUTE_SETTINGS + return 4 } BottomNavSanitize :: (routes: []s32, count: s32, diff --git a/src/app/launcher_policy.zi b/src/app/launcher_policy.zi index e8d9abf3e..280279d96 100644 --- a/src/app/launcher_policy.zi +++ b/src/app/launcher_policy.zi @@ -14,12 +14,12 @@ LauncherRoutes :: () -> [LAUNCHER_APP_COUNT]s32 { APP_NAV_ROUTE_LEADERBOARD} } -// Leaderboard is installed with the other apps but is not pinned. -LauncherDefaults :: (routes: []s32, desktop: bool) -> s32 { - defaults: [5]s32 = .{APP_NAV_ROUTE_LUMI, - APP_NAV_ROUTE_HABITS, APP_NAV_ROUTE_PRACTICE, - APP_NAV_ROUTE_ELIST, APP_NAV_ROUTE_DIARY} - count := cast(s32)(ifx desktop then 5 else 3) +// A new profile comes with Lumi, Habits and Practice installed and pinned, +// in this order. Every other app is added from More apps. +LauncherDefaults :: (routes: []s32) -> s32 { + defaults: [3]s32 = .{APP_NAV_ROUTE_LUMI, + APP_NAV_ROUTE_HABITS, APP_NAV_ROUTE_PRACTICE} + count := cast(s32)defaults.count if routes.count < count { return 0 } for index: cast(s32)0..count - 1 { routes[index] = defaults[index] @@ -27,6 +27,74 @@ LauncherDefaults :: (routes: []s32, desktop: bool) -> s32 { return count } +// The pinned order syncs between an account's devices as package names, the +// names in src/cells/catalog.zi, so it means the same apps on every version. +LAUNCHER_ORDER_TEXT_MAX :: 255 + +LauncherRouteName :: (route: s32) -> string { + if route == APP_NAV_ROUTE_DIARY { return "diary" } + if route == APP_NAV_ROUTE_HABITS { return "habits" } + if route == APP_NAV_ROUTE_ELIST { return "lists" } + if route == APP_NAV_ROUTE_LUMI { return "lumi" } + if route == APP_NAV_ROUTE_PRACTICE { return "practices" } + if route == APP_NAV_ROUTE_LEADERBOARD { return "leaderboard" } + return "" +} + +LauncherRouteForName :: (name: string) -> s32 { + if name.count == 0 { return APP_NAV_ROUTE_NONE } + routes := LauncherRoutes() + for index: cast(s32)0..cast(s32)routes.count - 1 { + if LauncherRouteName(routes[index]) == name { return routes[index] } + } + return APP_NAV_ROUTE_NONE +} + +// Writes the pinned apps as names separated by commas and returns the +// length. The output always ends with a zero byte. +LauncherOrderText :: (routes: []s32, count: s32, output: []u8) -> s32 { + if output.count == 0 { return 0 } + length: s32 = 0 + limit := count + if limit > cast(s32)routes.count { limit = cast(s32)routes.count } + for index: cast(s32)0..limit - 1 { + name := LauncherRouteName(routes[index]) + if name.count == 0 { continue } + needed := cast(s32)name.count + if length > 0 { needed += 1 } + if length + needed >= cast(s32)output.count { break } + if length > 0 { + output[length] = cast(u8)44 + length += 1 + } + for byte: name { + output[length] = byte + length += 1 + } + } + output[length] = cast(u8)0 + return length +} + +// Reads an order written by any version. Apps this version doesn't have +// are left out, and the others keep their order. +LauncherOrderRoutes :: (text: string, routes: []s32) -> s32 { + count: s32 = 0 + start: s64 = 0 + while start <= text.count { + end := start + while end < text.count && text[end] != cast(u8)44 { end += 1 } + route := LauncherRouteForName(text[start:end]) + if route != APP_NAV_ROUTE_NONE && count < cast(s32)routes.count && + !RouteListContains(routes, count, route) { + routes[count] = route + count += 1 + } + start = end + 1 + } + return count +} + LauncherSanitizeFavorites :: (routes: []s32, count: s32) -> s32 { allowed := LauncherRoutes() return RouteListSanitize(routes, count, allowed[:]) diff --git a/src/app/screenshots.zi b/src/app/screenshots.zi index efb021ed5..cbada917a 100644 --- a/src/app/screenshots.zi +++ b/src/app/screenshots.zi @@ -916,6 +916,9 @@ setup_screenshot_scene :: (app: *InnerBreeze, request: *ScreenshotRequest) { app.close_prompt_open = 1 app.close_prompt_result = cast(AppClosePromptResult)AppClosePromptNone } else if scene_text == "data_from_navigation" { + // Data opens from Lists, which a new profile adds from More apps. + app.enabled_apps |= APP_LISTS + unused CellsSetEnabled(app.enabled_apps) app.main_tab = APP_MAIN_TAB_ELIST app.breathing.screen = ScreenEList app_apply_nav_route(app, APP_NAV_ROUTE_DATA) diff --git a/src/app/settings_store.zi b/src/app/settings_store.zi index 4d4a78b11..f6bfd5a3e 100644 --- a/src/app/settings_store.zi +++ b/src/app/settings_store.zi @@ -8,6 +8,7 @@ c :: #system_library "c"; storage_set_setting_int :: (key: string, value: s32) #foreign c; storage_set_setting_text :: (key: string, value: string) #foreign c; +storage_set_setting_default_text :: (key: string, value: string) #foreign c; storage_get_setting_int :: (key: string, fallback: s32) -> s32 #foreign c; storage_list_settings :: (callback: SettingVisitor, user: *void) -> s32 #foreign c; storage_settings_empty :: () -> s32 #foreign c; @@ -95,6 +96,21 @@ SettingsStoreInt :: (key: string, value: s32) -> bool { return SettingsStoreKeyInt(SettingsKeyText(key), value) } +// A default the owner didn't choose. It never replaces a saved value, and +// a synced choice from the account replaces it. +SettingsStoreDefaultBool :: (key: string, value: bool) -> bool { + setting_key := SettingsKeyText(key) + if !SettingsKeyValid(setting_key) { + return false + } + if DataTemporary() { + return true + } + storage_set_setting_default_text(AppTextFromCString(*setting_key.bytes[0], setting_key.count + 1), + ifx value then "1" else "0") + return true +} + SettingsStoreText :: (key: string, value: []u8) -> bool { return SettingsStoreKeyText(SettingsKeyText(key), value) } diff --git a/src/app/web_actions.zi b/src/app/web_actions.zi index c440a388a..6bb8925ce 100644 --- a/src/app/web_actions.zi +++ b/src/app/web_actions.zi @@ -763,8 +763,8 @@ using AppThemeSource; if app == null { return } - // First-start Apps now includes every bundled application. Keep that - // same package set while the browser checks navigation during playback. + // The browser checks navigation through every bundled application + // during playback, so they are all installed for it. if CellsSetEnabled(APP_ALL) { app.enabled_apps = APP_ALL app.apps_selected = 1 diff --git a/src/cells/catalog.zi b/src/cells/catalog.zi index df672f59d..90b7c31d9 100644 --- a/src/cells/catalog.zi +++ b/src/cells/catalog.zi @@ -35,6 +35,16 @@ PackagePreferenceKey :: (index: s32) -> string { return keys[index] } +// The pinned apps' order syncs as one record of package names, in its own +// collection: a version that doesn't know it skips it. +AppOrderKey :: "app_order" +AppOrderCollection :: "private.inbe.v1.app-order" +// Set when another device's order arrives, until the pins take it. +AppOrderReceivedKey :: "app_order_received" +// A default is stored at this time, older than any choice, so a choice from +// the account replaces it. Defaults are never uploaded. +AppDefaultTime :: 1 + AppPreferenceValid :: (key: string) -> bool { return key == "app_used_lists" || key == "app_used_habits" || key == "app_used_practices" || key == "app_used_diary" || key == "app_used_lumi" || diff --git a/src/storage/storage_core.zi b/src/storage/storage_core.zi index b92359e70..d7475a705 100644 --- a/src/storage/storage_core.zi +++ b/src/storage/storage_core.zi @@ -395,7 +395,10 @@ storage_enqueue_all_sync_state :: () { exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'elist_item',id,0,strftime('%s','now') FROM elist_items WHERE user_id=(SELECT id FROM users LIMIT 1) ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at") exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit_entry',id,0,strftime('%s','now') FROM habit_entries WHERE user_id=(SELECT id FROM users LIMIT 1) ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at") exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit_change',id,0,strftime('%s','now') FROM habit_changes WHERE user_id=(SELECT id FROM users LIMIT 1) ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at") - exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'app_preference',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND key IN ('app_used_lists','app_used_habits','app_used_practices','app_used_diary','app_used_lumi','app_used_leaderboard') ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at") + // A default app choice (stored at AppDefaultTime) is not a choice and + // never goes out, so a new device cannot replace the account's apps. + exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'app_preference',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND key IN ('app_used_lists','app_used_habits','app_used_practices','app_used_diary','app_used_lumi','app_used_leaderboard') AND updated_at>1 ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at") + exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'app_order',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND key='app_order' AND updated_at>1 ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at") exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'cell_record',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND (key LIKE 'cell.lumi.%' OR key LIKE 'cell.diary.%' OR key LIKE 'cell.feedback.%') ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at") if owns_transaction != 0 { exec_sql("COMMIT") @@ -736,12 +739,41 @@ storage_set_setting_text :: (key: string, value: string) { if AppPreferenceValid(key) { unused storage_enqueue_sync_entity("app_preference", key, 0) } + if key == AppOrderKey { + unused storage_enqueue_sync_entity("app_order", key, 0) + } if storage_state_handle().settings_write_depth <= 0 { storage_schedule_persist() } } } +// Stores a default the owner didn't choose, such as a new profile's apps. +// It never replaces a saved value, is never uploaded, and is stored at +// AppDefaultTime, so a choice from the account's other devices replaces it. +#program_export +storage_set_setting_default_text :: (key: string, value: string) { + statement: *void = null + if storage_db_handle() == null || key.count == 0 { + return + } + if SqlitePrepareText(storage_db_handle(), + "INSERT INTO settings(user_id,key,value,updated_at) VALUES(?1,?2,?3,?4) ON CONFLICT(user_id,key) DO NOTHING", + -1, *statement, null) != SQLITE_OK { + return + } + bind_text(statement, 1, AppTextFromCString(storage_user_id_buffer(), 64)) + bind_text(statement, 2, key) + bind_text(statement, 3, value) + SqliteBindInt64(statement, 4, AppDefaultTime) + rc := SqliteStep(statement) + SqliteFinalize(statement) + if rc == SQLITE_DONE && sqlite3_changes(storage_db_handle()) > 0 && + storage_state_handle().settings_write_depth <= 0 { + storage_schedule_persist() + } +} + #program_export storage_settings_begin_write :: () { database := storage_db_handle() @@ -1294,6 +1326,18 @@ storage_append_app_preference_payload_json :: (json: *StorageJsonBuilder, key: s if !AppPreferenceValid(key) { return 0 } + return storage_append_setting_record_json(json, key, 16) +} + +storage_append_app_order_payload_json :: (json: *StorageJsonBuilder, key: string) -> s32 { + if key != AppOrderKey { + return 0 + } + return storage_append_setting_record_json(json, key, 256) +} + +// One setting as a synced record: its key, value and the time it changed. +storage_append_setting_record_json :: (json: *StorageJsonBuilder, key: string, value_capacity: s32) -> s32 { statement: *void = null if SqlitePrepareText(storage_db_handle(), "SELECT value,updated_at FROM settings WHERE user_id=?1 AND key=?2", -1, @@ -1311,7 +1355,7 @@ storage_append_app_preference_payload_json :: (json: *StorageJsonBuilder, key: s storage_json_builder_append_text(json, "{") storage_json_builder_key_value_text(json, "key", key) storage_json_builder_append_text(json, ",") - storage_json_builder_key_value_text(json, "value", AppTextFromCString(SqliteColumnText(statement, 0), 16)) + storage_json_builder_key_value_text(json, "value", AppTextFromCString(SqliteColumnText(statement, 0), value_capacity)) storage_json_builder_append_text(json, ",\"updated_at\":") storage_json_builder_append_epoch(json, SqliteColumnInt64(statement, 1)) storage_json_builder_append_text(json, "}") @@ -1342,6 +1386,8 @@ storage_append_sync_op_payload :: (json: *StorageJsonBuilder, entity_type: strin found = storage_append_cell_payload_json(json, entity_id) } else if entity_type == "app_preference" { found = storage_append_app_preference_payload_json(json, entity_id) + } else if entity_type == "app_order" { + found = storage_append_app_order_payload_json(json, entity_id) } else if storage_compare_text(entity_type, "habit") == 0 { found = storage_append_habit_payload_json(json, entity_id) @@ -1376,6 +1422,9 @@ storage_encrypted_collection_for_entity :: (entity_type: string, entity_id: stri if entity_type == "app_preference" { return "private.inbe.v1.app-preferences" } + if entity_type == "app_order" { + return AppOrderCollection + } if entity_type.count == 0 { return "" } @@ -2127,6 +2176,9 @@ storage_decrypted_array_name :: (collection: string) -> string { if collection == "private.inbe.v1.app-preferences" { return "app_preferences" } + if collection == AppOrderCollection { + return "app_order" + } if storage_compare_text(collection, "private.inbe.v1.habits") == 0 { return "habits" } @@ -2296,6 +2348,17 @@ storage_apply_decrypted_record :: (collection: string, record_id: string, plaint if ok != 0 { storage_set_setting_int("apps_setup_done", 1) } + } else if array_name == "app_order" { + // A record this version can't read, such as another key a newer + // version adds here, changes nothing and doesn't stop the sync. + records := Scan.FieldAt(record_response, Scan.FieldAt(record_response, 0, "changes"), "app_order") + ok = 1 + if Scan.ArrayCount(record_response, records) == 1 { + ok = storage_exec_json_user_sql(SyncAppOrderSQL, record_response) + if ok != 0 && sqlite3_changes(storage_db_handle()) > 0 { + storage_set_setting_int(AppOrderReceivedKey, 1) + } + } } else if storage_compare_text(array_name, "habits") == 0 { ok = ifx (storage_reconcile_remote_habit_ids(record_response) != 0 && storage_apply_sync_habits_json(record_response) != 0) then (1) else (0) diff --git a/src/storage/sync_sql.zi b/src/storage/sync_sql.zi index 916d0b58a..b58f86ec7 100644 --- a/src/storage/sync_sql.zi +++ b/src/storage/sync_sql.zi @@ -165,6 +165,25 @@ OR (excluded.updated_at = settings.updated_at AND NOT EXISTS ( )) SQL +// The pinned apps' order from another device: the newest order wins, and a +// pending local order wins a tie. The value is a list of package names. +SyncAppOrderSQL :: #string SQL +INSERT INTO settings(user_id,key,value,updated_at) +SELECT ?2,'app_order',json_extract(value,'$.value'), + CAST(strftime('%s',json_extract(value,'$.updated_at')) AS INTEGER) +FROM json_each(?1,'$.changes.app_order') +WHERE json_extract(value,'$.key')='app_order' +AND json_type(value,'$.value')='text' +AND length(CAST(json_extract(value,'$.value') AS BLOB))<=255 +AND strftime('%s',json_extract(value,'$.updated_at')) IS NOT NULL +ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value,updated_at=excluded.updated_at +WHERE excluded.updated_at > settings.updated_at +OR (excluded.updated_at = settings.updated_at AND excluded.value != settings.value AND NOT EXISTS ( + SELECT 1 FROM sync_outbox WHERE entity_type='app_order' + AND entity_id=settings.key AND local_date=0 +)) +SQL + // Local unacknowledged edits win ties; a remote record never queues itself. SyncCellRecordsSQL :: #string SQL INSERT INTO settings(user_id,key,value,updated_at) diff --git a/src/widgets/bottom_nav.zi b/src/widgets/bottom_nav.zi index 4cb140571..3daaa6b65 100644 --- a/src/widgets/bottom_nav.zi +++ b/src/widgets/bottom_nav.zi @@ -270,7 +270,7 @@ app_draw_dock :: (app: *InnerBreeze, over_practice: bool) { app.launcher_favorite_count = LauncherPlaceFavorite( app.launcher_favorites[:], app.launcher_favorite_count, app.launcher_drag_route, result.drop_index) - save_settings(app) + app_launcher_pins_changed(app) } app.launcher_drag_key = 0 app.launcher_drag_moving = false diff --git a/tests/app_nav_state_link_test.c b/tests/app_nav_state_link_test.c index 2b7d25d22..cbe82b818 100644 --- a/tests/app_nav_state_link_test.c +++ b/tests/app_nav_state_link_test.c @@ -46,12 +46,11 @@ int main(void) memset(&app, 0, sizeof(app)); app_reset_bottom_nav_routes(&app); - assert(app.bottom_nav_route_count == 5); + assert(app.bottom_nav_route_count == 4); assert(app.bottom_nav_routes[0] == AppNavRoute_APP_NAV_ROUTE_LUMI); - assert(app.bottom_nav_routes[1] == AppNavRoute_APP_NAV_ROUTE_ELIST); - assert(app.bottom_nav_routes[2] == AppNavRoute_APP_NAV_ROUTE_HABITS); - assert(app.bottom_nav_routes[3] == AppNavRoute_APP_NAV_ROUTE_PRACTICE); - assert(app.bottom_nav_routes[4] == AppNavRoute_APP_NAV_ROUTE_SETTINGS); + assert(app.bottom_nav_routes[1] == AppNavRoute_APP_NAV_ROUTE_HABITS); + assert(app.bottom_nav_routes[2] == AppNavRoute_APP_NAV_ROUTE_PRACTICE); + assert(app.bottom_nav_routes[3] == AppNavRoute_APP_NAV_ROUTE_SETTINGS); account_present = 0; account_alias = ""; app_nav_profile_identity(&app, out, sizeof(name), sub, sizeof(subtitle)); diff --git a/tests/app_preferences_sync_test.py b/tests/app_preferences_sync_test.py index 39a47dfca..a8d2e44c1 100644 --- a/tests/app_preferences_sync_test.py +++ b/tests/app_preferences_sync_test.py @@ -54,4 +54,33 @@ assert value("cells_auto_update") == "0" assert value("package_sequence_diary") == "10" assert value("app_used_lists") == "1" assert value("app_used_practices") == "1" -print("Account app choices: removals, independent merge, conflict handling, account isolation and device settings passed") + +# The pinned apps' order: the newest wins, a pending local order wins a tie, +# and a record this version can't read changes nothing. +order_sql = re.search(r"SyncAppOrderSQL :: #string SQL\n(.*?)\nSQL", source, re.S)[1] + + +def order(value, timestamp, key="app_order"): + record = dict(key=key, value=value, updated_at=timestamp) + database.execute(order_sql, (json.dumps(dict(changes=dict(app_order=[record]))), "account")) + + +order("lumi,diary,habits", "1970-01-01T00:03:20Z") +assert value("app_order") == "lumi,diary,habits", "a first order was not taken" +order("practices", "1970-01-01T00:01:40Z") +assert value("app_order") == "lumi,diary,habits", "an older order replaced a newer one" +database.execute("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('app_order','app_order',0,200)") +order("habits", "1970-01-01T00:03:20Z") +assert value("app_order") == "lumi,diary,habits", "a remote order beat a pending local one at the same time" +order("diary", "1970-01-01T00:05:00Z") +assert value("app_order") == "diary" +order("lumi", "1970-01-01T00:10:00Z", key="app_order_tablet") +order("lumi", "invalid") +order("x" * 256, "1970-01-01T00:10:00Z") +record = dict(key="app_order", value=dict(apps="lumi"), updated_at="1970-01-01T00:10:00Z") +database.execute(order_sql, (json.dumps(dict(changes=dict(app_order=[record]))), "account")) +assert value("app_order") == "diary", "an unreadable order changed the pins" +assert database.execute("SELECT COUNT(*) FROM settings WHERE key='app_order_tablet'").fetchone()[0] == 0 +order("", "1970-01-01T00:10:00Z") +assert value("app_order") == "", "an empty order did not unpin everything" +print("Account app choices: removals, independent merge, conflict handling, account isolation, device settings and pinned order passed") diff --git a/tests/bottom_nav_policy_behavior.zi b/tests/bottom_nav_policy_behavior.zi index f439e7401..b827f9024 100644 --- a/tests/bottom_nav_policy_behavior.zi +++ b/tests/bottom_nav_policy_behavior.zi @@ -7,11 +7,10 @@ using AppNavRoute; Answer :: () -> s32 { routes: [7]s32 count := BottomNavDefaults(routes[:]) - if count != 5 || routes[0] != APP_NAV_ROUTE_LUMI || - routes[1] != APP_NAV_ROUTE_ELIST || - routes[2] != APP_NAV_ROUTE_HABITS || - routes[3] != APP_NAV_ROUTE_PRACTICE || - routes[4] != APP_NAV_ROUTE_SETTINGS { return 2 } + if count != 4 || routes[0] != APP_NAV_ROUTE_LUMI || + routes[1] != APP_NAV_ROUTE_HABITS || + routes[2] != APP_NAV_ROUTE_PRACTICE || + routes[3] != APP_NAV_ROUTE_SETTINGS { return 2 } routes[0] = APP_NAV_ROUTE_HABITS routes[1] = APP_NAV_ROUTE_PROFILE routes[2] = APP_NAV_ROUTE_SETTINGS @@ -52,8 +51,8 @@ Answer :: () -> s32 { count = BottomNavSanitize(limited[:], 5, false) if count != 5 || limited[4] != APP_NAV_ROUTE_SETTINGS { return 12 } count = BottomNavSanitize(routes[:], 9, true) - if count != 5 || routes[0] != APP_NAV_ROUTE_LUMI || - routes[4] != APP_NAV_ROUTE_SETTINGS { return 9 } + if count != 4 || routes[0] != APP_NAV_ROUTE_LUMI || + routes[3] != APP_NAV_ROUTE_SETTINGS { return 9 } short: [2]s32 if BottomNavDefaults(short[:]) != 0 || diff --git a/tests/cells_onboarding_test.py b/tests/cells_onboarding_test.py index 315b3a4d8..9110ea724 100644 --- a/tests/cells_onboarding_test.py +++ b/tests/cells_onboarding_test.py @@ -119,8 +119,21 @@ with tempfile.TemporaryDirectory(prefix="inbe-app-choices-") as temporary: saved = settings(profile) assert saved["apps_setup_done"] == "0" assert saved["language_setup_done"] == "1" - assert saved["enabled_apps"] == "63" - assert [int(saved[f"launcher_favorite_{i}"]) for i in range(5)] == [12, 1, 2, 3, 11] + # A new profile comes with Lumi, Habits and Practice, pinned in that + # order. They are defaults, not choices: stored at time 1 and not + # queued, so an account's apps replace them after sign-in. + assert saved["enabled_apps"] == "22" + assert saved["launcher_favorite_count"] == "3" + assert [int(saved[f"launcher_favorite_{i}"]) for i in range(3)] == [12, 1, 2] + with sqlite3.connect(profile / "inbe.db", timeout=5) as db: + defaults = {key: (value, updated) for key, value, updated in db.execute( + "SELECT key,value,updated_at FROM settings WHERE key LIKE 'app_used_%'")} + queued = db.execute("SELECT COUNT(*) FROM sync_outbox WHERE entity_type IN " + "('app_preference','app_order')").fetchone()[0] + assert defaults == {f"app_used_{name}": (str(int(name in ("habits", "practices", "lumi"))), 1) + for name in ("lists", "habits", "practices", "diary", "lumi", "leaderboard")}, defaults + assert queued == 0, "a new profile queued its default apps" + assert "app_order" not in saved, "a new profile sent its default pins" # Closing before opening a tile keeps first-start Apps on restart. with application(profile, "resume-apps") as (window, log): capture(window, "resumed-apps") @@ -146,7 +159,8 @@ with tempfile.TemporaryDirectory(prefix="inbe-app-choices-") as temporary: tap(window, 180, 104) command("xdotool", "type", "--clearmodifiers", "Lists") time.sleep(.3) - tap(window, 180, 228) + # Lists is not installed, so its card is the first in More apps. + tap(window, 180, 270) wait_setting(profile, "apps_setup_done", 1) wait_setting(profile, "main_tab", 2) assert "screen=21->16" in log.read_text(), log.read_text() @@ -290,7 +304,7 @@ with tempfile.TemporaryDirectory(prefix="inbe-app-choices-") as temporary: capture(window, "existing-data-lists") result.update( first_start_apps_library=True, system_language=True, - default_favorites_lumi_habits_practices=True, restart_in_onboarding=True, + default_apps_lumi_habits_practice=True, default_apps_not_sent=True, restart_in_onboarding=True, open_tile_completes_setup=True, explicit_feature_cli=True, same_runtime_feature_property=True, mini_lists_only_and_zero_apps=True, mini_starts_practice_without_profile_writes=True, diff --git a/tests/flow_fake/http_transfer.zi b/tests/flow_fake/http_transfer.zi index f61218e72..24a132355 100644 --- a/tests/flow_fake/http_transfer.zi +++ b/tests/flow_fake/http_transfer.zi @@ -108,6 +108,15 @@ HttpTransferPoll :: (transfer: *HttpTransfer, status: *s32) -> s32 { return 1 } +// As Kryon's: HttpTransferPoll that also gives the answer's length, which +// the flows' answers do not have. +HttpTransferPollLength :: (transfer: *HttpTransfer, status: *s32, length: *s64) -> s32 { + if length != null { + length.* = 0 + } + return HttpTransferPoll(transfer, status) +} + HttpTransferCancel :: (transfer: *HttpTransfer) { operation := FlowFindOperation(transfer.handle) if operation != null { diff --git a/tests/launcher_policy_behavior.zi b/tests/launcher_policy_behavior.zi index c01524fd3..67d76aa59 100644 --- a/tests/launcher_policy_behavior.zi +++ b/tests/launcher_policy_behavior.zi @@ -6,16 +6,43 @@ using AppNavRoute; #program_export Answer :: () -> s32 { favorites: [LAUNCHER_APP_COUNT]s32 - if LauncherDefaults(favorites[:], true) != 5 || - favorites[0] != APP_NAV_ROUTE_LUMI || favorites[4] != APP_NAV_ROUTE_DIARY { + // A new profile pins Lumi, Habits and Practice, in that order, on every + // device; the other apps wait in More apps. + if LauncherDefaults(favorites[:]) != 3 || + favorites[0] != APP_NAV_ROUTE_LUMI || favorites[1] != APP_NAV_ROUTE_HABITS || + favorites[2] != APP_NAV_ROUTE_PRACTICE { return 18 } - // Leaderboard is installed with every profile but never pinned by default. - for index: cast(s32)0..cast(s32)4 { - if favorites[index] == APP_NAV_ROUTE_LEADERBOARD { return 20 } + short: [2]s32 + if LauncherDefaults(short[:]) != 0 { return 19 } + order: [LAUNCHER_ORDER_TEXT_MAX + 1]u8 + length := LauncherOrderText(favorites[:], 3, order[:]) + if length != 21 || TextView(order[:length]) != "lumi,habits,practices" || order[length] != cast(u8)0 { + return 20 } - if LauncherDefaults(favorites[:], false) != 3 || - favorites[2] != APP_NAV_ROUTE_PRACTICE { return 19 } + // Every app round-trips by name; unknown and repeated names drop out. + read: [LAUNCHER_APP_COUNT]s32 + if LauncherOrderRoutes("diary,chess,lumi,,diary,leaderboard,lists", read[:]) != 4 || + read[0] != APP_NAV_ROUTE_DIARY || read[1] != APP_NAV_ROUTE_LUMI || + read[2] != APP_NAV_ROUTE_LEADERBOARD || read[3] != APP_NAV_ROUTE_ELIST { + return 22 + } + if LauncherOrderRoutes("", read[:]) != 0 || LauncherOrderText(read[:], 0, order[:]) != 0 || + order[0] != cast(u8)0 { + return 23 + } + every := LauncherRoutes() + length = LauncherOrderText(every[:], cast(s32)every.count, order[:]) + if LauncherOrderRoutes(TextView(order[:length]), read[:]) != LAUNCHER_APP_COUNT { + return 24 + } + for index: cast(s32)0..LAUNCHER_APP_COUNT - 1 { + if read[index] != every[index] { return 25 } + } + // A full buffer keeps whole names only. + tiny: [12]u8 + length = LauncherOrderText(favorites[:], 3, tiny[:]) + if length != 11 || TextView(tiny[:length]) != "lumi,habits" { return 26 } favorites[0] = APP_NAV_ROUTE_HABITS favorites[1] = APP_NAV_ROUTE_PRACTICE count := LauncherToggleFavorite(favorites[:], 2, APP_NAV_ROUTE_DIARY) diff --git a/tests/launcher_ui_test.py b/tests/launcher_ui_test.py index def20f522..94e964e5e 100644 --- a/tests/launcher_ui_test.py +++ b/tests/launcher_ui_test.py @@ -274,7 +274,8 @@ with contextlib.ExitStack() as stack: user = db.execute("SELECT id FROM users WHERE kind='local' LIMIT 1").fetchone()[0] assert settings(profile)["language_setup_done"] == "0", "Fresh start skipped the language picker" assert settings(profile)["apps_setup_done"] == "0" - assert favorites(profile) == [12, 1, 2, 3, 11], "Desktop defaults omitted installed apps" + assert favorites(profile) == [12, 1, 2], "New profiles do not pin Lumi, Habits and Practice" + assert settings(profile)["enabled_apps"] == "22", "New profiles do not install Lumi, Habits and Practice" assert settings(profile)["theme"] == "9" and settings(profile)["theme_source"] == "0" assert settings(profile)["theme_mode"] == "2" # Merely opening and closing the picker does not complete setup. diff --git a/tests/leaderboard_ui_test.py b/tests/leaderboard_ui_test.py index adbf4edb1..f91bf637e 100644 --- a/tests/leaderboard_ui_test.py +++ b/tests/leaderboard_ui_test.py @@ -84,10 +84,11 @@ with tempfile.TemporaryDirectory(prefix="inbe-leaderboard-") as directory: saved = dict(db.execute("SELECT key,value FROM settings WHERE user_id=?", (user,))) favorites = [int(saved[f"launcher_favorite_{i}"]) for i in range(int(saved.get("launcher_favorite_count", 0)))] - assert int(saved["enabled_apps"]) & 32, "Leaderboard is not installed for a new profile" + # A new profile adds Leaderboard from More apps. + assert not int(saved["enabled_apps"]) & 32, "Leaderboard was installed for a new profile" assert LEADERBOARD_ROUTE not in favorites, "Leaderboard was pinned by default" settings = {"language": "en", "language_system": 0, "language_setup_done": 1, - "apps_setup_done": 1, "main_tab": 5, "tutorial_seen": 1, + "apps_setup_done": 1, "app_used_leaderboard": 1, "main_tab": 5, "tutorial_seen": 1, "habits_guide_seen": 1, "lumi_guides_seen": 127, "launcher_guide_seen": 1, "package_updates_allowed": 0, "apps_last_update_check": 1900000000, # Pinned here, so the page has no "back to Apps" bar and diff --git a/tests/startup_quit_ui_test.py b/tests/startup_quit_ui_test.py index 6d8940344..91ff4ecb5 100644 --- a/tests/startup_quit_ui_test.py +++ b/tests/startup_quit_ui_test.py @@ -125,19 +125,19 @@ with tempfile.TemporaryDirectory(prefix="inbe-startup-quit-") as temporary, cont saved = settings(profile) assert saved["enabled_apps"] == "22", "Startup changed saved app preferences" order = [int(saved[f"launcher_favorite_{i}"]) for i in range(int(saved["launcher_favorite_count"]))] - assert order == [12, 1, 2, 3, 11], "Desktop defaults omitted an installed app: " + str(order) + assert order == [12, 1, 2], "Defaults are not Lumi, Habits and Practice: " + str(order) deadline = time.monotonic() + 2 while "->0" not in log.read_text(): assert time.monotonic() < deadline, "Practices click was ignored\n" + log.read_text() time.sleep(.05) command("import", "-window", window, str(OUTPUT / "practices-open.png")) - # Diary is pinned but not installed, so the dock leaves it out; - # its card in the Apps library installs and opens it. + # Diary is not installed; its card in More apps installs and + # opens it. click(window, 44, 660) # Apps, in the sidebar's bottom corner. time.sleep(.4) - # Diary, the fifth pinned card: Apps fits five 144 wide cards - # in a row at this width. - click(window, 804, 228) + # Diary, the first card in More apps, under the row of three + # pinned cards. + click(window, 160, 380) deadline = time.monotonic() + 2 while "screen=0->22" not in log.read_text(): assert time.monotonic() < deadline, "Diary click was ignored\n" + log.read_text() diff --git a/tests/storage_sync_behavior.zi b/tests/storage_sync_behavior.zi index 4318445d6..a69e4f6c6 100644 --- a/tests/storage_sync_behavior.zi +++ b/tests/storage_sync_behavior.zi @@ -26,6 +26,7 @@ #import, file "../src/cells/diary_records.zi"; #import, file "../src/cells/package_files.zi"; #import, file "../src/storage/cell_records.zi"; +#import, file "../src/cells/catalog.zi"; #import, file "../src/storage/sync_nodes.zi"; #import, file "../src/storage/sync_node_storage.zi"; #import, file "../src/storage/sqlite.zi"; @@ -1836,6 +1837,137 @@ test_cell_records_round_trip :: () { storage_close() } +// The app choices a new profile starts with, stored as defaults. +store_default_apps :: () { + storage_set_setting_default_text("app_used_lists", "0") + storage_set_setting_default_text("app_used_habits", "1") + storage_set_setting_default_text("app_used_practices", "1") + storage_set_setting_default_text("app_used_diary", "0") + storage_set_setting_default_text("app_used_lumi", "1") + storage_set_setting_default_text("app_used_leaderboard", "0") +} + +// A new device's default apps are never sent, so they cannot remove the +// account's apps. The owner's choices reach the account's other devices, +// each app on its own, and an older record never undoes a newer choice. +test_app_choices_sync_between_devices :: () { + first := make_root("sync-apps-a") + second := make_root("sync-apps-b") + check_true("init apps device a", storage_init(first) != 0) + set_account() + store_default_apps() + storage_set_setting_default_text("app_used_diary", "1") + check_true("a default never replaces a stored value", storage_get_setting_text("app_used_diary") == "0") + check_int("defaults are stored at the oldest time", + read_db_count("SELECT COUNT(*) FROM settings WHERE key LIKE 'app_used_%' AND updated_at=1"), 6) + check_int("defaults are not queued", read_db_count("SELECT COUNT(*) FROM sync_outbox"), 0) + // The owner installs Diary and removes Habits on device A. + storage_set_setting_int("app_used_diary", 1) + storage_set_setting_int("app_used_habits", 0) + check_true("device a payload", build_payload()) + check_int("only the owner's two choices go out", + read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='app_preference'"), 2) + check_true("choices go in the app preferences collection", + contains(payload(), "private.inbe.v1.app-preferences")) + copy: TextBuffer + append(*copy, records_array()) + storage_close() + + check_true("init apps device b", storage_init(second) != 0) + set_account() + store_default_apps() + check_true("device b payload", build_payload()) + check_true("a new device's defaults never go out", + !contains(payload(), "private.inbe.v1.app-preferences")) + check_true("device b applies a's choices", + storage_apply_sync_response_json(response_with(3, TextFromCString(*copy.bytes[0]))) != 0) + check_true("Diary installed on a is installed on b", storage_get_setting_text("app_used_diary") == "1") + check_true("Habits removed on a is removed on b", storage_get_setting_text("app_used_habits") == "0") + check_true("b keeps its other apps", + storage_get_setting_text("app_used_practices") == "1" && storage_get_setting_text("app_used_lists") == "0") + check_int("b does not send a's choices back", + read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='app_preference'"), 0) + // An older device's record of an earlier choice does not undo Diary. + check_true("an older choice applies without error", + storage_apply_decrypted_record("private.inbe.v1.app-preferences", "app_used_diary", + "{\"key\":\"app_used_diary\",\"value\":\"0\",\"updated_at\":\"2023-11-14T22:13:20Z\"}") != 0) + check_true("an older choice keeps the newer one", storage_get_setting_text("app_used_diary") == "1") + check_true("a later removal applies", + storage_apply_decrypted_record("private.inbe.v1.app-preferences", "app_used_diary", + "{\"key\":\"app_used_diary\",\"value\":\"0\",\"updated_at\":\"2030-03-17T17:46:40Z\"}") != 0) + check_true("the later removal wins", storage_get_setting_text("app_used_diary") == "0") + storage_close() +} + +app_order_received :: () -> s32 { + return storage_get_setting_int(AppOrderReceivedKey, 0) +} + +// The pinned apps' order goes to the account's other devices in its own +// collection, which older versions skip. The newest order wins, a pending +// local order wins a tie, and a record this version can't read changes +// nothing without stopping the sync. +test_app_order_syncs_between_devices :: () { + first := make_root("sync-order-a") + second := make_root("sync-order-b") + check_true("init order device a", storage_init(first) != 0) + set_account() + storage_set_setting_text(AppOrderKey, "lumi,diary,habits") + check_true("order payload", build_payload()) + check_true("the order has its own collection", contains(payload(), "private.inbe.v1.app-order")) + check_true("the order is encrypted", !contains(payload(), "lumi,diary,habits")) + copy: TextBuffer + append(*copy, records_array()) + storage_close() + + check_true("init order device b", storage_init(second) != 0) + set_account() + check_true("device b applies the order", + storage_apply_sync_response_json(response_with(4, TextFromCString(*copy.bytes[0]))) != 0) + check_true("b has a's order", storage_get_setting_text(AppOrderKey) == "lumi,diary,habits") + check_int("b's pins take the order", app_order_received(), 1) + check_int("b does not send a's order back", + read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='app_order'"), 0) + storage_set_setting_int(AppOrderReceivedKey, 0) + check_true("an older order applies without error", + storage_apply_decrypted_record(AppOrderCollection, AppOrderKey, + "{\"key\":\"app_order\",\"value\":\"practices\",\"updated_at\":\"2023-11-14T22:13:20Z\"}") != 0) + check_true("an older order keeps the newer one", storage_get_setting_text(AppOrderKey) == "lumi,diary,habits") + check_int("an older order is not taken", app_order_received(), 0) + unreadable: [4]string = .[ + "{\"key\":\"app_order_tablet\",\"value\":\"lumi\",\"updated_at\":\"2030-03-17T17:46:40Z\"}", + "{\"key\":\"app_order\",\"value\":{\"apps\":\"lumi\"},\"updated_at\":\"2030-03-17T17:46:40Z\"}", + "{\"key\":\"app_order\",\"value\":\"lumi\"}", + "{\"key\":\"app_order\",\"value\":\"lumi\",\"updated_at\":\"2030-03-17T17:46:40Z\"},{\"key\":\"app_order\",\"value\":\"diary\",\"updated_at\":\"2030-03-17T17:46:40Z\"}" + ] + for plaintext: unreadable { + check_true("an unreadable order doesn't stop the sync", + storage_apply_decrypted_record(AppOrderCollection, AppOrderKey, plaintext) != 0) + } + check_true("an unreadable order changes nothing", storage_get_setting_text(AppOrderKey) == "lumi,diary,habits") + check_int("an unreadable order is not taken", app_order_received(), 0) + // The owner changes the pins on b while a's same-time order is on its way. + storage_set_setting_text(AppOrderKey, "habits") + exec_db_sql("UPDATE settings SET updated_at=1800000000 WHERE key='app_order'") + check_int("b's own order is queued", + read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='app_order'"), 1) + check_true("a same-time order applies without error", + storage_apply_decrypted_record(AppOrderCollection, AppOrderKey, + "{\"key\":\"app_order\",\"value\":\"diary\",\"updated_at\":\"2027-01-15T08:00:00Z\"}") != 0) + check_true("a pending local order wins a tie", storage_get_setting_text(AppOrderKey) == "habits") + check_true("a later order applies", + storage_apply_decrypted_record(AppOrderCollection, AppOrderKey, + "{\"key\":\"app_order\",\"value\":\"diary\",\"updated_at\":\"2030-03-17T17:46:40Z\"}") != 0) + check_true("the later order wins", storage_get_setting_text(AppOrderKey) == "diary") + check_int("the later order is taken", app_order_received(), 1) + // Nothing pinned is an order too. + check_true("an empty order applies", + storage_apply_decrypted_record(AppOrderCollection, AppOrderKey, + "{\"key\":\"app_order\",\"value\":\"\",\"updated_at\":\"2030-03-17T17:46:41Z\"}") != 0) + check_true("an empty order unpins everything", storage_get_setting_text(AppOrderKey) == "") + storage_close() +} + #program_export Check :: () -> s32 { guard := support_begin("/tmp/inbe-storage-sync-zi-test/") @@ -1893,5 +2025,7 @@ Check :: () -> s32 { test_waiting_review_merges() test_questions_and_entries_sync() test_kept_records_upload_kept() + test_app_choices_sync_between_devices() + test_app_order_syncs_between_devices() return failures } diff --git a/tests/sync_restore_sql_test.py b/tests/sync_restore_sql_test.py index 881533251..669a64e00 100644 --- a/tests/sync_restore_sql_test.py +++ b/tests/sync_restore_sql_test.py @@ -41,7 +41,7 @@ def restore_statements(): assert enqueue, "storage_enqueue_all_sync_state" inserts = re.findall(r'exec_sql\("(INSERT INTO sync_outbox[^"]*)"\)', enqueue.group(1)) - assert len(inserts) == 9, inserts + assert len(inserts) == 10, inserts return clear + inserts @@ -60,6 +60,7 @@ def insert_row(database, table, values): ENTITIES = [ ("habit", "h1", 0), ("habit", "h2", 0), ("habit_day", "h1", 20260101), ("app_preference", "app_used_lists", 0), ("app_preference", "app_used_diary", 0), + ("app_order", "app_order", 0), ("session", "s1", 0), ("elist_list", "l1", 0), ("elist_item", "i1", 0), ("habit_entry", "e1", 0), ("habit_change", "c1", 0), ("cell_record", "cell.lumi.message.history", 0), @@ -87,6 +88,9 @@ def open_database(): insert_row(database, "settings", {"user_id": "u1", "key": "app_used_lists", "value": "0", "updated_at": 2}) insert_row(database, "settings", {"user_id": "u1", "key": "app_used_diary", "value": "1", "updated_at": 2}) insert_row(database, "settings", {"user_id": "u1", "key": "cells_auto_update", "value": "0", "updated_at": 2}) + insert_row(database, "settings", {"user_id": "u1", "key": "app_order", "value": "lumi,diary", "updated_at": 2}) + # A default nobody chose is never queued. + insert_row(database, "settings", {"user_id": "u1", "key": "app_used_leaderboard", "value": "0", "updated_at": 1}) for key in ("cell.lumi.message.history", "cell.diary.entry.today", "cell.feedback.report"): insert_row(database, "settings", {"user_id": "u1", "key": key, "value": "{}", "updated_at": 2}) insert_row(database, "users", {"id": "u2"}) diff --git a/tests/telegram_account_flow_behavior.zi b/tests/telegram_account_flow_behavior.zi index 4844bc1a4..ec63e4172 100644 --- a/tests/telegram_account_flow_behavior.zi +++ b/tests/telegram_account_flow_behavior.zi @@ -489,9 +489,14 @@ CheckOrdinarySettings :: () { flow_host_hosted = false fixture_settings_app = InnerBreeze.{} unused app_load_settings(*fixture_settings_app) + // A new profile's apps are defaults, not choices: they are stored but + // never sent, so they cannot replace the account's apps. Expect("ordinary profile still introduces Lumi", storage_get_setting_int("app_used_lumi", 0) == 1 && - storage_get_setting_int("lumi_introduced", 0) == 1 && OutboxCount() == 1) + storage_get_setting_int("lumi_introduced", 0) == 1 && OutboxCount() == 0) + Expect("new profile defaults are Lumi, Habits and Practice", + fixture_settings_app.enabled_apps == APP_RECOMMENDED && + db_select_int64_text("SELECT COUNT(*) FROM settings WHERE key LIKE 'app_used_%' AND updated_at=1", -1) == 6) fixture_settings_app.apps_selected = 1 fixture_settings_app.enabled_apps = APP_LUMI save_settings(*fixture_settings_app) @@ -499,7 +504,7 @@ CheckOrdinarySettings :: () { db_select_int64_text("SELECT COUNT(*) FROM settings WHERE key LIKE 'app_used_%'", -1) == 6 && storage_get_setting_int("app_used_diary", -1) == 0 && storage_get_setting_int("app_used_leaderboard", -1) == 0 && - storage_get_setting_int("app_used_lumi", -1) == 1 && OutboxCount() == 6) + storage_get_setting_int("app_used_lumi", -1) == 1 && OutboxCount() == 2) } CheckCreatePreservesOwner :: () {