Separate scene handoff and attachment from the page shell

Move the page handoff sequence into SceneSwitcher and include restoration
in the application's candidate attachment. Release a failed candidate once
before the request coordinator recovers the working engine. Keep address
ordering, parked renderers, retained layers and cockpit resumption intact.

Define the layer session and its field owners. Share its retention decision
across teardown paths. Separate layer scene binding from lifecycle policy,
and shell scene composition from page controls. Keep failed renderer
releases in the binding owner, with the existing retry behavior.

Give Director the scene and use the engine host for its canvas and pack
container. Keep the existing tracked-subject interaction guard so neither
engine's behavior changes. Pass startup chrome the first backend's explicit
welcome policy instead of testing for a viewer. Cesium remains the behavior
reference; this restructuring intentionally changes no visible behavior on
either engine.

Viewer references outside the Cesium engine fall from 948 to 933. All other
coupling counts stay unchanged. Scene service ownership, raw debug access,
and the remaining shell and host queues still need consolidation.

Checked in the browser, keyless, on the dev server: the engine switch,
Director engine switch, layer panel and layer visibility on both engines
pass, and 14 of 15 strict scenarios pass (rapid, hidden-tab, context-loss,
parked-release, Navara HD, failure matrix and soak among them). app-once
and the Director next-shot step fail the same way before this change.
This commit is contained in:
German Khokhlov committed 2026-11-07 15:44:03 +04:00
1 parent f385986383
commit 656943641c
23 files changed
+1265 -888

No files matched your search

