A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Share: clear stale clipboard callbacks and fall back to download on a synchronous share throw (#2009)
Beri32e7d9cf85fc
diff --git a/changelog.d/1897-share-robustness.md b/changelog.d/1897-share-robustness.mdnew file mode 100644index 000000000..e5f6675d4--- /dev/null+++ b/changelog.d/1897-share-robustness.md@@ -0,0 +1 @@+- Make Share more robust in the browser: a late clipboard result from an older action no longer acts after a reset, and a share sheet that fails at once now falls back to downloading the picture.diff --git a/docs/share-1653-manual-checks.md b/docs/share-1653-manual-checks.mdindex 138aa8834..124c31acc 100644--- a/docs/share-1653-manual-checks.md+++ b/docs/share-1653-manual-checks.md@@ -1,6 +1,6 @@# Share #1653: manual checks for F1–F5 and native delivery-No checks in this record have been executed. This is the manual route for jslib behavior; EditMode delegates do not execute either jslib or prove trusted activation. No JS runner or harness is added. Keep #1653 open until the owner/coordinator supplies the device evidence.+No checks in this record have been executed. This is the manual route for jslib behavior; EditMode delegates do not execute either jslib or prove trusted activation. `tools/tests/test_share_shot_jslib.py` (#1897) runs `ShareShot.jslib` in node against a stubbed page; it checks late clipboard callbacks and a synchronous share throw, and proves no real-browser activation or delivery. Keep #1653 open until the owner/coordinator supplies the device evidence.## Execution prerequisites and recorddiff --git a/tools/tests/test_share_shot_jslib.py b/tools/tests/test_share_shot_jslib.pynew file mode 100644index 000000000..c7e7c04e2--- /dev/null+++ b/tools/tests/test_share_shot_jslib.py@@ -0,0 +1,102 @@+"""ShareShot.jslib (#1897): the browser half of the Share and Copy buttons, run in node with a stubbed page.++The Unity tests only see the C# side (the jslib is swapped for hooks), so the two robustness rules live here:+a clipboard callback from an older action must not act after a reset, and a share() that throws at once still+downloads the picture."""+import json+import shutil+import subprocess+from pathlib import Path++import pytest++JSLIB = Path(__file__).resolve().parents[2] / "unity/Assets/Scripts/UI/ShareShot.jslib"+pytestmark = pytest.mark.skipif(shutil.which("node") is None, reason="needs node")++# Loads the jslib the way Emscripten does: mergeInto collects the library, and every "$name" entry becomes a global.+DRIVER = r"""+const fs = require("fs"), vm = require("vm");+const scenario = process.argv[3];+const handlers = {}, clicks = [];+const canvas = { addEventListener: (t, f) => { handlers[t] = f; }, removeEventListener: () => {} };+const file = { name: "shot.png" };+let resolveWrite, shareBehaviour = "ok";+const ctx = {+ console, setTimeout, clearTimeout, Promise, URL: { createObjectURL: () => "blob:x", revokeObjectURL() {} },+ HEAPU8: new Uint8Array(4), UTF8ToString: () => "post text",+ File: function (b, name) { return { name }; }, ClipboardItem: function () {},+ navigator: {+ canShare: () => true,+ share: () => {+ if (shareBehaviour === "throw") throw new Error("NotAllowedError");+ return Promise.resolve();+ },+ clipboard: { write: () => new Promise((r) => { resolveWrite = r; }) },+ },+ document: {+ querySelector: () => canvas, addEventListener() {}, removeEventListener() {}, body: { appendChild() {} },+ createElement: () => ({ click() { clicks.push(1); }, remove() {} }),+ },+};+ctx.window = ctx;+ctx.addEventListener = () => {}; ctx.removeEventListener = () => {};+ctx.mergeInto = (lib, entries) => { ctx.lib = entries; };+ctx.LibraryManager = { library: {} };+vm.createContext(ctx);+vm.runInContext(fs.readFileSync(process.argv[2], "utf8"), ctx);+for (const [k, v] of Object.entries(ctx.lib)) if (k[0] === "$") ctx[k.slice(1)] = v;+const L = ctx.lib;+const press = () => handlers.pointerup({ type: "pointerup" });+const tick = () => new Promise((r) => setTimeout(r, 0));+(async () => {+ ctx.statecraftShareFile = file;+ const out = {};+ if (scenario === "late-copy-after-reset" || scenario === "late-copy-after-new-action") {+ L.StatecraftShareCopyOnRelease();+ press(); // the write is now pending, owned by the first copy action+ if (scenario === "late-copy-after-reset") L.StatecraftShareInvalidate();+ else L.StatecraftShareOnRelease(); // a new main action+ resolveWrite();+ await tick();+ out.copied = L.StatecraftShareCopied();+ } else if (scenario === "copy-still-lands") {+ L.StatecraftShareCopyOnRelease();+ press(); resolveWrite(); await tick();+ out.copied = L.StatecraftShareCopied();+ } else if (scenario === "sync-throw") {+ shareBehaviour = "throw";+ L.StatecraftShareOnRelease();+ press(); await tick();+ out.failed = L.StatecraftShareFailed(); out.downloads = clicks.length;+ }+ console.log(JSON.stringify(out));+})().catch((e) => { console.log(JSON.stringify({ crash: String(e) })); });+"""++[email protected](scope="module")+def run(tmp_path_factory):+ driver = tmp_path_factory.mktemp("share") / "driver.js"+ driver.write_text(DRIVER)++ def go(scenario):+ done = subprocess.run(["node", str(driver), str(JSLIB), scenario], capture_output=True, text=True, timeout=30)+ assert done.returncode == 0, done.stderr+ return json.loads(done.stdout.strip().splitlines()[-1])+ return go+++def test_a_copy_that_lands_in_time_reports_the_picture(run):+ assert run("copy-still-lands") == {"copied": 1}+++def test_a_late_clipboard_callback_cannot_act_after_a_lifecycle_reset(run):+ assert run("late-copy-after-reset") == {"copied": 0}+++def test_a_late_clipboard_callback_cannot_act_after_a_new_main_action(run):+ assert run("late-copy-after-new-action") == {"copied": 0}+++def test_a_synchronous_throw_from_share_still_downloads_the_picture(run):+ assert run("sync-throw") == {"failed": True, "downloads": 1}diff --git a/unity/Assets/Scripts/UI/ShareShot.jslib b/unity/Assets/Scripts/UI/ShareShot.jslibindex ecb1b8948..dda4d764c 100644--- a/unity/Assets/Scripts/UI/ShareShot.jslib+++ b/unity/Assets/Scripts/UI/ShareShot.jslib@@ -16,6 +16,8 @@ mergeInto(LibraryManager.library, {if (window.statecraftReleaseArm) window.statecraftReleaseArm.cancel();window.statecraftShareAttempt = (window.statecraftShareAttempt || 0) + 1;window.statecraftShareFailed = false;+ // A late clipboard callback from an older action must not act after a reset or a new main action (#1897).+ window.statecraftShareCopySerial = (window.statecraftShareCopySerial || 0) + 1;},$StatecraftBeginReleaseArm__deps: ["$StatecraftInvalidateShareAttempt"],$StatecraftBeginReleaseArm: function () {@@ -88,8 +90,6 @@ mergeInto(LibraryManager.library, {StatecraftShareKeep__deps: ["$StatecraftInvalidateShareAttempt"],StatecraftShareKeep: function (pngPtr, length, namePtr) {StatecraftInvalidateShareAttempt();- // A late rejected write from an old panel must not download after a new capture replaced its picture.- window.statecraftShareCopySerial = (window.statecraftShareCopySerial || 0) + 1;window.statecraftShareCopied = 0;var bytes = HEAPU8.slice(pngPtr, pngPtr + length);window.statecraftShareFile = new File([bytes], UTF8ToString(namePtr), { type: "image/png" });@@ -144,7 +144,10 @@ mergeInto(LibraryManager.library, {if (!canShare) { download(file); return; }// A cancelled sheet (AbortError) is not a failure. Any other refusal (an iframe without web-share, a share target// that fails) downloads the picture instead, and StatecraftShareFailed tells the panel to show the share links.- navigator.share({ files: [file], text: text }).catch(function (e) {+ var shared;+ try { shared = navigator.share({ files: [file], text: text }); }+ catch (e) { shared = Promise.reject(e); } // a synchronous throw takes the same fallback as a rejection (#1897)+ shared.catch(function (e) {if (e && e.name === "AbortError") return;download(file); // download checks the captured token before either side effect});