From 4f5fe9d8cddbf9940ff844e750ab496f2d2f2c12 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:31:49 +0000 Subject: [PATCH] fix(xr): an analysis that hangs or fails can no longer freeze the switcher Story S7 (#79) of epic #72. The in-scene mode switcher queued every transition behind the previous one with no limit, so one activate that never settled froze it for the session (LIFECYCLE-1). - changeAnalysis cancels instead of queueing: a newer pick aborts the activation in flight (AbortSignal on the activation and its token), activate has a timeout (45 s, project evolution 90 s), the cleanup hooks are abandoned after 8 s, and an abandoned activate that settles later is deactivated again. - A failure lands on the selector with its reason and a "Retry" option, does not become requestedMode, tells the room when the pick was local, and the room's echo of the failed pick is ignored (LIFECYCLE-3). - openSelector skips its selection announcement when a newer pick happened meanwhile (LIFECYCLE-2). - Dependency graph and historical comparison pass the signal to fetch and reject on a load failure; the dependency load error is sticky (LIFECYCLE-5); the dependency start shows progress on the selector, re-arms its watchdog on progress, attaches to a running analysis and bounds its send retries (LIFECYCLE-6, DEPGRAPH-7). - Project evolution re-entry after a half-built frame no longer throws (LIFECYCLE-4). - Collaboration: per-runtime error isolation with logging, analysis-view applied last, reconnect back-off, revision floor reset by a room snapshot, no silent give-up registering (LIFECYCLE-9, LIFECYCLE-11). - The end of a containment fit animation no longer re-shows a chart hidden meanwhile. - The mode and immersive harnesses are served over HTTP so the modes' datasets load. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKtAtQus8TVjhG9bhytC --- .claude/docs/DEVELOPMENT.md | 2 +- apps/vscode-extension/CHANGELOG.md | 9 + .../templates/components/COMPONENTS.md | 20 ++ .../constantsAndDomUtils.js | 20 +- .../analysisModeRuntime/selectorAndPanel.js | 291 ++++++++++++++++-- .../snapshotsAndLifecycles.js | 46 ++- .../transitionsAndViews.js | 16 +- .../containmentComponentCore.js | 6 + .../codexrCollaborationRuntime/clientCore.js | 23 +- .../codexrCollaborationRuntime/entitySync.js | 21 +- .../moduleAndConfig.js | 2 + .../dependencyGraphRuntime/configAndStatus.js | 5 + .../datasetProjection.js | 3 + .../scalesAndControls.js | 4 +- .../dependencyGraphRuntime/viewLifecycle.js | 106 ++++++- .../compareFlowAndMessages.js | 12 +- .../liveRefreshAndRegistration.js | 16 +- .../transportAndRegistration.js | 10 +- apps/vscode-extension/test/README.md | 2 +- .../analysisModeLifecycleContract.test.cjs | 272 ++++++++++++++++ .../analysis/analysisModeMegatest.test.cjs | 10 +- .../analysis/collaborationRuntime.test.cjs | 91 ++++++ .../test/analysis/dependencyGraph.test.cjs | 53 ++++ .../test/helpers/staticHttpServer.cjs | 73 +++++ .../test/runners/run-xr-immersive-harness.cjs | 15 +- .../runners/run-xr-mode-cycle-harness.cjs | 15 +- 26 files changed, 1068 insertions(+), 75 deletions(-) create mode 100644 apps/vscode-extension/test/analysis/analysisModeLifecycleContract.test.cjs create mode 100644 apps/vscode-extension/test/helpers/staticHttpServer.cjs diff --git a/.claude/docs/DEVELOPMENT.md b/.claude/docs/DEVELOPMENT.md index 8b7ec4a7..d03b293c 100644 --- a/.claude/docs/DEVELOPMENT.md +++ b/.claude/docs/DEVELOPMENT.md @@ -32,7 +32,7 @@ | `npm run test:htmlanalysis` | `test/runners/run-html-analysis-tests.cjs`: `test/analysis/livePanelDomIntegration.test.cjs` plus the Python suite `backend/tests/html_dom/` | After touching `backend/src/html/html_dom_parser.py` or DOM mode | | `npm run test:xr-harness` | `test/runners/run-xr-containment-harness.cjs` (browser harness, uses Playwright) | After touching table/containment runtimes | | `npm run test:xr-chart-bounds-harness` | `test/runners/run-xr-chart-bounds-harness.cjs` (generates REAL directory scenes with the compiled generator, opens them with A-Frame + BabiaXR in Playwright, asserts every chart type ends on the table for 3/30/300 files and that row-budgeted charts only ever read the slice; `CODEXR_CHART_BOUNDS_TYPES` / `CODEXR_CHART_BOUNDS_ROWS` narrow it; about 4 minutes) | After touching chart generation, containment, the row slice or the Babia compatibility patches | -| `npm run test:xr-mode-harness` | `test/runners/run-xr-mode-cycle-harness.cjs` — static contract over `test/manual/xr-mode-cycle-harness.html`, then (with Playwright) walks the analysis selector through every mode and back, asserting the controller's view/mode state at each step | After touching the analysis-mode controller, mapping UI, historical comparison or dependency graph runtimes | +| `npm run test:xr-mode-harness` | `test/runners/run-xr-mode-cycle-harness.cjs` — static contract over `test/manual/xr-mode-cycle-harness.html`, then (with Playwright) walks the analysis selector through every mode and back, asserting the controller's view/mode state at each step. Served over HTTP (`test/helpers/staticHttpServer.cjs`), so the modes' datasets really load; from `file://` Chromium blocked every fetch | After touching the analysis-mode controller, mapping UI, historical comparison or dependency graph runtimes | | `npm run test:project-evolution-harness` | `test/runners/run-project-evolution-harness.cjs` — Project Evolution playback harness (screenshots under `output/project-evolution-harness/`) | After touching project-evolution runtime | | `npm run test:xr-immersive-harness` | `test/runners/run-xr-immersive-harness.cjs` — AR/VR semantics against real A-Frame: AR hide/keep sets, rig floor-align + AR recenter, pointer handover; plus a static contract over both scene templates | After touching the scene templates, pointer-policy or immersive-rig | | `npm run package` | Production webpack build (hidden source maps) | Pre-packaging | diff --git a/apps/vscode-extension/CHANGELOG.md b/apps/vscode-extension/CHANGELOG.md index 91fb2e35..3e694c93 100644 --- a/apps/vscode-extension/CHANGELOG.md +++ b/apps/vscode-extension/CHANGELOG.md @@ -34,6 +34,15 @@ #### Fixed +- **The analysis switcher in the XR scene no longer gets stuck.** One analysis that never finished opening (a dependency or comparison file that never arrived over a slow tunnel, for example) froze the switcher for the rest of the session: every later pick, Normal analysis included, waited behind it until the page was reloaded. Several related problems are fixed: + - A new pick now cancels the analysis that is still opening and starts at once, and an analysis that takes longer than 45 s to open (90 s for project evolution) is reported as failed. + - When an analysis cannot open, the selector says why, and its option reads "Retry: …". Before, the message went to a panel that is hidden while the selector is up, so nothing seemed to happen. The failed analysis is no longer reopened by the "Analyses" button or by the room's echo of the pick, and the other participants are sent back to the selector instead of staying in the failed analysis. + - Dependency data that cannot be loaded (a server error, a stale link after a restart) now fails visibly instead of leaving an empty table whose panel says "ready", and the error stays on the dependency panel. + - Picking an analysis right after opening the selector no longer snaps you, and everyone in the room, back to the empty selector a second later. + - Opening the dependency graph shows its progress on the selector; a second click says it is still opening; a long first analysis is no longer reported as "did not respond" after 20 s while it is still progressing; picking it while a refresh runs joins that refresh instead of being refused; and the start request stops retrying after 20 s without a connection, with a message. + - Re-entering project evolution after a frame that failed half-way no longer throws and bounces to the selector every time. + - A chart that was hidden while its fit animation ran no longer reappears on the empty selector when the animation ends. + - In collaboration, one part of the scene that fails to apply a room update no longer silently drops the rest of it (the analysis shown is applied last and the failure is logged), a page that rejoins a restarted session follows the room again, a late-loading page keeps waiting for the room instead of giving up after 3 s, and reconnecting backs off up to 15 s instead of retrying every 0.9 s. - **Panels in the XR scene no longer show the content behind them.** Opening an element's info card in front of a virtual screen or the guide mixed the text of both: the card skipped the depth test, and the scene draws see-through surfaces in page order rather than by distance, so screens farther away were painted over it. Info cards, the dependency-graph path chip, virtual screens, the guide, the controller panel, the "Virtual screens" list, the comparison card and the evolution overlay now have opaque, depth-tested backings. Clicking an info card no longer passes through it to whatever is behind (it could start a screen share), and a virtual screen's idle message now wraps inside the screen instead of spilling past its edges. - **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. diff --git a/apps/vscode-extension/templates/components/COMPONENTS.md b/apps/vscode-extension/templates/components/COMPONENTS.md index 9681d987..e3d9191a 100644 --- a/apps/vscode-extension/templates/components/COMPONENTS.md +++ b/apps/vscode-extension/templates/components/COMPONENTS.md @@ -51,6 +51,23 @@ its parts directory. Manual harnesses load assembled copies from - Feeds row-budgeted charts (everything except boats) from a top-N sliced `babia-queryjson` datasource (`chartDataSlice.js` part): ranked by the mapped magnitude, rows violating `numeric-positive` value rules filtered out, one row per Babia element key. Chart construction (rotation, base attributes, budgets) follows the generator-injected presentation profile (`#codexr-chart-base-config`), with a fallback mirror in `mappingProfiles.js`. - `codexr/analysis-mode/analysisModeRuntime.js` - Owns mode switching between normal analysis, historical comparison and dependency graph. + - **Mode lifecycle contract** (epic #72, S7). `changeAnalysis` cancels instead of queueing: + a newer pick aborts the activation in flight (`activation.signal`, also on + `activation.token.signal`; `token.isCurrent()` turns false) and starts at once. A lifecycle + passes that signal to every `fetch` and returns early from `activate` when the token is no + longer current. `activate` has a timeout (`activateTimeoutMs` on the lifecycle, default 45 s; + project evolution declares 90 s); `captureState`/`restoreState`/`deactivate` are abandoned + after 8 s. An abandoned activate that settles later is deactivated once more. A failure (throw, + rejection or timeout) lands on the selector with the reason on its own status line and the + failed option relabelled "Retry: …", does not become `requestedMode`, and sends + `analysis-mode-selection` when the pick was local (not for a failure caused by the room's + echo); the echo of the failed pick is ignored for 5 s. `openSelector` announces the selection + only if no newer pick happened meanwhile. A mode reports opening progress with + `setSelectorStatus(message, tone)`. `getState()` exposes `activation`, `lastError` and + `selectorStatus`. A lifecycle whose data cannot load must reject (dependency graph and + historical comparison do, through `applySharedState(snapshot, { signal, rethrow: true })`), + never sit on an empty table that says "ready". Pinned by + `test/analysis/analysisModeLifecycleContract.test.cjs`. - `codexr/dependency-graph/dependencyGraphRuntime.js` - Owns the dependency graph visualization, layouts, filters, navigation and dependency-specific interaction. - Uses `CodeXRCommonRuntime` for tooltip presentation and billboard behavior. @@ -89,6 +106,9 @@ its parts directory. Manual harnesses load assembled copies from - Owns shared presence, identity, avatars, pointers and collaboration entities. - Terminal disconnects show a full-page screen (`disconnectScreen.js` part) and stop the reconnect loop: `session-ended` (host stopped the server) and `participant-kick`. + - Reconnects back off exponentially (0.9 s doubling, 15 s cap, jitter), reset on open. A + runtime that throws while applying a message or a snapshot entity is logged and isolated, so + the rest of the snapshot still applies; the `analysis-view` entity is applied last. - **Passive mode-entity contract** (applies to EVERY analysis-mode runtime, present and future): a mode's shared entity (`dependency-graph`, `historical-comparison`, `project-evolution`, …) carries DATA, never intent. `applySharedState` stores the payload and renders only if its own diff --git a/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/constantsAndDomUtils.js b/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/constantsAndDomUtils.js index d7947ff8..74236581 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/constantsAndDomUtils.js +++ b/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/constantsAndDomUtils.js @@ -62,8 +62,26 @@ selectionPanelView: 'visualization-mode', controllerView: 'single.mapping', panelRoot: null, - openingSelectorFromPanel: false + openingSelectorFromPanel: false, + // The activation in flight ({ mode, generation, abort }): a newer intent + // aborts it instead of queueing behind it (LIFECYCLE-1). + activation: null, + // The last activation that failed ({ mode, message, at }), shown on the + // selector until the next successful one (LIFECYCLE-3). + lastError: null, + // The room's echo of a mode that just failed here is not re-run. + suppressEcho: null, + // A progress line a mode reports while it opens, shown on the selector. + selectorStatus: null }; + // A mode's activate may take this long before it is treated as failed; a + // lifecycle can declare its own activateTimeoutMs (project evolution does). + var DEFAULT_ACTIVATE_TIMEOUT_MS = 45000; + // captureState/restoreState/deactivate are cleanup steps: one that hangs + // must not hold the switcher. + var LIFECYCLE_HOOK_TIMEOUT_MS = 8000; + // How long the room's echo of a mode that failed here is ignored. + var FAILED_MODE_ECHO_WINDOW_MS = 5000; function debugLog() { var args = Array.prototype.slice.call(arguments); diff --git a/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/selectorAndPanel.js b/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/selectorAndPanel.js index 254cad03..51d8825d 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/selectorAndPanel.js +++ b/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/selectorAndPanel.js @@ -7,7 +7,88 @@ } /** - * Like invoke(), but failures are logged and swallowed (sync throws too). + * An abort handle with the AbortSignal shape. The real AbortController is + * used when the page has one, so a lifecycle can hand the signal straight to + * fetch(); the fallback keeps the runtime working in a bare vm context. + */ + function createAbortHandle() { + if (typeof root.AbortController === 'function') { + return new root.AbortController(); + } + var listeners = []; + var signal = { + aborted: false, + reason: undefined, + addEventListener: function (type, listener) { + if (type === 'abort' && typeof listener === 'function') { listeners.push(listener); } + }, + removeEventListener: function (type, listener) { + listeners = listeners.filter(function (candidate) { return candidate !== listener; }); + } + }; + return { + signal: signal, + abort: function (reason) { + if (signal.aborted) { return; } + signal.aborted = true; + signal.reason = reason; + listeners.splice(0).forEach(function (listener) { + try { listener({ type: 'abort' }); } catch (_error) { /* a listener cannot stop the abort */ } + }); + } + }; + } + + function createModeError(code, message) { + var error = new Error(message); + error.name = code === 'aborted' ? 'AbortError' : 'CodeXRModeError'; + error.code = code; + return error; + } + + /** + * Settles with `promise`, or rejects once `timeoutMs` passes or `signal` + * aborts, whichever comes first. The lifecycle's own promise keeps running; + * this only stops the switcher from waiting on it. + */ + function settleWithin(promise, timeoutMs, signal, label) { + return new Promise(function (resolve, reject) { + var done = false; + var timer = null; + var onAbort = null; + function finish(callback, value) { + if (done) { return; } + done = true; + if (timer !== null) { root.clearTimeout?.(timer); } + if (onAbort) { signal?.removeEventListener?.('abort', onAbort); } + callback(value); + } + if (signal?.aborted) { + finish(reject, createModeError('aborted', label + ' was cancelled by a newer request.')); + return; + } + if (timeoutMs > 0 && typeof root.setTimeout === 'function') { + timer = root.setTimeout(function () { + finish(reject, createModeError('timeout', label + ' did not finish within ' + Math.round(timeoutMs / 1000) + ' s.')); + }, timeoutMs); + } + if (signal?.addEventListener) { + onAbort = function () { + finish(reject, createModeError('aborted', label + ' was cancelled by a newer request.')); + }; + signal.addEventListener('abort', onAbort); + } + Promise.resolve(promise).then(function (value) { + finish(resolve, value); + }, function (error) { + finish(reject, error); + }); + }); + } + + /** + * Like invoke(), but failures are logged and swallowed (sync throws too), + * and a hook that never settles is abandoned after LIFECYCLE_HOOK_TIMEOUT_MS. * Lifecycle hooks run through this: a mode that * fails to clean up may degrade itself, but it must never abort the * transition — otherwise the table keeps the old mode's theme and the @@ -15,7 +96,12 @@ */ function invokeSafely(lifecycle, method, context) { try { - return invoke(lifecycle, method, context).catch(function (error) { + return settleWithin( + invoke(lifecycle, method, context), + LIFECYCLE_HOOK_TIMEOUT_MS, + null, + 'Lifecycle ' + method + ).catch(function (error) { root.console?.error?.('[CodeXR][AnalysisMode] Lifecycle ' + method + ' failed:', error); }); } catch (error) { @@ -24,6 +110,16 @@ } } + function getModeLabel(mode) { + if (mode === 'single') { return 'Normal analysis'; } + var option = state.modeOptions.find(function (candidate) { return candidate.id === mode; }); + return option?.label || String(mode || 'this analysis'); + } + + function describeError(error) { + return error && typeof error.message === 'string' ? error.message : String(error); + } + function register(mode, lifecycle) { if (!VALID_MODES.has(mode) || !lifecycle) { return function () {}; @@ -39,6 +135,8 @@ if (!state.transitioning && state.mode === mode) { state.activeLifecycleMode = mode; } + }).catch(function (error) { + root.console?.error?.('[CodeXR][AnalysisMode] Could not activate late-registered mode:', mode, error); }); } return function () { @@ -136,18 +234,47 @@ }); } + /** + * The line above the options. It is the selector's own status line: an + * analysis that failed to open says so here (with its option relabelled + * "Retry"), and a mode that is still opening reports its progress here. + * Before, both went to the mapping view's status line, which is hidden + * while the selector is up, so a failure read as "nothing happened". + */ + function getSelectorHeadline() { + if (state.lastError) { + return { + value: 'Could not open ' + getModeLabel(state.lastError.mode) + ': ' + state.lastError.message + + '\nPick it again to retry, or choose another analysis.', + color: '#fecaca', + tone: 'error' + }; + } + if (state.selectorStatus?.message) { + return { + value: state.selectorStatus.message, + color: state.selectorStatus.tone === 'error' ? '#fecaca' : '#fde68a', + tone: state.selectorStatus.tone || 'info' + }; + } + return { value: 'Choose how the analysis table represents the data.', color: '#cde7ff', tone: 'info' }; + } + function renderModeOptions() { if (!state.panelRoot) { return; } while (state.panelRoot.firstChild) { state.panelRoot.removeChild(state.panelRoot.firstChild); } + var headline = getSelectorHeadline(); state.panelRoot.appendChild(createEntity('a-text', { - value: 'Choose how the analysis table represents the data.', + value: headline.value, position: '0 1.18 0.02', width: 5.5, - color: '#cde7ff', + color: headline.color, align: 'center', - baseline: 'center' + baseline: 'center', + 'wrap-count': 52, + 'data-codexr-mode-selector-status': headline.tone })); var options = [{ id: 'single', @@ -158,10 +285,25 @@ } }].concat(state.modeOptions); options.forEach(function (option, index) { - state.panelRoot.appendChild(createModeButton(option, 0.55 - (index * 0.62))); + var shown = option; + if (state.lastError?.mode === option.id && option.disabled !== true) { + shown = Object.assign({}, option, { label: 'Retry: ' + option.label }); + } + state.panelRoot.appendChild(createModeButton(shown, 0.55 - (index * 0.62))); }); } + /** + * Lets a mode report progress on the selector while it opens (the + * dependency graph's "Opening dependencies…", for one). Pass an empty + * message to clear it. + */ + function setSelectorStatus(message, tone) { + var text = String(message || '').trim(); + state.selectorStatus = text ? { message: text, tone: tone === 'error' ? 'error' : 'info', at: Date.now() } : null; + renderModeOptions(); + } + function registerModeOption(option) { if (!option?.id || typeof option.onSelect !== 'function') { return function () {}; @@ -196,11 +338,24 @@ transitioning: state.transitioning }); state.selectionPanelView = 'visualization-mode'; - return changeAnalysis('selection', { + var transition = changeAnalysis('selection', { reason: 'local-mode-selection', controllerView: 'visualization-menu', panelViewId: 'visualization-mode' - }).then(function () { + }); + // The generation this intent owns. If the user picks an analysis before + // the selection transition lands, that pick is newer: announcing the + // selection afterwards would make the room (and this page, through the + // echo) snap back to the empty selector (LIFECYCLE-2). + var selectionGeneration = state.generation; + return transition.then(function () { + if (state.generation !== selectionGeneration) { + debugLog('Selection announcement skipped: a newer analysis was picked', { + selectionGeneration: selectionGeneration, + generation: state.generation + }); + return false; + } root.CodeXRCollaborationRuntime?.getClient?.(root) ?.sendMessage?.('analysis-mode-selection', {}); return true; @@ -275,6 +430,45 @@ renderModeOptions(); } + /** + * An activation the switcher stopped waiting for (a newer pick, or its + * timeout) keeps running in the lifecycle. When it does settle, and its + * mode is no longer the one on the table, it is deactivated once more so + * whatever it mounted late is removed. + */ + function watchAbandonedActivation(mode, lifecycle, rawActivation, token) { + Promise.resolve(rawActivation).catch(function () {}).then(function () { + if (state.activeLifecycleMode === mode || state.pendingTransitionMode === mode) { + return; + } + debugLog('Abandoned activation settled; cleaning up', { mode: mode }); + return invokeSafely(lifecycle, 'deactivate', { + from: mode, + to: state.mode, + generation: token?.generation, + context: { reason: 'abandoned-activation-settled' }, + token: token + }); + }); + } + + /** + * A failed activation lands on the selector with the reason shown there, + * and the room is told, so the server and every guest leave the failed + * mode too. The room's echo of the failed pick (already in flight) is not + * re-run here. + */ + function recordActivationFailure(mode, error, context) { + state.lastError = { mode: mode, message: describeError(error), code: error?.code || 'error', at: Date.now() }; + state.suppressEcho = { mode: mode, until: Date.now() + FAILED_MODE_ECHO_WINDOW_MS }; + state.selectorStatus = null; + renderModeOptions(); + if (context?.reason !== 'authoritative-analysis-view') { + root.CodeXRCollaborationRuntime?.getClient?.(root) + ?.sendMessage?.('analysis-mode-selection', {}); + } + } + async function performTransition(mode, context, generation) { var previousMode = state.activeLifecycleMode; var activationToken = createActivationToken(mode, generation); @@ -314,52 +508,89 @@ token: activationToken }); if (generation !== state.generation) { return false; } + // requestedMode is what "Analyses" resumes; a mode that fails to open + // must not become it (pressing the header would retry the failure). + var requestedBefore = state.requestedMode; applyAnalysisMode(mode, context || null); + var lifecycle = lifecycles[mode]; + var abortHandle = createAbortHandle(); + var activation = { mode: mode, generation: generation, abort: abortHandle, startedAt: Date.now() }; + state.activation = activation; + activationToken.signal = abortHandle.signal; + var timeoutMs = Number(lifecycle?.activateTimeoutMs) > 0 + ? Number(lifecycle.activateTimeoutMs) + : DEFAULT_ACTIVATE_TIMEOUT_MS; + var rawActivation; try { - await invoke(lifecycles[mode], 'activate', { + rawActivation = invoke(lifecycle, 'activate', { from: previousMode, to: mode, generation: generation, context: context || null, savedState: state.modeSnapshots[mode], - token: activationToken + token: activationToken, + signal: abortHandle.signal }); } catch (error) { - if (generation === state.generation) { - await invokeSafely(lifecycles[mode], 'deactivate', { - from: mode, - to: 'selection', - generation: generation, - context: { reason: 'activation-error', error: error }, - token: activationToken - }); - applyAnalysisMode('selection', { panelViewId: state.selectionPanelView }); - await clearVisualizationsForSelection({ generation: generation }); + rawActivation = Promise.reject(error); + } + try { + await settleWithin(rawActivation, timeoutMs, abortHandle.signal, 'Opening ' + getModeLabel(mode)); + } catch (error) { + if (state.activation === activation) { state.activation = null; } + if (error?.code === 'aborted' || generation !== state.generation) { + // Superseded: the newer transition deactivates this mode as its + // previous one. If the abandoned activate settles later, it is + // cleaned up then (it may have mounted something after that). + watchAbandonedActivation(mode, lifecycle, rawActivation, activationToken); + debugLog('Analysis mode activation abandoned for a newer request', { mode: mode, generation: generation }); + return false; + } + // Stop the lifecycle's own work (fetches honour the signal), then clean up. + abortHandle.abort(error); + if (error?.code === 'timeout') { + watchAbandonedActivation(mode, lifecycle, rawActivation, activationToken); } - // Say it on the controller too: a failed activation silently bounces the - // user back to the analysis selector, which reads as "this analysis just - // won't open" with no clue why. - root.CodeXRMappingUiRuntime?.setStatusMessage?.( - 'CodeXR could not open this analysis. ' + (error instanceof Error ? error.message : String(error)), - 'error', - 6000 - ); + await invokeSafely(lifecycle, 'deactivate', { + from: mode, + to: 'selection', + generation: generation, + context: { reason: 'activation-error', error: error }, + token: activationToken + }); + if (generation !== state.generation) { return false; } + // The room's echo of this pick may already have set it (it can land + // before the transition starts); either way it must not be the failed + // mode. + state.requestedMode = requestedBefore !== mode ? requestedBefore : 'single'; + recordActivationFailure(mode, error, context); + applyAnalysisMode('selection', { panelViewId: 'visualization-mode', controllerView: 'visualization-menu' }); + await clearVisualizationsForSelection({ generation: generation }); console.error('[CodeXR][AnalysisMode] Could not activate mode:', mode, error); return false; } + if (state.activation === activation) { state.activation = null; } if (generation !== state.generation) { - await invokeSafely(lifecycles[mode], 'deactivate', { + await invokeSafely(lifecycle, 'deactivate', { from: mode, to: null, generation: generation, context: { reason: 'superseded-activation' }, token: activationToken }); - if (state.activeLifecycleMode === mode) { + if (state.activeLifecycleMode === mode && state.pendingTransitionMode !== mode) { state.activeLifecycleMode = null; } return false; } + if (mode !== 'selection') { + state.lastError = null; + state.suppressEcho = null; + } + if (state.selectorStatus || mode !== 'selection') { + state.selectorStatus = null; + renderModeOptions(); + } // The mode was applied once before activate (the lifecycle needs it in // place while it mounts). Re-applying it here would redo the table geometry // and the panel routing — and overwrite the view the lifecycle just chose 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 8ae149ed..8958034f 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 @@ -222,8 +222,15 @@ if (state.collaborationRegistered) { return; } var client = root.CodeXRCollaborationRuntime?.getClient?.(root); if (!client?.registerEntityRuntime) { - if (attempt < 30) { - root.setTimeout?.(function () { registerCollaboration(attempt + 1); }, 100); + // Keep looking, slower after 3 s, instead of giving up: a page whose + // collaboration client loads late used to ignore every mode change of + // the room, silently (LIFECYCLE-11). No client after a minute means + // this page has no room (a standalone scene). + if (attempt === 30) { + root.console?.warn?.('[CodeXR][AnalysisMode] Collaboration client not ready after 3 s; still waiting for it.'); + } + if (attempt < 90) { + root.setTimeout?.(function () { registerCollaboration(attempt + 1); }, attempt < 30 ? 100 : 1000)?.unref?.(); } return; } @@ -231,9 +238,15 @@ client.registerEntityRuntime({ entityKind: 'analysis-view', entityId: 'main', - applySharedState: function (snapshot) { + applySharedState: function (snapshot, meta) { if (VALID_MODES.has(snapshot?.mode)) { var viewRevision = Number(snapshot?.viewRevision || 0); + // A room snapshot (join or re-join) is the room's whole current + // state: it resets the revision floor, so a server whose session + // restarted at a lower revision is not ignored as "stale" forever. + if (meta?.source === 'snapshot') { + state.lastAuthoritativeViewRevision = 0; + } if ( viewRevision > 0 && viewRevision < state.lastAuthoritativeViewRevision @@ -257,6 +270,17 @@ sourceRevision: Number(snapshot.sourceRevision || 0) }; } + // The echo of a pick that just failed on this page: re-running it + // would fail again (twice per click, before). The failure already + // told the room to go back to the selector. + if ( + state.suppressEcho + && state.suppressEcho.mode === snapshot.mode + && Date.now() < state.suppressEcho.until + ) { + debugLog('Ignored the echo of an analysis that just failed here', { mode: snapshot.mode }); + return; + } state.requestedMode = snapshot.mode === 'selection' ? state.requestedMode : snapshot.mode; var visibleMode = snapshot.mode; // Echo dedupe: a transition toward this exact mode is already in @@ -267,6 +291,7 @@ if (state.transitioning && state.pendingTransitionMode === visibleMode) { return; } + // View routing: the mode's own lifecycle resolver wins over the // snapshot's controllerView. The server-side view can be stale (its // historical-comparison entity persists after the client clears the @@ -309,12 +334,21 @@ transitioning: state.transitioning, pendingTransitionMode: state.pendingTransitionMode, lastAuthoritativeViewRevision: state.lastAuthoritativeViewRevision, - generation: state.generation + generation: state.generation, + activation: state.activation + ? { mode: state.activation.mode, generation: state.activation.generation, runningMs: Date.now() - state.activation.startedAt } + : null, + lastError: state.lastError ? Object.assign({}, state.lastError) : null, + selectorStatus: state.selectorStatus ? Object.assign({}, state.selectorStatus) : null }; }, + setSelectorStatus: setSelectorStatus, __testing: { clearVisualizationsForSelection: clearVisualizationsForSelection, removeResidualVisualRoots: removeResidualVisualRoots, + setHookTimeoutMs: function (ms) { + LIFECYCLE_HOOK_TIMEOUT_MS = Number(ms) > 0 ? Number(ms) : LIFECYCLE_HOOK_TIMEOUT_MS; + }, reset: function () { Object.keys(lifecycles).forEach(function (key) { delete lifecycles[key]; }); state.mode = 'single'; @@ -332,6 +366,10 @@ state.lastNormalModeRevision = 0; state.modeOptions = []; state.selectionPanelView = 'visualization-mode'; + state.activation = null; + state.lastError = null; + state.suppressEcho = null; + state.selectorStatus = null; } } }; diff --git a/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/transitionsAndViews.js b/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/transitionsAndViews.js index f73159a5..6b79ca58 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/transitionsAndViews.js +++ b/apps/vscode-extension/templates/components/codexr/analysis-mode/analysisModeRuntime/transitionsAndViews.js @@ -43,6 +43,13 @@ }); } var generation = ++state.generation; + // Cancel, don't queue: the activation in flight belongs to an older + // intent. Before, this transition waited behind it with no limit, so one + // activate that never settled (a stalled dataset fetch) froze the switcher + // for the rest of the session (LIFECYCLE-1). + if (state.activation && state.activation.generation !== generation) { + state.activation.abort.abort(createModeError('aborted', 'Superseded by ' + mode + '.')); + } state.transitioning = true; // Target of the latest queued transition — lets the authoritative-echo // handler recognise a duplicate before it queues a second full cycle. @@ -226,17 +233,22 @@ } function createActivationToken(mode, generation) { - return { + var token = { mode: mode, generation: generation, + // Set by performTransition: aborted when a newer pick supersedes this + // activation or it times out. Lifecycles pass it to fetch(). + signal: null, isCurrent: function () { - return generation === state.generation + return !token.signal?.aborted + && generation === state.generation && ( state.pendingTransitionMode === mode || (!state.transitioning && state.mode === mode) ); } }; + return token; } function captureElementTransform(element) { diff --git a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/containmentComponentCore.js b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/containmentComponentCore.js index 33de6064..e385ff6e 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/containmentComponentCore.js +++ b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/containmentComponentCore.js @@ -181,7 +181,13 @@ self.containmentTransition.active = false; } if (self.el && self.el.object3D && toTransform) { + // The end of a fit animation lands the position and scale only. + // Visibility belongs to the analysis mode: a chart hidden while the + // animation ran (the selector opened, or a mode failed and returned + // to it) must stay hidden, not reappear on an empty selector. + var visibleNow = self.el.object3D.visible; restoreTransform(self.el.object3D, toTransform); + self.el.object3D.visible = visibleNow; self.syncTransformAttributes(); self.captureStableTransform(); } diff --git a/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/clientCore.js b/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/clientCore.js index 6570bdf1..d48a3f3a 100644 --- a/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/clientCore.js +++ b/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/clientCore.js @@ -238,10 +238,18 @@ ) { return; } + // Exponential back-off with jitter (0.9 s doubling up to 15 s): a server + // that is down is no longer hammered every 900 ms, with a console + // warning each time, for the rest of the session (LIFECYCLE-11). + const baseDelay = shared.config.reconnectDelayMs || DEFAULT_CONFIG.reconnectDelayMs; + const attempt = shared.reconnectAttempts || 0; + shared.reconnectAttempts = attempt + 1; + const delay = Math.min(RECONNECT_MAX_DELAY_MS, baseDelay * Math.pow(2, attempt)); + const jitter = Math.floor(Math.random() * Math.min(500, delay / 4)); shared.reconnectTimer = win.setTimeout(function () { shared.reconnectTimer = null; void ensureSocket(); - }, shared.config.reconnectDelayMs || DEFAULT_CONFIG.reconnectDelayMs); + }, delay + jitter); } async function ensureSocket() { @@ -276,6 +284,7 @@ const socket = new win.WebSocket(url); shared.socket = socket; socket.onopen = function () { + shared.reconnectAttempts = 0; shared.joinedRoom = false; shared.snapshotReady = false; setError(null); @@ -285,10 +294,20 @@ }); }; socket.onmessage = function (event) { + let message; try { - handleServerMessage(JSON.parse(event.data)); + message = JSON.parse(event.data); } catch (_error) { // Ignore malformed collaboration payloads. + return; + } + // Parsing and dispatch are separate: an exception thrown by a runtime + // while it applies a message used to be swallowed here as if the + // payload were malformed, with nothing in the console (LIFECYCLE-9). + try { + handleServerMessage(message); + } catch (error) { + win.console?.error?.('[CodeXR][Collab] Handling a "' + (message?.type || 'unknown') + '" message failed:', error); } }; socket.onclose = function (event) { diff --git a/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/entitySync.js b/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/entitySync.js index 7b44dc21..4297744a 100644 --- a/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/entitySync.js +++ b/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/entitySync.js @@ -141,7 +141,12 @@ function handleSnapshotEntities(entities) { shared.roomEntities.clear(); - (Array.isArray(entities) ? entities : []).forEach(function (entity) { + // The analysis view goes last, so a mode activates with its data + // entities (dependency graph, comparison, evolution) already applied. + const ordered = (Array.isArray(entities) ? entities : []).slice().sort(function (left, right) { + return Number(left?.entityKind === 'analysis-view') - Number(right?.entityKind === 'analysis-view'); + }); + ordered.forEach(function (entity) { if (!entity?.entityKind || !entity?.entityId) { return; } @@ -200,7 +205,19 @@ const key = getEntityKey(entity.entityKind, entity.entityId); const runtime = shared.entityRuntimes.get(key); if (runtime?.applySharedState) { - runtime.applySharedState(entity, meta || { source: 'room' }); + // One runtime that throws must not stop the rest of a room snapshot + // (the analysis view behind it, the participants, the presence), and + // the failure must reach the console (LIFECYCLE-9). + try { + const applied = runtime.applySharedState(entity, meta || { source: 'room' }); + if (applied && typeof applied.catch === 'function') { + applied.catch(function (error) { + win.console?.error?.('[CodeXR][Collab] Runtime "' + key + '" failed to apply the shared state:', error); + }); + } + } catch (error) { + win.console?.error?.('[CodeXR][Collab] Runtime "' + key + '" failed to apply the shared state:', error); + } return; } shared.pendingEntities.set(key, entity); diff --git a/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/moduleAndConfig.js b/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/moduleAndConfig.js index 95cb1ccd..459d6f7d 100644 --- a/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/moduleAndConfig.js +++ b/apps/vscode-extension/templates/components/codexr/collaboration/codexrCollaborationRuntime/moduleAndConfig.js @@ -29,6 +29,8 @@ // 'auto' asks the room for a colour nobody else there is using. avatarId: 'auto', }; + // Upper bound of the reconnect back-off (see scheduleReconnect). + const RECONNECT_MAX_DELAY_MS = 15000; const DEFAULT_CONFIG = { enabled: true, collaborationEnabled: true, diff --git a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/configAndStatus.js b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/configAndStatus.js index f309a4e6..c2828067 100644 --- a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/configAndStatus.js +++ b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/configAndStatus.js @@ -98,8 +98,13 @@ Swift: '#f05138', Kotlin: '#7f52ff', external: '#94a3b8', directory: '#22d3ee', parent: '#f59e0b', symbol: '#a78bfa' }; + // dependency-graph-start is retried every 500 ms while the socket is not + // open; 40 attempts match the 20 s transition-lock watchdog. + var START_SEND_MAX_ATTEMPTS = 40; var state = { initialized: false, + // The last dataset load failure, shown until a load succeeds. + loadError: null, availability: 'loading', unavailableReason: '', snapshot: null, diff --git a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/datasetProjection.js b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/datasetProjection.js index 51af6d45..24841185 100644 --- a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/datasetProjection.js +++ b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/datasetProjection.js @@ -105,6 +105,9 @@ if (state.transitionLocked) { state.transitionLocked = false; setStatus('The dependency analysis did not respond. Try again.', true); + if (root.CodeXRAnalysisModeRuntime?.getState?.()?.mode === 'selection') { + root.CodeXRAnalysisModeRuntime.setSelectorStatus?.('The dependency analysis did not respond. Try again.', 'error'); + } root.console?.warn?.('[CodeXR][DependencyGraph] dependency-graph-start received no response within 20s.'); } }, 20000); diff --git a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/scalesAndControls.js b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/scalesAndControls.js index dd8f070e..d7666756 100644 --- a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/scalesAndControls.js +++ b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/scalesAndControls.js @@ -440,7 +440,9 @@ 'Hover nodes or edges for details. Click once to pin and again to release.', rowPosition(0, PANEL_ROWS.hover), 5.9, '#cbd5e1', 'center', 74 )); - refs.status = text(state.snapshot.message || '', rowPosition(0, PANEL_ROWS.status), 5.6, '#fde68a'); + refs.status = state.loadError + ? text(state.loadError, rowPosition(0, PANEL_ROWS.status), 5.6, '#fca5a5') + : text(state.snapshot.message || '', rowPosition(0, PANEL_ROWS.status), 5.6, '#fde68a'); refs.controls.appendChild(refs.status); } diff --git a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/viewLifecycle.js b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/viewLifecycle.js index 4efe0f28..602ddaa3 100644 --- a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/viewLifecycle.js +++ b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/viewLifecycle.js @@ -74,10 +74,10 @@ // A file-scoped snapshot also points at the project-wide dataset; keep it // when it is still wanted. (Unlike the dataset fetch this does not re-check // snapshot identity - pinned as-is by dependencyGraph.test.cjs.) - async function loadProjectDataset(snapshot, loadGeneration, viewGeneration) { + async function loadProjectDataset(snapshot, loadGeneration, viewGeneration, signal) { var projectResponse = await fetch( snapshot.projectDatasetUrl + '?sourceRevision=' + Number(snapshot.sourceRevision || 0), - { cache: 'no-store' } + signal ? { cache: 'no-store', signal: signal } : { cache: 'no-store' } ); if (projectResponse.ok && isLoadCurrent(loadGeneration, viewGeneration)) { var projectDataset = await projectResponse.json(); @@ -87,9 +87,20 @@ } } - async function applySharedState(snapshot) { + /** + * options.signal aborts the dataset fetch (the mode switcher cancels an + * activation the user moved away from); options.rethrow makes a load + * failure reject, so the activation fails visibly on the selector instead + * of leaving an empty table that says "ready" (LIFECYCLE-5). + */ + async function applySharedState(snapshot, options) { + var signal = options?.signal || null; snapshot = withSnapshotDefaults(snapshot); state.snapshot = snapshot; + if (snapshot && snapshot.status !== 'ready') { + // A new analysis is under way: the old load error no longer applies. + state.loadError = null; + } if (!snapshot) { renderControls(); return; @@ -109,21 +120,36 @@ try { var loadGeneration = ++state.datasetLoadGeneration; var viewGeneration = state.viewGeneration; - var response = await fetch(snapshot.datasetUrl + '?revision=' + snapshot.revision, { cache: 'no-store' }); - if (!response.ok) { throw new Error('Dependency dataset could not be loaded.'); } + var response = await fetch( + snapshot.datasetUrl + '?revision=' + snapshot.revision, + signal ? { cache: 'no-store', signal: signal } : { cache: 'no-store' } + ); + if (!response.ok) { + throw new Error('The dependency data could not be loaded (HTTP ' + response.status + ').'); + } var dataset = await response.json(); if (!isLoadCurrent(loadGeneration, viewGeneration) || state.snapshot !== snapshot) { return; } storeDataset(snapshot, dataset); if (snapshot.projectDatasetUrl) { - await loadProjectDataset(snapshot, loadGeneration, viewGeneration); + await loadProjectDataset(snapshot, loadGeneration, viewGeneration, signal); } + state.loadError = null; renderGraph(); setTransitionLocked(false); } catch (error) { - setStatus(error instanceof Error ? error.message : String(error), true); setTransitionLocked(false); + if (signal?.aborted) { + // Cancelled by the switcher: not an error the user should read. + return; + } + var message = error && typeof error.message === 'string' ? error.message : String(error); + // Sticky: renderControls re-runs on every panel route and would + // otherwise overwrite it with the snapshot's "ready". + state.loadError = message; + setStatus(message, true); + if (options?.rethrow) { throw error; } } } @@ -131,8 +157,7 @@ return state.snapshot?.status === 'ready' && !!state.snapshot?.datasetUrl; } - function activateReadySnapshot(reason) { - if (!hasReadySnapshot()) { return false; } + function enterDependencyMode(reason) { var offline = client()?.isOfflineExport?.() === true; root.console?.log?.('[CodeXR.Debug]: Activating existing dependency graph snapshot', { offline: offline, @@ -151,12 +176,29 @@ return true; } + function activateReadySnapshot(reason) { + if (!hasReadySnapshot()) { return false; } + return enterDependencyMode(reason); + } + + /** Mirrors the opening progress on the selector, which is what is visible. */ + function reportOnSelector(message, isError) { + var modeRuntime = root.CodeXRAnalysisModeRuntime; + if (modeRuntime?.getState?.()?.mode !== 'selection') { return; } + modeRuntime.setSelectorStatus?.(message, isError ? 'error' : 'info'); + } + async function start() { if (state.availability !== 'enabled') { setStatus(state.unavailableReason, true); return; } - if (state.transitionLocked) { return; } + if (state.transitionLocked) { + // A second click while the first is still opening: say so instead of + // swallowing it (LIFECYCLE-6). + reportOnSelector('Still opening the dependency graph...', false); + return; + } if (hasReadySnapshot() && client()?.isOfflineExport?.()) { activateReadySnapshot('offline-dependency-snapshot'); return; @@ -173,6 +215,7 @@ return; } setTransitionLocked(true, 'Opening dependencies...'); + reportOnSelector('Opening dependencies...', false); // The hop to selection is cosmetic; the server's authoritative // analysis-view broadcast is what really drives the scene into // dependency mode. A failed local transition must never swallow the @@ -189,11 +232,22 @@ // until it goes through. Gated on a send generation of its own (the // transition lock legitimately clears during the hop to selection). var sendGeneration = state.startSendGeneration = (state.startSendGeneration || 0) + 1; + var attempts = 0; var attemptSend = function () { if (sendGeneration !== state.startSendGeneration) { return; } // Only an explicit `false` means "socket not ready, dropped" — clients // whose sendMessage returns nothing are treated as delivered. if (client()?.sendMessage?.('dependency-graph-start', {}) !== false) { return; } + attempts += 1; + // Bounded like the lock watchdog: a socket that stays down for 20 s + // gets a visible answer, not a retry loop for the rest of the session. + if (attempts >= START_SEND_MAX_ATTEMPTS) { + root.console?.warn?.('[CodeXR][DependencyGraph] collaboration socket stayed down; giving up on dependency-graph-start.'); + setTransitionLocked(false); + setStatus('CodeXR is not connected to VS Code. Try again once it reconnects.', true); + reportOnSelector('CodeXR is not connected to VS Code. Try again once it reconnects.', true); + return; + } root.console?.warn?.('[CodeXR][DependencyGraph] collaboration socket not ready; retrying dependency-graph-start...'); setTimeout(attemptSend, 500); }; @@ -212,6 +266,15 @@ if (activateReadySnapshot('local-dependency-mode-option')) { return; } + // A refresh is already running (a file was saved, or another participant + // started one): attach to it. The mode opens with its progress and + // renders when the ready snapshot lands. Starting again was refused by + // the server and stranded the user on the selector (DEPGRAPH-7). + if (state.snapshot?.status === 'analyzing' && !client()?.isOfflineExport?.()) { + root.console?.log?.('[CodeXR.Debug]: Dependency analysis already running; attaching to it'); + enterDependencyMode('attach-running-dependency-analysis'); + return; + } root.console?.log?.('[CodeXR.Debug]: Dependency graph mode selected; starting dependency analysis', { hasDataset: !!state.dataset, availability: state.availability @@ -248,11 +311,20 @@ function registerCollaboration() { var connection = client(); state.disposables.push(connection?.onMessage?.('dependency-graph-progress', function (message) { - setStatus(message?.payload?.message || 'Analyzing dependencies...', false); + var progress = message?.payload?.message || 'Analyzing dependencies...'; + setStatus(progress, false); + // Progress is an answer: re-arm the 20 s watchdog so a long first + // analysis is not reported as "did not respond" while it works. + if (state.transitionLocked) { + setTransitionLocked(true); + reportOnSelector(progress, false); + } })); state.disposables.push(connection?.onMessage?.('dependency-graph-error', function (message) { - root.console?.warn?.('[CodeXR][DependencyGraph] Server reported:', message?.payload?.message || 'Dependency analysis failed.'); - setStatus(message?.payload?.message || 'Dependency analysis failed.', true); + var failure = message?.payload?.message || 'Dependency analysis failed.'; + root.console?.warn?.('[CodeXR][DependencyGraph] Server reported:', failure); + setStatus(failure, true); + reportOnSelector(failure, true); setTransitionLocked(false); })); connection?.registerEntityRuntime?.({ @@ -267,7 +339,11 @@ if (!state.unregisterLifecycle && root.CodeXRAnalysisModeRuntime?.register) { state.unregisterLifecycle = root.CodeXRAnalysisModeRuntime.register('dependency-graph', { mappingContextId: null, - activate: function () { + activate: function (activation) { + // Abandoned by the switcher before it started: leave the table alone. + if (activation?.token?.isCurrent && !activation.token.isCurrent()) { + return false; + } state.active = true; state.viewGeneration += 1; parkOriginal(); @@ -279,7 +355,7 @@ return; } if (state.snapshot) { - return applySharedState(state.snapshot); + return applySharedState(state.snapshot, { signal: activation?.signal, rethrow: true }); } }, deactivate: function () { diff --git a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/compareFlowAndMessages.js b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/compareFlowAndMessages.js index 3fdfbd66..17644706 100644 --- a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/compareFlowAndMessages.js +++ b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/compareFlowAndMessages.js @@ -147,7 +147,9 @@ setStatus(friendlyMessage, 'error'); } - async function applySharedState(snapshot) { + async function applySharedState(snapshot, options) { + var signal = options?.signal || null; + var fetchOptions = signal ? { cache: 'no-store', signal: signal } : { cache: 'no-store' }; if (!snapshot || !snapshot.result) { return; } @@ -160,8 +162,8 @@ setStatus('Loading comparison datasets...', 'info'); var result = snapshot.result; var responses = await Promise.all([ - fetch(result.left.url + '?revision=' + result.revision, { cache: 'no-store' }), - fetch(result.right.url + '?revision=' + result.revision, { cache: 'no-store' }) + fetch(result.left.url + '?revision=' + result.revision, fetchOptions), + fetch(result.right.url + '?revision=' + result.revision, fetchOptions) ]); if (!responses[0].ok || !responses[1].ok) { throw new Error('Comparison datasets could not be loaded.'); @@ -182,6 +184,8 @@ } closePanel(); } catch (error) { - setStatus(error instanceof Error ? error.message : String(error), 'error'); + if (signal?.aborted) { return; } + setStatus(error && typeof error.message === 'string' ? error.message : String(error), 'error'); + if (options?.rethrow) { throw error; } } } diff --git a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/liveRefreshAndRegistration.js b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/liveRefreshAndRegistration.js index ea3ece25..ef459e96 100644 --- a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/liveRefreshAndRegistration.js +++ b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/liveRefreshAndRegistration.js @@ -179,7 +179,17 @@ state.initialized = true; state.unregisterLifecycle = root.CodeXRAnalysisModeRuntime?.register?.('historical-compare', { mappingContextId: 'historical-comparison', - activate: function () { + activate: function (activation) { + // An activation the switcher already abandoned (the user picked + // another analysis while it waited) must not route the panel or + // request references over the mode that replaced it. + if (activation?.token?.isCurrent && !activation.token.isCurrent()) { + return false; + } + // The switcher aborts this signal when the user picks another mode + // (or the activation times out); a load failure rejects so it lands + // on the selector with its reason (LIFECYCLE-1/3/5). + var loadOptions = { signal: activation?.signal || null, rethrow: true }; if (state.result) { // Comparison geometry still mounted (preserved on leave, or a // duplicate activation): restore it in place — no renderComparison, @@ -194,7 +204,7 @@ entityId: ENTITY_ID, mode: 'historical-compare', result: state.result - }); + }, loadOptions); } closePanel(); return true; @@ -213,7 +223,7 @@ entityId: ENTITY_ID, mode: 'historical-compare', result: state.result - }); + }, loadOptions); } showHistoricalSelectionPanel(); return true; diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js index 2ba1edf9..57790767 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js @@ -199,6 +199,10 @@ state.initialized = true; state.unregisterLifecycle = root.CodeXRAnalysisModeRuntime?.register?.(MODE, { mappingContextId: MODE, + // A frame can legitimately take a while (component waits, the frame + // apply and the containment settle are each bounded); past this the + // switcher reports the mode as failed instead of waiting forever. + activateTimeoutMs: 90000, captureState: captureEvolutionState, restoreState: function (activation) { if (activation?.token?.isCurrent && !activation.token.isCurrent()) { @@ -243,7 +247,11 @@ // may take several seconds, but the already-rendered frame is valid // saved state and must be visible as soon as the mode owns the table. var currentFrame = state.result.frames?.[state.frameIndex]; - if (currentFrame && refs.evolutionRoot) { + // A pipeline that failed half-way leaves the root without a chart; + // that is no preserved frame, and seek() below rebuilds it. Before, + // this threw and every later entry bounced to the selector + // (LIFECYCLE-4). + if (currentFrame && refs.evolutionRoot && refs.evolutionChart) { ensureEvolutionRoot(currentFrame); refs.evolutionChart.setAttribute?.('visible', true); root.CodeXRMappingUiRuntime?.setChartEntityIds?.( diff --git a/apps/vscode-extension/test/README.md b/apps/vscode-extension/test/README.md index 674c6573..10d150f0 100644 --- a/apps/vscode-extension/test/README.md +++ b/apps/vscode-extension/test/README.md @@ -28,7 +28,7 @@ Every `*.test.cjs` below `test/` is collected by `npm run test:unit`, except und - `npm run test:all`: run both the Node and Python suites. - `npm run test:analysis`: per-language end-to-end metrics over `backend/manual_test/` with the pinned lizard. - `npm run test:htmlanalysis`: the HTML/DOM analysis suite. -- `npm run test:xr-harness`, `test:xr-mode-harness`, `test:xr-immersive-harness`, `test:project-evolution-harness`, `test:xr-chart-bounds-harness`: browser harnesses (Playwright's Chromium and live CDNs; local only). +- `npm run test:xr-harness`, `test:xr-mode-harness`, `test:xr-immersive-harness`, `test:project-evolution-harness`, `test:xr-chart-bounds-harness`: browser harnesses (Playwright's Chromium and live CDNs; local only). The mode and immersive harnesses serve the project over HTTP on 127.0.0.1 (`test/helpers/staticHttpServer.cjs`) instead of opening `file://`, so `fetch()` works in them. The full table, with when to run each, is in `.claude/docs/DEVELOPMENT.md`. diff --git a/apps/vscode-extension/test/analysis/analysisModeLifecycleContract.test.cjs b/apps/vscode-extension/test/analysis/analysisModeLifecycleContract.test.cjs new file mode 100644 index 00000000..a9ac4d93 --- /dev/null +++ b/apps/vscode-extension/test/analysis/analysisModeLifecycleContract.test.cjs @@ -0,0 +1,272 @@ +// The in-scene mode lifecycle contract (epic #72, story S7): a mode that +// hangs, fails or is overtaken by a newer pick must always leave the switcher +// usable, say why on the selector, and keep the room in step. +const assert = require('node:assert/strict'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +const projectRoot = path.resolve(__dirname, '..', '..'); +const { readAssembledRuntime } = require(path.join(projectRoot, 'test', 'helpers', 'runtimeAssembly.cjs')); + +const quietConsole = { error() {}, warn() {}, log() {}, table() {} }; +const tick = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms)); + +function createFakeElement(tagName) { + const element = { + tagName, + attributes: {}, + children: [], + listeners: {}, + parentNode: null, + get firstChild() { return this.children[0] || null; }, + setAttribute(name, value) { this.attributes[name] = value; }, + getAttribute(name) { return this.attributes[name]; }, + appendChild(child) { child.parentNode = this; this.children.push(child); return child; }, + removeChild(child) { + this.children = this.children.filter(candidate => candidate !== child); + child.parentNode = null; + return child; + }, + addEventListener(type, listener) { (this.listeners[type] ||= []).push(listener); }, + }; + return element; +} + +/** Boots the runtime with a document, a controller panel and a room client. */ +function bootRuntime(options = {}) { + const sent = []; + const entityRuntimes = []; + let panelView = null; + const context = { + setTimeout, + clearTimeout, + Date, + console: options.console || quietConsole, + document: { + createElement: createFakeElement, + getElementById() { return null; }, + querySelector() { return null; }, + querySelectorAll() { return []; }, + }, + CodeXRMappingUiRuntime: { + isPanelReady() { return true; }, + registerPanelView(view) { panelView = view; return () => {}; }, + setPanelViewButtonColor() {}, + setChartEntityIds() {}, + }, + CodeXRCollaborationRuntime: { + getClient() { + return { + sendMessage(type, payload) { sent.push({ type, payload }); }, + registerEntityRuntime(runtime) { entityRuntimes.push(runtime); }, + }; + }, + }, + }; + vm.runInNewContext(readAssembledRuntime('analysis-mode', 'analysisModeRuntime.js'), context); + const runtime = context.CodeXRAnalysisModeRuntime; + return { + runtime, + sent, + get panelView() { return panelView; }, + analysisView: () => entityRuntimes.find(candidate => candidate.entityKind === 'analysis-view'), + headline() { + const text = panelView?.content?.children?.find(child => child.attributes['data-codexr-mode-selector-status']); + return text ? { value: text.attributes.value, tone: text.attributes['data-codexr-mode-selector-status'] } : null; + }, + optionLabels() { + return (panelView?.content?.children || []) + .filter(child => child.attributes['data-codexr-mode-option']) + .map(child => child.children[0].attributes.value); + }, + }; +} + +test('a never-settling activate is abandoned when the user picks another mode', async () => { + const { runtime } = bootRuntime(); + const roots = new Set(); + let releaseDependency; + let seenSignal = null; + runtime.register('dependency-graph', { + activate(activation) { + seenSignal = activation.signal; + roots.add('dependency-graph'); + // A dataset fetch that never answers. + return new Promise(resolve => { releaseDependency = resolve; }); + }, + deactivate() { + roots.delete('dependency-graph'); + roots.delete('dependency-graph-late-root'); + }, + }); + runtime.register('single', { + activate() { roots.add('single'); }, + deactivate() { roots.delete('single'); }, + }); + + const dependency = runtime.changeAnalysis('dependency-graph', { reason: 'test' }); + await tick(); + assert.equal(runtime.getState().activation.mode, 'dependency-graph'); + + // Picking Normal analysis no longer waits behind the hung activate. + const normal = runtime.changeAnalysis('single', { reason: 'test' }); + assert.equal(seenSignal.aborted, true, 'the hung activation is told to stop'); + assert.equal(await dependency, false); + assert.equal(await normal, true); + assert.equal(runtime.getState().mode, 'single'); + assert.equal(runtime.getState().transitioning, false); + assert.deepEqual(Array.from(roots), ['single']); + + // When the stale activate finally settles, what it mounted late is removed. + roots.add('dependency-graph-late-root'); + releaseDependency(); + await tick(5); + assert.deepEqual(Array.from(roots).filter(root => root.startsWith('dependency')), []); +}); + +test('an activate that times out lands on the selector with a visible error and a Retry option', async () => { + const harness = bootRuntime(); + const { runtime, sent } = harness; + runtime.registerModeOption({ id: 'dependency-graph', label: 'Dependency graph', onSelect() {} }); + let deactivated = 0; + let signal = null; + runtime.register('dependency-graph', { + activateTimeoutMs: 20, + activate(activation) { signal = activation.signal; return new Promise(() => {}); }, + deactivate() { deactivated += 1; }, + }); + runtime.register('selection', { activate() {} }); + + assert.equal(await runtime.changeAnalysis('dependency-graph', { reason: 'local-analysis-mode-option' }), false); + + const state = runtime.getState(); + assert.equal(state.mode, 'selection'); + assert.equal(state.transitioning, false); + assert.equal(state.lastError.mode, 'dependency-graph'); + assert.equal(state.lastError.code, 'timeout'); + assert.equal(signal.aborted, true, 'the timed-out activation is aborted'); + assert.ok(deactivated >= 1); + // "Analyses" must not resume the mode that just failed. + assert.equal(state.requestedMode, 'single'); + // The room is told to leave the failed mode. + assert.deepEqual(sent.map(message => message.type), ['analysis-mode-selection']); + // The selector says what happened, and the failed option reads "Retry". + const headline = harness.headline(); + assert.equal(headline.tone, 'error'); + assert.match(headline.value, /^Could not open Dependency graph: Opening Dependency graph did not finish within 0 s\./); + assert.ok(harness.optionLabels().includes('Retry: Dependency graph')); +}); + +test('a failed activation is not retried by the room echo, and success clears the error', async () => { + const harness = bootRuntime(); + const { runtime } = harness; + let activations = 0; + let fail = true; + runtime.register('historical-compare', { + activate() { + activations += 1; + if (fail) { throw new Error('comparison data could not be loaded (HTTP 500)'); } + }, + }); + runtime.register('selection', { activate() {} }); + + assert.equal(await runtime.changeAnalysis('historical-compare', { reason: 'local-analysis-mode-option' }), false); + assert.equal(activations, 1); + assert.match(harness.headline().value, /HTTP 500/); + + // The server's echo of the pick arrives after the failure. + harness.analysisView().applySharedState({ mode: 'historical-compare', viewRevision: 3 }); + await tick(5); + assert.equal(activations, 1, 'the echo did not re-run the failing activate'); + assert.equal(runtime.getState().mode, 'selection'); + + // A deliberate retry runs, and a success clears the error. + fail = false; + assert.equal(await runtime.changeAnalysis('historical-compare', { reason: 'local-analysis-mode-option' }), true); + assert.equal(activations, 2); + assert.equal(runtime.getState().lastError, null); + assert.equal(runtime.getState().requestedMode, 'historical-compare'); +}); + +test('a failure caused by the room echo does not send the room back to the selector', async () => { + const { runtime, sent, analysisView } = bootRuntime(); + runtime.register('project-evolution', { activate() { throw new Error('tree not available'); } }); + runtime.register('selection', { activate() {} }); + + analysisView().applySharedState({ mode: 'project-evolution', viewRevision: 2 }); + await tick(5); + assert.equal(runtime.getState().mode, 'selection'); + assert.equal(runtime.getState().lastError.mode, 'project-evolution'); + // Another participant chose it and it may work for them: this page only + // reports its own failure. + assert.deepEqual(sent, []); +}); + +test('picking an analysis while the selector is still opening keeps the pick (no late selection)', async () => { + const { runtime, sent } = bootRuntime(); + let releaseSelection; + runtime.register('selection', { + activate() { return new Promise(resolve => { releaseSelection = resolve; }); }, + }); + runtime.register('dependency-graph', { activate() {} }); + + const opening = runtime.openSelector(); + await tick(); + // The user picks Dependency graph before the selection transition lands. + sent.push({ type: 'analysis-mode-activate', payload: { mode: 'dependency-graph' } }); + const pick = runtime.changeAnalysis('dependency-graph', { reason: 'local-analysis-mode-option' }); + releaseSelection(); + assert.equal(await opening, false); + assert.equal(await pick, true); + + // The last word the server hears is the pick, not a stale "selection". + assert.equal(sent.at(-1).type, 'analysis-mode-activate'); + assert.ok(!sent.some(message => message.type === 'analysis-mode-selection')); + assert.equal(runtime.getState().mode, 'dependency-graph'); +}); + +test('a hook that never settles cannot hold the switcher', async () => { + const { runtime } = bootRuntime(); + runtime.__testing.setHookTimeoutMs(30); + runtime.register('project-evolution', { + activate() {}, + // A deactivate that hangs (a stuck animation wait, for one). + deactivate() { return new Promise(() => {}); }, + }); + runtime.register('single', { activate() {} }); + assert.equal(await runtime.changeAnalysis('project-evolution'), true); + const started = Date.now(); + assert.equal(await runtime.changeAnalysis('single'), true); + assert.ok(Date.now() - started < 2000, 'the hung deactivate was abandoned after its timeout'); + assert.equal(runtime.getState().mode, 'single'); +}); + +test('modes can report opening progress on the selector', () => { + const harness = bootRuntime(); + harness.runtime.setSelectorStatus('Opening dependencies...'); + assert.deepEqual(harness.headline(), { value: 'Opening dependencies...', tone: 'info' }); + harness.runtime.setSelectorStatus('The dependency analysis did not respond.', 'error'); + assert.equal(harness.headline().tone, 'error'); + harness.runtime.setSelectorStatus(''); + assert.equal(harness.headline().value, 'Choose how the analysis table represents the data.'); +}); + +test('a room snapshot after a server restart is applied even with a lower view revision', async () => { + const { runtime, analysisView } = bootRuntime(); + const entered = []; + runtime.register('dependency-graph', { activate() { entered.push('dependency-graph'); } }); + runtime.register('historical-compare', { activate() { entered.push('historical-compare'); } }); + analysisView().applySharedState({ mode: 'dependency-graph', viewRevision: 40 }, { source: 'room' }); + await tick(5); + // A plain update older than what was applied is stale and ignored... + analysisView().applySharedState({ mode: 'historical-compare', viewRevision: 3 }, { source: 'room' }); + await tick(5); + assert.equal(runtime.getState().mode, 'dependency-graph'); + // ...but a fresh room snapshot (re-join to a restarted session) is the + // room's whole state and resets the floor. + analysisView().applySharedState({ mode: 'historical-compare', viewRevision: 3 }, { source: 'snapshot' }); + await tick(5); + assert.equal(runtime.getState().mode, 'historical-compare'); + assert.equal(runtime.getState().lastAuthoritativeViewRevision, 3); +}); diff --git a/apps/vscode-extension/test/analysis/analysisModeMegatest.test.cjs b/apps/vscode-extension/test/analysis/analysisModeMegatest.test.cjs index 0c3efbe7..9792e07c 100644 --- a/apps/vscode-extension/test/analysis/analysisModeMegatest.test.cjs +++ b/apps/vscode-extension/test/analysis/analysisModeMegatest.test.cjs @@ -49,9 +49,10 @@ test('XR mode panel exposes one labelled Analyses button and no dependency heade // method (`refs.playButton?.querySelector('a-text').setAttribute?.(…)`). assert.doesNotMatch(evolutionRuntime, /querySelector\('a-text'\)\.setAttribute/); assert.doesNotMatch(evolutionRuntime, /refs\.(modeRoot|rangeRoot)\.children\[/); - // A failed activation is reported on the controller instead of silently - // returning to the selector. - assert.match(modeRuntime, /setStatusMessage\?\.\(\s*'CodeXR could not open this analysis\./); + // A failed activation is reported on the selector itself (the mapping + // view's status line is hidden while the selector is up), see + // analysisModeLifecycleContract.test.cjs for the behaviour. + assert.match(modeRuntime, /'Could not open ' \+ getModeLabel\(state\.lastError\.mode\)/); assert.match(evolutionRuntime, /registerPanelView\(\{/); assert.match(evolutionRuntime, /id: MODE/); assert.match(evolutionRuntime, /headerButton: false/); @@ -147,7 +148,8 @@ test('XR mode panel exposes one labelled Analyses button and no dependency heade assert.doesNotMatch(historyRuntime, /transitionTo\?\.\('selection', \{[\s\S]*historical-selection/); assert.match(dependencyRuntime, /function selectDependencyMode\(\)[\s\S]*activateReadySnapshot\('local-dependency-mode-option'\)/); assert.match(dependencyRuntime, /function hasReadySnapshot\(\)[\s\S]*snapshot\?\.status === 'ready'[\s\S]*snapshot\?\.datasetUrl/); - assert.match(dependencyRuntime, /function activateReadySnapshot\([\s\S]*analysis-mode-activate/); + assert.match(dependencyRuntime, /function enterDependencyMode\([\s\S]*analysis-mode-activate/); + assert.match(dependencyRuntime, /function activateReadySnapshot\([\s\S]*return enterDependencyMode\(reason\)/); assert.ok( historyRuntime.indexOf('state.result = result;') < historyRuntime.indexOf('await renderComparison(result, datasets[0], datasets[1]);'), diff --git a/apps/vscode-extension/test/analysis/collaborationRuntime.test.cjs b/apps/vscode-extension/test/analysis/collaborationRuntime.test.cjs index 0442146e..56163034 100644 --- a/apps/vscode-extension/test/analysis/collaborationRuntime.test.cjs +++ b/apps/vscode-extension/test/analysis/collaborationRuntime.test.cjs @@ -519,3 +519,94 @@ test('offline export: a session failure WITHOUT a manifest keeps the plain fallb // like a temporarily unreachable live server. assert.equal(sockets.length, 1); }); + +// Epic #72 / S7 (LIFECYCLE-9, LIFECYCLE-11). +function bootCollaborationClient() { + const sockets = []; + const timeouts = []; + const errors = []; + function createFakeElement(tag) { + return { + tagName: String(tag || '').toUpperCase(), id: '', style: {}, children: [], textContent: '', + appendChild(child) { this.children.push(child); return child; }, + setAttribute() {}, + }; + } + function FakeWebSocket(url) { + this.url = url; + this.readyState = 0; + sockets.push(this); + } + FakeWebSocket.prototype.send = function () {}; + FakeWebSocket.prototype.close = function () {}; + FakeWebSocket.OPEN = 1; + FakeWebSocket.CONNECTING = 0; + const body = createFakeElement('body'); + const fakeWindow = { + document: { + body, readyState: 'complete', createElement: createFakeElement, + getElementById() { return null; }, querySelector() { return null; }, + addEventListener() {}, dispatchEvent() { return true; }, + }, + location: { protocol: 'http:', host: '127.0.0.1:7777' }, + WebSocket: FakeWebSocket, + CustomEvent: class { constructor(type, init) { this.type = type; this.detail = init && init.detail; } }, + addEventListener() {}, + setTimeout(fn, ms) { timeouts.push({ fn, ms }); return timeouts.length; }, + clearTimeout() {}, + console: { log() {}, warn() {}, error(...args) { errors.push(args); } }, + }; + const client = collaborationRuntime.createClient(fakeWindow); + client.connect({ presenceEnabled: false, cursorPresenceEnabled: false }); + return { client, sockets, timeouts, errors }; +} + +test('a runtime that throws on a room snapshot does not stop the analysis view from applying', async () => { + const { client, sockets, errors } = bootCollaborationClient(); + await new Promise((resolve) => setImmediate(resolve)); + const applied = []; + client.registerEntityRuntime({ + entityKind: 'analysis-view', entityId: 'main', + applySharedState(entity) { applied.push(`analysis-view:${entity.mode}`); }, + }); + client.registerEntityRuntime({ + entityKind: 'dependency-graph', entityId: 'main', + applySharedState() { applied.push('dependency-graph'); throw new Error('unexpected payload shape'); }, + }); + sockets[0].onmessage({ data: JSON.stringify({ + type: 'room-snapshot', + payload: { + // The analysis view first on the wire: it is still applied last. + entities: [ + { entityKind: 'analysis-view', entityId: 'main', mode: 'dependency-graph' }, + { entityKind: 'dependency-graph', entityId: 'main', status: 'ready' }, + ], + participants: [], + }, + }) }); + assert.deepEqual(applied, ['dependency-graph', 'analysis-view:dependency-graph']); + assert.ok(errors.some((args) => /dependency-graph:main/.test(String(args[0]))), 'the failure is logged'); +}); + +test('a dropped room connection reconnects with a growing back-off, reset once it opens', async () => { + const { sockets, timeouts } = bootCollaborationClient(); + await new Promise((resolve) => setImmediate(resolve)); + const delays = []; + for (let attempt = 0; attempt < 6; attempt += 1) { + sockets.at(-1).onclose({ code: 1006 }); + const scheduled = timeouts.at(-1); + delays.push(scheduled.ms); + scheduled.fn(); + await new Promise((resolve) => setImmediate(resolve)); + } + // 0.9 s doubling (plus jitter of at most a quarter), capped at 15 s. + assert.ok(delays[0] >= 900 && delays[0] < 1200, `first delay ${delays[0]}`); + for (let index = 1; index < delays.length; index += 1) { + assert.ok(delays[index] >= Math.min(15000, 900 * 2 ** index), `delay ${index} = ${delays[index]}`); + assert.ok(delays[index] <= 15500, `delay ${index} = ${delays[index]} is capped`); + } + // A successful open resets the back-off. + sockets.at(-1).onopen(); + sockets.at(-1).onclose({ code: 1006 }); + assert.ok(timeouts.at(-1).ms < 1200); +}); diff --git a/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs b/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs index 65d1ffc9..de36bab3 100644 --- a/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs +++ b/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs @@ -1392,3 +1392,56 @@ test('dependency applySharedState: every branch behaves as before (characterizat } assert.deepEqual(results, DEPENDENCY_SHARED_STATE_CHARACTERIZATION); }); + +// Epic #72 / S7: a dataset that cannot be loaded on entry fails the +// activation (it lands on the selector with its reason) and stays visible on +// the panel instead of being overwritten with "ready" (LIFECYCLE-5). +test('a dataset load failure during activation rejects and stays as a sticky panel error', async () => { + const source = readAssembledRuntime('dependency-graph', 'dependencyGraphRuntime.js'); + const context = { setTimeout, clearTimeout, console: { log() {}, warn() {}, error() {}, info() {}, debug() {} } }; + context.CodeXRAnalysisModeRuntime = { getState: () => ({ mode: 'dependency-graph' }) }; + vm.runInNewContext(source, context); + const runtime = context.CodeXRDependencyGraphRuntime; + const state = runtime.getState(); + state.active = true; + let seenSignal = null; + context.fetch = async (_url, init) => { seenSignal = init?.signal || null; return { ok: false, status: 500 }; }; + const signal = { aborted: false, addEventListener() {}, removeEventListener() {} }; + + await assert.rejects( + runtime.applySharedState(readyDirectory, { signal, rethrow: true }), + /could not be loaded \(HTTP 500\)/ + ); + assert.equal(seenSignal, signal, 'the switcher signal reaches fetch'); + assert.match(state.loadError, /HTTP 500/); + + // A passive entity update keeps reporting it without throwing. + await runtime.applySharedState(readyDirectory); + assert.match(state.loadError, /HTTP 500/); + + // A new analysis clears it, and a successful load leaves no error behind. + await runtime.applySharedState({ status: 'analyzing', message: 'Analyzing dependencies...' }); + assert.equal(state.loadError, null); +}); + +test('a load cancelled by the switcher is not reported as an error', async () => { + const source = readAssembledRuntime('dependency-graph', 'dependencyGraphRuntime.js'); + const context = { setTimeout, clearTimeout, console: { log() {}, warn() {}, error() {}, info() {}, debug() {} } }; + context.CodeXRAnalysisModeRuntime = { getState: () => ({ mode: 'dependency-graph' }) }; + vm.runInNewContext(source, context); + const runtime = context.CodeXRDependencyGraphRuntime; + runtime.getState().active = true; + const signal = { aborted: true, addEventListener() {}, removeEventListener() {} }; + context.fetch = async () => { throw Object.assign(new Error('aborted'), { name: 'AbortError' }); }; + await runtime.applySharedState(readyDirectory, { signal, rethrow: true }); + assert.equal(runtime.getState().loadError, null); +}); + +test('picking the dependency graph while an analysis runs attaches to it instead of restarting (DEPGRAPH-7)', () => { + const source = readAssembledRuntime('dependency-graph', 'dependencyGraphRuntime.js'); + // selectDependencyMode attaches on an "analyzing" snapshot and only starts + // a new analysis when there is none; progress re-arms the 20 s watchdog. + assert.match(source, /state\.snapshot\?\.status === 'analyzing'[\s\S]{0,200}enterDependencyMode\('attach-running-dependency-analysis'\)/); + assert.match(source, /dependency-graph-progress[\s\S]{0,400}if \(state\.transitionLocked\) \{\s*setTransitionLocked\(true\);/); + assert.match(source, /attempts >= START_SEND_MAX_ATTEMPTS/); +}); diff --git a/apps/vscode-extension/test/helpers/staticHttpServer.cjs b/apps/vscode-extension/test/helpers/staticHttpServer.cjs new file mode 100644 index 00000000..c71c23fe --- /dev/null +++ b/apps/vscode-extension/test/helpers/staticHttpServer.cjs @@ -0,0 +1,73 @@ +'use strict'; +// Serves a folder over HTTP on 127.0.0.1 for the browser harnesses. +// Loaded from file://, Chromium blocks every fetch() (CORS), so the mode +// harnesses never loaded their datasets: they only checked panel routing over +// empty modes, and a mode whose data could not load looked "ready". Over HTTP +// the dependency, comparison and evolution data really load. +const fs = require('node:fs'); +const http = require('node:http'); +const path = require('node:path'); + +const CONTENT_TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'application/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.glb': 'model/gltf-binary', +}; + +/** + * @param {string} rootDir folder served at '/' + * @returns {Promise<{ url: (relativePath: string) => string, close: () => Promise }>} + */ +function startStaticServer(rootDir) { + const root = path.resolve(rootDir); + const server = http.createServer((request, response) => { + let pathname; + try { + pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname); + } catch { + response.writeHead(400); + response.end(); + return; + } + const filePath = path.resolve(root, '.' + pathname); + if (filePath !== root && !filePath.startsWith(root + path.sep)) { + response.writeHead(403); + response.end(); + return; + } + fs.stat(filePath, (error, stats) => { + if (error || !stats.isFile()) { + response.writeHead(404); + response.end(); + return; + } + response.writeHead(200, { + 'content-type': CONTENT_TYPES[path.extname(filePath).toLowerCase()] || 'application/octet-stream', + 'cache-control': 'no-store', + }); + fs.createReadStream(filePath).pipe(response); + }); + }); + return new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const { port } = server.address(); + resolve({ + url(relativePath) { + const normalized = path.relative(root, path.resolve(root, relativePath)).split(path.sep).join('/'); + return `http://127.0.0.1:${port}/${normalized}`; + }, + close() { + server.closeAllConnections?.(); + return new Promise((done) => server.close(() => done())); + }, + }); + }); + }); +} + +module.exports = { startStaticServer }; diff --git a/apps/vscode-extension/test/runners/run-xr-immersive-harness.cjs b/apps/vscode-extension/test/runners/run-xr-immersive-harness.cjs index 29aa247d..4a3bc303 100644 --- a/apps/vscode-extension/test/runners/run-xr-immersive-harness.cjs +++ b/apps/vscode-extension/test/runners/run-xr-immersive-harness.cjs @@ -1,11 +1,21 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); -const { pathToFileURL } = require('node:url'); +const { startStaticServer } = require('../helpers/staticHttpServer.cjs'); const { buildAssembledRuntimes } = require('../manual/buildAssembledRuntimes.cjs'); const projectRoot = path.resolve(__dirname, '..', '..'); const harnessPath = path.join(projectRoot, 'test', 'manual', 'xr-immersive-harness.html'); +// Served over HTTP (projectRoot at '/'): from file:// Chromium blocks fetch(), +// so the modes' datasets never loaded and a load failure went unnoticed. +let staticServer = null; +async function harnessUrl() { + staticServer ||= await startStaticServer(projectRoot); + return staticServer.url(path.relative(projectRoot, harnessPath)); +} +async function closeStaticServer() { + if (staticServer) { await staticServer.close(); staticServer = null; } +} buildAssembledRuntimes(); // --------------------------------------------------------------------------- @@ -159,6 +169,7 @@ async function runPlaywrightIfAvailable() { await runScenario(browser); } finally { await browser.close(); + await closeStaticServer(); } console.log('[xr-immersive-harness] AR/VR semantics validation passed.'); } @@ -166,7 +177,7 @@ async function runPlaywrightIfAvailable() { async function runScenario(browser) { const page = await browser.newPage({ viewport: { width: 1280, height: 900 } }); page.on('pageerror', (error) => console.error('[page error]', error)); - await page.goto(pathToFileURL(harnessPath).toString(), { waitUntil: 'domcontentloaded' }); + await page.goto(await harnessUrl(), { waitUntil: 'domcontentloaded' }); await page.waitForSelector('#scene', { timeout: 15000 }); await page.evaluate(() => new Promise((resolve) => { const scene = document.getElementById('scene'); diff --git a/apps/vscode-extension/test/runners/run-xr-mode-cycle-harness.cjs b/apps/vscode-extension/test/runners/run-xr-mode-cycle-harness.cjs index 3959a9db..19cc3498 100644 --- a/apps/vscode-extension/test/runners/run-xr-mode-cycle-harness.cjs +++ b/apps/vscode-extension/test/runners/run-xr-mode-cycle-harness.cjs @@ -1,11 +1,21 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); -const { pathToFileURL } = require('node:url'); +const { startStaticServer } = require('../helpers/staticHttpServer.cjs'); const { buildAssembledRuntimes } = require('../manual/buildAssembledRuntimes.cjs'); const projectRoot = path.resolve(__dirname, '..', '..'); const harnessPath = path.join(projectRoot, 'test', 'manual', 'xr-mode-cycle-harness.html'); +// Served over HTTP (projectRoot at '/'): from file:// Chromium blocks fetch(), +// so the modes' datasets never loaded and a load failure went unnoticed. +let staticServer = null; +async function harnessUrl() { + staticServer ||= await startStaticServer(projectRoot); + return staticServer.url(path.relative(projectRoot, harnessPath)); +} +async function closeStaticServer() { + if (staticServer) { await staticServer.close(); staticServer = null; } +} buildAssembledRuntimes(); const html = fs.readFileSync(harnessPath, 'utf8'); @@ -32,6 +42,7 @@ async function runPlaywrightIfAvailable() { await runScenario(browser); } finally { await browser.close(); + await closeStaticServer(); } console.log('[xr-mode-harness] controller mode-cycle validation passed.'); } @@ -42,7 +53,7 @@ async function runPlaywrightIfAvailable() { // the controller view/mode state at every step. async function runScenario(browser) { const page = await browser.newPage({ viewport: { width: 1280, height: 900 } }); - await page.goto(pathToFileURL(harnessPath).toString(), { waitUntil: 'domcontentloaded' }); + await page.goto(await harnessUrl(), { waitUntil: 'domcontentloaded' }); await page.waitForSelector('#scene', { timeout: 10000 }); await page.evaluate(() => new Promise((resolve) => { const scene = document.getElementById('scene');