import test, { afterEach } from 'node:test'; import assert from 'node:assert/strict'; import { createWeatherRendering, READY_WAKE_MS } from './rendering.js'; import { createWeatherLayer } from './index.js'; import { createWeatherClock } from './clock.js'; import { worldClock } from '../../time/worldClock.js'; import * as Cesium from 'cesium'; import { Color, ImageryLayerCollection, GeographicTilingScheme } from 'cesium'; import { NO_IMAGERY_HOST } from './imageryHost.js'; import { createWeatherShell } from './shellRendering.js'; import { createCesiumFields } from '../../render/cesium/drawFields.js'; import { WEATHER_IMAGERY_Z } from './imageryOrder.js'; import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; import { fakeSceneFrame } from '../../testSupport/fakeCesiumScene.mjs'; import { createCesiumGlobe } from '../../render/cesium/globe.js'; import { bindRenderer } from '../../render/rendererOf.js'; import { createShellCesium, createShellScene, renderShells, } from './shellFixture.mjs'; const times = [ '2026-09-15T20:00:00.000Z', '2026-09-15T20:05:00.000Z', '2026-09-15T20:10:00.000Z', ]; const snapshot = { product: 'radar', times, latest: times[2], bounds: { west: -130, south: 20, east: -60, north: 55 }, }; const deferred = () => { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; }; const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); }; // Time moves on the world clock the weather clock follows, as the timeline // moves it. const seekTo = (clock, time) => { clock.world.seek(Date.parse(time)); return flush(); }; const goLive = (clock) => { clock.world.goLive(); return flush(); }; function event() { const listeners = new Set(); return { addEventListener(fn) { listeners.add(fn); return () => listeners.delete(fn); }, emit(...args) { for (const fn of [...listeners]) fn(...args); }, get size() { return listeners.size; }, }; } function target(extra = {}) { const listeners = new Map(); return { ...extra, addEventListener(name, fn) { if (!listeners.has(name)) listeners.set(name, new Set()); listeners.get(name).add(fn); }, removeEventListener(name, fn) { listeners.get(name)?.delete(fn); }, emit(name) { for (const fn of [...(listeners.get(name) || [])]) fn(); }, get size() { return [...listeners.values()].reduce( (sum, entries) => sum + entries.size, 0, ); }, }; } // What a canvas double encoded, by its bytes' text: a fetched tile's bytes // are "decoded" back to the canvas that made them. const encodedCanvases = new Map(); function mockCanvas() { const canvas = { width: 0, height: 0 }; canvas.convertToBlob = async () => { const id = `canvas:${encodedCanvases.size}`; encodedCanvases.set(id, canvas); return new Blob([id]); }; canvas.getContext = () => ({ setTransform(...matrix) { canvas.transforms = [...(canvas.transforms ?? []), matrix]; }, drawImage(source, ...crop) { canvas.source = source; canvas.crop = crop; canvas.drawnWith = canvas.transforms?.at(-1) ?? null; }, getImageData: () => ({ data: new Uint8ClampedArray([194, 100, 0, 200]) }), putImageData(pixels) { canvas.pixels = pixels.data; }, }); return canvas; } const mockResponse = () => ({ ok: true, headers: new Headers(), arrayBuffer: async () => new ArrayBuffer(1), }); /** A camera port over a fake viewer's Cesium-shaped camera. */ const cameraOver = (viewer) => viewer.camera && { on: (event, cb) => event === 'moveEnd' ? viewer.camera.moveEnd?.addEventListener(cb) : () => {}, viewRectangle() { const rect = viewer.camera.computeViewRectangle?.(); if (!rect) return null; const deg = Cesium.Math.toDegrees; return { west: deg(rect.west), south: deg(rect.south), east: deg(rect.east), north: deg(rect.north), }; }, }; /** A credits port recording what is owed now. */ function fakeCredits() { const owed = []; return { owed, addStatic(credit) { const entry = { ...credit }; owed.push(entry); return () => { const i = owed.indexOf(entry); if (i >= 0) owed.splice(i, 1); }; }, list: () => owed.slice(), on: () => () => {}, }; } /** * Each layer added through the globe port, as a test drives it: `spec`, * the tile it answers with (`response`), `requestImage` through the * layer's hooks, and tile errors through `errorEvent.emit`. */ function layerDriver(layer, createCanvas) { const box = { response: null, requestArgs: undefined }; return { layer, spec: layer.spec, box, get response() { return box.response; }, set response(value) { box.response = value; }, get requestArgs() { return box.requestArgs; }, requestImage(x, y, level, request) { const tile = { x, y, level }; return layer.request(tile, () => { box.requestArgs = [x, y, level, request]; if (layer.spec.kind === 'canvas') { const canvas = createCanvas(); canvas.width = canvas.height = layer.spec.tileSize; layer.spec.drawTile(tile, canvas); return Promise.resolve(canvas); } if (layer.spec.fetchTile) { // The renderer fetches through the hook, then decodes the bytes. const controller = new AbortController(); box.abort = (reason) => controller.abort(reason); return layer.spec .fetchTile({ tile, url: layer.spec.url, signal: controller.signal }) .then((answer) => encodedCanvases.get(new TextDecoder().decode(answer.bytes)), ); } return box.response?.promise; }); }, errorEvent: { get size() { return layer.listenerCount('tileError'); }, emit(error) { const status = error?.error?.statusCode; layer.fail({ tile: { x: error.x, y: error.y, level: error.level }, ...(Number.isFinite(status) ? { status } : {}), }); }, }, }; } function renderingHarness(options = {}) { const providers = []; const postRender = event(); let renderRequests = 0; const viewer = { clock: { untouched: true }, imageryLayers: { isDestroyed: () => false }, scene: { postRender, primitives: createShellScene().primitives, globe: { tilesLoaded: true }, requestRender() { renderRequests++; }, }, }; const frame = fakeSceneFrame(viewer); const globe = fakeGlobePort({ settled: () => viewer.scene.globe.tilesLoaded, }); const createCanvas = options.createCanvas ?? mockCanvas; const add = globe.imagery.add; globe.imagery.add = (spec, index) => { const layer = add(spec, index); providers.push(layerDriver(layer, createCanvas)); return layer; }; const credits = fakeCredits(); const cesium = { ...createShellCesium(), Color, GeographicTilingScheme, Event: Cesium.Event, Credit: Cesium.Credit, Rectangle: Cesium.Rectangle, }; // The Cesium draw port's raster shells, over the doubles. const fields = createCesiumFields({ scene: viewer.scene, cesium }); const draw = { field: (spec) => fields.field(spec) }; const rendering = createWeatherRendering({ viewer, globeOf: () => globe, cameraOf: cameraOver, creditsOf: () => credits, frameOf: () => frame, toBitmap: (canvas) => canvas, createShell: (shellOptions) => createWeatherShell({ ...shellOptions, drawOf: () => draw, cameraOf: cameraOver, frameOf: () => frame, }), fetchImpl: async () => mockResponse(), decodeImage: async () => ({ width: 2048, height: 1024, close() {} }), createCanvas, ...options, }); const settle = () => { postRender.emit(); postRender.emit(); }; return { rendering, viewer, cesium, globe, credits, providers, layers: globe.layers, postRender, settle, shells: () => viewer.scene.primitives.items, renderShells: () => renderShells(cesium, viewer.scene), renders: () => renderRequests, }; } test('a ready weather frame does not wait for unrelated terrain, but requires successful quiet tiles', async () => { let now = 0; const h = renderingHarness({ now: () => now }); h.viewer.scene.globe.tilesLoaded = false; const loaded = h.rendering.setFrame(snapshot, times[0]); h.settle(); assert.equal( h.rendering.getDiagnostics().loading, true, 'no successful tiles is not ready', ); const tile = deferred(); h.providers[0].response = tile; const request = h.providers[0].requestImage(0, 0, 0, {}); tile.resolve({}); await request; now = 199; h.settle(); assert.equal( h.rendering.getDiagnostics().loading, true, 'scheduler quiet interval is required', ); h.providers[0].response = null; assert.equal(h.providers[0].requestImage(1, 0, 0, {}), undefined); now = 500; h.settle(); assert.equal( h.rendering.getDiagnostics().loading, true, 'a scheduler-deferred own tile prevents premature commit', ); const delayed = deferred(); h.providers[0].response = delayed; const admitted = h.providers[0].requestImage(1, 0, 0, {}); delayed.resolve({}); await admitted; now = 701; h.settle(); assert.equal(await loaded, true); assert.equal(h.rendering.getDiagnostics().loadedTiles, 2); assert.equal(h.rendering.getDiagnostics().frameLoadMs, 701); 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 }); const moveEnd = event(); h.viewer.camera = { moveEnd }; h.viewer.scene.globe.tilesLoaded = false; const stage = h.rendering.setFrame(snapshot, times[0]); assert.equal(moveEnd.size, 1); const provider = h.providers[0]; const first = deferred(); provider.response = first; const firstRequest = provider.requestImage(0, 0, 0, {}); first.resolve({}); await firstRequest; provider.response = null; assert.equal(provider.requestImage(1, 0, 0, {}), undefined); const pending = deferred(); provider.response = pending; const admitted = provider.requestImage(2, 0, 0, {}); assert.equal(h.rendering.getDiagnostics().deferredTiles, 1); assert.equal(h.rendering.getDiagnostics().pendingTiles, 1); now = 500; moveEnd.emit(); assert.equal( h.rendering.getDiagnostics().deferredTiles, 0, 'an unadmitted tile abandoned by the old viewport no longer blocks the stage', ); assert.equal( h.rendering.getDiagnostics().pendingTiles, 1, 'camera movement does not erase admitted request ownership', ); now = 800; h.settle(); assert.equal(h.rendering.getDiagnostics().loading, true); assert.equal( h.layers[0].alpha, 0, 'the new observation stays invisible while a request is pending', ); pending.resolve({}); await admitted; now = 999; h.settle(); assert.equal( h.rendering.getDiagnostics().loading, true, 'completion starts a new quiet interval', ); now = 1000; h.postRender.emit(); assert.equal( h.rendering.getDiagnostics().loading, true, 'commit still requires two settled renders', ); h.postRender.emit(); assert.equal(await stage, true); assert.equal(h.rendering.getDiagnostics().loadedTiles, 2); assert.equal(h.rendering.getDiagnostics().time, times[0]); assert.equal(moveEnd.size, 0, 'committing releases the stage listener'); const abandoned = h.rendering.setFrame(snapshot, times[1]); assert.equal(moveEnd.size, 1); h.rendering.clear(); assert.equal(await abandoned, false); assert.equal( moveEnd.size, 0, 'teardown also releases the stage camera listener', ); }); test('weather stages invisibly, waits for pending tiles and render readiness, and replaces atomically', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const h = renderingHarness(); const first = h.rendering.setFrame(snapshot, times[0]); const layer = h.layers[0]; assert.equal(layer.alpha, 0); assert.equal(layer.show, true); assert.equal(h.rendering.getDiagnostics().time, null); const tile = deferred(); h.providers[0].response = tile; const requested = h.providers[0].requestImage(0, 0, 0, { cancel() {} }); h.settle(); assert.equal(h.rendering.getDiagnostics().loading, true); tile.resolve({}); await requested; h.viewer.scene.globe.tilesLoaded = false; h.settle(); assert.equal(h.rendering.getDiagnostics().loading, true); h.viewer.scene.globe.tilesLoaded = true; h.postRender.emit(); assert.equal( h.rendering.getDiagnostics().time, null, 'one settled frame is insufficient', ); h.postRender.emit(); assert.equal(await first, true); assert.equal(layer.alpha, 0.7); const second = h.rendering.setFrame(snapshot, times[1]); assert.equal(h.layers.length, 2); assert.equal( h.rendering.getDiagnostics().time, times[0], 'displayed time remains old until commit', ); h.settle(); assert.equal(await second, true); assert.equal(h.layers.length, 2, 'old layer survives the admission render'); assert.equal( h.layers[1].alpha, 0.7, 'new layer is visible before retirement', ); assert.equal(layer.removed, false); h.postRender.emit(); assert.equal(h.layers.length, 1); assert.equal(layer.removed, true); assert.equal(h.providers[0].errorEvent.size, 0); assert.equal(h.rendering.getDiagnostics().time, times[1]); assert.deepEqual(h.viewer.clock, { untouched: true }); h.rendering.clear(); }); test('superseded stages cancel requests and cannot resurrect after a late tile response', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const h = renderingHarness(); const first = h.rendering.setFrame(snapshot, times[0]); const tile = deferred(); const oldProvider = h.providers[0]; oldProvider.response = tile; const requested = oldProvider.requestImage(0, 0, 0, {}); const second = h.rendering.setFrame(snapshot, times[1]); assert.equal(await first, false); assert.equal( oldProvider.layer.removed, true, 'removing the layer cancels its requests in flight', ); assert.equal(h.layers.length, 1); assert.equal(oldProvider.errorEvent.size, 0); tile.resolve({}); await requested; h.settle(); assert.equal(await second, true); assert.equal(h.rendering.getDiagnostics().time, times[1]); assert.equal(oldProvider.requestImage(0, 0, 0, {}), undefined); h.rendering.clear(); assert.equal(h.layers.length, 0); assert.equal(h.postRender.size, 0); assert.ok(h.providers.every((provider) => provider.errorEvent.size === 0)); t.mock.timers.tick(30_000); assert.equal(h.layers.length, 0); }); test('failed and timed-out stages retain the previous observation; a healthy replacement clears old errors', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const h = renderingHarness(); const first = h.rendering.setFrame(snapshot, times[0]); h.settle(); await first; const failed = h.rendering.setFrame(snapshot, times[1]); h.providers[1].errorEvent.emit(new Error('tile missing')); h.postRender.emit(); assert.equal(await failed, false); assert.equal(h.rendering.getDiagnostics().time, times[0]); assert.equal(h.layers.length, 1); const timeout = h.rendering.setFrame(snapshot, times[1]); h.viewer.scene.globe.tilesLoaded = false; t.mock.timers.tick(25_000); assert.equal(await timeout, false); assert.equal(h.rendering.getDiagnostics().time, times[0]); const healthy = h.rendering.setFrame(snapshot, times[2]); h.providers[0].errorEvent.emit( new Error('old visible tile failed while replacement loaded'), ); h.viewer.scene.globe.tilesLoaded = true; h.settle(); assert.equal(await healthy, true); assert.equal(h.rendering.getDiagnostics().error, null); h.rendering.clear(); }); // A layer built without a clock keeps its own on the page's world clock: // each test leaves that clock live, with no layer of its own on it. const harnessed = new Set(); afterEach(() => { for (const layer of harnessed) layer.destroy(); harnessed.clear(); worldClock.goLive(); worldClock.setRate(1); }); function layerHarness({ clock, reducedMotion = false, feed, id, eventTarget = target(), enable = true, } = {}) { const stages = []; const motion = target({ matches: reducedMotion }); const documentRef = target({ hidden: false }); const moveEnd = event(); let time = null; let infraredMode = 'filtered'; let active = null; let clearCount = 0; let hidden = false; let alpha = null; const rendering = { rehome() { active?.finish(false); }, setAlpha(value) { alpha = value; }, setHidden(value) { hidden = value; if (value) active?.finish(false); }, setFrame(value, selected, { signal, infrared = 'filtered' } = {}) { if (active) active.finish(false); const task = deferred(); const abort = () => stage.finish(false); const stage = { ...task, time: selected, infrared, signal, finish(ok = true) { signal?.removeEventListener('abort', abort); if (active === stage) { if (ok) { time = selected; infraredMode = infrared; } active = null; } task.resolve(ok); }, }; signal?.addEventListener('abort', abort, { once: true }); stages.push(stage); active = stage; return stage.promise; }, clear() { clearCount++; active?.finish(false); active = null; time = null; }, getDiagnostics: () => ({ time: hidden ? null : time, hidden, infrared: infraredMode, loading: Boolean(active), error: null, }), }; const viewer = { camera: { moveEnd } }; bindRenderer(viewer, { camera: cameraOver(viewer) }); const layer = createWeatherLayer({ clock, id, feed: feed ?? { getSnapshot: async () => snapshot }, documentRef, eventTarget, matchMedia: () => motion, createRendering: () => rendering, }); layer.init(viewer); if (enable) layer.enable(); harnessed.add(layer); return { layer, rendering, stages, eventTarget, motion, documentRef, moveEnd, clears: () => clearCount, getAlpha: () => alpha, }; } test('without a clock the layer keeps one of its own on the world clock and lets it go on destroy', async () => { const h = layerHarness(); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; assert.equal(worldClock.follows('weather-radar'), true); // The frames span the timeline's time; they are not marks on it. assert.deepEqual(worldClock.coverage(), { start: Date.parse(times[0]), end: Date.parse(times.at(-1)), marks: [], markDetails: [], }); h.layer.setParams({ play: true }); assert.equal(worldClock.isPlaying(), true); assert.equal(worldClock.getState().stepping, false); assert.equal(h.layer.getDiagnostics().playing, true); h.documentRef.hidden = true; h.documentRef.emit('visibilitychange'); await flush(); assert.equal(worldClock.isPlaying(), true, 'hiding suspends the layer only'); h.documentRef.hidden = false; h.documentRef.emit('visibilitychange'); h.layer.setParams({ play: true }); assert.equal(worldClock.isPlaying(), false); h.layer.disable(); assert.equal(h.layer.getDiagnostics().historyFrames, 0); h.layer.destroy(); assert.equal(worldClock.follows('weather-radar'), false); assert.equal(h.documentRef.size, 0); assert.equal(h.motion.size, 0); assert.equal(h.moveEnd.size, 0); assert.ok(h.clears() >= 1); }); test('a layer without a clock leaves the world clock alone until enabled, and never sends it live', async (t) => { const past = Date.parse(times[0]) - 3_600_000; worldClock.seek(past); const subscribe = t.mock.method(worldClock, 'subscribe'); const gate = t.mock.method(worldClock, 'gate'); const h = layerHarness({ enable: false }); h.layer.getRowControls(); h.layer.getDiagnostics(); h.layer.setParams({ play: true, step: -1 }); assert.equal(subscribe.mock.callCount(), 0, 'off, no clock is built'); assert.equal(gate.mock.callCount(), 0); assert.equal(worldClock.isPlaying(), false); h.layer.destroy(); harnessed.delete(h.layer); assert.equal(worldClock.now(), past, 'never on, the world is where it was'); assert.equal(worldClock.isLive(), false); const on = layerHarness({ enable: false }); on.layer.enable(); assert.equal(subscribe.mock.callCount(), 1, 'built on first enable'); const update = on.layer.update(); await flush(); on.stages.at(-1)?.finish(); await update; on.layer.disable(); on.layer.enable(); assert.equal(subscribe.mock.callCount(), 1, 'built once'); on.layer.destroy(); harnessed.delete(on.layer); assert.equal( worldClock.isLive(), false, 'its own clock does not send it live', ); assert.equal(worldClock.now(), past); }); test('destroyed, a layer without a clock stays off: enabling it builds no clock', (t) => { const subscribe = t.mock.method(worldClock, 'subscribe'); const h = layerHarness(); assert.equal(subscribe.mock.callCount(), 1, 'its clock, built on enable'); h.layer.destroy(); harnessed.delete(h.layer); h.layer.enable(); assert.equal(subscribe.mock.callCount(), 1, 'no clock built after destroy'); assert.equal(worldClock.follows('weather-radar'), false); h.layer.setParams({ play: true }); assert.equal(worldClock.isPlaying(), false); }); test('with no frames yet there is no timeline, and a row plays nothing', () => { worldClock.setRate(604_800); const h = layerHarness({ feed: { getSnapshot: () => new Promise(() => {}) }, }); void h.layer.update(); assert.equal(worldClock.coverage(), null); h.layer.setParams({ play: true }); assert.equal(worldClock.isLive(), true); assert.equal(worldClock.isPlaying(), false); }); test('a row plays at the speed the world clock keeps, from the start at the end of the covered time', async () => { const h = layerHarness(); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; // A speed chosen on the timeline, while live. worldClock.setRate(3_600); h.layer.setParams({ play: true }); assert.equal(worldClock.isPlaying(), true); assert.equal(worldClock.getRate(), 3_600, 'played at the speed chosen'); assert.ok( worldClock.now() - Date.parse(times[0]) < 3_600_000, 'live, play starts at the start of the covered time', ); h.layer.setParams({ play: true }); assert.equal(worldClock.isPlaying(), false); // Paused at the end of the covered time (it reaches to now), play starts // again from the start, as the timeline's does. worldClock.seek(worldClock.wallNow() + 1_000); h.layer.setParams({ play: true }); assert.equal(worldClock.isPlaying(), true); assert.ok(worldClock.now() - Date.parse(times[0]) < 3_600_000); assert.equal(worldClock.getRate(), 3_600); worldClock.pause(); }); test('reduced motion offers no play; steps still move the world clock from frame to frame', async () => { const h = layerHarness({ reducedMotion: true }); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; assert.equal( h.layer.getRowControls().chips.some((chip) => chip.id === 'play'), false, ); // Play, which the row does not offer, does nothing while it is suspended. h.layer.setParams({ play: true }); assert.equal(worldClock.isPlaying(), false); assert.equal(worldClock.isLive(), true); // A step back from live goes to the newest frame, and the next one back // to the frame before it. h.layer.setParams({ step: -1 }); await flush(); assert.equal(worldClock.now(), Date.parse(times[2])); h.layer.setParams({ step: -1 }); await flush(); assert.equal(worldClock.now(), Date.parse(times[1])); assert.equal(h.stages.at(-1).time, times[1]); }); test('a row steps forward and plays from a past time through the world clock', async () => { const h = layerHarness(); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; worldClock.seek(Date.parse(times[0])); await flush(); h.layer.setParams({ step: 1 }); assert.equal(worldClock.now(), Date.parse(times[1])); assert.equal(worldClock.isPlaying(), false); await flush(); assert.equal(h.stages.at(-1).time, times[1]); h.layer.setParams({ step: 1 }); assert.equal(worldClock.now(), Date.parse(times[2])); h.layer.setParams({ step: 1 }); assert.equal( worldClock.now(), Date.parse(times[2]), 'no frame after the newest', ); worldClock.seek(Date.parse(times[1])); await flush(); h.layer.setParams({ play: true }); assert.equal(worldClock.isPlaying(), true); assert.equal(worldClock.getState().stepping, false); assert.ok( worldClock.now() - Date.parse(times[1]) < 1_000, 'away from live, play goes on from the time shown', ); h.layer.setParams({ step: 1 }); assert.equal(worldClock.isPlaying(), false, 'a step holds play'); assert.equal(worldClock.now(), Date.parse(times[2])); }); test('disable invalidates an abort-insensitive source result and an already staged frame', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const source = deferred(); let signal; const h = layerHarness({ feed: { getSnapshot(options) { signal = options.signal; return source.promise; }, }, }); const update = h.layer.update(); h.layer.disable(); assert.equal(signal.aborted, true); source.resolve(snapshot); assert.equal(await update, false); assert.equal(h.stages.length, 0); h.layer.enable(); const next = h.layer.update(); await flush(); assert.equal(h.stages.length, 1); h.layer.disable(); await next; await flush(); assert.equal(h.layer.getStats().count, 0); assert.equal(h.layer.getStats().loading, false); h.layer.destroy(); }); test('external abort cancels a staged renderer request and releases its observer and deadline', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const h = renderingHarness(); const controller = new AbortController(); const stage = h.rendering.setFrame(snapshot, times[0], { signal: controller.signal, }); const tile = deferred(); h.providers[0].response = tile; const requested = h.providers[0].requestImage(0, 0, 0, {}); const before = h.renders(); controller.abort(); assert.equal(await stage, false); assert.equal( h.providers[0].layer.removed, true, 'removing the layer cancels its requests in flight', ); assert.equal(h.layers.length, 0); assert.equal(h.postRender.size, 0); assert.equal(h.providers[0].errorEvent.size, 0); assert.ok( h.renders() > before, 'cancellation requests a Cesium scheduler update', ); tile.resolve({}); await requested; t.mock.timers.tick(30_000); assert.equal(h.rendering.getDiagnostics().time, null); await assert.rejects( h.rendering.setFrame(snapshot, times[1], { signal: controller.signal }), { name: 'AbortError' }, ); assert.equal( h.providers.length, 1, 'already-aborted work creates no provider', ); h.rendering.clear(); }); test('update cancellation reaches imagery after source acquisition has completed', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const h = layerHarness(); const controller = new AbortController(); const update = h.layer.update(null, { signal: controller.signal }); await flush(); assert.equal(h.stages.length, 1); assert.equal(h.stages[0].signal.aborted, false); controller.abort(); assert.equal(await update, false); assert.equal(h.stages[0].signal.aborted, true); assert.equal(h.layer.getStats().count, 0); assert.equal(h.layer.getStats().loading, false); h.layer.destroy(); }); test('superseding a pending stage preserves the newer manifest loading state', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const later = deferred(); let fetches = 0; const h = layerHarness({ feed: { getSnapshot() { return ++fetches === 1 ? Promise.resolve(snapshot) : later.promise; }, }, }); const old = h.layer.update(); await flush(); const newer = h.layer.update(); await flush(); assert.equal( await old, true, 'replacement is accepted by the enable lifecycle', ); assert.equal( h.layer.getStats().loading, true, 'old stage finally must not clear a newer source loading state', ); later.resolve(snapshot); await flush(); h.stages.at(-1).finish(); assert.equal(await newer, true); assert.equal(h.layer.getStats().loading, false); h.layer.destroy(); }); test('global infrared is acquired before staging and cropped from one processed mosaic', async () => { let fetches = 0; const decode = deferred(); const h = renderingHarness({ fetchImpl: async () => { fetches++; return mockResponse(); }, decodeImage: () => decode.promise, }); const task = h.rendering.setFrame( { ...snapshot, product: 'clouds' }, times[0], ); await flush(); assert.equal(h.layers.length, 0); assert.equal(h.rendering.getDiagnostics().loading, true); assert.deepEqual(h.rendering.getDiagnostics().mosaic, { fetched: true, decodeMs: null, cached: false, }); decode.resolve({ width: 2048, height: 1024 }); await flush(); const provider = h.providers[0]; assert.equal(provider.spec.kind, 'canvas'); assert.equal(provider.spec.maxLevel, 3); assert.equal(provider.spec.tileSize, 256); assert.equal(provider.spec.shows, 'clouds'); assert.equal(provider.spec.tiling, 'geographic'); assert.deepEqual(provider.spec.rectangle, snapshot.bounds); const first = await provider.requestImage(0, 0, 0); const next = await provider.requestImage(1, 0, 0); assert.equal(first.source, next.source); assert.deepEqual( first.source.pixels, new Uint8ClampedArray([194, 100, 0, 98]), ); assert.equal(fetches, 1); h.settle(); assert.equal(await task, true); assert.equal(h.rendering.getDiagnostics().mosaic.fetched, true); assert.equal(typeof h.rendering.getDiagnostics().mosaic.decodeMs, 'number'); h.rendering.clear(); }); test('coverage navigation requires the shared shell handoff and detaches cleanly', async () => { const h = layerHarness(); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; assert.equal( h.layer.getRowControls().chips.find((chip) => chip.id === 'coverage') .disabled, true, ); let handoffs = 0; h.layer.attachShellServices({ runNavigation(navigate) { handoffs++; assert.equal(typeof navigate, 'function'); }, }); h.layer.setParams({ focus: true }); assert.equal(handoffs, 1); h.layer.attachShellServices(null); h.layer.setParams({ focus: true }); assert.equal(handoffs, 1); h.layer.destroy(); }); test('manifest refresh during a history stage restages the same time and does not strand loading controls', async () => { const h = layerHarness(); const first = h.layer.update(); await flush(); h.stages[0].finish(); await first; worldClock.seek(Date.parse(times[1])); await flush(); assert.equal(h.layer.getStats().loading, true); const refreshed = h.layer.update(); await flush(); assert.equal(h.stages.length, 3); assert.equal(h.stages[1].signal.aborted, true); assert.equal(h.stages[2].time, times[1], 'the refresh keeps the time'); h.stages[2].finish(); await refreshed; await flush(); assert.equal(h.layer.getStats().loading, false); assert.equal(h.layer.getStats().observedAt, times[1]); assert.equal( h.layer.getRowControls().chips.some((chip) => chip.id === 'previous'), false, ); h.layer.destroy(); }); test('historical observations do not relabel a fresh lightning feed as stale', async () => { const now = Date.now(); const old = new Date(now - 90 * 60_000).toISOString(); const recent = new Date(now - 5 * 60_000).toISOString(); const h = layerHarness({ id: 'weather-lightning', feed: { getSnapshot: async () => ({ ...snapshot, product: 'lightning', times: [old, recent], latest: recent, }), }, }); const first = h.layer.update(); await flush(); h.stages[0].finish(); await first; worldClock.seek(Date.parse(old)); await flush(); h.stages[1].finish(); await flush(); assert.equal(h.layer.getStats().stale, false); assert.match(h.layer.getRowControls().summary.detail, /History/); h.layer.destroy(); }); test('history loading updates an existing info line and preserves summary status', async (t) => { t.mock.method(Date, 'now', () => Date.parse(times[2])); const h = layerHarness(); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; h.layer.setParams({ step: -1 }); await flush(); const loading = h.layer.getRowControls(); assert.match(loading.info, /History: [^\n]+\n[^\n]+ · loading/); assert.equal(loading.summary.status, 'Loading next frame…'); h.stages.at(-1).finish(); await flush(); const ready = h.layer.getRowControls(); assert.equal(ready.info.split('\n').length, loading.info.split('\n').length); assert.doesNotMatch(ready.info, / · loading/); h.layer.destroy(); }); test('no host cancels a globe stage and hides the frame; weather keeps its order', async () => { let host; const h = renderingHarness({ getHost: () => host }); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; const stage = h.rendering.setFrame(snapshot, times[0]); h.settle(); assert.equal(await stage, true); const radar = h.layers[0]; const other = (zOrder) => h.globe.imagery.add({ kind: 'xyz', url: 'https://o.invalid', zOrder }); const cloud = other(WEATHER_IMAGERY_Z.clouds); const lightning = other(WEATHER_IMAGERY_Z.lightning); const overlay = other(undefined); assert.equal(radar.drapeOn, 'surface'); assert.deepEqual(h.layers, [overlay, cloud, radar, lightning]); assert.deepEqual(h.credits.owed, [{ text: 'NOAA nowCOAST · NWS/OAR MRMS' }]); const incoming = h.rendering.setFrame(snapshot, times[1]); host = { collection: null, kind: 'none' }; assert.equal(h.rendering.rehome(), true); assert.equal(await incoming, false); assert.deepEqual(h.layers, [overlay, cloud, radar, lightning]); assert.equal(radar.show, false, 'nothing draws without a host'); assert.deepEqual(h.credits.owed, [], 'nor is its credit owed'); assert.equal(await h.rendering.setFrame(snapshot, times[2]), false); assert.equal(h.rendering.getDiagnostics().error, NO_IMAGERY_HOST); assert.equal(h.rendering.getDiagnostics().time, times[0]); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; h.rendering.rehome(); assert.equal(radar.show, true); assert.equal(h.credits.owed.length, 1); assert.deepEqual(h.layers, [overlay, cloud, radar, lightning]); assert.equal(h.rendering.getDiagnostics().error, null); h.rendering.clear(); assert.deepEqual(h.layers, [overlay, cloud, lightning]); assert.equal(radar.removed, true); assert.deepEqual(h.credits.owed, []); }); const shellDecode = async () => ({ width: 4096, height: 2048, close() {} }); test('the tileset host draws a raised shell and drapes nothing, at any camera height', async () => { const tiles = new ImageryLayerCollection(); const h = renderingHarness({ getHost: () => ({ collection: tiles, kind: 'tileset' }), decodeImage: shellDecode, }); h.viewer.camera = { moveEnd: event(), positionCartographic: { height: 1200 }, }; const stage = h.rendering.setFrame(snapshot, times[0]); await flush(); assert.equal(tiles.length, 0); assert.equal(h.layers.length, 0); assert.equal(h.providers.length, 0); assert.equal(h.shells().length, 1); assert.equal(h.rendering.getDiagnostics().loading, true); h.renderShells(); assert.equal(await stage, true); const diagnostics = h.rendering.getDiagnostics(); assert.equal(diagnostics.host, 'shell'); assert.equal(diagnostics.height, 6_200); assert.equal(diagnostics.time, times[0]); assert.equal(diagnostics.error, null); assert.equal( h.viewer.camera.moveEnd.size, 1, 'one camera listener, for the detail window only', ); assert.equal(await h.rendering.prefetch(snapshot, times[1]), true); assert.equal(h.rendering.getDiagnostics().cache.mosaics, 2); h.rendering.clear(); assert.equal(h.shells().length, 0); assert.equal(h.postRender.size, 0); assert.equal(h.viewer.camera.moveEnd.size, 0); assert.equal(h.rendering.getDiagnostics().cache.mosaics, 0); }); test('a switch to 3D Tiles windows the current view; the globe host never requests a window', async () => { let host; const urls = []; const h = renderingHarness({ getHost: () => host, decodeImage: shellDecode, fetchImpl: async (url) => { urls.push(url); return mockResponse(); }, }); h.viewer.camera = { moveEnd: event(), computeViewRectangle: () => Cesium.Rectangle.fromDegrees(-100, 35, -98, 36), }; host = { collection: h.viewer.imageryLayers, kind: 'globe' }; const globe = h.rendering.setFrame(snapshot, times[0]); h.settle(); assert.equal(await globe, true); assert.equal(await h.rendering.prefetch(snapshot, times[1]), true); h.viewer.camera.moveEnd.emit(); await flush(); assert.equal(h.shells().length, 0); assert.equal(h.viewer.camera.moveEnd.size, 0); assert.equal(h.rendering.getDiagnostics().shell, undefined); assert.ok(urls.length > 0); assert.ok(urls.every((url) => !url.includes('bbox='))); host = { collection: new ImageryLayerCollection(), kind: 'tileset' }; assert.equal(h.rendering.rehome(), true); await flush(); h.renderShells(); await flush(); h.renderShells(); const detail = urls.filter((url) => url.includes('bbox=')); assert.deepEqual( detail.map((url) => new URL(url, 'https://example.test').searchParams.get('bbox'), ), ['-102,34,-96,37'], ); const diagnostics = h.rendering.getDiagnostics(); assert.equal(diagnostics.time, times[0]); assert.equal(diagnostics.shell.detail.ready, true); assert.equal(h.shells().length, 1, 'the detail draws on the shell surface'); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; assert.equal(h.rendering.rehome(), true); assert.equal(h.shells().length, 0, 'the shell surface goes with the host'); await flush(); h.settle(); await flush(); assert.equal(h.rendering.getDiagnostics().host, 'globe'); assert.equal(h.rendering.getDiagnostics().loading, false); assert.equal(h.viewer.camera.moveEnd.size, 0); assert.equal(urls.filter((url) => url.includes('bbox=')).length, 1); h.rendering.clear(); }); test('host switches tear one renderer down and restage the retained frame on the other', async () => { let host; const tiles = new ImageryLayerCollection(); const h = renderingHarness({ getHost: () => host, decodeImage: async () => ({ width: 2048, height: 1024, close() {} }), }); const clouds = { ...snapshot, product: 'clouds' }; host = { collection: h.viewer.imageryLayers, kind: 'globe' }; h.rendering.setAlpha(0.4); const first = h.rendering.setFrame(clouds, times[1], { infrared: 'full' }); await flush(); h.settle(); assert.equal(await first, true); const layer = h.layers[0]; host = { collection: tiles, kind: 'tileset' }; assert.equal(h.rendering.rehome(), true); assert.equal(h.layers.length, 0); assert.equal(layer.removed, true); assert.equal(tiles.length, 0); assert.equal( h.rendering.getDiagnostics().time, times[1], 'the retained time is reported while restaging', ); assert.equal(h.rendering.getDiagnostics().loading, true); await flush(); const [shell] = h.shells(); h.renderShells(); await flush(); let diagnostics = h.rendering.getDiagnostics(); assert.equal(diagnostics.host, 'shell'); assert.equal(diagnostics.height, 5_500); assert.equal(diagnostics.loading, false); assert.equal(diagnostics.time, times[1]); assert.equal(diagnostics.infrared, 'full'); assert.equal(shell.appearance.material.uniforms.alpha, 0.4); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; assert.equal(h.rendering.rehome(), true); assert.equal(shell.destroyed, true); assert.equal(shell.appearance.material.destroyed, true); assert.equal(h.shells().length, 0); assert.equal(h.rendering.getDiagnostics().time, times[1]); await flush(); assert.equal(h.layers.length, 1); h.settle(); await flush(); diagnostics = h.rendering.getDiagnostics(); assert.equal(diagnostics.host, 'globe'); assert.equal(diagnostics.loading, false); assert.equal(diagnostics.time, times[1]); assert.equal(diagnostics.infrared, 'full'); assert.equal(h.layers[0].alpha, 0.4); assert.equal(h.layers[0].spec.tileSize, 256); h.rendering.clear(); assert.equal(h.layers.length, 0); assert.equal(h.postRender.size, 0); }); test('a host without imagery keeps the active shell and its frame', async () => { let host = { collection: new ImageryLayerCollection(), kind: 'tileset' }; let fetches = 0; const h = renderingHarness({ getHost: () => host, decodeImage: shellDecode, fetchImpl: async () => { fetches++; return mockResponse(); }, }); const stage = h.rendering.setFrame(snapshot, times[0]); await flush(); h.renderShells(); assert.equal(await stage, true); const [shell] = h.shells(); host = { collection: null, kind: 'none' }; h.rendering.rehome(); assert.equal(shell.show, false); assert.equal(shell.destroyed, false); assert.equal(h.rendering.getDiagnostics().time, times[0]); assert.equal(h.rendering.getDiagnostics().error, NO_IMAGERY_HOST); assert.equal(await h.rendering.setFrame(snapshot, times[1]), false); host = { collection: new ImageryLayerCollection(), kind: 'tileset' }; h.rendering.rehome(); assert.equal(shell.show, true); assert.deepEqual(h.shells(), [shell]); assert.equal(fetches, 1); assert.equal(h.rendering.getDiagnostics().error, null); h.rendering.setHidden(true); assert.equal(shell.show, false); assert.equal(h.rendering.getDiagnostics().time, null); h.rendering.setHidden(false); assert.equal(shell.show, true); h.rendering.clear(); assert.equal(h.shells().length, 0); }); test('each product owns its shell height; a product change replaces the shell', async () => { let width = 2048; const h = renderingHarness({ getHost: () => ({ collection: null, kind: 'tileset' }), decodeImage: async () => ({ width, height: width / 2, close() {} }), }); const global = h.rendering.setFrame( { ...snapshot, product: 'clouds' }, times[0], ); await flush(); h.renderShells(); assert.equal(await global, true); const [first] = h.shells(); assert.equal(h.rendering.getDiagnostics().height, 5_500); width = 4096; const lightning = h.rendering.setFrame( { ...snapshot, product: 'lightning' }, times[0], ); assert.equal(first.destroyed, true); await flush(); h.renderShells(); assert.equal(await lightning, true); assert.equal(h.rendering.getDiagnostics().height, 6_600); assert.equal(h.rendering.getDiagnostics().product, 'lightning'); assert.equal(h.shells().length, 1); h.rendering.clear(); }); test('a stage without a current frame is cancelled on host change and detached frames are destroyed', async () => { const tiles = new ImageryLayerCollection(); let host = { collection: tiles, kind: 'tileset' }; const h = renderingHarness({ getHost: () => host }); const first = h.rendering.setFrame(snapshot, times[0]); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; h.rendering.rehome(); assert.equal(await first, false); assert.equal(tiles.length, 0); const ready = h.rendering.setFrame(snapshot, times[1]); h.settle(); await ready; const layer = h.layers[0]; host = { collection: null, kind: 'none' }; h.rendering.rehome(); h.rendering.clear(); assert.equal(layer.removed, true); }); for (const product of ['clouds', 'clouds-regional', 'radar', 'lightning']) { test(`${product} does not use a hard layer alpha cut on the globe host`, async () => { const collection = new ImageryLayerCollection(); const h = renderingHarness({ getHost: () => ({ collection, kind: 'globe' }), }); const stage = h.rendering.setFrame({ ...snapshot, product }, times[0]); await flush(); const layer = h.layers[0]; assert.equal(layer.spec.colorToAlpha, undefined); assert.equal(layer.alpha, 0); h.rendering.clear(); assert.equal(await stage, false); }); } test('throttled tiles are fetched again by the renderer; a tile that still fails fails the frame', async () => { let now = 0; const h = renderingHarness({ now: () => now }); const stage = h.rendering.setFrame(snapshot, times[0]); assert.deepEqual(h.providers[0].spec.retryStatuses, [429, 503]); h.providers[0].response = deferred(); const loaded = h.providers[0].requestImage(0, 0, 0, {}); h.providers[0].response.resolve({}); await loaded; now = 250; h.settle(); assert.equal(await stage, true); const exhausted = h.rendering.setFrame(snapshot, times[1]); h.providers[1].errorEvent.emit({ error: { statusCode: 429 }, x: 0, y: 0 }); h.settle(); assert.equal(await exhausted, false); assert.equal(h.rendering.getDiagnostics().time, times[0]); h.rendering.clear(); }); test('404 fails a frame without retry', async () => { const h = renderingHarness(); const stage = h.rendering.setFrame(snapshot, times[0]); const error = { error: { statusCode: 404 }, timesRetried: 0, retry: false }; h.providers[0].errorEvent.emit(error); h.settle(); assert.equal(error.retry, false); assert.equal(await stage, false); h.rendering.clear(); }); test('no host holds the shown history frame, refreshes metadata, and restores the retained time', async () => { let refreshes = 0; const h = layerHarness({ feed: { getSnapshot: async () => { refreshes++; return snapshot; }, }, }); let host = { collection: {}, kind: 'tileset' }; h.layer.attachShellServices({ imageryHost: () => host }); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; worldClock.seek(Date.parse(times[0])); await flush(); assert.equal(h.stages.length, 2); h.stages[1].finish(); await flush(); host = { collection: null, kind: 'none' }; h.eventTarget.emit('gev:map-stack-changed'); await flush(); assert.equal(h.layer.getRowControls().summary.status, NO_IMAGERY_HOST); assert.equal(h.layer.getRowControls().info, NO_IMAGERY_HOST); await h.layer.update(); assert.equal(refreshes, 2); assert.equal(h.stages.length, 2, 'nothing stages without a host'); host = { collection: {}, kind: 'globe' }; h.eventTarget.emit('gev:map-stack-changed'); await flush(); assert.equal(h.stages.at(-1).time, times[0], 'the retained time restages'); h.layer.destroy(); assert.equal(h.eventTarget.size, 0); }); test('host restore through update stages latest after a no-host start', async () => { const h = layerHarness(); let host = { collection: null, kind: 'none' }; h.layer.attachShellServices({ imageryHost: () => host }); await h.layer.update(); assert.equal(h.stages.length, 0); host = { collection: {}, kind: 'tileset' }; const update = h.layer.update(); await flush(); assert.equal(h.stages[0].time, snapshot.latest); h.stages[0].finish(); await update; assert.notEqual(h.layer.getRowControls().summary.status, NO_IMAGERY_HOST); h.layer.destroy(); }); test('the global infrared mosaic draws through the real Cesium globe port', async () => { const scene = { imageryLayers: new Cesium.ImageryLayerCollection(), globe: { show: true, tilesLoaded: true }, primitives: { length: 0, get: () => undefined }, }; const { port } = createCesiumGlobe( { scene }, { capabilities: new Set(['imageHooks', 'imageryOnTiles']), requestRender: () => {}, }, ); const h = renderingHarness({ globeOf: () => port }); const stage = h.rendering.setFrame( { ...snapshot, product: 'clouds', bounds: { west: -180, south: -60, east: 180, north: 60 }, }, times[0], ); await flush(); const layer = scene.imageryLayers.get(0); const provider = layer.imageryProvider; assert.ok(provider.tilingScheme instanceof Cesium.GeographicTilingScheme); assert.equal(provider.maximumLevel, 3); assert.equal(provider.tileWidth, 256); assert.equal(provider.tileHeight, 256); assert.equal(provider.tilingScheme.getNumberOfXTilesAtLevel(0), 2); assert.equal(provider.tilingScheme.getNumberOfYTilesAtLevel(0), 1); assert.ok( Cesium.Rectangle.equals( provider.rectangle, Cesium.Rectangle.fromDegrees(-180, -60, 180, 60), ), ); assert.equal(layer.colorToAlpha, undefined); assert.equal(layer.alpha, 0, 'staged transparent'); h.rendering.clear(); assert.equal(scene.imageryLayers.length, 0); assert.equal(await stage, false); }); for (const [id, product] of [ ['weather-radar', 'radar'], ['weather-satellite', 'clouds-regional'], ['weather-satellite', 'clouds'], ['weather-lightning', 'lightning'], ]) { test(`${product} shows on 3D Tiles at street level and keeps its history through host changes`, async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); t.mock.method(Date, 'now', () => Date.parse(times[2])); const size = product === 'clouds' ? { width: 2048, height: 1024 } : { width: 4096, height: 2048 }; let host; const h = renderingHarness({ getHost: () => host, decodeImage: async () => ({ ...size, close() {} }), }); host = { collection: new ImageryLayerCollection(), kind: 'tileset' }; const camera = { moveEnd: event(), positionCartographic: { height: 1200 }, }; h.viewer.camera = camera; bindRenderer(h.viewer, { camera: cameraOver(h.viewer) }); const events = target(); const layer = createWeatherLayer({ id, feed: { getSnapshot: async () => ({ ...snapshot, product }) }, createRendering: () => h.rendering, documentRef: target({ hidden: false }), eventTarget: events, matchMedia: () => target({ matches: false }), }); layer.init(h.viewer); layer.attachShellServices({ imageryHost: () => host }); layer.setParams({ product }); layer.enable(); const update = layer.update(); await flush(); h.renderShells(); await update; assert.equal(layer.getDiagnostics().time, times[2]); assert.equal(layer.getDiagnostics().host, 'shell'); assert.equal(layer.getRowControls().summary.status, null); assert.doesNotMatch(layer.getRowControls().info, /Hidden/); const [shell] = h.shells(); assert.equal(shell.show, true); worldClock.seek(Date.parse(times[0])); await flush(); assert.equal( layer.getDiagnostics().time, times[0], 'history moves at street level', ); camera.positionCartographic.height = 59_999; camera.moveEnd.emit(); assert.equal(shell.show, true, 'no height gate'); host = { collection: null, kind: 'none' }; events.emit('gev:map-stack-changed'); assert.equal(shell.show, false); assert.equal(layer.getRowControls().summary.status, NO_IMAGERY_HOST); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; events.emit('gev:map-stack-changed'); assert.equal(shell.destroyed, true); assert.equal( layer.getDiagnostics().time, times[0], 'the switch restages the shown history frame', ); await flush(); h.settle(); await flush(); assert.equal(layer.getDiagnostics().host, 'globe'); assert.equal(layer.getDiagnostics().time, times[0]); assert.equal(layer.getDiagnostics().loading, false); layer.destroy(); assert.equal(camera.moveEnd.size, 0); assert.equal(events.size, 0); assert.equal(h.shells().length, 0); assert.equal(h.postRender.size, 0); }); } for (const outcome of [ 'fetch failure', 'decode failure', 'timeout', 'abort', 'supersede', 'rehome', ]) { test(`mosaic ${outcome} retains the displayed frame and never installs a late decode`, async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const decode = deferred(); let signal, closed = 0, host; const h = renderingHarness({ getHost: () => host, fetchImpl: async (_url, options) => { signal = options.signal; if (outcome === 'fetch failure') throw new Error('offline'); return mockResponse(); }, decodeImage: () => decode.promise, }); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; const first = h.rendering.setFrame(snapshot, times[0]); h.settle(); await first; const original = h.layers[0]; const controller = new AbortController(); const pending = h.rendering.setFrame( { ...snapshot, product: 'clouds' }, times[1], { signal: controller.signal }, ); await flush(); assert.deepEqual(h.layers, [original]); if (outcome === 'decode failure') decode.reject(new Error('bad png')); if (outcome === 'timeout') t.mock.timers.tick(25_000); if (outcome === 'abort') controller.abort(); if (outcome === 'supersede') assert.equal(await h.rendering.setFrame(snapshot, times[0]), true); if (outcome === 'rehome') { host = { collection: null, kind: 'none' }; h.rendering.rehome(); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; h.rendering.rehome(); } assert.equal(await pending, false); assert.equal(signal.aborted, true); assert.equal(h.rendering.getDiagnostics().time, times[0]); assert.equal(original.alpha, 0.7); if (outcome !== 'decode failure') { decode.resolve({ width: 2048, height: 1024, close() { closed++; }, }); await flush(); if (outcome !== 'fetch failure') assert.equal(closed, 1); } assert.equal(h.layers.length, 1); h.rendering.clear(); assert.equal(h.postRender.size, 0); }); } test('regional transfer preserves deferrals, original Request, rejection and cancellation', async () => { const h = renderingHarness(); const stage = h.rendering.setFrame( { ...snapshot, product: 'clouds-regional' }, times[0], ); const provider = h.providers[0]; const request = {}; assert.equal(provider.requestImage(1, 2, 3, request), undefined); assert.deepEqual(provider.requestArgs, [1, 2, 3, request]); const image = { width: 256, height: 256 }; provider.response = { promise: Promise.resolve(image) }; const processed = await provider.requestImage(1, 2, 3, request); assert.equal(processed.source, image); assert.deepEqual([...processed.pixels], [194, 100, 0, 98]); const error = new Error('cancelled upstream'); provider.response = { promise: Promise.reject(error) }; await assert.rejects( provider.requestImage(0, 0, 0, request), (cause) => cause === error, ); provider.response = deferred(); const late = provider.requestImage(0, 0, 0, request); h.rendering.clear(); assert.equal(provider.layer.removed, true, 'its requests are cancelled'); provider.response.resolve(image); assert.equal(await late, image, 'closed frames do not process late images'); assert.equal(await stage, false); }); test('regional tiles are processed upright, as the renderer hands them over', async () => { const hadBitmap = Object.hasOwn(globalThis, 'ImageBitmap'); const previous = globalThis.ImageBitmap; globalThis.ImageBitmap = class ImageBitmap { width = 256; height = 256; }; try { const h = renderingHarness(); void h.rendering.setFrame( { ...snapshot, product: 'clouds-regional' }, times[0], ); const provider = h.providers[0]; // `tileTransform` is given the tile upright, whatever it was decoded as. provider.response = { promise: Promise.resolve(new ImageBitmap()) }; const bitmapTile = await provider.requestImage(0, 0, 0, {}); assert.equal(bitmapTile.drawnWith, null); provider.response = { promise: Promise.resolve({ width: 256, height: 256 }), }; const imageTile = await provider.requestImage(1, 0, 0, {}); assert.equal(imageTile.drawnWith, null); h.rendering.clear(); } finally { if (hadBitmap) globalThis.ImageBitmap = previous; else delete globalThis.ImageBitmap; } }); for (const kind of ['globe']) { test(`infrared mode restages the same time on ${kind}, retaining the old layer for one rendered frame`, async () => { let host, now = 0; const h = renderingHarness({ getHost: () => host, now: () => now }); host = { collection: h.viewer.imageryLayers, kind }; const clouds = { ...snapshot, product: 'clouds' }; const first = h.rendering.setFrame(clouds, times[0]); await flush(); await h.providers[0].requestImage(0, 0, 0); now = 250; h.settle(); await first; const previous = h.layers[0]; assert.equal(await h.rendering.setFrame(clouds, times[0]), true); assert.equal(h.providers.length, 1); const full = h.rendering.setFrame(clouds, times[0], { infrared: 'full' }); await flush(); const tile = await h.providers[1].requestImage(0, 0, 0); assert.deepEqual([...tile.source.pixels], [194, 100, 0, 200]); now = 500; h.settle(); assert.equal(await full, true); assert.equal(h.layers.length, 2); assert.equal(h.layers[1].alpha, 0.7); assert.equal(previous.removed, false); assert.equal(h.rendering.getDiagnostics().infrared, 'full'); h.postRender.emit(); assert.equal(h.layers.length, 1); assert.equal(previous.removed, true); h.rendering.clear(); assert.equal(h.postRender.size, 0); }); } test('satellite mode chips restage history without changing time or latest-follow intent', async () => { const h = layerHarness({ id: 'weather-satellite' }); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; worldClock.seek(Date.parse(times[1])); await flush(); h.stages[1].finish(); await flush(); h.layer.setParams({ infrared: 'full' }); await flush(); assert.equal(h.stages[2].time, times[1]); assert.equal(h.stages[2].infrared, 0); assert.equal(h.layer.getParams().infrared, 0); assert.deepEqual( h.layer .getRowControls() .chips.slice(0, 4) .map((chip) => chip.label), ['N. America', 'Global', 'Clouds only', 'Full'], ); h.stages[2].finish(); await flush(); assert.equal(h.layer.getDiagnostics().followLatest, false); assert.equal(h.layer.getDiagnostics().time, times[1]); h.layer.setParams({ infrared: 'invalid' }); assert.equal(h.layer.getParams().infrared, 0); assert.equal(h.stages.length, 3); h.layer.destroy(); }); test('satellite cloud filter spans Full to Clouds only without changing layer opacity', () => { const h = layerHarness({ id: 'weather-satellite' }); assert.equal(h.layer.getParams().infrared, 100); assert.equal(h.layer.getParams().opacity, 'strong'); assert.equal(h.getAlpha(), 0.7); const setting = h.layer .getRowControls() .summary.settings.find(({ id }) => id === 'image'); assert.equal(setting.range.param, 'infrared'); assert.equal(setting.range.value, 100); assert.equal(setting.range.min, 0); assert.equal(setting.range.max, 100); assert.equal(setting.range.step, 1); assert.equal(setting.range.commitOnChange, true); const full = h.layer.getRowControls().chips.find(({ id }) => id === 'full'); h.layer.setParams(full.params); assert.equal(h.layer.getParams().infrared, 0); assert.equal(h.getAlpha(), 0.7); assert.equal( h.layer.getRowControls().chips.find(({ id }) => id === 'full').active, true, ); h.layer.setParams({ infrared: 53 }); assert.equal(h.layer.getParams().infrared, 53); assert.equal(h.getAlpha(), 0.7, 'filter strength is not overall opacity'); assert.equal( h.layer.getRowControls().summary.settings.find(({ id }) => id === 'image') .range.value, 53, ); h.layer.setParams({ opacity: 'light' }); assert.equal(h.layer.getParams().opacity, 'light'); assert.equal( h.getAlpha(), 0.4, 'Soft remains the independent opacity preset', ); h.layer.setParams({ infrared: 101 }); assert.equal( h.layer.getParams().infrared, 53, 'invalid filter values are ignored', ); h.layer.destroy(); }); test('a rapid third selection waits for retirement before installing, and clear cancels that wait', async () => { for (const clear of [false, true]) { const h = renderingHarness(); const first = h.rendering.setFrame(snapshot, times[0]); h.settle(); await first; const second = h.rendering.setFrame(snapshot, times[1]); h.settle(); await second; assert.equal(h.layers.length, 2); const third = h.rendering.setFrame(snapshot, times[2]); assert.equal(h.layers.length, 2); assert.equal( h.providers.length, 2, 'third provider waits for outgoing retirement', ); if (clear) { h.rendering.clear(); assert.equal(await third, false); h.postRender.emit(); assert.equal(h.layers.length, 0); assert.equal(h.postRender.size, 0); } else { h.postRender.emit(); assert.equal(h.layers.length, 2); assert.equal(h.providers.length, 3); h.settle(); assert.equal(await third, true); h.postRender.emit(); assert.equal(h.layers.length, 1); h.rendering.clear(); } } }); test('a delayed installation failure retains the replacement and does not throw from postRender', async () => { const h = renderingHarness(); for (const time of times.slice(0, 2)) { const stage = h.rendering.setFrame(snapshot, time); h.settle(); assert.equal(await stage, true); } const third = h.rendering.setFrame(snapshot, times[2]); h.globe.imagery.add = () => { throw new Error('upload unavailable'); }; assert.doesNotThrow(() => h.postRender.emit()); assert.equal(await third, false); assert.equal(h.layers.length, 1); assert.equal(h.layers[0].alpha, 0.7); assert.equal(h.rendering.getDiagnostics().time, times[1]); h.rendering.clear(); }); test('a row steps the world clock through every registered observation; missing frames hide and latest goes live', async (t) => { const clock = createWeatherClock(); const radar = layerHarness({ clock }); const satellite = layerHarness({ clock, id: 'weather-satellite', feed: { getSnapshot: async () => ({ ...snapshot, product: 'clouds-regional', times: [times[1]], latest: times[1], }), }, }); t.after(() => { radar.layer.destroy(); satellite.layer.destroy(); clock.destroy(); }); const updates = [radar.layer.update(), satellite.layer.update()]; await flush(); radar.stages.at(-1).finish(); satellite.stages.at(-1).finish(); await Promise.all(updates); let satelliteChanges = 0; satellite.layer.setRowControlsListener(() => satelliteChanges++); const transport = (h) => h.layer .getRowControls() .chips.filter(({ id }) => ['previous', 'play', 'next', 'latest'].includes(id), ); // A step back from live goes to the newest frame, and the next one back // to the frame before it. radar.layer.setParams({ step: -1 }); await flush(); assert.equal(clock.getState().target, times[2]); assert.equal(clock.world.isPlaying(), false); for (const h of [radar, satellite]) h.stages.at(-1)?.finish(); await flush(); radar.layer.setParams({ step: -1 }); await flush(); assert.equal(clock.getState().target, times[1]); assert.equal(radar.stages.at(-1).time, times[1]); assert.equal(satellite.stages.at(-1).time, times[1]); radar.stages.at(-1).finish(); satellite.stages.at(-1).finish(); await flush(); assert.match(satellite.layer.getRowControls().summary.detail, /synced/); assert.ok(satelliteChanges > 0); assert.deepEqual(transport(radar), []); assert.deepEqual(transport(satellite), []); satellite.layer.setParams({ step: -1 }); await flush(); radar.stages.at(-1).finish(); await flush(); assert.equal(clock.getState().target, times[0]); assert.equal(satellite.layer.getDiagnostics().hidden, true); assert.match( satellite.layer.getRowControls().summary.status, /No frame within 30 min of 09-15 20:00 UTC/, ); radar.layer.setParams({ step: 1 }); await flush(); radar.stages.at(-1).finish(); satellite.stages.at(-1).finish(); await flush(); assert.equal(satellite.layer.getDiagnostics().hidden, false); radar.layer.setParams({ latest: true }); await flush(); radar.stages.at(-1).finish(); satellite.stages.at(-1).finish(); await flush(); assert.deepEqual( [radar.layer.getDiagnostics().time, satellite.layer.getDiagnostics().time], [times[2], times[1]], ); assert.deepEqual(radar.layer.getDiagnostics().clock, { mode: 'latest', target: null, playing: false, }); assert.deepEqual( radar.layer.getParams(), { opacity: 'strong' }, 'history is never serialized', ); satellite.layer.disable(); assert.equal(clock.getState().products.length, 1); }); test('a row’s play and latest move the world clock as its timeline does', async (t) => { const clock = createWeatherClock(); const { world } = clock; const h = layerHarness({ clock }); t.after(() => { h.layer.destroy(); clock.destroy(); }); const update = h.layer.update(); await flush(); h.stages.at(-1).finish(); await update; h.layer.setParams({ play: true }); assert.equal(world.isPlaying(), true); assert.equal(world.getState().stepping, false, 'the world plays on its own'); assert.ok( world.now() - Date.parse(times[0]) < 1_000, 'from the start when live', ); h.layer.setParams({ play: true }); assert.equal(world.isPlaying(), false); h.layer.setParams({ latest: true }); assert.equal(world.isLive(), true); await flush(); assert.equal(clock.getState().mode, 'latest'); }); test('history manifest expiry hides imagery without jumping to latest; host resume keeps the target', async (t) => { const clock = createWeatherClock(); let value = snapshot; const h = layerHarness({ clock, feed: { getSnapshot: async () => value } }); t.after(() => { h.layer.destroy(); clock.destroy(); }); let update = h.layer.update(); await flush(); h.stages.at(-1).finish(); await update; const history = seekTo(clock, times[0]); await flush(); h.stages.at(-1).finish(); await history; value = { ...snapshot, times: [times[2]] }; await h.layer.update(); assert.equal(h.layer.getDiagnostics().hidden, true); assert.equal(clock.getState().target, times[0]); h.documentRef.hidden = true; h.documentRef.emit('visibilitychange'); await flush(); assert.deepEqual(clock.getTimeline(), []); h.documentRef.hidden = false; h.documentRef.emit('visibilitychange'); await flush(); assert.equal(clock.getState().target, times[0]); assert.equal(h.layer.getDiagnostics().hidden, true); value = snapshot; update = h.layer.update(); await flush(); h.stages.at(-1).finish(); await update; assert.equal(h.layer.getDiagnostics().time, times[0]); }); test('hidden renderer retains the frame without displaying it and rehome cannot reveal it', async () => { const h = renderingHarness(); const first = h.rendering.setFrame(snapshot, times[0]); h.settle(); await first; const layer = h.layers[0]; const pending = h.rendering.setFrame(snapshot, times[1]); h.rendering.setHidden(true); assert.equal(await pending, false); assert.equal(h.layers.length, 1); assert.equal(h.layers[0], layer); assert.equal(layer.show, false); assert.equal(h.rendering.getDiagnostics().time, null); h.rendering.rehome(); assert.equal(layer.show, false); h.rendering.setHidden(false); assert.equal(layer.show, true); assert.equal(h.rendering.getDiagnostics().time, times[0]); h.rendering.clear(); }); test('satellite global selection uses the three-hour gap and preserves the shared target on product changes', async (t) => { const clock = createWeatherClock(); const earlier = '2026-09-15T18:00:00.000Z'; const h = layerHarness({ clock, id: 'weather-satellite', feed: { getSnapshot: async ({ product }) => ({ ...snapshot, product, times: [earlier], latest: earlier, }), }, }); t.after(() => { h.layer.destroy(); clock.destroy(); }); const update = h.layer.update(); await flush(); h.stages.at(-1).finish(); await update; await seekTo(clock, times[0]); assert.equal( h.layer.getDiagnostics().hidden, true, 'two-hour regional gap is ineligible', ); h.layer.setParams({ product: 'clouds' }); await flush(); assert.equal(h.stages.at(-1).time, earlier); h.stages.at(-1).finish(); await flush(); assert.equal(clock.getState().target, times[0]); assert.equal(h.layer.getDiagnostics().hidden, false); assert.match(h.layer.getRowControls().summary.detail, /18:00 UTC.*nearest/); const params = h.layer.getParams(); assert.equal(params.product, 'clouds'); assert.equal(params.target, undefined); }); test('satellite clouds from an hourly feed draw all through each hour and read late only past it', async (t) => { const clock = createWeatherClock(); const now = Date.now(); const hour = 3_600_000; const top = Math.floor(now / hour) * hour; // Frames an hour apart, the latest forty minutes old. const hourly = [3, 2, 1].map((back) => new Date(top - back * hour + 20 * 60_000).toISOString(), ); const latest = hourly.at(-1); const h = layerHarness({ clock, id: 'weather-satellite', feed: { getSnapshot: async ({ product }) => ({ ...snapshot, product, times: hourly, latest, }), }, }); t.after(() => { h.layer.destroy(); clock.destroy(); }); t.mock.method(Date, 'now', () => Date.parse(latest) + 40 * 60_000); const update = h.layer.update(); await flush(); h.stages.at(-1).finish(); await update; assert.equal(h.layer.getParams().product, 'clouds-regional'); assert.equal(h.layer.getRowControls().summary.maxGapMinutes, 90); assert.equal( h.layer.getStats().stale, false, 'forty minutes is within the hour', ); // Forty-five minutes past a frame, between it and the next, it still shows. const between = seekTo( clock, new Date(Date.parse(hourly[0]) + 45 * 60_000).toISOString(), ); await flush(); h.stages.at(-1).finish(); await between; assert.equal(h.layer.getDiagnostics().hidden, false); assert.equal(h.stages.at(-1).time, hourly[0]); // Live again (a past time judges delay from the timeline's time), past // one and a half hours it reads late. const live = goLive(clock); await flush(); h.stages.at(-1).finish(); await live; t.mock.method(Date, 'now', () => Date.parse(latest) + 100 * 60_000); assert.equal( h.layer.getStats().stale, true, 'past one and a half hours, late', ); }); test('switching to history cancels a still-loading latest refresh and a later target cancels the first history load', async (t) => { const clock = createWeatherClock(); const h = layerHarness({ clock }); t.after(() => { h.layer.destroy(); clock.destroy(); }); const update = h.layer.update(); await flush(); const latest = h.stages.at(-1); const oldHistory = seekTo(clock, times[0]); await flush(); assert.equal(latest.signal.aborted, true); const oldStage = h.stages.at(-1); const current = seekTo(clock, times[1]); await flush(); assert.equal(oldStage.signal.aborted, true); h.stages.at(-1).finish(); await current; latest.finish(); oldStage.finish(); await oldHistory; await update; assert.equal(h.layer.getDiagnostics().time, times[1]); assert.equal(h.layer.getDiagnostics().clock.target, times[1]); }); test('observed descriptors keep configuration only and label satellite clouds by coverage', () => { for (const [id, coverage] of [ ['weather-radar', 'CONUS'], ['weather-satellite', 'North America'], ['weather-lightning', 'Americas + Pacific'], ]) { const h = layerHarness({ id }); const controls = h.layer.getRowControls(); assert.equal(controls.readout, true); assert.equal(controls.summary.coverage, coverage); assert.equal(controls.summary.sections, undefined); assert.deepEqual( controls.summary.settings.map(({ label }) => label), id === 'weather-satellite' ? ['REGION', 'IMAGE', 'OPACITY'] : ['OPACITY'], ); assert.deepEqual( controls.summary.settings.flatMap(({ chips }) => chips), controls.chips.filter(({ id }) => id !== 'coverage'), ); assert.deepEqual(controls.summary.actions, [ controls.chips.find(({ id }) => id === 'coverage'), ]); assert.deepEqual(controls.summary.actions[0].params, { focus: true }); assert.equal( controls.chips.some(({ id }) => ['previous', 'play', 'next', 'latest'].includes(id), ), false, ); if (id === 'weather-satellite') { assert.equal(h.layer.name, 'Satellite clouds'); assert.equal(controls.summary.label, 'Satellite clouds'); assert.match( controls.infoTitle, /GOES-19\/18 longwave infrared Band 14 regional; NESDIS global longwave mosaic/, ); assert.equal( controls.chips.find(({ id }) => id === 'filtered').title, 'Apply the full cloud brightness key; 100% filter strength', ); const imageSetting = controls.summary.settings.find( ({ id }) => id === 'image', ); assert.equal(imageSetting.range.param, 'infrared'); assert.equal(imageSetting.range.value, 100); assert.equal(imageSetting.range.commitOnChange, true); h.layer.setParams({ product: 'clouds' }); assert.equal( h.layer.getRowControls().summary.coverage, 'Global · 60°S–60°N', ); assert.equal(h.layer.getRowControls().summary.maxGapMinutes, 180); } h.layer.destroy(); } }); const globalSnapshot = { ...snapshot, product: 'clouds' }; async function showMosaic(h, time, infrared = 'filtered') { const pending = h.rendering.setFrame(globalSnapshot, time, { infrared }); await flush(); h.settle(); assert.equal(await pending, true); h.settle(); } test('mosaic cache skips fetch and decode, separates modes, evicts LRU at 6 and clears per instance', async (t) => { let fetches = 0, decodes = 0; const h = renderingHarness({ fetchImpl: async () => { fetches++; return mockResponse(); }, decodeImage: async () => { decodes++; return { width: 2048, height: 1024 }; }, }); t.after(() => h.rendering.clear()); await showMosaic(h, times[0]); await showMosaic(h, times[1]); await showMosaic(h, times[0]); assert.equal(fetches, 2); assert.equal(decodes, 2); assert.deepEqual(h.rendering.getDiagnostics().mosaic, { fetched: false, cached: true, decodeMs: 0, }); await showMosaic(h, times[0], 'full'); assert.equal(fetches, 3); assert.equal(h.rendering.getDiagnostics().mosaic.cached, false); await showMosaic(h, times[0]); const extra = Array.from({ length: 4 }, (_, i) => new Date(Date.parse(times[2]) + i * 3600_000).toISOString(), ); for (const time of extra) await showMosaic(h, time); assert.deepEqual(h.rendering.getDiagnostics().cache, { mosaics: 6, prefetching: false, }); await showMosaic(h, times[0]); assert.equal( fetches, 7, 'touching the oldest frame retained it ahead of the second frame', ); await showMosaic(h, times[1]); assert.equal(fetches, 8, 'least recently used frame was evicted'); h.rendering.clear(); assert.deepEqual(h.rendering.getDiagnostics().cache, { mosaics: 0, prefetching: false, }); await showMosaic(h, times[0]); assert.equal(fetches, 9); const other = renderingHarness({ fetchImpl: async () => { fetches++; return mockResponse(); }, }); t.after(() => other.rendering.clear()); await showMosaic(other, times[0]); assert.equal(fetches, 10, 'instances do not share canvases'); }); test('global prefetch warms a decoded frame without staging imagery and hits on selection', async (t) => { let fetches = 0; const h = renderingHarness({ fetchImpl: async () => { fetches++; return mockResponse(); }, }); t.after(() => h.rendering.clear()); await showMosaic(h, times[0]); const warm = h.rendering.prefetch(globalSnapshot, times[1]); assert.equal(h.rendering.getDiagnostics().cache.prefetching, true); assert.equal(h.rendering.getDiagnostics().time, times[0]); assert.equal(h.layers.length, 1); assert.equal(await warm, true); await showMosaic(h, times[1]); assert.equal(fetches, 2); assert.equal(h.rendering.getDiagnostics().mosaic.cached, true); assert.equal(h.rendering.getDiagnostics().mosaic.decodeMs, 0); }); test('cancelled or cleared speculative decodes cannot repopulate the cache', async () => { for (const cancel of ['cancelPrefetch', 'clear', 'setHidden']) { const decoded = deferred(); let signal, closes = 0; const h = renderingHarness({ fetchImpl: async (_url, options) => { signal = options.signal; return mockResponse(); }, decodeImage: () => decoded.promise, }); const warm = h.rendering.prefetch(globalSnapshot, times[0]); await flush(); h.rendering[cancel](true); assert.equal(signal.aborted, true); decoded.resolve({ width: 2048, height: 1024, close() { closes++; }, }); assert.equal(await warm, false); assert.equal(closes, 1); assert.deepEqual(h.rendering.getDiagnostics().cache, { mosaics: 0, prefetching: false, }); h.rendering.clear(); } }); test('tiled prefetch covers only visible product bounds at levels 0/1, caps eight requests and drains bodies', async (t) => { const calls = []; let bodies = 0; const h = renderingHarness({ fetchImpl: async (url, { signal }) => { calls.push({ url: new URL(url, 'http://localhost'), signal }); return { ...mockResponse(), arrayBuffer: async () => { bodies++; return new ArrayBuffer(1); }, }; }, }); t.after(() => h.rendering.clear()); h.viewer.camera = { computeViewRectangle: () => Cesium.Rectangle.fromDegrees(-120, 25, -100, 50), }; assert.equal(await h.rendering.prefetch(snapshot, times[1]), true); assert.equal(calls.length, 2); assert.equal(bodies, 2); assert.deepEqual( calls.map(({ url }) => ['z', 'x', 'y'].map((key) => url.searchParams.get(key)), ), [ ['0', '0', '0'], ['1', '0', '0'], ], ); assert.ok( calls.every(({ url }) => url.searchParams.get('time') === times[1]), ); assert.equal( await h.rendering.prefetch(snapshot, times[1]), false, 'same completed work is not repeated', ); h.viewer.camera.computeViewRectangle = () => Cesium.Rectangle.fromDegrees(100, 25, 120, 50); await h.rendering.prefetch(snapshot, times[2]); assert.equal(calls.length, 2, 'view outside product bounds fetches nothing'); h.viewer.camera.computeViewRectangle = () => Cesium.Rectangle.MAX_VALUE; const world = { ...snapshot, bounds: { west: -180, south: -90, east: 180, north: 90 }, }; await h.rendering.prefetch(world, times[2]); assert.equal( calls.length, 10, 'world view is capped at eight additional requests', ); assert.equal(bodies, 10); assert.equal(new Set(calls.slice(2).map(({ url }) => url.href)).size, 8); }); test('prefetch is best effort, aborts on replacement or host suspension, and skips hidden frames', async (t) => { let host = { collection: null, kind: 'globe' }; const signals = []; const h = renderingHarness({ getHost: () => host, fetchImpl: (_url, { signal }) => new Promise((_, reject) => { signals.push(signal); signal.addEventListener('abort', () => reject(signal.reason), { once: true, }); }), }); host.collection = h.viewer.imageryLayers; t.after(() => h.rendering.clear()); const first = h.rendering.prefetch(snapshot, times[1]); const shown = h.rendering.setFrame(snapshot, times[0]); h.settle(); assert.equal( await shown, true, 'current frame never waits for speculative work', ); assert.equal(await first, false); assert.ok(signals.every((signal) => signal.aborted)); const second = h.rendering.prefetch(snapshot, times[1]); host = { collection: null, kind: 'none' }; h.rendering.rehome(); assert.equal(await second, false); const count = signals.length; assert.equal(await h.rendering.prefetch(snapshot, times[2]), false); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; h.rendering.setHidden(true); assert.equal(await h.rendering.prefetch(snapshot, times[2]), false); assert.equal(signals.length, count); assert.equal(h.rendering.getDiagnostics().cache.prefetching, false); }); test('failed prefetch leaves the current frame and errors unchanged and releases its deadline', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const h = renderingHarness({ fetchImpl: async () => { throw new Error('offline'); }, }); t.after(() => h.rendering.clear()); const shown = h.rendering.setFrame(snapshot, times[0]); h.settle(); await shown; const before = h.rendering.getDiagnostics(); assert.equal(await h.rendering.prefetch(snapshot, times[1]), false); assert.deepEqual(h.rendering.getDiagnostics(), before); t.mock.timers.tick(30_000); assert.deepEqual(h.rendering.getDiagnostics(), before); }); test('as the world plays, the layer warms the next advertised observation after each frame that shows', async (t) => { const clock = createWeatherClock(); const { world } = clock; const h = layerHarness({ clock }); const warmed = []; let cancels = 0; h.rendering.prefetch = async (manifest, time, options) => { warmed.push({ manifest, time, options }); }; h.rendering.cancelPrefetch = () => { cancels++; }; t.after(() => { h.layer.destroy(); clock.destroy(); }); const updated = h.layer.update(); await flush(); h.stages.at(-1).finish(); await updated; await seekTo(clock, times[0]); h.stages.at(-1).finish(); await flush(); assert.equal(warmed.length, 0, 'paused, nothing is warmed'); world.play({ rate: 1e-9, continuous: true }); assert.equal(clock.getState().advancing, true); await seekTo(clock, times[1]); assert.equal(warmed.length, 0, 'still staging'); h.stages.at(-1).finish(); await flush(); assert.deepEqual( warmed.map(({ time }) => time), [times[2]], ); assert.deepEqual(warmed[0].options, { infrared: 100 }); await seekTo(clock, times[0]); h.stages.at(-1).finish(false); await flush(); assert.equal(warmed.length, 1, 'a failed frame warms nothing'); await seekTo(clock, times[2]); h.stages.at(-1).finish(); await flush(); assert.equal(warmed.length, 1, 'the world plays on past the newest frame'); const priorCancels = cancels; world.pause(); await flush(); assert.ok(cancels > priorCancels); await seekTo(clock, times[1]); h.stages.at(-1).finish(); await flush(); assert.equal(warmed.length, 1); world.play({ rate: 1e-9, continuous: true }); h.documentRef.hidden = true; h.documentRef.emit('visibilitychange'); await flush(); h.stages.at(-1)?.finish(); await flush(); assert.equal(warmed.length, 1, 'hidden products do not prefetch'); world.goLive(); }); for (const product of ['radar', 'clouds-regional', 'lightning']) { test(`${product} on the globe host uses 256 px tiles to level 6`, async (t) => { const collection = new ImageryLayerCollection(); const h = renderingHarness({ getHost: () => ({ collection, kind: 'globe' }), }); t.after(() => h.rendering.clear()); h.viewer.camera = { moveEnd: event(), positionCartographic: { height: 60_000 }, }; const pending = h.rendering.setFrame({ ...snapshot, product }, times[0]); const { spec } = h.layers[0]; assert.equal(spec.kind, 'xyz'); assert.equal(spec.tileSize, 256); assert.equal(spec.maxLevel, 6); assert.equal(spec.tiling, 'geographic'); assert.equal( new URL(spec.url, 'https://example.test').searchParams.get('size'), '256', ); assert.equal(h.rendering.getDiagnostics().host, 'globe'); h.rendering.clear(); assert.equal(await pending, false); assert.equal(h.viewer.camera.moveEnd.size, 0); }); } test('a product replacement accepts supersession but never paints the obsolete first response', async () => { const pending = []; const h = layerHarness({ id: 'weather-satellite', feed: { getSnapshot: (args) => { const task = deferred(); pending.push({ ...args, ...task }); return task.promise; }, }, }); const first = h.layer.update(); h.layer.setParams({ product: 'clouds' }); assert.equal(pending.length, 2); pending[0].resolve({ ...snapshot, product: 'clouds-regional' }); assert.equal(await first, true); assert.equal(h.stages.length, 0); pending[1].resolve({ ...snapshot, product: 'clouds' }); await flush(); h.stages.at(-1).finish(); await flush(); assert.equal(h.layer.getParams().product, 'clouds'); h.layer.destroy(); }); test('disabled weather releases its camera listener and re-enabling binds only once', () => { const h = layerHarness(); h.layer.disable(); assert.equal(h.moveEnd.size, 0, 'disabled layers own no active camera work'); h.layer.enable(); h.layer.enable(); assert.equal(h.moveEnd.size, 1); h.layer.disable(); assert.equal(h.moveEnd.size, 0); h.layer.enable(); assert.equal(h.moveEnd.size, 1); h.layer.destroy(); assert.equal(h.moveEnd.size, 0); }); const suppliedTile = (size = 256) => ({ width: size, height: size, closes: 0, close() { this.closes++; }, }); test('a frame source supplies regional tiles in place of the tile route, through the readiness wrapper', async () => { let now = 0; const requests = []; const supplied = []; const h = renderingHarness({ now: () => now, fetchImpl: () => assert.fail('supplied tiles are not fetched'), frameSource: { getTile: async (request) => { requests.push(request); const tile = suppliedTile(); supplied.push(tile); return tile; }, }, }); h.viewer.scene.globe.tilesLoaded = false; const loaded = h.rendering.setFrame(snapshot, times[0]); assert.equal(h.providers.length, 1); const [provider] = h.providers; assert.equal(typeof provider.spec.fetchTile, 'function', 'not the route'); assert.equal(provider.spec.maxLevel, 6); assert.equal(provider.spec.maxConcurrentRequests, 6); const tile = await provider.requestImage(1, 0, 1, {}); assert.equal(tile.width, 256); assert.equal(tile.source, supplied[0]); assert.equal(supplied[0].closes, 1); assert.equal(requests[0].product, 'radar'); assert.equal(requests[0].time, times[0]); assert.deepEqual( [requests[0].z, requests[0].x, requests[0].y, requests[0].size], [1, 1, 0, 256], ); assert.equal(h.rendering.getDiagnostics().loadedTiles, 1); now = 500; h.settle(); assert.equal(await loaded, true); const gate = deferred(); let signal; const next = renderingHarness({ frameSource: { getTile: (request) => { signal = request.signal; return gate.promise; }, }, }); const staged = next.rendering.setFrame(snapshot, times[1]); const pending = next.providers[0].requestImage(0, 0, 0, {}); next.rendering.clear(); assert.equal(signal.aborted, true, 'clearing a frame aborts its tiles'); const late = suppliedTile(); gate.resolve(late); await assert.rejects(pending, { name: 'AbortError' }); assert.equal(late.closes, 1); assert.equal(await staged, false); h.rendering.clear(); }); test('a frame source that names its tile detail draws global clouds from its tiles to that level', async () => { let now = 0; const requests = []; const h = renderingHarness({ now: () => now, fetchImpl: () => assert.fail('supplied clouds are not fetched'), frameSource: { getImage: () => assert.fail('no mosaic when the feed tiles clouds'), getTile: async (request) => { requests.push(request); return suppliedTile(); }, maximumLevel: (product) => (product === 'clouds' ? 6 : 8), }, }); h.viewer.scene.globe.tilesLoaded = false; const loaded = h.rendering.setFrame(globalSnapshot, times[0]); assert.equal(h.providers.length, 1); const [provider] = h.providers; assert.equal(typeof provider.spec.fetchTile, 'function', 'not the route'); assert.equal(provider.spec.maxLevel, 6); await provider.requestImage(5, 3, 4, {}); assert.deepEqual( [requests[0].product, requests[0].z, requests[0].x, requests[0].y], ['clouds', 4, 5, 3], ); now = 500; h.settle(); assert.equal(await loaded, true); h.rendering.clear(); // Radar takes the level the feed names for it. const radar = renderingHarness({ frameSource: { getTile: async () => suppliedTile(), maximumLevel: () => 8, }, }); radar.rendering.setFrame(snapshot, times[0]); assert.equal(radar.providers[0].spec.maxLevel, 8); radar.rendering.clear(); }); test("a frame source naming no usable level keeps the layer's own detail", async () => { for (const maximumLevel of [ () => null, () => 13, () => 2.5, () => 'deep', () => { throw new Error('no level'); }, ]) { const h = renderingHarness({ frameSource: { getTile: async () => suppliedTile(), maximumLevel }, }); h.rendering.setFrame(snapshot, times[0]); assert.equal(h.providers[0].spec.maxLevel, 6); h.rendering.clear(); // Global clouds stay on the one image, cut to level 3. let mosaics = 0; const clouds = renderingHarness({ frameSource: { getImage: async () => { mosaics++; return { width: 2048, height: 1024, close() {} }; }, getTile: () => assert.fail('clouds are not tiled without a level'), maximumLevel, }, }); await showMosaic(clouds, times[0]); assert.equal(mosaics, 1); assert.equal(clouds.providers[0].spec.maxLevel, 3); clouds.rendering.clear(); } // A level without tiles leaves global clouds on the mosaic. let images = 0; const h = renderingHarness({ frameSource: { getImage: async () => { images++; return suppliedTile(); }, maximumLevel: () => 6, }, }); h.rendering.setFrame(globalSnapshot, times[0]); await flush(); assert.equal(images, 1); h.rendering.clear(); }); test('a failed supplied tile fails the staged frame through the tile error', async () => { const h = renderingHarness({ frameSource: { getTile: async () => { throw new Error('frame unavailable'); }, }, }); const staged = h.rendering.setFrame(snapshot, times[0]); const [provider] = h.providers; await assert.rejects(provider.requestImage(0, 0, 0, {})); provider.errorEvent.emit({ x: 0, y: 0, level: 0, error: {} }); h.settle(); assert.equal(await staged, false); assert.match(h.rendering.getDiagnostics().error, /Weather tiles unavailable/); h.rendering.clear(); }); test("supplied regional infrared tiles get the transfer upright, as the route's do", async () => { const hadBitmap = Object.hasOwn(globalThis, 'ImageBitmap'); const previous = globalThis.ImageBitmap; globalThis.ImageBitmap = class ImageBitmap { width = 256; height = 256; close() {} }; try { const h = renderingHarness({ frameSource: { getTile: async () => new globalThis.ImageBitmap() }, }); void h.rendering.setFrame( { ...snapshot, product: 'clouds-regional' }, times[0], ); const [provider] = h.providers; const decoded = await provider.requestImage(0, 0, 0, {}); const tile = await provider.spec.tileTransform( { x: 0, y: 0, level: 0 }, decoded, ); assert.equal(tile.drawnWith, null, 'drawn upright, not flipped'); assert.ok(tile.pixels, 'the infrared transfer ran'); const empty = renderingHarness({ frameSource: { getTile: async () => null }, }); void empty.rendering.setFrame( { ...snapshot, product: 'clouds-regional' }, times[0], ); const transparent = await empty.providers[0].requestImage(0, 0, 0, {}); assert.equal(transparent.width, 256, 'a null tile is still a drawn tile'); h.rendering.clear(); empty.rendering.clear(); } finally { if (hadBitmap) globalThis.ImageBitmap = previous; else delete globalThis.ImageBitmap; } }); test('global clouds tiles get the infrared transfer, and prefetch asks for tiles, not the image', async () => { const hadBitmap = Object.hasOwn(globalThis, 'ImageBitmap'); const previous = globalThis.ImageBitmap; globalThis.ImageBitmap = class ImageBitmap { width = 256; height = 256; close() {} }; try { const requests = []; const h = renderingHarness({ frameSource: { getImage: () => assert.fail('no image when the feed tiles clouds'), getTile: async (request) => { requests.push(request); return new globalThis.ImageBitmap(); }, maximumLevel: () => 6, }, }); void h.rendering.setFrame(globalSnapshot, times[0]); const [provider] = h.providers; const decoded = await provider.requestImage(5, 3, 4, {}); const tile = await provider.spec.tileTransform( { x: 5, y: 3, level: 4 }, decoded, ); assert.equal(tile.drawnWith, null, 'drawn upright, not flipped'); assert.ok(tile.pixels, 'the infrared transfer ran'); h.rendering.clear(); requests.length = 0; const warm = renderingHarness({ frameSource: { getImage: () => assert.fail('no image when the feed tiles clouds'), getTile: async (request) => { requests.push(request); return new globalThis.ImageBitmap(); }, maximumLevel: () => 6, }, }); assert.equal(await warm.rendering.prefetch(globalSnapshot, times[1]), true); assert.ok(requests.length > 0, 'prefetch asked for tiles'); assert.ok(requests.every((request) => request.product === 'clouds')); warm.rendering.clear(); } finally { if (hadBitmap) globalThis.ImageBitmap = previous; else delete globalThis.ImageBitmap; } }); test('tiled prefetch asks the frame source for the same level 0/1 tiles and releases them', async (t) => { const requests = []; const supplied = []; const h = renderingHarness({ fetchImpl: () => assert.fail('supplied tiles are not fetched'), frameSource: { getTile: async (request) => { requests.push(request); if (request.z === 0) return null; const tile = suppliedTile(); supplied.push(tile); return tile; }, }, }); t.after(() => h.rendering.clear()); h.viewer.camera = { computeViewRectangle: () => Cesium.Rectangle.fromDegrees(-120, 25, -100, 50), }; assert.equal(await h.rendering.prefetch(snapshot, times[1]), true); assert.deepEqual( requests.map(({ product, time, z, x, y, size }) => [ product, time, z, x, y, size, ]), [ ['radar', times[1], 0, 0, 0, 256], ['radar', times[1], 1, 0, 0, 256], ], ); assert.ok(requests.every(({ signal }) => signal instanceof AbortSignal)); assert.equal(supplied[0].closes, 1); assert.equal( await h.rendering.prefetch(snapshot, times[1]), false, 'same completed work is not repeated', ); assert.equal(requests.length, 2); const gate = deferred(); let signal; const slow = renderingHarness({ frameSource: { getTile: ({ signal: value }) => { signal = value; return gate.promise; }, }, }); t.after(() => slow.rendering.clear()); slow.viewer.camera = h.viewer.camera; const warm = slow.rendering.prefetch(snapshot, times[1]); slow.rendering.cancelPrefetch(); assert.equal(signal.aborted, true, 'cancelling a prefetch aborts its tiles'); gate.resolve(null); assert.equal(await warm, false); }); test('the global mosaic comes from the frame source image when present', async (t) => { const requests = []; const h = renderingHarness({ fetchImpl: () => assert.fail('a supplied mosaic is not fetched'), decodeImage: () => assert.fail('a supplied mosaic is not decoded'), frameSource: { getImage: async (request) => { requests.push(request); return { width: 2048, height: 1024, close() {} }; }, }, }); t.after(() => h.rendering.clear()); await showMosaic(h, times[0]); assert.equal(requests.length, 1); assert.equal(requests[0].product, 'clouds'); assert.deepEqual(requests[0].size, { width: 2048, height: 1024 }); assert.equal(requests[0].bbox, null); assert.equal(h.rendering.getDiagnostics().mosaic.fetched, true); }); test('the layer hands rendering a frame source only when its feed is one', () => { const seen = []; const createRendering = (args) => { seen.push(args.frameSource); return { setAlpha() {}, rehome() {}, clear() {}, getDiagnostics: () => ({}), }; }; const options = { documentRef: target({ hidden: false }), eventTarget: target(), matchMedia: () => target({ matches: false }), createRendering, }; createWeatherLayer({ ...options, feed: { getSnapshot: async () => snapshot }, }).init({}); const getFrameTile = async () => null; createWeatherLayer({ ...options, feed: { getSnapshot: async () => snapshot, getFrameTile }, }).init({}); assert.equal(seen[0], null); assert.equal(typeof seen[1].getTile, 'function'); assert.equal(seen[1].getImage, undefined); }); test('at a past time a frame is aged and its source judged delayed from the timeline time', async (t) => { // Live at twenty minutes past the newest frame: the source is late. t.mock.method(Date, 'now', () => Date.parse(times[2]) + 25 * 60_000); const clock = createWeatherClock(); const h = layerHarness({ clock }); t.after(() => { h.layer.destroy(); clock.destroy(); }); const update = h.layer.update(); await flush(); h.stages.at(-1).finish(); await update; await flush(); assert.equal( h.layer.getRowControls().summary.status, 'Source observations delayed', ); assert.match(h.layer.getRowControls().summary.detail, /25m ago/); // Years later, the world clock is moved back to the newest frame. Date.now.mock.mockImplementation(() => Date.parse('2032-01-01T00:00:00Z')); void seekTo(clock, times[2]); await flush(); h.stages.at(-1)?.finish(); await flush(); assert.equal(clock.getState().mode, 'history'); const controls = h.layer.getRowControls(); assert.equal(controls.summary.status, null); assert.match(controls.summary.detail, /History · 09-15 20:10 UTC · 0m ago/); assert.equal(h.layer.getStats().stale, false); // Ten minutes after the newest frame, the frame is ten minutes old. void seekTo(clock, '2026-09-15T20:20:00.000Z'); await flush(); h.stages.at(-1)?.finish(); await flush(); assert.match(h.layer.getRowControls().summary.detail, /10m ago · nearest/); assert.equal(h.layer.getRowControls().summary.status, null); }); test('a feed names the source behind each product, before any manifest does', (t) => { t.mock.method(console, 'warn', () => {}); const quiet = { documentRef: target({ hidden: false }), eventTarget: target(), matchMedia: () => target({ matches: false }), }; const asked = []; const feed = { getSnapshot: async () => snapshot, sourceName(kind) { asked.push(kind); if (kind === 'satellite') throw new Error('no name'); return kind === 'radar' ? ' NOAA MRMS ' : 'NOAA\u200b GLM'; }, }; const radar = createWeatherLayer({ ...quiet, feed, id: 'weather-radar' }); assert.equal(radar.source, 'NOAA MRMS'); const stats = radar.getStats(); assert.equal(stats.source, 'NOAA MRMS'); assert.equal(stats.sourceVerbatim, true); // A name a manifest could not carry, or a failing call, leaves nowCOAST, as // does a feed with no names. for (const id of ['weather-lightning', 'weather-satellite']) { const layer = createWeatherLayer({ ...quiet, feed, id }); assert.equal(layer.source, 'NOAA nowCOAST · OBSERVED', id); assert.equal(layer.getStats().source, 'NOAA nowCOAST', id); assert.equal(layer.getStats().sourceVerbatim, undefined, id); } assert.deepEqual(asked, ['radar', 'lightning', 'satellite']); const unnamed = createWeatherLayer({ ...quiet, feed: { getSnapshot: async () => snapshot }, }); assert.equal(unnamed.source, 'NOAA nowCOAST · OBSERVED'); });