Merge branch 'main' into exp/cctv-target-navigation

This commit is contained in:
German Khokhlov authored and GitHub committed 2026-11-18 17:39:59 +04:00
commit 7acc917ae0
16 files changed
+404 -113

No files matched your search

+3 -2
View File
@@ -1,6 +1,7 @@
import { msg } from '../i18n/marker.js';
// layers/installations/controls.js translates describeInstallationFeedback().
// installationFeedback() stays English for the analyst. ui/statusText.js and
// ui/shellFeedback.js (HUD) translate it: keep both in step with this wording.
const REASONS = Object.freeze({
rate_limited: msg('Overpass rate-limited'),
timeout: msg('Overpass timed out'),
@@ -19,7 +20,7 @@ const FALLBACK_REASON = msg('Overpass temporarily unavailable');
* @param {number} [now]
* @returns {{text: string, reason?: string, seconds?: number}|{count: number, km: ?number}}
*/
export function describeInstallationFeedback(stats = {}, now = Date.now()) {
function describeInstallationFeedback(stats = {}, now = Date.now()) {
const reason = REASONS[stats.failureReason] || FALLBACK_REASON;
if (stats.loading)
return {
+3 -7
View File
@@ -2,13 +2,9 @@ import {
formatAwarenessLabel,
AWARENESS_RADIUS_M,
} from '../../data/militaryAwarenessEngine.js';
import {
formatNumber,
onLocaleChange,
t,
translateKnown,
} from '../../i18n/index.js';
import { formatNumber, onLocaleChange, t } from '../../i18n/index.js';
import { sourceStatusLabel } from '../../ui/layerNames.js';
import { translateStatusMessage } from '../../ui/statusText.js';
import { formatQuantity } from '../../ui/unitLabels.js';
import { AWARENESS_PAGE_SIZE, AWARENESS_PAGE_ROTATE_MS } from './policy.js';
import { distanceParts } from '../../data/distanceFormat.js';
@@ -45,7 +41,7 @@ export function presentAwarenessDistance(meters) {
function presentAwarenessReason(summary = {}) {
return summary.reasonTemplate
? t(summary.reasonTemplate, summary.reasonValues)
: translateKnown(summary.reason || '');
: translateStatusMessage(summary.reason || '');
}
/**
+8 -35
View File
@@ -1,41 +1,15 @@
import { describeInstallationFeedback } from '../../data/installationFeedback.js';
import { installationFeedback } from '../../data/installationFeedback.js';
import {
LAYER_ID,
DISTANCE_PREFILTER_MARGIN_M,
ANCHOR_REFRESH_M,
} from './policy.js';
import { formatNumber, t, tn } from '../../i18n/index.js';
import { t } from '../../i18n/index.js';
import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js';
import { surfaceDistance } from '../../geo/geodesic.js';
import { toDegrees, toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
// installationFeedback.js is shared with the HUD (src/loadingFeedback.js) and
// hands back msg()-marked English plus values; getStats translates them here.
function localizeInstallationFeedback(feedback) {
if (feedback.text !== undefined) {
const values = {};
if (feedback.reason !== undefined) values.reason = t(feedback.reason);
if (feedback.seconds !== undefined) values.seconds = feedback.seconds;
return t(feedback.text, values);
}
const { count, km } = feedback;
if (km) {
const kmText = formatNumber(km);
return count === 0
? t('No mapped sites within {km} km of the contact', { km: kmText })
: tn(
count,
'{count} mapped site within {km} km of the contact',
'{count} mapped sites within {km} km of the contact',
{ km: kmText },
);
}
return count === 0
? t('No mapped sites in view')
: tn(count, '{count} mapped site in view', '{count} mapped sites in view');
}
export function createControls({ state: layerState, services, parts, source }) {
const methods = {
id: LAYER_ID,
@@ -285,13 +259,12 @@ export function createControls({ state: layerState, services, parts, source }) {
retryAt: layerState.retryAt,
retrying: layerState.loading && Boolean(layerState.failureReason),
failureReason: layerState.failureReason,
statusMessage: localizeInstallationFeedback(
describeInstallationFeedback({
...layerState,
count: layerState.lastUpdate ? mappedCount : undefined,
retrying: layerState.loading && Boolean(layerState.failureReason),
}),
),
// English: the analyst reads it as is; displays translate it.
statusMessage: installationFeedback({
...layerState,
count: layerState.lastUpdate ? mappedCount : undefined,
retrying: layerState.loading && Boolean(layerState.failureReason),
}),
loadingLabel: layerState.loading
? t('loading mapped installation context')
: '',
@@ -1,6 +1,8 @@
// statusMessage stays English (the analyst's empty note); displays translate it.
import test from 'node:test';
import assert from 'node:assert/strict';
import { setLocale, translateKnown } from '../../i18n/index.js';
import { setLocale, t, tn } from '../../i18n/index.js';
import { translateStatusMessage } from '../../ui/statusText.js';
import { createControls } from './controls.js';
function stats(state) {
@@ -13,67 +15,113 @@ function stats(state) {
}).methods.getStats();
}
for (const locale of ['es', 'ru']) {
test(`${locale}: installation feedback is in the UI language`, () => {
setLocale(locale);
const empty = stats({ status: 'empty', lastUpdate: 1 }).statusMessage;
assert.notEqual(empty, 'No mapped sites in view');
const found = stats({
function inLocale(locale, run) {
setLocale(locale);
try {
run();
} finally {
setLocale('en');
}
}
// A retry a minute out reads "60s" (rounded up).
const cases = [
[
{ status: 'empty', lastUpdate: 1 },
'No mapped sites in view',
() => t('No mapped sites in view'),
],
[
{ status: 'ready', lastUpdate: 1, records: [{ kind: 'installation' }] },
'1 mapped site in view',
() => tn(1, '{count} mapped site in view', '{count} mapped sites in view'),
],
[
{
status: 'ready',
lastUpdate: 1,
records: [{ kind: 'installation' }, { kind: 'installation' }],
}).statusMessage;
assert.notEqual(found, '2 mapped sites in view');
const tiles = stats({
status: 'unavailable',
failureReason: 'tiles_unavailable',
}).statusMessage;
assert.notEqual(tiles, 'Map tiles temporarily unavailable');
const retry = stats({
},
'2 mapped sites in view',
() => tn(2, '{count} mapped site in view', '{count} mapped sites in view'),
],
[
{
status: 'empty',
lastUpdate: 1,
wide: true,
coverage: { kind: 'subject', radiusM: 25000 },
},
'No mapped sites within 25 km of the contact',
() => t('No mapped sites within {km} km of the contact', { km: '25' }),
],
[
{
status: 'ready',
lastUpdate: 1,
wide: true,
coverage: { kind: 'subject', radiusM: 25000 },
records: [{ kind: 'installation' }],
},
'1 mapped site within 25 km of the contact',
() =>
tn(
1,
'{count} mapped site within {km} km of the contact',
'{count} mapped sites within {km} km of the contact',
{ km: '25' },
),
],
[
{ status: 'unavailable', failureReason: 'tiles_unavailable' },
'Map tiles temporarily unavailable',
() => t('Map tiles temporarily unavailable'),
],
[
{
status: 'unavailable',
failureReason: 'names_unavailable',
retryAt: Date.now() + 5000,
}).statusMessage;
assert.doesNotMatch(retry, /^Mapped names temporarily unavailable/);
for (const text of [
'Too many mapped sites in view to list them all',
'Installation context unavailable',
]) {
assert.notEqual(translateKnown(text), text);
}
get retryAt() {
return Date.now() + 60_000;
},
},
'Mapped names temporarily unavailable — retrying in 60s',
() =>
t('{reason} — retrying in {seconds}s', {
reason: t('Mapped names temporarily unavailable'),
seconds: 60,
}),
],
[
{ status: 'zoom-in' },
'Zoom in to search mapped installations',
() => t('Zoom in to search mapped installations'),
],
];
for (const locale of ['es', 'ru']) {
test(`${locale}: installation statusMessage stays English data`, () => {
inLocale(locale, () => {
for (const [state, english] of cases)
assert.equal(stats(state).statusMessage, english);
});
});
test(`${locale}: installation statusMessage is shown in the UI language`, () => {
inLocale(locale, () => {
for (const [state, english, shown] of cases) {
const shownText = translateStatusMessage(stats(state).statusMessage);
assert.notEqual(shownText, english);
assert.equal(shownText, shown());
}
});
});
}
test('en: installation feedback keeps its English wording', () => {
setLocale('en');
assert.equal(
stats({ status: 'empty', lastUpdate: 1 }).statusMessage,
'No mapped sites in view',
);
assert.equal(
stats({
status: 'ready',
lastUpdate: 1,
records: [{ kind: 'installation' }],
}).statusMessage,
'1 mapped site in view',
);
assert.equal(
stats({
status: 'ready',
lastUpdate: 1,
wide: true,
coverage: { kind: 'subject', radiusM: 25000 },
records: [{ kind: 'installation' }, { kind: 'installation' }],
}).statusMessage,
'2 mapped sites within 25 km of the contact',
);
assert.equal(
stats({
status: 'unavailable',
failureReason: 'names_unavailable',
retryAt: Date.now() + 5000,
}).statusMessage,
'Mapped names temporarily unavailable — retrying in 5s',
);
for (const [state, english] of cases) {
assert.equal(stats(state).statusMessage, english);
assert.equal(translateStatusMessage(english), english);
}
});
+21 -7
View File
@@ -574,12 +574,14 @@ export function createRecentImageryLayer({
const list = stripList();
if (!list.length) return;
reconcileFocus();
thumbnails.requestOrdered(list, _box, {
focusIndex: Math.max(0, focusIndexIn(list)),
firstVisible: _visible.first,
lastVisible: _visible.last,
extra: 2,
});
const wanted = new Set(
thumbnails.requestOrdered(list, _box, {
focusIndex: Math.max(0, focusIndexIn(list)),
firstVisible: _visible.first,
lastVisible: _visible.last,
extra: 2,
}),
);
for (const key of new Set([
_assigned.a,
_assigned.b,
@@ -587,8 +589,11 @@ export function createRecentImageryLayer({
_followKey,
])) {
const candidate = candidateFor(key);
if (sourceOn(candidate)) thumbnails.request(candidate, _box, 0);
if (!sourceOn(candidate)) continue;
thumbnails.request(candidate, _box, 0);
wanted.add(candidate.key);
}
thumbnails.retain(wanted);
}
function resetCatalog() {
@@ -821,7 +826,16 @@ export function createRecentImageryLayer({
// A probe can take a pinned day off the map or let a followed focus
// preview; both change more than the cards, so a full notification
// follows the thumbnail one.
const previousFollow = _followKey;
const previousPreview = _previewKey;
const pruned = pruneEmpty();
if (
pruned &&
(_followKey !== previousFollow || _previewKey !== previousPreview)
) {
// The new automatic day's probe may have been cancelled off-screen.
requestThumbnails();
}
if (pruned) syncRender();
const followed =
Boolean(_followKey) &&
+46
View File
@@ -1105,6 +1105,10 @@ test('alpha, split and visible range notify without re-rendering the row', async
f.layer.setSplit(0.25);
f.layer.setVisibleRange(1, 3);
assert.equal(f.thumbnails.calls.at(-1)[2].firstVisible, 1);
assert.ok(
f.thumbnails.retained.at(-1).includes(f.snap().focus.key),
'the current focus remains in the retained refinement intent',
);
assert.equal(rowRenders, rows);
assert.deepEqual(f.reasons.slice(-2), ['alpha', 'split']);
f.layer.setAlpha('bad');
@@ -1193,6 +1197,48 @@ const dailyViirs = () =>
),
);
test('empty auto VIIRS re-requests a cancelled successor', async () => {
const f = fixture();
const days = dailyViirs();
const newest = days[0].key;
const next = days[1].key;
f.layer.setSources({ hls: false });
await f.ready(days);
assert.equal(f.diag().following, newest);
assert.ok(
f.thumbnails.retained.at(-1).includes(next),
'the next day was originally scheduled',
);
// Move the visible window away before either day answers: retention
// cancels the next day's probe but keeps the currently followed day.
f.layer.setVisibleRange(25, 29);
assert.equal(
f.thumbnails.retained.at(-1).includes(next),
false,
'the next day is no longer retained',
);
const before = f.thumbnails.requests.filter(([key]) => key === next).length;
f.thumbnails.probe(newest, 'empty');
assert.equal(f.diag().following, next);
assert.equal(f.snap().preview.pending, next);
assert.ok(
f.thumbnails.retained.at(-1).includes(next),
'the new follow day is retained without scrolling again',
);
assert.equal(
f.thumbnails.requests.filter(([key]) => key === next).length,
before + 1,
'the cancelled successor is requested again',
);
f.thumbnails.probe(next, 'present');
assert.equal(f.snap().preview.key, next);
assert.deepEqual(f.drapes(), { a: `${next}|none`, b: null });
});
test('restored pins outside the visible strip window are probed and swipe once present', async () => {
const f = fixture();
const days = dailyViirs();
+10 -2
View File
@@ -258,6 +258,7 @@ export function fakeThumbnails() {
const requested = [];
/** Direct `request` calls: `[key, priority]`. */
const requests = [];
const retained = [];
const ask = (key) => {
if (!requested.includes(key)) requested.push(key);
};
@@ -265,21 +266,28 @@ export function fakeThumbnails() {
calls,
requested,
requests,
retained,
requestOrdered(candidates, box, window) {
calls.push(['ordered', candidates.map((c) => c.key), window]);
const { focusIndex, firstVisible, lastVisible, extra } = window;
thumbnailOrder(
const order = thumbnailOrder(
focusIndex,
firstVisible,
lastVisible,
candidates.length,
extra,
).forEach((index) => ask(candidates[index].key));
);
const keys = order.map((index) => candidates[index].key);
keys.forEach(ask);
return keys;
},
request(candidate, box, priority) {
ask(candidate.key);
requests.push([candidate.key, priority]);
},
retain(keys) {
retained.push([...keys]);
},
/** Settle every requested key still unknown, as the loader would. */
probeRequested(status = 'present') {
for (const key of requested)
+36 -1
View File
@@ -166,6 +166,19 @@ export function createThumbnailLoader({
const existing = entries.get(key);
if (existing) {
touch(existing);
if (existing.loading && existing.controller?.signal.aborted) {
// Wanted again before the abort settles: a fresh entry, so the old
// run cannot discard it.
const renewed = {
...existing,
priority,
loading: false,
controller: null,
};
entries.set(key, renewed);
enqueue(renewed);
return;
}
if (existing.loading) return;
if (existing.status === 'unknown') {
existing.priority = priority;
@@ -210,11 +223,33 @@ export function createThumbnailLoader({
candidates.length,
extra,
);
order.forEach((index, priority) => {
return order.map((index, priority) => {
this.request(candidates[index], box, priority);
return candidates[index].key;
});
},
/**
* Cancel queued and in-flight work for every key not in `keys`. Settled
* entries stay under the LRU; a cancelled re-fetch of a present day keeps
* its status.
* @param {Iterable<string>} keys
*/
retain(keys) {
const wanted = new Set(keys);
for (let index = queue.length - 1; index >= 0; index -= 1) {
const entry = queue[index];
if (wanted.has(entry.key)) continue;
queue.splice(index, 1);
if (entry.status === 'unknown') entries.delete(entry.key);
}
for (const entry of [...entries.values()]) {
if (!entry.loading || wanted.has(entry.key)) continue;
entry.controller?.abort();
if (entry.status === 'unknown') entries.delete(entry.key);
}
},
/**
* Abort every fetch in flight and forget every unsettled request. A
* known day whose image was being fetched again keeps what it knows.
@@ -336,3 +336,93 @@ test('injected thumbnail acquisition owns requests while the loader releases obj
loader.destroy();
assert.deepEqual(revoked, ['blob:1']);
});
test('retain aborts stale acquisition while allowing the current intent to start', async () => {
const { loader, fetch } = fixture({ maxInFlight: 1 });
const stale = candidate('S30', '2026-09-10');
const current = candidate('S30', '2026-09-11');
loader.request(stale, BOX, 0);
loader.request(current, BOX, 1);
assert.equal(fetch.calls.length, 1);
assert.match(fetch.calls[0].url, /TIME=2026-09-10/);
loader.retain([current.key]);
assert.equal(fetch.calls[0].signal.aborted, true);
await settle();
assert.equal(
fetch.calls.length,
2,
'current intent starts after stale abort',
);
assert.match(fetch.calls[1].url, /TIME=2026-09-11/);
assert.equal(loader.get(stale.key).status, 'unknown');
});
test('a cancelled re-fetch of a known-present day keeps its status and is retryable', async () => {
const { loader, fetch } = fixture({ maxInFlight: 1, maxDecoded: 1 });
const stale = candidate('S30', '2026-09-10');
const newer = candidate('S30', '2026-09-11');
loader.request(stale, BOX, 0);
fetch.respond(0);
await settle();
const acquisitionTime = loader.get(stale.key).acquisitionTime;
loader.request(newer, BOX, 0);
fetch.respond(1);
await settle();
assert.equal(loader.get(stale.key).status, 'present');
assert.equal(loader.get(stale.key).objectUrl, null);
loader.request(stale, BOX, 0);
assert.equal(fetch.calls.length, 3, 'an evicted known day re-fetches');
loader.retain([]);
assert.equal(fetch.calls[2].signal.aborted, true);
await settle();
assert.equal(loader.get(stale.key).status, 'present');
assert.equal(loader.get(stale.key).acquisitionTime, acquisitionTime);
loader.request(stale, BOX, 0);
assert.equal(fetch.calls.length, 4, 'a cancelled re-fetch is retryable');
fetch.respond(3);
await settle();
assert.equal(loader.get(stale.key).status, 'present');
});
for (const cancelRenewed of [false, true]) {
test(`a known-present day requested during abort settlement ${cancelRenewed ? 'can be cancelled again' : 'restarts without another intent change'}`, async (t) => {
const { loader, fetch } = fixture({ maxInFlight: 1, maxDecoded: 1 });
t.after(() => loader.destroy());
const day = candidate('S30', '2026-09-10');
const other = candidate('S30', '2026-09-11');
loader.request(day, BOX);
fetch.respond(0);
await settle();
const acquisitionTime = loader.get(day.key).acquisitionTime;
loader.request(other, BOX);
fetch.respond(1);
await settle();
assert.equal(loader.get(day.key).objectUrl, null);
loader.request(day, BOX);
loader.retain([]);
assert.equal(fetch.calls[2].signal.aborted, true);
// Deliberately do not await: the old run still owns its in-flight slot.
loader.request(day, BOX);
loader.retain(cancelRenewed ? [] : [day.key]);
assert.equal(fetch.calls.length, 3, 'renewal respects the concurrency cap');
await settle();
assert.equal(loader.get(day.key).acquisitionTime, acquisitionTime);
assert.equal(fetch.calls.length, cancelRenewed ? 3 : 4);
if (!cancelRenewed) {
assert.equal(fetch.calls[3].signal.aborted, false);
fetch.respond(3);
await settle();
assert.ok(loader.get(day.key).objectUrl);
assert.equal(loader.get(day.key).loading, false);
}
});
}
+2 -1
View File
@@ -1,5 +1,6 @@
import { t } from '../i18n/index.js';
import { spaceMissionsIndexFailure } from './contextActions.js';
import { translateStatusMessage } from './statusText.js';
import { shouldExpandGlobalContextPanel } from '../rightRailPolicy.js';
export function _initGlobalContextPanel() {
@@ -112,7 +113,7 @@ export function _initGlobalContextPanel() {
if (this.destroyed || searched === false) return false;
const stats = this.installations.getStats?.();
this.showToast(
stats?.statusMessage ||
(stats?.statusMessage && translateStatusMessage(stats.statusMessage)) ||
(stats?.status === 'zoom-in'
? t('Zoom in to search mapped installations')
: t('Nearby installations refreshed')),
+49 -1
View File
@@ -242,9 +242,57 @@ const STATUS_PIECE_PATTERNS = [
],
];
// Shapes of installationFeedback() (data/installationFeedback.js), which stays
// English for the analyst. Keep them in step with its wording.
const MAPPED_SITE_PATTERNS = [
[
/^(.+) — retrying in (\d+)s$/,
([, reason, seconds]) =>
t('{reason} — retrying in {seconds}s', {
reason: translateKnown(reason),
seconds,
}),
],
[
/^(.+) — retry pending$/,
([, reason]) =>
t('{reason} — retry pending', { reason: translateKnown(reason) }),
],
[/^No mapped sites in view$/, () => t('No mapped sites in view')],
[
/^(\d+) mapped sites? in view$/,
([, count]) =>
tn(
Number(count),
'{count} mapped site in view',
'{count} mapped sites in view',
),
],
[
/^No mapped sites within (\d+) km of the contact$/,
([, km]) =>
t('No mapped sites within {km} km of the contact', {
km: formatNumber(Number(km)),
}),
],
[
/^(\d+) mapped sites? within (\d+) km of the contact$/,
([, count, km]) =>
tn(
Number(count),
'{count} mapped site within {km} km of the contact',
'{count} mapped sites within {km} km of the contact',
{ km: formatNumber(Number(km)) },
),
],
];
// First match wins.
const STATUS_SHAPES = [...STATUS_PIECE_PATTERNS, ...MAPPED_SITE_PATTERNS];
/** A status piece by its shape in the UI language, or null. */
function statusPatternText(piece) {
for (const [pattern, format] of STATUS_PIECE_PATTERNS) {
for (const [pattern, format] of STATUS_SHAPES) {
const match = pattern.exec(piece);
if (match) return format(match);
}
+21
View File
@@ -74,6 +74,14 @@ const transitCoverage = [
'transit: No feed here yet · 12 regions available',
];
// Mapped Installations' statusMessage (data/installationFeedback.js).
const installationNotes = [
'military-installations: No mapped sites in view',
'military-installations: No mapped sites within 25 km of the contact',
'military-installations: Overpass timed out — retrying in 30s',
'military-installations: Zoom in to search mapped installations',
];
for (const locale of ['es', 'ru']) {
for (const [layerKey, caveat] of cases) {
test(`${locale}: analyst note "${caveat}" is translated`, () => {
@@ -85,6 +93,19 @@ for (const locale of ['es', 'ru']) {
});
}
test(`${locale}: Mapped Installations' empty note is translated on the analyst card`, () => {
inLocale(locale, () => {
for (const caveat of installationNotes) {
const notes = notesFor('military-installations', caveat);
assert.ok(notes.length > 0, 'the note is shown');
assert.doesNotMatch(
notes.join(' | '),
/mapped sites|retrying|Overpass timed out|Zoom in/,
);
}
});
});
test(`${locale}: Transit's empty note is translated on the analyst card`, () => {
inLocale(locale, () => {
for (const caveat of transitCoverage) {