From 681ec84748f055051cb899bc876fe9dd6c520dfd Mon Sep 17 00:00:00 2001 From: daikaginza Date: Sat, 17 Oct 2026 07:32:38 +0700 Subject: [PATCH 01/54] fix(voice): show FIRMS and ALPR entity labels translated on the voice card MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pointer chip, its live-region line and the get_entity_context card title now translate the English entity labels the FIRMS and ALPR layers register ("Fire · FRP {frp} MW", "ALPR camera"). Other names, such as callsigns and place names, show as they came. --- src/voice/speech.js | 14 +++++++- src/voice/voiceCardLocale.test.mjs | 58 ++++++++++++++++++++++++++++-- src/voice/voiceCardPresentation.js | 11 ++++-- 3 files changed, 77 insertions(+), 6 deletions(-) diff --git a/src/voice/speech.js b/src/voice/speech.js index ab129aad3c..7118055027 100644 --- a/src/voice/speech.js +++ b/src/voice/speech.js @@ -115,6 +115,18 @@ function shownSources(source) { return source ? [{ label: sourceLabel(source) }] : []; } +// Entity labels that layers register as English data (firms/, alpr/); keep in +// step with the producers. Other names (callsigns, places) show as they came. +const ENTITY_LABELS = new Set([msg('ALPR camera')]); +const FIRE_LABEL = /^Fire · FRP (\S+) MW$/; + +/** An entity label as the card shows it, in the active language. */ +export function shownEntityLabel(label) { + if (ENTITY_LABELS.has(label)) return t(label); + const fire = FIRE_LABEL.exec(label ?? ''); + return fire ? t('Fire · FRP {frp} MW', { frp: fire[1] }) : label; +} + /* * Tool errors stay English in the result (the model reads them). The card * translates the known ones; the English must match gevActions exactly. @@ -592,7 +604,7 @@ function getEntityContext(result) { return { say: null, display: { - title, + title: spokenLabel(shownEntityLabel(title)), lines: [ selected.layerName ? shownLayerName(selected.layerName, selected.layerId) diff --git a/src/voice/voiceCardLocale.test.mjs b/src/voice/voiceCardLocale.test.mjs index 08274d21b5..9c70d91f97 100644 --- a/src/voice/voiceCardLocale.test.mjs +++ b/src/voice/voiceCardLocale.test.mjs @@ -3,8 +3,16 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { setLocale } from '../i18n/index.js'; -import { attachVoiceResult, planStepLabel } from './speech.js'; -import { voiceCardView } from './voiceCardPresentation.js'; +import { + attachVoiceResult, + planStepLabel, + shownEntityLabel, +} from './speech.js'; +import { + initialVoiceCardState, + reduceVoiceCard, + voiceCardView, +} from './voiceCardPresentation.js'; for (const locale of ['ru', 'es']) { test(`voice card is in ${locale} for a layer switch`, (t) => { @@ -86,3 +94,49 @@ test('en: layer switch, distance and plan labels in English', () => { 'Earthquakes (24h) on', ); }); + +// FIRMS and ALPR register English entity labels: the model reads them as data +// (get_entity_context, pointer_context), the card shows them translated. +const ENTITY_LABELS = { + ru: { fire: 'Пожар · FRP 12 МВт', alpr: 'Камера ALPR' }, + es: { fire: 'Incendio · FRP 12 MW', alpr: 'Cámara ALPR' }, +}; + +for (const [locale, shown] of Object.entries(ENTITY_LABELS)) { + test(`entity labels stay English in the result and show in ${locale}`, (t) => { + t.after(() => setLocale('en')); + setLocale(locale); + const out = attachVoiceResult('get_entity_context', { + ok: true, + selected: { + id: 'fire-1', + name: 'Fire · FRP 12 MW', + layerId: 'local-firms', + layerName: 'NASA FIRMS', + }, + }); + assert.equal(out.selected.name, 'Fire · FRP 12 MW'); + assert.equal(out.display.title, shown.fire); + + const state = reduceVoiceCard(initialVoiceCardState(), { + type: 'pointer', + pointer: { kind: 'this', label: 'ALPR camera' }, + }); + assert.equal(state.pointer.label, 'ALPR camera'); + assert.equal(voiceCardView(state).pointer.text, shown.alpr); + assert.equal(state.announce, `This: ${shown.alpr}`); + }); +} + +test('only the registered entity labels are translated', () => { + assert.equal(shownEntityLabel('Fire · FRP 4.9 MW'), 'Fire · FRP 4.9 MW'); + assert.equal(shownEntityLabel('ALPR camera'), 'ALPR camera'); + setLocale('ru'); + try { + assert.equal(shownEntityLabel('Fire · FRP 4.9 MW'), 'Пожар · FRP 4.9 МВт'); + assert.equal(shownEntityLabel('UPS793'), 'UPS793'); + assert.equal(shownEntityLabel('Fire Station 5'), 'Fire Station 5'); + } finally { + setLocale('en'); + } +}); diff --git a/src/voice/voiceCardPresentation.js b/src/voice/voiceCardPresentation.js index f8bf8ff7df..218241488a 100644 --- a/src/voice/voiceCardPresentation.js +++ b/src/voice/voiceCardPresentation.js @@ -1,4 +1,9 @@ -import { planStepLabel, progressStepLabel, spokenLabel } from './speech.js'; +import { + planStepLabel, + progressStepLabel, + shownEntityLabel, + spokenLabel, +} from './speech.js'; import { presentResult } from './resultDisplay.js'; import { MAX_DISPLAYED_REFERENTS, normalizeReferents } from './referents.js'; @@ -132,7 +137,7 @@ export function reduceVoiceCard(state, event) { return reveal({ ...state, pointer, - announce: `${kind}: ${spokenLabel(pointer.label, 32)}`, + announce: `${kind}: ${spokenLabel(shownEntityLabel(pointer.label), 32)}`, }); } case 'transcript': { @@ -288,7 +293,7 @@ export function voiceCardView(state) { pointer: { visible: Boolean(state.pointer), kind: state.pointer?.kind === 'here' ? t('HERE') : t('THIS'), - text: spokenLabel(state.pointer?.label || '', 32), + text: spokenLabel(shownEntityLabel(state.pointer?.label || ''), 32), }, assistant: { visible: Boolean(state.assistant), From cec5d99e13e1564813d05a6ed5694e428dd831e8 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Sat, 17 Oct 2026 07:32:38 +0700 Subject: [PATCH 02/54] fix(voice): keep FIRMS and ALPR entity labels English in voice data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fire and camera labels in the context store, getStrongestFire() and getSelectedInfo() were translated at the source, so the voice model got "Пожар · FRP 12 МВт" or "Cámara ALPR" in track_entity, get_entity_context and pointer_context while every other entity name in those payloads is English. Keep them English, as before the interface was translated; the voice card translates them where it shows them. --- src/data/alprCameras.test.mjs | 20 ++++++++++++++++++++ src/data/firmsInteraction.test.mjs | 18 ++++++++++++++++++ src/layers/alpr/presentation.js | 4 ++-- src/layers/firms/queries.js | 10 ++++------ src/layers/firms/selection.js | 5 ++--- 5 files changed, 46 insertions(+), 11 deletions(-) diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index 5a50220d54..71ee6d6755 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -9,6 +9,7 @@ import alprCamerasLayer, { } from './alprCameras.js'; import { createAlprTileSource } from '../layers/alpr/source.js'; import { DATA_CREDITS } from './dataCredits.js'; +import { setLocale } from '../i18n/index.js'; import { clearSelectedEntityContextForLayer, getContextStore, @@ -473,6 +474,25 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a } }); +// The voice model reads the label as data; the voice card translates it. +test('the camera label stays English data in a translated interface', async () => { + const h = cameraHarness(); + setLocale('ru'); + try { + h.setFetch(async () => + cameraResponse([ + cameraNode(42, { tags: { 'surveillance:type': 'ALPR' } }), + ]), + ); + await alprCamerasLayer.update(); + h.click(h.source.entities.values[0].id); + assert.equal(getSelectedEntityContext().label, 'ALPR camera'); + } finally { + setLocale('en'); + h.restore(); + } +}); + test('invalid OSM ids and out-of-range coordinates never become camera entities', () => { for (const id of [undefined, null, 0, -1, 1.5, '42', NaN]) assert.equal(normalizeAlprNode(cameraNode(id, { id })), null); diff --git a/src/data/firmsInteraction.test.mjs b/src/data/firmsInteraction.test.mjs index 442af60b2c..cde867f87d 100644 --- a/src/data/firmsInteraction.test.mjs +++ b/src/data/firmsInteraction.test.mjs @@ -8,6 +8,8 @@ import * as Cesium from 'cesium'; import { createFirmsHeatmapLayer, applyFirmsOverlayPolicy, buildCellCard } from './firmsHeatmap.js'; import { fireDetectionKey } from './firmsLabels.js'; import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js'; +import { getSelectedEntityContext } from './contextStore.js'; +import { setLocale } from '../i18n/index.js'; import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js'; import { readLayerSource } from '../testSupport/readLayerSource.mjs'; import path from 'node:path'; @@ -234,6 +236,22 @@ test('clicking a fire CARD behaves exactly like clicking its sprite', () => { } }); +// The voice model reads these labels as data (track_entity, get_entity_context, +// pointer_context); the voice card translates them where it shows them. +test('fire labels stay English data in a translated interface', () => { + setLocale('ru'); + const h = harness({ fires: [makeFire()], picked: { id: 'firms-7' } }); + try { + h.click(); + assert.equal(getSelectedEntityContext().label, 'Fire · FRP 1520 MW'); + assert.equal(h.layer.getSelectedInfo().label, 'Fire · FRP 1520 MW'); + assert.equal(h.layer.getStrongestFire().label, 'Fire · FRP 1520 MW'); + } finally { + h.cleanup(); + setLocale('en'); + } +}); + test('a click on neither sprite nor card clears without moving the camera', () => { const h = harness({ picked: { primitive: {}, content: {}, featureId: 0 } }); try { diff --git a/src/layers/alpr/presentation.js b/src/layers/alpr/presentation.js index 866f15a6da..c7343d5738 100644 --- a/src/layers/alpr/presentation.js +++ b/src/layers/alpr/presentation.js @@ -13,7 +13,7 @@ import { MARKER_SCALE_BY_DISTANCE, } from './policy.js'; import { boxContains } from './model.js'; -import { t } from '../../i18n/index.js'; +import { msg } from '../../i18n/index.js'; import { createAlprFloorResolver } from './floors.js'; import { createAlprOverlay } from './overlay.js'; import { @@ -452,7 +452,7 @@ export function createAlprPresentation({ state, services, source }) { layerName: 'ALPR Cameras', source: source.attribution?.description || source.label || 'Camera source', - label: t('ALPR camera'), + label: msg('ALPR camera'), latitude: record.latitude, longitude: record.longitude, properties: { diff --git a/src/layers/firms/queries.js b/src/layers/firms/queries.js index a7d22589e8..16ca01166f 100644 --- a/src/layers/firms/queries.js +++ b/src/layers/firms/queries.js @@ -18,9 +18,8 @@ export function createQueries({ if (!fire) return null; return { id: fireDetectionKey(fire), - label: t('Fire · FRP {frp} MW', { - frp: components.model.formatFrp(fire.frp), - }), + // i18n-ignore: English entity label; the voice card translates it (shownEntityLabel) + label: `Fire · FRP ${components.model.formatFrp(fire.frp)} MW`, latitude: fire.lat, longitude: fire.lon, frp: fire.frp, @@ -117,9 +116,8 @@ export function createQueries({ latitude: strongest.lat, longitude: strongest.lon, frp: strongest.frp, - label: t('Fire · FRP {frp} MW', { - frp: components.model.formatFrp(strongest.frp), - }), + // i18n-ignore: English entity label; the voice card translates it (shownEntityLabel) + label: `Fire · FRP ${components.model.formatFrp(strongest.frp)} MW`, }; }, diff --git a/src/layers/firms/selection.js b/src/layers/firms/selection.js index fc05eea2ad..d5cfc4d26b 100644 --- a/src/layers/firms/selection.js +++ b/src/layers/firms/selection.js @@ -193,9 +193,8 @@ export function createSelection({ layerName: name, source: 'NASA FIRMS', dataSource: layerState._dataSource, - label: t('Fire · FRP {frp} MW', { - frp: components.model.formatFrp(fire.frp), - }), + // i18n-ignore: English entity label; the voice card translates it (shownEntityLabel) + label: `Fire · FRP ${components.model.formatFrp(fire.frp)} MW`, latitude: fire.lat, longitude: fire.lon, properties: { From 9011918731b4a3d2444c7c11e1a472195dce1035 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Sun, 18 Oct 2026 14:35:07 +0700 Subject: [PATCH 03/54] docs(changelog): add the #1207 entry --- changelog.d/1207-voice-entity-labels-english.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1207-voice-entity-labels-english.md diff --git a/changelog.d/1207-voice-entity-labels-english.md b/changelog.d/1207-voice-entity-labels-english.md new file mode 100644 index 0000000000..b69cdc7ed1 --- /dev/null +++ b/changelog.d/1207-voice-entity-labels-english.md @@ -0,0 +1,3 @@ +- Keep NASA FIRMS fire and ALPR camera labels English in voice tool results + (`track_entity`, `get_entity_context`, pointer context); the voice card still + shows them in the interface language (daikaginza, #1207). From 843c8b1a6bba03073b58e9a00e60467891827a4b Mon Sep 17 00:00:00 2001 From: daikaginza Date: Sun, 18 Oct 2026 15:22:31 +0700 Subject: [PATCH 04/54] test(i18n): feed real FIRMS and ALPR labels through the voice card The card's fire pattern is written by hand against the producers' template, so a format change upstream would silently show English. Both locale tests now pass the label the layer actually produced through shownEntityLabel() under ru, and set the locale inside the try that resets it. --- src/data/alprCameras.test.mjs | 7 ++++++- src/data/firmsInteraction.test.mjs | 8 +++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index 71ee6d6755..549adde96d 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -10,6 +10,7 @@ import alprCamerasLayer, { import { createAlprTileSource } from '../layers/alpr/source.js'; import { DATA_CREDITS } from './dataCredits.js'; import { setLocale } from '../i18n/index.js'; +import { shownEntityLabel } from '../voice/speech.js'; import { clearSelectedEntityContextForLayer, getContextStore, @@ -477,8 +478,8 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a // The voice model reads the label as data; the voice card translates it. test('the camera label stays English data in a translated interface', async () => { const h = cameraHarness(); - setLocale('ru'); try { + setLocale('ru'); h.setFetch(async () => cameraResponse([ cameraNode(42, { tags: { 'surveillance:type': 'ALPR' } }), @@ -487,6 +488,10 @@ test('the camera label stays English data in a translated interface', async () = await alprCamerasLayer.update(); h.click(h.source.entities.values[0].id); assert.equal(getSelectedEntityContext().label, 'ALPR camera'); + assert.equal( + shownEntityLabel(getSelectedEntityContext().label), + 'Камера ALPR', + ); } finally { setLocale('en'); h.restore(); diff --git a/src/data/firmsInteraction.test.mjs b/src/data/firmsInteraction.test.mjs index cde867f87d..d735df3f86 100644 --- a/src/data/firmsInteraction.test.mjs +++ b/src/data/firmsInteraction.test.mjs @@ -10,6 +10,7 @@ import { fireDetectionKey } from './firmsLabels.js'; import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js'; import { getSelectedEntityContext } from './contextStore.js'; import { setLocale } from '../i18n/index.js'; +import { shownEntityLabel } from '../voice/speech.js'; import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js'; import { readLayerSource } from '../testSupport/readLayerSource.mjs'; import path from 'node:path'; @@ -239,11 +240,16 @@ test('clicking a fire CARD behaves exactly like clicking its sprite', () => { // The voice model reads these labels as data (track_entity, get_entity_context, // pointer_context); the voice card translates them where it shows them. test('fire labels stay English data in a translated interface', () => { - setLocale('ru'); const h = harness({ fires: [makeFire()], picked: { id: 'firms-7' } }); try { + setLocale('ru'); h.click(); assert.equal(getSelectedEntityContext().label, 'Fire · FRP 1520 MW'); + // The card's pattern must match what the producer actually writes. + assert.equal( + shownEntityLabel(getSelectedEntityContext().label), + 'Пожар · FRP 1520 МВт', + ); assert.equal(h.layer.getSelectedInfo().label, 'Fire · FRP 1520 MW'); assert.equal(h.layer.getStrongestFire().label, 'Fire · FRP 1520 MW'); } finally { From 2379d20616a988924924e0500079de7b3dc9966b Mon Sep 17 00:00:00 2001 From: blowing-a-raspberry <120271497+blowing-a-raspberry@users.noreply.github.com> Date: Tue, 6 Oct 2026 14:01:48 -0500 Subject: [PATCH 05/54] Harden Vite fs deny for local logs and cache --- build/vite.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/build/vite.js b/build/vite.js index 4f2703e880..00479572d9 100644 --- a/build/vite.js +++ b/build/vite.js @@ -94,7 +94,16 @@ export function createBrowserViteConfig({ // build/allowedHosts.js); IP addresses are always accepted. allowedHosts: [...allowedHosts], fs: { - deny: ['.env', '.env.*', '*.{crt,pem}', '**/.git/**', '**/ENVIRONMENT'], + deny: [ + '.env', + '.env.*', + '*.{crt,pem}', + '**/.git/**', + '**/ENVIRONMENT', + '**/.gev-logs/**', + '**/.gev-cache/**', + '**/dist/**', + ], }, // These headers protect the document containing Provider Settings and // give the whole page a real Content-Security-Policy (BROWSER_CSP). From ccb7b7333d3e13f0bda8fdea45706e49a37ca705 Mon Sep 17 00:00:00 2001 From: blowing-a-raspberry <120271497+blowing-a-raspberry@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:55:37 -0500 Subject: [PATCH 06/54] fix: scope Vite dist deny to repository root --- build/vite.js | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/build/vite.js b/build/vite.js index 00479572d9..f390e359e2 100644 --- a/build/vite.js +++ b/build/vite.js @@ -1,9 +1,23 @@ +import { fileURLToPath } from 'node:url'; import { applicationHtmlPlugin } from './application-html.js'; import cesium from 'vite-plugin-cesium'; import { DEFAULT_ALLOWED_HOSTS, hostCheckPlugin } from './allowedHosts.js'; import { embedFramingPlugin } from './embed-framing.js'; import { panelBuildPlugin } from './panel.js'; +/** + * The repository root (this file lives at `/build/vite.js`), as a + * forward-slash path for glob matching. Vite's `fs.deny` patterns are + * matched against the full absolute file path, and a bare `**\/dist/**` + * matches a `dist` directory at *any* depth — including dependencies that + * ship their own, such as `node_modules/vite/dist/client/client.mjs` (the + * dev client itself). Anchoring to this repository's root denies only the + * project's own build output. + */ +const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url)) + .replace(/\\/g, '/') + .replace(/\/$/, ''); + /** * Content-Security-Policy for every document the dev/preview server serves. * No inline script is permitted, and the only foreign script origins are the @@ -102,7 +116,10 @@ export function createBrowserViteConfig({ '**/ENVIRONMENT', '**/.gev-logs/**', '**/.gev-cache/**', - '**/dist/**', + // Root-anchored: a bare '**/dist/**' would also deny every + // dependency's own dist/ (e.g. node_modules/vite/dist/client), + // breaking /@vite/client and other dev-client assets. + `${REPO_ROOT}/dist/**`, ], }, // These headers protect the document containing Provider Settings and From 509ab57e4b1136232198e7bbac8f43cb09194061 Mon Sep 17 00:00:00 2001 From: Blowing Raspberries <120271497+blowing-a-raspberry@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:52:27 -0500 Subject: [PATCH 07/54] fix: escape repo root in Vite deny glob --- build/vite.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/vite.js b/build/vite.js index f390e359e2..05d8e5fa6e 100644 --- a/build/vite.js +++ b/build/vite.js @@ -119,7 +119,7 @@ export function createBrowserViteConfig({ // Root-anchored: a bare '**/dist/**' would also deny every // dependency's own dist/ (e.g. node_modules/vite/dist/client), // breaking /@vite/client and other dev-client assets. - `${REPO_ROOT}/dist/**`, + `${REPO_ROOT_GLOB}/dist/**`, ], }, // These headers protect the document containing Provider Settings and From 0c1bb5a71b680fca09ff19fd133c81e18f4a51c1 Mon Sep 17 00:00:00 2001 From: Blowing Raspberries <120271497+blowing-a-raspberry@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:52:35 -0500 Subject: [PATCH 08/54] docs: note Vite fs deny hardening ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ .git/COMMIT_EDITMSG [unix] (16:23 16/10/2026) 1,1 All"/d/AI-Lab/Repos/gods-eye-view/.git/COMMIT_EDITMSG" [unix] 19L, 662B docs: note Vite fs deny hardening --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98d32365f1..2c7445ce69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -445,6 +445,7 @@ `ET-Client-Name: gods-eye-view-bikeshare` to Entur, as the operators ask, and accepts Entur's extensionless feed paths. Attributed under NLOD and Licence Ouverte. `get_bike_share` covers the six systems too. +- Harden Vite's filesystem deny list for local-only artifacts: repo `dist/`, `.gev-logs/`, and `.gev-cache/` are denied without blocking dependency `dist/` directories, and checkout paths containing glob metacharacters are escaped before building the root-anchored pattern. - Add Norway's road cameras from Statens vegvesen as a CCTV pack. The camera list is one keyless GeoJSON request to the agency's OGC API view of its From 1b641fde9f34462d508fc4520d4de21c642f8516 Mon Sep 17 00:00:00 2001 From: blowing-a-raspberry <120271497+blowing-a-raspberry@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:55:48 -0500 Subject: [PATCH 09/54] fix: restore escaped repo root after rebase --- build/vite.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/build/vite.js b/build/vite.js index 05d8e5fa6e..042b8e98da 100644 --- a/build/vite.js +++ b/build/vite.js @@ -18,6 +18,8 @@ const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url)) .replace(/\\/g, '/') .replace(/\/$/, ''); +const REPO_ROOT_GLOB = REPO_ROOT.replace(/[()[\]{}*?!+@|]/g, '\\$&'); + /** * Content-Security-Policy for every document the dev/preview server serves. * No inline script is permitted, and the only foreign script origins are the From e3e4fc7284fcc59716f888bee6cc64dd07089ac5 Mon Sep 17 00:00:00 2001 From: blowing-a-raspberry <120271497+blowing-a-raspberry@users.noreply.github.com> Date: Sun, 18 Oct 2026 15:55:56 -0500 Subject: [PATCH 10/54] test: cover Vite fs deny hardening --- CHANGELOG.md | 1 - build/vite.js | 6 +++++- changelog.d/948-vite-fs-deny.md | 4 ++++ src/tooling/viteBuild.test.mjs | 15 ++++++++++++++- 4 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 changelog.d/948-vite-fs-deny.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c7445ce69..98d32365f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -445,7 +445,6 @@ `ET-Client-Name: gods-eye-view-bikeshare` to Entur, as the operators ask, and accepts Entur's extensionless feed paths. Attributed under NLOD and Licence Ouverte. `get_bike_share` covers the six systems too. -- Harden Vite's filesystem deny list for local-only artifacts: repo `dist/`, `.gev-logs/`, and `.gev-cache/` are denied without blocking dependency `dist/` directories, and checkout paths containing glob metacharacters are escaped before building the root-anchored pattern. - Add Norway's road cameras from Statens vegvesen as a CCTV pack. The camera list is one keyless GeoJSON request to the agency's OGC API view of its diff --git a/build/vite.js b/build/vite.js index 042b8e98da..a541eb9aa2 100644 --- a/build/vite.js +++ b/build/vite.js @@ -18,7 +18,11 @@ const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url)) .replace(/\\/g, '/') .replace(/\/$/, ''); -const REPO_ROOT_GLOB = REPO_ROOT.replace(/[()[\]{}*?!+@|]/g, '\\$&'); +export function escapeFsDenyPath(path) { + return path.replace(/[()[\]{}*?!+@|]/g, '\\$&'); +} + +const REPO_ROOT_GLOB = escapeFsDenyPath(REPO_ROOT); /** * Content-Security-Policy for every document the dev/preview server serves. diff --git a/changelog.d/948-vite-fs-deny.md b/changelog.d/948-vite-fs-deny.md new file mode 100644 index 0000000000..642bafb1f7 --- /dev/null +++ b/changelog.d/948-vite-fs-deny.md @@ -0,0 +1,4 @@ +- Harden Vite's filesystem deny list for local-only artifacts: repo `dist/`, + `.gev-logs/`, and `.gev-cache/` are denied without blocking dependency + `dist/` directories, and checkout paths containing glob metacharacters are + escaped before building the root-anchored pattern (blowing-a-raspberry, #948). diff --git a/src/tooling/viteBuild.test.mjs b/src/tooling/viteBuild.test.mjs index 9e38a02950..9f309c48da 100644 --- a/src/tooling/viteBuild.test.mjs +++ b/src/tooling/viteBuild.test.mjs @@ -1,7 +1,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; -import { BROWSER_CSP, createBrowserViteConfig } from '../../build/vite.js'; +import { + BROWSER_CSP, + createBrowserViteConfig, + escapeFsDenyPath, +} from '../../build/vite.js'; import standaloneConfig, * as compatibility from '../../vite.config.js'; import * as providers from '../../server/providers/local.js'; @@ -21,6 +25,15 @@ test('explicit build inputs preserve browser-only defines, plugin order and loop assert.deepEqual(config.server.allowedHosts, ['localhost', '127.0.0.1']); assert.ok(config.server.fs.deny.includes('**/ENVIRONMENT')); assert.ok(config.server.fs.deny.includes('.env.*')); + assert.ok(config.server.fs.deny.includes('**/.gev-logs/**')); + assert.ok(config.server.fs.deny.includes('**/.gev-cache/**')); + assert.ok( + config.server.fs.deny.some((pattern) => pattern.endsWith('/dist/**')), + ); + assert.equal( + escapeFsDenyPath('C:/Users/a/gods-eye-view (1)'), + 'C:/Users/a/gods-eye-view \\(1\\)', + ); assert.equal(config.server.headers['X-Frame-Options'], 'DENY'); assert.equal(config.server.headers['X-Content-Type-Options'], 'nosniff'); const csp = config.server.headers['Content-Security-Policy']; From d2c80cffdb6d8a25d6c271e6548df57d0c957c8e Mon Sep 17 00:00:00 2001 From: Bortlesboat <169967362+Bortlesboat@users.noreply.github.com> Date: Sun, 18 Oct 2026 23:57:29 -0400 Subject: [PATCH 11/54] fix(gbfs): exclude stations with invalid coordinates Reject non-numeric and out-of-range feed coordinates before they reach the map or bike-share queries. Preserve numeric strings, aliases and zero. Cover malformed records at the parser and public query boundaries. Signed-off-by: Bortlesboat <169967362+Bortlesboat@users.noreply.github.com> --- changelog.d/0-gbfs-invalid-coordinates.md | 3 + docs/CURRENT-STATE.md | 6 +- src/sources/gbfsStations.js | 20 ++++++- src/sources/gbfsStations.test.mjs | 67 +++++++++++++++++++++++ src/tools/queries/mobility.test.mjs | 40 ++++++++++++++ 5 files changed, 132 insertions(+), 4 deletions(-) create mode 100644 changelog.d/0-gbfs-invalid-coordinates.md diff --git a/changelog.d/0-gbfs-invalid-coordinates.md b/changelog.d/0-gbfs-invalid-coordinates.md new file mode 100644 index 0000000000..ed1f0824e7 --- /dev/null +++ b/changelog.d/0-gbfs-invalid-coordinates.md @@ -0,0 +1,3 @@ +- Skip bike-share stations with missing, blank or invalid coordinates instead + of placing them at coerced zero coordinates or accepting out-of-range values. + Explicit zero coordinates and numeric strings remain supported (Bortlesboat, #0). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 9562dc9f5a..8aedf558a9 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1265,7 +1265,11 @@ camera is refused there with a JSON 404 and is served solely through ## GBFS upstream bounds Station information is normalized in `src/sources/gbfsStations.js` for both the -globe layer and `get_bike_share`. Names accept legacy strings or GBFS v3 Localized +globe layer and `get_bike_share`. Stations with missing, blank, nonnumeric or +out-of-range coordinates (latitude outside ±90, longitude outside ±180) are +skipped. Numbers and nonblank numeric strings are accepted, including genuine +zero and the `latitude`/`longitude` aliases; other JSON types are rejected. +Names accept legacy strings or GBFS v3 Localized String arrays regardless of the reported feed version. Nonempty English text (including regional `en-*` tags, case-insensitive) takes precedence, then the first usable translation. An unusable `name` falls back to `short_name` with the same diff --git a/src/sources/gbfsStations.js b/src/sources/gbfsStations.js index c37c2fae4d..c942579dbd 100644 --- a/src/sources/gbfsStations.js +++ b/src/sources/gbfsStations.js @@ -98,6 +98,13 @@ function dockCapacity(raw) { return capacity - geofenced; } +/** Read a numeric coordinate without treating blank text or other JSON types as zero. */ +function coordinateNumber(value) { + if (typeof value !== 'number' && (typeof value !== 'string' || !value.trim())) + return NaN; + return Number(value); +} + /** * Parse a GBFS station_information payload into a Map of station metadata. * Handles field-name variations across different GBFS providers @@ -113,9 +120,16 @@ export function parseStationInformation(payload) { for (const raw of stations) { // Accept both GBFS (station_id) and alternate (id) field names const stationId = String(raw?.station_id ?? raw?.id ?? '').trim(); - const lat = Number(raw?.lat ?? raw?.latitude); - const lon = Number(raw?.lon ?? raw?.longitude); - if (!stationId || !Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const lat = coordinateNumber(raw?.lat ?? raw?.latitude); + const lon = coordinateNumber(raw?.lon ?? raw?.longitude); + if ( + !stationId || + !Number.isFinite(lat) || + !Number.isFinite(lon) || + Math.abs(lat) > 90 || + Math.abs(lon) > 180 + ) + continue; stationMap.set(stationId, { stationId, diff --git a/src/sources/gbfsStations.test.mjs b/src/sources/gbfsStations.test.mjs index 91983df981..1ab2735564 100644 --- a/src/sources/gbfsStations.test.mjs +++ b/src/sources/gbfsStations.test.mjs @@ -19,6 +19,73 @@ const parseCapacity = (fields) => parseStationInformation({ data: { stations: [station(fields)] } }).get('s1') .capacity; +test('station information skips missing, blank and malformed coordinates', () => { + for (const field of ['lat', 'lon', 'latitude', 'longitude']) { + for (const value of [ + undefined, + null, + '', + ' \t ', + false, + true, + [], + [0], + {}, + 'bad', + NaN, + Infinity, + ]) { + const raw = { station_id: 'bad', lat: 0, lon: 0 }; + if (field === 'latitude') delete raw.lat; + if (field === 'longitude') delete raw.lon; + raw[field] = value; + const parsed = parseStationInformation({ + data: { stations: [raw, station({ station_id: 'good' })] }, + }); + assert.deepEqual( + [...parsed.keys()], + ['good'], + `${field} = ${JSON.stringify(value)}`, + ); + } + } +}); + +test('station information skips coordinates outside latitude and longitude bounds', () => { + for (const fields of [ + { lat: 90.001 }, + { lat: -90.001 }, + { lon: 180.001 }, + { lon: -180.001 }, + { lat: undefined, latitude: '91' }, + { lon: undefined, longitude: '-181' }, + ]) { + const parsed = parseStationInformation({ + data: { stations: [station(fields)] }, + }); + assert.equal(parsed.size, 0, JSON.stringify(fields)); + } +}); + +test('station information preserves zero, boundary coordinates and numeric aliases', () => { + for (const [fields, expected] of [ + [{ lat: 0, lon: 0 }, [0, 0]], + [{ lat: ' 0 ', lon: '0' }, [0, 0]], + [{ lat: 90, lon: 180 }, [90, 180]], + [{ lat: '-90', lon: '-180' }, [-90, -180]], + [ + { lat: null, lon: undefined, latitude: '30.2681', longitude: '-97.7469' }, + [30.2681, -97.7469], + ], + ]) { + const parsed = parseStationInformation({ + data: { stations: [station(fields)] }, + }).get('s1'); + assert.ok(parsed, JSON.stringify(fields)); + assert.deepEqual([parsed.lat, parsed.lon], expected); + } +}); + test('capacity counts docks, not the geofenced area PBSC adds to it', () => { // Bilbao Bizi, BiciMAD and Dbizi as published on 2026-10-17. assert.equal(parseCapacity({ capacity: 839, geofenced_capacity: 800 }), 39); diff --git a/src/tools/queries/mobility.test.mjs b/src/tools/queries/mobility.test.mjs index 011e431fd6..323173f034 100644 --- a/src/tools/queries/mobility.test.mjs +++ b/src/tools/queries/mobility.test.mjs @@ -171,6 +171,46 @@ test('bike share reports uncovered areas and failed systems honestly', async () ); }); +test('bike share excludes blank coordinates without losing stations on the prime meridian', async () => { + const stations = [ + { station_id: 'blank', lat: 51.5, lon: ' ' }, + { station_id: 'zero', lat: 51.5, lon: 0 }, + ]; + const catalog = composeCatalog({ + tools: coreTools, + services: { + bikeshare: { + systems: [system('fixture', 'Fixture Bikes', 51.5, 0)], + async getStations(url) { + return { + data: { + stations: url.endsWith('station_information.json') + ? stations + : stations.map(({ station_id }) => ({ + station_id, + num_bikes_available: 4, + })), + }, + }; + }, + }, + }, + }); + const result = await catalog.call('get_bike_share', { + area: { lat: 51.5, lon: 0, radius_km: 2 }, + }); + assert.deepEqual( + result.data.rows.map((row) => row.station_id), + ['zero'], + ); + assert.equal(result.data.total, 1); + assert.equal(result.data.rows[0].lon, 0); + assert.equal( + result.summary, + '1 bike-share station in 2 km around 51.500, 0.000 with 4 bikes available.', + ); +}); + const feed = { id: 'capmetro', name: 'CapMetro', From dd6e01353ab7897edc6d840177661ec481f5b394 Mon Sep 17 00:00:00 2001 From: Bortlesboat <169967362+Bortlesboat@users.noreply.github.com> Date: Sun, 18 Oct 2026 23:58:01 -0400 Subject: [PATCH 12/54] docs(gbfs): assign changelog fragment to PR 1232 Signed-off-by: Bortlesboat <169967362+Bortlesboat@users.noreply.github.com> --- ...-invalid-coordinates.md => 1232-gbfs-invalid-coordinates.md} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename changelog.d/{0-gbfs-invalid-coordinates.md => 1232-gbfs-invalid-coordinates.md} (90%) diff --git a/changelog.d/0-gbfs-invalid-coordinates.md b/changelog.d/1232-gbfs-invalid-coordinates.md similarity index 90% rename from changelog.d/0-gbfs-invalid-coordinates.md rename to changelog.d/1232-gbfs-invalid-coordinates.md index ed1f0824e7..4f3da2a97b 100644 --- a/changelog.d/0-gbfs-invalid-coordinates.md +++ b/changelog.d/1232-gbfs-invalid-coordinates.md @@ -1,3 +1,3 @@ - Skip bike-share stations with missing, blank or invalid coordinates instead of placing them at coerced zero coordinates or accepting out-of-range values. - Explicit zero coordinates and numeric strings remain supported (Bortlesboat, #0). + Explicit zero coordinates and numeric strings remain supported (Bortlesboat, #1232). From 1a72da81b5ffae71d330c1731545e3e908ea2b3d Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 07:54:47 -0700 Subject: [PATCH 13/54] docs(voice): document stable entity labels and localized presentation --- docs/CURRENT-STATE.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index e00041eac1..3cca1acc88 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -554,6 +554,9 @@ to layer toggles, fly_to_location, frame_overhead, select_nearest_aircraft, get_entity_context, annotate_map and analyst_query. Analyst speech and the card share one deterministic count/scope headline; lower bounds use "At least" and partial answers name the unanswered layers. `get_current_view_state` lists enabled layers only. +FIRMS and ALPR entity labels remain English in shared context and tool data; +voice-card titles and pointer presentation translate those known labels at display +time, while arbitrary names and callsigns remain unchanged. The model-free `gods-eye-view/agent/world-packet` export exposes `getWorldPacket({ viewer, styleManager, dataManager, sceneDirector })` to non-voice consumers. It reads the same enabled-only state and feed From 91144e88adb85f5dd7a35c6ab694bc0d6316cd21 Mon Sep 17 00:00:00 2001 From: quanticsoul4772 <71096528+quanticsoul4772@users.noreply.github.com> Date: Sun, 25 Oct 2026 08:08:43 -0700 Subject: [PATCH 14/54] perf(models): aircraft models skip Cesium's dynamic environment map (#1366) Skip per-aircraft dynamic environment maps while retaining default model lighting. Contribution by @quanticsoul4772. --- ...1366-aircraft-models-no-environment-map.md | 5 ++ docs/CURRENT-STATE.md | 1 + scripts/package-boundaries.json | 5 ++ src/data/aircraftModelLighting.js | 17 +++++++ src/data/aircraftModelLighting.test.mjs | 51 +++++++++++++++++++ src/layers/flights/rendering.js | 3 ++ src/layers/localAdsb/models.js | 2 + src/layers/military/rendering.js | 3 ++ 8 files changed, 87 insertions(+) create mode 100644 changelog.d/1366-aircraft-models-no-environment-map.md create mode 100644 src/data/aircraftModelLighting.js create mode 100644 src/data/aircraftModelLighting.test.mjs diff --git a/changelog.d/1366-aircraft-models-no-environment-map.md b/changelog.d/1366-aircraft-models-no-environment-map.md new file mode 100644 index 0000000000..8c5ad49c39 --- /dev/null +++ b/changelog.d/1366-aircraft-models-no-environment-map.md @@ -0,0 +1,5 @@ +- Aircraft 3D models (Flights, Military Flights, Local ADS-B) skip Cesium's + dynamic environment map, a sky render and GPU readback per model. With + ~150 models in the scene at Atlanta on Google 3D, GPU time per frame at + rest falls from 14.3-14.8 ms to 12.1-12.5 ms; a same-model comparison + showed no visible change (quanticsoul4772, #1366). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index e00041eac1..afbf18c45b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5255,6 +5255,7 @@ pins and share links already supply complete boxes. - **The TRACKED contact's 2D↔3D handoff is DEFAULT behaviour (2026-08-19), driven by camera distance alone.** It does NOT consult the DISPLAY-rail `3D` toggle, which continues to own the FLEET (the un-instanced draw-call budget stays the operator's decision). Policy lives in `src/data/trackedModelRegime.js` and is shared by both layers: enter below `TRACKED_MODEL_ENTER_ALT_M` = 150,000 m and hand back to the billboard only above `TRACKED_MODEL_EXIT_ALT_M` = 172,500 m. **The swap distance was set by playtesting on 2026-08-20:** a first pass at 1,000,000 m switched too early; 2D reads correctly at ~600 km and the handoff belongs at ~150 km. **Consequence, recorded on purpose:** the tracked contact now enters 3D NEARER than the FLEET does (`MODEL_ALT_CEIL_M` = 800,000 m, unchanged), so with the DISPLAY-rail `3D` toggle on, 150–800 km draws surrounding contacts as models while the selected one is still a glyph. Nothing double-draws (the fleet pass skips the tracked icao) and aligning the two is a fleet-side decision, deliberately out of scope. **The two thresholds are asymmetric on purpose:** a single threshold makes a tracked orbit sitting ON the boundary strobe billboard↔model as the camera's altitude wobbles across it. Do not collapse them. The latch is scoped per selection, so a new target re-evaluates against the ENTER ceiling rather than inheriting the previous target's exit band. Exactly ONE model is involved; it loads on demand when the regime opens, is HIDDEN (not released) on regime exit so re-entry has no load gap, and is released by the existing teardown on deselect/re-track/destroy. Cockpit and TR-3B suppression are unchanged. **Two invariants around it:** (a) the hysteresis latch AND the load-failure latch are per-selection state cleared by `_resetTrackedSelectionState()` in the tracking lifecycle (deselect / re-track / cross-layer / init / destroy) — the predicate's icao-change guard is defence only, since it needs a drawn frame while nothing is selected and the render governor's idle mode does not promise one; (b) on-demand loading is bounded at 3 attempts per selection with a 1.5 s backoff and one console warning naming the asset — the driver runs every `scene.preUpdate`, so an unbounded catch means a missing GLB spins load→reject at frame rate. The billboard stays the visual throughout a failed load. - **Grounded 3D handoff is terrain-validity gated (2026-08-23).** A ready civilian or military glTF does not own the visual until `groundSnap` (`src/data/groundSnap.js`) can answer with a MEASURED photoreal-surface height. On success the layer writes `height + the model's measured belly offset` before revealing the model. Cache movement is measured on the WGS84 surface, not across altitude, so a stationary contact keeps its snap through poll-time vertical-datum changes. Model existence or GPU readiness alone never suppresses the billboard floor, and ordinary zoom/style/deselect transitions preserve a valid snap cache. **Two states, and the difference is the whole design.** COLD — nothing has ever resolved for this icao (tiles still streaming on first sight, sample failure, backoff after a first miss): there is no evidence of where the ground is, `heightFor` returns null, the model stays hidden and the depth-test-free 2D billboard remains opaque and floored. WARM — a snap resolved and then a >`MOVE_INVALIDATE_M` (50 m) taxi move stopped it answering directly: the measurement is DEMOTED to a bounded last-known rather than deleted, and it keeps answering while the resample is outstanding, so a taxiing aircraft does not pop 3D→2D→3D across a 2–30 s retry backoff. The bound is `HELD_SNAP_MAX_DRIFT_M` = 250 m from the spot the value was measured at, past which the hold is dropped rather than stretched and the contact is COLD again. It is spatial with no timer beside it (ground under a contact that has not moved does not change; what invalidates the value is the contact MOVING) and deliberately a quarter of the billboard chain's `HELD_FLOOR_MAX_DRIFT_KM` — that hold only ever RAISES a sprite, while a held snap IS the model's placement, so its error shows in both directions. A fresh sample releases the hold, and so does a ground flip (which already calls `forget`). **A loading model is HIDDEN, never zero-scaled:** admission sets `show = false` (Cesium's default is `true`, and an unplaced primitive would claim the visual at the identity matrix), and ownership is `ready && show` — Cesium 1.138's `Model.update` has no `show` guard, so hiding a primitive costs its load nothing. - Commercial and military aircraft use the same high-level FLEET model regime: 2D billboards when zoomed out, optional glTF models when closer, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Since 2026-08-16 (Hangar fleet) models are PER-CLASS: real CC-BY GLBs for light/bizjet/turboprop/widebody/helicopter/uav (`CLASS_MODEL_REAL` in `src/data/aircraftClass.js` — meters-baked, scale 1, per-model belly/radius; provenance in `public/models/README.md`), the shared `airplane.glb` for the remaining civilian classes, and the military layer maps weight classes (real GLBs / 747 heavies / `jet.glb` fastjets, per-model heading offsets, flat amber or emergency red). Textured civilians carry a HEAVY tint, not a light one: `MODEL_COLOR_BLEND_AMOUNT` is `0.94` in BOTH layers under Cesium's `ColorBlendMode.MIX`, so the class colour supplies 94% of the surface and the asset's own texture ~6%. The visual direction is clean light silhouettes with only a weak diffuse contribution from the approved textures, so liveries deliberately do NOT read. IR boost raises the blend to a full `1.0`. Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit. +- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). With the class colour supplying 94% of the surface, the models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; the two preload calls only warm the glTF cache and are never drawn. - The DISPLAY-rail `3D` toggle is the user-facing activation path for both aircraft layers. Their small approved GLBs build their render resources without Cesium's frame-spread job queue, preventing continuous Photorealistic 3D Tiles streaming from starving model readiness; model caps, tracking, camera, and fallback billboards are unchanged. - **The `3D` toggle DEFAULTS ON in `proximity` on a first run.** Proximity is itself the budget — models appear only below `MODEL_ALT_CEIL_M` and only for the nearest `MODEL_MAX` in view — so the default costs nothing at globe scale, and `all` remains a deliberate opt-in. A fresh boot runs NO layer-state restoration (`LayerStateCoordinator.start()` returns early with neither a share payload nor stored state), so four independent initializers decide what a first-run operator sees and must agree: `booleanOption('models3d', 'e', true)` in `src/data/layerState.js`, `_models3dEnabled = true` in BOTH flight layers, `this._models3dEnabled = true` in `src/ui/aircraftDisplay.js`, and the `active` / `visible` classes on `#models3d-toggle` / `#models3d-mode-row` in `index.html`. All four are pinned together in `src/data/layerState.test.mjs`. Explicit state still wins: because the codec omits default-valued options, `models3d: false` is now what travels in a link (`lo=…f.e.0`) and restores OFF at both aircraft layers. **Consequence for returning users:** a stored `gev:layer-state:v2` blob is a FULL options snapshot, so a session that wrote one before this change carries `models3d:false` and keeps 3D off until the operator flips it (or clears the key) — the durable snapshot is treated as the recipient's own state, by design. - **Consequence of the flip on the recorded tracked/fleet inversion:** the 150–800 km band where surrounding contacts draw as models while the SELECTED one is still a glyph is now what an operator sees WITHOUT arming anything. The inversion itself is unchanged and still deliberate (see `src/data/trackedModelRegime.js`); only its reachability changed. diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 3970a1ee2d..c84a11cad5 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -957,6 +957,7 @@ "src/data/layerState.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", + "src/data/aircraftModelLighting.js", "src/data/motionModel.js", "src/data/renderAltitude.js", "src/data/routePlausible.js", @@ -1009,6 +1010,7 @@ "src/data/layerState.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", + "src/data/aircraftModelLighting.js", "src/data/motionModel.js", "src/data/renderAltitude.js", "src/data/trackedModelRegime.js", @@ -1054,6 +1056,7 @@ "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", + "src/data/aircraftModelLighting.js", "src/data/motionModel.js", "src/data/renderAltitude.js", "src/data/routePlausible.js", @@ -1872,6 +1875,7 @@ "src/data/militaryInstallations.js", "src/data/militaryRegistry.js", "src/data/modelVisualAnchor.js", + "src/data/aircraftModelLighting.js", "src/data/motionModel.js", "src/data/naturalEarthRegions.js", "src/data/adminBoundaries.js", @@ -2681,6 +2685,7 @@ "src/data/installationNames.js", "src/data/militaryInstallationData.js", "src/data/modelVisualAnchor.js", + "src/data/aircraftModelLighting.js", "src/data/motionModel.js", "src/data/naturalEarthRegions.js", "src/data/adminBoundaries.js", diff --git a/src/data/aircraftModelLighting.js b/src/data/aircraftModelLighting.js new file mode 100644 index 0000000000..c8051c67e3 --- /dev/null +++ b/src/data/aircraftModelLighting.js @@ -0,0 +1,17 @@ +/** + * Lighting options shared by every aircraft 3D model (Flights, Military + * Flights, Local ADS-B). + * + * Cesium gives each Model a dynamic environment map: it renders the sky around + * the model and reads the result back from the GPU (`readPixels`) to light it, + * when the model is first placed and again when it moves more than 1 km, when + * the scene's atmosphere settings change, or every scene hour under sunlight + * lighting. Aircraft models take 94% of their surface from the class colour + * (`colorBlendAmount`), so that lighting contributes little; without it they + * are lit from Cesium's default spherical harmonics. Measured 2026-10-24 + * (Intel Arc, Google 3D, ~150 models in the scene): GPU per frame at rest + * 14.3-14.8 -> 12.1-12.5 ms. + */ +export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({ + enabled: false, +}); diff --git a/src/data/aircraftModelLighting.test.mjs b/src/data/aircraftModelLighting.test.mjs new file mode 100644 index 0000000000..51fd9d97c6 --- /dev/null +++ b/src/data/aircraftModelLighting.test.mjs @@ -0,0 +1,51 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { readLayerSource } from '../testSupport/readLayerSource.mjs'; +import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js'; + +/** + * Every aircraft model drawn in the scene skips Cesium's dynamic environment + * map (a sky render and GPU readback per model). The preload calls only warm + * the glTF cache and are never added to the scene, so they are left out: + * drawn models are the calls that set a minimum pixel size. + */ +const SOURCES = [ + { + name: 'flights', + source: readLayerSource(new URL('./flights.js', import.meta.url)), + }, + { + name: 'militaryFlights', + source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)), + }, + { + name: 'localAdsb', + source: readFileSync( + new URL('../layers/localAdsb/models.js', import.meta.url), + 'utf8', + ), + }, +]; + +test('the shared option turns the dynamic environment map off', () => { + assert.deepEqual({ ...AIRCRAFT_ENVIRONMENT_MAP_OPTIONS }, { enabled: false }); + assert.ok(Object.isFrozen(AIRCRAFT_ENVIRONMENT_MAP_OPTIONS)); +}); + +for (const { name, source } of SOURCES) { + test(`${name}: every drawn aircraft model skips the dynamic environment map`, () => { + const calls = [ + ...source.matchAll(/(?:fromGltfAsync|loadModel)\(\{([\s\S]*?)\}\)/g), + ] + .map((match) => match[1]) + .filter((options) => /\bminimumPixelSize:/.test(options)); + assert.ok(calls.length >= 1, `expected drawn model calls in ${name}`); + for (const [index, options] of calls.entries()) + assert.match( + options, + /\benvironmentMapOptions:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\b/, + `${name} model call ${index + 1} must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`, + ); + }); +} diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index 8aff72e382..d4075a5652 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -37,6 +37,7 @@ import { ROTATION_REFRESH_MS, COURSE_MAX_DPS, } from './policy.js'; +import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; export function createRendering({ flightState, @@ -507,6 +508,7 @@ export function createRendering({ model = await Cesium.Model.fromGltfAsync({ url: resolveAsset(spec.url), asynchronous: false, + environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, minimumPixelSize: MODEL_MIN_PX, scale: spec.scale, color: flightState._irBoost ? Cesium.Color.WHITE : _modelColor(icao24), @@ -713,6 +715,7 @@ export function createRendering({ Cesium.Model.fromGltfAsync({ url: resolveAsset(trackedSpec.url), asynchronous: false, + environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, minimumPixelSize: TRACKED_MODEL_MIN_PX, scale: trackedSpec.scale, color: flightState._irBoost ? Cesium.Color.WHITE : Cesium.Color.CYAN, diff --git a/src/layers/localAdsb/models.js b/src/layers/localAdsb/models.js index 50cebe07e5..55fc2d11a2 100644 --- a/src/layers/localAdsb/models.js +++ b/src/layers/localAdsb/models.js @@ -14,6 +14,7 @@ import { MODEL_PROX_ADD_M, MODEL_PROX_KEEP_M, } from '../flights/policy.js'; +import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; const specKey = (spec) => `${spec.url}@${spec.scale}`; @@ -87,6 +88,7 @@ export function createLocalAdsbModels({ model = await loadModel({ url: resolveAsset(spec.url), asynchronous: false, + environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, minimumPixelSize: MODEL_MIN_PX, scale: spec.scale, color, diff --git a/src/layers/military/rendering.js b/src/layers/military/rendering.js index 089ae9ec80..504d79c80b 100644 --- a/src/layers/military/rendering.js +++ b/src/layers/military/rendering.js @@ -53,6 +53,7 @@ import { ROTATION_REFRESH_MS, COURSE_MAX_DPS, } from './policy.js'; +import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; export function createRendering({ flightState, @@ -473,6 +474,7 @@ export function createRendering({ model = await Cesium.Model.fromGltfAsync({ url: resolveAsset(spec.url), asynchronous: false, + environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, minimumPixelSize: MODEL_MIN_PX, scale: spec.scale, color: flightState._irBoost ? Cesium.Color.WHITE : _modelColor(icao24), @@ -676,6 +678,7 @@ export function createRendering({ Cesium.Model.fromGltfAsync({ url: resolveAsset(trackedSpec.url), asynchronous: false, + environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, minimumPixelSize: TRACKED_MODEL_MIN_PX, scale: trackedSpec.scale, color: flightState._irBoost ? Cesium.Color.WHITE : TRACKED_ICON_COLOR, From 6fee8382ce6cdd21502e447b12423cfe9e0668c6 Mon Sep 17 00:00:00 2001 From: KnottyDyes <47539659+KnottyDyes@users.noreply.github.com> Date: Sun, 25 Oct 2026 10:14:52 -0500 Subject: [PATCH 15/54] fix(first-run): make the dismiss hint a button so touch screens can close the card (#1226) Allow touch users to dismiss the welcome card through the existing dismissal path. Contribution by @KnottyDyes. --- changelog.d/1226-first-run-touch-dismiss.md | 4 ++ docs/CURRENT-STATE.md | 16 +++++-- src/firstRunExperience.js | 4 ++ src/firstRunExperience.test.mjs | 42 +++++++++++++++++ src/ui/styles/first-run.css | 51 +++++++++++++++++++-- src/ui/templates/welcome.html | 8 +++- 6 files changed, 115 insertions(+), 10 deletions(-) create mode 100644 changelog.d/1226-first-run-touch-dismiss.md diff --git a/changelog.d/1226-first-run-touch-dismiss.md b/changelog.d/1226-first-run-touch-dismiss.md new file mode 100644 index 0000000000..3eb802dac2 --- /dev/null +++ b/changelog.d/1226-first-run-touch-dismiss.md @@ -0,0 +1,4 @@ +- The first-run card can be closed on a phone or tablet. "ESC to dismiss" is + now a button that closes the card the same way ESC does; touch screens read + DISMISS, and phones no longer hide it, so choosing a mission is not the only + way out (KnottyDyes, #1226). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index afbf18c45b..d75f3f251b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2076,10 +2076,18 @@ fetching, trailing-24-hour filtering and partial-success caching are unchanged. > `localStorage['gev:first-run-mission:v1'] === 'suppressed'`, written **only** > by the "Don't show this again" checkbox → the per-session > `sessionStorage['gev:first-run-mission-session:v1'] === 'dismissed'`, written -> by **every** close path (mission, Explore, ESC). So it returns each fresh -> browser session until the visitor ticks the box; clearing storage un-ticks it, -> which is accepted. Both stores fail open — an unreadable store still shows the -> launcher rather than silently swallowing first launch. +> by **every** close path (mission, Explore, ESC, the footer dismiss button). So +> it returns each fresh browser session until the visitor ticks the box; clearing +> storage un-ticks it, which is accepted. Both stores fail open — an unreadable +> store still shows the launcher rather than silently swallowing first launch. +> +> **The footer dismiss button is the keyboardless ESC.** Phones and tablets have +> no ESC key, so the footer hint is a `data-first-run-dismiss` button that calls +> the same `dismiss()` as ESC. It stays visible at every width (phones used to +> hide it, leaving a mission as the only way out) and reads DISMISS on a +> `(hover: none) and (pointer: coarse)` screen, "ESC to dismiss" otherwise. Its +> 44px touch target is a `::before` outside the layout, so the footer row keeps +> its one-line height. > > **What a mission may persist (do not "simplify" this).** Layer enablement is > durable in this app (`gev:layer-state:v2`, written by diff --git a/src/firstRunExperience.js b/src/firstRunExperience.js index 408152295c..a3181ec152 100644 --- a/src/firstRunExperience.js +++ b/src/firstRunExperience.js @@ -543,6 +543,10 @@ export function initFirstRunExperience({ }); for (const button of buttons) button.addEventListener('click', onChoice); + // The same dismissal as ESC, for screens without a keyboard. + root + .querySelector('[data-first-run-dismiss]') + ?.addEventListener('click', () => dismiss()); suppressBox?.addEventListener('change', onSuppressChange); // Capture phase: the app binds its own global hotkeys (including bare letters // that cycle detection and styles), and the launcher owns the keyboard first. diff --git a/src/firstRunExperience.test.mjs b/src/firstRunExperience.test.mjs index a02c4391f8..603272e82e 100644 --- a/src/firstRunExperience.test.mjs +++ b/src/firstRunExperience.test.mjs @@ -913,6 +913,48 @@ test('markup, startup ordering and accessibility remain pinned', () => { assert.match(choicesBlock, /overflow-y: auto;/); }); +test('the card closes without a keyboard: the ESC hint is a button, kept on phones', () => { + const html = expandApplicationHtml( + fs.readFileSync(new URL('../index.html', import.meta.url), 'utf8'), + ); + const module = fs.readFileSync( + new URL('./firstRunExperience.js', import.meta.url), + 'utf8', + ); + // The whole stylesheet, so a hide rule added in any other file is caught too. + const css = readStylesheet(new URL('../style.css', import.meta.url)); + const footer = html.slice( + html.indexOf('class="first-run-footer"'), + html.indexOf('data-first-run-status'), + ); + assert.match( + footer, + / From 6bbf9b94c4f2045865a75d7fd4147491c970a63b Mon Sep 17 00:00:00 2001 From: quanticsoul4772 <71096528+quanticsoul4772@users.noreply.github.com> Date: Sun, 25 Oct 2026 08:26:26 -0700 Subject: [PATCH 16/54] fix(traffic): flag stale cached TomTom tiles in get_traffic_flow (#1239) Report stale traffic tiles and their fetch time, and release pending freshness metadata when tile requests fail or are cancelled. Contribution by @quanticsoul4772. --- changelog.d/1239-traffic-stale-flow.md | 3 + docs/CURRENT-STATE.md | 8 ++ server/providers/traffic.js | 15 ++- src/layers/traffic/flowSource.js | 77 +++++++++-- src/layers/traffic/source.test.mjs | 153 ++++++++++++++++++++++ src/tooling/environmentProviders.test.mjs | 9 +- src/tools/queries/mobility.js | 11 ++ src/tools/queries/mobility.test.mjs | 41 ++++++ 8 files changed, 299 insertions(+), 18 deletions(-) create mode 100644 changelog.d/1239-traffic-stale-flow.md diff --git a/changelog.d/1239-traffic-stale-flow.md b/changelog.d/1239-traffic-stale-flow.md new file mode 100644 index 0000000000..5338e8e602 --- /dev/null +++ b/changelog.d/1239-traffic-stale-flow.md @@ -0,0 +1,3 @@ +- `get_traffic_flow` flags stale cached TomTom tiles and reports the oldest + tile fetch time (`stale`, `oldest_tile_at`), with pending freshness metadata + released on failed or cancelled tile reads (quanticsoul4772, #1239). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 332b99283f..be09e5664a 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1701,6 +1701,14 @@ The TomTom `/api/tomtom/*` routes run the shared same-site admission gate before status, cache or upstream work, refusing cross-site browser requests while preserving same-origin app requests and non-browser local callers. The browser layers and their rendering remain in their existing modules. +Past the daily tile budget, or while TomTom fails, the proxy answers with its +last copy of a tile (`x-tomtom-cache: STALE-BUDGET` / `STALE-ERROR`) however old +it is, and every tile carries `x-tomtom-fetched-at`, the proxy fetch time +(or the persisted cache file time after restart). The flow source keeps that mark with each decoded tile, so +`get_traffic_flow` returns `stale` and `oldest_tile_at` and says when traffic +may be out of date instead of presenting cached tiles as live. Pending freshness +metadata is released when body reads fail, are cancelled, or exceed their size +limit, as well as when a tile decodes or the source resets. GBFS null or empty availability counts retain an unknown value through station parsing and rendering; they use the neutral station color rather than reporting an empty dock. Explicit zero and caller-supplied numeric fallbacks remain valid. diff --git a/server/providers/traffic.js b/server/providers/traffic.js index da8ae73de0..2069a08924 100644 --- a/server/providers/traffic.js +++ b/server/providers/traffic.js @@ -182,14 +182,17 @@ export function tomtomProxy() { }); res.end(JSON.stringify(obj)); }; - const sendTile = (buf, cacheStatus) => { + // x-tomtom-fetched-at is when the proxy fetched the tile (ms since the + // epoch), so a client handed a STALE-* copy can say how old it is. + const sendTile = (entry, cacheStatus) => { if (res.headersSent) return; res.writeHead(200, { 'Content-Type': 'application/x-protobuf', 'Cache-Control': 'no-store', 'x-tomtom-cache': cacheStatus, + 'x-tomtom-fetched-at': String(Math.round(entry.at)), }); - res.end(buf); + res.end(entry.buf); }; try { @@ -235,14 +238,14 @@ export function tomtomProxy() { } // Fresh cache hit — never counts against the budget. if (entry && now - entry.at < TILE_TTL_MS) { - sendTile(entry.buf, 'HIT'); + sendTile(entry, 'HIT'); return; } // Budget governor: over the soft cap, last-good data beats a dead layer. if (isTomTomOverBudget(currentBudget(), dailyBudgetLimit())) { if (entry) { - sendTile(entry.buf, 'STALE-BUDGET'); + sendTile(entry, 'STALE-BUDGET'); } else { sendJson(429, { error: 'budget' }); } @@ -271,9 +274,9 @@ export function tomtomProxy() { } const fresh = await inflight.get(key); if (fresh) { - sendTile(fresh.buf, 'MISS'); + sendTile(fresh, 'MISS'); } else if (entry) { - sendTile(entry.buf, 'STALE-ERROR'); // upstream down — stale beats empty + sendTile(entry, 'STALE-ERROR'); // upstream down — stale beats empty } else { sendJson(502, { error: 'upstream' }); } diff --git a/src/layers/traffic/flowSource.js b/src/layers/traffic/flowSource.js index 49567a9ee2..f517c99bcc 100644 --- a/src/layers/traffic/flowSource.js +++ b/src/layers/traffic/flowSource.js @@ -4,30 +4,79 @@ import { clipTileLine } from '../../sources/openFreeMap.js'; import { tileToBBox } from '../../data/tomtomTiles.js'; import { decodeFlowTile } from './flowDecode.js'; +const FLOW_TILE_PATH = (z, x, y) => `/api/tomtom/flow/${z}/${x}/${y}.pbf`; + +/** + * Whether the proxy answered a tile from its cache past the refresh window + * (STALE-BUDGET once the daily budget is spent, STALE-ERROR when TomTom + * fails), and when the proxy fetched it. + */ +function tileFreshness(response) { + const status = response.headers?.get?.('x-tomtom-cache') || ''; + const fetchedAt = Number(response.headers?.get?.('x-tomtom-fetched-at')); + return { + stale: status.startsWith('STALE'), + fetchedAt: fetchedAt > 0 ? fetchedAt : null, + }; +} + /** Own one bounded decoded flow cache; every request still passes the server tile budget. */ export function createFlowTileSource({ fetchImpl = (...args) => globalThis.fetch(...args), } = {}) { + // Freshness travels in response headers, but the tile cache keeps only + // decoded segments: hold each response's freshness until its tile decodes, + // then key it by the decoded tile, which the cache hands back on a hit. + const pending = new Map(); + const freshness = new WeakMap(); const tiles = createVectorTileSource({ - template: '/api/tomtom/flow/{z}/{x}/{y}.pbf', + template: FLOW_TILE_PATH('{z}', '{x}', '{y}'), allowedOrigin: 'http://localhost', - decode: (bytes, z, x, y) => - decodeFlowTile(bytes, z, x, y, { strict: true }) + decode: (bytes, z, x, y) => { + // Take the mark before decoding, so a tile that fails to decode + // leaves nothing behind. + const path = FLOW_TILE_PATH(z, x, y); + const entry = pending.get(path); + const mark = entry?.mark; + entry?.release(); + const segments = decodeFlowTile(bytes, z, x, y, { strict: true }) .filter(isDrivableFlowSegment) .flatMap((segment) => clipTileLine(segment.coords, tileToBBox(z, x, y)).map((coords) => ({ ...segment, coords, })), - ), - fetchImpl, + ); + if (mark) freshness.set(segments, mark); + return segments; + }, + fetchImpl: async (url, init) => { + const response = await fetchImpl(url, init); + if (response.ok && !init.signal.aborted) { + const path = String(url); + const entry = { + mark: tileFreshness(response), + release() { + if (pending.get(path) === entry) pending.delete(path); + init.signal.removeEventListener('abort', entry.release); + }, + }; + pending.get(path)?.release(); + pending.set(path, entry); + // The vector source aborts this signal for failed/cancelled body reads, + // including size-limit failures that never reach decode. + init.signal.addEventListener('abort', entry.release, { once: true }); + } + return response; + }, ttlMs: 120_000, maxTiles: 16, }); let partial = false; /** * Flow segments for bounds, with whether any covering tile failed to load - * for this request. + * for this request, whether any came from the proxy's stale cache, and when + * the oldest tile was fetched. */ async function fetchFlowDetail(bounds, { signal, zoom = 12 } = {}) { const result = await tiles.fetchBounds(bounds, { @@ -44,7 +93,16 @@ export function createFlowTileSource({ coords, })), ); - return { segments, partial: result.partial === true }; + const marks = result.tiles.map((tile) => freshness.get(tile) || {}); + const times = marks + .map((mark) => mark.fetchedAt) + .filter((at) => Number.isFinite(at)); + return { + segments, + partial: result.partial === true, + stale: marks.some((mark) => mark.stale === true), + oldestTileAt: times.length ? Math.min(...times) : null, + }; } return { fetchFlowDetail, @@ -52,6 +110,9 @@ export function createFlowTileSource({ return (await fetchFlowDetail(bounds, options)).segments; }, getFlowSessionStats: () => ({ ...tiles.getStats(), partial }), - resetFlowTileCache: () => tiles.clear(), + resetFlowTileCache: () => { + for (const entry of pending.values()) entry.release(); + tiles.clear(); + }, }; } diff --git a/src/layers/traffic/source.test.mjs b/src/layers/traffic/source.test.mjs index affaff56d3..927dc416e2 100644 --- a/src/layers/traffic/source.test.mjs +++ b/src/layers/traffic/source.test.mjs @@ -1,6 +1,8 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { readFileSync } from 'node:fs'; +import { getEventListeners } from 'node:events'; +import { createFlowTileSource } from './flowSource.js'; import { tilesForBounds, tileToBBox } from '../../data/tomtomTiles.js'; import { decodeFlowTile } from './flowDecode.js'; import { decodeOpenFreeMapTile } from '../../sources/openFreeMap.js'; @@ -867,3 +869,154 @@ test('traffic separates API and public tile transports, including the default ti assert.ok(publicUrls.length >= 4); assert.ok(apiUrls.length >= 4); }); + +test('flow detail reports stale proxy tiles and the oldest tile time, also from its cache', async () => { + const fetchedAt = Date.UTC(2026, 9, 16, 8); + const reply = (status, at) => async () => + new Response(fixture, { + headers: { 'x-tomtom-cache': status, 'x-tomtom-fetched-at': String(at) }, + }); + const stale = createTrafficSource({ + fetchImpl: reply('STALE-BUDGET', fetchedAt), + }); + const first = await stale.fetchFlowDetail(bounds); + assert.ok(first.segments.length > 0); + assert.equal(first.stale, true); + assert.equal(first.oldestTileAt, fetchedAt); + // The decoded tile is served from cache now, and keeps its mark. + const again = await stale.fetchFlowDetail(bounds); + assert.equal(stale.getFlowSessionStats().tilesFetched, 1); + assert.equal(again.stale, true); + assert.equal(again.oldestTileAt, fetchedAt); + + const fresh = createTrafficSource({ fetchImpl: reply('MISS', fetchedAt) }); + const live = await fresh.fetchFlowDetail(bounds); + assert.equal(live.stale, false); + assert.equal(live.oldestTileAt, fetchedAt); + + const unmarked = createTrafficSource({ + fetchImpl: async () => new Response(fixture), + }); + const plain = await unmarked.fetchFlowDetail(bounds); + assert.equal(plain.stale, false); + assert.equal(plain.oldestTileAt, null); +}); + +// Capture constructor-owned Maps only while constructing the source, so tests +// can assert retained metadata without adding a diagnostic API to production. +function flowSourceWithMaps(fetchImpl) { + const maps = []; + const NativeMap = globalThis.Map; + let source; + try { + globalThis.Map = class extends NativeMap { + constructor(...args) { + super(...args); + maps.push(this); + } + }; + source = createFlowTileSource({ fetchImpl }); + } finally { + globalThis.Map = NativeMap; + } + return { source, pending: maps[0] }; +} + +test('flow freshness is released after body failures, size rejection, decode and reset', async () => { + for (const failure of ['body', 'size', 'decode']) { + let requestSignal; + let fail = true; + const { source, pending } = flowSourceWithMaps(async (url, { signal }) => { + requestSignal = signal; + return { + ok: true, + headers: new Headers({ + 'x-tomtom-cache': fail ? 'STALE-ERROR' : 'MISS', + 'x-tomtom-fetched-at': fail ? '1000' : '2000', + ...(fail && failure === 'size' + ? { 'content-length': '99999999' } + : {}), + }), + async arrayBuffer() { + if (fail && failure === 'body') throw new Error('body disconnected'); + return fail && failure === 'decode' ? new Uint8Array([255]) : fixture; + }, + }; + }); + await assert.rejects(source.fetchFlowDetail(bounds)); + assert.equal(pending.size, 0, `${failure} leaves no pending metadata`); + assert.equal(getEventListeners(requestSignal, 'abort').length, 0); + assert.equal(source.getFlowSessionStats().cacheEntries, 0); + fail = false; + const fresh = await source.fetchFlowDetail(bounds); + assert.equal(fresh.stale, false); + assert.equal(fresh.oldestTileAt, 2000); + assert.equal(pending.size, 0, 'successful decode releases metadata'); + assert.equal(getEventListeners(requestSignal, 'abort').length, 0); + source.resetFlowTileCache(); + assert.equal(pending.size, 0); + } +}); + +test('flow reset and late cancelled headers cannot retain or replace newer freshness', async () => { + let resolveOld; + let oldSignal; + let calls = 0; + const { source, pending } = flowSourceWithMaps((url, { signal }) => { + if (++calls === 1) { + oldSignal = signal; + return new Promise((resolve) => { + resolveOld = resolve; + }); + } + return Promise.resolve( + new Response(fixture, { + headers: { 'x-tomtom-cache': 'MISS', 'x-tomtom-fetched-at': '2000' }, + }), + ); + }); + const old = source.fetchFlowDetail(bounds); + const rejected = assert.rejects(old, { name: 'AbortError' }); + while (!resolveOld) await new Promise((resolve) => setImmediate(resolve)); + source.resetFlowTileCache(); + const fresh = await source.fetchFlowDetail(bounds); + resolveOld( + new Response(fixture, { + headers: { + 'x-tomtom-cache': 'STALE-ERROR', + 'x-tomtom-fetched-at': '1000', + }, + }), + ); + await rejected; + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(pending.size, 0); + assert.equal(getEventListeners(oldSignal, 'abort').length, 0); + assert.equal(fresh.stale, false); + assert.equal(fresh.oldestTileAt, 2000); + assert.equal((await source.fetchFlowDetail(bounds)).oldestTileAt, 2000); +}); + +test('cancelling a flow body releases its freshness before a new request', async () => { + const controller = new AbortController(); + let requestSignal; + const { source, pending } = flowSourceWithMaps(async (url, { signal }) => { + requestSignal = signal; + return { + ok: true, + headers: new Headers({ 'x-tomtom-cache': 'STALE-ERROR' }), + async arrayBuffer() { + assert.equal(pending.size, 1); + controller.abort(); + return fixture; + }, + }; + }); + await assert.rejects( + source.fetchFlowDetail(bounds, { signal: controller.signal }), + { name: 'AbortError' }, + ); + assert.equal(pending.size, 0); + assert.equal(getEventListeners(requestSignal, 'abort').length, 0); + assert.equal(source.getFlowSessionStats().cacheEntries, 0); +}); diff --git a/src/tooling/environmentProviders.test.mjs b/src/tooling/environmentProviders.test.mjs index bbb0e9d6e6..5e786e4083 100644 --- a/src/tooling/environmentProviders.test.mjs +++ b/src/tooling/environmentProviders.test.mjs @@ -158,6 +158,7 @@ test('terrain middleware migrates valid legacy disk points without fabricating o test('traffic middleware preserves keyless mode, caching, stale budget fallback and UTC rollover', async (t) => { isolate(t, { TOMTOM_API_KEY: '', TOMTOM_DAILY_TILE_BUDGET: '1' }); let now = Date.UTC(2026, 8, 12, 12); + const fetchedAt = String(now); t.mock.method(Date, 'now', () => now); let calls = 0; t.mock.method(globalThis, 'fetch', async (raw) => { @@ -182,10 +183,10 @@ test('traffic middleware preserves keyless mode, caching, stale budget fallback assert.equal(json(await request('/status')).dailyCount, 1); assert.equal(calls, 1); now += 120001; - assert.equal( - (await request('/flow/8/1/1.pbf')).headers['x-tomtom-cache'], - 'STALE-BUDGET', - ); + const staleTile = await request('/flow/8/1/1.pbf'); + assert.equal(staleTile.headers['x-tomtom-cache'], 'STALE-BUDGET'); + // The stale copy still says when TomTom produced it. + assert.equal(staleTile.headers['x-tomtom-fetched-at'], fetchedAt); assert.equal((await request('/flow/8/2/1.pbf')).status, 429); assert.equal(calls, 1); now += 86400000; diff --git a/src/tools/queries/mobility.js b/src/tools/queries/mobility.js index 743fa22a2d..0a57ae3ae2 100644 --- a/src/tools/queries/mobility.js +++ b/src/tools/queries/mobility.js @@ -473,11 +473,22 @@ export const getTrafficFlow = defineTool({ : `No live traffic is reported in ${area.label}.`) + (flow.partial ? ' Some map tiles did not load, so these figures are partial.' + : '') + + // Past the daily TomTom budget, or while TomTom fails, the proxy + // serves its last copy of a tile however old it is. + (flow.stale + ? ' Some tiles are cached copies' + + (isoTime(flow.oldestTileAt) + ? `, the oldest from ${isoTime(flow.oldestTileAt)}` + : '') + + ', so traffic may be out of date.' : ''), data: { view: suggestView(services, { area, layers: ['traffic'] }), area: area.label, partial: flow.partial, + stale: flow.stale === true, + oldest_tile_at: isoTime(flow.oldestTileAt), speed_pct_of_free_flow: speedPct, measured_km: round(measuredKm, 1), congested_km: round(congestedKm, 1), diff --git a/src/tools/queries/mobility.test.mjs b/src/tools/queries/mobility.test.mjs index 011e431fd6..676351b6c4 100644 --- a/src/tools/queries/mobility.test.mjs +++ b/src/tools/queries/mobility.test.mjs @@ -555,6 +555,47 @@ test('traffic counts only roads inside a radius area and reports missing tiles', assert.match(partial.summary, /Some map tiles did not load/); }); +test('traffic says when the proxy served cached tiles, and how old the oldest is', async () => { + const road = [ + { + coords: [ + [-0.2, 0], + [0.2, 0], + ], + trafficLevel: 0.9, + }, + ]; + const call = (detail) => + composeCatalog({ + tools: coreTools, + services: { + traffic: { + getStatus: async () => ({ hasKey: true }), + fetchFlowDetail: async () => ({ + segments: road, + partial: false, + ...detail, + }), + }, + }, + }).call('get_traffic_flow', { area: { lat: 0, lon: 0, radius_km: 10 } }); + const oldest = Date.UTC(2026, 9, 16, 8); + const stale = await call({ stale: true, oldestTileAt: oldest }); + assert.equal(stale.data.stale, true); + assert.equal(stale.data.oldest_tile_at, '2026-10-16T08:00:00.000Z'); + assert.match( + stale.summary, + /cached copies, the oldest from 2026-10-16T08:00:00\.000Z, so traffic may be out of date\./, + ); + const live = await call({ stale: false, oldestTileAt: oldest }); + assert.equal(live.data.stale, false); + assert.doesNotMatch(live.summary, /out of date/); + // A source that can't tell (no freshness fields) isn't reported as stale. + const unknown = await call({}); + assert.equal(unknown.data.stale, false); + assert.equal(unknown.data.oldest_tile_at, null); +}); + test('a whole-world bike-share search names every system it skipped', async () => { const empty = { data: { stations: [] } }; const result = await composeCatalog({ From eb8b63fc62b04ac505d72cd2c2d8e8cdb2427240 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 25 Oct 2026 11:32:12 -0400 Subject: [PATCH 17/54] fix(directions): show a 59.6-second leg as 1 min, not 60 s routeDurationText checked the raw seconds against 60 but printed them rounded, so a leg of 59.5 s or more read "60 s". Compare the rounded seconds so it moves to minutes. --- changelog.d/1385-route-duration-minute.md | 3 +++ src/data/directions.test.mjs | 2 ++ src/layers/directions/index.js | 3 ++- 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 changelog.d/1385-route-duration-minute.md diff --git a/changelog.d/1385-route-duration-minute.md b/changelog.d/1385-route-duration-minute.md new file mode 100644 index 0000000000..fa354766bf --- /dev/null +++ b/changelog.d/1385-route-duration-minute.md @@ -0,0 +1,3 @@ +- Show a route leg of 59.5 seconds or more as 1 min. The route summary and step + cards kept seconds below 60, then rounded 59.6 s up to "60 s" + (Rudy Celekli, @rudycelekli, #1385). diff --git a/src/data/directions.test.mjs b/src/data/directions.test.mjs index 4c9b54bd8c..9426450a5c 100644 --- a/src/data/directions.test.mjs +++ b/src/data/directions.test.mjs @@ -849,6 +849,8 @@ test('route numbers follow the page language and never break from their unit', ( assert.equal(routeDistanceText(1500), '1.5\u00a0km'); assert.equal(routeDistanceText(2_345_000), '2345\u00a0km'); assert.equal(routeDurationText(39), '39\u00a0s'); + assert.equal(routeDurationText(59.4), '59\u00a0s'); + assert.equal(routeDurationText(59.6), '1\u00a0min'); assert.equal(routeDurationText(3900), '1\u00a0h\u00a05\u00a0min'); assert.equal(routeDurationText(7200), '2\u00a0h'); assert.equal(routeDistanceText(-1), ''); diff --git a/src/layers/directions/index.js b/src/layers/directions/index.js index 2b8f8875ea..8fec18f65b 100644 --- a/src/layers/directions/index.js +++ b/src/layers/directions/index.js @@ -130,7 +130,8 @@ export function routeDistanceText(meters) { */ export function routeDurationText(seconds) { if (!Number.isFinite(seconds) || seconds < 0) return ''; - if (seconds < 60) return formatQuantity(Math.round(seconds), 's'); + const wholeSeconds = Math.round(seconds); + if (wholeSeconds < 60) return formatQuantity(wholeSeconds, 's'); const minutes = Math.round(seconds / 60); if (minutes < 60) return formatQuantity(minutes, 'min'); const hours = formatQuantity(Math.floor(minutes / 60), 'h'); From b7e00f18a4b1ef2f92fdd17fd4418b72f250aae0 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 25 Oct 2026 11:32:15 -0400 Subject: [PATCH 18/54] fix(directions): show a 996 m leg as 1.0 km, not 1000 m routeDistanceText checked the raw meters against 1000 but printed them rounded to tens, so 995 m or more read "1000 m". Compare the rounded value so it moves to kilometres. --- changelog.d/1386-route-distance-kilometre.md | 3 +++ src/data/directions.test.mjs | 2 ++ src/layers/directions/index.js | 3 ++- 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 changelog.d/1386-route-distance-kilometre.md diff --git a/changelog.d/1386-route-distance-kilometre.md b/changelog.d/1386-route-distance-kilometre.md new file mode 100644 index 0000000000..0a60fcc62d --- /dev/null +++ b/changelog.d/1386-route-distance-kilometre.md @@ -0,0 +1,3 @@ +- Show a route leg of 995 m or more as 1.0 km. The route summary and step + cards kept meters below 1000, then rounded 996 m up to "1000 m" + (Rudy Celekli, @rudycelekli, #1386). diff --git a/src/data/directions.test.mjs b/src/data/directions.test.mjs index 4c9b54bd8c..187f1a8d0a 100644 --- a/src/data/directions.test.mjs +++ b/src/data/directions.test.mjs @@ -846,6 +846,8 @@ test('route numbers follow the page language and never break from their unit', ( t.after(() => setLocale('en')); assert.equal(routeDistanceText(8.4), '8\u00a0m'); assert.equal(routeDistanceText(236), '240\u00a0m'); + assert.equal(routeDistanceText(994), '990\u00a0m'); + assert.equal(routeDistanceText(996), '1.0\u00a0km'); assert.equal(routeDistanceText(1500), '1.5\u00a0km'); assert.equal(routeDistanceText(2_345_000), '2345\u00a0km'); assert.equal(routeDurationText(39), '39\u00a0s'); diff --git a/src/layers/directions/index.js b/src/layers/directions/index.js index 2b8f8875ea..95e4cf258d 100644 --- a/src/layers/directions/index.js +++ b/src/layers/directions/index.js @@ -112,7 +112,8 @@ export const FLIGHT_PROGRESS_MS = 250; export function routeDistanceText(meters) { if (!Number.isFinite(meters) || meters < 0) return ''; if (meters < 100) return formatQuantity(Math.round(meters), 'm'); - if (meters < 1000) return formatQuantity(Math.round(meters / 10) * 10, 'm'); + const tens = Math.round(meters / 10) * 10; + if (tens < 1000) return formatQuantity(tens, 'm'); const km = meters / 1000; return km < 10 ? formatQuantity(km, 'km', { From 6c225605c40aeb37964a6cfd489d3c0b83dc3c2b Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 25 Oct 2026 11:32:19 -0400 Subject: [PATCH 19/54] fix(awareness): show a 999.6 m contact as 1.0 km, not 1000 m The Contacts panel checked the raw meters against 1000 but printed them rounded, so 999.5 m or more read "1000 m". Compare the rounded meters so the distance moves to kilometres. --- changelog.d/1387-awareness-distance-kilometre.md | 3 +++ src/data/militaryAwareness.test.mjs | 11 ++++++++++- src/layers/awareness/panel.js | 5 +++-- 3 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 changelog.d/1387-awareness-distance-kilometre.md diff --git a/changelog.d/1387-awareness-distance-kilometre.md b/changelog.d/1387-awareness-distance-kilometre.md new file mode 100644 index 0000000000..4414b7c5f4 --- /dev/null +++ b/changelog.d/1387-awareness-distance-kilometre.md @@ -0,0 +1,3 @@ +- Show a Contacts entry 999.5 m or more away as 1.0 km. The panel kept meters + below 1000, then rounded 999.6 m up to "1000 m" + (Rudy Celekli, @rudycelekli, #1387). diff --git a/src/data/militaryAwareness.test.mjs b/src/data/militaryAwareness.test.mjs index 64104953eb..ccb5739f2a 100644 --- a/src/data/militaryAwareness.test.mjs +++ b/src/data/militaryAwareness.test.mjs @@ -42,7 +42,10 @@ import { formatAwarenessLabel, getAwarenessNavigationTargets, } from './militaryAwarenessEngine.js'; -import { formatAwarenessCount } from '../layers/awareness/panel.js'; +import { + formatAwarenessCount, + presentAwarenessDistance, +} from '../layers/awareness/panel.js'; import { NAVIGATION_AUTHORITY_EVENT } from '../navigationPolicy.js'; const militaryAwarenessSource = readLayerSource( @@ -69,6 +72,12 @@ test('Contacts labels a capped cohort as a lower bound', () => { assert.equal(formatAwarenessCount({ count: null }), '?'); }); +test('Contacts moves a distance that rounds to 1,000 m into kilometres', () => { + assert.equal(presentAwarenessDistance(999.4), '999\u00a0m'); + assert.equal(presentAwarenessDistance(999.6), '1.0\u00a0km'); + assert.equal(presentAwarenessDistance(4600), '4.6\u00a0km'); +}); + function installAwarenessRuntime({ isEnabled = () => true, isEffectivelyEnabled = isEnabled, diff --git a/src/layers/awareness/panel.js b/src/layers/awareness/panel.js index 5fe2a0ac8a..120e91b2c3 100644 --- a/src/layers/awareness/panel.js +++ b/src/layers/awareness/panel.js @@ -25,9 +25,10 @@ function presentAwarenessCount(summary = {}) { } /** A distance as the panel shows it: 850 m, 4.6 km, 120 km, in the UI language. */ -function presentAwarenessDistance(meters) { +export function presentAwarenessDistance(meters) { if (!Number.isFinite(meters) || meters < 0) return '—'; - if (meters < 1000) return formatQuantity(Math.round(meters), 'm'); + const wholeMeters = Math.round(meters); + if (wholeMeters < 1000) return formatQuantity(wholeMeters, 'm'); const digits = meters < 10000 ? 1 : 0; return formatQuantity(meters / 1000, 'km', { minimumFractionDigits: digits, From be869f916061017eadb251328829579e055c3a9a Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 08:48:22 -0700 Subject: [PATCH 20/54] docs: document PR #1385 rounding behavior --- docs/CURRENT-STATE.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index be09e5664a..848c6714f2 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4133,6 +4133,9 @@ and as the last line of the list, because the arrival step is among the ones dropped. A route of exactly 200 is complete, and a roundabout exit after the 200th keeps folding into it. +Route duration labels select their unit after rounding seconds: a leg of +59.5 seconds or more displays as `1 min`, rather than `60 s`. + A step's card opens from its dot on the globe or from its line in the list, and the list covers every step including departure and arrival, which have no dot. What a card needs is a resolved ground anchor: a step whose ground cell has not From d6ae581652effa0c207992ceaf57c68bf673b6e2 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 08:48:30 -0700 Subject: [PATCH 21/54] docs: document PR #1386 rounding behavior --- docs/CURRENT-STATE.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index be09e5664a..7543cb4f00 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4081,6 +4081,9 @@ routing it shows `Routing…`, and a router miss reads The layer holds continuous render only while a route is drawn (the dashes animate). Disable clears all state. +Route distance labels round to the nearest ten metres before selecting the +unit, so 995 metres and above display as `1.0 km` rather than `1000 m`. + **Keys needed: none.** Directions works on a keyless boot, and the layer is off until the operator turns it on. From c30d2d34734b5256c7ec21a2ac65d40a22bc10c1 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 08:48:37 -0700 Subject: [PATCH 22/54] docs: document PR #1387 rounding behavior --- docs/CURRENT-STATE.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index be09e5664a..dd9b15cda8 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4363,6 +4363,9 @@ silent for five minutes are removed. Credits appear when the feed is used. coordinator, but it is not a user-visible Data Layers entry. Its visible entry point is the right-side `CONTEXT` chooser's `CONTACTS` mode. +Contacts distance labels select metres or kilometres after rounding to the +nearest metre, so a 999.5-metre contact displays as `1.0 km`, not `1000 m`. + At global scale, ambient Radio cluster badges are hard-opacity shared-host entries: count/category updates and identity replacement do not run keyhole or enter/exit ramps. Shared collision, viewport rejection, allocation, and horizon From 4d64ac48bc20509075e31519019349386e275f8f Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 08:48:58 -0700 Subject: [PATCH 23/54] docs: clarify unit transition examples --- docs/CURRENT-STATE.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 848c6714f2..af916fcaf6 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4133,8 +4133,8 @@ and as the last line of the list, because the arrival step is among the ones dropped. A route of exactly 200 is complete, and a roundabout exit after the 200th keeps folding into it. -Route duration labels select their unit after rounding seconds: a leg of -59.5 seconds or more displays as `1 min`, rather than `60 s`. +Route duration labels select their unit after rounding seconds, switching to +minutes at 59.5 seconds; a 59.6-second leg displays as `1 min`, rather than `60 s`. A step's card opens from its dot on the globe or from its line in the list, and the list covers every step including departure and arrival, which have no dot. From 455dbf2b5f56932782bdb2b07ec435fabec9b559 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 08:49:00 -0700 Subject: [PATCH 24/54] docs: clarify unit transition examples --- docs/CURRENT-STATE.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7543cb4f00..f171806e0b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4082,7 +4082,8 @@ The layer holds continuous render only while a route is drawn (the dashes animate). Disable clears all state. Route distance labels round to the nearest ten metres before selecting the -unit, so 995 metres and above display as `1.0 km` rather than `1000 m`. +unit, switching to kilometres at 995 metres; a 996-metre leg displays as +`1.0 km` rather than `1000 m`. **Keys needed: none.** Directions works on a keyless boot, and the layer is off until the operator turns it on. From 48e649a95e57a9ae6d4f02dd89b16c0237b2e0e6 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 08:50:11 -0700 Subject: [PATCH 25/54] docs(directions): scope the distance rounding threshold precisely --- docs/CURRENT-STATE.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f171806e0b..87fadd8a74 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4081,9 +4081,9 @@ routing it shows `Routing…`, and a router miss reads The layer holds continuous render only while a route is drawn (the dashes animate). Disable clears all state. -Route distance labels round to the nearest ten metres before selecting the -unit, switching to kilometres at 995 metres; a 996-metre leg displays as -`1.0 km` rather than `1000 m`. +At the metre/kilometre boundary, route distance labels use the rounded +ten-metre value to select the unit, switching to kilometres at 995 metres; +a 996-metre leg displays as `1.0 km` rather than `1000 m`. **Keys needed: none.** Directions works on a keyless boot, and the layer is off until the operator turns it on. From 496d024431b95bb5bbddd5dac17b00fd01ad1409 Mon Sep 17 00:00:00 2001 From: quanticsoul4772 <71096528+quanticsoul4772@users.noreply.github.com> Date: Sun, 25 Oct 2026 09:18:22 -0700 Subject: [PATCH 26/54] fix(hud): drop a summary reply once the camera starts moving (#1384) Discard stale HUD summaries when camera movement starts and allow cancelled requests to retry for unchanged place context. Contribution by @quanticsoul4772. --- changelog.d/1384-hud-summary-moving.md | 4 + docs/CURRENT-STATE.md | 1 + src/hud.js | 47 +++- src/hudAltitudeDatum.test.mjs | 343 ++++++++++++++++++++++++- 4 files changed, 382 insertions(+), 13 deletions(-) create mode 100644 changelog.d/1384-hud-summary-moving.md diff --git a/changelog.d/1384-hud-summary-moving.md b/changelog.d/1384-hud-summary-moving.md new file mode 100644 index 0000000000..21965af96e --- /dev/null +++ b/changelog.d/1384-hud-summary-moving.md @@ -0,0 +1,4 @@ +- The HUD's AI place summary drops a reply that arrives after the camera has + started moving, so a summary asked for before a flight no longer names the + old place mid-flight. Cancelled or partially typed summaries retry even if the place + context stays the same (quanticsoul4772, #1384). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index eceb4c239a..9afb99c457 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5107,6 +5107,7 @@ and unreachable upstream (502/504) separately from road geometry. - HUD `SUMMARY` readout requests a five-word intelligence-style summary from `/api/openai/hud-summary` (model `OPENAI_HUD_SUMMARY_MODEL`, default `gpt-5-nano`, minimal reasoning). - Input is the live basemap label context (place/street/nearby-place labels + enabled layers) — the model is instructed not to infer from coordinates. - Output is sanitized to exactly five words; falls back to the deterministic telemetry summary on error/timeout (5s abort); typewriter animation on update. +- A summary asked for before the camera starts moving never paints over the next view: `moveStart` marks the summary dirty and bumps its revision, as `moveEnd` does, aborts the request in flight and stops a reply still typing; neither a reply nor a fallback line (on an error, the 5 s timeout, the abort, or a failed context build) paints once the revision has moved. A dropped request forgets its signature and a timeout counts as a failure, so the next 15 s tick asks again even over the same place. An interrupted typewriter reply also forgets its signature; fully displayed answers remain reusable. ### Place-search providers diff --git a/src/hud.js b/src/hud.js index 8190f4b1b6..cf7983da72 100644 --- a/src/hud.js +++ b/src/hud.js @@ -224,6 +224,20 @@ export class IntelHUD { // session, so this flips once — and both altitude readouts have to move // together when it does (see the repaint in _updateCameraData). this._geoidCorrectionApplied = false; + // A summary built for one view must not land on the next: a request in + // flight when the camera starts moving is aborted and nothing it ends + // with paints (the revision moves), a reply still typing stops, and the + // summary is marked dirty so the next periodic tick asks about the view + // the camera has moved to. + this._onCameraMoveStart = () => { + this._markSummaryDirty(); + if (this._summaryRequest || this._summaryTypingInterval) { + // Cancelled requests and partially typed replies are not reusable answers. + this._lastSummarySignature = null; + } + this._summaryRequest?.abort(); + this._stopSummaryTyping(); + }; this._onCameraMoveEnd = () => { this._markSummaryDirty(); // The 250 ms telemetry timer and 15 s semantic-summary timer must not @@ -249,6 +263,7 @@ export class IntelHUD { this._passNum = 100 + Math.floor(Math.random() * 200); this._buildDOM(); + this.viewer.camera.moveStart.addEventListener(this._onCameraMoveStart); this.viewer.camera.moveEnd.addEventListener(this._onCameraMoveEnd); this._startTimers(); } @@ -766,6 +781,12 @@ export class IntelHUD { return provenance ? `${line} | ${provenance}` : line; } + /** Stop a summary still typing out, leaving what it has typed so far. */ + _stopSummaryTyping() { + clearInterval(this._summaryTypingInterval); + this._summaryTypingInterval = null; + } + /** * Animate the summary text into the DOM using a typewriter effect * (2 characters every 24ms). @@ -816,8 +837,10 @@ export class IntelHUD { } catch (error) { console.warn('[HUD] summary context unavailable:', error); // Left dirty on purpose: the next periodic tick retries instead of - // sticking on the fallback line for the rest of the session. - this._setSummaryText(fallbackText, animate); + // sticking on the fallback line for the rest of the session. The + // fallback was composed for this view; a moved camera keeps its own. + if (revision === this._summaryRevision) + this._setSummaryText(fallbackText, animate); return; } if (revision !== this._summaryRevision) return; @@ -832,7 +855,11 @@ export class IntelHUD { this._summaryDirty = false; this._lastSummarySignature = signature; const controller = new AbortController(); - const timeout = window.setTimeout(() => controller.abort(), 5000); + let timedOut = false; + const timeout = window.setTimeout(() => { + timedOut = true; + controller.abort(); + }, 5000); this._summaryRequest = controller; try { this.summaryPolicy.onRequest?.(); @@ -855,17 +882,24 @@ export class IntelHUD { animate, ); } catch (error) { - if (error?.name !== 'AbortError') { + // The 5 s timeout is a failure like any other; a move's abort (or + // destroy's) is not. + const moved = revision !== this._summaryRevision; + if (error?.name !== 'AbortError' || timedOut) { console.warn('[HUD] AI summary unavailable:', error); // Invalidate the committed signature so the next periodic tick // retries instead of sticking on the fallback line forever. this._lastSummarySignature = null; this._summaryDirty = true; } - this._setSummaryText(fallbackText, animate); + if (!moved) this._setSummaryText(fallbackText, animate); } finally { window.clearTimeout(timeout); if (this._summaryRequest === controller) this._summaryRequest = null; + // A request whose answer was dropped (aborted by a move, or a reply + // that came back after one) committed a signature it never painted; + // forget it, or the next tick over the same place would skip asking. + if (revision !== this._summaryRevision) this._lastSummarySignature = null; } } @@ -874,6 +908,8 @@ export class IntelHUD { this._typeSummary(text); return; } + // A plain paint replaces any reply still typing. + this._stopSummaryTyping(); const el = document.getElementById('hud-summary'); if (el) el.textContent = text; } @@ -1044,6 +1080,7 @@ export class IntelHUD { clearInterval(this._timestampInterval); clearInterval(this._summaryInterval); clearInterval(this._summaryTypingInterval); + this.viewer.camera.moveStart.removeEventListener(this._onCameraMoveStart); this.viewer.camera.moveEnd.removeEventListener(this._onCameraMoveEnd); this._dataManagerUnsubscribe?.(); this._summaryRequest?.abort(); diff --git a/src/hudAltitudeDatum.test.mjs b/src/hudAltitudeDatum.test.mjs index eeb407da4c..ca14569e57 100644 --- a/src/hudAltitudeDatum.test.mjs +++ b/src/hudAltitudeDatum.test.mjs @@ -16,6 +16,9 @@ // globals exist: Cesium's widget bundle probes for a real `document` at module // scope and a partial stub sends it down the browser path. Hence hook → // import → install DOM, in that order. +// +// The same hook is why the live AI-summary test lives here too: this is the +// one file that can construct a real IntelHUD. import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; @@ -33,7 +36,8 @@ registerHooks({ return { format: 'module', shortCircuit: true, - source: 'export function forward() { return "10SEG55776339"; }\nexport default { forward };\n', + source: + 'export function forward() { return "10SEG55776339"; }\nexport default { forward };\n', }; } return next(url, context); @@ -59,10 +63,20 @@ const SFO_ELLIPSOIDAL_M = -15; */ function installHudEnvironment() { const elements = new Map( - ['hud-alt', 'hud-summary', 'hud-mgrs', 'hud-latlon', 'hud-bottom-line', 'hud-gsd', 'hud-coll', 'hud-ona', 'hud-mode'] - .map((id) => [id, { textContent: '' }]), + [ + 'hud-alt', + 'hud-summary', + 'hud-mgrs', + 'hud-latlon', + 'hud-bottom-line', + 'hud-gsd', + 'hud-coll', + 'hud-ona', + 'hud-mode', + ].map((id) => [id, { textContent: '' }]), ); const previousDocument = globalThis.document; + const cameraListeners = {}; globalThis.document = { getElementById: (id) => elements.get(id) ?? null, querySelectorAll: () => [], @@ -78,12 +92,24 @@ function installHudEnvironment() { height: SFO_ELLIPSOIDAL_M, }, computeViewRectangle: () => undefined, - moveEnd: { addEventListener() {}, removeEventListener() {} }, + moveStart: { + addEventListener(listener) { + cameraListeners.moveStart = listener; + }, + removeEventListener() {}, + }, + moveEnd: { + addEventListener(listener) { + cameraListeners.moveEnd = listener; + }, + removeEventListener() {}, + }, }, }; return { elements, viewer, + cameraListeners, restore() { if (previousDocument === undefined) delete globalThis.document; else globalThis.document = previousDocument; @@ -93,7 +119,9 @@ function installHudEnvironment() { test('hud.js corrects the camera height to MSL through the geoid module', () => { assert.equal( - has(/import \{[^}]*\bellipsoidalToMslDisplayM\b[^}]*\} from '\.\/data\/geoid\.js';/s), + has( + /import \{[^}]*\bellipsoidalToMslDisplayM\b[^}]*\} from '\.\/data\/geoid\.js';/s, + ), true, 'hud.js must take the datum correction from ./data/geoid.js, not re-derive one', ); @@ -108,7 +136,9 @@ test('hud.js corrects the camera height to MSL through the geoid module', () => 'the ~2.7 MB grid must be requested once, on demand — not at HUD construction', ); assert.equal( - has(/\.catch\(\(\) => \{\s*\/\* readout falls back to the uncorrected height \*\/\s*\}\)/), + has( + /\.catch\(\(\) => \{\s*\/\* readout falls back to the uncorrected height \*\/\s*\}\)/, + ), true, 'a failed geoid load must leave the readout uncorrected, not unhandled', ); @@ -141,7 +171,9 @@ test('the summary ALT tag agrees with the corner readout', () => { // Both are on screen together; a viewer reading "ALT -15M" in one corner and // "ALT: 17m" in the other has found a bug, not a distinction. assert.equal( - has(/const altDisplayM = Number\.isFinite\(m\.altMslM\) \? m\.altMslM : m\.altM;/), + has( + /const altDisplayM = Number\.isFinite\(m\.altMslM\) \? m\.altMslM : m\.altM;/, + ), true, 'the summary altitude tag must prefer the MSL datum and fall back to the raw height', ); @@ -188,7 +220,11 @@ test('a cold tick paints both readouts uncorrected, and resolving flips both in // Tick 1 — cold. This is also the tick that requests the grid. hud._updateCameraData(); assert.match(alt(), /^ALT: -15m/, `cold corner readout, got ${alt()}`); - assert.match(summary(), /\| ALT -15M \|/, `cold summary tag, got ${summary()}`); + assert.match( + summary(), + /\| ALT -15M \|/, + `cold summary tag, got ${summary()}`, + ); // The HUD registered its own continuation on this same shared promise // during tick 1, and it registered first, so awaiting here means its @@ -248,3 +284,294 @@ test('the corrected readouts are the MSL datum, not a coincidence of the SFO sig env.restore(); } }); + +test('a summary asked for one view is dropped once the camera moves', async () => { + const env = installHudEnvironment(); + const previousWindow = globalThis.window; + globalThis.window = globalThis; + const pending = []; + const summaryService = { + summarize: (context) => + new Promise((resolve) => { + pending.push({ + context, + reply: (summary) => + resolve({ ok: true, status: 200, data: { summary, error: null } }), + }); + }), + }; + let hud; + try { + hud = new IntelHUD(env.viewer, { summaryService }); + let place = 'Yellowstone'; + hud._summaryContext = async () => ({ place }); + const summary = () => env.elements.get('hud-summary').textContent; + const settle = () => new Promise((resolve) => setImmediate(resolve)); + hud._updateCameraData(); + + // The periodic tick's call (force=false): it asks only for a dirty + // summary. Asked over Yellowstone; the camera leaves before the reply + // lands. + const first = hud._updateSummary(false); + await settle(); + assert.equal(pending.length, 1); + env.cameraListeners.moveStart(); + pending[0].reply('Canyon Junction Wyoming'); + await first; + assert.doesNotMatch( + summary(), + /Canyon Junction/, + 'a reply for the old view is dropped', + ); + + // The next tick, with the camera still moving (a follow camera or an + // orbit emits no moveEnd), asks about where it is now and paints it. + place = 'Atlantic'; + const moving = hud._updateSummary(false); + await settle(); + assert.equal(pending.length, 2, 'the move marked the summary dirty'); + assert.deepEqual(pending[1].context, { place: 'Atlantic' }); + pending[1].reply('North Atlantic Ocean'); + await moving; + assert.equal(summary(), 'North Atlantic Ocean'); + } finally { + for (const request of pending) request.reply(''); + hud?.destroy(); + if (previousWindow === undefined) delete globalThis.window; + else globalThis.window = previousWindow; + env.restore(); + } +}); + +test('a request the camera leaves paints nothing: aborted, failed, or its context build throws', async () => { + const env = installHudEnvironment(); + const previousWindow = globalThis.window; + globalThis.window = globalThis; + const pending = []; + // Like fetch: an abort rejects with an AbortError, unless `ignoreAbort`. + let ignoreAbort = false; + const summaryService = { + summarize: (context, { signal }) => + new Promise((resolve, reject) => { + pending.push({ signal, reject }); + if (!ignoreAbort) + signal.addEventListener('abort', () => + reject(Object.assign(new Error('aborted'), { name: 'AbortError' })), + ); + }), + }; + let hud; + try { + hud = new IntelHUD(env.viewer, { summaryService }); + hud._summaryContext = async () => ({ place: 'Yellowstone' }); + const element = env.elements.get('hud-summary'); + const settle = () => new Promise((resolve) => setImmediate(resolve)); + hud._updateCameraData(); + + // The move aborts the request in flight, and the abort paints nothing. + let update = hud._updateSummary(false, true); + await settle(); + element.textContent = 'shown before the move'; + env.cameraListeners.moveStart(); + assert.equal(pending[0].signal.aborted, true, 'the request is aborted'); + await update; + assert.equal(element.textContent, 'shown before the move'); + + // A request that fails after the move (an error, the 5 s timeout) does + // not paint the old view's fallback line either. + ignoreAbort = true; + update = hud._updateSummary(false, true); + await settle(); + element.textContent = 'shown before the move'; + env.cameraListeners.moveStart(); + pending[1].reject(new Error('network')); + await update; + assert.equal(element.textContent, 'shown before the move'); + + // Nor does a context build that throws once the camera has moved. + hud._summaryContext = async () => { + env.cameraListeners.moveStart(); + throw new Error('view target unavailable'); + }; + element.textContent = 'shown before the move'; + await hud._updateSummary(false, true); + assert.equal(element.textContent, 'shown before the move'); + } finally { + hud?.destroy(); + if (previousWindow === undefined) delete globalThis.window; + else globalThis.window = previousWindow; + env.restore(); + } +}); + +test('a cancelled summary retries the same context but completed answers stay reusable', async () => { + const env = installHudEnvironment(); + const previousWindow = globalThis.window; + globalThis.window = globalThis; + const pending = []; + const summaryService = { + summarize: (context, { signal }) => + new Promise((resolve, reject) => { + pending.push({ + context, + reply: (summary) => + resolve({ ok: true, status: 200, data: { summary } }), + }); + signal.addEventListener('abort', () => + reject(Object.assign(new Error('aborted'), { name: 'AbortError' })), + ); + }), + }; + let hud; + try { + hud = new IntelHUD(env.viewer, { summaryService }); + hud._summaryContext = async () => ({ place: 'San Francisco' }); + hud._updateCameraData(); + const settle = () => new Promise((resolve) => setImmediate(resolve)); + const first = hud._updateSummary(false); + await settle(); + assert.equal(pending.length, 1); + env.cameraListeners.moveStart(); + await first; + + // An orbit can leave all semantic place/layer labels unchanged. The next + // periodic tick must retry even though its context equals the aborted one. + const retry = hud._updateSummary(false); + await settle(); + assert.equal( + pending.length, + 2, + 'the cancelled signature cannot suppress a retry', + ); + assert.deepEqual(pending[1].context, pending[0].context); + pending[1].reply('San Francisco Bay Urban Landscape'); + await retry; + assert.equal( + env.elements.get('hud-summary').textContent, + 'San Francisco Bay Urban Landscape', + ); + + // Movement without an active request must not discard a completed answer. + env.cameraListeners.moveStart(); + await hud._updateSummary(false); + assert.equal(pending.length, 2, 'completed context still deduplicates'); + } finally { + for (const request of pending) request.reply(''); + hud?.destroy(); + if (previousWindow === undefined) delete globalThis.window; + else globalThis.window = previousWindow; + env.restore(); + } +}); + +test('after a dropped or timed-out request the next tick asks again, and a move stops typing', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }); + const env = installHudEnvironment(); + const previousWindow = globalThis.window; + globalThis.window = globalThis; + const pending = []; + const summaryService = { + summarize: (context, { signal }) => + new Promise((resolve, reject) => { + pending.push({ resolve }); + signal.addEventListener('abort', () => + reject(Object.assign(new Error('aborted'), { name: 'AbortError' })), + ); + }), + }; + let hud; + try { + hud = new IntelHUD(env.viewer, { summaryService }); + // The same place before and after: a slow follow camera, a small pan. + hud._summaryContext = async () => ({ place: 'Lisboa' }); + const element = env.elements.get('hud-summary'); + const settle = () => new Promise((resolve) => setImmediate(resolve)); + hud._updateCameraData(); + + // A move aborts the request; the next tick over the same place asks again. + let update = hud._updateSummary(false); + await settle(); + env.cameraListeners.moveStart(); + await update; + update = hud._updateSummary(false); + await settle(); + assert.equal(pending.length, 2, 'asked again after the abort'); + + // That one times out at 5 s: retried like any failure. + t.mock.timers.tick(5_000); + await update; + update = hud._updateSummary(false); + await settle(); + assert.equal(pending.length, 3, 'asked again after the timeout'); + pending[2].resolve({ + ok: true, + status: 200, + data: { summary: 'Lisboa Rua Augusta', error: null }, + }); + await update; + + // A reply still typing stops when the camera starts moving. + hud._typeSummary('Canyon Junction Wyoming Yellowstone National Park'); + t.mock.timers.tick(48); + const typed = element.textContent; + env.cameraListeners.moveStart(); + t.mock.timers.tick(2_000); + assert.equal( + element.textContent, + typed, + 'no more characters after the move', + ); + } finally { + hud?.destroy(); + if (previousWindow === undefined) delete globalThis.window; + else globalThis.window = previousWindow; + env.restore(); + } +}); + +test('a summary interrupted while typing can retry unchanged context', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }); + const env = installHudEnvironment(); + const previousWindow = globalThis.window; + globalThis.window = globalThis; + let calls = 0; + const text = 'San Francisco Bay Urban Landscape'; + const summaryService = { + summarize: async () => { + calls++; + return { ok: true, status: 200, data: { summary: text } }; + }, + }; + let hud; + try { + hud = new IntelHUD(env.viewer, { summaryService }); + hud._summaryContext = async () => ({ place: 'San Francisco' }); + hud._updateCameraData(); + await hud._updateSummary(true); + t.mock.timers.tick(48); + const element = env.elements.get('hud-summary'); + assert.notEqual(element.textContent, text, 'the answer is still typing'); + assert.equal( + hud._summaryRequest, + null, + 'the network request already finished', + ); + env.cameraListeners.moveStart(); + assert.equal(hud._summaryTypingInterval, null); + await hud._updateSummary(false); + assert.equal( + calls, + 2, + 'a partially displayed answer must not suppress retry', + ); + assert.equal(element.textContent, text); + env.cameraListeners.moveStart(); + await hud._updateSummary(false); + assert.equal(calls, 2, 'the fully displayed answer remains reusable'); + } finally { + hud?.destroy(); + if (previousWindow === undefined) delete globalThis.window; + else globalThis.window = previousWindow; + env.restore(); + } +}); From 99429904d4c80709d4e4955aa908aedb9931972d Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 25 Oct 2026 12:32:10 -0400 Subject: [PATCH 27/54] fix(draw): show a 999.6 m line as 1.0 km, not 1000 m formatMeasure checked the raw length against 1000 but printed it rounded, so a drawn line of 999.5 m or more read "1000 m" in the hint. Compare the rounded metres so it moves to kilometres. --- changelog.d/1388-draw-line-kilometre.md | 3 +++ src/annotations/drawMode.js | 7 ++++--- src/annotations/drawMode.test.mjs | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 changelog.d/1388-draw-line-kilometre.md diff --git a/changelog.d/1388-draw-line-kilometre.md b/changelog.d/1388-draw-line-kilometre.md new file mode 100644 index 0000000000..1370757076 --- /dev/null +++ b/changelog.d/1388-draw-line-kilometre.md @@ -0,0 +1,3 @@ +- Show a drawn line of 999.5 m or more as 1.0 km. The draw hint kept metres + below 1000, then rounded 999.6 m up to "1000 m" + (Rudy Celekli, @rudycelekli, #1388). diff --git a/src/annotations/drawMode.js b/src/annotations/drawMode.js index fcfe08be6b..538c2e5da9 100644 --- a/src/annotations/drawMode.js +++ b/src/annotations/drawMode.js @@ -208,9 +208,10 @@ export function formatMeasure(session) { if (!session) return ''; if (session.shape === 'line') { const m = pathLengthM(session.vertices); - return m >= 1000 - ? `${(m / 1000).toFixed(m >= 10000 ? 0 : 1)} km` - : `${Math.round(m)} m`; + // Round before the kilometre cut. 999.6 m was printed as "1000 m". + const whole = Math.round(m); + if (whole < 1000) return `${whole} m`; + return `${(m / 1000).toFixed(m >= 10000 ? 0 : 1)} km`; } if (session.shape === 'area') { const m2 = ringAreaM2(session.vertices); diff --git a/src/annotations/drawMode.test.mjs b/src/annotations/drawMode.test.mjs index 50475cc9eb..be9894dda0 100644 --- a/src/annotations/drawMode.test.mjs +++ b/src/annotations/drawMode.test.mjs @@ -330,3 +330,18 @@ test('longitude unwrapping is continuous and re-wraps to one canonical range', ( assert.equal(wrapLongitude(180), -180); assert.equal(unwrapLongitudes([]).length, 0); }); + +test('a line that rounds up to a kilometre reads 1.0 km, not 1000 m', () => { + const metresPerDegree = (6371.0088 * 1000 * Math.PI) / 180; + const lat = 999.6 / metresPerDegree; + const line = createDrawSession('line'); + addVertex(line, { lon: 0, lat: 0 }); + addVertex(line, { lon: 0, lat }); + const metres = pathLengthM(line.vertices); + assert.ok( + metres >= 999.5 && metres < 1000, + `length should round to 1000 m, got ${metres}`, + ); + assert.equal(formatMeasure(line), '1.0 km'); + assert.match(drawHint(line), /^1\.0 km · /); +}); From 5ef12391e143099e445912222f8105633dad0cb9 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 25 Oct 2026 12:32:18 -0400 Subject: [PATCH 28/54] =?UTF-8?q?fix(cockpit):=20show=20wind=20from=20359.?= =?UTF-8?q?6=C2=B0=20as=200=C2=B0,=20not=20360=C2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit formatCockpitWindDirection rounded the bearing and printed that number, so wind from 359.5° or more read "N · 360°". Take the rounded degrees modulo 360 so north reads 0°. --- changelog.d/1389-cockpit-wind-north.md | 3 +++ src/ui/cockpitPresentation.js | 4 +++- src/ui/cockpitPresentation.test.mjs | 10 ++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 changelog.d/1389-cockpit-wind-north.md create mode 100644 src/ui/cockpitPresentation.test.mjs diff --git a/changelog.d/1389-cockpit-wind-north.md b/changelog.d/1389-cockpit-wind-north.md new file mode 100644 index 0000000000..cc81c362ec --- /dev/null +++ b/changelog.d/1389-cockpit-wind-north.md @@ -0,0 +1,3 @@ +- Show cockpit wind from 359.5° or more as 0°, not 360°. Rounding 359.6° + printed "N · 360°" on the local wind direction + (Rudy Celekli, @rudycelekli, #1389). diff --git a/src/ui/cockpitPresentation.js b/src/ui/cockpitPresentation.js index 8285b74b3f..b9c0005030 100644 --- a/src/ui/cockpitPresentation.js +++ b/src/ui/cockpitPresentation.js @@ -156,7 +156,9 @@ export function formatCockpitWindDirection(value) { if (!Number.isFinite(value)) return t('DIR UNKNOWN'); const labels = Object.keys(COMPASS_POINT_LABELS); const normalized = ((value % 360) + 360) % 360; - return `${compassPointLabel(labels[Math.round(normalized / 45) % labels.length])} · ${Math.round(normalized)}°`; + // 359.5° and above is north. Modulo keeps that from printing 360°. + const degrees = Math.round(normalized) % 360; + return `${compassPointLabel(labels[Math.round(normalized / 45) % labels.length])} · ${degrees}°`; } // Digit grouping and decimal marks (`26,175`, `26 175`, `26.175`) take a diff --git a/src/ui/cockpitPresentation.test.mjs b/src/ui/cockpitPresentation.test.mjs new file mode 100644 index 0000000000..da5c8e53bb --- /dev/null +++ b/src/ui/cockpitPresentation.test.mjs @@ -0,0 +1,10 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { formatCockpitWindDirection } from './cockpitPresentation.js'; + +test('wind just west of north reads 0°, not 360°', () => { + assert.equal(formatCockpitWindDirection(90), 'E · 90°'); + assert.equal(formatCockpitWindDirection(0), 'N · 0°'); + assert.equal(formatCockpitWindDirection(359.4), 'N · 359°'); + assert.equal(formatCockpitWindDirection(359.6), 'N · 0°'); +}); From 63866c201af35acabcef580662cae152d62faf20 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 25 Oct 2026 13:28:23 -0400 Subject: [PATCH 29/54] fix(awareness): wrap north-bound bearings --- changelog.d/1390-awareness-bearing-north.md | 2 ++ src/layers/awareness/presentation.js | 10 ++++++++++ src/layers/awareness/presentation.test.mjs | 11 +++++++++++ src/layers/awareness/rendering.js | 5 +++-- 4 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 changelog.d/1390-awareness-bearing-north.md create mode 100644 src/layers/awareness/presentation.js create mode 100644 src/layers/awareness/presentation.test.mjs diff --git a/changelog.d/1390-awareness-bearing-north.md b/changelog.d/1390-awareness-bearing-north.md new file mode 100644 index 0000000000..af7fb4da3b --- /dev/null +++ b/changelog.d/1390-awareness-bearing-north.md @@ -0,0 +1,2 @@ +- Render awareness-overlay bearings and courses that round through north as + `000°`, rather than `360°` (Rudy Celekli, #1390). diff --git a/src/layers/awareness/presentation.js b/src/layers/awareness/presentation.js new file mode 100644 index 0000000000..7439907d9c --- /dev/null +++ b/src/layers/awareness/presentation.js @@ -0,0 +1,10 @@ +/** + * Format a compass direction for the awareness overlay. + * @param {number} degrees + * @returns {string} + */ +export function formatAwarenessDirection(degrees) { + if (!Number.isFinite(degrees)) return '—'; + const normalized = ((degrees % 360) + 360) % 360; + return String(Math.round(normalized) % 360).padStart(3, '0'); +} diff --git a/src/layers/awareness/presentation.test.mjs b/src/layers/awareness/presentation.test.mjs new file mode 100644 index 0000000000..54d40765f0 --- /dev/null +++ b/src/layers/awareness/presentation.test.mjs @@ -0,0 +1,11 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { formatAwarenessDirection } from './presentation.js'; + +test('awareness bearings that round through north read 000, not 360', () => { + assert.equal(formatAwarenessDirection(359.4), '359'); + assert.equal(formatAwarenessDirection(359.6), '000'); + assert.equal(formatAwarenessDirection(0), '000'); + assert.equal(formatAwarenessDirection(-0.4), '000'); + assert.equal(formatAwarenessDirection(Number.NaN), '—'); +}); diff --git a/src/layers/awareness/rendering.js b/src/layers/awareness/rendering.js index 8fe147e460..957e0bbdd7 100644 --- a/src/layers/awareness/rendering.js +++ b/src/layers/awareness/rendering.js @@ -11,6 +11,7 @@ import { } from '../../data/militaryAwarenessEngine.js'; import { bearingBetweenCoordinates } from '../../cockpitMath.js'; import { AWARENESS_PAGE_SIZE, CONTEXT_RIM_HEIGHT_M } from './policy.js'; +import { formatAwarenessDirection } from './presentation.js'; export function createRendering({ state: layerState, @@ -225,12 +226,12 @@ export function createRendering({ : null; const bearingText = Number.isFinite(bearing) ? t('BRG {value}°', { - value: String(Math.round(bearing)).padStart(3, '0'), + value: formatAwarenessDirection(bearing), }) : t('BRG —'); const courseText = Number.isFinite(item.track) ? ` · ${t('CRS {value}°', { - value: String(Math.round(item.track)).padStart(3, '0'), + value: formatAwarenessDirection(item.track), })}` : ''; marker._label.textContent = `${label} · ${formatAwarenessDistance(item.distanceM)}\n${bearingText}${courseText}`; From f81ef406f7cafdb1a03ecb2a28aa19ca760cd23b Mon Sep 17 00:00:00 2001 From: John Rogers Date: Sun, 25 Oct 2026 14:08:14 -0500 Subject: [PATCH 30/54] =?UTF-8?q?(=E3=81=A3=E2=96=80=C2=AF=E2=96=80)?= =?UTF-8?q?=E3=81=A4=20--=20Issue=20#1240:=20added=20docker=20health=20che?= =?UTF-8?q?cks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Dockerfile b/Dockerfile index d34f4887ad..4628279aff 100644 --- a/Dockerfile +++ b/Dockerfile @@ -39,6 +39,11 @@ COPY --chown=node:node . . ENV HOST=0.0.0.0 ENV PORT=4173 EXPOSE 4173 +# node:slim has no curl, so probe with Node's built-in fetch. 127.0.0.1 is +# always on the Host allowlist, and the generous start period covers Vite's +# first-run dependency optimisation. +HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \ + CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||4173)+'/').then((r)=>process.exit(r.ok?0:1),()=>process.exit(1))"] # The launcher is `npm run dev` plus one step: it trusts the container's # gateway address for Provider Settings, because that is where Docker delivers # the host's own browser from (never 127.0.0.1). See scripts/docker-start.mjs. From 6ebdee6710bbfae5e678feb414b300a72a8a2efa Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 12:11:19 -0700 Subject: [PATCH 31/54] docs: document PR #1388 rounding behavior --- docs/CURRENT-STATE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 9afb99c457..438d41776f 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5240,6 +5240,7 @@ are omitted rather than framing the wrong part of the globe. - **A vertex is a lon/lat, and the mark is DRAPED.** Clicks are picked through `pickWorldFromScreen` — one of two scene helpers the annotation resolver factory (`src/annotations/resolver.js`) exposes alongside `sampleGroundHeight`, so the app has ONE depth-aware pick cascade rather than a second written beside it — which returns the height the pick landed on as well as the coordinate, so the live preview hangs on the roof or hillside under the pointer instead of sinking to sea level. The world renderer draws areas and routes with `clampToGround`, so the height is dropped at finish in one place (`finishSpec`) rather than being carried downstream and discarded silently: what you get is the outline you drew, lying on the surface beneath it. - **Draped marks classify onto `ClassificationType.BOTH`** — terrain AND 3D tiles — not onto 3D tiles alone. With only `CESIUM_3D_TILE`, every area fill, area outline, route and arrow rendered to nothing on a keyless boot, where Cesium's own globe carries Esri/OSM imagery and there are no tiles to classify against; the labels appeared and the geometry did not. That hit spoken annotations exactly as hard as hand-drawn ones. `scripts/qa-draw-tool.mjs` counts the mark's own colour in the rendered frame before and after a shape is finished, on a keyed AND a keyless server, so "the board says there is a mark" can no longer pass for "the mark is on screen". - **A finished area is a CLOSED ring.** The fill polygon closes itself but the outline beside it is a polyline, so an open ring drew every edge except the one back to the first vertex — a triangle with two sides. `finishSpec` repeats the first position at the end. A line is never closed: joining its ends would invent a segment nobody drew. +- Drawn-line distance labels select metres or kilometres after rounding to the nearest metre, so a 999.5-metre line displays as `1.0 km` rather than `1000 m`. - **Measurements and centres are computed on unwrapped longitudes** (`unwrapLongitudes` / `wrapLongitude` in `drawMode.js`, used by `ringAreaM2`, `ringCentroid` and the engine's manual-area anchor). A ~50,000 m² rectangle straddling the antimeridian reads its 0.002° width as 359.998° under raw arithmetic: it measured thousands of square kilometres and anchored on the Greenwich meridian, half a world from the shape. Path length was already safe — haversine is periodic in the longitude delta — and a test pins that so a "fix" cannot break it. - **Bounds.** One shape holds at most `MAX_VERTICES` = 512 points; two clicks within 0.5 m are one vertex (that is what makes a double-click finish without leaving a stray point); a vertex that is not a finite on-globe coordinate is refused. A shape that encloses nothing is refused rather than placed: three collinear points are not an area and a line under a metre long is not a line, and the hint says which. - Pointer ownership: while a session is open the tool holds the single pointer claim (`claimPointer('draw')`, `src/data/inputOwnership.js`) and **every** ambient scene selection handler — the shared tracking click gesture behind flights, military and CCTV, plus vessels, satellites, launches, fires, installations, bikeshare, radio, submarine cables, the bundled GeoJSON layers and the CCTV calibration gizmo — returns before picking. A vertex over an aircraft is a vertex, not a selection. From 8f025416573a88557ea65797750c31d80975960f Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 12:11:49 -0700 Subject: [PATCH 32/54] docs: document PR #1389 rounding behavior --- docs/CURRENT-STATE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 9afb99c457..dedc6489b6 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5460,6 +5460,7 @@ pins and share links already supply complete boxes. - **Cockpit Context scope:** the 250 km radius applies to the air/sea proximity cohorts. Installation counts come only from the currently loaded viewport and are labeled `CURRENT VIEWPORT ONLY` in the cockpit as well as the normal Context panel; neither surface presents them as a complete 250 km installation survey. - **Cockpit camera anchor:** first-person mode does not write feed-boundary corrections directly into the camera. A cockpit-only inertial anchor advances from the selected aircraft's displayed course and speed, then converges toward the authoritative delayed track with correction capped below forward motion. The displayed kinematics are derived from the same consecutive fix segment as the rendered position, with raw feed speed/course used only as fallback; a transient zero/missing feed speed therefore cannot freeze a visibly moving aircraft after layer enable or a map/cockpit handoff. Rendered altitude continues to come from that interpolated track position. Late ADS-B fixes and short render stalls can remove drift without accelerating or reversing the view. Camera placement runs before scene update/culling at a bounded 20 Hz so a moving cockpit does not force Photoreal 3D Tiles to retraverse on every display frame; textual instruments update at 10 Hz and context/layout work at 4 Hz. Every far Cockpit contact pip shares one stable Cesium texture-atlas entry and skips unused screen-projected course calculations, while only in-range 2D aircraft silhouettes pay the screen-projected rotation cost; ambient glTF collections are hidden/retained rather than synchronously destroyed at cockpit entry, and context rails lay out only on explicit content/state changes and viewport resize. The deliberate 15/30-second layer interpolation delays and per-Cesium-frame position caches remain unchanged. - **Cockpit route, vision, and view controls:** visible on-screen `COCKPIT`, `RESET`, and `EXIT COCKPIT` controls replace reliance on the `C` shortcut. RESET uses the same canonical globe route as the map and voice actions, exits Cockpit, and releases its camera ownership rather than exposing the hidden map-style top action. When the tracked commercial flight has a plausible ADSBDB route, the top of the right briefing rail shows a compact `FROM → TO` airport strip and the visor shows a centered estimated-destination chevron with its relative bearing; its destination label rounds to whole degrees in 000–359, wrapping rounded north to 000° while the chevron continues to use the relative bearing independently of label rounding; absent or implausible route data hides the strip and cue rather than guessing. The cockpit-local vision control is an interactive `PREV / CURRENT / NEXT` carousel over `NORMAL`, `CRT`, `NVG`, `FLIR`, `ANIME`, `NOIR`, and `SNOW`; its previous/next actions wrap, and activating the current value advances to the next style. Cockpit enters on the active map preset, so a Cyber FLIR map opens Cockpit on FLIR while Normal remains a distinct option instead of producing a second FLIR entry. Cockpit choices temporarily activate the existing Cesium post-process stages, while exiting Cockpit through either EXIT or RESET restores the pre-entry map style. The regional-news page uses a free Google News RSS locality query first, with the existing GDELT query retained only as a fail-soft fallback; linked headlines remain reporting, not verified incidents or risk intelligence. +- Cockpit wind-direction labels wrap after rounding to whole degrees, so a direction of 359.5° displays as `N · 0°` rather than `N · 360°`. - **Cockpit missing observations:** missing local weather observations remain unknown rather than being converted to zero or clear skies, in the briefing and in the cloud effects; a missing temperature drops the whole local weather record, including its wind and condition. - **Cockpit weather status:** the earlier multi-canvas atmospheric compositor remains fail-closed and is not attached to the live viewer. Cockpit clouds are a separate transparent WebGL pass with a capped 520×320 framebuffer, 24 ray steps, three FBM octaves, and a 12 FPS ceiling. It defaults off and starts only when local storage explicitly contains the persisted `WX ON` opt-in (`'1'`). When opted in, observations refresh after five minutes or 25 km of aircraft movement, fail transparent when unavailable or clear, and stop on exit or disable. `WX OFF` governs atmospheric rendering only: the briefing still fetches source-backed Natural Earth region, headline, and Open-Meteo local-information data, aborting and replacing any in-flight request when the selected aircraft changes. No weather effect runs in map mode and no synthetic fallback is shown. - **Cockpit trail visibility:** entering cockpit hides the selected aircraft's trail body and head so they cannot cross the first-person view; exit restores them. This cockpit-only presentation change does not alter the normal map-mode invariant that aircraft trails render through terrain using their depth-fail material. From 69fba2ebbe44d04d237852cc6b0c71a00d9db1e6 Mon Sep 17 00:00:00 2001 From: quanticsoul4772 <71096528+quanticsoul4772@users.noreply.github.com> Date: Sun, 25 Oct 2026 12:36:50 -0700 Subject: [PATCH 33/54] fix(perf): free a turned-off layer's entities that Cesium keeps (#1367) Release stale Cesium command references after disabling a layer while preserving current-frame commands. Contribution by @quanticsoul4772. --- changelog.d/1367-turned-off-layer-memory.md | 4 + docs/CURRENT-STATE.md | 10 ++ scripts/package-boundaries.json | 3 +- src/app/tools.js | 10 ++ src/sceneCommandRelease.js | 74 +++++++++++ src/sceneCommandRelease.test.mjs | 137 ++++++++++++++++++++ 6 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 changelog.d/1367-turned-off-layer-memory.md create mode 100644 src/sceneCommandRelease.js create mode 100644 src/sceneCommandRelease.test.mjs diff --git a/changelog.d/1367-turned-off-layer-memory.md b/changelog.d/1367-turned-off-layer-memory.md new file mode 100644 index 0000000000..08bbbad81f --- /dev/null +++ b/changelog.d/1367-turned-off-layer-memory.md @@ -0,0 +1,4 @@ +- Turning a layer off frees the memory its entities held. Cesium kept + removed layers' draw commands in reused per-pass arrays, so Data Centers + kept 116 MiB after it was switched off, submarine cables 74 MiB and dams + 30 MiB; they now keep 13, 9 and 9 MiB (quanticsoul4772, #1367). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index b9bc87ad2b..b15babbb2e 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2159,6 +2159,16 @@ fetching, trailing-24-hour filtering and partial-success caching are unchanged. > always exits non-zero, `1` meaning the control is healthy and `2` meaning it > is not. Plus the unit pins above. +> **2026-10-24 — a turned-off layer's memory is released:** Cesium 1.138 +> keeps the draw commands past each frame's count in the opaque and other +> per-pass arrays (`View.frustumCommandsList`) and in the offscreen pick view, +> so a turned-off layer's entities stayed reachable (Data Centers kept 116 +> MiB). `src/sceneCommandRelease.js`, installed in `src/app/tools.js`, +> requests one frame through `governorRequestRender` after every layer +> disable and then trims those arrays. It reads private Cesium fields; +> `src/sceneCommandRelease.test.mjs` pins them and fails if Cesium renames +> them or changes which passes it truncates. + > **2026-08-08 — performance waves 1+2:** the app idles via an explicit render > governor (`src/renderGovernor.js` — hold/release from every per-frame > animator; discrete mutators call `governorRequestRender`). Any NEW diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index c84a11cad5..68a57066aa 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2574,7 +2574,8 @@ "src/voice/geminiSession.js", "src/voice/geminiAudio.js", "src/voice/geminiCaptureWorklet.js", - "src/ui/statusBadge.js" + "src/ui/statusBadge.js", + "src/sceneCommandRelease.js" ], "external": [ "hls.js", diff --git a/src/app/tools.js b/src/app/tools.js index 7b3ea83c96..7aea39c22b 100644 --- a/src/app/tools.js +++ b/src/app/tools.js @@ -7,6 +7,7 @@ import { createRecentImageryPanel } from '../ui/recentImagery.js'; import { initGevVoiceCommands } from '../voice/gevRealtime.js'; import { installViews, isEmbeddedInline } from './embed.js'; import { installScopeMask, destroyScopeMask } from '../scopeMask.js'; +import { installLayerReleaseTrim } from '../sceneCommandRelease.js'; import { installRenderGovernor, getRenderGovernorDiagnostics, @@ -110,6 +111,15 @@ export function createApplicationTools({ // nothing animates per frame. Installed AFTER every module above has had // its chance to register pre-install holds. (perf wave 2) installRenderGovernor(viewer); + // Cesium keeps a turned-off layer's draw commands (and so all its entities) + // alive in reused per-pass arrays; trim them after each disable. + defer( + installLayerReleaseTrim({ + scene: viewer.scene, + dataManager, + requestRender: governorRequestRender, + }), + ); // Install the explicit scope mask used by the DISPLAY controls. installScopeMask(viewer); diff --git a/src/sceneCommandRelease.js b/src/sceneCommandRelease.js new file mode 100644 index 0000000000..4d85944018 --- /dev/null +++ b/src/sceneCommandRelease.js @@ -0,0 +1,74 @@ +/** + * Let a turned-off layer's memory go. + * + * Cesium (engine 22.3, `Scene/View.js`) reuses each view's per-pass command + * arrays: every frame resets `frustumCommands.indices[pass]` to 0 and + * overwrites `commands[pass][i]` from the start. `Scene.js` truncates the + * voxel, Gaussian-splat and translucent passes to their counts; the opaque + * and other passes keep the slots past the new count. When a layer is turned + * off the next frame has fewer commands, so that tail keeps the destroyed + * primitives' DrawCommands, and through `_owner` → primitive → entity → + * EntityCollection the whole data source stays reachable. The offscreen view + * `scene.sampleHeight` / `pickFromRay` render into keeps its last list the + * same way, until the next height sample. + * + * Measured (production build, heap after GC, Data Centers on → off): 116 MiB + * kept on main, 13 MiB with this module; heap snapshots traced the entities + * through `View.frustumCommandsList` and `Picking._pickOffscreenView`. + * + * After a layer finishes turning off, this renders one frame, trims the main + * view's arrays to that frame's counts, and empties the offscreen pick view's + * lists (it rebuilds them in full on every pick). It reads private Cesium + * fields: `src/sceneCommandRelease.test.mjs` fails if any of them is renamed + * or if Cesium changes which passes it truncates, and once Cesium clears the + * tail itself this module can go. + */ + +/** Drop command references a view no longer draws. */ +function trimView(view, { keepCurrent }) { + for (const frustum of view?.frustumCommandsList || []) { + const { commands, indices } = frustum; + for (let pass = 0; pass < commands.length; pass += 1) { + const keep = keepCurrent ? indices[pass] : 0; + if (commands[pass].length > keep) commands[pass].length = keep; + if (!keepCurrent) indices[pass] = 0; + } + } + if (!keepCurrent) + for (const extent of view?._commandExtents || []) + extent.command = undefined; +} + +/** + * Release stale command references in the scene's main view (keeping what + * the last frame drew) and in its offscreen pick view (all of it). + * @param {object} scene Cesium Scene, right after a render. + */ +export function trimStaleSceneCommands(scene) { + trimView(scene._defaultView, { keepCurrent: true }); + trimView(scene._picking?._pickOffscreenView, { keepCurrent: false }); +} + +/** + * After every layer disable, render one frame and trim once it is drawn. + * @param {{scene: object, dataManager: object, requestRender: (reason: string) => void}} deps + * @returns {() => void} uninstall + */ +export function installLayerReleaseTrim({ scene, dataManager, requestRender }) { + let removeOneShot = null; + const unsubscribe = dataManager.subscribe((change) => { + if (change?.type !== 'visibility' || change.enabled !== false) return; + if (removeOneShot) return; // a trim is already waiting for its frame + removeOneShot = scene.postRender.addEventListener(() => { + removeOneShot(); + removeOneShot = null; + trimStaleSceneCommands(scene); + }); + requestRender('layer-release-trim'); + }); + return () => { + unsubscribe(); + removeOneShot?.(); + removeOneShot = null; + }; +} diff --git a/src/sceneCommandRelease.test.mjs b/src/sceneCommandRelease.test.mjs new file mode 100644 index 0000000000..d880378721 --- /dev/null +++ b/src/sceneCommandRelease.test.mjs @@ -0,0 +1,137 @@ +// A turned-off layer's draw commands must not stay reachable through Cesium's +// reused per-pass command arrays (src/sceneCommandRelease.js). +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; +import { + installLayerReleaseTrim, + trimStaleSceneCommands, +} from './sceneCommandRelease.js'; + +const frustum = (lists, counts) => ({ + commands: lists.map((list) => [...list]), + indices: [...counts], +}); + +test('the main view keeps what the last frame drew and drops the stale tail', () => { + const view = { + frustumCommandsList: [frustum([['a', 'b', 'stale'], ['c'], []], [2, 1, 0])], + }; + trimStaleSceneCommands({ _defaultView: view }); + assert.deepEqual(view.frustumCommandsList[0].commands, [ + ['a', 'b'], + ['c'], + [], + ]); + assert.deepEqual(view.frustumCommandsList[0].indices, [2, 1, 0]); +}); + +test('the offscreen pick view is emptied, since every pick rebuilds it', () => { + const extents = [{ command: 'x' }, { command: 'y' }]; + const pick = { + frustumCommandsList: [frustum([['p', 'q'], ['r']], [2, 1])], + _commandExtents: extents, + }; + trimStaleSceneCommands({ + _defaultView: { frustumCommandsList: [] }, + _picking: { _pickOffscreenView: pick }, + }); + assert.deepEqual(pick.frustumCommandsList[0].commands, [[], []]); + assert.deepEqual(pick.frustumCommandsList[0].indices, [0, 0]); + assert.deepEqual( + extents.map((e) => e.command), + [undefined, undefined], + ); +}); + +test('a layer disable renders one frame and trims after it', () => { + const listeners = new Set(); + const postRender = new Set(); + const requests = []; + const view = { frustumCommandsList: [frustum([['a', 'stale']], [1])] }; + const scene = { + _defaultView: view, + postRender: { + addEventListener(fn) { + postRender.add(fn); + return () => postRender.delete(fn); + }, + }, + }; + const uninstall = installLayerReleaseTrim({ + scene, + dataManager: { + subscribe(fn) { + listeners.add(fn); + return () => listeners.delete(fn); + }, + }, + requestRender: (reason) => requests.push(reason), + }); + const emit = (change) => listeners.forEach((fn) => fn(change)); + + emit({ type: 'visibility', layerId: 'x', enabled: true }); + assert.equal(requests.length, 0, 'enabling trims nothing'); + emit({ type: 'visibility', layerId: 'x', enabled: false }); + emit({ type: 'visibility', layerId: 'y', enabled: false }); + assert.deepEqual( + requests, + ['layer-release-trim'], + 'one frame for back-to-back disables', + ); + assert.equal( + view.frustumCommandsList[0].commands[0].length, + 2, + 'not before the frame', + ); + postRender.forEach((fn) => fn()); + assert.deepEqual(view.frustumCommandsList[0].commands, [['a']]); + assert.equal(postRender.size, 0, 'the frame listener is one-shot'); + uninstall(); + assert.equal(listeners.size, 0); +}); + +// The workaround reads private Cesium fields. Pin the shape it relies on, and +// fail when Cesium starts clearing the tail itself so the module can go. +test('Cesium still reuses per-pass command arrays without clearing their tail', () => { + const require = createRequire(import.meta.url); + const enginePkg = require.resolve('@cesium/engine/package.json'); + const read = (rel) => + readFileSync(new URL(rel, pathToFileURL(enginePkg)), 'utf8'); + const scene = read('./Source/Scene/Scene.js'); + const view = read('./Source/Scene/View.js'); + const frustumCommands = read('./Source/Scene/FrustumCommands.js'); + const picking = read('./Source/Scene/Picking.js'); + // Every private field the trim reads. A rename would otherwise turn the + // trim into a silent no-op (it reaches them through `?.` and `|| []`). + assert.match(scene, /this\._picking = new Picking\(this\);/); + assert.match(scene, /this\._defaultView = new View\(/); + assert.match(picking, /this\._pickOffscreenView = new View\(/); + assert.match(view, /this\.frustumCommandsList = \[\];/); + assert.match(view, /frustumCommandsList\[n\]\.indices\[p\] = 0;/); + assert.match(view, /this\._commandExtents = \[\];/); + assert.match( + frustumCommands, + /this\.commands = commands;\s*this\.indices = indices;/, + ); + // Cesium truncates only the voxel, Gaussian-splat and translucent passes, + // each in its own draw step; the opaque and other passes keep their tail. + // A change here means Cesium's handling moved: re-check whether this + // module is still needed. + assert.doesNotMatch( + view, + /\.length\s*=\s*[^;]*indices\[/, + 'View.js now truncates the per-pass arrays: remove src/sceneCommandRelease.js', + ); + assert.deepEqual( + [ + ...scene.matchAll( + /commands\.length = frustumCommands\.indices\[Pass\.(\w+)\];/g, + ), + ].map((match) => match[1]), + ['VOXELS', 'GAUSSIAN_SPLATS', 'TRANSLUCENT'], + 'Scene.js truncates a different set of passes: re-check src/sceneCommandRelease.js', + ); +}); From ac8dc84f3cca503a55486de5211e69ab6f93b459 Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Sun, 25 Oct 2026 19:43:01 +0000 Subject: [PATCH 34/54] docs: require screenshots, recording, category and data licence on new-layer PRs (#957) Document visual evidence, category and data licensing requirements for new layers, using the changelog fragment workflow. Contribution by @asturksever. --- .github/pull_request_template.md | 59 ++++++++++++++++++++++++++++++++ CONTRIBUTING.md | 29 +++++++++++++++- 2 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 .github/pull_request_template.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..e8c9f8bdfe --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,59 @@ +## What this changes + + + +## How I verified it + +- [ ] `npm run build` +- [ ] `npm test` +- [ ] `npm run test:track` (dev server running) +- [ ] Feature gate for the area I touched: + + + +## New layer checklist + + + +**Screenshots** + + + +**Recording** + + + +**Proposed category** + + + +Category: + +**Data source and licence** + +- Source (provider and endpoint): +- Licence or terms (link): +- Attribution shown in the app: +- Needs a key? (none / optional / required): +- Fetched at runtime, or bundled in the repo: + + + +- [ ] Added a row to `DATA_SOURCES.md` +- [ ] Credit is registered in `src/data/dataCredits.js` +- [ ] Share-link token assigned with `npm run layer-token:next`, if the layer is shareable + +## Docs + +- [ ] `docs/CURRENT-STATE.md` updated and a `changelog.d/-.md` fragment added, or this PR doesn't change runtime behaviour diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bb2c2de9ee..a7fe8ab766 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -108,7 +108,7 @@ prints anything; never fix that by renaming or deleting PR A's published token. The highest-leverage places to jump in: - **🌆 Add a CCTV source pack.** Austin is the reference camera source. Adding another city means a clean public camera catalog with coordinates, attribution, and server-registered frame URLs (the proxy only fetches registered URLs — never client-supplied ones, see [SECURITY.md](SECURITY.md)). City packs are the best first lane. -- **🛰️ Add or improve a data layer.** Layer factories live in `src/layers//`, with source, record, controller and renderer owners implementing the layer interface (`init/enable/disable/update/destroy/getStats`, optional `getDetectableObjects`/`getStats`). Use an existing layer as a template. +- **🛰️ Add or improve a data layer.** Layer factories live in `src/layers//`, with source, record, controller and renderer owners implementing the layer interface (`init/enable/disable/update/destroy/getStats`, optional `getDetectableObjects`/`getStats`). Use an existing layer as a template, and see [Adding a new layer](#adding-a-new-layer) for what the PR needs. - **🎙️ Extend voice control.** Voice arguments are defined in `src/voice/actionSchemas.js`, with server-side descriptions in `server/providers/openai/tools.js` and client-side execution in `src/voice/gevActions.js`. Keep the tool surface tight and the responses honest (confirm only what actually happened). - **🎨 Add a visual style.** Styles are GLSL post-process shaders in `src/styles/`. - **🐛 Fix bugs / improve the first-run experience.** See [docs/KNOWN-ISSUES.md](docs/KNOWN-ISSUES.md). @@ -153,6 +153,33 @@ ownership and adoption process. 3. If you change runtime behavior, update `docs/CURRENT-STATE.md` in the same PR, and add your changelog entry as `changelog.d/-.md` instead of editing `CHANGELOG.md` — see [changelog.d/README.md](changelog.d/README.md). Distinct filenames don't conflict; a release assembles the directory into `CHANGELOG.md`. A documentation claim that needs a regression test should assert against `docs/CURRENT-STATE.md` or `README.md`, which a PR still edits directly. 4. If you add or change a data source, update [DATA_SOURCES.md](DATA_SOURCES.md) with its license and attribution. **Don't add data you don't have the right to redistribute** — fetch it at runtime instead. 5. Describe what you changed and how you verified it (screenshots welcome for anything visual). +6. If you add a new layer, fill in the new-layer section of the PR template. See [Adding a new layer](#adding-a-new-layer). + +## Adding a new layer + +A new layer changes what everyone sees on the globe, so maintainers need to see +it working and know where its data comes from before reviewing the code. PRs +that add a layer must include all four of these in the description. The PR +template has a section for them. + +1. **Screenshots.** At least one of the layer on the globe, plus its info card + or panel if it has one. +2. **A screen recording**, preferably 15 to 30 seconds: turn the layer on, move + around, and open a record. Drag an `.mp4` or `.mov` into the PR description. + GitHub accepts videos up to 10 MB on free accounts, so link to a larger file + instead of attaching it. +3. **The proposed category.** Say which layer-panel group the layer belongs in. + The groups are defined in `PANEL_GROUPS` in `src/ui/layerPanel.js` (today: + Movement, Cameras, Infrastructure, Events, Weather and Utilities). A layer + that isn't listed there falls under "Other layers". If none of the groups + fits, propose a new one and explain why. +4. **The data source and licence.** Name the provider and endpoint, link its + licence or terms, give the attribution shown in the app, and say whether it + needs a key and whether the data is fetched at runtime or bundled. Add the + same details to [DATA_SOURCES.md](DATA_SOURCES.md) and register the credit + in `src/data/dataCredits.js`. + +Maintainers may hold a layer PR until all four are there. ## Maintainers From 57df5f61ba84ed23628180388241a1765a523a9b Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 25 Oct 2026 15:58:45 -0400 Subject: [PATCH 35/54] fix(fires): report a 00:45 UTC detection as 00:45, not "45" get_active_fires joined FIRMS acq_date and the unpadded acq_time, so a detection at 00:45 UTC came back as "2026-01-01 45". The row now uses acquisitionMsUtc, which pads the time, and reports an ISO UTC timestamp like the other tool times. --- changelog.d/1395-fires-tool-acquired-time.md | 4 ++++ src/tools/queries/hazards.js | 4 ++-- src/tools/queries/hazards.test.mjs | 17 +++++++++++++++++ src/tools/queries/queries.test.mjs | 2 +- 4 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 changelog.d/1395-fires-tool-acquired-time.md create mode 100644 src/tools/queries/hazards.test.mjs diff --git a/changelog.d/1395-fires-tool-acquired-time.md b/changelog.d/1395-fires-tool-acquired-time.md new file mode 100644 index 0000000000..ea3bddd1df --- /dev/null +++ b/changelog.d/1395-fires-tool-acquired-time.md @@ -0,0 +1,4 @@ +- Report a fire detection's acquisition time as a UTC timestamp in + `get_active_fires`. The tool joined FIRMS's unpadded date and time, so a + 00:45 UTC detection read "2026-01-01 45"; it now reads + `2026-01-01T00:45:00.000Z` (Rudy Celekli, @rudycelekli, #1395). diff --git a/src/tools/queries/hazards.js b/src/tools/queries/hazards.js index 475df97bab..f644be5625 100644 --- a/src/tools/queries/hazards.js +++ b/src/tools/queries/hazards.js @@ -1,5 +1,6 @@ /** Natural hazard queries: earthquakes and active fires. */ +import { acquisitionMsUtc } from '../../data/firmsCsv.js'; import { suggestView } from '../views.js'; import { defineTool, ToolError } from '../catalog.js'; import { AREA_SCHEMA, areaContains, resolveArea } from '../area.js'; @@ -114,8 +115,7 @@ export const getActiveFires = defineTool({ lon: fire.lon, frp_mw: fire.frp ?? null, confidence: fire.confidence ?? null, - acquired: - [fire.acqDate, fire.acqTime].filter(Boolean).join(' ') || null, + acquired: isoTime(acquisitionMsUtc(fire.acqDate, fire.acqTime)), satellite: fire.satellite ?? null, day_night: fire.daynight ?? null, })), diff --git a/src/tools/queries/hazards.test.mjs b/src/tools/queries/hazards.test.mjs new file mode 100644 index 0000000000..fe2e6ac1f0 --- /dev/null +++ b/src/tools/queries/hazards.test.mjs @@ -0,0 +1,17 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { composeCatalog } from '../catalog.js'; +import { getActiveFires } from './hazards.js'; + +const catalogWith = (fires) => + composeCatalog({ + tools: [getActiveFires], + services: { fires: { getSnapshot: async () => ({ fires }) } }, + }); + +test('a fire acquired at 00:45 UTC reads as 00:45, not "45"', async () => { + const result = await catalogWith([ + { lat: 24, lon: 121, frp: 5, acqDate: '2026-01-01', acqTime: '45' }, + ]).call('get_active_fires', { area: { bbox: [120, 23, 122, 25] } }); + assert.equal(result.data.rows[0].acquired, '2026-01-01T00:45:00.000Z'); +}); diff --git a/src/tools/queries/queries.test.mjs b/src/tools/queries/queries.test.mjs index b64f5e009c..5f53cf9e8b 100644 --- a/src/tools/queries/queries.test.mjs +++ b/src/tools/queries/queries.test.mjs @@ -125,7 +125,7 @@ test('fires need an area and report a missing key as unavailable', async () => { result.data.rows.map((row) => row.frp_mw), [40, 12], ); - assert.equal(result.data.rows[1].acquired, '2026-01-01 0130'); + assert.equal(result.data.rows[1].acquired, '2026-01-01T01:30:00.000Z'); const keyless = composeCatalog({ tools: coreTools, From 315c0f5dc61304cdf0adbd71e5efb1633e47e474 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 25 Oct 2026 15:58:46 -0400 Subject: [PATCH 36/54] =?UTF-8?q?fix(local-adsb):=20show=20a=20359.7=C2=B0?= =?UTF-8?q?=20track=20as=20TRK=200=C2=B0,=20not=20TRK=20360=C2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Local ADS-B card rounded the track without wrapping, so an aircraft tracking 359.5° or more read "TRK 360°". The rounded track now wraps to 0°. --- changelog.d/1396-local-adsb-track-north.md | 3 +++ src/layers/localAdsb/card.js | 2 +- src/layers/localAdsb/card.test.mjs | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 changelog.d/1396-local-adsb-track-north.md create mode 100644 src/layers/localAdsb/card.test.mjs diff --git a/changelog.d/1396-local-adsb-track-north.md b/changelog.d/1396-local-adsb-track-north.md new file mode 100644 index 0000000000..9235a19a32 --- /dev/null +++ b/changelog.d/1396-local-adsb-track-north.md @@ -0,0 +1,3 @@ +- Show a locally heard aircraft tracking 359.5° or more as TRK 0°. The Local + ADS-B card rounded the track without wrapping, so 359.7° read "TRK 360°" + (Rudy Celekli, @rudycelekli, #1396). diff --git a/src/layers/localAdsb/card.js b/src/layers/localAdsb/card.js index 1b01229252..c1c923a8ca 100644 --- a/src/layers/localAdsb/card.js +++ b/src/layers/localAdsb/card.js @@ -152,7 +152,7 @@ export function localAdsbCardModel( t('ALT {altitude} FT · GS {speed} KT · TRK {track}', { altitude: grouped(altitude), speed: speed === null ? DASH : speed, - track: track === null ? DASH : `${track}°`, + track: track === null ? DASH : `${track % 360}°`, }), vertical === null ? t('V/S {rate}', { rate: DASH }) diff --git a/src/layers/localAdsb/card.test.mjs b/src/layers/localAdsb/card.test.mjs new file mode 100644 index 0000000000..ec53024dac --- /dev/null +++ b/src/layers/localAdsb/card.test.mjs @@ -0,0 +1,19 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { setLocale } from '../../i18n/index.js'; +import { localAdsbCardModel } from './card.js'; + +test('a track of 359.7° reads TRK 0°, not TRK 360°', () => { + setLocale('en'); + const { details } = localAdsbCardModel( + { + icao: 'abc123', + altitudeFt: 12500, + groundSpeedKt: 240, + trackDeg: 359.7, + lastPositionAt: 1000, + }, + 5000, + ); + assert.equal(details[1], 'ALT 12,500 FT · GS 240 KT · TRK 0°'); +}); From 224d71753b02eb2fde881e283e1053e9ca2b639b Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 25 Oct 2026 16:01:26 -0400 Subject: [PATCH 37/54] fix(fires): parse the detection time inside the tools package The tools package cannot import firmsCsv. Pad the FIRMS clock here so 00:45 UTC still reads as 00:45. --- src/tools/queries/hazards.js | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/tools/queries/hazards.js b/src/tools/queries/hazards.js index f644be5625..194f9b8c1f 100644 --- a/src/tools/queries/hazards.js +++ b/src/tools/queries/hazards.js @@ -1,11 +1,24 @@ /** Natural hazard queries: earthquakes and active fires. */ -import { acquisitionMsUtc } from '../../data/firmsCsv.js'; import { suggestView } from '../views.js'; import { defineTool, ToolError } from '../catalog.js'; import { AREA_SCHEMA, areaContains, resolveArea } from '../area.js'; import { LIMIT_SCHEMA, capRows, countNoun, isoTime } from '../results.js'; +function acquiredMsUtc(acqDate, acqTime) { + if (typeof acqDate !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(acqDate)) + return NaN; + const timeText = String(acqTime ?? '').trim(); + if (!/^\d{1,4}$/.test(timeText)) return NaN; + const hhmm = timeText.padStart(4, '0'); + const hours = Number(hhmm.slice(0, 2)); + const minutes = Number(hhmm.slice(2, 4)); + if (hours > 23 || minutes > 59) return NaN; + return Date.parse( + `${acqDate}T${hhmm.slice(0, 2)}:${hhmm.slice(2, 4)}:00.000Z`, + ); +} + export const getEarthquakes = defineTool({ name: 'get_earthquakes', title: 'Recent earthquakes', @@ -115,7 +128,7 @@ export const getActiveFires = defineTool({ lon: fire.lon, frp_mw: fire.frp ?? null, confidence: fire.confidence ?? null, - acquired: isoTime(acquisitionMsUtc(fire.acqDate, fire.acqTime)), + acquired: isoTime(acquiredMsUtc(fire.acqDate, fire.acqTime)), satellite: fire.satellite ?? null, day_night: fire.daynight ?? null, })), From 3de745bd33123b9203e2b160d8bbbb6772d399a1 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 14:08:25 -0700 Subject: [PATCH 38/54] fix(fires): reject rolled-over acquisition dates and document UTC times --- changelog.d/1395-fires-tool-acquired-time.md | 4 ++- docs/CURRENT-STATE.md | 3 ++ src/tools/queries/hazards.js | 6 +++- src/tools/queries/hazards.test.mjs | 29 ++++++++++++++++++++ 4 files changed, 40 insertions(+), 2 deletions(-) diff --git a/changelog.d/1395-fires-tool-acquired-time.md b/changelog.d/1395-fires-tool-acquired-time.md index ea3bddd1df..17d74e4818 100644 --- a/changelog.d/1395-fires-tool-acquired-time.md +++ b/changelog.d/1395-fires-tool-acquired-time.md @@ -1,4 +1,6 @@ - Report a fire detection's acquisition time as a UTC timestamp in `get_active_fires`. The tool joined FIRMS's unpadded date and time, so a 00:45 UTC detection read "2026-01-01 45"; it now reads - `2026-01-01T00:45:00.000Z` (Rudy Celekli, @rudycelekli, #1395). + `2026-01-01T00:45:00.000Z`. Missing or invalid dates and times remain + unknown rather than rolling into another calendar day + (Rudy Celekli, @rudycelekli, #1395). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index b15babbb2e..5332216e5f 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1984,6 +1984,9 @@ accessible name remains "Don't show this again". Control behavior is unchanged. ## FIRMS source status The FIRMS CSV parser rejects impossible acquisition calendar dates before the proxy filters records to the trailing 24 hours, while retaining valid UTC acquisition times. +The `get_active_fires` tool reports acquisition times as UTC ISO timestamps, +including zero-padded hours and minutes; missing or invalid dates and times +remain `null`, including impossible calendar dates from a custom source. The FIRMS proxy records source success after appending its rows. If aggregation throws, that source reports failure without a contradictory success entry. diff --git a/src/tools/queries/hazards.js b/src/tools/queries/hazards.js index 194f9b8c1f..2b11c639c2 100644 --- a/src/tools/queries/hazards.js +++ b/src/tools/queries/hazards.js @@ -14,9 +14,13 @@ function acquiredMsUtc(acqDate, acqTime) { const hours = Number(hhmm.slice(0, 2)); const minutes = Number(hhmm.slice(2, 4)); if (hours > 23 || minutes > 59) return NaN; - return Date.parse( + const timestamp = Date.parse( `${acqDate}T${hhmm.slice(0, 2)}:${hhmm.slice(2, 4)}:00.000Z`, ); + return Number.isFinite(timestamp) && + new Date(timestamp).toISOString().slice(0, 10) === acqDate + ? timestamp + : NaN; } export const getEarthquakes = defineTool({ diff --git a/src/tools/queries/hazards.test.mjs b/src/tools/queries/hazards.test.mjs index fe2e6ac1f0..fa17158ddb 100644 --- a/src/tools/queries/hazards.test.mjs +++ b/src/tools/queries/hazards.test.mjs @@ -15,3 +15,32 @@ test('a fire acquired at 00:45 UTC reads as 00:45, not "45"', async () => { ]).call('get_active_fires', { area: { bbox: [120, 23, 122, 25] } }); assert.equal(result.data.rows[0].acquired, '2026-01-01T00:45:00.000Z'); }); + +test('fire acquisition timestamps reject impossible calendar dates', async () => { + for (const acqDate of [ + '2026-02-29', + '2026-02-30', + '2026-04-31', + '1900-02-29', + '2026-13-01', + '2026-01-00', + ]) { + const result = await catalogWith([ + { lat: 24, lon: 121, acqDate, acqTime: '45' }, + ]).call('get_active_fires', { area: { bbox: [120, 23, 122, 25] } }); + assert.equal(result.data.rows[0].acquired, null, acqDate); + } +}); + +test('fire acquisition timestamps preserve valid leap days and UTC times', async () => { + for (const [acqDate, acqTime, expected] of [ + ['2024-02-29', '45', '2024-02-29T00:45:00.000Z'], + ['2000-02-29', 0, '2000-02-29T00:00:00.000Z'], + ['2026-04-30', '2359', '2026-04-30T23:59:00.000Z'], + ]) { + const result = await catalogWith([ + { lat: 24, lon: 121, acqDate, acqTime }, + ]).call('get_active_fires', { area: { bbox: [120, 23, 122, 25] } }); + assert.equal(result.data.rows[0].acquired, expected); + } +}); From 6642176de540776a04a7b3d9ed6413c190504530 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 14:08:32 -0700 Subject: [PATCH 39/54] docs: document Local ADS-B track rounding --- docs/CURRENT-STATE.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index b15babbb2e..9216047895 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5994,6 +5994,8 @@ callsign, class and category, adsbdb operator/type and a plausible route when known, altitude, ground speed, track, vertical rate, position age, message count, "Heard by your receiver"); markers are not camera-followed. Positioned aircraft join detection boxes, labelled only with a decoded callsign. +The card's `TRK` label wraps after rounding to whole degrees, so a track of +359.5° displays as `TRK 0°` rather than `TRK 360°`. Receivers publish one record shape from `src/sources/adsbRecords.js` (`icao`, `callsign`, `category`, `onGround`, `lat`, `lon`, `altitudeFt`, From 1ad472fecf9d35f6f64b4ba537e0f09692373a2e Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 14:08:32 -0700 Subject: [PATCH 40/54] fix(awareness): register and document bearing presentation --- docs/CURRENT-STATE.md | 1 + scripts/package-boundaries.json | 3 +++ 2 files changed, 4 insertions(+) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index b15babbb2e..722fcd8313 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4681,6 +4681,7 @@ silently demoting every later lookup for the session. - Selected AIS vessels use their layer-owned full-detail presentation model in the shared world-overlay host; mapped installations promote their own entry to a selected card. Both remain crisp above post-processing without duplicate selected labels; non-selected AIS cards retain their source-owned grid/visibility selection and are host-batched with other world cards. - Space Mission ascent replay uses the compact rocket/thrust overlay only through orbit insertion. Once the replay enters its orbit phase, that vehicle glyph is replaced by a fixed-size cyan dot following the same orbit path and callout. - While a subject is selected, an inner keyhole compass rotates against camera heading and up to three cyan shafted bearing arrows lock to its single faint tick-marked rim, with their labels inset just inside the circle. Labels explicitly separate the geographic bearing (`BRG`) from the contact's reported course (`CRS`) so the pointer direction is not confused with aircraft heading. They point toward the nearest observed/mapped examples; each cohort displays up to ten examples while retaining the complete locally loaded in-range cohort for navigation, with three visible at a time and a ten-second page rotation shared by the panel and arrows. This distinct neutral-context color avoids implying that all context indicators are military-flight symbols. `PREVIOUS`, `FOCUS`, and `NEXT` controls navigate selection history or the next nearby cohort example through the existing tracker. NEXT uses a cycle-scoped visited set and starts a deterministic new walk after exhausting the current candidates instead of re-admitting the nearest visited contact. +- Awareness `BRG` and `CRS` labels wrap after rounding to whole degrees, so a direction of 359.5° displays as `000°` rather than `360°`. - Installations are viewport-bounded OSM map features (`military=airfield|naval_base|range|barracks|base` and `landuse=military`), capped to a 10° non-dateline request and 700 upstream features. The proxy caches five minutes and serves a one-hour stale fallback. Empty, stale, unavailable, and zoom-too-wide states remain visibly distinct. - With a selected subject, Contacts hands the installation layer the subject position every refresh. The layer loads a window around the subject (see Installations and map-source guidance), because a follow or Cockpit camera never fires `moveEnd` and often looks at the horizon: a first load from a globe view used to leave the row at "?" for the whole track. The row and the Cockpit scope read `WITHIN 100 KM` instead of `CURRENT VIEWPORT ONLY`, and an empty window reads "none mapped within 100 km; not a complete 250 km survey". `scripts/qa-context-arrivals.mjs` flies synthetic aircraft over Camp Mabry and Fort Cavazos from a wide start, presses CONTACTS, Cockpit and SEARCH NEARBY SITES, and records a clip. - The selected-only visual is one static, unfilled blue circle. It marks the 250 km proximity context window only; it is not coverage or a radar/weapon envelope. Missing broadcasts and unmapped sites are explicitly not evidence of absence. diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 68a57066aa..cddb29c409 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1287,6 +1287,7 @@ "src/layers/awareness/navigation.js", "src/layers/awareness/panel.js", "src/layers/awareness/policy.js", + "src/layers/awareness/presentation.js", "src/layers/awareness/queries.js", "src/layers/awareness/rendering.js", "src/layers/awareness/state.js", @@ -1944,6 +1945,7 @@ "src/layers/awareness/navigation.js", "src/layers/awareness/panel.js", "src/layers/awareness/policy.js", + "src/layers/awareness/presentation.js", "src/layers/awareness/queries.js", "src/layers/awareness/rendering.js", "src/layers/awareness/state.js", @@ -2736,6 +2738,7 @@ "src/layers/awareness/navigation.js", "src/layers/awareness/panel.js", "src/layers/awareness/policy.js", + "src/layers/awareness/presentation.js", "src/layers/awareness/queries.js", "src/layers/awareness/rendering.js", "src/layers/awareness/state.js", From 7bc86224e942df1304d0532b57256e87ad5d55f3 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:28:09 -0400 Subject: [PATCH 41/54] fix(route): phrase ramp and lane modifiers as directions (#1343) Correct ramp and lane instructions consistently in server output and localized browser text. Contribution by @rudycelekli. --- changelog.d/1343-route-ramp-lane-wording.md | 4 ++ docs/CURRENT-STATE.md | 4 ++ src/data/directions.test.mjs | 43 +++++++++++++++++++++ src/data/routeSteps.js | 33 ++++++++++++---- src/data/routeSteps.test.mjs | 20 ++++++++++ src/i18n/locales/es.json | 4 ++ src/i18n/locales/ru.json | 4 ++ src/i18n/locales/zh-CN.json | 4 ++ src/layers/directions/index.js | 24 +++++++++--- 9 files changed, 127 insertions(+), 13 deletions(-) create mode 100644 changelog.d/1343-route-ramp-lane-wording.md diff --git a/changelog.d/1343-route-ramp-lane-wording.md b/changelog.d/1343-route-ramp-lane-wording.md new file mode 100644 index 0000000000..4f6817e9cb --- /dev/null +++ b/changelog.d/1343-route-ramp-lane-wording.md @@ -0,0 +1,4 @@ +- Phrase slight and sharp ramps as directions, so a ramp reads "slightly left" + instead of "on the slightly left", and a lane names its side in both + the proxy response and localized browser instructions + (Rudy Celekli, @rudycelekli, #1343). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index b0865b7b0c..cc4e7b8618 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4150,6 +4150,10 @@ and as the last line of the list, because the arrival step is among the ones dropped. A route of exactly 200 is complete, and a roundabout exit after the 200th keeps folding into it. +Directions ramp and exit text uses “on the left/right” only for a bare side; +slight and sharp modifiers read as “slightly/sharply left/right”. Lane instructions +name the left or right lane. The localized page and proxy English stay in sync. + Route duration labels select their unit after rounding seconds, switching to minutes at 59.5 seconds; a 59.6-second leg displays as `1 min`, rather than `60 s`. diff --git a/src/data/directions.test.mjs b/src/data/directions.test.mjs index b0c7503ac9..bf6e2878e8 100644 --- a/src/data/directions.test.mjs +++ b/src/data/directions.test.mjs @@ -876,3 +876,46 @@ test('route numbers follow the page language and never break from their unit', ( const list = directionsStepList({ route }); assert.equal(list.items[1].lead, '240\u00a0м'); }); + +test('ramp and lane wording stays localized after choosing the maneuver form', (t) => { + t.after(() => setLocale('en')); + const cases = [ + [ + 'ru', + 'Въезжайте по съезду плавно налево на I-95', + 'Сверните на съезд резко направо', + 'Займите левую полосу', + ], + [ + 'es', + 'Toma la rampa ligeramente a la izquierda hacia I-95', + 'Toma la salida bruscamente a la derecha', + 'Toma el carril izquierdo', + ], + [ + 'zh-CN', + '向左前方驶入匝道,进入 I-95', + '从出口向右后方驶出', + '使用左转车道', + ], + ]; + for (const [locale, ramp, exit, lane] of cases) { + setLocale(locale); + assert.equal( + directionsInstruction({ + type: 'on ramp', + modifier: 'slight left', + name: 'I-95', + }), + ramp, + ); + assert.equal( + directionsInstruction({ type: 'off ramp', modifier: 'sharp right' }), + exit, + ); + assert.equal( + directionsInstruction({ type: 'use lane', modifier: 'sharp left' }), + lane, + ); + } +}); diff --git a/src/data/routeSteps.js b/src/data/routeSteps.js index e3144bdf70..736d812eec 100644 --- a/src/data/routeSteps.js +++ b/src/data/routeSteps.js @@ -54,6 +54,21 @@ function direction(modifier) { return DIRECTION_WORDS[key] || key; } +/** + * "on the left" only fits a bare side. "slight left" is the adverb + * "slightly left", and "on the slightly left" is not an instruction. + * @param {string} prefix "Take the ramp" or "Take the exit". + * @param {string} modifier OSRM maneuver modifier. + * @param {string} onto " onto …", or "". + */ +function directedWay(prefix, modifier, onto) { + const dir = direction(modifier); + if (dir === 'left' || dir === 'right') + return `${prefix} on the ${dir}${onto}`; + if (dir && dir !== 'straight') return `${prefix} ${dir}${onto}`; + return `${prefix}${onto}`; +} + function ordinal(n) { if (!Number.isInteger(n) || n < 1) return null; const suffix = @@ -103,13 +118,9 @@ export function instructionFor(step) { case 'merge': return dir ? `Merge ${dir}${onto}` : `Merge${onto}`; case 'on ramp': - return dir - ? `Take the ramp on the ${dir}${onto}` - : `Take the ramp${onto}`; + return directedWay('Take the ramp', modifier, onto); case 'off ramp': - return dir - ? `Take the exit on the ${dir}${onto}` - : `Take the exit${onto}`; + return directedWay('Take the exit', modifier, onto); case 'roundabout': case 'rotary': { const exit = ordinal(step?.exit); @@ -124,8 +135,14 @@ export function instructionFor(step) { case 'exit roundabout': case 'exit rotary': return `Exit the roundabout${onto}`; - case 'use lane': - return dir ? `Use the ${dir} lane${onto}` : `Continue${onto}`; + case 'use lane': { + const lane = modifier.includes('left') + ? 'left' + : modifier.includes('right') + ? 'right' + : ''; + return lane ? `Use the ${lane} lane${onto}` : `Continue${onto}`; + } case 'notification': default: return `Continue${onto}`; diff --git a/src/data/routeSteps.test.mjs b/src/data/routeSteps.test.mjs index 6bf74dd08d..c0eb445dcd 100644 --- a/src/data/routeSteps.test.mjs +++ b/src/data/routeSteps.test.mjs @@ -77,6 +77,26 @@ test('instructions read like a navigator, one sentence per OSRM maneuver', () => instructionFor({ type: 'on ramp', modifier: 'left' }), 'Take the ramp on the left', ); + assert.equal( + instructionFor({ type: 'on ramp', modifier: 'slight left', name: 'I-95' }), + 'Take the ramp slightly left onto I-95', + ); + assert.equal( + instructionFor({ type: 'off ramp', modifier: 'sharp right', ref: 'I-280' }), + 'Take the exit sharply right onto I-280', + ); + assert.equal( + instructionFor({ type: 'on ramp', modifier: 'straight', name: 'US 101' }), + 'Take the ramp onto US 101', + ); + assert.equal( + instructionFor({ type: 'use lane', modifier: 'slight left' }), + 'Use the left lane', + ); + assert.equal( + instructionFor({ type: 'use lane', modifier: 'right', name: 'Main St' }), + 'Use the right lane onto Main St', + ); assert.equal( instructionFor({ type: 'merge', diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 4fe130f23a..098c82f55d 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -1867,11 +1867,15 @@ "maneuver|Merge": "Incorpórate", "Merge onto {road}": "Incorpórate a {road}", "Take the ramp on the {direction}": "Toma la rampa {direction}", + "Take the ramp {direction}": "Toma la rampa {direction}", "Take the ramp on the {direction} onto {road}": "Toma la rampa {direction} hacia {road}", + "Take the ramp {direction} onto {road}": "Toma la rampa {direction} hacia {road}", "Take the ramp": "Toma la rampa", "Take the ramp onto {road}": "Toma la rampa hacia {road}", "Take the exit on the {direction}": "Toma la salida {direction}", + "Take the exit {direction}": "Toma la salida {direction}", "Take the exit on the {direction} onto {road}": "Toma la salida {direction} hacia {road}", + "Take the exit {direction} onto {road}": "Toma la salida {direction} hacia {road}", "Take the exit": "Toma la salida", "Take the exit onto {road}": "Toma la salida hacia {road}", "At the roundabout, take the {exit} exit": "En la rotonda, toma la {exit} salida", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 978640951a..8d12ba43ee 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -1899,11 +1899,15 @@ "maneuver|Merge": "Перестройтесь", "Merge onto {road}": "Въезжайте на {road}", "Take the ramp on the {direction}": "Въезжайте на съезд {direction}", + "Take the ramp {direction}": "Въезжайте на съезд {direction}", "Take the ramp on the {direction} onto {road}": "Въезжайте по съезду {direction} на {road}", + "Take the ramp {direction} onto {road}": "Въезжайте по съезду {direction} на {road}", "Take the ramp": "Въезжайте на съезд", "Take the ramp onto {road}": "Въезжайте по съезду на {road}", "Take the exit on the {direction}": "Сверните на съезд {direction}", + "Take the exit {direction}": "Сверните на съезд {direction}", "Take the exit on the {direction} onto {road}": "Сверните на съезд {direction} на {road}", + "Take the exit {direction} onto {road}": "Сверните на съезд {direction} на {road}", "Take the exit": "Сверните на съезд", "Take the exit onto {road}": "Сверните на съезд на {road}", "At the roundabout, take the {exit} exit": "На кольце сверните на {exit} съезд", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 01c495a27e..e727b85167 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -626,11 +626,15 @@ "Merge onto {road}": "并入 {road}", "maneuver|Merge": "并道", "Take the ramp on the {direction} onto {road}": "{direction}驶入匝道,进入 {road}", + "Take the ramp {direction} onto {road}": "{direction}驶入匝道,进入 {road}", "Take the ramp on the {direction}": "{direction}驶入匝道", + "Take the ramp {direction}": "{direction}驶入匝道", "Take the ramp onto {road}": "驶入匝道,进入 {road}", "Take the ramp": "驶入匝道", "Take the exit on the {direction} onto {road}": "从出口{direction}驶出,进入 {road}", + "Take the exit {direction} onto {road}": "从出口{direction}驶出,进入 {road}", "Take the exit on the {direction}": "从出口{direction}驶出", + "Take the exit {direction}": "从出口{direction}驶出", "Take the exit onto {road}": "从出口驶出,进入 {road}", "Take the exit": "从出口驶出", "At the roundabout, take the {exit} exit onto {road}": "在环岛从{exit}出口驶出,进入 {road}", diff --git a/src/layers/directions/index.js b/src/layers/directions/index.js index e90e1be180..b8cceff028 100644 --- a/src/layers/directions/index.js +++ b/src/layers/directions/index.js @@ -308,16 +308,24 @@ export function directionsInstruction(step) { ? t('Merge onto {road}', values) : t('Merge', { context: 'maneuver' }); case 'on ramp': - if (direction) + if (modifier === 'left' || modifier === 'right') return road ? t('Take the ramp on the {direction} onto {road}', values) : t('Take the ramp on the {direction}', values); + if (direction && modifier !== 'straight') + return road + ? t('Take the ramp {direction} onto {road}', values) + : t('Take the ramp {direction}', values); return road ? t('Take the ramp onto {road}', values) : t('Take the ramp'); case 'off ramp': - if (direction) + if (modifier === 'left' || modifier === 'right') return road ? t('Take the exit on the {direction} onto {road}', values) : t('Take the exit on the {direction}', values); + if (direction && modifier !== 'straight') + return road + ? t('Take the exit {direction} onto {road}', values) + : t('Take the exit {direction}', values); return road ? t('Take the exit onto {road}', values) : t('Take the exit'); case 'roundabout': case 'rotary': @@ -346,9 +354,14 @@ export function directionsInstruction(step) { return road ? t('Exit the roundabout onto {road}', values) : t('Exit the roundabout'); - case 'use lane': - if (direction) { - const lane = { road, direction: laneWord(modifier) }; + case 'use lane': { + const side = modifier.includes('left') + ? 'left' + : modifier.includes('right') + ? 'right' + : ''; + if (side) { + const lane = { road, direction: laneWord(side) }; return road ? t('Use the {direction} lane onto {road}', lane) : t('Use the {direction} lane', lane); @@ -356,6 +369,7 @@ export function directionsInstruction(step) { return road ? t('Continue onto {road}', values) : t('Continue', { context: 'maneuver' }); + } default: return road ? t('Continue onto {road}', values) From a7da90fdfcbc17673cccb9f761930ccb812fcfe9 Mon Sep 17 00:00:00 2001 From: quanticsoul4772 <71096528+quanticsoul4772@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:51:56 -0700 Subject: [PATCH 42/54] fix(effects): run no sharpen pass when its slider is at 0 (#1398) Disable the sharpen pass when its intensity is zero. Contribution by @quanticsoul4772. --- changelog.d/1398-sharpen-zero-off.md | 2 ++ docs/CURRENT-STATE.md | 2 ++ src/ui/visualEffects.js | 14 +++++++++++++- src/ui/visualEffects.test.mjs | 18 ++++++++++++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 changelog.d/1398-sharpen-zero-off.md diff --git a/changelog.d/1398-sharpen-zero-off.md b/changelog.d/1398-sharpen-zero-off.md new file mode 100644 index 0000000000..ab05aa6f2a --- /dev/null +++ b/changelog.d/1398-sharpen-zero-off.md @@ -0,0 +1,2 @@ +- The Sharpen slider at 0 now turns the sharpen pass off instead of still + sharpening at a low amount (quanticsoul4772, #1398). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 07daef46cf..e2e24fc7de 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1301,6 +1301,8 @@ Stopping the controller revokes animation before asynchronous UI teardown; final destruction removes its stages and restores the borrowed bloom configuration. Snow's sideways sway stays within a fixed range at any session age; Wind scales its amplitude. +Sharpen runs only when enabled with intensity above 0.001. At slider zero its +stage is disabled; raising the slider resumes it when sharpen is enabled. ## Display control ownership diff --git a/src/ui/visualEffects.js b/src/ui/visualEffects.js index 8b5234ef24..9d10f0cef3 100644 --- a/src/ui/visualEffects.js +++ b/src/ui/visualEffects.js @@ -159,18 +159,30 @@ export class VisualEffects { this.requestRender('bloom'); } + /** + * Sharpen runs only when it is on and its slider is above 0, as the style + * stages do: the pass costs the same at any amount (~1.5 ms GPU per frame + * on the Arc, 2026-10-24), and `0.1 + value * 2` still sharpened at 0. + */ + syncSharpenEnabled() { + if (this.stopped || !this.sharpenStage) return; + this.sharpenStage.enabled = + this.sharpenEnabled && this.sharpenIntensity > 0.001; + } + applySharpenIntensity(value) { if (this.stopped) return; this.sharpenIntensity = value; if (this.sharpenStage) this.sharpenStage.uniforms.amount = 0.1 + value * 2.0; + this.syncSharpenEnabled(); this.requestRender('sharpen'); } setSharpenEnabled(enabled) { if (this.stopped) return; this.sharpenEnabled = !!enabled; - if (this.sharpenStage) this.sharpenStage.enabled = this.sharpenEnabled; + this.syncSharpenEnabled(); this.requestRender('sharpen'); } diff --git a/src/ui/visualEffects.test.mjs b/src/ui/visualEffects.test.mjs index 68fa459627..9e9542c522 100644 --- a/src/ui/visualEffects.test.mjs +++ b/src/ui/visualEffects.test.mjs @@ -224,6 +224,24 @@ test('sharpen uses the existing uniform scale and keeps values while disabled', f.effects.destroy(); }); +test('sharpen at 0 runs no pass, and comes back with the slider', () => { + const f = fixture(); + f.effects.initPostProcess(0.49); + f.effects.setSharpenEnabled(true); + assert.equal(f.effects.sharpenStage.enabled, true); + f.effects.applySharpenIntensity(0); + assert.equal( + f.effects.sharpenStage.enabled, + false, + 'no residual sharpen at 0', + ); + f.effects.setSharpenEnabled(true); + assert.equal(f.effects.sharpenStage.enabled, false, 'on at 0 is still off'); + f.effects.applySharpenIntensity(0.2); + assert.equal(f.effects.sharpenStage.enabled, true); + f.effects.destroy(); +}); + test('stop revokes pending work immediately but retains stages until final destruction', () => { const f = fixture(); f.effects.initStyles(); From ba292ce47554a38b07dec513db5779d67aeae17f Mon Sep 17 00:00:00 2001 From: quanticsoul4772 <71096528+quanticsoul4772@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:58:14 -0700 Subject: [PATCH 43/54] fix(flights): keep ground-snap sampling after the clock steps back (#1399) Recover aircraft ground-height sampling after backward wall-clock changes while preserving sampling budgets. Contribution by @quanticsoul4772. --- changelog.d/1399-ground-snap-clock-step.md | 3 ++ docs/CURRENT-STATE.md | 5 ++ src/services/groundSnap.js | 14 ++++- src/services/groundSnap.test.mjs | 62 ++++++++++++++++++++++ 4 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 changelog.d/1399-ground-snap-clock-step.md create mode 100644 src/services/groundSnap.test.mjs diff --git a/changelog.d/1399-ground-snap-clock-step.md b/changelog.d/1399-ground-snap-clock-step.md new file mode 100644 index 0000000000..73196986a6 --- /dev/null +++ b/changelog.d/1399-ground-snap-clock-step.md @@ -0,0 +1,3 @@ +- Aircraft on the ground keep getting ground-height samples after the + computer's clock steps back, instead of waiting for it to catch up + (quanticsoul4772, #1399). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index e2e24fc7de..c5cb8f9055 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5309,6 +5309,11 @@ pins and share links already supply complete boxes. - **The TRACKED contact's 2D↔3D handoff is DEFAULT behaviour (2026-08-19), driven by camera distance alone.** It does NOT consult the DISPLAY-rail `3D` toggle, which continues to own the FLEET (the un-instanced draw-call budget stays the operator's decision). Policy lives in `src/data/trackedModelRegime.js` and is shared by both layers: enter below `TRACKED_MODEL_ENTER_ALT_M` = 150,000 m and hand back to the billboard only above `TRACKED_MODEL_EXIT_ALT_M` = 172,500 m. **The swap distance was set by playtesting on 2026-08-20:** a first pass at 1,000,000 m switched too early; 2D reads correctly at ~600 km and the handoff belongs at ~150 km. **Consequence, recorded on purpose:** the tracked contact now enters 3D NEARER than the FLEET does (`MODEL_ALT_CEIL_M` = 800,000 m, unchanged), so with the DISPLAY-rail `3D` toggle on, 150–800 km draws surrounding contacts as models while the selected one is still a glyph. Nothing double-draws (the fleet pass skips the tracked icao) and aligning the two is a fleet-side decision, deliberately out of scope. **The two thresholds are asymmetric on purpose:** a single threshold makes a tracked orbit sitting ON the boundary strobe billboard↔model as the camera's altitude wobbles across it. Do not collapse them. The latch is scoped per selection, so a new target re-evaluates against the ENTER ceiling rather than inheriting the previous target's exit band. Exactly ONE model is involved; it loads on demand when the regime opens, is HIDDEN (not released) on regime exit so re-entry has no load gap, and is released by the existing teardown on deselect/re-track/destroy. Cockpit and TR-3B suppression are unchanged. **Two invariants around it:** (a) the hysteresis latch AND the load-failure latch are per-selection state cleared by `_resetTrackedSelectionState()` in the tracking lifecycle (deselect / re-track / cross-layer / init / destroy) — the predicate's icao-change guard is defence only, since it needs a drawn frame while nothing is selected and the render governor's idle mode does not promise one; (b) on-demand loading is bounded at 3 attempts per selection with a 1.5 s backoff and one console warning naming the asset — the driver runs every `scene.preUpdate`, so an unbounded catch means a missing GLB spins load→reject at frame rate. The billboard stays the visual throughout a failed load. - **Grounded 3D handoff is terrain-validity gated (2026-08-23).** A ready civilian or military glTF does not own the visual until `groundSnap` (`src/data/groundSnap.js`) can answer with a MEASURED photoreal-surface height. On success the layer writes `height + the model's measured belly offset` before revealing the model. Cache movement is measured on the WGS84 surface, not across altitude, so a stationary contact keeps its snap through poll-time vertical-datum changes. Model existence or GPU readiness alone never suppresses the billboard floor, and ordinary zoom/style/deselect transitions preserve a valid snap cache. **Two states, and the difference is the whole design.** COLD — nothing has ever resolved for this icao (tiles still streaming on first sight, sample failure, backoff after a first miss): there is no evidence of where the ground is, `heightFor` returns null, the model stays hidden and the depth-test-free 2D billboard remains opaque and floored. WARM — a snap resolved and then a >`MOVE_INVALIDATE_M` (50 m) taxi move stopped it answering directly: the measurement is DEMOTED to a bounded last-known rather than deleted, and it keeps answering while the resample is outstanding, so a taxiing aircraft does not pop 3D→2D→3D across a 2–30 s retry backoff. The bound is `HELD_SNAP_MAX_DRIFT_M` = 250 m from the spot the value was measured at, past which the hold is dropped rather than stretched and the contact is COLD again. It is spatial with no timer beside it (ground under a contact that has not moved does not change; what invalidates the value is the contact MOVING) and deliberately a quarter of the billboard chain's `HELD_FLOOR_MAX_DRIFT_KM` — that hold only ever RAISES a sprite, while a held snap IS the model's placement, so its error shows in both directions. A fresh sample releases the hold, and so does a ground flip (which already calls `forget`). **A loading model is HIDDEN, never zero-scaled:** admission sets `show = false` (Cesium's default is `true`, and an unplaced primitive would claim the visual at the identity matrix), and ownership is `ready && show` — Cesium 1.138's `Model.update` has no `show` guard, so hiding a primitive costs its load nothing. +- **Ground-snap clock rollback recovery.** If the wall clock moves before the + sampling-window start, ground snap opens a new window while retaining the + normal four-samples-per-250-ms budget. Retry timestamps more than the maximum + 30-second backoff ahead of the current clock are ignored. A smaller rollback + can retain a bounded retry delay of up to 30 seconds. - Commercial and military aircraft use the same high-level FLEET model regime: 2D billboards when zoomed out, optional glTF models when closer, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Since 2026-08-16 (Hangar fleet) models are PER-CLASS: real CC-BY GLBs for light/bizjet/turboprop/widebody/helicopter/uav (`CLASS_MODEL_REAL` in `src/data/aircraftClass.js` — meters-baked, scale 1, per-model belly/radius; provenance in `public/models/README.md`), the shared `airplane.glb` for the remaining civilian classes, and the military layer maps weight classes (real GLBs / 747 heavies / `jet.glb` fastjets, per-model heading offsets, flat amber or emergency red). Textured civilians carry a HEAVY tint, not a light one: `MODEL_COLOR_BLEND_AMOUNT` is `0.94` in BOTH layers under Cesium's `ColorBlendMode.MIX`, so the class colour supplies 94% of the surface and the asset's own texture ~6%. The visual direction is clean light silhouettes with only a weak diffuse contribution from the approved textures, so liveries deliberately do NOT read. IR boost raises the blend to a full `1.0`. Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit. - **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). With the class colour supplying 94% of the surface, the models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; the two preload calls only warm the glTF cache and are never drawn. - The DISPLAY-rail `3D` toggle is the user-facing activation path for both aircraft layers. Their small approved GLBs build their render resources without Cesium's frame-spread job queue, preventing continuous Photorealistic 3D Tiles streaming from starving model readiness; model caps, tracking, camera, and fallback billboards are unchanged. diff --git a/src/services/groundSnap.js b/src/services/groundSnap.js index 159cd66fd7..eecb1fa34f 100644 --- a/src/services/groundSnap.js +++ b/src/services/groundSnap.js @@ -307,10 +307,20 @@ export function createGroundSnap({ groundFloor }) { } const now = Date.now(); const entry = entries.get(icao); - if (entry && now < entry.nextRetryMs) return heldSnapM(entry, surfacePos); // backoff in force + // Backoff in force, unless it ends further off than any backoff can: + // a retry stamped before the clock stepped back would otherwise wait for + // the clock to catch up. + if ( + entry && + now < entry.nextRetryMs && + entry.nextRetryMs - now <= RETRY_MAX_MS + ) + return heldSnapM(entry, surfacePos); // Per-window budget: deny WITHOUT a retry stamp so the overflow simply // tries again next tick instead of waiting out a backoff it didn't earn. - if (now - windowStartMs > SAMPLE_WINDOW_MS) { + // A clock that stepped back also opens a new window, or none would open + // until it caught up. + if (now < windowStartMs || now - windowStartMs > SAMPLE_WINDOW_MS) { windowStartMs = now; windowCount = 0; } diff --git a/src/services/groundSnap.test.mjs b/src/services/groundSnap.test.mjs new file mode 100644 index 0000000000..8dfe42c46a --- /dev/null +++ b/src/services/groundSnap.test.mjs @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as Cesium from 'cesium'; +import { createGroundSnap } from './groundSnap.js'; + +const groundFloor = { + cachedMeshFloor: () => null, + meshFloorPreferred: () => false, + reportValidatedMeshFloorCell: () => {}, +}; + +/** A viewer whose ground is a loaded 3D tileset, counting height samples. */ +function makeViewer() { + const calls = { samples: 0 }; + const tileset = { show: true, tilesLoaded: true }; + return { + calls, + scene: { + primitives: { length: 1, get: () => tileset }, + sampleHeight() { + calls.samples += 1; + return 1650; + }, + globe: { getHeight: () => 1600 }, + }, + }; +} + +const atDenverAirport = Cesium.Cartesian3.fromDegrees(-104.6737, 39.8561, 0); + +test('a clock that steps back opens a new sample window instead of denying samples until it catches up', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: 1_000_000 }); + const viewer = makeViewer(); + const snap = createGroundSnap({ groundFloor }); + const icaos = ['a00001', 'a00002', 'a00003', 'a00004', 'a00005', 'a00006']; + for (const icao of icaos) snap.heightFor(viewer, icao, atDenverAirport); + assert.equal(viewer.calls.samples, 4, 'four samples per 250 ms window'); + t.mock.timers.setTime(1_000_000 - 60_000); + for (const icao of icaos) snap.heightFor(viewer, icao, atDenverAirport); + assert.equal( + viewer.calls.samples, + 6, + 'the two denied aircraft sample in the new window', + ); +}); + +test('a retry backoff stamped before the clock stepped back does not wait for it to catch up', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: 10_000_000 }); + const viewer = makeViewer(); + const tileset = viewer.scene.primitives.get(0); + const snap = createGroundSnap({ groundFloor }); + // Tiles still streaming: a miss, backed off for 2 s. + tileset.tilesLoaded = false; + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + tileset.tilesLoaded = true; + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + assert.equal(viewer.calls.samples, 0, 'the backoff holds'); + // The clock steps back an hour: the stamp is an hour off, past any backoff. + t.mock.timers.setTime(10_000_000 - 3_600_000); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), 1650); + assert.equal(viewer.calls.samples, 1); +}); From a43ff8619ea2966cd4ab51382f6d77b0f9e7379f Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Mon, 26 Oct 2026 00:04:43 +0000 Subject: [PATCH 44/54] fix(search): normalize geocoder bias across the antimeridian (#1272) Keep geocoder viewport bias near the antimeridian and omit misleading wrapped viewboxes. Contribution by @asturksever. --- changelog.d/1272-search-issue-fix.md | 1 + docs/CURRENT-STATE.md | 7 ++++++- src/keylessGeocoder.js | 25 ++++++++++++++++++++----- src/keylessGeocoder.test.mjs | 11 +++++++++++ src/nominatimGeocode.js | 4 +++- src/nominatimGeocode.test.mjs | 9 +++++++++ 6 files changed, 50 insertions(+), 7 deletions(-) create mode 100644 changelog.d/1272-search-issue-fix.md diff --git a/changelog.d/1272-search-issue-fix.md b/changelog.d/1272-search-issue-fix.md new file mode 100644 index 0000000000..48b803534d --- /dev/null +++ b/changelog.d/1272-search-issue-fix.md @@ -0,0 +1 @@ +- Normalize geocoder bias across the antimeridian (asturksever, #1272). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index c5cb8f9055..8be9af2049 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5197,9 +5197,14 @@ HTTP refusals and outages remain retryable. Searches share a 12-second total deadline, with Photon requests capped at six seconds each. Caller/application cancellation stops retries and late cache writes. Replacing a location search cancels the previous lookup; disposing its controls cancels the active lookup. Photon uses a soft proximity bias, up to five -candidates, and an unbiased retry for name mismatches. Invalid/wrapped bounds +candidates, and an unbiased retry for name mismatches. Invalid or wrapped bounds returned by providers are omitted rather than framing the wrong part of the globe. +For request viewport bias, Photon unwraps antimeridian-crossing longitude bounds +before computing their midpoint, then wraps that midpoint back into ±180 degrees. +Malformed viewport bounds add no proximity bias. Nominatim omits a crossing +request viewbox and continues searching without that geographic preference. + ### Map Stack Switcher (June 2026) - `src/mapStackController.js` switches between Google Photorealistic 3D (`photoreal`, the default when a Google or ion key is present), keyless Esri World Imagery (the zero-key default landing, with keyless terrain), Bing Aerial / Aerial-with-Labels via Cesium ion world imagery (require `CESIUM_ION_TOKEN`), and OSM tile fallback. Bing Road is **retired**: it is gone from `MAP_STACKS`, from the `set_map_stack` enum, and from the voice aliases (road phrasings now resolve to OSM, the one shipped road basemap). An old `map=bing-road` link is simply an unknown id and takes `setStack()`'s existing photoreal fallback with the Google 3D tile lit — pinned live in `scripts/qa-map-source-tray.mjs`. diff --git a/src/keylessGeocoder.js b/src/keylessGeocoder.js index 6033a6776d..7ca99a96d8 100644 --- a/src/keylessGeocoder.js +++ b/src/keylessGeocoder.js @@ -206,12 +206,27 @@ export function photonSearchUrl( url.searchParams.set('limit', String(limit)); const corners = String(bias ?? '').split('|'); - if (corners.length === 2) { - const [swLat, swLng] = corners[0].split(',').map(Number); - const [neLat, neLng] = corners[1].split(',').map(Number); - if ([swLat, swLng, neLat, neLng].every(Number.isFinite)) { + const tokens = corners.flatMap((corner) => corner.split(',')); + if ( + corners.length === 2 && + corners.every((corner) => corner.split(',').length === 2) && + tokens.every((token) => token.trim() !== '') + ) { + const [swLat, swLng, neLat, neLng] = tokens.map(Number); + if ( + [swLat, swLng, neLat, neLng].every(Number.isFinite) && + Math.abs(swLat) <= 90 && + Math.abs(neLat) <= 90 && + swLat <= neLat && + Math.abs(swLng) <= 180 && + Math.abs(neLng) <= 180 + ) { + const midpoint = (swLng + neLng + (swLng > neLng ? 360 : 0)) / 2; url.searchParams.set('lat', String((swLat + neLat) / 2)); - url.searchParams.set('lon', String((swLng + neLng) / 2)); + url.searchParams.set( + 'lon', + String(midpoint > 180 ? midpoint - 360 : midpoint), + ); } } return url.toString(); diff --git a/src/keylessGeocoder.test.mjs b/src/keylessGeocoder.test.mjs index 2ce8a70b4c..1a702fd02a 100644 --- a/src/keylessGeocoder.test.mjs +++ b/src/keylessGeocoder.test.mjs @@ -452,3 +452,14 @@ function readGeocodingConsumer(file) { ? [file, 'annotations/resolver.js'] : [file]; return files.map((name) => fs.readFileSync(path.join(ROOT, 'src', name), 'utf8')).join('\n'); } + + +test('wrapped view bias stays near the antimeridian and malformed coordinates are omitted', () => { + for (const [bias, expected] of [['-20,170|-10,-171', 179.5], ['50,175|60,-165', -175], ['0,180|10,-180', 180], ['0,-180|10,180', 0]]) { + const params = new URL(photonSearchUrl('island', { bias })).searchParams; + assert.equal(Number(params.get('lon')), expected); + } + for (const bias of ['-91,0|0,1', '0,181|1,0', '10,0|0,1', ',|,', '0,1,2|3,4', '0,1|Infinity,2']) { + assert.equal(new URL(photonSearchUrl('island', { bias })).searchParams.has('lon'), false); + } +}); diff --git a/src/nominatimGeocode.js b/src/nominatimGeocode.js index b7dd6145a6..4a5a1948e1 100644 --- a/src/nominatimGeocode.js +++ b/src/nominatimGeocode.js @@ -166,6 +166,8 @@ export function nominatimViewboxFromBounds(bounds) { const neLat = nominatimLatitude(match[3]); const neLng = nominatimLongitude(match[4]); if ([swLat, swLng, neLat, neLng].some((value) => value === null)) return null; - if (swLat >= neLat) return null; + // One Nominatim viewbox cannot express a wrapped interval. Omit this soft + // preference rather than biasing the search toward the opposite hemisphere. + if (swLat >= neLat || swLng > neLng) return null; return `${swLng},${neLat},${neLng},${swLat}`; } diff --git a/src/nominatimGeocode.test.mjs b/src/nominatimGeocode.test.mjs index b139ad8204..8517649d53 100644 --- a/src/nominatimGeocode.test.mjs +++ b/src/nominatimGeocode.test.mjs @@ -173,3 +173,12 @@ test('a viewport hint is sent only when every edge is a real coordinate', () => `${JSON.stringify(bounds)} must not become a viewbox`, ); }); + +test('wrapped viewports omit the Nominatim bias without rejecting the search', () => { + assert.equal(nominatimViewboxFromBounds('-20,170|-10,-171'), null); + assert.equal(nominatimViewboxFromBounds('50,175|60,-165'), null); + assert.equal( + nominatimViewboxFromBounds('-20,170|-10,180'), + '170,-10,180,-20', + ); +}); From 2006c035d9e14e63f8a3942c3d2694988a08f316 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 17:21:41 -0700 Subject: [PATCH 45/54] chore: remove four modules nothing in the app uses (#1403) * chore: remove four modules nothing in the app uses src/app/sourceSlot.js re-exported src/sources/sourceSlot.js, which every caller imports directly. src/data/flowTiles.js and src/data/issPass.js were reached only by their own tests. src/data/localGeojson.js wrapped localGeojsonCore.js with the app's services, which the catalog already passes itself. The local GeoJSON layer tests now build layers the way the catalog does, so they keep covering localGeojsonCore.js; only the test of the wrapper's own default host goes. Boundary lists, format scope and docs drop the removed paths. * docs: changelog for #1403 --- changelog.d/1403-remove-unused-modules.md | 5 + docs/CODE-BOUNDARIES.md | 2 - docs/CURRENT-STATE.md | 2 +- docs/INFRASTRUCTURE-LAYERS.md | 5 +- scripts/check-import-directions.mjs | 8 - scripts/format-scope.json | 2 - scripts/package-boundaries.json | 6 - src/app/sourceSlot.js | 2 - src/app/sourceSlot.test.mjs | 24 --- src/data/flowTiles.js | 6 - src/data/flowTiles.test.mjs | 162 ------------------- src/data/issPass.js | 46 ------ src/data/issPass.test.mjs | 42 ----- src/data/localGeojson.analyst.test.mjs | 13 +- src/data/localGeojson.js | 29 ---- src/data/localGeojson.test.mjs | 23 ++- src/data/localGeojsonLifecycle.test.mjs | 10 +- src/data/localGeojsonLod.js | 8 +- src/data/tomtomTiles.js | 2 +- src/layers/traffic/flowDecode.js | 2 +- src/overlays/worldOverlayAllocation.test.mjs | 2 +- 21 files changed, 46 insertions(+), 355 deletions(-) create mode 100644 changelog.d/1403-remove-unused-modules.md delete mode 100644 src/app/sourceSlot.js delete mode 100644 src/app/sourceSlot.test.mjs delete mode 100644 src/data/flowTiles.js delete mode 100644 src/data/flowTiles.test.mjs delete mode 100644 src/data/issPass.js delete mode 100644 src/data/issPass.test.mjs delete mode 100644 src/data/localGeojson.js diff --git a/changelog.d/1403-remove-unused-modules.md b/changelog.d/1403-remove-unused-modules.md new file mode 100644 index 0000000000..da95c7dcd2 --- /dev/null +++ b/changelog.d/1403-remove-unused-modules.md @@ -0,0 +1,5 @@ +- Remove four modules nothing in the app imports: `src/app/sourceSlot.js`, + `src/data/flowTiles.js`, `src/data/issPass.js` and `src/data/localGeojson.js`. + The local GeoJSON layer tests now build layers the way the catalog does, so + they keep covering `localGeojsonCore.js`. Package exports are unchanged + (samehkhamis, #1403). diff --git a/docs/CODE-BOUNDARIES.md b/docs/CODE-BOUNDARIES.md index 9085a7b722..9f8e0f6297 100644 --- a/docs/CODE-BOUNDARIES.md +++ b/docs/CODE-BOUNDARIES.md @@ -81,8 +81,6 @@ moves it. Do not label all ingestion modules platform-independent by filename. | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | `src/data/manager.js` | Lifecycle/panel compatibility and existing tests; normal assembly constructs lifecycle and presentation separately | | `src/data/.js` | Legacy default instances; new assembly calls layer factories with supplied sources | -| `src/data/localGeojson.js` | Infrastructure compatibility factories; catalog imports services from `src/app/localGeojsonServices.js` directly | -| `src/app/sourceSlot.js` | Re-export for direct callers/tests; portable slot ownership is `src/sources/sourceSlot.js` | | `src/app/sources.js`, `src/services/application.js` | Existing default/override API; current application construction supplies its own instances | | `server/providers/local.js` | Existing Node composition barrel and provider helper re-exports | diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 8be9af2049..3c53c93a2c 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4662,7 +4662,7 @@ current route throughout enabling, enabled, disabling, and uncertain lifecycle renders. Both routes preserve Radio power, playback, station, filter, and volume state. -Bundled datasets live in `src/data/local_data/` with per-folder provenance READMEs; they are lazily loaded via `src/data/localGeojson.js` (Vite `?url` assets) when toggled on. +Bundled datasets live in `src/data/local_data/` with per-folder provenance READMEs; they are lazily loaded via `src/data/localGeojsonCore.js` (Vite `?url` assets) when toggled on. A bundled dataset that fails to load is a broken install, not a blip, so it is never swallowed: `localGeojson.js` guards `response.ok`, reports `error` + diff --git a/docs/INFRASTRUCTURE-LAYERS.md b/docs/INFRASTRUCTURE-LAYERS.md index 76567e605f..31d3cb4cbf 100644 --- a/docs/INFRASTRUCTURE-LAYERS.md +++ b/docs/INFRASTRUCTURE-LAYERS.md @@ -53,9 +53,8 @@ Cesium installation shared with its viewer; it must not bundle separate copies. `gods-eye-view/infrastructure/geojson` exports the lower-level `createLocalGeoJsonLayer(options, services)` and existing infrastructure overlay helpers. `gods-eye-view/infrastructure/lod` exports the existing LOD policy helpers. -The standalone app's `src/data/localGeojson.js` keeps its original single-argument -factory and supplies its existing functions. Other consumers should use the package -exports, which do not import standalone application globals. +Consumers use the package exports, which do not import standalone application +globals. Dataset files and source/license notices remain under `src/data/local_data/`. Their input counts are 4,351 datacenter features and 704 dam features. Cesium may diff --git a/scripts/check-import-directions.mjs b/scripts/check-import-directions.mjs index 3f4fec617b..b6d8dba673 100644 --- a/scripts/check-import-directions.mjs +++ b/scripts/check-import-directions.mjs @@ -153,14 +153,6 @@ export function checkImportDirections(root) { file, 'Actions must consume feed state without the manager facade', ); - if ( - file === 'src/app/constructCatalog.js' && - to === 'src/data/localGeojson.js' - ) - report( - file, - 'Catalog must use the services owner without compatibility layer construction', - ); } return record; } diff --git a/scripts/format-scope.json b/scripts/format-scope.json index f88be2b6be..d62e8bb477 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -518,7 +518,6 @@ "src/layers/bikeshare/selection.js", "src/data/traffic.js", "src/data/bikeshare.js", - "src/data/flowTiles.js", "src/layers/traffic/source.test.mjs", "src/layers/bikeshare/source.test.mjs", "src/layers/bikeshare/proxyRoute.test.mjs", @@ -651,7 +650,6 @@ "src/agent/worldPacket.test.mjs", "src/voice/layerSummary.js", "build/application-html.js", - "src/app/sourceSlot.js", "src/app/sources.js", "src/ui/composition.js", "src/services/application.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index cddb29c409..89589091ad 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1163,7 +1163,6 @@ "satellites-layer": { "exports": ["./layers/satellites"], "modules": [ - "src/data/issPass.js", "src/data/satelliteClass.js", "src/data/satellitePass.js", "src/sources/tle.js", @@ -1853,14 +1852,12 @@ "src/data/iconOrientation.js", "src/data/infrastructure.js", "src/data/installationFeedback.js", - "src/data/issPass.js", "src/data/labelArbiter.js", "src/data/idSwitches.js", "src/data/layerState.js", "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/data/lifecycle.js", - "src/data/localGeojson.js", "src/data/localGeojsonCore.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", @@ -2672,13 +2669,11 @@ "src/data/iconOrientation.js", "src/data/infrastructure.js", "src/data/installationFeedback.js", - "src/data/issPass.js", "src/data/satellitePass.js", "src/data/labelArbiter.js", "src/data/idSwitches.js", "src/data/layerState.js", "src/data/layerStateTokenReservations.json", - "src/data/localGeojson.js", "src/data/localGeojsonCore.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", @@ -3663,7 +3658,6 @@ "exports": ["./layers/transit/standalone"], "modules": [ "src/cyberSonar.js", - "src/app/sourceSlot.js", "src/celestialRing.js", "src/data/approxDistance.js", "src/data/cameraSensitivity.js", diff --git a/src/app/sourceSlot.js b/src/app/sourceSlot.js deleted file mode 100644 index fe7590e3bc..0000000000 --- a/src/app/sourceSlot.js +++ /dev/null @@ -1,2 +0,0 @@ -// Compatibility entry; source contracts are owned by sources/. -export { createSourceSlot } from '../sources/sourceSlot.js'; diff --git a/src/app/sourceSlot.test.mjs b/src/app/sourceSlot.test.mjs deleted file mode 100644 index 1b1face0ca..0000000000 --- a/src/app/sourceSlot.test.mjs +++ /dev/null @@ -1,24 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { createSourceSlot } from './sourceSlot.js'; - -test('replacing a source rejects its late result and old cleanup cannot clear the new source', async () => { - let finish; - const slot = createSourceSlot({ read: async () => 'default' }, ['read']); - const old = slot.configure({ read: () => new Promise(resolve => { finish = resolve; }) }); - const pending = slot.source.read(); - const stop = slot.configure({ read: async () => 'replacement', attribution: { name: 'Replacement' } }); - old(); - finish('stale'); - await assert.rejects(pending, { name: 'AbortError' }); - assert.equal(await slot.source.read(), 'replacement'); - assert.equal(slot.source.attribution.name, 'Replacement'); - stop(); - assert.throws(() => slot.source.read(), /not configured/); -}); - -test('an invalid replacement leaves the working source intact', async () => { - const slot = createSourceSlot({ read: async () => 42 }, ['read']); - assert.throws(() => slot.configure({}), TypeError); - assert.equal(await slot.source.read(), 42); -}); diff --git a/src/data/flowTiles.js b/src/data/flowTiles.js deleted file mode 100644 index 07efb0d9a2..0000000000 --- a/src/data/flowTiles.js +++ /dev/null @@ -1,6 +0,0 @@ -import { createFlowTileSource } from '../layers/traffic/flowSource.js'; -export { tilesForBounds } from './tomtomTiles.js'; -export { decodeFlowTile } from '../layers/traffic/flowDecode.js'; -const source = createFlowTileSource(); -export const { fetchFlowForBounds, getFlowSessionStats, resetFlowTileCache } = - source; diff --git a/src/data/flowTiles.test.mjs b/src/data/flowTiles.test.mjs deleted file mode 100644 index 61a7ddb78b..0000000000 --- a/src/data/flowTiles.test.mjs +++ /dev/null @@ -1,162 +0,0 @@ -// src/data/flowTiles.test.mjs -import { test } from 'node:test'; -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { - decodeFlowTile, - fetchFlowForBounds, - tilesForBounds, - getFlowSessionStats, - resetFlowTileCache, -} from './flowTiles.js'; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); -// Real TomTom flow tile, downtown Austin z12 x935 y1686 (probed live 2026-07-16). -const FIXTURE = path.join(__dirname, 'fixtures', 'tomtom-flow-austin-12-935-1686.pbf'); -const FIXTURE_TILE = { z: 12, x: 935, y: 1686 }; - -function loadFixture() { - return fs.readFileSync(FIXTURE); -} - -// ── decodeFlowTile against the real fixture ───────────────── - -test('fixture decode: more than 50 flow segments', () => { - const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y); - assert.ok(segments.length > 50, `got ${segments.length}`); -}); - -test('fixture decode: every trafficLevel is within [0, 1]', () => { - const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y); - for (const s of segments) { - assert.ok(Number.isFinite(s.trafficLevel), `non-finite level: ${s.trafficLevel}`); - assert.ok(s.trafficLevel >= 0 && s.trafficLevel <= 1, `level out of range: ${s.trafficLevel}`); - } -}); - -test('fixture decode: all coordinates land in downtown Austin', () => { - const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y); - for (const s of segments) { - assert.ok(Array.isArray(s.coords) && s.coords.length >= 2, 'polyline too short'); - for (const [lon, lat] of s.coords) { - assert.ok(lon >= -98.0 && lon <= -97.5, `lon out of Austin range: ${lon}`); - assert.ok(lat >= 30.0 && lat <= 30.5, `lat out of Austin range: ${lat}`); - } - } -}); - -test('fixture decode: congestion exists (at least one trafficLevel < 1)', () => { - const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y); - assert.ok(segments.some((s) => s.trafficLevel < 1), 'no congested segment found'); -}); - -test('fixture decode: segment shape is {coords, trafficLevel, roadType, closure}', () => { - const segments = decodeFlowTile(loadFixture(), FIXTURE_TILE.z, FIXTURE_TILE.x, FIXTURE_TILE.y); - for (const s of segments) { - assert.equal(typeof s.roadType, 'string'); - assert.equal(typeof s.closure, 'boolean'); - } - // The fixture carries real closures — closure decoding is exercised, not vacuous. - assert.ok(segments.some((s) => s.closure === true), 'expected at least one closure in fixture'); -}); - -test('decode of a non-MVT buffer returns [] (defensive)', () => { - assert.deepEqual(decodeFlowTile(Buffer.from('not a protobuf tile'), 12, 935, 1686), []); -}); - -// ── tilesForBounds (re-exported slippy math) ──────────────── - -test('tilesForBounds: 30.2672,-97.7431 @ z12 -> covers x935 y1686', () => { - const tiles = tilesForBounds({ - south: 30.2672 - 0.001, north: 30.2672 + 0.001, - west: -97.7431 - 0.001, east: -97.7431 + 0.001, - }, 12); - assert.ok( - tiles.some((t) => t.z === 12 && t.x === 935 && t.y === 1686), - `fixture tile missing: ${JSON.stringify(tiles)}` - ); -}); - -// ── fetchFlowForBounds (stubbed fetch: cache + abort) ─────── - -/** Bounds fully inside the fixture tile. */ -const FIXTURE_BOUNDS = { south: 30.24, north: 30.26, west: -97.76, east: -97.74 }; - -function stubFetch(impl) { - const original = globalThis.fetch; - globalThis.fetch = impl; - return () => { globalThis.fetch = original; }; -} - -test('fetchFlowForBounds: fetches covering tiles via /api/tomtom and decodes', async () => { - resetFlowTileCache(); - const calls = []; - const restore = stubFetch(async (url) => { - calls.push(String(url)); - return new Response(loadFixture(), { - status: 200, - headers: { 'Content-Type': 'application/x-protobuf' }, - }); - }); - try { - const segments = await fetchFlowForBounds(FIXTURE_BOUNDS); - assert.equal(calls.length, 1); - assert.match(calls[0], /^\/api\/tomtom\/flow\/12\/935\/1686\.pbf$/); - assert.ok(segments.length > 50); - assert.ok(getFlowSessionStats().tilesFetched >= 1); - } finally { - restore(); - } -}); - -test('fetchFlowForBounds: decode cache serves repeat calls within TTL (no refetch)', async () => { - resetFlowTileCache(); - let calls = 0; - const restore = stubFetch(async () => { - calls += 1; - return new Response(loadFixture(), { status: 200 }); - }); - try { - const first = await fetchFlowForBounds(FIXTURE_BOUNDS); - const second = await fetchFlowForBounds(FIXTURE_BOUNDS); - assert.equal(calls, 1, 'second call must be served from the decode cache'); - assert.equal(second.length, first.length); - } finally { - restore(); - } -}); - -test('fetchFlowForBounds: aborted signal rejects (AbortSignal-aware)', async () => { - resetFlowTileCache(); - const restore = stubFetch(async (url, opts) => { - // Mimic real fetch abort semantics. - if (opts?.signal?.aborted) { - const err = new Error('aborted'); - err.name = 'AbortError'; - throw err; - } - return new Response(loadFixture(), { status: 200 }); - }); - try { - const controller = new AbortController(); - controller.abort(); - await assert.rejects( - fetchFlowForBounds(FIXTURE_BOUNDS, { signal: controller.signal }), - (err) => err.name === 'AbortError' - ); - } finally { - restore(); - } -}); - -test('fetchFlowForBounds: non-OK tile responses reject when nothing succeeds', async () => { - resetFlowTileCache(); - const restore = stubFetch(async () => new Response(JSON.stringify({ error: 'no_key' }), { status: 503 })); - try { - await assert.rejects(fetchFlowForBounds(FIXTURE_BOUNDS)); - } finally { - restore(); - } -}); diff --git a/src/data/issPass.js b/src/data/issPass.js deleted file mode 100644 index c3807d59f3..0000000000 --- a/src/data/issPass.js +++ /dev/null @@ -1,46 +0,0 @@ -// src/data/issPass.js -/** - * Next-ISS-pass prediction. Kept as a thin wrapper over satellitePass.js so the - * original findNextIssPass signature and defaults still work. - */ -import { findNextSatellitePass, lookAnglesAt } from './satellitePass.js'; - -export { lookAnglesAt }; - -/** - * Predict the next ISS pass over an observer location. - * @param {Object} options - * @param {Object} options.satrec SGP4 satellite record - * @param {number} options.latDeg Observer latitude in degrees [-90, 90] - * @param {number} options.lonDeg Observer longitude in degrees [-180, 180] - * @param {number} options.fromMs UTC start time in milliseconds - * @param {number} [options.minElevDeg=10] Elevation that defines rise and set, in degrees - * @param {number} [options.horizonHours=24] Maximum search window in hours - * @param {number} [options.coarseStepSec=30] Coarse search step in seconds - * @param {number} [options.fineStepSec=5] Fine transit step in seconds for peak tracking and visibility - * @param {boolean} [options.requireVisible=false] Require a naked-eye-visible pass - * @returns {{ riseMs: number, setMs: number, maxElevDeg: number, maxElevMs: number, riseAzDeg: number, visible: boolean, sunlit: boolean, observerDark: boolean } | null} - */ -export function findNextIssPass({ - satrec, - latDeg, - lonDeg, - fromMs, - minElevDeg = 10, - horizonHours = 24, - coarseStepSec = 30, - fineStepSec = 5, - requireVisible = false, -}) { - return findNextSatellitePass({ - satrec, - latDeg, - lonDeg, - fromMs, - minElevDeg, - horizonHours, - coarseStepSec, - fineStepSec, - requireVisible, - }); -} diff --git a/src/data/issPass.test.mjs b/src/data/issPass.test.mjs deleted file mode 100644 index aaaa87a559..0000000000 --- a/src/data/issPass.test.mjs +++ /dev/null @@ -1,42 +0,0 @@ -// src/data/issPass.test.mjs -import { test } from 'node:test'; -import assert from 'node:assert/strict'; -import { twoline2satrec } from 'satellite.js'; -import { findNextIssPass, lookAnglesAt } from './issPass.js'; -import { findNextSatellitePass } from './satellitePass.js'; - -// Canonical archived ISS TLE (valid checksums; epoch 2008-09-20 ~12:25 UTC). -const L1 = '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927'; -const L2 = '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537'; -const AUSTIN = { latDeg: 30.2672, lonDeg: -97.7431 }; -const FROM_MS = Date.UTC(2008, 8, 20, 12, 30, 0); // just after the TLE epoch - -test('finds a structurally-consistent ISS pass within 24h of the TLE epoch', () => { - const satrec = twoline2satrec(L1, L2); - const pass = findNextIssPass({ satrec, ...AUSTIN, fromMs: FROM_MS, minElevDeg: 10 }); - assert.ok(pass, 'expected a pass within 24h at 30°N for a 51.6° inclination orbit'); - assert.ok(pass.riseMs > FROM_MS); - assert.ok(pass.riseMs < pass.maxElevMs && pass.maxElevMs < pass.setMs); - assert.ok(pass.maxElevDeg >= 10); - assert.ok(pass.riseAzDeg >= 0 && pass.riseAzDeg < 360); - - // Independent re-check: elevation at the reported peak really is the max-ish - // and ≥ threshold; one minute before rise it is below threshold. - const peak = lookAnglesAt(satrec, pass.maxElevMs, AUSTIN.latDeg, AUSTIN.lonDeg); - assert.ok(peak && Math.abs(peak.elevDeg - pass.maxElevDeg) < 1.5); - const before = lookAnglesAt(satrec, pass.riseMs - 60_000, AUSTIN.latDeg, AUSTIN.lonDeg); - assert.ok(before && before.elevDeg < 10); -}); - -test('forwards its original 30 s coarse step and fineStepSec to the pass engine', () => { - const satrec = twoline2satrec(L1, L2); - const opts = { satrec, ...AUSTIN, fromMs: FROM_MS, minElevDeg: 10, fineStepSec: 30 }; - assert.deepEqual(findNextIssPass(opts), findNextSatellitePass({ ...opts, coarseStepSec: 30 })); - assert.notDeepEqual(findNextIssPass(opts), findNextIssPass({ ...opts, fineStepSec: 5 })); -}); - -test('returns null when no pass clears an absurd threshold', () => { - const satrec = twoline2satrec(L1, L2); - const pass = findNextIssPass({ satrec, ...AUSTIN, fromMs: FROM_MS, minElevDeg: 89.9, horizonHours: 2 }); - assert.equal(pass, null); -}); diff --git a/src/data/localGeojson.analyst.test.mjs b/src/data/localGeojson.analyst.test.mjs index 061a7f27c8..33d35a039a 100644 --- a/src/data/localGeojson.analyst.test.mjs +++ b/src/data/localGeojson.analyst.test.mjs @@ -2,7 +2,18 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { createLocalGeoJsonLayer, mapAnalystRecord } from './localGeojson.js'; +import { localGeoJsonServices } from '../app/localGeojsonServices.js'; +import { + createLocalGeoJsonLayer as createLayer, + mapAnalystRecord, +} from './localGeojsonCore.js'; + +/** The catalog's services, with the overlay host each test supplies. */ +const createLocalGeoJsonLayer = (options) => + createLayer(options, { + ...localGeoJsonServices, + overlayHost: options.overlayHost, + }); const DC_RAW = { id: '1176042553', diff --git a/src/data/localGeojson.js b/src/data/localGeojson.js deleted file mode 100644 index 61f6c3abf9..0000000000 --- a/src/data/localGeojson.js +++ /dev/null @@ -1,29 +0,0 @@ -import { localGeoJsonServices } from '../app/localGeojsonServices.js'; -import { - createLocalGeoJsonLayer as createLayer, - createLocalInfrastructureOverlayPublisher as createPublisher, -} from './localGeojsonCore.js'; - -export * from './localGeojsonCore.js'; - -/** Create a layer using the standalone app's operations; retain overlay overrides. */ -export function createLocalGeoJsonLayer(options) { - return createLayer(options, { - ...localGeoJsonServices, - overlayHost: - options.overlayHost === undefined - ? localGeoJsonServices.overlayHost - : options.overlayHost, - }); -} - -/** Create an overlay publisher using the standalone app's host by default. */ -export function createLocalInfrastructureOverlayPublisher(options) { - return createPublisher({ - ...options, - host: - options.host === undefined - ? localGeoJsonServices.overlayHost - : options.host, - }); -} diff --git a/src/data/localGeojson.test.mjs b/src/data/localGeojson.test.mjs index 1c44999143..13cde65a51 100644 --- a/src/data/localGeojson.test.mjs +++ b/src/data/localGeojson.test.mjs @@ -6,13 +6,14 @@ import { GROUND_SAMPLE_MAX_ARMED_RETRIES, LOCAL_OVERLAY_COHORT_LIMIT, LOCAL_STEM_TIP_EPSILON_M, - createLocalGeoJsonLayer, + createLocalGeoJsonLayer as createLayer, createLocalInfrastructureOverlayEntry, createLocalInfrastructureOverlayPublisher, localDatasetError, localInfrastructureOverlayCopy, selectLocalInfrastructureOverlayCohort, -} from './localGeojson.js'; +} from './localGeojsonCore.js'; +import { localGeoJsonServices } from '../app/localGeojsonServices.js'; import { layerFeedState } from './manager.js'; import { INFRA_LOD_ACTIVE_MIN, INFRA_LOD_ACTIVE_MAX } from './localGeojsonLod.js'; import { @@ -21,6 +22,13 @@ import { _resetRenderGovernorForTest, } from '../renderGovernor.js'; +/** The catalog's services, with the overlay host each test supplies. */ +const createLocalGeoJsonLayer = (options) => + createLayer(options, { + ...localGeoJsonServices, + overlayHost: options.overlayHost ?? localGeoJsonServices.overlayHost, + }); + class MockLayerEvent { constructor() { this.listeners = new Set(); @@ -1337,14 +1345,3 @@ test('globe-LOD re-selects during continuous motion, without ever seeing a moveE assert.deepEqual(env.layer.getLodDiagnostics(), parked, 'a parked camera never re-selects'); }); - -test('standalone publisher retains its default host for an undefined override', () => { - const publisher = createLocalInfrastructureOverlayPublisher({ - sourceId: 'local-default-host-test', host: undefined, - }); - assert.doesNotThrow(() => { - publisher.show(); - publisher.hide(); - publisher.destroy(); - }); -}); diff --git a/src/data/localGeojsonLifecycle.test.mjs b/src/data/localGeojsonLifecycle.test.mjs index 245867155a..8b5621ec48 100644 --- a/src/data/localGeojsonLifecycle.test.mjs +++ b/src/data/localGeojsonLifecycle.test.mjs @@ -1,9 +1,17 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { createLocalGeoJsonLayer } from './localGeojson.js'; +import { localGeoJsonServices } from '../app/localGeojsonServices.js'; +import { createLocalGeoJsonLayer as createLayer } from './localGeojsonCore.js'; import { getContextStore } from './contextStore.js'; +/** The catalog's services, with the overlay host each test supplies. */ +const createLocalGeoJsonLayer = (options) => + createLayer(options, { + ...localGeoJsonServices, + overlayHost: options.overlayHost, + }); + const dataset = JSON.stringify({ type: 'Feature', id: 'dam', properties: { name: 'Test dam' }, geometry: { type: 'Polygon', coordinates: [[[0, 0], [0.01, 0], [0, 0.01], [0, 0]]] }, diff --git a/src/data/localGeojsonLod.js b/src/data/localGeojsonLod.js index cfd082c042..4a2dd92daf 100644 --- a/src/data/localGeojsonLod.js +++ b/src/data/localGeojsonLod.js @@ -5,7 +5,7 @@ * Pure selection policy for the bundled local-infrastructure layers * (`local-datacenters`, `local-dams`, and any future `createLocalGeoJsonLayer` * dataset). Cesium-specific projection, occlusion, and stem geometry stay in - * `localGeojson.js`; this module turns the resulting in-view records into a + * `localGeojsonCore.js`; this module turns the resulting in-view records into a * bounded "active" set — the only records that layer should spend per-frame * stem-geometry and ground-sample work on. * @@ -80,7 +80,7 @@ export const INFRA_LOD_INCUMBENT_BONUS = 250; /** * Distance at or beyond which the proximity penalty is fully applied (m). - * Matches LOCAL_OVERLAY_MAX_DISTANCE_M's order of magnitude in localGeojson.js. + * Matches LOCAL_OVERLAY_MAX_DISTANCE_M's order of magnitude in infrastructureOverlayEntry.js. */ export const INFRA_LOD_FAR_M = 12_000_000; @@ -97,7 +97,7 @@ export const INFRA_LOD_MAX_DISTANCE_PENALTY = 200; * (callers only compare it), but every input is normalized so the output is * always a finite number. * - * @param {number} priority Existing label-priority score (localGeojson.js). + * @param {number} priority Existing label-priority score (localGeojsonCore.js). * @param {number} distanceM Camera→feature distance in metres. * @param {boolean} isIncumbent Record currently holds an active stem. * @param {object} [options] @@ -297,7 +297,7 @@ export function applyInfraEvictionGrace({ * ------------------------------------------------------------------ */ /** - * Probe window for the motion fallback. `localGeojson.js` marks its selection + * Probe window for the motion fallback. `localGeojsonCore.js` marks its selection * dirty on `moveEnd`, which covers drags, one-shot `setView`, and voice * `flyTo` — but a tracked-entity follow camera, a Cockpit view, a route * flight, or a continuous orbit never emits one. Without a fallback the diff --git a/src/data/tomtomTiles.js b/src/data/tomtomTiles.js index af4fc95b3b..26ec539ab6 100644 --- a/src/data/tomtomTiles.js +++ b/src/data/tomtomTiles.js @@ -2,7 +2,7 @@ * @file Pure tile math + budget accounting for the TomTom traffic-flow proxy. * * Shared by the `/api/tomtom` vite plugin (server-side: coordinate validation, - * daily budget governor) and `src/data/flowTiles.js` (client-side: which tiles + * daily budget governor) and `src/layers/traffic/flowSource.js` (client-side: which tiles * cover the current traffic fetch bounds). Zero dependencies, Cesium-free, so * both sides can unit-test against it with node:test. * diff --git a/src/layers/traffic/flowDecode.js b/src/layers/traffic/flowDecode.js index 6914965541..9a0c248dda 100644 --- a/src/layers/traffic/flowDecode.js +++ b/src/layers/traffic/flowDecode.js @@ -19,7 +19,7 @@ import { VectorTile } from '@mapbox/vector-tile'; * tree-shakeable; decoding happens client-side so the proxy stays a dumb * binary cache. * - * @module data/flowTiles + * @module layers/traffic/flowDecode */ const FLOW_LAYER_NAME = 'Traffic flow'; diff --git a/src/overlays/worldOverlayAllocation.test.mjs b/src/overlays/worldOverlayAllocation.test.mjs index e29785d487..2ff6d6c8ca 100644 --- a/src/overlays/worldOverlayAllocation.test.mjs +++ b/src/overlays/worldOverlayAllocation.test.mjs @@ -2,7 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; -import { LOCAL_OVERLAY_COHORT_LIMIT } from '../data/localGeojson.js'; +import { LOCAL_OVERLAY_COHORT_LIMIT } from '../data/localGeojsonCore.js'; import { FIRMS_AMBIENT_COHORT_LIMIT } from '../data/firmsLabels.js'; import { vesselOverlayCohortLimit } from '../data/vesselLabels.js'; import { CCTV_AMBIENT_CARD_MAX } from '../data/cctvLod.js'; From 3a28dcab0775388af2c42ae1dbd8fdb8c1d1f5e8 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 17:32:15 -0700 Subject: [PATCH 46/54] fix(docker): align health probe port parsing and document health status --- Dockerfile | 2 +- changelog.d/1394-docker-healthcheck.md | 2 ++ docs/CURRENT-STATE.md | 9 +++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 changelog.d/1394-docker-healthcheck.md diff --git a/Dockerfile b/Dockerfile index 4628279aff..433d170a86 100644 --- a/Dockerfile +++ b/Dockerfile @@ -43,7 +43,7 @@ EXPOSE 4173 # always on the Host allowlist, and the generous start period covers Vite's # first-run dependency optimisation. HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \ - CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||4173)+'/').then((r)=>process.exit(r.ok?0:1),()=>process.exit(1))"] + CMD ["node", "-e", "fetch('http://127.0.0.1:'+(Number.parseInt(process.env.PORT,10)||4173)+'/').then((r)=>process.exit(r.ok?0:1),()=>process.exit(1))"] # The launcher is `npm run dev` plus one step: it trusts the container's # gateway address for Provider Settings, because that is where Docker delivers # the host's own browser from (never 127.0.0.1). See scripts/docker-start.mjs. diff --git a/changelog.d/1394-docker-healthcheck.md b/changelog.d/1394-docker-healthcheck.md new file mode 100644 index 0000000000..75ead96673 --- /dev/null +++ b/changelog.d/1394-docker-healthcheck.md @@ -0,0 +1,2 @@ +- Report Docker container health with a local HTTP check using Node, with the + same port parsing as the launcher (John Rogers, @14traits, #1394). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 3c53c93a2c..63d523c280 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -6228,3 +6228,12 @@ when their footprints touch or contain one another, never across a seam toleranc - `scripts/qa-form-fields.mjs` exercises native selections, number validity, calibration commit/cancel and stale-camera/disposal guards against an installed controller with fixture ports, plus default/Cyber and narrow translated layouts. + +## Docker health reporting + +The Docker image probes its local HTTP root with Node every 30 seconds, using +the launcher's parsed `PORT` (default 4173). A successful HTTP response marks +the container healthy. Checks time out after 10 seconds, with a 30-second +startup grace period and three consecutive failures before reporting unhealthy. +This reports app HTTP availability, not individual provider health, and does not +configure automatic restarts. From 2a17491c8bd5afe0e7cf01ac9137361941329713 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?An=C4=B1l=20G=C3=BCven=C3=A7?= Date: Mon, 26 Oct 2026 03:54:16 +0300 Subject: [PATCH 47/54] fix(docker): let SELinux hosts read the bind-mounted checkout (#1391) Allow the Docker checkout bind mount on SELinux hosts. Contribution by @anilguvenc. --- README.md | 2 ++ changelog.d/1391-docker-selinux.md | 4 ++++ compose.yaml | 5 ++++- docs/CURRENT-STATE.md | 4 ++++ src/dockerLauncher.test.mjs | 1 + 5 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 changelog.d/1391-docker-selinux.md diff --git a/README.md b/README.md index 80f052571a..ca90bf2c0c 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,8 @@ env UID=1026 GID=100 docker compose up -d Keep the `env`: bash treats `UID` as read-only, so a plain `UID=1026` in front of a command is silently ignored. If the container can't write the checkout, it says so at start. Docker Desktop on macOS and Windows maps ownership for you. +On SELinux hosts (Fedora, RHEL), compose mounts the checkout with `:z` so the container may read it; Docker may relabel the checkout for container access, which can take a moment on a large checkout. Without that, the start fails with `Cannot find module '/app/scripts/docker-start.mjs'`. + Behind a reverse proxy, put your keys in `.env` or pass them as environment variables - Provider Settings refuses proxied requests on purpose - and add the hostname you serve it on, for example `GEV_ALLOWED_HOSTS=globe.example.lan` (see [Sharing an instance](#-sharing-an-instance)). diff --git a/changelog.d/1391-docker-selinux.md b/changelog.d/1391-docker-selinux.md new file mode 100644 index 0000000000..186147a2e3 --- /dev/null +++ b/changelog.d/1391-docker-selinux.md @@ -0,0 +1,4 @@ +- Start the Docker install on SELinux hosts such as Fedora and RHEL. Compose now + mounts the checkout with `:z`; without it the container could not read `/app` + and stopped with "Cannot find module '/app/scripts/docker-start.mjs'" + (Anıl Güvenç, @anilguvenc, #1391). diff --git a/compose.yaml b/compose.yaml index c2d3bf3d4f..38cf438ca0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -22,5 +22,8 @@ services: # UI land in the .env on your host instead of vanishing with the # container. node_modules stays in the image: sharp and friends are # compiled for Linux and must not be shadowed by a host install. - - .:/app + # `:z` relabels the checkout for containers on SELinux hosts (Fedora, + # RHEL); without it the container cannot read /app at all and Node + # reports the launcher as "Cannot find module". Elsewhere it is ignored. + - .:/app:z - /app/node_modules diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 63d523c280..98214e5412 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1,5 +1,9 @@ # God's Eye View Current State +Docker Compose mounts the checkout with the shared SELinux `:z` label so +containers can read it on enforcing SELinux hosts. The separate image-owned +`node_modules` volume and loopback-only port publishing remain unchanged. + Aircraft detection candidates reuse normalized display text until callsign or registration changes, including in-place enrichment. Each candidate resolves its fleet model once per collection. Positions, model ownership and tracked-aircraft diff --git a/src/dockerLauncher.test.mjs b/src/dockerLauncher.test.mjs index 213fe59dc2..4e97849c0a 100644 --- a/src/dockerLauncher.test.mjs +++ b/src/dockerLauncher.test.mjs @@ -75,4 +75,5 @@ test('the Docker install path keeps its loopback-only, launcher-owned contract', assert.match(compose, /^\s+- GEV_KEY_SETUP_TRUSTED_PEERS$/m, 'the operator policy reaches the launcher without a hard-coded address'); assert.match(compose, /^\s+- GEV_ALLOWED_HOSTS$/m, 'the host allowlist reaches Vite'); assert.doesNotMatch(compose, /network_mode/, 'the container keeps its own network namespace'); + assert.match(compose, /^\s+- \.:\/app:z$/m, 'SELinux hosts can read the bind-mounted checkout'); }); From a15fdd31340872a32e84453d1e59b48eb519b720 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:59:09 -0400 Subject: [PATCH 48/54] fix(hud): carry rounded DMS seconds into the minutes (#1339) Carry rounded HUD coordinate seconds into minutes and degrees. Contribution by @rudycelekli. --- changelog.d/1339-hud-dms-carry.md | 3 + docs/CURRENT-STATE.md | 6 ++ scripts/format-scope.json | 3 +- src/hud.js | 11 ++-- src/hudDms.test.mjs | 106 ++++++++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 6 deletions(-) create mode 100644 changelog.d/1339-hud-dms-carry.md create mode 100644 src/hudDms.test.mjs diff --git a/changelog.d/1339-hud-dms-carry.md b/changelog.d/1339-hud-dms-carry.md new file mode 100644 index 0000000000..588668afe0 --- /dev/null +++ b/changelog.d/1339-hud-dms-carry.md @@ -0,0 +1,3 @@ +- Carry HUD LAT/LON seconds that round up to 60.00" into the minutes and + degrees, so longitude -122.35 reads `122°21'00.00"W` instead of + `122°20'60.00"W` (rudycelekli, #1339). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 98214e5412..bfbfcca903 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4,6 +4,12 @@ Docker Compose mounts the checkout with the shared SELinux `:z` label so containers can read it on enforcing SELinux hosts. The separate image-owned `node_modules` volume and loopback-only port publishing remain unchanged. +The HUD's LAT/LON degrees-minutes-seconds readout rounds the coordinate once, to +hundredths of a second, and then splits it. A value within 0.005" of the next +whole minute carries into the minutes and degrees, so `-122.35` reads +`122°21'00.00"W` rather than `122°20'60.00"W`. The field widths and hemisphere +letters are unchanged. + Aircraft detection candidates reuse normalized display text until callsign or registration changes, including in-place enrichment. Each candidate resolves its fleet model once per collection. Positions, model ownership and tracked-aircraft diff --git a/scripts/format-scope.json b/scripts/format-scope.json index d62e8bb477..20e28122a6 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1087,5 +1087,6 @@ "scripts/qa-status-badges.mjs", "src/dockerTrustedPeers.test.mjs", "src/cameraGlobeRotation.test.mjs", - "src/voice/globeResetConfirmation.test.mjs" + "src/voice/globeResetConfirmation.test.mjs", + "src/hudDms.test.mjs" ] diff --git a/src/hud.js b/src/hud.js index cf7983da72..1428f8503d 100644 --- a/src/hud.js +++ b/src/hud.js @@ -574,11 +574,12 @@ export class IntelHUD { * @returns {string} Formatted DMS string, e.g. `"38°53'23.10"N"`. */ _toDMS(decimal, type) { - const abs = Math.abs(decimal); - const deg = Math.floor(abs); - const minFloat = (abs - deg) * 60; - const min = Math.floor(minFloat); - const sec = ((minFloat - min) * 60).toFixed(2); + // Round once, in hundredths of a second, so a value that rounds up to + // 60.00" carries into the minutes and degrees instead of printing 60. + const hundredths = Math.round(Math.abs(decimal) * 360000); + const deg = Math.floor(hundredths / 360000); + const min = Math.floor(hundredths / 6000) % 60; + const sec = ((hundredths % 6000) / 100).toFixed(2); let dir; if (type === 'lat') dir = decimal >= 0 ? 'N' : 'S'; diff --git a/src/hudDms.test.mjs b/src/hudDms.test.mjs new file mode 100644 index 0000000000..064906b5fc --- /dev/null +++ b/src/hudDms.test.mjs @@ -0,0 +1,106 @@ +// The HUD's LAT/LON readout in degrees-minutes-seconds. Seconds are printed to +// two decimals, so a value within 0.005" of the next whole minute rounds up. +// That carry must reach the minutes (and degrees): `122°20'60.00"W` is not a +// coordinate. Ordinary decimal inputs land there through binary floating +// point: 122.35 - 122 is 0.34999999999999432, so -122.35 read 20'60.00". +// +// hud.js imports `mgrs`, a CommonJS package whose named exports Node's ESM +// loader cannot see, so this installs the same one-specifier stub as +// hudAltitudeDatum.test.mjs before importing it. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { registerHooks } from 'node:module'; + +const MGRS_STUB_URL = 'gev-test-stub:mgrs'; +registerHooks({ + resolve(specifier, context, next) { + if (specifier === 'mgrs') return { url: MGRS_STUB_URL, shortCircuit: true }; + return next(specifier, context); + }, + load(url, context, next) { + if (url === MGRS_STUB_URL) { + return { + format: 'module', + shortCircuit: true, + source: + 'export function forward() { return "10SEG55776339"; }\nexport default { forward };\n', + }; + } + return next(url, context); + }, +}); + +const { IntelHUD } = await import('./hud.js'); + +const toDMS = (decimal, type) => IntelHUD.prototype._toDMS(decimal, type); + +test('a rounded-up second carries into the minutes', () => { + assert.equal(toDMS(-122.35, 'lon'), `122°21'00.00"W`); + assert.equal(toDMS(139.7, 'lon'), `139°42'00.00"E`); + assert.equal(toDMS(37.0166666, 'lat'), `37°01'00.00"N`); +}); + +test('a carry through 59 minutes reaches the degrees', () => { + assert.equal(toDMS(38.999999, 'lat'), `39°00'00.00"N`); + assert.equal(toDMS(-0.999999, 'lat'), `01°00'00.00"S`); + assert.equal(toDMS(179.999999, 'lon'), `180°00'00.00"E`); +}); + +test('ordinary values keep their existing format', () => { + assert.equal(toDMS(38.889722, 'lat'), `38°53'23.00"N`); + assert.equal(toDMS(-77.035278, 'lon'), `077°02'07.00"W`); + assert.equal(toDMS(51.5, 'lat'), `51°30'00.00"N`); + assert.equal(toDMS(-33.8568, 'lat'), `33°51'24.48"S`); + assert.equal(toDMS(0, 'lon'), `000°00'00.00"E`); + assert.equal(toDMS(90, 'lat'), `90°00'00.00"N`); +}); + +test('the telemetry tick paints the carried value into both readouts', () => { + const elements = new Map( + [ + 'hud-alt', + 'hud-summary', + 'hud-mgrs', + 'hud-latlon', + 'hud-bottom-line', + 'hud-gsd', + 'hud-coll', + 'hud-ona', + 'hud-mode', + ].map((id) => [id, { textContent: '' }]), + ); + const previousDocument = globalThis.document; + globalThis.document = { + getElementById: (id) => elements.get(id) ?? null, + querySelectorAll: () => [], + addEventListener() {}, + removeEventListener() {}, + }; + const viewer = { + camera: { + pitch: -Math.PI / 2, + positionCartographic: { + latitude: (37.75 * Math.PI) / 180, + longitude: (-122.35 * Math.PI) / 180, + height: 1500, + }, + computeViewRectangle: () => undefined, + moveStart: { addEventListener() {}, removeEventListener() {} }, + moveEnd: { addEventListener() {}, removeEventListener() {} }, + }, + }; + let hud; + try { + hud = new IntelHUD(viewer); + hud._updateCameraData(); + const latlon = elements.get('hud-latlon').textContent; + const bottom = elements.get('hud-bottom-line').textContent; + assert.equal(latlon, `37°45'00.00"N 122°21'00.00"W`); + assert.match(bottom, /LON: 122°21'00\.00"W/); + assert.doesNotMatch(`${latlon} ${bottom}`, /60\.00"/); + } finally { + hud?.destroy(); + if (previousDocument === undefined) delete globalThis.document; + else globalThis.document = previousDocument; + } +}); From 0dce2f8d04dc2048cf080d2e8894596f2ff5976a Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 18:47:57 -0700 Subject: [PATCH 49/54] fix: complete PR #948 integration and documentation --- SECURITY.md | 5 +++++ docs/CURRENT-STATE.md | 6 ++++++ src/tooling/viteBuild.test.mjs | 15 +++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/SECURITY.md b/SECURITY.md index 1baad029fd..4423eead3e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,6 +2,11 @@ God's Eye View is a local-first client for **public** data. It is built for exploration, demos, and learning — not as a hardened production service. This document explains the security model so you can run it safely and report issues responsibly. +Vite's development file server also denies `.gev-logs/`, `.gev-cache/`, and +the package checkout's root `dist/` directory. Dependency `dist/` directories +remain available. This filesystem deny list does not filter `public/` assets or +preview output; never put private artifacts in a public asset directory. + ## Reporting a vulnerability Please report security issues **privately** — do not open a public issue for anything exploitable. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index bfbfcca903..da82032644 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5385,6 +5385,12 @@ pins and share links already supply complete boxes. ## Auth + Launch +Vite's development filesystem deny list excludes local `.gev-logs/` and +`.gev-cache/` contents and the package checkout's root `dist/`, while allowing +dependency `dist/` assets. Checkout glob characters are escaped. This does not +apply to `public/` assets or built-preview serving. + + - Recommended launcher: `./scripts/dev-fresh.sh` (also: `dev-secure.sh` for stricter bindings, `dev-cctv.sh` for CCTV source-pack tuning) - A successful Pinokio install writes the owner-only `pinokio/.installed` marker. The nested launcher menu resolves that marker from its own directory: diff --git a/src/tooling/viteBuild.test.mjs b/src/tooling/viteBuild.test.mjs index 2ca9291767..075363e83e 100644 --- a/src/tooling/viteBuild.test.mjs +++ b/src/tooling/viteBuild.test.mjs @@ -1,3 +1,4 @@ +import { fileURLToPath } from 'node:url'; import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; @@ -30,6 +31,20 @@ test('explicit build inputs preserve browser-only defines, plugin order and loop assert.deepEqual(config.server.allowedHosts, ['localhost', '127.0.0.1']); assert.ok(config.server.fs.deny.includes('**/ENVIRONMENT')); assert.ok(config.server.fs.deny.includes('.env.*')); + assert.ok(config.server.fs.deny.includes('**/.gev-logs/**')); + assert.ok(config.server.fs.deny.includes('**/.gev-cache/**')); + const root = fileURLToPath(new URL('../../', import.meta.url)) + .replace(/\\/g, '/') + .replace(/\/$/, ''); + assert.deepEqual( + config.server.fs.deny.filter((pattern) => pattern.endsWith('/dist/**')), + [`${escapeFsDenyPath(root)}/dist/**`], + 'only project build output is denied, not dependency dist directories', + ); + assert.equal( + escapeFsDenyPath('C:/Users/a/project (1) [test]{copy}'), + 'C:/Users/a/project \\(1\\) \\[test\\]\\{copy\\}', + ); assert.equal(config.server.headers['X-Frame-Options'], 'DENY'); assert.equal(config.server.headers['X-Content-Type-Options'], 'nosniff'); const csp = config.server.headers['Content-Security-Policy']; From 1663733b58a33bfe1cdd9b233879ccebdcd9445e Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 25 Oct 2026 18:49:31 -0700 Subject: [PATCH 50/54] style: format Vite deny-list test imports --- src/tooling/viteBuild.test.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/tooling/viteBuild.test.mjs b/src/tooling/viteBuild.test.mjs index 075363e83e..2a4988e30a 100644 --- a/src/tooling/viteBuild.test.mjs +++ b/src/tooling/viteBuild.test.mjs @@ -6,7 +6,11 @@ import { rm, writeFile } from 'node:fs/promises'; import { request } from 'node:http'; import path from 'node:path'; import { build, createServer, preview } from 'vite'; -import { BROWSER_CSP, createBrowserViteConfig, escapeFsDenyPath } from '../../build/vite.js'; +import { + BROWSER_CSP, + createBrowserViteConfig, + escapeFsDenyPath, +} from '../../build/vite.js'; import standaloneConfig, * as compatibility from '../../vite.config.js'; import * as providers from '../../server/providers/local.js'; import { apiNotFoundPlugin } from '../../server/standalone/api-not-found.js'; From 3a724f055abece7a33005363b60eac183a5b35ee Mon Sep 17 00:00:00 2001 From: NukeThemAII <125676612+NukeThemAII@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:53:32 +0700 Subject: [PATCH 51/54] fix(pinokio): open the app in the system browser (#1222) Open the Pinokio app in the system browser while retaining application framing protection. Contribution by @NukeThemAII. --- README.md | 6 ++++-- changelog.d/1222-pinokio-open-in-browser.md | 3 +++ docs/CURRENT-STATE.md | 6 +++++- pinokio/pinokio.js | 4 +++- src/pinokioLauncherContract.test.mjs | 3 +++ 5 files changed, 18 insertions(+), 4 deletions(-) create mode 100644 changelog.d/1222-pinokio-open-in-browser.md diff --git a/README.md b/README.md index ca90bf2c0c..0a7509efad 100644 --- a/README.md +++ b/README.md @@ -111,13 +111,15 @@ app's **POWER UP** panel; [Keys & Costs](#-api-keys) explains the options. Available on **Windows, macOS, and Linux**. The Pinokio maintainer reports cross-platform testing of the fixed installer. The launcher installs the -locked dependencies, finds a free local port, and opens the app. +locked dependencies, finds a free local port, and opens the app in your system +browser. The Server menu item keeps the launcher console available. **Tried before and installation failed?** Update Pinokio and try again. Version 8.2 fixes the launcher installation issue; [details from the Pinokio maintainer](https://pinokio.co/posts/01m1m4p9xxm3qw7dnnpj2wr93g). -**Pinokio opens but the globe is very choppy?** Before treating that as a GPU +**Using an older launcher or opening the embedded view manually?** If the globe +is very choppy, before treating that as a GPU compatibility or minimum-hardware problem, copy the local server URL shown by Pinokio and open the same URL in your normal hardware-accelerated browser. One Pinokio 8.2.0 user reported severe stutter in Pinokio's embedded view that went diff --git a/changelog.d/1222-pinokio-open-in-browser.md b/changelog.d/1222-pinokio-open-in-browser.md new file mode 100644 index 0000000000..bc6b62402b --- /dev/null +++ b/changelog.d/1222-pinokio-open-in-browser.md @@ -0,0 +1,3 @@ +- Open God's Eye View from Pinokio in the system browser using the supported + `popout` menu option. The application's framing policy is unchanged + (NukeThemAII, #1222). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index bfbfcca903..439b292848 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5389,7 +5389,11 @@ pins and share links already supply complete boxes. - A successful Pinokio install writes the owner-only `pinokio/.installed` marker. The nested launcher menu resolves that marker from its own directory: an absent marker exposes Install, a present marker exposes Start, and a - running server with a captured ready URL exposes Open God's Eye View. + running server with a captured ready URL exposes Open God's Eye View. That + default item uses Pinokio's `popout` option to open the system browser; the + Server item retains the launcher console. The app's framing headers stay + unchanged. This does not assume all Pinokio desktop versions enforce those + headers in their embedded view. - Build gate: `npm run build` - Network access: local-only by default (`HOST=localhost` in dev-fresh.sh); LAN is an explicit opt-in via `HOST=0.0.0.0` (launcher prints a key-exposure warning + LAN URL; see SECURITY.md) - OpenSky default mode: OAuth (`OPENSKY_AUTH_MODE=oauth`; `anon` works without credentials) diff --git a/pinokio/pinokio.js b/pinokio/pinokio.js index d781c1a584..49c42a3618 100644 --- a/pinokio/pinokio.js +++ b/pinokio/pinokio.js @@ -22,8 +22,10 @@ module.exports = { if (starting) { const local = info.local('start.js'); if (local?.url) { + // Open in the system browser without changing the app's framing policy. + // This also avoids relying on Pinokio's embedded browser behavior. return [ - { default: true, icon: 'fa-solid fa-earth-americas', text: 'Open God\'s Eye View', href: local.url }, + { default: true, icon: 'fa-solid fa-earth-americas', text: 'Open God\'s Eye View', href: local.url, popout: true }, { icon: 'fa-solid fa-terminal', text: 'Server', href: 'start.js' }, ]; } diff --git a/src/pinokioLauncherContract.test.mjs b/src/pinokioLauncherContract.test.mjs index 24c9a9908b..78748ff322 100644 --- a/src/pinokioLauncherContract.test.mjs +++ b/src/pinokioLauncherContract.test.mjs @@ -113,6 +113,9 @@ test('Pinokio menu resolves the nested install marker and exposes each lifecycle runtime.url = url; const items = await menu(kernel, info); assert.equal(items.filter((item) => item.default).length, 1); + const ready = installed && running === 'start.js' && Boolean(url); + assert.equal(items[0].popout, ready ? true : undefined); + assert.ok(items.slice(1).every((item) => item.popout === undefined)); return items.map(({ text, href, default: isDefault = false }) => ({ text, href, default: isDefault })); }; From 06c51d3438cbcdc0367220ae997b62583a8b0527 Mon Sep 17 00:00:00 2001 From: nu-stats <113466924+nu-stats@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:07:12 -0400 Subject: [PATCH 52/54] perf(weather): wake a staged frame on a 150 ms timer, not every render (#1345) Wake staged weather imagery on a bounded timer instead of requesting every render. Contribution by @nu-stats. --- changelog.d/1345-weather-staging-wake.md | 3 ++ docs/CURRENT-STATE.md | 4 +++ src/layers/weather/rendering.js | 21 +++++++++-- src/layers/weather/weather.test.mjs | 46 +++++++++++++++++++++++- 4 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 changelog.d/1345-weather-staging-wake.md diff --git a/changelog.d/1345-weather-staging-wake.md b/changelog.d/1345-weather-staging-wake.md new file mode 100644 index 0000000000..fec4d54ec4 --- /dev/null +++ b/changelog.d/1345-weather-staging-wake.md @@ -0,0 +1,3 @@ +- Wake staged weather imagery on a 150 ms timer while waiting for readiness, + avoiding a continuous render loop and cancelling the wake when work ends + (@nu-stats, #1345). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index b09cef3315..4b9e306ea9 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -306,6 +306,10 @@ catalog construction owns each instance. Wind animates one forecast without advancing forecast time. Separate Weather observation layers provide radar and satellite history; none claims measured cloud volume. Weather imagery releases its camera move listener on disable and registers it once on re-enable. Disabling also clears active imagery work. +A staged weather frame with loaded tiles and no pending requests rechecks +readiness on a single 150 ms wake timer instead of requesting every render. +The existing readiness conditions and two settled frames still govern promotion; +completion, cancellation, replacement and teardown clear the wake timer. Weather imagery drapes onto the globe basemap. On photorealistic 3D Tiles each observed product is instead a raised, translucent shell: one rectangle over the product bounds at a fixed height (global infrared 5.5 km, regional infrared diff --git a/src/layers/weather/rendering.js b/src/layers/weather/rendering.js index b25bcceb29..0f2fad68b7 100644 --- a/src/layers/weather/rendering.js +++ b/src/layers/weather/rendering.js @@ -14,6 +14,8 @@ const GLOBAL_TILE_MAXIMUM_LEVEL = 3; // Six decoded 2048×1024 canvases (8 MiB each) bound the cache below 50 MiB. const MAX_MOSAICS = 6; const MAX_PREFETCH_TILES = 8; +// How often a staged frame waiting out its quiet interval rechecks readiness. +export const READY_WAKE_MS = 150; /** Globe imagery: own at most a displayed and a staging frame. Use native Cesium * tile scheduling, projection and texture disposal; the application clock is never touched. */ @@ -126,6 +128,7 @@ function createGlobeRendering({ frame.offRender?.(); frame.offCamera?.(); clearTimeout(frame.timeout); + clearTimeout(frame.wake); for (const request of frame.requests) request.cancel?.(); frame.requests.clear(); frame.retries.clear(); @@ -277,6 +280,8 @@ function createGlobeRendering({ frame.offCamera?.(); frame.offCamera = null; clearTimeout(frame.timeout); + clearTimeout(frame.wake); + frame.wake = null; frame.offAbort?.(); if (ok) { lastError = null; @@ -450,8 +455,20 @@ function createGlobeRendering({ if (++settled >= 2) finish(true); else viewer.scene.requestRender(); } else settled = 0; - if (incoming === frame && frame.pending === 0 && frame.loaded > 0) - viewer.scene.requestRender(); + // Waiting out the quiet interval needs another readiness check + // later, not a render every frame: wake on a timer so the render + // governor's frame cap still holds while a frame is staged. + if ( + incoming === frame && + frame.pending === 0 && + frame.loaded > 0 && + !frame.wake + ) + frame.wake = setTimeout(() => { + frame.wake = null; + if (!frame.closed && incoming === frame) + viewer.scene.requestRender(); + }, READY_WAKE_MS); }); viewer.scene.requestRender(); onChange(); diff --git a/src/layers/weather/weather.test.mjs b/src/layers/weather/weather.test.mjs index 486d425203..a42485ed0c 100644 --- a/src/layers/weather/weather.test.mjs +++ b/src/layers/weather/weather.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { createWeatherRendering } from './rendering.js'; +import { createWeatherRendering, READY_WAKE_MS } from './rendering.js'; import { createWeatherLayer } from './index.js'; import { createWeatherClock } from './clock.js'; import * as Cesium from 'cesium'; @@ -242,6 +242,50 @@ test('a ready weather frame does not wait for unrelated terrain, but requires su h.rendering.clear(); }); +test('a staged frame waiting out its quiet interval wakes on a timer, not every render', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + let now = 0; + const h = renderingHarness({ now: () => now }); + h.viewer.scene.globe.tilesLoaded = false; + const loaded = h.rendering.setFrame(snapshot, times[0]); + const tile = deferred(); + h.providers[0].response = tile; + const request = h.providers[0].requestImage(0, 0, 0, {}); + tile.resolve({}); + await request; + const before = h.renders(); + for (let i = 0; i < 10; i++) h.postRender.emit(); + assert.equal( + h.renders(), + before, + 'renders while waiting do not request further renders', + ); + t.mock.timers.tick(READY_WAKE_MS - 1); + assert.equal(h.renders(), before); + t.mock.timers.tick(1); + assert.equal(h.renders(), before + 1, 'one wake per interval'); + now = 200; + h.postRender.emit(); + h.postRender.emit(); + assert.equal(await loaded, true); + const settledRenders = h.renders(); + t.mock.timers.tick(READY_WAKE_MS * 4); + assert.equal(h.renders(), settledRenders, 'commit clears the wake timer'); + + const abandoned = h.rendering.setFrame(snapshot, times[1]); + const second = deferred(); + h.providers.at(-1).response = second; + const secondRequest = h.providers.at(-1).requestImage(0, 0, 0, {}); + second.resolve({}); + await secondRequest; + h.postRender.emit(); + h.rendering.clear(); + assert.equal(await abandoned, false); + const clearedRenders = h.renders(); + t.mock.timers.tick(READY_WAKE_MS * 4); + assert.equal(h.renders(), clearedRenders, 'clear cancels the wake timer'); +}); + test('camera movement drops abandoned deferred tiles but still waits for admitted requests', async () => { let now = 0; const h = renderingHarness({ now: () => now }); From a7fcb3c2322fbffdbc24b81f98b45ef9fafe8339 Mon Sep 17 00:00:00 2001 From: Jenil Patel Date: Sun, 25 Oct 2026 21:13:38 -0500 Subject: [PATCH 53/54] fix(maps): avoid 404 on keyless Google tiles-token probe (#1066) Return an uncached unavailable-token response for keyless Google tile-token requests. Contribution by @dvilrgamerz. --- changelog.d/1066-keyless-google-token.md | 3 + docs/CURRENT-STATE.md | 6 ++ server/standalone/google-token-unavailable.js | 27 ++++++ server/standalone/vite.config.js | 2 + src/maps/googleTokens.js | 1 + src/maps/googleTokens.test.mjs | 9 ++ src/tooling/googleTokenUnavailable.test.mjs | 94 +++++++++++++++++++ src/tooling/viteBuild.test.mjs | 9 +- 8 files changed, 147 insertions(+), 4 deletions(-) create mode 100644 changelog.d/1066-keyless-google-token.md create mode 100644 server/standalone/google-token-unavailable.js create mode 100644 src/tooling/googleTokenUnavailable.test.mjs diff --git a/changelog.d/1066-keyless-google-token.md b/changelog.d/1066-keyless-google-token.md new file mode 100644 index 0000000000..c07cbade89 --- /dev/null +++ b/changelog.d/1066-keyless-google-token.md @@ -0,0 +1,3 @@ +- Keyless standalone startup answers an unavailable Google tile-token endpoint + with uncached 204 instead of a browser-visible 404. Existing providers take + precedence, and unrelated API routes behave as before. (dvilrgamerz, #1066) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 4b9e306ea9..0ace86811c 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1853,6 +1853,12 @@ supported. `.env.example` and `pinokio/_ENVIRONMENT` document both entries. The Street View headings tool uses the same server-first selection after resolving environment overrides per variable; its explicit `--key` wins. +In standalone development and preview servers, a missing Google tile-token +provider returns an uncached `204 No Content` for `GET /api/google/tiles-token` +(and HEAD) instead of a browser-visible 404. The fallback is registered after +real token providers and before the unknown-API handler, so existing Google +browser keys, provider-issued tokens, and unrelated API routes remain unchanged. + ## Infrastructure marker visibility Datacenter/dam registration uses fresh reusable factories with the application's diff --git a/server/standalone/google-token-unavailable.js b/server/standalone/google-token-unavailable.js new file mode 100644 index 0000000000..6089b59412 --- /dev/null +++ b/server/standalone/google-token-unavailable.js @@ -0,0 +1,27 @@ +/** + * Treat an unavailable Google Maps tile-token endpoint as a supported, silent + * outcome. Install after real token providers and before the unknown-API 404. + */ +export function googleTokenUnavailablePlugin() { + const install = (server) => { + server.middlewares.use((req, res, next) => { + const pathname = String(req.url || '').split('?')[0]; + if ( + (req.method !== 'GET' && req.method !== 'HEAD') || + pathname !== '/api/google/tiles-token' + ) { + next(); + return; + } + + res.writeHead(204, { 'Cache-Control': 'no-store' }); + res.end(); + }); + }; + + return { + name: 'google-token-unavailable', + configureServer: install, + configurePreviewServer: install, + }; +} diff --git a/server/standalone/vite.config.js b/server/standalone/vite.config.js index ffe5124cec..f095ec2ac7 100644 --- a/server/standalone/vite.config.js +++ b/server/standalone/vite.config.js @@ -5,6 +5,7 @@ import { createBrowserViteConfig } from '../../build/vite.js'; import { localProviderPlugins } from '../providers/local.js'; import { localMcpPlugin } from '../mcp/plugin.js'; import { apiNotFoundPlugin } from './api-not-found.js'; +import { googleTokenUnavailablePlugin } from './google-token-unavailable.js'; import { standaloneVoiceTools } from './voiceTools.js'; import { unwatchedRuntimeDirsPlugin } from './unwatched-cache.js'; @@ -21,6 +22,7 @@ export default defineConfig(({ command, mode }) => { plugins: [ ...localProviderPlugins({ realtime: { tools }, gemini: { tools } }), localMcpPlugin(), + googleTokenUnavailablePlugin(), apiNotFoundPlugin(), unwatchedRuntimeDirsPlugin(), ], diff --git a/src/maps/googleTokens.js b/src/maps/googleTokens.js index 884c5b1995..089730139d 100644 --- a/src/maps/googleTokens.js +++ b/src/maps/googleTokens.js @@ -38,6 +38,7 @@ export function createGoogleTokenSource({ headers: { Accept: 'application/json' }, cache: 'no-store', }); + if (response.status === 204) return null; if (!response.ok) { await response.body?.cancel(); return null; diff --git a/src/maps/googleTokens.test.mjs b/src/maps/googleTokens.test.mjs index d8a1e84eda..10213db0c5 100644 --- a/src/maps/googleTokens.test.mjs +++ b/src/maps/googleTokens.test.mjs @@ -79,3 +79,12 @@ test('a server that does not offer tokens yields none', async () => { assert.equal(await createGoogleTokenSource({ fetchImpl }).token(), null); } }); + +test('an empty 204 response explicitly means no Google token is available', async () => { + const { calls, fetchImpl } = server([ + new Response(null, { status: 204, headers: { 'Cache-Control': 'no-store' } }), + ]); + const tokens = createGoogleTokenSource({ fetchImpl }); + assert.equal(await tokens.token(), null); + assert.deepEqual(calls, [GOOGLE_TOKEN_PATH]); +}); diff --git a/src/tooling/googleTokenUnavailable.test.mjs b/src/tooling/googleTokenUnavailable.test.mjs new file mode 100644 index 0000000000..e0ee192329 --- /dev/null +++ b/src/tooling/googleTokenUnavailable.test.mjs @@ -0,0 +1,94 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { once } from 'node:events'; +import { createGoogleTokenSource } from '../maps/googleTokens.js'; +import { googleTokenUnavailablePlugin } from '../../server/standalone/google-token-unavailable.js'; + +async function withServer({ beforeFallback } = {}, check) { + const middlewares = []; + const app = { + middlewares: { + use: (handler) => middlewares.push(handler), + }, + }; + if (beforeFallback) app.middlewares.use(beforeFallback); + googleTokenUnavailablePlugin().configureServer(app); + app.middlewares.use((_req, res) => { + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Unknown API route' })); + }); + + const server = createServer((req, res) => { + let index = 0; + const next = () => middlewares[index++]?.(req, res, next); + next(); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const address = server.address(); + const url = 'http://127.0.0.1:' + address.port; + try { + await check(url); + } finally { + server.close(); + await once(server, 'close'); + } +} + +test('keyless GET and HEAD return uncached 204 instead of 404', async () => { + await withServer({}, async (url) => { + for (const method of ['GET', 'HEAD']) { + const response = await fetch(url + '/api/google/tiles-token?probe=1', { + method, + }); + assert.equal(response.status, 204); + assert.equal(response.headers.get('cache-control'), 'no-store'); + assert.equal(await response.text(), ''); + } + }); +}); + +test('the existing client treats unavailable tokens as null', async () => { + await withServer({}, async (url) => { + const source = createGoogleTokenSource({ + fetchImpl: (path, options) => fetch(new URL(path, url), options), + }); + assert.equal(await source.token(), null); + }); +}); + +test('unrelated API paths and unsupported methods remain 404', async () => { + await withServer({}, async (url) => { + for (const [path, method] of [ + ['/api/google/tiles-token/extra', 'GET'], + ['/api/not-a-token', 'GET'], + ['/api/google/tiles-token', 'POST'], + ]) { + const response = await fetch(new URL(path, url), { method }); + assert.equal(response.status, 404); + } + }); +}); + +test('a real token provider registered first still wins', async () => { + await withServer( + { + beforeFallback: (req, res, next) => { + if (req.url !== '/api/google/tiles-token') return next(); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + accessToken: 'server-token', + expiresAt: 10000000000000, + }), + ); + }, + }, + async (url) => { + const response = await fetch(url + '/api/google/tiles-token'); + assert.equal(response.status, 200); + assert.equal((await response.json()).accessToken, 'server-token'); + }, + ); +}); diff --git a/src/tooling/viteBuild.test.mjs b/src/tooling/viteBuild.test.mjs index 2a4988e30a..a9e8c53989 100644 --- a/src/tooling/viteBuild.test.mjs +++ b/src/tooling/viteBuild.test.mjs @@ -117,7 +117,7 @@ test('root config retains existing named exports and standalone provider order', assert.equal(compatibility[name], value, name); const config = standaloneConfig({ mode: 'test' }); const standaloneProviders = config.plugins - .slice(4, -5) + .slice(4, -6) .map((plugin) => plugin.name); assert.equal( standaloneProviders.filter((name) => name === 'gemini-live-proxy').length, @@ -131,9 +131,10 @@ test('root config retains existing named exports and standalone provider order', standaloneProviders.filter((name) => name !== 'gemini-live-proxy'), providers.localProviderPlugins().map((plugin) => plugin.name), ); - assert.equal(config.plugins.at(-6).name, 'gev-key-setup'); - // The local MCP route follows every provider and precedes the API fallback. - assert.equal(config.plugins.at(-5).name, 'local-mcp'); + assert.equal(config.plugins.at(-7).name, 'gev-key-setup'); + // Token fallback follows real providers and local MCP before the API 404. + assert.equal(config.plugins.at(-6).name, 'local-mcp'); + assert.equal(config.plugins.at(-5).name, 'google-token-unavailable'); assert.equal(config.plugins.at(-4).name, 'api-not-found'); // Config-only, so it sits after the provider slice rather than in it. assert.equal(config.plugins.at(-3).name, 'gev-unwatched-runtime-dirs'); From a3a19883b4f9ebb879040e2a6969c689355c3008 Mon Sep 17 00:00:00 2001 From: Bilawal Sidhu <106619546+bilawalsidhu@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:24:27 -0500 Subject: [PATCH 54/54] feat: add Scope controls and conditional HUD text backplates (#1410) * feat: add scope controls and conditional HUD backplates * docs: assign scope changelog to PR 1410 * fix: stabilize title backplate and brighten secondary labels --------- Co-authored-by: Bilawal Sidhu --- .../1410-scope-controls-hud-readability.md | 8 + docs/CURRENT-STATE.md | 36 +- scripts/format-scope.json | 1 + scripts/package-boundaries.json | 10 +- scripts/qa-scope-hud.mjs | 681 ++++++++++++++++++ src/hud.js | 42 +- src/reasonableDefaults.test.mjs | 49 +- src/scopeMask.js | 46 +- src/scopeMask.test.mjs | 55 +- src/scopeMaskPolicy.js | 11 + src/sharelink.celestial.test.mjs | 20 +- src/sharelink.js | 16 +- src/ui/aircraftDisplay.js | 1 - src/ui/cyberTheme.test.mjs | 30 + src/ui/displayBindings.js | 20 +- src/ui/displayControls.js | 8 +- src/ui/displayControls.test.mjs | 26 + src/ui/frameRateMonitor.js | 2 +- src/ui/styles/command-dock-trays.css | 6 + src/ui/styles/controls.css | 21 + src/ui/styles/overlays.css | 131 ++++ src/ui/templates/display-controls.html | 14 +- src/ui/templates/scene-chrome.html | 6 +- src/ui/visualSettings.js | 16 +- 24 files changed, 1134 insertions(+), 122 deletions(-) create mode 100644 changelog.d/1410-scope-controls-hud-readability.md create mode 100644 scripts/qa-scope-hud.mjs create mode 100644 src/scopeMaskPolicy.js diff --git a/changelog.d/1410-scope-controls-hud-readability.md b/changelog.d/1410-scope-controls-hud-readability.md new file mode 100644 index 0000000000..38cfdf48e7 --- /dev/null +++ b/changelog.d/1410-scope-controls-hud-readability.md @@ -0,0 +1,8 @@ +- Add a Scope checkbox and extend feathering to 200%, retaining scope settings + across HUD layouts, share links and scenes. First run opens with Scope ON at + 100% feather; explicit settings and historical links retain their values. Give + Tactical, Operator and Minimal text black backplates only when Scope is OFF, + including vertical metadata, without changing the original HUD text color, glow or + opacity. Scope ON retains its original HUD presentation (bilawalsidhu, #1410). + Keep title and tagline positions stable when toggling Scope, include the eye + in the title backing, and brighten the two secondary labels only with Scope OFF. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 0ace86811c..b4ed2bacba 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -196,6 +196,23 @@ Regression coverage lives in `src/tools/area.test.mjs`, `src/tools/queries/environment.test.mjs` and `src/layers/perimeters/cards.test.mjs`. +## Scope display controls + +Display's native Scope checkbox defaults ON with feather at 100%, adjustable +from 0–200%. OFF disables the slider while retaining its value. HUD layout +changes preserve both settings; share links and scenes restore them. The +historical missing-`scf` fallback remains 35%; explicit 0% keeps the hard edge. + +With Scope OFF, Tactical, Operator and Minimal add text-sized black backplates +at 70% opacity behind telemetry, vertical metadata and scene chrome. Original +HUD text color, glow and opacity are preserved. Scope OFF brightens the tagline +and Active Style label with the shared secondary text color. The title plate +covers the eye and title without moving the title or tagline. Scope ON retains +the original HUD presentation; Cyber retains its existing skin. + +`node scripts/qa-scope-hud.mjs` checks native input, range, layout persistence, +restoration and both Scope presentations. `QA_SCREENSHOT_DIR` saves screenshots. + ## Cyber HUD — September 30, 2026 Display > HUD > Layout includes Cyber, also available through the HUD voice @@ -5545,10 +5562,11 @@ the `_detectionUserOverridden` / explicit-intent flags that would suppress a separate landed behaviour. Pinned in `src/reasonableDefaults.test.mjs` (feather, detection, OUTSIDE opacity) and `src/data/layerState.test.mjs` (3D). -**The 2026-08-24 defaults** (superseding the interim 08-23 values of 8%/3%): +**Current defaults** (scope feather revised to 100% on 2026-10-25; +detection and outside opacity retain the 2026-08-24 defaults): the first-run look is Detection DENSE -`75%`, ELASTIC allocation, Fade `7%`, OUTSIDE opacity `1%`, scope feather `11%`, -and 3D fleet mode PROXIMITY, with `AIRCRAFT_BRACKET_FLOOR_ANCHOR` at `0.01` so +`75%`, ELASTIC allocation, Fade `7%`, OUTSIDE opacity `1%`, Scope ON with feather +`100%`, and 3D fleet mode PROXIMITY, with `AIRCRAFT_BRACKET_FLOOR_ANCHOR` at `0.01` so brackets keep their approved brightness exactly at the new OUTSIDE default. Two terms that must never be conflated: scope FEATHER softens the black scope-mask edge; detection FADE is the label/card fading band around the keyhole. The @@ -5618,14 +5636,10 @@ easier to meet (detection is now on more often), but does not create it. calibrated so `AIRCRAFT_BRACKET_ALPHA_FLOOR` (0.35) lands exactly at the default, and the mapping follows bracket brightness rather than slider position. The `ko` PARSE fallback stays at `5`. -- **Scope feather: `11%`** — a soft scope-mask edge (moved `0% → 8% → 11%`; `0%` hard crop for one day, - `35%` before that). `SCOPE_FEATHER_RATIO_DEFAULT` in `src/scopeMask.js`, - mirrored by `#scope-feather-slider`'s markup value AND readout and - `_scopeFeatherPct` in `sharelink.js`. The slider is untouched and still spans - 0–100, and an explicit `0` is still the hard-crop path — pinned, so moving the - default cannot quietly delete it. The `scf` PARSE fallback deliberately stays - at `35`: a link predating `scf` was authored when 35 was what its author saw, - and restoring the author's view is what a share link is for. +- **Scope: `ON`, feather: `100%`**. `SCOPE_FEATHER_RATIO_DEFAULT` in + `src/scopeMask.js` matches the slider, readout and share generator. The range + is 0–200%; explicit 0% is a hard edge. Missing-`scf` links retain the historical + 35% parse fallback. - **3D aircraft models: `ON`, mode `proximity`** — see the 3D Aircraft section above and the DISPLAY-rail entry below (was `OFF`). - Style shader starting params: CRT/NVG/FLIR pixelation `1.2` (just above the native `1.0` floor); thermal/FLIR ships an optional Ironbow "Predator" palette (`palette` uniform, default `0` = accurate grayscale). diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 20e28122a6..e60413624c 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -194,6 +194,7 @@ "src/ui/visualInput.js", "src/ui/visualInput.test.mjs", "scripts/qa-visual-input.mjs", + "scripts/qa-scope-hud.mjs", "scripts/qa-segmented-controls.mjs", "src/ui/displayControls.js", "src/ui/segmentedControl.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 89589091ad..d158971757 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -805,7 +805,8 @@ "src/ui/keyGuidance.js", "src/ui/layerNames.js", "src/ui/statusText.js", - "src/ui/statusBadge.js" + "src/ui/statusBadge.js", + "src/scopeMaskPolicy.js" ], "external": ["cesium"] }, @@ -2574,7 +2575,8 @@ "src/voice/geminiAudio.js", "src/voice/geminiCaptureWorklet.js", "src/ui/statusBadge.js", - "src/sceneCommandRelease.js" + "src/sceneCommandRelease.js", + "src/scopeMaskPolicy.js" ], "external": [ "hls.js", @@ -3295,7 +3297,9 @@ "src/i18n/locale.js", "src/i18n/locales/es.json", "src/i18n/locales/ru.json", - "src/i18n/locales/zh-CN.json" + "src/i18n/locales/zh-CN.json", + "src/scopeMaskPolicy.js", + "src/ui/displayControls.js" ], "external": ["cesium"] }, diff --git a/scripts/qa-scope-hud.mjs b/scripts/qa-scope-hud.mjs new file mode 100644 index 0000000000..7fece45eea --- /dev/null +++ b/scripts/qa-scope-hud.mjs @@ -0,0 +1,681 @@ +#!/usr/bin/env node +/** + * Scope and HUD browser acceptance. Requires the development server. + * Run: node scripts/qa-scope-hud.mjs + * Optional: QA_BASE_URL, QA_SCREENSHOT_DIR (screenshots stay outside the repo). + * Proves a fresh boot defaults to Scope ON at 100%, native checkbox click/Space, + * feather 0/11/100/200, layout independence, + * share/scene restore, and visible text backing including rotated metadata. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; + +const browser = await puppeteer.launch({ + headless: true, + args: [ + '--no-sandbox', + ...(process.platform === 'darwin' + ? ['--use-angle=metal', '--enable-gpu'] + : ['--use-gl=angle', '--use-angle=swiftshader']), + ], +}); +const page = await browser.newPage(); +const errors = []; +page.on('pageerror', (error) => errors.push(error.message)); +let failures = 0; +const check = (name, passed, detail) => { + console.log(`[${passed ? 'PASS' : 'FAIL'}] ${name}`); + if (!passed) { + failures += 1; + if (detail) console.log(JSON.stringify(detail)); + } +}; +const readScope = () => + page.evaluate(() => { + const scope = window.__godsEyeView.styleManager.getVisualState().scope; + const canvas = document.getElementById('scope-mask'); + const context = canvas.getContext('2d'); + const radialX = Math.round( + canvas.width / 2 + Math.min(canvas.width, canvas.height) * 0.35, + ); + return { + enabled: scope.enabled, + feather: scope.featherPct / 100, + cornerAlpha: context.getImageData(1, 1, 1, 1).data[3], + radialAlpha: context.getImageData( + radialX, + Math.round(canvas.height / 2), + 1, + 1, + ).data[3], + checked: document.getElementById('scope-toggle').checked, + disabled: document.getElementById('scope-feather-slider').disabled, + value: Number(document.getElementById('scope-feather-slider').value), + readout: document.getElementById('scope-feather-value').textContent, + }; + }); + +const readHudGlyphs = () => + page.evaluate(() => { + const hud = document.getElementById('intel-hud'); + const probe = document.createElement('span'); + probe.style.display = 'none'; + hud.appendChild(probe); + const baseline = { + color: getComputedStyle(probe).color, + shadow: getComputedStyle(probe).textShadow, + }; + probe.remove(); + const glyphs = [ + '.hud-mode', + '.hud-system', + '.hud-summary-label', + '.hud-summary', + '.hud-orbital', + '#hud-mgrs', + '#hud-coll', + ].map((selector) => { + const el = hud.querySelector(selector); + const style = getComputedStyle(el); + let opacity = 1; + for ( + let current = el; + current && current !== hud; + current = current.parentElement + ) + opacity *= Number(getComputedStyle(current).opacity); + return { + selector, + color: style.color, + shadow: style.textShadow, + opacity, + }; + }); + return { baseline, glyphs }; + }); + +async function settleTextBackings(enabled) { + // The pre-existing active-style value transitions all properties for 300ms. + // Wait for its backing to finish changing before inspecting or capturing it. + await page + .waitForFunction( + (scopeEnabled) => { + const expected = scopeEnabled + ? 'rgba(0, 0, 0, 0)' + : 'rgba(0, 0, 0, 0.7)'; + return [ + ...document.querySelectorAll( + '#intel-hud .hud-readout, .scene-text-holdout', + ), + ].every( + (el) => + getComputedStyle(el).backgroundColor === expected && + getComputedStyle(el).boxShadow === 'none', + ); + }, + { timeout: 2_000 }, + enabled, + ) + .catch(() => null); +} + +const readSceneChrome = () => + page.evaluate(() => { + const title = document.querySelector('#title-bar h1'); + const eye = title.querySelector('.title-logo'); + const subtitle = document.querySelector('#title-bar .subtitle'); + const label = document.querySelector('#style-indicator .indicator-label'); + const rect = (el, text = false) => { + if (!el.getClientRects().length) return null; + const range = document.createRange(); + range.selectNodeContents(el); + const box = text + ? range.getBoundingClientRect() + : el.getBoundingClientRect(); + return { + left: box.left, + top: box.top, + right: box.right, + bottom: box.bottom, + }; + }; + const titleBox = rect(title); + const eyeBox = rect(eye); + const backing = getComputedStyle(title, '::before'); + const plate = { + left: titleBox.left + parseFloat(backing.left), + top: titleBox.top + parseFloat(backing.top), + right: titleBox.right - parseFloat(backing.right), + bottom: titleBox.bottom - parseFloat(backing.bottom), + }; + const contains = (box) => + Object.entries(box).every(([side, value]) => + ['left', 'top'].includes(side) + ? plate[side] <= value + 0.5 + : plate[side] >= value - 0.5, + ); + const probe = document.createElement('span'); + document.body.appendChild(probe); + probe.style.color = 'var(--text-dim)'; + const dim = getComputedStyle(probe).color; + probe.style.color = 'var(--text-secondary)'; + const secondary = getComputedStyle(probe).color; + probe.remove(); + return { + positions: { + title: titleBox, + eye: eyeBox, + text: rect(title.querySelector('[translate="no"]'), true), + subtitle: rect(subtitle, true), + }, + titleUnbacked: backing.backgroundColor === 'rgba(0, 0, 0, 0)', + titleCovered: + backing.position === 'absolute' && + backing.backgroundColor === 'rgba(0, 0, 0, 0.7)' && + contains(titleBox) && + contains(eyeBox), + leftAligned: + !rect(subtitle) || Math.abs(plate.left - rect(subtitle).left) <= 0.5, + colors: [getComputedStyle(subtitle).color, getComputedStyle(label).color], + dim, + secondary, + }; + }); + +function checkSceneChrome(name, before, after) { + const stable = Object.keys(before.positions).every((key) => { + const a = before.positions[key]; + const b = after.positions[key]; + return a && b + ? Object.keys(a).every((side) => Math.abs(a[side] - b[side]) <= 0.5) + : a === b; + }); + check(`${name}: title, eye and subtitle stay in place across Scope`, stable, { + before, + after, + }); + check( + `${name}: OFF title plate covers the eye and aligns with the subtitle`, + before.titleUnbacked && after.titleCovered && after.leftAligned, + after, + ); + check( + `${name}: secondary labels brighten only with Scope OFF`, + before.colors.every((color) => color === before.dim) && + after.colors.every((color) => color === after.secondary), + { before: before.colors, after: after.colors }, + ); +} + +async function openApplication(url) { + await page.goto(url.href, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction( + () => window.__godsEyeView?.styleManager?._applicationShortcuts, + { timeout: 60_000 }, + ); + await page.waitForFunction( + () => { + const cover = document.getElementById('loading-screen'); + return ( + cover?.classList.contains('hidden') && + Number(getComputedStyle(cover).opacity) === 0 + ); + }, + { timeout: 60_000 }, + ); +} + +try { + await page.setViewport({ width: 1440, height: 900 }); + const url = new URL(process.env.QA_BASE_URL || 'http://127.0.0.1:4173'); + url.searchParams.set('welcome', '0'); + // This browser has a fresh profile. Start without authored state so the + // first assertion exercises the defaults rather than a share-link restore. + url.hash = ''; + await openApplication(url); + const fresh = await readScope(); + check( + 'bare-URL fresh boot opens Scope ON with 100% feather', + fresh.enabled && + fresh.checked && + !fresh.disabled && + fresh.feather === 1 && + fresh.value === 100 && + fresh.readout === '100%' && + fresh.cornerAlpha > 0, + fresh, + ); + + // Use a known city view for canvas and readability checks below. + url.hash = + 'v=2&lat=30.2672&lon=-97.7431&alt=2500&heading=0&pitch=-45&roll=0&map=esri&sc=1&scf=100&l='; + // Changing only the hash does not rerun startup restoration. Leave the app + // document first so this fixture is applied by a new application boot. + await page.goto('about:blank'); + await openApplication(url); + await page.evaluate(() => { + const manager = window.__godsEyeView.styleManager; + manager.setPanelCollapsed('pp-toggles', false, { + persist: false, + syncShare: false, + }); + manager.hud.setMode('on'); + manager.setStyle('normal'); + }); + const initial = await readScope(); + check( + 'Austin fixture restores Scope ON and 100% feather', + initial.enabled && + initial.checked && + !initial.disabled && + initial.feather === 1 && + initial.value === 100 && + initial.readout === '100%' && + initial.cornerAlpha > 0, + initial, + ); + const name = await page.$eval('#scope-toggle', (el) => ({ + type: el.type, + label: el.labels?.[0]?.textContent.trim(), + })); + check( + 'Scope uses a native checkbox with a visible label', + name.type === 'checkbox' && name.label?.includes('Scope'), + name, + ); + await page.click('#scope-toggle'); + const off = await readScope(); + check( + 'click disables Scope and its feather slider', + !off.enabled && + !off.checked && + off.disabled && + off.feather === 1 && + off.cornerAlpha === 0, + off, + ); + await page.focus('#scope-toggle'); + await page.keyboard.press('Space'); + const on = await readScope(); + check( + 'Space re-enables the native checkbox without losing feather', + on.enabled && + on.checked && + !on.disabled && + on.feather === 1 && + on.cornerAlpha > 0, + on, + ); + + const paintedAlpha = []; + for (const pct of [0, 11, 100, 200]) { + await page.$eval( + '#scope-feather-slider', + (el, value) => { + el.value = String(value); + el.dispatchEvent(new Event('input', { bubbles: true })); + }, + pct, + ); + const state = await readScope(); + paintedAlpha.push(state.radialAlpha); + check( + `feather ${pct}% reaches the mask and readout`, + state.value === pct && + state.feather === pct / 100 && + state.readout === `${pct}%`, + state, + ); + } + check( + 'painted gradient widens beyond the old 100% ceiling', + paintedAlpha[0] === 0 && + paintedAlpha[1] === 0 && + paintedAlpha[2] > 0 && + paintedAlpha[3] > paintedAlpha[2], + paintedAlpha, + ); + await page.focus('#scope-feather-slider'); + await page.keyboard.press('Home'); + check('native Home reaches the hard edge', (await readScope()).feather === 0); + await page.keyboard.press('End'); + check( + 'native End reaches the expanded 200% maximum', + (await readScope()).feather === 2, + ); + await page.click('#scope-toggle'); + for (const layout of ['minimal', 'operator', 'cyber', 'tactical']) { + await page.select('#hud-layout-select', layout); + const state = await readScope(); + check( + `Scope OFF and 200% survive ${layout}`, + !state.enabled && + !state.checked && + state.disabled && + state.feather === 2 && + state.value === 200 && + state.cornerAlpha === 0, + state, + ); + } + + const restored = await page.evaluate(async () => { + const manager = window.__godsEyeView.styleManager; + const links = manager.shareLinkManager; + manager._syncShareState(); + const params = links._buildHashParams(); + const encoded = { enabled: params.get('sc'), feather: params.get('scf') }; + await manager.applyVisualState({ scope: { enabled: true, featherPct: 0 } }); + await manager._visualSettings.restoreShareState({ + scopeEnabled: encoded.enabled === '1', + scopeFeatherPct: Number(encoded.feather), + }); + const shared = manager.getVisualState().scope; + await manager.applyVisualState({ + scope: { enabled: true, featherPct: 200 }, + }); + const scene = manager.getVisualState().scope; + await manager.applyVisualState({ + scope: { enabled: false, featherPct: 200 }, + }); + return { encoded, shared, scene }; + }); + check( + 'share state serializes and restores Scope OFF with 200%', + restored.encoded.enabled === '0' && + restored.encoded.feather === '200' && + restored.shared.enabled === false && + restored.shared.featherPct === 200, + restored, + ); + check( + 'scene state restores Scope ON with 200%', + restored.scene.enabled === true && restored.scene.featherPct === 200, + restored, + ); + + for (const layout of ['minimal', 'operator', 'tactical']) { + await page.select('#hud-layout-select', layout); + await page.evaluate(() => + window.__godsEyeView.styleManager.applyVisualState({ + scope: { enabled: true, featherPct: 100 }, + }), + ); + await settleTextBackings(true); + const originalGlyphs = await readHudGlyphs(); + const originalChrome = await readSceneChrome(); + const original = await page.evaluate(() => { + const hud = document.getElementById('intel-hud'); + const wrappers = [...hud.querySelectorAll('.hud-readout')]; + const scene = [...document.querySelectorAll('.scene-text-holdout')]; + const unexpectedBackings = [...wrappers, ...scene] + .map((el) => { + const style = getComputedStyle(el); + return { + selector: el.id || el.className, + background: style.backgroundColor, + shadow: style.boxShadow, + }; + }) + .filter( + (style) => + style.background !== 'rgba(0, 0, 0, 0)' || style.shadow !== 'none', + ); + return { + markerAbsent: !document.documentElement.hasAttribute('data-scope-mask'), + unbacked: unexpectedBackings.length === 0, + unexpectedBackings, + wrappersTransparent: wrappers.every( + (el) => getComputedStyle(el).display === 'contents', + ), + operatorFrame: + hud.dataset.variant !== 'operator' || + (getComputedStyle(hud.querySelector('.hud-corner')) + .backgroundColor === 'rgba(0, 0, 0, 0.36)' && + getComputedStyle(hud.querySelector('.hud-top-bar')) + .backgroundImage !== 'none'), + }; + }); + check( + `${layout}: Scope ON retains the original presentation without new backplates`, + original.markerAbsent && + original.unbacked && + original.wrappersTransparent && + original.operatorFrame, + original, + ); + check( + `${layout}: original HUD color, glow and metadata alpha remain intact`, + originalGlyphs.glyphs.every( + (glyph) => + glyph.color === originalGlyphs.baseline.color && + glyph.shadow === originalGlyphs.baseline.shadow, + ) && + originalGlyphs.glyphs.find( + (glyph) => glyph.selector === '.hud-summary-label', + ).opacity === 0.55 && + originalGlyphs.glyphs.find((glyph) => glyph.selector === '.hud-orbital') + .opacity === 0.7 && + originalGlyphs.glyphs.find((glyph) => glyph.selector === '#hud-coll') + .opacity === 0.5, + originalGlyphs, + ); + if (process.env.QA_SCREENSHOT_DIR) { + fs.mkdirSync(process.env.QA_SCREENSHOT_DIR, { recursive: true }); + await page.screenshot({ + path: path.join( + process.env.QA_SCREENSHOT_DIR, + `scope-on-${layout}.png`, + ), + }); + } + await page.evaluate(() => + window.__godsEyeView.styleManager.applyVisualState({ + scope: { enabled: false }, + }), + ); + await settleTextBackings(false); + const backedGlyphs = await readHudGlyphs(); + checkSceneChrome(layout, originalChrome, await readSceneChrome()); + check( + `${layout}: Scope OFF adds backing without changing glyph styles`, + JSON.stringify(backedGlyphs) === JSON.stringify(originalGlyphs), + backedGlyphs, + ); + const coverage = await page.evaluate(() => { + const hud = document.getElementById('intel-hud'); + const walker = document.createTreeWalker(hud, NodeFilter.SHOW_TEXT); + const missing = []; + let visible = 0; + let node; + while ((node = walker.nextNode())) { + if ( + !node.textContent.trim() || + node.parentElement.closest('.hud-bracket') + ) + continue; + const range = document.createRange(); + range.selectNodeContents(node); + if ( + ![...range.getClientRects()].some( + (rect) => rect.width > 0 && rect.height > 0, + ) + ) + continue; + visible += 1; + const backing = node.parentElement.closest('.hud-readout'); + const color = backing && getComputedStyle(backing).backgroundColor; + if ( + !backing || + color !== 'rgba(0, 0, 0, 0.7)' || + getComputedStyle(backing).boxShadow !== 'none' || + backing.parentElement.closest('.hud-readout') + ) + missing.push(node.textContent.trim()); + } + const wrapped = [...hud.querySelectorAll('.hud-readout')].filter( + (el) => el.offsetWidth > 0 && el.offsetHeight > 0, + ); + const empty = wrapped.filter((el) => !el.innerText.trim()).length; + const overlaps = []; + for (const parent of new Set(wrapped.map((el) => el.parentElement))) { + const siblings = wrapped.filter((el) => el.parentElement === parent); + for (let i = 1; i < siblings.length; i += 1) { + const previous = siblings[i - 1].getBoundingClientRect(); + const current = siblings[i].getBoundingClientRect(); + const horizontal = + Math.min(previous.right, current.right) - + Math.max(previous.left, current.left); + const vertical = + Math.min(previous.bottom, current.bottom) - + Math.max(previous.top, current.top); + // Horizontal bars share a vertical band. Only intersecting text boxes + // can stack their backing alpha; allow subpixel layout rounding. + if (horizontal > 0.5 && vertical > 0.5) { + overlaps.push({ + parent: parent.className, + previous: siblings[i - 1].innerText, + current: siblings[i].innerText, + vertical, + }); + } + } + } + const lineIds = [ + 'hud-mgrs', + 'hud-latlon', + 'hud-gsd', + 'hud-alt', + 'hud-timestamp', + 'hud-bottom-line', + ]; + const multiline = lineIds.filter((id) => { + const el = document.getElementById(id); + if (!el.getClientRects().length) return false; + const range = document.createRange(); + range.selectNodeContents(el); + return ( + range.getBoundingClientRect().height > + parseFloat(getComputedStyle(el).lineHeight) * 1.5 + ); + }); + const edges = [...hud.querySelectorAll('.hud-edge')] + .filter((el) => getComputedStyle(el).display !== 'none') + .map((el) => { + const box = el.querySelector('.hud-readout').getBoundingClientRect(); + return ( + getComputedStyle(el).transform !== 'none' && + box.height > box.width && + Number(getComputedStyle(el).opacity) === 1 + ); + }); + const broadBackings = [ + ...hud.querySelectorAll('.hud-corner, .hud-top-bar, .hud-bottom-bar'), + ].filter( + (el) => + el.offsetWidth > 0 && + getComputedStyle(el).backgroundColor !== 'rgba(0, 0, 0, 0)', + ); + return { + scopeOff: document.documentElement.dataset.scopeMask === 'off', + visible, + missing, + empty, + overlaps, + multiline, + edges, + broadBackings: broadBackings.length, + }; + }); + check( + `${layout}: all visible HUD text has one backing`, + coverage.scopeOff && + coverage.visible > 0 && + coverage.missing.length === 0 && + coverage.empty === 0 && + coverage.broadBackings === 0, + coverage, + ); + check( + `${layout}: adjacent readout backings do not overlap`, + coverage.overlaps.length === 0, + coverage, + ); + check( + `${layout}: desktop telemetry remains single line; rotated backing follows the labels`, + coverage.multiline.length === 0 && coverage.edges.every(Boolean), + coverage, + ); + if (process.env.QA_SCREENSHOT_DIR) { + fs.mkdirSync(process.env.QA_SCREENSHOT_DIR, { recursive: true }); + await page.screenshot({ + path: path.join( + process.env.QA_SCREENSHOT_DIR, + `scope-off-${layout}.png`, + ), + }); + } + } + const details = await page.evaluate(() => { + const summary = document.getElementById('hud-summary'); + summary.textContent = 'LONG TELEMETRY SUMMARY '.repeat(30); + const ais = document.getElementById('hud-ais-vessel'); + ais.textContent = 'AIS: 4 VESSELS\nLATEST OBSERVATION'; + return { + summaryClipped: + summary.scrollWidth > summary.clientWidth && + getComputedStyle(summary).textOverflow === 'ellipsis', + aisMultiline: + getComputedStyle(ais).whiteSpace === 'pre-line' && + ais.textContent.split('\n').length === 2 && + ais.getBoundingClientRect().height + 0.5 >= + parseFloat(getComputedStyle(ais).lineHeight) * 2, + recColor: getComputedStyle(document.getElementById('hud-rec-dot')).color, + }; + }); + check( + 'summary clipping, multiline AIS and red REC dot retain their behavior', + details.summaryClipped && + details.aisMultiline && + details.recColor === 'rgb(255, 51, 51)', + details, + ); + await page.setViewport({ width: 390, height: 844 }); + await page.select('#hud-layout-select', 'minimal'); + const narrow = await page.evaluate(() => + [...document.querySelectorAll('#intel-hud .hud-readout')] + .filter( + (el) => + el.getClientRects().length && + getComputedStyle(el).display !== 'contents', + ) + .every((el) => { + const box = el.getBoundingClientRect(); + return box.left >= 0 && box.right <= innerWidth; + }), + ); + check('narrow HUD text backings stay within the viewport', narrow); + for (const layout of ['minimal', 'operator', 'tactical']) { + await page.select('#hud-layout-select', layout); + await page.evaluate(() => + window.__godsEyeView.styleManager.applyVisualState({ + scope: { enabled: true }, + }), + ); + await settleTextBackings(true); + const before = await readSceneChrome(); + await page.evaluate(() => + window.__godsEyeView.styleManager.applyVisualState({ + scope: { enabled: false }, + }), + ); + await settleTextBackings(false); + checkSceneChrome(`narrow ${layout}`, before, await readSceneChrome()); + } + check('runtime has no uncaught browser errors', errors.length === 0, errors); +} finally { + await browser.close(); +} +console.log(`RESULT: ${failures} failures`); +process.exitCode = failures ? 1 : 0; diff --git a/src/hud.js b/src/hud.js index 1428f8503d..954e3ea943 100644 --- a/src/hud.js +++ b/src/hud.js @@ -282,28 +282,28 @@ export class IntelHUD {
- TOP SECRET // SI-TK // NOFORN - ${this._missionId} - PAGE 1/1 + TOP SECRET // SI-TK // NOFORN + ${this._missionId} + PAGE 1/1
┌
-
TOP SECRET // SI-TK // NOFORN
-
${this._missionId} ${this._sensorId}
-
${t(MODE_LABELS.normal)}
+
TOP SECRET // SI-TK // NOFORN
+
${this._missionId} ${this._sensorId}
+
${t(MODE_LABELS.normal)}
-
${t('SUMMARY')}
-
${t('Awaiting telemetry...')}
+
${t('SUMMARY')}
+
${t('Awaiting telemetry...')}
-
● ${t('REC')} 2026-01-01 00:00:00Z
-
ORB: ${this._orbitNum} PASS: DESC-${this._passNum}
+
● ${t('REC')} 2026-01-01 00:00:00Z
+
ORB: ${this._orbitNum} PASS: DESC-${this._passNum}
┐
@@ -311,33 +311,33 @@ export class IntelHUD {
└
-
MGRS: ---
-
--°--'--"N ---°--'--"W
+
MGRS: ---
+
--°--'--"N ---°--'--"W
-
GSD: --m NIIRS: --
-
ALT: --m SUN: --° EL
-
${t('AIS: --')}
+
GSD: --m NIIRS: --
+
ALT: --m SUN: --° EL
+
${t('AIS: --')}
┘
-
COLL: --:--:--Z
-
ONA: --°
+
COLL: --:--:--Z
+
ONA: --°
-
BAND: PAN
-
BITS: 11
-
LVL: 1A
+
BAND: PAN
+
BITS: 11
+
LVL: 1A
- LAT: -- LON: -- MGRS: --- + LAT: -- LON: -- MGRS: ---
`; this._el.dataset.variant = this._variant; diff --git a/src/reasonableDefaults.test.mjs b/src/reasonableDefaults.test.mjs index dfd951377b..766079aa4a 100644 --- a/src/reasonableDefaults.test.mjs +++ b/src/reasonableDefaults.test.mjs @@ -11,9 +11,8 @@ import { expandApplicationHtml } from '../build/application-html.js'; // actually decides fresh-boot layer state — including the early return that // makes each layer's own initializer the operative default. // 2. Scope feather. Owner: "I like to hide feather" set it to 0% on -// 2026-08-22; the owner revised that to 8% on 2026-08-23 and locked 11% -// on 2026-08-24, a soft -// edge. The hard crop is still one drag away, and that is pinned too. +// 2026-08-22; later revisions were 8%, then 11%, then 100% on +// 2026-10-25. Scope stays ON on a fresh boot. The hard crop remains available. // 3. Detection ON (Dense @ 75%) for EVERY style, Normal included. // Owner: "detect should also be on by default." // 4. Detection OUTSIDE opacity 1% (owner final lock, 2026-08-24; 3% on 08-23, 5% before), with @@ -38,6 +37,7 @@ import { AIRCRAFT_BRACKET_FLOOR_ANCHOR } from './data/detectionPolicy.js'; import { SCOPE_FEATHER_RATIO_DEFAULT, getScopeMaskFeather, + isScopeMaskEnabled, scopeMaskGeometry, setScopeMaskFeather, } from './scopeMask.js'; @@ -75,32 +75,40 @@ function managerForHash(hash) { } // --------------------------------------------------------------------------- -// 2. Scope feather — a subtle soft edge on a first run +// 2. Scope ON with 100% feather on a first run // --------------------------------------------------------------------------- -test('first run opens with a subtle scope feather, at every surface that decides it', () => { - assert.equal(SCOPE_FEATHER_RATIO_DEFAULT, 0.11, - 'owner final lock 2026-08-24, superseding the 08-22 hard-crop and 08-23 8% rulings'); - assert.equal(getScopeMaskFeather(), 0.11, +test('first run opens with Scope ON and 100% feather at every default surface', () => { + assert.equal(isScopeMaskEnabled(), true, 'the live mask starts enabled'); + assert.equal(SCOPE_FEATHER_RATIO_DEFAULT, 1, 'owner preference 2026-10-25'); + assert.equal(getScopeMaskFeather(), 1, 'and the live module starts there, not merely documents it'); // The slider and its readout are the same default rendered as markup — a // fresh boot applies no restore, so a stale value here would show one number // over a mask drawn at another. - assert.match(indexHtml, /id="scope-feather-slider"[^>]*\svalue="11"/, - 'index.html: the feather slider ships at 11'); - assert.match(indexHtml, /id="scope-feather-value"[^>]*>11%]*\svalue="100"/, + 'index.html: the feather slider ships at 100'); + assert.match(indexHtml, /id="scope-feather-value"[^>]*>100%]*\schecked\s*\/>/, + 'the native Scope checkbox starts checked'); + // The link this session generates must describe the mask this session draws, // for the window before the first _syncShareState. - assert.match(shareSource, /this\._scopeFeatherPct = 11;/, + assert.match(shareSource, /this\._scopeFeatherPct = 100;/, 'sharelink.js: the generator starts from the same value the mask starts at'); + const params = managerForHash('')._buildHashParams(); + assert.equal(params.get('sc'), '1'); + assert.equal(params.get('scf'), '100'); }); -test('an explicit feather still wins over the subtle default', () => { +test('an explicit feather still wins over the 100% default', () => { // A link is authored state. The new default governs a session that said // nothing; it must never overwrite one that said something. + assert.equal(managerForHash('#lat=10&lon=20&scf=11').parseInitialHash().scopeFeatherPct, 11, + 'links carrying the previous default preserve their authored feather'); assert.equal(managerForHash('#lat=10&lon=20&scf=35').parseInitialHash().scopeFeatherPct, 35); assert.equal(managerForHash('#lat=10&lon=20&scf=64').parseInitialHash().scopeFeatherPct, 64); assert.equal(managerForHash('#lat=10&lon=20&scf=0').parseInitialHash().scopeFeatherPct, 0, @@ -113,23 +121,28 @@ test('an explicit feather still wins over the subtle default', () => { 'a pre-scf link restores the author\'s view, not the new default'); }); -test('the subtle default did not weaken the feather control, and 0 is still reachable', () => { +test('share links preserve explicit Scope OFF and feather choices over the defaults', () => { + const shared = managerForHash('#lat=10&lon=20&sc=0&scf=11').parseInitialHash(); + assert.equal(shared.scopeEnabled, false); + assert.equal(shared.scopeFeatherPct, 11); +}); + +test('the 100% default retains the expanded feather range and hard edge', () => { // The cheap way to move a default would be to nerf the control. Prove the // slider still spans its full range and the geometry is still DERIVED from // the ratio — a check that would pass vacuously if it only ever saw one value. - assert.match(indexHtml, /id="scope-feather-slider"[^>]*\smin="0"[^>]*\smax="100"/, + assert.match(indexHtml, /id="scope-feather-slider"[^>]*\smin="0"[^>]*\smax="200"/, 'the slider still offers the whole range'); const previous = getScopeMaskFeather(); try { - for (const ratio of [0.35, 0.7, 1]) { + for (const ratio of [0.35, 0.7, 1, 1.75, 2]) { setScopeMaskFeather(ratio); const geo = scopeMaskGeometry(1200, 900); const keyholeR = 900 * 0.5 * KEYHOLE_OUTER_RADIUS; assert.ok(Math.abs((geo.outerR - geo.innerR) - keyholeR * ratio) < 1e-9, `feather ${ratio} must still widen the band to that fraction of the keyhole`); } - // The new default is a real, narrow band — not the hard crop, and nowhere - // near the retired 35 % halo. + // The first-run value draws a band derived from the same keyhole radius. setScopeMaskFeather(SCOPE_FEATHER_RATIO_DEFAULT); const soft = scopeMaskGeometry(1200, 900); const keyholeR = 900 * 0.5 * KEYHOLE_OUTER_RADIUS; diff --git a/src/scopeMask.js b/src/scopeMask.js index 775a257f75..c431083776 100644 --- a/src/scopeMask.js +++ b/src/scopeMask.js @@ -1,4 +1,5 @@ import { getKeyholeGeometry } from './celestialRing.js'; +import { SCOPE_FEATHER_RATIO_MAX } from './scopeMaskPolicy.js'; /** * Scope mask — the app's signature circular viewport treatment, made real. @@ -41,25 +42,10 @@ import { getKeyholeGeometry } from './celestialRing.js'; /** Matches the page background the emergent scope faded into. */ const SCOPE_OUTSIDE_COLOR = { r: 5, g: 5, b: 8 }; /** - * Default edge feather as a fraction of the keyhole radius. - * - * 0.11 since 2026-08-24 (owner final lock; 0.08 on 08-23, hard-crop 0 on - * 08-22 — this supersedes both), REVISING the 2026-08-22 ruling that - * set it to zero: a subtle soft edge rather than either the hard crop or the - * retired 35 % halo. The slider is untouched and still spans 0..100; this is - * only where it STARTS. `setScopeMaskFeather` is unchanged, so any feather a - * share link carries, or the operator dials in, overrides this immediately, and - * the hard-crop path at 0 is still reachable from the handle. - * - * Keep in lockstep with `#scope-feather-slider`'s markup value AND readout in - * index.html and `_scopeFeatherPct` in sharelink.js — a fresh boot applies no - * restore, so those literals ARE the first-run state. NOT the `scf` PARSE - * fallback, which stays at 35 on purpose: a link predating that field was - * authored when 35 was what its author saw, and a link from the feather-0 era - * carries `scf=0` explicitly because the generator always writes the field. - * Pinned in reasonableDefaults.test.mjs. + * First-run feather ratio; the Display slider and share defaults use 100%. + * The historical missing-scf parse fallback remains 35%. */ -export const SCOPE_FEATHER_RATIO_DEFAULT = 0.11; +export const SCOPE_FEATHER_RATIO_DEFAULT = 1; /** * Terminus opacity at/above SCOPE_TERMINUS_FAR_M — slightly translucent so * faint stars survive in the corners at globe scale. @@ -344,7 +330,10 @@ function teardownDevicePixelRatioWatch() { export function scopeMaskGeometry(width, height, featherRatio = _featherRatio) { const keyhole = getKeyholeGeometry(width, height); if (!(keyhole.radius > 0)) return null; - const feather = Math.max(0, Math.min(1, Number(featherRatio) || 0)); + const feather = Math.max( + 0, + Math.min(SCOPE_FEATHER_RATIO_MAX, Number(featherRatio) || 0), + ); // Feather straddles the keyhole edge so the visible radius stays anchored // to the shared geometry every keyhole consumer (labels, cards) fades on. const half = keyhole.radius * feather * 0.5; @@ -423,6 +412,14 @@ function draw() { _painted = true; } +/** Expose only the OFF state; an absent attribute preserves the original HUD. */ +function syncScopeMaskAppearance(enabled = _enabled) { + const dataset = globalThis.document?.documentElement?.dataset; + if (!dataset) return; + if (enabled) delete dataset.scopeMask; + else dataset.scopeMask = 'off'; +} + /** * Install the scope mask into the viewer container. Idempotent. * @param {Cesium.Viewer} viewer @@ -430,6 +427,7 @@ function draw() { */ export function installScopeMask(viewer) { if (_canvas || !viewer?.container) return; + syncScopeMaskAppearance(); _container = viewer.container; _viewer = viewer; _canvas = document.createElement('canvas'); @@ -505,6 +503,7 @@ export function setScopeMaskEnabled(enabled) { const next = Boolean(enabled); const reEnabled = next && !_enabled; _enabled = next; + syncScopeMaskAppearance(); if (reEnabled) { // The camera moved freely while the scope was off and nothing sampled it, // so the painted terminus can be a whole altitude band stale. Re-sync once @@ -522,11 +521,14 @@ export function isScopeMaskEnabled() { } /** - * @param {number} ratio - Edge feather as a fraction of keyhole radius [0,1]. + * @param {number} ratio - Edge feather as a fraction of keyhole radius [0,2]. * @returns {void} */ export function setScopeMaskFeather(ratio) { - _featherRatio = Math.max(0, Math.min(1, Number(ratio) || 0)); + _featherRatio = Math.max( + 0, + Math.min(SCOPE_FEATHER_RATIO_MAX, Number(ratio) || 0), + ); draw(); } @@ -540,6 +542,7 @@ export function getScopeMaskFeather() { * @returns {void} */ export function destroyScopeMask() { + syncScopeMaskAppearance(true); _resizeObserver?.disconnect(); _resizeObserver = null; teardownDevicePixelRatioWatch(); @@ -553,6 +556,7 @@ export function destroyScopeMask() { /** Test seam. */ export function _resetScopeMaskForTest() { + syncScopeMaskAppearance(true); _resizeObserver?.disconnect(); _resizeObserver = null; teardownDevicePixelRatioWatch(); diff --git a/src/scopeMask.test.mjs b/src/scopeMask.test.mjs index 7f5dcba62b..d37b6b23bb 100644 --- a/src/scopeMask.test.mjs +++ b/src/scopeMask.test.mjs @@ -18,6 +18,7 @@ import { SCOPE_TERMINUS_MIN_PCT, SCOPE_TERMINUS_MAX_PCT, SCOPE_FEATHER_RATIO_DEFAULT, + getScopeMaskFeather, SCOPE_OUTSIDE_ALPHA, SCOPE_TERMINUS_ALPHA_NEAR, SCOPE_TERMINUS_FAR_M, @@ -26,6 +27,7 @@ import { _resetScopeMaskForTest, } from './scopeMask.js'; import { KEYHOLE_OUTER_RADIUS } from './celestialRing.js'; +import { SCOPE_FEATHER_RATIO_MAX, clampScopeFeatherPct } from './scopeMaskPolicy.js'; beforeEach(() => _resetScopeMaskForTest()); @@ -47,16 +49,34 @@ test('zero feather produces a hard edge exactly at the keyhole radius', () => { assert.equal(geo.outerR, keyholeR); }); -test('feather ratio is clamped to [0,1] and bad input falls back to 0', () => { +test('feather ratio reaches the center at 200% and clamps larger input', () => { const wide = scopeMaskGeometry(1000, 800, 7); - const one = scopeMaskGeometry(1000, 800, 1); - assert.equal(wide.innerR, one.innerR); - assert.equal(wide.outerR, one.outerR); + const maximum = scopeMaskGeometry(1000, 800, SCOPE_FEATHER_RATIO_MAX); + const keyholeR = 800 * 0.5 * KEYHOLE_OUTER_RADIUS; + assert.equal(maximum.innerR, 0); + assert.equal(maximum.outerR, keyholeR * 2); + assert.equal(wide.innerR, maximum.innerR); + assert.equal(wide.outerR, maximum.outerR); + for (const ratio of [1, 1.5, 2]) { + setScopeMaskFeather(ratio); + assert.equal(getScopeMaskFeather(), ratio); + const geometry = scopeMaskGeometry(1000, 800); + assert.equal((geometry.innerR + geometry.outerR) / 2, keyholeR); + assert.equal(geometry.outerR - geometry.innerR, keyholeR * ratio); + } + setScopeMaskFeather(7); + assert.equal(getScopeMaskFeather(), SCOPE_FEATHER_RATIO_MAX); const nan = scopeMaskGeometry(1000, 800, Number.NaN); const zero = scopeMaskGeometry(1000, 800, 0); assert.equal(nan.innerR, zero.innerR); }); +test('UI and share feather percentages share one bounded integer range', () => { + for (const [value, expected] of [[0, 0], [11, 11], [175.6, 176], [200, 200], [350, 200], [-4, 0], [Number.NaN, 0]]) { + assert.equal(clampScopeFeatherPct(value), expected); + } +}); + test('degenerate viewport yields null instead of a broken gradient', () => { assert.equal(scopeMaskGeometry(0, 0), null); assert.equal(scopeMaskGeometry(-5, 100), null); @@ -136,12 +156,14 @@ function stubScopeMaskDom({ width = 1000, height = 800, dpr = 1 } = {}) { removeEventListener: (type, fn) => listeners.delete(fn), }), }; - globalThis.document = { createElement: () => canvas }; + const documentElement = { dataset: {} }; + globalThis.document = { documentElement, createElement: () => canvas }; globalThis.ResizeObserver = class { observe() {} disconnect() {} }; const container = { clientWidth: width, clientHeight: height, appendChild() {} }; return { canvas, container, + documentElement, /** Canvas work counters: backing-store resizes, clears, fills. */ ops, /** Every fillStyle string assigned since install (hard-crop path). */ @@ -160,6 +182,29 @@ function stubScopeMaskDom({ width = 1000, height = 800, dpr = 1 } = {}) { }; } +test('scope appearance follows direct state changes and install/destroy lifecycles', () => { + const dom = stubScopeMaskDom(); + try { + setScopeMaskEnabled(false); + assert.equal(dom.documentElement.dataset.scopeMask, 'off'); + delete dom.documentElement.dataset.scopeMask; + installScopeMask({ container: dom.container }); + assert.equal(dom.documentElement.dataset.scopeMask, 'off', 'install publishes retained OFF state'); + destroyScopeMask(); + assert.equal(dom.documentElement.dataset.scopeMask, undefined, 'destroy clears the document marker'); + installScopeMask({ container: dom.container }); + assert.equal(dom.documentElement.dataset.scopeMask, 'off', 'reinstall retains the preference'); + setScopeMaskEnabled(true); + assert.equal(dom.documentElement.dataset.scopeMask, undefined, 'ON uses the original presentation'); + setScopeMaskEnabled(false); + _resetScopeMaskForTest(); + assert.equal(dom.documentElement.dataset.scopeMask, undefined, 'test reset clears the marker'); + } finally { + destroyScopeMask(); + dom.restore(); + } +}); + test('a DPR change with no resize still repaints the backing store', () => { const dom = stubScopeMaskDom({ width: 1000, height: 800, dpr: 1 }); try { diff --git a/src/scopeMaskPolicy.js b/src/scopeMaskPolicy.js new file mode 100644 index 0000000000..13515fb435 --- /dev/null +++ b/src/scopeMaskPolicy.js @@ -0,0 +1,11 @@ +/** A 200% feather reaches the center while keeping its midpoint on the keyhole. */ +export const SCOPE_FEATHER_RATIO_MAX = 2; +const SCOPE_FEATHER_MAX_PCT = SCOPE_FEATHER_RATIO_MAX * 100; + +/** Normalize a UI/share-link feather percentage to the supported integer range. */ +export function clampScopeFeatherPct(value) { + return Math.max( + 0, + Math.min(SCOPE_FEATHER_MAX_PCT, Math.round(Number(value) || 0)), + ); +} diff --git a/src/sharelink.celestial.test.mjs b/src/sharelink.celestial.test.mjs index 2308435849..746d5b3bcc 100644 --- a/src/sharelink.celestial.test.mjs +++ b/src/sharelink.celestial.test.mjs @@ -99,6 +99,22 @@ test('Nepal locator token is valid in v2 share links', () => { assert.equal(parsed.layerStateInvalid, false); }); +test('scope feather above 100% survives share parsing and serialization', () => { + const manager = makeManager('#v=2&lat=10&lon=20&sc=0&scf=200'); + const parsed = manager.parseInitialHash(); + assert.equal(parsed.scopeEnabled, false); + assert.equal(parsed.scopeFeatherPct, 200); + assert.equal(makeManager('#lat=10&lon=20&scf=175').parseInitialHash().scopeFeatherPct, 175); + assert.equal(makeManager('#lat=10&lon=20&scf=999').parseInitialHash().scopeFeatherPct, 200); + manager.onToggleChange(false, true, { scopeEnabled: false, scopeFeatherPct: 200 }); + const params = manager._buildHashParams(); + assert.equal(params.get('sc'), '0'); + assert.equal(params.get('scf'), '200'); + manager.onToggleChange(false, true, { scopeFeatherPct: 999 }); + assert.equal(manager._buildHashParams().get('scf'), '200'); + clearTimeout(manager._debounceTimer); +}); + test('share-link serialization emits the current celestial state', () => { const manager = makeManager(); manager.onToggleChange(false, false, { celestialRingEnabled: false }); @@ -498,8 +514,8 @@ test('every explicit visual UI gesture claims restore authority before it mutate ['cycleDetection: () => {', 'toggleCctv: () =>', 'cycleDetectionMode()', 'detection hotkey'], ['toggleBloom:', 'setBloomIntensity:', 'this._setBloomEnabled(', 'toggleBloom control'], ['setBloomIntensity:', 'toggleSharpen:', 'this._setBloomIntensity(', 'setBloomIntensity control'], - ['toggleSharpen:', 'toggleScope:', 'this._setSharpenEnabled(', 'toggleSharpen control'], - ['toggleScope:', 'setScopeFeather:', 'setScopeMaskEnabled(', 'toggleScope control'], + ['toggleSharpen:', 'setScopeEnabled:', 'this._setSharpenEnabled(', 'toggleSharpen control'], + ['setScopeEnabled:', 'setScopeFeather:', 'setScopeMaskEnabled(', 'setScopeEnabled control'], ['setScopeFeather:', 'setSharpenIntensity:', 'setScopeMaskFeather(', 'setScopeFeather control'], ['setSharpenIntensity:', 'setHudLayout:', 'this._applySharpenIntensity(', 'setSharpenIntensity control'], ['setHudLayout:', 'toggleCleanView:', 'this._setHudVariant(', 'setHudLayout control'], diff --git a/src/sharelink.js b/src/sharelink.js index 7e0e78b35a..c184a59f59 100644 --- a/src/sharelink.js +++ b/src/sharelink.js @@ -5,6 +5,7 @@ import { normalizeAllocationStrategy, } from './data/detectionPolicy.js'; import { clampScopeTerminusPct } from './scopeMask.js'; +import { clampScopeFeatherPct } from './scopeMaskPolicy.js'; import { decodeLayerStateParams, encodeLayerStateParams, @@ -112,10 +113,7 @@ export class ShareLinkManager { this._detectionOutsideOpacityPct = 1; this._celestialRingEnabled = false; this._scopeEnabled = true; - // Feather opens on a soft 11% scope-mask edge (owner final lock 2026-08-24, - // superseding the 08-22 hard-crop and 08-23 8% rulings) — mirrors - // SCOPE_FEATHER_RATIO_DEFAULT in scopeMask.js and the slider's markup value. - this._scopeFeatherPct = 11; + this._scopeFeatherPct = 100; // null = the altitude-adaptive terminus (the default). A number pins the // outside-fill opacity as a percent, 94..100. (`sce`, 2026-08-17) this._scopeTerminusPct = null; @@ -227,10 +225,7 @@ export class ShareLinkManager { // (`_scopeFeatherPct` in the constructor tracks the default: that one // mirrors live state for the link this session generates, so it must match // the mask, not the archive.) - scopeFeatherPct: Math.max( - 0, - Math.min(100, Math.round(parseOr(params.get('scf'), 35))), - ), + scopeFeatherPct: clampScopeFeatherPct(parseOr(params.get('scf'), 35)), // Absent (or non-numeric) `sce` = adaptive (null), the default behavior; // a value pins the terminus opacity percent, clamped into the SUPPORTED // 94..100 band. `sce=0` used to survive as a sub-94 terminus — a hole in @@ -494,10 +489,7 @@ export class ShareLinkManager { if (typeof extras.scopeEnabled === 'boolean') this._scopeEnabled = extras.scopeEnabled; if (typeof extras.scopeFeatherPct === 'number') { - this._scopeFeatherPct = Math.max( - 0, - Math.min(100, Math.round(extras.scopeFeatherPct)), - ); + this._scopeFeatherPct = clampScopeFeatherPct(extras.scopeFeatherPct); } if (extras.scopeTerminusPct === null) this._scopeTerminusPct = null; else if (typeof extras.scopeTerminusPct === 'number') { diff --git a/src/ui/aircraftDisplay.js b/src/ui/aircraftDisplay.js index ba325f6e9d..6e14e0adf1 100644 --- a/src/ui/aircraftDisplay.js +++ b/src/ui/aircraftDisplay.js @@ -70,7 +70,6 @@ export class AircraftDisplay { // a screen reader without this. It matters more now that the button ships // ACTIVE from markup (default-on, 2026-08-22): the very first thing assistive // tech reported was an unpressed-looking control over an armed layer. - // Mirrors #scope-toggle, which has always carried aria-pressed. this._models3dBtn?.setAttribute( 'aria-pressed', String(this._models3dEnabled), diff --git a/src/ui/cyberTheme.test.mjs b/src/ui/cyberTheme.test.mjs index 68710a36a7..03ee75f08a 100644 --- a/src/ui/cyberTheme.test.mjs +++ b/src/ui/cyberTheme.test.mjs @@ -1,3 +1,4 @@ +import { getScopeMaskFeather, isScopeMaskEnabled, setScopeMaskEnabled, setScopeMaskFeather } from '../scopeMask.js'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import test from 'node:test'; @@ -271,6 +272,35 @@ test('Display and voice HUD routes preserve explicit Cyber entry and exit author assert.equal(voice.owner.activeStyle, 'snow'); }); +test('scope choice and expanded feather survive every HUD layout and both restore paths', async (t) => { + const { owner } = styleOwner(t, 'tactical'); + const previous = { enabled: isScopeMaskEnabled(), feather: getScopeMaskFeather() }; + t.after(() => { setScopeMaskEnabled(previous.enabled); setScopeMaskFeather(previous.feather); }); + Object.assign(owner.services, { setScopeMaskEnabled, setScopeMaskFeather }); + owner._scopeBtn = { checked: true }; + owner._scopeFeatherSlider = { value: '11', disabled: false }; + owner._scopeFeatherValue = {}; + await owner.restoreShareState({ scopeEnabled: false, scopeFeatherPct: 200 }); + assert.equal(owner._scopeBtn.checked, false); + assert.equal(owner._scopeFeatherSlider.disabled, true); + assert.equal(owner._scopeFeatherSlider.value, '200'); + for (const layout of ['minimal', 'operator', 'cyber', 'tactical']) { + owner._setHudVariant(layout, { applyVisualDefaults: true }); + assert.equal(isScopeMaskEnabled(), false, layout); + assert.equal(getScopeMaskFeather(), 2, layout); + assert.equal(owner._scopeBtn.checked, false, layout); + } + await owner.applyVisualState({ scope: { enabled: true, featherPct: 175 } }); + assert.equal(isScopeMaskEnabled(), true); + assert.equal(getScopeMaskFeather(), 1.75); + assert.equal(owner._scopeBtn.checked, true); + assert.equal(owner._scopeFeatherSlider.disabled, false); + assert.equal(owner._scopeFeatherValue.textContent, '175%'); + await owner.applyVisualState({ scope: { featherPct: 500 } }); + assert.equal(getScopeMaskFeather(), 2); + assert.equal(owner._scopeFeatherSlider.value, '200'); +}); + test('scene and share HUD transitions do not restore a local pre-Cyber preset', async (t) => { const { owner, hud } = styleOwner(t, 'tactical'); owner.setStyle('noir'); diff --git a/src/ui/displayBindings.js b/src/ui/displayBindings.js index 329681798b..3ae874c3c7 100644 --- a/src/ui/displayBindings.js +++ b/src/ui/displayBindings.js @@ -1,6 +1,7 @@ +import { clampScopeFeatherPct } from '../scopeMaskPolicy.js'; import { createFrameRateMonitor } from './frameRateMonitor.js'; import { bindApplicationShortcuts } from './visualInput.js'; -import { bindDisplayControls } from './displayControls.js'; +import { bindDisplayControls, syncScopeControls } from './displayControls.js'; import { canonicalizeDensity } from '../data/detectionPolicy.js'; /** Own keyboard/display event subscriptions; settings remain with their state owners. */ @@ -92,6 +93,11 @@ export class DisplayBindings { }, }); + syncScopeControls( + this._scopeBtn, + this._scopeFeatherSlider, + isScopeMaskEnabled(), + ); this._displayControls?.destroy(); this._displayControls = bindDisplayControls({ elements: { @@ -100,7 +106,7 @@ export class DisplayBindings { bloomSlider: this._bloomSlider, sharpenButton: this._sharpenBtn, sharpenSlider: this._sharpenSlider, - scopeButton: this._scopeBtn, + scopeToggle: this._scopeBtn, scopeFeatherSlider: this._scopeFeatherSlider, hudLayout: this._hudLayoutSelect, hudButton: this._hudBtn, @@ -134,17 +140,15 @@ export class DisplayBindings { this.shareLinkManager?.claimRestoreLane?.('visual'); this._setSharpenEnabled(!this.sharpenEnabled); }, - toggleScope: () => { + setScopeEnabled: (enabled) => { this.shareLinkManager?.claimRestoreLane?.('visual'); - const next = !isScopeMaskEnabled(); - setScopeMaskEnabled(next); - this._scopeBtn.classList.toggle('active', next); - this._scopeBtn.setAttribute('aria-pressed', String(next)); + setScopeMaskEnabled(enabled); + syncScopeControls(this._scopeBtn, this._scopeFeatherSlider, enabled); this._syncShareState(); }, setScopeFeather: (value) => { this.shareLinkManager?.claimRestoreLane?.('visual'); - const pct = Math.max(0, Math.min(100, value || 0)); + const pct = clampScopeFeatherPct(value); if (this._scopeFeatherValue) this._scopeFeatherValue.textContent = `${pct}%`; setScopeMaskFeather(pct / 100); diff --git a/src/ui/displayControls.js b/src/ui/displayControls.js index e0d76d3388..ceab61d91b 100644 --- a/src/ui/displayControls.js +++ b/src/ui/displayControls.js @@ -18,7 +18,6 @@ export function bindDisplayControls({ elements, actions }) { for (const [name, action] of [ ['bloomButton', 'toggleBloom'], ['sharpenButton', 'toggleSharpen'], - ['scopeButton', 'toggleScope'], ['cleanViewButton', 'toggleCleanView'], ['cleanViewExitButton', 'exitCleanView'], ['celestialButton', 'toggleCelestial'], @@ -34,6 +33,7 @@ export function bindDisplayControls({ elements, actions }) { ['scopeFeatherSlider', 'setScopeFeather'], ]) listen(elements[name], 'input', action, integer); + listen(elements.scopeToggle, 'change', 'setScopeEnabled', (el) => el.checked); listen(elements.densitySlider, 'input', 'setDensity', (el) => el.value); listen(elements.hudLayout, 'change', 'setHudLayout', (el) => el.value); for (const [name, action] of [ @@ -72,3 +72,9 @@ export function bindDisplayControls({ elements, actions }) { }, }; } + +/** Keep the native Scope checkbox and feather availability in step with the mask. */ +export function syncScopeControls(toggle, featherSlider, enabled) { + if (toggle) toggle.checked = enabled; + if (featherSlider) featherSlider.disabled = !enabled; +} diff --git a/src/ui/displayControls.test.mjs b/src/ui/displayControls.test.mjs index 705a9f7754..f7c5bcafb7 100644 --- a/src/ui/displayControls.test.mjs +++ b/src/ui/displayControls.test.mjs @@ -158,3 +158,29 @@ test('optional controls are absent safely and subscriptions stay instance-owned' assert.deepEqual(calls, ['b']); two.destroy(); }); + +test('the native Scope checkbox reads checked state on change and disposes its listener', () => { + const scopeToggle = element(); + scopeToggle.checked = true; + const scopeFeatherSlider = element('200'); + const calls = []; + const controls = bindDisplayControls({ + elements: { scopeToggle, scopeFeatherSlider }, + actions: { + setScopeEnabled: (value) => calls.push(['enabled', value]), + setScopeFeather: (value) => calls.push(['feather', value]), + }, + }); + scopeToggle.checked = false; + scopeToggle.dispatchEvent(new Event('change')); + scopeToggle.checked = true; + scopeToggle.dispatchEvent(new Event('change')); + scopeFeatherSlider.dispatchEvent(new Event('input')); + controls.destroy(); + scopeToggle.dispatchEvent(new Event('change')); + assert.deepEqual(calls, [ + ['enabled', false], + ['enabled', true], + ['feather', 200], + ]); +}); diff --git a/src/ui/frameRateMonitor.js b/src/ui/frameRateMonitor.js index 3bad73a200..2f6ab8e8d5 100644 --- a/src/ui/frameRateMonitor.js +++ b/src/ui/frameRateMonitor.js @@ -6,7 +6,7 @@ export function createFrameRateMonitor({ viewer, documentRef = document }) { if (!host || !frameEvent) return { destroy() {} }; const readout = documentRef.createElement('div'); - readout.className = 'frame-rate-readout'; + readout.className = 'frame-rate-readout scene-text-holdout'; readout.hidden = true; // i18n-ignore: FPS is a unit code, the same in every language readout.textContent = 'FPS —'; diff --git a/src/ui/styles/command-dock-trays.css b/src/ui/styles/command-dock-trays.css index eef3c60019..547037de78 100644 --- a/src/ui/styles/command-dock-trays.css +++ b/src/ui/styles/command-dock-trays.css @@ -478,6 +478,12 @@ body:not(.ui-clean-view):not(.recording-mode):has( bottom: calc(2vh + 5.4rem); } +:root[data-scope-mask='off'] + #intel-hud[data-variant='minimal'] + .hud-bottom-left { + bottom: calc(2vh + 6.5rem); +} + #intel-hud[data-variant='minimal'] .hud-bottom-bar { bottom: calc(2vh + 9rem); } diff --git a/src/ui/styles/controls.css b/src/ui/styles/controls.css index f11378bb92..59f2751091 100644 --- a/src/ui/styles/controls.css +++ b/src/ui/styles/controls.css @@ -501,6 +501,27 @@ html:not([lang='en']) .panel-collapse-btn { color: var(--accent); } +.pp-scope-toggle input { + width: 14px; + height: 14px; + margin: 0 0 0 auto; + accent-color: var(--accent); + cursor: pointer; +} + +.pp-scope-toggle:has(input:checked) .pp-label { + color: var(--accent); +} + +.pp-scope-toggle:has(input:focus-visible) { + outline: 1px solid var(--accent); + outline-offset: 2px; +} + +#scope-slider-row:has(input:disabled) { + opacity: 0.45; +} + /* ── Bloom Slider (inline with toggle) ───────── */ .pp-toggle-group { display: flex; diff --git a/src/ui/styles/overlays.css b/src/ui/styles/overlays.css index 227d2d6d06..7f491439b7 100644 --- a/src/ui/styles/overlays.css +++ b/src/ui/styles/overlays.css @@ -371,3 +371,134 @@ #intel-hud[data-variant='minimal'] .hud-summary-wrap { max-width: 280px; } + +/* Scope OFF adds text-sized backing; Scope ON retains the original HUD. */ +.hud-readout { + display: contents; +} + +:root[data-scope-mask='off'] + #intel-hud:is( + [data-variant='minimal'], + [data-variant='operator'], + [data-variant='tactical'] + ) + .hud-readout, +:root[data-scope-mask='off']:not([data-ui-theme='cyber']) .scene-text-holdout { + background: rgba(0, 0, 0, 0.7); + box-shadow: none; + border-radius: 2px; + padding-block: 0; + padding-inline: 6px; + margin-block: 0; + margin-inline: -6px; + width: fit-content; + max-width: 100%; + box-sizing: content-box; + white-space: nowrap; +} + +:root[data-scope-mask='off'] + #intel-hud:is( + [data-variant='minimal'], + [data-variant='operator'], + [data-variant='tactical'] + ) + .hud-readout { + display: block; + width: max-content; + min-width: 0; + box-sizing: content-box; + white-space: nowrap; +} + +:root[data-scope-mask='off'] + #intel-hud:is( + [data-variant='minimal'], + [data-variant='operator'], + [data-variant='tactical'] + ) + :is(.hud-top-right, .hud-bottom-right) + .hud-readout, +:root[data-scope-mask='off']:not([data-ui-theme='cyber']) + #style-indicator + .scene-text-holdout { + margin-inline-start: auto; +} + +/* Preserve glyph opacity without dimming the vertical backplates. */ +:root[data-scope-mask='off'] + #intel-hud:is([data-variant='operator'], [data-variant='tactical']) + .hud-edge { + opacity: 1; +} + +:root[data-scope-mask='off'] + #intel-hud:is([data-variant='operator'], [data-variant='tactical']) + .hud-edge + .hud-readout + > * { + opacity: 0.5; +} + +:root[data-scope-mask='off'] #intel-hud[data-variant='operator'] .hud-corner, +:root[data-scope-mask='off'] + #intel-hud:is([data-variant='minimal'], [data-variant='operator']) + :is(.hud-top-bar, .hud-bottom-bar) { + background: transparent; +} + +:root[data-scope-mask='off'] + #intel-hud:is([data-variant='minimal'], [data-variant='operator']) + :is(.hud-top-bar, .hud-bottom-bar) { + width: fit-content; + max-width: calc(100vw - 120px); + gap: 24px; +} + +:root[data-scope-mask='off'] + #intel-hud:is([data-variant='minimal'], [data-variant='operator']) + :is(.hud-top-bar, .hud-bottom-bar) + .hud-readout { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +:root[data-scope-mask='off']:not([data-ui-theme='cyber']) + #title-bar + h1::before { + content: ''; + position: absolute; + inset: -0.12em -6px; + z-index: -1; + border-radius: 2px; + background: rgba(0, 0, 0, 0.7); +} + +:root[data-scope-mask='off']:not([data-ui-theme='cyber']) + :is(#title-bar .subtitle, #style-indicator .indicator-label) { + color: var(--text-secondary); +} + +:root[data-scope-mask='off']:not([data-ui-theme='cyber']) #title-bar .subtitle { + margin-top: 8px; +} + +:root[data-scope-mask='off']:not([data-ui-theme='cyber']) + #style-indicator + .indicator-value { + margin-top: 4px; +} + +:root[data-scope-mask='off'] + #intel-hud[data-variant='minimal'] + .hud-readout:has(> :is(.hud-classification, .hud-system)) { + display: none; +} + +:root[data-scope-mask='off']:not([data-ui-theme='cyber']) + #title-bar + .frame-rate-readout { + margin-top: 6px; +} diff --git a/src/ui/templates/display-controls.html b/src/ui/templates/display-controls.html index f31453b6c8..f6af311279 100644 --- a/src/ui/templates/display-controls.html +++ b/src/ui/templates/display-controls.html @@ -106,19 +106,15 @@
- + +
Feather - - - 11% + + 100%
diff --git a/src/ui/templates/scene-chrome.html b/src/ui/templates/scene-chrome.html index b3c9785f12..ba786c30b3 100644 --- a/src/ui/templates/scene-chrome.html +++ b/src/ui/templates/scene-chrome.html @@ -11,13 +11,13 @@

GOD'S EYE VIEW

-

NO PLACE LEFT BEHIND

+

NO PLACE LEFT BEHIND

- ACTIVE STYLE - NORMAL + ACTIVE STYLE + NORMAL
diff --git a/src/ui/visualSettings.js b/src/ui/visualSettings.js index c804ea3421..1d5f16a281 100644 --- a/src/ui/visualSettings.js +++ b/src/ui/visualSettings.js @@ -1,3 +1,5 @@ +import { clampScopeFeatherPct } from '../scopeMaskPolicy.js'; +import { syncScopeControls } from './displayControls.js'; import { STYLE_STATUS_LABELS } from './visualPresets.js'; import { syncSegmentedControl } from './segmentedControl.js'; import { t } from '../i18n/index.js'; @@ -136,11 +138,10 @@ export class VisualSettings { } if (typeof scopeEnabled === 'boolean') { setScopeMaskEnabled(scopeEnabled); - this._scopeBtn?.classList.toggle('active', scopeEnabled); - this._scopeBtn?.setAttribute('aria-pressed', String(scopeEnabled)); + syncScopeControls(this._scopeBtn, this._scopeFeatherSlider, scopeEnabled); } if (typeof scopeFeatherPct === 'number' && this._scopeFeatherSlider) { - const pct = Math.max(0, Math.min(100, Math.round(scopeFeatherPct))); + const pct = clampScopeFeatherPct(scopeFeatherPct); this._scopeFeatherSlider.value = String(pct); if (this._scopeFeatherValue) this._scopeFeatherValue.textContent = `${pct}%`; @@ -1302,11 +1303,14 @@ export class VisualSettings { const scopeState = state.scope || {}; if (typeof scopeState.enabled === 'boolean') { setScopeMaskEnabled(scopeState.enabled); - this._scopeBtn?.classList.toggle('active', scopeState.enabled); - this._scopeBtn?.setAttribute('aria-pressed', String(scopeState.enabled)); + syncScopeControls( + this._scopeBtn, + this._scopeFeatherSlider, + scopeState.enabled, + ); } if (typeof scopeState.featherPct === 'number' && this._scopeFeatherSlider) { - const pct = Math.max(0, Math.min(100, Math.round(scopeState.featherPct))); + const pct = clampScopeFeatherPct(scopeState.featherPct); this._scopeFeatherSlider.value = String(pct); if (this._scopeFeatherValue) this._scopeFeatherValue.textContent = `${pct}%`;