A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Web: a failed IndexedDB save shows its message, and New Game writes its save at once instead of deleting (Fixes #2632, #2693) (#2634)
Eyal Golan1697bf0c8c3c
diff --git a/changelog.d/2632-web-save-failure-toast.md b/changelog.d/2632-web-save-failure-toast.mdnew file mode 100644index 000000000..4ae6b75b6--- /dev/null+++ b/changelog.d/2632-web-save-failure-toast.md@@ -0,0 +1,4 @@+### Fixed++- In the web version, a save that the browser fails to store (for example when its storage is full) now shows the+ "could not be saved" message instead of failing silently.diff --git a/changelog.d/2693.md b/changelog.d/2693.mdnew file mode 100644index 000000000..ade4ddadb--- /dev/null+++ b/changelog.d/2693.md@@ -0,0 +1,5 @@+### Fixed++- A confirmed New Game no longer deletes the autosave; it writes the new game's autosave at once (it used to write+ nothing until the next order or turn). In the web version the browser finishes storing it a moment later, so closing+ the tab immediately can still lose it.diff --git a/docs/WRITING_UI.md b/docs/WRITING_UI.mdindex 1bd072049..5f7efce6a 100644--- a/docs/WRITING_UI.md+++ b/docs/WRITING_UI.md@@ -75,7 +75,6 @@ Check: a pattern search over the strings files.### UI-05 A refusal says what, why and what nextStatus: proposed (observed in the save and start-up strings). Reason: NN/g and GOV.UK agree that an error message should name the specific problem and say how to fix it. Neither requires a separate "why", but in a game the reason is a rule the player can act on, so it is kept. Where nothing can be done, say what happens instead.-- Good: "The old saved game could not be removed; it will be replaced the next time the game saves." (`newgame.delete_failed`): what happened and what happens next.- Good: "Statecraft could not start: {0}. Reload the page." (`boot.failed`): what happened and what to do.- Good: "Your saved game could not be loaded ({0}). A new game has started." (`save.unreadable`).- Mixed: "Not enough attention (need {0:0.0}, have {1:0.0})" (`order.no_attention`) gives the rule and the numbers but no next step. It is also shown after "Not done: " (`toast.refused`), so the player reads "Not done: Not enough attention (...)".@@ -167,7 +166,6 @@ Check: manual.| Key | String | Verdict | Rule ||---|---|---|---|-| `newgame.delete_failed` | The old saved game could not be removed; it will be replaced the next time the game saves. | Good | UI-05 || `boot.failed` | Statecraft could not start: {0}. Reload the page. | Good (the `{0}` is the fixed `boot.reason_other`, #705) | UI-05, UI-07 || `save.reason_other` | the file could not be read or replayed | Good, a fixed player reason | UI-07 || `why.empty` | Nothing has happened yet: end the turn to see its causes. | Good, empty state with a next step | UI-10 |diff --git a/tools/tests/test_autosave_persistence.py b/tools/tests/test_autosave_persistence.pyindex cc6b28895..d149b9ddd 100644--- a/tools/tests/test_autosave_persistence.py+++ b/tools/tests/test_autosave_persistence.py@@ -12,11 +12,12 @@ pytestmark = pytest.mark.skipif(shutil.which("node") is None, reason="needs nodedef run(body):driver = r'''const assert = require("node:assert/strict");-const mount = {}, other = {}, calls = [], logs = [], errors = [], callbacks = [];+const mount = {}, other = {}, calls = [], logs = [], errors = [], callbacks = [], messages = [];const Module = { __unityIdbfsMount: { mount }, autoSyncPersistentDataPath: true };const LibraryManager = { library: {} };function mergeInto(target, value) { Object.assign(target, value); }function UTF8ToString(value) { return value; }+function SendMessage(target, method, value) { messages.push([target, method, value]); }const console = { log: value => logs.push(value), error: value => errors.push(value) };const IDBFS = { syncfs(target, populate, callback) {assert.equal(this, IDBFS);@@ -27,6 +28,7 @@ const IDBFS = { syncfs(target, populate, callback) {const StatecraftAutosave = LibraryManager.library.$StatecraftAutosave;const request = LibraryManager.library.StatecraftPersistAutosave;const one = "1 1948-06-15 turn 1 hash aa", two = "2 1948-07-15 turn 2 hash bb";+function save(value, target = "UI") { request("save " + value, target); }function flush(target = mount, populate = false) {return IDBFS.syncfs(target, populate, error => callbacks.push(error));}@@ -36,13 +38,14 @@ function flush(target = mount, populate = false) {def test_save_ack_waits_for_the_existing_sync_callback_and_starts_no_sync():run(r'''-request(one);+save(one);assert.equal(calls.length, 0); // file close already queued Unity's timer; the observer must not launch a competing syncassert.deepEqual(logs, []);assert.equal(flush(), "existing sync result");assert.deepEqual(logs, []);calls[0].callback(null);assert.deepEqual(logs, ["AUTOSAVE OK " + one]);+assert.deepEqual(messages, [["UI", "OnSavePersistenceResult", "ok save " + one]]);assert.deepEqual(callbacks, [null]);assert.deepEqual(errors, []);''')@@ -51,55 +54,61 @@ assert.deepEqual(errors, []);def test_a_first_request_during_an_older_sync_waits_for_the_followup():run(r'''flush(); // Unity was already syncing before our observer was installed-request(one);+save(one);calls[0].callback(null);assert.deepEqual(logs, []);flush();calls[1].callback(null);assert.deepEqual(logs, ["AUTOSAVE OK " + one]);+assert.deepEqual(messages, [["UI", "OnSavePersistenceResult", "ok save " + one]]);assert.equal(calls.length, 2);''')def test_each_generation_belongs_to_the_snapshot_that_started_after_its_request():run(r'''-request(one);+save(one);IDBFS.syncfs(mount, false, error => { callbacks.push(error); flush(); }); // Unity's 'again' callback starts the next sync-request(two); // writes made while the first snapshot is in flight+save(two); // writes made while the first snapshot is in flightcalls[0].callback(null);assert.equal(calls.length, 2);assert.deepEqual(logs, []); // a superseded snapshot must not claim either exact file state+assert.deepEqual(messages, []);calls[1].callback(null);assert.deepEqual(logs, ["AUTOSAVE OK " + two]);+assert.deepEqual(messages, [["UI", "OnSavePersistenceResult", "ok save " + two]]);assert.deepEqual(callbacks, [null, null]);''')def test_sync_errors_are_not_success_and_do_not_poison_the_next_save():run(r'''-request(one);+save(one);flush();const error = new Error("storage denied");calls[0].callback(error);assert.deepEqual(logs, []);assert.deepEqual(errors, ["AUTOSAVE FAIL " + one]);+assert.deepEqual(messages, [["UI", "OnSavePersistenceResult", "fail save " + one]]);assert.equal(callbacks[0], error);-request(two);+save(two);flush();calls[1].callback(null);assert.deepEqual(logs, ["AUTOSAVE OK " + two]);+assert.deepEqual(messages[1], ["UI", "OnSavePersistenceResult", "ok save " + two]);''')def test_boot_populate_and_other_mounts_pass_through_without_taking_save_requests():run(r'''-request(one);+save(one);assert.equal(flush(mount, true), "existing sync result");flush(other);calls[0].callback(null); calls[1].callback(null);assert.deepEqual(logs, []);flush(); calls[2].callback(null);assert.deepEqual(logs, ["AUTOSAVE OK " + one]);+assert.deepEqual(messages, [["UI", "OnSavePersistenceResult", "ok save " + one]]);assert.equal(calls[0].populate, true);assert.equal(calls[1].target, other);''')@@ -108,18 +117,70 @@ assert.equal(calls[1].target, other);@pytest.mark.parametrize("disable", ["Module.autoSyncPersistentDataPath = false;", "delete Module.__unityIdbfsMount;"])def test_missing_autosync_fails_instead_of_announcing_durability(disable):run(disable + r'''-request(one);+save(one);assert.deepEqual(errors, ["AUTOSAVE FAIL " + one]);assert.deepEqual(logs, []);+assert.deepEqual(messages, [["UI", "OnSavePersistenceResult", "fail save " + one]]);assert.equal(calls.length, 0);''')def test_multiple_writes_before_one_flush_acknowledge_only_the_latest_file_contents():run(r'''-request(one);-request(two); // one file path now contains two's bytes, not one's+save(one);+save(two); // one file path now contains two's bytes, not one'sflush();calls[0].callback(null);assert.deepEqual(logs, ["AUTOSAVE OK " + two]);+assert.deepEqual(messages, [["UI", "OnSavePersistenceResult", "ok save " + two]]);+''')+++def test_delete_success_reports_to_its_requesting_game_root_without_an_autosave_receipt():+ run(r'''+request("delete", "GameRoot");+flush();+calls[0].callback(null);+assert.deepEqual(logs, []);+assert.deepEqual(errors, []);+assert.deepEqual(messages, [["GameRoot", "OnSavePersistenceResult", "ok delete"]]);+''')+++def test_delete_failure_reports_to_its_requesting_game_root_without_an_autosave_receipt():+ run(r'''+request("delete", "GameRoot");+flush();+calls[0].callback(new Error("storage denied"));+assert.deepEqual(logs, []);+assert.deepEqual(errors, []);+assert.deepEqual(messages, [["GameRoot", "OnSavePersistenceResult", "fail delete"]]);+''')+++def test_a_delete_before_the_flush_replaces_the_pending_save_and_only_the_delete_reports():+ run(r'''+save(one);+request("delete", "GameRoot"); // New Game deletes the file before the queued flush starts+flush();+calls[0].callback(null);+assert.deepEqual(logs, []); // the save's bytes are gone, so its receipt must not be announced as durable+assert.deepEqual(errors, []);+assert.deepEqual(messages, [["GameRoot", "OnSavePersistenceResult", "ok delete"]]);+''')+++def test_a_save_flush_failing_after_a_delete_request_still_reports_the_save_failure():+ run(r'''+save(one);+flush(); // the save's snapshot is in flight+request("delete", "GameRoot");+const error = new Error("storage denied");+calls[0].callback(error);+assert.deepEqual(errors, ["AUTOSAVE FAIL " + one]);+assert.deepEqual(messages, [["UI", "OnSavePersistenceResult", "fail save " + one]]);+flush();+calls[1].callback(null);+assert.deepEqual(messages[1], ["GameRoot", "OnSavePersistenceResult", "ok delete"]);+assert.deepEqual(logs, []);''')diff --git a/tools/tests/test_web_check.py b/tools/tests/test_web_check.pyindex a737b4b7e..58aa6023d 100644--- a/tools/tests/test_web_check.py+++ b/tools/tests/test_web_check.py@@ -883,10 +883,20 @@ def test_a_commit_timeout_fails_even_without_any_further_console_line():_ = check.done-def test_an_indexeddb_failure_fails_the_driver_loudly():+def test_an_indexeddb_failure_without_the_player_message_fails_after_the_toast_deadline():+ clock = [0.0]+ check = wc.PersistenceCheck(*_quiet(), lambda seconds: None, now=lambda: clock[0], save_timeout=5)+ check.feed("AUTOSAVE FAIL 1 1948-06-15 turn 1 hash bb")+ clock[0] = 5+ with pytest.raises(ValueError, match="save.write_failed was not shown to the player"):+ _ = check.done+++def test_an_indexeddb_failure_with_the_player_message_still_fails_but_records_coverage():check = wc.PersistenceCheck(*_quiet(), lambda seconds: None)- with pytest.raises(ValueError, match="IndexedDB autosave failed"):- check.feed("AUTOSAVE FAIL 1 1948-06-15 turn 1 hash bb")+ check.feed("AUTOSAVE FAIL 1 1948-06-15 turn 1 hash bb")+ with pytest.raises(ValueError, match="save.write_failed was shown to the player"):+ check.feed("SAVE FAILURE SHOWN save.write_failed")def test_commit_ack_before_turn_diagnostic_is_not_lost():diff --git a/tools/web_check.py b/tools/web_check.pyindex 479c28d93..1f3ae84fa 100644--- a/tools/web_check.py+++ b/tools/web_check.py@@ -411,6 +411,7 @@ NAVLOG = "navlog"GAME_STATE = re.compile(r"^GAME OK (\d{4}-\d{2}-\d{2}) turn (\d+) hash ([0-9a-f]+)$")TURN_STATE = re.compile(r"^TURN (\d+) (\d{4}-\d{2}-\d{2}) hash ([0-9a-f]+)$")SAVE_STATE = re.compile(r"^AUTOSAVE (PENDING|OK|FAIL) ([1-9]\d*) (\d{4}-\d{2}-\d{2}) turn (\d+) hash ([0-9a-f]+)$")+SAVE_FAILURE_SHOWN = "SAVE FAILURE SHOWN save.write_failed"class StartButtons:@@ -712,11 +713,15 @@ class PersistenceCheck:self.end_turn = EndTurn(action, tail, hebrew=False, settle=settle)self.stage, self.saved, self._done = "first_boot", None, Falseself.pending, self.acknowledged, self.deadline = None, None, None+ self.persistence_failure = None@propertydef done(self) -> bool:# watch polls this even when no more console lines arrive.if self.deadline is not None and self.now() >= self.deadline:+ if self.persistence_failure is not None:+ raise ValueError("PERSISTENCE FAIL IndexedDB autosave failed but "+ "save.write_failed was not shown to the player")raise ValueError(f"PERSISTENCE FAIL no matching IndexedDB commit within {self.save_timeout:g}s: "f"{self.saved}; pending receipt {self.pending}")return self._done@@ -744,7 +749,9 @@ class PersistenceCheck:kind, generation, date, turn, digest = receipt.groups()value = (int(generation), date, int(turn), digest)if kind == "FAIL":- raise ValueError(f"PERSISTENCE FAIL IndexedDB autosave failed: {value}")+ self.persistence_failure = value+ self.deadline = self.now() + self.save_timeout+ returnif kind == "PENDING":if self.pending is None or value[0] > self.pending[0]:self.pending, self.acknowledged = value, None@@ -752,6 +759,9 @@ class PersistenceCheck:self.acknowledged = valueself._reload_when_durable()return+ if text == SAVE_FAILURE_SHOWN and self.persistence_failure is not None:+ raise ValueError("PERSISTENCE FAIL IndexedDB autosave failed and "+ f"save.write_failed was shown to the player: {self.persistence_failure}")game, turn = GAME_STATE.match(text), TURN_STATE.match(text)if game:state, kind = (game.group(1), int(game.group(2)), game.group(3)), "GAME"diff --git a/unity/Assets/Scripts/SaveStore.cs b/unity/Assets/Scripts/SaveStore.csindex 0c2317151..df2904f3b 100644--- a/unity/Assets/Scripts/SaveStore.cs+++ b/unity/Assets/Scripts/SaveStore.cs@@ -26,7 +26,7 @@ namespace Statecraft.Gamepublic string AutosavePath => Path.Combine(Directory, AutosaveName);- public void WriteAutosave(string text)+ public virtual void WriteAutosave(string text){System.IO.Directory.CreateDirectory(Directory);var tmp = AutosavePath + ".tmp";@@ -63,12 +63,5 @@ namespace Statecraft.Gameif (File.Exists(bad)) bad = Path.Combine(Directory, "autosave.bad." + System.Guid.NewGuid().ToString("N") + ".txt");File.Move(source, bad);}-- /// <summary>Removes the autosave and any lingering .tmp (a leftover would be resurrected by the next start).</summary>- public virtual void DeleteAutosave()- {- if (File.Exists(AutosavePath)) File.Delete(AutosavePath);- if (File.Exists(AutosavePath + ".tmp")) File.Delete(AutosavePath + ".tmp");- }}}diff --git a/unity/Assets/Scripts/UI/AutosavePersistence.jslib b/unity/Assets/Scripts/UI/AutosavePersistence.jslibindex 0a5e072ca..09971cbb6 100644--- a/unity/Assets/Scripts/UI/AutosavePersistence.jslib+++ b/unity/Assets/Scripts/UI/AutosavePersistence.jslib@@ -1,14 +1,27 @@// Observe Unity 6000.3's existing autosync, never start a concurrent FS.syncfs. SaveStore has already closed and// renamed the file; autoPersist queued that mount. Capture requests when its next flush starts, so a request made-// during an older in-flight flush cannot be acknowledged by the older snapshot. TURN remains a sim diagnostic.+// during an older in-flight flush cannot be acknowledged by the older snapshot. Report the result to the requesting+// GameRoot as well as the console. TURN remains a sim diagnostic.mergeInto(LibraryManager.library, {$StatecraftAutosave: { pending: null, latest: null, installed: false },StatecraftPersistAutosave__deps: ["$StatecraftAutosave", "$IDBFS"],- StatecraftPersistAutosave: function (receiptPtr) {- var receipt = UTF8ToString(receiptPtr);+ StatecraftPersistAutosave: function (requestPtr, targetPtr) {+ var request = {+ value: UTF8ToString(requestPtr),+ target: UTF8ToString(targetPtr),+ };+ function report(saved, error) {+ var save = saved.value.indexOf("save ") === 0;+ var receipt = save ? saved.value.substring(5) : null;+ if (save) {+ if (error) console.error("AUTOSAVE FAIL " + receipt);+ else console.log("AUTOSAVE OK " + receipt);+ }+ SendMessage(saved.target, "OnSavePersistenceResult", (error ? "fail " : "ok ") + saved.value);+ }var mount = Module.__unityIdbfsMount && Module.__unityIdbfsMount.mount;if (!mount || !Module.autoSyncPersistentDataPath) {- console.error("AUTOSAVE FAIL " + receipt);+ report(request, new Error("IndexedDB autosync is unavailable"));return;}var saves = StatecraftAutosave;@@ -23,8 +36,8 @@ mergeInto(LibraryManager.library, {try { callback(error); }finally {if (saved) {- if (error) console.error("AUTOSAVE FAIL " + saved);- else if (saved === saves.latest) console.log("AUTOSAVE OK " + saved);+ if (error) report(saved, error);+ else if (saved === saves.latest) report(saved, null);}}});@@ -32,6 +45,6 @@ mergeInto(LibraryManager.library, {saves.installed = true;}// Multiple writes before the queued flush overwrite the same autosave path: only its latest bytes can be durable.- saves.pending = saves.latest = receipt;+ saves.pending = saves.latest = request;},});diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 1fdd11e40..ea0811b75 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -26,6 +26,12 @@ namespace Statecraft.Game.UI[ExecuteAlways]public sealed class GameRoot : MonoBehaviour{+ Action<string>? savePersistenceResult;++ /// <summary>Unity WebGL SendMessage entry point for IndexedDB save/delete results.</summary>+ [UnityEngine.Scripting.Preserve]+ public void OnSavePersistenceResult(string result) => savePersistenceResult?.Invoke(result);+/// <summary>Turns a bare smoke flag ("?smoke", "-smoke") plays.</summary>internal const int DefaultSmokeTurns = 5;/// <summary>Maximum time after closing the start screen for the normal-media browser check's first card to become usable.@@ -317,6 +323,14 @@ namespace Statecraft.Game.UI// The toast first: the autosave (below) must report a failed write after the toast has shown the turn's refusals.var toast = Own(new ToastPresenter(root, bridge, text));+ savePersistenceResult = result =>+ {+ if (result.StartsWith("fail save ", StringComparison.Ordinal))+ {+ toast.Append(text["save.write_failed"]);+ Debug.Log("SAVE FAILURE SHOWN save.write_failed");+ }+ };unseenSkipped = () => toast.Show(text["toast.unit_unseen_skipped"]);var hudPresenter = Own(new HudPresenter(root, bridge, text, selectUnit: _ => FocusNextUnit()));nav = Own(new ScreenNav(root, text)); // every screen starts hidden (USS); ScreenNav opens one at a time@@ -487,15 +501,15 @@ namespace Statecraft.Game.UIunitDone: FocusNextUnit, showRoute: map.ShowRoute, showArrow: map.ShowMoveArrow, selectPioneer: FocusPioneer, clearSelection: () => { unitLayer.Select(null); map.ClearSelection(); }));toast.Units = unitData; toast.TownNamesHe = townNamesHe; why.TownNamesHe = townNamesHe; bridge.TownNamesHe = townNamesHe;report.TownNamesHe = townNamesHe; hudPresenter.TownNamesHe = townNamesHe;- // A smoke session never touches the player's save: no autosave, and no New Game (which deletes the autosave).- // Leaving New Game out is safer than handing it a throwaway store: no file is ever deleted, no path has to be+ // A smoke session never touches the player's save: no autosave, and no New Game (which writes the autosave).+ // Leaving New Game out is safer than handing it a throwaway store: no file is ever written, no path has to be// right on every platform, and the scripted run never presses it.NewGamePresenter? newGame = null;if (smoke == 0){- newGame = Own(new NewGamePresenter(root, bridge, store, toast, text, GameStart.NewSeed));+ newGame = Own(new NewGamePresenter(root, bridge, store, toast, text, GameStart.NewSeed, gameObject.name));this.newGame = newGame;- Own(GameStart.Autosave(bridge, store, text, toast.Append)); // appends: the turn's refusals stay visible+ Own(GameStart.Autosave(bridge, store, text, toast.Append, gameObject.name)); // appends: the turn's refusals stay visible}// Once the game is over, the sim's end report (#812); after the autosave, so the last turn is saved first. New Game// is its two presses; a smoke run has none.@@ -972,6 +986,7 @@ namespace Statecraft.Game.UIif (keepCompanionPage && companion != null) { owned.Remove(companion); companion.Dispose(clearPage: false); }for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();owned.Clear();+ savePersistenceResult = null;if (hoveredCity != null) { hoveredCity = null; HandCursor(false); } // the next Begin's pills start unlitcompanion = null; minimap = null; unseenSkipped = null; labels = null; nav = null; start = null; opening = null; card = null; outcomes = null; report = null; end = null; advisor = null; cabinet = null; newGame = null; encyclopedia = null; feedback = null; share = null; info = null; rig = null; drawn = null; drawnSites = null; units = null; Regions = null; logCamera = false;// A ?profile run cut short (a stopped coroutine never reaches its restore line) must not leave the terrain at thediff --git a/unity/Assets/Scripts/UI/GameStart.cs b/unity/Assets/Scripts/UI/GameStart.csindex eb5a0f3df..e3be15e39 100644--- a/unity/Assets/Scripts/UI/GameStart.cs+++ b/unity/Assets/Scripts/UI/GameStart.cs@@ -77,32 +77,40 @@ namespace Statecraft.Game.UIreturn GameSession.New(c, newSeed(), Mode.Historical);}- /// <summary>Writes the save after every committed order and every turn. A write that fails (a full or read-only disk) never stops the game:- /// the reason goes to <paramref name="onError"/>. Dispose the result to stop autosaving.</summary>- public static IDisposable Autosave(SimBridge bridge, SaveStore store, UiText text, Action<string>? onError = null)+ /// <summary>Writes <paramref name="session"/> through the complete autosave path. A failure never stops play: the+ /// reason goes to <paramref name="onError"/> and false is returned. On WebGL <paramref name="persistenceTarget"/>+ /// receives the asynchronous IndexedDB result.</summary>+ internal static bool WriteAutosave(GameSession session, SaveStore store, UiText text, Action<string>? onError = null,+ string? persistenceTarget = null){- void Save(IReadOnlyList<Rejection> _)+ try{- try- {- store.WriteAutosave(bridge.Session.Save.Write());- // Capture this save, not the mutable session at an asynchronous commit's completion.- var state = bridge.TurnStart;- var generation = System.Threading.Interlocked.Increment(ref saveGeneration);- var receipt = FormattableString.Invariant($"{generation} {state.Date:yyyy-MM-dd} turn {state.Turn} hash {state.Hash()}");- UnityEngine.Debug.Log("AUTOSAVE PENDING " + receipt);+ store.WriteAutosave(session.Save.Write());+ // Capture this save, not a bridge whose session may be replaced before an asynchronous commit completes.+ var state = session.State;+ var generation = System.Threading.Interlocked.Increment(ref saveGeneration);+ var receipt = FormattableString.Invariant($"{generation} {state.Date:yyyy-MM-dd} turn {state.Turn} hash {state.Hash()}");+ UnityEngine.Debug.Log("AUTOSAVE PENDING " + receipt);#if UNITY_WEBGL && !UNITY_EDITOR- StatecraftPersistAutosave(receipt);+ StatecraftPersistAutosave("save " + receipt, persistenceTarget ?? "");#else- UnityEngine.Debug.Log("AUTOSAVE OK " + receipt);+ UnityEngine.Debug.Log("AUTOSAVE OK " + receipt);#endif- }- catch (Exception e)- {- UnityEngine.Debug.LogWarning("Autosave could not be written: " + e);- onError?.Invoke(text["save.write_failed"]);- }+ return true;}+ catch (Exception e)+ {+ UnityEngine.Debug.LogWarning("Autosave could not be written: " + e);+ onError?.Invoke(text["save.write_failed"]);+ return false;+ }+ }++ /// <summary>Writes the save after every committed order and every turn. Dispose the result to stop autosaving.</summary>+ public static IDisposable Autosave(SimBridge bridge, SaveStore store, UiText text, Action<string>? onError = null,+ string? persistenceTarget = null)+ {+ void Save(IReadOnlyList<Rejection> _) => WriteAutosave(bridge.Session, store, text, onError, persistenceTarget);Action<IReadOnlyList<Cause>> onCommit = _ => Save(Array.Empty<Rejection>());bridge.Committed += onCommit;bridge.TurnEnded += Save;@@ -111,7 +119,7 @@ namespace Statecraft.Game.UI#if UNITY_WEBGL && !UNITY_EDITOR[System.Runtime.InteropServices.DllImport("__Internal")]- static extern void StatecraftPersistAutosave(string receipt);+ static extern void StatecraftPersistAutosave(string request, string target);#endifsealed class Unsubscribe : IDisposablediff --git a/unity/Assets/Scripts/UI/NewGamePresenter.cs b/unity/Assets/Scripts/UI/NewGamePresenter.csindex f0afe4c49..4109fb885 100644--- a/unity/Assets/Scripts/UI/NewGamePresenter.cs+++ b/unity/Assets/Scripts/UI/NewGamePresenter.cs@@ -5,16 +5,20 @@ using UnityEngine.UIElements;namespace Statecraft.Game.UI{- /// <summary>New Game asks for a second press (no browser confirm dialogs in WebGL), then deletes the autosave and- /// starts a new Historical game. Ending a turn in between cancels the request. The start screen's New Game goes through+ /// <summary>New Game asks for a second press (no browser confirm dialogs in WebGL), then starts and immediately saves a+ /// new Historical game. Ending a turn in between cancels the request. The start screen's New Game goes through/// the same two presses (Press), so neither button can wipe the save with one stray press (#175, B6).</summary>public sealed class NewGamePresenter : IDisposable{- readonly VisualElement root; readonly SimBridge bridge; readonly SaveStore store; readonly ToastPresenter toast; readonly UiText text; readonly Func<ulong> seed;+ readonly VisualElement root; readonly SimBridge bridge; readonly SaveStore store;+ readonly ToastPresenter toast; readonly UiText text; readonly Func<ulong> seed;+ readonly string? persistenceTarget;- public NewGamePresenter(VisualElement root, SimBridge bridge, SaveStore store, ToastPresenter toast, UiText text, Func<ulong> seed)+ public NewGamePresenter(VisualElement root, SimBridge bridge, SaveStore store, ToastPresenter toast, UiText text,+ Func<ulong> seed, string? persistenceTarget = null){this.root = root; this.bridge = bridge; this.store = store; this.toast = toast; this.text = text; this.seed = seed;+ this.persistenceTarget = persistenceTarget;button = root.Q<Button>("new-game");button.clicked += Press;bridge.Changed += Disarm;@@ -47,11 +51,9 @@ namespace Statecraft.Game.UI{if (!Armed) { Armed = true; toast.Show(text["newgame.confirm"]); return; }Armed = false;- bool deleted = true;- // An old autosave that cannot be deleted is overwritten by the next autosave anyway (after the next order or turn), so the new game still starts.- try { store.DeleteAutosave(); } catch (Exception e) { deleted = false; UnityEngine.Debug.LogWarning("Autosave could not be deleted: " + e); }- bridge.Replace(GameSession.New(bridge.Content, seed(), Mode.Historical));- if (deleted) toast.Clear(); else toast.Show(text["newgame.delete_failed"]);+ var fresh = GameSession.New(bridge.Content, seed(), Mode.Historical);+ bridge.Replace(fresh);+ if (GameStart.WriteAutosave(fresh, store, text, toast.Show, persistenceTarget)) toast.Clear();Started?.Invoke();}}diff --git a/unity/Assets/Scripts/UI/StartScreenPresenter.cs b/unity/Assets/Scripts/UI/StartScreenPresenter.csindex 2e2a64ced..e125b51f4 100644--- a/unity/Assets/Scripts/UI/StartScreenPresenter.cs+++ b/unity/Assets/Scripts/UI/StartScreenPresenter.cs@@ -218,13 +218,13 @@ namespace Statecraft.Game.UIvoid NewGame(){if (!IsOpen) return;- if (!Resumed) { Close(); FreshGameOpened?.Invoke(); return; } // nothing to wipe: the session is already a new game+ if (!Resumed) { Close(); FreshGameOpened?.Invoke(); return; } // nothing to replace: the session is already a new gamenewGame.Press(); // arms on the first press; the second starts the new game (Started closes)}void Started(){- Resumed = false; // the save is gone (or will be replaced): nothing to continue any more+ Resumed = false; // the replacement is the current game: nothing older to continue any moreClose();}diff --git a/unity/Assets/Tests/EditMode/AdvisorOpeningParityTests.cs b/unity/Assets/Tests/EditMode/AdvisorOpeningParityTests.csindex e444635ab..efef71b1d 100644--- a/unity/Assets/Tests/EditMode/AdvisorOpeningParityTests.cs+++ b/unity/Assets/Tests/EditMode/AdvisorOpeningParityTests.cs@@ -138,14 +138,18 @@ public class AdvisorOpeningParityTestsBegin(game, Inputs, 0); // the tests' and tools' Begin: no start screenUiTestKit.Press(Ui.Q<Button>("new-game")); UiTestKit.Press(Ui.Q<Button>("new-game"));Assert.IsFalse(game.Advisor!.InChain, "an automated run");+ // #2693: the top bar's New Game writes the new game's autosave (it used to delete the old one), so the start screens+ // below have a save, and their New Game takes a confirming second press (StartScreenPresenter: a resumed screen goes+ // through NewGamePresenter.Press), as ANewGameFromASavedStartScreen... presses.+ Assert.IsNotNull(store.ReadAutosave(), "precondition: the top bar's New Game left an autosave");game.Settings = null; // EditMode with no settings fileBegin(game, Inputs, 0, startScreen: true);- UiTestKit.Press(Ui.Q<Button>("start-new-game"));+ UiTestKit.Press(Ui.Q<Button>("start-new-game")); UiTestKit.Press(Ui.Q<Button>("start-new-game"));Assert.IsFalse(game.Advisor!.InChain, "nowhere to remember it: never by itself");game.Settings = settings;Begin(game, Inputs, 0, startScreen: true);- UiTestKit.Press(Ui.Q<Button>("start-new-game"));+ UiTestKit.Press(Ui.Q<Button>("start-new-game")); UiTestKit.Press(Ui.Q<Button>("start-new-game"));Assert.IsTrue(game.Advisor!.InChain, "the first new game in this profile");}diff --git a/unity/Assets/Tests/EditMode/EndScreenTests.cs b/unity/Assets/Tests/EditMode/EndScreenTests.csindex 4800d9646..463693b21 100644--- a/unity/Assets/Tests/EditMode/EndScreenTests.cs+++ b/unity/Assets/Tests/EditMode/EndScreenTests.cs@@ -386,7 +386,10 @@ public class EndScreenTestsUiTestKit.Press(k.Ui.Q<Button>("end-screen-new-game"));Assert.IsNull(k.Bridge.State.GameOver, "the second press starts a new game");Assert.IsFalse(k.End.IsOpen, "which has no end screen");- Assert.IsFalse(File.Exists(k.Store.AutosavePath), "New Game removes the old save, as it always has");+ Assert.IsTrue(File.Exists(k.Store.AutosavePath), "New Game saves its replacement immediately");+ var resumed = GameStart.Begin(C, k.Store, () => 1UL, new List<string>(), En);+ Assert.AreEqual(k.Bridge.State.Hash(), resumed.State.Hash());+ Assert.IsNull(resumed.State.GameOver);}[Test]diff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.csindex 3f5697b8a..2bfef1028 100644--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs@@ -44,12 +44,13 @@ public class GameSceneTests/// <summary>Opens Map.unity, builds the map from the repository inputs and starts the game the way GameBoot.Ready does,/// with the saves in a temporary folder (never the player's real autosave).</summary>- GameRoot Boot(SaveStore? store = null)+ GameRoot Boot(SaveStore? store = null, string? language = null){EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);Object.FindFirstObjectByType<MapScene>().Build(Inputs.Map);var root = Object.FindFirstObjectByType<GameRoot>();root.Store = store ?? new SaveStore(saveDir);+ root.Language = language;root.Begin(Inputs, 0);return root;}@@ -722,6 +723,29 @@ public class GameSceneTestsAssert.AreEqual(DisplayStyle.Flex, Ui.Q("toast").style.display.value);}+ [TestCase(false)]+ [TestCase(true)]+ public void WebSavePersistenceFailuresUseTheCurrentLanguagesExistingToast(bool hebrew)+ {+ var language = hebrew ? UiLanguage.Hebrew : UiLanguage.English;+ var text = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(hebrew ? UiPaths.StringsHebrew : UiPaths.Strings).text,+ hebrew ? "strings.he.yaml" : "strings.en.yaml");+ var root = Boot(language: language);++ root.OnSavePersistenceResult("fail save 1 1948-06-15 turn 1 hash aa");+ Assert.AreEqual(text["save.write_failed"], Ui.Q<Label>("toast").text);+ Assert.AreEqual(DisplayStyle.Flex, Ui.Q("toast").style.display.value);+ }++ [Test]+ public void SuccessfulWebPersistenceResultsDoNotShowAnError()+ {+ var root = Boot();+ root.OnSavePersistenceResult("ok save 1 1948-06-15 turn 1 hash aa");+ Assert.AreEqual("", Ui.Q<Label>("toast").text);+ Assert.AreEqual(DisplayStyle.None, Ui.Q("toast").style.display.value);+ }+/// <summary>#2152: the game reports earned achievements to the store set in PlatformServices.Current (a Steam build's).</summary>[Test]public void TheGameReportsAchievementsToTheCurrentStore()diff --git a/unity/Assets/Tests/EditMode/OpeningRoutingTests.cs b/unity/Assets/Tests/EditMode/OpeningRoutingTests.csindex f29bfced7..e0a2ae19d 100644--- a/unity/Assets/Tests/EditMode/OpeningRoutingTests.cs+++ b/unity/Assets/Tests/EditMode/OpeningRoutingTests.cs@@ -11,6 +11,7 @@ using Statecraft.Game.Boot;using Statecraft.Game.Map;using Statecraft.Game.UI;using Statecraft.Sim;+using UnityEditor;using UnityEditor.SceneManagement;using UnityEngine;using UnityEngine.TestTools;@@ -25,11 +26,20 @@ public class OpeningRoutingTestsreadonly List<(PanelSettings panel, RenderTexture texture)> panels = new List<(PanelSettings, RenderTexture)>();static VisualElement Ui => Object.FindFirstObjectByType<UIDocument>().rootVisualElement;static bool StartOpen => Ui.Q("root").ClassListContains(StartScreenPresenter.OpenClass);- GameRoot Open(bool saved, out SaveStore store)+ string NewDirectory(){var dir = Path.Combine(Path.GetTempPath(), "statecraft-opening-routing-" + Guid.NewGuid().ToString("N"));- directories.Add(dir); store = new SaveStore(dir);+ directories.Add(dir);+ return dir;+ }+ GameRoot Open(bool saved, out SaveStore store)+ {+ store = new SaveStore(NewDirectory());if (saved) store.WriteAutosave(GameSession.New(Inputs.Content, 23UL, Mode.Historical).Save.Write());+ return Open(store);+ }+ GameRoot Open(SaveStore store)+ {EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);var doc = Object.FindFirstObjectByType<UIDocument>();var panel = Object.Instantiate(doc.panelSettings);@@ -58,7 +68,7 @@ public class OpeningRoutingTests}[UnityTest]- public IEnumerator SavedNewGameStillRequiresBothConfirmations()+ public IEnumerator SavedNewGameStillRequiresBothConfirmationsAndTheNextRootLoadsIt(){var root = Open(saved: true, out var store);string save = File.ReadAllText(store.AutosavePath), hash = root.Bridge!.State.Hash();@@ -72,8 +82,57 @@ public class OpeningRoutingTestsyield return null;Assert.IsFalse(StartOpen);Assert.AreEqual(DisplayStyle.Flex, Ui.Q("opening-layer").resolvedStyle.display);- Assert.IsFalse(File.Exists(store.AutosavePath), "the confirmed new game uses the existing deletion flow");Assert.AreEqual(0, root.Bridge.State.Turn, "opening is before the first turn");+ var newHash = root.Bridge.State.Hash();+ Assert.IsTrue(File.Exists(store.AutosavePath), "the confirmed new game is saved before any order or turn");++ var restarted = Open(store);+ yield return null;+ Assert.IsTrue(StartOpen);+ Assert.AreEqual(DisplayStyle.Flex, Ui.Q<Button>("start-continue").style.display.value, "Continue is offered");+ Assert.AreEqual(0, restarted.Bridge!.State.Turn);+ Assert.AreEqual(newHash, restarted.Bridge.State.Hash(), "a second real GameRoot loads the immediate New Game save");+ }++ sealed class FailNextWriteStore : SaveStore+ {+ public bool FailNextWrite;+ public FailNextWriteStore(string directory) : base(directory) { }+ public override void WriteAutosave(string text)+ {+ if (FailNextWrite) { FailNextWrite = false; throw new IOException("locked"); }+ base.WriteAutosave(text);+ }+ }++ [UnityTest]+ public IEnumerator AFailedNewGameWriteKeepsTheOldSaveForTheNextRoot()+ {+ var store = new FailNextWriteStore(NewDirectory());+ var old = new SimBridge(GameSession.New(Inputs.Content, 23UL, Mode.Historical),+ UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text));+ old.EndTurn(); old.EndTurn();+ store.WriteAutosave(old.Session.Save.Write());+ var oldHash = old.State.Hash();+ var first = Open(store);+ Assert.AreEqual(2, first.Bridge!.State.Turn, "precondition: the first root resumed the old game");+ store.FailNextWrite = true;++ UiTestKit.Press(Ui.Q<Button>("start-new-game"));+ yield return null;+ LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("^Autosave could not be written"));+ UiTestKit.Press(Ui.Q<Button>("start-new-game"));+ yield return null;+ Assert.AreEqual(0, first.Bridge.State.Turn, "the in-memory New Game proceeds despite the failed write");+ Assert.AreEqual(UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text)["save.write_failed"],+ Ui.Q<Label>("toast").text);++ var restarted = Open(store);+ yield return null;+ Assert.IsTrue(StartOpen);+ Assert.AreEqual(DisplayStyle.Flex, Ui.Q<Button>("start-continue").style.display.value, "the preserved save still offers Continue");+ Assert.AreEqual(2, restarted.Bridge!.State.Turn);+ Assert.AreEqual(oldHash, restarted.Bridge.State.Hash(), "a second real GameRoot resumes the untouched old autosave");}[UnityTest]diff --git a/unity/Assets/Tests/EditMode/SaveUiTests.cs b/unity/Assets/Tests/EditMode/SaveUiTests.csindex 37beb21bb..626914212 100644--- a/unity/Assets/Tests/EditMode/SaveUiTests.cs+++ b/unity/Assets/Tests/EditMode/SaveUiTests.cs@@ -438,26 +438,35 @@ public class SaveUiTests}[Test]- public void AFailedDeleteStillStartsTheNewGame()+ public void AFailedWriteStillStartsTheNewGameAndKeepsTheOldAutosave(){using var ui = new UiTestKit();var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);bridge.EndTurn();var toast = new ToastPresenter(ui.Root, bridge, Text);- var store = new DeleteFailsStore();+ var directory = TempStore().Directory;+ var store = new WriteFailsStore(directory);+ store.WriteAutosave(bridge.Session.Save.Write());+ var oldAutosave = File.ReadAllBytes(store.AutosavePath);+ store.FailNextWrite = true;new NewGamePresenter(ui.Root, bridge, store, toast, Text, () => 4UL);ui.Press("new-game");+ LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("^Autosave could not be written"));Assert.DoesNotThrow(() => ui.Press("new-game"));Assert.AreEqual(0, bridge.State.Turn);- Assert.AreEqual("The old saved game could not be removed; it will be replaced the next time the game saves.",- ui.Q<Label>("toast").text,- "was 'The old saved game could not be removed; it will be replaced after your next turn.'; autosave also runs after committed orders");+ CollectionAssert.AreEqual(oldAutosave, File.ReadAllBytes(store.AutosavePath));+ Assert.AreEqual(Text["save.write_failed"], ui.Q<Label>("toast").text);}- sealed class DeleteFailsStore : SaveStore+ sealed class WriteFailsStore : SaveStore{- public DeleteFailsStore() : base(Path.Combine(Path.GetTempPath(), "statecraft-faulty")) { }- public override void DeleteAutosave() => throw new IOException("locked");+ public bool FailNextWrite;+ public WriteFailsStore(string directory) : base(directory) { }+ public override void WriteAutosave(string text)+ {+ if (FailNextWrite) { FailNextWrite = false; throw new IOException("locked"); }+ base.WriteAutosave(text);+ }}[Test]@@ -476,7 +485,10 @@ public class SaveUiTestsAssert.AreEqual(1, bridge.State.Turn);ui.Press("new-game");Assert.AreEqual(0, bridge.State.Turn);- Assert.IsFalse(File.Exists(store.AutosavePath));+ Assert.IsTrue(File.Exists(store.AutosavePath));+ var resumed = GameStart.Begin(C, store, () => 1UL, new List<string>(), Text);+ Assert.AreEqual(bridge.State.Hash(), resumed.State.Hash());+ Assert.AreEqual(0, resumed.State.Turn);}[Test]@@ -606,7 +618,7 @@ public class SaveUiTests}[Test]- public void NewGameAlsoRemovesALingeringTmp()+ public void NewGameOverwritesALingeringTmpWithTheNewSession(){using var ui = new UiTestKit();var store = TempStore();@@ -619,7 +631,9 @@ public class SaveUiTestsui.Press("new-game"); ui.Press("new-game");Assert.IsFalse(File.Exists(store.AutosavePath + ".tmp"));var notes = new List<string>();- Assert.AreEqual(0, GameStart.Begin(C, store, () => 1UL, notes, Text).State.Turn, "the next start does not resurrect the abandoned game");+ var resumed = GameStart.Begin(C, store, () => 1UL, notes, Text);+ Assert.AreEqual(0, resumed.State.Turn, "the next start does not resurrect the abandoned game");+ Assert.AreEqual(played.State.Hash(), resumed.State.Hash(), "the next start loads the replacement written over the .tmp");Assert.IsEmpty(notes);}}diff --git a/unity/Assets/Tests/EditMode/StartScreenTests.cs b/unity/Assets/Tests/EditMode/StartScreenTests.csindex 83b65ff31..fec8fdca8 100644--- a/unity/Assets/Tests/EditMode/StartScreenTests.cs+++ b/unity/Assets/Tests/EditMode/StartScreenTests.cs@@ -333,7 +333,9 @@ public class StartScreenTestsrig.Ui.Press("start-new-game");Assert.IsFalse(rig.Start.IsOpen);Assert.AreEqual(0, rig.Bridge.State.Turn, "a new game");- Assert.IsFalse(File.Exists(store.AutosavePath), "the abandoned save is gone");+ Assert.IsTrue(File.Exists(store.AutosavePath), "the replacement game is saved immediately");+ var resumed = GameStart.Begin(C, store, () => 1UL, new List<string>(), Text);+ Assert.AreEqual(rig.Bridge.State.Hash(), resumed.State.Hash());Assert.IsFalse(rig.Start.Resumed);}diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex b99620c70..ae47c99d0 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -752,7 +752,6 @@ unit.send_home_queued: "Send home ordered: the unit goes home when you end the tunit.order.reinforce: "Reinforce +{0}"unit.reinforce_queued: "Reinforce ordered: the replacements start training when you end the turn"newgame.confirm: "Press New game again to abandon this game and start over."-newgame.delete_failed: "The old saved game could not be removed; it will be replaced the next time the game saves."save.unreadable: "Your saved game could not be loaded ({0}). A new game has started."save.reason_other: "the file could not be read or replayed"save.refused.older_rules: "Your saved game was made with an earlier version of the game's rules and cannot be continued. A new game has started."diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yamlindex ce7731b2d..4065180a2 100644--- a/unity/Assets/UI/strings.he.yaml+++ b/unity/Assets/UI/strings.he.yaml@@ -885,8 +885,6 @@ unit.send_home_queued: "ניתנה פקודת שליחה הביתה: היחידunit.order.reinforce: "תגבור +{0}"unit.reinforce_queued: "ניתנה פקודת תגבור: כוח ההשלמה יתחיל באימון בסיום התור"newgame.confirm: "יש ללחוץ שוב על משחק חדש כדי לעזוב את המשחק הזה ולהתחיל מחדש."-# For the native reviewer (#564): agent-drafted, #2552-newgame.delete_failed: "לא ניתן היה להסיר את השמירה הקודמת; היא תוחלף בפעם הבאה שהמשחק יישמר."save.unreadable: "לא ניתן היה לטעון את המשחק השמור ({0}). משחק חדש התחיל."save.reason_other: "לא ניתן היה לקרוא את הקובץ או לשחזר את המשחק"save.refused.older_rules: "המשחק השמור נוצר בגרסה קודמת של חוקי המשחק ואי אפשר להמשיך אותו. משחק חדש התחיל."