A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
WebGL companion: never throw into the player, one live region, End Turn report (Refs #1119) (#1920)
Eyal Golan49b5a0712c82
diff --git a/changelog.d/1119-companion.md b/changelog.d/1119-companion.mdnew file mode 100644index 000000000..43272da26--- /dev/null+++ b/changelog.d/1119-companion.md@@ -0,0 +1 @@+- Add a read-only WebGL companion beside the game for the current event, choices, game focus, status and the End Turn report. It is off by default (the owner's ruling of 1 November 2026, "Opt-in for now (Recommended)"): turn it on with Settings > Screen reader companion, or open the game with `?companion=1`. Keyboard play stays in the game; real screen-reader validation and the phone layout remain pending.diff --git a/docs/accessibility-audit-2026-10-14.md b/docs/accessibility-audit-2026-10-14.mdindex 066d03cf7..0edced650 100644--- a/docs/accessibility-audit-2026-10-14.md+++ b/docs/accessibility-audit-2026-10-14.md@@ -504,6 +504,29 @@ leaves the focus on the last stop instead of dropping it; and a drawn scope stilfirst control, asserted on `minimap-overview` so the fallback cannot satisfy the test). No UIstring was added, so nothing goes to #564.+## The WebGL companion is opt-in, 1 November 2026++The first step proposed under H5 is the read-only WebGL companion (#1119, PR #1920): an HTML panel beside the canvas+(`WebGLTemplates/Statecraft/index.html`, `WebCompanion.jslib`) that mirrors the open event, its choices, the game's focus,+the status line and the End Turn report, with the status line as its one live region.++The owner's ruling, 1 November 2026, on whether every WebGL player gets the panel: "Opt-in for now (Recommended)". It+holds until the VoiceOver test on a real screen reader and the phone layout are done. So the companion is off by default+and turns on in one of two ways:++- the Settings row "Screen reader companion" (`settings.companion`), which shows only in the WebGL player; it applies at+ once, is kept with the other settings, and once pressed it wins over the address for the rest of that page's visit;+- `?companion=1` in the page address, a whole query parameter with the whole value `1` (`?companion=0`, `?companion`+ and `?companion=10` do not turn it on). The owner's ruling, 2 November 2026: "Link wins, that visit (Recommended)".+ The address turns the companion on for that visit even over a stored "off", and the saved choice is not changed.++`WebCompanion.On` holds the rule. `WebCompanionTests` pins it, the Settings row and the real root (off at start, on and+off from Settings, kept for a later game; the address over a stored "off" for that visit only). The page carries the panel's skeleton from load, `hidden`, so with the+companion off there is no empty landmark or heading in the accessibility tree. The first snapshot shows the panel and+writes its status line in a later task, so the live region is in the tree before its first announcement; a repeated+status on a new turn is also cleared and written again in a later task. Whether VoiceOver announces both is part of the+pending VoiceOver test.+## ScreenshotsIn `.superpowers/a11y-2026-10-14/` (1568x752 unless noted), with the driver and the contrast, colour-vision anddiff --git a/tools/tests/test_webgl_companion.py b/tools/tests/test_webgl_companion.pynew file mode 100644index 000000000..eb70e4168--- /dev/null+++ b/tools/tests/test_webgl_companion.py@@ -0,0 +1,353 @@+"""Read-only companion transport and cached-page regressions. Not a browser/VoiceOver gate."""+import json+import re+import shutil+import subprocess+from html.parser import HTMLParser+from pathlib import Path++import pytest+import test_webgl_stale_page as stale++ROOT = Path(__file__).resolve().parents[2]+PLUGIN = ROOT / 'unity/Assets/Scripts/UI/WebCompanion.jslib'+CAPTURE = ROOT / 'unity/Assets/Scripts/UI/WebCompanion.cs'++DRIVER = r'''+const assert = require('assert');+let writes = 0;+const elements = {};+class Element {+ constructor(tag) { this.tag = tag; this.children = []; this.value = ''; this.hidden = false; this.attributes = {}; this.sets = 0; }+ set id(value) { this._id = value; elements[value] = this; }+ get id() { return this._id; }+ set textContent(value) { writes++; this.sets++; this.value = value; this.children = []; }+ get textContent() { return this.value; }+ appendChild(child) { this.children.push(child); child.parentNode = this; }+ setAttribute(key, value) { this.attributes[key] = value; if (key === 'hidden') this.hidden = true; }+}+const classes = new Set();+let createLimit = Infinity;+const document = {+ getElementById(id) { return elements[id] || null; },+ createElement(tag) {+ if (createLimit-- <= 0) throw new Error('createElement unavailable');+ assert(['style','aside','h2','p','section','h3','div','ol','li'].includes(tag)); return new Element(tag);+ },+ head: new Element('head'), body: new Element('body')+};+document.body.classList = { toggle(name, on) { assert.equal(name, 'has-companion'); if(on) classes.add(name); else classes.delete(name); } };+document.activeElement = document.body;+const canvas = new Element('canvas'); canvas.id = 'unity-canvas';+const window = {};+const LibraryManager = {library: {}};+function mergeInto(target, values) { Object.assign(target, values); }+let outbound;+function UTF8ToString(pointer) { assert.equal(pointer, 42); return outbound; }+const live = () => Object.values(elements).filter(e => e.attributes['aria-live'] || e.attributes.role === 'status');+const call = () => assert.doesNotThrow(() => LibraryManager.library.StatecraftCompanion(42), 'the bridge must never throw into Unity');+// Fake timers: a deferred status write runs only when a test flushes, so a test sees the task it lands in.+const timers = [];+function setTimeout(run, ms) { timers.push(run); return timers.length; }+function clearTimeout(id) { if (id >= 1) timers[id - 1] = null; }+const pendingTimers = () => timers.filter(Boolean).length;+const flush = () => { for (let i = 0; i < timers.length; i++) { const run = timers[i]; timers[i] = null; if (run) run(); } };+'''+++def run(script):+ assert shutil.which('node'), 'node is required: zero executed transport cases is not a pass'+ result = subprocess.run(['node', '-e', script], capture_output=True, text=True)+ assert result.returncode == 0, result.stderr+ return result.stdout+++def payload():+ return dict(lang='he', turn=1, heading='מלווה', help='Read only', focusHeading='Focus', statusHeading='Status',+ choicesHeading='Choices', empty='No decision waiting', unavailable='Unavailable',+ title='<img src=x onerror="bad()"> & שלום', body=['Line one\nLine two', '<script>bad()</script>'],+ choices=[dict(text='First', available=True, note='Returns to the recorded course.'),+ dict(text='Second', available=False, note='')], focus='מפה', status='Not done: reason',+ reportTitle='', report=[])+++class _Skeleton(HTMLParser):+ """The companion elements of the stock page, in document order: (tag, id, parent id, attributes)."""++ def __init__(self):+ super().__init__()+ self.found, self.stack = [], []++ def handle_starttag(self, tag, attrs):+ attrs = dict(attrs)+ inside = bool(self.stack) or attrs.get('id') == 'companion'+ if inside:+ self.found.append((tag, attrs.get('id'), self.stack[-1] if self.stack else None, attrs))+ self.stack.append(attrs.get('id'))++ def handle_endtag(self, tag):+ if self.stack:+ self.stack.pop()+++def skeleton():+ parser = _Skeleton()+ parser.feed(stale.page())+ return parser.found+++def bootstrapped(extra=''):+ """The plugin bootstrapped on a cached stock page (no skeleton) with the standard payload."""+ return DRIVER + PLUGIN.read_text() + '\nconst payload = ' + json.dumps(payload()) + ';\n' + r'''+outbound = JSON.stringify(payload); call(); flush();+assert.equal(elements['companion-title'].textContent, payload.title);+''' + extra+++def test_cached_stock_page_receives_the_bridge_dom_and_literal_payload():+ # Execute the real current stock page's supported cached-HTML URL refresh before loading the new player's plugin.+ page = re.sub(r'\{\{\{ JSON\.stringify\((\w+)\) \}\}\}', r'"\1"', stale.rendered())+ # The page's inline script: from its first <script> to its last </script> (our own template, not a filter).+ script = page[page.index('<script>') + len('<script>'):page.rindex('</script>')].split('fetch(location.href')[0]+ current = page.replace('aaaa', '1111').replace('bbbb', '2222')+ code = DRIVER + script + '\nuseCurrentPage(' + json.dumps(current) + ');\n'+ code += "assert.equal(loaderUrl, 'Build/1111.loader.js'); assert.equal(config.dataUrl, 'Build/2222.data');\n"+ code += "assert.equal(typeof window.statecraftCompanion, 'undefined');\n" + PLUGIN.read_text()+ code += '\nconst payload = ' + json.dumps(payload()) + ';\n'+ code += r'''+outbound = JSON.stringify(payload);+const focused = document.activeElement;+call();+assert.equal(document.activeElement, focused, 'a push never moves focus');+assert.equal(elements['companion'].hidden, false, 'a snapshot shows the panel');+assert.equal(elements['companion-status'].textContent, '', 'the first status waits for a later task, so the region is in the tree first');+flush();+assert.equal(elements['companion'].attributes['aria-labelledby'], 'companion-heading');+// Condition 4: only the status/result line is live; the card and the focus line are read on demand.+assert.deepEqual(live().map(e => e.id), ['companion-status']);+assert.equal(elements['companion-status'].attributes.role, 'status');+assert.equal(elements['companion-event'].attributes['aria-live'], undefined);+assert.equal(elements['companion-focus'].attributes['aria-live'], undefined);+// The owner's narrow exception: tabindex=-1 on the scroll container only, so it never becomes an implicit Tab stop.+assert.deepEqual(Object.values(elements).filter(e => 'tabindex' in e.attributes).map(e => [e.id, e.attributes.tabindex]), [['companion', '-1']]);+assert.equal(elements['companion'].lang, 'he');+assert(classes.has('has-companion'));+assert.equal(elements['companion-title'].textContent, payload.title);+assert.deepEqual(elements['companion-body'].children.map(x => x.textContent), payload.body);+assert.deepEqual(elements['companion-choices'].children.map(x => x.textContent), ['First\nReturns to the recorded course.', 'Second: Unavailable']);+assert.equal(elements['companion-focus'].textContent, 'מפה');+assert.equal(elements['companion-status'].textContent, 'Not done: reason');+assert.equal(elements['companion-report'].hidden, true);+assert.equal(document.head.children.length, 1);+const paragraphs = elements['companion-body'].children.slice();+const choices = elements['companion-choices'].children.slice();+const count = writes;+call();+assert.equal(writes, count, 'unchanged snapshots must not re-announce');+payload.focus = 'Second'; payload.status = '';+outbound = JSON.stringify(payload); call();+// The same nodes, not equal copies: a rebuilt list would move a screen reader's virtual cursor.+assert.equal(elements['companion-body'].children.length, paragraphs.length);+paragraphs.forEach((p, i) => assert.strictEqual(elements['companion-body'].children[i], p, 'body paragraphs are not rebuilt'));+assert.equal(elements['companion-choices'].children.length, choices.length);+choices.forEach((c, i) => assert.strictEqual(elements['companion-choices'].children[i], c, 'choices are not rebuilt'));+assert.equal(writes, count + 2, 'a focus and status change writes those two lines only');+assert.equal(elements['companion-status'].textContent, '');+outbound = 'null'; call();+assert(!classes.has('has-companion'));+assert.equal(elements['companion'].hidden, true, 'off is off: the cleared panel leaves the accessibility tree');+assert.equal(elements['companion-title'].textContent, '');+assert.equal(elements['companion-choices'].children.length, 0);+payload.title = ''; payload.body = []; payload.choices = [];+outbound = JSON.stringify(payload); call();+assert(classes.has('has-companion'));+assert.equal(elements['companion-title'].textContent, payload.empty);+assert.equal(elements['companion-choice-group'].hidden, true);+assert.equal(document.head.children.length, 1, 'no duplicate bootstrap on restart');+'''+ run(code)+++def test_the_status_region_is_in_the_stock_page_from_load_and_the_bridge_reuses_it():+ found = skeleton()+ assert found, 'the stock page must carry the companion skeleton'+ status = [f for f in found if f[3].get('role') == 'status' or 'aria-live' in f[3]]+ assert [f[1] for f in status] == ['companion-status'], 'exactly one live region, the status line'+ assert [f[1] for f in found if 'hidden' in f[3]] == ['companion'], \+ 'off is off (opt-in, owner 1 November 2026): the panel is hidden, with no empty landmark or headings, until the game fills it'+ assert 'body:not(.has-companion) #companion' in stale.page(), 'the empty panel is out of sight until the game fills it'+ made = json.loads(run(bootstrapped(r'''+console.log(JSON.stringify(Object.values(elements).filter(e => e.id.startsWith('companion') && e.tag !== 'style')+ .map(e => [e.tag, e.id, e.parentNode.id || null, e.attributes])));+''')))+ assert made == [[tag, id_, parent, {k: v or '' for k, v in attrs.items() if k != 'id'}] for tag, id_, parent, attrs in found], \+ 'the stock page skeleton and the cached-page bootstrap must build the same elements'+ build = ''.join(+ f"(() => {{ const e = new Element({json.dumps(tag)}); e.id = {json.dumps(id_)}; "+ f"Object.entries({json.dumps({k: v or '' for k, v in attrs.items() if k != 'id'})}).forEach(([k, v]) => e.setAttribute(k, v)); "+ f"(elements[{json.dumps(parent)}] || document.body).appendChild(e); }})();\n"+ for tag, id_, parent, attrs in found)+ run(DRIVER + build + r'''+const status = elements['companion-status'];+const shape = () => Object.values(elements).filter(e => e.tag !== 'style').map(e => [e.tag, e.id, JSON.stringify(e.attributes)]);+const spec = shape();+const bodyChildren = document.body.children.length;+''' + PLUGIN.read_text() + '\nconst payload = ' + json.dumps(payload()) + ';\n' + r'''+assert.equal(elements['companion'].hidden, true, 'precondition: the page-load panel is hidden');+outbound = JSON.stringify(payload); call();+assert.equal(elements['companion'].hidden, false);+assert.equal(status.textContent, '', 'shown first, its status written in a later task');+flush();+assert.strictEqual(elements['companion-status'], status, 'the page-load region is reused, not replaced');+assert.equal(document.body.children.length, bodyChildren, 'no second panel');+assert.deepEqual(shape(), spec, 'the page-load elements are used as they are');+assert.equal(status.textContent, 'Not done: reason');+''')+++def test_malformed_snapshot_keeps_the_last_good_panel_and_a_later_good_one_recovers():+ run(bootstrapped(r'''+const before = writes;+for (const bad of ['{not json', '', '[]', '42', '"text"',+ JSON.stringify(Object.assign({}, payload, {body: 'not a list'})),+ JSON.stringify(Object.assign({}, payload, {choices: [{text: 1}]})),+ JSON.stringify(Object.assign({}, payload, {lang: 'fr'})),+ JSON.stringify(Object.assign({}, payload, {title: null})),+ JSON.stringify({lang: 'en'})]) {+ outbound = bad; call();+}+assert.equal(writes, before, 'a bad payload writes nothing');+assert.equal(elements['companion-title'].textContent, payload.title);+assert(classes.has('has-companion'));+payload.title = 'Recovered'; outbound = JSON.stringify(payload); call();+assert.equal(elements['companion-title'].textContent, 'Recovered');+'''))+++def test_missing_child_node_writes_nothing_and_recovers_when_it_returns():+ run(bootstrapped(r'''+const focusNode = elements['companion-focus'];+delete elements['companion-focus'];+const before = writes;+payload.title = 'Next'; payload.focus = 'Elsewhere'; outbound = JSON.stringify(payload); call();+assert.equal(writes, before, 'nodes are resolved before any write');+assert.equal(elements['companion-title'].textContent, '<img src=x onerror="bad()"> & שלום');+outbound = 'null'; call();+assert.equal(writes, before, 'clearing also needs every node');+elements['companion-focus'] = focusNode;+outbound = JSON.stringify(payload); call();+assert.equal(elements['companion-title'].textContent, 'Next');+assert.equal(focusNode.textContent, 'Elsewhere');+'''))+++def test_missing_page_apis_never_throw_and_bootstrap_is_retried():+ run(DRIVER + PLUGIN.read_text() + '\nconst payload = ' + json.dumps(payload()) + ';\n' + r'''+outbound = JSON.stringify(payload);+const head = document.head; document.head = undefined; call();+assert.equal(typeof window.statecraftCompanion, 'undefined', 'no callback without a usable page');+document.head = head;+createLimit = 3; call();+assert.equal(typeof window.statecraftCompanion, 'undefined', 'a failed bootstrap stays retryable');+createLimit = Infinity; call();+assert.equal(typeof window.statecraftCompanion, 'function');+assert.equal(elements['companion-title'].textContent, payload.title);+assert.equal(document.head.children.length, 1, 'the retry reuses what the failed attempt made');+assert.equal(document.body.children.filter(e => e.id === 'companion').length, 1);+''')+++def test_utf8_conversion_failure_never_throws():+ run(DRIVER + PLUGIN.read_text() + r'''+UTF8ToString = () => { throw new Error('bad pointer'); };+call();+''')+++def test_custom_callback_is_forwarded_without_bootstrapping_or_input():+ run(DRIVER + PLUGIN.read_text() + r'''+let got = [];+window.statecraftCompanion = value => got.push(value);+outbound = '{"status":"custom"}'; call();+outbound = 'null'; call();+assert.deepEqual(got, ['{"status":"custom"}', 'null']);+assert.equal(document.head.children.length, 0);+assert.equal(document.body.children.length, 0);+''')+++def test_a_throwing_custom_callback_never_reaches_unity():+ run(DRIVER + PLUGIN.read_text() + r'''+window.statecraftCompanion = () => { throw new Error('page script bug'); };+outbound = '{}'; call();+''')+++def test_status_is_rewritten_for_a_new_turn_even_with_the_same_text():+ run(bootstrapped(r'''+const status = elements['companion-status'];+let sets = status.sets;+outbound = JSON.stringify(payload); call();+assert.equal(status.sets, sets, 'same text, same turn: no write');+payload.turn = 2; outbound = JSON.stringify(payload); call();+// Clear and write in one task leave the region's text unchanged, which a screen reader may not announce.+assert.equal(status.textContent, '', 'cleared now');+assert.equal(pendingTimers(), 1, 'and written again in a later task');+flush();+assert(status.sets > sets, 'same text on a new turn is announced again');+assert.equal(status.textContent, 'Not done: reason');+payload.turn = 3; outbound = JSON.stringify(payload); call();+payload.status = 'Newer'; outbound = JSON.stringify(payload); call();+assert.equal(status.textContent, 'Newer', 'a new status is written at once');+flush();+assert.equal(status.textContent, 'Newer', 'a dropped deferred write never brings back an older status');+payload.turn = 4; outbound = JSON.stringify(payload); call();+outbound = 'null'; call(); flush();+assert.equal(status.textContent, '', 'a deferred write never fills a cleared panel');+payload.status = 'Not done: reason'; outbound = JSON.stringify(payload); call(); flush();+sets = status.sets;+payload.focus = 'Moved'; outbound = JSON.stringify(payload); call();+assert.equal(status.sets, sets, 'a focus move alone does not touch the status line');+'''))+++def test_turn_report_is_a_readable_section_that_is_not_live():+ run(bootstrapped(r'''+payload.turn = 2; payload.status = 'What happened this turn';+payload.reportTitle = 'What happened this turn';+payload.report = ['What changed in the top bar:', 'Money: -5\nWages paid'];+outbound = JSON.stringify(payload); call();+assert.equal(elements['companion-report'].hidden, false);+assert.equal(elements['companion-report-title'].textContent, 'What happened this turn');+assert.deepEqual(elements['companion-report-rows'].children.map(x => x.textContent), payload.report);+assert.deepEqual(live().map(e => e.id), ['companion-status']);+payload.reportTitle = ''; payload.report = []; outbound = JSON.stringify(payload); call();+assert.equal(elements['companion-report'].hidden, true);+assert.equal(elements['companion-report-rows'].children.length, 0);+'''))+++def test_nonstock_template_without_canvas_keeps_its_own_layout():+ run(DRIVER + PLUGIN.read_text() + r'''+delete elements['unity-canvas']; outbound = '{}';+call();+assert.equal(typeof window.statecraftCompanion, 'undefined');+assert.equal(document.head.children.length, 0);+''')+++def test_csharp_import_js_export_and_production_hook_agree():+ csharp = CAPTURE.read_text()+ plugin = PLUGIN.read_text()+ root = (ROOT / 'unity/Assets/Scripts/UI/GameRoot.cs').read_text()+ assert re.search(r'DllImport\("__Internal"\)\]\s*static extern void StatecraftCompanion\(string json\)', csharp)+ assert 'StatecraftCompanion(json);' in csharp+ assert re.search(r'StatecraftCompanion:\s*function\s*\(json\)', plugin)+ assert 'companion = Own(new WebCompanion(root, text, bridge, () => card?.Shown != null, CompanionSend));' in root+ assert 'Application.platform == RuntimePlatform.WebGLPlayer || CompanionSend != null' in root+ # Opt-in (owner, 1 November 2026: "Opt-in for now (Recommended)"): the page or test transport only makes it possible;+ # the Settings switch, a stored "on" or "?companion=1" turns it on.+ # The address is the page's own (Application.absoluteURL) unless a test sets CompanionAddress.+ assert 'WebCompanion.On(companionPicked, SettingsFile()?.Read(SettingsPresenter.CompanionKey), CompanionAddress ?? Application.absoluteURL)' in root+ assert 'companion = null; minimap = null;' in root, "Shutdown's reset (the toggle's own 'companion = null;' is not it)"+ assert all(word not in plugin for word in ['innerHTML', '.focus(', 'addEventListener', 'SendMessage'])diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex a7a4b87b8..94135ac46 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -57,6 +57,20 @@ namespace Statecraft.Game.UIEventCardPresenter? card;/// <summary>Tests: the decision card of the last Begin.</summary>internal EventCardPresenter? Card => card;+ WebCompanion? companion;+ // The Settings switch for the companion, once pressed in this page's session: it wins over the stored choice and the+ // address for every later Begin (a language switch or New Game), so "Off" holds under "?companion=1" too.+ bool? companionPicked;+ // Outbound test transport only; the shipping bridge remains one-way. Like the WebGL page, it is a page the companion+ // can be turned on for; it does not turn it on.+ internal Action<string>? CompanionSend { get; set; }+ /// <summary>Tests: the page address the companion reads ("?companion=1"); null reads the real one+ /// (Application.absoluteURL, which the Editor leaves empty).</summary>+ internal string? CompanionAddress { get; set; }+ internal WebCompanion? Companion => companion;+ bool CompanionPage => Application.platform == RuntimePlatform.WebGLPlayer || CompanionSend != null;+ /// <summary>Whether a Begin runs the companion: where a page can show it and WebCompanion.On says so.</summary>+ bool CompanionWanted() => CompanionPage && WebCompanion.On(companionPicked, SettingsFile()?.Read(SettingsPresenter.CompanionKey), CompanionAddress ?? Application.absoluteURL);CaptureDialogPresenter? capture;/// <summary>Tests: the capture dialog of the last Begin.</summary>internal CaptureDialogPresenter? Capture => capture;@@ -233,7 +247,8 @@ namespace Statecraft.Game.UI// where a test asks for it with the start screen (OpeningInEditMode).bool enableOpening = smoke == 0 && !StartScreenPresenter.Skipped()&& (Application.isPlaying || startScreen && OpeningInEditMode);- Shutdown();+ // A companion this Begin runs again keeps the page's panel until its replacement publishes (WebCompanion.Dispose).+ Shutdown(keepCompanionPage: companion != null && CompanionWanted());smokeRun = smoke > 0;var text = Strings();@@ -318,7 +333,24 @@ namespace Statecraft.Game.UI// own settings must not leak into a test. Each Begin (New Game too) reads the file again.// The language switch (#1036) builds every screen again in the new language over this game (SwitchLanguage).Action<string> switchLanguage = language => SwitchLanguage(inputs, language); // the start screen's too (#2054)- Own(new SettingsPresenter(root, text, SettingsFile(), switchLanguage, panel: document.panelSettings, audio: audio, advisors: AdvisorSession.Settings));+ // The WebGL companion (#1119) is opt-in (WebCompanion.On): Settings turns it on and off at once, where a page shows it.+ Action<bool>? setCompanion = null;+ (Func<bool> on, Action<bool> set)? companionSwitch = null;+ if (CompanionPage)+ {+ Action<bool> set = on =>+ {+ if (on == (companion != null)) return;+ if (on) { companion = Own(new WebCompanion(root, text, bridge, () => card?.Shown != null, CompanionSend)); return; }+ var off = companion!; companion = null;+ owned.Remove(off);+ off.Dispose(); // clears the page+ };+ setCompanion = set;+ companionSwitch = (() => companion != null, on => { companionPicked = on; set(on); });+ }+ Own(new SettingsPresenter(root, text, SettingsFile(), switchLanguage, panel: document.panelSettings, audio: audio, advisors: AdvisorSession.Settings,+ companion: companionSwitch));// "Report a bug or idea" (#1169), from Settings and the start screen: the version line names the content GameBoot logged.feedback = Own(new FeedbackPresenter(root, text, ReportLinks.Version(Application.version, inputs.Content.Hash)));var feedbackPanel = feedback;@@ -668,6 +700,7 @@ namespace Statecraft.Game.UI}if (hebrew) Own(new UiDirection(root, bridge));root.Q("root")?.RemoveFromClassList("loading"); // ready: the bar, panels and screens may show (P2-1)+ if (setCompanion != null && CompanionWanted()) setCompanion(true);DiagLog.BootPhase("screens ready");if (notes.Count > 0) toast.Show(notes);@@ -868,7 +901,9 @@ namespace Statecraft.Game.UIcontroller.SetFixedNorth(CameraHeadingPolicy.IsFixedNorth(ruleset));/// <summary>Disposes every presenter, the autosave and the camera/pointer hooks (newest first). Safe to call twice.</summary>- void Shutdown()+ /// <param name="keepCompanionPage">A rebuild whose next companion replaces the page's panel: the old one goes without+ /// clearing it, so the panel does not blink, the canvas is not resized twice and the status is not read again.</param>+ void Shutdown(bool keepCompanionPage = false){StopAllCoroutines();// The card first: disposing the start screen uncovers the decision layer, and a card still waiting for it would@@ -878,10 +913,11 @@ namespace Statecraft.Game.UI// going away draw its step again and show its city or unit on a camera being destroyed.if (advisor != null) { owned.Remove(advisor); advisor.Dispose(); }if (card != null) { owned.Remove(card); card.Dispose(); }+ if (keepCompanionPage && companion != null) { owned.Remove(companion); companion.Dispose(clearPage: false); }for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();owned.Clear();if (hoveredCity != null) { hoveredCity = null; HandCursor(false); } // the next Begin's pills start unlit- minimap = null; unseenSkipped = null; labels = null; nav = null; start = null; opening = null; card = null; outcomes = null; report = null; end = null; advisor = null; encyclopedia = null; feedback = null; share = null; info = null; rig = null; drawn = null; drawnSites = null; units = null; Regions = null; logCamera = false;+ companion = null; minimap = null; unseenSkipped = null; labels = null; nav = null; start = null; opening = null; card = null; outcomes = null; report = null; end = null; advisor = 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 the// profile's pixel error (Task 24 review M1). Nothing else changes it, so restoring is always right.if (map != null && map.Terrain != null) map.Terrain.heightmapPixelError = MapBuilder.TerrainPixelError;diff --git a/unity/Assets/Scripts/UI/SettingsPresenter.cs b/unity/Assets/Scripts/UI/SettingsPresenter.csindex 9eeae85b3..7b45fda94 100644--- a/unity/Assets/Scripts/UI/SettingsPresenter.cs+++ b/unity/Assets/Scripts/UI/SettingsPresenter.cs@@ -11,14 +11,14 @@ namespace Statecraft.Game.UI{/// <summary>The Settings screen (#40), opened from the left column's gear like the other screens (ScreenNav). Its options:/// the graphics quality (GraphicsQuality: Auto / High / Low), the sound effects volume (GameAudio, #39), the UI's language (#1036),- /// the UI scale (100% / 125% / 150%), the tilt-shift blur, and a Community row whose "Star on GitHub" opens the repository+ /// the UI scale (100% / 125% / 150%), the tilt-shift blur, the WebGL companion (#1119, its row only where a page shows it) and a Community row whose "Star on GitHub" opens the repository/// (#1168, ExternalLink). The blur option turns it off and on: applied at once (TiltShift.Enabled, what the "tiltshift"/// toggle sets) and kept in the SettingsStore, so it holds after a reload. A stored "off" only ever turns the blur off, so ?notiltshift still boots without it. The/// button says what is set ("On" / "Off"), not only a colour: the player's choice (Enabled), not the web tier's/// automatic last fallback step (TiltShift.FallbackOff), which it never changes.</summary>public sealed class SettingsPresenter : IDisposable{- public const string TiltShiftKey = "tiltshift", QualityKey = "quality", LanguageKey = "lang", UiScaleKey = "uiscale", SoundKey = "sfx", SelectedClass = "settings-choice-selected";+ public const string TiltShiftKey = "tiltshift", QualityKey = "quality", LanguageKey = "lang", UiScaleKey = "uiscale", SoundKey = "sfx", CompanionKey = "companion", SelectedClass = "settings-choice-selected";/// <summary>The owner's UI scales (#40, 18 Oct 2026), in percent; the first is the default.</summary>public static readonly int[] UiScales = { 100, 125, 150 };/// <summary>The owner's ruling on #1011 (19 Oct 2026): Settings offers only the UI scales verified to fit, and 100% always,@@ -45,6 +45,8 @@ namespace Statecraft.Game.UIreadonly Button quit;/// <summary>True between Quit's first press, which asks, and its second, which quits (#2188).</summary>bool quitAsked;+ readonly Button companionSwitch;+ readonly (Func<bool> on, Action<bool> set)? companion;/// <param name="store">Where the choice is kept; null keeps nothing (the option still works until the page closes).</param>/// <param name="switchLanguage">Puts the UI in the language pressed (GameRoot builds the screens again); null changes@@ -52,9 +54,12 @@ namespace Statecraft.Game.UI/// <param name="panel">The UI's panel, which the UI scale scales; null leaves the scale alone.</param>/// <param name="advisors">The live advisor settings; null hides its row.</param>/// <param name="audio">The sound effects the volume applies to; null keeps only the choice.</param>- public SettingsPresenter(VisualElement root, UiText text, SettingsStore? store, Action<string>? switchLanguage = null, PanelSettings? panel = null, GameAudio? audio = null, AdvisorSettings? advisors = null)+ /// <param name="companion">The WebGL companion (#1119, WebCompanion): whether it runs, and what turns it on or off at+ /// once; null (no page to show it in) hides its row.</param>+ public SettingsPresenter(VisualElement root, UiText text, SettingsStore? store, Action<string>? switchLanguage = null, PanelSettings? panel = null, GameAudio? audio = null, AdvisorSettings? advisors = null,+ (Func<bool> on, Action<bool> set)? companion = null){- this.store = store; this.text = text; this.root = root; this.audio = audio; this.advisors = advisors;+ this.store = store; this.text = text; this.root = root; this.audio = audio; this.advisors = advisors; this.companion = companion;screen = root.Q<VisualElement>("screen-settings");screen.Q<Label>("settings-screen-title").text = text["settings.title"];screen.Q<Label>("settings-tiltshift-label").text = text["settings.tiltshift"];@@ -126,6 +131,12 @@ namespace Statecraft.Game.UI// The fit depends on the window's shape, which a resize changes: the offer and the applied scale follow the// root's geometry (as TopBarInset does). The file keeps the choice, so a shape that holds it again gets it back.root.RegisterCallback<GeometryChangedEvent>(OnGeometry);+ // The WebGL companion (#1119): off unless the player turns it on here or the address asks for it (WebCompanion.On).+ screen.Q<Label>("settings-companion-label").text = text["settings.companion"];+ companionSwitch = screen.Q<Button>("settings-companion");+ if (companion == null) companionSwitch.parent.style.display = DisplayStyle.None;+ else companionSwitch.parent.style.display = StyleKeyword.Null; // GameRoot reuses the tree an earlier Begin hid it in+ companionSwitch.clicked += FlipCompanion;// Community (#1168): Star on GitHub opens the repository in a new tab.screen.Q<Label>("settings-community-label").text = text["settings.community"];var star = screen.Q<Button>("settings-star");@@ -144,6 +155,7 @@ namespace Statecraft.Game.UIpublic void Dispose(){tiltShift.clicked -= Flip;+ companionSwitch.clicked -= FlipCompanion;foreach (var (b, _, pick) in quality) b.clicked -= pick;languages.Dispose();foreach (var (b, _, pick) in sound) b.clicked -= pick;@@ -165,6 +177,19 @@ namespace Statecraft.Game.UIvoid WithdrawQuit() { quitAsked = false; quit.text = text["ui.quit"]; }+ void FlipCompanion()+ {+ if (companion is not { } c) return;+ bool on = !c.on();+ c.set(on);+ Show();+ try { store?.Write(CompanionKey, on ? "on" : "off"); }+ catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)+ {+ Debug.LogWarning($"Settings: could not keep the companion choice ({e.Message}); it holds until the page is closed");+ }+ }+void Flip(){TiltShift.Enabled = !TiltShift.Enabled;@@ -248,6 +273,7 @@ namespace Statecraft.Game.UIvoid Show(){tiltShift.text = text[TiltShift.Enabled ? "settings.on" : "settings.off"];+ companionSwitch.text = text[companion?.on() == true ? "settings.on" : "settings.off"];foreach (var (b, c, _) in quality) b.EnableInClassList(SelectedClass, c == GraphicsQuality.Current);languages.Mark();foreach (var (b, l, _) in sound) b.EnableInClassList(SelectedClass, l == soundLevel);diff --git a/unity/Assets/Scripts/UI/WebCompanion.cs b/unity/Assets/Scripts/UI/WebCompanion.csnew file mode 100644index 000000000..4d46f5c1f--- /dev/null+++ b/unity/Assets/Scripts/UI/WebCompanion.cs@@ -0,0 +1,205 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Runtime.InteropServices;+using System.Text.RegularExpressions;+using UnityEngine;+using UnityEngine.UIElements;++namespace Statecraft.Game.UI+{+ /// <summary>One-way WebGL mirror of the presenter's words. It never receives game commands or changes focus. Opt-in+ /// (<see cref="On"/>): the Settings switch or "?companion=1" turns it on.+ /// It publishes in the frame after a sim change, an End Turn, a refused order, a click, a submit or a focus move, once+ /// the presenters have rendered; periodic sampling also catches toast writes and controls rebuilt without any of those.+ /// Nothing is published before the first frame. Owned by GameRoot: a restart/language switch disposes it without clearing+ /// the page, and the next mirror's first snapshot replaces the panel; turning it off or disabling GameRoot clears it.</summary>+ public sealed class WebCompanion : IDisposable+ {+ [Serializable]+ public sealed class Choice+ {+ public string text = "", note = "";+ public bool available;+ }++ [Serializable]+ public sealed class Snapshot+ {+ public string lang = "", heading = "", help = "", focusHeading = "", statusHeading = "", choicesHeading = "", empty = "", unavailable = "";+ public string title = "", focus = "", status = "", reportTitle = "";+ /// <summary>The game turn: the page announces the same status again when it comes on a new turn.</summary>+ public int turn;+ public string[] body = Array.Empty<string>();+ /// <summary>The open turn report's introduction, then one entry a row: its heading and its causes, one a line.</summary>+ public string[] report = Array.Empty<string>();+ public Choice[] choices = Array.Empty<Choice>();+ }++ // "?companion=1": a whole query parameter with a whole value (UrlFlags' rule), so "?companion=10" and "?xcompanion=1"+ // are not it.+ static readonly Regex Asked = new Regex(@"[?&]companion=1(?=&|#|$)", RegexOptions.CultureInvariant);++ /// <summary>Whether the mirror runs: off unless asked for. The owner's ruling of 1 November 2026, "Opt-in for now+ /// (Recommended)", until the VoiceOver test and the phone layout are done. <paramref name="picked"/> is the Settings+ /// switch pressed in this page's session, which wins; else the stored choice (<see cref="SettingsPresenter.CompanionKey"/>+ /// "on") or "?companion=1" in the page address turns it on. The address wins over a stored "off" for that visit and+ /// writes nothing: the owner's ruling of 2 November 2026, "Link wins, that visit (Recommended)".</summary>+ public static bool On(bool? picked, string? stored, string? url) => picked ?? (stored == "on" || Asked.IsMatch(url ?? ""));++ readonly VisualElement root;+ readonly UiText text;+ readonly SimBridge? bridge;+ readonly Func<bool> hasEvent;+ readonly Action<string> send;+ readonly IVisualElementScheduledItem poll;+ readonly Action later;+ readonly Action<IReadOnlyList<Statecraft.Sim.Rejection>> onTurn;+ readonly Action<string> onRefused;+ readonly EventCallback<ClickEvent> onClick;+ readonly EventCallback<NavigationSubmitEvent> onSubmit;+ readonly EventCallback<FocusInEvent> onFocus;+ IVisualElementScheduledItem? next;+ string? previous;+ bool disposed;++ /// <param name="bridge">The game's bridge, for the turn and its events; null in tests of a bare tree.</param>+ public WebCompanion(VisualElement root, UiText text, SimBridge? bridge, Func<bool> hasEvent, Action<string>? send = null)+ {+ this.root = root; this.text = text; this.bridge = bridge; this.hasEvent = hasEvent; this.send = send ?? Publish;+ // One publication in the next frame however many notifications arrive in this one (as UiDirection schedules).+ later = () => { if (disposed) return; next?.Pause(); next = root.schedule.Execute(Refresh); };+ onTurn = _ => later(); onRefused = _ => later();+ onClick = _ => later(); onSubmit = _ => later(); onFocus = _ => later();+ if (bridge != null) { bridge.Changed += later; bridge.TurnEnded += onTurn; bridge.Refused += onRefused; }+ root.RegisterCallback(onClick, TrickleDown.TrickleDown);+ root.RegisterCallback(onSubmit, TrickleDown.TrickleDown);+ root.RegisterCallback(onFocus, TrickleDown.TrickleDown);+ poll = root.schedule.Execute(Refresh).Every(100);+ later();+ }++ /// <summary>Copies rendered/localised strings, not event IDs or an independently formatted sim projection.+ /// A collapsed/covered current event stays readable; hasEvent prevents the presenter's retained labels from+ /// leaking the previous event after the final answer. Disabled choices remain ordinary readable list items.</summary>+ internal Snapshot Capture(VisualElement? focused = null)+ {+ var snapshot = new Snapshot+ {+ lang = text["ui.lang"], heading = text["companion.title"], help = text["companion.help"],+ focusHeading = text["companion.focus"], statusHeading = text["companion.status"],+ choicesHeading = text["companion.choices"], empty = text["companion.empty"], unavailable = text["companion.unavailable"],+ turn = bridge?.State.Turn ?? 0,+ };+ var toast = root.Q<Label>("toast");+ if (Visible(toast) && toast!.text.Length > 0) snapshot.status = toast.text;+ // The End Turn result, whether or not a decision waits: the report section carries its rows as the panel shows+ // them, and the status line names the open report while no toast is showing. Never both: the line is one atomic+ // live region, read whole on any change: a toast joined to the title would read the title when the toast came+ // and again when it went.+ var report = root.Q(TurnReportPresenter.ElementName);+ if (Visible(report))+ {+ snapshot.reportTitle = Words("turn-report-title");+ if (snapshot.status.Length == 0) snapshot.status = snapshot.reportTitle;+ var lines = new List<string>();+ var intro = Words("turn-report-intro");+ if (intro.Length > 0) lines.Add(intro);+ var rows = report!.Q<ScrollView>("turn-report-rows");+ if (rows != null)+ foreach (var row in rows.Children())+ {+ var words = new List<string>();+ row.Query<Label>().ForEach(l => { if (l.text.Length > 0) words.Add(l.text); });+ if (words.Count > 0) lines.Add(string.Join("\n", words));+ }+ snapshot.report = lines.ToArray();+ }+ focused ??= root.focusController?.focusedElement as VisualElement;+ if (focused != null && root.Contains(focused) && Visible(focused))+ {+ if (focused == root.Q("map-focus")) snapshot.focus = text["companion.map"];+ else if (focused.name == "event-card" && hasEvent()) snapshot.focus = Words("event-title");+ else if (!string.IsNullOrEmpty(focused.tooltip)) snapshot.focus = focused.tooltip;+ else if (focused is TextElement label) snapshot.focus = label.text;+ else+ {+ var labels = new List<string>();+ focused.Query<Label>().ForEach(l => { if (Visible(l) && l.text.Length > 0) labels.Add(l.text); });+ snapshot.focus = string.Join("\n", labels);+ }+ }+ if (!hasEvent()) return snapshot;+ snapshot.title = Words("event-title");+ var body = new List<string>();+ foreach (var name in new[] { "event-draft", "event-office", "event-alt-banner", "event-text", "event-objective", "event-delegate", "event-count" })+ {+ var label = root.Q<Label>(name);+ // Test only the label itself: collapsing the event must not erase its text from the companion.+ if (label != null && label.style.display.value != DisplayStyle.None && label.text.Length > 0) body.Add(label.text);+ }+ snapshot.body = body.ToArray();+ var choices = new List<Choice>();+ var options = root.Q("event-options");+ if (options != null)+ foreach (var child in options.Children())+ {+ if (child is Button b) choices.Add(new Choice { text = b.text, available = b.enabledInHierarchy });+ else if (child is Label note && note.ClassListContains(EventCardPresenter.RejoinClass) && choices.Count > 0)+ choices[choices.Count - 1].note = note.text;+ }+ snapshot.choices = choices.ToArray();+ return snapshot;+ }++ string Words(string name) => root.Q<Label>(name)?.text ?? "";++ static bool Visible(VisualElement? element)+ {+ if (element == null) return false;+ for (var e = element; e != null; e = e.parent)+ if (e.style.display.value == DisplayStyle.None || e.resolvedStyle.display == DisplayStyle.None ||+ e.style.visibility.value == Visibility.Hidden || e.resolvedStyle.visibility == Visibility.Hidden) return false;+ return true;+ }++ internal void Refresh()+ {+ if (disposed) return;+ var json = JsonUtility.ToJson(Capture());+ if (json == previous) return;+ send(json);+ previous = json; // only once it has gone out: a publication that threw is tried again+ }++ public void Dispose() => Dispose(clearPage: true);++ /// <param name="clearPage">False for GameRoot's rebuild (a language switch, New Game): the next mirror's first+ /// snapshot replaces the panel, so the page neither blinks nor reads its status again.</param>+ internal void Dispose(bool clearPage)+ {+ if (disposed) return;+ disposed = true;+ poll.Pause(); next?.Pause(); next = null;+ if (bridge != null) { bridge.Changed -= later; bridge.TurnEnded -= onTurn; bridge.Refused -= onRefused; }+ root.UnregisterCallback(onClick, TrickleDown.TrickleDown);+ root.UnregisterCallback(onSubmit, TrickleDown.TrickleDown);+ root.UnregisterCallback(onFocus, TrickleDown.TrickleDown);+ // Last, and never thrown on: GameRoot disposes its owned presenters in one loop, and a page or test transport+ // that throws here must not leave the rest of them undisposed.+ if (!clearPage) return;+ try { send("null"); }+ catch (Exception e) { Debug.LogException(e); }+ }++#if UNITY_WEBGL && !UNITY_EDITOR+ [DllImport("__Internal")] static extern void StatecraftCompanion(string json);+#endif+ static void Publish(string json)+ {+#if UNITY_WEBGL && !UNITY_EDITOR+ StatecraftCompanion(json);+#endif+ }+ }+}diff --git a/unity/Assets/Scripts/UI/WebCompanion.cs.meta b/unity/Assets/Scripts/UI/WebCompanion.cs.metanew file mode 100644index 000000000..d5b9aceba--- /dev/null+++ b/unity/Assets/Scripts/UI/WebCompanion.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ae4b44426bcb406d9dc1c09de2e6b8c8diff --git a/unity/Assets/Scripts/UI/WebCompanion.jslib b/unity/Assets/Scripts/UI/WebCompanion.jslibnew file mode 100644index 000000000..3741cab0a--- /dev/null+++ b/unity/Assets/Scripts/UI/WebCompanion.jslib@@ -0,0 +1,167 @@+// Outbound only, and optional: nothing here may throw back into the Unity call that published a snapshot. A malformed+// snapshot, a missing element or a failing page script leaves the last good panel, and a failed bootstrap is tried again+// on the next snapshot. The stock page carries the panel from load, hidden (the companion is opt-in: off is out of the+// accessibility tree); a cached older page gets the same elements from the bootstrap below, which travels with the+// hashed player. A snapshot shows the panel and writes its first status in a later task, so the one live region (the+// status line) is in the tree before its first announcement. An existing custom callback is respected. Pages without the stock canvas keep their own layout.+mergeInto(LibraryManager.library, {+ StatecraftCompanion: function (json) {+ try {+ var payload = UTF8ToString(json);+ if (typeof window === "undefined" || typeof document === "undefined" || !document) return;+ if (typeof window.statecraftCompanion !== "function") {+ if (!document.head || !document.body || typeof document.createElement !== "function" ||+ typeof document.getElementById !== "function" || !document.getElementById("unity-canvas")) return;+ if (!document.getElementById("companion-style")) {+ var style = document.createElement("style");+ style.id = "companion-style";+ style.textContent =+ " body:not(.has-companion) #companion { position: absolute; width: 1px; height: 1px; overflow: hidden;\n" ++ " clip-path: inset(50%); white-space: nowrap; }\n" ++ " body.has-companion #unity-canvas { width: calc(100% - 22rem); }\n" ++ " body.has-companion #companion { position: fixed; right: 0; top: 0; bottom: 0; box-sizing: border-box;\n" ++ " width: 22rem; overflow: auto; color: #ece4d2; background: #0e1626;\n" ++ " padding: max(1rem, env(safe-area-inset-top)) max(1rem, env(safe-area-inset-right))\n" ++ " max(1rem, env(safe-area-inset-bottom)) 1rem;\n" ++ " border-left: 1px solid #c4a05c; font: 16px/1.5 Georgia, serif; overflow-wrap: anywhere; }\n" ++ " #companion p, #companion li { white-space: pre-wrap; }\n" ++ " #companion h2, #companion h3 { font-size: 1.15rem; }\n" ++ " #companion ol { padding-inline: 0; list-style-position: inside; }\n" ++ " @media (max-width: 900px) {\n" ++ " body.has-companion #unity-canvas { width: 100%; height: 65%; }\n" ++ " body.has-companion #companion { top: 65%; width: 100%; border-left: 0; border-top: 1px solid #c4a05c;\n" ++ " padding: 1rem max(1rem, env(safe-area-inset-right)) max(1rem, env(safe-area-inset-bottom))\n" ++ " max(1rem, env(safe-area-inset-left)); }\n" ++ " }";+ document.head.appendChild(style);+ }+ // Tag, id, parent id, attributes: the same elements, in the same order, as the stock page's skeleton (index.html).+ var specs = [+ ["aside", "companion", null, { "aria-labelledby": "companion-heading", "tabindex": "-1", "dir": "auto", "hidden": "" }],+ ["h2", "companion-heading", "companion", { "dir": "auto" }],+ ["p", "companion-help", "companion", { "dir": "auto" }],+ ["section", "companion-event", "companion", { "dir": "auto" }],+ ["h3", "companion-title", "companion-event", { "dir": "auto" }],+ ["div", "companion-body", "companion-event", { "dir": "auto" }],+ ["div", "companion-choice-group", "companion-event", { "dir": "auto" }],+ ["h3", "companion-choice-heading", "companion-choice-group", { "dir": "auto" }],+ ["ol", "companion-choices", "companion-choice-group", { "dir": "auto" }],+ ["h3", "companion-focus-heading", "companion", { "dir": "auto" }],+ ["p", "companion-focus", "companion", { "dir": "auto" }],+ ["h3", "companion-status-heading", "companion", { "dir": "auto" }],+ ["p", "companion-status", "companion", { "role": "status", "aria-atomic": "true", "dir": "auto" }],+ ["section", "companion-report", "companion", { "dir": "auto" }],+ ["h3", "companion-report-title", "companion-report", { "dir": "auto" }],+ ["div", "companion-report-rows", "companion-report", { "dir": "auto" }]+ ];+ for (var i = 0; i < specs.length; i++) {+ var spec = specs[i];+ if (document.getElementById(spec[1])) continue; // the stock page's own element, or a failed attempt's+ var parent = spec[2] ? document.getElementById(spec[2]) : document.body;+ if (!parent) return;+ var made = document.createElement(spec[0]);+ made.id = spec[1];+ for (var key in spec[3]) made.setAttribute(key, spec[3][key]);+ parent.appendChild(made);+ }+ var texts = ["heading", "help", "focusHeading", "statusHeading", "choicesHeading", "empty", "unavailable",+ "title", "focus", "status", "reportTitle"];+ var strings = function (list) {+ if (!Array.isArray(list)) return false;+ for (var n = 0; n < list.length; n++) if (typeof list[n] !== "string") return false;+ return true;+ };+ // The whole shape is checked before anything on the page changes.+ var valid = function (s) {+ if (s === null) return true;+ if (typeof s !== "object" || Array.isArray(s)) return false;+ if (s.lang !== "en" && s.lang !== "he") return false; // a fixed language, never game text+ if (typeof s.turn !== "number") return false;+ for (var n = 0; n < texts.length; n++) if (typeof s[texts[n]] !== "string") return false;+ if (!strings(s.body) || !strings(s.report) || !Array.isArray(s.choices)) return false;+ for (n = 0; n < s.choices.length; n++) {+ var c = s.choices[n];+ if (!c || typeof c.text !== "string" || typeof c.note !== "string" || typeof c.available !== "boolean") return false;+ }+ return true;+ };+ var parts = ["heading", "help", "title", "body", "choice-group", "choice-heading", "choices", "focus-heading",+ "focus", "status-heading", "status", "report", "report-title", "report-rows"];+ var cleared = ["heading", "help", "title", "body", "choice-heading", "choices", "focus-heading", "focus",+ "status-heading", "status", "report-title", "report-rows"];+ var previous = null;+ var pending = null; // the timer of a status write waiting for a later task+ // Clears the status line now and writes it in a later task: a clear and a write in one task leave the text the+ // same, which a screen reader may not announce.+ var announceLater = function (status, value) {+ status.textContent = "";+ pending = setTimeout(function () {+ pending = null;+ try { status.textContent = value; } catch (e) { /* the game must keep running */ }+ }, 150);+ };+ window.statecraftCompanion = function (json) {+ var snapshot;+ try { snapshot = JSON.parse(json); } catch (e) { return; }+ if (!valid(snapshot)) return;+ var panel = document.getElementById("companion");+ if (!panel) return; // A custom callback may own a different DOM.+ var node = {};+ for (var n = 0; n < parts.length; n++) {+ node[parts[n]] = document.getElementById("companion-" + parts[n]);+ if (!node[parts[n]]) return;+ }+ var words = function (part, value) { if (node[part].textContent !== value) node[part].textContent = value; };+ var lines = function (part, tag, values) {+ node[part].textContent = "";+ values.forEach(function (value) {+ var e = document.createElement(tag); e.setAttribute("dir", "auto"); e.textContent = value;+ node[part].appendChild(e);+ });+ };+ document.body.classList.toggle("has-companion", snapshot !== null);+ // A status write still waiting is dropped: this snapshot says what the line holds now.+ if (pending !== null) { clearTimeout(pending); pending = null; }+ if (snapshot === null) {+ cleared.forEach(function (part) { node[part].textContent = ""; });+ node.report.hidden = true;+ panel.hidden = true; // off is off: no empty landmark or headings in the accessibility tree+ previous = null;+ return;+ }+ var appearing = panel.hidden;+ panel.hidden = false;+ if (panel.lang !== snapshot.lang) panel.lang = snapshot.lang;+ // Containers need the UI direction; leaf paragraphs/choices still resolve mixed-script text independently.+ var direction = snapshot.lang === "he" ? "rtl" : "ltr";+ if (panel.dir !== direction) panel.dir = direction;+ words("heading", snapshot.heading);+ words("help", snapshot.help);+ words("title", snapshot.title || snapshot.empty);+ words("choice-heading", snapshot.choicesHeading);+ words("focus-heading", snapshot.focusHeading);+ words("focus", snapshot.focus);+ words("status-heading", snapshot.statusHeading);+ // The one live region: written when its text changes, and written again when the same result comes on a new turn.+ // Its first text after the panel appears, and a repeat, go in a later task (announceLater).+ if (appearing && snapshot.status !== "") announceLater(node.status, snapshot.status);+ else if (node.status.textContent !== snapshot.status) node.status.textContent = snapshot.status;+ else if (previous && previous.turn !== snapshot.turn && snapshot.status !== "") announceLater(node.status, snapshot.status);+ if (!previous || JSON.stringify(previous.body) !== JSON.stringify(snapshot.body)) lines("body", "p", snapshot.body);+ node["choice-group"].hidden = snapshot.choices.length === 0;+ if (!previous || previous.unavailable !== snapshot.unavailable || JSON.stringify(previous.choices) !== JSON.stringify(snapshot.choices))+ lines("choices", "li", snapshot.choices.map(function (choice) {+ return choice.text + (choice.available ? "" : ": " + snapshot.unavailable) + (choice.note ? "\n" + choice.note : "");+ }));+ node.report.hidden = snapshot.reportTitle === "" && snapshot.report.length === 0;+ words("report-title", snapshot.reportTitle);+ if (!previous || JSON.stringify(previous.report) !== JSON.stringify(snapshot.report)) lines("report-rows", "p", snapshot.report);+ previous = snapshot;+ };+ }+ window.statecraftCompanion(payload);+ } catch (e) {+ // Swallowed on purpose: the game must keep running whatever the page does with the mirror.+ }+ }+});diff --git a/unity/Assets/Scripts/UI/WebCompanion.jslib.meta b/unity/Assets/Scripts/UI/WebCompanion.jslib.metanew file mode 100644index 000000000..1dbb1b49e--- /dev/null+++ b/unity/Assets/Scripts/UI/WebCompanion.jslib.meta@@ -0,0 +1,32 @@+fileFormatVersion: 2+guid: 450dfe9c9ff443c699da53368d767e21+PluginImporter:+ externalObjects: {}+ serializedVersion: 2+ iconMap: {}+ executionOrder: {}+ defineConstraints: []+ isPreloaded: 0+ isOverridable: 0+ isExplicitlyReferenced: 0+ validateReferences: 1+ platformData:+ - first:+ Any:+ second:+ enabled: 0+ settings: {}+ - first:+ Editor: Editor+ second:+ enabled: 0+ settings:+ DefaultValueInitialized: true+ - first:+ WebGL: WebGL+ second:+ enabled: 1+ settings: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Tests/EditMode/HebrewUiTests.cs b/unity/Assets/Tests/EditMode/HebrewUiTests.csindex babffaa52..e416fc5bf 100644--- a/unity/Assets/Tests/EditMode/HebrewUiTests.cs+++ b/unity/Assets/Tests/EditMode/HebrewUiTests.cs@@ -513,7 +513,7 @@ public class HebrewUiTests("settings-sound-label", "settings.sound"), ("settings-sound-off", "settings.sound.off"),("settings-sound-low", "settings.sound.low"), ("settings-sound-high", "settings.sound.high"),("settings-advisors-label", "settings.advisors"), ("settings-language-label", "settings.language"),- ("settings-uiscale-label", "settings.uiscale"),+ ("settings-uiscale-label", "settings.uiscale"), ("settings-companion-label", "settings.companion"), // #1119("settings-community-label", "settings.community"), ("settings-star", "community.star"), ("start-star", "community.star"),("settings-report", "feedback.open"), ("start-report", "feedback.open"), ("feedback-title", "feedback.open"), // #1169("hud-star", "community.star"), ("hud-report", "feedback.open"), ("hud-share", "share.open"), // #1236diff --git a/unity/Assets/Tests/EditMode/WebCompanionTests.cs b/unity/Assets/Tests/EditMode/WebCompanionTests.csnew file mode 100644index 000000000..e3df41d87--- /dev/null+++ b/unity/Assets/Tests/EditMode/WebCompanionTests.cs@@ -0,0 +1,574 @@+#nullable enable+using System.Collections;+using System.Collections.Generic;+using NUnit.Framework;+using Statecraft.Game.UI;+using UnityEditor;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;++public sealed class WebCompanionTests+{+ static UiText Text => UiText.Parse("ui.lang: en\ncompanion.title: Game companion\ncompanion.help: Read only\ncompanion.focus: Game focus\ncompanion.status: Status\ncompanion.choices: Choices\ncompanion.empty: No decision waiting\ncompanion.unavailable: Unavailable\n");++ static VisualElement Tree()+ {+ var root = new VisualElement();+ var card = new VisualElement { name = "event-card" }; root.Add(card);+ card.Add(new Label("A <title> & a name") { name = "event-title" });+ card.Add(new Label("Body שלום") { name = "event-text" });+ var options = new VisualElement { name = "event-options" }; card.Add(options);+ options.Add(new Button { text = "First", name = "option-internal-id" });+ var disabled = new Button { text = "Second" }; disabled.SetEnabled(false); options.Add(disabled);+ root.Add(new Label("Not done: reason") { name = "toast" });+ return root;+ }++ [Test]+ public void MirrorsRenderedWordsAndChoiceOrderWithoutInvokingControls()+ {+ var root = Tree(); bool active = true; int inputs = 0;+ root.Q<Button>().clicked += () => inputs++;+ var sent = new List<string>();+ using var mirror = new WebCompanion(root, Text, null, () => active, sent.Add);+ var state = mirror.Capture(root.Q<Button>());+ Assert.AreEqual("A <title> & a name", state.title);+ CollectionAssert.Contains(state.body, "Body שלום");+ Assert.AreEqual("First", state.choices[0].text);+ Assert.IsTrue(state.choices[0].available);+ Assert.AreEqual("Second", state.choices[1].text);+ Assert.IsFalse(state.choices[1].available);+ Assert.AreEqual("First", state.focus);+ Assert.AreEqual("Not done: reason", state.status);+ Assert.AreEqual(0, inputs);+ Assert.IsFalse(JsonUtility.ToJson(state).Contains("option-internal-id"));+ active = false; // presenter retains old label text after its last event is answered+ state = mirror.Capture();+ Assert.AreEqual("", state.title);+ Assert.IsEmpty(state.body);+ Assert.IsEmpty(state.choices);+ }++ [Test]+ public void HiddenStatusAndFocusAreClearedAndUnnamedCardHasItsTitle()+ {+ var root = Tree();+ using var mirror = new WebCompanion(root, Text, null, () => true, _ => { });+ Assert.AreEqual("A <title> & a name", mirror.Capture(root.Q("event-card")).focus);+ root.style.display = DisplayStyle.None;+ var state = mirror.Capture(root.Q<Button>());+ Assert.AreEqual("", state.focus);+ Assert.AreEqual("", state.status);+ }+++ [UnityTest]+ public IEnumerator ScheduledMirrorFollowsActualPanelFocusAndToastChanges()+ {+ var ui = new UiTestKit();+ var settings = Object.Instantiate(ui.Doc.panelSettings);+ var texture = new RenderTexture(640, 480, 0);+ settings.targetTexture = texture;+ try+ {+ ui.Doc.panelSettings = settings; // a rendered runtime panel, as KeyboardFocusTests uses+ ui.Root.Clear();+ var root = Tree(); ui.Root.Add(root);+ var sent = new List<string>();+ using var mirror = new WebCompanion(root, Text, null, () => true, sent.Add);+ yield return null;+ yield return null;+ var button = root.Q<Button>();+ button.Focus();+ for (int i = 0; i < 10 && root.focusController.focusedElement != button; i++) { yield return null; button.Focus(); }+ Assert.AreSame(button, root.focusController.focusedElement, "precondition: real runtime keyboard focus");+ Assert.AreEqual("First", mirror.Capture().focus, "precondition: capture sees actual keyboard focus");+ root.Q<Label>("toast").text = "New result";+ var until = EditorApplication.timeSinceStartup + 2;+ WebCompanion.Snapshot state;+ do+ {+ // EditMode yields alone do not pump a UIDocument's runtime timer scheduler.+ EditorApplication.QueuePlayerLoopUpdate();+ yield return null;+ state = JsonUtility.FromJson<WebCompanion.Snapshot>(sent[sent.Count - 1]);+ } while ((state.focus != "First" || state.status != "New result") && EditorApplication.timeSinceStartup < until);+ Assert.AreEqual("First", state.focus);+ Assert.AreEqual("New result", state.status);+ mirror.Dispose();+ var count = sent.Count;+ root.Q<Label>("toast").text = "After disposal";+ until = EditorApplication.timeSinceStartup + 0.3;+ while (EditorApplication.timeSinceStartup < until) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }+ Assert.AreEqual(count, sent.Count, "the disposed schedule sends no stale state");+ }+ finally+ {+ ui.Dispose(); Object.DestroyImmediate(settings); texture.Release(); Object.DestroyImmediate(texture);+ }+ }++ [Test]+ public void SendsOnlyChangedSnapshotsAndDisposalClearsAndStopsPublishing()+ {+ var root = Tree(); var sent = new List<string>();+ var mirror = new WebCompanion(root, Text, null, () => true, sent.Add);+ Assert.IsEmpty(sent, "nothing is published before the first frame");+ mirror.Refresh(); var initial = sent.Count;+ Assert.AreEqual(1, initial);+ mirror.Refresh(); Assert.AreEqual(initial, sent.Count);+ root.Q<Label>("toast").text = "Result";+ mirror.Refresh(); Assert.AreEqual(initial + 1, sent.Count);+ mirror.Dispose(); Assert.AreEqual("null", sent[sent.Count - 1]);+ var disposed = sent.Count;+ mirror.Refresh(); mirror.Dispose(); Assert.AreEqual(disposed, sent.Count);+ using var next = new WebCompanion(root, Text, null, () => false, sent.Add);+ next.Refresh();+ Assert.AreEqual("", JsonUtility.FromJson<WebCompanion.Snapshot>(sent[sent.Count - 1]).title);+ }++ [Test]+ public void APublicationThatThrewIsTriedAgain()+ {+ var root = Tree(); var sent = new List<string>(); var fail = true;+ using var mirror = new WebCompanion(root, Text, null, () => true, json => { if (fail) throw new System.InvalidOperationException("page"); sent.Add(json); });+ Assert.Throws<System.InvalidOperationException>(mirror.Refresh);+ fail = false;+ mirror.Refresh();+ Assert.AreEqual(1, sent.Count, "the unchanged snapshot goes out once the page takes it");+ }++ static int Handlers(Statecraft.Game.UI.SimBridge bridge, string name) =>+ (typeof(Statecraft.Game.UI.SimBridge).GetField(name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!+ .GetValue(bridge) as System.Delegate)?.GetInvocationList().Length ?? 0;++ /// <summary>Disposal itself unsubscribes and stops the schedule: the disposed flag alone would hide a leak of every old+ /// mirror (and the tree and GameRoot it holds) on each language switch, since the bridge outlives it.</summary>+ [Test]+ public void DisposeRemovesEveryBridgeAndRootHandlerAndStopsTheSchedule()+ {+ var bridge = NewBridge(Locale(false));+ var events = new[] { "Changed", "TurnEnded", "Refused" };+ var before = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select(events, n => Handlers(bridge, n)));+ var root = new VisualElement();+ Assert.IsFalse(root.HasTrickleDownHandlers(), "precondition: a bare tree has no handlers");+ var mirror = new WebCompanion(root, Text, bridge, () => false, _ => { });+ foreach (var (name, i) in System.Linq.Enumerable.Select(events, (n, i) => (n, i)))+ Assert.AreEqual(before[i] + 1, Handlers(bridge, name), $"precondition: the mirror listens to {name}");+ Assert.IsTrue(root.HasTrickleDownHandlers(), "precondition: the mirror listens on the root");+ var poll = (IVisualElementScheduledItem)typeof(WebCompanion).GetField("poll", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(mirror);+ Assert.IsTrue(poll.isActive, "precondition: the fallback poll runs");+ mirror.Dispose();+ CollectionAssert.AreEqual(before, System.Linq.Enumerable.Select(events, n => Handlers(bridge, n)), "every bridge handler is removed");+ Assert.IsFalse(root.HasTrickleDownHandlers(), "every root handler is removed");+ Assert.IsFalse(poll.isActive, "the fallback poll is stopped");+ }++ [Test]+ public void ATransportThatThrowsOnDisposalDoesNotStopTheTeardown()+ {+ var bridge = NewBridge(Locale(false));+ var before = Handlers(bridge, "Changed");+ var mirror = new WebCompanion(new VisualElement(), Text, bridge, () => false, json => { if (json == "null") throw new System.InvalidOperationException("page"); });+ LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("page"));+ Assert.DoesNotThrow(mirror.Dispose, "GameRoot disposes the presenters owned before the mirror in the same loop");+ Assert.AreEqual(before, Handlers(bridge, "Changed"));+ }++ static UiText Locale(bool he) => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(he ? UiPaths.StringsHebrew : UiPaths.Strings).text, he ? "strings.he.yaml" : "strings.en.yaml");++ [TestCase(false, "Map")]+ [TestCase(true, "מפה")]+ public void RealMapStopHasALocalizedNameAndKeepsItsInput(bool he, string expected)+ {+ using var ui = new UiTestKit();+ var stop = ui.Root.Q("map-focus");+ Assert.IsTrue(stop.focusable);+ int inputs = 0;+ stop.RegisterCallback<NavigationSubmitEvent>(_ => inputs++);+ using var mirror = new WebCompanion(ui.Root, Locale(he), null, () => false, _ => { });+ Assert.AreEqual(expected, mirror.Capture(stop).focus);+ using (var e = NavigationSubmitEvent.GetPooled()) { e.target = stop; stop.SendEvent(e); }+ Assert.AreEqual(1, inputs, "the mirror's submit handler leaves the map stop's own submit alone");+ Assert.IsTrue(stop.focusable);+ }++ [TestCase(false)]+ [TestCase(true)]+ public void RealPresenterRejoinNoteFollowsItsChoiceAndClearsWithIt(bool he)+ {+ var text = Locale(he);+ var c = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content);+ var e = System.Linq.Enumerable.First(c.Events, x => x.Id == "armistice_egypt");+ e.Options[0].Rejoin = "first_truce"; // presentation-only fixture: a real event id, because the card now resolves the rejoin target for its effect rows+ var game = Statecraft.Sim.GameSession.New(c, Statecraft.Sim.GoldenRun.Seed, Statecraft.Sim.Mode.Historical);+ game.State.Date = e.From;+ game.State.PendingEvents.Clear(); game.State.PendingEvents.Add(e.Id);+ var bridge = new Statecraft.Game.UI.SimBridge(game, text);+ using var ui = new UiTestKit();+ using var card = new EventCardPresenter(ui.Root, bridge, text, null);+ using var mirror = new WebCompanion(ui.Root, text, bridge, () => card.Shown != null, _ => { });+ Assert.AreEqual(e.Id, card.Shown!.Id);+ var capture = System.Environment.GetEnvironmentVariable("WEB_COMPANION_CAPTURE_DIR");+ if (!string.IsNullOrEmpty(capture))+ {+ System.IO.Directory.CreateDirectory(capture);+ System.IO.File.WriteAllText(System.IO.Path.Combine(capture, he ? "event-he.json" : "event-en.json"), JsonUtility.ToJson(mirror.Capture()));+ }+ Assert.AreEqual(text["event.rejoin"], mirror.Capture().choices[0].note);+ Assert.AreEqual("", mirror.Capture().choices[1].note);+ card.Collapse();+ Assert.AreEqual(text["event.rejoin"], mirror.Capture().choices[0].note);+ card.Reopen();+ Assert.AreEqual(text["event.rejoin"], mirror.Capture().choices[0].note);+ game.State.PendingEvents.Clear(); game.State.PendingEvents.Add("first_truce");+ card.Render();+ Assert.AreEqual("first_truce", card.Shown!.Id);+ foreach (var choice in mirror.Capture().choices) Assert.AreEqual("", choice.note);+ game.State.PendingEvents.Clear(); card.Render();+ Assert.IsEmpty(mirror.Capture().choices);+ }++ [Test]+ public void ActualRootRebuildLanguageSwitchAndDisableOwnTheOutboundLifetime()+ {+ var dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "statecraft-companion-" + System.Guid.NewGuid().ToString("N"));+ var inputs = Statecraft.Game.Boot.GameInputs.FromDisk(Statecraft.Game.Paths.Content, Statecraft.Game.Paths.StreamingMap);+ try+ {+ UnityEditor.SceneManagement.EditorSceneManager.OpenScene("Assets/Map.unity", UnityEditor.SceneManagement.OpenSceneMode.Single);+ Object.FindFirstObjectByType<Statecraft.Game.Map.MapScene>().Build(inputs.Map);+ var game = Object.FindFirstObjectByType<GameRoot>();+ game.Store = new Statecraft.Game.SaveStore(dir);+ game.Settings = new Statecraft.Game.SettingsStore(dir);+ game.Settings.Write(SettingsPresenter.CompanionKey, "on"); // opt-in (owner, 1 November 2026)+ var sent = new List<string>(); game.CompanionSend = sent.Add;+ game.Language = UiLanguage.English;+ game.Begin(inputs, 0);+ Assert.IsEmpty(sent, "nothing is published before the first frame");+ game.Companion!.Refresh();+ Assert.IsNotEmpty(sent, "Begin must create the mirror with the production hookup");+ var old = game.Companion!;+ Assert.AreEqual("en", JsonUtility.FromJson<WebCompanion.Snapshot>(sent[sent.Count - 1]).lang);+ var session = game.Bridge!.Session;+ var state = game.Bridge.State;+ game.Card!.Collapse();+ var ui = Object.FindFirstObjectByType<UIDocument>().rootVisualElement;+ UiTestKit.Press(ui.Q<Button>("nav-settings"));+ UiTestKit.Press(ui.Q<Button>("settings-language-he"));+ Assert.AreEqual("he", game.Language);+ Assert.AreSame(session, game.Bridge!.Session);+ Assert.AreSame(state, game.Bridge.State);+ // A rebuild does not clear the page: the next mirror's first snapshot replaces the panel, so it does not blink,+ // the canvas is not resized twice and the status is not read again (key-2 review C5).+ CollectionAssert.DoesNotContain(sent, "null", "a language switch keeps the page's panel");+ game.Companion!.Refresh();+ Assert.AreEqual("he", JsonUtility.FromJson<WebCompanion.Snapshot>(sent[sent.Count - 1]).lang);+ var count = sent.Count; old.Refresh(); Assert.AreEqual(count, sent.Count);+ var current = game.Companion!;+ game.Begin(inputs, 0);+ Assert.AreNotSame(current, game.Companion);+ count = sent.Count; current.Refresh(); Assert.AreEqual(count, sent.Count);+ CollectionAssert.DoesNotContain(sent, "null", "New Game keeps the page's panel too");+ game.enabled = false; Assert.AreEqual("null", sent[sent.Count - 1]);+ Assert.IsNull(game.Companion);+ }+ finally+ {+ UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.EmptyScene, UnityEditor.SceneManagement.NewSceneMode.Single);+ Statecraft.Game.Map.VisualToggles.Clear();+ if (System.IO.Directory.Exists(dir)) System.IO.Directory.Delete(dir, true);+ }+ }++ // The owner's ruling of 1 November 2026, "Opt-in for now (Recommended)": off unless the Settings switch, a stored "on" or+ // "?companion=1" asks for it; a switch pressed in this session wins over both.+ [TestCase(null, null, null, false)]+ [TestCase(null, null, "", false)]+ [TestCase(null, null, "https://example.org/statecraft/index.html", false)]+ [TestCase(null, "off", "https://example.org/statecraft/index.html?lang=he", false)]+ [TestCase(null, null, "https://example.org/statecraft/index.html?companion=1", true)]+ [TestCase(null, null, "https://example.org/statecraft/index.html?lang=he&companion=1#x", true)]+ [TestCase(null, "off", "https://example.org/statecraft/index.html?companion=1", true)]+ [TestCase(null, null, "https://example.org/statecraft/index.html?companion=0", false)]+ [TestCase(null, null, "https://example.org/statecraft/index.html?companion", false)]+ [TestCase(null, null, "https://example.org/statecraft/index.html?companion=10", false)]+ [TestCase(null, null, "https://example.org/statecraft/index.html?xcompanion=1", false)]+ [TestCase(null, null, "https://example.org/companion=1/index.html", false)]+ [TestCase(null, "on", "", true)]+ [TestCase(null, "yes", "", false)]+ [TestCase(false, "on", "https://example.org/statecraft/index.html?companion=1", false)]+ [TestCase(true, "off", "", true)]+ public void TheCompanionIsOptIn(bool? picked, string? stored, string? url, bool expected) =>+ Assert.AreEqual(expected, WebCompanion.On(picked, stored, url));++ [Test]+ public void TheSettingsRowShowsOnlyWhereAPageCanShowTheCompanionAndSaysWhatIsSet([Values(false, true)] bool hebrew)+ {+ var text = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(hebrew ? UiPaths.StringsHebrew : UiPaths.Strings).text,+ hebrew ? "strings.he.yaml" : "strings.en.yaml");+ var dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "statecraft-companion-" + System.Guid.NewGuid().ToString("N"));+ try+ {+ using (var ui = new UiTestKit())+ using (new SettingsPresenter(ui.Root, text, new Statecraft.Game.SettingsStore(dir)))+ {+ Assert.AreEqual(text["settings.companion"], ui.Q<Label>("settings-companion-label").text);+ Assert.AreEqual(DisplayStyle.None, ui.Q<Button>("settings-companion").parent.style.display.value, "no page: no row");+ }+ // GameRoot reuses one tree for every Begin: a presenter with a page shows the row an earlier one hid (key-2 H7).+ using (var ui = new UiTestKit())+ {+ using (new SettingsPresenter(ui.Root, text, new Statecraft.Game.SettingsStore(dir))) { }+ using (new SettingsPresenter(ui.Root, text, new Statecraft.Game.SettingsStore(dir), companion: (() => false, _ => { })))+ Assert.AreNotEqual(DisplayStyle.None, ui.Q<Button>("settings-companion").parent.style.display.value, "the same tree, now with a page: the row shows");+ }+ bool on = false; var asked = new List<bool>();+ using (var ui = new UiTestKit())+ using (new SettingsPresenter(ui.Root, text, new Statecraft.Game.SettingsStore(dir), companion: (() => on, v => { asked.Add(v); on = v; })))+ {+ var button = ui.Q<Button>("settings-companion");+ Assert.AreNotEqual(DisplayStyle.None, button.parent.style.display.value);+ Assert.AreEqual(text["settings.off"], button.text, "off by default");+ UiTestKit.Press(button);+ CollectionAssert.AreEqual(new[] { true }, asked, "turned on at once");+ Assert.AreEqual(text["settings.on"], button.text);+ Assert.AreEqual("on", new Statecraft.Game.SettingsStore(dir).Read(SettingsPresenter.CompanionKey), "and kept");+ UiTestKit.Press(button);+ CollectionAssert.AreEqual(new[] { true, false }, asked);+ Assert.AreEqual(text["settings.off"], button.text);+ Assert.AreEqual("off", new Statecraft.Game.SettingsStore(dir).Read(SettingsPresenter.CompanionKey));+ }+ }+ finally { if (System.IO.Directory.Exists(dir)) System.IO.Directory.Delete(dir, true); }+ }++ [Test]+ public void TheRealRootStartsWithoutTheCompanionAndItsSettingTurnsItOnAndOffForThisAndLaterGames()+ {+ var dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "statecraft-companion-" + System.Guid.NewGuid().ToString("N"));+ var inputs = Statecraft.Game.Boot.GameInputs.FromDisk(Statecraft.Game.Paths.Content, Statecraft.Game.Paths.StreamingMap);+ try+ {+ UnityEditor.SceneManagement.EditorSceneManager.OpenScene("Assets/Map.unity", UnityEditor.SceneManagement.OpenSceneMode.Single);+ Object.FindFirstObjectByType<Statecraft.Game.Map.MapScene>().Build(inputs.Map);+ var game = Object.FindFirstObjectByType<GameRoot>();+ game.Store = new Statecraft.Game.SaveStore(dir);+ game.Settings = new Statecraft.Game.SettingsStore(dir);+ var sent = new List<string>(); game.CompanionSend = sent.Add;+ game.Language = UiLanguage.English;+ game.Begin(inputs, 0);+ Assert.IsNull(game.Companion, "off by default, with a page that could show it");+ var ui = Object.FindFirstObjectByType<UIDocument>().rootVisualElement;+ UiTestKit.Press(ui.Q<Button>("nav-settings"));+ var button = ui.Q<Button>("settings-companion");+ Assert.AreNotEqual(DisplayStyle.None, button.parent.style.display.value, "the row shows where a page can show the companion");+ UiTestKit.Press(button);+ Assert.IsNotNull(game.Companion, "the switch turns it on at once");+ game.Companion!.Refresh();+ Assert.AreEqual("en", JsonUtility.FromJson<WebCompanion.Snapshot>(sent[sent.Count - 1]).lang);+ game.Begin(inputs, 0);+ Assert.IsNotNull(game.Companion, "a later game keeps it on");+ UiTestKit.Press(ui.Q<Button>("nav-settings"));+ UiTestKit.Press(ui.Q<Button>("settings-companion"));+ Assert.IsNull(game.Companion, "the switch turns it off at once");+ Assert.AreEqual("null", sent[sent.Count - 1], "and clears the page");+ Assert.AreEqual("off", game.Settings.Read(SettingsPresenter.CompanionKey));+ var count = sent.Count;+ game.Begin(inputs, 0);+ Assert.IsNull(game.Companion, "a later game keeps it off");+ game.enabled = false;+ Assert.AreEqual(count, sent.Count, "nothing was published while it was off");+ }+ finally+ {+ UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.EmptyScene, UnityEditor.SceneManagement.NewSceneMode.Single);+ Statecraft.Game.Map.VisualToggles.Clear();+ if (System.IO.Directory.Exists(dir)) System.IO.Directory.Delete(dir, true);+ }+ }++ // The owner's ruling of 2 November 2026, "Link wins, that visit (Recommended)": "?companion=1" turns the companion on+ // for that visit over a stored "off", and the saved Settings choice is kept for later visits.+ [Test]+ public void TheLinkTurnsTheCompanionOnForThatVisitAndKeepsTheSavedOff()+ {+ var dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "statecraft-companion-" + System.Guid.NewGuid().ToString("N"));+ var inputs = Statecraft.Game.Boot.GameInputs.FromDisk(Statecraft.Game.Paths.Content, Statecraft.Game.Paths.StreamingMap);+ try+ {+ UnityEditor.SceneManagement.EditorSceneManager.OpenScene("Assets/Map.unity", UnityEditor.SceneManagement.OpenSceneMode.Single);+ Object.FindFirstObjectByType<Statecraft.Game.Map.MapScene>().Build(inputs.Map);+ var game = Object.FindFirstObjectByType<GameRoot>();+ game.Store = new Statecraft.Game.SaveStore(dir);+ game.Settings = new Statecraft.Game.SettingsStore(dir);+ game.Settings.Write(SettingsPresenter.CompanionKey, "off");+ var saved = System.IO.File.ReadAllText(game.Settings.FilePath);+ var sent = new List<string>(); game.CompanionSend = sent.Add;+ game.Language = UiLanguage.English;+ game.CompanionAddress = "https://example.org/statecraft/index.html?companion=1";+ game.Begin(inputs, 0);+ Assert.IsNotNull(game.Companion, "the link wins over a stored \"off\" for this visit");+ game.Companion!.Refresh();+ Assert.IsNotEmpty(sent, "and it publishes");+ game.Begin(inputs, 0);+ Assert.IsNotNull(game.Companion, "a New Game in the same visit keeps it on");+ Assert.AreEqual(saved, System.IO.File.ReadAllText(game.Settings.FilePath), "the link writes nothing to the saved settings");+ Assert.AreEqual("off", game.Settings.Read(SettingsPresenter.CompanionKey));+ // A later visit without the link: the saved "off" holds again.+ game.CompanionAddress = "https://example.org/statecraft/index.html";+ game.Begin(inputs, 0);+ Assert.IsNull(game.Companion, "a later visit without the link keeps the saved \"off\"");+ Assert.AreEqual("null", sent[sent.Count - 1], "and the page's panel is cleared");+ Assert.AreEqual(saved, System.IO.File.ReadAllText(game.Settings.FilePath));+ game.enabled = false;+ }+ finally+ {+ UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.EmptyScene, UnityEditor.SceneManagement.NewSceneMode.Single);+ Statecraft.Game.Map.VisualToggles.Clear();+ if (System.IO.Directory.Exists(dir)) System.IO.Directory.Delete(dir, true);+ }+ }++ static readonly Statecraft.Sim.Content GameContent = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content);++ static Statecraft.Game.UI.SimBridge NewBridge(UiText text) =>+ new Statecraft.Game.UI.SimBridge(Statecraft.Sim.GameSession.New(GameContent, Statecraft.Sim.GoldenRun.Seed, Statecraft.Sim.Mode.Historical), text);++ [Test]+ public void CoveredChoicesAreUnavailableAndComeBackWhenUncovered()+ {+ // The production cover rule: an open screen disables the decision layer, not each button's own state.+ var root = new VisualElement { name = "root" };+ var layer = new VisualElement { name = "event-layer" }; root.Add(layer);+ layer.Add(Tree());+ using var mirror = new WebCompanion(root, Text, null, () => true, _ => { });+ CollectionAssert.AreEqual(new[] { true, false }, System.Linq.Enumerable.Select(mirror.Capture().choices, c => c.available));+ root.AddToClassList(ScreenNav.ScreenOpenClass);+ ScreenNav.DisableCovered(root);+ Assert.IsFalse(layer.enabledSelf, "precondition: the open screen covers the decision layer");+ var covered = mirror.Capture();+ CollectionAssert.AreEqual(new[] { false, false }, System.Linq.Enumerable.Select(covered.choices, c => c.available));+ Assert.AreEqual("First", covered.choices[0].text, "a covered choice stays readable");+ root.RemoveFromClassList(ScreenNav.ScreenOpenClass);+ ScreenNav.DisableCovered(root);+ CollectionAssert.AreEqual(new[] { true, false }, System.Linq.Enumerable.Select(mirror.Capture().choices, c => c.available),+ "uncovered: each choice is back to its own state, the unpaid one still unavailable");+ }++ [TestCase(false)]+ [TestCase(true)]+ public void EndTurnReportIsMirroredWithoutAnEventAndClearsWhenClosed(bool he)+ {+ var text = Locale(he);+ var bridge = NewBridge(text);+ using var ui = new UiTestKit();+ using var nav = new ScreenNav(ui.Root);+ using var toast = new ToastPresenter(ui.Root, bridge, text);+ using var report = new TurnReportPresenter(ui.Root, bridge, text, nav);+ using var mirror = new WebCompanion(ui.Root, text, bridge, () => false, _ => { });+ Assert.AreEqual("", mirror.Capture().reportTitle);+ Assert.IsEmpty(mirror.Capture().report);+ bridge.EndTurn();+ Assert.IsTrue(report.IsOpen, "precondition: End Turn opens the report");+ toast.Clear(); // the status line with no toast showing+ var state = mirror.Capture();+ Assert.AreEqual(bridge.State.Turn, state.turn);+ Assert.AreEqual(text["report.title"], state.reportTitle);+ StringAssert.Contains(text["report.title"], state.status, "the status line names the result");+ var expected = new List<string> { text["report.intro"] };+ foreach (var row in ui.Q<ScrollView>("turn-report-rows").Children())+ expected.Add(string.Join("\n", System.Linq.Enumerable.Where(System.Linq.Enumerable.Select(row.Query<Label>().ToList(), l => l.text), t => t.Length > 0)));+ Assert.Greater(expected.Count, 1, "precondition: the report has rows");+ CollectionAssert.AreEqual(expected, state.report, "the report's own words, in its order");+ // The status line is one atomic live region, read whole on any change: a toast over the open report is the line+ // alone, so one toast does not read the report title again with it, and again when it goes (key-2 review C1).+ toast.Refuse("x");+ Assert.AreEqual(text.Format("toast.refused", "x"), mirror.Capture().status, "a toast over the report is the status alone");+ CollectionAssert.AreEqual(expected, mirror.Capture().report, "the report section keeps its rows under the toast");+ toast.Clear();+ Assert.AreEqual(text["report.title"], mirror.Capture().status, "the report's title again once the toast goes");+ var capture = System.Environment.GetEnvironmentVariable("WEB_COMPANION_CAPTURE_DIR");+ if (!string.IsNullOrEmpty(capture))+ {+ System.IO.Directory.CreateDirectory(capture);+ System.IO.File.WriteAllText(System.IO.Path.Combine(capture, he ? "report-he.json" : "report-en.json"), JsonUtility.ToJson(state));+ }+ report.Close();+ state = mirror.Capture();+ Assert.AreEqual("", state.reportTitle);+ Assert.IsEmpty(state.report);+ StringAssert.DoesNotContain(text["report.title"], state.status);+ }++ [UnityTest]+ public IEnumerator RefusalWithoutChangedAndTheSameResultOnTheNextTurnArePublished()+ {+ var ui = new UiTestKit();+ var settings = Object.Instantiate(ui.Doc.panelSettings);+ var texture = new RenderTexture(640, 480, 0);+ settings.targetTexture = texture;+ var text = Locale(false);+ var bridge = NewBridge(text);+ try+ {+ ui.Doc.panelSettings = settings; // a rendered runtime panel, so its scheduler runs+ ui.Root.Clear();+ var root = Tree(); ui.Root.Add(root);+ using var toast = new ToastPresenter(root, bridge, text);+ var sent = new List<string>();+ var changed = 0; bridge.Changed += () => changed++;+ var mirror = new WebCompanion(root, text, bridge, () => true, sent.Add);+ Assert.IsEmpty(sent, "nothing is published before the first frame");+ yield return Pump(() => sent.Count > 0);+ Assert.IsNotEmpty(sent, "the first frame publishes");+ // The fallback poll stopped: what follows reaches the page through the mirror's own subscriptions (key-2 review+ // C4; with the poll running, removing them left this test green).+ ((IVisualElementScheduledItem)typeof(WebCompanion).GetField("poll", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(mirror)).Pause();+ WebCompanion.Snapshot Last() => JsonUtility.FromJson<WebCompanion.Snapshot>(sent[sent.Count - 1]);++ var reason = bridge.Queue(new Statecraft.Sim.SetPolicy("curfew", 1));+ Assert.IsNotNull(reason, "precondition: the order is refused");+ Assert.AreEqual(0, changed, "precondition: a refusal raises no Changed");+ var refused = text.Format("toast.refused", reason!);+ yield return Pump(() => Last().status == refused);+ Assert.AreEqual(refused, Last().status, "a refusal without Changed reaches the page");+ var firstTurn = Last().turn;++ bridge.EndTurn();+ Assert.AreEqual(reason, bridge.Queue(new Statecraft.Sim.SetPolicy("curfew", 1)), "precondition: the same refusal");+ yield return Pump(() => Last().turn != firstTurn && Last().status == refused);+ Assert.AreEqual(refused, Last().status);+ Assert.AreEqual(bridge.State.Turn, Last().turn, "the same result on a new turn is a new publication");+ Assert.AreNotEqual(firstTurn, Last().turn);++ bridge.Queue(new Statecraft.Sim.SetPolicy("curfew", 2)); // schedules a publication...+ mirror.Dispose(); // ...that disposal cancels+ var count = sent.Count;+ Assert.AreEqual("null", sent[count - 1]);+ yield return Pump(() => false, 0.3);+ Assert.AreEqual(count, sent.Count, "a pending publication never runs after disposal");+ bridge.Queue(new Statecraft.Sim.SetPolicy("curfew", 3));+ yield return Pump(() => false, 0.3);+ Assert.AreEqual(count, sent.Count, "disposal unsubscribes from the bridge");+ }+ finally+ {+ ui.Dispose(); Object.DestroyImmediate(settings); texture.Release(); Object.DestroyImmediate(texture);+ }+ }++ /// <summary>Frames until the condition holds or the time runs out (EditMode yields alone do not pump a UIDocument's+ /// runtime scheduler).</summary>+ static IEnumerator Pump(System.Func<bool> until, double seconds = 2)+ {+ var end = EditorApplication.timeSinceStartup + seconds;+ while (!until() && EditorApplication.timeSinceStartup < end)+ {+ EditorApplication.QueuePlayerLoopUpdate();+ yield return null;+ }+ }+}diff --git a/unity/Assets/Tests/EditMode/WebCompanionTests.cs.meta b/unity/Assets/Tests/EditMode/WebCompanionTests.cs.metanew file mode 100644index 000000000..6bf2bf9f0--- /dev/null+++ b/unity/Assets/Tests/EditMode/WebCompanionTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 9b9c956140234bbcaa15945a3c77e905diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxmlindex be8a8d2ca..568449133 100644--- a/unity/Assets/UI/Game.uxml+++ b/unity/Assets/UI/Game.uxml@@ -501,6 +501,11 @@<ui:Button name="settings-uiscale-150" text="150%" class="settings-switch" /></ui:VisualElement></ui:VisualElement>+ <!-- The WebGL companion (#1119, WebCompanion): opt-in, off by default; the row shows only where a page can show it. -->+ <ui:VisualElement class="row settings-row">+ <ui:Label name="settings-companion-label" text="Screen reader companion" class="settings-name" />+ <ui:Button name="settings-companion" class="settings-switch" />+ </ui:VisualElement><!-- Community (#1168): "Star on GitHub" opens the repository in a new tab (ExternalLink); "Report a bug or idea"opens the report panel (#1169, FeedbackPresenter); "Share" opens the share panel with a picture of the game(#1170, SharePresenter). -->diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex 01f406bfd..7653862e8 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -147,6 +147,8 @@ settings.title: "Settings"settings.tiltshift: "Blur at the top and bottom of the map"settings.on: "On"settings.off: "Off"+# The WebGL companion switch (#1119); the Hebrew awaits native review.+settings.companion: "Screen reader companion"settings.quality: "Quality"settings.quality.auto: "Automatic"settings.quality.high: "High"@@ -1151,3 +1153,13 @@ dollars.refused_monthly: "That is more dollars than may be converted this month"dollars.refused_total: "That would pass the total of dollars that may be converted"dollars.refused_reserves: "There are not enough dollars in the reserves"why.cause.dollars_converted: "Converted {0} of foreign currency into Money: {1}"++# Read-only WebGL companion (#1119); Hebrew additions await native review.+companion.title: "Game companion"+companion.help: "Read-only. Play with the game's keyboard controls."+companion.focus: "Game focus"+companion.status: "Status"+companion.choices: "Choices"+companion.empty: "No decision waiting"+companion.unavailable: "Unavailable"+companion.map: "Map"diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yamlindex 87fdaf196..4ea247b79 100644--- a/unity/Assets/UI/strings.he.yaml+++ b/unity/Assets/UI/strings.he.yaml@@ -153,6 +153,8 @@ settings.title: "הגדרות"settings.tiltshift: "טשטוש בחלק העליון ובחלק התחתון של המפה"settings.on: "מופעל"settings.off: "כבוי"+# The WebGL companion switch (#1119); the Hebrew awaits native review.+settings.companion: "מלווה לקוראי מסך"# The graphics quality choice (#40). Adjectives in the feminine, agreeing with "איכות". Approved by Beri, a native# speaker, on #40 (17 Oct 2026). For the native reviewer (#564).settings.quality: "איכות גרפית"@@ -1270,3 +1272,13 @@ dollars.refused_monthly: "זה יותר מהסכום שמותר להמיר החdollars.refused_total: "ההמרה תעבור את הסכום הכולל שמותר להמיר"dollars.refused_reserves: "אין די דולרים ביתרות מטבע החוץ"why.cause.dollars_converted: "המרת מטבע חוץ לכסף: {0}; כסף: שינוי {1}"++# Read-only WebGL companion (#1119); Hebrew additions await native review.+companion.title: "מלווה למשחק"+companion.help: "תצוגה לקריאה בלבד. המשחק מתנהל באמצעות מקשי המקלדת של המשחק."+companion.focus: "המיקוד במשחק"+companion.status: "מצב"+companion.choices: "אפשרויות"+companion.empty: "אין החלטה ממתינה"+companion.unavailable: "לא זמין"+companion.map: "מפה"diff --git a/unity/Assets/WebGLTemplates/Statecraft/index.html b/unity/Assets/WebGLTemplates/Statecraft/index.htmlindex 3ecb7a6fa..ed0854a3f 100644--- a/unity/Assets/WebGLTemplates/Statecraft/index.html+++ b/unity/Assets/WebGLTemplates/Statecraft/index.html@@ -14,12 +14,37 @@#fill { width: 0; height: 100%; background: #c4a05c; }#error { display: none; position: fixed; left: 10%; right: 10%; top: 40%; color: #de7868; background: #0e1626;border: 1px solid #c4a05c; padding: 16px; font: 16px Georgia, serif; white-space: pre-wrap; }+ /* Issue #1119: the read-only companion is in the page from load, hidden: it is opt-in, and off keeps it out of the+ accessibility tree. WebCompanion.jslib shows and styles it once the game publishes, and writes its first status+ in a later task, so the status region is in the tree before its first announcement. */+ body:not(.has-companion) #companion { position: absolute; width: 1px; height: 1px; overflow: hidden;+ clip-path: inset(50%); white-space: nowrap; }</style></head><body><canvas id="unity-canvas" tabindex="-1"></canvas><div id="loading">Statecraft: Israel<div id="bar"><div id="fill"></div></div></div><div id="error"></div>+ <aside id="companion" aria-labelledby="companion-heading" tabindex="-1" dir="auto" hidden>+ <h2 id="companion-heading" dir="auto"></h2>+ <p id="companion-help" dir="auto"></p>+ <section id="companion-event" dir="auto">+ <h3 id="companion-title" dir="auto"></h3>+ <div id="companion-body" dir="auto"></div>+ <div id="companion-choice-group" dir="auto">+ <h3 id="companion-choice-heading" dir="auto"></h3>+ <ol id="companion-choices" dir="auto"></ol>+ </div>+ </section>+ <h3 id="companion-focus-heading" dir="auto"></h3>+ <p id="companion-focus" dir="auto"></p>+ <h3 id="companion-status-heading" dir="auto"></h3>+ <p id="companion-status" role="status" aria-atomic="true" dir="auto"></p>+ <section id="companion-report" dir="auto">+ <h3 id="companion-report-title" dir="auto"></h3>+ <div id="companion-report-rows" dir="auto"></div>+ </section>+ </aside><script>// Full-window canvas: Unity keeps the render size matched to the canvas's CSS size, so the UI Toolkit panel// (ScaleWithScreenSize, 1920x1080, match 0.5) rescales on every browser resize.