diff --git a/CHANGELOG.md b/CHANGELOG.md index fb02c8e17..e4edaeef7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,9 @@ ## [2.1.39] - 2026-10-22 -- Keep the Sun Salutation guide visible and its Back button working. +- Fix account sync, Shop borrowing and history, Android key backups and Profile navigation. +- Share photo storage between Diary and Photos and compress new uploads. +- Keep practice guides visible, browser animations smooth and web saves recoverable. ## [2.1.38] - 2026-10-21 diff --git a/fastlane/metadata/android/en-US/changelogs/176.txt b/fastlane/metadata/android/en-US/changelogs/176.txt index 3bc2a46ba..6b99722b0 100644 --- a/fastlane/metadata/android/en-US/changelogs/176.txt +++ b/fastlane/metadata/android/en-US/changelogs/176.txt @@ -1 +1,3 @@ -- Keep the Sun Salutation guide visible and its Back button working. +- Fix account sync, Shop borrowing and history, Android key backups and Profile navigation. +- Share photo storage between Diary and Photos and compress new uploads. +- Keep practice guides visible, browser animations smooth and web saves recoverable. diff --git a/scripts/web-smoke-test.mjs b/scripts/web-smoke-test.mjs index e683e30c7..6713b3c5e 100755 --- a/scripts/web-smoke-test.mjs +++ b/scripts/web-smoke-test.mjs @@ -377,6 +377,8 @@ function connectBidi(wsUrl) { } function eventText(event) { + if (event.method === 'log.entryAdded') + return event.params.text || ''; if (event.method === 'Runtime.consoleAPICalled') { return (event.params.args || []).map(arg => arg.value ?? arg.description ?? '').join(' '); } @@ -668,11 +670,14 @@ async function waitForStorageIdle(client) { expression: `(() => ({ syncing: !!Module.__inbeStorageSyncing, pending: !!Module.__inbeStorageSyncPending, - timer: !!Module.__inbeStorageSyncTimer + timer: !!Module.__inbeStorageSyncTimer, + error: Module.__inbeStorageSyncLastError || '' }))()`, returnByValue: true }); lastState = result.result?.value; + if (lastState && !lastState.syncing && !lastState.timer && lastState.error) + throw new Error('IDBFS save failed: ' + lastState.error); if (lastState && !lastState.syncing && !lastState.pending && !lastState.timer) return; await new Promise(resolveDelay => setTimeout(resolveDelay, 50)); @@ -1925,7 +1930,15 @@ try { 'about:blank' ]; const firefoxStderr = []; - chrome = spawn(browser, args, { stdio: ['ignore', 'ignore', 'pipe'], detached: true, env: browserEnvironment }); + // Linux Firefox needs a display for WebGL, even in headless mode. + // Start our own server after scrubbing the owner's display variables. + const displayRunner = process.platform === 'linux' ? findOnPath('xvfb-run') : ''; + if (process.platform === 'linux' && !displayRunner) + throw new Error('Firefox checks require xvfb-run for a private graphics display'); + const command = displayRunner || browser; + const argumentsForBrowser = displayRunner ? + ['-a', '-s', '-screen 0 1366x900x24', browser, ...args] : args; + chrome = spawn(command, argumentsForBrowser, { stdio: ['ignore', 'ignore', 'pipe'], detached: true, env: browserEnvironment }); chrome.stderr.setEncoding('utf8'); chrome.stderr.on('data', chunk => { firefoxStderr.push(chunk); @@ -2007,6 +2020,17 @@ try { await client.send('Log.enable'); await client.send('Page.enable'); await client.send('Page.addScriptToEvaluateOnNewDocument', { source: musicAudioInstrumentation }); + if (process.env.WEB_SMOKE_NO_WEBGL === '1') { + await client.send('Page.addScriptToEvaluateOnNewDocument', { source: ` + for (const prototype of [HTMLCanvasElement.prototype, OffscreenCanvas.prototype]) { + const original = prototype.getContext; + prototype.getContext = function(kind, ...args) { + if (kind === 'webgl' || kind === 'webgl2' || kind === 'experimental-webgl') return null; + return original.call(this, kind, ...args); + }; + } + ` }); + } if (process.env.WEB_SMOKE_CPU_THROTTLE) await client.send('Emulation.setCPUThrottlingRate', { rate: Number(process.env.WEB_SMOKE_CPU_THROTTLE) @@ -2042,6 +2066,9 @@ try { } } } + const rejected = client.events.map(eventText).filter(text => text.includes('APP: frame rejected')); + if (rejected.length) + throw new Error(`Application rejected ${rejected.length} UI frames: ${rejected.join(' | ')}`); console.log(`web smoke: PASS (${renderer})`); } catch (error) { failure = error; diff --git a/scripts/web-sun-salutation-test.mjs b/scripts/web-sun-salutation-test.mjs index 2de375ed8..5fa434c82 100644 --- a/scripts/web-sun-salutation-test.mjs +++ b/scripts/web-sun-salutation-test.mjs @@ -45,6 +45,9 @@ const stateExpression = `(() => { })()`; export async function verifySunSalutationCanvas({ evaluate, click, resize, capture, callHook, browser }) { + const poseCount = Number(process.env.WEB_SMOKE_SUN_POSES || 12); + if (!Number.isInteger(poseCount) || poseCount < 2 || poseCount > 12) + throw new Error('WEB_SMOKE_SUN_POSES must be an integer from 2 to 12'); const output = process.env.WEB_SMOKE_ARTIFACT_DIR; if (output) mkdirSync(output, { recursive: true }); const evidence = []; @@ -206,7 +209,8 @@ export async function verifySunSalutationCanvas({ evaluate, click, resize, captu await evaluate(`(() => { const probe = window.__inbeAnimationProbe = { - active: false, last: 0, gaps: [], decodes: [], readbacks: 0, uploads: 0 + active: false, last: 0, gaps: [], decodes: [], readbacks: 0, uploads: 0, + meshSources: new WeakMap(), meshTransfers: 0, meshPixels: 0, meshStacks: [] }; for (const prototype of [CanvasRenderingContext2D.prototype, ...(typeof OffscreenCanvasRenderingContext2D === 'undefined' ? [] : @@ -220,6 +224,21 @@ export async function verifySunSalutationCanvas({ evaluate, click, resize, captu if (probe.last) probe.gaps.push(now - probe.last); probe.last = now; } + if (method === 'drawImage' && args[0] && + (args[0] instanceof HTMLCanvasElement || + (typeof OffscreenCanvas !== 'undefined' && args[0] instanceof OffscreenCanvas))) { + const source = args[0]; + if (!probe.meshSources.has(source)) + probe.meshSources.set(source, !!source.getContext('webgl')); + if (probe.meshSources.get(source)) { + probe.meshTransfers++; + probe.meshPixels += source.width * source.height; + if (${process.env.WEB_SMOKE_MESH_TRACE === '1'} && probe.meshStacks.length < 2) { + Error.stackTraceLimit = 40; + probe.meshStacks.push(new Error('mesh transfer').stack); + } + } + } if (this.canvas !== Module.canvas && method === 'getImageData') probe.readbacks++; if (method === 'putImageData') probe.uploads++; } @@ -317,7 +336,7 @@ export async function verifySunSalutationCanvas({ evaluate, click, resize, captu if ((await state()).step !== 0) throw new Error('Sun Salutation Previous did not return'); await save(`${label}-mountain`); - for (let step = 1; step < 12; step++) { + for (let step = 1; step < poseCount; step++) { await control(2); const before = await state(); if (before.step !== step || before.paused !== 1 || before.ticks !== 0) @@ -369,7 +388,7 @@ export async function verifySunSalutationCanvas({ evaluate, click, resize, captu if (label === 'phone') await save(`${label}-pose-${String(step + 1).padStart(2, '0')}`); evidence.push({ viewport: label, step: step + 1, ...held }); } - console.log(`web Sun Salutation: all 12 poses, previews, controls and pause passed (${browser}, ${label})`); + console.log(`web Sun Salutation: ${poseCount} poses, previews, controls and pause passed (${browser}, ${label})`); } const performance = await evaluate(`(() => { const probe = window.__inbeAnimationProbe; @@ -382,7 +401,9 @@ export async function verifySunSalutationCanvas({ evaluate, click, resize, captu maxMs: sorted[sorted.length - 1], decodes: probe.decodes.length, decodeMeanMs: probe.decodes.reduce((sum, value) => sum + value, 0) / probe.decodes.length, - readbacks: probe.readbacks, uploads: probe.uploads + readbacks: probe.readbacks, uploads: probe.uploads, + meshTransfers: probe.meshTransfers, meshPixels: probe.meshPixels, + meshStacks: probe.meshStacks }; })()`); console.log('web Sun Salutation frame timing: ' + JSON.stringify({ browser, ...performance })); diff --git a/src/app/app_launcher.zi b/src/app/app_launcher.zi index 3f1acd08e..b9f22c177 100644 --- a/src/app/app_launcher.zi +++ b/src/app/app_launcher.zi @@ -178,7 +178,7 @@ LauncherLibraryMove :: (app: *InnerBreeze, items: []s32, item: s32, target: s32) } #program_export -app_draw_launcher :: (app: *InnerBreeze) { +app_draw_launcher :: (app: *InnerBreeze, dock_drawn: bool) { app.launcher_panel_node = -1 if !app.launcher_open || app.host_feature != 0 { return @@ -458,7 +458,9 @@ app_draw_launcher :: (app: *InnerBreeze) { } unused End(app.ui.session) } - app_draw_favorites_dock(app) + if !dock_drawn { + app_draw_favorites_dock(app) + } if app.launcher_drag_key != 0 && app.launcher_drag_moving { point := app.launcher_drag_pointer target := app.launcher_dock_drop_index diff --git a/src/app/application_update.zi b/src/app/application_update.zi index 3f4246ea3..a255a4c6e 100644 --- a/src/app/application_update.zi +++ b/src/app/application_update.zi @@ -232,7 +232,9 @@ updateapp :: (app: *InnerBreeze) { // Resolve dock input before drawing the page on every viewport. A // bottom-dock click must draw its destination in this frame, just like // the desktop rail, so a cold page cannot swallow the next tap. - app_draw_bottom_nav(app) + // A dock click can open Apps, and the page can start a practice. Keep + // the dock already emitted this frame when either route changes below. + dock_drawn := app_draw_bottom_nav(app) app_draw_return_bar(app) // Kryon gives the top overlay first refusal of Escape, before page // navigation or the idle-home quit shortcut can see that same press. @@ -419,7 +421,9 @@ updateapp :: (app: *InnerBreeze) { } if launcher_owns_input { unused TreeInputResume(app.ui.session, launcher_input) } view_height = frame_view_height - app_draw_session_nav(app) + if !dock_drawn { + dock_drawn = app_draw_session_nav(app) + } // The Apps screen covers the page, so the practice window is drawn on it // while it is open. launcher_covers_page := app.launcher_open @@ -437,7 +441,7 @@ updateapp :: (app: *InnerBreeze) { if !launcher_covers_page { app_draw_close_prompt(app) } - app_draw_launcher(app) + app_draw_launcher(app, dock_drawn) if launcher_covers_page { // Apps is an overlay above the page, so the window and the close // prompt are drawn inside its panel, above the apps. If Apps closed diff --git a/src/habits/habit_types.zi b/src/habits/habit_types.zi index 45ffd609d..e2bb747e4 100644 --- a/src/habits/habit_types.zi +++ b/src/habits/habit_types.zi @@ -175,6 +175,7 @@ HabitCoinActivity :: struct { icon: s32 halves: s64 local_date: s32 + at: s64 } HabitDay :: struct { diff --git a/src/main.zi b/src/main.zi index 53fb6e88a..0b5255d52 100644 --- a/src/main.zi +++ b/src/main.zi @@ -150,7 +150,7 @@ run_practice_probe :: (mode: s32, size: WindowSize) -> s32 { if first_probe_frame { TraceLog(LOG_INFO, "APP PROBE: before navigation bar") } - app_draw_bottom_nav(*app) + unused app_draw_bottom_nav(*app) if first_probe_frame { TraceLog(LOG_INFO, "APP PROBE: after navigation bar") } diff --git a/src/storage/db.zi b/src/storage/db.zi index 05557569d..83eb83126 100644 --- a/src/storage/db.zi +++ b/src/storage/db.zi @@ -77,6 +77,7 @@ storage_migrate_habit_ids_to_uuid :: () -> s32 #foreign c; storage_migrate_default_meditation_activity_mask :: () -> s32 #foreign c; storage_migrate_sync_enabled_flag :: () -> s32 #foreign c; storage_migrate_lumi_collection :: () -> s32 #foreign c; +storage_migrate_habit_settings :: () -> s32 #foreign c; storage_materialize_session_habit_days :: () -> s32 #foreign c; migrate_legacy_file_sessions_once :: (root: *u8) -> s32 #foreign c; #import, file "user.zi"; @@ -243,7 +244,7 @@ storage_init :: (root: string) -> s32 { storage_migrate_habit_ids_to_uuid() storage_migrate_default_meditation_activity_mask() storage_migrate_sync_enabled_flag() - if storage_migrate_lumi_collection() == 0 { + if storage_migrate_lumi_collection() == 0 || storage_migrate_habit_settings() == 0 { sqlite3_close(storage_state_handle().db) storage_state_handle().db = null return 0 diff --git a/src/storage/habit_settings.zi b/src/storage/habit_settings.zi new file mode 100644 index 000000000..4a1d43758 --- /dev/null +++ b/src/storage/habit_settings.zi @@ -0,0 +1,7 @@ +// Account-owned Habits settings travel separately from older collections, +// so hosts that do not understand them can still finish syncing. +HabitSettingsCollection :: "private.inbe.v1.habit-settings" + +HabitSettingKeyValid :: (key: string) -> bool { + return key == "habit_shop_borrow_limit" +} diff --git a/src/storage/storage_habit_wallet.zi b/src/storage/storage_habit_wallet.zi index 1cb9ee3f3..65a62b34a 100644 --- a/src/storage/storage_habit_wallet.zi +++ b/src/storage/storage_habit_wallet.zi @@ -58,7 +58,7 @@ SQL // Each day's signed earnings and purchases, newest first. StorageHabitActivitySQL :: #string SQL WITH days AS ( -SELECT h.id,h.name,h.icon,d.local_date AS day, +SELECT h.id,h.name,h.icon,d.local_date AS day,d.updated_at AS at, h.custom_coins,h.coin_halves, COALESCE((SELECT c.old_value FROM habit_changes c WHERE c.habit_id=h.id AND c.kind=20 AND c.deleted_at=0 AND @@ -84,17 +84,17 @@ WHEN old_coins='' AND custom_coins<>0 THEN ELSE '0:'||CAST(CASE WHEN level=3 THEN 1 ELSE 2+2*MIN(MAX(level,0),2) END AS TEXT) END AS policy FROM days ), earned AS ( -SELECT id,name,icon,day,CAST(substr(policy,3) AS INTEGER)* +SELECT id,name,icon,day,at,CAST(substr(policy,3) AS INTEGER)* CASE WHEN substr(policy,1,1)='1' THEN occurrences ELSE done END AS halves FROM valued ) -SELECT name,icon,halves,day FROM ( -SELECT name,icon,halves,day,0 AS at FROM earned WHERE halves<>0 +SELECT name,icon,halves,day,at FROM ( +SELECT name,icon,halves,day,at,id FROM earned WHERE halves<>0 UNION ALL SELECT c.name,COALESCE(r.icon,0),-2*c.coins, -CAST(strftime('%Y%m%d',c.at,'unixepoch','localtime') AS INTEGER),c.at +CAST(strftime('%Y%m%d',c.at,'unixepoch','localtime') AS INTEGER),c.at,c.id FROM habit_coins c LEFT JOIN habit_rewards r ON r.id=c.reward_id WHERE c.user_id=?1 AND c.deleted_at=0 AND c.kind=1) -ORDER BY day DESC,at DESC LIMIT ?2 +ORDER BY at DESC,day DESC,id DESC LIMIT ?2 SQL storage_habit_activity_load :: (output: []HabitCoinActivity) -> s32 { @@ -114,6 +114,7 @@ storage_habit_activity_load :: (output: []HabitCoinActivity) -> s32 { entry.icon = sqlite3_column_int(stmt, 1) entry.halves = SqliteColumnInt64(stmt, 2) entry.local_date = sqlite3_column_int(stmt, 3) + entry.at = SqliteColumnInt64(stmt, 4) count += 1 } SqliteFinalize(stmt) diff --git a/src/storage/storage_settings.zi b/src/storage/storage_settings.zi index b8fcfb246..f90b9ee6b 100644 --- a/src/storage/storage_settings.zi +++ b/src/storage/storage_settings.zi @@ -9,6 +9,7 @@ #import, file "cell_records.zi"; #import, file "app_records.zi"; #import, file "media_records.zi"; +#import, file "habit_settings.zi"; #import, file "db.zi"; #import, file "storage_core.zi"; #import, file "sync_outbox.zi"; @@ -329,6 +330,9 @@ storage_set_setting_text :: (key: string, value: string) { rc = SqliteStep(stmt) SqliteFinalize(stmt) if rc == SQLITE_DONE && sqlite3_changes(storage_db_handle()) > 0 { + if HabitSettingKeyValid(key) { + unused storage_enqueue_sync_entity("habit_setting", key, 0) + } if CellRecordValid(key) { unused storage_enqueue_sync_entity("cell_record", key, 0) } diff --git a/src/storage/sync_apply.zi b/src/storage/sync_apply.zi index fb9604e9c..eabaee63a 100644 --- a/src/storage/sync_apply.zi +++ b/src/storage/sync_apply.zi @@ -250,6 +250,13 @@ storage_apply_decrypted_record :: (collection: string, record_id: string, plaint ok = storage_exec_json_user_sql(SyncAppRecordsSQL, record_response) } } + } else if array_name == "habit_settings" { + records := Scan.FieldAt(record_response, Scan.FieldAt(record_response, 0, "changes"), array_name) + ok = 1 + if record_id == "habit_shop_borrow_limit" && + Scan.ArrayCount(record_response, records) == 1 && storage_cell_plaintext_fields_valid(plaintext) { + ok = storage_exec_json_user_sql(SyncHabitSettingsSQL, record_response) + } } 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. diff --git a/src/storage/sync_collections.zi b/src/storage/sync_collections.zi index cfcd89b2c..808f64de1 100644 --- a/src/storage/sync_collections.zi +++ b/src/storage/sync_collections.zi @@ -7,6 +7,7 @@ #import, file "achievement_records.zi"; #import, file "app_records.zi"; #import, file "media_records.zi"; +#import, file "habit_settings.zi"; #import, file "storage_layout.zi"; #import, file "storage_core.zi"; @@ -28,6 +29,9 @@ storage_node_app_records_collection :: (key: string) -> string { } storage_encrypted_collection_for_entity :: (entity_type: string, entity_id: string) -> string { + if entity_type == "habit_setting" { + return ifx HabitSettingKeyValid(entity_id) then HabitSettingsCollection else "" + } if entity_type == "cell_record" { if AchievementRecordValid(entity_id) { return AchievementCollection } if LumiCellRecordValid(entity_id) { @@ -121,6 +125,7 @@ storage_encrypted_collection_key_id :: (collection: string) -> string { } storage_decrypted_array_name :: (collection: string) -> string { + if collection == HabitSettingsCollection { return "habit_settings" } if collection == LegacyPrivateCellsCollection || collection == LumiPrivateCollection || collection == AchievementCollection { return "cell_records" } diff --git a/src/storage/sync_migrations.zi b/src/storage/sync_migrations.zi index e243a321e..f20b586a9 100644 --- a/src/storage/sync_migrations.zi +++ b/src/storage/sync_migrations.zi @@ -20,6 +20,30 @@ storage_migrate_preinstalled_apps :: () { if MigrationChanges(storage_db_handle()) > 0 { storage_schedule_persist() } } +// Queue an older device's allowance without changing its value or clock. +#program_export +storage_migrate_habit_settings :: () -> s32 { + if storage_meta_int64("sync_habit_settings_v1_done", 0) != 0 { return 1 } + if exec_sql("SAVEPOINT inbe_habit_settings_migration") == 0 { return 0 } + queued := exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit_setting',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND key='habit_shop_borrow_limit' ON CONFLICT(entity_type,entity_id,local_date) DO NOTHING") + marked: s32 = 0 + if queued != 0 { + marked = exec_sql("INSERT INTO meta(key,value) VALUES('sync_habit_settings_v1_done','1') ON CONFLICT(key) DO UPDATE SET value=excluded.value") + } + if queued == 0 || marked == 0 { + unused exec_sql("ROLLBACK TO inbe_habit_settings_migration") + unused exec_sql("RELEASE inbe_habit_settings_migration") + return 0 + } + if exec_sql("RELEASE inbe_habit_settings_migration") == 0 { + unused exec_sql("ROLLBACK TO inbe_habit_settings_migration") + unused exec_sql("RELEASE inbe_habit_settings_migration") + return 0 + } + storage_schedule_persist() + return 1 +} + #program_export // The outbox and marker commit together. The old settings and server history // remain intact; new writes and queued copies use the separate Lumi scope. diff --git a/src/storage/sync_outbox.zi b/src/storage/sync_outbox.zi index b5b49a8f9..a2e02b097 100644 --- a/src/storage/sync_outbox.zi +++ b/src/storage/sync_outbox.zi @@ -19,9 +19,9 @@ storage_enqueue_sync_entity :: (entity_type: string, entity_id: string, local_da return 0 } query := "INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES(?1,?2,?3,?4) ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at" - if entity_type == "cell_record" { - // Cell receipts name the exact submitted sequence. Replacing a cell - // allocates a fresh sequence even for edits within the same second. + if entity_type == "cell_record" || entity_type == "habit_setting" { + // These receipts name the exact submitted sequence. Replacing a + // setting allocates a fresh sequence even within the same second. // Owner habit/session saves retain their existing queue behaviour. query = "INSERT OR REPLACE INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES(?1,?2,?3,?4)" } @@ -106,6 +106,7 @@ storage_enqueue_all_sync_state :: () { exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit_coin',id,0,strftime('%s','now') FROM habit_coins 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") // 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 'habit_setting',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND key='habit_shop_borrow_limit' 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') 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 'app_install',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND key GLOB 'app_used_[a-z]*' AND length(key) BETWEEN 11 AND 33 AND substr(key,10) NOT GLOB '*[^a-z0-9]*' AND key NOT IN ('app_used_inbe','app_used_lists','app_used_habits','app_used_practices','app_used_practice','app_used_diary','app_used_lumi','app_used_leaderboard','app_used_feedback','app_used_app','app_used_apps','app_used_media','app_used_achievement') AND updated_at>1 ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at") diff --git a/src/storage/sync_record_codec.zi b/src/storage/sync_record_codec.zi index 195376ba7..2f2e171d1 100644 --- a/src/storage/sync_record_codec.zi +++ b/src/storage/sync_record_codec.zi @@ -6,6 +6,7 @@ #import, file "sqlite.zi"; #import, file "json.zi"; #import, file "cell_records.zi"; +#import, file "habit_settings.zi"; #import, file "app_records.zi"; #import, file "media_records.zi"; #import, file "db.zi"; @@ -559,7 +560,9 @@ storage_append_cell_payload_json :: (json: *StorageJsonBuilder, key: string) -> storage_append_sync_op_payload :: (json: *StorageJsonBuilder, entity_type: string, entity_id: string, local_date: s32) { found: s32 = 0 - if entity_type == "cell_record" { + if entity_type == "habit_setting" && HabitSettingKeyValid(entity_id) { + found = storage_append_setting_record_json(json, entity_id, 8) + } else if entity_type == "cell_record" { 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) diff --git a/src/storage/sync_sql.zi b/src/storage/sync_sql.zi index dcefd5221..e89ef8e32 100644 --- a/src/storage/sync_sql.zi +++ b/src/storage/sync_sql.zi @@ -165,6 +165,26 @@ OR (excluded.updated_at = settings.updated_at AND NOT EXISTS ( )) SQL +// A borrowed-coin allowance belongs to the account. Keep pending local edits +// on a timestamp tie, and never let a remote setting write another key. +SyncHabitSettingsSQL :: #string SQL +INSERT INTO settings(user_id,key,value,updated_at) +SELECT ?2,json_extract(value,'$.key'),json_extract(value,'$.value'), + CAST(strftime('%s',json_extract(value,'$.updated_at')) AS INTEGER) +FROM json_each(?1,'$.changes.habit_settings') +WHERE json_extract(value,'$.key')='habit_shop_borrow_limit' +AND json_type(value,'$.value')='text' +AND length(json_extract(value,'$.value')) BETWEEN 1 AND 4 +AND json_extract(value,'$.value') NOT GLOB '*[^0-9]*' +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='habit_setting' + AND entity_id=settings.key AND local_date=0 +)) +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 diff --git a/src/web_boot.js b/src/web_boot.js index b67281598..33505ec73 100644 --- a/src/web_boot.js +++ b/src/web_boot.js @@ -198,6 +198,7 @@ function runStorageSync(retryDelay) { var shouldLog = !!Module.__inbeStorageSyncLogSuccess; Module.__inbeStorageSyncLogSuccess = false; if (!Module.__inbeStorageSyncPromise) { + Module.__inbeStorageSyncRetry = 0; Module.__inbeStorageSyncPromise = new Promise(function(resolve) { Module.__inbeStorageSyncResolve = resolve; }); @@ -229,13 +230,35 @@ function runStorageSync(retryDelay) { }, retryDelay); } + function storageSyncFailed(error) { + var message = error && (error.message || error.name); + if (!message) message = String(error); + if (error && typeof error.errno === 'number') message += ' (errno ' + error.errno + ')'; + Module.__inbeStorageSyncLastError = message; + Module.__inbeStorageSyncPending = true; + console.error('IDBFS save failed: ' + message); + // A package can replace a temporary file while IDBFS enumerates it. + // Start a fresh snapshot after that race; persistent failures still + // resolve false, leaving the dirty state available to an explicit save. + var transient = error && (error.errno === 44 || error.name === 'NotFoundError' || error.name === 'AbortError'); + var attempt = Module.__inbeStorageSyncRetry || 0; + if (transient && attempt < 3) { + Module.__inbeStorageSyncRetry = attempt + 1; + if (Module.__inbeStorageSyncTimer) clearTimeout(Module.__inbeStorageSyncTimer); + Module.__inbeStorageSyncTimer = setTimeout(function() { + Module.__inbeStorageSyncTimer = 0; + runStorageSync(retryDelay); + }, 100 * Math.pow(2, attempt)); + return; + } + finishStorageSync(false); + } + try { FS.syncfs(false, function(err) { Module.__inbeStorageSyncing = false; if (err) { - Module.__inbeStorageSyncLastError = err && err.message ? err.message : String(err); - console.error('IDBFS save failed:', err); - finishStorageSync(false); + storageSyncFailed(err); } else { if (shouldLog) console.log('IDBFS synced'); drainPendingStorageSync(); @@ -243,8 +266,7 @@ function runStorageSync(retryDelay) { }); } catch (e) { Module.__inbeStorageSyncing = false; - console.error('IDBFS sync error:', e); - finishStorageSync(false); + storageSyncFailed(e); } return promise; diff --git a/src/widgets/bottom_nav.zi b/src/widgets/bottom_nav.zi index 17294765c..4410aa664 100644 --- a/src/widgets/bottom_nav.zi +++ b/src/widgets/bottom_nav.zi @@ -296,22 +296,24 @@ app_draw_dock :: (app: *InnerBreeze, over_practice: bool) { } #program_export -app_draw_bottom_nav :: (app: *InnerBreeze) { +app_draw_bottom_nav :: (app: *InnerBreeze) -> bool { if app == null || AppMiniMode() || app.host_feature != 0 || app.launcher_open || app.file_dialog_active != 0 || - !SessionValid(app.ui.session) { return } - if app_nav_desktop_rail_enabled(app) == 0 && app_navigation_height(app) == 0 { return } + !SessionValid(app.ui.session) { return false } + if app_nav_desktop_rail_enabled(app) == 0 && app_navigation_height(app) == 0 { return false } app_draw_favorites_dock(app) + return true } // The navigation a practice reveals from its edge, drawn over the practice // after its page so its taps come first. -app_draw_session_nav :: (app: *InnerBreeze) { +app_draw_session_nav :: (app: *InnerBreeze) -> bool { if app == null || AppMiniMode() || app.host_feature != 0 || app.launcher_open || app.file_dialog_active != 0 || !SessionValid(app.ui.session) || !app_is_session_screen(app.breathing.screen) || app.session_window.nav_shown <= 0.01 { - return + return false } app_draw_dock(app, true) + return true } diff --git a/tests/storage_habits_behavior.zi b/tests/storage_habits_behavior.zi index 035a92637..141b71c88 100644 --- a/tests/storage_habits_behavior.zi +++ b/tests/storage_habits_behavior.zi @@ -27,6 +27,9 @@ #import, file "../src/storage/storage_habit_wallet.zi"; #import, file "../src/storage/storage_habit_sync.zi"; #import, file "../src/storage/sync_record_codec.zi"; +#import, file "../src/storage/sync_apply.zi"; +#import, file "../src/storage/sync_collections.zi"; +#import, file "../src/storage/sync_outbox.zi"; #import, file "../src/storage/json.zi"; c :: #system_library "c"; @@ -1084,10 +1087,68 @@ Check :: () -> s32 { test_average_goals_and_changes() test_stale_copy_keeps_synced_values() test_habit_wallet() + test_habit_shop_order_and_borrow_sync() test_zero_target_and_custom_coins() return failures } +test_habit_shop_order_and_borrow_sync :: () { + root := make_root("habit-shop-order-sync") + check_true("open shop fixture", storage_init(root) != 0) + storage_close() + raw_exec(root, "INSERT INTO settings(user_id,key,value,updated_at) SELECT id,'habit_shop_borrow_limit','75',123 FROM users LIMIT 1;DELETE FROM meta WHERE key='sync_habit_settings_v1_done';INSERT INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,difficulty,coins_from) VALUES('walk',(SELECT id FROM users LIMIT 1),'Walk',1,2,3,0,0,0,1,0,0,1,0,20261001);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('walk',20261005,1,1,0,300);INSERT INTO habit_coins(id,user_id,kind,reward_id,name,coins,at,deleted_at,updated_at) VALUES('buy-first',(SELECT id FROM users LIMIT 1),1,'','First purchase',2,100,0,100),('buy-last',(SELECT id FROM users LIMIT 1),1,'','Last purchase',3,400,0,400);") + check_true("upgrade shop fixture", storage_init(root) != 0) + check_true("existing allowance and clock survive upgrade", + storage_get_setting_int("habit_shop_borrow_limit", 0) == 75 && read_db_count( + "SELECT updated_at FROM settings WHERE key='habit_shop_borrow_limit'") == 123) + check_int("existing allowance is queued once", read_db_count( + "SELECT COUNT(*) FROM sync_outbox WHERE entity_type='habit_setting' AND entity_id='habit_shop_borrow_limit'"), 1) + activity: [4]HabitCoinActivity + check_int("all coin movements load", storage_habit_activity_load(activity[:]), 3) + check_true("earnings and purchases interleave by their actual timestamp", + TextUntilNul(activity[0].name[:]) == "Last purchase" && activity[0].at == 400 && + TextUntilNul(activity[1].name[:]) == "Walk" && activity[1].at == 300 && + activity[1].local_date == 20261005 && activity[2].at == 100) + queued_sequence := read_db_count("SELECT rowid FROM sync_outbox WHERE entity_type='habit_setting' AND entity_id='habit_shop_borrow_limit'") + storage_set_setting_int("habit_shop_borrow_limit", 125) + check_true("an older receipt cannot clear a newer allowance", read_db_count( + "SELECT rowid FROM sync_outbox WHERE entity_type='habit_setting' AND entity_id='habit_shop_borrow_limit'") > queued_sequence) + check_true("borrow settings use their own encrypted collection", + storage_encrypted_collection_for_entity("habit_setting", "habit_shop_borrow_limit") == + "private.inbe.v1.habit-settings" && + storage_decrypted_array_name("private.inbe.v1.habit-settings") == "habit_settings") + buffer: [2048]u8 + payload := synced_changes("habit_setting", "habit_shop_borrow_limit", "habit_settings", buffer[:]) + check_true("sync includes the current allowance", contains(payload, "\"value\":\"125\"")) + collection := "private.inbe.v1.habit-settings" + newest := "{\"key\":\"habit_shop_borrow_limit\",\"value\":\"250\",\"updated_at\":\"2030-01-01T00:00:00Z\"}" + check_true("receive another device's allowance", + storage_apply_decrypted_record(collection, "habit_shop_borrow_limit", newest) != 0 && + storage_get_setting_int("habit_shop_borrow_limit", 0) == 250) + exec_db_sql("UPDATE settings SET value='300' WHERE key='habit_shop_borrow_limit';") + check_true("a pending local edit wins a timestamp tie", + storage_apply_decrypted_record(collection, "habit_shop_borrow_limit", newest) != 0 && + storage_get_setting_int("habit_shop_borrow_limit", 0) == 300) + invalid := "{\"key\":\"habit_shop_borrow_limit\",\"value\":\"-1\",\"updated_at\":\"2031-01-01T00:00:00Z\"}" + check_true("invalid allowances cannot replace the saved amount", + storage_apply_decrypted_record(collection, "habit_shop_borrow_limit", invalid) != 0 && + storage_get_setting_int("habit_shop_borrow_limit", 0) == 300) + foreign := "{\"key\":\"sync_private_key\",\"value\":\"999\",\"updated_at\":\"2031-01-01T00:00:00Z\"}" + check_true("shop records cannot write other settings", + storage_apply_decrypted_record(collection, "habit_shop_borrow_limit", foreign) != 0 && + storage_get_setting_text("sync_private_key").count == 0) + exec_db_sql("DELETE FROM sync_outbox;") + storage_enqueue_all_sync_state() + check_int("full sync includes the allowance", read_db_count( + "SELECT COUNT(*) FROM sync_outbox WHERE entity_type='habit_setting' AND entity_id='habit_shop_borrow_limit'"), 1) + exec_db_sql("DELETE FROM sync_outbox;") + storage_close() + check_true("reopen upgraded shop", storage_init(root) != 0) + check_int("completed migration does not replay acknowledged settings", read_db_count( + "SELECT COUNT(*) FROM sync_outbox WHERE entity_type='habit_setting'"), 0) + storage_close() +} + test_zero_target_and_custom_coins :: () { root := make_root("habit-custom-coins") check_true("init custom coins db", storage_init(root) != 0) diff --git a/tests/sync_restore_sql_test.py b/tests/sync_restore_sql_test.py index 8f20b59e3..e0bb058ec 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) == 16, inserts + assert len(inserts) == 17, inserts return clear + inserts @@ -80,6 +80,7 @@ EXTRA = [ ("media_record", "cell.media.preview." + "ab" * 32, 0), ("habit_reward", "r1", 0), ("habit_coin", "k1", 0), + ("habit_setting", "habit_shop_borrow_limit", 0), ] @@ -105,6 +106,7 @@ def open_database(): 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}) + insert_row(database, "settings", {"user_id": "u1", "key": "habit_shop_borrow_limit", "value": "75", "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"): @@ -120,6 +122,7 @@ def open_database(): "nested." + "ab" * 32 + ".Big", "app_used_achievement"): insert_row(database, "settings", {"user_id": "u1", "key": key, "value": "1", "updated_at": 2}) insert_row(database, "users", {"id": "u2"}) + insert_row(database, "settings", {"user_id": "u2", "key": "habit_shop_borrow_limit", "value": "999", "updated_at": 2}) insert_row(database, "settings", {"user_id": "u2", "key": "nested." + "cd" * 32 + ".position", "value": "foreign", "updated_at": 2}) insert_row(database, "settings", {"user_id": "u2", "key": "cell.lumi.message.foreign", "value": "{}", "updated_at": 2}) insert_row(database, "settings", {"user_id": "u1", "key": "telegram.sent.local", "value": "1", "updated_at": 2}) diff --git a/tests/sync_server_behavior.zi b/tests/sync_server_behavior.zi index ab03fc565..5817c50ed 100644 --- a/tests/sync_server_behavior.zi +++ b/tests/sync_server_behavior.zi @@ -385,6 +385,7 @@ Check :: () -> s32 { open_client(a) check_true("generate account", sync_account_generate(*account) != 0) check_true("save account", sync_account_save(*account, ask) == ok) + storage_set_setting_int("habit_shop_borrow_limit", 75) habit_name: string = "Recovery meditation" habits_a = Habits.{} habits_a.count = 1 @@ -436,10 +437,17 @@ Check :: () -> s32 { check_int("session reaches the second device", storage_session_count(), 1) expect_habit(AlbumHabitId(), habit_name, 20260919) expect_list(list_text, item_text, "Travel", "Passport", 0) + check_int("borrow allowance reaches the second device", + storage_get_setting_int("habit_shop_borrow_limit", 0), 75) + storage_set_setting_int("habit_shop_borrow_limit", 125) + synchronize(url) // Private live activity uses the same authenticated, encrypted account // transport as Lumi history, without creating another completed result. open_client(a) live: AccountActivity + synchronize(url) + check_int("updated borrow allowance returns to the first device", + storage_get_setting_int("habit_shop_borrow_limit", 0), 125) unused AppCopyText("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", live.session_id[:]) unused AppCopyText("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", live.device_id[:]) live.active = 1 @@ -568,6 +576,8 @@ Check :: () -> s32 { storage_set_sync_enabled(1) synchronize(url) check_true("alias restored", storage_get_setting_text("sync_account_alias") == alias) + check_int("borrow allowance restores with the account", + storage_get_setting_int("habit_shop_borrow_limit", 0), 125) check_int("friends fetch", FetchFriends(url, friends_text[:]), 0) check_true("friendship recovered", contains(TextFromCString(*friends_text[0]), TextFromCString(*friend_account.public_id[0]))) diff --git a/tests/web_storage_test.mjs b/tests/web_storage_test.mjs index 1fceeb065..6a3f4b802 100644 --- a/tests/web_storage_test.mjs +++ b/tests/web_storage_test.mjs @@ -46,4 +46,33 @@ callbacks.shift()(null); assert.equal(await first, true); assert.equal(await second, true); assert.equal(queued.__inbeStorageSyncPending, false); + +const racedCallbacks = []; +const raced = boot((populate, done) => racedCallbacks.push(done)); +const recovered = raced.__inbeFlushStorageSync(false); +racedCallbacks.shift()({ errno: 44 }); +await new Promise(resolve => setTimeout(resolve, 150)); +assert.equal(racedCallbacks.length, 1, 'a replaced file starts a fresh storage snapshot'); +racedCallbacks.shift()(null); +assert.equal(await recovered, true); +assert.equal(raced.__inbeStorageSyncPending, false); +assert.equal(raced.__inbeStorageSyncLastError, ''); + +let attempts = 0; +let storeUnavailable = true; +const unavailable = boot((populate, done) => { attempts++; done(storeUnavailable ? { name: 'AbortError' } : null); }); +assert.equal(await unavailable.__inbeFlushStorageSync(false), false); +assert.equal(attempts, 4, 'transient storage retries must be bounded'); +assert.equal(unavailable.__inbeStorageSyncPending, true, 'failed writes remain dirty'); +assert.equal(unavailable.__inbeStorageSyncing, false); +assert.equal(unavailable.__inbeStorageSyncTimer, 0); +storeUnavailable = false; +assert.equal(await unavailable.__inbeFlushStorageSync(false), true); +assert.equal(unavailable.__inbeStorageSyncPending, false); +assert.equal(unavailable.__inbeStorageSyncLastError, ''); + +let quotaAttempts = 0; +const quota = boot((populate, done) => { quotaAttempts++; done({ name: 'QuotaExceededError' }); }); +assert.equal(await quota.__inbeFlushStorageSync(false), false); +assert.equal(quotaAttempts, 1, 'a full store must report failure without retrying'); console.log('web storage tests passed'); diff --git a/ziran.lock b/ziran.lock index fb45a3723..959637e5e 100644 --- a/ziran.lock +++ b/ziran.lock @@ -1,6 +1,14 @@ { "format": 1, "packages": [ + { + "commit": "538ff10dcdc8fbb55739987806b10eab3f65682d", + "dependencies": {"raylib": "p5a77c9c35110e925"}, + "id": "p01a877b1b6e5a303", + "name": "kryon", + "ref": "master", + "url": "https://github.com/kryonlabs/kryon.git" + }, { "commit": "b31299434c785d0f2bd82f36b5bfd2fd36ba1216", "dependencies": {}, @@ -12,7 +20,7 @@ }, { "commit": "db5349c476bdc243c22b9c73fda4ec06d0a25ffc", - "dependencies": {"crypto": "pf039d7a776333200", "kryon": "pee63a9a74289ff8a"}, + "dependencies": {"crypto": "pf039d7a776333200", "kryon": "p01a877b1b6e5a303"}, "id": "p0c45ce9ed9a0f8cf", "name": "Apps", "ref": "master", @@ -36,7 +44,7 @@ }, { "commit": "1cb9df183089a77c8a16448a556186f30b261a98", - "dependencies": {"kryon": "pee63a9a74289ff8a"}, + "dependencies": {"kryon": "p01a877b1b6e5a303"}, "id": "p1b13dda539ed2a39", "name": "Kss", "ref": "master", @@ -44,7 +52,7 @@ }, { "commit": "bad2caaa84ef3eae61e40c99bf572d2b060d0ca2", - "dependencies": {"kryon": "pee63a9a74289ff8a"}, + "dependencies": {"kryon": "p01a877b1b6e5a303"}, "id": "p20eb23d3e6db3711", "name": "Game2D", "ref": "master", @@ -104,7 +112,7 @@ }, { "commit": "4b0e25bd2df86b54a8f5af3db48282bd41daab1a", - "dependencies": {"kryon": "pee63a9a74289ff8a"}, + "dependencies": {"kryon": "p01a877b1b6e5a303"}, "id": "pe8e21a1f2b5ff52c", "name": "plot", "ref": "master", @@ -119,14 +127,6 @@ "source": true, "url": "https://github.com/sqlite/sqlite.git" }, - { - "commit": "05e3cc642c35b103068d846c12a871d7e3153bc8", - "dependencies": {"raylib": "p5a77c9c35110e925"}, - "id": "pee63a9a74289ff8a", - "name": "kryon", - "ref": "master", - "url": "https://github.com/kryonlabs/kryon.git" - }, { "commit": "08bbad051379813d0fd1c3bb7bb6814f3491da75", "dependencies": {}, @@ -137,7 +137,7 @@ }, { "commit": "47e4798f355fa626fc08c470392b5bfa56bf2bbc", - "dependencies": {"daochi_client": "p0cff069893bdc938", "kryon": "pee63a9a74289ff8a", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"}, + "dependencies": {"daochi_client": "p0cff069893bdc938", "kryon": "p01a877b1b6e5a303", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"}, "id": "pf97603bf1b626f3b", "name": "Self", "ref": "master", @@ -145,7 +145,7 @@ } ], "root": { - "dependencies": {"apps": "p0c45ce9ed9a0f8cf", "crypto": "pf039d7a776333200", "curl": "pd4bcd11b7d623073", "daochi_client": "p0cff069893bdc938", "game2d": "p20eb23d3e6db3711", "kryon": "pee63a9a74289ff8a", "kss": "p1b13dda539ed2a39", "liboqs": "p7766f6d294641ca8", "mingcute": "pe1027b9d16704793", "monocypher": "p809b4d31a48625a3", "oqs": "p7098ac9cd92f7e5f", "plot": "pe8e21a1f2b5ff52c", "qrcode": "p0dfa70137405b096", "rini": "p09fa77e94b0dfc6c", "self": "pf97603bf1b626f3b", "sqlite": "peaa43c4b7ef72edf"}, + "dependencies": {"apps": "p0c45ce9ed9a0f8cf", "crypto": "pf039d7a776333200", "curl": "pd4bcd11b7d623073", "daochi_client": "p0cff069893bdc938", "game2d": "p20eb23d3e6db3711", "kryon": "p01a877b1b6e5a303", "kss": "p1b13dda539ed2a39", "liboqs": "p7766f6d294641ca8", "mingcute": "pe1027b9d16704793", "monocypher": "p809b4d31a48625a3", "oqs": "p7098ac9cd92f7e5f", "plot": "pe8e21a1f2b5ff52c", "qrcode": "p0dfa70137405b096", "rini": "p09fa77e94b0dfc6c", "self": "pf97603bf1b626f3b", "sqlite": "peaa43c4b7ef72edf"}, "name": "Inbe" }, "toolchain": {