From e129761d0d2c4fa74ea691a23edca348dcf15df8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:01:33 +0000 Subject: [PATCH] fix(xr): live reload survives a dropped connection and refreshes data sources safely MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - live_sse_fileXR.js: one connectLiveReload() binds every handler; the old reconnect opened a bare EventSource with no handlers, so after one network error the scene stopped following re-analyses (audit CHARTS-10 / LIFECYCLE-10). The browser's own retry is left alone; a source it gave up on is reopened with back-off (1 s doubling to 30 s). Connection state is published as codexr-live-reload-status. - Cache busting reads both babia-queryjson forms, keeps existing query parameters (?revision=), skips chart slices and inline-data sources (they were pointed at '?t=…', i.e. the page itself), and strips a leaked 'url:' prefix (CHARTS-11). - analysisModeRuntime refreshNormalDataSources reads the raw declaration form, which used to turn the url into 'url: url: ./data.json' (LIFECYCLE-7). - live_sse_fileDOM.js: no reload loop on errors; reconnect with back-off and reload once when the connection is back. Tests: liveReloadClient.test.cjs (fake EventSource: reconnect, back-off, stale-source, cache-bust shapes, offline export, DOM client) and a raw-declaration refresh test. Headless check with a generated scene: after the server drops the SSE client, a 12-row re-analysis now reaches the chart (before: it stayed on the previous 20 rows). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKtAtQus8TVjhG9bhytC --- apps/vscode-extension/CHANGELOG.md | 1 + .../snapshotsAndLifecycles.js | 22 +- .../templates/xr/sse/live_sse_fileDOM.js | 68 +++-- .../templates/xr/sse/live_sse_fileXR.js | 225 +++++++++++----- .../test/analysis/dependencyGraph.test.cjs | 24 +- .../test/analysis/liveReloadClient.test.cjs | 252 ++++++++++++++++++ 6 files changed, 501 insertions(+), 91 deletions(-) create mode 100644 apps/vscode-extension/test/analysis/liveReloadClient.test.cjs diff --git a/apps/vscode-extension/CHANGELOG.md b/apps/vscode-extension/CHANGELOG.md index 7418cb28..330a597b 100644 --- a/apps/vscode-extension/CHANGELOG.md +++ b/apps/vscode-extension/CHANGELOG.md @@ -34,6 +34,7 @@ #### Fixed +- **XR scenes keep updating after the connection to VS Code drops.** After any network error the scene reconnected with a connection that listened to nothing, so it silently stopped following re-analyses until the page was reloaded. It now reconnects with every handler in place, leaves the browser's own retry alone and backs off up to 30 s when the server is gone. A refresh also no longer breaks the chart's row-limited data source (it was pointed at the page itself), keeps the other parameters of a data URL such as a comparison's revision, and repairs a data URL that had been corrupted to `url: url: ./data.json` at startup. The DOM visualization no longer reloads the page every 3 s while the server is unreachable; it reloads once, when the connection is back. - **Historical comparison and project evolution no longer refuse a folder opened through a link.** When the analyzed folder was reached through a symbolic link, a junction, or a shortened Windows path (`C:\Users\JOHNDO~1\...`), Code-XR compared it with the repository path Git reports and wrongly concluded the folder was outside the repository, so the Git-based analyses were unavailable. Both paths are now resolved to their real location before they are compared. - **The installed extension only ever runs the Python analysis scripts it ships with.** If its bundled copy of an analysis script was missing (a damaged or partially deleted install), Code-XR fell back to a developer location two folders above the extension, which in an installed copy is your home folder, and could have run a file found there. That fallback is now limited to development builds; an installed extension reports the missing script instead. - **The analysis backend loads again on Python 3.8 and 3.9.** One type annotation in the line-metrics module used syntax that only exists from Python 3.10, so on 3.8 or 3.9 every analysis failed as soon as the backend loaded, although the extension asks only for Python 3.7 or newer. The annotation now uses the older spelling; results on newer Python versions are unchanged. diff --git a/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/snapshotsAndLifecycles.js b/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/snapshotsAndLifecycles.js index 81d8d7ef..8ae149ed 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/snapshotsAndLifecycles.js +++ b/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/snapshotsAndLifecycles.js @@ -69,6 +69,26 @@ return Array.from(new Set(dataEntities)); } + // Reads the url of a babia-queryjson value in either form: the parsed + // object, or the raw declaration string ("url: ./data.json; ...") that + // getAttribute returns before A-Frame initialised the component. Reading + // the raw string as the url produced "url: url: ./data.json?...", which no + // later refresh could repair; any leaked "url:" prefix is stripped here. + function readQueryJsonUrl(value) { + var raw = ''; + if (typeof value === 'string') { + var match = /(?:^|;)\s*url\s*:\s*([^;]*)/.exec(value); + raw = match ? match[1] : ''; + } else if (value && typeof value.url === 'string') { + raw = value.url; + } + raw = raw.trim(); + while (/^url\s*:/i.test(raw)) { + raw = raw.replace(/^url\s*:\s*/i, ''); + } + return raw.trim(); + } + async function refreshNormalDataSources(modeRevision) { var doc = root.document; if (!doc || modeRevision <= state.lastNormalModeRevision) { @@ -83,7 +103,7 @@ if (!current) { return; } - var currentUrl = typeof current === 'string' ? current : current.url || ''; + var currentUrl = readQueryJsonUrl(current); if (!currentUrl) { return; } diff --git a/apps/vscode-extension/templates/xr/sse/live_sse_fileDOM.js b/apps/vscode-extension/templates/xr/sse/live_sse_fileDOM.js index 46e39822..d8788cd4 100644 --- a/apps/vscode-extension/templates/xr/sse/live_sse_fileDOM.js +++ b/apps/vscode-extension/templates/xr/sse/live_sse_fileDOM.js @@ -16,8 +16,13 @@ function liveReloadDebugLog(...args) { liveReloadDebugLog('Setting up EventSource for HTML live reload...'); -const eventSource = new EventSource('/events'); +let eventSource = null; let isXRMode = false; +let hadConnectionError = false; +let reconnectDelayMs = 0; +let reconnectTimer = null; +const RECONNECT_MIN_DELAY_MS = 1000; +const RECONNECT_MAX_DELAY_MS = 30000; function checkXRMode() { isXRMode = !!document.querySelector('a-scene'); @@ -47,21 +52,50 @@ function applyBabiaHtmlComponent(entity, htmlContent, distanceLevels) { document.addEventListener('DOMContentLoaded', checkXRMode); -eventSource.onopen = function () { - liveReloadDebugLog('HTML EventSource connection established'); - liveReloadDebugLog('DOM Visualization live reload ready - file changes will update automatically'); -}; - -eventSource.onerror = function (err) { - console.error('HTML EventSource error:', err); - setTimeout(() => { - liveReloadDebugLog('Attempting to reconnect HTML EventSource...'); - eventSource.close(); - location.reload(); - }, 3000); -}; +// Opens the connection and binds every handler to it. An error used to +// reload the page after 3 s whatever happened: with the server down that +// replaced the visualization with the browser's error page, and with +// /events answering 404 the page reloaded forever. Now the browser's own +// retry is left alone, a connection it gave up on is reopened with back-off, +// and the page reloads only once a connection is back after an error (to +// pick up any update missed while it was down). +function connectLiveReload() { + reconnectTimer = null; + const source = new EventSource('/events'); + eventSource = source; + source.onopen = function () { + reconnectDelayMs = 0; + liveReloadDebugLog('HTML EventSource connection established'); + if (hadConnectionError) { + hadConnectionError = false; + liveReloadDebugLog('Connection restored after an error; reloading to catch up...'); + location.reload(); + return; + } + liveReloadDebugLog('DOM Visualization live reload ready - file changes will update automatically'); + }; + source.onerror = function (err) { + if (source !== eventSource) { + return; + } + console.error('HTML EventSource error:', err); + hadConnectionError = true; + if (source.readyState !== 2) { + return; + } + source.close(); + if (!reconnectTimer) { + reconnectDelayMs = reconnectDelayMs + ? Math.min(RECONNECT_MAX_DELAY_MS, reconnectDelayMs * 2) + : RECONNECT_MIN_DELAY_MS; + reconnectTimer = setTimeout(connectLiveReload, reconnectDelayMs); + } + }; + source.addEventListener('message', handleLiveReloadMessage); + return source; +} -eventSource.addEventListener('message', function(event) { +function handleLiveReloadMessage(event) { try { const data = JSON.parse(event.data); liveReloadDebugLog('SSE received:', data); @@ -91,7 +125,7 @@ eventSource.addEventListener('message', function(event) { } catch (error) { console.error('Error parsing SSE message:', error); } -}); +} function updateBabiaHtmlComponent(entity, htmlContent) { try { @@ -105,3 +139,5 @@ function updateBabiaHtmlComponent(entity, htmlContent) { location.reload(); } } + +connectLiveReload(); diff --git a/apps/vscode-extension/templates/xr/sse/live_sse_fileXR.js b/apps/vscode-extension/templates/xr/sse/live_sse_fileXR.js index 2929275c..f1dd8dc7 100644 --- a/apps/vscode-extension/templates/xr/sse/live_sse_fileXR.js +++ b/apps/vscode-extension/templates/xr/sse/live_sse_fileXR.js @@ -28,10 +28,14 @@ onerror: null, onmessage: null }; - const eventSource = liveReloadDisabled - ? disabledEventSource - : new EventSource('/events'); + // The live connection. It is reassigned on every reconnect, so read it + // through this variable, never capture it. + let eventSource = disabledEventSource; let isXRMode = false; + let reconnectDelayMs = 0; + let reconnectTimer = null; + const RECONNECT_MIN_DELAY_MS = 1000; + const RECONNECT_MAX_DELAY_MS = 30000; if (liveReloadDisabled) { liveReloadDebugLog(' Offline export detected: live reload disabled.'); @@ -45,7 +49,7 @@ .then((manifest) => { if (manifest && manifest.kind === 'codexr-export') { liveReloadDebugLog(' Offline export detected: live reload disabled.'); - eventSource.close(); + stopLiveReload(); } }) .catch(() => {}); @@ -131,30 +135,143 @@ } } - eventSource.onopen = function() { - liveReloadDebugLog(' EventSource connection established'); - }; + // Live-reload connection state, readable by the scene and by tests: + // 'connecting' | 'open' | 'reconnecting' | 'disabled'. + function setLiveReloadStatus(status) { + window.__CODEXR_LIVE_RELOAD_STATUS__ = status; + try { + document.dispatchEvent(new CustomEvent('codexr-live-reload-status', { detail: { status: status } })); + } catch (_error) { + // CustomEvent is missing only in non-browser hosts. + } + } - eventSource.onerror = function(err) { - if (liveReloadDisabled) { - eventSource.close(); - return; + function stopLiveReload() { + if (reconnectTimer) { + clearTimeout(reconnectTimer); + reconnectTimer = null; } - console.error(' EventSource error:', err); - // Try to reconnect after a delay - setTimeout(() => { - if (liveReloadDisabled) { + eventSource.close(); + eventSource = disabledEventSource; + setLiveReloadStatus('disabled'); + } + + // Opens the connection and binds EVERY handler to it. The previous + // reconnect opened a bare `new EventSource('/events')` with no handlers + // and closed the one that had them, so after one network drop the scene + // silently stopped updating until the page was reloaded. + function connectLiveReload() { + reconnectTimer = null; + const source = new EventSource('/events'); + eventSource = source; + setLiveReloadStatus('connecting'); + source.onopen = function () { + reconnectDelayMs = 0; + setLiveReloadStatus('open'); + liveReloadDebugLog(' EventSource connection established'); + }; + source.onerror = function (err) { + if (source !== eventSource) { return; } - liveReloadDebugLog(' Attempting to reconnect...'); - eventSource.close(); - new EventSource('/events'); - }, 3000); - }; + console.error(' EventSource error:', err); + // While the browser is retrying on its own (CONNECTING) there is + // nothing to do. It only gives up (CLOSED) on a fatal answer such as + // a 404, and then a fresh connection is opened with back-off. + if (source.readyState !== 2) { + setLiveReloadStatus('reconnecting'); + return; + } + source.close(); + scheduleReconnect(); + }; + source.addEventListener('analysis-updated', handleAnalysisUpdated); + source.addEventListener('dataRefresh', handleDataRefresh); + source.onmessage = handleGenericMessage; + return source; + } + + function scheduleReconnect() { + if (liveReloadDisabled || reconnectTimer) { + return; + } + reconnectDelayMs = reconnectDelayMs + ? Math.min(RECONNECT_MAX_DELAY_MS, reconnectDelayMs * 2) + : RECONNECT_MIN_DELAY_MS; + setLiveReloadStatus('reconnecting'); + liveReloadDebugLog(' Reconnecting in ' + reconnectDelayMs + ' ms...'); + reconnectTimer = setTimeout(connectLiveReload, reconnectDelayMs); + } + + // --- Data-source cache busting ------------------------------------- + // A babia-queryjson value is either the parsed object ({ url, ... }) or, + // before A-Frame initialised the component, the raw declaration string + // ("url: ./data.json; ..."). Both forms are read the same way, and any + // "url:" prefix that leaked into the url itself is stripped, which also + // heals a value already corrupted to "url: url: ./data.json". + function readQueryJsonUrl(value) { + let raw = ''; + if (typeof value === 'string') { + const match = /(?:^|;)\s*url\s*:\s*([^;]*)/.exec(value); + raw = match ? match[1] : ''; + } else if (value && typeof value.url === 'string') { + raw = value.url; + } + raw = raw.trim(); + while (/^url\s*:/i.test(raw)) { + raw = raw.replace(/^url\s*:\s*/i, ''); + } + return raw.trim(); + } + + // Sets one query parameter and keeps every other one (comparison sources + // carry ?revision=, which the old split('?')[0] dropped). + function withQueryParam(url, key, value) { + const hashIndex = url.indexOf('#'); + const hash = hashIndex >= 0 ? url.slice(hashIndex) : ''; + const withoutHash = hashIndex >= 0 ? url.slice(0, hashIndex) : url; + const queryIndex = withoutHash.indexOf('?'); + const base = queryIndex >= 0 ? withoutHash.slice(0, queryIndex) : withoutHash; + const params = new URLSearchParams(queryIndex >= 0 ? withoutHash.slice(queryIndex + 1) : ''); + params.set(key, String(value)); + return base + '?' + params.toString() + hash; + } + + function isDerivedDataSource(dataEntity) { + // The row-budgeted chart slices hold inline data fed by their producer; + // they have no URL of their own to refresh. + const id = dataEntity && dataEntity.id ? String(dataEntity.id) : ''; + return id.indexOf('codexrChartDataSlice__') === 0; + } + // Cache-busts one data source. Returns false when the entity has no URL + // to refresh (inline data, chart slices), so it is left untouched. + function bustDataSource(dataEntity, timestamp) { + if (!dataEntity || typeof dataEntity.getAttribute !== 'function' || isDerivedDataSource(dataEntity)) { + return false; + } + const queryjson = dataEntity.getAttribute('babia-queryjson'); + if (!queryjson) { + return false; + } + const currentUrl = readQueryJsonUrl(queryjson); + if (!currentUrl) { + return false; + } + const nextUrl = withQueryParam(currentUrl, 't', timestamp); + if (typeof queryjson === 'string') { + const rest = queryjson.split(';') + .map(part => part.trim()) + .filter(part => part && !/^url\s*:/i.test(part)); + dataEntity.setAttribute('babia-queryjson', ['url: ' + nextUrl].concat(rest).join('; ')); + } else { + dataEntity.setAttribute('babia-queryjson', Object.assign({}, queryjson, { url: nextUrl })); + } + return true; + } // Handle analysis-updated events - eventSource.addEventListener('analysis-updated', function(event) { + function handleAnalysisUpdated(event) { liveReloadDebugLog(' Received analysis-updated event:', event); // Find data entities using all provided selectors @@ -181,28 +298,9 @@ const timestamp = Date.now(); liveReloadDebugLog(' Refreshing ' + dataEntities.length + ' data entities'); - // Update each data entity - dataEntities.forEach(dataEntity => { - // Get current attributes - const queryjson = dataEntity.getAttribute('babia-queryjson'); - if (queryjson) { - // Add cache busting parameter - const urlStr = typeof queryjson === 'string' ? queryjson : queryjson.url || ''; - let url = ''; - - if (typeof urlStr === 'string') { - url = urlStr.split('?')[0] + '?t=' + timestamp; - } - - // Handle both string and object attributes - if (typeof queryjson === 'string') { - dataEntity.setAttribute('babia-queryjson', url); - } else { - const newAttr = { ...queryjson }; - newAttr.url = url; - dataEntity.setAttribute('babia-queryjson', newAttr); - } - + // Update each data entity (once, even when it matches both selectors) + Array.from(new Set(dataEntities)).forEach(dataEntity => { + if (bustDataSource(dataEntity, timestamp)) { // Trigger data refresh event after a short delay setTimeout(() => { dataEntity.emit('data-loaded', {}); @@ -238,11 +336,11 @@ if (dataEntities.length === 0) { void completeNormalRefresh(refreshGeneration, 'analysis-updated-no-data', chartEntities); } - }); - + } + // Handle dataRefresh events - eventSource.addEventListener('dataRefresh', function(event) { + function handleDataRefresh(event) { liveReloadDebugLog(' Received dataRefresh event:', event); liveReloadDebugLog(' Reloading data.json for XR chart refresh...'); @@ -256,25 +354,8 @@ liveReloadDebugLog(' Refreshing ' + dataEntities.length + ' data entities with cache busting'); dataEntities.forEach(dataEntity => { - const queryjson = dataEntity.getAttribute('babia-queryjson'); - if (queryjson) { - // Simple cache busting - let A-Frame handle the rest - const urlStr = typeof queryjson === 'string' ? queryjson : queryjson.url || ''; - let newUrl = ''; - - if (typeof urlStr === 'string') { - newUrl = urlStr.split('?')[0] + '?t=' + timestamp; - } - - // Update the data source URL - if (typeof queryjson === 'string') { - dataEntity.setAttribute('babia-queryjson', newUrl); - } else { - const newAttr = { ...queryjson }; - newAttr.url = newUrl; - dataEntity.setAttribute('babia-queryjson', newAttr); - } - + // Simple cache busting - let A-Frame handle the rest + if (bustDataSource(dataEntity, timestamp)) { liveReloadDebugLog(' Data entity refreshed with cache busting'); } }); @@ -308,11 +389,11 @@ if (dataEntities.length === 0) { void completeNormalRefresh(refreshGeneration, 'dataRefresh-no-data', []); } - }); - + } + // Handle general reload messages - eventSource.onmessage = function(event) { + function handleGenericMessage(event) { liveReloadDebugLog('Generic message received:', event.data); // Skip reload if in XR mode @@ -325,4 +406,10 @@ liveReloadDebugLog(' Live reload triggered, refreshing page...'); window.location.reload(); } - }; + } + + if (liveReloadDisabled) { + setLiveReloadStatus('disabled'); + } else { + connectLiveReload(); + } diff --git a/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs b/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs index 07287eca..65d1ffc9 100644 --- a/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs +++ b/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs @@ -453,14 +453,14 @@ test('analysis mode coordinator disposes an activation superseded while it is lo assert.equal(runtime.getState().mode, 'single'); }); -test('normal analysis restores its cached chart immediately and refreshes its revision in place', async () => { +async function runNormalRefreshScenario(initialDataSource) { const source = readAssembledRuntime('analysis-mode', 'analysisModeRuntime.js'); const attributes = new Map([['visible', true]]); const chart = { setAttribute(name, value) { attributes.set(name, value); }, getAttribute(name) { return attributes.get(name); }, }; - let dataSource = { url: 'data.json' }; + let dataSource = initialDataSource; const dataEntity = { getAttribute(name) { return name === 'babia-queryjson' ? dataSource : null; @@ -547,11 +547,25 @@ test('normal analysis restores its cached chart immediately and refreshes its re await new Promise(resolve => setTimeout(resolve, 520)); assert.equal(attributes.get('visible'), true); assert.equal(context.CodeXRAnalysisModeRuntime.getState().mode, 'single'); - const refreshedDataSource = typeof dataSource === 'string' ? dataSource : dataSource.url; - assert.match(refreshedDataSource, /^url: data\.json/); - assert.match(refreshedDataSource, /codexrModeRevision=1/); assert.deepEqual(activeChartIds, ['normalChart']); assert.equal(restoredMapping.lastKnownGoodMapping.area, 'totalLines'); + return typeof dataSource === 'string' ? dataSource : dataSource.url; +} + +test('normal analysis restores its cached chart immediately and refreshes its revision in place', async () => { + const refreshedDataSource = await runNormalRefreshScenario({ url: 'data.json' }); + assert.match(refreshedDataSource, /^url: data\.json/); + assert.match(refreshedDataSource, /codexrModeRevision=1/); +}); + +// XR epic, story S2 (audit LIFECYCLE-7): before A-Frame initialises the data +// component, getAttribute returns the raw declaration "url: ./data.json", and +// reading it as the url produced "url: url: ./data.json?..." for good. +test('normal refresh reads the raw declaration form and heals a corrupted url', async () => { + for (const initial of ['url: ./data.json', 'url: ./data.json; from: tree', { url: 'url: url: ./data.json?t=1' }]) { + const refreshed = await runNormalRefreshScenario(initial); + assert.match(refreshed, /^url: \.\/data\.json\?codexrModeRevision=1&t=\d+$/, JSON.stringify(initial)); + } }); test('XR SSE signals normal analysis readiness after Babia stabilization', () => { diff --git a/apps/vscode-extension/test/analysis/liveReloadClient.test.cjs b/apps/vscode-extension/test/analysis/liveReloadClient.test.cjs new file mode 100644 index 00000000..204de531 --- /dev/null +++ b/apps/vscode-extension/test/analysis/liveReloadClient.test.cjs @@ -0,0 +1,252 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +// XR epic, story S2 (audit CHARTS-10, CHARTS-11, LIFECYCLE-10): the live +// reload clients injected into every generated XR and DOM scene. + +const projectRoot = path.resolve(__dirname, '..', '..'); +const xrSource = fs.readFileSync(path.join(projectRoot, 'templates', 'xr', 'sse', 'live_sse_fileXR.js'), 'utf8'); +const domSource = fs.readFileSync(path.join(projectRoot, 'templates', 'xr', 'sse', 'live_sse_fileDOM.js'), 'utf8'); + +function createEventSourceClass(registry) { + return class FakeEventSource { + constructor(url) { + this.url = url; + this.readyState = 0; + this.listeners = {}; + this.closed = false; + registry.push(this); + } + addEventListener(type, handler) { + (this.listeners[type] = this.listeners[type] || []).push(handler); + } + close() { + this.closed = true; + this.readyState = 2; + } + open() { + this.readyState = 1; + this.onopen?.({}); + } + fail(fatal) { + this.readyState = fatal ? 2 : 0; + this.onerror?.({ type: 'error' }); + } + dispatch(type, data = '{}') { + const event = { type, data }; + if (type === 'message') { + this.onmessage?.(event); + } + for (const handler of this.listeners[type] || []) { + handler(event); + } + } + }; +} + +function createTimers() { + const pending = []; + return { + pending, + setTimeout(fn, ms) { + const timer = { fn, ms, cancelled: false }; + pending.push(timer); + return timer; + }, + clearTimeout(timer) { + if (timer) { + timer.cancelled = true; + } + }, + runAll() { + while (pending.length) { + const timer = pending.shift(); + if (!timer.cancelled) { + timer.fn(); + } + } + }, + }; +} + +function createDataEntity(id, value) { + const entity = { + id, + value, + emitted: [], + getAttribute(name) { + return name === 'babia-queryjson' ? entity.value : null; + }, + setAttribute(name, next) { + if (name === 'babia-queryjson') { + entity.value = next; + } + }, + emit(name) { + entity.emitted.push(name); + }, + }; + return entity; +} + +function loadXrClient({ dataEntities = [], offlineExport = false } = {}) { + const sources = []; + const timers = createTimers(); + const statuses = []; + const context = { + console: { log() {}, warn() {}, error() {} }, + URLSearchParams, + EventSource: null, + setTimeout: timers.setTimeout, + clearTimeout: timers.clearTimeout, + fetch: () => Promise.resolve({ ok: false }), + CustomEvent: class CustomEvent { + constructor(type, init) { + this.type = type; + this.detail = init && init.detail; + } + }, + document: { + getElementById(id) { + if (id === 'codexr-tooling-config-virtual-screen') { + return { textContent: JSON.stringify({ offlineExport }) }; + } + return null; + }, + querySelector() { + return { tagName: 'A-SCENE' }; + }, + querySelectorAll(selector) { + return selector === '[babia-queryjson]' ? dataEntities : []; + }, + addEventListener() {}, + dispatchEvent(event) { + if (event.type === 'codexr-live-reload-status') { + statuses.push(event.detail.status); + } + }, + }, + }; + context.EventSource = createEventSourceClass(sources); + context.window = context; + vm.runInNewContext(xrSource, context, { filename: 'live_sse_fileXR.js' }); + return { context, sources, timers, statuses }; +} + +test('XR live reload: a connection the browser gave up on is reopened with every handler bound', () => { + const data = createDataEntity('data', { url: './data.json' }); + const { sources, timers, statuses } = loadXrClient({ dataEntities: [data] }); + assert.equal(sources.length, 1); + sources[0].open(); + + sources[0].fail(true); + assert.equal(sources.length, 1, 'no reconnect before the back-off delay'); + assert.equal(timers.pending.at(-1).ms, 1000); + timers.runAll(); + + assert.equal(sources.length, 2); + sources[1].open(); + sources[1].dispatch('dataRefresh'); + assert.match(data.value.url, /^\.\/data\.json\?t=\d+$/, 'the reconnected source still refreshes the data'); + assert.deepEqual(statuses.slice(0, 4), ['connecting', 'open', 'reconnecting', 'connecting']); +}); + +test('XR live reload: the browser\'s own retry is left alone, and back-off doubles up to its cap', () => { + const { sources, timers } = loadXrClient(); + sources[0].fail(false); + assert.equal(timers.pending.length, 0, 'a CONNECTING source is retried by the browser itself'); + assert.equal(sources[0].closed, false); + + const delays = []; + for (let attempt = 0; attempt < 7; attempt += 1) { + sources.at(-1).fail(true); + delays.push(timers.pending.at(-1).ms); + timers.runAll(); + } + assert.deepEqual(delays, [1000, 2000, 4000, 8000, 16000, 30000, 30000]); + sources.at(-1).open(); + sources.at(-1).fail(true); + assert.equal(timers.pending.at(-1).ms, 1000, 'a successful connection resets the back-off'); +}); + +test('XR live reload: events from a replaced connection are ignored', () => { + const { sources, timers } = loadXrClient(); + const first = sources[0]; + first.fail(true); + timers.runAll(); + first.fail(true); + assert.equal(timers.pending.length, 0); +}); + +test('XR live reload: cache busting keeps query parameters and skips sources without a url', () => { + const plain = createDataEntity('data', { url: './data.json', from: '' }); + const revision = createDataEntity('compareRight', { url: './comparison/revision-2/data.json?revision=abc' }); + const slice = createDataEntity('codexrChartDataSlice__data', { url: '', data: '[]' }); + const inline = createDataEntity('inline', { url: '', data: '[1]' }); + const raw = createDataEntity('raw', 'url: ./tree.json; path: x'); + const poisoned = createDataEntity('poisoned', { url: 'url: url: ./data.json?codexrModeRevision=1' }); + const { sources, timers } = loadXrClient({ dataEntities: [plain, revision, slice, inline, raw, poisoned] }); + sources[0].open(); + sources[0].dispatch('analysis-updated'); + timers.runAll(); + + assert.match(plain.value.url, /^\.\/data\.json\?t=\d+$/); + assert.equal(plain.value.from, ''); + assert.match(revision.value.url, /^\.\/comparison\/revision-2\/data\.json\?revision=abc&t=\d+$/); + assert.deepEqual(slice.value, { url: '', data: '[]' }); + assert.deepEqual(inline.value, { url: '', data: '[1]' }); + assert.match(raw.value, /^url: \.\/tree\.json\?t=\d+; path: x$/); + assert.match(poisoned.value.url, /^\.\/data\.json\?codexrModeRevision=1&t=\d+$/); + assert.deepEqual(plain.emitted, ['data-loaded']); + assert.deepEqual(slice.emitted, []); +}); + +test('XR live reload: an offline export never opens a connection', () => { + const { sources, statuses } = loadXrClient({ offlineExport: true }); + assert.equal(sources.length, 0); + assert.deepEqual(statuses, ['disabled']); +}); + +function loadDomClient() { + const sources = []; + const timers = createTimers(); + const reloads = []; + const context = { + console: { log() {}, warn() {}, error() {} }, + setTimeout: timers.setTimeout, + clearTimeout: timers.clearTimeout, + requestAnimationFrame: (fn) => fn(), + location: { reload: () => reloads.push(Date.now()) }, + document: { + querySelector() { return null; }, + addEventListener() {}, + }, + }; + context.EventSource = createEventSourceClass(sources); + context.window = context; + vm.runInNewContext(domSource, context, { filename: 'live_sse_fileDOM.js' }); + return { sources, timers, reloads }; +} + +test('DOM live reload: errors never reload the page in a loop; one reload once the server is back', () => { + const { sources, timers, reloads } = loadDomClient(); + sources[0].open(); + for (let attempt = 0; attempt < 5; attempt += 1) { + sources.at(-1).fail(true); + timers.runAll(); + } + assert.equal(reloads.length, 0, 'no reload while the server is unreachable'); + assert.equal(sources.length, 6); + sources.at(-1).open(); + assert.equal(reloads.length, 1, 'reload once to pick up updates missed while disconnected'); +}); + +test('DOM live reload: a reconnected source still applies HTML updates', () => { + const { sources, timers } = loadDomClient(); + sources[0].fail(true); + timers.runAll(); + assert.equal(sources[1].listeners.message.length, 1); +});