Voice Cockpit entry no longer switches Contacts on (#1889)

* fix(voice): voice Cockpit entry no longer turns Contacts on

Voice entry now changes no Context mode or detection setting, as the COCKPIT
button does not. An entry that names a layer or class searches that layer's
own aircraft, nearest first from the followed aircraft or the ground under
the camera, and follows the nearest match before entering; the followed
aircraft counts when it matches. A military request while Military Flights
is off switches that layer on as a plain layer. The class filter is shared
with Contacts navigation.

* fix(voice): a military Cockpit entry waits for the layer's first data and leaves no layer behind

A military entry that switched Military Flights on waits for that layer to
report its first data before searching it, bounded by that update, the
layer failing or going off, and the request's cancellation. If entry then
fails, the layer is switched off again; a layer that was already on stays
on. The search covers only the aircraft the person's filters show.

* Add the changelog entry
This commit is contained in:
Sameh Khamis authored and GitHub committed 2026-11-20 22:01:03 -08:00
1 parent 5608b12a25
commit fbbe6cd91f
9 files changed
+568 -384

No files matched your search

@@ -0,0 +1,3 @@
- Voice Cockpit entry no longer switches Contacts on; a request for a class
such as a military helicopter finds the nearest matching aircraft itself
and switches on only the layer it needs (samehkhamis, #1889).
+11 -2
View File
@@ -9093,8 +9093,17 @@ apply to `public/` assets or built-preview serving.
ending, by its own switch or one of its layers going off, restores the
pre-Contacts layers but keeps the ridden one and the view; Live Signals then
drops the rows Contacts built and shows `CONTEXT STANDBY`. The visible
Cockpit actions, double-click and voice use the same gate; voice entry still
opens Contacts first, as its layer-targeted entry navigates through Contacts.
Cockpit actions, double-click and voice use the same gate. Voice entry, like
the COCKPIT button, never turns Contacts or detection on. A
voice entry that names a layer or class ("a military helicopter") searches
the aircraft that layer shows under the person's filters, nearest first,
from the followed aircraft or the ground under the camera, and follows the
nearest match (the followed aircraft counts when it matches) before it
enters (`_retargetCockpitEntryLayer` in `src/ui/cockpitCoordinator.js`). A
military request while Military Flights is off switches that layer on as a
plain layer the person can switch off, waits for its first data before
searching, and switches it off again if entry then fails; a layer that was
already on stays on. Contacts stays as it is.
The ship bridge and the orbital view have their own own-layer gates
(`bridgeEntryAllowed`, `orbitEntryAllowed`; see
[Ship bridge view](#ship-bridge-view) and [Orbital view](#orbital-view)).
+20 -6
View File
@@ -1165,7 +1165,10 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
mobileCockpit[1],
/@media \(min-width: 390px\) and \(min-height: 240px\),\s*\(min-height: 450px\) \{\s*body\.cockpit-mode\.mobile-shell/,
);
assert.match(css, /\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/);
assert.match(
css,
/\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/,
);
assert.match(
mobileCockpit[1],
/body\.cockpit-mode \.cockpit-utility-control\.is-expanded[\s\S]*?top:\s*96px;/,
@@ -1185,8 +1188,14 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
});
test('the unread Stories announcement waits until Cockpit closes', () => {
assert.match(css, /body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/);
const storiesView = fs.readFileSync(path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'), 'utf8');
assert.match(
css,
/body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/,
);
const storiesView = fs.readFileSync(
path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'),
'utf8',
);
assert.match(
storiesView,
/async function openExplore\(\) \{[^}]*?if \(await store\.controller\.open\(\)\) markPopSeen\(\);/,
@@ -1374,12 +1383,17 @@ test('voice Cockpit entry honours a requested contact layer before it enters', (
const retarget = ui.slice(
ui.indexOf(' _retargetCockpitEntryLayer({'),
ui.indexOf(' * Controls cockpit entry/exit and context navigation.'),
ui.indexOf(' controlCockpit(\n'),
);
assert.match(
retarget,
/militaryAwarenessLayer\.navigateNext\(\{\s*targetLayer,\s*aircraftClass,\s*origin: 'voice',\s*\}\)/,
'retargeting reuses filtered navigation with durable voice selection authority',
/layer\.trackById\?\.\(match\.icao24, \{ origin: 'voice' \}\)/,
'retargeting follows the match with durable voice selection authority',
);
assert.doesNotMatch(
retarget,
/militaryAwarenessLayer/,
'retargeting needs nothing from Contacts',
);
assert.match(
retarget,
+29
View File
@@ -14,6 +14,35 @@ export const AWARENESS_RELATIONSHIP = Object.freeze({
UNKNOWN: 'UNKNOWN',
});
/**
* Whether an aircraft matches a spoken class filter ("helicopter", "tanker"),
* on its class or type fields. No filter matches everything; an aircraft
* with no class or type matches no filter.
* @param {object} item Aircraft summary (`getNearby` row or cohort item).
* @param {string|null} aircraftClass Requested class.
* @returns {boolean}
*/
export function aircraftClassMatches(item, aircraftClass) {
const normalize = (value) =>
String(value || '')
.trim()
.toLowerCase();
const requested = normalize(aircraftClass);
if (!requested) return true;
return [
item?.aircraftClass,
item?.klass,
item?.type,
item?.typeCode,
item?.typeName,
]
.map(normalize)
.filter(Boolean)
.some(
(candidate) => candidate === requested || candidate.includes(requested),
);
}
/**
* Search an expanding area synchronously, doubling the radius after each miss.
* The maximum covers the farthest possible Earth-surface chord while keeping
+2 -24
View File
@@ -4,6 +4,7 @@ import {
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
findByDoublingRadius,
AWARENESS_RADIUS_M,
aircraftClassMatches,
} from '../../data/militaryAwarenessEngine.js';
import {
AWARENESS_MAX_EXAMPLES,
@@ -52,29 +53,7 @@ export function createNavigation({
return layerId === 'flights' || layerId === 'military';
}
function normalizeAircraftClass(value) {
return String(value || '')
.trim()
.toLowerCase();
}
function aircraftClassMatchesFilter(item, aircraftClass) {
const requested = normalizeAircraftClass(aircraftClass);
if (!requested) return true;
const candidates = [
item?.aircraftClass,
item?.klass,
item?.type,
item?.typeCode,
item?.typeName,
]
.map((value) => normalizeAircraftClass(value))
.filter(Boolean);
if (!candidates.length) return false;
return candidates.some(
(candidate) => candidate === requested || candidate.includes(requested),
);
}
const aircraftClassMatchesFilter = aircraftClassMatches;
function selectNavigationTargets(
sourceCohorts,
@@ -265,7 +244,6 @@ export function createNavigation({
summarizeAwarenessCohortForNavigation,
resetNavigationVisitedCycle,
isFlightLayer,
normalizeAircraftClass,
aircraftClassMatchesFilter,
selectNavigationTargets,
alternativeFlightAvailable,
+57 -8
View File
@@ -9,7 +9,13 @@ import {
subjectEntryAllowed,
} from '../contextModePolicy.js';
import { cockpitSubjectProviders } from '../cockpitSubjectProviders.js';
import { formatAwarenessLabel } from '../data/militaryAwarenessEngine.js';
import {
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
aircraftClassMatches,
formatAwarenessLabel,
} from '../data/militaryAwarenessEngine.js';
import { fromDegreesInto } from '../geo/ellipsoid.js';
import { findCamera } from '../render/rendererOf.js';
import { enterCockpitWithTracking } from '../cockpitTracking.js';
import { cockpitVisionModeForStyle } from '../cockpitVisionPolicy.js';
import { readEntityRecord } from '../data/entityRecords.js';
@@ -352,13 +358,41 @@ export class CockpitCoordinator {
};
}
/**
* Where a requested-layer entry searches from: the aircraft the camera
* follows, else the ground under the camera.
* @param {{layerId: string}|null} currentTarget The tracked aircraft.
* @returns {{x: number, y: number, z: number}|null}
*/
_cockpitEntrySearchOrigin(currentTarget) {
const { flightsLayer, militaryFlightsLayer } = this.services;
const layer =
currentTarget?.layerId === 'military'
? militaryFlightsLayer
: currentTarget?.layerId === 'flights'
? flightsLayer
: null;
const subject = layer?.getTrackedSubject?.();
if (subject?.position) return subject.position;
const pose = findCamera(this.viewer)?.pose?.();
if (!Number.isFinite(pose?.lat) || !Number.isFinite(pose?.lon)) return null;
return fromDegreesInto(pose.lon, pose.lat, 0, { x: 0, y: 0, z: 0 });
}
/**
* Retarget a voice entry to the requested layer and class before entering.
* It searches the aircraft that layer shows, under the person's own
* filters, nearest first, from the followed aircraft or the camera, and
* follows the nearest match; the aircraft already followed counts when it
* matches. It needs nothing from Contacts.
*/
_retargetCockpitEntryLayer({
targetLayer,
aircraftClass,
currentTarget,
selectedTarget,
}) {
const { militaryAwarenessLayer } = this.services;
const { flightsLayer, militaryFlightsLayer } = this.services;
if (!['flights', 'military'].includes(targetLayer)) {
return {
ok: false,
@@ -370,12 +404,27 @@ export class CockpitCoordinator {
const alreadyOnLayer = activeLayer === targetLayer;
if (alreadyOnLayer && !aircraftClass)
return { ok: true, retargeted: false };
const moved = militaryAwarenessLayer?.navigateNext
? !!militaryAwarenessLayer.navigateNext({
targetLayer,
aircraftClass,
origin: 'voice',
})
const layer =
targetLayer === 'military' ? militaryFlightsLayer : flightsLayer;
const origin = this._cockpitEntrySearchOrigin(currentTarget);
const nearby =
origin && typeof layer?.getNearby === 'function'
? layer.getNearby(
origin,
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
targetLayer === 'military' ? 5000 : 25000,
)
: [];
const match = nearby.find(
(item) => item?.icao24 && aircraftClassMatches(item, aircraftClass),
);
const followed =
match &&
currentTarget?.layerId === targetLayer &&
String(currentTarget.id) === String(match.icao24);
if (followed) return { ok: true, retargeted: false };
const moved = match
? !!layer.trackById?.(match.icao24, { origin: 'voice' })
: false;
if (moved) return { ok: true, retargeted: true };
// A filter that matched nothing still enters, as long as the layer is
+76
View File
@@ -869,3 +869,79 @@ test('a malformed provider is left out and the built-in kinds are unchanged', as
assert.equal(cockpit.enter(), true);
assert.equal(cockpit.subjectKind, 'aircraft');
});
// A requested-layer entry finds its aircraft in that layer, from the
// aircraft the camera follows; it never asks Contacts.
function retargetFixture(t, nearby) {
const { coordinator } = fixture(t, {
enabled: ['flights', 'military'],
tracked: { layerId: 'flights', info: CIVIL },
});
const tracked = [];
const searches = [];
coordinator.services.militaryAwarenessLayer.navigateNext = () =>
assert.fail('entry must not navigate through Contacts');
coordinator.services.flightsLayer.getTrackedSubject = () => ({
layerId: 'flights',
id: CIVIL.icao24,
position: { x: 1, y: 2, z: 3 },
});
coordinator.services.militaryFlightsLayer.getNearby = (...args) => {
searches.push(args);
return nearby;
};
coordinator.services.militaryFlightsLayer.trackById = (id, options) => {
tracked.push([id, options.origin]);
return true;
};
return { coordinator, tracked, searches };
}
test('a voice entry asking for a military class follows the nearest match without Contacts', (t) => {
const { coordinator, tracked, searches } = retargetFixture(t, [
{ icao24: 'jet1', aircraftClass: 'fighter', distance: 10 },
{ icao24: 'helo1', aircraftClass: 'helicopter', distance: 20 },
{ icao24: 'helo2', aircraftClass: 'helicopter', distance: 30 },
]);
const result = coordinator._retargetCockpitEntryLayer({
targetLayer: 'military',
aircraftClass: 'helicopter',
currentTarget: { layerId: 'flights', id: CIVIL.icao24 },
selectedTarget: null,
});
assert.deepEqual(result, { ok: true, retargeted: true });
assert.deepEqual(tracked, [['helo1', 'voice']]);
// Searched from the followed aircraft, among the aircraft the person's
// filters show: never the hidden ones.
assert.deepEqual(searches[0][0], { x: 1, y: 2, z: 3 });
assert.equal(searches[0][3], undefined);
});
test('a voice entry whose followed aircraft already matches stays on it', (t) => {
const { coordinator, tracked } = retargetFixture(t, [
{ icao24: 'helo1', aircraftClass: 'helicopter', distance: 0 },
]);
const result = coordinator._retargetCockpitEntryLayer({
targetLayer: 'military',
aircraftClass: 'helicopter',
currentTarget: { layerId: 'military', id: 'helo1' },
selectedTarget: null,
});
assert.deepEqual(result, { ok: true, retargeted: false });
assert.deepEqual(tracked, []);
});
test('a voice entry with no matching aircraft says so and follows nothing', (t) => {
const { coordinator, tracked } = retargetFixture(t, [
{ icao24: 'jet1', aircraftClass: 'fighter', distance: 10 },
]);
const result = coordinator._retargetCockpitEntryLayer({
targetLayer: 'military',
aircraftClass: 'helicopter',
currentTarget: { layerId: 'flights', id: CIVIL.icao24 },
selectedTarget: null,
});
assert.equal(result.ok, false);
assert.match(result.error, /No helicopter military contact is available/);
assert.deepEqual(tracked, []);
});
+103 -69
View File
@@ -1210,13 +1210,28 @@ export function createGevActionRunner({
args.type ||
args.filterType,
);
let contextChangedForEntry = false;
let priorContextMode = null;
let rollbackTarget = null;
if (
action === 'enter' &&
typeof styleManager.setContextMode === 'function'
) {
// Entry changes no Context mode, layer or detection setting, as the
// COCKPIT button does not. The one exception is a military entry while
// Military Flights is off: that layer is switched on as a plain layer
// the person can switch off, and switched off again if entry fails.
// Contacts stays as it is.
let rollbackTarget;
let switchedOn = null;
// A switch-off undoing this action's own switch-on; it runs even for a
// turn that went stale, so a failed entry leaves no layer behind.
const switchBackOff = async () => {
if (!switchedOn) return null;
return runGevAction(
'set_layer_visibility',
{ layerId: switchedOn, enabled: false },
{},
);
};
const failed = async (result) => {
const layerRollback = await switchBackOff();
return layerRollback ? { ...result, layerRollback } : result;
};
if (action === 'enter') {
if (!current()) {
return {
ok: false,
@@ -1227,51 +1242,37 @@ export function createGevActionRunner({
};
}
rollbackTarget = styleManager.getAircraftTrackingTarget?.() || null;
const contextState =
typeof styleManager.getContextModeState === 'function'
? styleManager.getContextModeState()
: {};
priorContextMode = contextState?.mode || null;
const contactsReady =
contextState?.mode === 'flights' &&
contextState?.active !== false &&
contextState?.changing !== true;
if (!contactsReady) {
const contextResult = await styleManager.setContextMode('flights', {
signal: runOptions.signal,
isCurrent: runOptions.isCurrent,
// Cockpit entry establishes Contacts as its own precondition. That
// is internal choreography, not an operator Context request, so it
// must stay inert: claiming here would cancel a pending shared
// style/detection restore the operator never overrode.
claimVisualAuthority: false,
});
contextChangedForEntry = contextResult?.ok === true;
if (contextResult?.ok !== true || !current()) {
const contextRollback = contextChangedForEntry
? await styleManager.setContextMode(priorContextMode, {
claimVisualAuthority: false,
})
: null;
return {
if (
targetLayer === 'military' &&
dataManager.layers?.has?.('military') &&
!dataManager.isEnabled?.('military')
) {
const layer = await runGevAction(
'set_layer_visibility',
{ layerId: 'military', enabled: true },
runOptions,
);
if (layer?.ok === true) switchedOn = 'military';
// The search needs the layer's aircraft, which arrive with its
// first data, not with the switch.
if (layer?.ok === true && current())
await waitForLayerFirstData(dataManager, 'military', runOptions);
if (layer?.ok !== true || !current()) {
return failed({
ok: false,
action: 'control_cockpit',
cancelled: !current() || Boolean(contextResult?.cancelled),
cancelled: !current() || Boolean(layer?.cancelled),
error:
contextResult?.error ||
'Contacts context could not be established for Cockpit entry',
context: contextResult
? withContextModeVocabulary(contextResult)
: null,
contextRollback: withContextModeVocabulary(contextRollback),
layer?.error ||
(layer?.ok === true
? 'Cockpit entry was cancelled before it could run'
: 'Military Flights could not be switched on'),
layer,
state: styleManager.getCockpitState?.() || null,
};
});
}
}
}
// Contacts activation can adopt a newer explicit aircraft selection.
// Sample only after that transaction settles so an older voice snapshot
// cannot overwrite the operator's newer choice.
const selectedTarget =
action === 'enter' ? selectedCockpitTarget(dataManager) : null;
let cockpitResult;
@@ -1291,30 +1292,7 @@ export function createGevActionRunner({
state: styleManager.getCockpitState?.() || null,
};
}
if (
action === 'enter' &&
cockpitResult?.ok !== true &&
contextChangedForEntry
) {
const contextRollback = await styleManager.setContextMode(
priorContextMode,
{
// Undoing this action's own precondition — still choreography.
claimVisualAuthority: false,
...(current()
? {
signal: runOptions.signal,
isCurrent: runOptions.isCurrent,
}
: {}),
},
);
return {
...cockpitResult,
contextRollback: withContextModeVocabulary(contextRollback),
};
}
return cockpitResult;
return cockpitResult?.ok === true ? cockpitResult : failed(cockpitResult);
}
if (name === 'show_data_layers_menu') {
@@ -2903,6 +2881,62 @@ export function formatTrackedEntityLabel(found, query = '') {
);
}
/**
* Wait for a layer just switched on to report its first data: its stats name
* an update, or its next update lands. Bounded by that update, the layer
* failing or going off, and the request's own cancellation.
* @returns {Promise<boolean>} Whether the layer has reported data.
*/
function waitForLayerFirstData(
dataManager,
layerId,
{ signal = null, isCurrent = null } = {},
) {
const reported = () => {
try {
const stats = dataManager.layers?.get?.(layerId)?.module?.getStats?.();
return stats?.lastUpdate != null;
} catch {
return false;
}
};
if (reported()) return Promise.resolve(true);
if (typeof dataManager.subscribeActivity !== 'function' || signal?.aborted)
return Promise.resolve(false);
return new Promise((resolve) => {
const offs = [];
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
for (const off of offs) off?.();
resolve(value);
};
const onAbort = () => done(false);
signal?.addEventListener?.('abort', onAbort, { once: true });
offs.push(() => signal?.removeEventListener?.('abort', onAbort));
offs.push(
dataManager.subscribeActivity((change) => {
if (
!dataManager.isEnabled?.(layerId) ||
(typeof isCurrent === 'function' && !isCurrent())
)
return done(false);
if (reported()) return done(true);
if (change?.type === 'data-updated' && change.layerId === layerId)
done(reported());
}),
);
offs.push(
dataManager.subscribe?.((change) => {
if (change?.layerId !== layerId) return;
if (change.type === 'refresh-failed' || change.enabled === false)
done(false);
}),
);
});
}
/** Finds and tracks/selects an entity by spoken query across layer families. */
async function trackEntity(
viewer,
+267 -275
View File
@@ -2974,7 +2974,7 @@ test('control_cockpit resolves spoken TR-3B spellings to the tr3b class id', asy
}
});
test('control_cockpit delegates selected-flight adoption to the canonical cockpit owner', async () => {
test('control_cockpit delegates selected-flight adoption to the canonical cockpit owner and leaves Context alone', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
@@ -2995,16 +2995,7 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi
changing: false,
};
},
async setContextMode(mode) {
calls.push({ action: 'context', mode });
contextActive = mode === 'flights';
return {
ok: contextActive,
mode,
active: contextActive,
changing: false,
};
},
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit(action, options) {
calls.push({ action, selectedTarget: options.selectedTarget });
return {
@@ -3040,7 +3031,6 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, true);
assert.deepEqual(calls, [
{ action: 'context', mode: 'flights' },
{
action: 'enter',
selectedTarget: { layerId: 'flights', id: 'abc123' },
@@ -3048,46 +3038,6 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi
]);
});
test('control_cockpit does not mutate selection when Contacts entry fails', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const styleManager = {
getContextModeState: () => ({ mode: null, active: false, changing: false }),
setContextMode: async () => ({
ok: false,
mode: null,
active: false,
changing: false,
error: 'Contacts activation failed',
}),
controlCockpit: () =>
assert.fail('Cockpit must not run after failed Contacts entry'),
getCockpitState: () => ({ active: false }),
};
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map(),
isEnabled: () => false,
getAll: () => [],
},
});
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, false);
assert.equal(result.error, 'Contacts activation failed');
assert.deepEqual(result.state, { active: false });
});
test('control_cockpit cancellation is inert when Contacts is already active', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
@@ -3134,77 +3084,7 @@ test('control_cockpit cancellation is inert when Contacts is already active', as
assert.deepEqual(result.state, { active: false });
});
test('control_cockpit rolls Contacts back when the turn becomes stale at commit', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const calls = [];
let requestCurrent = true;
let contextMode = null;
const styleManager = {
getContextModeState: () => ({
mode: contextMode,
active: Boolean(contextMode),
changing: false,
}),
async setContextMode(mode, options) {
calls.push({ mode, options: options || null });
contextMode = mode;
if (mode === 'flights') requestCurrent = false;
return { ok: true, mode, active: Boolean(mode), changing: false };
},
controlCockpit: () => assert.fail('stale turn must not enter Cockpit'),
getCockpitState: () => ({ active: false }),
};
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map(),
isEnabled: () => false,
getAll: () => [],
},
});
const result = await runner(
'control_cockpit',
{ action: 'enter' },
{
isCurrent: () => requestCurrent,
},
);
assert.equal(result.ok, false);
assert.equal(result.cancelled, true);
assert.equal(contextMode, null);
assert.deepEqual(
calls.map(({ mode }) => mode),
['flights', null],
);
assert.equal(
calls[1].options?.signal ?? null,
null,
'rollback must not inherit stale cancellation authority',
);
assert.equal(
calls[1].options?.isCurrent ?? null,
null,
'rollback must not inherit a stale currency probe',
);
assert.equal(
calls[1].options?.claimVisualAuthority,
false,
'rollback is cockpit choreography and must not claim the visual lane',
);
});
test('control_cockpit adopts the newest selection after Contacts settles', async () => {
test('control_cockpit enters on the current selection and keeps the prior track for rollback', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
@@ -3229,16 +3109,15 @@ test('control_cockpit adopts the newest selection after Contacts settles', async
);
contextStore.selectedEntityId = first.id;
contextStore.selectedAt = Date.now();
// A newer selection before the turn runs is the one entered.
contextStore.selectedEntityId = second.id;
contextStore.selectedAt = Date.now();
let receivedTarget = null;
let receivedRollbackTarget = null;
const styleManager = {
getAircraftTrackingTarget: () => ({ layerId: 'military', id: 'prior' }),
getContextModeState: () => ({ mode: null, active: false, changing: false }),
async setContextMode() {
contextStore.selectedEntityId = second.id;
contextStore.selectedAt = Date.now();
return { ok: true, mode: 'flights', active: true, changing: false };
},
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit(_action, options) {
receivedTarget = options.selectedTarget;
receivedRollbackTarget = options.rollbackTarget;
@@ -3277,25 +3156,16 @@ test('control_cockpit adopts the newest selection after Contacts settles', async
});
});
test('control_cockpit restores the prior Context mode after Cockpit entry fails', async () => {
test('a failed voice Cockpit entry leaves the Context mode as it was', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const calls = [];
let contextMode = null;
const styleManager = {
getContextModeState: () => ({
mode: contextMode,
active: Boolean(contextMode),
changing: false,
}),
async setContextMode(mode) {
contextMode = mode;
calls.push(`context:${mode || 'off'}`);
return { ok: true, mode, active: Boolean(mode), changing: false };
},
getContextModeState: () => ({ mode: null, active: false, changing: false }),
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit() {
calls.push('cockpit:enter');
return {
@@ -3322,31 +3192,21 @@ test('control_cockpit restores the prior Context mode after Cockpit entry fails'
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, false);
assert.deepEqual(calls, ['context:flights', 'cockpit:enter', 'context:off']);
assert.equal(contextMode, null);
assert.equal(result.contextRollback.ok, true);
assert.equal(result.error, 'Cockpit entry was unavailable');
assert.deepEqual(calls, ['cockpit:enter']);
assert.equal(result.contextRollback, undefined);
});
test('control_cockpit contains entry exceptions and still restores the prior Context mode', async () => {
test('control_cockpit contains entry exceptions and passes the prior track for rollback', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const calls = [];
let contextMode = null;
const styleManager = {
getAircraftTrackingTarget: () => ({ layerId: 'military', id: 'prior' }),
getContextModeState: () => ({
mode: contextMode,
active: Boolean(contextMode),
changing: false,
}),
async setContextMode(mode) {
contextMode = mode;
calls.push(`context:${mode || 'off'}`);
return { ok: true, mode, active: Boolean(mode), changing: false };
},
getContextModeState: () => ({ mode: null, active: false, changing: false }),
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit(_action, options) {
calls.push(['cockpit:enter', options.rollbackTarget]);
throw new Error('entry exploded');
@@ -3371,15 +3231,11 @@ test('control_cockpit contains entry exceptions and still restores the prior Con
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, false);
assert.equal(result.error, 'entry exploded');
assert.equal(result.contextRollback.ok, true);
assert.equal(contextMode, null);
assert.deepEqual(result.state, { active: false });
assert.deepEqual(calls, [
'context:flights',
['cockpit:enter', { layerId: 'military', id: 'prior' }],
'context:off',
]);
});
test('set_context_mode forwards cancellation authority and reports a stale turn', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
@@ -3538,11 +3394,7 @@ test('control_cockpit enter skips selected non-flight context', async () => {
active: contextActive,
changing: false,
}),
async setContextMode(mode) {
contextActive = mode === 'flights';
calls.push(`context:${mode}`);
return { ok: true, mode, active: true, changing: false };
},
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit(action) {
calls.push(`cockpit:${action}`);
return {
@@ -3577,7 +3429,7 @@ test('control_cockpit enter skips selected non-flight context', async () => {
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, true);
assert.deepEqual(calls, ['context:flights', 'cockpit:enter']);
assert.deepEqual(calls, ['cockpit:enter']);
});
test('voice CCTV select, next, prev, and nearest report tracking-refused flights after selection', async () => {
@@ -4543,6 +4395,66 @@ test('voice Radio Pause while disabled is a truthful playback-only no-op', async
// THE TWO APART, which a claim-count-only assertion cannot.
// ---------------------------------------------------------------------------
test('voice Cockpit entry, entered or failed, never changes the Context mode', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
for (const entered of [true, false]) {
const calls = [];
const styleManager = {
getContextModeState: () => ({
mode: null,
active: false,
changing: false,
}),
setPanelCollapsed() {},
setContextMode: async (mode) => {
calls.push(mode);
return { ok: true, mode, active: true };
},
controlCockpit: async () =>
entered
? { ok: true, action: 'control_cockpit', state: { active: true } }
: {
ok: false,
action: 'control_cockpit',
error: 'entry failed',
state: { active: false },
},
getCockpitState: () => ({ active: false }),
getAircraftTrackingTarget: () => null,
};
const layerCalls = [];
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map([
['flights', { module: {} }],
['military', { module: {} }],
]),
isEnabled: (layerId) => layerId === 'flights',
setEnabled: async (...args) => {
layerCalls.push(args);
return true;
},
getAll: () => [],
},
});
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, entered);
assert.deepEqual(calls, [], 'no Context mode change');
assert.deepEqual(layerCalls, [], 'no layer change');
}
});
function contextClaimProbe({
entrySucceeds = true,
cockpitSucceeds = true,
@@ -4591,48 +4503,6 @@ function contextClaimProbe({
return { runner, calls };
}
test('Cockpit entry establishes Contacts WITHOUT claiming the visual lane', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const probe = contextClaimProbe();
await probe.runner('control_cockpit', { action: 'enter' });
assert.ok(probe.calls.length >= 1, 'Cockpit entry must establish Contacts');
for (const call of probe.calls) {
assert.equal(
call.claimVisualAuthority,
false,
`cockpit choreography must not claim (mode=${call.mode})`,
);
}
});
test('Cockpit entry rollback also stays inert on the visual lane', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const probe = contextClaimProbe({ cockpitSucceeds: false });
await probe.runner('control_cockpit', { action: 'enter' });
// Establish + roll back: BOTH are this action's own choreography.
assert.ok(
probe.calls.length >= 2,
`expected an entry and a rollback, saw ${probe.calls.length}`,
);
for (const call of probe.calls) {
assert.equal(
call.claimVisualAuthority,
false,
`rollback must not claim (mode=${call.mode})`,
);
}
});
test('a genuine set_context_mode request DOES claim the visual lane', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
@@ -5083,71 +4953,6 @@ test('an absent secondary mode stays absent instead of claiming to be off', asyn
);
});
test('a nested Cockpit rollback result is translated too', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
// The prior mode is Contacts, whose INTERNAL id is 'flights' — the id that
// must not reach the model. `active: false` keeps Contacts from reading as
// ready, so entry runs and the failed Cockpit rolls back to it.
let contextMode = 'flights';
const styleManager = {
getContextModeState: () => ({
mode: contextMode,
active: false,
changing: false,
}),
getCockpitState: () => ({ active: false }),
getAircraftTrackingTarget: () => null,
async setContextMode(mode) {
// Entry to Contacts succeeds; Cockpit then fails and the prior mode is
// rolled back — the rollback result is what the model reads.
contextMode = mode;
return {
ok: true,
action: 'set_context_mode',
mode,
active: true,
changing: false,
};
},
controlCockpit: () => ({
ok: false,
error: 'Cockpit entry failed',
state: { active: false },
}),
};
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map(),
isEnabled: () => false,
getAll: () => [],
},
});
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, false);
assert.equal(
result.contextRollback?.mode,
'contacts',
'the rollback names the mode the tools name',
);
assert.equal(result.contextRollback?.modeInternal, 'flights');
assert.doesNotMatch(
JSON.stringify(result.contextRollback || {}),
/"mode":"flights"/,
'a nested rollback result must not leak the internal id either',
);
});
/**
* Front 5 (owner's live trial, 2026-08-22 01:42-01:44). Contacts was active
* with contact N546PC as its subject, a DATACENTER sat in the recency slot,
@@ -5294,7 +5099,6 @@ function analystRunner(awareness, { getAll } = {}) {
},
});
}
test('front5: a nearby ask centres on the Contacts SUBJECT, not the selected datacenter', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
@@ -8954,3 +8758,191 @@ test('show_street_level shows every photo it opens, also over a panel the user h
});
assert.deepEqual(missing.revealed, [], 'nothing opened, nothing revealed');
});
test('a military voice Cockpit entry switches Military Flights on as a plain layer, never Contacts', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
for (const militaryOn of [false, true]) {
const enabled = new Set(militaryOn ? ['flights', 'military'] : ['flights']);
const layerCalls = [];
const entries = [];
const styleManager = {
getContextModeState: () => ({
mode: null,
active: false,
changing: false,
}),
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
setDetection: () => assert.fail('Cockpit entry must not touch detection'),
controlCockpit(action, options) {
entries.push([action, options.targetLayer, options.aircraftClass]);
return { ok: true, action: 'control_cockpit', state: { active: true } };
},
getCockpitState: () => ({ active: false }),
getAircraftTrackingTarget: () => ({ layerId: 'flights', id: 'civil' }),
};
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map([
['flights', { module: {} }],
['military', { module: {} }],
]),
isEnabled: (layerId) => enabled.has(layerId),
async setEnabled(layerId, on, options) {
layerCalls.push([layerId, on, options.origin]);
if (on) enabled.add(layerId);
return true;
},
getAll: () => [],
},
});
const result = await runner('control_cockpit', {
action: 'enter',
targetLayer: 'military',
aircraftClass: 'helicopter',
});
assert.equal(result.ok, true, result.error);
assert.deepEqual(
layerCalls,
militaryOn ? [] : [['military', true, 'voice']],
'only a Military Flights layer that is off is switched on',
);
assert.deepEqual(entries, [['enter', 'military', 'helicopter']]);
}
});
// A data manager whose Military Flights layer is off, switches on empty and
// reports its first data only when the test lands it.
function militaryOffManager({ militaryOn = false } = {}) {
const enabled = new Set(militaryOn ? ['flights', 'military'] : ['flights']);
const activity = new Set();
const layerCalls = [];
let lastUpdate = militaryOn ? 1 : null;
const manager = {
layers: new Map([
['flights', { module: {} }],
['military', { module: { getStats: () => ({ lastUpdate }) } }],
]),
isEnabled: (layerId) => enabled.has(layerId),
async setEnabled(layerId, on, options) {
layerCalls.push([layerId, on, options.origin]);
if (on) enabled.add(layerId);
else enabled.delete(layerId);
return true;
},
subscribeActivity(callback) {
activity.add(callback);
return () => activity.delete(callback);
},
getAll: () => [],
};
return {
manager,
layerCalls,
enabled,
listening: () => activity.size,
landFirstData() {
lastUpdate = 2;
for (const callback of [...activity])
callback({ type: 'data-updated', layerId: 'military' });
},
};
}
function militaryEntryRunner(manager, controlCockpit) {
return createGevActionRunner({
viewer: {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
},
styleManager: {
getContextModeState: () => ({
mode: null,
active: false,
changing: false,
}),
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit,
getCockpitState: () => ({ active: false }),
getAircraftTrackingTarget: () => ({ layerId: 'flights', id: 'civil' }),
},
dataManager: manager,
});
}
test('a military voice entry waits for a just-switched-on layer to report its first data', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const fixture = militaryOffManager();
let searchedWithData = null;
const runner = militaryEntryRunner(fixture.manager, () => {
searchedWithData =
fixture.manager.layers.get('military').module.getStats().lastUpdate !==
null;
return { ok: true, action: 'control_cockpit', state: { active: true } };
});
const pending = runner('control_cockpit', {
action: 'enter',
targetLayer: 'military',
aircraftClass: 'helicopter',
});
for (let i = 0; i < 10; i++) await Promise.resolve();
assert.equal(searchedWithData, null, 'no search on an empty layer');
assert.equal(fixture.listening(), 1);
fixture.landFirstData();
const result = await pending;
assert.equal(result.ok, true, result.error);
assert.equal(searchedWithData, true);
assert.equal(fixture.listening(), 0, 'the wait lets go of the layer');
});
test('a failed military voice entry switches off only the layer it switched on', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
for (const militaryOn of [false, true]) {
const fixture = militaryOffManager({ militaryOn });
const runner = militaryEntryRunner(fixture.manager, () => ({
ok: false,
action: 'control_cockpit',
error: 'No helicopter military contact is available to enter',
state: { active: false },
}));
const pending = runner('control_cockpit', {
action: 'enter',
targetLayer: 'military',
aircraftClass: 'helicopter',
});
for (let i = 0; i < 10; i++) await Promise.resolve();
if (!militaryOn) fixture.landFirstData();
const result = await pending;
assert.equal(result.ok, false);
assert.match(result.error, /No helicopter military contact/);
assert.deepEqual(
fixture.layerCalls,
militaryOn
? []
: [
['military', true, 'voice'],
['military', false, 'voice'],
],
);
assert.equal(fixture.enabled.has('military'), militaryOn);
}
});