From 09013ce29b6e9f83322c9ac2d592d98688941351 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 21:26:50 +0000 Subject: [PATCH] fix(launcher): one transactional launch path for every analysis kind (S5, #77) Every launch (XR, LivePanel, VisualizeDOM) now runs as one transaction under LaunchControl: an abort signal, a 10-minute deadline and a teardown stack per session. The server starts before the watcher for every kind; a failure, the deadline or Close Analysis kills the running Python analysis and undoes the started steps newest first, exactly once. A closed launch is silent; a failed one shows one error. - targetKey(): one identity per target (case-folded on Windows/macOS, no trailing separator); the registry reserves a target before its first await, so concurrent launches yield one session (LAUNCHER-2, -17) - SSE channel and file map keyed by session id; SessionServerManager and SseNotificationManager removed; the close path matches servers by metadata.sessionId only, never by path substring - analysis types and launch kinds are descriptors (core/analysis/launch); server capabilities, default controller views and router snapshot probes are derived from them; resolveLauncher refuses unsupported combinations by name - startup cleanup sweeps the folders the launchers actually write (LAUNCHER-14) - Python output read as UTF-8 on every platform - docs/adding-an-analysis-type.md; CHANGELOG [1.2.1] Fixed; test/analysis/launchTransaction.test.cjs (15 tests); guardrail baseline regenerated; ESLint warning budget 158 -> 155 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKtAtQus8TVjhG9bhytC --- .claude/docs/ARCHITECTURE.md | 15 +- .claude/docs/V1.2.1_STATUS.md | 8 + apps/vscode-extension/CHANGELOG.md | 9 + .../docs/adding-an-analysis-type.md | 73 +++ apps/vscode-extension/package.json | 2 +- .../src/core/analysis/analysisOrchestrator.ts | 83 +--- .../src/core/analysis/launch/analysisTypes.ts | 105 +++++ .../src/core/analysis/launch/launchControl.ts | 196 ++++++++ .../src/core/analysis/launch/launchKinds.ts | 67 +++ .../core/analysis/launch/storageFolders.ts | 22 + .../src/core/analysis/launch/targetKey.ts | 40 ++ .../core/analysis/launchers/launchPipeline.ts | 321 +++++++------ .../analysis/launchers/launcherLivePanel.ts | 5 +- .../launchers/launcherVisualizeDOM.ts | 4 +- .../analysis/launchers/launcherXRAnalysis.ts | 5 +- .../src/core/analysis/python/executePython.ts | 30 +- .../analysis/refresh/analysisViewModes.ts | 28 +- .../serverLaunchOrchestrator.ts | 25 +- .../session-servers/sessionServerManager.ts | 199 -------- .../session-servers/sessionServerModels.ts | 18 +- .../session-servers/sseNotificationManager.ts | 159 ------- .../core/analysis/session/sessionRegistry.ts | 43 +- .../analysis/watchers/directoryReAnalyzer.ts | 17 +- .../analysis/watchers/reAnalysisManager.ts | 6 +- .../server/analysis/analysisFeatureHost.ts | 7 +- .../server/analysis/analysisMessageRouter.ts | 21 +- .../core/server/analysisServerCapabilities.ts | 44 +- .../collaboration/collaborationSessionApi.ts | 3 +- .../src/core/server/serverControl.ts | 28 +- .../src/core/server/serverFactory.ts | 19 + .../commands/cleanAnalysisCommands.ts | 56 +-- .../services/serverWatcherIntegration.ts | 68 ++- .../analysisServerCapabilities.test.cjs | 31 +- .../test/analysis/launchTransaction.test.cjs | 430 ++++++++++++++++++ .../analysis/livePanelHistorical.test.cjs | 13 +- .../test/tooling/guardrail-baseline.json | 39 +- 36 files changed, 1405 insertions(+), 834 deletions(-) create mode 100644 apps/vscode-extension/docs/adding-an-analysis-type.md create mode 100644 apps/vscode-extension/src/core/analysis/launch/analysisTypes.ts create mode 100644 apps/vscode-extension/src/core/analysis/launch/launchControl.ts create mode 100644 apps/vscode-extension/src/core/analysis/launch/launchKinds.ts create mode 100644 apps/vscode-extension/src/core/analysis/launch/storageFolders.ts create mode 100644 apps/vscode-extension/src/core/analysis/launch/targetKey.ts delete mode 100644 apps/vscode-extension/src/core/analysis/session-servers/sessionServerManager.ts delete mode 100644 apps/vscode-extension/src/core/analysis/session-servers/sseNotificationManager.ts create mode 100644 apps/vscode-extension/test/analysis/launchTransaction.test.cjs diff --git a/.claude/docs/ARCHITECTURE.md b/.claude/docs/ARCHITECTURE.md index cbc717f8d..a02a929eb 100644 --- a/.claude/docs/ARCHITECTURE.md +++ b/.claude/docs/ARCHITECTURE.md @@ -13,20 +13,25 @@ CodeXR is a VS Code extension (291 TS files under `src/`, in five layers since # ``` User command (context menu / tree / palette) └─> src/features/analysis/commands/... (per-mode command handlers) - └─> src/core/analysis/launchers/launcherXRAnalysis.ts | launcherLivePanel.ts | launcherVisualizeDOM.ts - └─> launchers/launchPipeline.ts → creates a UnifiedAnalysisSession + └─> src/core/analysis/analysisOrchestrator.ts → session/sessionRegistry.ts (one session per targetKey) + └─> launch/launchKinds.ts resolveLauncher(kind, targetType) + └─> launchers/launcherXRAnalysis.ts | launcherLivePanel.ts | launcherVisualizeDOM.ts + └─> launchers/launchPipeline.ts → one transaction under launch/launchControl.ts + (abort signal + 10 min deadline + teardown stack; process → save → server → watcher) ├─> python/executePython.ts → spawns managed venv, runs python/main.py → JSON metrics ├─> src/core/charts/ → validates dimension mapping, fills HTML template │ (chart registry + placeholder processing over templates/xr/...) ├─> scene-assets/*ComponentAsset.ts │ → inlines browser runtimes from templates/components/**/*.js into the HTML - └─> session-servers/serverLaunchOrchestrator.ts (+ sessionServerManager) + └─> session-servers/serverLaunchOrchestrator.ts (SSE + file map keyed by session id) └─> src/core/server (HTTP/HTTPS) serves the scene └─> registered in src/core/server/registry → shown in sidebar tree (src/features/active-servers) Live updates: core/analysis/watchers/* detect file changes → re-run Python → - core/analysis/session-servers/sseNotificationManager.ts → src/core/server/sse/SSEManager.ts → browser reloads data + src/core/server/sse/SSEManager.ts (by session id) → browser reloads data ``` +Analysis types (what the table shows) and launch kinds (how a page is served) are descriptors in `core/analysis/launch/` (`analysisTypes.ts`, `launchKinds.ts`, `storageFolders.ts`); the server-capability, controller-view and snapshot-probe tables are derived from them. Checklist: `apps/vscode-extension/docs/adding-an-analysis-type.md`. + Three analysis modes share this pipeline: **XR** (A-Frame scene in browser/headset), **LivePanel** (2D webview panel), **DOM visualization** (HTML DOM structure in XR). Each mode has its own launcher and parser (`core/analysis/parsers/`); one shared requirement processor (`core/analysis/processors/FileRequirementProcessor.ts` → `analysisBootstrap.ts`) loads the templates the mode needs. ## Activation flow (`src/extension.ts`) @@ -46,7 +51,7 @@ Three analysis modes share this pipeline: **XR** (A-Frame scene in browser/heads | Module | Responsibility | Key files | |---|---|---| | `features/analysis/` | The ANALYSES section: the per-mode analysis commands (file, directory, DOM, clean), the tree and its subsections (active analyses, files/project by language, analysis settings), the workspace scan and the server watcher integration | `commands/analysisCommandRegistrations.ts`, `commands/analysisCommands.ts`, `commands/{file,directory,dom}/`, `views/AnalysisSectionProvider.ts`, `sections/active-analyses/activeAnalysesCommands.ts` (Active Analyses actions and export), `sections/settings/` (one folder per setting; `chartTypeCommandFactory.ts` and the two `shared*SettingCore.ts` at its root), `workspace/workspaceSnapshotService.ts`, `workspace/workspaceFileScanner.ts`, `services/serverWatcherIntegration.ts` | -| `core/analysis/` | **The analysis engine.** Pipeline: launchers, parsers, the requirement processor, sessions, session servers, watchers, refresh, the Python bridge, the scene-asset injection, the language tables | `analysisOrchestrator.ts`, `launchers/launchPipeline.ts`, `launchers/launcherXRAnalysis.ts`, `session/analysisSession.ts`, `session/sessionRegistry.ts`, `session-servers/sessionServerManager.ts`, `watchers/sessionWatcherManager.ts`, `python/executePython.ts`, `python/xrFieldSchemaService.ts`, `configuration/analysisConfigurationStorage.ts`, `languages/languageMetadata.ts`, `languages/supportedLanguages.ts` | +| `core/analysis/` | **The analysis engine.** Pipeline: launchers, parsers, the requirement processor, sessions, session servers, watchers, refresh, the Python bridge, the scene-asset injection, the language tables | `analysisOrchestrator.ts`, `launchers/launchPipeline.ts`, `launchers/launcherXRAnalysis.ts`, `session/analysisSession.ts`, `session/sessionRegistry.ts`, `launch/launchControl.ts`, `launch/analysisTypes.ts`, `launch/launchKinds.ts`, `session-servers/serverLaunchOrchestrator.ts`, `watchers/sessionWatcherManager.ts`, `python/executePython.ts`, `python/xrFieldSchemaService.ts`, `configuration/analysisConfigurationStorage.ts`, `languages/languageMetadata.ts`, `languages/supportedLanguages.ts` | | `backend/src/` (repository root, outside `src/`) | Python analysis backend (see `PYTHON_ANALYSIS.md`); copied into `dist/code_analysis/python` by webpack | `main.py`, `tools/lizard_analyzer.py`, `utils/xr_field_schema.py` | | `core/dependencies/` | Dependency-graph analysis service (see `docs/features/DEPENDENCY_GRAPH_XR.md`) | `dependencyGraphService.ts`, `dependencyGraphModels.ts` | | `core/export/` | Analysis export: the manifest, the package transaction and the Git-revision exporter with its Python worker pool | `exportManifest.ts`, `exportPackageTransaction.ts`, `gitRevisionExporter.ts`, `gitRevisionExportCore.ts`, `gitTimelineBlobAnalyzer.ts` | diff --git a/.claude/docs/V1.2.1_STATUS.md b/.claude/docs/V1.2.1_STATUS.md index 2064d56e0..fbcafcfa7 100644 --- a/.claude/docs/V1.2.1_STATUS.md +++ b/.claude/docs/V1.2.1_STATUS.md @@ -282,3 +282,11 @@ Then pushed `v1.2.1` to `origin` at the maintainer's request. **No merge and no **E2E findings (older behaviour, identical on the pre-cleanup VSIX, recorded for 1.3.0)**: the Barsmap and Pie examples get 404 for `../../data/*.json` (static root is the example folder); the same target analysed in two modes at once leaves the first server's `/events` at 404 (one port per file in the file-to-server map); `babia-html`'s html2canvas throws in headless Chromium. **Where it is written up**: `docs/cleanup/REPORT.md` (repository root): findings, story/PR table, neutrality evidence, the §5 table, the 1.3.0 deferrals, the E2E result per feature-baseline §10 row and the **consolidated maintainer F5/VSIX checklist**, which is what remains before the release is cut. + +### XR bug-fix epic #72 — S5 unified launcher (#77) [confirmed by unit tests] (2026-11-25, branch `claude/project-thread-kvvyg6-launcher`) + +**Scope**: the XR audit (`docs/xr-audit/`, PR #67) found the launch path non-transactional (LAUNCHER-2/5/7/10/14/17 and related). Fixes of this epic land in 1.2.1 by the author's decision (CHANGELOG `Fixed`), overriding the maintenance-only rule for them. + +**What changed**: `core/analysis/launch/` (new): `targetKey.ts`, `launchControl.ts` (AbortController + 10 min deadline + teardown stack per session, signal carried to the Python spawn via AsyncLocalStorage), `analysisTypes.ts` / `launchKinds.ts` / `storageFolders.ts` (descriptors; server capabilities, default controller views and router snapshot probes are derived). `launchPipeline.ts` is a transaction: server before watcher for every kind, rollback newest first, one error toast, silent on Close. Registry reserves the target before its first await. SSE + file map keyed by session id; `sessionServerManager.ts` and `sseNotificationManager.ts` deleted; close path matches servers by `metadata.sessionId` only. Startup cleanup sweeps the folders the launchers write. + +**Measured**: ESLint warnings 158 → 155 (budget `--max-warnings` lowered to 155); guardrails any.total 84 → 83, complexity.over10 53 → 52 (baseline regenerated). New suite `test/analysis/launchTransaction.test.cjs` (15 tests). Not done here: progress notifications are not cancellable (Close Analysis is the cancel path); LAUNCHER-11 belongs to another story. diff --git a/apps/vscode-extension/CHANGELOG.md b/apps/vscode-extension/CHANGELOG.md index 7358ce528..83d5408ea 100644 --- a/apps/vscode-extension/CHANGELOG.md +++ b/apps/vscode-extension/CHANGELOG.md @@ -60,6 +60,15 @@ - The table fit checked the chart's size but not its position: centring the bars could push the axis off one side. The axes are now kept on the table, and a chart that still sticks out is no longer reported as fitted. - The fit could measure a cached, outdated size of a line that had just changed. Sizes are now re-read when the geometry changes. - Generated scenes first built every chart over all files and only then switched to the top 20/30 shown. They now build once, from the files that are shown. +- **Launching an analysis is one transaction that can be stopped.** Every analysis kind (XR, LivePanel, DOM visualization) now runs through the same launcher, and several problems it had are fixed: + - Closing an analysis while it is still analysing stops it: the Python analysis is killed and no server or file watcher is started afterwards. Before, the launch went on and left a server and a watcher running that nothing could reach. + - If the server cannot start, the file watcher is not left running, and you get one error message instead of two. The server now starts before the watcher for every kind. + - A launch that takes more than 10 minutes is stopped and reported instead of waiting forever. + - Two quick launches of the same file, or the same file spelled differently (`C:\proj\a.ts` and `c:\proj\a.ts` on Windows, a trailing slash on a folder), no longer create two sessions. + - Two analyses of the same file no longer share one live-reload channel, and closing one analysis no longer stops the server of another whose path merely contains the same text. + - Startup cleanup now removes the old generated files of file, folder and DOM analyses. It used to clean a folder nothing wrote to, so the real ones grew without limit. + - Analysis output with non-ASCII characters (accented file names, for example) is read correctly on Windows. + - Internally, the analysis types and launch kinds are declared once and the tables that repeated them are derived; `docs/adding-an-analysis-type.md` explains how to add one. - A source file of the XR chart-mapping runtime contained a raw control character typed into a string. Behaviour was correct, but the file was invisible to code search and review tools. It now uses the equivalent escape sequence; the runtime value is identical. ## [1.2.0] - 2026-07-30 diff --git a/apps/vscode-extension/docs/adding-an-analysis-type.md b/apps/vscode-extension/docs/adding-an-analysis-type.md new file mode 100644 index 000000000..1dda0aadd --- /dev/null +++ b/apps/vscode-extension/docs/adding-an-analysis-type.md @@ -0,0 +1,73 @@ +# Adding an analysis type + +An **analysis type** is *what* the analysis table shows: the classic chart, +the dependency graph, the historical comparison, the project evolution. A +**launch kind** is *how* a page is produced and served for a target: an XR +scene, a LivePanel webview, a DOM visualization. Since 1.2.1 (S5, issue #77) +both are declared once, as descriptors, and the host tables that used to +restate them are derived. + +| Descriptor list | File | Read by | +|---|---|---| +| `ANALYSIS_TYPES` | `src/core/analysis/launch/analysisTypes.ts` | server features per surface (`core/server/analysisServerCapabilities.ts`), the default controller view per mode (`core/analysis/refresh/analysisViewModes.ts`, also used by the export manifest), the room-cache probes of the collaboration router (`core/server/analysis/analysisMessageRouter.ts`) | +| `LAUNCH_KINDS` | `src/core/analysis/launch/launchKinds.ts` | `AnalysisOrchestrator` (dispatch through `resolveLauncher`) | +| `ANALYSIS_STORAGE_FOLDERS` | `src/core/analysis/launch/storageFolders.ts` | the launchers (where to write) and startup cleanup (what to sweep) | + +## Checklist: a new in-scene analysis + +1. **Descriptor.** Add an entry to `ANALYSIS_TYPES`: `id` (also the + coordinator mode and the browser runtime id), `label`, `controllerView`, + `serverFeature` (or `null`), `surfaces`, and a `snapshotProbe` if the room + can replay its result from a cached entity. Keep the file import-free: the + export manifest requires it from `out/` without a vscode stub. +2. **Server feature** (only if it needs endpoints). Add the name to + `AnalysisServerFeature` and a boolean to `AnalysisServerCapabilities`, then + attach the service where the existing ones are attached (follow + `projectEvolution` through `core/server/analysis/analysisFeatureHost.ts`). + A service that resolves an XR-only session must only be listed on the + surfaces that serve it, or it aborts every other launch. +3. **Browser runtime.** Register the mode in the analysis-mode runtime + (`templates/components/codexr/analysis-mode/`) with the same `id`, and add + its view to `MODE_CONTROLLER_VIEW_BY_ID` there. + `test/analysis/controllerViewMapSync.test.cjs` fails until the browser map + and the descriptors agree. Respect the load order in + `templates/components/COMPONENTS.md` and rebuild the assembled runtimes + (`node test/manual/buildAssembledRuntimes.cjs`). +4. **Chart.** Build and rebuild its chart through the analysis-table + containment (`beginRebuild` → fit → reveal) and read rows through a + row-budgeted slice (`prepareChartDataSlice`), never the raw source; see + "Rebuild and reveal (1.2.1)" in `COMPONENTS.md`. +5. **Tests.** Extend `test/analysis/launchTransaction.test.cjs` ("the host + tables derived from the analysis types are unchanged") with the new row, + plus the capability test (`analysisServerCapabilities.test.cjs`) if it + attaches a feature. + +## Checklist: a new launch kind + +1. Add the id to `LaunchKindId` (`analysisTypes.ts`) and to `AnalysisMode`. +2. Write a launcher that builds a `LaunchPipelineConfig` and calls + `executeLaunchPipeline` (see `launchers/launcherLivePanel.ts`). Do not start + a server or a watcher yourself: the pipeline starts the server, then the + watcher, and owns their teardown. +3. Add a folder to `ANALYSIS_STORAGE_FOLDERS` and pass it as `folderName` + (never a string literal: the cleanup test checks it). +4. Add the descriptor to `LAUNCH_KINDS` with one launcher per supported target + type; an unsupported combination is refused by `resolveLauncher` with a + message that names it. +5. List the kind in the `surfaces` of the analysis types it serves. + +## What the pipeline guarantees + +Every launch runs as a transaction under `LaunchControl` +(`launch/launchControl.ts`): + +- one session per target: the registry reserves the target **before** its + first `await`, and compares targets through `targetKey()` (resolved, no + trailing separator, case-folded on Windows and macOS); +- steps run in order pre-validation → analysis → save → server → watcher, and + each step that starts something records how to undo it; +- a failure, the 10-minute deadline or **Close Analysis** aborts the launch, + kills a running Python analysis, and undoes the started steps newest first, + exactly once. A closed launch shows nothing; a failed one shows one error; +- the server's SSE channel and file mapping are keyed by the session id, so + two sessions on the same file never cross their live reloads. diff --git a/apps/vscode-extension/package.json b/apps/vscode-extension/package.json index c295ca8be..9c017c96c 100644 --- a/apps/vscode-extension/package.json +++ b/apps/vscode-extension/package.json @@ -752,7 +752,7 @@ "typecheck": "node ../../node_modules/typescript/bin/tsc --noEmit --incremental false -p tsconfig.check.json && node ../../node_modules/typescript/bin/tsc --incremental false -p tsconfig.tooling.json", "compile-tests": "node -e \"require('fs').rmSync('out',{recursive:true,force:true})\" && node ../../node_modules/typescript/bin/tsc -p . --outDir out", "watch-tests": "node ../../node_modules/typescript/bin/tsc -p . -w --outDir out", - "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 158", + "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 155", "test": "npm run test:basic", "test:basic": "npm run typecheck && npm run lint && npm run compile-tests && npm run test:unit", "test:unit": "node test/runners/run-node-tests.cjs", diff --git a/apps/vscode-extension/src/core/analysis/analysisOrchestrator.ts b/apps/vscode-extension/src/core/analysis/analysisOrchestrator.ts index 39341a1b9..acb47cab7 100644 --- a/apps/vscode-extension/src/core/analysis/analysisOrchestrator.ts +++ b/apps/vscode-extension/src/core/analysis/analysisOrchestrator.ts @@ -4,9 +4,7 @@ */ import * as vscode from 'vscode'; -import { LauncherLivePanel } from './launchers/launcherLivePanel'; -import { LauncherXRAnalysis } from './launchers/launcherXRAnalysis'; -import { LauncherVisualizeDOM } from './launchers/launcherVisualizeDOM'; +import { resolveLauncher } from './launch/launchKinds'; import { UnifiedSessionRegistry } from './session/sessionRegistry'; import { UnifiedAnalysisSession, AnalysisMode, TargetType } from './session/analysisSession'; import { getLogger } from '../../platform/logging/sink'; @@ -99,81 +97,24 @@ export class AnalysisOrchestrator { status: session.status }); - // Send session to appropriate launcher - switch (analysisMode) { - case 'LivePanel': - await this.orchestrateLivePanelAnalysis(session, context); - break; - - case 'XR': - await this.orchestrateXRAnalysis(session, context); - break; - - case 'VisualizeDOM': - await this.orchestrateVisualizeDOMAnalysis(session, context); - break; - - default: - throw new Error(`Unknown analysis mode: ${analysisMode}`); + // One table of launch kinds (launch/launchKinds.ts) instead of a + // switch per mode and target type. Resolved before anything runs, + // so an unsupported combination is refused, not half-launched. + let launch: ReturnType; + try { + launch = resolveLauncher(analysisMode, session.targetType); + } catch (unsupported) { + registry.removeSession(session.id); + throw unsupported; } - + await launch(session, context); + } catch (error) { logger.error('Error orchestrating analysis:', error); throw error; } } - /** - * Orchestrate Live Panel analysis with session - */ - private static async orchestrateLivePanelAnalysis(session: UnifiedAnalysisSession, context: vscode.ExtensionContext): Promise { - switch (session.targetType) { - case 'file': - logger.debug('Launching Live Panel analysis for file:', session.targetPath); - await LauncherLivePanel.launchFileLivePanelAnalysis(session, context); - break; - - case 'directory': - logger.debug('Launching Live Panel analysis for directory:', session.targetPath); - await LauncherLivePanel.launchDirectoryLivePanelAnalysis(session, context); - break; - - default: - throw new Error(`Unknown target type: ${session.targetType}`); - } - } - - /** - * Orchestrate XR analysis with session - */ - private static async orchestrateXRAnalysis(session: UnifiedAnalysisSession, context: vscode.ExtensionContext): Promise { - switch (session.targetType) { - case 'file': - await LauncherXRAnalysis.launchFileXRAnalysis(session, context); - break; - - case 'directory': - await LauncherXRAnalysis.launchDirectoryXRAnalysis(session, context); - break; - - default: - throw new Error(`Unknown target type: ${session.targetType}`); - } - } - - /** - * Orchestrate VisualizeDOM analysis with session - */ - private static async orchestrateVisualizeDOMAnalysis(session: UnifiedAnalysisSession, context: vscode.ExtensionContext): Promise { - // VisualizeDOM only supports files (HTML files specifically) - if (session.targetType !== 'file') { - throw new Error(`VisualizeDOM analysis only supports files, not ${session.targetType}`); - } - - logger.debug('Launching VisualizeDOM analysis for file:', session.targetPath); - await LauncherVisualizeDOM.launchVisualizeDOMAnalysis(session, context); - } - /** * Get analysis type identifier for the given parameters */ diff --git a/apps/vscode-extension/src/core/analysis/launch/analysisTypes.ts b/apps/vscode-extension/src/core/analysis/launch/analysisTypes.ts new file mode 100644 index 000000000..dfff0b9c4 --- /dev/null +++ b/apps/vscode-extension/src/core/analysis/launch/analysisTypes.ts @@ -0,0 +1,105 @@ +/** + * The in-scene analyses, one descriptor each. + * + * An analysis type is WHAT the table shows (classic, dependency graph, + * historical comparison, project evolution); a launch kind (launchKinds.ts) + * is HOW a page is produced and served (XR, LivePanel, VisualizeDOM). Several + * host tables used to restate these facts independently: which server + * features each surface attaches (analysisServerCapabilities.ts), the view + * each mode opens with (analysisViewModes.ts) and which cached room entity + * makes a mode available (analysisMessageRouter.ts). They are now derived + * from this list, so adding an analysis type starts with one entry here (see + * apps/vscode-extension/docs/adding-an-analysis-type.md for the rest of the + * checklist). + * + * Deliberately pure, with zero imports: `analysisViewModes.ts` reads it and + * must stay require()-able from `out/` without a vscode stub. + */ + +/** A launch surface, as `AnalysisMode` names it. */ +export type LaunchKindId = 'XR' | 'LivePanel' | 'VisualizeDOM'; + +/** The server feature an analysis type needs attached (null: none). */ +export type AnalysisServerFeature = 'dependencyGraph' | 'historicalComparison' | 'projectEvolution'; + +export interface AnalysisSnapshotProbe { + /** The room entity kind that carries this analysis's result. */ + entityKind: string; + /** Whether a cached entity is enough to show the analysis at once. */ + isAvailable(snapshot: Record | null | undefined): boolean; +} + +export interface AnalysisTypeDescriptor { + /** Also the coordinator mode and the in-scene runtime id. */ + id: string; + label: string; + /** The controller view the analysis opens with when none is named. */ + controllerView: string; + /** The server feature it needs; null when it needs none (classic). */ + serverFeature: AnalysisServerFeature | null; + /** The surfaces that serve it. */ + surfaces: ReadonlyArray; + /** How the router tells, from the room cache, that its result is ready. */ + snapshotProbe?: AnalysisSnapshotProbe; +} + +export const ANALYSIS_TYPES: ReadonlyArray = Object.freeze([ + { + id: 'single', + label: 'Classic analysis', + controllerView: 'single.mapping', + serverFeature: null, + surfaces: ['XR', 'LivePanel'], + }, + { + id: 'dependency-graph', + label: 'Dependency graph', + controllerView: 'dependency.settings', + serverFeature: 'dependencyGraph', + surfaces: ['XR', 'LivePanel'], + snapshotProbe: { + entityKind: 'dependency-graph', + isAvailable: (snapshot) => typeof snapshot?.datasetUrl === 'string', + }, + }, + { + id: 'historical-compare', + label: 'Historical comparison', + controllerView: 'historical.selection', + serverFeature: 'historicalComparison', + surfaces: ['XR', 'LivePanel'], + snapshotProbe: { + entityKind: 'historical-comparison', + isAvailable: (snapshot) => !!snapshot?.result, + }, + }, + { + id: 'project-evolution', + label: 'Project evolution', + controllerView: 'project-evolution', + serverFeature: 'projectEvolution', + surfaces: ['XR'], + snapshotProbe: { + entityKind: 'project-evolution', + isAvailable: (snapshot) => !!snapshot?.result, + }, + }, +]); + +/** The menu every surface opens on; not an analysis itself. */ +export const SELECTION_MODE = Object.freeze({ id: 'selection', controllerView: 'visualization-menu' }); + +export function getAnalysisType(id: string): AnalysisTypeDescriptor | undefined { + return ANALYSIS_TYPES.find((type) => type.id === id); +} + +/** The server features a surface must attach for the analyses it serves. */ +export function getServerFeaturesForSurface(surface: string | undefined): Set { + const features = new Set(); + for (const type of ANALYSIS_TYPES) { + if (type.serverFeature && (type.surfaces as ReadonlyArray).includes(surface ?? '')) { + features.add(type.serverFeature); + } + } + return features; +} diff --git a/apps/vscode-extension/src/core/analysis/launch/launchControl.ts b/apps/vscode-extension/src/core/analysis/launch/launchControl.ts new file mode 100644 index 000000000..a5bfafcfb --- /dev/null +++ b/apps/vscode-extension/src/core/analysis/launch/launchControl.ts @@ -0,0 +1,196 @@ +/** + * Per-launch control: one AbortController, one deadline and one teardown + * stack for every analysis launch, keyed by session id. + * + * Before this, nothing on the launch path could be cancelled or timed out + * (LAUNCHER-10), closing an analysis while it was still analysing let the + * pipeline go on to start a server and a watcher nobody could reach + * (LAUNCHER-7), and a launch that failed at the server step left its watcher + * running (LAUNCHER-5). Each step that starts something pushes how to undo + * it; a failure, a timeout or a Close disposes the stack in reverse, exactly + * once. + * + * The Python backend is reached many calls deep from the pipeline. Rather + * than thread a signal through every processor, the pipeline runs inside + * `runWithLaunchSignal`, and the Python spawner reads the signal from the + * async context (`currentLaunchSignal`) and kills its child on abort. + */ +import { AsyncLocalStorage } from 'async_hooks'; +import { getLogger } from '../../../platform/logging/sink'; + +const logger = getLogger('LAUNCH_CONTROL'); + +/** Default time a launch may take before it is aborted: 10 minutes. */ +export const DEFAULT_LAUNCH_TIMEOUT_MS = 10 * 60 * 1000; + +export type LaunchAbortReason = 'closed' | 'timeout' | 'failed' | 'superseded'; + +export class LaunchAbortedError extends Error { + constructor(public readonly reason: LaunchAbortReason, message?: string) { + super(message || describeAbortReason(reason)); + this.name = 'LaunchAbortedError'; + } +} + +export function describeAbortReason(reason: LaunchAbortReason | string | undefined): string { + switch (reason) { + case 'closed': return 'The analysis was closed before it finished.'; + case 'timeout': return 'The analysis took too long and was stopped.'; + case 'superseded': return 'The analysis was replaced by a newer launch.'; + default: return 'The analysis launch was stopped.'; + } +} + +interface TeardownStep { + name: string; + dispose: () => unknown | Promise; +} + +interface LaunchRecord { + sessionId: string; + controller: AbortController; + teardown: TeardownStep[]; + timer: ReturnType | null; + disposed: boolean; +} + +const signalContext = new AsyncLocalStorage(); + +export class LaunchControl { + private static instance: LaunchControl | null = null; + private readonly records = new Map(); + + static getInstance(): LaunchControl { + if (!LaunchControl.instance) { + LaunchControl.instance = new LaunchControl(); + } + return LaunchControl.instance; + } + + /** Test seam: a fresh instance, without touching the shared one. */ + static createForTesting(): LaunchControl { + return new LaunchControl(); + } + + /** + * Opens the control record of a launch. `timeoutMs <= 0` disables the + * deadline. Beginning a session that already has a record aborts the old + * one first: there is never more than one launch per session. + */ + begin(sessionId: string, timeoutMs: number = DEFAULT_LAUNCH_TIMEOUT_MS): AbortSignal { + const previous = this.records.get(sessionId); + if (previous) { + void this.abort(sessionId, 'superseded'); + } + const record: LaunchRecord = { + sessionId, + controller: new AbortController(), + teardown: [], + timer: null, + disposed: false, + }; + if (timeoutMs > 0) { + record.timer = setTimeout(() => { + logger.warn(`Launch ${sessionId} timed out after ${timeoutMs} ms`); + void this.abort(sessionId, 'timeout'); + }, timeoutMs); + // A pending launch deadline must not keep the extension host alive. + (record.timer as { unref?: () => void }).unref?.(); + } + this.records.set(sessionId, record); + return record.controller.signal; + } + + signal(sessionId: string): AbortSignal | undefined { + return this.records.get(sessionId)?.controller.signal; + } + + /** Records how to undo a step that just succeeded. */ + push(sessionId: string, name: string, dispose: () => unknown | Promise): void { + const record = this.records.get(sessionId); + if (!record || record.disposed) { + // The launch is already gone: undo immediately rather than leak. + void Promise.resolve().then(dispose).catch((error) => logger.error(`Teardown of ${name} failed:`, error)); + return; + } + record.teardown.push({ name, dispose }); + } + + /** Throws when the launch was aborted; call it between steps. */ + throwIfAborted(sessionId: string): void { + const signal = this.signal(sessionId); + if (signal?.aborted) { + throw new LaunchAbortedError((signal.reason as LaunchAbortReason) || 'closed'); + } + } + + /** The launch reached its final state: the deadline no longer applies. */ + settle(sessionId: string): void { + const record = this.records.get(sessionId); + if (record?.timer) { + clearTimeout(record.timer); + record.timer = null; + } + } + + /** + * Aborts the launch (if still running) and undoes everything it started, + * newest first. Safe to call more than once and for unknown sessions. + * Returns the names of the steps that were undone. + */ + async abort(sessionId: string, reason: LaunchAbortReason): Promise { + const record = this.records.get(sessionId); + if (!record) { + return []; + } + if (!record.controller.signal.aborted) { + record.controller.abort(reason); + } + return this.dispose(record); + } + + /** Closes a finished launch: same teardown, recorded as 'closed'. */ + close(sessionId: string): Promise { + return this.abort(sessionId, 'closed'); + } + + has(sessionId: string): boolean { + return this.records.has(sessionId); + } + + private async dispose(record: LaunchRecord): Promise { + if (record.timer) { + clearTimeout(record.timer); + record.timer = null; + } + if (record.disposed) { + return []; + } + record.disposed = true; + this.records.delete(record.sessionId); + const undone: string[] = []; + while (record.teardown.length) { + const step = record.teardown.pop()!; + try { + await step.dispose(); + undone.push(step.name); + } catch (error) { + logger.error(`Teardown of ${step.name} for ${record.sessionId} failed:`, error); + } + } + return undone; + } +} + +/** Runs `fn` with `signal` visible to `currentLaunchSignal()` below it. */ +export function runWithLaunchSignal(signal: AbortSignal | undefined, fn: () => Promise): Promise { + if (!signal) { + return fn(); + } + return signalContext.run(signal, fn); +} + +/** The abort signal of the launch this call runs under, if any. */ +export function currentLaunchSignal(): AbortSignal | undefined { + return signalContext.getStore(); +} diff --git a/apps/vscode-extension/src/core/analysis/launch/launchKinds.ts b/apps/vscode-extension/src/core/analysis/launch/launchKinds.ts new file mode 100644 index 000000000..ffdbad833 --- /dev/null +++ b/apps/vscode-extension/src/core/analysis/launch/launchKinds.ts @@ -0,0 +1,67 @@ +/** + * The launch surfaces, one descriptor each: HOW a page is produced and + * served for a target. The orchestrator dispatches through this table + * instead of a nested switch per mode and target type. + * + * Every kind runs the same transactional pipeline (launchPipeline.ts): the + * descriptor only names its launcher per target type. The in-scene analyses a + * surface offers are declared on the analysis types (analysisTypes.ts). + */ +import * as vscode from 'vscode'; +import { UnifiedAnalysisSession, TargetType } from '../session/analysisSession'; +import { LauncherLivePanel } from '../launchers/launcherLivePanel'; +import { LauncherXRAnalysis } from '../launchers/launcherXRAnalysis'; +import { LauncherVisualizeDOM } from '../launchers/launcherVisualizeDOM'; +import { LaunchKindId } from './analysisTypes'; + +type Launch = (session: UnifiedAnalysisSession, context: vscode.ExtensionContext) => Promise; + +export interface LaunchKind { + id: LaunchKindId; + label: string; + /** The launcher per supported target type; a missing entry is unsupported. */ + launchers: Readonly>>; +} + +export const LAUNCH_KINDS: Readonly> = Object.freeze({ + XR: { + id: 'XR', + label: 'XR scene', + launchers: { + file: (session, context) => LauncherXRAnalysis.launchFileXRAnalysis(session, context), + directory: (session, context) => LauncherXRAnalysis.launchDirectoryXRAnalysis(session, context), + }, + }, + LivePanel: { + id: 'LivePanel', + label: 'LivePanel', + launchers: { + file: (session, context) => LauncherLivePanel.launchFileLivePanelAnalysis(session, context), + directory: (session, context) => LauncherLivePanel.launchDirectoryLivePanelAnalysis(session, context), + }, + }, + VisualizeDOM: { + id: 'VisualizeDOM', + label: 'DOM visualization', + launchers: { + file: (session, context) => LauncherVisualizeDOM.launchVisualizeDOMAnalysis(session, context), + }, + }, +}); + +/** The launcher for a kind and target type, or an error naming what is unsupported. */ +export function resolveLauncher(kindId: string, targetType: TargetType): Launch { + // Own-property lookup: a mode such as "constructor" must be refused, not + // resolve to an Object.prototype member. + const kind = Object.prototype.hasOwnProperty.call(LAUNCH_KINDS, kindId) + ? (LAUNCH_KINDS as Record)[kindId] + : undefined; + if (!kind) { + throw new Error(`Unknown analysis mode: ${kindId}`); + } + const launch = kind.launchers[targetType]; + if (!launch) { + throw new Error(`${kind.label} analysis only supports ${Object.keys(kind.launchers).join(' and ')} targets, not ${targetType}`); + } + return launch; +} diff --git a/apps/vscode-extension/src/core/analysis/launch/storageFolders.ts b/apps/vscode-extension/src/core/analysis/launch/storageFolders.ts new file mode 100644 index 000000000..de2cac8e1 --- /dev/null +++ b/apps/vscode-extension/src/core/analysis/launch/storageFolders.ts @@ -0,0 +1,22 @@ +/** + * Where each launch kind keeps its generated files in workspace storage. + * + * One table read by the launchers (where to write) and by startup cleanup + * (what to sweep). Cleanup used to sweep `storage/analysis`, a folder nothing + * writes, so the real folders grew without bound (LAUNCHER-14). + * + * Deliberately pure, with zero imports. + */ +export const ANALYSIS_STORAGE_FOLDERS = Object.freeze({ + file: 'fileAnalysis', + directory: 'directoryAnalysis', + visualizeDOM: 'visualizeDOMAnalysis', +}); + +/** An old root nothing writes any more; still swept so it disappears. */ +export const LEGACY_ANALYSIS_STORAGE_FOLDER = 'analysis'; + +/** Every root startup cleanup sweeps. */ +export function getSweptStorageFolders(): string[] { + return [...Object.values(ANALYSIS_STORAGE_FOLDERS), LEGACY_ANALYSIS_STORAGE_FOLDER]; +} diff --git a/apps/vscode-extension/src/core/analysis/launch/targetKey.ts b/apps/vscode-extension/src/core/analysis/launch/targetKey.ts new file mode 100644 index 000000000..d736c2943 --- /dev/null +++ b/apps/vscode-extension/src/core/analysis/launch/targetKey.ts @@ -0,0 +1,40 @@ +/** + * One identity for an analysis target, whatever produced its path. + * + * Entry points hand the launcher paths spelled differently: `uri.fsPath` + * (lower-case drive letter on Windows), `path.resolve(workspace, rel)`, and + * paths reported by the Python backend. Compared raw, `C:\proj\a.ts` and + * `c:\proj\a.ts` were two targets, which let a second launch past the + * duplicate guard (LAUNCHER-17). Every identity comparison goes through this; + * the original string is kept for display and for spawning. + * + * Deliberately pure (only `path`), so it is testable for every platform from + * any platform. + */ +import * as path from 'path'; + +/** + * Normalised identity of `targetPath`: resolved, without a trailing + * separator, and case-folded where the file system usually is + * case-insensitive (Windows always, macOS by default). + */ +export function targetKey(targetPath: string, platform: NodeJS.Platform = process.platform): string { + const api = platform === 'win32' ? path.win32 : path.posix; + let resolved = api.resolve(String(targetPath || '')); + const root = api.parse(resolved).root; + while (resolved.length > root.length && (resolved.endsWith(api.sep) || resolved.endsWith('/'))) { + resolved = resolved.slice(0, -1); + } + return platform === 'win32' || platform === 'darwin' ? resolved.toLowerCase() : resolved; +} + +/** The key one launch reserves: a kind on a target, at one depth. */ +export function launchKey( + kind: string, + targetPath: string, + targetType: string, + isDeep: boolean, + platform: NodeJS.Platform = process.platform, +): string { + return [kind, targetType, isDeep ? 'deep' : 'shallow', targetKey(targetPath, platform)].join('|'); +} diff --git a/apps/vscode-extension/src/core/analysis/launchers/launchPipeline.ts b/apps/vscode-extension/src/core/analysis/launchers/launchPipeline.ts index 9d8e04f30..ec82a994c 100644 --- a/apps/vscode-extension/src/core/analysis/launchers/launchPipeline.ts +++ b/apps/vscode-extension/src/core/analysis/launchers/launchPipeline.ts @@ -1,11 +1,18 @@ /** * Launch Pipeline — shared execution logic for all analysis launchers. * - * Encapsulates the common 4-step flow: + * Encapsulates the common flow: * 1. Process/get required files * 2. Save files to storage - * 3. Start watcher for live updates - * 4. Start server with SSE + * 3. Start the server with SSE + * 4. Start the watcher for live updates + * + * The launch is a transaction (S5, LAUNCHER-5/7/10): it runs under a + * `LaunchControl` record with an abort signal and a deadline, every step that + * starts something pushes how to undo it, and any failure, timeout or Close + * undoes the whole stack in reverse. The server starts BEFORE the watcher for + * every kind, so a server that cannot start never leaves a watcher re-running + * the analysis for a page that does not exist. * * Each launcher configures the pipeline via {@link LaunchPipelineConfig} without * duplicating the orchestration boilerplate. @@ -16,7 +23,18 @@ import { UnifiedAnalysisSession } from '../session/analysisSession'; import { UnifiedSessionRegistry } from '../session/sessionRegistry'; import { ProcessedRequirements } from '../processors/FileRequirementProcessor'; import { SaveFiles } from '../utils/saveFiles'; -import { SessionServerManager } from '../session-servers/sessionServerManager'; +import { ServerLaunchOrchestrator } from '../session-servers/serverLaunchOrchestrator'; +import { SessionWatcherManager } from '../watchers/sessionWatcherManager'; +import { ServerControl } from '../../server/serverControl'; +import { getActiveServerRegistry } from '../../server/registry/activeServerRegistry'; +import { + DEFAULT_LAUNCH_TIMEOUT_MS, + LaunchAbortedError, + LaunchAbortReason, + LaunchControl, + describeAbortReason, + runWithLaunchSignal, +} from '../launch/launchControl'; import { getLogger } from '../../../platform/logging/sink'; const logger = getLogger('LAUNCH_PIPELINE'); @@ -27,9 +45,9 @@ export interface ProgressSteps { process: number; /** After files saved */ save: number; - /** After watcher started (or server, if startServerBeforeWatcher) */ + /** After the server started */ watcherOrServer: number; - /** After server started (or watcher, if startServerBeforeWatcher) */ + /** After the watcher started */ serverOrWatcher: number; /** Final — monitoring */ done: number; @@ -63,9 +81,6 @@ export interface LaunchPipelineConfig { /** Called after server started successfully (e.g. show info messages). */ onSuccess?: (serverPort: number | undefined, serverUrl: string | undefined) => void; - /** If true, the step order is Save → Server → Watcher instead of Save → Watcher → Server */ - startServerBeforeWatcher?: boolean; - /** If true, `session.endTime` is set on completion. */ setEndTime?: boolean; @@ -74,15 +89,17 @@ export interface LaunchPipelineConfig { } /** - * Execute the shared 4-step launch pipeline. + * Execute the shared launch pipeline for one session. * - * Maintains **identical** runtime behaviour to the original per-launcher code - * while eliminating ~400 lines of duplication. + * Resolves when the analysis is served and watched. A launch that was closed + * while running resolves quietly (the user asked for it); any other failure + * shows ONE error message and, for kinds that ask for it, rethrows. */ export async function executeLaunchPipeline( session: UnifiedAnalysisSession, context: vscode.ExtensionContext, config: LaunchPipelineConfig, + options: { timeoutMs?: number; control?: LaunchControl } = {}, ): Promise { const log = (msg: string) => logger.debug(() => `${config.logPrefix}: ${msg}`); const logError = (msg: string) => logger.error(`${config.logPrefix}: ${msg}`); @@ -90,153 +107,197 @@ export async function executeLaunchPipeline( log(`Starting analysis with session ${session.id}`); const registry = UnifiedSessionRegistry.getInstance(context); + const control = options.control ?? LaunchControl.getInstance(); + const signal = control.begin(session.id, options.timeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS); + const step = (work: Promise): Promise => untilAborted(work, signal); + const checkpoint = () => control.throwIfAborted(session.id); try { - // ── Optional pre-validation ────────────────────────────── - if (config.preValidation) { - await config.preValidation(); + await runWithLaunchSignal(signal, async () => { + // ── Optional pre-validation ────────────────────────────── + if (config.preValidation) { + await step(config.preValidation()); + } + checkpoint(); + + // ── STEP 1: Process requirements ───────────────────────── + log(`STEP 1 - Getting template files and data.json...`); + registry.updateSessionStatus(session.id, 'analyzing', config.progress.process); + + const processedFiles = await step(config.processRequirements()); + checkpoint(); + + log(`Received ${processedFiles.loadedFiles.size} processed template files`); + + // ── STEP 2: Save files ─────────────────────────────────── + log(`STEP 2 - Saving processed files to storage...`); + registry.updateSessionStatus(session.id, 'analyzing', config.progress.save); + + const saveFiles = new SaveFiles(); + const savedPath = await step(saveFiles.saveFilesToStorage( + processedFiles.loadedFiles, + config.folderName, + session.outputDirectory, + context, + )); + checkpoint(); + + log(`Files successfully saved to: ${savedPath}`); + + session.savedFilesPath = savedPath; + for (const [fileName, content] of processedFiles.loadedFiles) { + session.requiredFiles.set(fileName, content); + } + + const steps: StepContext = { session, context, registry, config, control, log, step }; + + // ── STEP 3: Server ─────────────────────────────────────── + await startServer(steps); + checkpoint(); + + // ── STEP 4: Watcher ────────────────────────────────────── + await startWatcher(steps, savedPath); + checkpoint(); + }); + + control.settle(session.id); + registry.updateSessionStatus(session.id, 'monitoring', config.progress.done); + if (config.setEndTime) { + session.endTime = new Date(); } + config.onSuccess?.(session.assignedPort, session.serverUrl); + log(`Analysis completed successfully!`); - // ── STEP 1: Process requirements ───────────────────────── - log(`STEP 1 - Getting template files and data.json...`); - registry.updateSessionStatus(session.id, 'analyzing', config.progress.process); - - const processedFiles = await config.processRequirements(); - - log(`Received ${processedFiles.loadedFiles.size} processed template files`); - for (const [fileName, content] of processedFiles.loadedFiles) { - log(` ${fileName} (${content.length} chars)`); - } + } catch (error) { + const reason = signal.aborted ? (signal.reason as LaunchAbortReason) : 'failed'; + await handleLaunchFailure(error, reason, { session, registry, config, control, log, logError }); + } +} - // ── STEP 2: Save files ─────────────────────────────────── - log(`STEP 2 - Saving processed files to storage...`); - registry.updateSessionStatus(session.id, 'analyzing', config.progress.save); +// ── Internal helpers ───────────────────────────────────────────── - const saveFiles = new SaveFiles(); - const savedPath = await saveFiles.saveFilesToStorage( - processedFiles.loadedFiles, - config.folderName, - session.outputDirectory, - context, - ); +/** What the server and watcher steps share. */ +interface StepContext { + session: UnifiedAnalysisSession; + context: vscode.ExtensionContext; + registry: UnifiedSessionRegistry; + config: LaunchPipelineConfig; + control: LaunchControl; + log: (msg: string) => void; + step: (work: Promise) => Promise; +} - log(`Files successfully saved to: ${savedPath}`); +/** + * Rolls a failed or stopped launch back and reports it: silent when the user + * closed it (or a newer launch replaced it), one error message otherwise. + */ +async function handleLaunchFailure( + error: unknown, + reason: LaunchAbortReason, + ctx: Omit & { logError: (msg: string) => void }, +): Promise { + const { session, registry, config, control, log } = ctx; + // Undo whatever this launch started, newest first: watcher, server. + const undone = await control.abort(session.id, reason); + if (undone.length) { + log(`Rolled back: ${undone.join(', ')}`); + } - // Update session with save information - session.savedFilesPath = savedPath; - for (const [fileName, content] of processedFiles.loadedFiles) { - session.requiredFiles.set(fileName, content); - } + if (reason === 'closed' || reason === 'superseded') { + // Nothing to report: the session is already being removed. + log(`Launch stopped: ${describeAbortReason(reason)}`); + return; + } - // ── STEPS 3 & 4: Watcher + Server (order configurable) ── - if (config.startServerBeforeWatcher) { - await startServer(session, context, registry, config, log, logError, savedPath); - await startWatcher(session, registry, config, log, savedPath); - } else { - await startWatcher(session, registry, config, log, savedPath); - await startServer(session, context, registry, config, log, logError, savedPath); - } + const message = reason === 'timeout' + ? describeAbortReason('timeout') + : (error instanceof Error ? error.message : String(error)); + ctx.logError(`Error during analysis: ${message}`); - // ── Finalize ───────────────────────────────────────────── - if (config.setEndTime) { - session.endTime = new Date(); - } + registry.updateSessionStatus(session.id, 'error', config.rethrowErrors ? 0 : undefined, message); + if (config.setEndTime) { + session.status = 'error'; + session.endTime = new Date(); + } - log(`Analysis completed successfully!`); + void vscode.window.showErrorMessage(`Failed to start analysis: ${message}`); - } catch (error) { - logError(`Error during analysis: ${error}`); + if (config.rethrowErrors) { + throw error instanceof LaunchAbortedError ? new Error(message) : error; + } +} - registry.updateSessionStatus( - session.id, - 'error', - config.rethrowErrors ? 0 : undefined, - error instanceof Error ? error.message : String(error), +/** + * Settles with `work`, or rejects as soon as the launch is aborted: Close and + * the deadline take effect at once, not when the step happens to return. + */ +function untilAborted(work: Promise, signal: AbortSignal): Promise { + if (signal.aborted) { + work.catch(() => undefined); + return Promise.reject(new LaunchAbortedError(signal.reason as LaunchAbortReason)); + } + return new Promise((resolve, reject) => { + const onAbort = () => reject(new LaunchAbortedError(signal.reason as LaunchAbortReason)); + signal.addEventListener('abort', onAbort, { once: true }); + work.then( + (value) => { signal.removeEventListener('abort', onAbort); resolve(value); }, + (error) => { signal.removeEventListener('abort', onAbort); reject(error); }, ); + }); +} - if (config.setEndTime) { - session.status = 'error'; - session.endTime = new Date(); +async function startServer(ctx: StepContext): Promise { + const { session, context, registry, config, control, log, step } = ctx; + log(`Starting server with SSE...`); + registry.updateSessionStatus(session.id, 'analyzing', config.progress.watcherOrServer); + + const orchestrator = new ServerLaunchOrchestrator(context); + const launch = orchestrator.launchServerForSession( + { sessionId: session.id, targetPath: session.targetPath, serverType: 'http' }, + session, + ); + // A server that comes up after the launch was aborted (Close or the + // deadline hit while it was starting) is stopped as soon as it resolves: + // `step()` below has already rejected, so nothing else would own it. + void launch.then((result) => { + if (result.success && result.sessionServerInfo && control.signal(session.id)?.aborted !== false) { + void stopSessionServer(result.sessionServerInfo.serverId); } + }); + const result = await step(launch); - void vscode.window.showErrorMessage( - `Failed to start analysis: ${error instanceof Error ? error.message : String(error)}`, - ); - - if (config.rethrowErrors) { - throw error; - } + if (!result.success || !result.sessionServerInfo) { + throw new Error(result.error || 'The analysis server could not be started.'); } + const info = result.sessionServerInfo; + control.push(session.id, 'server', () => stopSessionServer(info.serverId)); + + log(`Server started successfully on port ${info.port}`); + registry.registerSessionPort(session.id, info.port); + session.assignedPort = info.port; + session.serverUrl = info.serverUrl; + session.serverId = info.serverId; } -// ── Internal helpers ───────────────────────────────────────────── - -async function startWatcher( - session: UnifiedAnalysisSession, - registry: UnifiedSessionRegistry, - config: LaunchPipelineConfig, - log: (msg: string) => void, - savedPath: string, -): Promise { - const stepProgress = config.startServerBeforeWatcher - ? config.progress.serverOrWatcher - : config.progress.watcherOrServer; - +async function startWatcher(ctx: StepContext, savedPath: string): Promise { + const { session, context, registry, config, control, log, step } = ctx; log(`Starting watcher...`); - registry.updateSessionStatus(session.id, 'analyzing', stepProgress); + registry.updateSessionStatus(session.id, 'analyzing', config.progress.serverOrWatcher); - const watcherId = await config.startWatcher(savedPath); + const watcherId = await step(config.startWatcher(savedPath)); if (watcherId) { log(`Watcher started successfully with ID: ${watcherId}`); session.watcherId = watcherId; + control.push(session.id, 'watcher', () => new SessionWatcherManager(context).stopWatchingSession(session.id)); } else { log(`Watcher could not be started`); } } -async function startServer( - session: UnifiedAnalysisSession, - context: vscode.ExtensionContext, - registry: UnifiedSessionRegistry, - config: LaunchPipelineConfig, - log: (msg: string) => void, - logError: (msg: string) => void, - _savedPath: string, -): Promise { - const stepProgress = config.startServerBeforeWatcher - ? config.progress.watcherOrServer - : config.progress.serverOrWatcher; - - log(`Starting server with SSE...`); - registry.updateSessionStatus(session.id, 'analyzing', stepProgress); - - const sessionServerManager = new SessionServerManager(context); - const serverStatus = await sessionServerManager.startServerForSession(session); - - if (serverStatus.isServerActive) { - log(`Server started successfully on port ${serverStatus.port}`); - log(`Server URL: ${serverStatus.serverUrl}`); - - if (serverStatus.port) { - const portRegistered = registry.registerSessionPort(session.id, serverStatus.port); - log(`Port ${serverStatus.port} registration result: ${portRegistered}`); - } - - session.assignedPort = serverStatus.port; - session.serverUrl = serverStatus.serverUrl; - - registry.updateSessionStatus(session.id, 'monitoring', config.progress.done); - - // Optional success callback - config.onSuccess?.(serverStatus.port, serverStatus.serverUrl); - } else { - logError(`Server could not be started for session ${session.id}`); - - if (config.startServerBeforeWatcher) { - // VisualizeDOM pattern: throw to abort remaining steps - throw new Error(`Failed to start server for analysis`); - } else { - registry.updateSessionStatus(session.id, 'error', undefined, 'Server could not be started'); - } +/** Stops a session's server if it is still registered; silent and idempotent. */ +async function stopSessionServer(serverId: string | undefined): Promise { + if (!serverId || !getActiveServerRegistry().getServer(serverId)) { + return; } + await ServerControl.stopServer(serverId, { silent: true }); } diff --git a/apps/vscode-extension/src/core/analysis/launchers/launcherLivePanel.ts b/apps/vscode-extension/src/core/analysis/launchers/launcherLivePanel.ts index 71feaf9c2..412720536 100644 --- a/apps/vscode-extension/src/core/analysis/launchers/launcherLivePanel.ts +++ b/apps/vscode-extension/src/core/analysis/launchers/launcherLivePanel.ts @@ -13,6 +13,7 @@ import { FileRequirementProcessor, ProcessedRequirements } from '../processors/F import { SessionWatcherManager } from '../watchers/sessionWatcherManager'; import { AnalysisConfigurationStorage } from '../configuration/analysisConfigurationStorage'; import { executeLaunchPipeline } from './launchPipeline'; +import { ANALYSIS_STORAGE_FOLDERS } from '../launch/storageFolders'; import { getLogger } from '../../../platform/logging/sink'; const logger = getLogger('LAUNCHER_LIVE_PANEL'); @@ -54,7 +55,7 @@ export class LauncherLivePanel { await executeLaunchPipeline(session, context, { logPrefix: LOG_PREFIX, - folderName: 'fileAnalysis', + folderName: ANALYSIS_STORAGE_FOLDERS.file, progress: { process: 20, save: 40, watcherOrServer: 60, serverOrWatcher: 80, done: 100 }, preValidation: async () => { @@ -82,7 +83,7 @@ export class LauncherLivePanel { await executeLaunchPipeline(session, context, { logPrefix: LOG_PREFIX, - folderName: 'directoryAnalysis', + folderName: ANALYSIS_STORAGE_FOLDERS.directory, progress: { process: 20, save: 40, watcherOrServer: 60, serverOrWatcher: 80, done: 100 }, preValidation: async () => { diff --git a/apps/vscode-extension/src/core/analysis/launchers/launcherVisualizeDOM.ts b/apps/vscode-extension/src/core/analysis/launchers/launcherVisualizeDOM.ts index 4fa1c923b..528929430 100644 --- a/apps/vscode-extension/src/core/analysis/launchers/launcherVisualizeDOM.ts +++ b/apps/vscode-extension/src/core/analysis/launchers/launcherVisualizeDOM.ts @@ -8,6 +8,7 @@ import { UnifiedAnalysisSession } from '../session/analysisSession'; import { FileRequirementProcessor } from '../processors/FileRequirementProcessor'; import { SessionWatcherManager } from '../watchers/sessionWatcherManager'; import { executeLaunchPipeline } from './launchPipeline'; +import { ANALYSIS_STORAGE_FOLDERS } from '../launch/storageFolders'; import { getLogger } from '../../../platform/logging/sink'; const logger = getLogger('LAUNCHER_VISUALIZE_DOM'); @@ -24,9 +25,8 @@ export class LauncherVisualizeDOM { await executeLaunchPipeline(session, context, { logPrefix: LOG_PREFIX, - folderName: 'visualizeDOMAnalysis', + folderName: ANALYSIS_STORAGE_FOLDERS.visualizeDOM, progress: { process: 20, save: 40, watcherOrServer: 60, serverOrWatcher: 80, done: 100 }, - startServerBeforeWatcher: true, setEndTime: true, rethrowErrors: true, diff --git a/apps/vscode-extension/src/core/analysis/launchers/launcherXRAnalysis.ts b/apps/vscode-extension/src/core/analysis/launchers/launcherXRAnalysis.ts index 5abf2230f..1cea8e8f6 100644 --- a/apps/vscode-extension/src/core/analysis/launchers/launcherXRAnalysis.ts +++ b/apps/vscode-extension/src/core/analysis/launchers/launcherXRAnalysis.ts @@ -17,6 +17,7 @@ import { DimensionValidator } from '../../charts/processing/dimensionValidator'; import { BabiaChartRegistry } from '../../charts/chartRegistry'; import { DimensionMapping } from '../../charts/chartModels'; import { executeLaunchPipeline } from './launchPipeline'; +import { ANALYSIS_STORAGE_FOLDERS } from '../launch/storageFolders'; import { XRFieldSchemaService } from '../python/xrFieldSchemaService'; import { getLogger } from '../../../platform/logging/sink'; @@ -154,7 +155,7 @@ export class LauncherXRAnalysis { await executeLaunchPipeline(session, context, { logPrefix: LOG_PREFIX, - folderName: 'fileAnalysis', + folderName: ANALYSIS_STORAGE_FOLDERS.file, progress: { process: 30, save: 50, watcherOrServer: 70, serverOrWatcher: 90, done: 100 }, preValidation: async () => { @@ -180,7 +181,7 @@ export class LauncherXRAnalysis { await executeLaunchPipeline(session, context, { logPrefix: LOG_PREFIX, - folderName: 'directoryAnalysis', + folderName: ANALYSIS_STORAGE_FOLDERS.directory, progress: { process: 30, save: 50, watcherOrServer: 80, serverOrWatcher: 90, done: 100 }, preValidation: async () => { diff --git a/apps/vscode-extension/src/core/analysis/python/executePython.ts b/apps/vscode-extension/src/core/analysis/python/executePython.ts index d1b5bac18..e92d6f7bd 100644 --- a/apps/vscode-extension/src/core/analysis/python/executePython.ts +++ b/apps/vscode-extension/src/core/analysis/python/executePython.ts @@ -6,6 +6,7 @@ import { UnifiedAnalysisSession } from '../session/analysisSession'; import { VenvManager } from '../../python-env/venvManager'; import { getBackendScriptCandidates, resolveBackendScriptPath } from './backendScriptPath'; import { classifyStderrLine } from './pythonStderrStream'; +import { currentLaunchSignal } from '../launch/launchControl'; import { getLogger } from '../../../platform/logging/sink'; const logger = getLogger('EXECUTE_PYTHON'); @@ -447,12 +448,33 @@ export class ExecutePython { return new Promise((resolve) => { const childProcess = cp.spawn(executable, fullArgs, { cwd, - env: process.env, + // UTF-8 on every platform: a piped stdout on Windows otherwise + // uses the ANSI code page, and the DOM backend crashed writing + // `→` or any non-Latin text (LAUNCHER-15). + env: { ...process.env, PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' }, stdio: ['pipe', 'pipe', 'pipe'], }); logger.debug(() => `Process spawned with PID: ${childProcess.pid}`); + // A launch that is closed or times out kills its analysis instead + // of leaving Python running for a page nobody will open (LAUNCHER-10). + const launchSignal = currentLaunchSignal(); + const killOnAbort = () => { + logger.debug(() => `Launch aborted: killing Python process ${childProcess.pid}`); + childProcess.kill(); + }; + if (launchSignal?.aborted) { + killOnAbort(); + } else { + launchSignal?.addEventListener('abort', killOnAbort, { once: true }); + childProcess.on('close', () => launchSignal?.removeEventListener('abort', killOnAbort)); + } + // Decode as a stream, so a multi-byte character split across two + // chunks is not turned into U+FFFD. + childProcess.stdout.setEncoding('utf8'); + childProcess.stderr.setEncoding('utf8'); + childProcess.on('error', (error: NodeJS.ErrnoException) => { logger.error('Failed to start Python process:', error); logger.error('Error details:', { @@ -468,12 +490,12 @@ export class ExecutePython { let stderr = ''; childProcess.stdout.on('data', (data) => { - stdout += data.toString(); - logger.debug(() => `stdout chunk received (${data.toString().length} chars)`); + stdout += String(data); + logger.debug(() => `stdout chunk received (${String(data).length} chars)`); }); childProcess.stderr.on('data', (data) => { - const stderrChunk = data.toString(); + const stderrChunk = String(data); stderr += stderrChunk; for (const line of stderrChunk.split('\n')) { diff --git a/apps/vscode-extension/src/core/analysis/refresh/analysisViewModes.ts b/apps/vscode-extension/src/core/analysis/refresh/analysisViewModes.ts index 92cfa54ee..ab16d6acc 100644 --- a/apps/vscode-extension/src/core/analysis/refresh/analysisViewModes.ts +++ b/apps/vscode-extension/src/core/analysis/refresh/analysisViewModes.ts @@ -3,21 +3,25 @@ * * One table for the extension host: the refresh coordinator (live sessions), * the export manifest (offline replay) and the collaboration message router - * all read it. The browser keeps its own copy (`MODE_CONTROLLER_VIEW_BY_ID` in - * the analysis-mode runtime); `test/analysis/controllerViewMapSync.test.cjs` + * all read it. It is derived from the analysis-type descriptors + * (`core/analysis/launch/analysisTypes.ts`) plus the selection menu. The + * browser keeps its own copy (`MODE_CONTROLLER_VIEW_BY_ID` in the + * analysis-mode runtime); `test/analysis/controllerViewMapSync.test.cjs` * keeps the two in step. * - * Deliberately pure, with zero imports: `exportManifest.ts` must stay - * require()-able from `out/` without a vscode stub, and importing the - * coordinator module would instantiate its singleton at load time. + * Deliberately pure (its only import is the pure descriptor list): + * `exportManifest.ts` must stay require()-able from `out/` without a vscode + * stub, and importing the coordinator module would instantiate its singleton + * at load time. */ -export const ANALYSIS_CONTROLLER_VIEW_BY_MODE: Readonly> = Object.freeze({ - selection: 'visualization-menu', - single: 'single.mapping', - 'dependency-graph': 'dependency.settings', - 'historical-compare': 'historical.selection', - 'project-evolution': 'project-evolution', -}); +import { ANALYSIS_TYPES, SELECTION_MODE } from '../launch/analysisTypes'; + +export const ANALYSIS_CONTROLLER_VIEW_BY_MODE: Readonly> = Object.freeze( + Object.fromEntries([ + [SELECTION_MODE.id, SELECTION_MODE.controllerView], + ...ANALYSIS_TYPES.map((type) => [type.id, type.controllerView]), + ]), +); /** The view an unknown mode falls back to: the single-analysis mapping panel. */ export const FALLBACK_CONTROLLER_VIEW = 'single.mapping'; diff --git a/apps/vscode-extension/src/core/analysis/session-servers/serverLaunchOrchestrator.ts b/apps/vscode-extension/src/core/analysis/session-servers/serverLaunchOrchestrator.ts index 197090e87..ae548ba1a 100644 --- a/apps/vscode-extension/src/core/analysis/session-servers/serverLaunchOrchestrator.ts +++ b/apps/vscode-extension/src/core/analysis/session-servers/serverLaunchOrchestrator.ts @@ -40,7 +40,7 @@ export class ServerLaunchOrchestrator { const serverSettings = this.serverSettingsManager.getServerSettings(); const serverType = this.getDefaultServerType(serverSettings); - const tempDir = session?.savedFilesPath || this.getTempDirForSession(request.sessionId); + const tempDir = session?.savedFilesPath; if (!tempDir || !fs.existsSync(tempDir)) { return { @@ -80,7 +80,11 @@ export class ServerLaunchOrchestrator { startedAt: new Date(), }; - fileToServerMap.registerMapping(request.targetPath, { + // Keyed by SESSION, not target path: a second session on the + // same target (another mode, or XR-deep) used to overwrite the + // first one's entry, so the first page's /events returned 404 + // and refreshes were cross-wired between the two (LAUNCHER-3). + fileToServerMap.registerMapping(request.sessionId, { port: launchResult.port, tempDir, fileUri: request.targetPath, @@ -109,27 +113,10 @@ export class ServerLaunchOrchestrator { } } - async stopServerForSession(sessionId: string, targetPath: string): Promise { - try { - fileToServerMap.unregisterMapping(targetPath); - logger.debug(() => `Stopped server for session ${sessionId}`); - return true; - } catch (error) { - logger.error('Error stopping server:', error); - return false; - } - } - private getDefaultServerType(_serverSettings: any): 'http' | 'https-default' | 'https-custom' { return 'http'; } - private getTempDirForSession(sessionId: string): string { - const workspaceStorage = this.context.storageUri?.fsPath || ''; - const analysisDir = path.join(workspaceStorage, 'analysis', sessionId); - return analysisDir; - } - private findMainHtmlFile(baseDir: string, preferredFileName?: string): string | undefined { if (preferredFileName) { const preferredPath = path.join(baseDir, preferredFileName); diff --git a/apps/vscode-extension/src/core/analysis/session-servers/sessionServerManager.ts b/apps/vscode-extension/src/core/analysis/session-servers/sessionServerManager.ts deleted file mode 100644 index 96a8eced9..000000000 --- a/apps/vscode-extension/src/core/analysis/session-servers/sessionServerManager.ts +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Session Server Manager - * Maneja servidores por sesión siguiendo el patrón muñecas rusas - */ - -import * as vscode from 'vscode'; -import { ServerLaunchOrchestrator } from './serverLaunchOrchestrator'; -import { SSENotificationManager } from './sseNotificationManager'; -import { UnifiedAnalysisSession } from '../session/analysisSession'; -import { - SessionServerInfo, - ServerLaunchRequest, - SessionServerStatus -} from './sessionServerModels'; -import { getLogger } from '../../../platform/logging/sink'; - -const logger = getLogger('SESSION_SERVER_MANAGER'); - -export class SessionServerManager { - private serverOrchestrator: ServerLaunchOrchestrator; - private sseManager: SSENotificationManager; - private activeSessions: Map = new Map(); - - constructor(context: vscode.ExtensionContext) { - logger.debug('Initializing manager'); - this.serverOrchestrator = new ServerLaunchOrchestrator(context); - this.sseManager = new SSENotificationManager(); - } - - /** - * Inicia un servidor para una sesión de análisis - */ - async startServerForSession(session: UnifiedAnalysisSession): Promise { - try { - logger.debug(() => `Starting server for session ${session.id}`); - - // Verificar si ya hay un servidor activo para esta sesión - if (this.activeSessions.has(session.id)) { - const existing = this.activeSessions.get(session.id)!; - if (existing.isActive) { - logger.debug(() => `Server already active for session ${session.id}`); - return this.getSessionStatus(session.id); - } - } - - // Crear request de lanzamiento - const launchRequest: ServerLaunchRequest = { - sessionId: session.id, - targetPath: session.targetPath, - serverType: 'http' // Por defecto HTTP para LivePanels - }; - - // Lanzar servidor pasando la sesión completa para obtener savedFilesPath - const launchResult = await this.serverOrchestrator.launchServerForSession(launchRequest, session); - - if (launchResult.success && launchResult.sessionServerInfo) { - // Registrar sesión activa - this.activeSessions.set(session.id, launchResult.sessionServerInfo); - - // Actualizar la sesión con el puerto asignado - session.assignedPort = launchResult.sessionServerInfo.port; - session.serverUrl = launchResult.sessionServerInfo.serverUrl; - - logger.debug(() => `Server started for session ${session.id} on port ${session.assignedPort}`); - - // Enviar notificación SSE - await this.sseManager.notifyServerStarted(launchResult.sessionServerInfo); - - return { - sessionId: session.id, - isServerActive: true, - isWatcherActive: true, // Asumimos que el watcher ya está activo - port: launchResult.sessionServerInfo.port, - serverUrl: launchResult.sessionServerInfo.serverUrl, - lastUpdate: new Date() - }; - } else { - logger.error(`Failed to start server:`, launchResult.error); - throw new Error(launchResult.error || 'Unknown server launch error'); - } - - } catch (error) { - logger.error(`Error starting server for session ${session.id}:`, error); - return { - sessionId: session.id, - isServerActive: false, - isWatcherActive: false - }; - } - } - - /** - * Detiene un servidor para una sesión específica - */ - async stopServerForSession(sessionId: string): Promise { - try { - logger.debug(() => `Stopping server for session ${sessionId}`); - - const sessionInfo = this.activeSessions.get(sessionId); - if (!sessionInfo) { - logger.debug(() => `No active server found for session ${sessionId}`); - return true; // Ya estaba detenido - } - - // Detener servidor usando orchestrator - const success = await this.serverOrchestrator.stopServerForSession( - sessionId, - sessionInfo.targetPath - ); - - if (success) { - // Remover de sesiones activas - this.activeSessions.delete(sessionId); - - // Enviar notificación SSE - await this.sseManager.notifyServerStopped(sessionInfo); - - logger.debug(() => `Server stopped for session ${sessionId}`); - } - - return success; - - } catch (error) { - logger.error(`Error stopping server for session ${sessionId}:`, error); - return false; - } - } - - /** - * Notifica que el análisis se ha actualizado (para SSE) - */ - async notifyAnalysisUpdated(sessionId: string): Promise { - const sessionInfo = this.activeSessions.get(sessionId); - if (sessionInfo) { - await this.sseManager.notifyAnalysisUpdated(sessionInfo); - } - } - - /** - * Obtiene el estado de una sesión - */ - getSessionStatus(sessionId: string): SessionServerStatus { - const sessionInfo = this.activeSessions.get(sessionId); - - if (sessionInfo) { - return { - sessionId, - isServerActive: sessionInfo.isActive, - isWatcherActive: true, // TODO: conectar con SessionWatcherManager - port: sessionInfo.port, - serverUrl: sessionInfo.serverUrl, - lastUpdate: new Date() - }; - } - - return { - sessionId, - isServerActive: false, - isWatcherActive: false - }; - } - - /** - * Obtiene todas las sesiones activas - */ - getAllActiveSessions(): SessionServerInfo[] { - return Array.from(this.activeSessions.values()); - } - - /** - * Obtiene información del servidor por puerto - */ - getSessionByPort(port: number): SessionServerInfo | null { - for (const sessionInfo of this.activeSessions.values()) { - if (sessionInfo.port === port) { - return sessionInfo; - } - } - return null; - } - - /** - * Limpia todas las sesiones activas - */ - async cleanup(): Promise { - logger.debug(() => `Cleaning up ${this.activeSessions.size} active sessions`); - - const cleanupPromises = Array.from(this.activeSessions.keys()).map(sessionId => - this.stopServerForSession(sessionId) - ); - - await Promise.all(cleanupPromises); - this.activeSessions.clear(); - - logger.debug(`Cleanup completed`); - } -} - -export default SessionServerManager; diff --git a/apps/vscode-extension/src/core/analysis/session-servers/sessionServerModels.ts b/apps/vscode-extension/src/core/analysis/session-servers/sessionServerModels.ts index ca0a010ce..82cb71549 100644 --- a/apps/vscode-extension/src/core/analysis/session-servers/sessionServerModels.ts +++ b/apps/vscode-extension/src/core/analysis/session-servers/sessionServerModels.ts @@ -1,6 +1,6 @@ /** * Session Server Models - * Interfaces para la gestión de servidores por sesión + * Types of the server a launch starts for its session */ export interface SessionServerInfo { @@ -29,19 +29,3 @@ export interface ServerLaunchResult { portChanged?: boolean; originalPort?: number; } - -export interface SSENotification { - type: 'file-changed' | 'analysis-updated' | 'server-started' | 'server-stopped'; - sessionId: string; - timestamp: Date; - data?: any; -} - -export interface SessionServerStatus { - sessionId: string; - isServerActive: boolean; - isWatcherActive: boolean; - port?: number; - serverUrl?: string; - lastUpdate?: Date; -} diff --git a/apps/vscode-extension/src/core/analysis/session-servers/sseNotificationManager.ts b/apps/vscode-extension/src/core/analysis/session-servers/sseNotificationManager.ts deleted file mode 100644 index 49108e3e1..000000000 --- a/apps/vscode-extension/src/core/analysis/session-servers/sseNotificationManager.ts +++ /dev/null @@ -1,159 +0,0 @@ -/** - * SSE Notification Manager - * Maneja las notificaciones SSE para sesiones de análisis - */ - -import { SessionServerInfo, SSENotification } from './sessionServerModels'; -import { SSEManager } from '../../server/sse/SSEManager'; -import { getLogger } from '../../../platform/logging/sink'; - -const logger = getLogger('SSE_NOTIFICATION_MANAGER'); - -export class SSENotificationManager { - - constructor() { - logger.debug('Initializing SSE manager'); - } /** - * Notifica que un servidor ha sido iniciado - */ - async notifyServerStarted(sessionInfo: SessionServerInfo): Promise { - try { - logger.debug(() => `Notifying server started for session ${sessionInfo.sessionId}`); - - const notification: SSENotification = { - type: 'server-started', - sessionId: sessionInfo.sessionId, - timestamp: new Date(), - data: { - port: sessionInfo.port, - serverUrl: sessionInfo.serverUrl, - targetPath: sessionInfo.targetPath - } - }; - - await this.sendSSENotification(notification); - - } catch (error) { - logger.error(`Error notifying server started:`, error); - } - } - - /** - * Notifica que un servidor ha sido detenido - */ - async notifyServerStopped(sessionInfo: SessionServerInfo): Promise { - try { - logger.debug(() => `Notifying server stopped for session ${sessionInfo.sessionId}`); - - const notification: SSENotification = { - type: 'server-stopped', - sessionId: sessionInfo.sessionId, - timestamp: new Date(), - data: { - port: sessionInfo.port, - targetPath: sessionInfo.targetPath - } - }; - - await this.sendSSENotification(notification); - - } catch (error) { - logger.error(`Error notifying server stopped:`, error); - } - } - - /** - * Notifica que el análisis ha sido actualizado - */ - async notifyAnalysisUpdated(sessionInfo: SessionServerInfo): Promise { - try { - logger.debug(() => `Notifying analysis updated for session ${sessionInfo.sessionId}`); - - const notification: SSENotification = { - type: 'analysis-updated', - sessionId: sessionInfo.sessionId, - timestamp: new Date(), - data: { - port: sessionInfo.port, - serverUrl: sessionInfo.serverUrl, - targetPath: sessionInfo.targetPath - } - }; - - await this.sendSSENotification(notification); - - } catch (error) { - logger.error(`Error notifying analysis updated:`, error); - } - } - - /** - * Notifica que un archivo ha cambiado - */ - async notifyFileChanged(sessionInfo: SessionServerInfo, changedFile: string): Promise { - try { - logger.debug(() => `Notifying file changed for session ${sessionInfo.sessionId}`); - - const notification: SSENotification = { - type: 'file-changed', - sessionId: sessionInfo.sessionId, - timestamp: new Date(), - data: { - port: sessionInfo.port, - targetPath: sessionInfo.targetPath, - changedFile - } - }; - - await this.sendSSENotification(notification); - - } catch (error) { - logger.error(`Error notifying file changed:`, error); - } - } - - /** - * Envía una notificación SSE a todos los clientes conectados - */ - private async sendSSENotification(notification: SSENotification): Promise { - try { - logger.debug(`Sending SSE notification:`, { - type: notification.type, - sessionId: notification.sessionId, - timestamp: notification.timestamp - }); - - // Obtener el SSEManager real - const sseManager = SSEManager.getInstance(); - - // Para sesiones de análisis, usar el targetPath como identificador SSE - const targetPath = notification.data?.targetPath; - - if (targetPath) { - logger.debug(() => `Sending to clients of: ${targetPath}`); - - // Crear el mensaje SSE en el formato esperado por el cliente - const sseMessage = { - type: notification.type, - fileUri: targetPath, - sessionId: notification.sessionId, - timestamp: notification.timestamp, - data: notification.data - }; - - // Enviar usando el SSEManager real - sseManager.sendCustomMessage(targetPath, sseMessage); - - logger.debug(() => `SSE notification sent successfully to ${targetPath}`); - } else { - logger.warn(`No targetPath found in notification data`); - } - - } catch (error) { - logger.error(`Error sending SSE notification:`, error); - throw error; - } - } -} - -export default SSENotificationManager; diff --git a/apps/vscode-extension/src/core/analysis/session/sessionRegistry.ts b/apps/vscode-extension/src/core/analysis/session/sessionRegistry.ts index 1700e1f7d..44176efaa 100644 --- a/apps/vscode-extension/src/core/analysis/session/sessionRegistry.ts +++ b/apps/vscode-extension/src/core/analysis/session/sessionRegistry.ts @@ -16,6 +16,7 @@ import { } from './analysisSession'; import { SHA256Generator } from '../utils/sha256Generator'; import { getLogger } from '../../../platform/logging/sink'; +import { targetKey } from '../launch/targetKey'; const logger = getLogger('UNIFIED_REGISTRY'); @@ -57,9 +58,12 @@ export class UnifiedSessionRegistry { private hasDuplicateSession(params: SessionCreationParams): UnifiedAnalysisSession | null { const existingSessions = this.getAllSessions(); + // Compared by normalised key, not raw string: `C:\p\a.ts` and + // `c:\p\a.ts` are one target (LAUNCHER-17). + const wantedKey = targetKey(params.targetPath); for (const session of existingSessions) { const isDuplicate = - session.targetPath === params.targetPath && + targetKey(session.targetPath) === wantedKey && session.analysisMode === params.analysisMode && session.targetType === params.targetType && session.isDeep === (params.isDeep || false) && @@ -96,8 +100,12 @@ export class UnifiedSessionRegistry { const id = generateNonce(); const targetName = path.basename(params.targetPath); const { outputDirectory, outputPath } = this.buildSessionPaths(params, id, targetName); - const calculatedHash = params.targetType === 'file' ? await this.hashTargetFile(params.targetPath) : ''; + // Reserve BEFORE the first await (LAUNCHER-4): the duplicate check + // above and this insertion run in the same tick, so a double click + // finds the first session already registered as `creating`. The + // hash and the directory check below used to run in between, which + // let two launches of one target through. const session: UnifiedAnalysisSession = { id, targetPath: params.targetPath, @@ -107,7 +115,7 @@ export class UnifiedSessionRegistry { isDeep: params.isDeep || false, status: 'creating', startTime: new Date(), - hash256: calculatedHash, + hash256: '', outputDirectory, outputPath, requiredFiles: new Map(), @@ -115,17 +123,27 @@ export class UnifiedSessionRegistry { metadata: {} }; - if (params.targetType === 'directory') { - await this.assertDirectoryTarget(params.targetPath); + this.sessions.set(id, session); - // Directory scanning and initial hashes are populated after Python - // completes the first analysis, keeping the startup path lightweight. - session.directoriesToAnalyze = []; - session.filesToHash = []; - logger.debug('Directory session will populate tracked files after initial analysis'); + try { + if (params.targetType === 'file') { + session.hash256 = await this.hashTargetFile(params.targetPath); + } else { + await this.assertDirectoryTarget(params.targetPath); + + // Directory scanning and initial hashes are populated after Python + // completes the first analysis, keeping the startup path lightweight. + session.directoriesToAnalyze = []; + session.filesToHash = []; + logger.debug('Directory session will populate tracked files after initial analysis'); + } + } catch (validationError) { + // Release the reservation: a target that cannot be read must + // not block the next attempt as "already in progress". + this.sessions.delete(id); + throw validationError; } - this.sessions.set(id, session); this._onSessionChanged.fire(session); logger.debug(() => `Created session ${id} for ${targetName}`); @@ -305,7 +323,8 @@ export class UnifiedSessionRegistry { * Get sessions by target path - SIMPLE */ getSessionsByTargetPath(targetPath: string): UnifiedAnalysisSession[] { - return this.getAllSessions().filter(s => s.targetPath === targetPath); + const wantedKey = targetKey(targetPath); + return this.getAllSessions().filter(s => targetKey(s.targetPath) === wantedKey); } /** diff --git a/apps/vscode-extension/src/core/analysis/watchers/directoryReAnalyzer.ts b/apps/vscode-extension/src/core/analysis/watchers/directoryReAnalyzer.ts index fb60256c5..feeda70be 100644 --- a/apps/vscode-extension/src/core/analysis/watchers/directoryReAnalyzer.ts +++ b/apps/vscode-extension/src/core/analysis/watchers/directoryReAnalyzer.ts @@ -8,7 +8,6 @@ import * as fs from 'fs'; import * as path from 'path'; import { UnifiedAnalysisSession } from '../session/analysisSession'; import { ExecutePython } from '../python/executePython'; -import { SessionServerManager } from '../session-servers/sessionServerManager'; import { SHA256Generator } from '../utils/sha256Generator'; import { FileHashTracker } from './fileHashTracker'; import { @@ -41,11 +40,9 @@ interface IncrementalChangeSet { export class DirectoryReAnalyzer { private executePython: ExecutePython; - private sessionServerManager: SessionServerManager; constructor(context: vscode.ExtensionContext) { this.executePython = new ExecutePython(context); - this.sessionServerManager = new SessionServerManager(context); } async reAnalyzeFiles(changedFiles: string[]): Promise { @@ -263,22 +260,20 @@ export class DirectoryReAnalyzer { } async sendSSENotification(session: UnifiedAnalysisSession): Promise { + // SSE channels are keyed by session id, so two sessions on one target + // (two modes, or XR and XR-deep) each refresh only their own page + // (LAUNCHER-3). try { const { SSEManager } = require('../../server/sse/SSEManager'); const sseManager = SSEManager.getInstance(); if (session.analysisMode === 'XR') { - sseManager.sendDataRefresh(session.targetPath); + sseManager.sendDataRefresh(session.id); } else { - sseManager.sendUpdate(session.targetPath); + sseManager.sendUpdate(session.id); } } catch (sseError) { - logger.error('SSE direct failed, trying fallback...'); - try { - await this.sessionServerManager.notifyAnalysisUpdated(session.id); - } catch (fallbackError) { - logger.error('SSE fallback also failed:', fallbackError); - } + logger.error('SSE notification failed:', sseError); } } } diff --git a/apps/vscode-extension/src/core/analysis/watchers/reAnalysisManager.ts b/apps/vscode-extension/src/core/analysis/watchers/reAnalysisManager.ts index d6580a152..2bee9b731 100644 --- a/apps/vscode-extension/src/core/analysis/watchers/reAnalysisManager.ts +++ b/apps/vscode-extension/src/core/analysis/watchers/reAnalysisManager.ts @@ -52,9 +52,9 @@ export class ReAnalysisManager { if (options.notifyClients !== false) { if (session.analysisMode === 'XR') { - this.sseManager.sendDataRefresh(session.targetPath); + this.sseManager.sendDataRefresh(session.id); } else { - this.sseManager.sendUpdate(session.targetPath); + this.sseManager.sendUpdate(session.id); } } @@ -94,7 +94,7 @@ export class ReAnalysisManager { } const htmlContent = this.extractVisualizeDOMHtmlContent(session, processedFiles.loadedFiles); - this.sseManager.sendCustomMessage(session.targetPath, { + this.sseManager.sendCustomMessage(session.id, { type: 'htmlUpdated', htmlContent, action: 'reload-html', diff --git a/apps/vscode-extension/src/core/server/analysis/analysisFeatureHost.ts b/apps/vscode-extension/src/core/server/analysis/analysisFeatureHost.ts index 3813ffc2b..cfae928fb 100644 --- a/apps/vscode-extension/src/core/server/analysis/analysisFeatureHost.ts +++ b/apps/vscode-extension/src/core/server/analysis/analysisFeatureHost.ts @@ -335,14 +335,15 @@ export class AnalysisFeatureHost { /** * LivePanel pages have no collaboration room; feature updates reach them - * over SSE, keyed by the analysis file this server serves. Returns null - * for every other mode so the notify helpers are safe to call anywhere. + * over SSE, on the channel of the session this server serves (channels + * are keyed by session id). Returns null for every other mode so the + * notify helpers are safe to call anywhere. */ private getLivePanelSseTarget(): string | null { if (this.analysisMode !== 'LivePanel') { return null; } - return fileToServerMap.findFileByPort(this.config.port); + return this.config.analysisSessionId || fileToServerMap.findFileByPort(this.config.port); } public notifyLivePanelDependencyUpdated(revision: number): void { diff --git a/apps/vscode-extension/src/core/server/analysis/analysisMessageRouter.ts b/apps/vscode-extension/src/core/server/analysis/analysisMessageRouter.ts index fafc8c4ac..c3e61eb4e 100644 --- a/apps/vscode-extension/src/core/server/analysis/analysisMessageRouter.ts +++ b/apps/vscode-extension/src/core/server/analysis/analysisMessageRouter.ts @@ -2,7 +2,6 @@ import { CollaborationApplicationMessageContext, CollaborationMessage, CollaborationRoomServer, - SharedEntityState, } from '../collaboration/collaborationRoomServer'; import { AnalysisViewMode, analysisRefreshCoordinator } from '../../analysis/refresh/analysisRefreshCoordinator'; import { defaultControllerView } from '../../analysis/refresh/analysisViewModes'; @@ -10,6 +9,7 @@ import { AnalysisFeatureHost } from './analysisFeatureHost'; import { DependencyGraphBridge } from './dependencyGraphBridge'; import { HistoricalComparisonBridge } from './historicalComparisonBridge'; import { ProjectEvolutionBridge } from './projectEvolutionBridge'; +import { ANALYSIS_TYPES, AnalysisSnapshotProbe } from '../../analysis/launch/analysisTypes'; import { getLogger } from '../../../platform/logging/sink'; const logger = getLogger('ANALYSIS_MESSAGE_ROUTER'); @@ -24,19 +24,14 @@ type SnapshotMode = Exclude; /** * The cached room entity each snapshot-backed mode probes on activation, and - * what makes it usable: a git result, or the dependency dataset URL. + * what makes it usable: a git result, or the dependency dataset URL. Read + * from the analysis-type descriptors (`snapshotProbe`). */ -const SNAPSHOT_PROBE_BY_MODE: Readonly> = { - 'historical-compare': { entityKind: 'historical-comparison', isAvailable: (snapshot) => !!snapshot?.result }, - 'project-evolution': { entityKind: 'project-evolution', isAvailable: (snapshot) => !!snapshot?.result }, - 'dependency-graph': { - entityKind: 'dependency-graph', - isAvailable: (snapshot) => typeof snapshot?.datasetUrl === 'string', - }, -}; +const SNAPSHOT_PROBE_BY_MODE: Readonly> = Object.freeze( + Object.fromEntries(ANALYSIS_TYPES + .filter((type) => !!type.snapshotProbe) + .map((type) => [type.id, type.snapshotProbe!])), +); /** * Dispatches collaboration room application messages to their feature diff --git a/apps/vscode-extension/src/core/server/analysisServerCapabilities.ts b/apps/vscode-extension/src/core/server/analysisServerCapabilities.ts index 5dd7ad904..e86e8c75f 100644 --- a/apps/vscode-extension/src/core/server/analysisServerCapabilities.ts +++ b/apps/vscode-extension/src/core/server/analysisServerCapabilities.ts @@ -16,10 +16,13 @@ * construction through this table is what lets the shared launch path succeed for * every mode. * - * To add a new analysis mode, add one entry to `CAPABILITIES_BY_MODE` declaring - * exactly which features its server exposes — the shared launch path then works - * for it automatically, with no changes to the launcher or the server core. + * The table is DERIVED from the analysis-type descriptors + * (`core/analysis/launch/analysisTypes.ts`): a surface attaches the feature of + * every analysis type it serves. To add an analysis type, add its descriptor + * there; to serve an existing one on another surface, list the surface in it. */ +import { getServerFeaturesForSurface } from '../analysis/launch/analysisTypes'; + export interface AnalysisServerCapabilities { /** Dependency-graph summary/refresh endpoints (XR + LivePanel). */ dependencyGraph: boolean; @@ -29,41 +32,22 @@ export interface AnalysisServerCapabilities { projectEvolution: boolean; } -const NO_CAPABILITIES: AnalysisServerCapabilities = { - dependencyGraph: false, - historicalComparison: false, - projectEvolution: false, -}; - -const CAPABILITIES_BY_MODE: Readonly> = { - XR: { - dependencyGraph: true, - historicalComparison: true, - projectEvolution: true, - }, - LivePanel: { - dependencyGraph: true, - historicalComparison: true, - projectEvolution: false, - }, - VisualizeDOM: { - dependencyGraph: false, - historicalComparison: false, - projectEvolution: false, - }, -}; - /** * Resolve the feature services the shared server should attach for a mode. * * Unknown or undefined modes get no optional services: the server still launches * (static files + SSE + collaboration) but exposes no analysis feature endpoints, * which is the safe default for a brand-new mode until its capabilities are - * declared above. + * declared in the analysis-type descriptors. */ export function resolveAnalysisServerCapabilities( analysisMode: string | undefined, ): AnalysisServerCapabilities { - // Return a fresh copy so a caller can never mutate the shared table entries. - return { ...(CAPABILITIES_BY_MODE[analysisMode ?? ''] ?? NO_CAPABILITIES) }; + // A fresh object per call, so a caller can never mutate shared state. + const features = getServerFeaturesForSurface(analysisMode); + return { + dependencyGraph: features.has('dependencyGraph'), + historicalComparison: features.has('historicalComparison'), + projectEvolution: features.has('projectEvolution'), + }; } diff --git a/apps/vscode-extension/src/core/server/collaboration/collaborationSessionApi.ts b/apps/vscode-extension/src/core/server/collaboration/collaborationSessionApi.ts index 38f3e8d1f..7ac75ee29 100644 --- a/apps/vscode-extension/src/core/server/collaboration/collaborationSessionApi.ts +++ b/apps/vscode-extension/src/core/server/collaboration/collaborationSessionApi.ts @@ -94,7 +94,8 @@ export class CollaborationSessionApi { return { roomId: `codexr-session:${activeServerId}`, activeServerId, - fileUri: fileUri || null, + // The map is keyed by session id; the analysed path is the entry's fileUri. + fileUri: mapping?.fileUri || null, capabilities: { collaboration: true, presence: true, diff --git a/apps/vscode-extension/src/core/server/serverControl.ts b/apps/vscode-extension/src/core/server/serverControl.ts index 00adb786b..2d8276507 100644 --- a/apps/vscode-extension/src/core/server/serverControl.ts +++ b/apps/vscode-extension/src/core/server/serverControl.ts @@ -238,30 +238,10 @@ export class ServerControl { } } - // If not found, try to find by matching output directory or static root - if (!associatedSession) { - const serverRoot = server.metadata?.staticRoot || server.htmlFile; - logger.debug(() => `DEBUG - Trying to find session by server root: ${serverRoot}`); - - for (const session of allSessions) { - logger.debug(() => `DEBUG - Checking session ${session.id} with outputPath: ${session.outputPath}`); - - if (session.outputPath && serverRoot && ( - session.outputPath === serverRoot || - serverRoot.includes(session.outputPath) || - session.outputPath.includes(serverRoot) - )) { - associatedSession = session; - logger.debug(() => `Found session by output directory match: ${session.id}`); - break; - } - } - - if (!associatedSession) { - logger.debug(`No session found by directory matching`); - } - } - + // Only by session id: matching output paths by substring in both + // directions closed sessions that belonged to other servers + // (LAUNCHER-8). + // If found, close the session if (associatedSession) { logger.debug(() => `DEBUG - Closing associated analysis session ${associatedSession.id}`); diff --git a/apps/vscode-extension/src/core/server/serverFactory.ts b/apps/vscode-extension/src/core/server/serverFactory.ts index 53b1980f5..61b659040 100644 --- a/apps/vscode-extension/src/core/server/serverFactory.ts +++ b/apps/vscode-extension/src/core/server/serverFactory.ts @@ -122,6 +122,12 @@ export async function launchServerByType( htmlFile?: string, additionalMetadata?: Record, ): Promise { + // Hoisted so the catch can release it: the constructor already built the + // analysis feature host (refresh handler, listeners, for LivePanel a + // background dependency scan) and start() may have attached the room + // sockets. A failed start used to leave all of that wired to the session + // (LAUNCHER-6). + let created: ServerInstance | undefined; try { let server: ServerInstance; let serverUrl: string; @@ -196,6 +202,7 @@ export async function launchServerByType( } // Start the server + created = server; logger.debug(() => `Starting ${serverType} server...`); serverUrl = await server.start(); @@ -211,6 +218,7 @@ export async function launchServerByType( } catch (error) { logger.error(`Error launching ${serverType} server:`, error); + releaseFailedServer(created); return { success: false, error: error instanceof Error ? error.message : String(error), @@ -218,3 +226,14 @@ export async function launchServerByType( }; } } + +/** Drops the features and sockets of a server whose start() failed (LAUNCHER-6). */ +function releaseFailedServer(server: ServerInstance | undefined): void { + try { + if (server && typeof server.forceStop === 'function') { + server.forceStop(); + } + } catch (disposeError) { + logger.error('Error releasing a server that failed to start:', disposeError); + } +} diff --git a/apps/vscode-extension/src/features/analysis/commands/cleanAnalysisCommands.ts b/apps/vscode-extension/src/features/analysis/commands/cleanAnalysisCommands.ts index d30711bbf..b179a5196 100644 --- a/apps/vscode-extension/src/features/analysis/commands/cleanAnalysisCommands.ts +++ b/apps/vscode-extension/src/features/analysis/commands/cleanAnalysisCommands.ts @@ -7,6 +7,7 @@ import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; import { CodeXRLogger } from '../../../platform/logging/logger'; +import { getSweptStorageFolders } from '../../../core/analysis/launch/storageFolders'; const logger = CodeXRLogger.getLogger('CLEAN_ANALYSIS'); @@ -24,43 +25,44 @@ export class CleanAnalysisCommands { } /** - * Clean analysis artifacts that were already present before activation completed. + * Clean analysis artifacts that were already present before activation + * completed. Sessions live in memory only, so every folder written before + * this activation belongs to a session that no longer exists. Sweeps the + * folders the launchers actually write (LAUNCHER-14); it used to sweep + * `storage/analysis`, which nothing writes. */ private static async cleanStaleAnalysisArtifacts( context: vscode.ExtensionContext, activationStartedAt: number, ): Promise { - try { - const analysisPath = this.getAnalysisPath(context); - if (!analysisPath || !fs.existsSync(analysisPath)) { - return true; - } - - const entries = fs.readdirSync(analysisPath, { withFileTypes: true }); - for (const entry of entries) { - const entryPath = path.join(analysisPath, entry.name); - const stats = fs.statSync(entryPath); - if (stats.mtimeMs >= activationStartedAt) { + if (!context.storageUri) { + return true; + } + let clean = true; + for (const folderName of getSweptStorageFolders()) { + const analysisPath = path.join(context.storageUri.fsPath, folderName); + try { + if (!fs.existsSync(analysisPath)) { continue; } + const entries = fs.readdirSync(analysisPath, { withFileTypes: true }); + for (const entry of entries) { + const entryPath = path.join(analysisPath, entry.name); + const stats = fs.statSync(entryPath); + if (stats.mtimeMs >= activationStartedAt) { + continue; + } + + await this.deletePathRecursive(entryPath); + } - await this.deletePathRecursive(entryPath); + this.removeDirectoryIfEmpty(analysisPath); + } catch (error) { + logger.warn(`Error cleaning startup analysis artifacts in ${folderName}.`, error); + clean = false; } - - this.removeDirectoryIfEmpty(analysisPath); - return true; - } catch (error) { - logger.warn('Error cleaning startup analysis artifacts.', error); - return false; } - } - - private static getAnalysisPath(context: vscode.ExtensionContext): string | null { - if (!context.storageUri) { - return null; - } - - return path.join(context.storageUri.fsPath, 'analysis'); + return clean; } private static async deletePathRecursive(targetPath: string): Promise { diff --git a/apps/vscode-extension/src/features/analysis/services/serverWatcherIntegration.ts b/apps/vscode-extension/src/features/analysis/services/serverWatcherIntegration.ts index bc65cdde3..458f0fe14 100644 --- a/apps/vscode-extension/src/features/analysis/services/serverWatcherIntegration.ts +++ b/apps/vscode-extension/src/features/analysis/services/serverWatcherIntegration.ts @@ -8,6 +8,7 @@ import { UnifiedSessionRegistry } from '../../../core/analysis/session/sessionRe import { SessionWatcherManager } from '../../../core/analysis/watchers/sessionWatcherManager'; import { getActiveServerRegistry } from '../../../core/server/registry/activeServerRegistry'; import { ServerControl } from '../../../core/server/serverControl'; +import { LaunchControl } from '../../../core/analysis/launch/launchControl'; import * as fs from 'fs'; import { getLogger } from '../../../platform/logging/sink'; import type { ActiveServer, RegistryEvent } from '../../../core/server/registry/activeServerModel'; @@ -53,7 +54,12 @@ export class ServerWatcherIntegration { private async handleServerRemoved(serverId: string, server: ActiveServer): Promise { try { const sessionRegistry = UnifiedSessionRegistry.getInstance(this.context); - const affectedSessions = sessionRegistry.getAllSessions().filter((session: UnifiedAnalysisSession) => session.port === server.port); + // By session id only: ports are reused, and a port match closed + // sessions that belonged to another server (LAUNCHER-8). + const ownerSessionId = server.metadata?.sessionId; + const affectedSessions = ownerSessionId + ? sessionRegistry.getAllSessions().filter((session: UnifiedAnalysisSession) => session.id === ownerSessionId) + : []; logger.debug(() => `Found ${affectedSessions.length} affected sessions for server ${serverId}`); for (const session of affectedSessions) { @@ -68,10 +74,16 @@ export class ServerWatcherIntegration { try { const sessionRegistry = UnifiedSessionRegistry.getInstance(this.context); const session = sessionRegistry.getSession(sessionId); - if (!session) { + // Only a session that was being served: a launch rolling back (or + // one already being closed) undoes its own resources and reports + // once, without a second "cleaned up" message. + if (!session || session.status !== 'monitoring') { return; } + // The server is already gone; this releases the launch record and + // stops its watcher (teardown steps are idempotent). + await LaunchControl.getInstance().close(sessionId); await this.stopFileWatcherForSession(sessionId, session.targetPath); await this.cleanupAnalysisFiles(session.outputPath); sessionRegistry.updateSessionStatus(sessionId, 'closed'); @@ -117,13 +129,13 @@ export class ServerWatcherIntegration { return false; } - const sessionPort = session.assignedPort; - if (sessionPort) { - await this.stopServerByPort(sessionPort); - } else { - await this.findAndStopServerForSession(sessionId, session); - } - + // Aborts a launch still in progress (Python is killed, no server + // or watcher is started afterwards) and undoes what a finished + // launch started (LAUNCHER-7). Mark it closed first so the + // server-removed listener does not announce a second cleanup. + sessionRegistry.updateSessionStatus(sessionId, 'closed'); + await LaunchControl.getInstance().close(sessionId); + await this.stopServerForSession(sessionId); await this.stopFileWatcherForSession(sessionId, session.targetPath); await this.cleanupAnalysisFiles(session.outputPath); return sessionRegistry.updateSessionStatus(sessionId, 'closed'); @@ -133,38 +145,22 @@ export class ServerWatcherIntegration { } } - private async stopServerByPort(port: number): Promise { - try { - const serverRegistry = getActiveServerRegistry(); - const serverToStop = serverRegistry.getAllServers().find((server: ActiveServer) => server.port === port); - if (serverToStop) { - await ServerControl.stopServer(serverToStop.id); - } - } catch (error) { - logger.error(`Error stopping server by port ${port}:`, error); - } - } - - private async findAndStopServerForSession(sessionId: string, session: UnifiedAnalysisSession): Promise { + /** + * Stops the server that was started for this session, matched by the + * session id it was launched with and by nothing else. The old fallbacks + * (any server whose name contained "Analysis", or whose file path + * contained the output path) stopped unrelated servers (LAUNCHER-8). + */ + private async stopServerForSession(sessionId: string): Promise { try { const serverRegistry = getActiveServerRegistry(); - const servers = serverRegistry.getAllServers(); - - let matchingServer = servers.find((server: ActiveServer) => server.metadata && server.metadata.sessionId === sessionId); - - if (!matchingServer && session.outputPath) { - matchingServer = servers.find((server: ActiveServer) => server.htmlFile?.includes(session.outputPath)); - } - - if (!matchingServer) { - matchingServer = servers.find((server: ActiveServer) => server.customName?.includes('Analysis')); - } - + const matchingServer = serverRegistry.getAllServers() + .find((server: ActiveServer) => server.metadata?.sessionId === sessionId); if (matchingServer) { - await ServerControl.stopServer(matchingServer.id); + await ServerControl.stopServer(matchingServer.id, { silent: true }); } } catch (error) { - logger.error(`Error finding and stopping server for session ${sessionId}:`, error); + logger.error(`Error stopping the server of session ${sessionId}:`, error); } } diff --git a/apps/vscode-extension/test/analysis/analysisServerCapabilities.test.cjs b/apps/vscode-extension/test/analysis/analysisServerCapabilities.test.cjs index 054c9a22b..28e991d97 100644 --- a/apps/vscode-extension/test/analysis/analysisServerCapabilities.test.cjs +++ b/apps/vscode-extension/test/analysis/analysisServerCapabilities.test.cjs @@ -2,7 +2,6 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); -const ts = require('typescript'); const projectRoot = path.resolve(__dirname, '..', '..'); @@ -11,33 +10,13 @@ function readProjectFile(...segments) { } /** - * Transpiles and executes the real `analysisServerCapabilities.ts` module. It has - * no imports (in particular no `vscode`), so it can run directly under node with - * a plain CommonJS transpile — this exercises the actual shipped resolver logic, - * not a re-implementation of it. + * Loads the real compiled `analysisServerCapabilities` module from `out/` + * (npm test compiles first). Its only dependency is the pure analysis-type + * descriptor list, so no `vscode` stub is needed: this exercises the shipped + * resolver, derived from the descriptors, not a re-implementation of it. */ function loadCapabilitiesModule() { - const sourcePath = path.join( - projectRoot, - 'src', - 'core', - 'server', - 'analysisServerCapabilities.ts', - ); - const source = fs.readFileSync(sourcePath, 'utf8'); - const transpiled = ts.transpileModule(source, { - compilerOptions: { - module: ts.ModuleKind.CommonJS, - target: ts.ScriptTarget.ES2022, - esModuleInterop: true, - }, - fileName: sourcePath, - }).outputText; - - const moduleExports = {}; - const moduleWrapper = new Function('exports', 'require', 'module', '__filename', '__dirname', transpiled); - moduleWrapper(moduleExports, require, { exports: moduleExports }, sourcePath, path.dirname(sourcePath)); - return moduleExports; + return require(path.join(projectRoot, 'out', 'core', 'server', 'analysisServerCapabilities.js')); } // ── Common server-launch capability gating ───────────────────────────────── diff --git a/apps/vscode-extension/test/analysis/launchTransaction.test.cjs b/apps/vscode-extension/test/analysis/launchTransaction.test.cjs new file mode 100644 index 000000000..8ff5ac9a1 --- /dev/null +++ b/apps/vscode-extension/test/analysis/launchTransaction.test.cjs @@ -0,0 +1,430 @@ +'use strict'; + +/** + * The unified launcher (S5, issue #77), executed from out/ under the fake + * vscode: + * + * - `targetKey`: one identity per target whatever spelled its path + * (LAUNCHER-17), for every platform from any platform; + * - the session registry reserves a target before its first await, so two + * concurrent launches of one file yield one session (LAUNCHER-2); + * - `LaunchControl`: teardown newest first, exactly once; a step that lands + * after the launch is gone is undone at once; the deadline aborts; + * - `executeLaunchPipeline` as a transaction: a server failure starts no + * watcher and shows one error; a Close while analysing starts nothing and + * shows nothing; a watcher failure stops the server it started; a timeout + * rolls back and reports it (LAUNCHER-5/7/10); + * - `resolveLauncher` and the storage folders cleanup sweeps (LAUNCHER-14). + */ + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const { createFakeVscode, withFakeVscode, fakeExtensionContext } = require('../helpers/fakeVscode.cjs'); + +function silenceConsole() { + const methods = ['log', 'info', 'warn', 'error', 'debug']; + const original = methods.map((method) => console[method]); + methods.forEach((method) => { + console[method] = () => {}; + }); + return () => methods.forEach((method, index) => { + console[method] = original[index]; + }); +} + +async function withOut(body) { + const fake = createFakeVscode(); + const context = fakeExtensionContext(); + const restoreConsole = silenceConsole(); + try { + await withFakeVscode(fake, async ({ requireOut }) => body({ requireOut, fake, context })); + } finally { + restoreConsole(); + context.cleanup(); + } +} + +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +// ── targetKey ──────────────────────────────────────────────────────── + +test('targetKey folds case on Windows and macOS, keeps it on Linux, and drops trailing separators', async () => { + await withOut(async ({ requireOut }) => { + const { targetKey, launchKey } = requireOut('core/analysis/launch/targetKey.js'); + + assert.equal(targetKey('C:\\Proj\\A.ts', 'win32'), targetKey('c:\\proj\\a.ts', 'win32')); + assert.equal(targetKey('C:\\Proj\\src\\', 'win32'), 'c:\\proj\\src'); + assert.equal(targetKey('C:/Proj/src/', 'win32'), 'c:\\proj\\src'); + assert.equal(targetKey('C:\\', 'win32'), 'c:\\', 'a drive root keeps its separator'); + + assert.equal(targetKey('/Users/Ana/Proj/A.ts', 'darwin'), '/users/ana/proj/a.ts'); + assert.equal(targetKey('/Users/Ana/Proj/', 'darwin'), '/users/ana/proj'); + + assert.equal(targetKey('/home/ana/Proj/A.ts', 'linux'), '/home/ana/Proj/A.ts'); + assert.notEqual(targetKey('/home/ana/A.ts', 'linux'), targetKey('/home/ana/a.ts', 'linux')); + assert.equal(targetKey('/home/ana/proj///', 'linux'), '/home/ana/proj'); + assert.equal(targetKey('/home/ana/./proj/../proj', 'linux'), '/home/ana/proj'); + assert.equal(targetKey('/', 'linux'), '/'); + + assert.equal( + launchKey('XR', 'C:\\Proj\\A.ts', 'file', false, 'win32'), + launchKey('XR', 'c:\\proj\\a.ts', 'file', false, 'win32'), + ); + assert.notEqual( + launchKey('XR', '/p/a.ts', 'file', false, 'linux'), + launchKey('XR', '/p/a.ts', 'file', true, 'linux'), + ); + }); +}); + +// ── Session registry: reservation before the first await ──────────── + +test('two concurrent launches of one target create one session; the second is a duplicate', async () => { + await withOut(async ({ requireOut, context }) => { + const workRoot = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-launch-tx-'))); + try { + const target = path.join(workRoot, 'a.ts'); + fs.writeFileSync(target, 'export const a = 1;\n'); + const { UnifiedSessionRegistry } = requireOut('core/analysis/session/sessionRegistry.js'); + const registry = UnifiedSessionRegistry.getInstance(context); + + const request = { targetPath: target, analysisMode: 'XR', targetType: 'file', context }; + const [first, second] = await Promise.all([ + registry.createSession(request), + registry.createSession({ ...request, targetPath: `${target}${path.sep}` }), + ]); + assert.deepEqual([first.kind, second.kind], ['created', 'duplicate']); + assert.equal(second.existing.id, first.session.id); + assert.equal(registry.getSessionsByTargetPath(target).length, 1); + } finally { + fs.rmSync(workRoot, { recursive: true, force: true }); + } + }); +}); + +// ── LaunchControl ──────────────────────────────────────────────────── + +test('LaunchControl undoes steps newest first, exactly once', async () => { + await withOut(async ({ requireOut }) => { + const { LaunchControl } = requireOut('core/analysis/launch/launchControl.js'); + const control = LaunchControl.createForTesting(); + const undone = []; + const signal = control.begin('s1', 0); + control.push('s1', 'server', () => undone.push('server')); + control.push('s1', 'watcher', () => undone.push('watcher')); + + assert.deepEqual(await control.abort('s1', 'failed'), ['watcher', 'server']); + assert.equal(signal.aborted, true); + assert.equal(signal.reason, 'failed'); + assert.deepEqual(await control.abort('s1', 'failed'), [], 'a second abort undoes nothing'); + assert.deepEqual(await control.close('s1'), []); + assert.deepEqual(undone, ['watcher', 'server']); + assert.equal(control.has('s1'), false); + }); +}); + +test('a step pushed after the launch is gone is undone at once; a failing teardown does not stop the rest', async () => { + await withOut(async ({ requireOut }) => { + const { LaunchControl } = requireOut('core/analysis/launch/launchControl.js'); + const control = LaunchControl.createForTesting(); + const undone = []; + control.begin('s1', 0); + control.push('s1', 'first', () => undone.push('first')); + control.push('s1', 'broken', () => { + throw new Error('teardown failed'); + }); + assert.deepEqual(await control.close('s1'), ['first']); + + control.push('s1', 'late-server', () => undone.push('late-server')); + await tick(); + assert.deepEqual(undone, ['first', 'late-server']); + }); +}); + +test('the deadline aborts the launch with reason "timeout"; settle() cancels it', async () => { + await withOut(async ({ requireOut }) => { + const { LaunchControl, LaunchAbortedError } = requireOut('core/analysis/launch/launchControl.js'); + const control = LaunchControl.createForTesting(); + const undone = []; + + const timed = control.begin('slow', 20); + control.push('slow', 'server', () => undone.push('server')); + await new Promise((resolve) => setTimeout(resolve, 60)); + assert.equal(timed.aborted, true); + assert.equal(timed.reason, 'timeout'); + assert.deepEqual(undone, ['server']); + + const settled = control.begin('fast', 20); + control.settle('fast'); + await new Promise((resolve) => setTimeout(resolve, 60)); + assert.equal(settled.aborted, false); + assert.equal(control.has('fast'), true); + + // Between steps, an aborted launch throws a LaunchAbortedError carrying its reason. + control.begin('stopped', 0); + const record = control.signal('stopped'); + const controller = { signal: record }; + assert.equal(controller.signal.aborted, false); + control.throwIfAborted('stopped'); + await control.close('fast'); + await control.close('stopped'); + assert.equal(record.aborted, true); + assert.equal(new LaunchAbortedError('timeout').message, 'The analysis took too long and was stopped.'); + }); +}); + +test('beginning a session twice supersedes the first launch', async () => { + await withOut(async ({ requireOut }) => { + const { LaunchControl } = requireOut('core/analysis/launch/launchControl.js'); + const control = LaunchControl.createForTesting(); + const undone = []; + const first = control.begin('s1', 0); + control.push('s1', 'old-server', () => undone.push('old-server')); + const second = control.begin('s1', 0); + await tick(); + assert.equal(first.aborted, true); + assert.equal(first.reason, 'superseded'); + assert.equal(second.aborted, false); + assert.deepEqual(undone, ['old-server']); + await control.close('s1'); + }); +}); + +// ── executeLaunchPipeline as a transaction ────────────────────────── + +async function withPipeline(body) { + await withOut(async ({ requireOut, fake, context }) => { + const events = []; + const statuses = []; + const behaviour = { + server: async () => ({ success: true, sessionServerInfo: { serverId: 'srv-1', port: 3100, serverUrl: 'http://localhost:3100' } }), + }; + + const { UnifiedSessionRegistry } = requireOut('core/analysis/session/sessionRegistry.js'); + UnifiedSessionRegistry.getInstance = () => ({ + updateSessionStatus(id, status) { + statuses.push(status); + return true; + }, + registerSessionPort() { + return true; + }, + }); + const { SaveFiles } = requireOut('core/analysis/utils/saveFiles.js'); + SaveFiles.prototype.saveFilesToStorage = async () => '/saved/path'; + const { ServerLaunchOrchestrator } = requireOut('core/analysis/session-servers/serverLaunchOrchestrator.js'); + ServerLaunchOrchestrator.prototype.launchServerForSession = async () => { + events.push('server:start'); + return behaviour.server(); + }; + const liveServers = new Set(); + const registryModule = requireOut('core/server/registry/activeServerRegistry.js'); + registryModule.getActiveServerRegistry = () => ({ getServer: (id) => (liveServers.has(id) ? { id } : undefined) }); + const { ServerControl } = requireOut('core/server/serverControl.js'); + ServerControl.stopServer = async (id) => { + events.push(`server:stop:${id}`); + liveServers.delete(id); + return true; + }; + const { SessionWatcherManager } = requireOut('core/analysis/watchers/sessionWatcherManager.js'); + SessionWatcherManager.prototype.stopWatchingSession = async () => { + events.push('watcher:stop'); + }; + const { LaunchControl } = requireOut('core/analysis/launch/launchControl.js'); + const { executeLaunchPipeline } = requireOut('core/analysis/launchers/launchPipeline.js'); + + const control = LaunchControl.createForTesting(); + const session = { + id: 'session-1', + targetPath: '/tmp/a.ts', + outputDirectory: 'a_XR_file_session-1', + requiredFiles: new Map(), + }; + const config = (overrides = {}) => ({ + logPrefix: 'TEST', + folderName: 'fileAnalysis', + progress: { process: 10, save: 20, watcherOrServer: 30, serverOrWatcher: 40, done: 100 }, + processRequirements: async () => { + events.push('process'); + return { loadedFiles: new Map([['index.html', '']]) }; + }, + startWatcher: async () => { + events.push('watcher:start'); + return 'watcher-1'; + }, + ...overrides, + }); + const errors = () => fake.messages.filter((m) => m.kind === 'error').map((m) => m.message); + const markServerLive = () => liveServers.add('srv-1'); + await body({ executeLaunchPipeline, control, session, context, config, events, statuses, behaviour, errors, markServerLive }); + }); +} + +test('a successful launch starts the server before the watcher and ends monitoring', async () => { + await withPipeline(async ({ executeLaunchPipeline, control, session, context, config, events, statuses, errors, markServerLive }) => { + let served = null; + await executeLaunchPipeline(session, context, config({ + startWatcher: async () => { + markServerLive(); + events.push('watcher:start'); + return 'watcher-1'; + }, + onSuccess: (port, url) => { + served = { port, url }; + }, + }), { control, timeoutMs: 0 }); + + assert.deepEqual(events, ['process', 'server:start', 'watcher:start']); + assert.equal(statuses.at(-1), 'monitoring'); + assert.deepEqual(served, { port: 3100, url: 'http://localhost:3100' }); + assert.deepEqual(errors(), []); + + // Closing the finished analysis undoes both steps, watcher first. + assert.deepEqual(await control.close(session.id), ['watcher', 'server']); + assert.deepEqual(events.slice(3), ['watcher:stop', 'server:stop:srv-1']); + }); +}); + +test('a server that cannot start leaves no watcher behind and shows exactly one error', async () => { + await withPipeline(async ({ executeLaunchPipeline, control, session, context, config, events, statuses, behaviour, errors }) => { + behaviour.server = async () => ({ success: false, error: 'No free port' }); + await executeLaunchPipeline(session, context, config(), { control, timeoutMs: 0 }); + + assert.deepEqual(events, ['process', 'server:start']); + assert.equal(statuses.at(-1), 'error'); + assert.deepEqual(errors(), ['Failed to start analysis: No free port']); + assert.equal(control.has(session.id), false); + }); +}); + +test('a watcher failure stops the server the launch started', async () => { + await withPipeline(async ({ executeLaunchPipeline, control, session, context, config, events, errors, markServerLive }) => { + await assert.rejects(executeLaunchPipeline(session, context, config({ + rethrowErrors: true, + startWatcher: async () => { + markServerLive(); + throw new Error('watch failed'); + }, + }), { control, timeoutMs: 0 }), /watch failed/); + + assert.deepEqual(events, ['process', 'server:start', 'server:stop:srv-1']); + assert.deepEqual(errors(), ['Failed to start analysis: watch failed']); + }); +}); + +test('closing while the analysis runs starts no server, no watcher and shows no error', async () => { + await withPipeline(async ({ executeLaunchPipeline, control, session, context, config, events, errors }) => { + let release; + const launch = executeLaunchPipeline(session, context, config({ + processRequirements: () => new Promise((resolve) => { + events.push('process'); + release = () => resolve({ loadedFiles: new Map() }); + }), + }), { control, timeoutMs: 0 }); + await tick(); + await control.close(session.id); + await launch; + release(); + await tick(); + + assert.deepEqual(events, ['process']); + assert.deepEqual(errors(), []); + }); +}); + +test('a launch past its deadline is rolled back and reported as a timeout', async () => { + await withPipeline(async ({ executeLaunchPipeline, control, session, context, config, events, statuses, errors }) => { + await executeLaunchPipeline(session, context, config({ + processRequirements: () => new Promise(() => { + events.push('process'); + }), + }), { control, timeoutMs: 30 }); + + assert.deepEqual(events, ['process']); + assert.equal(statuses.at(-1), 'error'); + assert.deepEqual(errors(), ['Failed to start analysis: The analysis took too long and was stopped.']); + }); +}); + +test('the launch signal reaches code running below the pipeline', async () => { + await withOut(async ({ requireOut }) => { + const { runWithLaunchSignal, currentLaunchSignal } = requireOut('core/analysis/launch/launchControl.js'); + const controller = new AbortController(); + assert.equal(currentLaunchSignal(), undefined); + const seen = await runWithLaunchSignal(controller.signal, async () => { + await tick(); + return currentLaunchSignal(); + }); + assert.equal(seen, controller.signal); + }); +}); + +// ── Launch kinds, storage folders, analysis-type tables ───────────── + +test('resolveLauncher dispatches every supported kind and refuses the rest by name', async () => { + await withOut(async ({ requireOut }) => { + const { resolveLauncher, LAUNCH_KINDS } = requireOut('core/analysis/launch/launchKinds.js'); + for (const kind of ['XR', 'LivePanel']) { + assert.equal(typeof resolveLauncher(kind, 'file'), 'function'); + assert.equal(typeof resolveLauncher(kind, 'directory'), 'function'); + } + assert.equal(typeof resolveLauncher('VisualizeDOM', 'file'), 'function'); + assert.throws(() => resolveLauncher('VisualizeDOM', 'directory'), /DOM visualization analysis only supports file targets, not directory/); + assert.throws(() => resolveLauncher('Hologram', 'file'), /Unknown analysis mode: Hologram/); + assert.throws(() => resolveLauncher('constructor', 'file'), /Unknown analysis mode/); + assert.deepEqual(Object.keys(LAUNCH_KINDS), ['XR', 'LivePanel', 'VisualizeDOM']); + }); +}); + +test('cleanup sweeps every folder the launchers write, plus the legacy root', async () => { + await withOut(async ({ requireOut }) => { + const { ANALYSIS_STORAGE_FOLDERS, getSweptStorageFolders } = requireOut('core/analysis/launch/storageFolders.js'); + assert.deepEqual(getSweptStorageFolders(), ['fileAnalysis', 'directoryAnalysis', 'visualizeDOMAnalysis', 'analysis']); + + // Every folder name a launcher passes to the pipeline is swept. + const launcherSources = ['launcherXRAnalysis.ts', 'launcherLivePanel.ts', 'launcherVisualizeDOM.ts'] + .map((name) => fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'core', 'analysis', 'launchers', name), 'utf8')) + .join('\n'); + const used = [...launcherSources.matchAll(/ANALYSIS_STORAGE_FOLDERS\.(\w+)/g)].map((m) => ANALYSIS_STORAGE_FOLDERS[m[1]]); + assert.ok(used.length >= 3); + assert.equal(/folderName:\s*['"]/.test(launcherSources), false, 'no launcher spells a folder name by hand'); + for (const folder of used) { + assert.ok(getSweptStorageFolders().includes(folder), folder); + } + }); +}); + +test('the host tables derived from the analysis types are unchanged', async () => { + await withOut(async ({ requireOut }) => { + const { ANALYSIS_CONTROLLER_VIEW_BY_MODE, defaultControllerView } = requireOut('core/analysis/refresh/analysisViewModes.js'); + assert.deepEqual({ ...ANALYSIS_CONTROLLER_VIEW_BY_MODE }, { + selection: 'visualization-menu', + single: 'single.mapping', + 'dependency-graph': 'dependency.settings', + 'historical-compare': 'historical.selection', + 'project-evolution': 'project-evolution', + }); + assert.equal(defaultControllerView('constructor'), 'single.mapping'); + + const { getServerFeaturesForSurface, ANALYSIS_TYPES } = requireOut('core/analysis/launch/analysisTypes.js'); + assert.deepEqual([...getServerFeaturesForSurface('XR')].sort(), ['dependencyGraph', 'historicalComparison', 'projectEvolution']); + assert.deepEqual([...getServerFeaturesForSurface('LivePanel')].sort(), ['dependencyGraph', 'historicalComparison']); + assert.deepEqual([...getServerFeaturesForSurface('VisualizeDOM')], []); + assert.deepEqual([...getServerFeaturesForSurface(undefined)], []); + + const probes = Object.fromEntries(ANALYSIS_TYPES.filter((t) => t.snapshotProbe).map((t) => [t.id, t.snapshotProbe.entityKind])); + assert.deepEqual(probes, { + 'dependency-graph': 'dependency-graph', + 'historical-compare': 'historical-comparison', + 'project-evolution': 'project-evolution', + }); + const dep = ANALYSIS_TYPES.find((t) => t.id === 'dependency-graph').snapshotProbe; + assert.equal(dep.isAvailable({ datasetUrl: '/d.json' }), true); + assert.equal(dep.isAvailable({}), false); + assert.equal(dep.isAvailable(null), false); + }); +}); diff --git a/apps/vscode-extension/test/analysis/livePanelHistorical.test.cjs b/apps/vscode-extension/test/analysis/livePanelHistorical.test.cjs index 2878585d6..09dbe9d49 100644 --- a/apps/vscode-extension/test/analysis/livePanelHistorical.test.cjs +++ b/apps/vscode-extension/test/analysis/livePanelHistorical.test.cjs @@ -22,11 +22,14 @@ function readProjectFile(...segments) { } test('the capability table grants LivePanel historical comparison while project evolution stays XR-only', () => { - const capabilities = readProjectFile('src', 'core', 'server', 'analysisServerCapabilities.ts'); - const livePanelEntry = capabilities.match(/LivePanel: \{[\s\S]*?\},/)?.[0] || ''; - assert.match(livePanelEntry, /dependencyGraph: true/); - assert.match(livePanelEntry, /historicalComparison: true/); - assert.match(livePanelEntry, /projectEvolution: false/); + // Derived from the analysis-type descriptors (S5); asserted on the + // compiled resolver rather than on the source text. + const { resolveAnalysisServerCapabilities } = require(path.join(projectRoot, 'out', 'core', 'server', 'analysisServerCapabilities.js')); + assert.deepEqual(resolveAnalysisServerCapabilities('LivePanel'), { + dependencyGraph: true, + historicalComparison: true, + projectEvolution: false, + }); }); test('the historical comparison service admits LivePanel sessions and still throws for anything else', () => { diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index 7acd984c9..b4ce61f32 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -24,10 +24,10 @@ }, "catch.consoleOnly": 0, "catch.emptyNoComment": 0, - "any.total": 84, + "any.total": 83, "any.byModule": { "app": 8, - "core/analysis": 14, + "core/analysis": 13, "core/charts": 6, "core/python-env": 5, "core/server": 10, @@ -56,8 +56,8 @@ "src/features/active-servers/views/handleServerActions.ts", "src/features/analysis/sections/active-analyses/activeAnalysesCommands.ts" ], - "functions.over80Lines": 36, - "complexity.over10": 53, + "functions.over80Lines": 35, + "complexity.over10": 51, "complexity.over15": 8, "complexity.over20": 0, "complexity.over30": 0, @@ -71,9 +71,9 @@ } }, "informational": { - "src.files": 291, - "src.lines": 49064, - "src.functions": 3338, + "src.files": 294, + "src.lines": 49282, + "src.functions": 3360, "src.unreachableLines": 0, "console.byFile": { "src/platform/logging/sink.ts": 2 @@ -93,7 +93,6 @@ "src/core/analysis/processors/analysisBootstrap.ts": 2, "src/core/analysis/python/executePython.ts": 2, "src/core/analysis/session-servers/serverLaunchOrchestrator.ts": 2, - "src/core/analysis/session-servers/sessionServerModels.ts": 1, "src/core/analysis/session/analysisSession.ts": 1, "src/core/analysis/utils/themeUtils.ts": 1, "src/core/charts/processing/templateProcessor.ts": 2, @@ -241,15 +240,15 @@ }, { "ccn": 15, - "lines": 81, - "function": "closeAssociatedAnalysisSession", - "file": "src/core/server/serverControl.ts" + "lines": 157, + "function": "launchServer", + "file": "src/core/server/multiServerLauncher.ts" }, { "ccn": 15, - "lines": 88, - "function": "startLocalServer", - "file": "src/features/servers/commands/serverCommands.ts" + "lines": 113, + "function": "launchServerByType", + "file": "src/core/server/serverFactory.ts" } ], "size.largest10": [ @@ -271,7 +270,7 @@ }, { "file": "src/features/active-servers/views/handleServerActions.ts", - "lines": 624 + "lines": 628 }, { "file": "src/core/history/gitRepositoryService.ts", @@ -279,15 +278,15 @@ }, { "file": "src/core/server/httpServer.ts", - "lines": 582 + "lines": 596 }, { - "file": "src/core/server/broadcast/screenBroadcastSignalingServer.ts", - "lines": 581 + "file": "src/core/analysis/python/executePython.ts", + "lines": 589 }, { - "file": "src/core/analysis/python/executePython.ts", - "lines": 567 + "file": "src/core/server/broadcast/screenBroadcastSignalingServer.ts", + "lines": 581 }, { "file": "src/core/remote-access/remoteAccessManager.ts",