Files
gods-eye-view/src/contextSessionOrdering.test.mjs
T
Manjunath PaparajuandSameh Khamis 0a6fd5f43f Make Space Missions an ordinary layer with its own panel
Space Missions no longer runs as a Context mode. The launches layer owns
its Satellites dependency, including the rule that a Satellites off
asked for after Space Missions was switched on ends it (request order
decides), and a small controller connects the layer to its own panel and
store. Context no longer isolates, snapshots or restores Space Missions
or Satellites, so Contacts and Space Missions run together in either
order, and scene playback no longer exits an isolating mode. Settled by
the owner: Contacts leaves Satellites as it is, and only a person's or
voice Satellites off ends Space Missions; a scene, story, preset or
other programmatic off does not.

Turning the layer on by hand or by voice, choosing it at first run, or
picking a mission on the globe opens the Space Missions panel, and on a
phone its Missions sheet. Asking voice to open the panel while the layer
is off is refused with a reason, and voice never opens it while the
Cockpit owns the screen. With no Context mode on, a voice Context off
switches Space Missions off. A failed Satellites restore no longer cuts
the layer's teardown short. Mission labels on the globe select their
mission. The layer names a failed first index load itself, so the
Context toast no longer imports Space Missions code.

Also carries the satellites request ordering and
DataLayerManager.waitForLayerIdle, the share token for the panel, voice
panel ids, Cockpit folding the panel away and the phone tab ellipsis.
The panel shares the rail gutters and hover border of the other side
panels.

On top of the Omnibar: "open space missions panel" reaches the new
panel, and Open Context no longer answers to "missions".

Co-authored-by: Sameh Khamis <[email protected]>
2026-11-18 16:03:51 -08:00

330 lines
18 KiB
JavaScript