+23 -7
View File
@@ -1,3 +1,4 @@
import { retainsLayerSession } from '../app/layerSession.js';
import { createStandaloneCatalog } from './catalog.js';
import { createStandalonePlaceSearch } from './placeSearch.js';
import { CITY_POIS } from '../cityPois.js';
@@ -94,7 +95,9 @@ export function createStandaloneApplication({
async function openScene(kind) {
const controller = new AbortController();
const releases = [];
const release = async () => {
let releasing;
const release = () => (releasing ??= releaseResources());
const releaseResources = async () => {
// A reason made here would keep this call's stack, and with it the
// released scene, alive in every closure that still holds `signal`.
controller.abort(SCENE_RELEASED);
@@ -156,6 +159,7 @@ export function createStandaloneApplication({
});
return Object.freeze({
...scene,
signal,
kind,
catalog: sceneCatalog,
release,
@@ -254,10 +258,7 @@ export function createStandaloneApplication({
// the globe's renderer is parked or released.
context.defer(async () => {
await sceneHost.detach({
handoff: Boolean(
layerSession?.handoffLayers &&
!layerSession.lifetime.signal.aborted,
),
handoff: retainsLayerSession(layerSession),
});
const scene = current;
current = null;
@@ -332,14 +333,30 @@ export function createStandaloneApplication({
* detaches what attached and releases the candidate; the session stays as
* it was, ready for the working engine to attach again.
*/
async function attachScene(kind) {
async function attachScene(kind, { resume } = {}) {
if (application.getState().status !== 'ready')
throw new Error('The application is not running');
if (current) throw new Error('A globe is attached; detach it first');
const next = await openScene(kind);
try {
await sceneHost.attach(next);
current = next;
await resume?.();
lifetime.throwIfAborted();
} catch (error) {
// attach() releases partial parts itself; a failed resume leaves a
// complete attachment for this transaction to detach.
if (current === next) {
current = null;
await sceneHost
.detach({ handoff: !lifetime.aborted })
.catch((cleanupError) =>
console.error(
'A failed globe could not be released:',
cleanupError,
),
);
}
await next
.release()
.catch((cleanupError) =>
@@ -347,7 +364,6 @@ export function createStandaloneApplication({
);
throw error;
}
current = next;
return sceneView;
}
+51
View File
@@ -5,6 +5,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import { retainsLayerSession } from '../app/layerSession.js';
import { createSceneHost } from '../app/sceneHost.js';
import { attachScenePart } from '../app/sceneParts.js';
@@ -50,6 +51,7 @@ function standalone({ failOpen = null } = {}) {
return { viewer: null, engine, operations: { kind: 'operations' } };
},
createSceneHost,
retainsLayerSession,
attachScenePart,
AbortController,
AbortSignal,
@@ -111,3 +113,52 @@ test('a failed candidate releases what it attached and the working engine attach
);
assert.equal(opened.length, 3);
});
test('a failed resume detaches and releases its candidate once before recovery', async () => {
const { app, opened, released } = standalone();
const scene = await app.createScene({ signal: new AbortController().signal, defer() {} });
const detached = [];
await scene.sceneHost.register({
name: 'part',
attachScene(next) { this.kind = next.kind; },
detachScene(options) { detached.push([this.kind, options.handoff]); },
});
await app.detachScene({ handoff: true });
await assert.rejects(app.attachScene('navara', {
resume() {
assert.equal(scene.engine, opened[1], 'resume sees the attached candidate');
throw new Error('restore failed');
},
}), /restore failed/);
assert.equal(scene.engine, null);
assert.equal(scene.sceneHost.state(), 'detached');
assert.deepEqual(detached, [['cesium', true], ['navara', true]]);
assert.deepEqual(released, opened);
await app.attachScene('cesium');
assert.equal(scene.engine, opened[2]);
assert.equal(released.length, 2);
});
test('page teardown during resume releases the candidate only once', async () => {
const { app, opened, released } = standalone();
const lifetime = new AbortController();
const scene = await app.createScene({ signal: lifetime.signal, defer() {} });
await app.detachScene({ handoff: true });
let finishResume;
let enteredResume;
const entered = new Promise((resolve) => { enteredResume = resolve; });
const pending = app.attachScene('navara', {
resume: () => {
enteredResume();
return new Promise((resolve) => { finishResume = resolve; });
},
});
const rejected = assert.rejects(pending, { name: 'AbortError' });
await entered;
lifetime.abort();
const leaving = app.detachScene({ handoff: false });
finishResume();
await Promise.all([leaving, rejected]);
assert.equal(scene.engine, null);
assert.deepEqual(released, opened);
});
+118
View File
@@ -0,0 +1,118 @@
import {
createEngineSwitch,
handOffSession,
resumeSession,
waitForFirstFrame,
} from './engineSwitch.js';
/**
* One scene-switch transaction: retain the session, detach and park the
* outgoing globe, attach and resume the candidate, then uncover its frame.
* The request coordinator owns ordering and the single rollback. The
* application owns candidate cleanup, including a failure during resume.
*
* @param {object} options
* @param {import('../app/layerSession.js').LayerSession} options.layerSession
*/
export function createSceneSwitcher({
getApplication,
startApplication,
layerSession,
renderers,
diagnostics,
keepFrame,
onSettled,
...options
}) {
const { signal } = layerSession.lifetime;
let cover = null;
let cockpit = null;
const count = (name) => diagnostics?.count(name);
const liveComponents = () => {
const app = getApplication();
if (app?.getState().status !== 'ready') return null;
const components = app.getComponents();
return components.scene?.engine ? components : null;
};
async function leave(from) {
const components = liveComponents();
if (components) {
cover ??= keepFrame?.(components.scene.engine);
const style = components.controls.styleManager;
cockpit = style.getCockpitState();
handOffSession(layerSession, {
addressLayerIds:
style.shareLinkManager?.currentLayerState?.()?.enabledLayerIds,
});
renderers.retain(from);
await getApplication().detachScene({ handoff: true });
}
count('detaches');
}
async function resume(style) {
signal.throwIfAborted();
await style.initialRestorePromise;
signal.throwIfAborted();
layerSession.restoringView = false;
count('attachments');
resumeSession(layerSession);
// A visited entry or a stale track may replace the outgoing subject.
const target = style.getAircraftTrackingTarget();
if (
cockpit?.active &&
target &&
target.id === cockpit.subject?.id &&
target.layerId === cockpit.subject?.layerId &&
style.controlCockpit('enter').ok
) {
style.cockpitView.setVisionMode(cockpit.visionMode);
}
}
async function enter(kind, { recovery = false } = {}) {
layerSession.restoringView = true;
let app = getApplication();
if (!app || app.getState().status !== 'ready') {
app = startApplication(kind);
try {
const { controls } = await app.start();
await resume(controls.styleManager);
} catch (error) {
if (!signal.aborted)
await app
.destroy()
.catch((cleanupError) =>
console.error(
'A failed globe could not be released:',
cleanupError,
),
);
throw error;
}
} else {
await app.attachScene(kind, {
resume: () => resume(app.getComponents().controls.styleManager),
});
}
if (recovery) count('rollbacks');
}
async function settle() {
const components = liveComponents();
try {
if (cover && components) await waitForFirstFrame(components.scene.engine);
} finally {
cover?.remove();
cover = null;
}
if (!components) return;
layerSession.handoffLayers = null;
cockpit = null;
onSettled?.();
components.controls.styleManager.shareLinkManager?.resumeNavigation?.();
}
return createEngineSwitch({ ...options, signal, leave, enter, settle });
}
+137
View File
@@ -0,0 +1,137 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createSceneSwitcher } from './sceneSwitcher.js';
import { createLayerSession } from '../app/layerSession.js';
function fixture({ failResume = false, changeTarget = false } = {}) {
const session = createLayerSession();
const log = [];
let current = 'first';
let address = 'first';
const target = { id: 'track', layerId: 'flights' };
const style = {
initialRestorePromise: Promise.resolve(),
getCockpitState: () => ({
active: true,
subject: target,
visionMode: 'ir',
}),
getAircraftTrackingTarget: () =>
changeTarget ? { ...target, id: 'other' } : target,
controlCockpit: () => {
log.push('cockpit');
return { ok: true };
},
cockpitView: { setVisionMode: (mode) => log.push(mode) },
shareLinkManager: {
currentLayerState: () => ({ enabledLayerIds: ['flights'] }),
resumeNavigation: () => log.push('navigation'),
},
};
const entry = {
module: {
attachRenderer() {},
resumeViewport() {
log.push('viewport');
},
},
};
session.manager = {
layers: new Map([['flights', entry]]),
isEffectivelyEnabled: () => true,
};
session.director = {
suspendScene: () => log.push('suspend-director'),
resumeScene: () => {
log.push('resume-director');
if (failResume && current === 'navara') throw new Error('resume failed');
},
};
const app = {
getState: () => ({ status: 'ready' }),
getComponents: () => ({
scene: { engine: current ? { kind: current } : null },
controls: { styleManager: style },
}),
async detachScene({ handoff }) {
log.push(['detach', current, handoff]);
current = null;
},
async attachScene(kind, { resume }) {
current = kind;
log.push(['attach', kind]);
try {
await resume();
} catch (error) {
log.push(['release', kind]);
current = null;
throw error;
}
},
};
const switcher = createSceneSwitcher({
kind: 'first',
requested: () => address,
layerSession: session,
getApplication: () => app,
renderers: { retain: (kind) => log.push(['park', kind]) },
address: {
select: () => 'old-entry',
commit: (token, kind) => {
address = kind;
log.push(['commit', token, kind]);
},
restore: (kind) => {
address = kind;
},
},
onSettled: () => log.push('settled'),
onFailure: (error, { recovered }) =>
log.push(['failure', error.message, recovered]),
});
return { switcher, session, log, current: () => current };
}
test('a scene switch parks once, resumes the session and cockpit, then returns navigation', async () => {
const { switcher, session, log, current } = fixture();
await switcher.select('navara');
assert.equal(current(), 'navara');
assert.equal(session.handoffLayers, null);
assert.equal(session.restoringView, false);
assert.deepEqual(log, [
'suspend-director',
['park', 'first'],
['detach', 'first', true],
['attach', 'navara'],
'viewport',
'resume-director',
'cockpit',
'ir',
['commit', 'old-entry', 'navara'],
'settled',
'navigation',
]);
});
test('resume failure has one candidate release and one rollback on the retained session', async () => {
const { switcher, session, log, current } = fixture({ failResume: true });
await switcher.select('navara');
assert.equal(current(), 'first');
assert.deepEqual(log.filter(Array.isArray), [
['park', 'first'],
['detach', 'first', true],
['attach', 'navara'],
['release', 'navara'],
['attach', 'first'],
['failure', 'resume failed', true],
]);
assert.equal(session.handoffLayers, null);
assert.equal(switcher.state().busy, false);
});
test('a changed tracking target does not resume the outgoing cockpit', async () => {
const { switcher, log } = fixture({ changeTarget: true });
await switcher.select('navara');
assert.equal(log.includes('cockpit'), false);
assert.equal(log.includes('ir'), false);
});