A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Keep Share actions and release tickets current (Refs #1653) (#1905)
Eyal Golan24644898f407
diff --git a/changelog.d/1653-share-arm.md b/changelog.d/1653-share-arm.mdnew file mode 100644index 000000000..468729c47--- /dev/null+++ b/changelog.d/1653-share-arm.md@@ -0,0 +1 @@+- Keep screenshot sharing on the intended release, report delayed download fallback, and cancel superseded share actions.diff --git a/docs/share-1653-manual-checks.md b/docs/share-1653-manual-checks.mdnew file mode 100644index 000000000..138aa8834--- /dev/null+++ b/docs/share-1653-manual-checks.md@@ -0,0 +1,50 @@+# 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.++## Execution prerequisites and record++Coordinator supplies an approved post-fix WebGL build identifier and exact playable HTTPS URL for each top-level and itch iframe context. Neither an approved URL/build nor confirmed installed targets has been supplied for this change. The itch page is a candidate location, not an approved build. Confirm installed targets and an executor before running a cell. Use a distinctive game state A and a visibly different recaptured state B. Redact recipient identities in attachments.++For every case record: case ID, executor/time in UTC, build/URL/context, OS/browser/target versions, EN/HE, pointer/touch/hardware keyboard, event order and elapsed time, counts of sheets/download requests/saved files/site tabs, preview/file name/type/dimensions/bytes, note text, evidence path, and result (pass/fail/unverified/unavailable). A clicked download anchor is only a request; open the saved PNG. A resolved share promise or visible sheet is not recipient delivery. Optional passive debugging may observe capabilities, tickets, tokens and promise ordering; do not pause away activation or alter live permissions to fabricate a pass.++| Physical platform/browser | Native targets, separately | Contexts | Input |+|---|---|---|---|+| iPhone/iPad Safari | Apple Mail, Messages | approved top-level and itch embedded URLs/builds pending | touch; hardware Enter only if available |+| Android Chrome | Gmail, WhatsApp | same, pending | touch; hardware Enter only if available |+| macOS Chrome | Apple Mail, Messages if exposed | same, pending | mouse and physical Enter |+| macOS Safari | Apple Mail, Messages if exposed | same, pending | mouse and physical Enter |++All cells start unverified. Unsupported file sharing is fallback-only, unavailable targets remain unavailable, and mobile Enter remains unverified without a hardware keyboard. Expand each row into separate target/context/input/language records.++## Release eligibility and cancellation (F1/F5)++1. Open Settings → Share and wait for the preview. Use physical Enter down for 0.2–0.5 seconds, then Enter up on main Share; expect one current sheet or download. Repeat with pointer release and Instagram, then Copy. Repeat quick Enter and a hold longer than 1.5 seconds, recording actual ordering. The long hold may expire the arm; do not report it as ordinary Enter success.+2. Within the arm timeout, release Shift before Enter; Shift must do nothing and leave the arm available for Enter. Repeat Tab keyup without moving focus if physically obtainable. A real Tab focus switch is allowed to cancel the old ticket via focus-out; distinguish that from keyup filtering. Single-space and legacy `Spacebar` key values are accepted; the literal `Space` key value is ignored. If the device cannot produce a legacy/literal value, record that subcase unverified. Do not manufacture a JS event and call it trusted input.+3. Arm, press Escape **keydown**, then release Escape and Enter. Expect no old action. Repeat Close before release, focus-out before release, fresh canvas pointerdown, pointercancel if obtainable, window blur/resize/visibility change, and timeout. A subsequent release must not revive that ticket. For main Share/Copy this does not add ExternalLink's pointer rectangle/identity/button validation: main pointerup eligibility otherwise stays as before. Record drag-off separately; do not claim geometry parity. For main Share, Instagram and Copy, explicitly try pointer-arm → unrelated keyup (Shift) → pointerup: the keyup must leave the ticket armed and pointerup must act once. Then try keyboard-arm → pointerup: pointerup must act once because these arms are intentionally mode-less. Finally try eligible keyup → pointerup on the same ticket: the keyup consumes it, so pointerup must add zero actions. Keep each sequence within the timeout without intervening focus-out or a new arm; if physically unreachable, record it unverified.+4. Before 1.5 seconds expires, replace an armed main Share with each of X/Facebook/WhatsApp/Telegram/LinkedIn, then release Enter: only the current site's image-copy/download plus one site open, zero main action. Reverse the order. Repeat Instagram/site and Copy/site both directions, Share/Instagram both directions, Share/Copy, site/site, and same-control replacement. Every new arm must cancel the previous ticket. If the UI cannot produce an overlap sequence, mark it unverified/unreachable in that run; do not substitute an assumed deterministic result.+5. Where observable, deliver an old owner's focus-out/cancel/timeout after another control has armed. Only the old ticket may be cancelled; the current release must still work once. Close with a site ticket current, reopen without Send, and release: zero old actions. Dispose/rebuild the UI with an arm pending and repeat. Check for extra tabs/sheets/downloads and orphan listeners/timers through passive diagnostics if available. Include a non-share ExternalLink (for example Star) in replacement checks where physically reachable: it shares the same release slot.++## Failure reporting and attempt isolation (F2/F3/F4)++6. In a native-capable cell, obtain a real non-Abort refusal delayed beyond three seconds while the panel remains open. Expect exactly the current fallback note and one current-file download request. Repeat Instagram: only its note may appear. Current success/cancel remains silent; its Failed-only observer stays alive until failure, a new action, Close or Dispose. Cancel the sheet, wait at least five seconds, confirm no fallback, then retry. Record no-target Abort separately. If a delayed refusal cannot be obtained, leave it unverified.+7. Where capability legitimately changes from true at panel-open to false/missing/throwing at release, expect the current failure flag before the download request and then the fallback note. Use passive inspection if possible to establish flag/request ordering. Stable unsupported capability should immediately show the existing attach note and request a PNG on release. If the capability transition cannot be produced on an approved build, mark that transition unverified; do not edit host permissions or install a runner as part of this check.+8. Release share A and, only where its native promise actually remains pending, Close → recapture B → press/release B → observe non-Abort rejection A. There must be no A download, no A failure flag attributed to B and no A note. A current B refusal should request only File B and show only B's note. Repeat A rejection after B press but before B release; B resolves then A rejects; B aborts then A rejects. Repeat replacing A with Copy, Instagram and each site; Keep, Close and Dispose must invalidate A as well. If any A/B settlement ordering cannot be obtained, it remains **unverified**. No synthetic promise harness is included, and no deterministic substitute is claimed.+9. Native-sheet focus transfer after the normal release must not invalidate that same attempt: a current non-Abort refusal may still download its own file on return. Focus-out before release cancels only its still-armed ticket. Close/reopen without Send must not revive a poll or note. Switch Share → Instagram and reverse, then Copy and each site while a share result is pending: only the latest observer may report. Repeat UI disposal while the visual tree remains alive where an approved diagnostic build permits it; do not claim runtime coverage from EditMode alone.++## Owner's attachment and site acceptance checks++10. Preview A must depict the game state without the panel. Obtain a saved PNG using main “Download the picture” when shown, or the X button in the approved itch iframe where image copying is confirmed blocked. That route must both save the picture and open X from one release. If neither control is available, mark the saved-PNG control unavailable. Open the PNG and verify name, PNG type, dimensions, bytes and recognizable game content. Repeat opening from the turn report.+11. For every native target/context/input cell, share via main Share with the existing files-plus-text payload. Check that both the composer and the **received** message/post contain the recognizable screenshot, and record text/both links. Repeat physical Enter independently of pointer, cancellation/retry, EN/HE, landscape and a detailed/high-DPR scene exercising the 1920 cap. A target-specific dropped attachment remains an open issue even if F1–F5 checks pass.+12. For all five sites, verify copy → open → pasteable picture and the matching note when image copying is allowed. Where blocked, verify one saved PNG plus site open and the downloaded-picture note. Repeat pointer and physical Enter; Instagram follows the main share path and its own note. A site pass never substitutes for main Share delivery. For each site, explicitly repeat pointer-arm → unrelated keyup → primary pointerup inside its rectangle: keyup must retain the ticket, then pointerup performs one copy/download and one open. Try keyboard-arm → pointerup: pointerup must do nothing and leave the ticket available for an eligible keyup. After that eligible keyup consumes the ticket, a further pointerup must add zero actions. Unlike main's mode-less arms, ExternalLink restricts release to the arm's input mode. Separately probe a pointer arm dragged outside the site rectangle before primary release: zero copy/download/open, ticket consumed; a later release must not revive it. Probe non-primary pointerup (isPrimary false or button other than 0) while pointer-armed: zero actions, ticket retained for a primary release inside the rectangle. With a keyboard site arm, Shift keyup must retain the ticket for Enter; Escape keydown must cancel it so subsequent Enter/pointerup causes zero actions. Record counts and physically unavailable sequences honestly; do not introduce a synthetic JS runner.+13. If a target still drops the picture with a valid PNG, route environment/target evidence via the coordinator. Only a separately approved diagnostic may compare files+text with files-only on separate fresh gestures using the same File. No automatic retry, payload change, size limit or UA policy is part of this patch. The owner must decide any files-only tradeoff.++## Agreed fallback (owner ruling, 27 Oct 2026)++Current owner ruling for #1653, 27 Oct 2026, verbatim: "Ship C319 as is (Recommended)", recorded on #1653 ([comment of 2026-10-27T04:21Z](https://github.com/eyalgolan/statecraft-israel/issues/1653#issuecomment-6433680784)). The share keeps its files-plus-text payload for every target, as is. A picture-only fallback is approved only for a target shown to drop the picture when text is attached. This is evidence-driven: this PR makes no code change for it, and a picture-only route is added later only for a target where the step 13 evidence shows the drop. The device, browser and app of the original report are not known.++Earlier answer, 26 Oct 2026, verbatim: "Picture-only is OK". The 27 Oct ruling above is the one in force.++## Remaining gates++All runtime/device cases above are owed by the owner/coordinator; no saved-file, native-delivery, activation, permission or stale-promise result is claimed here. Record unavailable orderings honestly. Future deterministic JS coverage would need separately approved tooling/scope. Run full Unity EditMode and a WebGL build on the merged tree under the coordinator gate, then run this matrix against the approved resulting build. Attach matched game-state screenshots of the changed fallback notes and event evidence to the PR. Use “Refs #1653” until delivery acceptance is evidenced.diff --git a/unity/Assets/Scripts/UI/ExternalLink.jslib b/unity/Assets/Scripts/UI/ExternalLink.jslibindex 4d52cb467..437958006 100644--- a/unity/Assets/Scripts/UI/ExternalLink.jslib+++ b/unity/Assets/Scripts/UI/ExternalLink.jslib@@ -7,18 +7,17 @@// new canvas press, Escape, blur, resize or a hidden tab, and when Unity cancels its ticket (focus out, Dispose).mergeInto(LibraryManager.library, {StatecraftCancelExternalLink: function (ticket) {- if (typeof window !== "undefined" && window.statecraftOpenOnRelease && window.statecraftOpenOnRelease.id === ticket) window.statecraftOpenOnRelease.cancel();+ if (typeof window !== "undefined" && window.statecraftReleaseArm && window.statecraftReleaseArm.id === ticket) window.statecraftReleaseArm.cancel();},- StatecraftOpenOnRelease__deps: ["$StatecraftCopySharePicture"],+ StatecraftOpenOnRelease__deps: ["$StatecraftCopySharePicture", "$StatecraftBeginReleaseArm"],StatecraftOpenOnRelease: function (urlPtr, left, top, right, bottom, keyboard, copyPostPtr) {if (typeof window === "undefined") return 0;var url = UTF8ToString(urlPtr);var copyPost = copyPostPtr ? UTF8ToString(copyPostPtr) : "";var copySerial = 0;- if (window.statecraftOpenOnRelease) window.statecraftOpenOnRelease.cancel();+ var id = StatecraftBeginReleaseArm();var canvas = document.querySelector("#unity-canvas");if (!canvas) return 0;- var id = window.statecraftExternalLinkSerial = (window.statecraftExternalLinkSerial || 0) + 1;if (copyPost) {copySerial = window.statecraftShareCopySerial = (window.statecraftShareCopySerial || 0) + 1;window.statecraftShareCopied = 0;@@ -34,10 +33,11 @@ mergeInto(LibraryManager.library, {document.removeEventListener("visibilitychange", disarm);window.removeEventListener("blur", disarm);window.removeEventListener("resize", disarm);- if (window.statecraftOpenOnRelease && window.statecraftOpenOnRelease.id === id) window.statecraftOpenOnRelease = null;+ if (window.statecraftReleaseArm && window.statecraftReleaseArm.id === id) window.statecraftReleaseArm = null;};var escape = function (e) { if (e.key === "Escape") disarm(); };var release = function (e) {+ if (!window.statecraftReleaseArm || window.statecraftReleaseArm.id !== id) return;var valid = false;if (keyboard) {if (e.type !== "keyup" || (e.key !== "Enter" && e.key !== " " && e.key !== "Spacebar")) return;@@ -59,7 +59,7 @@ mergeInto(LibraryManager.library, {window.open(url, "_blank", "noopener");}};- window.statecraftOpenOnRelease = { cancel: disarm, id: id };+ window.statecraftReleaseArm = { cancel: disarm, id: id };canvas.addEventListener("pointerup", release);canvas.addEventListener("pointerdown", disarm);canvas.addEventListener("pointercancel", disarm);diff --git a/unity/Assets/Scripts/UI/SharePresenter.cs b/unity/Assets/Scripts/UI/SharePresenter.csindex 64d4f70d4..9630ded31 100644--- a/unity/Assets/Scripts/UI/SharePresenter.cs+++ b/unity/Assets/Scripts/UI/SharePresenter.cs@@ -39,26 +39,32 @@ namespace Statecraft.Game.UIreadonly EventCallback<PointerDownEvent> onCopyPointer;readonly EventCallback<NavigationSubmitEvent> onCopySubmit;readonly EventCallback<NavigationCancelEvent> onCancel;+ readonly EventCallback<FocusOutEvent> onGoBlur, onInstagramBlur, onCopyBlur;+ readonly Func<Action, IVisualElementScheduledItem> scheduleSharePoll;readonly List<Action> unbindSites = new List<Action>();readonly List<(VisualElement part, bool enabled)> covered = new List<(VisualElement, bool)>();Button? opener;/// <summary>The post as it is shared and copied (ShareShot.Text); the label shows ShareShot.Shown's form of it.</summary>string postText = "";UnityEngine.Texture2D? picture; // the preview's, released on Close- IVisualElementScheduledItem? copyPoll;+ IVisualElementScheduledItem? copyPoll, sharePoll;+ int generation, goTicket, instagramTicket, copyTicket;bool capturing, canShareFiles, disposed;int closedAt = -1;/// <param name="capture">Captures the frame at its end and hands over its PNG (GameRoot: ShareShot.Capture as a/// coroutine; a test hands over bytes at once).</param>- public SharePresenter(VisualElement root, SimBridge bridge, UiText text, Action<Action<byte[]?>> capture)+ public SharePresenter(VisualElement root, SimBridge bridge, UiText text, Action<Action<byte[]?>> capture,+ Func<Action, IVisualElementScheduledItem>? scheduleSharePoll = null){this.bridge = bridge; this.text = text; this.capture = capture;hudRoot = root.Q("root") ?? root;layer = root.Q("share-layer");fallback = layer.Q("share-fallback");preview = layer.Q("share-preview");- go = layer.Q<Button>("share-go"); close = layer.Q<Button>("share-close");+ go = layer.Q<Button>("share-go");+ this.scheduleSharePoll = scheduleSharePoll ?? (check => go.schedule.Execute(check));+ close = layer.Q<Button>("share-close");post = layer.Q<Label>("share-post");copy = layer.Q<Button>("share-copy"); copied = layer.Q<Label>("share-copied");copy.text = text["share.copy"];@@ -77,14 +83,20 @@ namespace Statecraft.Game.UIonGoSubmit = _ => Go();go.RegisterCallback(onGoPointer, TrickleDown.TrickleDown);go.RegisterCallback(onGoSubmit, TrickleDown.TrickleDown);- onInstagramPointer = e => { if (e.button == 0) Send(instagramNote); };- onInstagramSubmit = _ => Send(instagramNote);+ onInstagramPointer = e => { if (e.button == 0) InstagramShare(); };+ onInstagramSubmit = _ => InstagramShare();instagram.RegisterCallback(onInstagramPointer, TrickleDown.TrickleDown);instagram.RegisterCallback(onInstagramSubmit, TrickleDown.TrickleDown);onCopyPointer = e => { if (e.button == 0) Copy(); };onCopySubmit = _ => Copy();copy.RegisterCallback(onCopyPointer, TrickleDown.TrickleDown);copy.RegisterCallback(onCopySubmit, TrickleDown.TrickleDown);+ onGoBlur = _ => CancelTicket(ref goTicket);+ onInstagramBlur = _ => CancelTicket(ref instagramTicket);+ onCopyBlur = _ => CancelTicket(ref copyTicket);+ go.RegisterCallback(onGoBlur);+ instagram.RegisterCallback(onInstagramBlur);+ copy.RegisterCallback(onCopyBlur);settingsOpen.clicked += OpenFromSettings;reportOpen.clicked += OpenFromReport;close.clicked += Close;@@ -101,12 +113,15 @@ namespace Statecraft.Game.UI/// focus back on Close.</summary>public void Open(Button? from = null){- if (IsOpen || capturing) return;+ if (disposed || IsOpen || capturing) return;+ InvalidateAction();+ var opening = generation;capturing = true;capture(png =>{+ if (disposed || opening != generation) return;capturing = false;- if (png == null || disposed) return; // no picture (ShareShot.Capture logged why), or the UI was rebuilt meanwhile+ if (png == null) return; // no picture (ShareShot.Capture logged why)var shown = HudModel.From(bridge, text);ShareShot.Keep(png, ShareShot.FileName(bridge.State.Date));canShareFiles = ShareShot.CanShareFiles();@@ -119,7 +134,7 @@ namespace Statecraft.Game.UIShowPreview(png);foreach (var unbind in unbindSites) unbind();unbindSites.Clear();- foreach (var site in ShareShot.Sites.Where(s => s != Instagram)) unbindSites.Add(ExternalLink.Bind(layer.Q<Button>("share-" + site), ShareShot.IntentUrl(site, postText), postText, () => PollCopy(site: true)));+ foreach (var site in ShareShot.Sites.Where(s => s != Instagram)) unbindSites.Add(ExternalLink.Bind(layer.Q<Button>("share-" + site), ShareShot.IntentUrl(site, postText), postText, SiteActivated));opener = from;// Each part's own state comes back on Close. The panel takes every press meanwhile, so no screen opens or// closes under it; a resize may still run ScreenNav.DisableCovered, and Close then puts back the states from before.@@ -128,23 +143,68 @@ namespace Statecraft.Game.UIhudRoot.AddToClassList(OpenClass);go.Focus();// An element shown this frame may not take the focus yet (TurnReportPresenter does the same).- go.schedule.Execute(() => { if (IsOpen && layer.focusController?.focusedElement != go) go.Focus(); });+ go.schedule.Execute(() => { if (!disposed && opening == generation && IsOpen && layer.focusController?.focusedElement != go) go.Focus(); });});}/// <summary>Share: the browser's share sheet, or the download and then the note to attach the picture.</summary>- void Go() => Send(fallback);+ void Go() { if (Send(fallback)) goTicket = ShareShot.ArmTicket(); }+ void InstagramShare() { if (Send(instagramNote)) instagramTicket = ShareShot.ArmTicket(); }++ static void CancelTicket(ref int ticket)+ {+ if (ticket != 0) ShareShot.CancelArm(ticket);+ ticket = 0;+ }++ void StopObservers()+ {+ generation++;+ sharePoll?.Pause(); sharePoll = null;+ copyPoll?.Pause(); copyPoll = null;+ }++ void InvalidateAction()+ {+ StopObservers();+ ShareShot.Invalidate();+ goTicket = instagramTicket = copyTicket = 0;+ }++ void HideNotes()+ {+ fallback.style.display = instagramNote.style.display = copied.style.display = DisplayStyle.None;+ }++ void SiteActivated()+ {+ // ExternalLink has ALREADY installed its shared ticket and invalidated the JS attempt.+ // Only retire C# observers here: lifecycle invalidation here would cancel the new site arm.+ if (disposed || !IsOpen) return;+ StopObservers();+ HideNotes();+ PollCopy(site: true);+ }/// <summary>Share and Instagram: the share sheet where the browser can share files, else the download, and then/// <paramref name="note"/> says what to do with the downloaded picture.</summary>- void Send(VisualElement note)+ bool Send(VisualElement note){- if (!IsOpen) return;+ if (disposed || !IsOpen) return false;+ InvalidateAction();+ HideNotes();ShareShot.Share(postText);- if (!canShareFiles) { note.style.display = DisplayStyle.Flex; return; }- // The share sheet can still be refused on the release (ShareShot.jslib); then the picture downloads and the- // note shows, as where files cannot be shared. A refusal comes at once; a few seconds is enough to wait.- go.schedule.Execute(() => { if (IsOpen && ShareShot.Failed()) note.style.display = DisplayStyle.Flex; }).Every(250).ForDuration(3000);+ if (!canShareFiles) { note.style.display = DisplayStyle.Flex; return true; }+ var attempt = generation;+ sharePoll = scheduleSharePoll(() =>+ {+ if (disposed || !IsOpen || attempt != generation) return;+ if (!ShareShot.Failed()) return;+ note.style.display = DisplayStyle.Flex;+ StopObservers(); // also invalidate an already queued callback after this failure+ }).Every(250);+ // Failed exposes no success/cancel signal. Keep this one observer until failure, new action or panel teardown.+ return true;}/// <summary>The preview: the PNG that is shared, decoded into a texture of its own (none if it does not decode).</summary>@@ -175,8 +235,11 @@ namespace Statecraft.Game.UI/// for the answer as it looks for a refused share sheet, and then says what was copied, or that nothing was.</summary>void Copy(){- if (!IsOpen) return;+ if (disposed || !IsOpen) return;+ InvalidateAction();+ HideNotes();ShareShot.Copy(postText);+ copyTicket = ShareShot.ArmTicket();PollCopy(site: false);}@@ -186,9 +249,11 @@ namespace Statecraft.Game.UIcopied.style.display = DisplayStyle.None;// A press whose release never reached the browser (shorter than a frame, or another press first) copies// nothing and stays Pending: after a few seconds the panel says so rather than staying silent.+ var attempt = generation;var giveUpAt = UnityEngine.Time.realtimeSinceStartup + 4.5f;copyPoll = copy.schedule.Execute(() =>{+ if (disposed || !IsOpen || attempt != generation) return;var result = ShareShot.Copied();if (!site && result == ShareShot.CopyResult.Pending && UnityEngine.Time.realtimeSinceStartup >= giveUpAt) result = ShareShot.CopyResult.Failed;if (!IsOpen || result == ShareShot.CopyResult.Pending) return;@@ -214,8 +279,10 @@ namespace Statecraft.Game.UIpublic void Close(){+ if (disposed) return;+ InvalidateAction();+ capturing = false;if (!IsOpen) return;- copyPoll?.Pause();foreach (var unbind in unbindSites) unbind();unbindSites.Clear();closedAt = UnityEngine.Time.frameCount;@@ -238,9 +305,13 @@ namespace Statecraft.Game.UIpublic void Dispose(){- disposed = true;+ if (disposed) return;Close();+ disposed = true;foreach (var unbind in unbindSites) unbind();+ go.UnregisterCallback(onGoBlur);+ instagram.UnregisterCallback(onInstagramBlur);+ copy.UnregisterCallback(onCopyBlur);go.UnregisterCallback(onGoPointer, TrickleDown.TrickleDown);go.UnregisterCallback(onGoSubmit, TrickleDown.TrickleDown);instagram.UnregisterCallback(onInstagramPointer, TrickleDown.TrickleDown);diff --git a/unity/Assets/Scripts/UI/ShareShot.cs b/unity/Assets/Scripts/UI/ShareShot.csindex f60eaa561..249af9701 100644--- a/unity/Assets/Scripts/UI/ShareShot.cs+++ b/unity/Assets/Scripts/UI/ShareShot.cs@@ -37,6 +37,12 @@ namespace Statecraft.Game.UI/// <summary>Copies the kept picture on the player's release, or the post text if the browser refuses the picture.</summary>public static Action<string> Copy = DefaultCopy;public static Func<CopyResult> Copied = DefaultCopied;+ /// <summary>Cancel the current release arm and invalidate pending native-share results on lifecycle/new action.</summary>+ public static Action Invalidate = DefaultInvalidate;+ /// <summary>The current shared release ticket, captured immediately after arming a main control.</summary>+ public static Func<int> ArmTicket = DefaultArmTicket;+ /// <summary>Cancel only this still-armed ticket; focus-out after release must preserve the pending native result.</summary>+ public static Action<int> CancelArm = DefaultCancelArm;/// <summary>The post, in the UI's language, with the in-game date and turn, the itch URL and the repository's.</summary>public static string Text(UiText text, string date, int turn) => text.Format("share.post", date, turn, Itch, Repo);@@ -122,6 +128,12 @@ namespace Statecraft.Game.UI}#if UNITY_WEBGL && !UNITY_EDITOR+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern void StatecraftShareInvalidate();+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern int StatecraftShareArmTicket();+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern void StatecraftShareCancelArm(int ticket);+ public static void DefaultInvalidate() => StatecraftShareInvalidate();+ public static int DefaultArmTicket() => StatecraftShareArmTicket();+ public static void DefaultCancelArm(int ticket) => StatecraftShareCancelArm(ticket);[System.Runtime.InteropServices.DllImport("__Internal")] static extern void StatecraftShareKeep(byte[] png, int length, string name);[System.Runtime.InteropServices.DllImport("__Internal")] static extern int StatecraftShareCanShareFiles();[System.Runtime.InteropServices.DllImport("__Internal")] static extern void StatecraftShareOnRelease(string text);@@ -135,6 +147,9 @@ namespace Statecraft.Game.UIpublic static void DefaultCopy(string text) => StatecraftShareCopyOnRelease(text);public static CopyResult DefaultCopied() => (CopyResult)StatecraftShareCopied();#else+ public static void DefaultInvalidate() { }+ public static int DefaultArmTicket() => 0;+ public static void DefaultCancelArm(int ticket) { }static byte[]? kept; static string keptName = "";public static void DefaultKeep(byte[] png, string name) { kept = png; keptName = name; }/// <summary>The editor and desktop builds have no share sheet: the fallback, as in Firefox.</summary>diff --git a/unity/Assets/Scripts/UI/ShareShot.jslib b/unity/Assets/Scripts/UI/ShareShot.jslibindex cb53d838b..ecb1b8948 100644--- a/unity/Assets/Scripts/UI/ShareShot.jslib+++ b/unity/Assets/Scripts/UI/ShareShot.jslib@@ -11,6 +11,23 @@// clipboard-write) it copies the post text instead, then through a hidden textarea (execCommand), which some iframes// still allow. StatecraftShareCopied tells the panel which one landed: 1 the picture, 2 the text, 3 neither, 0 not yet.mergeInto(LibraryManager.library, {+ // One release owner across Share, Instagram, Copy and every ExternalLink. IDs also protect late focus/timeout callbacks.+ $StatecraftInvalidateShareAttempt: function () {+ if (window.statecraftReleaseArm) window.statecraftReleaseArm.cancel();+ window.statecraftShareAttempt = (window.statecraftShareAttempt || 0) + 1;+ window.statecraftShareFailed = false;+ },+ $StatecraftBeginReleaseArm__deps: ["$StatecraftInvalidateShareAttempt"],+ $StatecraftBeginReleaseArm: function () {+ StatecraftInvalidateShareAttempt(); // cancel the previous ticket BEFORE installing its replacement+ return window.statecraftReleaseSerial = (window.statecraftReleaseSerial || 0) + 1;+ },+ StatecraftShareInvalidate__deps: ["$StatecraftInvalidateShareAttempt"],+ StatecraftShareInvalidate: function () { StatecraftInvalidateShareAttempt(); },+ StatecraftShareArmTicket: function () { return window.statecraftReleaseArm ? window.statecraftReleaseArm.id : 0; },+ StatecraftShareCancelArm: function (ticket) {+ if (window.statecraftReleaseArm && window.statecraftReleaseArm.id === ticket) window.statecraftReleaseArm.cancel();+ },// Shared by Copy and copy-then-open. Kept PNG means clipboard.write starts in this very release event.$StatecraftCopySharePicture: function (text, serial, site) {var done = function (result) { if (serial === window.statecraftShareCopySerial) window.statecraftShareCopied = result; };@@ -68,7 +85,9 @@ mergeInto(LibraryManager.library, {catch (e) { copyText(); }},+ 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;@@ -80,20 +99,30 @@ mergeInto(LibraryManager.library, {try { return file && navigator.canShare && navigator.canShare({ files: [file] }) ? 1 : 0; } catch (e) { return 0; }},StatecraftShareFailed: function () { return window.statecraftShareFailed ? 1 : 0; },+ StatecraftShareOnRelease__deps: ["$StatecraftBeginReleaseArm"],StatecraftShareOnRelease: function (textPtr) {var text = UTF8ToString(textPtr); // both links are already in the post; no separate URL (#1653)if (typeof window === "undefined") return;- if (window.statecraftShareDisarm) window.statecraftShareDisarm();+ var id = StatecraftBeginReleaseArm();var canvas = document.querySelector("#unity-canvas") || document;var timer;var disarm = function () {clearTimeout(timer);canvas.removeEventListener("pointerup", go);canvas.removeEventListener("pointerdown", disarm);+ canvas.removeEventListener("pointercancel", disarm);document.removeEventListener("keyup", go);- window.statecraftShareDisarm = null;+ document.removeEventListener("keydown", escape);+ document.removeEventListener("visibilitychange", disarm);+ window.removeEventListener("blur", disarm);+ window.removeEventListener("resize", disarm);+ if (window.statecraftReleaseArm && window.statecraftReleaseArm.id === id) window.statecraftReleaseArm = null;};+ var attempt = window.statecraftShareAttempt;+ var escape = function (e) { if (e.key === "Escape") disarm(); };var download = function (file) {+ if (attempt !== window.statecraftShareAttempt) return;+ window.statecraftShareFailed = true; // publish BEFORE requesting the fallback, including canShare falsevar link = document.createElement("a");link.href = URL.createObjectURL(file);link.download = file.name;@@ -102,8 +131,12 @@ mergeInto(LibraryManager.library, {link.remove();setTimeout(function () { URL.revokeObjectURL(link.href); }, 10000);};- var go = function () {- disarm();+ var go = function (e) {+ if (e.type === "keyup") {+ if (e.key !== "Enter" && e.key !== " " && e.key !== "Spacebar") return;+ }+ if (!window.statecraftReleaseArm || window.statecraftReleaseArm.id !== id) return;+ disarm(); // consume only the release ticket; the native result still owns its attempt tokenvar file = window.statecraftShareFile;if (!file) return;var canShare = false;@@ -113,8 +146,7 @@ mergeInto(LibraryManager.library, {// 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) {if (e && e.name === "AbortError") return;- window.statecraftShareFailed = true;- download(file);+ download(file); // download checks the captured token before either side effect});};// Reset here, not on the release: the panel asks StatecraftShareFailed after this press, and after an earlier@@ -122,33 +154,55 @@ mergeInto(LibraryManager.library, {window.statecraftShareFailed = false;canvas.addEventListener("pointerup", go);canvas.addEventListener("pointerdown", disarm);+ canvas.addEventListener("pointercancel", disarm);document.addEventListener("keyup", go);- window.statecraftShareDisarm = disarm;+ document.addEventListener("keydown", escape);+ document.addEventListener("visibilitychange", disarm);+ window.addEventListener("blur", disarm);+ window.addEventListener("resize", disarm);+ window.statecraftReleaseArm = { id: id, cancel: disarm };timer = setTimeout(disarm, 1500);},StatecraftShareCopied: function () { return window.statecraftShareCopied || 0; },- StatecraftShareCopyOnRelease__deps: ["$StatecraftCopySharePicture"],+ StatecraftShareCopyOnRelease__deps: ["$StatecraftCopySharePicture", "$StatecraftBeginReleaseArm"],StatecraftShareCopyOnRelease: function (textPtr) {var text = UTF8ToString(textPtr);if (typeof window === "undefined") return;- if (window.statecraftShareDisarm) window.statecraftShareDisarm();+ var id = StatecraftBeginReleaseArm();var canvas = document.querySelector("#unity-canvas") || document;var timer;var disarm = function () {clearTimeout(timer);canvas.removeEventListener("pointerup", go);canvas.removeEventListener("pointerdown", disarm);+ canvas.removeEventListener("pointercancel", disarm);document.removeEventListener("keyup", go);- window.statecraftShareDisarm = null;+ document.removeEventListener("keydown", escape);+ document.removeEventListener("visibilitychange", disarm);+ window.removeEventListener("blur", disarm);+ window.removeEventListener("resize", disarm);+ if (window.statecraftReleaseArm && window.statecraftReleaseArm.id === id) window.statecraftReleaseArm = null;};var serial = window.statecraftShareCopySerial = (window.statecraftShareCopySerial || 0) + 1;- var go = function () { disarm(); StatecraftCopySharePicture(text, serial); };+ var escape = function (e) { if (e.key === "Escape") disarm(); };+ var go = function (e) {+ if (e.type === "keyup") {+ if (e.key !== "Enter" && e.key !== " " && e.key !== "Spacebar") return;+ }+ if (!window.statecraftReleaseArm || window.statecraftReleaseArm.id !== id) return;+ disarm(); StatecraftCopySharePicture(text, serial);+ };// Reset on the press, as statecraftShareFailed is: the panel starts asking right after it.window.statecraftShareCopied = 0;canvas.addEventListener("pointerup", go);canvas.addEventListener("pointerdown", disarm);+ canvas.addEventListener("pointercancel", disarm);document.addEventListener("keyup", go);- window.statecraftShareDisarm = disarm;+ document.addEventListener("keydown", escape);+ document.addEventListener("visibilitychange", disarm);+ window.addEventListener("blur", disarm);+ window.addEventListener("resize", disarm);+ window.statecraftReleaseArm = { id: id, cancel: disarm };timer = setTimeout(disarm, 1500);},});diff --git a/unity/Assets/Tests/EditMode/ShareShotTests.cs b/unity/Assets/Tests/EditMode/ShareShotTests.csindex af30e5a80..aba1d1e34 100644--- a/unity/Assets/Tests/EditMode/ShareShotTests.cs+++ b/unity/Assets/Tests/EditMode/ShareShotTests.cs@@ -512,4 +512,177 @@ public class ShareShotTests}}+ // #1653: C# lifetime/bridge regressions only. No DOM, native sheet or promise is exercised here.+ sealed class ShareAttemptUi : IDisposable+ {+ public readonly UiTestKit Ui = new UiTestKit();+ public readonly List<Action> Checks = new List<Action>();+ public readonly List<IVisualElementScheduledItem> Polls = new List<IVisualElementScheduledItem>();+ public readonly List<int> Cancelled = new List<int>();+ public readonly List<string> Calls = new List<string>();+ public readonly SharePresenter Presenter;+ public bool Failed;+ public int Reads, Ticket;+ readonly Action<byte[], string> keep = ShareShot.Keep;+ readonly Func<bool> can = ShareShot.CanShareFiles, failed = ShareShot.Failed;+ readonly Action<string> share = ShareShot.Share, copy = ShareShot.Copy, open = ExternalLink.Opener;+ readonly Action invalidate = ShareShot.Invalidate;+ readonly Func<int> armTicket = ShareShot.ArmTicket;+ readonly Action<int> cancelArm = ShareShot.CancelArm;+ readonly Func<ShareShot.CopyResult> copied = ShareShot.Copied;++ public ShareAttemptUi()+ {+ SharePresenter? presenter = null;+ try+ {+ ShareShot.Invalidate = () => Calls.Add("invalidate");+ ShareShot.ArmTicket = () => Ticket;+ ShareShot.CancelArm = Cancelled.Add;+ ShareShot.Keep = (_, __) => Calls.Add("keep");+ ShareShot.CanShareFiles = () => true;+ ShareShot.Share = _ => { Calls.Add("share"); Ticket++; Failed = false; };+ ShareShot.Copy = _ => { Calls.Add("copy"); Ticket++; };+ ShareShot.Copied = () => ShareShot.CopyResult.Pending;+ ShareShot.Failed = () => { Reads++; return Failed; };+ ExternalLink.Opener = _ => Calls.Add("open");+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);+ presenter = new SharePresenter(Ui.Root, bridge, En, done => done(new byte[] { 1 }), check =>+ {+ Checks.Add(check);+ var poll = Ui.Q<Button>("share-go").schedule.Execute(check);+ Polls.Add(poll);+ return poll;+ });+ Presenter = presenter;+ Presenter.Open();+ }+ catch+ {+ Cleanup(presenter);+ throw;+ }+ }++ public void Press(string name) => UiTestKit.Press(Ui.Q<Button>("share-" + name));+ public DisplayStyle Note(string name) => Ui.Q<VisualElement>(name).style.display.value;+ public void Dispose() => Cleanup(Presenter);+ void Cleanup(SharePresenter? presenter)+ {+ try+ {+ if (presenter != null) presenter.Dispose();+ }+ finally+ {+ try { Ui.Dispose(); }+ finally+ {+ ShareShot.Keep = keep; ShareShot.CanShareFiles = can; ShareShot.Failed = failed;+ ShareShot.Share = share; ShareShot.Copy = copy; ShareShot.Copied = copied; ExternalLink.Opener = open;+ ShareShot.Invalidate = invalidate; ShareShot.ArmTicket = armTicket; ShareShot.CancelArm = cancelArm;+ }+ }+ }+ }++ [UnityEngine.TestTools.UnityTest]+ public System.Collections.IEnumerator MainShareStillObservesFailureAfterThreeSeconds()+ {+ using var attempt = new ShareAttemptUi();+ attempt.Press("go");+ var until = Time.realtimeSinceStartup + 3.6f;+ while (Time.realtimeSinceStartup < until) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }+ Assert.AreEqual(DisplayStyle.None, attempt.Note("share-fallback"), "false Failed stays silent");+ Assert.IsTrue(attempt.Polls.Single().isActive, "success/cancel cannot be distinguished by Failed alone");+ attempt.Failed = true;+ until = Time.realtimeSinceStartup + 2f;+ while (attempt.Note("share-fallback") != DisplayStyle.Flex && Time.realtimeSinceStartup < until)+ { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }+ Assert.AreEqual(DisplayStyle.Flex, attempt.Note("share-fallback"));+ Assert.IsFalse(attempt.Polls.Single().isActive, "failure stops the owned poll");+ var reads = attempt.Reads;+ attempt.Checks.Single()();+ Assert.AreEqual(reads, attempt.Reads, "even a queued callback after failure is inert");+ }++ [Test]+ public void OldShareObserverCannotSurviveCloseReopenOrDispose()+ {+ using var attempt = new ShareAttemptUi();+ attempt.Press("go");+ var old = attempt.Checks.Single();+ attempt.Presenter.Close();+ Assert.IsFalse(attempt.Polls.Single().isActive);+ attempt.Presenter.Open(); // deliberately no new Send+ attempt.Failed = true;+ var reads = attempt.Reads;+ old();+ Assert.AreEqual(reads, attempt.Reads);+ Assert.AreEqual(DisplayStyle.None, attempt.Note("share-fallback"));+ attempt.Press("instagram");+ var current = attempt.Checks.Last();+ attempt.Presenter.Dispose();+ reads = attempt.Reads;+ current(); old();+ Assert.AreEqual(reads, attempt.Reads, "disposed callbacks must not even read the bridge");+ Assert.IsTrue(attempt.Polls.All(p => !p.isActive));+ var calls = attempt.Calls.Count;+ attempt.Press("go"); attempt.Press("instagram"); attempt.Press("copy");+ attempt.Presenter.Open(); attempt.Presenter.Close(); attempt.Presenter.Dispose();+ Assert.AreEqual(calls, attempt.Calls.Count, "disposal unbinds the controls, and Open, Close and a second Dispose are inert");+ }++ [Test]+ public void EveryNewActionInvalidatesTheOldObserver(+ [Values("go", "instagram")] string first,+ [Values("go", "instagram", "copy", "x", "facebook", "whatsapp", "telegram", "linkedin")] string next)+ {+ using var attempt = new ShareAttemptUi();+ attempt.Press(first);+ var old = attempt.Checks.Single();+ attempt.Press(next);+ Assert.IsFalse(attempt.Polls.First().isActive);+ attempt.Failed = true;+ var reads = attempt.Reads;+ old(); // model a callback already queued before Pause+ Assert.AreEqual(reads, attempt.Reads, "generation must reject it before querying Failed");+ Assert.AreEqual(DisplayStyle.None, attempt.Note("share-fallback"));+ Assert.AreEqual(DisplayStyle.None, attempt.Note("share-instagram-note"));+ if (next == "go" || next == "instagram")+ {+ attempt.Checks.Last()();+ Assert.AreEqual(DisplayStyle.Flex, attempt.Note(next == "go" ? "share-fallback" : "share-instagram-note"));+ Assert.AreEqual(DisplayStyle.None, attempt.Note(next == "go" ? "share-instagram-note" : "share-fallback"));+ }+ }++ /// <summary>The C# half only: focus-out hands JS the ticket this control stored, not the current one. That JS cancels+ /// nothing but a still-armed matching ticket (StatecraftShareCancelArm) is outside what this fake can check; it is in+ /// the manual record (docs/share-1653-manual-checks.md, step 5).</summary>+ [Test]+ public void LifecycleInvalidatesBeforeKeepAndActionsAndFocusOutPassesItsOwnTicket(+ [Values("go", "instagram", "copy")] string control)+ {+ using var attempt = new ShareAttemptUi();+ CollectionAssert.AreEqual(new[] { "invalidate", "keep" }, attempt.Calls);+ attempt.Calls.Clear();+ attempt.Press(control);+ CollectionAssert.AreEqual(new[] { "invalidate", control == "copy" ? "copy" : "share" }, attempt.Calls);+ var owner = attempt.Ticket;+ attempt.Ticket++; // a newer browser ticket can now belong to a site+ var count = attempt.Calls.Count;+ var button = attempt.Ui.Q<Button>("share-" + control);+ button.Focus(); button.Blur();+ CollectionAssert.AreEqual(new[] { owner }, attempt.Cancelled, "focus-out passes the stored ticket, not the newer one");+ Assert.AreEqual(count, attempt.Calls.Count, "focus-out must not invalidate a released native promise");+ attempt.Presenter.Close();+ Assert.AreEqual("invalidate", attempt.Calls.Last());+ attempt.Calls.Clear();+ attempt.Presenter.Open();+ CollectionAssert.AreEqual(new[] { "invalidate", "keep" }, attempt.Calls);+ attempt.Presenter.Dispose();+ Assert.AreEqual("invalidate", attempt.Calls.Last());+ }+}