import { readShellSource } from './testSupport/readShellSource.mjs';
import { _handleContextLayerChange } from './ui/contextLayerChanges.js';
import { connectContextManager } from './ui/contextSubscriptions.js';
import { _restoreContextSession, _restoreContextSessionAfterLayerSettles } from './ui/contextSession.js';
import { _selectContextMode, _clearLayersOutsideContextMode } from './ui/contextTransactions.js';
import { _initGlobalContextPanel } from './ui/contextBindings.js';
import { setContextMode as contextModeAction } from './ui/contextActions.js';
import { ContextControls } from './ui/contextControls.js';
import { readFileSync as readRadioSource } from 'node:fs';
const radioBindings = readRadioSource(new URL('./ui/radioBindings.js', import.meta.url), 'utf8');
const radioControlsSource = readRadioSource(new URL('./ui/radioControls.js', import.meta.url), 'utf8');
// Source-contract pins read the actual Context owners and root disposal wiring. Each pin guards a bug that shipped or nearly shipped:
// - session bookkeeping ran AFTER the exit early-return, so the compensating
// userAdded.delete never ran on the left-panel chip exit and restoration
// resurrected the mission layer the user just disabled;
// - a failed direct Contacts START cleared siblings with no rollback;
// - the right-rail entry ignored the activation result entirely.
import { test } from 'node:test';
import assert from 'node:assert/strict';
const src = readShellSource();
const handler = _handleContextLayerChange.toString();
test('context handler: session bookkeeping runs before the exit early-return', () => {
const record = handler.indexOf('recordContextSessionUserChange(');
const exit = handler.indexOf('shouldExitContextForLayerChange(');
assert.ok(record > 0, 'bookkeeping call present');
assert.ok(exit > 0, 'exit predicate present');
assert.ok(record < exit, 'bookkeeping must precede the exit check');
});
test('Space Missions is an ordinary layer the Context handler never enters', () => {
assert.doesNotMatch(handler, /'space-missions'/);
assert.doesNotMatch(handler, /_contextModeEntering = /);
const attach = connectContextManager.toString();
assert.doesNotMatch(attach, /rocket-launches|space-missions/);
});
test('a cancelled visibility request returns before settled bookkeeping', () => {
const cancelled = handler.indexOf("change?.type === 'visibility-cancelled'");
const bookkeeping = handler.indexOf('recordContextSessionUserChange(');
assert.ok(cancelled > 0, 'cancellation branch present');
assert.ok(cancelled < bookkeeping, 'cancellation returns before settled session bookkeeping');
const branch = handler.slice(cancelled, handler.indexOf("change?.type === 'visibility-blocked'"));
assert.match(branch, /this\._syncContextModeButtons\(\);\s*return;/);
});
test('direct Context entry captures on the synchronous request boundary', () => {
const attach = connectContextManager.toString();
assert.match(
attach,
/subscribeVisibilityRequests\(\(change\) => \{[\s\S]*?shouldCaptureContextSession\(change\)/,
);
});
test('only a direct Contacts entry request snapshots the layers', () => {
let request;
const controls = new ContextControls({
elements: {},
installations: {},
actions: { getCockpit: () => null },
});
const captures = [];
controls._captureContextSessionSnapshot = (options) => captures.push(options);
controls._syncContextModeButtons = () => {};
controls.connect({
subscribe: () => () => {},
subscribeVisibilityRequests(listener) {
request = listener;
return () => {};
},
});
for (const layerId of ['rocket-launches', 'military-awareness'])
request({ type: 'visibility-requested', layerId, enabled: true, origin: 'user', intentEpoch: 1 });
controls.stop();
assert.deepEqual(captures, [{ excludeLayerIds: ['military-awareness'] }]);
});
test('context restore replays explicit companion intent after the stale restore queue drains', () => {
const restore = _restoreContextSession.toString();
const restoreAwait = restore.indexOf('await this._dataManager.restoreEnabledLayerIds(');
const replay = restore.indexOf('await settleContextIntentReplay(');
assert.ok(restoreAwait > 0, 'restore queue is awaited');
assert.ok(replay > restoreAwait, 'newer explicit intent is replayed after the stale restore');
assert.match(handler, /recordContextRestoreExplicitChange\(\{/);
});
test('context restore settles the Contacts coordinator before dependency fanout', () => {
const restore = _restoreContextSession.toString();
const settle = restore.indexOf("const contactsCoordinatorId = 'military-awareness'");
const coordinatorOff = restore.indexOf('const coordinatorSettled = await this._dataManager.setEnabled(', settle);
const fanout = restore.indexOf('await this._dataManager.restoreEnabledLayerIds(', settle);
assert.ok(settle > 0, 'Contacts coordinator settlement is present');
assert.ok(coordinatorOff > settle, 'Contacts OFF is awaited');
assert.ok(fanout > coordinatorOff, 'snapshot fanout starts after Contacts settles');
assert.match(restore, /excludeLayerIds: \[[\s\S]*?CONTEXT_INDEPENDENT_LAYER_IDS[\s\S]*?settleContactsCoordinator \? \[contactsCoordinatorId\]/);
});
test('Clear All during the Contacts settle stops the snapshot coming back', () => {
const restore = _restoreContextSession.toString();
const coordinatorOff = restore.indexOf('const coordinatorSettled = await this._dataManager.setEnabled(');
const cancelled = restore.indexOf('if (restoreState.cancelled) return;', coordinatorOff);
const fanout = restore.indexOf('await this._dataManager.restoreEnabledLayerIds(', coordinatorOff);
assert.ok(cancelled > coordinatorOff, 'the cancellation is checked after Contacts settles');
assert.ok(fanout > cancelled, 'and before the snapshot fans out');
});
test('context restore preserves its exact pending target after a failed transition', () => {
const restore = _restoreContextSession.toString();
assert.match(restore, /const replayError = await settleContextIntentReplay\(\{/);
assert.match(restore, /if \(restoreError && !this\._contextSessionSnapshot\)/);
assert.match(restore, /enabledLayerIds: new Set\(restoreState\.enabledLayerIds\)/);
assert.match(restore, /this\._contextSessionSnapshot = \{/);
});
test('context handler: either failed direct Context-shell start rolls the session back', () => {
const failedBranch = handler.slice(
handler.indexOf("change?.type === 'visibility-failed'"),
handler.indexOf("change?.type === 'visibility-will-change'"),
);
assert.match(failedBranch, /change\.layerId === 'military-awareness' &&/);
assert.match(
failedBranch,
/_restoreContextSessionAfterLayerSettles\(\s*change\.layerId,\s*\{\s*notificationToken,?\s*\},?\s*\)/,
);
assert.match(failedBranch, /_runUserFacingContextAction/);
assert.match(failedBranch, /const failureMessage =/);
assert.match(
failedBranch,
/await this\._restoreContextSessionAfterLayerSettles\([\s\S]*?this\.showToast\(failureMessage\);\s*return true;/,
);
assert.match(failedBranch, /\},\s*failureMessage,?\s*\),?\s*\);/);
assert.match(failedBranch, /_trackContextLayerReaction\(/);
assert.match(
failedBranch,
/else if \(\s*!this\._userFacingContextNotificationTokens\.has\(change\.notificationToken\)\s*\)/,
);
const deferredRestore = _restoreContextSessionAfterLayerSettles.toString();
assert.match(deferredRestore, /await this\._dataManager\?\.waitForLayerSettled\?\.\(layerId\)/);
assert.match(deferredRestore, /return this\._restoreContextSession\(\{ notificationToken \}\)/);
assert.doesNotMatch(failedBranch, /excludeLayerIds/);
});
test('wrapped visibility blocks leave the accessible toast to the wrapper token owner', () => {
const blockedBranch = handler.slice(
handler.indexOf("change?.type === 'visibility-blocked'"),
handler.indexOf("change?.type === 'visibility-failed'"),
);
assert.match(
blockedBranch,
/!this\._userFacingContextNotificationTokens\.has\(change\.notificationToken\)/,
);
assert.match(blockedBranch, /this\.showToast\(/);
});
test('every user-facing Context exit route settles through the failure surface', () => {
const initPanel = _initGlobalContextPanel.toString();
assert.equal((initPanel.match(/void this\._runUserFacingContextAction/g) || []).length, 2);
assert.doesNotMatch(initPanel, /falseIsFailure:\s*false/);
assert.doesNotMatch(initPanel, /void this\._selectContextMode/);
const deactivationCalls = [...handler.matchAll(
/void this\._trackContextLayerReaction\(\s*this\._runUserFacingContextAction\(\(notificationToken\) =>\s*this\._deactivateContextForLayerChange\(\{ notificationToken \}\),?\s*\),?\s*\)/g,
)];
assert.equal(deactivationCalls.length, 3, 'dependency and primary layer exits share the caught restore path');
assert.doesNotMatch(handler, /void this\._deactivateContextForLayerChange\(\)/);
});
test('the Radio chip catches lifecycle rejection and semantic false through the toast wrapper', () => {
const radioControls = radioBindings.slice(
radioBindings.indexOf('const toggleRadio = async (trigger) => {'),
radioBindings.indexOf('this._storeToken = this.store?.connect?.('),
);
assert.match(radioControls, /await this\.actions\.runUserAction\(/);
assert.match(radioControls, /Radio could not \$\{enabling \? 'start' : 'stop'\} cleanly/);
assert.match(radioControls, /if \(this\.destroyed \|\| toggled === false\) return/);
});
test('only the expanded Radio Enable gesture requests the contained post-enable reveal', () => {
const radioControls = radioBindings.slice(
radioBindings.indexOf('const toggleRadio = async (trigger) => {'),
radioBindings.indexOf('this._storeToken = this.store?.connect?.('),
);
assert.match(radioControls, /revealAfterEnable = enabling && trigger === this\._radioEnableBtn/);
assert.match(radioControls, /if \(revealAfterEnable\)\s*await this\._revealRadioControlsAfterExplicitEnable\(trigger\)/);
assert.equal((radioBindings.match(/_revealRadioControlsAfterExplicitEnable\(trigger\)/g) || []).length, 1);
assert.match(radioControlsSource, /async _revealRadioControlsAfterExplicitEnable\(trigger\)/);
});
test('right-rail context entry is transactional: activation result gates the mode', () => {
const select = _selectContextMode.toString();
const activation = select.indexOf('activationIntent = this._dataManager._setEnabledWithIntent(');
assert.ok(activation > 0, 'activation result captured');
const failureBlock = select.slice(activation);
assert.match(failureBlock, /activated = await activationIntent\.promise/);
assert.match(failureBlock, /catch \(error\) \{\s*activationError = error;/);
assert.match(failureBlock, /await this\._dataManager\._waitForVisibilityIntent\?\.\(/);
assert.match(failureBlock, /activationError\s*\|\|\s*activated === false\s*\|\|\s*!this\._dataManager\.isEnabled\(entryLayerId\)/);
assert.match(failureBlock, /cancelledAndSettled\s*=\s*terminalIntentOutcome\?\.succeeded === false/);
assert.match(failureBlock, /\['caller-abort', 'resource-abort', 'superseded'\]/);
assert.match(failureBlock, /this\._contextMode = null/);
assert.match(failureBlock, /await this\._restoreContextSession\(\{[\s\S]*?excludeLayerIds: \[entryLayerId\],[\s\S]*?notificationToken/);
assert.match(failureBlock, /return cancelledAndSettled \? null : false/);
});
test('Context entry awaits isolation and direct shell routes isolate in the visibility guard', () => {
const select = _selectContextMode.toString();
assert.match(select, /await this\._clearLayersOutsideContextMode\(mode,\s*\{\s*notificationToken,\s*signal,?\s*\}\)/);
assert.match(select, /await this\._restoreContextSession\(\{ notificationToken, signal \}\)/);
assert.doesNotMatch(select, /void this\._clearLayersOutsideContextMode\(mode\)/);
// The cross-mode teardown restores UNCONDITIONALLY — an aborted caller must
// never skip it — and then stops. A cancelled or failed cross-mode switch
// rests on Context OFF; the honesty lives in the REPORT, not in a racy
// attempt to put the prior mode back (see the note above
// _restoreContextSessionAfterLayerSettles).
const capture = select.indexOf('this._captureContextSessionSnapshot(');
assert.ok(capture > 0, 'Context snapshot capture is missing');
const crossMode = select.slice(
select.indexOf('const crossModeSwitch = Boolean('),
capture,
);
assert.ok(crossMode, 'cross-mode teardown block is missing');
assert.doesNotMatch(crossMode, /if \(signal\?\.aborted\)[\s\S]*?await this\._restoreContextSession/);
assert.match(
crossMode,
/await this\._restoreContextSession\(\{ notificationToken, signal \}\);\s*if \(!isCurrent\(\)\) return false;\s*if \(signal\?\.aborted\) return false;/,
'an aborted cross-mode switch restores the baseline, then stops',
);
// No reinstatement anywhere: the transaction was removed deliberately, and a
// reintroduction has to come with its own interleaving story rather than
// reappearing quietly.
assert.doesNotMatch(src, /_reinstatePriorContextMode/);
assert.doesNotMatch(src, /reinstateContextMode/);
// The generation discipline that outlived the reinstatement: dispose still
// invalidates in-flight Context transactions so teardown cannot be raced into
// publishing a mode.
const dispose = src.slice(src.indexOf(' async dispose() {'), src.indexOf('this._stampNavigation();', src.indexOf(' async dispose() {')));
assert.match(dispose, /this\._contextControls\.stop\(\)/);
assert.match(ContextControls.prototype.stop.toString(), /this\._contextModeGeneration\+\+/);
const guard = connectContextManager.toString();
assert.match(guard, /change\.layerId !== 'military-awareness'/);
assert.match(guard, /const notificationToken\s*=\s*change\.notificationToken\s*\|\|\s*Symbol\('direct-context-shell-entry'\)/);
assert.match(guard, /this\._userFacingContextNotificationTokens\.add\(notificationToken\)/);
assert.match(guard, /await this\._clearLayersOutsideContextMode\(null,\s*\{\s*notificationToken,?\s*\}\)/);
assert.match(
guard,
/await this\._restoreContextSession\(\{\s*excludeLayerIds: \[change\.layerId\],\s*notificationToken,\s*\}\)/,
);
assert.match(guard, /this\._userFacingContextNotificationTokens\.delete\(\s*notificationToken,?\s*\)/);
});
test('a lost cross-mode switch says Context is off, and the state agrees', () => {
// The defect this replaced was the LIE, not the OFF: the transition reported
// a bare "did not complete" while the operator's Context was silently gone.
// Text and state are derived from the same verdict so they cannot disagree,
// and the failed layer ids survive (Manjunath's honesty requirement).
const setter = contextModeAction.toString();
assert.match(setter, /const priorMode = this\._contextMode;/, 'the report knows what was lost');
assert.match(
setter,
/const crossModeSwitchLost\s*=\s*transitioned !== true\s*&&\s*Boolean\(priorMode\)\s*&&\s*priorMode !== canonical\s*&&\s*!state\.mode;/,
'the verdict requires a real cross-mode switch that ended with no mode',
);
assert.match(
setter,
/error: crossModeSwitchLost\s*\? `Switch to \$\{contextModeWord\(canonical\)\} did not complete — Context is now off`/,
'a lost switch is reported in plain words, in the vocabulary the reader uses',
);
assert.match(setter, /\{ contextOff: true, priorMode \}/, 'and machine-readably');
assert.match(
setter,
/failedLayerIds: \[\.\.\.this\._contextTransitionFailedLayerIds\]/,
'failed layer ids are still exposed',
);
});
test('Context cancellation reaches isolation and restore lifecycle mutations', () => {
const clear = _clearLayersOutsideContextMode.toString();
assert.match(clear, /setEnabled\(layerId, false, \{[\s\S]*?signal/);
const restore = _restoreContextSession.toString();
assert.match(restore, /restoreEnabledLayerIds\([\s\S]*?signal/);
assert.match(restore, /setEnabled: \(layerId, enabled, options = \{\}\)[\s\S]*?signal/);
assert.match(restore, /error\.failedLayerIds = \[contactsCoordinatorId\]/);
assert.match(restore, /const restoreSnapshot = async \(restoreSignal = null\)/);
assert.match(restore, /signal\?\.aborted[\s\S]*?await restoreSnapshot\(null\)/);
assert.match(restore, /const replaySignal = signal\?\.aborted \? null : signal/);
assert.match(restore, /replaySignal \? \{ signal: replaySignal \} : \{\}/);
});
test('Context facade preserves success when cancellation arrives after commit', () => {
const setContextMode = contextModeAction.toString();
assert.match(
setContextMode,
/transitioned === null \|\| \(!requestIsCurrent\(\) && transitioned !== true\)/,
);
assert.match(
setContextMode,
/result === null \|\| \(!requestIsCurrent\(\) && result !== true\)/,
);
});
test('Context production rollback paths merge primary and restore failed-layer identities', () => {
const select = _selectContextMode.toString();
assert.equal(
(select.match(/mergeContextTransitionErrors\(\s*transitionError,\s*restoreError,?\s*\)/g) || []).length,
2,
);
assert.match(select, /transitionError\.failedLayerIds = \[\s*\.\.\.new Set\(\[/);
assert.match(select, /this\._contextTransitionFailedLayerIds = \[\s*\.\.\.\(transitionError\.failedLayerIds \|\| \[\]\),?\s*\]/);
});
test('stale Context cancellation preserves rollback failed-layer identities', () => {
const setContextMode = contextModeAction.toString();
assert.match(
setContextMode,
/if \(!requestIsCurrent\(\)\) \{[\s\S]*?\.\.\.cancellationResult\(\),[\s\S]*?failedLayerIds: \[\.\.\.error\.failedLayerIds\]/,
);
assert.match(
setContextMode,
/const cancellationResult = \(\) => \(\{[\s\S]*?_contextTransitionFailedLayerIds\?\.length[\s\S]*?failedLayerIds: \[\.\.\.this\._contextTransitionFailedLayerIds\]/,
);
});