diff --git a/.claude/docs/AI_WORKFLOWS.md b/.claude/docs/AI_WORKFLOWS.md
index f79174108..8fdf2c13b 100644
--- a/.claude/docs/AI_WORKFLOWS.md
+++ b/.claude/docs/AI_WORKFLOWS.md
@@ -5,58 +5,71 @@
## Universal session rules
-1. **One unit of work per session** — one feature, one bug, one refactor, or one docs/release task. Finish and validate it before starting anything else.
-2. **Start from `INDEX.md`** and read only the documents mapped to your task type. Do not scan `src/` broadly; `src/code_analysis/` alone is 246 files.
+0. **Know the version's scope.** The active version is **v1.2.1, a maintenance release: cleanup, optimization and hygiene, no new features.** Read `V1.2.1_STATUS.md` for the ranked backlog and the baseline numbers. If a task would add user-visible behaviour, it belongs in 1.3.0 — say so instead of quietly widening 1.2.1.
+1. **One unit of work per session** — one feature, one bug, one refactor, or one docs/release task. Finish and validate it before starting anything else. **Exception — the v1.2.1 cleanup programme:** there the unit is the *commit*, not the session. One roadmap item = one bisectable commit, a session may land several in roadmap order with the gate run after each, and a red gate ends the session at the last green commit (`cleanup` skill §1).
+2. **Start from `INDEX.md`** and read only the documents mapped to your task type. Do not scan `src/` broadly; `src/core/analysis/` and `src/features/analysis/` together are about 120 files.
3. **Distinguish claim levels** in everything you report and write: confirmed (you verified it), self-assessed (a doc claims it), inferred, open question.
4. **Validate before declaring done**: at minimum `npm run test:basic`; plus the narrowest specialized script for the touched area (matrix in `DEVELOPMENT.md`).
5. **End-of-session checklist**:
- [ ] Relevant tests pass (say which ones ran).
- - [ ] `V1.2.0_STATUS.md` updated if the version state changed.
- - [ ] `CHANGELOG.md` "[1.2.0] – Unreleased" updated for user-visible changes.
+ - [ ] `V1.2.1_STATUS.md` updated if the version state changed — including the baseline row you moved.
+ - [ ] `CHANGELOG.md` `[1.2.1]` section updated for user-visible changes (pure internal hygiene is summarized there once, under "Internal improvements"; it does not get a line per commit).
- [ ] Architecture/development docs updated if their subject changed.
- - [ ] Work committed on `v1.2.0` (never commit directly to `master`).
+ - [ ] Work committed on `v1.2.1` (never commit directly to `master`).
## Playbook: new feature
-1. Read: `ARCHITECTURE.md`, `V1.2.0_STATUS.md`, plus the area doc (`XR_COMPONENTS.md` and/or `PYTHON_ANALYSIS.md`) and any relevant `docs/*.md` feature doc.
-2. Check the roadmap (`docs/project/ROADMAP_V1.2.0.md`) — is the feature in scope for this version? Respect scope decisions (e.g., boats/Code City is paused).
-3. Follow the per-feature module convention (`commands/` + `model/` + `runtime|services/` + `views/{items,interactions}`); register commands through the module's registration array consumed by `src/commands/index.ts` (IDs must be unique — `assertUniqueCommandIds` enforces this).
+1. Read: `ARCHITECTURE.md`, `V1.2.1_STATUS.md` (the active status doc), plus the area doc (`XR_COMPONENTS.md` and/or `PYTHON_ANALYSIS.md`) and any relevant `docs/*.md` feature doc.
+2. Check the scope of the active version — 1.2.1 is maintenance only (`V1.2.1_STATUS.md`, `v1.2.1/ROADMAP.md`), so a feature belongs in 1.3.0; `docs/project/ROADMAP_V1.2.0.md` is the historical 1.2.0 plan. Respect scope decisions (e.g., boats/Code City is paused).
+3. Follow the per-feature module convention (`commands/` + `model/` + `runtime|services/` + `views/{items,interactions}`); register commands through the module's registration array consumed by `src/app/commands/registerAllCommands.ts` (IDs must be unique — `assertUniqueCommandIds` enforces this).
4. If the feature adds metrics or chart dimensions, plan the Python schema ↔ TS validator sync first (`PYTHON_ANALYSIS.md` → field-schema contract).
5. Add tests: unit `.test.cjs` in `test//`; runtime changes under `templates/components/` get a runtime test; consider a manual harness for visual behavior.
6. Validate: narrow test script → `npm run test:basic` → F5 manual flow (`DEVELOPMENT.md`).
-7. Update: CHANGELOG Unreleased, `V1.2.0_STATUS.md`, and the area doc if the mechanism changed.
+7. Update: CHANGELOG (the active version's section, `[1.2.1]` today), `V1.2.1_STATUS.md`, and the area doc if the mechanism changed.
## Playbook: bug fix
1. Read: `ARCHITECTURE.md` module map to locate the subsystem; the area doc if the bug touches a contract seam.
2. **Reproduce first** — via the narrowest test script or the F5 flow. Write a failing test when feasible (`test//*.test.cjs` or `test/python/`).
-3. Fix at the root cause; do not patch around watchers/session lifecycle without reading `engine/core/analysisSession.ts` + `engine/watchers/` behavior.
+3. Fix at the root cause; do not patch around watchers/session lifecycle without reading `core/analysis/session/analysisSession.ts` + `core/analysis/watchers/` behavior.
4. Validate: the new/affected test + `npm run test:basic`.
5. Update CHANGELOG (Fixed) and, if the bug revealed wrong documentation, correct the doc in the same session.
+## Playbook: cleanup / optimization (the v1.2.1 default)
+
+Full procedure lives in the **`cleanup` skill** — invoke it. Summary:
+
+1. Read `V1.2.1_STATUS.md` (where we are) and `v1.2.1/ROADMAP.md` §A-E plus your wave (what is next). **One roadmap item = one commit**; never fold two items together or add opportunistic extras (they destroy bisectability, which is the safety net of a cleanup branch). A characterization test and the reshaping it protects are two commits, test first.
+2. **Prove deadness, never assume it — four checks**: zero importers · no name/path-string reference in `src/ templates/ test/ scripts/ webpack.config.js package.json` · registers no command · **no test reads the file as text** (about half the unit tests regex the source of `src/` and `templates/`). Grep `v1.2.1/AUDIT.md` for the file first: every area ends with a "looks dead but is ALIVE" list. Two known traps: a file can look dead and still register a command (`debugThemeProblem.ts` was one, removed in v1.2.1 W2-49), and `src/active_servers/views/` vs `src/views/active_servers/` is deliberate historical duplication (see §refactor rule 4).
+3. Reshaping a file → characterize first. Before touching file F, `grep -rn "" test/ scripts/` and classify each pin (**G** permanent guard: keep, retarget the haystack if F is split · **S** shape pin: a behavioural characterization lands in a prior commit · **L** log-literal: the text survives verbatim). Two standards prove nothing was lost: **H1** (unreachable file deleted, or types-only change) = `dist/extension.js` sha256 identical on the production build; **H2** (dead declaration in a live file) = reviewed dist shrink. Precedent: `httpServer.ts` 2,102 → 487 lines with a byte-identical characterization diff.
+4. Behaviour-neutral unless the CHANGELOG says otherwise. Users should notice a smaller package and nothing else.
+5. Off-limits in a cleanup session: git history rewrites (the 1.03 GiB pack is *propose only* — it breaks every clone), removing 1.1.0 upgrade migrations or published `Legacy*` command aliases, deleting docs or rewriting their history sections (a line-level drift fix travels with the commit that causes it), a blanket `eslint --fix` or any Python formatter (tests pin import lines and quote styles), the XR field-schema contract.
+6. Verify per the `verify` skill. Lint-config changes: land config + fallout together, never leave the gate red. Asset/`files` changes: `npm run package:vsix` and inspect the zip.
+7. Record the number. `npm run guardrails:update` regenerates `test/tooling/guardrail-baseline.json` in the same commit — that diff is the item's before/after. Append a session-log entry to `V1.2.1_STATUS.md` and move the "Now" column of its tool-measured baseline. A cleanup with no measurement is a claim, not a result.
+
## Playbook: refactor
1. Confirm scope with the user first if the refactor crosses module boundaries or touches a contract seam (field schema, chart registry, command registration, component injection, SSE keying).
2. Read: `ARCHITECTURE.md` (esp. "cross-module contracts") + the area doc.
3. Refactors must be behavior-neutral: run the full relevant matrix before *and* after (`test:basic`, plus `test:python`/`test:analysis` if analysis is touched, harnesses if runtimes are touched).
-4. Respect known duplication that is historical, not accidental (e.g. `active_servers/views/` vs `views/active_servers/`) — don't "clean up" aggregation wiring without tracing imports.
+4. Respect known duplication that is historical, not accidental (e.g. the two example item factories and click handlers in `features/examples/views/`) — don't "clean up" aggregation wiring without tracing imports.
5. Update `ARCHITECTURE.md` if module responsibilities or seams moved.
## Playbook: documentation update
-1. Read `INDEX.md` + the target doc. Check `V1.2.0_STATUS.md` → "Documentation debt" — your task may already be catalogued there.
-2. Rules: never delete existing docs; record inconsistencies instead of silently rewriting history; keep `docs/*` (user-shipped, mixed ES/EN) separate in tone from `.claude/docs/*` (internal, English).
-3. Remember `docs/**` ships in the VSIX; `.claude/**` does not.
-4. If you fix an inconsistency listed in `V1.2.0_STATUS.md`, remove it from the debt list in the same session.
+1. Read `INDEX.md` + the target doc. Check `V1.2.1_STATUS.md` → "Carried-over debt from 1.2.0" and the historical `V1.2.0_STATUS.md` → "Documentation debt" — your task may already be catalogued there.
+2. Rules: never delete existing docs; record inconsistencies instead of silently rewriting history; keep `docs/*` (user-facing, mixed ES/EN) separate in tone from `.claude/docs/*` (internal, English).
+3. Neither `docs/**` (since 1.2.1; the README links it on GitHub) nor `.claude/**` ships in the VSIX.
+4. If you fix a catalogued inconsistency, record the fix in `V1.2.1_STATUS.md` in the same session (`V1.2.0_STATUS.md` is a closed historical record).
## Playbook: release preparation
-1. Read: `V1.2.0_STATUS.md` (entire file), `docs/project/ROADMAP_V1.2.0.md` (exit criteria + delivery sequence), `DEVELOPMENT.md` (packaging).
-2. Resolve every "Needs verification" row in `V1.2.0_STATUS.md` (each has a how-to-verify hint).
-3. Reconcile docs: README "What's New" → v1.2.0 content; CHANGELOG `[1.2.0] – Unreleased` → dated release entry; roadmap statuses; language-count claim fixed against `src/utils/languageMetadata.ts`; rename leftovers.
+1. Read: `V1.2.1_STATUS.md` (entire file), `v1.2.1/ROADMAP.md` (decisions and exit criteria; `docs/project/ROADMAP_V1.2.0.md` holds the historical 1.2.0 ones), `DEVELOPMENT.md` (packaging).
+2. Resolve every open verification row in `V1.2.1_STATUS.md` (each has a how-to-verify hint).
+3. Reconcile docs: README "What's New" → the release's content; CHANGELOG `[1.2.1]` → its provisional date moved to the real release date; roadmap statuses; language-count claim fixed against `src/core/analysis/languages/languageMetadata.ts`; rename leftovers.
4. Quality gate: `npm run test:all` + `npm run test:analysis` + harnesses for touched runtimes; F5 smoke of the three analysis modes.
5. Package: `npm run package:vsix`; **inspect the VSIX contents** against the package.json `files` allowlist (no `.vscodeignore` exists — the allowlist is the only control). Verify no unintended files ship and nothing required is missing.
-6. Respect the pre-release sequence (`1.2.0-alpha.1` → … → `rc.1` → stable) — do not jump to stable.
+6. Respect the pre-release sequence a feature release used (1.2.0: `1.2.0-alpha.1` → … → `rc.1` → stable) — do not jump to stable.
7. Roadmap exit criteria are hard requirements: no analysis-flow regressions vs 1.1.0, server-validated admin ops, collaboration works without avatar download, no downloads without consent.
## Context-efficiency rules (cost control)
diff --git a/.claude/docs/ARCHITECTURE.md b/.claude/docs/ARCHITECTURE.md
index a4f5780ee..21b5ffa64 100644
--- a/.claude/docs/ARCHITECTURE.md
+++ b/.claude/docs/ARCHITECTURE.md
@@ -2,40 +2,45 @@
> **Purpose**: High-level system architecture for AI agents and developers. Read this before touching anything under `src/`.
> **Stability**: Stable — update only when the architecture itself changes (new module, changed data flow), not for feature-level changes.
-> Facts here were verified against the code on 2026-07-08. Items marked *[inferred]* are conclusions from structure/naming, not verified line-by-line.
+> Facts here were verified against the code on 2026-07-08; the module map and every path were re-verified on 2026-11-25 (story #43) after the monorepo move and the feature-first `src/` layout (#55). Items marked *[inferred]* are conclusions from structure/naming, not verified line-by-line.
## The one-paragraph summary
-CodeXR is a VS Code extension (~337 TS files) that analyzes source code with a **Python backend** (Lizard metrics, run in a managed virtual environment) and renders the results as **BabiaXR/A-Frame XR scenes** served by **local HTTP/HTTPS servers** with **SSE live-reload**. The extension side is TypeScript; the in-scene runtime is plain JavaScript living in `templates/components/` and injected into generated HTML.
+CodeXR is a VS Code extension (291 TS files under `src/`, in five layers since #55) that analyzes source code with a **Python backend** (its own code-metrics analyzer, `backend/src/tools/code_metrics/`, which replaced Lizard in 1.2.1; run in a managed virtual environment) and renders the results as **BabiaXR/A-Frame XR scenes** served by **local HTTP/HTTPS servers** with **SSE live-reload**. The extension side is TypeScript; the in-scene runtime is plain JavaScript living in `templates/components/` and injected into generated HTML.
## Main data flow (the pipeline)
```
User command (context menu / tree / palette)
- └─> src/code_analysis/commands/... (per-mode command handlers)
- └─> engine/launchers/launcherXRAnalysis.ts | launcherLivePanel.ts | launcherVisualizeDOM.ts
- └─> engine/launchers/launchPipeline.ts → creates a UnifiedAnalysisSession
- ├─> engine/utils/executePython.ts → spawns managed venv, runs python/main.py → JSON metrics
- ├─> src/babia_templates/ → validates dimension mapping, fills HTML template
+ └─> src/features/analysis/commands/... (per-mode command handlers)
+ └─> 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/...)
- ├─> engine/components/customComponents/*ComponentAsset.ts
+ ├─> scene-assets/*ComponentAsset.ts
│ → inlines browser runtimes from templates/components/**/*.js into the HTML
- └─> engine/servers/serverLaunchOrchestrator.ts (+ sessionServerManager)
- └─> src/servers/runtime (HTTP/HTTPS) serves the scene
- └─> registered in src/active_servers → shown in sidebar tree
-Live updates: engine/watchers/* detect file changes → re-run Python →
- engine/servers/sseNotificationManager.ts → src/servers/runtime/sse/SSEManager.ts → browser reloads data
+ └─> 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 →
+ src/core/server/sse/SSEManager.ts (by session id) → browser reloads data
```
-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, parser (`engine/parsers/`), and requirement rules (`engine/processors/requirementRules/`) that decide which artifacts must be generated.
+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`)
-1. `initializeExtensionContext` + `CodeXRLogger.initialize` (`src/core/`).
+1. `initializeExtensionContext`, `initializeHost(createVSCodeHost(context))` (#13: the core's host seam, see the module map), `setLaunchNotifier(launchNotifications)` (the post-launch toasts `core/server/multiServerLauncher.ts` shows, registered from `features/active-servers` so the core never imports a feature) and `setServerPanelCloser` (how `ServerControl` closes a stopped server's lateral panel, over `platform/webview/panelManager.ts`) and `CodeXRLogger.initialize` (`src/platform/`). The logger attaches the "CodeXR" output channel to the vscode-free log sink; everything logged before this (including at module load) was buffered by the sink and is flushed into the channel now.
2. Singletons initialized: `AnalysisConfigurationStorage`, `CollaborationProfileManager`, `RemoteAccessManager`, `ServerSettingsManager`, `getActiveServerRegistry()`, `ServerControl`.
-3. `ModularTreeDataProvider` (`src/views/ModularTreeDataProvider.ts`) registered as the single tree view `codexrTree` (one activity-bar container hosts all sections: servers, active servers, examples, visualize data, analyses, python env, visualization settings, learn more). **Collaboration is not a root section**: `CollaborationSectionProvider` is mounted by `ActiveServersSectionProvider` as the nested `COLLABORATION` group (item type `collaboration-group`), so its items — including `Join Remote Session` — render inside `ACTIVE SERVERS`.
-4. `registerAllCommands` (`src/commands/index.ts`) merges command arrays from every feature module and registers them via `CommandBuilder.registerAll`. **`assertUniqueCommandIds` throws on duplicate command IDs** — keep this in mind when adding commands.
-5. `StartupCoordinator` (`src/core/startup/startupCoordinator.ts`, max 3 concurrent) defers heavy work: restore server settings + ensure HTTPS cert pair, init `ServerWatcherIntegration`, init Python env + prefetch XR field schema, clean stale analysis artifacts.
+3. `ModularTreeDataProvider` (`src/app/sidebar/ModularTreeDataProvider.ts`) registered as the single tree view `codexrTree` (one activity-bar container hosts all sections: servers, active servers, examples, visualize data, analyses, python env, visualization settings, learn more). **Collaboration is not a root section**: `CollaborationSectionProvider` is mounted by `ActiveServersSectionProvider` as the nested `COLLABORATION` group (item type `collaboration-group`), so its items — including `Join Remote Session` — render inside `ACTIVE SERVERS`.
+4. `registerAllCommands` (`src/app/commands/registerAllCommands.ts`) merges command arrays from every feature module and registers them via `CommandBuilder.registerAll`. **`assertUniqueCommandIds` throws on duplicate command IDs** — keep this in mind when adding commands.
+5. `StartupCoordinator` (`src/app/startup/startupCoordinator.ts`, max 3 concurrent) defers heavy work: restore server settings + ensure HTTPS cert pair, init `ServerWatcherIntegration`, init Python env + prefetch XR field schema, clean stale analysis artifacts.
`deactivate()` tears down remote access, the active-server registry, the SSE manager + `fileToServerMap`, and the tree provider.
@@ -45,58 +50,83 @@ Three analysis modes share this pipeline: **XR** (A-Frame scene in browser/heads
| Module | Responsibility | Key files |
|---|---|---|
-| `code_analysis/` | **The core (246 files).** Analysis engine, sessions, watchers, Python backend, dependency + historical analysis | `engine/launchers/launcherXRAnalysis.ts`, `engine/core/analysisSession.ts`, `engine/orchestrator` → `analysisOrchestrator.ts` |
-| `code_analysis/engine/` | Pipeline: launchers, parsers, processors/requirement rules, session servers, watchers, component-asset injection | `launchPipeline.ts`, `servers/sessionServerManager.ts`, `watchers/sessionWatcherManager.ts`, `utils/executePython.ts` |
-| `code_analysis/python/` | Python analysis backend (see `PYTHON_ANALYSIS.md`) | `main.py`, `tools/lizard_analyzer.py`, `utils/xr_field_schema.py` |
-| `code_analysis/dependencies/` | Dependency-graph analysis service (see `docs/features/DEPENDENCY_GRAPH_XR.md`) | `DependencyGraphService` *[inferred name from docs]* |
-| `code_analysis/historical/` | Git history: comparator + Project Evolution | `gitRepositoryService.ts`, `historicalComparisonService.ts`, `projectEvolutionService.ts` |
-| `code_analysis/services/` | Cross-cutting services | `xrFieldSchemaService.ts`, `workspaceSnapshotService.ts`, `serverWatcherIntegration.ts` |
-| `babia_templates/` | Chart template system: registry, models, dimension validation, HTML placeholder processing | `registry/chartRegistry.ts`, `processing/dimensionValidator.ts`, `processing/templateHTMLProcessor.ts` |
-| `babia_examples/` | Bundled BabiaXR demo examples (tree section + launcher) | `runtime/exampleLauncher.ts` |
-| `servers/` | Server **infrastructure**: HTTP/HTTPS, ports, self-signed certs, SSE, collaboration/broadcast signaling | `runtime/httpServer.ts` (façade + composition root), `runtime/sse/SSEManager.ts`, `runtime/collaboration/collaborationRoomServer.ts` |
-| `servers/runtime/http/` | Response helpers (`httpRespond.ts`: free functions `sendJsonResponse`/`sendErrorResponse`/CORS/body reading) + `StaticAssetServer` (pages, MIME, traversal guard, no-store) | `httpRespond.ts`, `staticAssets.ts` |
-| `servers/runtime/remote/` | Remote pairing + authorization: `RemoteAccessPolicy` (request/WS auth, cookie-free allowlist) and `RemotePairingApi` (identity → pair → confirm → browser token exchange, guest page) | `remoteAccessPolicy.ts`, `remotePairingApi.ts`, `pairingPage.ts` |
-| `servers/runtime/collaboration/` | WebSocket room + session descriptor API (`CollaborationSessionApi`: descriptor, avatar model, room id) | `collaborationRoomServer.ts`, `collaborationSessionApi.ts` |
-| `servers/runtime/analysis/` | Analysis features behind the server: `AnalysisFeatureHost` (capability-gated service construction, refresh wiring, LivePanel SSE notifiers, dispose) + one bridge per feature + the room-message router. Bridges depend on the host; nothing here imports the façade | `analysisFeatureHost.ts`, `analysisMessageRouter.ts`, `dependencyGraphBridge.ts`, `historicalComparisonBridge.ts`, `projectEvolutionBridge.ts` |
-| `active_servers/` | Registry + lifecycle of **running** server instances (tree section, stop/open/copy-URL actions) | `registry/activeServerRegistry.ts`, `runtime/serverControl.ts` |
-| `views/` | The unified sidebar tree: one provider delegating to per-section providers | `ModularTreeDataProvider.ts`, `*/items/`, `*/interactions/` |
-| `commands/` | Central command registration aggregator | `index.ts` (`registerAllCommands`, `assertUniqueCommandIds`) |
-| `collaboration/` | Identity/profiles for collaborative sessions (names, avatars) | `CollaborationProfileManager` |
-| `remote_access/` | Cross-network sharing via pinned `cloudflared` Quick Tunnel | `cloudflaredBinaryManager`, `remoteAccessManager`, `remoteSessionAuthority` |
-| `python_env/` | Managed Python virtual environment (create/verify/reinstall + UI state) | `runtime/venvManager.ts` |
-| `visualize_data/` | User-driven "visualize your own JSON" flow | commands + launcher |
-| `visualization_settings/` | Visualization settings (colors, chart config) + color picker | storage + model |
-| `core/` | Extension context, logging, startup coordination | `extensionContext.ts`, `logging/logger.ts`, `startup/startupCoordinator.ts` |
-| `learn_more/` | "Learn more" help section in the tree | commands + views |
-| `utils/` | Shared helpers | `languageMetadata.ts`, `fileToServerMap.ts`, `commandBuilder.ts`, `errorHandler.ts`, `nonceGenerator.ts` |
-
-**Per-feature layout convention** (followed by most modules): `commands/` + `model(s)/` + `runtime/` or `services/` + `views/{items,interactions}` + `registry|storage|state/`. When adding a feature, mirror this pattern.
-
-Note: there is some historical duplication — e.g. `active_servers/views/` **and** `views/active_servers/`. The `src/views/` tree and `src/commands/index.ts` are the current *aggregation points*; per-module `views/`/`commands/` folders are the feature implementations they pull from. *[inferred from import wiring]*
+| `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`, `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` |
+| `core/history/` | Git history: comparator + Project Evolution. Both services compose a `GitAnalysisSessionContext` (catalogue, per-commit payload cache, analyze/exclude) and a `SingleJobGate` (one job at a time, last successful request); `gitAnalysisShared.ts` holds the pure helpers the export core shares | `gitRepositoryService.ts`, `historicalComparisonService.ts`, `projectEvolutionService.ts`, `gitAnalysisSessionContext.ts`, `gitAnalysisShared.ts` |
+| `core/charts/` | Chart template system: registry, models, dimension validation, HTML placeholder processing, the visualization configuration read by every launch | `chartRegistry.ts`, `chartModels.ts`, `xrFieldModels.ts`, `templateCharts.ts`, `chartPresentation.ts`, `getVisualizationConfiguration.ts` (lazy `require` of `settings/settingsAccessors.ts`), `processing/dimensionValidator.ts`, `processing/templateHTMLProcessor.ts`, `processing/templateProcessor.ts`, `processing/placeholders/` |
+| `features/examples/` | Bundled BabiaXR demo examples (tree section + launcher) | `services/exampleLauncher.ts`, `commands/babiaExamplesCommands.ts`, `commands/babiaExamplesCommandRegistrations.ts`, `model/babiaExampleModel.ts`, `views/BabiaExamplesSectionProvider.ts`, `views/babiaExamplesTreeView.ts`, `views/{exampleItems,babiaExampleItems}.ts`, `views/{handleExampleClicks,handleBabiaExampleClicks}.ts` (two factories and two click handlers: a duplication recorded for 1.3.0, src-layout.md §2.1) |
+| `core/server/` | Server **infrastructure**: HTTP/HTTPS, ports, self-signed certs, SSE, collaboration/broadcast signaling, server settings, the running-server registry and its control | `httpServer.ts` (façade + composition root), `httpsServerBase.ts` (state, port search, TLS wiring and delegation shared by `httpsCustomServer.ts`/`httpsDefaultServer.ts`; TLS literal in `httpsTlsOptions.ts`), `sse/SSEManager.ts`, `collaboration/collaborationRoomServer.ts`, `multiServerLauncher.ts` (launch orchestration; `serverFactory.ts` picks, builds and starts the server class; the toasts after a launch are in `features/active-servers/views/launchNotifications.ts`, the one allow-listed upward edge), `launchServerWithFile.ts` (was `servers/runtime/index.ts`), `serverControl.ts`, `serverSettingsManager.ts`, `networkUtils.ts`, `fileToServerMap.ts` |
+| `core/server/registry/` | The running-server registry (stays in core: the analysis engine, the server and two features use it) | `activeServerRegistry.ts`, `activeServerModel.ts`, `serverRegistrar.ts` |
+| `core/server/http/` | Response helpers (`httpRespond.ts`: free functions `sendJsonResponse`/`sendErrorResponse`/CORS/body reading) + `StaticAssetServer` (pages, MIME, traversal guard, no-store) | `httpRespond.ts`, `staticAssets.ts` |
+| `core/server/remote/` | Remote pairing + authorization: `RemoteAccessPolicy` (request/WS auth, cookie-free allowlist) and `RemotePairingApi` (identity → pair → confirm → browser token exchange, guest page) | `remoteAccessPolicy.ts`, `remotePairingApi.ts`, `pairingPage.ts` |
+| `core/server/ws/` | The WebSocket scaffold the room and the broadcast server share: one path on the shared server's `upgrade` event, authorize-or-destroy, detach; plus the wire constant `DEFAULT_ROOM_ID` | `webSocketEndpoint.ts` |
+| `core/server/collaboration/` | WebSocket room + session descriptor API (`CollaborationSessionApi`: descriptor, avatar model, room id). The room server (`collaborationRoomServer.ts`: connection lifecycle, message routing, membership and roles) is the façade over `roomRegistry.ts` (peer and room maps, broadcast), `roomSharedState.ts` (entities, locks, presence, presenter), `participantIdentity.ts` (names and avatar colours), `roomMessageCodec.ts` (parse/send/normalize) and `roomTypes.ts` | `collaborationRoomServer.ts`, `collaborationSessionApi.ts` |
+| `core/server/broadcast/` | Screen-broadcast signalling (sender/viewer roles, peer-to-peer negotiation, the media relay for viewers P2P cannot reach). The server (`screenBroadcastSignalingServer.ts`) is the façade over `relayPolicy.ts` (who is relayed, the audience told to the sender, per-viewer thinning thresholds), `mediaFrame.ts` (the relay wire format shared with the runtime: header constants, validation, header read) and `broadcastTypes.ts` | `screenBroadcastSignalingServer.ts` |
+| `core/server/analysis/` | Analysis features behind the server: `AnalysisFeatureHost` (capability-gated service construction, refresh wiring, LivePanel SSE notifiers, dispose) + one bridge per feature + the room-message router. Bridges depend on the host; nothing here imports the façade | `analysisFeatureHost.ts`, `analysisMessageRouter.ts`, `dependencyGraphBridge.ts`, `historicalComparisonBridge.ts`, `projectEvolutionBridge.ts`, `analysisBridgeReplies.ts` (the git bridges' shared reference and error replies) |
+| `features/active-servers/` | The ACTIVE SERVERS section: the **running** servers' tree and actions (stop/open/copy-URL), the preview renderer and the launch toasts; the registry and `serverControl.ts` are in `core/server/` | `views/ActiveServersSectionProvider.ts`, `views/activeServerItems.ts`, `views/handleServerActions.ts` (the tree's server actions; the dialog text is in `serverDetailsFormat.ts`), `views/launchNotifications.ts`, `services/serverOpenActions.ts` (open a registered server in the browser or the panel; used by the tree actions and the launch notifications), `services/withServer.ts` (the unknown-id guard every server action shares), `services/previewRenderer.ts`, `commands/activeServersCommands.ts`, `commands/activeServersCommandRegistrations.ts` |
+| `features/servers/` | The SERVERS section: server configuration commands and tree | `commands/serverCommands.ts`, `commands/serverCommandRegistrations.ts`, `views/ServersSectionProvider.ts`, `views/serverItems.ts`, `views/configurationItems.ts`, `views/handleConfigurationClicks.ts` |
+| `app/` | The composition root under `extension.ts`: the one command aggregator, the unified sidebar tree and the deferred startup work. The only layer that may import every feature | `commands/registerAllCommands.ts` (`registerAllCommands`; `assertUniqueCommandIds` is in `platform/commands/commandRegistry.ts`), `commands/generalCommands.ts`, `sidebar/ModularTreeDataProvider.ts` (section-item bridge table with the eight lazy `require()`s), `sidebar/sectionDefinitions.ts` (the eight root sections), `sidebar/sectionChild.ts`, `sidebar/commonCommands.ts`, `startup/startupCoordinator.ts` |
+| `core/collaboration/` | Identity/profiles for collaborative sessions (names, avatars), used by the server and two features | `collaborationProfileManager.ts`, `collaborationProfile.ts`, `anonymousName.ts`, `connectedParticipant.ts` |
+| `features/collaboration/` | The collaboration commands and the COLLABORATION tree group (nested inside ACTIVE SERVERS) | `commands/collaborationCommands.ts`, `views/CollaborationSectionProvider.ts`, `views/collaborationItems.ts` |
+| `core/metrics/` | Per-function metrics and the checks built on them, shared with the Code-XR IDE (#173, #178): pure, vscode-free and import-free logic (the IDE also loads it in its sandboxed renderer) plus a host-neutral tracker that runs the backend's `functions` mode after a folder's analysis and re-measures changed files. The extension's adapter is `features/metrics-in-editor/` (diagnostics, CodeLens, decorations), fed by `core/analysis/analysisEvents.ts` | `functionMetrics.ts`, `functionMetricsTracker.ts` |
+| `core/remote-access/` | Cross-network sharing via pinned `cloudflared` Quick Tunnel (no sidebar section of its own) | `cloudflaredBinaryManager.ts`, `remoteAccessManager.ts`, `remoteSessionAuthority.ts`, `remoteAccessModel.ts` |
+| `core/python-env/` | Managed Python virtual environment (create/verify/reinstall + UI state); used by the analysis engine and the git export | `venvManager.ts`, `pythonPackageManifest.ts`, `pythonEnvStorage.ts`, `pythonEnvUtils.ts`, `pythonEnvUiState.ts` |
+| `features/python-env/` | The Python-environment commands and sidebar section | `commands/pythonEnvCommands.ts`, `commands/pythonEnvCommandRegistrations.ts`, `views/PythonEnvSectionProvider.ts`, `views/pythonEnvItems.ts` |
+| `features/visualize-data/` | User-driven "visualize your own JSON" flow | `commands/visualizeDataCommands.ts`, `commands/visualizeDataCommandRegistrations.ts`, `model/visualizeDataModel.ts`, `model/visualizeDataState.ts`, `services/visualizationLauncher.ts`, `services/visualizationRestorer.ts`, `services/jsonFieldAnalyzer.ts`, `views/VisualizeDataSectionProvider.ts`, `views/visualizeDataItems.ts` (item factory), `views/visualizeDataSectionItems.ts` (section adapter) |
+| `core/host/` | **The host seam (#13, epic #11).** `CodeXRHost`: what the core needs from the application it runs in (paths, key-value state, notifications and consent, progress, prompt, clipboard, external URLs, workspace folders, UI signals), so the same core can run in the VS Code extension and in the Code-XR IDE (`apps/ide`). vscode-free, checked by `test/host/codeXRHost.test.cjs`. `hostRegistry.ts` holds the one host (`initializeHost`/`getHost`/`resetHostForTests`). `hostPaths.ts` bridges a still-unmigrated module's `ExtensionContext` to `HostPaths` (`hostPathsFromContext`) and holds the single private-storage rule (`privateStorageRoot`). The VS Code adapter is `app/host/vscodeHost.ts` (`createVSCodeHost`). Since #13 step 9 no file under `core/` reaches `vscode` (guarded by `codeXRHost.test.cjs`); core modules take `CoreContext` (`hostPaths.ts`) where they used to take `vscode.ExtensionContext` (docs/ide/vscode-api-inventory.md §4.2) | `codeXRHost.ts`, `hostRegistry.ts`, `hostPaths.ts` |
+| `core/charts/settings/` | The visualization-settings store (palette, environment, colours) that the chart pipeline reads | `settingsModel.ts`, `settingsStorage.ts`, `settingsFile.ts`, `settingsAccessors.ts` |
+| `features/visualization-settings/` | The visualization-settings commands, sidebar section and colour picker | `commands/visualizationSettingsCommands.ts`, `commands/visualizationSettingsCommandRegistrations.ts`, `views/VisualizationSettingsSectionProvider.ts`, `views/visualizationSettingsItems.ts` (item factory), `views/visualizationSettingsSectionItems.ts` (section adapter), `views/handleSettingsInteraction.ts`, `views/colorPickerUtils.ts`, `views/dynamicColorIconGenerator.ts` |
+| `platform/` | Extension-host plumbing with no feature knowledge (the layer `docs/cleanup/src-layout.md` proposes; filled as files move) | `extensionContext.ts`, `logging/sink.ts` (vscode-free: `getLogger(scope)`, pre-activation buffer, console fallback), `logging/logger.ts` (attaches the output channel, tracks `codeXR.debug.verboseLogs`), `logging/logPolicy.ts`, `templatePaths.ts` (`resolveTemplatePath`), `commands/commandRegistry.ts` (`ExtensionCommandRegistration`, `assertUniqueCommandIds`: the pure command model every feature imports), `commands/commandBuilder.ts`, `tree/baseInterfaces.ts` (the section-provider contract every sidebar section implements), `ui/errorHandler.ts`, `ui/detailDialog.ts`, `webview/panelManager.ts` (the `serverId → WebviewPanel` registry) |
+| `shared/` | Helpers with no VS Code and no domain | `nonceGenerator.ts` |
+| `features/learn-more/` | "Learn more" help section in the tree | `commands/learnMoreCommands.ts`, `commands/learnMoreCommandRegistrations.ts`, `views/LearnMoreSectionProvider.ts`, `views/learnMoreItems.ts`, `views/handleLearnMoreClicks.ts` |
+
+**Layout** (story #55, `docs/cleanup/src-layout.md` §3; pinned by `test/tooling/srcLayout.test.cjs`): `src/` holds `extension.ts` and five layers, `app/` (composition root) → `features/` (one folder per sidebar section) → `core/` (the engine, one folder per domain) → `platform/` (VS Code host plumbing, no feature knowledge) → `shared/` (no VS Code, no domain). Folder names are kebab-case; `core/` and `features/` hold folders only; there are no re-export barrels.
+
+**Per-feature layout convention**: `features//` has `commands/` (`Commands.ts`, the handlers, and `CommandRegistrations.ts`, the registration array `app/commands/registerAllCommands.ts` collects), `views/` (the `*SectionProvider.ts`, item factories and click handlers, flat), and where needed `services/` and `model/`. A section with subsections nests them under `sections//` (see `features/analysis/`). Engine code that more than one feature, the servers or the analysis pipeline uses goes in `core//`, not in a feature. When adding a feature, mirror this pattern.
+
+**Folder dependencies** (stories #42, #55): which folder may import which is data in `test/tooling/folderDependencies.json`, checked by `test/tooling/dependencyDirection.test.cjs` (type imports count). A folder is the first directory under `src/`, or the first two under `core/` and `features/` (`twoLevelAreas`); the same file holds the layer order `app → features → core → platform → shared` (`layers`), which the test enforces (no upward edge, no feature importing another feature) except for the reasoned entries in `layerExceptions`. A new cross-folder direction fails the gate until it is added there; a new two-way pair also needs a written reason. The remaining pairs are each documented in that file (all inside the server/analysis subsystems: `core/server`, `core/remote-access`, `core/analysis` with `core/history`, plus `core/server`/`features/active-servers`, which is the one allow-listed upward edge). `platform/` imports no feature folder, and `core/` none besides that edge.
+
+**Barrel policy** (decided 2026-09-18, measured): 82% of the relative imports in `src/` (807 of 981) already name a concrete file, and 32 of the 82 `index.ts` barrels have no importer at all. So: **import the concrete file; do not add a barrel "for symmetry"**. An unimported barrel is dead code and keeps otherwise-dead modules looking referenced. Story #55 (batch 0) dissolved every re-export barrel that was left: `src/` has none, and the two `index.ts` files that held code are renamed in the move.
+
+**Export convention**: export what another file or a test consumes. A symbol used only inside its own file does not need `export`; an exported symbol with no consumer anywhere in `src/` **and** `test/` is dead (tests load compiled code from `out/`, so a test-only consumer counts as a consumer).
+
+Note: before #55 a feature was split between a feature folder and `views//` (e.g. `active_servers/views/` **and** `views/active_servers/`); the moves put both halves in `features//views/`. `src/app/sidebar/` and `src/app/commands/registerAllCommands.ts` are the current *aggregation points*; per-module `views/`/`commands/` folders are the feature implementations they pull from. *[inferred from import wiring]*
## Cross-module contracts (the seams that matter)
-1. **XR field schema**: Python defines analyzable fields in `code_analysis/python/utils/xr_field_schema.py`; TypeScript consumes it via `code_analysis/services/xrFieldSchemaService.ts` (backed by `main.py --mode schema`). Dimension-mapping validation in `babia_templates/processing/dimensionValidator.ts` checks user mappings against this schema. **Changing metrics on the Python side requires keeping this schema in sync.**
-2. **Chart registry**: `babia_templates/registry/chartRegistry.ts` (`BabiaChartRegistry` singleton) is the source of truth for available chart types and their dimension requirements.
-3. **File ↔ server mapping**: `src/utils/fileToServerMap.ts` links analyzed files to the server instance serving their visualization; SSE clients are keyed by file URI in `SSEManager`.
-4. **Component-asset injection**: TS files in `code_analysis/engine/components/customComponents/*ComponentAsset.ts` read runtime JS from `templates/components/` and inline it into generated HTML. The browser runtimes never import TS code; the contract is the injected globals and entity schemas (see `templates/components/COMPONENTS.md`).
-5. **Command registration**: every module exports a command-registration array consumed by `src/commands/index.ts`. Command IDs use prefixes `codeXR.*` / `codexr.*` (both exist — check before adding).
+1. **XR field schema**: Python defines analyzable fields in `backend/src/utils/xr_field_schema.py`; TypeScript consumes it via `core/analysis/python/xrFieldSchemaService.ts` (backed by `main.py --mode schema`). Dimension-mapping validation in `core/charts/processing/dimensionValidator.ts` checks user mappings against this schema. **Changing metrics on the Python side requires keeping this schema in sync.**
+2. **Chart registry**: `core/charts/chartRegistry.ts` (`BabiaChartRegistry` singleton) is the source of truth for available chart types and their dimension requirements.
+3. **File ↔ server mapping**: `src/core/server/fileToServerMap.ts` links analyzed files to the server instance serving their visualization; SSE clients are keyed by file URI in `SSEManager`.
+4. **Component-asset injection**: TS files in `core/analysis/scene-assets/*ComponentAsset.ts` read runtime JS from `templates/components/` and inline it into generated HTML. A runtime shipped as one file is a row of the `SINGLE_FILE_RUNTIME_ASSETS` descriptor table in `scene-assets/singleFileRuntimeAssets.ts` (output name, folder, refusal label), and its `*ComponentAsset.ts` is a thin wrapper keeping the named exports; multi-part runtimes go through `runtimeAssembly.ts`. The browser runtimes never import TS code; the contract is the injected globals and entity schemas (see `templates/components/COMPONENTS.md`).
+5. **Command registration**: every module exports a command-registration array consumed by `src/app/commands/registerAllCommands.ts`. Command IDs use prefixes `codeXR.*` / `codexr.*` (both exist — check before adding).
+
+## Logging (since 1.2.1)
+
+Every diagnostic of the extension host goes through `src/platform/logging`. A module logs with `const logger = getLogger('SCOPE')` from `platform/logging/sink.ts`, which has no `vscode` import, so any module (and any unit test that loads it from `out/` without the fake vscode) can log. Lines land in the **CodeXR** output channel as `[ISO time] [LEVEL] [SCOPE] message`, with an optional metadata line (an Error's stack, a string, or JSON).
+
+- **Levels.** `warn` and `error` are always written. `debug` and `info` are written only in development mode or with `codeXR.debug.verboseLogs` on (`logPolicy.ts`). Anything carrying a file system path is `debug`, passed lazily (`logger.debug(() => ...)`), so it costs nothing while verbose logging is off. A caught failure is reported at `warn` or `error`, never only at `debug`.
+- **Before activation** the sink keeps up to 1,000 lines in a buffer and flushes them through the level policy when `CodeXRLogger.initialize` attaches the channel; while no channel is attached (and after it is disposed), `warn`/`error` are also echoed to the console.
+- **No `console.*` in `src/`.** ESLint's `no-console` is an error for `src/**/*.ts`; `sink.ts` is the only allowlisted file (its console fallback). Browser runtimes under `templates/` are not extension-host code and keep their own (gated) console output.
+- `observeLogEntries` on the sink is a test seam: characterization suites record what a module logs (`test/helpers/logCapture.cjs`). Nothing in the extension observes.
## Repo-root layers (outside `src/`)
| Path | What it is |
|---|---|
-| `templates/` | Raw HTML templates + **browser-side JS runtimes**. `xr/` (scene templates + SSE client scripts), `analysis_livePanel/` (webview panels), `components/` (A-Frame component runtimes — see `templates/components/COMPONENTS.md`; `components/livepanel/` holds shared 2D LivePanel components such as `dataTable.{js,css}` that `LivePanelParser` bundles ahead of each panel's own `main.js`/`style.css`), `utils/color-picker.html`. Copied into `dist/templates` at build. |
-| `test/` | All tests. `.test.cjs` unit suites (Node native runner), Python suites, language fixtures, manual HTML harnesses. See `DEVELOPMENT.md`. |
+| `templates/` | Raw HTML templates + **browser-side JS runtimes**. `xr/` (scene templates + SSE client scripts), `analysis_livePanel/` (webview panels), `components/` (A-Frame component runtimes — see `templates/components/COMPONENTS.md`; `components/livepanel/` holds shared 2D LivePanel components such as `dataTable.{js,css}` that `LivePanelParser` bundles ahead of each panel's own `main.js`/`style.css`), `utils/color-picker.html`. Read in place at `/templates` and shipped by the `files` allowlist; not copied into `dist/` since 1.2.1. Source code builds every template path with `resolveTemplatePath(extensionPath, …)` (`src/platform/templatePaths.ts`), never from `__dirname` (wrong from the bundle); tests use `test/helpers/templatesRoot.cjs`. |
+| `test/` | The extension's tests: `.test.cjs` unit suites (Node native runner), the feature baseline, the tooling ratchet, manual HTML harnesses. The Python suites, fixtures and per-language corpus live in `backend/tests/` and `backend/manual_test/`. See `DEVELOPMENT.md`. |
| `resources/` | Icons and media (per-language icons, collaboration/comparison/screen assets). |
| `examples/` | Bundled sample charts + data for the Babia Examples tree section. |
-| `scripts/` | Build utilities: `package-vsix.mjs`, `prepare-dev-extension.mjs`, `report-manual-metrics.py`. |
-| `docs/` | Human-facing feature docs (**shipped in the VSIX** via package.json `files`). |
-| `manual_test/` | Per-language fixtures for `npm run test:analysis` (see its README). |
-| `pages/` | GitHub Pages redirect page (deployed by the only CI workflow). |
+| `scripts/` | Build utilities: `package-vsix.mjs`, `prepare-dev-extension.mjs` (the manual-metrics report tool is `backend/scripts/report-manual-metrics.py`). |
+| `docs/` | Human-facing feature docs, linked from the README (vsce rewrites those links to GitHub). Not shipped in the VSIX since 1.2.1. |
+| `backend/manual_test/` | Per-language fixtures for `npm run test:analysis` (see its README); outside this package since 1.2.1. |
+| `pages/` | GitHub Pages redirect page (deployed by `.github/workflows/deploy-pages-redirect.yml`; the gates run in `ci.yml`). |
## How future agents should use this document
-- Use the module map to jump straight to the right folder instead of scanning `src/` (`code_analysis/` alone is 246 files).
+- Use the module map to jump straight to the right folder instead of scanning `src/` (`core/analysis/` and `features/analysis/` together are about 120 files).
- Use the "cross-module contracts" section to know what else must change when you touch a seam (especially Python metrics ↔ field schema ↔ dimension validation).
- For feature-specific depth (dependency graph, historical comparison, project evolution, remote access), read the existing docs in `docs/` — this file deliberately does not duplicate them. See `INDEX.md` for the task → docs mapping.
diff --git a/.claude/docs/DEVELOPMENT.md b/.claude/docs/DEVELOPMENT.md
index 30220d4cd..537cd8389 100644
--- a/.claude/docs/DEVELOPMENT.md
+++ b/.claude/docs/DEVELOPMENT.md
@@ -2,38 +2,53 @@
> **Purpose**: Build, test, run and package the extension. Read this before running any command or claiming a change "works".
> **Stability**: Stable — update when scripts, launch configs, or test layers change.
-> Verified against `package.json`, `.vscode/launch.json`, `.vscode/tasks.json` and `test/runners/` on 2026-07-08.
+> Verified against `package.json`, `.vscode/launch.json`, `.vscode/tasks.json` and `test/runners/` on 2026-07-08; scripts, paths and the test layout re-verified on 2026-11-25 (story #43).
+
+> **Monorepo (2026-11-25):** run `npm ci` and every `npm run …` from the repository root; scripts delegate to the `code-xr` workspace in `apps/vscode-extension/`, where the paths below live (the Python backend is `backend/src/`, its tests `backend/tests/`). See `docs/monorepo.md`.
## Environment
- **Platform**: developed on Windows 11; npm scripts deliberately call tool binaries via `node ./node_modules//bin/...` instead of bare CLI names (Windows robustness). Keep that style when adding scripts.
-- **Requirements**: VS Code ≥ 1.98.0, Node.js 16+, Python 3.7+ (the extension creates and manages its own venv — see `PYTHON_ANALYSIS.md`).
-- **Git**: work happens on branch `v1.2.0`; `master` is the default/PR target. Expect CRLF warnings from git on this machine — they are noise, but be aware `git status` may list files whose only difference is line endings.
+- **Requirements**: VS Code ≥ 1.98.0, **Node.js 24** (pinned in `.nvmrc`, which CI reads; the unit runner passes `--test-isolation=none`, which older Node versions do not have), Python 3.7+ (the extension creates and manages its own venv — see `PYTHON_ANALYSIS.md`).
+- **Git**: work happens on branch `v1.2.1`; `master` is the default/PR target. Expect CRLF warnings from git on this machine — they are noise, but be aware `git status` may list files whose only difference is line endings.
## npm scripts
| Script | What it does | When to use |
|---|---|---|
-| `npm run compile` | webpack build → `dist/extension.js` (+ CopyPlugin copies `src/code_analysis/python`, `templates/`, `examples/` into `dist/`) | Before F5 "workspace direct"; quick build check |
+| `npm run compile` | webpack build → `dist/extension.js` (+ CopyPlugin copies `/backend/src` into `dist/code_analysis/python`; `templates/` and `examples/` ship as they are, not copied, since 1.2.1) | Before F5 "workspace direct"; quick build check |
| `npm run compile:dev-host` | `compile` + `scripts/prepare-dev-extension.mjs` → stages an isolated dev copy under `.vscode-test/dev-extension` | Used automatically by the primary F5 launch config |
| `npm run watch` | webpack watch mode | Iterating on TS changes |
-| `npm run typecheck` | `tsc --noEmit` (non-incremental) over the whole project | Fast correctness gate; part of `test:basic` |
-| `npm run lint` | ESLint (flat config, `eslint.config.mjs`) over `src/` | Part of `test:basic`; rules are mostly "warn" |
-| `npm test` = `npm run test:basic` | `typecheck` + `lint` + `compile-tests` (tsc → `out/`) + `test:unit` | **The default gate. Run before declaring any change done.** |
-| `npm run test:unit` | `test/runners/run-node-tests.cjs` → collects `test/**/*.test.cjs`, runs `node --test --test-isolation=none --test-concurrency=1` | Unit/runtime tests only (fast) |
-| `npm run test:python` | `test/runners/run-python-tests.cjs` → Python suites under `test/python/` | After touching `src/code_analysis/python/` |
+| `npm run typecheck` | `tsc --noEmit` (non-incremental) over the whole project with `tsconfig.check.json`, which extends `tsconfig.json` and adds `noUnusedLocals`, `noFallthroughCasesInSwitch`, `noImplicitReturns` and `noUnusedParameters` (an unused parameter kept for a signature is named `_x`). `compile`, `compile-tests` and webpack stay on `tsconfig.json`, so an unused symbol fails the gate but never the F5 build. Then a second pass, `tsconfig.tooling.json`: `checkJs` over `scripts/*.mjs`, `webpack.config.js` and `eslint.config.mjs` (strict except `noImplicitAny`; a JSDoc `@type` is the fix for a finding there) | Fast correctness gate; part of `test:basic` |
+| `npm run lint` | ESLint (flat config, `eslint.config.mjs`) over explicit roots — `src/`, `test/`, `scripts/`, `templates/`, `webpack.config.js`, `eslint.config.mjs` — with a `--max-warnings` budget (the number in the script). The roots are listed rather than `eslint .`, so the scope is reviewable in the diff | Part of `test:basic` (~7 s: the type-aware block builds the TypeScript program). Style and unused-symbol rules are errors (Node-side JS also gets `no-undef` and `no-eval`). The standalone `templates/` runtimes get a relaxed browser block (classic scripts: top-level names are page globals, `== null` is allowed; the LivePanel page's shared globals are listed in the config); the multi-part runtime directories (`templates/components/codexr/*/*Runtime/`) are ignored, because a part does not parse on its own; `no-console` is an error over `src/**/*.ts` with the log sink (`src/platform/logging/sink.ts`) as the only allowlisted file (extension diagnostics go through the logger, see ARCHITECTURE.md "Logging"); the warn-only budget rules, all on `src/` (`no-explicit-any`; `complexity` 15, `max-depth` 4, `max-params` 5, `max-lines-per-function` 80, `max-lines` 600; type-aware `no-misused-promises`), count toward the budget, which is recorded in the guardrail baseline (`eslint.maxWarnings`) and only ever lowered: when a cleanup removes warnings, lower the number in the script and run `guardrails:update`. The type-aware `no-floating-promises` (with `checkThenables`) is an **error** since v1.2.1 T56-T59: await the promise, or mark a deliberate fire-and-forget with `void` |
+| `npm run compile-tests` | Removes `out/`, then `tsc -p . --outDir out`. Starting empty matters: tsc never deletes output for a source that is gone, so a module deleted from `src/` would keep a compiled twin the suites still load | Part of `test:basic` |
+| `npm run watch-tests` | `tsc -p . -w --outDir out`: keeps `out/` current while iterating on tests (the runner's stale-output check is per file, so this stays valid) | Iterating with `npm run test:unit` |
+| `npm test` = `npm run test:basic` | `typecheck` + `lint` + `compile-tests` (tsc → `out/`) + `test:unit`. Needs **no** webpack build. At the root it then runs `ide:test` | **The default gate. Run before declaring any change done.** |
+| `npm run ide:test` / `ide:dev` / `ide:build` / `ide:start` / `ide:smoke` (root only; workspace `code-xr-ide`) | The Code-XR IDE (`apps/ide`, epic #11). `ide:test`: `tsc` over `tsconfig.node.json` and `tsconfig.web.json` + ESLint with `--max-warnings 0` + `node --test` over `apps/ide/test/**/*.test.ts` (Node's type stripping, no compile step); the root `npm test` runs it after the extension gate. `ide:dev`: Vite dev server + Electron restart on main/preload changes. `ide:smoke`: build, launch hidden with `--codexr-smoke`, assert the security baseline from inside the real window (CI job `ide-smoke` on the three OSes; Linux needs `xvfb-run -a`). Details: `apps/ide/README.md` | After touching `apps/ide/` |
+| `npm run test:unit` | `test/runners/run-node-tests.cjs` → first refuses to start if `out/` does not match `src/` (a source newer than its output, an uncompiled source, or a compiled file whose source is gone), then collects `test/**/*.test.cjs` and runs `node --test --test-isolation=none --test-concurrency=1` — **every suite in one process**, so a test must never leave global state behind | Unit/runtime tests only (fast) |
+| `npm run test:python` (root `test:backend` runs the same file directly) | `backend/scripts/run-python-tests.cjs` → `unittest discover` over `backend/tests/`. A test folder **needs an `__init__.py`** or discovery skips it silently. With no interpreter it skips locally and **fails under `CI`** | After touching `backend/src/` |
+| `npm run lint:python` (root only) | `backend/scripts/run-ruff.cjs` → `ruff check` in `backend/` with `backend/ruff.toml`: pyflakes (`F`) plus the pycodestyle error classes `E4`/`E7`/`E9` and the modernization lock-ins of story #56 (`E722`, `UP004`, `UP008`, `UP031`, `UP032`, and `FA100`/`UP006`/`UP007`/`UP037`/`UP045`: builtin generics in annotations behind `from __future__ import annotations`, and `UP012`/`UP015`/`RUF010`; `docs/cleanup/modernization.md`), target Python 3.7, fixture corpora (`manual_test/`, `tests/fixtures/`) excluded, `E402` ignored per file (with the reason) where a module bootstraps `sys.path` before its imports. **Lint only — no formatter, no isort**: tests pin import lines and statement order. Ruff is pinned in `backend/requirements-dev.txt` (`python -m pip install -r backend/requirements-dev.txt`); a missing ruff is a failure, never a skip | After touching `backend/` |
| `npm run test:all` | `test:basic` + `test:python` | Pre-release / after cross-language changes |
-| `npm run test:analysis` | `test/runners/run-analysis-tests.cjs` over `manual_test/` fixtures (one per supported language); asserts XR and LivePanel produce the same `data.json` | After changing analysis output or language support |
-| `npm run test:htmlanalysis` | HTML/DOM analysis tests | After touching `python/html/html_dom_parser.py` or DOM mode |
+| `npm run test:analysis` | `backend/scripts/run-analysis-tests.cjs` (venv in `backend/artifacts/analysis-test-venv`) over the `backend/manual_test/` fixtures (one per supported language); asserts XR and LivePanel produce the same `data.json`. Its venv installs the **lizard version the extension pins** (read from `backend/requirements.txt`, the generated mirror of `pythonPackageManifest.ts`) | After changing analysis output or language support |
+| `npm run test:htmlanalysis` | `test/runners/run-html-analysis-tests.cjs`: `test/analysis/livePanelDomIntegration.test.cjs` plus the Python suite `backend/tests/html_dom/` | After touching `backend/src/html/html_dom_parser.py` or DOM mode |
+| `npm run test:core-smoke` | `test/runners/run-core-smoke.cjs`: loads the compiled core from `out/` with `vscode` unresolvable, registers a stub `CodeXRHost` and runs one LivePanel file analysis through `ExecutePython` (#13). Needs `compile-tests` and the venv of `test:analysis`; downloads nothing | After touching `core/host`, `executePython.ts` or anything the core imports |
| `npm run test:xr-harness` | `test/runners/run-xr-containment-harness.cjs` (browser harness, uses Playwright) | After touching table/containment runtimes |
-| `npm run test:project-evolution-harness` | Project Evolution playback harness | After touching project-evolution runtime |
+| `npm run test:xr-chart-bounds-harness` | `test/runners/run-xr-chart-bounds-harness.cjs` (generates REAL directory scenes with the compiled generator, opens them with A-Frame + BabiaXR in Playwright, asserts every chart type ends on the table for 3/30/300 files and that row-budgeted charts only ever read the slice; `CODEXR_CHART_BOUNDS_TYPES` / `CODEXR_CHART_BOUNDS_ROWS` narrow it; about 4 minutes) | After touching chart generation, containment, the row slice or the Babia compatibility patches |
+| `npm run test:xr-mode-harness` | `test/runners/run-xr-mode-cycle-harness.cjs` — static contract over `test/manual/xr-mode-cycle-harness.html`, then (with Playwright) walks the analysis selector through every mode and back, asserting the controller's view/mode state at each step. Then four dependency-graph scenarios (DEPGRAPH-12): drill-down plus late-joiner reload, a 900-node project past the render budget, worker balance over three enter/leave cycles, and entering while a refresh runs; a scenario sets the room entity with `window.__DEP_STATE` and reads the page's requests from `CodeXRHarness.sent`. Served over HTTP (`test/helpers/staticHttpServer.cjs`), so the modes' datasets really load; from `file://` Chromium blocked every fetch | After touching the analysis-mode controller, mapping UI, historical comparison or dependency graph runtimes |
+| `npm run test:project-evolution-harness` | `test/runners/run-project-evolution-harness.cjs` — Project Evolution playback harness (screenshots under `output/project-evolution-harness/`) | After touching project-evolution runtime |
| `npm run test:xr-immersive-harness` | `test/runners/run-xr-immersive-harness.cjs` — AR/VR semantics against real A-Frame: AR hide/keep sets, rig floor-align + AR recenter, pointer handover; plus a static contract over both scene templates | After touching the scene templates, pointer-policy or immersive-rig |
+| `npm run test:xr-panel-placement-harness` | `test/runners/run-xr-panel-placement-harness.cjs` — real room, virtual screens, guide and multi-screen manager: Bring default + Bring guide leave both visible, Bring next to a wall stays in the room, and the common runtime's `resolvePanelPlacement` (evolution overlay, controller panel) avoids the chart volume, occlusion and the walls (#103) | After touching screen placement (`placementRegistry.js`) or `resolvePanelPlacement` |
+| `npm run test:harnesses` | The six browser harnesses in a row (`test:xr-harness`, `test:xr-chart-bounds-harness`, `test:xr-mode-harness`, `test:xr-immersive-harness`, `test:project-evolution-harness`, `test:xr-panel-placement-harness`). Offline: `test/helpers/harnessBrowser.cjs` serves the CDN scene libraries from `test/vendor/scene-libraries/` (byte-identical releases with their licences) and aborts every other non-local request, so a harness never depends on a CDN being up. Needs Playwright's Chromium (`npx playwright install chromium`) | After touching any scene runtime; CI runs it in the `harnesses` job on Ubuntu |
| `npm run package` | Production webpack build (hidden source maps) | Pre-packaging |
-| `npm run package:vsix` | `package` + `scripts/package-vsix.mjs` → builds the `.vsix` | Release preparation |
-| `npm run test:integration` | `@vscode/test-cli` — **currently targets `out/test/**/*.test.js`, which doesn't exist; the integration layer is unpopulated** | Don't rely on it (needs verification/setup) |
+| `npm run package:vsix` | `package` + `scripts/package-vsix.mjs` → builds the `.vsix` (refuses to package without `dist/extension.js`) | Release preparation |
+| `node scripts/dist-fingerprint.mjs --out ` · `node scripts/dist-diff.mjs --expect-identical-bundle` | Hash everything under `dist/` and compare two fingerprints. **H1**: an unreachable file was deleted ⇒ `extension.js` byte-identical (the production build is deterministic). `--allow-removed ` names copied assets that are meant to disappear. **H2**: `--bundle-lines ` for a dead declaration removed from a live file | Proving a cleanup commit changed nothing that ships (`cleanup` skill §3) |
+| `node scripts/vsix-listing.mjs [--vsix ] [--out ]` | Reads the built VSIX's zip directory (Node builtins) and checks it: required entries (`dist/extension.js`, the Python `main.py`, `templates/`, `examples/`, the icon, README/CHANGELOG/LICENSE) present; source maps, TypeScript sources, Python bytecode, build configs, `src/`/`test/`/`node_modules/`… absent. Exits 1 on any violation | After `npm run package:vsix`; CI runs it in the package job |
| `npm run report:manual-metrics` | analysis test runner in report-only mode | Metric reports without assertions |
+| `npm run guardrails:measure` | `test/tooling/measureGuardrails.cjs` — prints the cleanup metrics from the TypeScript AST (~2 s): `console.*` per module, console-only catch blocks, `any`, suppressions, files over 500 lines, functions over 80 lines, CCN over 10/15/20/30, modules unreachable from `src/extension.ts`, `console.log` in `templates/`, the lint `--max-warnings` | Before and after any cleanup item |
+| `npm run guardrails:update` | Same script with `--write`: regenerates `test/tooling/guardrail-baseline.json`. For a commit that moves files, pass the move map: `npm run guardrails:update -- --renamed ../../docs/cleanup/src-move-map.json` re-keys the committed baseline through it (paths at their new location, per-module counts regrouped from the per-file ones), so a pure move reports no change and needs no waiver. `console.byModule` / `any.byModule` group by the first folder under `src/`, or the first two under `src/core/` and `src/features/` | In the **same commit** as a change that moves a metric — the baseline diff is that item's recorded before/after |
+| `npm run python:requirements` | `compile-tests` + `test/tooling/pythonRequirements.cjs --write`: regenerates `backend/requirements.txt` from `CODEXR_PYTHON_PACKAGES` in `src/core/python-env/pythonPackageManifest.ts` (the source of truth); `test/python_env/pythonRequirements.test.cjs` fails while the two disagree | In the same commit as any change to the Python package pins |
-**Test framework note**: unit tests are **`.test.cjs` files run by Node's native test runner** (`node --test`), *not* Mocha, despite `@types/mocha` being present (that belongs to the unpopulated integration layer). New unit tests go in `test//*.test.cjs`.
+**Test framework note**: unit tests are **`.test.cjs` files run by Node's native test runner** (`node --test`), *not* Mocha (there is no Mocha in the dependency tree). New unit tests go in `test//*.test.cjs`.
## Running the extension (F5)
@@ -48,34 +63,49 @@ Manual validation flow for a change: F5 → open a workspace with source files
```
test/
-├── analysis/ ~33 .test.cjs suites — runtimes (common, boats, visual style, charts,
-│ tables, mapping), collaboration, historical, dependency graph, watchers…
-│ + manual_metrics_suite.py
-├── commands/ commandRegistry.test.cjs (unique-ID and registration checks)
+├── analysis/ 80 .test.cjs suites — runtimes (common, boats, charts, tables, mapping),
+│ collaboration, historical, dependency graph, export, watchers…
+├── commands/ commandRegistry.test.cjs (unique-ID checks on synthetic arrays) +
+│ commandContributions.test.cjs: executes the REAL registerAllCommands under the
+│ fake vscode and ties it to package.json; internalCommandIds.cjs lists every
+│ registered-but-uncontributed command with how it is reached
├── directory_analysis/ directory-mode tests
-├── logging/, python_env/, servers/, startup/ focused suites per subsystem
-├── python/ pytest-style suites (dependencies, scanning, html_dom, xr schema…)
-├── fixtures/dependency-languages/ sample sources in ~25 languages
+├── logging/, python_env/, servers/, startup/, collaboration/, packaging/, utils/, views/,
+│ visualize_data/, visualization_settings/ focused suites per subsystem
+│ (126 .test.cjs files in all, 1,064 tests at the end of 1.2.1)
+├── helpers/ sourceText.cjs (LF readers, assertAbsent with a mandatory canary),
+│ fakeVscode.cjs (scoped fake `vscode` to EXECUTE out/ modules),
+│ runtimeAssembly.cjs (test-side mirror of the runtime assembler),
+│ logCapture.cjs, templatesRoot.cjs, sceneAssetModules.cjs
+├── baseline/ the feature baseline of the cleanup epic: snapshot of the user-visible
+│ surface + the register of authorized removals (featureSurface.cjs --write)
+├── tooling/ measureGuardrails.cjs + guardrail-baseline.json + the ratchet test;
+│ lintContract (what lint/typecheck cover and how strict), npmScripts
+│ (every script target exists; every test:* script is documented here),
+│ dependencyDirection (the folder import matrix and its two-way pairs,
+│ data in folderDependencies.json; `node test/tooling/folderDependencies.cjs`),
+│ srcLayout (src/ = five layers + extension.ts, kebab-case folders, no barrels)
├── manual/ browser-run HTML harnesses (xr-containment, project-evolution-playback…)
-└── runners/ the .cjs runner scripts npm scripts point to
+└── runners/ the .cjs runner scripts npm scripts point to (the two Python-only ones,
+ run-python-tests and run-analysis-tests, are in backend/scripts/)
```
-Also `manual_test/` (repo root): per-language fixtures consumed by `npm run test:analysis` (see `manual_test/README.md`).
+The Python `unittest` suites (dependencies + goldens, analyzers, scanning, html_dom, xr schema…; `backend_sandbox.py` scopes a fake lizard to one module) live in `backend/tests/`, and the dependency-graph sample sources (~25 languages) with them: `backend/tests/fixtures/dependency-languages/`.
+
+Also `backend/manual_test/`: per-language fixtures consumed by `npm run test:analysis` (see `backend/manual_test/README.md`); that runner drives `backend/tests/manual_metrics_suite.py` and `backend/scripts/report-manual-metrics.py` (reports land in `backend/artifacts/manual_test_reports/`).
## Packaging
- Bundler: **webpack** (`webpack.config.js`), target node, entry `src/extension.ts` → `dist/extension.js` (commonjs2, `clean: true`), `vscode` external.
-- **No `.vscodeignore`** — VSIX contents are controlled by the `files` allowlist in package.json: `dist/**`, selected `resources/`, README/LICENSE/notices/CHANGELOG, **`docs/**`** (yes, docs ship to users), `templates/**`, `examples/**`. `.claude/` is **not** in the list and never ships.
+- **No `.vscodeignore`** — VSIX contents are controlled by the `files` allowlist in package.json: `dist/**`, selected `resources/`, README/LICENSE/notices/CHANGELOG, `templates/**`, `examples/**`. `.claude/` is **not** in the list and never ships; neither does `docs/` since 1.2.1 (nothing reads it at runtime, and vsce rewrites the README links into it to GitHub URLs via `--baseContentUrl`).
- `npm run package:vsix` produces the installable `.vsix`. During release prep, inspect the VSIX contents against the allowlist (see `AI_WORKFLOWS.md`).
## Known tooling quirks (do not "fix" casually)
-- **No CI for build/lint/test.** The only workflow is `.github/workflows/deploy-pages-redirect.yml` (GitHub Pages redirect on push to `master`). All gates are local.
-- **`esbuild.config.mjs` is unreferenced** by any npm script — webpack is the active bundler. Likely legacy from the 0.0.8-era ESBuild migration. *Needs verification before removal.*
-- **`.vscode-test.mjs` / `test:integration` mismatch**: points to `out/test/**/*.test.js`, but no such tests exist.
+- **CI** (`.github/workflows/ci.yml`, since 1.2.1) runs on pull requests to `master` and to release branches: `npm test` on `windows-latest`, `ubuntu-latest` and `macos-latest`; on the same three, the Python job (`lint:python` with the pinned ruff from `backend/requirements-dev.txt`, the backend unit suites, `test:analysis`, the HTML DOM suite); and a Windows job that packages the VSIX, checks its listing (`scripts/vsix-listing.mjs`) and uploads it with its dist fingerprint and listing. All jobs block (no `continue-on-error`); making them *required* for merging is a branch-protection setting only the maintainer can change. It runs exactly the local gates — nothing is CI-only. Since S15 (#87) a fourth job, `harnesses` (Ubuntu), installs Playwright's Chromium and runs `npm run test:harnesses`; the scene libraries come from `test/vendor/scene-libraries/`, never from a CDN. The other workflow, `deploy-pages-redirect.yml`, only publishes the GitHub Pages redirect.
+- **webpack is the only bundler.** The orphan `esbuild.config.mjs` (no script ran it, `esbuild` was never a dependency) was deleted in 1.2.1.
- `tsconfig.json` `outDir` is `out/` (used for `compile-tests`/typecheck output); the shipped bundle goes to `dist/` via webpack. Don't confuse the two.
- `tsconfig.tsbuildinfo` at root is a build cache — never edit or commit-review it.
-- A leftover `CodeXR.helloWorld` command exists in package.json (scaffolding; see `V1.2.0_STATUS.md` documentation debt).
## How future agents should use this document
diff --git a/.claude/docs/INDEX.md b/.claude/docs/INDEX.md
index fe75fc671..12b3b6e2a 100644
--- a/.claude/docs/INDEX.md
+++ b/.claude/docs/INDEX.md
@@ -3,6 +3,8 @@
> **Purpose**: The navigation hub. Every session starts here (pointed from `CLAUDE.md`) and reads *only* the documents mapped to its task.
> **Stability**: Update whenever a document is added, removed, or repurposed.
+> **Monorepo (2026-11-25):** paths in these docs predate the move. `src/`, `test/`, `templates/`, `scripts/`, `docs/` → `apps/vscode-extension/…`; `src/code_analysis/python/` → `backend/src/`; `test/python/` → `backend/tests/`; `manual_test/` → `backend/manual_test/` (1.2.1). Layout and rationale: `docs/monorepo.md` (repository root). Inside `src/`, paths written before story #55 (2026-11-25: `code_analysis/`, `servers/`, `views/`, …) moved to the feature-first layers `app/ → features/ → core/ → platform/ → shared/`; translate any old path with `docs/cleanup/src-move-map.json`.
+
## Document inventory
### Internal AI/dev context (`.claude/docs/` — never shipped in the VSIX)
@@ -14,7 +16,14 @@
| `DEVELOPMENT.md` | npm scripts, launch configs, test layers, packaging, tooling quirks |
| `PYTHON_ANALYSIS.md` | The Python metrics backend, venv, field-schema contract |
| `XR_COMPONENTS.md` | Scene generation, browser runtimes, table modes, chart system |
-| `V1.2.0_STATUS.md` | **Volatile** dated snapshot: implemented / in progress / pending / needs-verification / documentation debt |
+| `V1.2.1_STATUS.md` | **Volatile — the active status doc.** Cleanup backlog (ranked), baseline measurements, session log |
+| `v1.2.1/ROADMAP.md` | **The v1.2.1 programme**: maintainer decisions, per-commit protocol, tool-measured baseline, the override table, commit-by-commit tables per wave (W0-W5), the record-only register for 1.3.0, exit criteria. Read sections A-E, then only your wave |
+| `v1.2.1/AUDIT.md` | Frozen evidence: 220 findings with skeptic verdicts + the "looks dead but is ALIVE" lists. ~275 KB — **grep it** (finding id or file name), never read it whole |
+| `v1.2.1/DESIGN_GUARDRAILS.md` | File-level design for the safety net, the ratchet, H1/H2, the ESLint/tsc/ruff rollout, the vscode-free log sink, typing |
+| `v1.2.1/DESIGN_STRUCTURAL.md` | Target architecture + commit slicing for every W4/W5 refactor, each with the characterization test that must land first, and a cut order |
+| `v1.2.1/CRITIC_REVIEW.md` | The 38 corrections to those designs, with file:line evidence; summarized in the ROADMAP override table |
+| `v1.2.1/sessions/*.md` | One log per cleanup story of epic #26 (`-.md`): commits, before/after numbers, gates, what was deliberately left, quirks for 1.3.0, the F5 checks for the maintainer. `docs/cleanup/REPORT.md` consolidates them |
+| `V1.2.0_STATUS.md` | Historical record of the closed 1.2.0 cycle (released 2026-07-30); source of carried-over debt. Do not rewrite |
| `AI_WORKFLOWS.md` | Playbooks per task type + universal session rules |
### Project skills (`.claude/skills/` — never shipped; invoked via the Skill tool or `/`)
@@ -25,40 +34,49 @@
| `session-close` | End-of-session checklist: status doc, CHANGELOG, doc sync, commit hygiene |
| `runtime-component` | Rules for `templates/components/` runtimes: injection paths, load order, tests |
| `add-language` | Language-support changes: Python contract ↔ TS metadata, fixtures, test matrix |
+| `capture-media` | README/website screenshots driven from a real running analysis (`media/SHOTLIST.md`) |
+| `cleanup` | **v1.2.1 default**: dead-code removal, file splits, lint tightening, size optimization — proof-before-delete + measurement ritual |
-### Existing project docs (shipped in the VSIX via `docs/**`)
+### Existing project docs (README/CHANGELOG ship in the VSIX; `docs/` does not since 1.2.1 — the README links it on GitHub)
| Document | Language | One-line purpose |
|---|---|---|
| `README.md` | EN | User-facing overview, features, install (partly one release behind — see status doc) |
-| `CHANGELOG.md` | EN | Version history; `[1.2.0] – Unreleased` is the active section |
-| `docs/project/ROADMAP_V1.2.0.md` | ES | v1.2.0 goals, per-area status table, delivery sequence, exit criteria |
-| `docs/features/DEPENDENCY_GRAPH_XR.md` | EN | Dependency-graph XR mode: architecture, 23 languages, layouts, limits |
+| `CHANGELOG.md` | EN | Version history; `[1.2.1]` is the active section (provisional date; 1.2.0 released 2026-07-30) |
+| `docs/project/ROADMAP_V1.2.0.md` | EN | v1.2.0 goals, per-area status table, delivery sequence, exit criteria |
+| `docs/features/DEPENDENCY_GRAPH_XR.md` | EN | Dependency-graph XR mode: architecture, 28 languages, layouts, limits |
| `docs/features/HISTORICAL_COMPARISON_XR.md` | ES | Historical comparator: dual table, safe Git access, caching, limits |
-| `docs/features/PROJECT_EVOLUTION_XR.md` | EN | Project Evolution "movie" mode (in progress; file currently untracked) |
+| `docs/features/PROJECT_EVOLUTION_XR.md` | EN | Project Evolution "movie" mode |
| `docs/features/CLOUDFLARE_REMOTE_ACCESS.md` | ES | Quick Tunnel remote access: flow, limits, authorization layer |
| `docs/xr-testing/XR_DEBUG_COMMANDS.md` | EN | Browser-console debug APIs for generated XR scenes |
| `THIRD_PARTY_NOTICES.md` | EN | Third-party licenses; what is and isn't bundled |
| `templates/components/COMPONENTS.md` | EN | Inventory + load order of browser-side component runtimes |
| `test/README.md` | EN | Test suite layout and commands |
-| `manual_test/README.md` | EN | Per-language fixtures for `npm run test:analysis` |
+| `backend/manual_test/README.md` | EN | Per-language fixtures for `npm run test:analysis` |
+| `docs/cleanup/README.md` (repository root) | EN | The v1.2.1 deep-cleanup epic (#26): story map, baseline, how "no functionality lost" is proved; links the documents below |
+| `docs/cleanup/REPORT.md` | EN | **Final report of the cleanup**: findings, every story and PR, behaviour-neutrality evidence, exit criteria, what is left for 1.3.0, automated E2E results and the consolidated maintainer F5 checklist |
+| `docs/cleanup/feature-baseline.md` | EN | Inventory of everything the extension contributes and does (pinned by `test/baseline/`), with the §10 verification checklist |
+| `docs/cleanup/src-layout.md`, `src-move-map.json` | EN | Story #55: the feature-first `src/` layout and the old → new path map |
+| `docs/cleanup/{host-boundary,modernization,sweep-outside-src,w2-revalidation}.md` | EN | Layering, idiom modernization, the sweep outside `src/`, the W2 re-validation |
+| `docs/xr-audit/README.md` (repository root) | EN | **XR environment audit (2026-11-25)**: 102 findings across panels, launcher, charts/containment, project evolution, dependency graph, historical comparison and mode lifecycle, each with evidence, repro status and proposed fix; per-area reports beside it. Read before fixing anything in the XR epic |
## Task → reading list
| Task | Read (in order) | Likely folders |
|---|---|---|
| **Any session (always)** | `CLAUDE.md` → this index | — |
-| **New feature** | `ARCHITECTURE.md` → `V1.2.0_STATUS.md` → area doc(s) → `AI_WORKFLOWS.md` §feature | per module convention |
+| **Cleanup / optimization (v1.2.1 default)** | `V1.2.1_STATUS.md` (where we are: waves + session log) → `v1.2.1/ROADMAP.md` §A-E, then your wave's table → `cleanup` skill → grep `v1.2.1/AUDIT.md` for the finding id / file before deleting; `v1.2.1/DESIGN_*.md` for the design of the item | whatever the roadmap row names |
+| **New feature** | `ARCHITECTURE.md` → `V1.2.1_STATUS.md` → area doc(s) → `AI_WORKFLOWS.md` §feature. **Note: features are out of scope for 1.2.1** | per module convention |
| **Bug fix** | `ARCHITECTURE.md` (module map) → `AI_WORKFLOWS.md` §bug fix; area doc if a contract seam is involved | the one module |
| **Refactor** | `ARCHITECTURE.md` (contracts!) → `AI_WORKFLOWS.md` §refactor | crossing modules |
-| **XR visuals / scene / runtimes** | `XR_COMPONENTS.md` → `templates/components/COMPONENTS.md`; `docs/xr-testing/XR_DEBUG_COMMANDS.md` when debugging | `templates/`, `src/babia_templates/`, `engine/components/` |
-| **Analysis / metrics / languages** | `PYTHON_ANALYSIS.md` → `ARCHITECTURE.md` §contracts | `src/code_analysis/python/`, `engine/`, `src/utils/languageMetadata.ts` |
-| **Dependency graph** | `XR_COMPONENTS.md` → `docs/features/DEPENDENCY_GRAPH_XR.md` | `code_analysis/dependencies/`, graph runtime |
-| **Historical / Project Evolution** | `V1.2.0_STATUS.md` → `docs/features/HISTORICAL_COMPARISON_XR.md` / `docs/features/PROJECT_EVOLUTION_XR.md` | `code_analysis/historical/` |
-| **Servers / SSE / collaboration / remote** | `ARCHITECTURE.md` → `docs/features/CLOUDFLARE_REMOTE_ACCESS.md` for tunnels | `src/servers/`, `active_servers/`, `collaboration/`, `remote_access/` |
+| **XR visuals / scene / runtimes** | `XR_COMPONENTS.md` → `templates/components/COMPONENTS.md`; `docs/xr-testing/XR_DEBUG_COMMANDS.md` when debugging | `templates/`, `src/core/charts/`, `src/core/analysis/scene-assets/` |
+| **Analysis / metrics / languages** | `PYTHON_ANALYSIS.md` → `ARCHITECTURE.md` §contracts | `backend/src/`, `src/core/analysis/`, `src/core/analysis/languages/languageMetadata.ts` |
+| **Dependency graph** | `XR_COMPONENTS.md` → `docs/features/DEPENDENCY_GRAPH_XR.md` | `core/dependencies/`, graph runtime |
+| **Historical / Project Evolution** | `V1.2.0_STATUS.md` → `docs/features/HISTORICAL_COMPARISON_XR.md` / `docs/features/PROJECT_EVOLUTION_XR.md` | `core/history/`, `core/export/` |
+| **Servers / SSE / collaboration / remote** | `ARCHITECTURE.md` → `docs/features/CLOUDFLARE_REMOTE_ACCESS.md` for tunnels | `src/core/server/`, `src/features/servers/`, `src/features/active-servers/`, `core/collaboration/`, `features/collaboration/`, `core/remote-access/` |
| **Build / test / tooling** | `DEVELOPMENT.md` | `scripts/`, configs |
-| **Docs update** | `AI_WORKFLOWS.md` §docs → `V1.2.0_STATUS.md` §documentation debt | `docs/`, `.claude/docs/` |
-| **Release preparation** | `V1.2.0_STATUS.md` (all) → `docs/project/ROADMAP_V1.2.0.md` → `AI_WORKFLOWS.md` §release → `DEVELOPMENT.md` §packaging | everything user-visible |
+| **Docs update** | `AI_WORKFLOWS.md` §docs → `V1.2.1_STATUS.md` §carried-over debt → `V1.2.0_STATUS.md` §documentation debt | `docs/`, `.claude/docs/` |
+| **Release preparation** | `V1.2.1_STATUS.md` (all) → `docs/cleanup/REPORT.md` (exit criteria, maintainer F5 checklist) → `AI_WORKFLOWS.md` §release → `DEVELOPMENT.md` §packaging; `docs/project/ROADMAP_V1.2.0.md` only for historical exit criteria | everything user-visible |
## Folders to avoid (context cost / generated)
@@ -67,7 +85,7 @@
| `node_modules/`, `dist/`, `out/`, `output/`, `artifacts/`, `.vscode-test/` | Generated / dependencies; never read or edit |
| `tsconfig.tsbuildinfo`, `package-lock.json` | Build cache / lockfile; huge, no signal |
| `resources/` (media), `examples/` | Binary/media assets; only relevant when explicitly working on them |
-| `src/code_analysis/` *as a whole* | 246 files — enter via `ARCHITECTURE.md` module map, never scan |
+| `src/core/analysis/` + `src/features/analysis/` *as a whole* | about 120 files — enter via `ARCHITECTURE.md` module map, never scan |
| `package.json` *as a whole* | ~70 commands; grep the section you need |
## Keeping this index current
diff --git a/.claude/docs/PYTHON_ANALYSIS.md b/.claude/docs/PYTHON_ANALYSIS.md
index b6977dffb..18ff8044b 100644
--- a/.claude/docs/PYTHON_ANALYSIS.md
+++ b/.claude/docs/PYTHON_ANALYSIS.md
@@ -2,33 +2,36 @@
> **Purpose**: Understand the only non-TypeScript subsystem — the Python engine that produces all code metrics — and its contract with the extension.
> **Stability**: Stable — update when CLI modes, the field schema contract, or the venv mechanism change.
-> Verified against `src/code_analysis/python/` and `src/python_env/` structure on 2026-07-08.
+> Verified against `src/code_analysis/python/` and `src/python_env/` structure on 2026-07-08; paths re-verified on 2026-11-25 (story #43) against the monorepo (`backend/src/`) and the feature-first `src/` (story #55).
## Why this file exists
The Python backend is a frequent source of confusion:
-- It lives in `src/code_analysis/python/` but is **not compiled** — webpack's CopyPlugin copies it verbatim into `dist/code_analysis/python` at build time (excluding `*.ts` and `__pycache__`).
+- It lives in `backend/src/` (outside the extension package since the monorepo move; it was `src/code_analysis/python/`) and is **not compiled** — webpack's CopyPlugin copies it verbatim into `dist/code_analysis/python` at build time (excluding `__pycache__`). In Development mode only, the extension falls back to `/backend/src` when the `dist/` copy is missing.
- It runs inside a **managed virtual environment** created by the extension itself, not the system Python.
- Its output schema drives TypeScript-side validation, so Python and TS must change together.
## Entry point and CLI
-`src/code_analysis/python/main.py` — argparse CLI, JSON output on stdout.
+`backend/src/main.py` — argparse CLI, JSON output on stdout.
-- `--mode {livePanel, xr, schema, dependencies}`
-- `--type {file, directory, project}`
+- `--mode {livePanel, xr, schema, dependencies, functions}` (`functions`, added for the Code-XR IDE's Problems panel #173, returns each analysable file's functions with line range, CCN, NLOC and parameter count, from `utils/function_metrics.py`; with `--type file`, `--project-root` makes the path relative; the extension does not use it)
+- `--type {file, directory}` (the unused `project` alias and the unread `--output` flag were removed in 1.2.1; `--target`, `--files`, `--deep`, `--cache`, `--dependency-refresh`, `--project-root` remain)
+- Three more scripts are spawned directly by TypeScript: `html/html_dom_parser.py` (DOM mode), `summaryFiles/file_reanalysis_coordinator.py` (watcher re-analysis; the folder was misspelled `sumaryFiles/` until 1.2.1) and `export/git_export_analysis_worker.py` (Git export worker pool).
-The TS bridge is `src/code_analysis/engine/utils/executePython.ts`, which spawns the venv's interpreter against `main.py` and parses the JSON. Progress is streamed via `python/utils/progress_logger.py` conventions. *[inferred: exact progress protocol — verify in executePython.ts if you need it]*
+The TS bridge is `src/core/analysis/python/executePython.ts`, which spawns the venv's interpreter against `main.py` and parses the JSON. Progress is streamed on stderr as JSON lines (`{"progress": {...}}`, `{"debug": ...}`, `{"warning": ...}`, `{"error": ...}`) by `backend/src/utils/progress_logger.py`; `src/core/analysis/python/pythonStderrStream.ts` classifies them and `executePython.ts` reports the progress.
## Layout
```
-src/code_analysis/python/
+backend/src/
├── main.py CLI entry; wires sys.path for subpackages
├── tools/ analyzer wrappers
-│ ├── lizard_analyzer.py Lizard → cyclomatic complexity, function/line counts
+│ ├── code_metrics_analyzer.py per-function metrics (CCN, NLOC, params, nesting, cognitive, Halstead, MI), same JSON as the old Lizard wrapper plus the epic #219 fields
+│ ├── code_metrics/ the analyzer itself: lexer + one parser per language family (spec: docs/lizard-replacement/SPEC.md)
│ ├── class_counter_analyzer.py
│ └── python_comment_analyzer.py
+├── export/ git_export_analysis_worker.py (Git export worker)
├── utils/ engines and shared helpers
│ ├── file_analysis_engine.py / directory_analysis_engine.py
│ ├── dependency_analysis_engine.py (dependency graph; tree-sitter-language-pack)
@@ -36,42 +39,53 @@ src/code_analysis/python/
│ ├── xr_field_schema.py ★ the field schema (see contract below)
│ ├── file_metric_summary.py, line_metric_utils.py, directory_scan_utils.py
│ └── babia_path_utils.py, progress_logger.py
-├── livePanels/ LivePanel coordinators (file/directory, deep, reanalysis)
+├── livePanels/ LivePanel coordinators (file/directory, deep)
├── XR/ xr_file_analysis_coordinator.py, xr_directory_analysis_coordinator.py
├── html/ html_dom_parser.py (DOM visualization backend)
-└── examples/, sumaryFiles/ progress/reanalysis coordinators
+└── summaryFiles/ file reanalysis coordinator (watcher re-analysis)
```
## The field-schema contract (critical seam)
-1. `python/utils/xr_field_schema.py` defines which metric fields exist per analysis type.
-2. TS fetches it via `main.py --mode schema`, cached/served by `src/code_analysis/services/xrFieldSchemaService.ts` (prefetched at startup by the `StartupCoordinator`).
-3. `src/babia_templates/processing/dimensionValidator.ts` validates user dimension mappings against that schema before launching an XR scene.
+1. `backend/src/utils/xr_field_schema.py` defines which metric fields exist per analysis type.
+2. TS fetches it via `main.py --mode schema`, cached/served by `src/core/analysis/python/xrFieldSchemaService.ts` (prefetched at startup by the `StartupCoordinator`).
+3. `src/core/charts/processing/dimensionValidator.ts` validates user dimension mappings against that schema before launching an XR scene.
**Rule**: any metric added/renamed/removed in Python must flow through the schema, and the analysis/manual-metrics tests must be re-run. A mismatch surfaces as dimension-mapping validation failures or empty charts.
-## Virtual environment (`src/python_env/`)
+**Do not touch in a cleanup (audited 2026-09-18).** The contract is five hops long (`xr_field_schema.py` → `get_xr_schema` → `main.py --mode schema` → `executePython.ts` → `xrFieldSchemaService.ts` → `dimensionValidator.ts`), frozen by tests on both sides, and the schema is **persisted** in the user's `globalState` (`codeXR.analysis.xrFieldSchemaCache.v1`), so a Python-side change can be masked locally and surface later as a mapping failure. Therefore none of these is cleanup material:
+- `XR_SCHEMA_VERSION` — a bump invalidates every user's cached schema.
+- The order, count and exact label strings of `XR_FILE_FIELDS` (13) and `XR_DIRECTORY_FIELDS` (25); `backend/tests/xr_schema/test_xr_schema.py` pins the counts.
+- The `_text_field(…)` / `_numeric_field(…)` call syntax — `test/analysis/xrFieldSchemaIntegration.test.cjs` regex-matches five of those source lines, double quotes included.
+- The `build_complexity_band` thresholds (`>25`, `>10`), mirrored in `code_metrics_analyzer.calculate_complexity_metrics` and `summarize_function_metrics`. Three copies on purpose: de-duplicating them is a contract change, not a cleanup.
+- `summarize_function_metrics` — Lizard reported CCN 18, but that is `or 0` guards inside comprehensions, not branching. Leave it alone.
+- Every id in `XR_DIRECTORY_FIELDS` must stay a key emitted by `utils/file_metric_summary.py`, and every id in `XR_FILE_FIELDS` a key emitted by `utils/file_analysis_engine.py` (subset checks in `backend/tests/manual_metrics_suite.py`).
-- `runtime/venvManager.ts` creates/verifies/reinstalls the venv; package manifest and env UI state live alongside it. User-facing commands: `codeXR.pythonEnv.*` (create/delete/status/reinitialize/verify/debug).
-- Python dependencies (e.g. `lizard`, `tree-sitter-language-pack`) are installed into this venv at runtime. **Needs verification**: the exact dependency manifest location (there is no top-level `requirements.txt`; the manifest appears to live inside `src/python_env/` — confirm before changing dependencies).
+Python source is also pinned on **quote style and import order** by source-text tests (`main.py`'s `choices=['livePanel', …]`, `print('=== JSON_START ===')`, the imports that follow the `sys.path` setup). No formatter, no isort.
+
+## Virtual environment (`src/core/python-env/`, commands and tree in `src/features/python-env/`)
+
+- `venvManager.ts` creates/verifies/reinstalls the venv; the package manifest (`pythonPackageManifest.ts`), storage and env UI state live alongside it. User-facing commands: `codeXR.pythonEnv.*` (create/delete/status/reinitialize/verify/debug).
+- Python dependencies are installed into this venv at runtime. The source of truth for the pins is `CODEXR_PYTHON_PACKAGES` in `src/core/python-env/pythonPackageManifest.ts` (only `tree-sitter-language-pack` 1.8.1 since 1.2.1: the metrics need no third-party package); `backend/requirements.txt` is its generated mirror (`npm run python:requirements`, checked by `test/python_env/pythonRequirements.test.cjs`). Note: `tree-sitter-language-pack` 1.x downloads parser libraries from GitHub on first use. Since 1.2.1 only the set-up does that: `VenvManager` runs `backend/src/tools/download_parsers.py` after installing the packages (and in the startup repair path, which fetches only missing parsers), into `/codexr-tree-sitter`; `backend/src/utils/tree_sitter_parsers.py` points the pack there, and the dependency engine calls `process()` only when `is_available(grammar)`, otherwise it uses its regex fallback. The install verification only imports the package.
- Context key `codeXR.pythonEnv.uiLocked` gates analysis context menus while the env is being set up.
## Languages and metrics
-- Metrics: cyclomatic complexity (CCN), LOC/comment lines, function/class counts, parameters — primarily via **Lizard**. Dependency relations via **tree-sitter-language-pack** (pinned; confidence levels exact/best-effort/unsupported/ambiguous — see `docs/features/DEPENDENCY_GRAPH_XR.md`).
-- Language support: README claims 24, dependency-graph doc and roadmap say 23, and `test/fixtures/dependency-languages/` holds ~25 fixture languages. **The source of truth is `src/utils/languageMetadata.ts` (TS side) + `python/utils/metric_language_contract.py` (Python side)** — check those, not the docs, when a language question matters. (Recorded as documentation debt in `V1.2.0_STATUS.md`.)
+- Metrics: cyclomatic complexity (CCN), cognitive complexity, Halstead (volume, difficulty, effort, estimated bugs), maintainability index, LOC/comment lines, function/class counts, parameters, nesting depth — computed by Code-XR's own analyzer (`backend/src/tools/code_metrics/`, spec in `docs/lizard-replacement/SPEC.md`, differential tests against frozen Lizard output in `backend/tests/metrics_differential/`). Dependency relations via **tree-sitter-language-pack** (pinned; confidence levels exact/best-effort/unsupported/ambiguous — see `docs/features/DEPENDENCY_GRAPH_XR.md`).
+- Language support: README claims 24, dependency-graph doc and roadmap say 23, and `backend/tests/fixtures/dependency-languages/` holds ~25 fixture languages. **The source of truth is `src/core/analysis/languages/languageMetadata.ts` (TS side) + `backend/src/utils/metric_language_contract.py` (Python side: 28 languages, 55 extensions since epic #219 added Rust, Dart, Shell, PowerShell and R, plus HTML as DOM-only)** — check those, not the docs, when a language question matters. (Recorded as documentation debt in `V1.2.0_STATUS.md`.)
## Testing the Python side
| Command | Covers |
|---|---|
-| `npm run test:python` | pytest-style suites in `test/python/` (dependencies, directory scanning, html_dom protocol, path normalization, xr file analysis, xr schema) |
-| `npm run test:analysis` | End-to-end metric equivalence over `manual_test/` fixtures (one per language); asserts XR and LivePanel produce identical `data.json` |
-| `npm run test:htmlanalysis` | HTML/DOM parser |
-| `test/analysis/manual_metrics_suite.py` | Manual metrics suite (driven by the analysis runner) |
+| `npm run test:python` | `unittest` suites in `backend/tests/` (analyzers + goldens, dependencies + goldens, directory scanning, git export, html_dom protocol, path normalization, xr file analysis, xr schema): 73 tests at the end of 1.2.1. They need Python 3.10+ (two tests use 3.9/3.10 APIs), while `backend/src` itself targets 3.7 |
+| `npm run test:analysis` | End-to-end metric equivalence over `backend/manual_test/` fixtures (one per language); asserts XR and LivePanel produce identical `data.json` |
+| `npm run test:htmlanalysis` | HTML/DOM parser (`backend/tests/html_dom/` + `test/analysis/livePanelDomIntegration.test.cjs`) |
+| `npm run lint:python` | `ruff check` over `backend/` (`backend/ruff.toml`, ruff pinned in `backend/requirements-dev.txt`); lint only, never a formatter |
+| `backend/tests/manual_metrics_suite.py` | Manual metrics suite (driven by the analysis runner) |
## How future agents should use this document
-- Touching anything under `python/`? Plan the TS-side schema/validation impact first (section "field-schema contract"), then run `test:python` + `test:analysis`.
+- Touching anything under `backend/src/`? Plan the TS-side schema/validation impact first (section "field-schema contract"), then run `test:python` + `test:analysis`.
- Never assume system Python is used — always reason in terms of the managed venv.
-- Don't edit anything under `dist/` — the Python files there are build artifacts copied from `src/`.
+- Don't edit anything under `dist/` — the Python files there are build artifacts copied from `backend/src/`.
diff --git a/.claude/docs/V1.2.1_STATUS.md b/.claude/docs/V1.2.1_STATUS.md
new file mode 100644
index 000000000..21f29b8ca
--- /dev/null
+++ b/.claude/docs/V1.2.1_STATUS.md
@@ -0,0 +1,739 @@
+# v1.2.1 Status Snapshot — Cleanup & Optimization
+
+> **Snapshot date: 2026-11-25** (opened 2026-08-03; programme approved 2026-09-18; cleanup epic #26 executed and verified 2026-11-25, final report `docs/cleanup/REPORT.md`). This is the *volatile* document for v1.2.1 — update it whenever a cleanup item lands, a measurement changes, or a new debt is found. Supersedes `V1.2.0_STATUS.md` as the active status doc; that file stays as the historical record of the 1.2.0 cycle and must not be rewritten.
+> Labels: **[confirmed]** measured/verified directly in this repo · **[self-assessed]** a doc's own claim, not independently validated · **[inferred]** conclusion from evidence · **[open]** unresolved question.
+
+## What this version is for
+
+**1.2.1 is a maintenance release. No new features.** The scope is: delete what is dead, shrink what is oversized, tighten what silently allows rot, and make the existing paths cheaper. Every change must be **behaviour-neutral for the user** unless the CHANGELOG says otherwise.
+
+If a task turns out to need a behaviour change to be worth doing, stop and ask — it belongs in 1.3.0, not here.
+
+## The programme (approved 2026-09-18) [confirmed]
+
+The backlog below was the opening hunch. On 2026-09-17/18 the whole repo was audited (10 areas, each finding re-verified by an independent skeptic: **220 findings — 140 upheld, 72 corrected, 8 refuted, 52 added**), three designs were drawn from it and a critic reviewed them. The maintainer approved the result: **everything, in six waves of increasing risk, about 270 bisectable commits.**
+
+| Wave | What | State |
+|---|---|---|
+| W0 | Setup: tool-measured baseline, make grep trustworthy, persist the audit | **done** (2026-09-18, 5 commits) |
+| W1 | Safety net: test helpers, contract/sync tests, the ratchet, H1/H2 tooling, CI | **done** (2026-09-18, 30 commits; CI first ran on PR #24, 2026-11-25, and blocks on Windows, Linux and macOS since #33) |
+| W2 | Proven deletions (unreachable files, dead declarations, authorized command removals) | **done** (2026-11-25, stories #29-#32, PRs #45-#52) |
+| W3 | Guardrails on (ESLint + tsc strictness staged, ruff, docs) | **done** (2026-11-25, story #33, PR #53) |
+| W4 | Logging programme, then low-risk de-duplication and complexity | **done** (2026-11-25, stories #34-#37, #56; PRs #49, #50, #58, #61-#64) |
+| W5 | Structural refactors, each after its characterization test | **done**, with the documented cuts (2026-11-25, stories #38-#42, #55; PRs #51, #54, #57, #59, #60, #65). Final verification: story #43, `docs/cleanup/REPORT.md` |
+
+Everything needed to execute it lives in **`.claude/docs/v1.2.1/`**: `ROADMAP.md` (decisions, per-commit protocol, the override table, the commit-by-commit tables, the record-only register for 1.3.0, exit criteria), `AUDIT.md` (every finding with its verdict, plus the "looks dead but is ALIVE" lists — grep it before deleting anything), `DESIGN_GUARDRAILS.md`, `DESIGN_STRUCTURAL.md`, `CRITIC_REVIEW.md`.
+
+The ranked backlog further down stays as written; `ROADMAP.md` supersedes it as an **ordering**. Every one of its nine items is covered there (item 8, the `.git` pack, remains propose-only).
+
+**The constraint that shapes every refactor [confirmed]:** about half of the unit-test files assert regexes over the *source text* of `src/**` and `templates/**` (`readFileSync` + `assert.match`). Moving a line can turn a test red with identical behaviour; a negative assertion goes vacuous when its file is split; a file read as text by a test is not dead even with zero importers. Hence the per-commit protocol in `ROADMAP.md` §D: grep `test/` for the basename first, classify each pin, and land a behavioural characterization before reshaping anything a shape-pin guards.
+
+## Version and branch state [confirmed]
+
+- `package.json` version: `1.2.1`. CHANGELOG has `[1.2.1] - 2026-09-18`, a **provisional** date set by the maintainer on 2026-09-18 and to be moved forward when the release is cut; **1.2.0 released 2026-07-30 (Thursday)**.
+- Branch `v1.2.1`, cut from `master` at `bcb34bd5` (the PR #6 merge), pushed and tracking `origin/v1.2.1`.
+- Branch `v1.2.0` **deleted** (local + remote) after verifying `master` contained it: zero unmerged commits and **identical tree hash** `15122d77`. The **tag `v1.2.0` is kept** at `c3e09927` — that is the recoverable pointer to the release.
+- `master` is the only principal branch and the PR target. There is no `main` branch; a rename was considered and explicitly declined (2026-08-03) to avoid breaking CI and existing clones.
+- Remaining branches: `master`, `v1.2.1`.
+
+## Baseline measurements (2026-08-03, before any cleanup) [confirmed]
+
+These are the "before" numbers. Re-measure at the end of the cycle and record the delta.
+
+| Metric | Baseline | Command |
+|---|---|---|
+| TypeScript files in `src/` | 369 | `find src -name "*.ts" \| wc -l` |
+| TypeScript lines in `src/` | 52,605 | `find src -name "*.ts" -exec wc -l {} +` |
+| `npm run lint` | clean (see caveat below) | `npm run lint` |
+| `console.log` calls in `src/` | 1,261 | `grep -rn "console\.log" src --include="*.ts" \| wc -l` |
+| Files importing the real logger | 15 | `grep -rl "core/logging/logger" src --include="*.ts"` |
+| `: any` / `as any` / `` in `src/` | 193 | `grep -rn ": any\b\|as any\b\|" src --include="*.ts"` |
+| `@ts-ignore` / `@ts-expect-error` | **0** — keep it there | `grep -rn "@ts-ignore\|@ts-expect-error" src` |
+| `TODO` markers in `src/` + `templates/` | 30 (in 28 lines) | `grep -rn "TODO\|FIXME\|HACK" src templates` |
+| Unit test files | 55 | `find test -name "*.test.cjs" \| wc -l` |
+| `resources/languages_icons/no_color/` | 34 MB, 25 files (**deleted** in #31, W2-67) | `du -sh` |
+| `resources/languages_icons/color/` | 2.8 MB | `du -sh` |
+| `.git` pack size | **1.03 GiB** | `git count-objects -vH` |
+
+## Tool-measured baseline (2026-09-18, branch point `2d301577`) [confirmed]
+
+The table above used grep-based commands; two of its rows under-count (52,605 lines and 193 `any` against 52,974 and 219 from the AST). From here on **one command owns the source metrics**: `npm run guardrails:measure` (`test/tooling/measureGuardrails.cjs`, TypeScript AST, counting units spelled out in the baseline's `definitions`). The committed `test/tooling/guardrail-baseline.json` is the current value of every row marked †; its git diff is the before/after of each cleanup item.
+
+"Now" was re-measured at the end of the cleanup epic (story #43, 2026-11-25, `v1.2.1` at `913cb362`, Linux); the before/after per story is in `docs/cleanup/REPORT.md`.
+
+| Metric | Baseline 2026-09-18 | Now (2026-11-25, end of epic #26) |
+|---|---|---|
+| `npm test` | 554 / 554 | **1,064 / 1,064** (126 test files) |
+| `npm run test:python` · `test:analysis` | 29 / 29 · green (24 root + 3 deep fixtures) | **73 / 73** · green (24 root + 3 deep fixtures, pinned lizard 1.17.31); `test:htmlanalysis` 12 + 5; `lint:python` clean |
+| Production `dist/extension.js` | 1,257,031 bytes, deterministic (two builds, one sha256) | **1,173,899 bytes** (−6.6 %): deleted modules and the 46 barrels |
+| VSIX | 6,450,820 bytes, 360 entries | **4,204,772 bytes, 199 entries** (−34.8 %, −161 entries) |
+| † Source files · lines · functions | 369 · 52,974 · 2,864 | **291 · 49,064 · 3,338** (smaller functions, so more of them) |
+| † CCN over 10 / 15 / 20 / 30 (worst) | 81 / 31 / 10 / 6 (`buildExportManifest` 61) | **53 / 8 / 0 / 0** (worst `sampleTimeline` 20) |
+| † Modules unreachable from `src/extension.ts` | 54 (2,317 lines) | **0**, waivers `[]` |
+| † `console.*` calls · console-only catch blocks | 1,646 · 65 | **2** (the log sink's console fallback, the only allowlisted file) · **0** |
+| † `any` · suppressions | 219 · 0 | **84** · **0** |
+| † Files over 500 lines · functions over 80 lines | 19 · 57 | **13 · 36** (6 files over 600; largest `core/python-env/venvManager.ts` 850) |
+| † `console.log` in `templates/` (excluding xr-chart-debug) | 117 | **31** (all behind the runtimes' debug flags) |
+| Text files containing a raw NUL byte | 1 | **0** |
+| tsc flag fallout (`noUnusedLocals` / `noUnusedParameters` / `noImplicitReturns` / `noFallthroughCasesInSwitch`) | 55 / 17 / 0 / 0 | **all four on** (`tsconfig.check.json`), 0 findings |
+| ESLint messages today · `no-unused-vars` · `no-require-imports` fallout | 0 · 32 · 26 | **0 errors, 158 warnings = the `--max-warnings` budget** (608 when W3 introduced it, only lowered since); `no-unused-vars`, `no-console`, `no-floating-promises`, `no-require-imports` are errors |
+| Two-way dependency pairs between top-level `src/` folders | 9 (15 counting the `commands/shared` back-edges) | **4**, each with a written reason in `test/tooling/folderDependencies.json` |
+| `src/` shape: folders · `index.ts` barrels · snake_case folder names | 179 · 82 · 55 | **98 · 0 · 0** (five layers `app/ features/ core/ platform/ shared/`) |
+
+Lizard — the engine the extension ships — cannot be the yardstick for TypeScript: it misses async and arrow class methods and reported none of the four worst functions. That is recorded for 1.3.0 as a product observation (the TS metrics CodeXR shows are a floor, not the value).
+
+## Cleanup backlog — ranked
+
+Ranked by value-to-risk. Take **one item per session**, verify, update this doc and the CHANGELOG, commit. Do not bundle items.
+
+### 1. ESLint config barely checks anything — the highest-leverage fix [confirmed]
+
+> **Status 2026-11-25: done** (#33, PR #53): the five rules are errors, plus `no-unused-vars`, `no-console`, `no-floating-promises` and the #56 idiom rules; warn-only budget rules counted under `--max-warnings 158`. The config is `apps/vscode-extension/eslint.config.mjs`.
+
+
+`eslint.config.mjs` defines **five rules** (`naming-convention` for imports, `curly`, `eqeqeq`, `no-throw-literal`, `semi`) and **all of them are `warn`**. There is no `no-unused-vars`, no `no-explicit-any`, no `no-floating-promises`, and the TypeScript plugin is loaded but essentially unused.
+
+**Consequence:** `npm run lint` passing today is close to meaningless, and `npm test` includes it as a gate. Dead variables, unused imports and unawaited promises pass silently — which is exactly the rot this version is supposed to remove.
+
+**Do this first**, because every later item is easier once the linter can actually find things. Suggested order: enable `@typescript-eslint/no-unused-vars` and `no-unused-imports` → fix the fallout → then consider `no-floating-promises` (needs type-aware linting, `parserOptions.project`) → decide per-rule whether `warn` or `error`. Expect a large first fallout; land the config and the fixes together so the gate is never left red.
+
+### 2. Dead file: `configurationManagerExample.ts` [confirmed]
+
+> **Status 2026-11-25: deleted** (#29, W2-11).
+
+
+`src/code_analysis/configuration/configurationManagerExample.ts` has **zero importers anywhere in `src/`** and contains 44 `console.log` calls. It is an example file that shipped into the source tree. Delete it.
+
+### 3. `debugThemeProblem.ts` is a registered debug command [confirmed]
+
+> **Status 2026-11-25: removed** with its two command ids (#30, W2-49; CHANGELOG `[1.2.1]` → Removed).
+
+
+`src/code_analysis/configuration/debugThemeProblem.ts` (42 `console.log`) **is** imported — `src/commands/index.ts:15` registers `DebugThemeProblem`. So it is not dead, it is a debug tool exposed to end users in the command palette. Decide deliberately: remove the command, or gate it behind a development-only condition. **Do not just delete it** — the command ID is registered and `assertUniqueCommandIds` runs over that array.
+
+### 4. 1,261 `console.log` vs a logger nobody uses [confirmed]
+
+> **Status 2026-11-25: done** (#34, PR #58): every diagnostic goes through `src/platform/logging/` (the logger moved there in #55); 2 `console.*` calls remain, the sink's own fallback. CHANGELOG `[1.2.1]` → Changed.
+
+
+`src/core/logging/logger.ts` exports `ScopedLogger` and `CodeXRLogger`, but only **15 files** use it against **1,261** raw `console.log` calls. For a VS Code extension this is the wrong surface: `console.log` goes to a devtools console the user never opens, not to an output channel.
+
+Worst offenders: `executePython.ts` (100), `multiServerLauncher.ts` (44), `configurationManagerExample.ts` (44, dead — see item 2), `debugThemeProblem.ts` (42), `serverControl.ts` (41), `visualizeDOMParser.ts` (35).
+
+Migrate **area by area, not repo-wide in one commit**. Start with `executePython.ts` since it is both the worst offender and on the hot analysis path.
+
+### 5. 34 MB of dead icons in the repo [confirmed measurement, self-assessed deadness]
+
+> **Status 2026-11-25: done.** `no_color/` deleted (#31, W2-67); the shipped `icon.png`, `ttcn3.svg` and `default.svg` re-encoded pixel-identically and the duplicate `favicon.ico` dropped from the VSIX (#41). The visual re-export of the two PNG-in-SVG icons stays in the 1.3.0 register.
+
+
+`resources/languages_icons/no_color/` is 34 MB across 25 PNGs (~1.4 MB each). `V1.2.0_STATUS.md:132` states this set has been dead since `95f7c367` and it is already excluded from the VSIX `files` allowlist — so removing it does **not** change the published package, only the working tree and future clones. **Confirm the deadness independently** (grep for `no_color` across `src/`, `templates/`, `package.json`) before deleting.
+
+Related, and *not* dead — these ship: `color/ttcn3.svg` (1.4 MB) and `color/default.svg` (1.3 MB) are SVGs with embedded bitmaps, plus `icon.png` and `favicon.ico` at ~1.2 MB each. Re-encoding them is a real VSIX size win. Carried over from `V1.2.0_STATUS.md:132`, where the debt was flagged but deliberately not taken.
+
+### 6. Oversized modules [confirmed]
+
+> **Status 2026-11-25:** `collaborationRoomServer.ts` 1,174 → 560, `multiServerLauncher.ts` 677 → 275, `screenBroadcastSignalingServer.ts` 781 → 580, `handleServerActions.ts` 815 → 623 (#39), `projectEvolutionService.ts` 668 → under 500 (#38). The paths below are pre-#55 (now `src/core/server/…`, `src/features/active-servers/views/…`). Six files remain over 600 lines, each listed with its reason in `docs/cleanup/REPORT.md` (exit criteria).
+
+
+There is precedent: `httpServer.ts` went 2,102 → 487 lines by responsibility split, with byte-identical characterization (`V1.2.0_STATUS.md:513`). Same technique applies to:
+
+| File | Lines |
+|---|---|
+| `src/servers/runtime/collaboration/collaborationRoomServer.ts` | 1,174 |
+| `src/python_env/runtime/venvManager.ts` | 851 |
+| `src/active_servers/views/interactions/handleServerActions.ts` | 815 |
+| `src/servers/runtime/broadcast/screenBroadcastSignalingServer.ts` | 781 |
+| `src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts` | 685 |
+| `src/servers/runtime/multiServerLauncher.ts` | 677 |
+
+**Read `AI_WORKFLOWS.md` §refactor first.** These are live server/session paths; a split must be behaviour-neutral and characterization-tested, not a vibe reorganization.
+
+### 7. 193 `any` escapes [confirmed]
+
+> **Status 2026-11-25:** 219 (AST count) → **84**; four folders are `any`-free by lint error (`codexr/any-free-folders` in `eslint.config.mjs`). The rest is recorded for 1.3.0.
+
+
+193 occurrences of `: any` / `as any` / `` in `src/`. Note the good news: **zero** `@ts-ignore` — the codebase never silences the compiler outright. Tighten opportunistically while working an area rather than as one mass sweep, and keep the zero at zero.
+
+### 8. `.git` is 1.03 GiB — **propose only, do not execute** [confirmed measurement]
+
+The pack is dominated by binaries committed long ago: `code-xr-0.0.8.vsix` (55 MB and again at 38/36 MB), `code-xr-0.0.9.vsix` (37.6 MB ×3), `code-xr-0.0.6.vsix` (31.7 MB ×2), and `media/v1.1.0/gifts/*.gif` (43.5, 40.6, 37.5 MB).
+
+Shrinking this requires **rewriting history** (`git filter-repo`), which changes every commit hash, forces a force-push to `origin`, and requires every clone to be re-made. That is destructive and outward-facing. **Never do it as part of a routine cleanup session.** If it is ever wanted, it is its own decision with its own explicit approval — and the current `.gitignore` should be checked first so no *new* build artifacts keep landing in history. **[open]**
+
+### 9. Known duplication — trace before touching [self-assessed, from V1.2.0_STATUS.md]
+
+> **Status 2026-11-25:** the two active-servers folders are one (`src/features/active-servers/views/`, #55); the avatar ids are pinned by a sync test (W1); `LegacyServerConfig` / `getLegacyConfig` keep their name (now in `src/core/server/serverSettingsManager.ts`): a rename is not cleanup.
+
+
+- `src/active_servers/views/` and `src/views/active_servers/` both exist. `AI_WORKFLOWS.md:42` explicitly warns this is **historical, not accidental** — do not "clean up" the aggregation wiring without tracing imports first.
+- `LegacyServerConfig` / `getLegacyConfig` in `servers/storage`: live API with a bad name (`V1.2.0_STATUS.md:507`). Renaming is a real refactor, not a rename-in-place.
+- Avatar IDs are duplicated across 4 places: `collaborationProfile.ts`, `CODEXR_AVATAR_IDS` in the room server, `SKINS` in the browser runtime, and a regex in `clientCore.js` (`V1.2.0_STATUS.md:601`). Consolidating crosses the TS↔runtime seam — read `XR_COMPONENTS.md` first.
+
+## Carried-over debt from 1.2.0 (not cleanup — do not silently absorb)
+
+These are open items from the 1.2.0 cycle that are **not** part of the cleanup scope. Listed so they are not lost:
+
+- Several features are marked "confirmed en tests; **pendiente F5**" — live validation by the user was never completed (export offline bundle, cross-network defaults, screen-share role controls, kick flow). See `V1.2.0_STATUS.md`.
+- Documentation debt: `docs/xr-testing/XR_DEBUG_COMMANDS.md:382` references the removed `revealOffsetY` parameter; `ROADMAP_V1.2.0.md:249-251` and its config screenshots are stale on the cross-network default.
+- The `.vsix` attached to the 1.2.0 GitHub release carries an older README (`V1.2.0_STATUS.md:124`).
+
+## Session log
+
+*(Append one section per session: what was cleaned, what was measured before/after, which gates ran, what was deliberately not touched.)*
+
+### Branch opened + 1.2.0 dated — DONE [confirmed] (2026-08-03, rama `v1.2.1`)
+
+Closed the 1.2.0 cycle and opened this one. Verified `master` contained `v1.2.0` by ancestry **and** identical tree hash before deleting the branch; kept the tag. Dated the CHANGELOG release **2026-07-30**, bumped `package.json` to `1.2.1`, added the `[1.2.1] – Unreleased` section, created this doc, and pointed `CLAUDE.md` / `INDEX.md` / `AI_WORKFLOWS.md` at it. Measured the baseline table above. **No source code touched.**
+
+### W0 — audit, plan and tool-measured baseline — DONE [confirmed] (2026-09-17/18, rama `v1.2.1`)
+
+**Audit and plan (read-only, 2026-09-17/18).** Measured the repo with the extension's own Lizard (Python, browser JS), a real TypeScript AST walk (Lizard under-detects TS), an import-graph reachability walk from `src/extension.ts` and a normalized-window clone detector; then a ten-area audit in which every explorer's findings were re-verified by an independent skeptic (220 findings: 140 upheld, 72 corrected, 8 refuted, 52 added), three designs and a critic review. The maintainer approved the programme on 2026-09-18 — see "The programme" above and `.claude/docs/v1.2.1/`.
+
+**Step 0 (no commit).** `git switch v1.2.1`, `npm ci`, then every gate once on the untouched branch point: `npm test` 554/554, `test:python` 29/29, `test:analysis` green, production build deterministic, VSIX 6,450,820 bytes / 360 entries. Measured what a read-only audit could not: tsc flag fallout and ESLint candidate-rule fallout (table above).
+
+| Commit | What | Measured | Gate |
+|---|---|---|---|
+| `21da06da` | test(runtime): pin chart-row de-duplication by composite key | tests 554 → 555 | suite 32/32, green against the unchanged runtime |
+| `0f33dbb1` | fix(templates): the composite-key separator in `chartDataSlice.js:125` was a raw NUL byte typed into the string literal; now the escape `'\u0000'` (same runtime value) + a policy test "no text source contains a NUL byte" | NUL-bearing text files 1 → 0; tests 555 → 556 | `npm test` 556/556 |
+| `aba51207` | test(tooling): `measureGuardrails.cjs` + generated `guardrail-baseline.json`, `npm run guardrails:measure` / `guardrails:update` | baseline table above; reproduces the audit's numbers exactly | `npm test` 556/556 |
+
+Why the NUL fix went first: one raw NUL makes ripgrep and git treat the whole file as binary and skip it silently, so every repo-wide search — and therefore every grep-based deadness proof in W2 — was blind to a shipped runtime part.
+
+**Deliberately not touched:** any source under `src/` (W0 and W1 add tests, tooling and docs only).
+
+### W1 — safety net — DONE [confirmed] (2026-09-18, rama `v1.2.1`, 30 commits `3df7d8ac`..`fc0950ba`)
+
+No file under `src/` was touched. Every commit adds a test, a helper, a script or a doc; one fixes a shipped template comment-equivalent (the NUL escape, W0).
+
+**Proof that nothing was lost.** At the end of the wave the production bundle hashes to `d6e5cb0da40865fb…`, the same value as the untouched branch point. Gates at the end state: `npm test` 708/708 (was 554), `npm run test:python` 52/52 (was 29, and stable under `PYTHONHASHSEED` 0, 1, 12345), `npm run test:analysis` green with the pinned lizard.
+
+**What now exists** (details in each commit message):
+- *Runners that cannot lie*: `compile-tests` starts from an empty `out/` (a deleted module no longer keeps a compiled twin the suites still load); `test:unit` refuses a stale `out/`, per file, in both directions; the unit gate no longer needs a webpack build (the dist check moved into `scripts/package-vsix.mjs`); the Python runner fails under `CI` when it finds no interpreter; the analysis venv installs the lizard the extension pins (it had **1.24.0** against the shipped **1.17.31**).
+- *Helpers*: `test/helpers/sourceText.cjs` (LF readers, `assertAbsent` with a mandatory canary, policy G/S/L in `test/README.md`); `test/helpers/fakeVscode.cjs` (scoped fake `vscode`: executes `out/` modules, restores `Module._load`, evicts what it loaded); `test/python/backend_sandbox.py` (scoped fake lizard).
+- *Contracts executed for the first time*: the logger (`test/logging/logger.test.cjs`, including the pre-initialize drop the sink will replace); the **real** `registerAllCommands` against `package.json` (123 registered / 70 contributed / 53 internal, each internal id with its `kind`; the 17 `pending-removal` ids are W2c's list; `codexr.servers.refreshServers` is fenced as a legacy alias).
+- *The ratchet* (`test/tooling/guardrailRatchet.test.cjs`): tight in both directions; `--write` refuses a regression without `--allow-regression ""`.
+- *H1 / H2 tooling*: `scripts/dist-fingerprint.mjs`, `scripts/dist-diff.mjs`.
+- *Contract and sync tests, each written by one agent and then attacked by a reviewer for vacuity*: XR parser copy/guard/ship sets; the 16 watcher extensions outside the metric contract; the two live language tables with their divergences; test-side vs shipped runtime assembler; browser `buildOfflineDelta` vs extension `buildDelta`; avatar ids across six declarations; controller-view routing across four tables; three copies of two runtime helpers; analyzer dispatch per extension; dependency-engine goldens; first behavioural net for `visualize_data` and `visualization_settings`; every shipped resource has a consumer; the DOM scene loads nothing from `common/`.
+- *CI*: `.github/workflows/ci.yml` (+ `.nvmrc` = 24). **Not run yet** - it needs a push, which waits for the maintainer.
+
+**Found while building the net — real behaviour, pinned as it is, recorded for 1.3.0** (none of these is a cleanup):
+1. **The dependency engine is not deterministic across processes.** `_normalize_reference` returns `list({...})` and the first candidate that resolves wins, so with the fixture corpus `#include "shared.h"` resolves to `shared.h` or to `shared.gd` depending on the interpreter's str hash seed. The goldens neutralize it with a sorting shim that must be deleted in the same change that makes the list ordered.
+2. `JsonFieldAnalyzer.analyzeRecord` does `return` instead of `continue` on a null value: every field after the first null in a record is skipped for that record.
+3. In brace languages `_infer_class_owner` makes a top-level function declared after a class a method of that class; with lizard the class counter reports the blank line above a class, so Python methods lose their owner; owner-by-name is a substring test (`rebase` belongs to `Base`).
+4. `fileXRParser` copies `main.js` with a bare `copyFile` that is silently skipped when its source is missing, while `directoryXRParser` hard-fails on the same condition.
+5. `resources/languages_icons/color/rust.svg` ships although no live code can reach it (there is no Rust entry in `languageMetadata`; the only source naming it is the dead `fileDisplayUtils.ts`).
+6. `iconId` in `languageMetadata` and the `icon` field `getLanguageByExtension` adds have no reader anywhere; Fortran's extension order differs between the two live tables.
+7. Visualization settings: storage and accessors disagree (for a file without colours the accessors return the globalState colours, `getSettings()` the defaults); the legacy migration has no "migrated" flag and every save still mirrors into the legacy key, so a deleted settings file is silently rebuilt. The audit labelled that migration "1.1.0 -> 1.2.0"; the three files are byte-identical from tag `v1.0.0` to HEAD, so it is older. It stays protected either way.
+8. The `|auto` branch of the `clientCore.js` avatar regex is unobservable (a rejected id falls back to the default, which is also `auto`); the room server trims padded ids while the model and the browser reject them.
+9. `analyze_classes` and the comment analyzer are silent for nine and six contract extensions respectively (`.pyw .pyi .rbw .mjs .cjs .hxx .zig .ttcn .ttcn3` / `.pyw .pyi .phtml .php3 .php4 .php5`).
+10. A cache-only refresh of the dependency engine loses per-file read warnings; its "hash-based" cache writes `content_hash` but never compares it.
+
+**Corrections to the audit, measured:** 22 copy steps / 23 guard clauses in `fileXRParser` (not "24 assets"); 51 analysed and 54 labelled extensions (not "60-odd"); four controller-view tables (not two); six avatar-id declarations (not four); `test/python/directory_scanning/` had no `__init__.py`, so its three tests had never run - and could not have passed.
+
+**CHANGELOG:** no entry. W0 and W1 are internal; a user upgrading sees nothing.
+
+**Deliberately not touched:** everything under `src/`. The "plus comment" half of roadmap row W1-08 (a comment above the guard in `fileXRParser.ts`) waits for W4-T09, which edits that block anyway.
+
+**F5 checklist for the maintainer:** none for this wave - nothing that runs in the extension host changed.
+
+### CHANGELOG entry for 1.2.1, provisionally dated — DONE [confirmed] (2026-09-18, rama `v1.2.1`)
+
+Maintainer's request: keep `[1.2.0] - 2026-07-30` (it already was), and give 1.2.1 a real entry dated **2026-09-18** "for now", stating that the release adds nothing and consists of internal code improvements. This supersedes the line "CHANGELOG: no entry" in the W1 log above: the release as a whole gets ONE user-facing summary ("Internal improvements" + "Fixed"), not a line per internal commit.
+
+Rules that follow from it: the date is **provisional** — move it forward when the release is actually cut; when W2 lands the authorized removals (Hello World command, the 17 unreachable commands, the hidden debug command) they go under a `#### Removed` heading in that entry, and the logging move goes under `#### Changed`; the numbers in the entry (554 -> 708, 29 -> 52) are end-of-W1 values and should be refreshed at release time.
+
+Docs that still said `[1.2.1] – Unreleased` were corrected in the same commit (CLAUDE.md, INDEX.md, AI_WORKFLOWS.md, the `cleanup` skill, this file's branch-state section). Gate: `npm test` 708/708.
+
+Then pushed `v1.2.1` to `origin` at the maintainer's request. **No merge and no pull request into `master`.** Consequence to keep in mind: `.github/workflows/ci.yml` triggers on pull requests to `master`, on pushes to `master` and on manual dispatch (which GitHub only offers once the workflow file exists on the default branch) — so the new CI has still not run.
+
+### 2026-11-25 — Repository restructured as an npm-workspaces monorepo [confirmed]
+
+**Ask (user, TFM epic #11)**: prepare the repository for the Code-XR IDE (Electron + Monaco) by moving and organizing the code into a monorepo, without starting the IDE. Branch `claude/project-thread-2djsoy`, cut from `v1.2.1` at `8a0d7b2b`.
+
+**Layout**: extension → `apps/vscode-extension/` (all its relative paths unchanged inside it); Python backend `src/code_analysis/python/` → `backend/src/`, `test/python/` → `backend/tests/`; `apps/ide/` and `packages/` are README-only placeholders; root keeps `media/`, `pages/`, `.github/`, `.claude/`, `.vscode/`, the only lockfile and a workspace `package.json` mirroring every script. Rationale and the full before/after table: `docs/monorepo.md`.
+
+**Not extracted (deliberately)**: `packages/xr-scenes` (templates are resolved at runtime from `context.extensionPath/templates` and ship via the `files` allowlist) and `packages/core` (the TS logic imports `vscode` throughout; needs the W5-style separation first). Reasons in `packages/README.md`.
+
+**Proof of neutrality**: same 360 VSIX files, all byte-identical except `dist/extension.js`, the lazy chunk (renamed `268` → `515`, token-identical) and `package.json` (script paths, `overrides` moved to the root). The bundle differs, token by token, only in webpack numeric module ids and in the development fallback paths to `/backend/src` in `executePython.ts` and `gitRevisionExporter.ts`. Gate 707/708 on Linux before and after (the failure is the pre-existing Windows-path assertion in the unified decorator test, unchanged); Python 52/52; HTML DOM 12 + 5; per-language fixtures green; `compile:dev-host` stages correctly.
+
+**Fixes the move exposed**: (1) vsce would pull the hoisted root `node_modules` into the VSIX (671 files) → `--no-dependencies`; (2) with an absolute `from`, copy-webpack-plugin's `__pycache__` ignore stops matching → `context` + relative `from`, and `noErrorOnMissing: false` for the backend; (3) vsce rewrites README links against the repo root → `--baseContentUrl`/`--baseImagesUrl` with the package subpath; (4) `uiPolicy.test.cjs` silently skipped missing folders (the `.claude` scan would have gone vacuous) → it now asserts every scanned root exists, and scans `backend/` too.
+
+**CI**: matrix extended to macOS (non-blocking like ubuntu) and triggered for PRs to release branches (`v[0-9]*`) as well as `master`.
+
+**Impact on the rest of the programme**: the W2-W5 tables in `v1.2.1/ROADMAP.md` name files by their pre-move paths; read them with the path convention in `CLAUDE.md`. Git rename detection carries edits made on `v1.2.1` onto the moved files when merging.
+
+### Fix: Git target behind a symlink or a Windows short path — DONE [confirmed in tests] (2026-11-25, branch `claude/project-thread-2djsoy-git-realpath`)
+
+**Found by** the first CI run (PR #24, monorepo): 8 Git tests in `gitRevisionExporter.test.cjs` / `historicalComparison.test.cjs` failed on windows-latest and macos-latest with `analysis-target-outside-repository`, never on a developer machine. **Root cause**: `GitRepositoryService.resolveTargetRelativePath` did `path.relative(repositoryRoot, targetPath)` with `repositoryRoot` from `git rev-parse --show-toplevel` (canonical) and `targetPath` as given; `os.tmpdir()` is `/var/...` -> `/private/var/...` on macOS and `C:\Users\RUNNER~1\...` on Windows, so they never shared a prefix. Users hit it with any workspace opened through a symlink/junction or a short path. **Fix**: compare `fs.realpathSync.native` of both sides (falls back to `path.resolve` when the path cannot be resolved). **Behaviour change, user-approved** (decision 2026-11-25), recorded under CHANGELOG `[1.2.1]` → Fixed. **Test**: new `historicalComparison.test.cjs` case with a junction-linked repository (fails before: `analysis-target-outside-repository`; passes after) plus a real outside-folder rejection. Gate 708/709 on Linux (the one failure is the pre-existing Windows-path assertion in the unified decorator test).
+
+### Epic #26 deep cleanup, closed by #43 final verification — DONE [confirmed] (2026-11-25, PRs #44-#65 into `v1.2.1`; #43 on branch `claude/project-thread-n2s3q6-final-verification`)
+
+**What landed**: 20 pull requests (#44-#65) executed waves W2-W5 of `v1.2.1/ROADMAP.md` plus the post-monorepo sweep, the layering work, the feature-first `src/` layout (#55) and the idiom modernization (#56). One log per story, each with its commits, before/after numbers, gates, what was left and its F5 list, in `v1.2.1/sessions/`:
+`29-dead-code.md`, `30-authorized-command-removals.md`, `31-assets-media-tooling.md`, `31-python-dead-code.md`, `31-templates-runtime.md`, `32-monorepo-seams.md`, `33-guardrails.md`, `34-logging.md`, `35a-ts-pipeline.md`, `35b-ts-dedup.md`, `36-python-backend.md`, `37-runtime-dedup.md`, `38-git-services.md`, `39-server-splits.md`, `40-tree-assets.md`, `41-vsix-size.md`, `42-layering.md`, `55-src-layout.md`, `56a-modernize-py-js.md`, `56b-modernize-ts.md`.
+
+**Final verification (#43, on `913cb362`)**: `npm test` 1,064/1,064 (lint 0 errors, 158/158 warnings); `test:python` 73; `test:analysis` green (24 root + 3 deep fixtures); `test:htmlanalysis` 12 + 5; `lint:python` clean; the four browser harnesses pass with the CDN scripts served locally (the sandbox proxy refuses the CDNs); `package:vsix` 4,204,772 bytes / 199 files; CI green on three OSes on PR #65. The packaged VSIX was driven end to end under the fake `vscode` host with a real venv, real servers and headless Chromium (`@vscode/test-electron` cannot download VS Code here). Story #27: `test/baseline/featureBaseline.test.cjs` green without `--write`.
+
+**Epic before/after (`399494af` → `913cb362`)**: `src/` 369 → 291 files, 52,988 → 49,064 lines; unreachable modules 54 → 0; `console.*` 1,646 → 2; `any` 219 → 84; CCN over 20 10 → 0 (worst 61 → 20); files over 600 lines 11 → 6; folders 179 → 98, barrels 82 → 0; tests 708 → 1,064, backend 52 → 73; VSIX 6.45 MB / 360 → 4.20 MB / 199.
+
+**Exit criteria**: 20 of 27 met, 2 partial (complexity still a warning; CI "required" needs branch protection), 5 not met with recorded reasons (9 dead exports, `src/` 64 lines over 49,000, Python worst CCN 18 in the do-not-touch schema contract, 6 files over 600 lines, largest file 850).
+
+**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.
+
+### XR bug-fix epic #72 — S6 cancellable jobs (#78) [confirmed by unit tests] (2026-11-25, PR #91 merged into `v1.2.1`)
+
+**What changed**: `core/analysis/launch/jobRunner.ts` (new) replaces `SingleJobGate`: atomic `tryReserve` before the first await, cancel that reaches the Git/Python children through the launch signal, a deadline per job (evolution 30 min, comparison 15, dependency graph 10), late results discarded, slot held until the work ends (grace 5 s). Per-revision watchdog (5 min) and per-Git-command timeout (3 min); a cancelled analysis is never recorded as a deterministic exclusion. Evolution and comparison runtimes gained Cancel. `projectEvolutionArtifacts.ts` split out of the service (filesOver500 must not grow).
+
+**Measured**: `npm test` 1,135/1,135; ESLint warnings 155 → 154 (budget lowered). Not done: the real Python kill path needs a manual check; HIST-10 and the piling-up dependency dataset revisions (second half of DEPGRAPH-9) are out of scope.
+
+### XR bug-fix epic #72 — S9 panels without overlaps (#81) [confirmed by unit tests + a real A-Frame page] (2026-11-25, branch `claude/project-thread-kvvyg6-panels`)
+
+**What changed**: new runtime part `virtual-screen/virtualScreenRuntime/placementRegistry.js`: the obstacle registry (other screens, any shown entity tagged `data-codexr-panel-obstacle`, the analysis table plus 2.2 m of chart headroom), an oriented-box separating-axis test replacing the 9-point sampling against obstacles, `findFreePlacement` (right, left, up, rings of one screen size plus 0.25 m) used by add/Bring, and an escape so a screen already inside an obstacle is not frozen. Follow now goes through `constrainPosition`. Added screens read the scene config (`readSceneConfig`, JSON script first) and label with their display name. Dependency-graph legend: `legendSlotPosition` gained `maxRows` (2), pinned cards a close button; the legend board and the evolution playback overlay register as obstacles.
+
+**Measured**: `npm test` 1,138/1,138; ESLint warnings unchanged at 154. In Chromium + A-Frame 1.7.1 (scratch page, not committed): before, two added screens both at (0, 2.30, -10.20); after, (0, 2.40, -10.40) and (5.05, 2.40, -10.40); with the table in front of the user the screen goes above the chart volume (y 5.35); a followed screen stops at another screen. Not done: text sizes for VR legibility need a headset (manual guide); the evolution overlay keeps its fixed position (now an obstacle, not moved).
+
+### XR bug-fix epic #72 — S10 reliable project evolution (#82) [confirmed by unit tests + harnesses] (2026-11-25, branch `claude/project-thread-kvvyg6-evolution`)
+
+**What changed**: EVO-5, frames load by their own immutable `dataN.json` URL. The `data.json` bridge is gone, `applyFrameToBridge` became `resolveFrame` (validation only), and apply-frame errors go to the requester only. LIFECYCLE-4, a half-built pipeline is torn down (`failEvolutionPipeline`) and component waits went from 1200 to 4000 ms. EVO-14, progress carries `completed` and the bar is monotonic. EVO-8 (partial), revision analyses run `silent`, snapshots are released after each analysis, and the payload cache is an LRU of 128. EVO-11, one `revision-N` on disk, Clear removes `evolution/`, and revision numbers never reuse a folder. EVO-15, Play at the end restarts, a same-revision replay keeps `frameIndex`, and `setSpeed` does not re-arm under a seek. EVO-13, manual picks are sorted chronologically online and more than `maxFrames` is refused on both ends. EVO-18, the remote HEAD alias is filtered by full ref. EVO-1 was already covered by S6 (plus `applySharedState` now ends `generating`).
+
+**Measured**: `npm test` 1,139/1,139; ESLint 154 (unchanged); filesOver500 unchanged (`resolveEvolutionFrame`/`evolutionDirectoryOf` moved to `projectEvolutionArtifacts.ts`). Harnesses xr-mode, project-evolution (now asserts each frame loads `data.json` and that no bridge file exists) and xr pass. **Not done**: live evolution still materializes snapshots with one `git show` per file and runs the directory analysis per revision; reusing the export's blob pipeline (`GitTimelineBlobAnalyzer` + worker pool) needs a payload-parity check first and is left as follow-up.
+
+### XR bug-fix epic #72 — S11 evolution follows the checked-out history (#83) [confirmed by unit tests on real repositories] (2026-11-25, branch `claude/project-thread-kvvyg6-history`)
+
+**What changed**: EVO-6, `listTimelineSources(maxCount, tip = 'HEAD', exclude?)` walks `git log --first-parent` of HEAD (or a range tip), never `--all`; the picker's commit list is `--branches --tags --remotes` (no stash, no notes). EVO-7, new `core/history/projectEvolutionTimeline.ts`: the Auto movie lists the whole first-parent history and thins it to `TIMELINE_SCAN_SAMPLE` = 240 spread over all of it (first and last kept), so the eligibility index and the picker cost what the old newest-240 window cost; a range is resolved by Git (`isAncestor`, `mergeBase`, `listTimelineSources(null, newer, older)`), in either order, diverging ends from their merge base; `resolveTimelineIndex` and `TIMELINE_SCAN_LIMIT` are gone; tags whose peeled object is not a commit are dropped. EVO-12, no 1000 clamp, and the timeline log is streamed through the new `core/history/gitLineStream.ts` (spawn + readline, same timeout, cancel signal and error codes as `runGit`); `countTimelineCommits` is `rev-list --first-parent --count HEAD`, 0 in an empty repository. The export prompt names the checked-out branch's history. EVO-19, `PROJECT_EVOLUTION_XR.md` rewritten for the timeline and the export.
+
+**Measured**: new `test/analysis/gitTimeline.test.cjs` (7 tests on real repositories: stash + notes + newer branch + detached HEAD, merge as one step, 300 commits sampled from the root with an old tag as range start, range in either order and across diverging branches, tree tag not offered, 1,100 commits with latest 1,050 returned, empty repository). Behaviour change for the export: other branches are no longer exported, by design of the story.
+
+### XR bug-fix epic #72 — S12 historical comparison stays correct over time (#84) [confirmed by unit tests + xr-mode harness] (2026-11-26, branch `claude/project-thread-kvvyg6-historical`)
+
+**What changed**: HIST-1, `AnalysisFeatureHost` retries a failed live refresh at 0.7 s and 1.4 s (`HISTORICAL_REFRESH_MAX_ATTEMPTS` = 3), only while the view is History, then broadcasts `historical-comparison-error` (`comparison-live-refresh-stopped`), sends SSE `historical-progress` state `error` to LivePanel (HIST-13) and calls the new `HistoricalComparisonService.suspendLiveRefresh()`, cleared by the next successful comparison; the historical wiring moved to `attachHistoricalComparison()`. HIST-4, a refresh skipped outside History runs on re-entry (`onStateChanged`); the client stores `state.result` before any await and decides against `refs.renderedResult`. HIST-2, `listReferences` no longer clears `sourceById`; `resolveSource` reports a deleted ref as `comparison-reference-not-found`. HIST-5, `materialize(source, { recursive })` from `session.isDeep`; the snapshot plan moved to the new pure `core/history/gitSnapshotPlan.ts`. HIST-8, only the current and previous `comparison/revision-N*` files are kept, and every snapshot `fs.rm` uses `maxRetries: 5`. HIST-10, `classifyHistoricalComparisonError` gives `comparison-reference-gone`, `-snapshot-limit`, `-step-timeout`; the client shows them and clears the loading text after a render. HIST-11, `PICKER_COMMIT_COUNT` = 200 and `isDeterministicNoDataError` no longer matches process failures.
+
+**Measured**: `npm test` 1,158/1,158; ESLint warnings 154 → 152 (budget lowered); `test:xr-mode-harness` passes. New `test/analysis/historicalStaysCorrect.test.cjs` (9 tests). Not done: a polling status endpoint for LivePanel after an SSE drop (HIST-13 second half), and a "load more" beyond 200 commits.
+
+
+### XR bug-fix epic #72 — S13 dependency graph with correct numbers (#85) [confirmed by unit + backend tests; headset frame time not measured] (2026-11-26, branch `claude/project-thread-kvvyg6-depgraph`)
+
+**What changed**: engine (`backend/src/utils/dependency_analysis_engine.py`): DEPGRAPH-2, an unresolved `call` is dropped in directory mode as in file mode, `CALL_KEYWORDS` gains `this/super/self/constructor/async/await/...`, receivers `this.`/`self.`/`super.` and definition sites (`def|function|func|fn|fun|sub|proc|method` before the name) are skipped; the `with` mixin pattern needs a declaration line and the Ada `with` import its `;`. On `apps/vscode-extension/src` (298 files) external nodes went from ~2,450 (audit) to 30. DEPGRAPH-3, `_normalize_reference` is an ordered `dict.fromkeys` list, new `_relative_reference_keys` / `_resolve_reference` / `_path_keys` resolve `./`, `../` and Python leading-dot specifiers against the importer's folder first (exact full-path lookup, `index`/`__init__`/`mod`), with a stem fallback downgraded to `probable`; the bare `import x` patterns skip `import type` and lines with `from '...'` (`_NOT_JS_IMPORT`); `executePython.ts` spawns with `PYTHONHASHSEED=0`. DEPGRAPH-10, file node ids hash the exact path. Runtime: DEPGRAPH-1 `addNodeMetrics` sums only lines/files/files-in-cycle, `aggregateMetricsFromEdges` recomputes fan-in/out/degree/relations of `group` nodes from the drawn edges after the filters; cards show Files and "In cycles" (folders) / "Cycle size" (files). DEPGRAPH-5 `applyRenderBudget` (600/2,000, "N more" node `scope:budget-rest`, status notice) and a real Fruchterman-Reingold force-3d. DEPGRAPH-6 `isGraphComponentReady` gates `setGraph` on `initialized`, `init` terminates a pre-init worker, Blob URL revoked, `worker.onerror`. DEPGRAPH-4/8/11 entity carries `projectDatasetUrl` + `fileDatasetUrl`/`fileDatasetPath`; the settings handler pairs scope and URL (`scopeWithItsDataset`) and refuses a file scope without its dataset; `openFile` always asks the server (offline exports use the cache); `datasetUrlForScope`, `setProjectDataset` (clears file datasets on a new revision), `loadProjectDataset` re-checks snapshot identity. The golden test's `canonical_candidate_order` shim is gone (its docstring said to delete it with this fix) and the goldens regenerated: the diff is the fix (junk call externals gone, `shared.h`→`shared.h`, `import './shared.sol'`→`shared.sol`, double-counted default imports once).
+
+**Measured**: new `backend/tests/dependencies/test_dependency_resolution.py` (8 tests, three hash seeds in subprocesses) and `test/analysis/dependencyGraphS13.test.cjs` (6 tests: folder card on a 3-file fixture, 2,000-node budget, >20 distinct radii for 300 nodes inside the table with linked nodes closer, Blob URL revoked, init gating, scope URL choice, cache invalidation); one bridge test added, two bridge tests and the shared-state characterization updated (`project after snapshot replaced` now drops the stale project dataset). Not done: DEPGRAPH-9 (job cancel, revision pruning), the harness scenarios of DEPGRAPH-12.
+### XR bug-fix epic #72 — S14 cross-platform and offline Git/Python paths (#86) [confirmed by unit tests on Linux, Windows-only behaviour emulated; maintainer to check on Windows] (2026-11-26, branch `claude/project-thread-kvvyg6-platform`)
+
+**What changed**: EVO-9, `gitExportPythonWorkerPool.ts` spawns the export worker with `PYTHONUTF8=1`/`PYTHONIOENCODING=utf-8` and writes commands through the new `asciiJson` (non-ASCII escaped as `\uXXXX`); `git_export_analysis_worker.py` reads `sys.stdin.buffer` decoded as UTF-8 and no longer uses `unlink(missing_ok=True)` (Python 3.8+). LAUNCHER-15 was already fixed (executePython env + `setEncoding`); pinned by a test. HIST-6, `toPortableRelativePath` (`gitAnalysisShared.ts`) compares both sides in the drive-less POSIX form Python uses, platform-independent (`path.posix`, own absolute check), with a case-insensitive fallback; UNC roots work. EVO-10, new `core/history/gitOfflineEnvironment.ts`: every history git process (`runGit`, `runGitBuffer`, `streamGitLines`, both `cat-file` batch readers) runs with `GIT_NO_LAZY_FETCH=1`, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`; "could not fetch ... from promisor remote" becomes `git-object-missing: ... (partial clone)`, which `isDeterministicNoDataError` treats as an exclusion.
+
+**Measured**: new `test/analysis/crossPlatformOffline.test.cjs` (4 tests; the partial-clone one builds a real `--filter=blob:none` clone of a `file://` origin, asserts the rejection and an unchanged object count, and fails without the env: verified) and a worker test run under `PYTHONIOENCODING=cp1252` with a raw-UTF-8 `Adrián/código` path (fails without the worker fix: verified). Not done: a promisor-remote notice in `getAvailability()`; real Windows/macOS runs beyond CI. CI follow-up: Git 2.56 (the runners) lists a missing blob in `ls-tree -l` with size `BAD` instead of failing (2.43 fails; `-` is also handled), and `planTreeEntry` dropped the line as unparsable, so the partial-clone test passed on 2.43 and failed in CI; a blob with a non-numeric size is now `git-object-missing` (`gitSnapshotPlan.ts`, new test in `gitMaterializeDirectory.test.cjs`), and the real-clone test skips when Git kept the blob.
+
+### XR bug-fix epic #72 — S15 automated tests that run real scenes (#87) [confirmed: all five harnesses pass offline locally; CI job result in the PR] (2026-11-26, branch `claude/project-thread-kvvyg6-harnesses`)
+
+**What changed**: `test/vendor/scene-libraries/` holds the six CDN builds the scenes load (aframe 1.7.1, aframe-babia-components 1.3.4, aframe-extras 7.5.4, aframe-environment-component 1.5.0, aframe-geometry-merger-component 2.0.1, html2canvas 1.4.1), byte-identical to the CDN files, with their licences and a README naming each source URL. `test/helpers/harnessBrowser.cjs` (`launchHarnessChromium`) routes those URLs to the vendored files and aborts every other non-local request, and all five `test/runners/run-*harness.cjs` use it. `npm run test:harnesses` (root and workspace) chains the five; `.github/workflows/ci.yml` gains a `harnesses` job (ubuntu-latest, `npx playwright install --with-deps chromium`). The immersive harness viewport went from 1280x900 to 640x480: on a software-rendered Chromium a frame took ~217 ms, over aframe-extras' 200 ms cutoff in `movement-controls`, which zeroes velocity, so the locomotion check failed intermittently; at 640x480 it passed 3/3. The emoji policy in `uiPolicy.test.cjs` skips `vendor/` directories (third-party text kept as released). Shipped code: none (nothing under `src/`, `templates/` or `examples/` changed).
+
+**Measured**: `test:xr-harness`, `test:xr-chart-bounds-harness`, `test:xr-mode-harness`, `test:xr-immersive-harness`, `test:project-evolution-harness` all pass with the network blocked; `npm test` green. Not done: the DEPGRAPH-12 scenarios (budget notice and folder cards in the mode-cycle harness) stay open in #85's notes.
+
+### XR bug-fix epic #72 — follow-ups left out of S13/S14 (DEPGRAPH-9 pruning, DEPGRAPH-12 harness scenarios, partial-clone notice) [confirmed by unit tests and the mode-cycle harness] (2026-11-26, branch `claude/project-thread-kvvyg6-leftovers`)
+
+**What changed**: DEPGRAPH-9: job cancel and timeout already landed with S6 (`JobRunner`, `dependency-graph-cancelled/timeout`); what was left is the files. `DependencyGraphService` now writes compact JSON and, after each write, `pruneDatasetRevisions` keeps only the newest `KEPT_DATASET_REVISIONS` (2) `dependency-graph-.json` and `dependency-scope-.json` in the served `dependencies/` folder (the one the room entity points at plus the one a page may still be fetching); a file still open elsewhere is left for the next pass. `dependency-graph.json` at the root stays (the LivePanel summary reads it). Partial-clone notice: `GitRepositoryService.listReferences()` adds `partialClone` / `notice` (from `git config --get-regexp '^(extensions\.partialclone|remote\..*\.promisor)$'`, `isPartialCloneConfig`, `PARTIAL_CLONE_NOTICE` in `gitOfflineEnvironment.ts`); the XR selection panel and the LivePanel history panel show it when the references arrive. DEPGRAPH-12: `test/manual/xr-mode-cycle-harness.html` takes the room entity from `window.__DEP_STATE`, records every message in `CodeXRHarness.sent`, and answers `dependency-graph-settings` and `dependency-file-scope-request` like the bridge (scope plus `fileDatasetUrl`, new fixture `xr-mode-dependency-scope.json` produced by the real engine); `run-xr-mode-cycle-harness.cjs` adds four scenarios: drill into a file then reload as a late joiner with the entity left behind, a generated 900-node project past the render budget (600 nodes, notice, every node on the table), three enter/leave cycles with at most one live layout worker, and entering while a refresh is `analyzing` then drawing when it lands.
+
+**Measured**: new tests in `dependencyFileScope.test.cjs` (5 cache hits leave 2 scope files, compact; prune by number per prefix) and `crossPlatformOffline.test.cjs` (real partial clone reports `partialClone: true` with the notice, the full origin `false`; config parser; both UIs read `notice`); `test:xr-mode-harness` passes 3/3 in about 30 s. Not verified: the notice text on a headset (manual guide row 4.3).
+
+### XR bug-fix epic #72 — robustness pass on the remaining minor findings (#109) [confirmed by unit tests, real-browser probes and the XR harnesses] (2026-11-26, branch `claude/project-thread-svsl9c-robustness`)
+
+**What changed**: CHARTS-16: `babiaCompat.js` wraps `babia-pie`/`babia-doughnut` init so the chart element's `removeChild` ignores a `.babiaxrLegend` that is no longer its child (Babia's `mouseleave` after a rebuild); every other `removeChild` keeps the native error. CHARTS-18: `escapeChartTitleForComponent` (`createChart.ts`) turns `;` into `,` (A-Frame has no escape for it) and HTML-escapes the title, including `$ { }`, so it cannot become a placeholder; `replacePlaceholders` uses a function replacement (`$&` in a value is text). `buildFilteredBounds` skips the subtree of a hidden node; the measured root stays exempt because containment measures a chart while it is hidden. EVO-16: both transitions in `framePlaybackEngine.js` run in try/finally and cancel when nothing settled them. LIFECYCLE-11: dependency-graph `mount` warns once when it gives up after 3 s, naming what was missing; analysis-view `registerCollaboration` logs once (info) after ~1 min. LIFECYCLE-12: the `single` activation's `waitForNormalChartReady` has a `.catch` that logs and still shows the chart. DEPGRAPH-7: `publishState` while locked shows "Busy, please wait..." and the unlock clears it only if it is still the shown message. HIST-8: `historical-comparisons` is in `getSweptStorageFolders()` (`HISTORICAL_COMPARISON_STORAGE_FOLDER`), and `HistoricalComparisonService.dispose()` `rmdir`s the emptied `` folder (a non-empty one is left for the sweep).
+
+**Measured**: new `xrRobustnessPass.test.cjs` (12 tests, each fails on the old code) plus the dispose assertion in `gitHistoryServices.test.cjs`; `npm test` passes (extension 1197, IDE 57). Real Chromium on generated scenes: `pie-legend` / `pie-legend-switch` probes give no page error (before: `removeChild` NotFoundError); a scene titled `my;proj` has `title: Directory Analysis: my,proj;`. Not verified: the busy notice and pie hover in a headset (manual guide). Known limit: the startup sweep, like the existing folders, cannot tell a live session of another VS Code window on the same workspace from a stale one older than this activation.
+
+### XR bug-fix epic #72 — #105 partial clones on Git 2.43 (EVO-10 follow-up) [confirmed by unit tests on Git 2.43 and the verification repro] (2026-11-26, branch `claude/project-thread-svsl9c-partial-clone`)
+
+**What changed**: with `GIT_NO_LAZY_FETCH`, Git 2.43 answers a missing promisor object by dying (`fatal: could not fetch … from promisor remote`, exit 128) instead of printing `missing`; `GitBatchMetadataReader` and `GitBatchObjectReader` then failed every queued and future request, so the catalogue excluded every revision, HEAD included. Both readers now share `GitCatFileProcess` (`gitBatchObjectReader.ts`): when the process dies with a partial-clone diagnostic, the request at the head of the queue (Git answers in order and flushes each answer, so it is the one that killed it) is rejected with `PARTIAL_CLONE_MISSING_MESSAGE`, a new process is started and the rest of the queue is re-sent; every restart consumes one request, so it cannot loop. A ` missing` line or a non-numeric size (newer Git) for a full object id is mapped to the same message. `classifyIndexedRevision` shows that message as the reason as is. `gitOfflineEnvironment()` adds `GIT_ALLOW_PROTOCOL=codexr-offline` (no transport allowed), so a Git without `GIT_NO_LAZY_FETCH` (upstream < 2.44; Ubuntu's 2.43 has it backported) still cannot fetch. Docs: oldest Git tested is 2.43 (`HISTORICAL_COMPARISON_XR.md` limits, `PROJECT_EVOLUTION_XR.md` limits).
+
+**Measured**: verification repro `partial.cjs` (5 commits, 4 blobs missing) on Git 2.43: before, picker `['main (live)']` and generate "1 remain after filtering"; after, picker `['main (live)', 'origin/main', 'facaa2b0']`, generate 2 frames, the 4 incomplete commits excluded with the partial-clone reason, missing blobs 4 → 4. Three new tests in `crossPlatformOffline.test.cjs` (both readers with missing objects interleaved and recovery afterwards; `GitTimelineBlobIndex` keeps HEAD and excludes the two incomplete revisions; lazy fetch blocked without `GIT_NO_LAZY_FETCH`), all failing on the old code (verified). Inferred, not run here: CI's newer Git reports the object instead of dying, which the same tests cover through the `missing`/non-numeric-size branch.
+
+### XR bug-fix epic #72 — independent verification of the fixes [confirmed by re-running the audit repros and new probes] (2026-11-26, branch `claude/project-thread-svsl9c`)
+
+**Result** (`docs/xr-audit/verification/`): on `v1.2.1` @ `6f827a19`, 80 of 102 audit findings fully fixed, 17 partial, 4 minor still failing (CHARTS-16, EVO-16, HIST-12, LIFECYCLE-8), 1 manual-only (PANELS-8). All 6 blockers fixed. Partial majors: PANELS-3, EVO-2, EVO-8, EVO-10 (git 2.43 partial clones), HIST-3, HIST-7. Gate: unit 1173/1173, Python 83/83, all five harnesses pass; `test:xr-immersive-harness` still fails under heavy CPU load (aframe-extras 200 ms frame drop). No code changed; follow-up issues are proposed in the verification README, not yet created.
+
+### XR bug-fix epic #72 — comparison keeps its data on every chart switch (#107: HIST-3, HIST-12, LIFECYCLE-8) [confirmed by unit tests + the mode-cycle harness] (2026-11-26, branch `claude/project-thread-svsl9c-compare-charts`)
+
+**What changed**: HIST-3, a chart entity can now declare its own sources: `entity.__codexrChartSource(chartId)` returns `{ from }` or `{ data, field }`, and `applyChartTypeToEntity` (mapping runtime, new `buildEntityChartData`) follows it instead of guessing from the previous `from` (which sent Bars→Boats to `tree` and Boats→flat to `data`). Each comparison clone declares its side: flat charts read `codexrComparisonData{Left,Right}` (sliced as before), boats an inline tree of that side's payload (`buildComparisonSideTree`, namespaced `codexr-left/right`). Both producers are now created whatever the first chart is, and a live refresh updates the side's producer under boats too. HIST-12 / LIFECYCLE-8, `createChartFromTemplate` copies only `COMPARISON_CLONE_INHERITED_ATTRIBUTES` (`codexr-boats-layout-stability`); everything else is derived, so no `data-codexr-*` marker of the scene chart reaches a clone. The mode-cycle harness now wraps the chart in `#codexrAnalysisSurface > #codexrNormalAnalysisRoot` like `xr-visualization.html`, its history fixtures carry `filePath`, and `run-xr-mode-cycle-harness.cjs` gained `runComparisonScenarios` (enter; Bars→Boats→Bars→Boats→Cyls→Pie; leave to single; re-enter; Boats/Bars again), with the scene chart stamped with normal-root markers to reproduce the old leak.
+
+**Measured**: `npm test` passes (extension 1,187/1,187, IDE 57/57); ESLint warnings 151 (unchanged); `test:xr-mode-harness`, `test:xr-harness`, `test:project-evolution-harness` pass. The new harness scenario fails on the previous runtime (copied marker). **Observed, not changed**: the controller's chart type is shared across modes, so re-entering the comparison after the Normal analysis shows it on the Normal analysis' chart type, not the one it was left on (data stays correct).
+
+### XR bug-fix epic #72 — screens never hide each other or leave the room (#103, PANELS-3/9) [confirmed by the new panel-placement harness and unit tests; headset feel not checked] (2026-11-26, branch `claude/project-thread-svsl9c-panels`)
+
+**What changed**: `placementRegistry.js` (virtual screen runtime): `findFreePlacement` now takes the viewer position and tests each spot with the pose the screen will actually take (facing the viewer). A spot is blocked when it intersects an obstacle **or** when its silhouette seen from the viewer overlaps another screen's or a tagged panel's (`hidesAnotherPanel`; screens and `data-codexr-panel-obstacle` entities carry `occluder: true`, the table/chart volume does not). Every spot tried is clamped into the room shell first (`clampIntoRoom`, twice, since the face-the-viewer turn changes the extents), and "nothing free" returns the clamped target instead of the raw one. Corners beside or behind the viewer are pulled onto a near plane instead of being ignored (a 4.8 m screen turned toward the user reaches past them; ignoring it let the guide land in front of it). `codexrCommonRuntime.js` gains `resolvePanelPlacement(panelEl, target, { size, viewer, avoidTable, preferUp })`, the same registry for non-screen panels (same obstacles, found by the same selectors; boxes from visible geometry only, because `Box3.setFromObject` counts hidden children and made a screen look 28 m wide). The evolution playback overlay is placed through it each time it is shown (preferred spot still `0 3.35 -18`, which lies inside the 2.2 m chart headroom, so it moves; up first, then sides); the field-mapping controller's adaptive corner goes through it every frame with `avoidTable: false` (it belongs at the table corner). New `test:xr-panel-placement-harness` (real room, real screen/guide/manager runtimes; part of `test:harnesses`); `buildAssembledRuntimes.cjs` also assembles the virtual screen and guide runtimes.
+
+**Measured**: the harness fails on the old runtimes for both screen cases (guide covers default; wall case root at x -12.46 vs inner wall -10.75) and passes after. Unit 1193/1193, IDE 57/57. Not verified: how the moved overlay and the side-placed screens feel on a headset (manual guide). Not done: the guide's anchor (`guideScreen.js`) is still derived from the default screen only (PANELS-9 third bullet, not in #103's criteria).
+
+
+### XR bug-fix epic #72 — LivePanel cancel and status for historical comparisons (#108, HIST-7/HIST-13) [confirmed by unit tests; the page-close beacon needs a real browser check] (2026-11-26, branch `claude/project-thread-svsl9c-livepanel-history`)
+
+**What changed**: `HistoricalComparisonService` gained `getComparisonStatus()` (mapping in the new vscode-free `core/history/historicalComparisonStatus.ts`, kept out of the service so it stays under 500 lines: idle/running/done/error, `jobId`, last successful `revision`, message; a timed-out job is `error`) and `cancelComparisonWithoutResult()`, which spares the job that is a live refresh (`refreshActiveComparison` now reserves its own ticket and records `refreshJobId`). `HistoricalComparisonBridge`: new `POST /api/historical/cancel` (optional `jobId` scope) and `GET /api/historical/status`, routed in `httpServer.ts`; the room cancel and the REST cancel share `cancelRunningComparison()`; a cancelled LivePanel job sends SSE `historical-progress` state `cancelled` (new state in `HistoricalComparisonProgress`), a timed-out one the timeout sentence. `AnalysisFeatureHost.handleHistoricalViewChanged()` replaces the inline re-entry listener and, on leaving `historical-compare`, cancels a job without a result and broadcasts `historical-comparison-cancelled`; a cancelled live refresh is no longer retried as a failure. LivePanel client (`historicalPanel.js`): `#historical-cancel-btn` in both templates (visible only while busy), `cancel()`, `syncStatus()` on load and after every SSE reconnect (`panelShell.js` calls it on the second and later `onopen`), and a `pagehide` beacon cancelling this page's own unfinished job by id. LivePanel has no mode switch, so "leaving History" there is closing the page.
+
+**Measured**: new `test/analysis/livePanelHistoricalCancel.test.cjs` (10 tests: status transitions over a real `JobRunner`, timeout as error, refresh spared on leave, cancel/status routes over a real HTTP server with slot freed and SSE `cancelled`, 405s and routing, room leave cancel + broadcast, cancelled refresh not retried, panel Cancel/visibility, page-close beacon, status on load and after reconnect); `livePanelSse.test.cjs` transcript gained the reconnect step. Not done: polling while the stream is healthy (the reconnect read covers a dropped stream).
+
+### XR bug-fix epic #72 — #106 faster revision snapshots for evolution and deep comparison (EVO-8 + deep historical copy) [confirmed by unit tests and a before/after measurement on Git 2.43] (2026-11-26, branch `claude/project-thread-svsl9c-batch-snapshots`, built on #105's branch)
+
+**What changed**: `GitRepositoryService.materializeDirectory` no longer spawns `git show :` per file. `planDirectorySnapshot` now also returns the blob id of each planned file (`PlannedSnapshotFile`), and the new `core/history/gitSnapshotWriter.ts` (`writeSnapshotFiles`) reads them through one `GitBatchObjectReader` (`cat-file --batch`) per revision, 16 blobs in flight, killed on the job's Cancel signal (`git-command-cancelled`). `GitSnapshotBlobStore` (one per service, `snapshots/blob-store/`) keeps the first copy of each blob and hard-links it into every snapshot that needs it (copy fallback when links fail: FAT, some shares, the NTFS link limit), so a blob unchanged across frames, or across the two sides of a comparison, is read from Git and written once. Bounded: what released snapshots leave behind is at most `MAX_SNAPSHOT_BYTES` (100 MiB); past it a blob is written straight into its snapshot. The store goes with `dispose()`, like the snapshots. A failed or cancelled read is not remembered. Single-file targets keep `git show` (one file). Partial clones: unchanged, the plan still rejects a blob listed without a size before any read, and the reader (with #105) answers a missing object with `PARTIAL_CLONE_MISSING_MESSAGE`; nothing is fetched. EVO-8's `releaseSnapshot` and the per-commit snapshot folders (#104) are untouched; #104's "snapshot released" assertion now ignores `blob-store/`.
+
+**Measured** (Git 2.43, Linux, 4 cores under load from parallel agents, two runs each; `bench.cjs`: 1,000 files in 10 folders, 24 commits changing 20 files each, recursive materialize): one 1,000-file revision **7.1–11.2 s → 0.20–0.39 s**; all 24 revisions (materialize + release) **155–289 s → 2.3–3.6 s**. Deep historical copy of the verification repo `mid` (1,501 files): **8.2–8.4 s → 0.16–0.17 s** (3 runs each; the verification measured 10.9 s). Tests: `gitMaterializeDirectory.test.cjs` characterization moved from the `git show` stub to an `openBlobSource` stub, plus three new tests (real repository over three commits: byte-identical contents including CRLF and NUL bytes, no `git show`, one reader per revision, 43 distinct blobs read once for 126 files, files hard-linked on POSIX, dispose removes the store; budget; Cancel kills the reader and keeps nothing half-read). Analysis-side dedupe (Python analysing a blob once across frames) was not done: the payload cache stays per commit.
+
+### IDE epic #11 — story #12 secure Electron scaffold [confirmed by unit tests and the smoke run on Linux; Windows/macOS by CI] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `apps/ide/` becomes the npm workspace `code-xr-ide` (Electron 45, Vite 8, strict TypeScript, no UI framework). Main/preload/renderer split with `src/shared/api.ts` as the only contract; preload exposes a frozen `window.codexr`; IPC answered only for `IPC_CHANNELS` from trusted origins; renderer served from `codexr://app/` with a CSP header; navigation, `window.open`, `` and every permission denied; `assertSecureWebPreferences` checks the live window at startup. Root scripts `ide:*`; the root `npm test` also runs the IDE gate; CI job `ide-smoke` on the three OSes; `ELECTRON_SKIP_BINARY_DOWNLOAD=1` everywhere else. `test/tooling/npmScripts.test.cjs` now checks the IDE workspace's scripts and lets a root mirror run more after the extension command. The extension itself is untouched (nothing under `apps/vscode-extension/src`, `templates` or `examples`).
+
+**Measured**: `apps/ide` 57 unit tests; `ide:smoke` passes on Linux under xvfb (all nine probes); extension `npm test` unchanged apart from the tooling test.
+
+
+### IDE epic #11 — story #13 step 1: the `CodeXRHost` seam [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `docs/ide/vscode-api-inventory.md` (the inventory #13 asks for: 171 of 300 files import `vscode`, 114 reach it not at all, the proposed host and a ten-step migration). New vscode-free `core/host/codeXRHost.ts` (the interface) and `core/host/hostRegistry.ts` (`initializeHost`/`getHost`/`hasHost`/`resetHostForTests`); `app/host/vscodeHost.ts` (`createVSCodeHost`, `signalToCommand`, `hostModeOf`) forwards each member to the call the core makes today; `extension.ts` initializes it right after `initializeExtensionContext`. No core module uses it yet (behaviour-neutral). `folderDependencies.json`: `core/host` entry, `app` and `(root)` may import it, `vscodeFreeFloor` 106 → 116.
+
+**Measured**: new `test/host/codeXRHost.test.cjs` (12 tests: vscode-free check, registry, paths, modes, notify/confirm/progress/prompt/clipboard/openExternal/workspaceFolders, every signal's command); `npm test` 1,185/1,185 + IDE 57/57; ESLint warnings unchanged (151).
+
+### XR bug-fix epic #72 — EVO-2 follow-up: the same commit picked twice (#104) [confirmed by unit tests + the verification repros] (2026-11-26, branch `claude/project-thread-svsl9c-evo-dedupe`)
+
+**What changed**: the verification (`docs/xr-audit/verification/evolution.md`, EVO-2 partial) showed a tag and its commit picked together in a manual movie racing on one `snapshots/` folder: `materialize` wiped it for the second worker and the EVO-8 `releaseSnapshot` deleted it as soon as the first analysis ended, giving partial frames (`v1.0:9` of 30 files), ENOENT or "no data records" exclusions that the catalogue then recorded as deterministic. `GitAnalysisSessionContext.analyzeSource` now keeps an in-flight `Map`: a second source on the same commit (same cache key) awaits the running analysis instead of starting one, so there is one materialize, one Python run and one release per commit (the snapshot is released only after that analysis). The evolution service relabels a shared exclusion with each source's own id and label (`ownExclusion`). Historical comparison gets the same sharing for free (tag on one side, its commit on the other). `GitRepositoryService` / `GitBatchMetadataReader` untouched (#105/#106 change them in parallel).
+
+**Measured**: two new tests in `gitHistoryServices.test.cjs` (tag + its commit + live: one analyzer call and one materialize for the sha, both frames 3 records with identical `data1.json`/`data2.json`, no exclusion recorded, snapshots folder empty, both still offered afterwards; a failing shared commit is excluded under both names) fail on the old code (2 analyses) and pass; suite 33/33. Verification probes against the fixed build: `g2.cjs` 8 runs, all `[v1.0:30, cb35686e:30, main (live):1]` with no exclusions (was `v1.0:9` and ENOENT in some of 11 runs); `hostVerify.cjs G` `[feature:30, cb35686e:30, main (live):1]`, excluded none.
+
+
+### IDE epic #11 — story #13 step 2a: host paths for the backend resolver and the private storage root [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: new vscode-free `core/host/hostPaths.ts`: `hostPathsFromContext` (structural `ExtensionContext` → `HostPaths`), `hostModeFromExtensionMode` with `EXTENSION_MODE` (1/2/3, checked against `@types/vscode`), and `privateStorageRoot` (`workspaceStorageDir || globalStorageDir`, the `||` kept so an empty path still falls back). `core/analysis/python/backendScriptPath.ts` takes `Pick` and no longer imports `vscode`; `executePython.ts` and `gitRevisionExporter.ts` convert their context. The five hand-written private-storage expressions (`historicalComparisonService`, `projectEvolutionService`, `dependencyGraphService`, `gitRevisionExporter` ×2) use `privateStorageRoot`. `app/host/vscodeHost.ts` builds its paths with the same function. Behaviour-neutral. `vscodeFreeFloor` 116 → 118; `core/analysis`, `core/history`, `core/dependencies`, `core/export` may import `core/host`.
+
+**Measured**: new `test/host/hostPaths.test.cjs` (6 tests, one proving the new rule equals the old expression on four contexts, one guarding against a hand-written copy coming back); `backendScriptPath`, `packagedLayout` and `analysisPaths` suites adapted to host paths; the private-storage guard in `historicalComparison.test.cjs` retargeted to the shared rule. `npm test` 1,191/1,191; ESLint warnings unchanged (151).
+
+### XR bug-fix epic #72 — #111 port probe, code part (LAUNCHER-13 fallback) [confirmed by unit tests on Linux; macOS/Windows hand check pending] (2026-11-26, branch `claude/project-thread-svsl9c-port-probe`)
+
+**What changed**: `core/server/portManager.ts`: the get-port failure fallback is now `PortManager.scanSequentially(start, end, host?)` (public, so it can be tested without breaking the dynamic `import('get-port')`). `isPortAvailable` treats a wildcard host (`0.0.0.0`, `::`) like no host and runs `isPortFreeEverywhere` over `PortManager.PROBED_HOSTS` (`0.0.0.0`, `127.0.0.1`, `::1`, exclusive binds), so the fallback, whose default host is `0.0.0.0`, and `HttpsServerBase.resolveListeningPort` (host `0.0.0.0`) check the same three addresses as the main probe. An explicit non-wildcard host (the `127.0.0.1` callers) is still probed alone.
+
+**Measured**: new test in `test/servers/serverLifecycle.test.cjs` (stubbed per-host probe: a port taken on `127.0.0.1` only is skipped, probe order `0.0.0.0`, `127.0.0.1`, `::1`; `::` counts as wildcard; a real `127.0.0.1` listener is skipped). Not verified: the co-bind on macOS/Windows, which Linux refuses anyway; the manual-test-guide row and the maintainer's run on Windows/macOS are the remaining criteria of #111.
+
+### XR bug-fix epic #72 — #110 dependency graph shows no fake external packages [confirmed by backend + unit tests] (2026-11-26, branch `claude/project-thread-svsl9c-depgraph-packages`)
+
+**What changed**: `backend/src/utils/dependency_analysis_engine.py`: the inheritance pattern skips a generic parameter list after the type name (`_TYPE_PARAMETERS`, three nesting levels) and a Kotlin/Scala primary constructor, captures a type name without `<>` (`_TYPE_NAME`, `::` allowed), is split in an `extends` pattern and a `:` pattern that skips C++ access specifiers; the `:` pattern is off for Python and GDScript (`_NO_COLON_BASES`), so `_iter_raw_targets`/`_extract_targets`/`_extract_targets_with_lines` take the file's `language` (both directory and file scope pass it). The mixin `with` pattern only fires on a declaration line (`_DECLARATION_START`), and `require` ignores the string `'require'` and a blank specifier. `CACHE_VERSION` 3 → 4 so cached targets are re-extracted. Python bases (`class B(A)`) are still not extracted: adding them turned in-file classes into external nodes, left for a later story. `DependencyGraphService` seeds `revision` from `highestDatasetRevision(/dependencies)`, the max over `dependency-graph-*` and `dependency-scope-*`, so a re-created service continues after the files on disk instead of writing a revision `pruneDatasetRevisions` deletes at once (verification observation 2).
+
+**Measured**: new `backend/tests/dependencies/test_inheritance_targets.py` (8 tests: Python, TypeScript and Java class/interface/generic fixtures in directory and file scope, C++/C#/Swift/Kotlin/Objective-C `:` bases, `require`); goldens regenerated, only the cache `version` changed; on `apps/vscode-extension/src` the lexical inheritance/implementation/require targets drop from 62 to 53, the nine removed being exactly `vscode.TreeItem>` x2, `any`, `string`, `string>`, `scheme`, `HttpsServerBaseConfig>`, `object` and `|`. New test in `dependencyFileScope.test.cjs` (counter continues at 42 after files 40/41, and the written file survives pruning).
+
+### IDE epic #11 — story #13 step 2b: four more leaf modules off `vscode` [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `core/host/hostPaths.ts` adds the structural `FileLocation` (`{ fsPath }`) and `GlobalStorageContext` (`Pick<…, 'globalStorageUri'>`). `core/charts/settings/settingsFile.ts`, `core/server/generatedHttpsCertificateManager.ts`, `core/python-env/pythonEnvStorage.ts` and `core/analysis/utils/themeUtils.ts` use them instead of `vscode.Uri` / `vscode.ExtensionContext`, so they no longer reach `vscode`; an `ExtensionContext` still fits, so no caller changed. `themeUtils.ts` logs through `platform/logging/sink` (same logger, `CodeXRLogger.getLogger` delegates to it). Behaviour-neutral. `core/charts`, `core/server`, `core/python-env` may import `core/host`; `vscodeFreeFloor` 118 → 122.
+
+**Measured**: `test/host/hostPaths.test.cjs` now pins all six modules migrated in step 2 as vscode-free; `npm test` 1,191/1,191 + IDE 57/57; ESLint warnings unchanged (151).
+
+### IDE epic #11 — story #13 step 3: Node events instead of `vscode.EventEmitter` in the core [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: new vscode-free `core/host/hostEmitter.ts` (`HostEmitter` on Node `events`, keeping the `vscode.Event` call shape and contract, like `ActiveServerRegistry.onRegistryChange`). It replaces `vscode.EventEmitter` in `core/analysis/session/sessionRegistry.ts`, `core/collaboration/collaborationProfileManager.ts` and `core/python-env/pythonEnvUiState.ts` (each passes its own logger for listener errors, which `vscode.EventEmitter` sent to the console); `HostDisposable` replaces `vscode.Disposable` type positions there and in `httpServer.ts` and `remoteAccessManager.ts`. `collaborationProfileManager.ts` takes a structural `CollaborationProfileContext` and is vscode-free. Subscribers in `features/` compile unchanged. `core/collaboration` may import `core/host` and `platform`, `core/remote-access` may import `core/host`; `vscodeFreeFloor` 122 → 125.
+
+**Measured**: new `test/host/hostEmitter.test.cjs` (6 tests: order and `thisArgs`, a throwing listener, subscription dispose and the `disposables` bag, nothing after dispose, the migrated modules stay vscode-free, no `new vscode.EventEmitter` left under `core/`); `npm test` 1,197/1,197 + IDE 57/57; ESLint warnings unchanged (151).
+
+### IDE epic #11 — story #13 step 4 (types): host progress and cancellation in the core [confirmed by typecheck and unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `HostProgress` / `HostCancellation` (from `core/host/codeXRHost.ts`) replace `vscode.Progress<…>` / `vscode.CancellationToken` in `core/export/gitRevisionExporter.ts`, `core/analysis/python/executePython.ts` (9) and `core/python-env/venvManager.ts` (6). Type-only; a VS Code progress and token still fit. The five `vscode.window.withProgress` call sites (`executePython.ts`, `venvManager.ts` ×3, `cloudflaredBinaryManager.ts`) move in step 6 with the notifications of the same classes, because both need those classes to reach a `CodeXRHost`. No file became vscode-free, so the floor stays 125.
+
+### IDE epic #11 — story #13 step 5 (first part): the visualization settings off `vscode` [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `core/host/hostPaths.ts` adds the structural `GlobalStateContext` (`globalStorageUri` + `globalState: HostKeyValueStore`). `core/charts/settings/settingsStorage.ts` and `settingsAccessors.ts` take it instead of `vscode.ExtensionContext`; same keys, same files, so stored settings survive. Both are vscode-free, and so is `core/charts/getVisualizationConfiguration.ts`, which reached `vscode` only through its runtime `require` of the accessors. `xrFieldSchemaService.ts` and the cloudflared consent flag keep their context until steps 9 and 6. `vscodeFreeFloor` 125 → 128.
+
+**Measured**: `test/host/hostPaths.test.cjs` pins the three modules as vscode-free; `npm test` 1,199/1,199 + IDE 57/57; ESLint warnings unchanged (151).
+
+### IDE epic #11 — story #13 step 6 (first part): a host in every fake-vscode test scope, and the first notifications through it [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `core/host/hostRegistry.ts` adds `setHostFallbackForTests` (a factory `getHost()` uses only when nothing called `initializeHost`, built on first use; `resetHostForTests` clears it; the extension never sets it, so a missing host still throws in production). `test/helpers/fakeVscode.cjs` sets it in every `withFakeVscode` scope to `createVSCodeHost` over the same fake, from `fake.hostContext` or a throwaway context removed with the scope; both modules are evicted with the scope, so no host leaks between suites (inventory risk 12). `app/host/vscodeHost.ts` looks up `vscode.window.show*Message` on each call instead of capturing them. `core/analysis/launchers/launchPipeline.ts`, `launcherXRAnalysis.ts` and `core/analysis/parsers/fileXRParser.ts` notify through `getHost().notifier.notify(...)`: same messages, same severities. Second commit: `analysisOrchestrator.ts`, `fileWatcherOrchestrator.ts` (and its status-bar message, via `notifier.status`), `serverControl.ts` and `httpsCustomServer.ts` too, with their two adjacent command calls as `host.signal` (`revealSidebar`, `openServerSettings`). Behaviour-neutral.
+
+**Measured**: `test/host/codeXRHost.test.cjs` +3 tests (fallback semantics; a notification inside a scope lands in `fake.messages` and no host survives the scope; the seven modules call no `vscode.window` message or status-bar API, with a canary); `npm test` 1,205/1,205 + IDE 57/57; ESLint warnings unchanged (151).
+
+### IDE epic #11 — story #13 step 6 (second part): HTTPS server and cloudflared consent through the host [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `HostNotifier.confirm` takes an optional `severity` (icon only, default `warning`; the VS Code adapter moved it into a helper to stay under the function-length limit). `core/server/httpsDefaultServer.ts` uses the host for its notification, the two clipboard copies and the modal instructions, and no longer imports `vscode`. `core/remote-access/cloudflaredBinaryManager.ts` asks its download consent through `notifier.confirm` (still modal, still info, still unanswered by default), downloads under `host.withProgress`, and takes a structural `GlobalStateContext` (same consent key): vscode-free. `vscodeFreeFloor` 128 → 130.
+
+**Measured**: new tests: the cloudflared consent with no answer returns no binary, downloads nothing and stores nothing (inventory risk 8, first behavioural test of that path); `confirm` severities; `httpsDefaultServer.ts` joins the no-`vscode.window` guard; `cloudflaredBinaryManager.ts` pinned vscode-free. `npm test` 1,230/1,230 + IDE 57/57; ESLint warnings unchanged (151).
+
+**Then**: `HostNotifier.createStatusIndicator` takes an optional `priority`; `core/analysis/watchers/debounceManager.ts` builds its re-analysis countdown through it (left, priority 100, as before). Two more tests (the adapter keeps alignment and priority; the countdown calls no `vscode.window`). `npm test` 1,232/1,232.
+
+### IDE epic #11 — story #13 step 6 (third part): the Python environment through the host [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `core/python-env/venvManager.ts` runs its three progress notifications through `host.withProgress`, asks the delete-environment question through `notifier.confirm` (still modal, still unanswered by default), notifies through the host, logs through the sink and takes a `GlobalStorageContext`. `core/python-env/pythonEnvUiState.ts` sends `codeXR.pythonEnv.uiLocked` / `retryAvailable` as `host.signal({ kind: 'state' })`. `app/host/vscodeHost.ts` spells those context keys out in full (`CONTEXT_KEYS`: package.json `when` clauses and the feature baseline read them as literals — a template string failed the baseline) and logs a failing signal command instead of leaving an unhandled rejection. Both modules are vscode-free; `vscodeFreeFloor` 130 → 133. Behaviour-neutral.
+
+**Measured**: new tests: delete-environment with no answer deletes nothing; a failing signal leaves no unhandled rejection; both modules pinned vscode-free; `venvManager.ts` in the no-`vscode.window` guard. `npm test` 1,238/1,238 + IDE 57/57; ESLint warnings unchanged (151).
+
+### IDE epic #11 — story #13 step 6 (last part): remote access, and no `vscode.window` left in the core [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `CodeXRHost.prompt` takes `HostPromptOptions` (`title`, `validate`, `keepOpen` added; the adapter maps them to `validateInput` / `ignoreFocusOut` in a helper and sets only what was given). `core/remote-access/remoteAccessManager.ts` moves its notifications, clipboard copies, `openExternal`, both input boxes (invitation link, pairing code) and its refresh command (`host.signal({ kind: 'refresh', view: 'activeServers' })`) to the host. `executePython.ts` (its analysis progress) and `directoryReAnalyzer.ts` (its status-line message) too; both now take `ExtensionContextPaths`. After this commit no file under `src/core/` calls `vscode.window` or `vscode.env`. Behaviour-neutral; floor unchanged (these still reach `vscode` through `analysisSession.ts` / `ServerSettingsManager`, step 9).
+
+**Measured**: prompt mapping test; the no-direct-`vscode` guard now also rejects `showInputBox`, `withProgress`, `vscode.env` and `vscode.commands` and covers `remoteAccessManager.ts`, `executePython.ts`, `directoryReAnalyzer.ts`. `npm test` 1,244/1,244 + IDE 57/57; ESLint warnings unchanged (151); guardrail baseline unchanged (a first draft put the prompt mapping inline and pushed `createVSCodeHost` over 80 lines, which the ratchet caught).
+
+### IDE epic #11 — story #13 step 7 (first part): the last direct editor calls in the core [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `core/server/serverSettingsManager.ts` sends its two server-list refreshes as `host.signal({ kind: 'refresh', view: 'servers' })`; `core/dependencies/dependencyGraphService.ts` finds the project root from `host.workspaceFolders()` and takes `ExtensionContextPaths`. Behaviour-neutral; floor unchanged.
+
+**Measured**: a new test walks every `.ts` under `src/core/` (with a file-count canary) and fails on `vscode.window`, `vscode.env`, `vscode.commands` or `vscode.workspace.workspaceFolders`. `npm test` 1,245/1,245 + IDE 57/57; ESLint warnings unchanged (151).
+
+### IDE epic #11 — story #13 step 8: the analysis configuration on Node `fs` [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: `core/analysis/configuration/analysisConfigurationStorage.ts` replaces `vscode.workspace.fs` + `Uri.joinPath` with `fs/promises` + `path.join` (same `/codexr_analysis/configuration_analysis.json`, same JSON, so saved configurations are still read; `file:` was the only scheme the rest of the core supported anyway) and takes a `GlobalStorageContext`. vscode-free; `vscodeFreeFloor` 133 → 134. Finding: the unit suites' fake `vscode` never had `workspace.fs`, so until now every test that touched this storage silently took the "file not found, using defaults" path.
+
+**Measured**: new `test/host/analysisConfigurationStorage.test.cjs` (3 tests: vscode-free; defaults written to the expected path; a file from an earlier version read and merged). `npm test` 1,248/1,248 + IDE 57/57; ESLint warnings unchanged (151).
+
+### IDE epic #11 — story #13 step 7 (second part): launch notifications through a registered notifier [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: new `core/server/launchNotifier.ts` (`LaunchNotifier`, `setLaunchNotifier`, `getLaunchNotifier`, which throws when nothing is registered). `multiServerLauncher.ts` no longer imports `features/active-servers/views/launchNotifications.ts`; `extension.ts` registers that module right after `initializeHost`. `folderDependencies.json` loses the `core/server->features/active-servers` layer exception and the `core/server<->features/active-servers` two-way pair; `(root)` may now import `features/active-servers`. Behaviour unchanged: the same three functions run at the same moments.
+
+**Measured**: new `test/host/launchNotifier.test.cjs` (3 tests); `multiServerLauncher.test.cjs` registers the notifier in its scope. Still open in step 7: `serverControl.ts` -> `platform/webview` / `platform/ui`.
+
+### IDE epic #11 — story #13 step 7 (last part): server panels and errors without editor UI in the core [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: new `core/server/serverPanels.ts` (`ServerPanelCloser`, `setServerPanelCloser`, `closeServerPanels`, a no-op when nothing is registered). `serverControl.ts` closes lateral panels through it instead of `platform/webview/panelManager.ts`; `extension.ts` registers `getPanelManager().removePanelsForServers`. `serverControl.ts` and `directoryWatcherOrchestrator.ts` no longer use `platform/ui/errorHandler.ts`: the same `DOMAIN: operation` messages go to their own sink loggers, and the one user-facing case (a server that fails to stop) notifies through `getHost().notifier`. No file under `core/` imports `platform/webview` or `platform/ui`. `vscodeFreeFloor` 134 → 135 (`serverPanels.ts`); `serverControl.ts` still reaches `vscode` through its `ExtensionContext` (step 9). `functions.over80Lines` 33 → 32 (`stopServer`).
+
+**Measured**: `npm test` gate below. Step 7 of docs/ide/vscode-api-inventory.md §4.2 is done; step 9 remains.
+
+### IDE epic #11 — story #13 step 9: the whole core is vscode-free [confirmed by unit tests] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: the last `vscode` in `src/core/` was the `ExtensionContext` type, in 36 files. `core/host/hostPaths.ts` adds `CoreContext` (`ExtensionContextPaths & GlobalStateContext`); those files take it instead (type-only, a real `ExtensionContext` still fits, no caller changed). `RemoteAccessManager.initialize` takes `CoreContext & { subscriptions: HostDisposable[] }`. `serverSettingsManager.ts` logs through the sink instead of `CodeXRLogger`. Two source-text assertions (`livePanelDomIntegration`, `reanalysisArchitecture`) now expect `CoreContext`.
+
+**Measured**: all 174 files under `core/` are in `measure().vscodeFree`; `vscodeFreeFloor` 135 → 187; new guard in `test/host/codeXRHost.test.cjs` fails on any core file reaching `vscode`. `npm test` 1,254/1,254 + IDE 57/57; ESLint warnings unchanged (151). Story #13's plan (docs/ide/vscode-api-inventory.md §4.2) is complete.
+
+### IDE epic #11 — story #13: the core runs an analysis without VS Code [confirmed by the smoke script, locally] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed**: new `apps/vscode-extension/test/runners/run-core-smoke.cjs` (`npm run test:core-smoke`, and a "Core without VS Code" step in the CI python job after the HTML DOM step). It makes `require('vscode')` throw, registers a stub `CodeXRHost` (no UI, never answers a consent question), links the `test:analysis` venv into a throwaway global storage and runs a LivePanel analysis of `backend/manual_test/python_metrics.py` through `ExecutePython` in development mode. Nothing is downloaded. This is #13's last acceptance criterion; the F5 flow on top of the extracted core is Adrián's manual check.
+
+**Measured**: `core smoke: OK ... through 12 core modules, no vscode, stub host`.
+
+### IDE epic #11 — story #14 (first part): open a folder and browse it [confirmed by unit tests and the smoke run] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed** (`apps/ide` only): `window.codexr.workspace` (`openFolder`, `current`, `listDirectory`, `readFile`, `onDidChange`) on four new channels plus one main-to-renderer event. `src/main/workspace/`: `workspacePath.ts` (the renderer may only send `/`-separated workspace-relative paths; `..`, absolute, drive letters, `\`, NUL refused), `ignoreRules.ts` (`.git`, `node_modules`, `.DS_Store` never listed; root `.gitignore` matches listed dimmed, with negation, anchoring, `*`, `?`, `[...]`, `**`), `workspace.ts` (lists folders first in natural order, reads text up to 5 MB, reports binary or oversized files, compares real paths so a symlink cannot lead out), `workspaceWindows.ts` (one folder per window, keyed by `webContents.id`). File > Open Folder… (Ctrl/Cmd+O) and `--folder=`. Renderer: `explorer.ts`, a lazily loaded ARIA tree with keyboard navigation. Clicking a file shows its path in the status bar until Monaco lands.
+
+**Measured**: IDE unit tests 57 → 95; `npm run ide:smoke` now opens `apps/ide` with `--folder=`, checks the explorer lists it, reads `package.json` and confirms `../package.json` is refused. Screenshot: /mnt/project-files/ide-build/14a-explorer.png.
+
+### IDE epic #11 — story #14 (second part): Monaco tabs and saving [confirmed by unit tests and the smoke run] (2026-11-26, branch `claude/project-thread-zeculq`)
+
+**What changed** (`apps/ide` only): `monaco-editor` 0.57.0 (exact pin; 0.58.0 was three days old) as the IDE's first runtime dependency, bundled by Vite with its editor, JSON, CSS, HTML and TypeScript workers from the app origin (`src/renderer/editor/monaco.ts`), loaded on the first file open in its own chunk. `editor/editorGroup.ts`: one editor, one model per file, a tab strip (dirty mark from Monaco's alternative version id, middle-click and Ctrl/Cmd+W close with a confirmation when dirty, view state kept per tab). `workspace.writeFile(path, text, expectedMtimeMs)`: existing files only, refused with `MODIFIED_ON_DISK` when the file moved since it was read. Menu: Save, Save All, Close Editor, and Open Folder… now asks the renderer first so unsaved editors can veto it (`commands.onCommand`, a closed list `IDE_COMMANDS`). TypeScript semantic diagnostics are off (files open without their project, so every import was flagged); syntax errors still show.
+
+**Security decision**: the production CSP now allows `'unsafe-inline'` in `style-src` only. Monaco creates `
-
CodeXR Server - File Not Found
+
Code-XR Server - File Not Found
Selected HTML File Not Found
The HTML file you selected could not be located.
diff --git a/src/servers/runtime/httpServer.ts b/apps/vscode-extension/src/core/server/httpServer.ts
similarity index 76%
rename from src/servers/runtime/httpServer.ts
rename to apps/vscode-extension/src/core/server/httpServer.ts
index 872cf4009..3c6f21329 100644
--- a/src/servers/runtime/httpServer.ts
+++ b/apps/vscode-extension/src/core/server/httpServer.ts
@@ -1,14 +1,15 @@
import * as http from 'http';
-import * as path from 'path';
-import * as fs from 'fs';
-import * as vscode from 'vscode';
+import type { HostDisposable } from '../host/codeXRHost';
import { sseManager } from './sse/SSEManager';
-import { fileToServerMap } from '../../utils/fileToServerMap';
-import { NetworkUtils } from '../utils/networkUtils';
+import { fileToServerMap } from './fileToServerMap';
+import { NetworkUtils } from './networkUtils';
import { ScreenBroadcastSignalingServer } from './broadcast/screenBroadcastSignalingServer';
-import { CollaborationRoomServer } from './collaboration/collaborationRoomServer';
-import { CollaborationProfileManager, ConnectedParticipantSummary } from '../../collaboration';
-import { RemoteSessionAuthority } from '../../remote_access';
+import { CollaborationApplicationMessageContext, CollaborationMessage, CollaborationRoomServer } from './collaboration/collaborationRoomServer';
+import { CollaborationProfileManager } from '../collaboration/collaborationProfileManager';
+import { ConnectedParticipantSummary } from '../collaboration/connectedParticipant';
+import { RemoteSessionAuthority } from '../remote-access/remoteSessionAuthority';
+import { handleOpenInEditorMessage, isLoopbackAddress, sessionAnalysisRoot } from './analysis/editorNavigation';
+import { REVEAL_IN_SCENE_MESSAGE, scenePathOf } from './analysis/sceneReveal';
import { addCorsHeaders, sendErrorResponse, sendJsonResponse } from './http/httpRespond';
import { StaticAssetServer } from './http/staticAssets';
import { RemoteAccessPolicy } from './remote/remoteAccessPolicy';
@@ -19,6 +20,11 @@ import { AnalysisMessageRouter } from './analysis/analysisMessageRouter';
import { DependencyGraphBridge } from './analysis/dependencyGraphBridge';
import { HistoricalComparisonBridge } from './analysis/historicalComparisonBridge';
import { ProjectEvolutionBridge } from './analysis/projectEvolutionBridge';
+import { getLogger } from '../../platform/logging/sink';
+import { resolveTemplatePath } from '../../platform/templatePaths';
+import type { CoreContext } from '../host/hostPaths';
+
+const logger = getLogger('SERVER');
/**
* HTTP Server Configuration
@@ -37,7 +43,7 @@ export interface HttpServerConfig {
enableCors?: boolean;
allowedOrigins?: string[];
mainFile?: string; // Optional main file to serve at root
- extensionContext?: vscode.ExtensionContext;
+ extensionContext?: CoreContext;
analysisSessionId?: string;
}
@@ -56,7 +62,7 @@ export class HttpServer {
private upgradeAttached = false;
private broadcastSignalingServer: ScreenBroadcastSignalingServer | null = null;
private collaborationRoomServer: CollaborationRoomServer | null = null;
- private collaborationProfileSubscription: vscode.Disposable | null = null;
+ private collaborationProfileSubscription: HostDisposable | null = null;
private readonly remoteSessionAuthority = new RemoteSessionAuthority();
private remotePublicUrl: string | null = null;
private readonly analysisHost: AnalysisFeatureHost;
@@ -73,14 +79,19 @@ export class HttpServer {
this.config = {
host: '0.0.0.0', // Listen on all network interfaces for VR/mobile access
- staticRoot: path.join(__dirname, '../../../templates'),
+ staticRoot: cleanConfig.extensionContext
+ ? resolveTemplatePath(cleanConfig.extensionContext.extensionPath)
+ : undefined,
enableCors: true,
allowedOrigins: ['*'],
...cleanConfig
};
+ if (!this.config.staticRoot) {
+ throw new Error('SERVER: HttpServer needs a staticRoot or an extension context');
+ }
this.staticAssets = new StaticAssetServer({
- staticRoot: this.config.staticRoot!,
+ staticRoot: this.config.staticRoot,
mainFile: this.config.mainFile,
port: this.config.port,
host: this.config.host,
@@ -123,7 +134,7 @@ export class HttpServer {
roomHooks,
);
- console.log('SERVER: HTTP server initialized with config:', this.config);
+ logger.debug('HTTP server initialized with config:', this.config);
}
/**
@@ -141,7 +152,7 @@ export class HttpServer {
this.attachToNodeServer(this.server);
this.server.on('error', (error: NodeJS.ErrnoException) => {
- console.error('SERVER: HTTP server error:', error);
+ logger.error('HTTP server error:', error);
this.isRunning = false;
if (error.code === 'EADDRINUSE') {
@@ -155,8 +166,8 @@ export class HttpServer {
const address = this.server?.address();
const portNumber = Number(this.config.port);
- console.log(`SERVER: HTTP server listening on http://${this.config.host}:${this.config.port}`);
- console.log('SERVER: Server address info:', address);
+ logger.debug(() => `HTTP server listening on http://${this.config.host}:${this.config.port}`);
+ logger.debug('Server address info:', address);
// Display network information for external access
NetworkUtils.displayNetworkInfo(portNumber, 'http');
@@ -170,14 +181,14 @@ export class HttpServer {
// Add graceful shutdown handling
this.server.on('close', () => {
- console.log('SERVER: HTTP server closed');
+ logger.debug('HTTP server closed');
this.isRunning = false;
});
this.server.listen(this.config.port, this.config.host);
} catch (error) {
- console.error('SERVER: Error starting HTTP server:', error);
+ logger.error('Error starting HTTP server:', error);
reject(error);
}
});
@@ -189,7 +200,7 @@ export class HttpServer {
*/
public async stop(): Promise {
if (!this.server || !this.isRunning) {
- console.log('SERVER: HTTP server is not running');
+ logger.debug('HTTP server is not running');
return;
}
@@ -204,10 +215,10 @@ export class HttpServer {
return new Promise((resolve, reject) => {
this.server!.close((error) => {
if (error) {
- console.error('SERVER: Error stopping HTTP server:', error);
+ logger.error('Error stopping HTTP server:', error);
reject(error);
} else {
- console.log('SERVER: HTTP server stopped successfully');
+ logger.debug('HTTP server stopped successfully');
this.isRunning = false;
this.server = null;
resolve();
@@ -221,8 +232,22 @@ export class HttpServer {
*/
public forceStop(): void {
this.disposeRuntimeFeatures();
- this.server?.closeAllConnections();
+ const server = this.server;
+ this.server = null;
this.isRunning = false;
+ if (server) {
+ // close() stops accepting connections and releases the port; it
+ // was never called here, so a force-stopped server kept listening
+ // with no entry left in the tree to stop it from.
+ server.close(() => undefined);
+ server.closeAllConnections();
+ }
+ }
+
+ /** The port the listener is actually bound to, or null when not listening. */
+ public getListeningPort(): number | null {
+ const address = this.server?.address();
+ return address && typeof address === 'object' ? address.port : null;
}
/**
@@ -257,7 +282,7 @@ export class HttpServer {
}
public getConnectedParticipants(): ConnectedParticipantSummary[] {
- return this.collaborationRoomServer?.getConnectedParticipants(this.sessionApi.getCollaborationRoomId()) || [];
+ return this.collaborationRoomServer?.getConnectedParticipants(this.sessionApi.getCollaborationRoomId()) ?? [];
}
/**
@@ -302,6 +327,20 @@ export class HttpServer {
this.remotePublicUrl = publicUrl;
}
+ /** #178: sends `reveal-in-scene` to the room when `absolutePath` is under the analysed folder. */
+ public revealInScene(absolutePath: string): boolean {
+ const root = sessionAnalysisRoot(this.config.extensionContext, this.config.analysisSessionId);
+ const scenePath = root === null ? null : scenePathOf(root, absolutePath);
+ if (scenePath === null || !this.collaborationRoomServer) {
+ return false;
+ }
+ this.collaborationRoomServer.broadcastServerMessage(this.sessionApi.getCollaborationRoomId(), {
+ type: REVEAL_IN_SCENE_MESSAGE,
+ payload: { path: scenePath },
+ });
+ return true;
+ }
+
public createAuthenticatedBrowserUrl(baseUrl: string): string {
const profileManager = CollaborationProfileManager.getInstance();
if (!profileManager) {
@@ -338,7 +377,7 @@ export class HttpServer {
const safeRequestUrl = new URL(requestUrl, 'http://codexr.local').pathname;
const method = req.method || 'GET';
- console.log(`SERVER: ${method} ${safeRequestUrl} - Processing request`);
+ logger.debug(() => `${method} ${safeRequestUrl} - Processing request`);
if (!this.policy.isRequestAuthorized(req, requestUrl)) {
sendErrorResponse(res, 404, 'Resource not found');
@@ -361,10 +400,10 @@ export class HttpServer {
this.routeRequest(req, res, requestUrl)
.then(() => {
const duration = Date.now() - startTime;
- console.log(`SERVER: ${method} ${safeRequestUrl} - Completed in ${duration}ms`);
+ logger.debug(() => `${method} ${safeRequestUrl} - Completed in ${duration}ms`);
})
.catch((error) => {
- console.error(`SERVER: ${method} ${safeRequestUrl} - Error:`, error);
+ logger.error(`${method} ${safeRequestUrl} - Error:`, error);
sendErrorResponse(res, 500, 'Internal Server Error');
});
}
@@ -396,7 +435,7 @@ export class HttpServer {
sendJsonResponse(res, 200, {
status: 'healthy',
timestamp: new Date().toISOString(),
- server: 'CodeXR HTTP Server'
+ server: 'Code-XR HTTP Server'
});
return;
}
@@ -433,7 +472,7 @@ export class HttpServer {
switch (apiPath) {
case '/status':
sendJsonResponse(res, 200, {
- server: 'CodeXR HTTP Server',
+ server: 'Code-XR HTTP Server',
mode: 'HTTP',
port: this.config.port,
uptime: process.uptime(),
@@ -490,6 +529,14 @@ export class HttpServer {
await this.historicalBridge.handleHistoricalCompare(req, res);
break;
+ case '/historical/cancel':
+ await this.historicalBridge.handleHistoricalCancel(req, res);
+ break;
+
+ case '/historical/status':
+ this.historicalBridge.handleHistoricalStatus(req, res);
+ break;
+
default:
sendErrorResponse(res, 404, 'API endpoint not found');
}
@@ -506,34 +553,46 @@ export class HttpServer {
/**
* Handle Server-Sent Events request for analysis updates
- * @param req - HTTP request
+ * @param _req - HTTP request (unused)
* @param res - HTTP response
*/
- private async handleSSERequest(req: http.IncomingMessage, res: http.ServerResponse): Promise {
- console.log('REQUEST_UPDATE: SSE connection request received on server');
- console.log(`REQUEST_UPDATE: Server port: ${this.config.port}`);
+ private async handleSSERequest(_req: http.IncomingMessage, res: http.ServerResponse): Promise {
+ logger.debug('REQUEST_UPDATE: SSE connection request received on server');
+ logger.debug(() => `REQUEST_UPDATE: Server port: ${this.config.port}`);
// Find which analysis file this server is serving
const serverPort = this.config.port;
const fileUri = fileToServerMap.findFileByPort(serverPort);
- console.log(`REQUEST_UPDATE: Looking up file for port ${serverPort}`);
- console.log(`REQUEST_UPDATE: Found file mapping: ${fileUri || 'NOT FOUND'}`);
+ logger.debug(() => `REQUEST_UPDATE: Looking up file for port ${serverPort}`);
+ logger.debug(() => `REQUEST_UPDATE: Found file mapping: ${fileUri || 'NOT FOUND'}`);
if (!fileUri) {
- console.warn(`REQUEST_UPDATE: No file mapping found for server on port ${serverPort}`);
- console.warn(`REQUEST_UPDATE: Available mappings: ${fileToServerMap.getAllFileUris().join(', ')}`);
+ logger.warn(`REQUEST_UPDATE: No file mapping found for server on port ${serverPort}`);
+ logger.warn(`REQUEST_UPDATE: Available mappings: ${fileToServerMap.getAllFileUris().join(', ')}`);
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('No analysis file associated with this server');
return;
}
- console.log(`REQUEST_UPDATE: Setting up SSE for analysis file: ${fileUri}`);
+ logger.debug(() => `REQUEST_UPDATE: Setting up SSE for analysis file: ${fileUri}`);
// Register the SSE client with the manager
sseManager.registerClient(fileUri, res);
- console.log(`REQUEST_UPDATE: SSE client registration completed for ${fileUri}`);
+ logger.debug(() => `REQUEST_UPDATE: SSE client registration completed for ${fileUri}`);
+ }
+
+ /** Room messages for the analysis; #16 "Open in editor" is answered for every analysis and every host. */
+ private handleRoomMessage(
+ messageContext: CollaborationApplicationMessageContext,
+ message: CollaborationMessage,
+ ): Promise | boolean {
+ if (message.type === 'open-in-editor') {
+ const root = sessionAnalysisRoot(this.config.extensionContext, this.config.analysisSessionId);
+ return handleOpenInEditorMessage(messageContext, message.payload, root);
+ }
+ return this.analysisRouter.handleCollaborationMessage(messageContext, message);
}
public attachToNodeServer(server: http.Server): void {
@@ -544,8 +603,8 @@ export class HttpServer {
this.collaborationRoomServer = new CollaborationRoomServer(server, '/codexr-room', {
authorizeUpgrade: (request) => this.policy.isWebSocketAuthorized(request),
resolveSession: (request) => this.remoteSessionAuthority.resolveCookie(request.headers.cookie),
- handleApplicationMessage: (messageContext, message) =>
- this.analysisRouter.handleCollaborationMessage(messageContext, message),
+ isLocalRequest: (request) => !this.policy.isRemoteRequest(request) && isLoopbackAddress(request.socket.remoteAddress),
+ handleApplicationMessage: (messageContext, message) => this.handleRoomMessage(messageContext, message),
});
if (this.config.analysisSessionId) {
this.analysisHost.publishAnalysisViewState();
@@ -559,7 +618,7 @@ export class HttpServer {
for (const session of sessions) {
this.collaborationRoomServer?.updateSessionProfile(session.sessionId, session.profile);
}
- }) || null;
+ }) ?? null;
this.broadcastSignalingServer = new ScreenBroadcastSignalingServer(
server,
'/codexr-broadcast',
diff --git a/apps/vscode-extension/src/core/server/httpsCustomServer.ts b/apps/vscode-extension/src/core/server/httpsCustomServer.ts
new file mode 100644
index 000000000..19d0665f2
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/httpsCustomServer.ts
@@ -0,0 +1,164 @@
+import * as fs from 'fs';
+import { NetworkUtils } from './networkUtils';
+import { HttpServer } from './httpServer';
+import { HttpsServerBase, HttpsServerBaseConfig } from './httpsServerBase';
+import { isCertificateRejectedByClient } from './httpsTlsOptions';
+import { getLogger } from '../../platform/logging/sink';
+import { getHost } from '../host/hostRegistry';
+
+const logger = getLogger('SERVER');
+
+export interface HttpsCustomServerConfig extends HttpsServerBaseConfig {
+ certPath: string;
+ keyPath: string;
+}
+
+export class HttpsCustomServer extends HttpsServerBase {
+ private usingFallbackCerts = false;
+
+ constructor(config: HttpsCustomServerConfig) {
+ if (!config.certPath || !config.keyPath) {
+ throw new Error('SERVER: Certificate path and key path are required for custom HTTPS server');
+ }
+
+ if (!config.extensionContext) {
+ throw new Error('SERVER: Extension context is required for HTTPS certificate fallback.');
+ }
+
+ super(config, (httpConfig) => new HttpServer(httpConfig));
+
+ logger.debug('HTTPS server (custom certificates) initialized with config:', {
+ ...this.config,
+ certPath: '***REDACTED***',
+ keyPath: '***REDACTED***',
+ });
+ }
+
+ public async start(): Promise {
+ this.assertNotRunning();
+
+ await this.resolveCertificatePaths();
+ await this.validateCertificates();
+ await this.resolveListeningPort();
+
+ const loadSslOptions = () => this.loadSslOptions(
+ 'Custom SSL certificates loaded successfully',
+ 'SERVER: Failed to load custom SSL certificates',
+ );
+ return this.listenWithTls(loadSslOptions, (server, resolve) => {
+ server.on('listening', () => {
+ const port = this.config.port;
+ const primaryExternalUrl = NetworkUtils.getPrimaryExternalUrl(port, 'https');
+
+ logger.debug(() => `HTTPS server listening on port ${port}`);
+ if (this.usingFallbackCerts) {
+ logger.warn('Using generated local certificates instead of custom certificates');
+ void getHost().notifier.notify('warning',
+ 'HTTPS server started with generated local certificates because the custom certificate pair was missing or invalid.',
+ 'Configure Certificates',
+ ).then((action) => {
+ if (action === 'Configure Certificates') {
+ getHost().signal({ kind: 'openServerSettings' });
+ }
+ });
+ } else {
+ logger.debug('Using custom certificates');
+ }
+
+ NetworkUtils.displayNetworkInfo(port, 'https');
+ logger.debug(() => `Primary external URL: ${primaryExternalUrl}`);
+
+ this.isRunning = true;
+ resolve(NetworkUtils.getLocalhostUrl(port, 'https'));
+ });
+
+ server.on('tlsClientError', (err) => {
+ if (isCertificateRejectedByClient(err)) {
+ logger.warn('Client rejected the certificate - this may be expected');
+ logger.warn('Open the server URL in a browser first and accept the certificate');
+ logger.warn(`Navigate to https://${this.config.host}:${this.config.port} and proceed manually`);
+ } else if (err.message.includes('certificate')) {
+ logger.warn('Certificate-related TLS error:', err.message);
+ } else {
+ logger.warn('TLS client error (non-critical):', err.message);
+ }
+ });
+
+ server.listen(this.config.port, this.config.host);
+ });
+ }
+
+ public getConfig(): HttpsCustomServerConfig {
+ return {
+ ...this.config,
+ certPath: '***REDACTED***',
+ keyPath: '***REDACTED***',
+ };
+ }
+
+ private async resolveCertificatePaths(): Promise {
+ const customResult = await this.tryUseCustomCertificates();
+ if (customResult) {
+ this.usingFallbackCerts = false;
+ return;
+ }
+
+ logger.warn('Falling back to generated local certificates because the custom pair is missing or invalid');
+ const generatedPaths = await this.certificateManager.ensureDefaultCertificatePair();
+ this.config.certPath = generatedPaths.certPath;
+ this.config.keyPath = generatedPaths.keyPath;
+ this.usingFallbackCerts = true;
+ }
+
+ private async tryUseCustomCertificates(): Promise {
+ const certExists = fs.existsSync(this.config.certPath);
+ const keyExists = fs.existsSync(this.config.keyPath);
+
+ if (!certExists || !keyExists) {
+ if (!certExists) {
+ logger.warn(`Custom certificate file not found: ${this.config.certPath}`);
+ }
+ if (!keyExists) {
+ logger.warn(`Custom key file not found: ${this.config.keyPath}`);
+ }
+ return false;
+ }
+
+ try {
+ await this.validateCertificatePair(this.config.certPath, this.config.keyPath);
+ return true;
+ } catch (error) {
+ logger.warn('Custom certificate pair failed validation and will use generated fallback:', error);
+ return false;
+ }
+ }
+
+ private async validateCertificates(): Promise {
+ await this.validateCertificatePair(this.config.certPath, this.config.keyPath);
+ }
+
+ private async validateCertificatePair(certPath: string, keyPath: string): Promise {
+ await this.assertCertificatePairReadable(certPath, keyPath);
+
+ const certContent = await fs.promises.readFile(certPath, 'utf8');
+ const keyContent = await fs.promises.readFile(keyPath, 'utf8');
+
+ if (!certContent.includes('BEGIN CERTIFICATE')) {
+ throw new Error('SERVER: Certificate file does not appear to be a valid certificate');
+ }
+
+ if (
+ !keyContent.includes('BEGIN PRIVATE KEY') &&
+ !keyContent.includes('BEGIN RSA PRIVATE KEY') &&
+ !keyContent.includes('BEGIN EC PRIVATE KEY')
+ ) {
+ throw new Error('SERVER: Key file does not appear to be a valid private key');
+ }
+ }
+
+ protected describeStartError(error: NodeJS.ErrnoException): Error | undefined {
+ return error.code === 'ENOENT'
+ ? new Error('SERVER: Certificate file not found. Please check your certificate paths.')
+ : undefined;
+ }
+}
diff --git a/apps/vscode-extension/src/core/server/httpsDefaultServer.ts b/apps/vscode-extension/src/core/server/httpsDefaultServer.ts
new file mode 100644
index 000000000..07e40b000
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/httpsDefaultServer.ts
@@ -0,0 +1,143 @@
+import { NetworkUtils } from './networkUtils';
+import { HttpServer } from './httpServer';
+import { HttpsServerBase, HttpsServerBaseConfig } from './httpsServerBase';
+import { isCertificateRejectedByClient } from './httpsTlsOptions';
+import { getLogger } from '../../platform/logging/sink';
+import { getHost } from '../host/hostRegistry';
+
+const logger = getLogger('SERVER');
+
+export type HttpsDefaultServerConfig = HttpsServerBaseConfig;
+
+export class HttpsDefaultServer extends HttpsServerBase {
+ constructor(config: HttpsDefaultServerConfig) {
+ if (!config.extensionContext) {
+ throw new Error('SERVER: Extension context is required for generated HTTPS certificates.');
+ }
+
+ super(config, (httpConfig) => new HttpServer(httpConfig));
+
+ logger.debug('HTTPS server (generated local certificates) initialized with config:', {
+ ...this.config,
+ certPath: this.config.certPath ? '***REDACTED***' : undefined,
+ keyPath: this.config.keyPath ? '***REDACTED***' : undefined,
+ });
+ }
+
+ public async start(): Promise {
+ this.assertNotRunning();
+
+ await this.ensureGeneratedCertificates();
+ await this.validateCertificates();
+ await this.resolveListeningPort();
+
+ const loadSslOptions = () => this.loadSslOptions(
+ 'SSL certificates loaded successfully',
+ 'SERVER: Failed to load SSL certificates',
+ );
+ return this.listenWithTls(loadSslOptions, (server, resolve) => {
+ server.on('listening', () => {
+ const address = this.server?.address();
+ const port = this.config.port;
+ const urls = NetworkUtils.generateServerUrls(port, 'https');
+ const primaryExternalUrl = NetworkUtils.getPrimaryExternalUrl(port, 'https');
+
+ logger.debug('HTTPS server successfully listening.');
+ logger.debug('Address object:', address);
+ logger.debug(() => `Config host: "${this.config.host}"`);
+ logger.debug(() => `Config port: ${this.config.port}`);
+ logger.debug(() => `Generated local certificates loaded from ${this.config.certPath}`);
+ logger.debug('NOTE: Using self-signed certificate - browsers may show security warnings');
+
+ NetworkUtils.displayNetworkInfo(port, 'https');
+ this.showVRCertificateInstructions(primaryExternalUrl, urls.localhost);
+
+ this.isRunning = true;
+ resolve(NetworkUtils.getLocalhostUrl(port, 'https'));
+ });
+
+ server.on('tlsClientError', (err) => {
+ if (isCertificateRejectedByClient(err)) {
+ logger.warn('Client rejected self-signed certificate - this is expected behavior');
+ logger.warn('VR solution: open the server URL in a browser first and accept the certificate');
+ logger.warn(`Navigate to https://${this.config.host}:${this.config.port} and proceed manually`);
+ } else {
+ logger.warn('TLS client error (non-critical):', err.message);
+ }
+ });
+
+ logger.debug(() => `About to call server.listen with ${this.config.host}:${this.config.port}`);
+ server.listen(this.config.port, this.config.host, () => {
+ logger.debug('Listen callback executed successfully');
+ });
+ });
+ }
+
+ public getConfig(): HttpsDefaultServerConfig {
+ return { ...this.config };
+ }
+
+ private async ensureGeneratedCertificates(): Promise {
+ const paths = await this.certificateManager.ensureDefaultCertificatePair();
+ this.config.certPath = paths.certPath;
+ this.config.keyPath = paths.keyPath;
+ }
+
+ private async validateCertificates(): Promise {
+ const certPath = this.config.certPath;
+ const keyPath = this.config.keyPath;
+
+ if (!certPath || !keyPath) {
+ throw new Error('SERVER: Generated local certificate paths are not available.');
+ }
+
+ logger.debug('Validating generated local certificates...');
+ logger.debug('Certificate path:', certPath);
+ logger.debug('Key path:', keyPath);
+
+ await this.assertCertificatePairReadable(certPath, keyPath);
+ }
+
+
+ private showVRCertificateInstructions(externalUrl: string, localhostUrl?: string): void {
+ const primaryUrl = externalUrl;
+ const fallbackUrl = localhostUrl || externalUrl;
+
+ const message = `VR/HTTPS server ready! For VR headsets to work:\n\n` +
+ `1. Primary URL (VR/Mobile): ${primaryUrl}\n` +
+ `2. Local URL (Testing): ${fallbackUrl}\n\n` +
+ `For VR/Mobile devices:\n` +
+ ` - Open browser and go to: ${primaryUrl}\n` +
+ ` - Click "Advanced" and proceed manually\n` +
+ ` - Now your VR headset can access securely\n\n` +
+ `This accepts the self-signed certificate for your session.`;
+
+ logger.debug('VR certificate instructions:');
+ logger.debug('=====================================');
+ logger.debug(() => `VR/Mobile URL: ${primaryUrl}`);
+ logger.debug(() => `Local URL: ${fallbackUrl}`);
+ logger.debug('1. Navigate to the VR/Mobile URL from your device');
+ logger.debug('2. Accept certificate warning in browser');
+ logger.debug('3. Then use VR headset to access the same URL');
+ logger.debug('=====================================');
+
+ const host = getHost();
+ void host.notifier.notify(
+ 'info',
+ `HTTPS server ready. VR/Mobile: ${primaryUrl}`,
+ 'Copy VR URL',
+ 'Copy Local URL',
+ 'Show Instructions',
+ ).then((selection) => {
+ if (selection === 'Copy VR URL') {
+ void host.clipboardWrite(primaryUrl);
+ void host.notifier.notify('info', 'VR/Mobile URL copied to clipboard.');
+ } else if (selection === 'Copy Local URL') {
+ void host.clipboardWrite(fallbackUrl);
+ void host.notifier.notify('info', 'Local URL copied to clipboard.');
+ } else if (selection === 'Show Instructions') {
+ void host.notifier.confirm(message, { modal: true, severity: 'info', actions: [] });
+ }
+ });
+ }
+}
diff --git a/apps/vscode-extension/src/core/server/httpsServerBase.ts b/apps/vscode-extension/src/core/server/httpsServerBase.ts
new file mode 100644
index 000000000..455a88f58
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/httpsServerBase.ts
@@ -0,0 +1,285 @@
+import * as https from 'https';
+import * as fs from 'fs';
+import type { HttpServer, HttpServerConfig, ParticipantRemovalOutcome } from './httpServer';
+import type { ConnectedParticipantSummary } from '../collaboration/connectedParticipant';
+import { PortManager } from './portManager';
+import { GeneratedHttpsCertificateManager } from './generatedHttpsCertificateManager';
+import { buildTlsServerOptions } from './httpsTlsOptions';
+import type { RemoteSessionAuthority } from '../remote-access/remoteSessionAuthority';
+import { getLogger } from '../../platform/logging/sink';
+import { resolveTemplatePath } from '../../platform/templatePaths';
+import type { CoreContext } from '../host/hostPaths';
+
+const logger = getLogger('SERVER');
+
+/** The config shape both HTTPS servers share; each narrows it in its own interface. */
+export interface HttpsServerBaseConfig extends Omit {
+ port: number;
+ certPath?: string;
+ keyPath?: string;
+ extensionContext?: CoreContext;
+}
+
+/**
+ * State and plumbing shared by HttpsCustomServer and HttpsDefaultServer: the
+ * embedded HttpServer that answers every request and upgrade, the port
+ * search, the TLS server wiring and the public delegation surface.
+ *
+ * Each subclass keeps what genuinely differs: its constructor guards (run
+ * before super(), in their own order), its constructor log, the start()
+ * orchestration with its listening and TLS-error handlers, where the
+ * certificate pair comes from, and getConfig() (the custom server redacts).
+ * Subclasses must not redeclare a field declared here: with ES2022 class
+ * fields a redeclaration resets it to undefined after this constructor ran.
+ *
+ * This module imports httpServer for types only, and each subclass hands in
+ * the HttpServer factory. httpServer.ts reaches the HTTPS subclasses again
+ * through an import cycle (analysis host -> watchers -> server launcher), and
+ * a runtime import here would let a subclass evaluate `extends` while this
+ * module is still half-loaded.
+ */
+export abstract class HttpsServerBase {
+ protected server: https.Server | null = null;
+ protected config: TConfig;
+ protected isRunning = false;
+ protected httpHandler: HttpServer;
+ protected readonly certificateManager: GeneratedHttpsCertificateManager;
+
+ /** Callers have already checked that `config.extensionContext` is set. */
+ protected constructor(config: TConfig, createHttpServer: (httpConfig: HttpServerConfig) => HttpServer) {
+ this.certificateManager = new GeneratedHttpsCertificateManager(config.extensionContext!);
+ this.config = {
+ host: '0.0.0.0',
+ staticRoot: resolveTemplatePath(config.extensionContext!.extensionPath),
+ enableCors: true,
+ allowedOrigins: ['*'],
+ ...config,
+ };
+
+ this.httpHandler = createHttpServer({
+ port: this.config.port,
+ host: this.config.host,
+ staticRoot: this.config.staticRoot,
+ enableCors: this.config.enableCors,
+ allowedOrigins: this.config.allowedOrigins,
+ mainFile: this.config.mainFile,
+ extensionContext: this.config.extensionContext,
+ analysisSessionId: this.config.analysisSessionId,
+ });
+ }
+
+ public abstract start(): Promise;
+
+ public abstract getConfig(): TConfig;
+
+ public async stop(): Promise {
+ if (!this.server || !this.isRunning) {
+ logger.debug('HTTPS server is not running');
+ return;
+ }
+
+ // Dispose BEFORE close, exactly as HttpServer.stop() does: close()
+ // waits for every socket to drain, and the sockets that never drain
+ // on their own are the ones the runtime features own (collaboration
+ // and broadcast WebSockets, open SSE responses). Disposing inside the
+ // close callback deadlocks the shutdown (a shipped 1.2.0 fix).
+ this.httpHandler.disposeRuntimeFeatures();
+ this.server.closeAllConnections();
+
+ return new Promise((resolve, reject) => {
+ this.server!.close((error) => {
+ if (error) {
+ logger.error('Error stopping HTTPS server:', error);
+ reject(error);
+ } else {
+ logger.debug('HTTPS server stopped successfully');
+ this.isRunning = false;
+ this.server = null;
+ resolve();
+ }
+ });
+ });
+ }
+
+ /**
+ * Drop every open socket without waiting for a graceful close.
+ */
+ public forceStop(): void {
+ this.httpHandler.disposeRuntimeFeatures();
+ const server = this.server;
+ this.server = null;
+ this.isRunning = false;
+ if (server) {
+ // close() stops accepting connections and releases the port; it
+ // was never called here, so a force-stopped server kept listening
+ // with no entry left in the tree to stop it from.
+ server.close(() => undefined);
+ server.closeAllConnections();
+ }
+ }
+
+ /** The port the listener is actually bound to, or null when not listening. */
+ public getListeningPort(): number | null {
+ const address = this.server?.address();
+ return address && typeof address === 'object' ? address.port : null;
+ }
+
+ public getIsRunning(): boolean {
+ return this.isRunning;
+ }
+
+ public getServerUrl(): string | null {
+ if (!this.isRunning) {
+ return null;
+ }
+ return `https://${this.config.host}:${this.config.port}`;
+ }
+
+ public createAuthenticatedBrowserUrl(baseUrl: string): string {
+ return this.httpHandler.createAuthenticatedBrowserUrl(baseUrl);
+ }
+
+ /** #178: the scene is served by the embedded HttpServer, which owns the room. */
+ public revealInScene(absolutePath: string): boolean {
+ return this.httpHandler.revealInScene(absolutePath);
+ }
+
+ public createInvitation(): string {
+ return this.httpHandler.createInvitation();
+ }
+
+ public setRemotePublicUrl(publicUrl: string | null): void {
+ this.httpHandler.setRemotePublicUrl(publicUrl);
+ }
+
+ public getRemoteSessionAuthority(): RemoteSessionAuthority {
+ return this.httpHandler.getRemoteSessionAuthority();
+ }
+
+ public getConnectedParticipants(): ConnectedParticipantSummary[] {
+ return this.httpHandler.getConnectedParticipants();
+ }
+
+ public removeParticipant(peerId: string): ParticipantRemovalOutcome {
+ return this.httpHandler.removeParticipant(peerId);
+ }
+
+ public onConnectedParticipantsChanged(
+ listener: (participants: ConnectedParticipantSummary[]) => void,
+ ): () => void {
+ return this.httpHandler.onConnectedParticipantsChanged(listener);
+ }
+
+ protected assertNotRunning(): void {
+ if (this.isRunning) {
+ throw new Error('SERVER: HTTPS server is already running');
+ }
+ }
+
+ /**
+ * Keeps the configured port when it is free, and only otherwise searches
+ * upwards and adopts the next free one. The launcher has already picked a
+ * free port; searching again unconditionally went through get-port, which
+ * locks every port it returns for 15-30 s and therefore skipped the very
+ * port the launcher had just chosen, so the server listened one port above
+ * the one shown in the tree, the toast and the LAN URL.
+ */
+ protected async resolveListeningPort(): Promise {
+ if (await PortManager.isPortAvailable(this.config.port, this.config.host)) {
+ logger.debug(() => `Port ${this.config.port} is available on host ${this.config.host}`);
+ return;
+ }
+ logger.debug(() => `Looking for available port starting from ${this.config.port} on host ${this.config.host}...`);
+ const availablePort = await PortManager.findAvailablePort(this.config.port, this.config.port + 100, this.config.host);
+
+ if (availablePort !== this.config.port) {
+ logger.debug(() => `Port ${this.config.port} was busy, using ${availablePort} instead on host ${this.config.host}`);
+ this.config.port = availablePort;
+ } else {
+ logger.debug(() => `Port ${this.config.port} is available on host ${this.config.host}`);
+ }
+ }
+
+ /**
+ * Runs start()'s listen step: creates the TLS server, hands its requests
+ * and upgrades to HttpServer, handles 'close' and listen errors, and lets
+ * `wire` add the subclass's own 'listening' and 'tlsClientError' handlers
+ * and call listen(). A throw (for instance while loading the certificate
+ * pair) rejects start().
+ */
+ protected listenWithTls(
+ loadSslOptions: () => https.ServerOptions,
+ wire: (server: https.Server, resolve: (url: string) => void) => void,
+ ): Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ const server = https.createServer(loadSslOptions(), (req, res) => {
+ this.httpHandler.handleRequest(req, res);
+ });
+ this.server = server;
+ this.httpHandler.attachToNodeServer(server);
+
+ server.on('error', (error: NodeJS.ErrnoException) => this.rejectStart(error, reject));
+
+ server.on('close', () => {
+ logger.debug('HTTPS server closed');
+ this.isRunning = false;
+ });
+
+ wire(server, resolve);
+ } catch (error) {
+ logger.error('Error starting HTTPS server:', error);
+ reject(error);
+ }
+ });
+ }
+
+ /** The listen 'error' handler; `describeStartError` lets a subclass add an arm. */
+ private rejectStart(error: NodeJS.ErrnoException, reject: (reason: Error) => void): void {
+ logger.error('HTTPS server error:', error);
+ this.isRunning = false;
+
+ if (error.code === 'EADDRINUSE') {
+ reject(new Error(`SERVER: Port ${this.config.port} is already in use`));
+ } else if (error.code === 'EACCES') {
+ reject(new Error(`SERVER: Permission denied. May need to run as administrator for port ${this.config.port}`));
+ } else {
+ reject(this.describeStartError(error) ?? new Error(`SERVER: Failed to start HTTPS server: ${error.message}`));
+ }
+ }
+
+ protected describeStartError(_error: NodeJS.ErrnoException): Error | undefined {
+ return undefined;
+ }
+
+ /** Both files exist and are readable; throws the first problem found. */
+ protected async assertCertificatePairReadable(certPath: string, keyPath: string): Promise {
+ if (!fs.existsSync(certPath)) {
+ throw new Error(`SERVER: Certificate file not found: ${certPath}`);
+ }
+
+ if (!fs.existsSync(keyPath)) {
+ throw new Error(`SERVER: Private key file not found: ${keyPath}`);
+ }
+
+ await fs.promises.access(certPath, fs.constants.R_OK);
+ await fs.promises.access(keyPath, fs.constants.R_OK);
+ }
+
+ /**
+ * Reads the configured pair into the TLS options. Each subclass passes its
+ * own success log and failure prefix, so both strings stay per class.
+ */
+ protected loadSslOptions(loadedMessage: string, failurePrefix: string): https.ServerOptions {
+ try {
+ const cert = fs.readFileSync(this.config.certPath!, 'utf8');
+ const key = fs.readFileSync(this.config.keyPath!, 'utf8');
+
+ logger.debug(loadedMessage);
+
+ return buildTlsServerOptions(cert, key);
+ } catch (error) {
+ throw new Error(`${failurePrefix}: ${error}`);
+ }
+ }
+}
diff --git a/apps/vscode-extension/src/core/server/httpsTlsOptions.ts b/apps/vscode-extension/src/core/server/httpsTlsOptions.ts
new file mode 100644
index 000000000..a0e581925
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/httpsTlsOptions.ts
@@ -0,0 +1,40 @@
+import * as https from 'https';
+
+/**
+ * TLS settings shared by both HTTPS servers. RSA suites only: the generated
+ * local certificate is RSA, and so is any pair a user is told to configure.
+ * TLS 1.3 negotiates its own suites and is not limited by this list.
+ */
+export const HTTPS_CIPHER_SUITES: readonly string[] = [
+ 'ECDHE-RSA-AES128-GCM-SHA256',
+ 'ECDHE-RSA-AES256-GCM-SHA384',
+ 'ECDHE-RSA-AES128-SHA256',
+ 'ECDHE-RSA-AES256-SHA384',
+ 'DHE-RSA-AES128-GCM-SHA256',
+ 'DHE-RSA-AES256-GCM-SHA384',
+ 'AES128-GCM-SHA256',
+ 'AES256-GCM-SHA384',
+];
+
+export function buildTlsServerOptions(cert: string, key: string): https.ServerOptions {
+ return {
+ cert,
+ key,
+ rejectUnauthorized: false,
+ requestCert: false,
+ secureProtocol: 'TLS_method',
+ honorCipherOrder: false,
+ ciphers: HTTPS_CIPHER_SUITES.join(':'),
+ secureOptions: 0,
+ SNICallback: (_servername: string, callback: (err: Error | null, ctx?: any) => void) => {
+ callback(null);
+ },
+ };
+}
+
+/** A client (usually a headset browser) refused the self-signed certificate. */
+export function isCertificateRejectedByClient(error: Error): boolean {
+ return error.message.includes('SSLV3_ALERT_CERTIFICATE_UNKNOWN') ||
+ error.message.includes('certificate unknown') ||
+ error.message.includes('SSL alert number 46');
+}
diff --git a/apps/vscode-extension/src/core/server/launchNotifier.ts b/apps/vscode-extension/src/core/server/launchNotifier.ts
new file mode 100644
index 000000000..43d8f8304
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/launchNotifier.ts
@@ -0,0 +1,38 @@
+import type { ServerSettings } from './serverSettingsManager';
+import type { LaunchMode } from './registry/activeServerModel';
+
+/**
+ * What a person sees around a `MultiServerLauncher` launch: the HTTPS-to-HTTP
+ * override warning for the lateral panel, the busy-port notice and the
+ * auto-open (or its "Open Now" toast). The launcher holds no UI: the
+ * application registers an implementation at start-up (the extension:
+ * `features/active-servers/views/launchNotifications.ts`, from `extension.ts`),
+ * which is what removed the `core/server -> features/active-servers` layer
+ * exception (#13, step 7).
+ */
+export interface LaunchNotifier {
+ warnHttpsOverriddenForPanel(): void;
+ notifyPortChanged(requestedPort: number, finalPort: number): void;
+ handleAutoOpening(
+ settings: ServerSettings,
+ serverUrl: string,
+ htmlFile: string | undefined,
+ launchMode: LaunchMode,
+ activeServerId: string,
+ ): Promise;
+}
+
+let current: LaunchNotifier | null = null;
+
+/** Registers the launch UI. Called once at start-up; a later call replaces it (tests). */
+export function setLaunchNotifier(notifier: LaunchNotifier | null): void {
+ current = notifier;
+}
+
+/** The registered launch UI. Throws if none was registered, so a missing registration is loud. */
+export function getLaunchNotifier(): LaunchNotifier {
+ if (!current) {
+ throw new Error('No launch notifier registered. Call setLaunchNotifier(...) at start-up first.');
+ }
+ return current;
+}
diff --git a/apps/vscode-extension/src/core/server/launchServerWithFile.ts b/apps/vscode-extension/src/core/server/launchServerWithFile.ts
new file mode 100644
index 000000000..8d59fabd9
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/launchServerWithFile.ts
@@ -0,0 +1,42 @@
+/**
+ * Server Runtime Module
+ *
+ * This module provides the complete server runtime infrastructure for the CodeXR extension.
+ * It includes HTTP/HTTPS servers, port management, and a unified launcher system.
+ */
+
+// Core server implementations
+export { HttpServer, HttpServerConfig, ParticipantRemovalOutcome } from './httpServer';
+export { HttpsDefaultServer, HttpsDefaultServerConfig } from './httpsDefaultServer';
+export { HttpsCustomServer, HttpsCustomServerConfig } from './httpsCustomServer';
+
+// Utility classes
+export { PortManager } from './portManager';
+export { ScreenBroadcastSignalingServer } from './broadcast/screenBroadcastSignalingServer';
+export { CollaborationRoomServer } from './collaboration/collaborationRoomServer';
+
+// Main launcher and types
+export {
+ MultiServerLauncher,
+ MultiServerLaunchResult,
+ LaunchResult, // Now exported from multiServerLauncher.ts
+ ServerType,
+ ServerInstance
+} from './multiServerLauncher';
+
+// Import for use in utility functions
+import { MultiServerLauncher, MultiServerLaunchResult } from './multiServerLauncher';
+
+/**
+ * Launch server with a specific HTML file
+ * @param context - VS Code extension context
+ * @param htmlFilePath - Path to HTML file to serve
+ * @param customName - Optional custom display name for the server
+ * @param sessionId - Optional analysis session ID to link server to analysis
+ * @returns Promise
+ */
+export async function launchServerWithFile(context: any, htmlFilePath: string, customName?: string, sessionId?: string): Promise {
+ const launcher = new MultiServerLauncher(context);
+ const additionalMetadata = sessionId ? { sessionId } : undefined;
+ return launcher.launchServer(htmlFilePath, customName, additionalMetadata);
+}
diff --git a/apps/vscode-extension/src/core/server/multiServerLauncher.ts b/apps/vscode-extension/src/core/server/multiServerLauncher.ts
new file mode 100644
index 000000000..67ac54178
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/multiServerLauncher.ts
@@ -0,0 +1,327 @@
+import { PortManager } from './portManager';
+import { ServerSettingsManager } from './serverSettingsManager';
+import { LaunchMode, CertMode } from './registry/activeServerModel';
+import { getServerRegistrar } from './registry/serverRegistrar';
+import { getLaunchNotifier, type LaunchNotifier } from './launchNotifier';
+import {
+ determineCertMode,
+ determineLaunchMode,
+ launchServerByType,
+ resolveServerTypeForOpenMode,
+ ServerInstance,
+ ServerType,
+} from './serverFactory';
+import { getLogger } from '../../platform/logging/sink';
+import type { CoreContext } from '../host/hostPaths';
+
+const logger = getLogger('SERVER');
+
+export type { ServerInstance, ServerType } from './serverFactory';
+
+/**
+ * Launch result interface (consolidated from launcher.ts)
+ */
+export interface LaunchResult {
+ success: boolean;
+ serverUrl?: string;
+ serverType?: ServerType;
+ error?: string;
+ port?: number;
+ httpsOverridden?: boolean; // Indicates if HTTPS was overridden to HTTP for lateral panel compatibility
+}
+
+/**
+ * Multi-server launch result interface
+ */
+export interface MultiServerLaunchResult {
+ success: boolean;
+ serverUrl?: string;
+ serverType?: ServerType;
+ serverId?: string;
+ activeServerId?: string;
+ error?: string;
+ port?: number;
+ httpsOverridden?: boolean;
+ portChanged?: boolean;
+ originalPort?: number;
+}
+
+/**
+ * Running server info
+ */
+interface RunningServerInfo {
+ id: string;
+ server: ServerInstance;
+ serverType: ServerType;
+ port: number;
+ htmlFile?: string;
+ activeServerId: string;
+}
+
+/**
+ * Multi-Server Launcher
+ * Manages multiple HTTP/HTTPS servers running concurrently with dynamic port allocation
+ */
+export class MultiServerLauncher {
+ private servers: Map = new Map();
+ private settingsManager: ServerSettingsManager;
+
+ constructor(private context: CoreContext) {
+ this.settingsManager = ServerSettingsManager.getInstance(context);
+ logger.debug('Multi-server launcher initialized');
+ }
+
+ /** Logs (and, when it differs, announces) the port a server bound; returns whether it changed. */
+ private reportBoundPort(requestedPort: number, boundPort: number): boolean {
+ if (boundPort === requestedPort) {
+ logger.debug(() => `Using requested port ${boundPort}`);
+ return false;
+ }
+ logger.debug(() => `Port ${requestedPort} already in use. Using port ${boundPort} instead.`);
+ getLaunchNotifier().notifyPortChanged(requestedPort, boundPort);
+ return true;
+ }
+
+ /** Opens a freshly launched server per the settings; a failure is logged, never thrown. */
+ private async openLaunchedServer(
+ settings: Parameters[0],
+ serverUrl: string,
+ htmlFile: string | undefined,
+ activeServerId: string
+ ): Promise {
+ try {
+ await getLaunchNotifier().handleAutoOpening(settings, serverUrl, htmlFile, determineLaunchMode(settings), activeServerId);
+ } catch (error) {
+ logger.error('Failed to open the launched server:', error);
+ }
+ }
+
+ /** Stops a server that started but could not be registered, falling back to forceStop. */
+ private async discardUnregisteredServer(instance: { stop?: () => Promise; forceStop?: () => void } | undefined): Promise {
+ try {
+ if (typeof instance?.stop === 'function') {
+ await instance.stop();
+ }
+ } catch (stopError) {
+ logger.warn('Stopping the unregistered server failed; forcing it closed:', stopError);
+ try {
+ instance?.forceStop?.();
+ } catch (forceError) {
+ logger.warn('Forcing the unregistered server closed failed:', forceError);
+ }
+ }
+ }
+
+ /**
+ * Launch a new server instance with dynamic port allocation
+ * @param htmlFile Optional HTML file to serve
+ * @param customName Optional custom display name for the server
+ * @returns Promise
+ */
+ public async launchServer(
+ htmlFile?: string,
+ customName?: string,
+ additionalMetadata?: Record,
+ ): Promise {
+ try {
+ logger.debug('Starting multi-server launch process...');
+ logger.debug('launchServer called with parameters:', { htmlFile, customName });
+
+ // Load current settings
+ await this.settingsManager.ensureInitialized();
+ const settings = this.settingsManager.getServerSettings();
+ logger.debug('Loaded settings:', {
+ ...settings,
+ https: settings.https ? {
+ ...settings.https,
+ certPath: settings.https.certPath ? '***REDACTED***' : undefined,
+ keyPath: settings.https.keyPath ? '***REDACTED***' : undefined
+ } : undefined
+ });
+
+ // Check for HTTPS + lateral panel conflict and handle appropriately
+ const serverTypeResult = resolveServerTypeForOpenMode(settings);
+ const serverType = serverTypeResult.serverType;
+ const isHttpsOverridden = serverTypeResult.isOverridden;
+ if (isHttpsOverridden) {
+ getLaunchNotifier().warnHttpsOverriddenForPanel();
+ }
+
+ logger.debug('Determined server type:', serverType);
+ if (isHttpsOverridden) {
+ logger.debug('*** IMPORTANT *** Temporarily overriding HTTPS to HTTP for lateral panel compatibility');
+ }
+
+ // Find available port using dynamic allocation
+ const requestedPort = settings.defaultPort;
+ const finalPort = await this.findAvailablePortWithLogging(requestedPort);
+
+ // Launch the server - Use 0.0.0.0 to listen on all network interfaces for external access
+ const host = '0.0.0.0';
+ logger.debug(() => `DEBUG - Configuring server to listen on ${host}:${finalPort} for network access`);
+ const result = await launchServerByType(
+ this.context,
+ serverType,
+ settings,
+ finalPort,
+ host,
+ htmlFile,
+ additionalMetadata,
+ );
+
+ if (result.success && result.serverUrl) {
+ // The port the server really listens on. Everything below
+ // (registry, session, toasts, LAN URL) uses it, never the port
+ // that was only requested.
+ const boundPort = result.port ?? finalPort;
+ const portChanged = this.reportBoundPort(requestedPort, boundPort);
+ logger.debug(() => `Successfully launched ${serverType} server on port ${boundPort}`);
+
+ // Generate unique server ID
+ const serverId = this.generateServerId();
+
+ // Store server info
+ const serverInfo: RunningServerInfo = {
+ id: serverId,
+ server: result.serverInstance!,
+ serverType: serverType,
+ port: boundPort,
+ htmlFile: htmlFile,
+ activeServerId: ''
+ };
+
+ // Register server in active servers registry
+ try {
+ const launchMode: LaunchMode = determineLaunchMode(settings);
+ const certMode: CertMode = determineCertMode(serverType, result.httpsOverridden);
+
+ logger.debug('DEBUG - About to register server with the following details:');
+ logger.debug('DEBUG - customName:', customName);
+ logger.debug('DEBUG - port:', boundPort);
+ logger.debug('DEBUG - url:', result.serverUrl);
+
+ const registrar = getServerRegistrar();
+ const activeServer = registrar.registerServer({
+ port: boundPort,
+ url: result.serverUrl,
+ launchMode: launchMode,
+ certMode: certMode,
+ timestamp: Date.now(),
+ htmlFile: htmlFile,
+ customName: customName,
+ serverInstance: result.serverInstance,
+ metadata: {
+ serverType: serverType,
+ originalPort: requestedPort,
+ portChanged: portChanged,
+ httpsOverridden: isHttpsOverridden,
+ launcherId: 'multi-server',
+ serverInstanceId: serverId,
+ ...additionalMetadata // Add any additional metadata passed in
+ }
+ });
+
+ logger.debug('Successfully registered server with registry:');
+ logger.debug('Registered server ID:', activeServer.id);
+ logger.debug('Registered server customName:', activeServer.customName);
+
+ serverInfo.activeServerId = activeServer.id;
+ this.servers.set(serverId, serverInfo);
+
+ logger.debug(() => `Successfully registered server ${serverId} (active ID: ${activeServer.id}) via registrar service`);
+ logger.debug(() => `Currently managing ${this.servers.size} server(s)`);
+ } catch (error) {
+ // A server nobody registered cannot be found, listed or
+ // stopped again: stop it now and report the launch as failed
+ // instead of leaving an unreachable listener on 0.0.0.0.
+ logger.error('Failed to register server in registry:', error);
+ this.servers.delete(serverId);
+ await this.discardUnregisteredServer(result.serverInstance);
+ return {
+ success: false,
+ error: `Failed to register the server: ${error instanceof Error ? error.message : String(error)}`,
+ httpsOverridden: isHttpsOverridden
+ };
+ }
+
+ // Handle auto-opening based on configuration. A failure to open
+ // the page does not undo a server that is running and listed.
+ await this.openLaunchedServer(settings, result.serverUrl, htmlFile, serverInfo.activeServerId);
+
+ return {
+ success: true,
+ serverUrl: result.serverUrl,
+ serverType: serverType,
+ serverId: serverId,
+ activeServerId: serverInfo.activeServerId || undefined,
+ port: boundPort,
+ httpsOverridden: isHttpsOverridden,
+ portChanged: portChanged,
+ originalPort: requestedPort
+ };
+ } else {
+ return {
+ success: false,
+ error: result.error || 'Unknown server launch error',
+ httpsOverridden: isHttpsOverridden
+ };
+ }
+
+ } catch (error) {
+ logger.error('Error during multi-server launch:', error);
+ return {
+ success: false,
+ error: `Failed to launch server: ${error instanceof Error ? error.message : String(error)}`
+ };
+ }
+ }
+
+ /**
+ * Get count of running servers
+ * @returns number
+ */
+ public getRunningServerCount(): number {
+ return this.servers.size;
+ }
+
+ /**
+ * Find available port with enhanced logging
+ * @private
+ */
+ private async findAvailablePortWithLogging(requestedPort: number): Promise {
+ logger.debug(() => `Checking availability of port ${requestedPort}...`);
+
+ const isAvailable = await PortManager.isPortAvailable(requestedPort);
+ if (isAvailable) {
+ logger.debug(() => `Port ${requestedPort} is available`);
+ return requestedPort;
+ }
+
+ logger.debug(() => `Port ${requestedPort} already in use. Searching for next available port (${requestedPort + 1})...`);
+
+ try {
+ // The search window follows the requested port: the default end port
+ // (8080) made a busy 8080 (allowed by the settings) fail every launch.
+ const availablePort = await PortManager.findAvailablePort(
+ requestedPort + 1,
+ Math.min(65535, requestedPort + 100),
+ );
+ logger.debug(() => `Free port found at ${availablePort}. Launching server...`);
+ return availablePort;
+ } catch (error) {
+ logger.error(`Failed to find available port starting from ${requestedPort + 1}:`, error);
+ throw new Error(`No available ports found starting from ${requestedPort}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ /**
+ * Generate unique server ID
+ * @private
+ */
+ private generateServerId(): string {
+ const timestamp = Date.now();
+ const random = Math.random().toString(36).slice(2, 7);
+ return `server_${timestamp}_${random}`;
+ }
+}
+
diff --git a/apps/vscode-extension/src/core/server/networkUtils.ts b/apps/vscode-extension/src/core/server/networkUtils.ts
new file mode 100644
index 000000000..709c6bced
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/networkUtils.ts
@@ -0,0 +1,133 @@
+/**
+ * Network Utilities for Server Configuration
+ * Provides network-related helper functions for server setup
+ */
+
+import * as os from 'os';
+import { getLogger } from '../../platform/logging/sink';
+
+const logger = getLogger('NETWORK_UTILS');
+
+export class NetworkUtils {
+
+ /**
+ * Get the local IP address for external device access
+ * @returns string - Local IP address or fallback to localhost
+ */
+ static getLocalIPAddress(): string {
+ const interfaces = os.networkInterfaces();
+
+ // Look for non-internal IPv4 addresses
+ for (const name of Object.keys(interfaces)) {
+ if (interfaces[name]) {
+ for (const iface of interfaces[name]!) {
+ // Skip internal (localhost) and IPv6 addresses
+ if (iface.family === 'IPv4' && !iface.internal) {
+ logger.debug(() => `SERVER: Found local IP address: ${iface.address} (${name})`);
+ return iface.address;
+ }
+ }
+ }
+ }
+
+ logger.warn('SERVER: Could not find local IP address, falling back to localhost');
+ return 'localhost';
+ }
+
+ /**
+ * Generate server URLs for different access methods
+ * @param port - Server port
+ * @param protocol - 'http' or 'https'
+ * @returns Object with different URL options
+ */
+ static generateServerUrls(port: number, protocol: 'http' | 'https' = 'https'): {
+ localhost: string;
+ localIP: string;
+ allInterfaces: string[];
+ } {
+ const localIP = this.getLocalIPAddress();
+
+ return {
+ localhost: `${protocol}://localhost:${port}`,
+ localIP: `${protocol}://${localIP}:${port}`,
+ allInterfaces: [
+ `${protocol}://localhost:${port}`,
+ `${protocol}://${localIP}:${port}`,
+ `${protocol}://0.0.0.0:${port}`
+ ]
+ };
+ }
+
+ /**
+ * Get the primary external URL for client connections
+ * @param port - Server port
+ * @param protocol - 'http' or 'https'
+ * @returns string - Primary external URL
+ */
+ static getPrimaryExternalUrl(port: number, protocol: 'http' | 'https' = 'https'): string {
+ const localIP = this.getLocalIPAddress();
+ return `${protocol}://${localIP}:${port}`;
+ }
+
+ /**
+ * Get the localhost URL for browser/panel access
+ * @param port - Server port
+ * @param protocol - 'http' or 'https'
+ * @returns string - Localhost URL for local access
+ */
+ static getLocalhostUrl(port: number, protocol: 'http' | 'https' = 'https'): string {
+ return `${protocol}://localhost:${port}`;
+ }
+
+ /**
+ * Display network configuration information
+ * @param port - Server port
+ * @param protocol - 'http' or 'https'
+ */
+ static displayNetworkInfo(port: number, protocol: 'http' | 'https' = 'https'): void {
+ const urls = this.generateServerUrls(port, protocol);
+
+ logger.debug('\n=== SERVER NETWORK CONFIGURATION ===');
+ logger.debug('====================================');
+ logger.debug(() => `Primary External URL: ${urls.localIP}`);
+ logger.debug(() => `Localhost URL: ${urls.localhost}`);
+ logger.debug(() => `For VR/Mobile devices use: ${urls.localIP}`);
+ logger.debug(() => `For local testing use: ${urls.localhost}`);
+ logger.debug('Network Diagnostics:');
+ logger.debug(() => ` - Server listening on: 0.0.0.0:${port}`);
+ logger.debug(() => ` - Local IP detected: ${this.getLocalIPAddress()}`);
+ logger.debug(() => ` - Protocol: ${protocol.toUpperCase()}`);
+ logger.debug('====================================\n');
+
+ // Additional diagnostic info
+ this.performNetworkDiagnostics(port);
+ }
+
+ /**
+ * Perform network diagnostics
+ * @param port - Server port to diagnose
+ */
+ static performNetworkDiagnostics(port: number): void {
+ logger.debug('=== NETWORK DIAGNOSTICS ===');
+
+ // Check all network interfaces
+ const interfaces = os.networkInterfaces();
+ logger.debug('Available network interfaces:');
+
+ for (const [name, details] of Object.entries(interfaces)) {
+ if (details) {
+ for (const detail of details) {
+ if (detail.family === 'IPv4') {
+ const status = detail.internal ? '(internal)' : '(external)';
+ logger.debug(() => ` ${name}: ${detail.address} ${status}`);
+ }
+ }
+ }
+ }
+
+ logger.debug(`\nServer should be accessible at:`);
+ logger.debug(() => ` - Local: http://127.0.0.1:${port}`);
+ logger.debug(() => ` - Network: http://${this.getLocalIPAddress()}:${port}`);
+ logger.debug('===========================\n');
+ }
+}
diff --git a/apps/vscode-extension/src/core/server/portManager.ts b/apps/vscode-extension/src/core/server/portManager.ts
new file mode 100644
index 000000000..384387c31
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/portManager.ts
@@ -0,0 +1,173 @@
+import * as net from 'net';
+import { getLogger } from '../../platform/logging/sink';
+
+const logger = getLogger('SERVER');
+
+/**
+ * Port availability checker and manager
+ * Provides utilities to find available ports starting from a given port number
+ */
+export class PortManager {
+ private static readonly DEFAULT_START_PORT = 3000;
+ private static readonly DEFAULT_END_PORT = 8080;
+ private static readonly MAX_RETRIES = 50;
+ /** Addresses that listen on every interface, loopback included. */
+ private static readonly WILDCARD_HOSTS = new Set(['0.0.0.0', '::']);
+ /** The addresses a host-less or wildcard probe checks (LAUNCHER-13, #111). */
+ public static readonly PROBED_HOSTS: readonly string[] = ['0.0.0.0', '127.0.0.1', '::1'];
+
+ /**
+ * Check if a specific port is available
+ * @param port - The port number to check
+ * @param host - The host to bind to. Without one, or with a wildcard
+ * address (`0.0.0.0`, `::`), the port must be free on the wildcard
+ * address and on loopback (see isPortFreeEverywhere): a server on the
+ * wildcard answers "localhost" too, so loopback is where it collides.
+ * @returns Promise - True if port is available, false otherwise
+ */
+ public static async isPortAvailable(port: number, host?: string): Promise {
+ if (host === undefined || PortManager.WILDCARD_HOSTS.has(host)) {
+ return PortManager.isPortFreeEverywhere(port);
+ }
+ return new Promise((resolve) => {
+ const server = net.createServer();
+
+ server.listen(port, host, () => {
+ server.close(() => {
+ logger.debug(() => `Port ${port} is available on ${host}`);
+ resolve(true);
+ });
+ });
+
+ server.on('error', (err: NodeJS.ErrnoException) => {
+ if (err.code === 'EADDRINUSE') {
+ logger.debug(() => `Port ${port} is already in use on ${host}`);
+ resolve(false);
+ } else {
+ logger.error(`Error checking port ${port}:`, err);
+ resolve(false);
+ }
+ });
+ });
+ }
+
+ /**
+ * True only when the port is free on the wildcard address AND on loopback
+ * (IPv4 and IPv6). Checking 0.0.0.0 alone is not enough on macOS and
+ * Windows: a wildcard bind can succeed while another process (a Vite or
+ * Next dev server, typically on 3000) owns 127.0.0.1 or ::1, and
+ * "localhost" then reaches that other app instead of Code-XR.
+ */
+ public static async isPortFreeEverywhere(port: number): Promise {
+ for (const host of PortManager.PROBED_HOSTS) {
+ const free = await PortManager.isPortAvailableOnHost(port, host);
+ if (!free) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /** Like isPortAvailable, but a host this machine does not have (no IPv6) counts as free. */
+ private static isPortAvailableOnHost(port: number, host: string): Promise {
+ return new Promise((resolve) => {
+ const server = net.createServer();
+ server.once('error', (err: NodeJS.ErrnoException) => {
+ resolve(err.code === 'EADDRNOTAVAIL' || err.code === 'EAFNOSUPPORT');
+ });
+ server.listen({ port, host, exclusive: true }, () => {
+ server.close(() => resolve(true));
+ });
+ });
+ }
+
+ /**
+ * Find the first available port starting from a given port number
+ * @param startPort - The starting port number (default: 3000)
+ * @param endPort - The ending port number (default: 8080)
+ * @param host - The host to bind to (default: '0.0.0.0')
+ * @returns Promise - The first available port found
+ * @throws Error if no available port is found within the range
+ */
+ public static async findAvailablePort(
+ startPort: number = PortManager.DEFAULT_START_PORT,
+ endPort: number = PortManager.DEFAULT_END_PORT,
+ host: string = '0.0.0.0'
+ ): Promise {
+ logger.debug(() => `Searching for available port starting from ${startPort} on host ${host}`);
+
+ // Validate inputs
+ if (startPort < 1 || startPort > 65535) {
+ throw new Error(`SERVER: Invalid start port ${startPort}. Must be between 1 and 65535`);
+ }
+
+ if (endPort < startPort || endPort > 65535) {
+ throw new Error(`SERVER: Invalid end port ${endPort}. Must be between ${startPort} and 65535`);
+ }
+
+ try {
+ // Use get-port for more reliable port detection with sequential checking
+ const getPort = (await import('get-port')).default;
+
+ // Create a sequential range array for get-port
+ const maxRange = Math.min(endPort - startPort + 1, 100); // Check up to 100 ports sequentially
+ const ports: number[] = [];
+ for (let i = 0; i < maxRange; i++) {
+ const port = startPort + i;
+ if (port <= endPort) {
+ ports.push(port);
+ }
+ }
+
+ logger.debug(() => `Checking ${ports.length} ports sequentially from ${startPort} to ${startPort + maxRange - 1}`);
+
+ // No host: get-port then checks the wildcard and every local
+ // interface, loopback included (see isPortFreeEverywhere).
+ const availablePort = await getPort({
+ port: ports,
+ });
+
+ logger.debug(() => `Found available port: ${availablePort} (sequential search successful)`);
+ return availablePort;
+ } catch (error) {
+ logger.error(`get-port failed, using manual sequential detection:`, error);
+
+ return PortManager.scanSequentially(startPort, endPort, host);
+ }
+ }
+
+ /**
+ * The fallback when get-port fails: the first port from `startPort` that
+ * isPortAvailable accepts, trying at most MAX_RETRIES ports. With the
+ * default wildcard host that is the same three-address check as the main
+ * probe (#111); it used to bind 0.0.0.0 alone, which succeeds on macOS and
+ * Windows while a dev server owns 127.0.0.1 on the same port.
+ */
+ public static async scanSequentially(startPort: number, endPort: number, host?: string): Promise {
+ logger.debug(() => `Manual port scanning from ${startPort} to ${endPort}`);
+ let currentPort = startPort;
+ let attempts = 0;
+ const maxAttempts = Math.min(endPort - startPort + 1, PortManager.MAX_RETRIES);
+
+ while (attempts < maxAttempts) {
+ if (currentPort > endPort) {
+ break;
+ }
+
+ logger.debug(() => `Testing port ${currentPort} availability on ${host ?? 'all local addresses'}`);
+ if (await PortManager.isPortAvailable(currentPort, host)) {
+ logger.debug(() => `Port ${currentPort} is available and ready for use`);
+ return currentPort;
+ } else {
+ logger.debug(() => `Port ${currentPort} is occupied, trying next port ${currentPort + 1}`);
+ }
+
+ currentPort++;
+ attempts++;
+ }
+
+ throw new Error(
+ `SERVER: No available port found in range ${startPort}-${endPort} after checking ${attempts} ports sequentially`
+ );
+ }
+}
diff --git a/apps/vscode-extension/src/core/server/registry/activeServerModel.ts b/apps/vscode-extension/src/core/server/registry/activeServerModel.ts
new file mode 100644
index 000000000..71f2dcfd6
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/registry/activeServerModel.ts
@@ -0,0 +1,108 @@
+/**
+ * Active Server Model
+ * Type definitions for active server tracking
+ */
+
+/**
+ * Certificate mode used by the server
+ */
+export type CertMode = 'http' | 'https-default' | 'https-custom';
+
+/**
+ * Launch mode for server opening
+ */
+export type LaunchMode = 'browser' | 'lateralPanel';
+
+/**
+ * Server status information
+ */
+export type ServerStatus = 'running' | 'stopped' | 'error';
+
+/**
+ * Active server information
+ */
+export interface ActiveServer {
+ /** Unique identifier for the server */
+ id: string;
+
+ /** Server port */
+ port: number;
+
+ /** Complete server URL */
+ url: string;
+
+ /** Launch mode (browser/lateralPanel) */
+ launchMode: LaunchMode;
+
+ /** Certificate mode (http/https-default/https-custom) */
+ certMode: CertMode;
+
+ /** Timestamp when server was launched */
+ timestamp: number;
+
+ /** Current server status */
+ status: ServerStatus;
+
+ /** Optional public tunnel state for this server. */
+ remoteAccess?: RemoteAccessState;
+
+ /** HTML file being served (if any) */
+ htmlFile?: string;
+
+ /** Custom display name for the server (overrides default filename display) */
+ customName?: string;
+
+ /** Server instance reference for control operations */
+ serverInstance?: ActiveServerRuntime;
+
+ /** Additional metadata */
+ metadata?: ActiveServerMetadata;
+}
+
+/**
+ * The runtime behind a registered server (HttpServer or one of the HTTPS
+ * servers). Declared structurally, with only what the extension calls on it,
+ * so this model stays free of the server runtime and of vscode.
+ */
+export interface ActiveServerRuntime {
+ stop(): Promise;
+ forceStop(): void;
+ createAuthenticatedBrowserUrl(baseUrl: string): string;
+ /** #178: asks the scene to reveal a file of its analysed folder; false when the file is not in it. */
+ revealInScene?(absolutePath: string): boolean;
+}
+
+/**
+ * Registration metadata, stored as given: the fields the extension reads,
+ * plus whatever the launcher records (serverType, originalPort, portChanged,
+ * launcherId, ...) and its callers add.
+ */
+export interface ActiveServerMetadata {
+ host?: string;
+ staticRoot?: string;
+ description?: string;
+ /** The analysis session the server serves, when the registration names one. */
+ sessionId?: string;
+ [field: string]: unknown;
+}
+
+/**
+ * Server action types for UI interactions
+ */
+export type ServerAction = 'openBrowser' | 'openPanel' | 'copyUrl' | 'stop' | 'details';
+
+/**
+ * Registry event types
+ */
+export type RegistryEventType = 'serverAdded' | 'serverRemoved' | 'serverUpdated' | 'registryCleared';
+
+/**
+ * Registry event data
+ */
+export interface RegistryEvent {
+ type: RegistryEventType;
+ serverId?: string;
+ server?: ActiveServer;
+ timestamp: number;
+}
+import { RemoteAccessState } from '../../remote-access/remoteAccessModel';
diff --git a/apps/vscode-extension/src/core/server/registry/activeServerRegistry.ts b/apps/vscode-extension/src/core/server/registry/activeServerRegistry.ts
new file mode 100644
index 000000000..5181c3e22
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/registry/activeServerRegistry.ts
@@ -0,0 +1,350 @@
+import { EventEmitter } from 'events';
+import { ActiveServer, ActiveServerMetadata, ActiveServerRuntime, RegistryEvent, RegistryEventType, LaunchMode, CertMode } from './activeServerModel';
+import { RemoteAccessState } from '../../remote-access/remoteAccessModel';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('ACTIVE_SERVERS');
+
+const REGISTRY_CHANGE = 'change';
+
+/** What a subscription returns: structurally a `vscode.Disposable`. */
+export interface RegistrySubscription {
+ dispose(): void;
+}
+
+/** Same call shape as `vscode.Event`, without depending on vscode. */
+export type RegistryChangeEvent = (
+ listener: (event: RegistryEvent) => unknown,
+ thisArgs?: unknown,
+ disposables?: RegistrySubscription[],
+) => RegistrySubscription;
+
+/**
+ * Active Server Registry
+ * Centralized tracking and management of all active servers
+ */
+export class ActiveServerRegistry {
+ private static instance: ActiveServerRegistry | null = null;
+ private servers: Map = new Map();
+ private readonly eventEmitter = new EventEmitter();
+ private disposed = false;
+
+ /**
+ * Event fired when registry changes. Keeps the `vscode.Event` contract:
+ * listeners run in subscription order, a throwing listener is reported and
+ * does not stop the others, and nothing is delivered after `dispose()`.
+ */
+ public readonly onRegistryChange: RegistryChangeEvent = (listener, thisArgs, disposables) => {
+ const bound = (event: RegistryEvent): void => {
+ try {
+ listener.call(thisArgs, event);
+ } catch (error) {
+ logger.error('Registry change listener failed:', error);
+ }
+ };
+ if (!this.disposed) {
+ this.eventEmitter.on(REGISTRY_CHANGE, bound);
+ }
+ const subscription: RegistrySubscription = {
+ dispose: () => {
+ this.eventEmitter.off(REGISTRY_CHANGE, bound);
+ },
+ };
+ disposables?.push(subscription);
+ return subscription;
+ };
+
+ private constructor() {
+ // No leak warning: the tree, the watcher integration and remote access subscribe once each.
+ this.eventEmitter.setMaxListeners(0);
+ logger.debug('Registry initialized');
+ }
+
+ /**
+ * Get singleton instance
+ */
+ public static getInstance(): ActiveServerRegistry {
+ if (!ActiveServerRegistry.instance) {
+ ActiveServerRegistry.instance = new ActiveServerRegistry();
+ }
+ return ActiveServerRegistry.instance;
+ }
+
+ /**
+ * Register a new active server
+ */
+ public registerServer(config: {
+ port: number;
+ url: string;
+ launchMode: LaunchMode;
+ certMode: CertMode;
+ timestamp: number;
+ htmlFile?: string;
+ customName?: string;
+ serverInstance?: ActiveServerRuntime;
+ metadata?: ActiveServerMetadata;
+ }): ActiveServer {
+ logger.debug('SERVER: registerServer called with config:', {
+ port: config.port,
+ htmlFile: config.htmlFile,
+ customName: config.customName,
+ url: config.url
+ });
+
+ const serverId = this.generateServerId(config.port, config.timestamp);
+
+ const server: ActiveServer = {
+ id: serverId,
+ port: config.port,
+ url: config.url,
+ launchMode: config.launchMode,
+ certMode: config.certMode,
+ timestamp: config.timestamp,
+ status: 'running',
+ htmlFile: config.htmlFile,
+ customName: config.customName,
+ serverInstance: config.serverInstance,
+ metadata: config.metadata
+ };
+
+ this.servers.set(serverId, server);
+
+ // Enhanced logging for custom names
+ logger.debug(() => `Registered server ${serverId} at ${config.url} (${config.certMode}/${config.launchMode})`);
+ if (config.customName && config.customName.trim().length > 0) {
+ logger.debug(() => `Received custom name from launcher: ${config.customName}`);
+ logger.debug(() => `Registering server with name: ${config.customName}`);
+ } else {
+ const fallbackName = `localhost:${config.port}`;
+ logger.debug(() => `No custom name provided. Using default name: ${fallbackName}`);
+ }
+
+ this.emitEvent('serverAdded', serverId, server);
+
+ return server;
+ }
+
+ /**
+ * Remove a server from the registry
+ */
+ public unregisterServer(serverId: string): boolean {
+ const server = this.servers.get(serverId);
+ if (!server) {
+ logger.warn(`Attempted to unregister non-existent server: ${serverId}`);
+ return false;
+ }
+
+ this.servers.delete(serverId);
+
+ logger.debug(() => `Unregistered server ${serverId} (${server.url})`);
+
+ this.emitEvent('serverRemoved', serverId, server);
+
+ return true;
+ }
+
+ /**
+ * Update server status
+ */
+ public updateServerStatus(serverId: string, status: 'running' | 'stopped' | 'error'): boolean {
+ const server = this.servers.get(serverId);
+ if (!server) {
+ logger.warn(`Attempted to update status of non-existent server: ${serverId}`);
+ return false;
+ }
+
+ server.status = status;
+
+ logger.debug(() => `Updated server ${serverId} status to ${status}`);
+
+ this.emitEvent('serverUpdated', serverId, server);
+
+ return true;
+ }
+
+ public updateRemoteAccessState(serverId: string, state: RemoteAccessState): boolean {
+ const server = this.servers.get(serverId);
+ if (!server) {
+ return false;
+ }
+ server.remoteAccess = { ...state };
+ this.emitEvent('serverUpdated', serverId, server);
+ return true;
+ }
+
+ /**
+ * Get server by ID
+ */
+ public getServer(serverId: string): ActiveServer | undefined {
+ return this.servers.get(serverId);
+ }
+
+ /**
+ * Get all active servers
+ */
+ public getAllServers(): ActiveServer[] {
+ return Array.from(this.servers.values());
+ }
+
+ /**
+ * Get servers by status
+ */
+ public getServersByStatus(status: 'running' | 'stopped' | 'error'): ActiveServer[] {
+ return this.getAllServers().filter(server => server.status === status);
+ }
+
+ /**
+ * Get servers by port
+ */
+ public getServerByPort(port: number): ActiveServer | undefined {
+ return this.getAllServers().find(server => server.port === port);
+ }
+
+ /**
+ * Check if a server is registered
+ */
+ public hasServer(serverId: string): boolean {
+ return this.servers.has(serverId);
+ }
+
+ /**
+ * Get count of active servers
+ */
+ public getServerCount(): number {
+ return this.servers.size;
+ }
+
+ /**
+ * Get count of running servers
+ */
+ public getRunningServerCount(): number {
+ return this.getServersByStatus('running').length;
+ }
+
+ /**
+ * Clear all servers from registry
+ */
+ public clearAll(): void {
+ const count = this.servers.size;
+ this.servers.clear();
+
+ logger.debug(() => `Cleared all servers (${count} removed)`);
+
+ this.emitEvent('registryCleared');
+ }
+
+ /**
+ * Cleanup stopped/error servers
+ */
+ public cleanupInactiveServers(): number {
+ const inactiveServers = this.getAllServers().filter(server =>
+ server.status === 'stopped' || server.status === 'error'
+ );
+
+ let removedCount = 0;
+ for (const server of inactiveServers) {
+ if (this.unregisterServer(server.id)) {
+ removedCount++;
+ }
+ }
+
+ if (removedCount > 0) {
+ logger.debug(() => `Cleaned up ${removedCount} inactive servers`);
+ }
+
+ return removedCount;
+ }
+
+ /**
+ * Get registry statistics
+ */
+ public getStats(): {
+ total: number;
+ running: number;
+ stopped: number;
+ error: number;
+ byMode: { [mode: string]: number };
+ byCertMode: { [mode: string]: number };
+ } {
+ const servers = this.getAllServers();
+
+ const stats = {
+ total: servers.length,
+ running: 0,
+ stopped: 0,
+ error: 0,
+ byMode: {} as { [mode: string]: number },
+ byCertMode: {} as { [mode: string]: number }
+ };
+
+ for (const server of servers) {
+ // Count by status
+ stats[server.status]++;
+
+ // Count by launch mode
+ stats.byMode[server.launchMode] = (stats.byMode[server.launchMode] || 0) + 1;
+
+ // Count by cert mode
+ stats.byCertMode[server.certMode] = (stats.byCertMode[server.certMode] || 0) + 1;
+ }
+
+ return stats;
+ }
+
+ /**
+ * Dispose of the registry
+ */
+ public dispose(): void {
+ this.disposed = true;
+ this.eventEmitter.removeAllListeners();
+ this.clearAll();
+ logger.debug('Registry disposed');
+ }
+
+ /**
+ * Generate unique server ID
+ * @private
+ */
+ private generateServerId(port: number, timestamp: number): string {
+ return `server-${port}-${timestamp}`;
+ }
+
+ /**
+ * Emit registry event
+ * @private
+ */
+ private emitEvent(type: RegistryEventType, serverId?: string, server?: ActiveServer): void {
+ const event: RegistryEvent = {
+ type,
+ serverId,
+ server,
+ timestamp: Date.now()
+ };
+
+ this.eventEmitter.emit(REGISTRY_CHANGE, event);
+ }
+}
+
+/**
+ * Convenience function to get the registry instance
+ */
+export function getActiveServerRegistry(): ActiveServerRegistry {
+ return ActiveServerRegistry.getInstance();
+}
+
+/**
+ * Convenience function to register a server
+ */
+export function registerActiveServer(config: {
+ port: number;
+ url: string;
+ launchMode: LaunchMode;
+ certMode: CertMode;
+ timestamp: number;
+ htmlFile?: string;
+ customName?: string;
+ serverInstance?: ActiveServerRuntime;
+ metadata?: ActiveServerMetadata;
+}): ActiveServer {
+ return getActiveServerRegistry().registerServer(config);
+}
diff --git a/src/active_servers/services/serverRegistrar.ts b/apps/vscode-extension/src/core/server/registry/serverRegistrar.ts
similarity index 84%
rename from src/active_servers/services/serverRegistrar.ts
rename to apps/vscode-extension/src/core/server/registry/serverRegistrar.ts
index cc892106b..cb43bd112 100644
--- a/src/active_servers/services/serverRegistrar.ts
+++ b/apps/vscode-extension/src/core/server/registry/serverRegistrar.ts
@@ -1,5 +1,8 @@
-import { ActiveServer, LaunchMode, CertMode } from '../model/activeServerModel';
-import { registerActiveServer } from '../registry/activeServerRegistry';
+import { ActiveServer, ActiveServerMetadata, ActiveServerRuntime, LaunchMode, CertMode } from './activeServerModel';
+import { registerActiveServer } from './activeServerRegistry';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('SERVER_REGISTRAR');
/**
* Server registration configuration interface
@@ -12,8 +15,8 @@ export interface ServerRegistrationConfig {
timestamp: number;
htmlFile?: string;
customName?: string;
- serverInstance?: any;
- metadata?: any;
+ serverInstance?: ActiveServerRuntime;
+ metadata?: ActiveServerMetadata;
}
/**
@@ -25,7 +28,7 @@ export class ServerRegistrar {
private static instance: ServerRegistrar | null = null;
private constructor() {
- console.log('SERVER_REGISTRAR: Service initialized');
+ logger.debug('Service initialized');
}
/**
@@ -44,7 +47,7 @@ export class ServerRegistrar {
* @returns Registered ActiveServer
*/
public registerServer(config: ServerRegistrationConfig): ActiveServer {
- console.log('SERVER_REGISTRAR: Registering server with config:', {
+ logger.debug('Registering server with config:', {
port: config.port,
customName: config.customName,
url: config.url,
@@ -59,12 +62,12 @@ export class ServerRegistrar {
// Register with the registry
const activeServer = registerActiveServer(config);
- console.log(`SERVER_REGISTRAR: Successfully registered server ${activeServer.id}`);
+ logger.debug(() => `Successfully registered server ${activeServer.id}`);
return activeServer;
} catch (error) {
- console.error('SERVER_REGISTRAR: Failed to register server:', error);
+ logger.error('Failed to register server:', error);
throw new Error(`Server registration failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
diff --git a/src/servers/runtime/remote/brandMark.ts b/apps/vscode-extension/src/core/server/remote/brandMark.ts
similarity index 100%
rename from src/servers/runtime/remote/brandMark.ts
rename to apps/vscode-extension/src/core/server/remote/brandMark.ts
diff --git a/src/servers/runtime/remote/pairingPage.ts b/apps/vscode-extension/src/core/server/remote/pairingPage.ts
similarity index 96%
rename from src/servers/runtime/remote/pairingPage.ts
rename to apps/vscode-extension/src/core/server/remote/pairingPage.ts
index b358e5edf..0cf0b7f25 100644
--- a/src/servers/runtime/remote/pairingPage.ts
+++ b/apps/vscode-extension/src/core/server/remote/pairingPage.ts
@@ -163,7 +163,7 @@ export function renderPairingPage(invitationToken: string): string {
const body = `
Join the XR session
-
Connect to a CodeXR workspace shared across networks.
+
Connect to a Code-XR workspace shared across networks.
Step 1 · How you appear
-
CodeXR reserved this anonymous alias for you.
+
Code-XR reserved this anonymous alias for you.
Then ask the host for the temporary six-digit code.
@@ -186,7 +186,7 @@ export function renderPairingPage(invitationToken: string): string {
const invitationToken=${tokenLiteral};let requestId='',identityToken='',anonymousAlias='';
const status=document.querySelector('#status'),code=document.querySelector('#code'),confirmButton=document.querySelector('#confirm'),nameInput=document.querySelector('#name'),requestButton=document.querySelector('#request');
function selectedMode(){return document.querySelector('input[name="identity"]:checked').value}
-function updateIdentityMode(){const custom=selectedMode()==='custom';nameInput.disabled=!custom;nameInput.value=custom?'':anonymousAlias;document.querySelector('#identity-hint').textContent=custom?'Use between 2 and 32 characters.':'CodeXR reserved this anonymous alias for you.'}
+function updateIdentityMode(){const custom=selectedMode()==='custom';nameInput.disabled=!custom;nameInput.value=custom?'':anonymousAlias;document.querySelector('#identity-hint').textContent=custom?'Use between 2 and 32 characters.':'Code-XR reserved this anonymous alias for you.'}
document.querySelectorAll('input[name="identity"]').forEach(input=>input.onchange=updateIdentityMode);
async function prepareIdentity(){requestButton.disabled=true;status.textContent='Preparing identity...';try{const response=await fetch('/api/remote/identity',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({invitationToken})});if(!response.ok)throw new Error();const data=await response.json();identityToken=data.identityToken;anonymousAlias=data.anonymousAlias;nameInput.value=anonymousAlias;requestButton.disabled=false;status.textContent='';}catch{status.className='error';status.textContent='This invitation is not valid or is no longer available.'}}
document.querySelector('#request').onclick=async()=>{status.textContent='Requesting access...';try{
@@ -204,7 +204,7 @@ location.replace(data.browserUrl);
prepareIdentity();
`;
- return shell('Join CodeXR', body, script);
+ return shell('Join Code-XR', body, script);
}
/**
@@ -218,7 +218,7 @@ export function renderInvitationErrorPage(title: string, message: string): strin
Invitation links are temporary by design
`;
- return shell('CodeXR · invitation unavailable', body);
+ return shell('Code-XR · invitation unavailable', body);
}
function escapeHtml(value: string): string {
diff --git a/src/servers/runtime/remote/remoteAccessPolicy.ts b/apps/vscode-extension/src/core/server/remote/remoteAccessPolicy.ts
similarity index 94%
rename from src/servers/runtime/remote/remoteAccessPolicy.ts
rename to apps/vscode-extension/src/core/server/remote/remoteAccessPolicy.ts
index 0006b709d..8f07fbc28 100644
--- a/src/servers/runtime/remote/remoteAccessPolicy.ts
+++ b/apps/vscode-extension/src/core/server/remote/remoteAccessPolicy.ts
@@ -1,5 +1,5 @@
import * as http from 'http';
-import { RemoteSessionAuthority } from '../../../remote_access';
+import { RemoteSessionAuthority } from '../../remote-access/remoteSessionAuthority';
/**
* The only paths a remote guest may reach without a session cookie: the
diff --git a/src/servers/runtime/remote/remotePairingApi.ts b/apps/vscode-extension/src/core/server/remote/remotePairingApi.ts
similarity index 98%
rename from src/servers/runtime/remote/remotePairingApi.ts
rename to apps/vscode-extension/src/core/server/remote/remotePairingApi.ts
index e93e445e0..d11a1a0a9 100644
--- a/src/servers/runtime/remote/remotePairingApi.ts
+++ b/apps/vscode-extension/src/core/server/remote/remotePairingApi.ts
@@ -1,7 +1,7 @@
import * as http from 'http';
import * as crypto from 'crypto';
-import { CollaborationProfile, DEFAULT_COLLABORATION_PROFILE } from '../../../collaboration';
-import { RemoteSessionAuthority } from '../../../remote_access';
+import { CollaborationProfile, DEFAULT_COLLABORATION_PROFILE } from '../../collaboration/collaborationProfile';
+import { RemoteSessionAuthority } from '../../remote-access/remoteSessionAuthority';
import { CollaborationRoomServer } from '../collaboration/collaborationRoomServer';
import { renderInvitationErrorPage, renderPairingPage } from './pairingPage';
import {
diff --git a/apps/vscode-extension/src/core/server/serverControl.ts b/apps/vscode-extension/src/core/server/serverControl.ts
new file mode 100644
index 000000000..0818b2bad
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/serverControl.ts
@@ -0,0 +1,269 @@
+import { ActiveServer, ActiveServerRuntime } from './registry/activeServerModel';
+import type { UnifiedAnalysisSession } from '../analysis/session/analysisSession';
+import { getActiveServerRegistry } from './registry/activeServerRegistry';
+import { closeServerPanels } from './serverPanels';
+import { fileToServerMap } from './fileToServerMap';
+import { sseManager } from './sse/SSEManager';
+import { UnifiedSessionRegistry } from '../analysis/session/sessionRegistry';
+import { getLogger } from '../../platform/logging/sink';
+import { getHost } from '../host/hostRegistry';
+import type { CoreContext } from '../host/hostPaths';
+
+const logger = getLogger('ACTIVE_SERVERS');
+
+/** A server that failed to stop: logged, and shown to the person (what `handleError(..., User)` did before #13 step 7). */
+function reportStopFailure(url: string, error: unknown): void {
+ const prefix = `ACTIVE_SERVERS: Failed to stop server ${url}`;
+ logger.error(prefix, error);
+ void getHost().notifier.notify('error', `${prefix}: ${error instanceof Error ? error.message : String(error)}`);
+}
+
+/** How long a graceful shutdown may take before it is forced. */
+const STOP_TIMEOUT_MS = 4000;
+
+/**
+ * Server Control
+ * Runtime operations for managing active servers
+ */
+/** What a bulk stop did: how many running servers it tried, and how many stopped cleanly. */
+export interface StopAllServersResult {
+ requested: number;
+ stopped: number;
+}
+
+export class ServerControl {
+ private static extensionContext: CoreContext;
+
+ /**
+ * Initialize with extension context
+ */
+ public static initialize(context: CoreContext): void {
+ ServerControl.extensionContext = context;
+ }
+
+ /**
+ * Stop an active server
+ */
+ public static async stopServer(serverId: string, options: { silent?: boolean } = {}): Promise {
+ logger.debug(() => `DEBUG - Attempting to stop server ${serverId}`);
+
+ const registry = getActiveServerRegistry();
+ const server = registry.getServer(serverId);
+
+ if (!server) {
+ logger.error(`Server ${serverId} not found in registry`);
+ void getHost().notifier.notify('error', `Server not found: ${serverId}`);
+ return false;
+ }
+
+ logger.debug(`DEBUG - Server found:`, {
+ id: server.id,
+ port: server.port,
+ url: server.url,
+ status: server.status,
+ launchMode: server.launchMode,
+ customName: server.customName,
+ htmlFile: server.htmlFile,
+ metadata: server.metadata
+ });
+
+ try {
+ // Close associated lateral panel if it exists
+ if (server.launchMode === 'lateralPanel' && closeServerPanels([serverId]) > 0) {
+ logger.debug(() => `ACTIVE_SERVER_PANEL: Closed lateral panel for server ${serverId}`);
+ }
+
+ // Check if this server is associated with an analysis file and clean up
+ logger.debug(() => `DEBUG - Checking for file-to-server mapping for server on port ${server.port}`);
+ const fileUri = fileToServerMap.findFileByPort(server.port);
+ if (fileUri) {
+ logger.debug(() => `Found associated analysis file: ${fileUri}`);
+
+ // Clean up SSE clients for this file
+ logger.debug(() => `DEBUG - Cleaning up SSE clients for ${fileUri}`);
+ sseManager.removeAllClients(fileUri);
+
+ // Remove the file-to-server mapping
+ logger.debug(() => `DEBUG - Removing file-to-server mapping for ${fileUri}`);
+ fileToServerMap.unregisterMapping(fileUri);
+ } else {
+ logger.debug(() => `No associated analysis file found for server on port ${server.port}`);
+ }
+
+ // Close associated analysis session if it exists
+ logger.debug(`DEBUG - Attempting to close associated analysis session`);
+ await this.closeAssociatedAnalysisSession(serverId, server);
+
+ // Update status to indicate stopping
+ logger.debug(`DEBUG - Updating server status to 'stopped'`);
+ registry.updateServerStatus(serverId, 'stopped');
+
+ // Stop the actual server instance if available
+ let cleanShutdown = true;
+ if (server.serverInstance && typeof server.serverInstance.stop === 'function') {
+ logger.debug(() => `DEBUG - Stopping server instance for ${serverId}`);
+ cleanShutdown = await this.stopInstanceOrForce(serverId, server.serverInstance);
+ } else {
+ logger.debug(() => `No server instance or stop method for ${serverId}`);
+ }
+
+ logger.debug(() => `Stopped server ${serverId} (${server.url}), clean: ${cleanShutdown}`);
+ if (cleanShutdown && !options.silent) {
+ void getHost().notifier.notify('info', `Server stopped: ${server.url}`);
+ }
+
+ return cleanShutdown;
+
+ } catch (error) {
+ reportStopFailure(server.url, error);
+ return false;
+ } finally {
+ // The row always leaves the list: a runtime that refuses to shut
+ // down must never leave a zombie entry behind.
+ logger.debug(`DEBUG - Removing server from registry`);
+ registry.unregisterServer(serverId);
+ }
+ }
+
+ /**
+ * Await the instance's graceful stop, falling back to a forced socket close
+ * if it hangs or fails. Returns false when the shutdown was not clean.
+ */
+ private static async stopInstanceOrForce(serverId: string, instance: ActiveServerRuntime): Promise {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ await Promise.race([
+ Promise.resolve(instance.stop()),
+ new Promise((_resolve, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`Shutdown timed out after ${STOP_TIMEOUT_MS} ms`)),
+ STOP_TIMEOUT_MS,
+ );
+ }),
+ ]);
+ logger.debug(() => `Server instance stopped for ${serverId}`);
+ return true;
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ logger.error(`Graceful stop failed for ${serverId}: ${reason}`);
+ if (typeof instance.forceStop === 'function') {
+ try {
+ instance.forceStop();
+ logger.debug(() => `Forced shutdown for ${serverId}`);
+ } catch (forceError) {
+ logger.error(`Forced shutdown failed for ${serverId}:`, forceError);
+ }
+ }
+ void getHost().notifier.notify('warning',
+ `Server removed from the list, but its runtime did not shut down cleanly: ${reason}`,
+ );
+ return false;
+ } finally {
+ if (timer) {
+ clearTimeout(timer);
+ }
+ }
+ }
+
+ /**
+ * Stop every running server. Shows no message of its own: the caller
+ * reports one summary from the returned counts. (It used to return a bare
+ * count that its caller read as a yes/no, and both layers toasted, so a
+ * partial failure showed "Stopped 2/3" followed by "Stopped all 3".)
+ */
+ public static async stopAllServers(): Promise {
+ logger.debug('Stopping all active servers');
+
+ const registry = getActiveServerRegistry();
+ const runningServers = registry.getServersByStatus('running');
+
+ if (runningServers.length === 0) {
+ logger.debug('No running servers to stop');
+ return { requested: 0, stopped: 0 };
+ }
+
+ // First, close all lateral panels for servers that have them
+ const lateralPanelServers = runningServers.filter(server => server.launchMode === 'lateralPanel');
+
+ if (lateralPanelServers.length > 0) {
+ logger.debug(() => `ACTIVE_SERVER_PANEL: Closing ${lateralPanelServers.length} lateral panels before stopping servers`);
+ const serverIdsWithPanels = lateralPanelServers.map(server => server.id);
+ const closedPanelCount = closeServerPanels(serverIdsWithPanels);
+ logger.debug(() => `ACTIVE_SERVER_PANEL: Closed ${closedPanelCount}/${lateralPanelServers.length} lateral panels`);
+ }
+
+ const results = await Promise.all(
+ runningServers.map(server => this.stopServer(server.id, { silent: true })),
+ );
+ const stopped = results.filter(Boolean).length;
+
+ logger.debug(() => `Stopped ${stopped}/${runningServers.length} servers`);
+ return { requested: runningServers.length, stopped };
+ }
+
+ /**
+ * Close analysis session associated with a server
+ */
+ private static async closeAssociatedAnalysisSession(serverId: string, server: ActiveServer): Promise {
+ try {
+ logger.debug(() => `DEBUG - Looking for analysis session associated with server ${serverId}`);
+ logger.debug(`DEBUG - Server details:`, {
+ id: serverId,
+ port: server.port,
+ htmlFile: server.htmlFile,
+ metadata: server.metadata
+ });
+
+ const sessionRegistry = UnifiedSessionRegistry.getInstance(ServerControl.extensionContext);
+ const allSessions = sessionRegistry.getAllSessions();
+
+ logger.debug(() => `DEBUG - Found ${allSessions.length} active analysis sessions`);
+ allSessions.forEach((session: UnifiedAnalysisSession, index: number) => {
+ logger.debug(() => `DEBUG - Session ${index + 1}:`, {
+ id: session.id,
+ targetPath: session.targetPath,
+ outputPath: session.outputPath,
+ status: session.status
+ });
+ });
+
+ // Find session that matches this server
+ let associatedSession = null;
+
+ // Try to find by sessionId in server metadata (when implemented)
+ if (server.metadata?.sessionId) {
+ const sessionId = server.metadata.sessionId;
+ logger.debug(() => `DEBUG - Trying to find session by metadata sessionId: ${sessionId}`);
+ associatedSession = sessionRegistry.getSession(sessionId);
+ if (associatedSession) {
+ logger.debug(() => `Found session by metadata sessionId: ${sessionId}`);
+ } else {
+ logger.debug(() => `No session found with sessionId: ${sessionId}`);
+ }
+ }
+
+ // 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}`);
+
+ const success = sessionRegistry.closeSession(associatedSession.id);
+
+ if (success) {
+ logger.debug(() => `Successfully closed associated analysis session ${associatedSession.id}`);
+ } else {
+ logger.warn(`Failed to close associated analysis session ${associatedSession.id}`);
+ }
+ } else {
+ logger.debug(() => `No associated analysis session found for server ${serverId}`);
+ }
+
+ } catch (error) {
+ logger.warn(`ACTIVE_SERVERS: Closing associated analysis session for server ${serverId}`, error);
+ }
+ }
+}
+
diff --git a/apps/vscode-extension/src/core/server/serverFactory.ts b/apps/vscode-extension/src/core/server/serverFactory.ts
new file mode 100644
index 000000000..75ae1b498
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/serverFactory.ts
@@ -0,0 +1,239 @@
+import * as path from 'path';
+import { HttpServer } from './httpServer';
+import { HttpsDefaultServer } from './httpsDefaultServer';
+import { HttpsCustomServer } from './httpsCustomServer';
+import type { ServerSettings } from './serverSettingsManager';
+import type { LaunchMode, CertMode } from './registry/activeServerModel';
+import { getLogger } from '../../platform/logging/sink';
+import { resolveTemplatePath } from '../../platform/templatePaths';
+import type { CoreContext } from '../host/hostPaths';
+
+const logger = getLogger('SERVER');
+
+/*
+ * The server factory behind MultiServerLauncher: which server class a set of
+ * settings asks for, and building and starting it. With no scene file the
+ * static root is the extension's templates folder (resolveTemplatePath).
+ */
+
+/**
+ * Server types supported by the launcher
+ */
+export type ServerType = 'http' | 'https-default' | 'https-custom';
+
+/**
+ * Server instance type for the running server
+ */
+export type ServerInstance = HttpServer | HttpsDefaultServer | HttpsCustomServer;
+
+/** What launchServerByType reports back to the launcher. */
+export interface ServerFactoryResult {
+ success: boolean;
+ serverUrl?: string;
+ serverType?: ServerType;
+ port?: number;
+ error?: string;
+ httpsOverridden?: boolean;
+ serverInstance?: ServerInstance;
+}
+
+/**
+ * Determine server type based on settings
+ */
+export function determineServerType(settings: ServerSettings): ServerType {
+ if (settings.mode === 'HTTP') {
+ return 'http';
+ } else if (settings.mode === 'HTTPS') {
+ return settings.https.certSource === 'default' ? 'https-default' : 'https-custom';
+ }
+
+ throw new Error(`Invalid server mode: ${settings.mode}`);
+}
+
+/**
+ * Check for lateral panel + HTTPS conflict and provide fallback. The
+ * launcher tells the user (warnHttpsOverriddenForPanel) when it is overridden.
+ * @param settings - Server settings
+ * @returns Modified server type if fallback needed, original type otherwise
+ */
+export function resolveServerTypeForOpenMode(settings: ServerSettings): {
+ serverType: ServerType;
+ isOverridden: boolean;
+} {
+ const originalServerType = determineServerType(settings);
+
+ // Check if we have lateral panel + HTTPS combination
+ const isLateralPanel = settings.launch.openMode === 'lateralPanel';
+ const isHttps = originalServerType === 'https-default' || originalServerType === 'https-custom';
+
+ if (isLateralPanel && isHttps) {
+ logger.debug('HTTPS + Lateral Panel conflict detected - overriding to HTTP for compatibility');
+ logger.debug(() => `Original server type would have been: ${originalServerType}`);
+ logger.debug('VS Code webview panels do not support HTTPS content, using HTTP fallback');
+
+ return {
+ serverType: 'http',
+ isOverridden: true
+ };
+ }
+
+ return {
+ serverType: originalServerType,
+ isOverridden: false
+ };
+}
+
+/**
+ * Determine launch mode based on settings
+ */
+export function determineLaunchMode(settings: ServerSettings): LaunchMode {
+ return settings.launch.openMode === 'lateralPanel' ? 'lateralPanel' as LaunchMode : 'browser' as LaunchMode;
+}
+
+/**
+ * Determine certificate mode based on server type and overrides
+ */
+export function determineCertMode(serverType: ServerType, httpsOverridden?: boolean): CertMode {
+ if (httpsOverridden) {
+ return 'http';
+ }
+
+ switch (serverType) {
+ case 'http':
+ return 'http';
+ case 'https-default':
+ return 'https-default';
+ case 'https-custom':
+ return 'https-custom';
+ default:
+ return 'http';
+ }
+}
+
+/**
+ * Launch server by type - delegates to existing server implementations
+ */
+export async function launchServerByType(
+ context: CoreContext,
+ serverType: ServerType,
+ settings: ServerSettings,
+ port: number,
+ host: string,
+ 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;
+
+ // Default server configuration
+ const staticRoot = htmlFile ? path.dirname(htmlFile) : resolveTemplatePath(context.extensionPath);
+ const mainFile = htmlFile ? path.basename(htmlFile) : undefined;
+ const enableCors = true;
+ const allowedOrigins = ['*'];
+
+ logger.debug(() => `Using static root: ${staticRoot}`);
+ if (mainFile) {
+ logger.debug(() => `Main file configured: ${mainFile}`);
+ }
+
+ switch (serverType) {
+ case 'http':
+ logger.debug('Creating HTTP server...');
+ server = new HttpServer({
+ port,
+ host,
+ staticRoot,
+ enableCors,
+ allowedOrigins,
+ mainFile,
+ extensionContext: context,
+ analysisSessionId: typeof additionalMetadata?.sessionId === 'string'
+ ? additionalMetadata.sessionId
+ : undefined,
+ });
+ break;
+
+ case 'https-default':
+ logger.debug('Creating HTTPS server with generated local certificates...');
+ server = new HttpsDefaultServer({
+ port,
+ host,
+ staticRoot,
+ enableCors,
+ allowedOrigins,
+ mainFile,
+ extensionContext: context,
+ analysisSessionId: typeof additionalMetadata?.sessionId === 'string'
+ ? additionalMetadata.sessionId
+ : undefined,
+ });
+ break;
+
+ case 'https-custom':
+ logger.debug('Creating HTTPS server with custom certificates...');
+ if (!settings.https?.certPath || !settings.https.keyPath) {
+ throw new Error('Custom certificate paths are required for custom HTTPS server');
+ }
+ server = new HttpsCustomServer({
+ port,
+ host,
+ staticRoot,
+ enableCors,
+ allowedOrigins,
+ mainFile,
+ certPath: settings.https.certPath,
+ keyPath: settings.https.keyPath,
+ extensionContext: context,
+ analysisSessionId: typeof additionalMetadata?.sessionId === 'string'
+ ? additionalMetadata.sessionId
+ : undefined,
+ });
+ break;
+
+ default:
+ throw new Error(`Unsupported server type: ${serverType}`);
+ }
+
+ // Start the server
+ created = server;
+ logger.debug(() => `Starting ${serverType} server...`);
+ serverUrl = await server.start();
+
+ return {
+ success: true,
+ serverUrl,
+ serverType,
+ // Report the port the listener is bound to, which is what every
+ // URL, tree entry and session must use.
+ port: server.getListeningPort?.() ?? port,
+ serverInstance: server
+ };
+
+ } catch (error) {
+ logger.error(`Error launching ${serverType} server:`, error);
+ releaseFailedServer(created);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ serverType
+ };
+ }
+}
+
+/** 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/core/server/serverPanels.ts b/apps/vscode-extension/src/core/server/serverPanels.ts
new file mode 100644
index 000000000..a2f82de29
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/serverPanels.ts
@@ -0,0 +1,26 @@
+/**
+ * Closing the editor panels that show a server, as seen from the core (#13, step 7).
+ *
+ * `ServerControl` closes a lateral panel when its server stops. The panels
+ * themselves are editor UI (the extension: `platform/webview/panelManager.ts`),
+ * so the core only knows this callback, which the application registers at
+ * start-up from `extension.ts`. A host with no panels (the IDE for now, the
+ * unit tests) registers nothing, and closing is then a no-op: there is no
+ * panel to leave behind.
+ */
+export interface ServerPanelCloser {
+ /** Closes the panels of these servers; returns how many were closed. */
+ closeServerPanels(serverIds: readonly string[]): number;
+}
+
+let current: ServerPanelCloser | null = null;
+
+/** Registers the panel closer. Called once at start-up; a later call replaces it (tests). */
+export function setServerPanelCloser(closer: ServerPanelCloser | null): void {
+ current = closer;
+}
+
+/** Closes the panels of these servers through the registered closer; 0 when none is registered. */
+export function closeServerPanels(serverIds: readonly string[]): number {
+ return current ? current.closeServerPanels(serverIds) : 0;
+}
diff --git a/src/servers/storage/serverSettingsManager.ts b/apps/vscode-extension/src/core/server/serverSettingsManager.ts
similarity index 94%
rename from src/servers/storage/serverSettingsManager.ts
rename to apps/vscode-extension/src/core/server/serverSettingsManager.ts
index dcb363e8b..04efc9396 100644
--- a/src/servers/storage/serverSettingsManager.ts
+++ b/apps/vscode-extension/src/core/server/serverSettingsManager.ts
@@ -1,14 +1,15 @@
-import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
-import { generateNonce } from '../../utils/nonceGenerator';
-import { CodeXRLogger } from '../../core/logging/logger';
+import { generateNonce } from '../../shared/nonceGenerator';
+import { getLogger } from '../../platform/logging/sink';
import {
DEFAULT_REMOTE_ACCESS_SETTINGS,
RemoteAccessSettings,
-} from '../../remote_access';
+} from '../remote-access/remoteAccessModel';
+import { getHost } from '../host/hostRegistry';
+import type { CoreContext } from '../host/hostPaths';
-const logger = CodeXRLogger.getLogger('SERVER_SETTINGS');
+const logger = getLogger('SERVER_SETTINGS');
/**
* Structured server configuration interface
@@ -57,13 +58,13 @@ export const DEFAULT_SERVER_SETTINGS: ServerSettings = {
export class ServerSettingsManager {
private static instance: ServerSettingsManager;
private settings: ServerSettings;
- private context: vscode.ExtensionContext;
+ private context: CoreContext;
private readonly SETTINGS_FILENAME = 'server-settings.json';
private settingsFilePath: string;
private initializationPromise: Promise | null = null;
private initialized = false;
- private constructor(context: vscode.ExtensionContext) {
+ private constructor(context: CoreContext) {
this.context = context;
this.settings = { ...DEFAULT_SERVER_SETTINGS, configNonce: generateNonce() };
this.settingsFilePath = path.join(context.globalStorageUri.fsPath, this.SETTINGS_FILENAME);
@@ -83,7 +84,7 @@ export class ServerSettingsManager {
/**
* Get singleton instance.
*/
- public static getInstance(context?: vscode.ExtensionContext): ServerSettingsManager {
+ public static getInstance(context?: CoreContext): ServerSettingsManager {
if (!ServerSettingsManager.instance) {
if (!context) {
throw new Error('SERVER: Context required for first initialization');
@@ -125,7 +126,7 @@ export class ServerSettingsManager {
/**
* Get extension context.
*/
- public getExtensionContext(): vscode.ExtensionContext {
+ public getExtensionContext(): CoreContext {
return this.context;
}
@@ -137,7 +138,7 @@ export class ServerSettingsManager {
this.settings = this.withRuntimeNonce(this.deepMerge(this.settings, updates));
await this.persistSettings();
- void vscode.commands.executeCommand('codexr.servers.refresh');
+ getHost().signal({ kind: 'refresh', view: 'servers' });
}
/**
@@ -190,7 +191,7 @@ export class ServerSettingsManager {
await this.ensureInitialized();
this.settings = this.withRuntimeNonce({ ...DEFAULT_SERVER_SETTINGS });
await this.persistSettings();
- void vscode.commands.executeCommand('codexr.servers.refresh');
+ getHost().signal({ kind: 'refresh', view: 'servers' });
}
/**
diff --git a/apps/vscode-extension/src/core/server/sse/SSEManager.ts b/apps/vscode-extension/src/core/server/sse/SSEManager.ts
new file mode 100644
index 000000000..5bf656f2c
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/sse/SSEManager.ts
@@ -0,0 +1,276 @@
+import * as fs from 'fs';
+import * as path from 'path';
+import * as http from 'http';
+import { SSEClientRegistry } from './sseClientRegistry';
+import { fileToServerMap } from '../fileToServerMap';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('SSE_MANAGER');
+
+/**
+ * SSE Manager
+ * Central module for managing Server-Sent Events for analysis updates
+ */
+export class SSEManager {
+ private static instance: SSEManager | null = null;
+ private clientRegistry: SSEClientRegistry;
+
+ private constructor() {
+ logger.debug('[SSE_MANAGER] Initializing SSE manager');
+ this.clientRegistry = SSEClientRegistry.getInstance();
+ }
+
+ /**
+ * Get the singleton instance
+ */
+ static getInstance(): SSEManager {
+ if (!SSEManager.instance) {
+ SSEManager.instance = new SSEManager();
+ }
+ return SSEManager.instance;
+ }
+
+ /**
+ * Register a new SSE client for a specific analysis file
+ * Sets up the SSE connection with proper headers and keep-alive
+ *
+ * @param fileUri - URI of the analyzed file
+ * @param res - HTTP response object
+ */
+ registerClient(fileUri: string, res: http.ServerResponse): void {
+ logger.debug(() => `[SSE_MANAGER] Setting up SSE connection for: ${fileUri}`);
+
+ // Set SSE headers
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Headers': 'Cache-Control',
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
+ });
+
+ // Send initial connection message
+ res.write(`data: ${JSON.stringify({
+ type: 'connected',
+ fileUri: fileUri,
+ timestamp: new Date().toISOString(),
+ message: 'SSE connection established for analysis updates'
+ })}\n\n`);
+
+ // Register the client
+ this.clientRegistry.registerClient(fileUri, res);
+
+ logger.debug(() => `[SSE_MANAGER] SSE client registered for: ${fileUri}`);
+ }
+
+ /**
+ * Unregister an SSE client
+ *
+ * @param fileUri - URI of the analyzed file
+ * @param res - HTTP response object
+ */
+ unregisterClient(fileUri: string, res: http.ServerResponse): void {
+ logger.debug(() => `[SSE_MANAGER] Unregistering SSE client for: ${fileUri}`);
+ this.clientRegistry.unregisterClient(fileUri, res);
+ }
+
+ /**
+ * Send an update notification to all clients of a specific analysis file
+ * This is called when the data.json file is regenerated
+ *
+ * @param fileUri - URI of the analyzed file that was updated
+ */
+ sendUpdate(fileUri: string): void {
+ logger.debug(() => `REQUEST_UPDATE: Server received update request for file: ${fileUri}`);
+ logger.debug(() => `[SSE_MANAGER] Sending analysis update for: ${fileUri}`);
+
+ // Debug: Check file-to-server mapping
+ const mapping = fileToServerMap.getServerInfo(fileUri);
+ if (mapping) {
+ logger.debug(() => `REQUEST_UPDATE: Found mapping - Port: ${mapping.port}, TempDir: ${mapping.tempDir}`);
+
+ // Verify data.json exists in the temp directory
+ const dataJsonPath = path.join(mapping.tempDir, 'data.json');
+ try {
+ const exists = fs.existsSync(dataJsonPath);
+ logger.debug(() => `REQUEST_UPDATE: data.json exists at ${dataJsonPath}: ${exists}`);
+ if (exists) {
+ const stats = fs.statSync(dataJsonPath);
+ logger.debug(() => `REQUEST_UPDATE: data.json size: ${stats.size} bytes, modified: ${stats.mtime}`);
+ }
+ } catch (fileError) {
+ logger.error(`REQUEST_UPDATE: Error checking data.json:`, fileError);
+ }
+ } else {
+ logger.debug(() => `REQUEST_UPDATE: No mapping found for file: ${fileUri}`);
+ }
+
+ const updateMessage = JSON.stringify({
+ type: 'analysis-updated',
+ fileUri: fileUri,
+ timestamp: new Date().toISOString(),
+ message: 'Analysis data has been updated, please refresh',
+ action: 'reload-data'
+ });
+
+ this.clientRegistry.sendToClients(fileUri, updateMessage);
+
+ logger.debug(() => `[SSE_MANAGER] Update notification sent for: ${fileUri}`);
+ logger.debug(() => `REQUEST_UPDATE: Update message dispatched to clients for: ${fileUri}`);
+ }
+
+ /**
+ * Send a dataRefresh event specifically for XR visualizations
+ * This triggers the dataRefresh event listener in live_sse_fileXR.js
+ *
+ * @param fileUri - URI of the analyzed file that was updated
+ */
+ sendDataRefresh(fileUri: string): void {
+ logger.debug(() => `[SSE_MANAGER] Sending dataRefresh event for XR visualization: ${fileUri}`);
+
+ // Create the dataRefresh event data
+ const refreshData = JSON.stringify({
+ type: 'dataRefresh',
+ fileUri: fileUri,
+ timestamp: new Date().toISOString(),
+ message: 'XR data has been refreshed, updating visualization',
+ action: 'xr-data-refresh'
+ });
+
+ // Send as a specific SSE event
+ this.clientRegistry.sendEventToClients(fileUri, 'dataRefresh', refreshData);
+
+ logger.debug(() => `[SSE_MANAGER] dataRefresh event sent for XR visualization: ${fileUri}`);
+ }
+
+ /**
+ * Send a custom message to all clients of a specific analysis file
+ *
+ * @param fileUri - URI of the analyzed file
+ * @param message - Custom message object
+ */
+ sendCustomMessage(fileUri: string, message: object): void {
+ logger.debug(() => `[SSE_MANAGER] Sending custom message for: ${fileUri}`);
+ logger.debug(() => `[SSE_MANAGER] Message type: ${(message as any).type || 'unknown'}`);
+
+ const customMessage = JSON.stringify({
+ ...message,
+ timestamp: new Date().toISOString()
+ });
+
+ logger.debug(() => `[SSE_MANAGER] Full message content: ${customMessage}`);
+ logger.debug(() => `[SSE_MANAGER] Message size: ${customMessage.length} characters`);
+
+ // Check if we have clients for this fileUri
+ const clientCount = this.clientRegistry.getClients(fileUri).length;
+ logger.debug(() => `[SSE_MANAGER] Number of clients for ${fileUri}: ${clientCount}`);
+
+ this.clientRegistry.sendToClients(fileUri, customMessage);
+ logger.debug(() => `[SSE_MANAGER] Message sent to ${clientCount} clients of: ${fileUri}`);
+ }
+
+ /**
+ * Send a specific SSE event to all clients of a specific analysis file
+ *
+ * @param fileUri - URI of the analyzed file
+ * @param eventType - Type of SSE event (e.g., 'analysisUpdated')
+ * @param message - Message object or string
+ */
+ sendEventMessage(fileUri: string, eventType: string, message: object | string): void {
+ logger.debug(() => `[SSE_MANAGER] Sending SSE event '${eventType}' for: ${fileUri}`);
+
+ let eventMessage: string;
+ if (typeof message === 'string') {
+ eventMessage = message;
+ } else {
+ eventMessage = JSON.stringify({
+ ...message,
+ timestamp: new Date().toISOString()
+ });
+ }
+
+ this.clientRegistry.sendEventToClients(fileUri, eventType, eventMessage);
+ }
+
+ /**
+ * Send a heartbeat/keep-alive message to all clients of a specific file
+ *
+ * @param fileUri - URI of the analyzed file
+ */
+ sendHeartbeat(fileUri: string): void {
+ const heartbeatMessage = JSON.stringify({
+ type: 'heartbeat',
+ timestamp: new Date().toISOString()
+ });
+
+ this.clientRegistry.sendToClients(fileUri, heartbeatMessage);
+ }
+
+ /**
+ * Send heartbeat to all active files
+ * Useful for maintaining connections
+ */
+ sendHeartbeatToAll(): void {
+ const activeFiles = this.clientRegistry.getActiveFiles();
+
+ if (activeFiles.length > 0) {
+ logger.debug(() => `[SSE_MANAGER] Sending heartbeat to ${activeFiles.length} active file(s)`);
+
+ for (const fileUri of activeFiles) {
+ this.sendHeartbeat(fileUri);
+ }
+ }
+ }
+
+ /**
+ * Get the number of active clients for a specific file
+ *
+ * @param fileUri - URI of the analyzed file
+ * @returns Number of active clients
+ */
+ getClientCount(fileUri: string): number {
+ return this.clientRegistry.getClients(fileUri).length;
+ }
+
+ /**
+ * Get all file URIs that have active SSE clients
+ *
+ * @returns Array of file URIs with active clients
+ */
+ getActiveFiles(): string[] {
+ return this.clientRegistry.getActiveFiles();
+ }
+
+ /**
+ * Remove all clients for a specific file
+ * Useful when an analysis is stopped or file is deleted
+ *
+ * @param fileUri - URI of the analyzed file
+ */
+ removeAllClients(fileUri: string): void {
+ logger.debug(() => `[SSE_MANAGER] Removing all SSE clients for: ${fileUri}`);
+ this.clientRegistry.removeAllClients(fileUri);
+ }
+
+ /**
+ * Get statistics about active SSE connections
+ *
+ * @returns Statistics object
+ */
+ getStats(): { fileCount: number; totalClients: number; clientsPerFile: { [fileUri: string]: number } } {
+ return this.clientRegistry.getStats();
+ }
+
+ /**
+ * Clean up all SSE connections
+ * Should be called during extension deactivation
+ */
+ dispose(): void {
+ logger.debug('[SSE_MANAGER] Disposing SSE manager');
+ this.clientRegistry.clearAll();
+ }
+}
+
+// Export singleton instance for easy access
+export const sseManager = SSEManager.getInstance();
diff --git a/apps/vscode-extension/src/core/server/sse/sseClientRegistry.ts b/apps/vscode-extension/src/core/server/sse/sseClientRegistry.ts
new file mode 100644
index 000000000..f2c3ed6fe
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/sse/sseClientRegistry.ts
@@ -0,0 +1,274 @@
+import * as http from 'http';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('SSE_CLIENT_REGISTRY');
+
+/**
+ * SSE Client Registry
+ * Maintains active Server-Sent Events connections for analysis updates
+ */
+export class SSEClientRegistry {
+ private static instance: SSEClientRegistry | null = null;
+ private clients: Map = new Map();
+
+ private constructor() {
+ logger.debug('[SSE_CLIENT_REGISTRY] Initializing SSE client registry');
+ }
+
+ /**
+ * Get the singleton instance
+ */
+ static getInstance(): SSEClientRegistry {
+ if (!SSEClientRegistry.instance) {
+ SSEClientRegistry.instance = new SSEClientRegistry();
+ }
+ return SSEClientRegistry.instance;
+ }
+
+ /**
+ * Register a new SSE client for a specific file
+ * @param fileUri - URI of the analyzed file
+ * @param res - HTTP response object for SSE
+ */
+ registerClient(fileUri: string, res: http.ServerResponse): void {
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Registering SSE client for: ${fileUri}`);
+
+ if (!this.clients.has(fileUri)) {
+ this.clients.set(fileUri, []);
+ }
+
+ const clientList = this.clients.get(fileUri)!;
+ clientList.push(res);
+
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Client registered. Total clients for ${fileUri}: ${clientList.length}`);
+
+ // Set up cleanup when client disconnects
+ res.on('close', () => {
+ this.unregisterClient(fileUri, res);
+ });
+
+ res.on('error', (error) => {
+ logger.error(`[SSE_CLIENT_REGISTRY] Client error for ${fileUri}:`, error);
+ this.unregisterClient(fileUri, res);
+ });
+ }
+
+ /**
+ * Unregister an SSE client
+ * @param fileUri - URI of the analyzed file
+ * @param res - HTTP response object for SSE
+ */
+ unregisterClient(fileUri: string, res: http.ServerResponse): void {
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Unregistering SSE client for: ${fileUri}`);
+
+ const clientList = this.clients.get(fileUri);
+ if (!clientList) {
+ return;
+ }
+
+ const index = clientList.indexOf(res);
+ if (index > -1) {
+ clientList.splice(index, 1);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Client unregistered. Remaining clients for ${fileUri}: ${clientList.length}`);
+
+ // Clean up empty arrays
+ if (clientList.length === 0) {
+ this.clients.delete(fileUri);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Removed empty client list for: ${fileUri}`);
+ }
+ }
+ }
+
+ /**
+ * Get all active clients for a file
+ * @param fileUri - URI of the analyzed file
+ * @returns Array of response objects
+ */
+ getClients(fileUri: string): http.ServerResponse[] {
+ return this.clients.get(fileUri) ?? [];
+ }
+
+ /**
+ * Send a message to all clients for a specific file
+ * @param fileUri - URI of the analyzed file
+ * @param message - Message to send
+ */
+ sendToClients(fileUri: string, message: string): void {
+ const clientList = this.clients.get(fileUri);
+ logger.debug(() => `REQUEST_UPDATE: SSE Registry lookup for file: ${fileUri}`);
+ logger.debug(() => `REQUEST_UPDATE: Found ${clientList ? clientList.length : 0} client(s) for file: ${fileUri}`);
+
+ if (!clientList || clientList.length === 0) {
+ logger.debug(() => `REQUEST_UPDATE: No SSE clients registered for: ${fileUri}`);
+ logger.debug(() => `REQUEST_UPDATE: Available files in registry: ${Array.from(this.clients.keys()).join(', ')}`);
+ return;
+ }
+
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Sending message to ${clientList.length} client(s) for: ${fileUri}`);
+ logger.debug(() => `REQUEST_UPDATE: About to send message to ${clientList.length} client(s)`);
+
+ // Send to all active clients, removing any that error out
+ const activeClients = [];
+ for (const client of clientList) {
+ try {
+ if (!client.headersSent) {
+ // Headers not sent yet, this shouldn't happen in SSE
+ logger.warn(`[SSE_CLIENT_REGISTRY] Skipping client with unsent headers for: ${fileUri}`);
+ continue;
+ }
+
+ client.write(`data: ${message}\n\n`);
+ activeClients.push(client);
+ logger.debug(`REQUEST_UPDATE: Message sent to client successfully`);
+ } catch (error) {
+ logger.error(`[SSE_CLIENT_REGISTRY] Error sending to client for ${fileUri}:`, error);
+ logger.error(`REQUEST_UPDATE: Failed to send to client: ${error}`);
+ // Client will be removed via error event handler
+ }
+ }
+
+ // Update the client list to only include active clients
+ if (activeClients.length !== clientList.length) {
+ if (activeClients.length === 0) {
+ this.clients.delete(fileUri);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] All clients disconnected for: ${fileUri}`);
+ } else {
+ this.clients.set(fileUri, activeClients);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Updated active clients for ${fileUri}: ${activeClients.length}`);
+ }
+ }
+ }
+
+ /**
+ * Send a specific SSE event to all clients for a specific file
+ * @param fileUri - URI of the analyzed file
+ * @param eventType - Type of SSE event (e.g., 'analysisUpdated')
+ * @param data - Data to send with the event
+ */
+ sendEventToClients(fileUri: string, eventType: string, data: string): void {
+ const clientList = this.clients.get(fileUri);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Sending SSE event '${eventType}' to clients for: ${fileUri}`);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Found ${clientList ? clientList.length : 0} client(s) for file: ${fileUri}`);
+
+ if (!clientList || clientList.length === 0) {
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] No SSE clients registered for: ${fileUri}`);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Available files in registry: ${Array.from(this.clients.keys()).join(', ')}`);
+ return;
+ }
+
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Sending SSE event '${eventType}' to ${clientList.length} client(s)`);
+
+ // Send to all active clients, removing any that error out
+ const activeClients = [];
+ for (const client of clientList) {
+ try {
+ if (!client.headersSent) {
+ // Headers not sent yet, this shouldn't happen in SSE
+ logger.warn(`[SSE_CLIENT_REGISTRY] Skipping client with unsent headers for: ${fileUri}`);
+ continue;
+ }
+
+ // Send as specific SSE event: event: eventType\ndata: data\n\n
+ client.write(`event: ${eventType}\ndata: ${data}\n\n`);
+ activeClients.push(client);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] SSE event '${eventType}' sent to client successfully`);
+ } catch (error) {
+ logger.error(`[SSE_CLIENT_REGISTRY] Error sending SSE event '${eventType}' to client for ${fileUri}:`, error);
+ // Client will be removed via error event handler
+ }
+ }
+
+ // Update the client list to only include active clients
+ if (activeClients.length !== clientList.length) {
+ if (activeClients.length === 0) {
+ this.clients.delete(fileUri);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] All clients disconnected for: ${fileUri}`);
+ } else {
+ this.clients.set(fileUri, activeClients);
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Updated active clients for ${fileUri}: ${activeClients.length}`);
+ }
+ }
+ }
+
+ /**
+ * Get all file URIs with active clients
+ * @returns Array of file URIs
+ */
+ getActiveFiles(): string[] {
+ return Array.from(this.clients.keys());
+ }
+
+ /**
+ * Get total number of active clients across all files
+ * @returns Total client count
+ */
+ getTotalClientCount(): number {
+ let total = 0;
+ for (const clientList of this.clients.values()) {
+ total += clientList.length;
+ }
+ return total;
+ }
+
+ /**
+ * Remove all clients for a specific file
+ * @param fileUri - URI of the analyzed file
+ */
+ removeAllClients(fileUri: string): void {
+ const clientList = this.clients.get(fileUri);
+ if (!clientList) {
+ return;
+ }
+
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Removing all ${clientList.length} client(s) for: ${fileUri}`);
+
+ // Close all connections
+ for (const client of clientList) {
+ try {
+ client.end();
+ } catch (error) {
+ logger.error(`[SSE_CLIENT_REGISTRY] Error closing client for ${fileUri}:`, error);
+ }
+ }
+
+ this.clients.delete(fileUri);
+ }
+
+ /**
+ * Clear all clients (useful for cleanup)
+ */
+ clearAll(): void {
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Clearing all clients for ${this.clients.size} file(s)`);
+
+ for (const [fileUri, clientList] of this.clients.entries()) {
+ logger.debug(() => `[SSE_CLIENT_REGISTRY] Closing ${clientList.length} client(s) for: ${fileUri}`);
+ for (const client of clientList) {
+ try {
+ client.end();
+ } catch (error) {
+ logger.error(`[SSE_CLIENT_REGISTRY] Error closing client:`, error);
+ }
+ }
+ }
+
+ this.clients.clear();
+ }
+
+ /**
+ * Get statistics about the registry
+ * @returns Registry statistics
+ */
+ getStats(): { fileCount: number; totalClients: number; clientsPerFile: { [fileUri: string]: number } } {
+ const clientsPerFile: { [fileUri: string]: number } = {};
+
+ for (const [fileUri, clientList] of this.clients.entries()) {
+ clientsPerFile[fileUri] = clientList.length;
+ }
+
+ return {
+ fileCount: this.clients.size,
+ totalClients: this.getTotalClientCount(),
+ clientsPerFile
+ };
+ }
+}
diff --git a/apps/vscode-extension/src/core/server/ws/webSocketEndpoint.ts b/apps/vscode-extension/src/core/server/ws/webSocketEndpoint.ts
new file mode 100644
index 000000000..54f52e569
--- /dev/null
+++ b/apps/vscode-extension/src/core/server/ws/webSocketEndpoint.ts
@@ -0,0 +1,61 @@
+import * as http from 'http';
+import * as net from 'net';
+import { WebSocket, WebSocketServer } from 'ws';
+
+/**
+ * The room every browser joins when it names none. It is part of the wire
+ * contract: the collaboration room and the broadcast server must agree on it.
+ */
+export const DEFAULT_ROOM_ID = 'codexr-session:default';
+
+export interface WebSocketEndpointHandlers {
+ /** Decides an upgrade on this path; a refused one has its socket destroyed. */
+ authorize: (request: http.IncomingMessage) => boolean;
+ onConnection: (socket: WebSocket, request: http.IncomingMessage) => void;
+}
+
+export interface WebSocketEndpoint {
+ readonly socketServer: WebSocketServer;
+ /** Stops answering upgrades on the shared HTTP server. */
+ detach(): void;
+}
+
+/**
+ * Serves one WebSocket path on an existing HTTP(S) server. Several endpoints
+ * share the server's 'upgrade' event, so each one ignores every other path
+ * (leaving it to its owner) instead of rejecting it.
+ */
+export function attachWebSocketEndpoint(
+ server: http.Server,
+ path: string,
+ handlers: WebSocketEndpointHandlers,
+): WebSocketEndpoint {
+ const endpointPath = path.startsWith('/') ? path : `/${path}`;
+ const socketServer = new WebSocketServer({ noServer: true });
+ const upgradeHandler = (req: http.IncomingMessage, socket: net.Socket, head: Buffer): void => {
+ const pathname = new URL(req.url || '/', 'http://codexr.local').pathname;
+ if (pathname !== endpointPath) {
+ return;
+ }
+ if (!handlers.authorize(req)) {
+ socket.destroy();
+ return;
+ }
+
+ socketServer.handleUpgrade(req, socket, head, (ws: WebSocket) => {
+ socketServer.emit('connection', ws, req);
+ });
+ };
+
+ server.on('upgrade', upgradeHandler);
+ socketServer.on('connection', (socket: WebSocket, request: http.IncomingMessage) => {
+ handlers.onConnection(socket, request);
+ });
+
+ return {
+ socketServer,
+ detach: () => {
+ server.off('upgrade', upgradeHandler);
+ },
+ };
+}
diff --git a/apps/vscode-extension/src/core/xr/headsetQr.ts b/apps/vscode-extension/src/core/xr/headsetQr.ts
new file mode 100644
index 000000000..f590c9da6
--- /dev/null
+++ b/apps/vscode-extension/src/core/xr/headsetQr.ts
@@ -0,0 +1,47 @@
+import qrcode from 'qrcode-generator';
+
+/**
+ * #19: the QR code of the address a standalone headset opens to join a
+ * scene, shared by the VS Code extension (a webview) and the Code-XR IDE
+ * (its scene header). Pure and vscode-free: one SVG path, a 1x1 square per
+ * dark module, inside the 4-module quiet zone scanners expect.
+ */
+export interface QrDrawing {
+ /** The side of the square viewBox, modules plus the quiet zone. */
+ readonly size: number;
+ readonly path: string;
+}
+
+const QUIET_ZONE = 4;
+
+export function qrDrawing(text: string): QrDrawing {
+ const code = qrcode(0, 'M');
+ code.addData(text);
+ code.make();
+ const count = code.getModuleCount();
+ const parts: string[] = [];
+ for (let row = 0; row < count; row++) {
+ for (let col = 0; col < count; col++) {
+ if (code.isDark(row, col)) {
+ parts.push(`M${col + QUIET_ZONE} ${row + QUIET_ZONE}h1v1h-1z`);
+ }
+ }
+ }
+ return { size: count + QUIET_ZONE * 2, path: parts.join('') };
+}
+
+function escapeXml(text: string): string {
+ return text.replace(/[&<>"']/g, (char) => `${char.charCodeAt(0)};`);
+}
+
+/**
+ * The same code as standalone SVG markup, black on white whatever the theme,
+ * for a page that is written as HTML (the extension's webview). The text only
+ * ever lands in an escaped attribute.
+ */
+export function qrSvgMarkup(text: string, pixels = 240): string {
+ const drawing = qrDrawing(text);
+ return ``;
+}
diff --git a/apps/vscode-extension/src/extension.ts b/apps/vscode-extension/src/extension.ts
new file mode 100644
index 000000000..0b297020a
--- /dev/null
+++ b/apps/vscode-extension/src/extension.ts
@@ -0,0 +1,160 @@
+import * as vscode from 'vscode';
+import { registerAllCommands } from './app/commands/registerAllCommands';
+import { registerMetricsInEditor } from './features/metrics-in-editor/metricsInEditor';
+import { initializePythonEnvOnStartup } from './features/python-env/commands/pythonEnvCommandRegistrations';
+import { XRFieldSchemaService } from './core/analysis/python/xrFieldSchemaService';
+import { ModularTreeDataProvider } from './app/sidebar/ModularTreeDataProvider';
+import { CommonCommands } from './app/sidebar/commonCommands';
+import { ServerSettingsManager } from './core/server/serverSettingsManager';
+import { GeneratedHttpsCertificateManager } from './core/server/generatedHttpsCertificateManager';
+import { getActiveServerRegistry } from './core/server/registry/activeServerRegistry';
+import { ServerControl } from './core/server/serverControl';
+import { sseManager } from './core/server/sse/SSEManager';
+import { fileToServerMap } from './core/server/fileToServerMap';
+import { ServerWatcherIntegration } from './features/analysis/services/serverWatcherIntegration';
+import { CleanAnalysisCommands } from './features/analysis/commands/cleanAnalysisCommands';
+import { AnalysisConfigurationStorage } from './core/analysis/configuration/analysisConfigurationStorage';
+import { handleError, ErrorDomain, ErrorSeverity } from './platform/ui/errorHandler';
+import { initializeExtensionContext } from './platform/extensionContext';
+import { initializeHost } from './core/host/hostRegistry';
+import { createVSCodeHost } from './app/host/vscodeHost';
+import { setLaunchNotifier } from './core/server/launchNotifier';
+import * as launchNotifications from './features/active-servers/views/launchNotifications';
+import { setServerPanelCloser } from './core/server/serverPanels';
+import { getPanelManager } from './platform/webview/panelManager';
+import { CodeXRLogger } from './platform/logging/logger';
+import { StartupCoordinator } from './app/startup/startupCoordinator';
+import { CollaborationProfileManager } from './core/collaboration/collaborationProfileManager';
+import { RemoteAccessManager } from './core/remote-access/remoteAccessManager';
+
+const startupLogger = CodeXRLogger.getLogger('STARTUP');
+
+let globalModularTreeDataProvider: ModularTreeDataProvider | null = null;
+
+export async function activate(context: vscode.ExtensionContext) {
+ const activationStartedAt = Date.now();
+
+ initializeExtensionContext(context);
+ initializeHost(createVSCodeHost(context));
+ setLaunchNotifier(launchNotifications);
+ setServerPanelCloser({ closeServerPanels: (serverIds) => getPanelManager().removePanelsForServers([...serverIds]) });
+ CodeXRLogger.initialize(context);
+
+ startupLogger.info('Activating CodeXR.');
+
+ try {
+ AnalysisConfigurationStorage.initialize(context);
+ CollaborationProfileManager.initialize(context);
+ RemoteAccessManager.initialize(context);
+
+ const settingsManager = ServerSettingsManager.getInstance(context);
+ getActiveServerRegistry();
+ ServerControl.initialize(context);
+
+ const modularTreeDataProvider = new ModularTreeDataProvider(context);
+ globalModularTreeDataProvider = modularTreeDataProvider;
+
+ const modularTreeView = vscode.window.createTreeView('codexrTree', {
+ treeDataProvider: modularTreeDataProvider,
+ showCollapseAll: true,
+ canSelectMany: false,
+ });
+
+ context.subscriptions.push(modularTreeView);
+ CommonCommands.setModularTreeProvider(modularTreeDataProvider);
+ registerAllCommands(context, modularTreeDataProvider, undefined);
+ // #173/#178: the Code-XR IDE's metric checks and lenses, from the same core.
+ registerMetricsInEditor(context);
+
+ const startupCoordinator = new StartupCoordinator(
+ CodeXRLogger.getLogger('STARTUP_DEFERRED'),
+ undefined,
+ { maxConcurrent: 3 },
+ );
+
+ context.subscriptions.push({
+ dispose: () => startupCoordinator.dispose(),
+ });
+ const xrFieldSchemaService = XRFieldSchemaService.getInstance(context);
+
+ startupCoordinator.schedule({
+ id: 'restore-server-settings',
+ run: async () => {
+ await settingsManager.ensureInitialized();
+ await new GeneratedHttpsCertificateManager(context).ensureDefaultCertificatePair();
+ modularTreeDataProvider.refreshSection('SERVERS');
+ },
+ });
+
+ startupCoordinator.schedule({
+ id: 'initialize-server-watcher-integration',
+ run: async () => {
+ ServerWatcherIntegration.initialize(context);
+ },
+ });
+
+ startupCoordinator.schedule({
+ id: 'initialize-python-env',
+ run: async () => {
+ await initializePythonEnvOnStartup();
+ await xrFieldSchemaService.prefetchAll();
+ modularTreeDataProvider.refreshSection('pythonEnv');
+ modularTreeDataProvider.refreshSection('analysis');
+ },
+ });
+
+ startupCoordinator.schedule({
+ id: 'cleanup-stale-analysis-artifacts',
+ run: async () => {
+ await CleanAnalysisCommands.executeStartupCleanup(context, activationStartedAt);
+ },
+ });
+
+ startupCoordinator.start();
+ startupLogger.info('Code-XR activation completed. Deferred startup tasks queued.');
+ } catch (error) {
+ startupLogger.error('Extension activation failed.', error);
+ void vscode.window.showErrorMessage(`Code-XR activation failed: ${error}`);
+ }
+}
+
+export async function deactivate() {
+ startupLogger.info('Deactivating CodeXR.');
+
+ try {
+ await RemoteAccessManager.getInstance()?.stopAll();
+ } catch (error) {
+ handleError(ErrorDomain.ActiveServers, 'Remote access cleanup', error, ErrorSeverity.Warn);
+ }
+
+ try {
+ const registry = getActiveServerRegistry();
+ const cleanedCount = registry.cleanupInactiveServers();
+ startupLogger.debug(() => `Active server registry cleanup removed ${cleanedCount} inactive servers.`);
+ } catch (error) {
+ handleError(ErrorDomain.ActiveServers, 'Registry cleanup', error, ErrorSeverity.Warn);
+ }
+
+ try {
+ sseManager.dispose();
+ fileToServerMap.clearAll();
+ } catch (error) {
+ handleError(ErrorDomain.SSE, 'SSE and file mapping cleanup', error, ErrorSeverity.Warn);
+ }
+
+ try {
+ if (globalModularTreeDataProvider) {
+ globalModularTreeDataProvider.dispose();
+ globalModularTreeDataProvider = null;
+ }
+ } catch (error) {
+ handleError(ErrorDomain.UI, 'Modular tree cleanup', error, ErrorSeverity.Warn);
+ }
+}
+
+
+
+
+
+
+
diff --git a/apps/vscode-extension/src/features/active-servers/commands/activeServersCommandRegistrations.ts b/apps/vscode-extension/src/features/active-servers/commands/activeServersCommandRegistrations.ts
new file mode 100644
index 000000000..0b12c817f
--- /dev/null
+++ b/apps/vscode-extension/src/features/active-servers/commands/activeServersCommandRegistrations.ts
@@ -0,0 +1,12 @@
+import { ActiveServersCommands } from './activeServersCommands';
+import { ExtensionCommandRegistration } from '../../../platform/commands/commandRegistry';
+
+interface RefreshableTreeProvider {
+ refresh(): void;
+}
+
+export function getActiveServersCommandRegistrations(
+ treeDataProvider?: RefreshableTreeProvider,
+): ExtensionCommandRegistration[] {
+ return ActiveServersCommands.getCommandRegistrations(treeDataProvider);
+}
diff --git a/apps/vscode-extension/src/features/active-servers/commands/activeServersCommands.ts b/apps/vscode-extension/src/features/active-servers/commands/activeServersCommands.ts
new file mode 100644
index 000000000..5c1909a04
--- /dev/null
+++ b/apps/vscode-extension/src/features/active-servers/commands/activeServersCommands.ts
@@ -0,0 +1,191 @@
+import * as vscode from 'vscode';
+import { ServerActionHandlers } from '../views/handleServerActions';
+import { ExtensionCommandRegistration } from '../../../platform/commands/commandRegistry';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('ACTIVE_SERVER');
+
+/** A command whose only argument is a server, as a tree item or a bare id. */
+interface ServerIdCommand {
+ id: string;
+ description: string;
+ action: ServerIdAction;
+ errorMessage: string;
+}
+
+type ServerIdAction =
+ | 'openInBrowser'
+ | 'openInPanel'
+ | 'copyUrl'
+ | 'copyLanUrl'
+ | 'showHeadsetQr'
+ | 'startRemoteAccess'
+ | 'copyRemoteInvitation'
+ | 'stopRemoteAccess'
+ | 'showRemoteStatus'
+ | 'stopServer'
+ | 'showServerDetails'
+ | 'regeneratePairingCode';
+
+/** In registration order, between showActions and showParticipantDetails. */
+const SERVER_ID_COMMANDS: readonly ServerIdCommand[] = [
+ { id: 'codeXR.activeServers.openInBrowser', description: 'Open active server in browser', action: 'openInBrowser', errorMessage: 'Failed to open active server in browser' },
+ { id: 'codeXR.activeServers.openInPanel', description: 'Open active server in panel', action: 'openInPanel', errorMessage: 'Failed to open active server in panel' },
+ { id: 'codeXR.activeServers.copyUrl', description: 'Copy active server URL', action: 'copyUrl', errorMessage: 'Failed to copy active server URL' },
+ { id: 'codeXR.activeServers.copyLanUrl', description: 'Copy active server LAN URL', action: 'copyLanUrl', errorMessage: 'Failed to copy active server LAN URL' },
+ { id: 'codeXR.activeServers.showHeadsetQr', description: 'Show the headset address and QR code', action: 'showHeadsetQr', errorMessage: 'Failed to show the headset address' },
+ { id: 'codeXR.activeServers.startRemoteAccess', description: 'Start remote access', action: 'startRemoteAccess', errorMessage: 'Failed to start remote access' },
+ { id: 'codeXR.activeServers.copyRemoteInvitation', description: 'Copy remote invitation', action: 'copyRemoteInvitation', errorMessage: 'Failed to copy remote invitation' },
+ { id: 'codeXR.activeServers.stopRemoteAccess', description: 'Stop remote access', action: 'stopRemoteAccess', errorMessage: 'Failed to stop remote access' },
+ { id: 'codeXR.activeServers.showRemoteStatus', description: 'Show remote access status', action: 'showRemoteStatus', errorMessage: 'Failed to show remote access status' },
+ { id: 'codeXR.activeServers.stopServer', description: 'Stop active server', action: 'stopServer', errorMessage: 'Failed to stop active server' },
+ { id: 'codeXR.activeServers.showDetails', description: 'Show active server details', action: 'showServerDetails', errorMessage: 'Failed to show active server details' },
+ { id: 'codeXR.activeServers.regeneratePairingCode', description: 'Generate a new pairing code', action: 'regeneratePairingCode', errorMessage: 'Failed to generate a new pairing code' },
+];
+
+/**
+ * Active Servers Commands
+ * Command declarations for active servers functionality.
+ */
+export class ActiveServersCommands {
+ private static treeDataProvider: { refresh(): void } | undefined;
+
+ public static getCommandRegistrations(treeDataProvider?: { refresh(): void }): ExtensionCommandRegistration[] {
+ this.treeDataProvider = treeDataProvider;
+
+ return [
+ {
+ id: 'codeXR.activeServers.showActions',
+ module: 'ACTIVE_SERVER',
+ description: 'Show server actions',
+ handler: async (serverId: string) => {
+ await ServerActionHandlers.showServerActions(serverId);
+ },
+ errorMessage: 'Failed to show server actions'
+ },
+ ...SERVER_ID_COMMANDS.map((command) => this.serverIdCommand(command)),
+ {
+ id: 'codeXR.activeServers.showParticipantDetails',
+ module: 'ACTIVE_SERVER',
+ description: 'Show connected participant details',
+ handler: async (serverId: string, peerId: string) => {
+ await ServerActionHandlers.showParticipantDetails(serverId, peerId);
+ },
+ errorMessage: 'Failed to show participant details'
+ },
+ {
+ id: 'codeXR.activeServers.removeParticipant',
+ module: 'ACTIVE_SERVER',
+ description: 'Remove a participant from the session',
+ handler: async (target: unknown, peerIdArgument?: string) => {
+ // Invoked either from the details modal (serverId, peerId)
+ // or from the tree context menu (the participant row).
+ const participantTarget = typeof target === 'string' && peerIdArgument
+ ? { serverId: target, peerId: peerIdArgument }
+ : this.extractParticipantFromTreeItem(target);
+ if (!participantTarget) {
+ // Never fail silently: an unresolvable target used to
+ // look exactly like a command that did nothing.
+ void vscode.window.showWarningMessage(
+ 'Could not tell which participant to remove. Refresh the view and try again.',
+ );
+ return;
+ }
+ await ServerActionHandlers.removeParticipant(
+ participantTarget.serverId,
+ participantTarget.peerId,
+ );
+ },
+ errorMessage: 'Failed to remove the participant',
+ },
+ {
+ id: 'codeXR.activeServers.stopAllServers',
+ module: 'ACTIVE_SERVER',
+ description: 'Stop all active servers',
+ handler: async () => {
+ await ServerActionHandlers.stopAllServers();
+ },
+ errorMessage: 'Failed to stop all active servers'
+ },
+ {
+ id: 'codeXR.activeServers.refreshServers',
+ module: 'ACTIVE_SERVER',
+ description: 'Refresh active servers',
+ handler: async () => {
+ if (this.treeDataProvider?.refresh) {
+ logger.debug('Refreshing unified tree view');
+ this.treeDataProvider.refresh();
+ return;
+ }
+
+ logger.debug('Using fallback refresh handler');
+ await vscode.commands.executeCommand('codexr.tree.refresh');
+ },
+ errorMessage: 'Failed to refresh active servers'
+ },
+ {
+ id: 'codeXR.activeServers.openView',
+ module: 'ACTIVE_SERVER',
+ description: 'Open active servers view',
+ handler: async () => {
+ await vscode.commands.executeCommand('codexrTree.focus');
+ },
+ errorMessage: 'Failed to open active servers view'
+ }
+ ];
+ }
+
+ /** The registration of a table row: resolve the server id, then run the action (nothing when unresolvable). */
+ private static serverIdCommand(command: ServerIdCommand): ExtensionCommandRegistration {
+ return {
+ id: command.id,
+ module: 'ACTIVE_SERVER',
+ description: command.description,
+ handler: async (treeItem: unknown) => {
+ const serverId = this.extractServerIdFromTreeItem(treeItem);
+ if (serverId) {
+ await ServerActionHandlers[command.action](serverId);
+ }
+ },
+ errorMessage: command.errorMessage,
+ };
+ }
+
+ private static extractParticipantFromTreeItem(
+ treeItem: unknown,
+ ): { serverId: string; peerId: string } | null {
+ if (typeof treeItem !== 'object' || treeItem === null) {
+ return null;
+ }
+ const item = treeItem as {
+ activeServer?: { id?: string };
+ server?: { id?: string };
+ participant?: { peerId?: string };
+ };
+ const serverId = item.activeServer?.id || item.server?.id;
+ const peerId = item.participant?.peerId;
+ if (!serverId || !peerId) {
+ logger.error('Could not extract participant from tree item:', treeItem);
+ return null;
+ }
+ return { serverId, peerId };
+ }
+
+ private static extractServerIdFromTreeItem(treeItem: unknown): string | null {
+ if (typeof treeItem === 'object' && treeItem !== null && 'server' in treeItem) {
+ const server = (treeItem as { server?: { id?: string } }).server;
+ if (server?.id) {
+ logger.debug(() => `Extracted server ID from tree item: ${server.id}`);
+ return server.id;
+ }
+ }
+
+ if (typeof treeItem === 'string') {
+ logger.debug(() => `Using direct server ID: ${treeItem}`);
+ return treeItem;
+ }
+
+ logger.error('Could not extract server ID from tree item:', treeItem);
+ return null;
+ }
+}
diff --git a/apps/vscode-extension/src/features/active-servers/services/headsetPage.ts b/apps/vscode-extension/src/features/active-servers/services/headsetPage.ts
new file mode 100644
index 000000000..22b8fa8d6
--- /dev/null
+++ b/apps/vscode-extension/src/features/active-servers/services/headsetPage.ts
@@ -0,0 +1,66 @@
+import type { ActiveServer } from '../../../core/server/registry/activeServerModel';
+import { qrSvgMarkup } from '../../../core/xr/headsetQr';
+
+/**
+ * #19: what a standalone headset opens to join a scene, and the page that
+ * shows it. vscode-free, so it is unit-tested; `headsetQrPanel.ts` shows it.
+ *
+ * WebXR needs a secure context, so a headset needs an HTTPS address:
+ * - the Cloudflare invitation link while the server is shared (a real
+ * certificate, reachable from anywhere; the guest is let in with the
+ * pairing code VS Code shows);
+ * - else the local network address of an HTTPS server (same network only;
+ * the headset's browser warns about the self-signed certificate once);
+ * - else nothing: a plain HTTP server must be shared first.
+ */
+export type HeadsetTarget =
+ | { readonly kind: 'invitation' | 'lan'; readonly url: string }
+ | { readonly kind: 'none' };
+
+export function headsetTarget(server: Pick, lanUrl: string): HeadsetTarget {
+ const invitation = server.remoteAccess?.status === 'shared' ? server.remoteAccess.invitationUrl : undefined;
+ if (invitation?.startsWith('https://')) {
+ return { kind: 'invitation', url: invitation };
+ }
+ if (server.certMode !== 'http' && lanUrl.startsWith('https://')) {
+ return { kind: 'lan', url: lanUrl };
+ }
+ return { kind: 'none' };
+}
+
+function escapeHtml(text: string): string {
+ return text.replace(/[&<>"']/g, (char) => `${char.charCodeAt(0)};`);
+}
+
+const STEPS: Readonly> = {
+ invitation: 'On the headset, open the browser and scan this code, or type the link. Enter the pairing code VS Code shows, then press the scene\'s VR button.',
+ lan: 'Put the headset on the same network as this computer. Open its browser and scan this code, or type the address, and accept the certificate warning once (the certificate is generated by Code-XR). Then press the scene\'s VR button.',
+};
+
+/** The webview's whole page: no script, inline styles only, the QR code as inline SVG. */
+export function headsetPageHtml(target: HeadsetTarget, serverLabel: string, cspSource: string): string {
+ const body = target.kind === 'none'
+ ? `
A headset needs an HTTPS address it can reach, and this server is served over plain HTTP.
+
Start remote access for it (Start Remote Access on the server in ACTIVE SERVERS), then open this page again.
`
+ : `
${qrSvgMarkup(target.url)}
+
${escapeHtml(STEPS[target.kind])}
+
${escapeHtml(target.url)}
`;
+ return `
+
+
+
+
+
+Open on a headset
+
+
+
+
Open ${escapeHtml(serverLabel)} on a headset
+${body}
+
+`;
+}
diff --git a/apps/vscode-extension/src/features/active-servers/services/headsetQrPanel.ts b/apps/vscode-extension/src/features/active-servers/services/headsetQrPanel.ts
new file mode 100644
index 000000000..96bcd8031
--- /dev/null
+++ b/apps/vscode-extension/src/features/active-servers/services/headsetQrPanel.ts
@@ -0,0 +1,19 @@
+import * as vscode from 'vscode';
+import { NetworkUtils } from '../../../core/server/networkUtils';
+import type { ActiveServer } from '../../../core/server/registry/activeServerModel';
+import { headsetPageHtml, headsetTarget } from './headsetPage';
+
+/**
+ * #19: "Open on a Headset" for a server in ACTIVE SERVERS: a webview with
+ * the address a standalone headset opens and its QR code, the same code the
+ * Code-XR IDE shows in its scene header (core/xr/headsetQr.ts).
+ */
+export function showHeadsetQrPanel(server: ActiveServer): void {
+ const lanUrl = NetworkUtils.getPrimaryExternalUrl(server.port, server.url.startsWith('https') ? 'https' : 'http');
+ const label = server.customName || `the server on port ${server.port}`;
+ const panel = vscode.window.createWebviewPanel('codexrHeadsetQr', 'Open on a Headset', vscode.ViewColumn.Active, {
+ enableScripts: false,
+ localResourceRoots: [],
+ });
+ panel.webview.html = headsetPageHtml(headsetTarget(server, lanUrl), label, panel.webview.cspSource);
+}
diff --git a/src/servers/runtime/previewRenderer.ts b/apps/vscode-extension/src/features/active-servers/services/previewRenderer.ts
similarity index 85%
rename from src/servers/runtime/previewRenderer.ts
rename to apps/vscode-extension/src/features/active-servers/services/previewRenderer.ts
index 3d54e5bcc..f20046ba3 100644
--- a/src/servers/runtime/previewRenderer.ts
+++ b/apps/vscode-extension/src/features/active-servers/services/previewRenderer.ts
@@ -1,6 +1,9 @@
import * as vscode from 'vscode';
import * as path from 'path';
-import { getPanelManager } from '../../active_servers/services/panelManager';
+import { getPanelManager } from '../../../platform/webview/panelManager';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('SERVER');
/**
* Preview Renderer
@@ -21,7 +24,7 @@ export class PreviewRenderer {
openMode: 'browser' | 'lateralPanel',
serverId?: string
): Promise {
- console.log(`SERVER: Opening preview for ${htmlFilePath} at ${serverUrl} in ${openMode} mode`);
+ logger.debug(() => `Opening preview for ${htmlFilePath} at ${serverUrl} in ${openMode} mode`);
try {
if (openMode === 'browser') {
@@ -35,8 +38,8 @@ export class PreviewRenderer {
throw new Error(`Unsupported open mode: ${openMode}`);
}
} catch (error) {
- console.error(`SERVER: Error opening preview: ${error}`);
- vscode.window.showWarningMessage(`Failed to open preview: ${error instanceof Error ? error.message : String(error)}`);
+ logger.error(`Error opening preview: ${error}`);
+ void vscode.window.showWarningMessage(`Failed to open preview: ${error instanceof Error ? error.message : String(error)}`);
}
}
@@ -45,9 +48,9 @@ export class PreviewRenderer {
* @private
*/
private static async openInBrowser(serverUrl: string): Promise {
- console.log(`SERVER: Opening ${serverUrl} in external browser`);
+ logger.debug(() => `Opening ${serverUrl} in external browser`);
await vscode.env.openExternal(vscode.Uri.parse(serverUrl));
- vscode.window.showInformationMessage(`Opened ${serverUrl} in browser`);
+ void vscode.window.showInformationMessage(`Opened ${serverUrl} in browser`);
}
/**
@@ -55,7 +58,7 @@ export class PreviewRenderer {
* @private
*/
private static async openInWebviewPanel(serverUrl: string, htmlFilePath: string, serverId: string): Promise {
- console.log(`ACTIVE_SERVER_PANEL: Opening ${serverUrl} in VS Code webview panel for server ${serverId}`);
+ logger.debug(() => `ACTIVE_SERVER_PANEL: Opening ${serverUrl} in VS Code webview panel for server ${serverId}`);
try {
const fileName = path.basename(htmlFilePath);
@@ -75,7 +78,7 @@ export class PreviewRenderer {
// Register panel with panel manager
const panelManager = getPanelManager();
panelManager.registerPanel(serverId, panel);
- console.log(`ACTIVE_SERVER_PANEL: Panel registered for server ${serverId}`);
+ logger.debug(() => `ACTIVE_SERVER_PANEL: Panel registered for server ${serverId}`);
// Create iframe HTML pointing to the server URL
const iframeHtml = this.createIframeHtml(serverUrl, fileName);
@@ -86,16 +89,16 @@ export class PreviewRenderer {
// Handle messages from webview
panel.webview.onDidReceiveMessage(
message => {
- console.log(`ACTIVE_SERVER_PANEL: Webview message for server ${serverId}:`, message);
+ logger.debug(() => `ACTIVE_SERVER_PANEL: Webview message for server ${serverId}:`, message);
switch (message.command) {
case 'openExternal':
- vscode.env.openExternal(vscode.Uri.parse(message.url));
+ void vscode.env.openExternal(vscode.Uri.parse(message.url));
break;
case 'showError':
- vscode.window.showErrorMessage(message.text);
+ void vscode.window.showErrorMessage(message.text);
break;
case 'serverError':
- vscode.window.showWarningMessage(`Server Error: ${message.text}`);
+ void vscode.window.showWarningMessage(`Server Error: ${message.text}`);
break;
}
},
@@ -104,15 +107,15 @@ export class PreviewRenderer {
// Handle panel disposal
panel.onDidDispose(() => {
- console.log(`ACTIVE_SERVER_PANEL: Webview panel disposed for server ${serverId}`);
+ logger.debug(() => `ACTIVE_SERVER_PANEL: Webview panel disposed for server ${serverId}`);
// Panel manager will automatically clean up via its disposal listener
});
- console.log(`SERVER: Created webview panel for ${serverUrl}`);
- vscode.window.showInformationMessage(`Opened ${fileName} in VS Code panel`);
+ logger.debug(() => `Created webview panel for ${serverUrl}`);
+ void vscode.window.showInformationMessage(`Opened ${fileName} in VS Code panel`);
} catch (error) {
- console.error(`SERVER: Error creating webview panel: ${error}`);
+ logger.error(`Error creating webview panel: ${error}`);
throw new Error(`Failed to create webview panel: ${error instanceof Error ? error.message : String(error)}`);
}
}
diff --git a/apps/vscode-extension/src/features/active-servers/services/serverOpenActions.ts b/apps/vscode-extension/src/features/active-servers/services/serverOpenActions.ts
new file mode 100644
index 000000000..feb4e5a2d
--- /dev/null
+++ b/apps/vscode-extension/src/features/active-servers/services/serverOpenActions.ts
@@ -0,0 +1,78 @@
+import * as vscode from 'vscode';
+import { withServer } from './withServer';
+import { PreviewRenderer } from './previewRenderer';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('ACTIVE_SERVER');
+
+/*
+ * Opening a registered server, in the browser or in the lateral panel. Shared
+ * by the server actions of the tree and by the launch notifications, so the
+ * launcher does not have to import a view module to open what it launched.
+ */
+
+/**
+ * Open server in browser
+ */
+export async function openServerInBrowser(serverId: string): Promise {
+ logger.debug(() => `Opening server ${serverId} in browser`);
+
+ return withServer(serverId, async (server) => {
+ try {
+ const browserUrl = typeof server.serverInstance?.createAuthenticatedBrowserUrl === 'function'
+ ? server.serverInstance.createAuthenticatedBrowserUrl(server.url)
+ : server.url;
+ await PreviewRenderer.openPreview(browserUrl, server.htmlFile || '', 'browser');
+ logger.debug(() => `Opened ${server.url} in browser`);
+ void vscode.window.showInformationMessage(`Opened ${server.url} in browser`);
+ } catch (error) {
+ logger.error(`Error opening ${server.url} in browser:`, error);
+ void vscode.window.showErrorMessage(
+ `Failed to open in browser: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+ });
+}
+
+/**
+ * Open server in lateral panel
+ */
+export async function openServerInPanel(serverId: string): Promise {
+ logger.debug(() => `Opening server ${serverId} in lateral panel`);
+
+ return withServer(serverId, async (server) => {
+ // Check for HTTPS + lateral panel conflict
+ if (server.certMode !== 'http') {
+ logger.debug(() => `HTTPS server ${serverId} cannot be opened in lateral panel - cert mode: ${server.certMode}`);
+
+ const response = await vscode.window.showWarningMessage(
+ 'HTTPS content cannot be displayed in VS Code panels due to security restrictions. The content will not load properly.',
+ 'Open in Browser Instead',
+ 'Cancel'
+ );
+
+ if (response === 'Open in Browser Instead') {
+ logger.debug(() => `Redirecting server ${serverId} to browser due to HTTPS incompatibility`);
+ return openServerInBrowser(serverId);
+ } else {
+ logger.debug(() => `User cancelled opening HTTPS server ${serverId} in panel`);
+ return; // User cancelled
+ }
+ }
+
+ try {
+ logger.debug(() => `Opening HTTP server ${serverId} (${server.url}) in lateral panel`);
+ const panelUrl = typeof server.serverInstance?.createAuthenticatedBrowserUrl === 'function'
+ ? server.serverInstance.createAuthenticatedBrowserUrl(server.url)
+ : server.url;
+ await PreviewRenderer.openPreview(panelUrl, server.htmlFile || '', 'lateralPanel', serverId);
+ logger.debug(() => `Successfully opened ${server.url} in lateral panel`);
+ void vscode.window.showInformationMessage(`Opened ${server.url} in VS Code panel`);
+ } catch (error) {
+ logger.error(`Error opening ${server.url} in panel:`, error);
+ void vscode.window.showErrorMessage(
+ `Failed to open in panel: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+ });
+}
diff --git a/apps/vscode-extension/src/features/active-servers/services/withServer.ts b/apps/vscode-extension/src/features/active-servers/services/withServer.ts
new file mode 100644
index 000000000..749e9e04d
--- /dev/null
+++ b/apps/vscode-extension/src/features/active-servers/services/withServer.ts
@@ -0,0 +1,27 @@
+import * as vscode from 'vscode';
+import { ActiveServer } from '../../../core/server/registry/activeServerModel';
+import { getActiveServerRegistry } from '../../../core/server/registry/activeServerRegistry';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('ACTIVE_SERVER');
+
+/**
+ * Run an action on a registered server. An unknown id is logged and reported
+ * with the same toast every server action has always shown, and the action
+ * does not run.
+ */
+export async function withServer(
+ serverId: string,
+ action: (server: ActiveServer) => Promise,
+): Promise {
+ const registry = getActiveServerRegistry();
+ const server = registry.getServer(serverId);
+
+ if (!server) {
+ logger.error(`Server ${serverId} not found`);
+ void vscode.window.showErrorMessage(`Server not found: ${serverId}`);
+ return;
+ }
+
+ return action(server);
+}
diff --git a/src/views/active_servers/ActiveServersSectionProvider.ts b/apps/vscode-extension/src/features/active-servers/views/ActiveServersSectionProvider.ts
similarity index 76%
rename from src/views/active_servers/ActiveServersSectionProvider.ts
rename to apps/vscode-extension/src/features/active-servers/views/ActiveServersSectionProvider.ts
index 53a7a15f6..af73c2c09 100644
--- a/src/views/active_servers/ActiveServersSectionProvider.ts
+++ b/apps/vscode-extension/src/features/active-servers/views/ActiveServersSectionProvider.ts
@@ -1,11 +1,13 @@
import * as vscode from 'vscode';
-import { SectionProvider } from '../common/baseInterfaces';
-import { ActiveServerTreeItem, ActiveServerItemFactory } from './items/activeServerItems';
-import { ActiveServerClickHandler } from './interactions/handleActiveServerClicks';
-import { CollaborationSectionProvider } from '../collaboration';
-import { getActiveServerRegistry } from '../../active_servers/registry/activeServerRegistry';
-import { ActiveServer } from '../../active_servers/model/activeServerModel';
-import { ConnectedParticipantSummary } from '../../collaboration';
+import { SectionProvider } from '../../../platform/tree/baseInterfaces';
+import { ActiveServerTreeItem, ActiveServerItemFactory } from './activeServerItems';
+import { CollaborationSectionProvider } from '../../collaboration/views/CollaborationSectionProvider';
+import { getActiveServerRegistry } from '../../../core/server/registry/activeServerRegistry';
+import { ActiveServer } from '../../../core/server/registry/activeServerModel';
+import { ConnectedParticipantSummary } from '../../../core/collaboration/connectedParticipant';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('ACTIVE_SERVERS_MODULAR');
interface ParticipantAwareServer {
getConnectedParticipants(): ConnectedParticipantSummary[];
@@ -24,15 +26,13 @@ export class ActiveServersSectionProvider implements SectionProvider =
this._onDidChangeTreeData.event;
- private clickHandler: ActiveServerClickHandler;
private readonly participantSubscriptions = new Map void>();
private readonly registrySubscription: vscode.Disposable;
private readonly collaborationProvider: CollaborationSectionProvider;
private readonly collaborationSubscription: vscode.Disposable;
- constructor(private context: vscode.ExtensionContext) {
- console.log('ACTIVE_SERVERS_MODULAR: Initializing Active Servers section provider');
- this.clickHandler = new ActiveServerClickHandler(context);
+ constructor(context: vscode.ExtensionContext) {
+ logger.debug('Initializing Active Servers section provider');
// Collaboration lives as a nested group inside this section; its provider
// stays the single source of truth for the shared profile items.
@@ -41,10 +41,10 @@ export class ActiveServersSectionProvider implements SectionProvider `Connected to active server registry, current servers: ${registry.getAllServers().length}`);
this.registrySubscription = registry.onRegistryChange(() => {
- console.log('ACTIVE_SERVERS_MODULAR: Active servers registry changed, refreshing section');
+ logger.debug('Active servers registry changed, refreshing section');
this.reconcileParticipantSubscriptions();
this.refresh();
});
@@ -114,13 +114,13 @@ export class ActiveServersSectionProvider implements SectionProvider server.status === 'running');
- console.log(`ACTIVE_SERVERS_MODULAR: Found ${activeServers.length} total servers, ${runningServers.length} running`);
+ logger.debug(() => `Found ${activeServers.length} total servers, ${runningServers.length} running`);
// The collaboration group is always reachable: joining a remote session
// does not require a local server.
@@ -128,7 +128,7 @@ export class ActiveServersSectionProvider implements SectionProvider= 2) {
- console.log(`ACTIVE_SERVERS_MODULAR: Adding "Stop All Servers" option for ${runningServers.length} running servers`);
+ logger.debug(() => `Adding "Stop All Servers" option for ${runningServers.length} running servers`);
children.push(ActiveServerItemFactory.createStopAllServersItem(runningServers.length));
}
// A lone server opens expanded; with several, they stay compact.
- console.log(`ACTIVE_SERVERS_MODULAR: Creating ${runningServers.length} individual server items`);
+ logger.debug(() => `Creating ${runningServers.length} individual server items`);
const serverItems = runningServers.map(server =>
ActiveServerItemFactory.createServerItem(server, runningServers.length === 1)
);
children.push(...serverItems);
- console.log(`ACTIVE_SERVERS_MODULAR: Returning ${children.length} children for Active Servers section`);
+ logger.debug(() => `Returning ${children.length} children for Active Servers section`);
return children;
}
@@ -156,7 +156,7 @@ export class ActiveServersSectionProvider implements SectionProvider {
- await this.clickHandler.handleActiveServerClick(item);
- }
-
- /**
- * Handle context menu actions (additional method for interaction)
- */
- async handleContextMenu(action: string, item: ActiveServerTreeItem): Promise {
- await this.clickHandler.handleContextMenuAction(action, item);
- }
-
private getParticipants(server: ActiveServer): ConnectedParticipantSummary[] {
const runtime = this.asParticipantAwareServer(server);
- return runtime?.getConnectedParticipants() || [];
+ return runtime?.getConnectedParticipants() ?? [];
}
private reconcileParticipantSubscriptions(): void {
diff --git a/src/views/active_servers/items/activeServerItems.ts b/apps/vscode-extension/src/features/active-servers/views/activeServerItems.ts
similarity index 92%
rename from src/views/active_servers/items/activeServerItems.ts
rename to apps/vscode-extension/src/features/active-servers/views/activeServerItems.ts
index 45873d7b7..f1ac7197d 100644
--- a/src/views/active_servers/items/activeServerItems.ts
+++ b/apps/vscode-extension/src/features/active-servers/views/activeServerItems.ts
@@ -1,9 +1,14 @@
+import * as path from 'path';
import * as vscode from 'vscode';
-import { ActiveServer } from '../../../active_servers/model/activeServerModel';
-import { COLLABORATION_AVATARS, ConnectedParticipantSummary } from '../../../collaboration';
-import { NetworkUtils } from '../../../servers/utils/networkUtils';
-import { CollaborationTreeItem } from '../../collaboration/items/collaborationItems';
-import { ServerSettingsManager } from '../../../servers/storage/serverSettingsManager';
+import { ActiveServer } from '../../../core/server/registry/activeServerModel';
+import { COLLABORATION_AVATARS } from '../../../core/collaboration/collaborationProfile';
+import { ConnectedParticipantSummary } from '../../../core/collaboration/connectedParticipant';
+import { NetworkUtils } from '../../../core/server/networkUtils';
+import { CollaborationTreeItem } from '../../collaboration/views/collaborationItems';
+import { ServerSettingsManager } from '../../../core/server/serverSettingsManager';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('ACTIVE_SERVERS');
export type ActiveServerItemType =
| 'server-item'
@@ -52,7 +57,7 @@ export class ActiveServerItemFactory {
* Create "No active servers" message item
*/
static createNoServersItem(): ActiveServerTreeItem {
- console.log('ACTIVE_SERVERS: Creating "No active servers" message item');
+ logger.debug('Creating "No active servers" message item');
return new ActiveServerTreeItem(
'No active servers',
@@ -103,7 +108,7 @@ export class ActiveServerItemFactory {
* Create "Stop All Servers" control option
*/
static createStopAllServersItem(runningCount: number): ActiveServerTreeItem {
- console.log(`ACTIVE_SERVERS: Creating "Stop All Servers" option for ${runningCount} running servers`);
+ logger.debug(() => `Creating "Stop All Servers" option for ${runningCount} running servers`);
return new ActiveServerTreeItem(
'Stop All Servers',
@@ -126,13 +131,13 @@ export class ActiveServerItemFactory {
static createServerItem(server: ActiveServer, expanded = false): ActiveServerTreeItem {
// Use custom name if provided, otherwise fallback to localhost:port
const label = server.customName?.trim() || `localhost:${server.port}`;
- console.log(`ACTIVE_SERVERS: Creating server item with label: "${label}" (customName: "${server.customName}", port: ${server.port})`);
+ logger.debug(() => `Creating server item with label: "${label}" (customName: "${server.customName}", port: ${server.port})`);
const description = ActiveServerItemFactory.getServerDescription(server);
const icon = ActiveServerItemFactory.getServerIcon(server);
const tooltip = ActiveServerItemFactory.getServerTooltip(server);
- console.log(`ACTIVE_SERVERS: Creating server item: ${label} (${description})`);
+ logger.debug(() => `Creating server item: ${label} (${description})`);
// Create command to show server actions on left-click
const command: vscode.Command = {
@@ -164,7 +169,7 @@ export class ActiveServerItemFactory {
participants: ConnectedParticipantSummary[],
): ActiveServerTreeItem[] {
const protocol = server.certMode === 'http' ? 'http' : 'https';
- const lanUrl = `${protocol}://${NetworkUtils.getLocalIPAddress()}:${server.port}`;
+ const lanUrl = NetworkUtils.getPrimaryExternalUrl(server.port, protocol);
const children = [
this.createCommandItem(
'Local network address',
@@ -190,6 +195,17 @@ export class ActiveServerItemFactory {
));
}
+ // #19: what a standalone headset opens, with its QR code.
+ children.push(this.createCommandItem(
+ 'Open on a headset',
+ 'QR code',
+ 'device-mobile',
+ 'codeXR.activeServers.showHeadsetQr',
+ server,
+ 'info-item',
+ 'Show the address a standalone headset (Quest browser...) opens to join this scene, with its QR code.',
+ ));
+
// The cross-network group exists only when the global setting allows it.
// Defensive: a live tunnel is never hidden, even if the setting was
// disabled underneath it.
@@ -242,7 +258,7 @@ export class ActiveServerItemFactory {
return participants.map((participant) => {
const avatar = COLLABORATION_AVATARS.find((candidate) => candidate.id === participant.avatarId);
- const client = participant.clientKind === 'codexr' ? 'CodeXR' : 'Browser';
+ const client = participant.clientKind === 'codexr' ? 'Code-XR' : 'Browser';
const scope = participant.connectionScope === 'remote' ? 'Remote' : 'Local';
const avatarLabel = avatar?.label || participant.avatarId;
return new ActiveServerTreeItem(
@@ -510,7 +526,7 @@ Mode: ${mode}
Port: ${server.port}`;
if (server.htmlFile) {
- const fileName = require('path').basename(server.htmlFile);
+ const fileName = path.basename(server.htmlFile);
tooltip += `\nFile: ${fileName}`;
}
diff --git a/apps/vscode-extension/src/features/active-servers/views/handleServerActions.ts b/apps/vscode-extension/src/features/active-servers/views/handleServerActions.ts
new file mode 100644
index 000000000..35b8cd59d
--- /dev/null
+++ b/apps/vscode-extension/src/features/active-servers/views/handleServerActions.ts
@@ -0,0 +1,633 @@
+import * as vscode from 'vscode';
+import { ActiveServer } from '../../../core/server/registry/activeServerModel';
+import { getActiveServerRegistry } from '../../../core/server/registry/activeServerRegistry';
+import { ServerControl } from '../../../core/server/serverControl';
+import { openServerInBrowser, openServerInPanel } from '../services/serverOpenActions';
+import { withServer } from '../services/withServer';
+import { showHeadsetQrPanel } from '../services/headsetQrPanel';
+import { NetworkUtils } from '../../../core/server/networkUtils';
+import { RemoteAccessManager } from '../../../core/remote-access/remoteAccessManager';
+import { ServerSettingsManager } from '../../../core/server/serverSettingsManager';
+import { COLLABORATION_AVATARS } from '../../../core/collaboration/collaborationProfile';
+import { ConnectedParticipantSummary } from '../../../core/collaboration/connectedParticipant';
+import type { PairingRequestSummary } from '../../../core/remote-access/remoteSessionAuthority';
+import { formatDetailSections, formatDuration } from '../../../platform/ui/detailDialog';
+import {
+ formatPendingRequests,
+ formatRemoteStatus,
+ formatServerDetails,
+ getServerLabel,
+} from './serverDetailsFormat';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('ACTIVE_SERVER');
+
+/** Minimal shape needed to hand out pairing codes; kept structural so the
+ * handler does not depend on the concrete server runtime class. */
+interface PairingAuthority {
+ listPendingPairingRequests(): PairingRequestSummary[];
+ regeneratePairingCode(requestId: string): { code: string; expiresAt: number };
+}
+
+/** Minimal shape of a server runtime that hosts collaboration participants. */
+interface ParticipantHostRuntime {
+ getConnectedParticipants?: () => ConnectedParticipantSummary[];
+ removeParticipant?: (peerId: string) => { removed: boolean; sessionRevoked: boolean };
+}
+
+const REMOVE_PARTICIPANT_ACTION = 'Remove from Session';
+
+/**
+ * Server Action Handlers
+ * Handle user interactions with active servers
+ */
+export class ServerActionHandlers {
+
+ /**
+ * Show server actions quick pick
+ */
+ public static async showServerActions(serverId: string): Promise {
+ logger.debug(() => `Showing actions for server ${serverId}`);
+
+ return withServer(serverId, async (server) => {
+ const actions = this.getAvailableActions(server);
+
+ const selectedAction = await vscode.window.showQuickPick(actions, {
+ placeHolder: `Actions for ${server.url}`,
+ title: `Server Actions - localhost:${server.port}`
+ });
+
+ if (selectedAction) {
+ await this.executeAction(selectedAction.action, server);
+ }
+ });
+ }
+
+ /**
+ * Open server in browser
+ */
+ public static async openInBrowser(serverId: string): Promise {
+ return openServerInBrowser(serverId);
+ }
+
+ /**
+ * Open server in lateral panel
+ */
+ public static async openInPanel(serverId: string): Promise {
+ return openServerInPanel(serverId);
+ }
+
+ /**
+ * Copy server URL to clipboard
+ */
+ public static async copyUrl(serverId: string): Promise {
+ logger.debug(() => `Copying URL for server ${serverId}`);
+
+ return withServer(serverId, async (server) => {
+ try {
+ // Extract port and protocol from server URL
+ const portMatch = server.url.match(/:(\d+)/);
+ const port = portMatch ? parseInt(portMatch[1]) : null;
+ const protocol = server.url.startsWith('https') ? 'https' : 'http';
+
+ const localIP = NetworkUtils.getLocalIPAddress();
+ const hasNetworkAccess = localIP !== 'localhost' && port;
+
+ if (hasNetworkAccess) {
+ // Show options for localhost vs network URL
+ const networkUrl = `${protocol}://${localIP}:${port}`;
+ const choice = await vscode.window.showQuickPick([
+ {
+ label: 'Local URL',
+ description: server.url,
+ detail: 'For use on this computer only'
+ },
+ {
+ label: 'Network URL',
+ description: networkUrl,
+ detail: 'For access from other devices on the network'
+ }
+ ], {
+ placeHolder: 'Choose URL type to copy'
+ });
+
+ if (!choice) {
+ return; // User cancelled
+ }
+
+ const urlToCopy = choice.label.includes('Network') ? networkUrl : server.url;
+ await vscode.env.clipboard.writeText(urlToCopy);
+ logger.debug(() => `Copied ${urlToCopy} to clipboard`);
+ void vscode.window.showInformationMessage(`Copied ${choice.label.includes('Network') ? 'Network' : 'Local'} URL to clipboard`);
+ } else {
+ // Fallback to original behavior if no network access available
+ await vscode.env.clipboard.writeText(server.url);
+ logger.debug(() => `Copied ${server.url} to clipboard`);
+ void vscode.window.showInformationMessage(`Copied ${server.url} to clipboard`);
+ }
+ } catch (error) {
+ logger.error(`Error copying URL to clipboard:`, error);
+ void vscode.window.showErrorMessage('Failed to copy URL to clipboard');
+ }
+ });
+ }
+
+ public static async copyLanUrl(serverId: string): Promise {
+ const server = getActiveServerRegistry().getServer(serverId);
+ if (!server) {
+ void vscode.window.showErrorMessage(`Server not found: ${serverId}`);
+ return;
+ }
+ const protocol = server.url.startsWith('https') ? 'https' : 'http';
+ const lanUrl = NetworkUtils.getPrimaryExternalUrl(server.port, protocol);
+ await vscode.env.clipboard.writeText(lanUrl);
+ void vscode.window.showInformationMessage(`Network address copied: ${lanUrl}`);
+ }
+
+ /** #19: the address a standalone headset opens to join this server's scene, and its QR code. */
+ public static async showHeadsetQr(serverId: string): Promise {
+ return withServer(serverId, async (server) => showHeadsetQrPanel(server));
+ }
+
+ public static async startRemoteAccess(serverId: string): Promise {
+ const manager = this.requireRemoteManager();
+ const state = await manager.startSharing(serverId);
+ if (state.status === 'shared' && state.invitationUrl) {
+ await vscode.env.clipboard.writeText(state.invitationUrl);
+ void vscode.window.showInformationMessage(
+ 'Server shared through Cloudflare. The invitation link has been copied to the clipboard.',
+ );
+ }
+ }
+
+ public static async copyRemoteInvitation(serverId: string): Promise {
+ const manager = this.requireRemoteManager();
+ await manager.copyInvitation(serverId);
+ }
+
+ public static async stopRemoteAccess(serverId: string): Promise {
+ const manager = this.requireRemoteManager();
+ await manager.stopSharing(serverId);
+ }
+
+ /**
+ * Show a modal with the details of one connected participant
+ */
+ public static async showParticipantDetails(serverId: string, peerId: string): Promise {
+ const participant = this.findConnectedParticipant(serverId, peerId);
+
+ if (!participant) {
+ void vscode.window.showInformationMessage('This participant is no longer connected.');
+ return;
+ }
+
+ const avatar = COLLABORATION_AVATARS.find((candidate) => candidate.id === participant.avatarId);
+ const connectedAt = new Date(participant.connectedAt);
+ const connectedFor = Number.isNaN(connectedAt.getTime())
+ ? participant.connectedAt
+ : `${connectedAt.toLocaleTimeString()} · ${formatDuration(Date.now() - connectedAt.getTime())} ago`;
+
+ const detail = formatDetailSections([
+ [
+ ['Name', participant.displayName],
+ ['Role', participant.role === 'host' ? 'Host' : 'Guest'],
+ ['Avatar', avatar?.label || participant.avatarId],
+ ],
+ [
+ ['Client', participant.clientKind === 'codexr' ? 'Code-XR' : 'Browser'],
+ ['Connection', participant.connectionScope === 'remote' ? 'Remote (cross-network)' : 'Local network'],
+ ['IP address', participant.remoteAddress],
+ ['Connected', connectedFor],
+ ],
+ ]);
+
+ // The host cannot remove themselves, so their own row keeps only Close.
+ const actions = participant.role === 'host' ? [] : [REMOVE_PARTICIPANT_ACTION];
+ const choice = await vscode.window.showInformationMessage(
+ `Participant — ${participant.displayName}`,
+ { modal: true, detail },
+ ...actions,
+ );
+
+ if (choice === REMOVE_PARTICIPANT_ACTION) {
+ await this.removeParticipant(serverId, peerId);
+ }
+ }
+
+ /**
+ * Disconnect a participant from the session, after confirmation. A remote
+ * guest also loses their session, so they need a new invitation to return.
+ */
+ public static async removeParticipant(serverId: string, peerId: string): Promise {
+ const participant = this.findConnectedParticipant(serverId, peerId);
+ if (!participant) {
+ void vscode.window.showInformationMessage('This participant is no longer connected.');
+ return;
+ }
+ if (participant.role === 'host') {
+ void vscode.window.showWarningMessage('The host of the session cannot be removed.');
+ return;
+ }
+
+ const isRemote = participant.connectionScope === 'remote';
+ const consequence = isRemote
+ ? 'Their remote session will be revoked: they will need a new invitation and pairing code to join again.'
+ : 'They are on the local network, so they can open the server address again unless you stop the server.';
+ const confirmation = await vscode.window.showWarningMessage(
+ `Remove ${participant.displayName} from the session?`,
+ { modal: true, detail: `${consequence}\n\nThey will see a message explaining they were removed.` },
+ 'Remove',
+ );
+ if (confirmation !== 'Remove') {
+ return;
+ }
+
+ const runtime = this.getParticipantHostRuntime(serverId);
+ if (typeof runtime?.removeParticipant !== 'function') {
+ void vscode.window.showWarningMessage('This server does not support removing participants.');
+ return;
+ }
+
+ const outcome = runtime.removeParticipant(peerId);
+ if (!outcome.removed) {
+ void vscode.window.showInformationMessage(
+ `${participant.displayName} had already left the session.`,
+ );
+ return;
+ }
+
+ void vscode.window.showInformationMessage(
+ outcome.sessionRevoked
+ ? `${participant.displayName} was removed. Their remote session was revoked.`
+ : `${participant.displayName} was removed from the session.`,
+ );
+ }
+
+ /** The remote access manager, or the error every remote action has always thrown without one. */
+ private static requireRemoteManager(): RemoteAccessManager {
+ const manager = RemoteAccessManager.getInstance();
+ if (!manager) {
+ throw new Error('The remote access manager is not initialized.');
+ }
+ return manager;
+ }
+
+ private static getParticipantHostRuntime(serverId: string): ParticipantHostRuntime | undefined {
+ const server = getActiveServerRegistry().getServer(serverId);
+ return server?.serverInstance as ParticipantHostRuntime | undefined;
+ }
+
+ private static findConnectedParticipant(
+ serverId: string,
+ peerId: string,
+ ): ConnectedParticipantSummary | undefined {
+ const runtime = this.getParticipantHostRuntime(serverId);
+ const participants = typeof runtime?.getConnectedParticipants === 'function'
+ ? runtime.getConnectedParticipants()
+ : [];
+ return participants.find((candidate) => candidate.peerId === peerId);
+ }
+
+ /**
+ * Issue a new pairing code for a waiting guest, invalidating the old one
+ */
+ public static async regeneratePairingCode(serverId: string): Promise {
+ const server = getActiveServerRegistry().getServer(serverId);
+ const runtime = server?.serverInstance as
+ | { getRemoteSessionAuthority?: () => PairingAuthority }
+ | undefined;
+ const authority = typeof runtime?.getRemoteSessionAuthority === 'function'
+ ? runtime.getRemoteSessionAuthority()
+ : undefined;
+
+ if (!authority) {
+ void vscode.window.showWarningMessage('This server does not support remote access.');
+ return;
+ }
+
+ const pending = authority.listPendingPairingRequests();
+ if (pending.length === 0) {
+ void vscode.window.showInformationMessage('Nobody is waiting to connect right now.');
+ return;
+ }
+
+ let requestId = pending[0].requestId;
+ if (pending.length > 1) {
+ const selection = await vscode.window.showQuickPick(
+ pending.map((request) => ({
+ label: request.displayName,
+ description: request.remoteAddress,
+ detail: request.codeValid
+ ? 'Waiting for the code'
+ : 'Their code was invalidated by a failed attempt',
+ requestId: request.requestId,
+ })),
+ { title: 'Generate new pairing code', placeHolder: 'Who is trying to connect?' },
+ );
+ if (!selection) {
+ return;
+ }
+ requestId = selection.requestId;
+ }
+
+ // The authority emits a pairing-request event, which drives the toast
+ // that shows the new code to the host.
+ authority.regeneratePairingCode(requestId);
+ }
+
+ public static async showRemoteStatus(serverId: string): Promise {
+ const server = getActiveServerRegistry().getServer(serverId);
+ const state = server?.remoteAccess;
+ const title = server
+ ? `Cross-network connection — ${getServerLabel(server)}`
+ : 'Cross-network connection';
+
+ const detail = state
+ ? formatDetailSections([
+ [
+ ['Status', formatRemoteStatus(state, false)],
+ ['Pending', state.status === 'shared'
+ ? formatPendingRequests(state.pendingRequests)
+ : undefined],
+ ],
+ [
+ ['Invitation', state.invitationUrl],
+ ['Public URL', state.publicUrl],
+ ],
+ [
+ ['Error', state.error],
+ ],
+ ])
+ : formatDetailSections([[['Status', 'Not shared']]]);
+
+ await vscode.window.showInformationMessage(title, { modal: true, detail });
+ }
+
+ /**
+ * Stop server
+ */
+ public static async stopServer(serverId: string): Promise {
+ logger.debug(() => `Stopping server ${serverId}`);
+
+ return withServer(serverId, async (server) => {
+ const response = await vscode.window.showWarningMessage(
+ `Stop server ${server.url}?`,
+ 'Stop',
+ 'Cancel'
+ );
+
+ if (response === 'Stop') {
+ try {
+ await RemoteAccessManager.getInstance()?.stopSharing(serverId, false);
+ logger.debug(() => `Stopping server ${serverId} (${server.url})`);
+ const success = await ServerControl.stopServer(serverId);
+
+ if (success) {
+ logger.debug(() => `Successfully stopped server ${serverId}`);
+ void vscode.window.showInformationMessage(`Stopped server ${server.url}`);
+
+ // Refresh the tree view
+ void vscode.commands.executeCommand('codeXR.activeServers.refreshServers');
+ } else {
+ logger.error(`Failed to stop server ${serverId}`);
+ void vscode.window.showErrorMessage(`Failed to stop server ${server.url}`);
+ }
+ } catch (error) {
+ logger.error(`Error stopping server ${serverId}:`, error);
+ void vscode.window.showErrorMessage(
+ `Error stopping server: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+ } else {
+ logger.debug(() => `User cancelled stopping server ${serverId}`);
+ }
+ });
+ }
+
+ /**
+ * Show detailed server information
+ */
+ public static async showServerDetails(serverId: string): Promise {
+ logger.debug(() => `Showing details for server ${serverId}`);
+
+ return withServer(serverId, async (server) => {
+ const details = formatServerDetails(server);
+
+ logger.debug(() => `Displaying detailed information for server ${serverId}`);
+ await vscode.window.showInformationMessage(
+ `Server Information — ${getServerLabel(server)}`,
+ { modal: true, detail: details }
+ );
+ });
+ }
+
+ /**
+ * Stop all servers
+ */
+ public static async stopAllServers(): Promise {
+ logger.debug('Stopping all servers');
+
+ // Count what "Stop all" will actually stop: the running servers. The
+ // prompt used to count every entry, whatever its status.
+ const registry = getActiveServerRegistry();
+ const runningCount = registry.getServersByStatus('running').length;
+
+ if (runningCount === 0) {
+ void vscode.window.showInformationMessage('No servers are currently running');
+ return;
+ }
+
+ const response = await vscode.window.showWarningMessage(
+ `Stop all ${runningCount} server(s)?`,
+ 'Stop All',
+ 'Cancel'
+ );
+
+ if (response === 'Stop All') {
+ try {
+ await RemoteAccessManager.getInstance()?.stopAll();
+ logger.debug(() => `Stopping ${runningCount} servers`);
+ const { requested, stopped } = await ServerControl.stopAllServers();
+
+ if (stopped === requested) {
+ logger.debug('Successfully stopped all servers');
+ void vscode.window.showInformationMessage(`Stopped ${stopped} server(s)`);
+ } else {
+ logger.error(`Stopped ${stopped} of ${requested} servers`);
+ void vscode.window.showWarningMessage(
+ `Stopped ${stopped} of ${requested} server(s). The others were removed from the list but did not shut down cleanly; see the Code-XR output.`
+ );
+ }
+
+ // Refresh the tree view
+ void vscode.commands.executeCommand('codeXR.activeServers.refreshServers');
+ } catch (error) {
+ logger.error('Error stopping all servers:', error);
+ void vscode.window.showErrorMessage(
+ `Error stopping servers: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+ } else {
+ logger.debug('User cancelled stopping all servers');
+ }
+ }
+
+ /**
+ * Refresh servers display
+ */
+ public static async refreshServers(): Promise {
+ logger.debug('Refreshing servers display');
+ void vscode.commands.executeCommand('codeXR.activeServers.refreshServers');
+ }
+
+ /**
+ * Get available actions for a server based on its type
+ * @private
+ */
+ private static getAvailableActions(server: ActiveServer): Array<{
+ label: string;
+ description: string;
+ action: string;
+ }> {
+ const isHttp = server.certMode === 'http';
+
+ const actions = [
+ {
+ label: 'Open in Browser',
+ description: 'Open server in external browser',
+ action: 'openInBrowser'
+ }
+ ];
+
+ if (this.isRemoteAccessRelevant(server)) {
+ this.appendRemoteActions(actions, server);
+ }
+
+ // Add lateral panel option only for HTTP servers
+ if (isHttp) {
+ actions.push({
+ label: 'Open in Panel',
+ description: 'Open server in VS Code lateral panel',
+ action: 'openInPanel'
+ });
+ }
+
+ actions.push(
+ {
+ label: 'Copy URL',
+ description: 'Copy server URL to clipboard',
+ action: 'copyUrl'
+ },
+ {
+ label: 'Server Info',
+ description: 'Show detailed server information',
+ action: 'showDetails'
+ },
+ {
+ label: 'Stop Server',
+ description: 'Stop this server',
+ action: 'stopServer'
+ }
+ );
+
+ return actions;
+ }
+
+ /**
+ * Mirror of the tree rule: remote entries appear only when the global
+ * cross-network setting is enabled, or a tunnel is already active.
+ */
+ private static isRemoteAccessRelevant(server: ActiveServer): boolean {
+ const status = server.remoteAccess?.status || 'stopped';
+ if (status !== 'stopped') {
+ return true;
+ }
+ try {
+ return ServerSettingsManager.getInstance().getServerSettings().remoteAccess.enabled;
+ } catch {
+ return false;
+ }
+ }
+
+ /**
+ * Append the remote-access QuickPick entries for the server's tunnel state
+ */
+ private static appendRemoteActions(
+ actions: Array<{ label: string; description: string; action: string }>,
+ server: ActiveServer,
+ ): void {
+ if (server.remoteAccess?.status === 'shared' || server.remoteAccess?.status === 'starting') {
+ actions.push(
+ {
+ label: 'Copy remote invitation',
+ description: 'Copy the protected temporary link',
+ action: 'copyRemoteInvitation',
+ },
+ {
+ label: 'Remote status',
+ description: 'View pending requests and tunnel status',
+ action: 'remoteStatus',
+ },
+ {
+ label: 'Stop remote connection',
+ description: 'Close the tunnel and revoke the remote sessions',
+ action: 'stopRemoteAccess',
+ },
+ );
+ } else {
+ actions.push({
+ label: 'Start remote connection',
+ description: 'Publish temporarily through a Cloudflare Quick Tunnel',
+ action: 'startRemoteAccess',
+ });
+ if (server.remoteAccess?.status === 'error') {
+ actions.push({
+ label: 'View remote error',
+ description: server.remoteAccess.error || 'Tunnel error',
+ action: 'remoteStatus',
+ });
+ }
+ }
+ }
+
+ /**
+ * Execute an action on a server
+ * @private
+ */
+ private static async executeAction(action: string, server: ActiveServer): Promise {
+ logger.debug(() => `Executing action '${action}' on server ${server.id}`);
+
+ switch (action) {
+ case 'openInBrowser':
+ await this.openInBrowser(server.id);
+ break;
+ case 'openInPanel':
+ await this.openInPanel(server.id);
+ break;
+ case 'copyUrl':
+ await this.copyUrl(server.id);
+ break;
+ case 'showDetails':
+ await this.showServerDetails(server.id);
+ break;
+ case 'startRemoteAccess':
+ await this.startRemoteAccess(server.id);
+ break;
+ case 'copyRemoteInvitation':
+ await this.copyRemoteInvitation(server.id);
+ break;
+ case 'remoteStatus':
+ await this.showRemoteStatus(server.id);
+ break;
+ case 'stopRemoteAccess':
+ await this.stopRemoteAccess(server.id);
+ break;
+ case 'stopServer':
+ await this.stopServer(server.id);
+ break;
+ default:
+ logger.error(`Unknown action: ${action}`);
+ void vscode.window.showErrorMessage(`Unknown action: ${action}`);
+ }
+ }
+}
diff --git a/apps/vscode-extension/src/features/active-servers/views/launchNotifications.ts b/apps/vscode-extension/src/features/active-servers/views/launchNotifications.ts
new file mode 100644
index 000000000..809577f0d
--- /dev/null
+++ b/apps/vscode-extension/src/features/active-servers/views/launchNotifications.ts
@@ -0,0 +1,155 @@
+import * as vscode from 'vscode';
+import type { ServerSettings } from '../../../core/server/serverSettingsManager';
+import type { LaunchMode } from '../../../core/server/registry/activeServerModel';
+import { openServerInBrowser, openServerInPanel } from '../services/serverOpenActions';
+import { NetworkUtils } from '../../../core/server/networkUtils';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('SERVER');
+
+/*
+ * What the user sees around a MultiServerLauncher launch: the HTTPS-to-HTTP
+ * override warning for the lateral panel, the busy-port notice, the
+ * auto-open (or the "Open Now" / "Copy Network URL" toast when auto-open is
+ * off) and the retry toast when auto-open fails.
+ * Kept out of servers/runtime/ so the launcher holds no UI.
+ */
+
+/**
+ * HTTPS was overridden to HTTP because the lateral panel cannot show HTTPS
+ * content: say so, and offer to switch the open mode to the browser.
+ */
+export function warnHttpsOverriddenForPanel(): void {
+ // Show non-blocking warning to user with actionable information
+ void vscode.window.showWarningMessage(
+ 'Launching in HTTP mode due to VS Code limitations: lateral panel views do not support HTTPS content. Use browser mode to preserve HTTPS.',
+ 'Change to Browser Mode'
+ ).then(action => {
+ if (action === 'Change to Browser Mode') {
+ // Open the configuration to change open mode
+ void vscode.commands.executeCommand('codexr.server.config.openMode');
+ }
+ });
+}
+
+/**
+ * Tell the user the configured port was busy and which one is used instead.
+ */
+export function notifyPortChanged(requestedPort: number, finalPort: number): void {
+ void vscode.window.showInformationMessage(
+ `Port ${requestedPort} was busy, launching server on port ${finalPort} instead.`
+ );
+}
+
+/**
+ * Handle auto-opening based on configuration
+ */
+export async function handleAutoOpening(
+ settings: ServerSettings,
+ serverUrl: string,
+ _htmlFile: string | undefined,
+ launchMode: LaunchMode,
+ activeServerId: string
+): Promise {
+ const isAutoOpenEnabled = settings.launch.autoOpen;
+
+ logger.debug(() => `Auto-open configuration: enabled=${isAutoOpenEnabled}, mode=${launchMode}`);
+
+ if (!isAutoOpenEnabled) {
+ logger.debug('Auto-open is disabled, showing success notification only');
+
+ // Extract port from serverUrl to generate network URLs
+ const portMatch = serverUrl.match(/:(\d+)/);
+ const port = portMatch ? parseInt(portMatch[1]) : null;
+ const protocol = serverUrl.startsWith('https') ? 'https' : 'http';
+
+ let notificationMessage = `Server launched successfully on ${serverUrl}`;
+
+ // Add network access information if port is available
+ if (port) {
+ const localIP = NetworkUtils.getLocalIPAddress();
+ if (localIP !== 'localhost') {
+ const networkUrl = `${protocol}://${localIP}:${port}`;
+ notificationMessage = `Server launched successfully! Network: ${networkUrl} Local: ${serverUrl}`;
+ logger.debug(() => `Network access URL: ${networkUrl}`);
+ }
+ }
+
+ void vscode.window.showInformationMessage(
+ notificationMessage,
+ 'Open Now', 'Copy Network URL'
+ ).then(action => {
+ if (action === 'Open Now') {
+ // Use the active server action handler to respect the configured mode
+ if (launchMode === 'browser') {
+ void openLaunchedServerInBrowser(activeServerId);
+ } else {
+ void openLaunchedServerInPanel(activeServerId);
+ }
+ } else if (action === 'Copy Network URL' && port) {
+ const localIP = NetworkUtils.getLocalIPAddress();
+ if (localIP !== 'localhost') {
+ const networkUrl = `${protocol}://${localIP}:${port}`;
+ void vscode.env.clipboard.writeText(networkUrl);
+ void vscode.window.showInformationMessage('Network URL copied to clipboard');
+ }
+ }
+ });
+ return;
+ }
+
+ logger.debug(() => `Auto-opening server in ${launchMode} mode`);
+
+ try {
+ // Auto-open using the configured launch mode
+ if (launchMode === 'browser') {
+ await openLaunchedServerInBrowser(activeServerId);
+ } else {
+ await openLaunchedServerInPanel(activeServerId);
+ }
+ } catch (error) {
+ logger.error('Error during auto-opening:', error);
+ void vscode.window.showWarningMessage(
+ `Server launched but failed to auto-open: ${error instanceof Error ? error.message : String(error)}`,
+ 'Open Manually'
+ ).then(action => {
+ if (action === 'Open Manually') {
+ if (launchMode === 'browser') {
+ void openLaunchedServerInBrowser(activeServerId);
+ } else {
+ void openLaunchedServerInPanel(activeServerId);
+ }
+ }
+ });
+ }
+}
+
+// 1.3.0: the toast callbacks above start these two helpers with `void`, but
+// they log and rethrow, so a failed open there is an unhandled rejection;
+// await and report it instead. The "Copy Network URL" action likewise
+// confirms the copy without awaiting clipboard.writeText.
+/**
+ * Open server in browser using shared handler
+ */
+async function openLaunchedServerInBrowser(activeServerId: string): Promise {
+ logger.debug(() => `Opening server ${activeServerId} in browser via shared handler`);
+ try {
+ await openServerInBrowser(activeServerId);
+ } catch (error) {
+ logger.error(`Failed to open server in browser: ${error}`);
+ throw error;
+ }
+}
+
+/**
+ * Open server in lateral panel using shared handler
+ */
+async function openLaunchedServerInPanel(activeServerId: string): Promise {
+ logger.debug(() => `Opening server ${activeServerId} in lateral panel via shared handler`);
+ try {
+ await openServerInPanel(activeServerId);
+ } catch (error) {
+ logger.error(`Failed to open server in lateral panel: ${error}`);
+ throw error;
+ }
+}
diff --git a/apps/vscode-extension/src/features/active-servers/views/serverDetailsFormat.ts b/apps/vscode-extension/src/features/active-servers/views/serverDetailsFormat.ts
new file mode 100644
index 000000000..4136cf9ed
--- /dev/null
+++ b/apps/vscode-extension/src/features/active-servers/views/serverDetailsFormat.ts
@@ -0,0 +1,102 @@
+import * as path from 'path';
+import type { ActiveServer } from '../../../core/server/registry/activeServerModel';
+import { NetworkUtils } from '../../../core/server/networkUtils';
+import { formatDetailSections, formatDuration } from '../../../platform/ui/detailDialog';
+
+/*
+ * The text of the server dialogs: the "Server Information" detail, the
+ * remote-status lines and the dialog titles. Pure formatting over an
+ * ActiveServer; ServerActionHandlers shows it.
+ */
+
+/** Friendly server name used as dialog titles. */
+export function getServerLabel(server: ActiveServer): string {
+ return server.customName?.trim() || `localhost:${server.port}`;
+}
+
+/**
+ * Format server details for display
+ */
+export function formatServerDetails(server: ActiveServer): string {
+ const metadata = (server.metadata ?? {}) as Record;
+ const remote = server.remoteAccess;
+ const protocol = server.certMode === 'http' ? 'http' : 'https';
+ const lanUrl = NetworkUtils.getPrimaryExternalUrl(server.port, protocol);
+
+ return formatDetailSections([
+ [
+ ['Status', `${formatServerStatus(server)} · up ${formatDuration(Date.now() - server.timestamp)}`],
+ ['Address', server.url],
+ ['Network', lanUrl],
+ ['Port', String(server.port)],
+ ['Security', formatCertMode(server.certMode)],
+ ['Mode', server.launchMode === 'browser' ? 'Browser' : 'Panel'],
+ ],
+ [
+ ['Serving', server.htmlFile ? path.basename(server.htmlFile) : undefined],
+ ['Folder', shortenPath(String(metadata.staticRoot || ''))],
+ ['Type', metadata.serverType ? String(metadata.serverType) : undefined],
+ ['Details', metadata.description ? String(metadata.description) : undefined],
+ ],
+ [
+ ['Cross-network', remote && remote.status !== 'stopped'
+ ? formatRemoteStatus(remote)
+ : undefined],
+ ['Invitation', remote?.invitationUrl],
+ ],
+ ]);
+}
+
+function formatServerStatus(server: ActiveServer): string {
+ return server.status.charAt(0).toUpperCase() + server.status.slice(1);
+}
+
+function formatCertMode(certMode: ActiveServer['certMode']): string {
+ switch (certMode) {
+ case 'https-default':
+ return 'HTTPS (self-signed)';
+ case 'https-custom':
+ return 'HTTPS (custom certificate)';
+ default:
+ return 'HTTP';
+ }
+}
+
+export function formatRemoteStatus(
+ state: NonNullable,
+ withPending = true,
+): string {
+ if (state.status === 'error') {
+ return `Error · ${state.error || 'tunnel failed'}`;
+ }
+ if (state.status === 'starting') {
+ return 'Starting...';
+ }
+ if (state.status === 'shared') {
+ return withPending && state.pendingRequests > 0
+ ? `Shared · ${formatPendingRequests(state.pendingRequests)}`
+ : 'Shared';
+ }
+ return 'Not shared';
+}
+
+export function formatPendingRequests(count: number): string {
+ if (count === 0) {
+ return 'None';
+ }
+ return count === 1 ? '1 request waiting' : `${count} requests waiting`;
+}
+
+/**
+ * Keep long paths readable: leading segments collapse into an ellipsis.
+ */
+function shortenPath(value: string, keepSegments = 2): string | undefined {
+ if (!value) {
+ return undefined;
+ }
+ const segments = value.split(/[\\/]/).filter(Boolean);
+ if (segments.length <= keepSegments) {
+ return value;
+ }
+ return `…${path.sep}${segments.slice(-keepSegments).join(path.sep)}`;
+}
diff --git a/apps/vscode-extension/src/features/ai-agents/views/AiAgentsSectionProvider.ts b/apps/vscode-extension/src/features/ai-agents/views/AiAgentsSectionProvider.ts
new file mode 100644
index 000000000..7689a16fb
--- /dev/null
+++ b/apps/vscode-extension/src/features/ai-agents/views/AiAgentsSectionProvider.ts
@@ -0,0 +1,27 @@
+import * as vscode from 'vscode';
+import { BaseSectionProvider } from '../../../platform/tree/baseInterfaces';
+import { AI_AGENTS_TOOLTIP, AiAgentsTreeItem, createComingSoonItem } from './aiAgentsItems';
+
+/** The AI AGENTS section: a "coming soon" placeholder in 1.2.1. */
+export class AiAgentsSectionProvider extends BaseSectionProvider {
+ getSectionName(): string {
+ return 'aiAgents';
+ }
+
+ getSectionItem(): AiAgentsTreeItem {
+ return new AiAgentsTreeItem(
+ 'AI AGENTS',
+ vscode.TreeItemCollapsibleState.Collapsed,
+ 'coming-soon',
+ undefined,
+ new vscode.ThemeIcon('sparkle'),
+ AI_AGENTS_TOOLTIP,
+ 'Coming soon',
+ 'aiAgentsSection',
+ );
+ }
+
+ async getChildren(element?: AiAgentsTreeItem): Promise {
+ return element ? [] : [createComingSoonItem()];
+ }
+}
diff --git a/apps/vscode-extension/src/features/ai-agents/views/aiAgentsItems.ts b/apps/vscode-extension/src/features/ai-agents/views/aiAgentsItems.ts
new file mode 100644
index 000000000..23516bbdd
--- /dev/null
+++ b/apps/vscode-extension/src/features/ai-agents/views/aiAgentsItems.ts
@@ -0,0 +1,50 @@
+import * as vscode from 'vscode';
+
+/**
+ * Rows of the AI AGENTS section. In 1.2.1 the section is a placeholder that
+ * only says the feature is coming (epic #189, stories #214-#216): it offers
+ * no command and makes no network call.
+ */
+export type AiAgentsItemType = 'coming-soon';
+
+/** The positional arguments ModularTreeDataProvider's section adapter passes. */
+type AiAgentsItemArgs = [
+ label: string,
+ collapsibleState: vscode.TreeItemCollapsibleState,
+ aiAgentsItemType: AiAgentsItemType,
+ command?: vscode.Command,
+ iconPath?: vscode.ThemeIcon | vscode.Uri,
+ tooltip?: string,
+ description?: string,
+ contextValue?: string,
+];
+
+export class AiAgentsTreeItem extends vscode.TreeItem {
+ public readonly aiAgentsItemType: AiAgentsItemType;
+
+ constructor(...[label, collapsibleState, aiAgentsItemType, command, iconPath, tooltip, description, contextValue]: AiAgentsItemArgs) {
+ super(label, collapsibleState);
+ this.aiAgentsItemType = aiAgentsItemType;
+ this.command = command;
+ this.iconPath = iconPath;
+ this.tooltip = tooltip ?? label;
+ this.description = description;
+ this.contextValue = contextValue;
+ }
+}
+
+export const AI_AGENTS_TOOLTIP = 'Chat with AI agents about your code and its Code-XR analyses, with your own provider keys. Coming soon.';
+
+/** The section's only row. */
+export function createComingSoonItem(): AiAgentsTreeItem {
+ return new AiAgentsTreeItem(
+ 'AI agents are coming soon',
+ vscode.TreeItemCollapsibleState.None,
+ 'coming-soon',
+ undefined,
+ new vscode.ThemeIcon('sparkle'),
+ AI_AGENTS_TOOLTIP,
+ undefined,
+ 'codeXR.aiAgents.comingSoon',
+ );
+}
diff --git a/apps/vscode-extension/src/features/analysis/commands/analysisCommandRegistrations.ts b/apps/vscode-extension/src/features/analysis/commands/analysisCommandRegistrations.ts
new file mode 100644
index 000000000..5164f0ad1
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/commands/analysisCommandRegistrations.ts
@@ -0,0 +1,85 @@
+/**
+ * Analysis Commands Registration
+ * Converts analysis registrations to the shared command format.
+ */
+import * as vscode from 'vscode';
+import { CodeAnalysisCommands } from './analysisCommands';
+import { ExtensionCommandRegistration } from '../../../platform/commands/commandRegistry';
+import { getRevealInSceneRegistrations } from './revealInSceneCommand';
+
+const LAST_ANALYSIS_STORAGE_KEY = 'codeXR.analysis.lastKind';
+const LAST_ANALYSIS_CONTEXT_KEY = 'codeXR.analysis.lastKind';
+const DEFAULT_LAST_ANALYSIS_KIND = 'analyzeProjectXRDeep';
+
+const ANALYSIS_ACTIONS = [
+ { kind: 'analyzeFile', commandId: 'codeXR.analysis.analyzeFile' },
+ { kind: 'analyzeFileXR', commandId: 'codeXR.analysis.analyzeFileXR' },
+ { kind: 'analyzeDirectory', commandId: 'codeXR.analysis.analyzeDirectory' },
+ { kind: 'analyzeDirectoryDeep', commandId: 'codeXR.analysis.analyzeDirectoryDeep' },
+ { kind: 'analyzeDirectoryXR', commandId: 'codeXR.analysis.analyzeDirectoryXR' },
+ { kind: 'analyzeDirectoryXRDeep', commandId: 'codeXR.analysis.analyzeDirectoryXRDeep' },
+ { kind: 'analyzeProject', commandId: 'codeXR.analysis.analyzeProject' },
+ { kind: 'analyzeProjectDeep', commandId: 'codeXR.analysis.analyzeProjectDeep' },
+ { kind: 'analyzeProjectXR', commandId: 'codeXR.analysis.analyzeProjectXR' },
+ { kind: 'analyzeProjectXRDeep', commandId: 'codeXR.analysis.analyzeProjectXRDeep' },
+ { kind: 'visualizeDOM', commandId: 'codeXR.analysis.visualizeDOM' },
+] as const;
+
+const ANALYSIS_ACTION_BY_KIND = new Map(ANALYSIS_ACTIONS.map((action) => [action.kind, action.commandId]));
+const ANALYSIS_KIND_BY_COMMAND = new Map(ANALYSIS_ACTIONS.map((action) => [action.commandId, action.kind]));
+
+async function setLastAnalysisKind(context: vscode.ExtensionContext, kind: string): Promise {
+ const normalizedKind = ANALYSIS_ACTION_BY_KIND.has(kind as any) ? kind : DEFAULT_LAST_ANALYSIS_KIND;
+ await context.globalState.update(LAST_ANALYSIS_STORAGE_KEY, normalizedKind);
+ await vscode.commands.executeCommand('setContext', LAST_ANALYSIS_CONTEXT_KEY, normalizedKind);
+}
+
+function getLastAnalysisKind(context: vscode.ExtensionContext): string {
+ const stored = context.globalState.get(LAST_ANALYSIS_STORAGE_KEY);
+ return stored && ANALYSIS_ACTION_BY_KIND.has(stored as any) ? stored : DEFAULT_LAST_ANALYSIS_KIND;
+}
+
+function createRunLastRegistrations(context: vscode.ExtensionContext): ExtensionCommandRegistration[] {
+ void vscode.commands.executeCommand('setContext', LAST_ANALYSIS_CONTEXT_KEY, getLastAnalysisKind(context));
+ return ANALYSIS_ACTIONS.map((action) => ({
+ id: `codeXR.analysis.runLast.${action.kind}`,
+ module: 'ANALYSIS',
+ description: `Run last analysis (${action.kind})`,
+ handler: async (...args: any[]) => {
+ const targetKind = getLastAnalysisKind(context);
+ const targetCommandId = ANALYSIS_ACTION_BY_KIND.get(targetKind as any)
+ || ANALYSIS_ACTION_BY_KIND.get(DEFAULT_LAST_ANALYSIS_KIND);
+ if (!targetCommandId) {
+ throw new Error('No Code-XR analysis command is available to run.');
+ }
+ await vscode.commands.executeCommand(targetCommandId, ...args);
+ },
+ errorMessage: 'Failed to run last Code-XR analysis',
+ }));
+}
+
+export function getAnalysisCommandRegistrations(
+ context: vscode.ExtensionContext,
+ refreshCallback?: () => void,
+): ExtensionCommandRegistration[] {
+ const registrations = CodeAnalysisCommands.getCommandRegistrations(context, refreshCallback).map((registration) => ({
+ id: registration.commandId,
+ module: registration.module ?? 'ANALYSIS',
+ description: registration.description,
+ handler: async (...args: any[]) => {
+ const lastKind = ANALYSIS_KIND_BY_COMMAND.get(registration.commandId);
+ await registration.callback(...args);
+ if (lastKind) {
+ await setLastAnalysisKind(context, lastKind);
+ }
+ },
+ errorMessage: registration.errorMessage,
+ silentErrors: registration.silentErrors,
+ }));
+ return [
+ ...registrations,
+ ...createRunLastRegistrations(context),
+ ...getRevealInSceneRegistrations(context),
+ ];
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/commands/analysisCommands.ts b/apps/vscode-extension/src/features/analysis/commands/analysisCommands.ts
new file mode 100644
index 000000000..75cb1f928
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/commands/analysisCommands.ts
@@ -0,0 +1,83 @@
+/**
+ * New Code Analysis Commands
+ * Command metadata collector for the new analysis module.
+ */
+
+import * as vscode from 'vscode';
+import { AnalysisSettingsCommands } from '../sections/settings/analysisSettingsCommands';
+import { ActiveAnalysesCommandRegistrations } from '../sections/active-analyses/activeAnalysesCommandRegistrations';
+import { ProjectByLanguageCommands } from '../sections/project-by-language/projectByLanguageCommands';
+import { FilesByLanguageCommands } from '../sections/files-by-language/filesByLanguageCommands';
+import { FileAnalysisCommands } from './file/fileAnalysisCommands';
+import { DirectoryAnalysisCommands } from './directory/directoryAnalysisCommands';
+import { ProjectAnalysisCommands } from './directory/projectAnalysisCommands';
+import { DOMVisualizationCommands } from './dom/domVisualizationCommands';
+import { CommandRegistration } from '../sections/settings/analysis-file-mode/analysisFileModeCommands';
+import { AnalysisFileSetting } from '../sections/settings/analysis-file-mode/analysisFileMode';
+import { AnalysisDirectorySetting } from '../sections/settings/analysis-directory-mode/analysisDirectoryMode';
+import { ViewThemeSetting } from '../sections/settings/view-theme/viewTheme';
+import { AutoAnalysisDelaySetting } from '../sections/settings/auto-analysis-delay/autoAnalysisDelay';
+import { AutoAnalysisEnabledSetting } from '../sections/settings/auto-analysis-enabled/autoAnalysisEnabled';
+import { ChartTypeFileSetting } from '../sections/settings/chart-type-file/chartTypeFile';
+import { ChartTypeDirectorySetting } from '../sections/settings/chart-type-directory/chartTypeDirectory';
+import { DimensionMappingFileSetting } from '../sections/settings/dimension-mapping-file/dimensionMappingFile';
+import { DimensionMappingDirectorySetting } from '../sections/settings/dimension-mapping-directory/dimensionMappingDirectory';
+import { FilesByLanguageSortingSetting } from '../sections/settings/files-by-language-sorting/filesByLanguageSorting';
+import { ProfileConfigurationSetting } from '../sections/settings/profile-configuration/profileConfiguration';
+import { AnalysisConfigurationStorage } from '../../../core/analysis/configuration/analysisConfigurationStorage';
+import { getLogger } from '../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
+
+export class CodeAnalysisCommands {
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ refreshCallback?: () => void,
+ ): CommandRegistration[] {
+ logger.debug('Collecting all command registrations');
+
+ const defaultRefreshCallback = refreshCallback ?? (() => {
+ logger.debug('Default refresh callback executed');
+ });
+
+ const tempAnalysisFileSetting = new AnalysisFileSetting(context);
+ const tempAnalysisDirectorySetting = new AnalysisDirectorySetting(context);
+ const tempViewThemeSetting = new ViewThemeSetting(context);
+ const tempAutoAnalysisDelaySetting = new AutoAnalysisDelaySetting(context);
+ const tempAutoAnalysisEnabledSetting = new AutoAnalysisEnabledSetting(context);
+ const tempChartTypeFileSetting = new ChartTypeFileSetting(context);
+ const tempChartTypeDirectorySetting = new ChartTypeDirectorySetting(context);
+ const tempDimensionMappingFileSetting = new DimensionMappingFileSetting(context);
+ const tempDimensionMappingDirectorySetting = new DimensionMappingDirectorySetting(context);
+ const tempFilesByLanguageSortingSetting = new FilesByLanguageSortingSetting(context);
+ const storage = AnalysisConfigurationStorage.getInstance(context);
+ const tempProfileConfigurationSetting = new ProfileConfigurationSetting(context, storage);
+
+ const registrations: CommandRegistration[] = [];
+ registrations.push(...AnalysisSettingsCommands.getCommandRegistrations(
+ context,
+ tempAnalysisFileSetting,
+ tempAnalysisDirectorySetting,
+ tempViewThemeSetting,
+ tempAutoAnalysisDelaySetting,
+ tempAutoAnalysisEnabledSetting,
+ tempChartTypeFileSetting,
+ tempChartTypeDirectorySetting,
+ tempDimensionMappingFileSetting,
+ tempDimensionMappingDirectorySetting,
+ tempFilesByLanguageSortingSetting,
+ tempProfileConfigurationSetting,
+ defaultRefreshCallback,
+ ));
+ registrations.push(...ActiveAnalysesCommandRegistrations.getCommandRegistrations(context, defaultRefreshCallback));
+ registrations.push(...ProjectByLanguageCommands.getCommandRegistrations(context, defaultRefreshCallback));
+ registrations.push(...FilesByLanguageCommands.getCommandRegistrations(context));
+ registrations.push(...FileAnalysisCommands.getCommandRegistrations(context));
+ registrations.push(...DirectoryAnalysisCommands.getCommandRegistrations(context));
+ registrations.push(...ProjectAnalysisCommands.getCommandRegistrations(context));
+ registrations.push(...DOMVisualizationCommands.getCommandRegistrations(context, defaultRefreshCallback));
+
+ return registrations;
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/commands/cleanAnalysisCommands.ts b/apps/vscode-extension/src/features/analysis/commands/cleanAnalysisCommands.ts
new file mode 100644
index 000000000..b179a5196
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/commands/cleanAnalysisCommands.ts
@@ -0,0 +1,97 @@
+/**
+ * Clean Analysis
+ * Startup cleanup of stale analysis files in workspace storage (run from extension.ts)
+ */
+
+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');
+
+export class CleanAnalysisCommands {
+
+ /**
+ * Execute cleanup of stale analysis files on plugin startup.
+ */
+ static async executeStartupCleanup(context: vscode.ExtensionContext, activationStartedAt: number): Promise {
+ try {
+ await CleanAnalysisCommands.cleanStaleAnalysisArtifacts(context, activationStartedAt);
+ } catch (error) {
+ logger.warn('Startup cleanup failed.', error);
+ }
+ }
+
+ /**
+ * 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 {
+ 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);
+ }
+
+ this.removeDirectoryIfEmpty(analysisPath);
+ } catch (error) {
+ logger.warn(`Error cleaning startup analysis artifacts in ${folderName}.`, error);
+ clean = false;
+ }
+ }
+ return clean;
+ }
+
+ private static async deletePathRecursive(targetPath: string): Promise {
+ if (!fs.existsSync(targetPath)) {
+ return;
+ }
+
+ const stat = fs.statSync(targetPath);
+ if (!stat.isDirectory()) {
+ fs.unlinkSync(targetPath);
+ return;
+ }
+
+ const files = fs.readdirSync(targetPath);
+ for (const file of files) {
+ await this.deletePathRecursive(path.join(targetPath, file));
+ }
+
+ fs.rmdirSync(targetPath);
+ }
+
+ private static removeDirectoryIfEmpty(dirPath: string): void {
+ if (!fs.existsSync(dirPath)) {
+ return;
+ }
+
+ if (fs.readdirSync(dirPath).length === 0) {
+ fs.rmdirSync(dirPath);
+ }
+ }
+}
+
diff --git a/src/code_analysis/commands/directory_analysis/directoryAnalysisCommands.ts b/apps/vscode-extension/src/features/analysis/commands/directory/directoryAnalysisCommands.ts
similarity index 85%
rename from src/code_analysis/commands/directory_analysis/directoryAnalysisCommands.ts
rename to apps/vscode-extension/src/features/analysis/commands/directory/directoryAnalysisCommands.ts
index e4eabf119..3a6a12278 100644
--- a/src/code_analysis/commands/directory_analysis/directoryAnalysisCommands.ts
+++ b/apps/vscode-extension/src/features/analysis/commands/directory/directoryAnalysisCommands.ts
@@ -6,7 +6,7 @@
import * as vscode from 'vscode';
import { DirectoryAnalysisLivePanelCommands } from './directoryAnalysisLivePanelCommands';
import { DirectoryAnalysisXRCommands } from './directoryAnalysisXRCommands';
-import { CommandRegistration } from '../subsections/analysis_settings/analysis_file_mode';
+import { CommandRegistration } from '../../sections/settings/analysis-file-mode/analysisFileModeCommands';
export class DirectoryAnalysisCommands {
static getCommandRegistrations(context: vscode.ExtensionContext): CommandRegistration[] {
diff --git a/apps/vscode-extension/src/features/analysis/commands/directory/directoryAnalysisLivePanelCommands.ts b/apps/vscode-extension/src/features/analysis/commands/directory/directoryAnalysisLivePanelCommands.ts
new file mode 100644
index 000000000..4ddf4a8ac
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/commands/directory/directoryAnalysisLivePanelCommands.ts
@@ -0,0 +1,111 @@
+/**
+ * Directory Analysis LivePanel Commands
+ * Commands for analyzing directories in LivePanel mode.
+ */
+
+import * as path from 'path';
+import * as vscode from 'vscode';
+import { AnalysisOrchestrator } from '../../../../core/analysis/analysisOrchestrator';
+import { CommandRegistration } from '../../sections/settings/analysis-file-mode/analysisFileModeCommands';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('DIRECTORY_ANALYSIS_LIVEPANEL_COMMANDS');
+
+export class DirectoryAnalysisLivePanelCommands {
+ constructor(private context: vscode.ExtensionContext) {}
+
+ static getCommandRegistrations(context: vscode.ExtensionContext): CommandRegistration[] {
+ const commands = new DirectoryAnalysisLivePanelCommands(context);
+ return [
+ {
+ commandId: 'codeXR.analysis.analyzeDirectory',
+ callback: (uri?: vscode.Uri) => commands.analyzeDirectoryLivePanel(uri),
+ description: 'Analyze directory in LivePanel mode',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to analyze directory in LivePanel mode'
+ },
+ {
+ commandId: 'codeXR.analysis.analyzeDirectoryDeep',
+ callback: (uri?: vscode.Uri) => commands.analyzeDirectoryLivePanelDeep(uri),
+ description: 'Analyze directory in LivePanel deep mode',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to analyze directory in LivePanel deep mode'
+ }
+ ];
+ }
+
+ private async analyzeDirectoryLivePanel(uri?: vscode.Uri): Promise {
+ try {
+ let directoryPath: string;
+
+ if (uri) {
+ if (uri.scheme !== 'file') {
+ void vscode.window.showWarningMessage('Code-XR: Invalid URI for directory analysis');
+ return;
+ }
+
+ const stat = await vscode.workspace.fs.stat(uri);
+ if (stat.type === vscode.FileType.Directory) {
+ directoryPath = uri.fsPath;
+ } else {
+ directoryPath = path.dirname(uri.fsPath);
+ }
+ } else if (vscode.workspace.workspaceFolders?.length) {
+ if (vscode.workspace.workspaceFolders.length === 1) {
+ directoryPath = vscode.workspace.workspaceFolders[0].uri.fsPath;
+ } else {
+ const picked = await vscode.window.showWorkspaceFolderPick();
+ if (!picked) {
+ return;
+ }
+ directoryPath = picked.uri.fsPath;
+ }
+ } else {
+ const activeEditor = vscode.window.activeTextEditor;
+ if (!activeEditor) {
+ void vscode.window.showWarningMessage('Code-XR: No directory selected for LivePanel analysis');
+ return;
+ }
+ directoryPath = path.dirname(activeEditor.document.fileName);
+ }
+
+ await AnalysisOrchestrator.orchestrateAnalysis(directoryPath, 'LivePanel', 'directory', this.context, false);
+ } catch (error) {
+ logger.error('Error in LivePanel analyze directory command:', error);
+ void vscode.window.showErrorMessage(`Code-XR: Directory LivePanel analysis failed - ${error}`);
+ }
+ }
+
+ private async analyzeDirectoryLivePanelDeep(uri?: vscode.Uri): Promise {
+ try {
+ let directoryPath: string;
+
+ if (uri) {
+ if (uri.scheme !== 'file') {
+ void vscode.window.showErrorMessage('Code-XR: Invalid directory URI for LivePanel Deep analysis');
+ return;
+ }
+
+ const stat = await vscode.workspace.fs.stat(uri);
+ directoryPath = stat.type === vscode.FileType.Directory
+ ? uri.fsPath
+ : path.dirname(uri.fsPath);
+ } else if (vscode.workspace.workspaceFolders?.length) {
+ directoryPath = vscode.workspace.workspaceFolders[0].uri.fsPath;
+ } else {
+ const activeEditor = vscode.window.activeTextEditor;
+ if (!activeEditor) {
+ void vscode.window.showWarningMessage('Code-XR: No directory selected for LivePanel Deep analysis');
+ return;
+ }
+ directoryPath = path.dirname(activeEditor.document.fileName);
+ }
+
+ await AnalysisOrchestrator.orchestrateAnalysis(directoryPath, 'LivePanel', 'directory', this.context, true);
+ } catch (error) {
+ logger.error('Error in LivePanel Deep analyze directory command:', error);
+ void vscode.window.showErrorMessage(`Code-XR: Directory LivePanel Deep analysis failed - ${error}`);
+ }
+ }
+}
+
diff --git a/src/code_analysis/commands/directory_analysis/directoryAnalysisXRCommands.ts b/apps/vscode-extension/src/features/analysis/commands/directory/directoryAnalysisXRCommands.ts
similarity index 86%
rename from src/code_analysis/commands/directory_analysis/directoryAnalysisXRCommands.ts
rename to apps/vscode-extension/src/features/analysis/commands/directory/directoryAnalysisXRCommands.ts
index 7e260fc1d..5adfafb32 100644
--- a/src/code_analysis/commands/directory_analysis/directoryAnalysisXRCommands.ts
+++ b/apps/vscode-extension/src/features/analysis/commands/directory/directoryAnalysisXRCommands.ts
@@ -4,8 +4,11 @@
*/
import * as vscode from 'vscode';
-import { AnalysisOrchestrator } from '../../engine/analysisOrchestrator';
-import { CommandRegistration } from '../subsections/analysis_settings/analysis_file_mode';
+import { AnalysisOrchestrator } from '../../../../core/analysis/analysisOrchestrator';
+import { CommandRegistration } from '../../sections/settings/analysis-file-mode/analysisFileModeCommands';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('DIRECTORY_ANALYSIS_XR_COMMANDS');
export class DirectoryAnalysisXRCommands {
constructor(private context: vscode.ExtensionContext) {}
@@ -53,8 +56,8 @@ export class DirectoryAnalysisXRCommands {
await AnalysisOrchestrator.orchestrateAnalysis(directoryPath, 'XR', 'directory', this.context, false);
} catch (error) {
- console.error('DIRECTORY_ANALYSIS_XR_COMMANDS: Error in analyzeDirectoryXR:', error);
- vscode.window.showErrorMessage(
+ logger.error('Error in analyzeDirectoryXR:', error);
+ void vscode.window.showErrorMessage(
`Failed to start directory XR analysis: ${error instanceof Error ? error.message : String(error)}`,
);
}
@@ -69,8 +72,8 @@ export class DirectoryAnalysisXRCommands {
await AnalysisOrchestrator.orchestrateAnalysis(directoryPath, 'XR', 'directory', this.context, true);
} catch (error) {
- console.error('DIRECTORY_ANALYSIS_XR_COMMANDS: Error in analyzeDirectoryXRDeep:', error);
- vscode.window.showErrorMessage(
+ logger.error('Error in analyzeDirectoryXRDeep:', error);
+ void vscode.window.showErrorMessage(
`Failed to start directory XR Deep analysis: ${error instanceof Error ? error.message : String(error)}`,
);
}
@@ -97,7 +100,7 @@ export class DirectoryAnalysisXRCommands {
private async resolveDirectoryPath(uri: vscode.Uri | undefined, dialogLabel: string): Promise {
if (uri) {
if (uri.scheme !== 'file') {
- vscode.window.showErrorMessage('Invalid file path for directory analysis');
+ void vscode.window.showErrorMessage('Invalid file path for directory analysis');
return undefined;
}
@@ -120,7 +123,7 @@ export class DirectoryAnalysisXRCommands {
private async resolveProjectPath(placeHolder: string): Promise {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders || workspaceFolders.length === 0) {
- vscode.window.showErrorMessage('No workspace folder found. Please open a project folder first.');
+ void vscode.window.showErrorMessage('No workspace folder found. Please open a project folder first.');
return undefined;
}
diff --git a/src/code_analysis/commands/directory_analysis/projectAnalysisCommands.ts b/apps/vscode-extension/src/features/analysis/commands/directory/projectAnalysisCommands.ts
similarity index 93%
rename from src/code_analysis/commands/directory_analysis/projectAnalysisCommands.ts
rename to apps/vscode-extension/src/features/analysis/commands/directory/projectAnalysisCommands.ts
index 5e6d788c6..fa80693aa 100644
--- a/src/code_analysis/commands/directory_analysis/projectAnalysisCommands.ts
+++ b/apps/vscode-extension/src/features/analysis/commands/directory/projectAnalysisCommands.ts
@@ -4,8 +4,8 @@
*/
import * as vscode from 'vscode';
-import { AnalysisOrchestrator } from '../../engine/analysisOrchestrator';
-import { CommandRegistration } from '../subsections/analysis_settings/analysis_file_mode';
+import { AnalysisOrchestrator } from '../../../../core/analysis/analysisOrchestrator';
+import { CommandRegistration } from '../../sections/settings/analysis-file-mode/analysisFileModeCommands';
export class ProjectAnalysisCommands {
constructor(private context: vscode.ExtensionContext) {}
@@ -65,7 +65,7 @@ export class ProjectAnalysisCommands {
private async pickWorkspaceFolder(placeHolder: string): Promise {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders || workspaceFolders.length === 0) {
- vscode.window.showErrorMessage(
+ void vscode.window.showErrorMessage(
'No workspace is currently open. Please open a project folder to analyze.',
);
return undefined;
diff --git a/apps/vscode-extension/src/features/analysis/commands/dom/domVisualizationCommands.ts b/apps/vscode-extension/src/features/analysis/commands/dom/domVisualizationCommands.ts
new file mode 100644
index 000000000..6941a998a
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/commands/dom/domVisualizationCommands.ts
@@ -0,0 +1,56 @@
+/**
+ * DOM Visualization Commands
+ * Handles commands for visualizing HTML DOM structure.
+ */
+
+import * as vscode from 'vscode';
+import { AnalysisOrchestrator } from '../../../../core/analysis/analysisOrchestrator';
+import { LauncherVisualizeDOM } from '../../../../core/analysis/launchers/launcherVisualizeDOM';
+import { CommandRegistration } from '../../sections/settings/analysis-file-mode/analysisFileModeCommands';
+import { getFileSystemPathFromEditorOrInput } from './uriPathConverter';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('DOM_VISUALIZATION_COMMANDS');
+
+export class DOMVisualizationCommands {
+ constructor(private context: vscode.ExtensionContext) {}
+
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ _refreshCallback?: () => void,
+ ): CommandRegistration[] {
+ const domVisualizationInstance = new DOMVisualizationCommands(context);
+ return [
+ {
+ commandId: 'codeXR.analysis.visualizeDOM',
+ callback: (filePath?: unknown) => domVisualizationInstance.visualizeDOM(filePath),
+ description: 'Visualize HTML DOM structure',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to visualize HTML DOM structure'
+ }
+ ];
+ }
+
+ async visualizeDOM(filePath?: unknown): Promise {
+ try {
+ const fsPath = getFileSystemPathFromEditorOrInput(filePath);
+ if (!fsPath) {
+ void vscode.window.showErrorMessage('No HTML file selected or file path could not be determined');
+ return;
+ }
+
+ if (!LauncherVisualizeDOM.canVisualizeFile(fsPath)) {
+ void vscode.window.showWarningMessage(`File "${fsPath}" is not a supported HTML file for DOM visualization`);
+ return;
+ }
+
+ await AnalysisOrchestrator.orchestrateAnalysis(fsPath, 'VisualizeDOM', 'file', this.context, false);
+ } catch (error) {
+ logger.error('Error visualizing DOM:', error);
+ void vscode.window.showErrorMessage(
+ `Failed to visualize DOM: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/commands/dom/uriPathConverter.ts b/apps/vscode-extension/src/features/analysis/commands/dom/uriPathConverter.ts
new file mode 100644
index 000000000..b24cbc2ad
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/commands/dom/uriPathConverter.ts
@@ -0,0 +1,137 @@
+/**
+ * URI Path Converter Utility
+ * Handles conversion between VS Code URIs and file system paths
+ */
+
+import * as vscode from 'vscode';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('URI_PATH_CONVERTER');
+
+function isUriString(value: string): boolean {
+ return value.startsWith('file://') || value.startsWith('vscode-');
+}
+
+function isObjectInput(input: unknown): input is Record {
+ return !!input && typeof input === 'object';
+}
+
+/**
+ * One way of reading a path out of a command argument: the path, or `null`
+ * when the input is not of that shape. An empty string is a result, not a miss.
+ */
+type UriResolver = (input: unknown) => string | null;
+
+/** A string: a URI string is parsed, anything else is already a path. */
+const fromStringInput: UriResolver = (input) => {
+ if (typeof input !== 'string') {
+ return null;
+ }
+ if (isUriString(input)) {
+ const uri = vscode.Uri.parse(input);
+ logger.debug('Converted URI string to path:', uri.fsPath);
+ return uri.fsPath;
+ }
+ logger.debug('Input is already a file system path:', input);
+ return input;
+};
+
+/** A VS Code Uri, or anything carrying a string fsPath. */
+const fromFsPathProperty: UriResolver = (input) => {
+ if (!isObjectInput(input) || !('fsPath' in input) || typeof input.fsPath !== 'string') {
+ return null;
+ }
+ logger.debug('Extracted fsPath from URI object:', input.fsPath);
+ return input.fsPath;
+};
+
+/** A URI-like object with scheme and path. */
+const fromSchemeAndPath: UriResolver = (input) => {
+ if (!isObjectInput(input) || !('scheme' in input) || !('path' in input)) {
+ return null;
+ }
+ const uri = vscode.Uri.from(input as unknown as { scheme: string; path: string });
+ logger.debug('Created URI from object and extracted path:', uri.fsPath);
+ return uri.fsPath;
+};
+
+/** Any other object whose string form is a URI string. */
+const fromStringifiedObject: UriResolver = (input) => {
+ if (!isObjectInput(input)) {
+ return null;
+ }
+ const stringified = String(input);
+ if (!isUriString(stringified)) {
+ return null;
+ }
+ const uri = vscode.Uri.parse(stringified);
+ logger.debug('Converted stringified object to path:', uri.fsPath);
+ return uri.fsPath;
+};
+
+/** Tried in this order; the first non-null result wins. */
+const URI_RESOLVERS: readonly UriResolver[] = [
+ fromStringInput,
+ fromFsPathProperty,
+ fromSchemeAndPath,
+ fromStringifiedObject,
+];
+
+/**
+ * Convert VS Code URI or file path to a standard file system path
+ * Handles various input types that VS Code commands can receive
+ */
+export function convertToFileSystemPath(input: unknown): string | null {
+ try {
+ // Handle null/undefined
+ if (!input) {
+ return null;
+ }
+
+ logger.debug(() => `Processing input (${typeof input})`, input);
+
+ for (const resolve of URI_RESOLVERS) {
+ const resolved = resolve(input);
+ if (resolved !== null) {
+ return resolved;
+ }
+ }
+
+ logger.warn('Could not convert input to file system path:', input);
+ return null;
+
+ } catch (error) {
+ logger.error('Error converting input to file system path:', error);
+ return null;
+ }
+}
+
+/**
+ * Get file system path from active editor or provided input
+ */
+export function getFileSystemPathFromEditorOrInput(input?: any): string | null {
+ try {
+ // First try to convert the provided input
+ if (input) {
+ const convertedPath = convertToFileSystemPath(input);
+ if (convertedPath) {
+ return convertedPath;
+ }
+ }
+
+ // Fallback to active editor
+ const activeEditor = vscode.window.activeTextEditor;
+ if (activeEditor) {
+ const editorPath = activeEditor.document.uri.fsPath;
+ logger.debug('Using active editor path:', editorPath);
+ return editorPath;
+ }
+
+ logger.warn('No valid file path found from input or active editor');
+ return null;
+
+ } catch (error) {
+ logger.error('Error getting file system path:', error);
+ return null;
+ }
+}
diff --git a/src/code_analysis/commands/file_analysis/fileAnalysisCommands.ts b/apps/vscode-extension/src/features/analysis/commands/file/fileAnalysisCommands.ts
similarity index 84%
rename from src/code_analysis/commands/file_analysis/fileAnalysisCommands.ts
rename to apps/vscode-extension/src/features/analysis/commands/file/fileAnalysisCommands.ts
index b16191d92..1a772f2c1 100644
--- a/src/code_analysis/commands/file_analysis/fileAnalysisCommands.ts
+++ b/apps/vscode-extension/src/features/analysis/commands/file/fileAnalysisCommands.ts
@@ -6,7 +6,7 @@
import * as vscode from 'vscode';
import { FileAnalysisLivePanelCommands } from './fileAnalysisLivePanelCommands';
import { FileAnalysisXRCommands } from './fileAnalysisXRCommands';
-import { CommandRegistration } from '../subsections/analysis_settings/analysis_file_mode';
+import { CommandRegistration } from '../../sections/settings/analysis-file-mode/analysisFileModeCommands';
export class FileAnalysisCommands {
static getCommandRegistrations(context: vscode.ExtensionContext): CommandRegistration[] {
diff --git a/apps/vscode-extension/src/features/analysis/commands/file/fileAnalysisLivePanelCommands.ts b/apps/vscode-extension/src/features/analysis/commands/file/fileAnalysisLivePanelCommands.ts
new file mode 100644
index 000000000..7f756dd97
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/commands/file/fileAnalysisLivePanelCommands.ts
@@ -0,0 +1,53 @@
+/**
+ * File Analysis LivePanel Commands
+ * Commands for analyzing individual files in LivePanel mode.
+ */
+
+import * as vscode from 'vscode';
+import { AnalysisOrchestrator } from '../../../../core/analysis/analysisOrchestrator';
+import { CommandRegistration } from '../../sections/settings/analysis-file-mode/analysisFileModeCommands';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('FILE_ANALYSIS_LIVEPANEL_COMMANDS');
+
+export class FileAnalysisLivePanelCommands {
+ constructor(private context: vscode.ExtensionContext) {}
+
+ static getCommandRegistrations(context: vscode.ExtensionContext): CommandRegistration[] {
+ const commands = new FileAnalysisLivePanelCommands(context);
+ return [
+ {
+ commandId: 'codeXR.analysis.analyzeFile',
+ callback: (uri?: vscode.Uri) => commands.analyzeFileLivePanel(uri),
+ description: 'Analyze file in LivePanel mode',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to analyze file in LivePanel mode'
+ }
+ ];
+ }
+
+ private async analyzeFileLivePanel(uri?: vscode.Uri): Promise {
+ try {
+ let filePath: string;
+
+ if (uri) {
+ filePath = uri.fsPath;
+ logger.debug(() => `LivePanel analysis requested from context menu for: ${filePath}`);
+ } else {
+ const activeEditor = vscode.window.activeTextEditor;
+ if (!activeEditor) {
+ void vscode.window.showWarningMessage('Code-XR: No file selected for LivePanel analysis');
+ return;
+ }
+ filePath = activeEditor.document.fileName;
+ logger.debug(() => `LivePanel analysis requested from command palette for: ${filePath}`);
+ }
+
+ await AnalysisOrchestrator.orchestrateAnalysis(filePath, 'LivePanel', 'file', this.context, false);
+ } catch (error) {
+ logger.error('Error in LivePanel analyze file command:', error);
+ void vscode.window.showErrorMessage(`Code-XR: LivePanel analysis failed - ${error}`);
+ }
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/commands/file/fileAnalysisXRCommands.ts b/apps/vscode-extension/src/features/analysis/commands/file/fileAnalysisXRCommands.ts
new file mode 100644
index 000000000..ffa7316ab
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/commands/file/fileAnalysisXRCommands.ts
@@ -0,0 +1,61 @@
+/**
+ * File Analysis XR Commands
+ * Commands for analyzing individual files in XR mode.
+ */
+
+import * as vscode from 'vscode';
+import * as path from 'path';
+import { getLanguageForFile } from '../../../../core/analysis/languages/languageMetadata';
+import { AnalysisOrchestrator } from '../../../../core/analysis/analysisOrchestrator';
+import { CommandRegistration } from '../../sections/settings/analysis-file-mode/analysisFileModeCommands';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('FILE_ANALYSIS_XR_COMMANDS');
+
+export class FileAnalysisXRCommands {
+ constructor(private context: vscode.ExtensionContext) {}
+
+ static getCommandRegistrations(context: vscode.ExtensionContext): CommandRegistration[] {
+ const commands = new FileAnalysisXRCommands(context);
+ return [
+ {
+ commandId: 'codeXR.analysis.analyzeFileXR',
+ callback: (uri?: vscode.Uri) => commands.analyzeFileXR(uri),
+ description: 'Analyze file in XR mode',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to analyze file in XR mode'
+ }
+ ];
+ }
+
+ private async analyzeFileXR(uri?: vscode.Uri): Promise {
+ try {
+ let filePath: string;
+
+ if (uri) {
+ filePath = uri.fsPath;
+ } else {
+ const activeEditor = vscode.window.activeTextEditor;
+ if (!activeEditor) {
+ void vscode.window.showWarningMessage('Code-XR: No file selected for XR analysis');
+ return;
+ }
+ filePath = activeEditor.document.fileName;
+ }
+
+ const languageInfo = getLanguageForFile(filePath);
+ if (!languageInfo) {
+ void vscode.window.showWarningMessage(
+ `Code-XR: File "${path.basename(filePath)}" - Language not supported for XR analysis`,
+ );
+ return;
+ }
+
+ await AnalysisOrchestrator.orchestrateAnalysis(filePath, 'XR', 'file', this.context, false);
+ } catch (error) {
+ logger.error('Error in XR file analysis:', error);
+ void vscode.window.showErrorMessage(`Code-XR: XR analysis failed - ${error}`);
+ }
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/commands/revealInSceneCommand.ts b/apps/vscode-extension/src/features/analysis/commands/revealInSceneCommand.ts
new file mode 100644
index 000000000..379c724f0
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/commands/revealInSceneCommand.ts
@@ -0,0 +1,42 @@
+/**
+ * #178: "CodeXR: Reveal in XR Scene" in the VS Code extension. The editor, its
+ * tab and the explorer offer it on a file while an analysis server runs; the
+ * core (core/server/analysis/sceneReveal.ts, shared with the Code-XR IDE)
+ * asks every running scene whose analysed folder holds the file to mark it.
+ */
+import * as vscode from 'vscode';
+import { revealInScene } from '../../../core/server/analysis/sceneReveal';
+import { getActiveServerRegistry } from '../../../core/server/registry/activeServerRegistry';
+import { ExtensionCommandRegistration } from '../../../platform/commands/commandRegistry';
+
+export const REVEAL_IN_SCENE_COMMAND = 'codeXR.analysis.revealInScene';
+/** True while an analysis server runs: the menus offer the command only then. */
+const SCENE_RUNNING_CONTEXT_KEY = 'codeXR.analysis.sceneRunning';
+
+export const NO_SCENE_MESSAGE = 'No running Code-XR scene shows this file. Start an XR analysis of a folder that holds it.';
+
+function targetPath(resource: unknown): string | undefined {
+ const uri = resource instanceof vscode.Uri ? resource : vscode.window.activeTextEditor?.document.uri;
+ return uri?.scheme === 'file' ? uri.fsPath : undefined;
+}
+
+function publishSceneRunning(): void {
+ void vscode.commands.executeCommand('setContext', SCENE_RUNNING_CONTEXT_KEY, getActiveServerRegistry().getRunningServerCount() > 0);
+}
+
+export function getRevealInSceneRegistrations(context: vscode.ExtensionContext): ExtensionCommandRegistration[] {
+ publishSceneRunning();
+ context.subscriptions.push(getActiveServerRegistry().onRegistryChange(publishSceneRunning));
+ return [{
+ id: REVEAL_IN_SCENE_COMMAND,
+ module: 'ANALYSIS',
+ description: 'Mark a file in the running XR scenes',
+ handler: async (resource?: unknown) => {
+ const file = targetPath(resource);
+ if (!file || revealInScene(file) === 0) {
+ void vscode.window.showInformationMessage(NO_SCENE_MESSAGE);
+ }
+ },
+ errorMessage: 'Failed to reveal the file in the XR scene',
+ }];
+}
diff --git a/apps/vscode-extension/src/features/analysis/sections/active-analyses/activeAnalysesCommandRegistrations.ts b/apps/vscode-extension/src/features/analysis/sections/active-analyses/activeAnalysesCommandRegistrations.ts
new file mode 100644
index 000000000..84352fceb
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/active-analyses/activeAnalysesCommandRegistrations.ts
@@ -0,0 +1,33 @@
+/**
+ * Active Analyses Commands
+ * Commands specific to the Active Analyses subsection.
+ */
+
+import * as vscode from 'vscode';
+import { CommandRegistration } from '../settings/analysis-file-mode/analysisFileModeCommands';
+import { UnifiedSessionRegistry } from '../../../../core/analysis/session/sessionRegistry';
+import { ServerWatcherIntegration } from '../../services/serverWatcherIntegration';
+import { ActiveAnalysesCommands as ActiveAnalysesViewCommands } from './activeAnalysesCommands';
+
+export class ActiveAnalysesCommandRegistrations {
+ constructor(_context: vscode.ExtensionContext) {}
+
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ _refreshCallback: () => void,
+ ): CommandRegistration[] {
+ const sessionRegistry = UnifiedSessionRegistry.getInstance(context);
+ const serverWatcher = ServerWatcherIntegration.getInstance(context);
+ // This is the canonical command-registration path and therefore the
+ // first caller in normal extension activation. Pass the context here,
+ // rather than hoping the tree provider initializes the singleton
+ // later: the current AnalysisSectionProvider reads Active Analyses
+ // directly and does not construct that legacy subsection provider.
+ const viewCommands = ActiveAnalysesViewCommands.getInstance(
+ sessionRegistry,
+ serverWatcher,
+ context,
+ );
+ return viewCommands.getCommandRegistrations();
+ }
+}
diff --git a/apps/vscode-extension/src/features/analysis/sections/active-analyses/activeAnalysesCommands.ts b/apps/vscode-extension/src/features/analysis/sections/active-analyses/activeAnalysesCommands.ts
new file mode 100644
index 000000000..a1bd911ca
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/active-analyses/activeAnalysesCommands.ts
@@ -0,0 +1,802 @@
+/**
+ * Active Analyses Commands
+ * Handles command registration metadata and execution for active analysis operations.
+ */
+
+import * as vscode from 'vscode';
+import * as fs from 'fs';
+import * as path from 'path';
+import { UnifiedAnalysisSession } from '../../../../core/analysis/session/analysisSession';
+import { UnifiedSessionRegistry } from '../../../../core/analysis/session/sessionRegistry';
+import { ServerWatcherIntegration } from '../../services/serverWatcherIntegration';
+import { ActiveAnalysesDataService } from './activeAnalysesDataService';
+import { CommandRegistration } from '../settings/analysis-file-mode/analysisFileModeCommands';
+import { analysisRefreshCoordinator } from '../../../../core/analysis/refresh/analysisRefreshCoordinator';
+import {
+ AnalysisServerCapabilities,
+ resolveAnalysisServerCapabilities,
+} from '../../../../core/server/analysisServerCapabilities';
+import {
+ buildExportManifest,
+ configureOfflineExportHtml,
+ isXrSceneFolder,
+ refreshRuntimeCopies,
+ relativizeExportArtifacts,
+ writeExportReadme,
+} from '../../../../core/export/exportManifest';
+import { buildExportModeItems, ExportSelection, interpretExportSelection } from '../../../../core/export/exportModeSelection';
+import {
+ exportGitRevisionData,
+ inspectGitRevisionExport,
+} from '../../../../core/export/gitRevisionExporter';
+import { GitExportOutcome } from '../../../../core/export/gitRevisionExportCore';
+import {
+ calculateGitExportWorkerPlan,
+ GitExportPerformanceProfile,
+ GitRevisionExportRequest,
+ GitRevisionScope,
+ validateGitRevisionScope,
+} from '../../../../core/export/gitExportOptions';
+import {
+ abortExportPackage,
+ beginExportPackageTransaction,
+ ExportPackageTransaction,
+ pruneExportPackage,
+ publishExportPackage,
+ validateExportPackage,
+} from '../../../../core/export/exportPackageTransaction';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('ACTIVE_ANALYSES_COMMANDS');
+
+/** The id-bearing fields extractSessionId looks for on a command argument. */
+interface SessionIdCarrier {
+ session?: { id?: string };
+ sessionId?: string;
+ id?: string;
+}
+
+/**
+ * What an Active Analyses command receives: a session id, the data item
+ * (an ActiveAnalysisItem fits SessionIdCarrier), the TreeItem tagged with the
+ * session fields, or a wrapper holding the data item as originalAnalysisItem.
+ */
+type ActiveAnalysisCommandArg =
+ | string
+ | (SessionIdCarrier & { originalAnalysisItem?: SessionIdCarrier });
+
+/** The Git steps of the export wizard: a request to run, or the wizard stops. */
+type GitExportPrompt =
+ | { kind: 'cancelled' }
+ | { kind: 'request'; request: GitRevisionExportRequest };
+
+/** What the wizard decided; gitExportRequest is set exactly when selection.gitTimeline is. */
+interface ExportPlan {
+ sourcePath: string;
+ destinationPath: string;
+ selection: ExportSelection;
+ capabilities: AnalysisServerCapabilities;
+ gitExportRequest: GitRevisionExportRequest | undefined;
+}
+
+class ExportCancelledError extends Error {
+ public constructor() {
+ super('export-cancelled');
+ }
+}
+
+export class ActiveAnalysesCommands {
+ private static instance: ActiveAnalysesCommands;
+ private commands: CommandRegistration[];
+
+ private constructor(
+ private sessionRegistry: UnifiedSessionRegistry,
+ private serverWatcher: ServerWatcherIntegration,
+ private readonly extensionContext: vscode.ExtensionContext,
+ ) {
+ this.commands = [
+ {
+ commandId: 'codeXR.analysis.activeAnalyses.showActions',
+ description: 'Show active analysis actions',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to show active analysis actions',
+ callback: this.showActions.bind(this),
+ },
+ {
+ commandId: 'codeXR.analysis.activeAnalyses.showDetails',
+ description: 'Show analysis details',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to show analysis details',
+ callback: this.showDetails.bind(this),
+ },
+ {
+ commandId: 'codeXR.analysis.activeAnalyses.close',
+ description: 'Close analysis',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to close analysis',
+ callback: this.closeAnalysis.bind(this),
+ },
+ {
+ commandId: 'codeXR.analysis.activeAnalyses.viewInBrowser',
+ description: 'Open analysis in browser',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to open analysis in browser',
+ callback: this.viewInBrowser.bind(this),
+ },
+ {
+ commandId: 'codeXR.analysis.activeAnalyses.exportFolder',
+ description: 'Export analysis folder',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to export analysis folder',
+ callback: this.exportFolder.bind(this),
+ },
+ {
+ commandId: 'codeXR.analysis.activeAnalyses.refresh',
+ description: 'Refresh active analyses',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to refresh active analyses',
+ callback: this.refreshAnalyses.bind(this),
+ },
+ ];
+ }
+
+ public static getInstance(
+ sessionRegistry?: UnifiedSessionRegistry,
+ serverWatcher?: ServerWatcherIntegration,
+ extensionContext?: vscode.ExtensionContext,
+ ): ActiveAnalysesCommands {
+ if (!ActiveAnalysesCommands.instance) {
+ if (!sessionRegistry || !serverWatcher || !extensionContext) {
+ throw new Error(
+ 'SessionRegistry, ServerWatcher, and ExtensionContext are required for first initialization',
+ );
+ }
+ ActiveAnalysesCommands.instance = new ActiveAnalysesCommands(
+ sessionRegistry, serverWatcher, extensionContext,
+ );
+ }
+ return ActiveAnalysesCommands.instance;
+ }
+
+ public getCommandRegistrations(): CommandRegistration[] {
+ return [...this.commands];
+ }
+
+ private async showActions(arg?: ActiveAnalysisCommandArg): Promise {
+ const selected = this.resolveSelectedSession(arg);
+ if (!selected) {
+ return;
+ }
+ const { sessionId, session } = selected;
+
+ const exportSourcePath = this.resolveExportSourcePath(session);
+ const quickPickItems: Array = [
+ {
+ label: 'View Details',
+ description: 'Open the analysis session details in a markdown document',
+ action: 'details',
+ },
+ ];
+
+ if (session.serverUrl || session.assignedPort) {
+ quickPickItems.push({
+ label: 'Open in Browser',
+ description: 'Open the active analysis in your default browser',
+ action: 'browser',
+ });
+ }
+
+ if (exportSourcePath) {
+ quickPickItems.push({
+ label: 'Export Analysis Folder',
+ description: 'Copy the generated analysis files to a folder you choose',
+ action: 'export',
+ });
+ }
+
+ if (session.status !== 'closed') {
+ quickPickItems.push({
+ label: 'Close Analysis',
+ description: 'Stop the analysis server and remove the session',
+ action: 'close',
+ });
+ }
+
+ const targetLabel = path.basename(session.targetPath || session.targetName || 'Unknown');
+ const selectedAction = await vscode.window.showQuickPick(quickPickItems, {
+ placeHolder: `Choose an action for ${targetLabel}`,
+ title: `Active Analysis Actions - ${targetLabel}`,
+ });
+
+ if (!selectedAction) {
+ return;
+ }
+
+ switch (selectedAction.action) {
+ case 'details':
+ await this.showDetails(sessionId);
+ return;
+ case 'browser':
+ await this.viewInBrowser(sessionId);
+ return;
+ case 'export':
+ await this.exportFolder(sessionId);
+ return;
+ case 'close':
+ await this.closeAnalysis(sessionId);
+ return;
+ }
+ }
+
+ private async showDetails(arg?: ActiveAnalysisCommandArg): Promise {
+ const selected = this.resolveSelectedSession(arg);
+ if (!selected) {
+ return;
+ }
+ const { session } = selected;
+
+ const detailsContent = this.generateDetailsContent(session);
+ const doc = await vscode.workspace.openTextDocument({
+ content: detailsContent,
+ language: 'markdown',
+ });
+ await vscode.window.showTextDocument(doc);
+ }
+
+ private async closeAnalysis(arg?: ActiveAnalysisCommandArg): Promise {
+ const selected = this.resolveSelectedSession(arg);
+ if (!selected) {
+ return;
+ }
+ const { sessionId, session } = selected;
+
+ const targetLabel = path.basename(session.targetPath || session.targetName || 'Unknown');
+ const choice = await vscode.window.showWarningMessage(
+ `Close analysis for "${targetLabel}"?`,
+ {
+ modal: true,
+ detail: `This will stop the analysis server, stop any active watchers, and remove the session from Active Analyses.\n\nTarget: ${session.targetPath || session.targetName || 'Unknown'}\nType: ${session.targetType || 'Unknown'}\nMode: ${session.analysisMode || 'Unknown'}\nStatus: ${session.status || 'Unknown'}\nOutput: ${session.savedFilesPath || session.outputPath || 'Not available'}\n\nExport the analysis folder first if you want to keep the generated artifacts for debugging.`,
+ },
+ 'Close Analysis',
+ 'Cancel',
+ );
+
+ if (choice !== 'Close Analysis') {
+ return;
+ }
+
+ const cleanupSuccess = await this.serverWatcher.triggerManualCleanup(sessionId);
+ const removed = this.sessionRegistry.removeSession(sessionId);
+ await vscode.commands.executeCommand('codeXR.analysis.activeAnalyses.refresh');
+
+ if (cleanupSuccess && removed) {
+ void vscode.window.showInformationMessage('Analysis closed successfully');
+ return;
+ }
+
+ if (!cleanupSuccess && removed) {
+ void vscode.window.showWarningMessage(
+ 'Analysis was removed from Active Analyses, but server or watcher cleanup may not have completed fully.',
+ );
+ return;
+ }
+
+ if (cleanupSuccess && !removed) {
+ void vscode.window.showWarningMessage(
+ 'Analysis resources were cleaned up, but the session entry could not be removed from Active Analyses.',
+ );
+ return;
+ }
+
+ void vscode.window.showErrorMessage('Failed to close the analysis session cleanly');
+ }
+
+ private async viewInBrowser(arg?: ActiveAnalysisCommandArg): Promise {
+ const selected = this.resolveSelectedSession(arg);
+ if (!selected) {
+ return;
+ }
+ const { session } = selected;
+
+ if (!session.serverUrl && !session.assignedPort) {
+ void vscode.window.showErrorMessage('No server URL available for this analysis');
+ return;
+ }
+
+ const url = session.serverUrl || `http://localhost:${session.assignedPort}`;
+ if (!url) {
+ void vscode.window.showErrorMessage('Could not determine server URL for this analysis');
+ return;
+ }
+
+ await vscode.env.openExternal(vscode.Uri.parse(url));
+ }
+
+ private async exportFolder(arg?: ActiveAnalysisCommandArg): Promise {
+ const selected = this.resolveSelectedSession(arg);
+ if (!selected) {
+ return;
+ }
+ const { session } = selected;
+
+ const sourcePath = this.resolveExportSourcePath(session);
+ if (!sourcePath) {
+ void vscode.window.showErrorMessage('No analysis output folder is available to export');
+ return;
+ }
+
+ // The modal comes first: what goes into the copy decides how long the
+ // export takes, so the user chooses before picking a destination.
+ const capabilities = resolveAnalysisServerCapabilities(session.analysisMode);
+ const selection = interpretExportSelection(await vscode.window.showQuickPick(
+ buildExportModeItems(capabilities),
+ {
+ canPickMany: true,
+ title: 'Export Analysis Folder: choose the analyses to include',
+ placeHolder: 'Normal is always included; the git analyses pre-compute the whole timeline',
+ },
+ ));
+ if (selection.cancelled) {
+ return;
+ }
+
+ let gitExportRequest: GitRevisionExportRequest | undefined;
+ if (selection.gitTimeline) {
+ const gitPrompt = await this.promptGitExportRequest(session, selection);
+ if (gitPrompt.kind === 'cancelled') {
+ return;
+ }
+ gitExportRequest = gitPrompt.request;
+ }
+
+ const destinationPath = await this.chooseExportDestination(session, sourcePath);
+ if (!destinationPath) {
+ return;
+ }
+ await this.writeExportPackage(session, {
+ sourcePath,
+ destinationPath,
+ selection,
+ capabilities,
+ gitExportRequest,
+ });
+ }
+
+ /**
+ * The Git timeline steps of the export wizard: preflight, history range,
+ * N, performance and the modal 'Continue Export'. Every dismissal and
+ * every failure (already reported) is `cancelled`.
+ */
+ private async promptGitExportRequest(
+ session: UnifiedAnalysisSession,
+ selection: ExportSelection,
+ ): Promise {
+ try {
+ const preflight = await inspectGitRevisionExport(this.extensionContext, session);
+ if (preflight.commitCount < 1) {
+ void vscode.window.showErrorMessage(
+ 'Historical comparison and Project evolution need at least one Git commit to export.',
+ );
+ return { kind: 'cancelled' };
+ }
+ const scope = await this.promptGitRevisionScope(preflight.commitCount);
+ if (!scope) {
+ return { kind: 'cancelled' };
+ }
+
+ const balancedPlan = calculateGitExportWorkerPlan('balanced');
+ const maximumPlan = calculateGitExportWorkerPlan('maximum');
+ const performanceItem = await vscode.window.showQuickPick([
+ {
+ label: `Balanced — ${balancedPlan.workerCount} workers`,
+ description: 'Keeps CPU and memory available for VS Code',
+ profile: 'balanced' as GitExportPerformanceProfile,
+ },
+ {
+ label: `Maximum speed — ${maximumPlan.workerCount} workers`,
+ description: 'Uses the highest safe local concurrency',
+ profile: 'maximum' as GitExportPerformanceProfile,
+ },
+ ], {
+ title: 'Export Git timeline: choose performance',
+ placeHolder: 'Workers are persistent and analyze distinct Git files in parallel',
+ });
+ if (!performanceItem) {
+ return { kind: 'cancelled' };
+ }
+
+ const selectedCount = scope.kind === 'all'
+ ? preflight.commitCount
+ : scope.count;
+ const selectedPlan = performanceItem.profile === 'maximum'
+ ? maximumPlan
+ : balancedPlan;
+ if (!(await this.confirmGitExport(selection, selectedCount, selectedPlan.workerCount))) {
+ return { kind: 'cancelled' };
+ }
+ return { kind: 'request', request: { scope, performanceProfile: performanceItem.profile } };
+ } catch (error) {
+ void vscode.window.showErrorMessage(
+ `The Git timeline cannot be exported: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ return { kind: 'cancelled' };
+ }
+ }
+
+ /** The modal confirmation; true only on 'Continue Export'. */
+ private async confirmGitExport(
+ selection: ExportSelection,
+ selectedCount: number,
+ workerCount: number,
+ ): Promise {
+ const gitModeNames = [
+ selection.historicalComparison ? 'Historical comparison' : '',
+ selection.projectEvolution ? 'Project evolution' : '',
+ ].filter(Boolean).join(' and ');
+ const confirmation = await vscode.window.showWarningMessage(
+ `${gitModeNames} will export ${selectedCount.toLocaleString()} Git commits`
+ + ` plus the working copy using ${workerCount} persistent workers. `
+ + 'Unchanged Git files are analyzed once and shared across revisions.',
+ { modal: true },
+ 'Continue Export',
+ );
+ return confirmation === 'Continue Export';
+ }
+
+ /** History range, then N for "latest"; undefined when either is dismissed. */
+ private async promptGitRevisionScope(commitCount: number): Promise {
+ const scopeItem = await vscode.window.showQuickPick([
+ {
+ label: `Entire history of the checked-out branch — ${commitCount.toLocaleString()} commits`,
+ description: 'Every commit of HEAD from the first one (first parent: a merge is one step)',
+ scope: { kind: 'all' } as GitRevisionScope,
+ },
+ {
+ label: 'Only the latest N commits…',
+ description: 'The newest commits of the checked-out branch; the working copy is added separately',
+ scope: { kind: 'latest', count: 1 } as GitRevisionScope,
+ },
+ ], {
+ title: 'Export Git timeline: choose history range',
+ placeHolder: `${commitCount.toLocaleString()} commits on the checked-out branch. Other branches, stashes and notes are not exported.`,
+ });
+ if (!scopeItem) {
+ return undefined;
+ }
+ if (scopeItem.scope.kind !== 'latest') {
+ return scopeItem.scope;
+ }
+ const rawCount = await vscode.window.showInputBox({
+ title: 'Export Git timeline: number of latest commits',
+ prompt: `Enter a value from 1 to ${commitCount.toLocaleString()}.`
+ + ' The working copy is included in addition to this number.',
+ value: String(Math.min(100, commitCount)),
+ validateInput: (value) => {
+ const count = Number(value);
+ return Number.isInteger(count)
+ && count >= 1
+ && count <= commitCount
+ ? undefined
+ : `Enter a whole number between 1 and ${commitCount}.`;
+ },
+ });
+ if (rawCount === undefined) {
+ return undefined;
+ }
+ return validateGitRevisionScope(
+ { kind: 'latest', count: Number(rawCount) },
+ commitCount,
+ );
+ }
+
+ /** The destination picker; refuses (and reports) a folder that already exists. */
+ private async chooseExportDestination(
+ session: UnifiedAnalysisSession,
+ sourcePath: string,
+ ): Promise {
+ const selectedFolder = await vscode.window.showOpenDialog({
+ canSelectFiles: false,
+ canSelectFolders: true,
+ canSelectMany: false,
+ openLabel: 'Select Export Destination',
+ title: 'Choose where to copy the analysis folder',
+ });
+
+ if (!selectedFolder || selectedFolder.length === 0) {
+ return undefined;
+ }
+
+ const exportFolderName = session.outputDirectory || path.basename(sourcePath);
+ const destinationPath = path.join(selectedFolder[0].fsPath, exportFolderName);
+
+ if (fs.existsSync(destinationPath)) {
+ void vscode.window.showWarningMessage(
+ `The destination folder already exists: ${destinationPath}. Choose a different location or remove the existing folder first.`,
+ );
+ return undefined;
+ }
+ return destinationPath;
+ }
+
+ /**
+ * Stage, post-process and atomically publish the copy, then report. Any
+ * failure or cancellation aborts the transaction, so nothing partial is
+ * ever published.
+ */
+ private async writeExportPackage(session: UnifiedAnalysisSession, plan: ExportPlan): Promise {
+ const { sourcePath, destinationPath, selection, capabilities } = plan;
+ const capturedViewState = analysisRefreshCoordinator.getViewState(session.id);
+ let transaction: ExportPackageTransaction | undefined;
+ try {
+ if (
+ selection.dependencyGraph
+ && capabilities.dependencyGraph
+ && !this.hasDependencyDataset(sourcePath)
+ ) {
+ const dependencyFailure = await this.pregenerateDependencyDataset(
+ session.id,
+ sourcePath,
+ );
+ if (dependencyFailure) {
+ throw new Error(dependencyFailure);
+ }
+ }
+
+ transaction = await beginExportPackageTransaction(sourcePath, destinationPath);
+ const stagingPath = transaction.stagingPath;
+ await pruneExportPackage(stagingPath, selection);
+ await configureOfflineExportHtml(stagingPath);
+
+ // Everything below touches the DESTINATION copy only.
+ await relativizeExportArtifacts(stagingPath);
+ let gitCounts = { analyzedRevisions: 0, partialGitSources: 0 };
+ if (isXrSceneFolder(stagingPath)) {
+ gitCounts = await this.completeXrExport(session, stagingPath, plan, capturedViewState);
+ }
+
+ await publishExportPackage(transaction);
+ this.reportExportPublished(destinationPath, gitCounts.analyzedRevisions, gitCounts.partialGitSources);
+ } catch (error) {
+ await abortExportPackage(transaction);
+ if (error instanceof ExportCancelledError) {
+ void vscode.window.showInformationMessage(
+ 'Analysis export cancelled. No partial folder was published.',
+ );
+ } else {
+ void vscode.window.showErrorMessage(
+ `Failed to export analysis folder: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+ }
+
+ /**
+ * XR scene staging: fresh runtimes, the shared Git timeline pass (one pass
+ * serves both historical comparison and project evolution offline), then
+ * the manifest, README and package validation.
+ */
+ private async completeXrExport(
+ session: UnifiedAnalysisSession,
+ stagingPath: string,
+ plan: ExportPlan,
+ capturedViewState: ReturnType,
+ ): Promise<{ analyzedRevisions: number; partialGitSources: number }> {
+ const { selection, capabilities, gitExportRequest } = plan;
+ await refreshRuntimeCopies(stagingPath, this.extensionContext.extensionPath);
+
+ // gitExportRequest is set exactly when selection.gitTimeline is (exportFolder).
+ const gitOutcome = gitExportRequest
+ ? await this.exportGitTimeline(session, stagingPath, gitExportRequest)
+ : undefined;
+
+ const manifest = await buildExportManifest(stagingPath, {
+ target: {
+ name: session.targetName || path.basename(session.targetPath || '') || 'analysis',
+ type: session.targetType || 'directory',
+ analysisMode: session.analysisMode || 'XR',
+ },
+ serverCapabilities: capabilities,
+ viewState: {
+ mode: String(capturedViewState.mode || 'single'),
+ controllerView: capturedViewState.controllerView,
+ },
+ gitData: gitOutcome?.gitData,
+ gitDataFailureReason: gitOutcome?.failureReason,
+ gitDataSelected: selection.gitTimeline,
+ selectedModes: selection,
+ });
+ await writeExportReadme(stagingPath, manifest);
+ await validateExportPackage(stagingPath, manifest);
+ return {
+ analyzedRevisions: gitOutcome?.gitData?.analyzedRevisionCount || 0,
+ partialGitSources: gitOutcome?.gitData?.skippedRevisions?.length || 0,
+ };
+ }
+
+ /**
+ * Git timeline pre-analysis: one shared pass serves both historical
+ * comparison and project evolution offline. A cancelled pass, or one
+ * without usable revisions, aborts the whole export.
+ */
+ private async exportGitTimeline(
+ session: UnifiedAnalysisSession,
+ stagingPath: string,
+ gitExportRequest: GitRevisionExportRequest,
+ ): Promise {
+ const gitOutcome = await vscode.window.withProgress(
+ {
+ location: vscode.ProgressLocation.Notification,
+ title: 'Code-XR: analyzing the complete Git timeline for the export…',
+ cancellable: true,
+ },
+ (progress, token) => exportGitRevisionData(
+ this.extensionContext,
+ session,
+ stagingPath,
+ gitExportRequest,
+ { progress, token },
+ ),
+ );
+ if (gitOutcome.cancelled) {
+ throw new ExportCancelledError();
+ }
+ if (!gitOutcome.gitData) {
+ throw new Error(
+ gitOutcome.failureReason
+ || 'The Git timeline did not produce enough usable revisions.',
+ );
+ }
+ return gitOutcome;
+ }
+
+ private reportExportPublished(destinationPath: string, analyzedRevisions: number, partialGitSources: number): void {
+ const revisionsNote = analyzedRevisions
+ ? ` ${analyzedRevisions} git revisions travel with it.`
+ : '';
+ const partialNote = partialGitSources
+ ? ` ${partialGitSources} revision source(s) were discarded because they had no usable data; details are listed in the manifest.`
+ : '';
+ const completionMessage = `Analysis folder exported to ${destinationPath}.${revisionsNote}${partialNote} `
+ + 'Serve it with any static HTTP server (e.g. "npx serve") to open it outside VS Code.';
+ if (partialGitSources) {
+ void vscode.window.showWarningMessage(completionMessage);
+ } else {
+ void vscode.window.showInformationMessage(completionMessage);
+ }
+ }
+
+ private hasDependencyDataset(sourcePath: string): boolean {
+ const dependenciesDir = path.join(sourcePath, 'dependencies');
+ if (!fs.existsSync(dependenciesDir)) {
+ return false;
+ }
+ return fs.readdirSync(dependenciesDir)
+ .some((name) => /^dependency-graph-\d+\.json$/.test(name));
+ }
+
+ /**
+ * Run the same dependency analysis the in-scene "dependency graph" mode
+ * would trigger, and wait for it, so the export ships a usable dataset.
+ * Returns a reason string when the dataset could not be produced. A
+ * selected mode is a package invariant, so the transaction then aborts.
+ */
+ private async pregenerateDependencyDataset(
+ sessionId: string,
+ sourcePath: string,
+ ): Promise {
+ try {
+ await vscode.window.withProgress(
+ {
+ location: vscode.ProgressLocation.Notification,
+ title: 'Code-XR: preparing export (analyzing dependencies)…',
+ },
+ () => analysisRefreshCoordinator.forceRefreshModeAndWait(
+ sessionId,
+ 'dependency-graph',
+ 600_000,
+ ),
+ );
+ if (!this.hasDependencyDataset(sourcePath)) {
+ return 'The dependency analysis completed without producing an exportable dataset.';
+ }
+ return undefined;
+ } catch (error) {
+ return `The dependency analysis failed during export: ${error instanceof Error ? error.message : String(error)}`;
+ }
+ }
+
+ private async refreshAnalyses(): Promise {
+ ActiveAnalysesDataService.getInstance().refresh();
+ logger.debug('Refresh triggered via data service');
+ }
+
+ /**
+ * The prelude every handler opens with: resolve the argument to a session
+ * id, then to a live session, reporting the first step that fails.
+ */
+ private resolveSelectedSession(
+ arg: ActiveAnalysisCommandArg | undefined,
+ ): { sessionId: string; session: UnifiedAnalysisSession } | undefined {
+ const sessionId = this.extractSessionId(arg);
+ if (!sessionId) {
+ void vscode.window.showErrorMessage('No analysis selected');
+ return undefined;
+ }
+
+ const session = this.sessionRegistry.getSession(sessionId);
+ if (!session) {
+ void vscode.window.showErrorMessage('Analysis session not found');
+ return undefined;
+ }
+ return { sessionId, session };
+ }
+
+ private extractSessionId(arg?: ActiveAnalysisCommandArg): string | undefined {
+ if (typeof arg === 'string') {
+ return arg;
+ }
+ if (arg?.session?.id) {
+ return arg.session.id;
+ }
+ if (arg?.sessionId) {
+ return arg.sessionId;
+ }
+ if (arg?.id) {
+ return arg.id;
+ }
+ if (arg?.originalAnalysisItem?.sessionId) {
+ return arg.originalAnalysisItem.sessionId;
+ }
+ if (arg?.originalAnalysisItem?.id) {
+ return arg.originalAnalysisItem.id;
+ }
+ if (arg?.originalAnalysisItem?.session?.id) {
+ return arg.originalAnalysisItem.session.id;
+ }
+ return undefined;
+ }
+
+ private resolveExportSourcePath(session: {
+ savedFilesPath?: string;
+ outputPath?: string;
+ }): string | undefined {
+ if (session.savedFilesPath && fs.existsSync(session.savedFilesPath)) {
+ return session.savedFilesPath;
+ }
+
+ if (session.outputPath && fs.existsSync(session.outputPath)) {
+ return session.outputPath;
+ }
+
+ return undefined;
+ }
+
+ private generateDetailsContent(session: UnifiedAnalysisSession): string {
+ return `# Analysis Details
+
+## Session Information
+- **Session ID**: ${session.id}
+- **Target Path**: ${session.targetPath}
+- **Target Type**: ${session.targetType}
+- **Analysis Mode**: ${session.analysisMode}
+- **Start Time**: ${session.startTime || 'Unknown'}
+- **Status**: ${session.status || 'Active'}
+
+## Server Information
+${session.assignedPort ? `- **Port**: ${session.assignedPort}` : ''}
+${session.serverUrl ? `- **Server URL**: ${session.serverUrl}` : ''}
+${session.serverId ? `- **Server ID**: ${session.serverId}` : ''}
+
+## Configuration
+- **Is Deep Analysis**: ${session.isDeep || false}
+- **Output Directory**: ${session.outputDirectory || 'Not set'}
+
+## Progress
+${session.progress ? `- **Progress**: ${session.progress}%` : '- **Progress**: Not available'}
+${session.error ? `- **Error**: ${session.error}` : ''}
+`;
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/sections/active-analyses/activeAnalysesDataService.ts b/apps/vscode-extension/src/features/analysis/sections/active-analyses/activeAnalysesDataService.ts
new file mode 100644
index 000000000..ff55722da
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/active-analyses/activeAnalysesDataService.ts
@@ -0,0 +1,483 @@
+/**
+ * Active Analyses Data Service
+ * Provides data for the Active Analyses TreeView
+ */
+
+import * as vscode from 'vscode';
+import * as path from 'path';
+import { UnifiedAnalysisSession } from '../../../../core/analysis/session/analysisSession';
+import { UnifiedSessionRegistry } from '../../../../core/analysis/session/sessionRegistry';
+import type { CodeAnalysisTreeItem } from '../../views/analysisItems';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('ACTIVE_ANALYSES_DATA_SERVICE');
+
+export interface ActiveAnalysisItem {
+ // Core session properties - SIMPLIFIED
+ id: string;
+ sessionId: string;
+ label: string;
+ description?: string;
+ analysisType: string;
+ status: string;
+ filePath?: string;
+ targetPath?: string;
+ resourceUri?: vscode.Uri;
+ contextValue: string;
+ iconPath?: vscode.ThemeIcon;
+ serverUrl?: string;
+ assignedPort?: number;
+ // Direct session reference for commands - NO MORE COMPLEX TRANSFORMATIONS
+ session: UnifiedAnalysisSession;
+}
+
+/**
+ * The session fields copied onto the TreeItem: VS Code passes the TreeItem,
+ * not the element, to context-menu commands, and they locate the session
+ * through these.
+ */
+type ActiveAnalysisTreeItem = vscode.TreeItem & Pick<
+ ActiveAnalysisItem,
+ 'sessionId' | 'analysisType' | 'status' | 'targetPath' | 'serverUrl' | 'assignedPort'
+>;
+
+/** Icon colour per analysis mode for file targets; legacy mode names included. */
+const FILE_ICON_COLORS: Readonly> = {
+ LivePanel: 'charts.green',
+ FileLivePanel: 'charts.green',
+ XR: 'charts.purple',
+ FileXRAnalysis: 'charts.purple',
+ VisualizeDOM: 'charts.orange',
+ FileVisualizeDOM: 'charts.orange',
+};
+
+/** Icon colour per analysis mode for directory targets; legacy mode names included. */
+const DIRECTORY_ICON_COLORS: Readonly> = {
+ LivePanel: 'charts.green',
+ DirectoryLivePanel: 'charts.green',
+ DeepDirectoryLivePanel: 'charts.green',
+ XR: 'charts.purple',
+ DirectoryXRAnalysis: 'charts.purple',
+ DeepDirectoryXRAnalysis: 'charts.purple',
+ VisualizeDOM: 'charts.orange',
+};
+
+/**
+ * The tree item's resourceUri: the trimmed, normalized target path, or
+ * undefined for a blank or non-string path, or one Uri.file rejects.
+ */
+function safeResourceUri(targetPath: unknown): vscode.Uri | undefined {
+ if (typeof targetPath !== 'string' || targetPath.trim().length === 0) {
+ return undefined;
+ }
+ try {
+ return vscode.Uri.file(path.normalize(targetPath.trim()));
+ } catch (uriError) {
+ logger.warn(`Invalid path for URI creation: ${targetPath}`, uriError);
+ return undefined;
+ }
+}
+
+export class ActiveAnalysesDataService {
+ private static instance: ActiveAnalysesDataService;
+ private _onDidChangeTreeData: vscode.EventEmitter = new vscode.EventEmitter();
+ readonly onDidChangeTreeData: vscode.Event = this._onDidChangeTreeData.event;
+
+ private sessionRegistry: UnifiedSessionRegistry | null = null;
+
+ private constructor() {
+ logger.debug('Initialized');
+ }
+
+ public static getInstance(): ActiveAnalysesDataService {
+ if (!ActiveAnalysesDataService.instance) {
+ ActiveAnalysesDataService.instance = new ActiveAnalysesDataService();
+ }
+ return ActiveAnalysesDataService.instance;
+ }
+
+ public initialize(context: vscode.ExtensionContext): void {
+ if (!this.sessionRegistry) {
+ this.sessionRegistry = UnifiedSessionRegistry.getInstance(context);
+
+ // Listen to session changes
+ this.sessionRegistry.onSessionChanged(() => {
+ this.refresh();
+ });
+ }
+ }
+
+ /**
+ * Refresh the tree view
+ */
+ public refresh(): void {
+ logger.debug('Refreshing tree view');
+ this._onDidChangeTreeData.fire();
+ }
+
+ /**
+ * Get tree children
+ */
+ public getChildren(element?: ActiveAnalysisItem): Promise {
+ if (!element) {
+ // Root level - return all active analyses
+ return Promise.resolve(this.getAllActiveAnalyses());
+ } else {
+ // No children for analysis items - flat list
+ return Promise.resolve([]);
+ }
+ }
+
+ /**
+ * Get tree item
+ */
+ public getTreeItem(element: ActiveAnalysisItem): vscode.TreeItem {
+ try {
+ if (!element) {
+ logger.error('getTreeItem called with null/undefined element');
+ return new vscode.TreeItem('Error: Invalid item');
+ }
+
+ const item = new vscode.TreeItem(element.label || 'Unknown Analysis');
+ item.description = element.description;
+ item.contextValue = element.contextValue;
+
+ // Safely set resourceUri
+ if (element.resourceUri) {
+ try {
+ item.resourceUri = element.resourceUri;
+ } catch (uriError) {
+ logger.warn('Error setting resourceUri:', uriError);
+ item.resourceUri = undefined;
+ }
+ }
+
+ item.iconPath = element.iconPath;
+
+ // CRITICAL: Add sessionId to the TreeItem so commands can locate the session
+ // VS Code passes the TreeItem object to context menu commands, not the original element
+ (item as ActiveAnalysisTreeItem).sessionId = element.sessionId;
+ (item as ActiveAnalysisTreeItem).id = element.id;
+ (item as ActiveAnalysisTreeItem).analysisType = element.analysisType;
+ (item as ActiveAnalysisTreeItem).status = element.status;
+ (item as ActiveAnalysisTreeItem).targetPath = element.targetPath;
+ (item as ActiveAnalysisTreeItem).serverUrl = element.serverUrl;
+ (item as ActiveAnalysisTreeItem).assignedPort = element.assignedPort;
+
+ logger.debug('Created TreeItem with session info:', {
+ sessionId: element.sessionId,
+ id: element.id,
+ label: element.label,
+ targetPath: element.targetPath
+ });
+
+ item.tooltip = element.description
+ ? `${element.description}\n\nLeft-click to show available actions.`
+ : 'Left-click to show available actions.';
+
+ // Add command to show available actions when clicked.
+ item.command = {
+ command: 'codeXR.analysis.activeAnalyses.showActions',
+ title: 'Show Analysis Actions',
+ arguments: element ? [element] : [] // Ensure arguments array is never undefined
+ };
+
+ // Analysis items are always leaf nodes (no children)
+ item.collapsibleState = vscode.TreeItemCollapsibleState.None;
+
+ return item;
+ } catch (error) {
+ logger.error('Error in getTreeItem:', error);
+ return new vscode.TreeItem('Error: Failed to create tree item');
+ }
+ }
+
+ /**
+ * Get all active analyses
+ */
+ private getAllActiveAnalyses(): ActiveAnalysisItem[] {
+ const analyses: ActiveAnalysisItem[] = [];
+
+ try {
+ if (!this.sessionRegistry) {
+ logger.warn('Session registry not initialized');
+ return analyses;
+ }
+
+ // Get all sessions with safety check
+ let allSessions;
+ try {
+ allSessions = this.sessionRegistry.getAllSessions();
+ } catch (error) {
+ logger.error('Error getting sessions from registry:', error);
+ return analyses;
+ }
+
+ if (!Array.isArray(allSessions)) {
+ logger.warn('getAllSessions() returned non-array:', typeof allSessions);
+ return analyses;
+ }
+
+ logger.debug(() => `Found ${allSessions.length} sessions`);
+
+ for (const session of allSessions) {
+ if (!session) {
+ logger.warn('Found null/undefined session in registry');
+ continue;
+ }
+
+ if (session.status !== 'closed') {
+ try {
+ // Determine type based on session properties
+ const type = session.targetType === 'directory' ? 'directory' : 'file';
+ const analysisItem = this.createAnalysisItem(session, type);
+ if (analysisItem) {
+ analyses.push(analysisItem);
+ }
+ } catch (error) {
+ logger.error(`Error creating analysis item for session: ${session.id}`, error);
+ }
+ }
+ }
+
+ } catch (error) {
+ logger.error('Error getting analyses:', error);
+ }
+
+ logger.debug(() => `Returning ${analyses.length} active analyses`);
+ return analyses;
+ }
+
+ /**
+ * Create analysis item for tree view
+ */
+ private createAnalysisItem(session: UnifiedAnalysisSession, type: 'file' | 'directory'): ActiveAnalysisItem | null {
+ try {
+ if (!session) {
+ logger.warn('Cannot create analysis item - session is null/undefined');
+ return null;
+ }
+
+ if (!session.id) {
+ logger.warn('Cannot create analysis item - session has no ID');
+ return null;
+ }
+
+ // Use analysis type icon instead of status icon for better visual differentiation
+ const analysisIcon = this.getAnalysisTypeIcon(session.analysisMode, type);
+ const analysisTypeLabel = this.getAnalysisTypeLabel(session.analysisMode);
+
+ // Safe property access with fallbacks
+ const targetName = session.targetName || (session.targetPath ? path.basename(session.targetPath) : 'Unknown');
+ const status = session.status || 'unknown';
+ const analysisMode = session.analysisMode || 'unknown';
+ const targetPath = session.targetPath;
+
+ const resourceUri = safeResourceUri(targetPath);
+
+ logger.debug('Creating analysis item for session:', {
+ sessionId: session.id,
+ targetName: targetName,
+ targetPath: targetPath
+ });
+
+ return {
+ id: session.id,
+ sessionId: session.id, // For command compatibility
+ label: targetName,
+ description: `${analysisTypeLabel} - ${this.getStatusLabel(status)}`,
+ analysisType: analysisMode,
+ status: status,
+ filePath: targetPath || undefined,
+ targetPath: targetPath || undefined,
+ serverUrl: session.serverUrl || undefined,
+ assignedPort: session.assignedPort || undefined,
+ resourceUri: resourceUri,
+ // Fix contextValue to match package.json patterns - remove type from the middle
+ contextValue: `activeAnalysis.${status}`,
+ iconPath: analysisIcon,
+ // SIMPLIFIED: Direct session reference for commands
+ session: session
+ };
+ } catch (error) {
+ logger.error('Error creating analysis item:', error);
+ return null;
+ }
+ }
+
+ /**
+ * Get analysis type icon based on analysis mode and target type: a file or
+ * folder icon, coloured by mode (green LivePanel, purple XR, orange DOM).
+ */
+ private getAnalysisTypeIcon(analysisMode: string, targetType: 'file' | 'directory'): vscode.ThemeIcon {
+ const iconId = targetType === 'file' ? 'file' : 'folder';
+ const colors = targetType === 'file' ? FILE_ICON_COLORS : DIRECTORY_ICON_COLORS;
+ const color = Object.prototype.hasOwnProperty.call(colors, analysisMode) ? colors[analysisMode] : undefined;
+ return color ? new vscode.ThemeIcon(iconId, new vscode.ThemeColor(color)) : new vscode.ThemeIcon(iconId);
+ }
+
+ /**
+ * Get status label
+ */
+ private getStatusLabel(status: string): string {
+ switch (status) {
+ case 'creating':
+ return 'Creating...';
+ case 'analyzing':
+ return 'Analyzing...';
+ case 'monitoring':
+ return 'Monitoring';
+ case 'completed':
+ return 'Ready';
+ case 'error':
+ return 'Error';
+ case 'failed':
+ return 'Failed';
+ case 'closed':
+ return 'Closed';
+ case 'closing':
+ return 'Closing...';
+ default:
+ return status;
+ }
+ }
+
+ /**
+ * Get analysis type label
+ */
+ private getAnalysisTypeLabel(analysisType: string): string {
+ switch (analysisType) {
+ // New engine modes
+ case 'LivePanel':
+ return 'Live Panel';
+ case 'XR':
+ return 'XR Analysis';
+ case 'VisualizeDOM':
+ return 'Visualize DOM';
+ // Legacy modes
+ case 'FileLivePanel':
+ return 'Live Panel';
+ case 'FileVisualizeDOM':
+ return 'Visualize DOM';
+ case 'FileXRAnalysis':
+ return 'XR Analysis';
+ case 'DirectoryLivePanel':
+ return 'Directory Live Panel';
+ case 'DeepDirectoryLivePanel':
+ return 'Deep Directory Live Panel';
+ case 'DirectoryXRAnalysis':
+ return 'Directory XR Analysis';
+ case 'DeepDirectoryXRAnalysis':
+ return 'Deep Directory XR Analysis';
+ default:
+ return analysisType;
+ }
+ }
+
+ /**
+ * Get analysis by ID
+ */
+ public getAnalysisById(id: string): UnifiedAnalysisSession | undefined | null {
+ try {
+ if (!this.sessionRegistry) {
+ logger.warn('Session registry not initialized');
+ return null;
+ }
+
+ return this.sessionRegistry.getSession(id);
+ } catch (error) {
+ logger.error(`Error getting analysis ${id}:`, error);
+ return null;
+ }
+ }
+
+ /**
+ * Get analysis count by status
+ */
+ public getAnalysisCountByStatus(): { creating: number; analyzing: number; monitoring: number; completed: number; error: number; failed: number; closed: number; closing: number; total: number } {
+ const analyses = this.getAllActiveAnalyses();
+
+ const counts = {
+ creating: 0,
+ analyzing: 0,
+ monitoring: 0,
+ completed: 0,
+ error: 0,
+ failed: 0,
+ closed: 0,
+ closing: 0,
+ total: analyses.length
+ };
+
+ for (const analysis of analyses) {
+ switch (analysis.status) {
+ case 'creating':
+ counts.creating++;
+ break;
+ case 'analyzing':
+ counts.analyzing++;
+ break;
+ case 'monitoring':
+ counts.monitoring++;
+ break;
+ case 'completed':
+ counts.completed++;
+ break;
+ case 'error':
+ counts.error++;
+ break;
+ case 'failed':
+ counts.failed++;
+ break;
+ case 'closed':
+ counts.closed++;
+ break;
+ case 'closing':
+ counts.closing++;
+ break;
+ }
+ }
+
+ return counts;
+ }
+
+ /**
+ * Get active analyses (alias for getAllActiveAnalyses for compatibility)
+ */
+ public getActiveAnalyses(): ActiveAnalysisItem[] {
+ return this.getAllActiveAnalyses();
+ }
+
+ /**
+ * Get subsection item for the tree (SIMPLIFIED integration)
+ */
+ public getSubsectionItem(): CodeAnalysisTreeItem {
+ try {
+ const activeCount = this.getAllActiveAnalyses().length;
+ return {
+ label: `Active Analyses (${activeCount})`,
+ collapsibleState: 1, // Expanded
+ contextValue: 'activeAnalysesSubsection',
+ analysisItemType: 'subsection',
+ iconPath: new vscode.ThemeIcon(
+ 'play-circle',
+ activeCount > 0 ? new vscode.ThemeColor('charts.green') : new vscode.ThemeColor('charts.gray')
+ ),
+ tooltip: `${activeCount} active analysis sessions`,
+ description: activeCount > 0 ? `${activeCount} running` : 'No active sessions'
+ };
+ } catch (error) {
+ logger.error('Error creating subsection item:', error);
+ return {
+ label: 'Active Analyses (Error)',
+ collapsibleState: 1,
+ contextValue: 'activeAnalysesSubsection',
+ analysisItemType: 'subsection',
+ iconPath: new vscode.ThemeIcon('error'),
+ tooltip: 'Error loading active analyses',
+ description: 'Error'
+ };
+ }
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/sections/files-by-language/filesByLanguageCommands.ts b/apps/vscode-extension/src/features/analysis/sections/files-by-language/filesByLanguageCommands.ts
new file mode 100644
index 000000000..edaaa8690
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/files-by-language/filesByLanguageCommands.ts
@@ -0,0 +1,106 @@
+/**
+ * Files By Language Commands
+ * Commands specific to the Files By Language subsection
+ */
+
+import * as path from 'path';
+import * as vscode from 'vscode';
+import { CommandRegistration } from '../settings/analysis-file-mode/analysisFileModeCommands';
+import { AnalysisConfigurationStorage } from '../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { AnalysisOrchestrator } from '../../../../core/analysis/analysisOrchestrator';
+import { CodeXRLogger } from '../../../../platform/logging/logger';
+
+const logger = CodeXRLogger.getLogger('FILES_BY_LANGUAGE_COMMANDS');
+
+export class FilesByLanguageCommands {
+ constructor(_context: vscode.ExtensionContext) {}
+
+ /**
+ * Get files by language command registrations (nested dolls pattern)
+ */
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ ): CommandRegistration[] {
+ const commandRegistrations: CommandRegistration[] = [
+ {
+ commandId: 'codeXR.analysis.runAndAnalyzeFile',
+ callback: async (filePath: string, languageName: string) => {
+ await FilesByLanguageCommands.runAndAnalyzeFile(filePath, languageName, context);
+ },
+ description: 'Run and analyze file according to current analysis settings',
+ },
+ ];
+
+ return commandRegistrations;
+ }
+
+ /**
+ * Run and analyze file according to current analysis settings
+ */
+ static async runAndAnalyzeFile(filePath: string, languageName: string, context: vscode.ExtensionContext): Promise {
+ try {
+ const absolutePath = FilesByLanguageCommands.resolveFilePath(filePath);
+ if (!absolutePath) {
+ void vscode.window.showErrorMessage('No workspace folder found');
+ return;
+ }
+
+ const fileUri = vscode.Uri.file(absolutePath);
+ await vscode.window.showTextDocument(fileUri);
+
+ const storage = AnalysisConfigurationStorage.getInstance(context);
+ const analysisMode = await storage.getAnalysisMode();
+
+ if (languageName === 'HTML') {
+ await AnalysisOrchestrator.orchestrateAnalysis(
+ absolutePath,
+ 'VisualizeDOM',
+ 'file',
+ context,
+ false,
+ );
+ return;
+ }
+
+ if (analysisMode === 'XR') {
+ await AnalysisOrchestrator.orchestrateAnalysis(
+ absolutePath,
+ 'XR',
+ 'file',
+ context,
+ false,
+ );
+ return;
+ }
+
+ if (analysisMode === 'LivePanel') {
+ await AnalysisOrchestrator.orchestrateAnalysis(
+ absolutePath,
+ 'LivePanel',
+ 'file',
+ context,
+ false,
+ );
+ return;
+ }
+
+ void vscode.window.showWarningMessage(`Unknown analysis mode: ${analysisMode}`);
+ } catch (error) {
+ logger.error(() => `Failed to run and analyze file ${filePath}.`, error);
+ void vscode.window.showErrorMessage(`Failed to analyze file: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ private static resolveFilePath(filePath: string): string | null {
+ if (path.isAbsolute(filePath)) {
+ return filePath;
+ }
+
+ const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
+ if (!workspaceFolder) {
+ return null;
+ }
+
+ return path.resolve(workspaceFolder.uri.fsPath, filePath);
+ }
+}
diff --git a/src/code_analysis/views/subsections/files_by_language/filesByLanguageSubsectionProvider.ts b/apps/vscode-extension/src/features/analysis/sections/files-by-language/filesByLanguageSubsectionProvider.ts
similarity index 93%
rename from src/code_analysis/views/subsections/files_by_language/filesByLanguageSubsectionProvider.ts
rename to apps/vscode-extension/src/features/analysis/sections/files-by-language/filesByLanguageSubsectionProvider.ts
index 7bd4db68f..40aa745c3 100644
--- a/src/code_analysis/views/subsections/files_by_language/filesByLanguageSubsectionProvider.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/files-by-language/filesByLanguageSubsectionProvider.ts
@@ -5,12 +5,12 @@
import * as path from 'path';
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../items/analysisItems';
-import { WorkspaceFileScanner } from '../../../utils/workspaceFileScanner';
-import { FilesByLanguageSortingUtils } from '../../../utils/filesByLanguageSortingUtils';
-import { AnalysisConfigurationStorage } from '../../../configuration/analysisConfigurationStorage';
-import { WorkspaceSnapshotService } from '../../../services/workspaceSnapshotService';
-import { CodeXRLogger } from '../../../../core/logging/logger';
+import { CodeAnalysisTreeItem } from '../../views/analysisItems';
+import { WorkspaceFileScanner } from '../../workspace/workspaceFileScanner';
+import { FilesByLanguageSortingUtils } from '../settings/files-by-language-sorting/filesByLanguageSortingUtils';
+import { AnalysisConfigurationStorage } from '../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { WorkspaceSnapshotService } from '../../workspace/workspaceSnapshotService';
+import { CodeXRLogger } from '../../../../platform/logging/logger';
const logger = CodeXRLogger.getLogger('FILES_BY_LANGUAGE');
diff --git a/apps/vscode-extension/src/features/analysis/sections/project-by-language/projectByLanguageCommands.ts b/apps/vscode-extension/src/features/analysis/sections/project-by-language/projectByLanguageCommands.ts
new file mode 100644
index 000000000..0d85a968e
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/project-by-language/projectByLanguageCommands.ts
@@ -0,0 +1,195 @@
+/**
+ * Project Structure Commands
+ * Commands for analyzing files and directories from project structure
+ */
+
+import * as vscode from 'vscode';
+import * as path from 'path';
+import { CommandRegistration } from '../settings/analysis-file-mode/analysisFileModeCommands';
+import { AnalysisConfigurationStorage } from '../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { AnalysisOrchestrator } from '../../../../core/analysis/analysisOrchestrator';
+import { getLanguageByExtension } from '../../../../core/analysis/languages/supportedLanguages';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('PROJECT_STRUCTURE_COMMANDS');
+
+export class ProjectByLanguageCommands {
+
+ constructor(private context: vscode.ExtensionContext) {}
+
+ /**
+ * Get project structure command registrations (nested dolls pattern)
+ */
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ refreshCallback: () => void
+ ): CommandRegistration[] {
+ logger.debug('ANALYSIS: Collecting Project Structure command registrations');
+ const commands = new ProjectByLanguageCommands(context);
+
+ const commandRegistrations: CommandRegistration[] = [
+ {
+ commandId: 'codeXR.analysis.projectStructure.analyzeFile',
+ callback: async (filePath: string) => {
+ logger.debug(() => `Analyze file command TRIGGERED for: ${filePath}`);
+ logger.debug(() => `Callback argument type: ${typeof filePath}`);
+ logger.debug(() => `Callback argument value: "${filePath}"`);
+ await commands.analyzeFile(filePath);
+ refreshCallback();
+ },
+ description: 'Analyze a file using the configured analysis mode from Project Structure'
+ },
+ {
+ commandId: 'codeXR.analysis.projectStructure.analyzeDirectory',
+ callback: async (directoryPath: string) => {
+ logger.debug(() => `Analyze directory command TRIGGERED for: ${directoryPath}`);
+ logger.debug(() => `Callback argument type: ${typeof directoryPath}`);
+ logger.debug(() => `Callback argument value: "${directoryPath}"`);
+ await commands.analyzeDirectory(directoryPath);
+ refreshCallback();
+ },
+ description: 'Analyze a directory using the configured analysis mode from Project Structure'
+ }
+ ];
+
+ logger.debug(() => `ANALYSIS: Collected ${commandRegistrations.length} Project Structure command registrations`);
+ return commandRegistrations;
+ }
+
+ /**
+ * Analyze a file using the configured file analysis mode
+ */
+ private async analyzeFile(filePath: string): Promise {
+ logger.debug(() => `Analyzing file: ${filePath}`);
+ logger.debug(() => `FilePath type: ${typeof filePath}`);
+ logger.debug(() => `FilePath value: "${filePath}"`);
+
+ try {
+ // Validate input
+ if (!filePath || typeof filePath !== 'string') {
+ logger.error('Invalid filePath received:', filePath);
+ void vscode.window.showErrorMessage('Invalid file path received');
+ return;
+ }
+
+ const storage = AnalysisConfigurationStorage.getInstance(this.context);
+ const analysisMode = await storage.getAnalysisMode();
+
+ logger.debug(() => `Using analysis mode: ${analysisMode}`);
+
+ // Get file extension and language
+ const ext = path.extname(filePath).toLowerCase();
+ const languageConfig = getLanguageByExtension(ext);
+ const languageName = languageConfig?.name || 'Unknown';
+
+ logger.debug(() => `Running analysis for ${filePath} (${languageName}) in ${analysisMode} mode`);
+
+ // Determine which analysis to run based on file type and configuration
+ if (languageName === 'HTML') {
+ // HTML files always use DOM Visualization using NEW ENGINE
+ logger.debug('Running DOM Visualization for HTML file using NEW ENGINE');
+ await AnalysisOrchestrator.orchestrateAnalysis(
+ filePath,
+ 'VisualizeDOM',
+ 'file',
+ this.context,
+ false
+ );
+ } else {
+ // For other files, use the configured analysis mode with NEW ENGINE
+ if (analysisMode === 'XR') {
+ logger.debug('Running XR Analysis using NEW ENGINE');
+ await AnalysisOrchestrator.orchestrateAnalysis(
+ filePath,
+ 'XR',
+ 'file',
+ this.context,
+ false
+ );
+ } else if (analysisMode === 'LivePanel') {
+ logger.debug('Running LivePanel Analysis using NEW ENGINE');
+ await AnalysisOrchestrator.orchestrateAnalysis(
+ filePath,
+ 'LivePanel',
+ 'file',
+ this.context,
+ false
+ );
+ } else {
+ void vscode.window.showWarningMessage(`Unknown analysis mode: ${analysisMode}`);
+ }
+ }
+
+ void vscode.window.showInformationMessage(`Started ${analysisMode} analysis for file: ${path.basename(filePath)}`);
+
+ } catch (error) {
+ logger.error('Error analyzing file:', error);
+ void vscode.window.showErrorMessage(`Failed to analyze file: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ /**
+ * Analyze a directory using the configured directory analysis mode
+ */
+ private async analyzeDirectory(directoryPath: string): Promise {
+ logger.debug(() => `Analyzing directory: ${directoryPath}`);
+ logger.debug(() => `DirectoryPath type: ${typeof directoryPath}`);
+ logger.debug(() => `DirectoryPath value: "${directoryPath}"`);
+
+ try {
+ // Validate input
+ if (!directoryPath || typeof directoryPath !== 'string') {
+ logger.error('Invalid directoryPath received:', directoryPath);
+ void vscode.window.showErrorMessage('Invalid directory path received');
+ return;
+ }
+
+ const storage = AnalysisConfigurationStorage.getInstance(this.context);
+ const directoryAnalysisMode = await storage.getAnalysisDirectoryMode();
+
+ logger.debug(() => `Using directory analysis mode: ${directoryAnalysisMode}`);
+
+ // Map directory analysis mode to AnalysisOrchestrator parameters
+ let analysisMode: 'XR' | 'LivePanel';
+ let isDeep: boolean;
+
+ switch (directoryAnalysisMode) {
+ case 'XR':
+ analysisMode = 'XR';
+ isDeep = false;
+ break;
+ case 'XRDeep':
+ analysisMode = 'XR';
+ isDeep = true;
+ break;
+ case 'LivePanel':
+ analysisMode = 'LivePanel';
+ isDeep = false;
+ break;
+ case 'LivePanelDeep':
+ analysisMode = 'LivePanel';
+ isDeep = true;
+ break;
+ default:
+ void vscode.window.showWarningMessage(`Unknown directory analysis mode: ${directoryAnalysisMode}`);
+ return;
+ }
+
+ logger.debug(() => `Running ${analysisMode} Directory Analysis (Deep: ${isDeep}) using NEW ENGINE`);
+ await AnalysisOrchestrator.orchestrateAnalysis(
+ directoryPath,
+ analysisMode,
+ 'directory',
+ this.context,
+ isDeep
+ );
+
+ void vscode.window.showInformationMessage(`Started ${directoryAnalysisMode} analysis for directory: ${path.basename(directoryPath)}`);
+
+ } catch (error) {
+ logger.error('Error analyzing directory:', error);
+ void vscode.window.showErrorMessage(`Failed to analyze directory: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+}
+
diff --git a/src/code_analysis/views/subsections/project_by_language/projectByLanguageSubsectionProvider.ts b/apps/vscode-extension/src/features/analysis/sections/project-by-language/projectByLanguageSubsectionProvider.ts
similarity index 96%
rename from src/code_analysis/views/subsections/project_by_language/projectByLanguageSubsectionProvider.ts
rename to apps/vscode-extension/src/features/analysis/sections/project-by-language/projectByLanguageSubsectionProvider.ts
index 041211b0d..c6a430782 100644
--- a/src/code_analysis/views/subsections/project_by_language/projectByLanguageSubsectionProvider.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/project-by-language/projectByLanguageSubsectionProvider.ts
@@ -5,9 +5,9 @@
import * as path from 'path';
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../items/analysisItems';
-import { WorkspaceFileScanner } from '../../../utils/workspaceFileScanner';
-import { WorkspaceSnapshotNode, WorkspaceSnapshotService } from '../../../services/workspaceSnapshotService';
+import { CodeAnalysisTreeItem } from '../../views/analysisItems';
+import { WorkspaceFileScanner } from '../../workspace/workspaceFileScanner';
+import { WorkspaceSnapshotNode, WorkspaceSnapshotService } from '../../workspace/workspaceSnapshotService';
export class ProjectByLanguageSubsectionProvider {
private readonly workspaceSnapshotService: WorkspaceSnapshotService;
diff --git a/src/code_analysis/views/subsections/analysis_settings/analysis_directory_mode/analysisDirectoryMode.ts b/apps/vscode-extension/src/features/analysis/sections/settings/analysis-directory-mode/analysisDirectoryMode.ts
similarity index 84%
rename from src/code_analysis/views/subsections/analysis_settings/analysis_directory_mode/analysisDirectoryMode.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/analysis-directory-mode/analysisDirectoryMode.ts
index 88e1a58c7..1923311b9 100644
--- a/src/code_analysis/views/subsections/analysis_settings/analysis_directory_mode/analysisDirectoryMode.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/analysis-directory-mode/analysisDirectoryMode.ts
@@ -4,19 +4,23 @@
*/
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../../items/analysisItems';
-import { AnalysisConfigurationStorage, AnalysisDirectoryMode } from '../../../../configuration';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { AnalysisDirectoryMode } from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { getLogger } from '../../../../../platform/logging/sink';
-export { AnalysisDirectoryMode } from '../../../../configuration';
+const logger = getLogger('ANALYSIS');
+
+export { AnalysisDirectoryMode } from '../../../../../core/analysis/configuration/analysisConfiguration';
export class AnalysisDirectorySetting {
private currentMode: AnalysisDirectoryMode = 'XR'; // Default mode (will be loaded from storage)
private storage: AnalysisConfigurationStorage;
- constructor(private context: vscode.ExtensionContext) {
- console.log('ANALYSIS: Initializing Analysis Directory setting');
+ constructor(context: vscode.ExtensionContext) {
+ logger.debug('Initializing Analysis Directory setting');
this.storage = AnalysisConfigurationStorage.getInstance(context);
- this.loadSavedMode();
+ void this.loadSavedMode();
}
/**
@@ -151,7 +155,7 @@ export class AnalysisDirectorySetting {
async setMode(mode: AnalysisDirectoryMode): Promise {
this.currentMode = mode;
await this.saveModeToSettings();
- console.log(`ANALYSIS: Analysis directory mode set to ${mode}`);
+ logger.debug(() => `Analysis directory mode set to ${mode}`);
}
/**
@@ -160,9 +164,9 @@ export class AnalysisDirectorySetting {
private async loadSavedMode(): Promise {
try {
this.currentMode = await this.storage.getAnalysisDirectoryMode();
- console.log(`ANALYSIS: Loaded analysis directory mode: ${this.currentMode}`);
+ logger.debug(() => `Loaded analysis directory mode: ${this.currentMode}`);
} catch (error) {
- console.error('ANALYSIS: Error loading analysis directory mode:', error);
+ logger.error('Error loading analysis directory mode:', error);
// Keep default mode
}
}
@@ -173,19 +177,9 @@ export class AnalysisDirectorySetting {
private async saveModeToSettings(): Promise {
try {
await this.storage.setAnalysisDirectoryMode(this.currentMode);
- console.log(`ANALYSIS: Saved analysis directory mode: ${this.currentMode}`);
+ logger.debug(() => `Saved analysis directory mode: ${this.currentMode}`);
} catch (error) {
- console.error('ANALYSIS: Error saving analysis directory mode:', error);
+ logger.error('Error saving analysis directory mode:', error);
}
}
}
-
-/**
- * Command registration interface for the nested dolls pattern
- */
-export interface CommandRegistration {
- commandId: string;
- callback: (...args: any[]) => any;
- description?: string;
-}
-
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/analysis-directory-mode/analysisDirectoryModeCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/analysis-directory-mode/analysisDirectoryModeCommands.ts
new file mode 100644
index 000000000..410f57f05
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/analysis-directory-mode/analysisDirectoryModeCommands.ts
@@ -0,0 +1,63 @@
+/**
+ * Analysis Directory Mode Commands
+ * Command handlers for the analysis directory mode setting
+ */
+
+import * as vscode from 'vscode';
+import { AnalysisDirectorySetting } from './analysisDirectoryMode';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
+
+export class AnalysisDirectoryModeCommands {
+
+ /**
+ * Get command registrations for analysis directory mode (nested dolls pattern)
+ */
+ static getCommandRegistrations(
+ _context: vscode.ExtensionContext,
+ analysisDirectorySetting: AnalysisDirectorySetting,
+ refreshCallback: () => void
+ ): CommandRegistration[] {
+ logger.debug('Collecting Analysis Directory Mode command registrations');
+
+ const commandRegistrations: CommandRegistration[] = [
+ {
+ commandId: 'codeXR.analysis.selectAnalysisDirectoryMode',
+ callback: async () => {
+ try {
+ logger.debug('Select Analysis Directory Mode command executed');
+
+ const selectedMode = await analysisDirectorySetting.selectMode();
+
+ if (selectedMode) {
+ const modeText = selectedMode.includes('Deep')
+ ? `${selectedMode.replace('Deep', '')} Deep`
+ : selectedMode;
+
+ void vscode.window.showInformationMessage(
+ `Directory analysis mode set to: ${modeText}`,
+ 'OK'
+ );
+
+ // Refresh tree to show updated state
+ refreshCallback();
+ }
+
+ } catch (error) {
+ logger.error('Error selecting analysis directory mode:', error);
+ void vscode.window.showErrorMessage(
+ `Failed to select directory analysis mode: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+ },
+ description: 'Select between LivePanel, LivePanelDeep, XR, and XRDeep modes for directory analysis'
+ }
+ ];
+
+ logger.debug(() => `Collected ${commandRegistrations.length} Analysis Directory Mode command registrations`);
+ return commandRegistrations;
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/analysis-file-mode/analysisFileMode.ts b/apps/vscode-extension/src/features/analysis/sections/settings/analysis-file-mode/analysisFileMode.ts
new file mode 100644
index 000000000..63826888d
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/analysis-file-mode/analysisFileMode.ts
@@ -0,0 +1,109 @@
+/**
+ * Analysis File Setting Item
+ * Manages the analysis file mode (XR/LivePanel) configuration
+ */
+
+import * as vscode from 'vscode';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { AnalysisFileMode } from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
+
+export { AnalysisFileMode } from '../../../../../core/analysis/configuration/analysisConfiguration';
+
+export class AnalysisFileSetting {
+ private currentMode: AnalysisFileMode = 'XR'; // Default mode (will be loaded from storage)
+ private storage: AnalysisConfigurationStorage;
+
+ constructor(context: vscode.ExtensionContext) {
+ logger.debug('Initializing Analysis File setting');
+ this.storage = AnalysisConfigurationStorage.getInstance(context);
+ void this.loadSavedMode();
+ }
+
+ /**
+ * Get the tree item for this setting
+ */
+ async getSettingItem(): Promise {
+ // Always get the current value from storage to ensure it's up to date
+ const currentMode = await this.storage.getAnalysisFileMode();
+
+ const modeText = currentMode === 'XR'
+ ? 'Analysis File with Immersive VR/AR'
+ : 'Analysis File with Standard Experience';
+ const iconPath = currentMode === 'LivePanel'
+ ? new vscode.ThemeIcon('file-code', new vscode.ThemeColor('charts.green'))
+ : new vscode.ThemeIcon('vr', new vscode.ThemeColor('charts.purple'));
+
+ return new CodeAnalysisTreeItem(
+ modeText,
+ vscode.TreeItemCollapsibleState.None,
+ 'analysis-result',
+ {
+ command: 'codeXR.analysis.toggleAnalysisFileMode',
+ title: 'Toggle Analysis File Mode',
+ arguments: []
+ },
+ iconPath,
+ `Click to switch between analysis modes. Current: ${currentMode === 'XR' ? 'Immersive VR/AR experience for detailed analysis' : 'Standard panel for quick review'}`,
+ currentMode,
+ 'analysisFileModeSetting'
+ );
+ }
+
+ /**
+ * Toggle between XR and LivePanel modes
+ */
+ async toggleMode(): Promise {
+ this.currentMode = this.currentMode === 'XR' ? 'LivePanel' : 'XR';
+ logger.debug(() => `Analysis file mode switched to ${this.currentMode}`);
+
+ await this.saveModeToSettings();
+
+ return this.currentMode;
+ }
+
+ /**
+ * Get current mode
+ */
+ getCurrentMode(): AnalysisFileMode {
+ return this.currentMode;
+ }
+
+ /**
+ * Set specific mode
+ */
+ async setMode(mode: AnalysisFileMode): Promise {
+ this.currentMode = mode;
+ await this.saveModeToSettings();
+ }
+
+ /**
+ * Load saved mode from globalStorage
+ */
+ private async loadSavedMode(): Promise {
+ try {
+ const savedMode = await this.storage.getAnalysisFileMode();
+ this.currentMode = savedMode;
+ logger.debug(() => `Loaded analysis file mode from storage: ${this.currentMode}`);
+ } catch (error) {
+ logger.error('Error loading saved mode, using default:', error);
+ this.currentMode = 'XR'; // Fallback to default
+ }
+ }
+
+ /**
+ * Save mode to globalStorage
+ */
+ private async saveModeToSettings(): Promise {
+ try {
+ await this.storage.setAnalysisFileMode(this.currentMode);
+ logger.debug(() => `Saved analysis file mode to storage: ${this.currentMode}`);
+ } catch (error) {
+ logger.error('Error saving mode to storage:', error);
+ }
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/analysis-file-mode/analysisFileModeCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/analysis-file-mode/analysisFileModeCommands.ts
new file mode 100644
index 000000000..0f8dbaba9
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/analysis-file-mode/analysisFileModeCommands.ts
@@ -0,0 +1,57 @@
+/**
+ * Analysis File Mode Commands
+ * Commands specific to the Analysis File Mode setting
+ */
+
+import * as vscode from 'vscode';
+import { AnalysisFileSetting } from './analysisFileMode';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
+
+export interface CommandRegistration {
+ commandId: string;
+ callback: (...args: any[]) => Promise | void;
+ description: string;
+ module?: string;
+ errorMessage?: string;
+ silentErrors?: boolean;
+}
+
+export class AnalysisFileModeCommands {
+ constructor(
+ _context: vscode.ExtensionContext,
+ private analysisFileSetting: AnalysisFileSetting,
+ ) {}
+
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ analysisFileSetting: AnalysisFileSetting,
+ refreshCallback: () => void,
+ ): CommandRegistration[] {
+ const commands = new AnalysisFileModeCommands(context, analysisFileSetting);
+
+ return [
+ {
+ commandId: 'codeXR.analysis.toggleAnalysisFileMode',
+ callback: () => commands.toggleAnalysisFileMode(refreshCallback),
+ description: 'Toggle analysis file mode between XR and LivePanel',
+ module: 'ANALYSIS',
+ errorMessage: 'Failed to toggle analysis file mode'
+ }
+ ];
+ }
+
+ private async toggleAnalysisFileMode(refreshCallback: () => void): Promise {
+ try {
+ const newMode = await this.analysisFileSetting.toggleMode();
+ void vscode.window.showInformationMessage(`Analysis File mode switched to: ${newMode}`, { modal: false });
+ refreshCallback();
+ logger.debug(() => `Command executed - Analysis file mode: ${newMode}`);
+ } catch (error) {
+ logger.error('Error toggling analysis file mode:', error);
+ void vscode.window.showErrorMessage(`Failed to toggle analysis file mode: ${error}`);
+ }
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/analysisSettingsCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/analysisSettingsCommands.ts
new file mode 100644
index 000000000..ebfefc027
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/analysisSettingsCommands.ts
@@ -0,0 +1,153 @@
+/**
+ * Analysis Settings Commands Coordinator
+ * Coordinates all commands for the Analysis Settings subsection
+ */
+
+import * as vscode from 'vscode';
+import { AnalysisFileSetting } from './analysis-file-mode/analysisFileMode';
+import { AnalysisDirectorySetting } from './analysis-directory-mode/analysisDirectoryMode';
+import { ViewThemeSetting } from './view-theme/viewTheme';
+import { AutoAnalysisDelaySetting } from './auto-analysis-delay/autoAnalysisDelay';
+import { AutoAnalysisEnabledSetting } from './auto-analysis-enabled/autoAnalysisEnabled';
+import { ChartTypeFileSetting } from './chart-type-file/chartTypeFile';
+import { ChartTypeDirectorySetting } from './chart-type-directory/chartTypeDirectory';
+import { DimensionMappingFileSetting } from './dimension-mapping-file/dimensionMappingFile';
+import { DimensionMappingDirectorySetting } from './dimension-mapping-directory/dimensionMappingDirectory';
+import { FilesByLanguageSortingSetting } from './files-by-language-sorting/filesByLanguageSorting';
+import { ProfileConfigurationSetting } from './profile-configuration/profileConfiguration';
+import { AnalysisFileModeCommands, CommandRegistration } from './analysis-file-mode/analysisFileModeCommands';
+import { AnalysisDirectoryModeCommands } from './analysis-directory-mode/analysisDirectoryModeCommands';
+import { ViewThemeCommands } from './view-theme/viewThemeCommands';
+import { AutoAnalysisDelayCommands } from './auto-analysis-delay/autoAnalysisDelayCommands';
+import { AutoAnalysisEnabledCommands } from './auto-analysis-enabled/autoAnalysisEnabledCommands';
+import { ChartTypeFileCommands } from './chart-type-file/chartTypeFileCommands';
+import { ChartTypeDirectoryCommands } from './chart-type-directory/chartTypeDirectoryCommands';
+import { DimensionMappingFileCommands } from './dimension-mapping-file/dimensionMappingFileCommands';
+import { DimensionMappingDirectoryCommands } from './dimension-mapping-directory/dimensionMappingDirectoryCommands';
+import { FilesByLanguageSortingCommands } from './files-by-language-sorting/filesByLanguageSortingCommands';
+import { ProfileConfigurationCommands } from './profile-configuration/profileConfigurationCommands';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
+
+export class AnalysisSettingsCommands {
+
+ constructor(_context: vscode.ExtensionContext) {}
+
+ /**
+ * Get all analysis settings command registrations (nested dolls pattern)
+ * Collects commands from all sub-components without registering them
+ */
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ analysisFileSetting: AnalysisFileSetting,
+ analysisDirectorySetting: AnalysisDirectorySetting,
+ viewThemeSetting: ViewThemeSetting,
+ autoAnalysisDelaySetting: AutoAnalysisDelaySetting,
+ autoAnalysisEnabledSetting: AutoAnalysisEnabledSetting,
+ chartTypeFileSetting: ChartTypeFileSetting,
+ chartTypeDirectorySetting: ChartTypeDirectorySetting,
+ dimensionMappingFileSetting: DimensionMappingFileSetting,
+ dimensionMappingDirectorySetting: DimensionMappingDirectorySetting,
+ filesByLanguageSortingSetting: FilesByLanguageSortingSetting,
+ profileConfigurationSetting: ProfileConfigurationSetting,
+ refreshCallback: () => void
+ ): CommandRegistration[] {
+ logger.debug('Collecting Analysis Settings command registrations');
+
+ const commandRegistrations: CommandRegistration[] = [];
+
+ // Collect analysis file mode command registrations
+ const fileModeCommands = AnalysisFileModeCommands.getCommandRegistrations(
+ context,
+ analysisFileSetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...fileModeCommands);
+
+ // Collect analysis directory mode command registrations
+ const directoryModeCommands = AnalysisDirectoryModeCommands.getCommandRegistrations(
+ context,
+ analysisDirectorySetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...directoryModeCommands);
+
+ // Collect view theme command registrations
+ const viewThemeCommands = ViewThemeCommands.getCommandRegistrations(
+ context,
+ viewThemeSetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...viewThemeCommands);
+
+ // Collect chart type file command registrations
+ const chartTypeFileCommands = ChartTypeFileCommands.getCommandRegistrations(
+ context,
+ chartTypeFileSetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...chartTypeFileCommands);
+
+ // Collect chart type directory command registrations
+ const chartTypeDirectoryCommands = ChartTypeDirectoryCommands.getCommandRegistrations(
+ context,
+ chartTypeDirectorySetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...chartTypeDirectoryCommands);
+
+ // Collect dimension mapping file command registrations
+ const dimensionMappingFileCommands = DimensionMappingFileCommands.getCommandRegistrations(
+ context,
+ dimensionMappingFileSetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...dimensionMappingFileCommands);
+
+ // Collect dimension mapping directory command registrations
+ const dimensionMappingDirectoryCommands = DimensionMappingDirectoryCommands.getCommandRegistrations(
+ context,
+ dimensionMappingDirectorySetting,
+ refreshCallback
+ );
+ logger.debug(() => `ANALYSIS_SETTINGS_COMMANDS: Got ${dimensionMappingDirectoryCommands.length} dimension mapping directory commands`);
+ commandRegistrations.push(...dimensionMappingDirectoryCommands);
+
+ // Collect auto-analysis delay command registrations
+ const autoAnalysisDelayCommands = AutoAnalysisDelayCommands.getCommandRegistrations(
+ context,
+ autoAnalysisDelaySetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...autoAnalysisDelayCommands);
+
+ // Collect auto-analysis enabled command registrations
+ const autoAnalysisEnabledCommands = AutoAnalysisEnabledCommands.getCommandRegistrations(
+ context,
+ autoAnalysisEnabledSetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...autoAnalysisEnabledCommands);
+
+ // Collect files by language sorting command registrations
+ const filesByLanguageSortingCommands = FilesByLanguageSortingCommands.getCommandRegistrations(
+ context,
+ filesByLanguageSortingSetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...filesByLanguageSortingCommands);
+
+ // Collect profile configuration command registrations
+ const profileConfigurationCommands = ProfileConfigurationCommands.getCommandRegistrations(
+ context,
+ profileConfigurationSetting,
+ refreshCallback
+ );
+ commandRegistrations.push(...profileConfigurationCommands);
+
+ logger.debug(() => `Collected ${commandRegistrations.length} Analysis Settings command registrations`);
+ return commandRegistrations;
+ }
+}
+
diff --git a/src/code_analysis/views/subsections/analysis_settings/analysisSettingsSubsectionProvider.ts b/apps/vscode-extension/src/features/analysis/sections/settings/analysisSettingsSubsectionProvider.ts
similarity index 81%
rename from src/code_analysis/views/subsections/analysis_settings/analysisSettingsSubsectionProvider.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/analysisSettingsSubsectionProvider.ts
index 7555349d1..128aaeebe 100644
--- a/src/code_analysis/views/subsections/analysis_settings/analysisSettingsSubsectionProvider.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/analysisSettingsSubsectionProvider.ts
@@ -4,19 +4,22 @@
*/
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../items/analysisItems';
-import { AnalysisFileSetting } from './analysis_file_mode';
-import { AnalysisDirectorySetting } from './analysis_directory_mode';
-import { ViewThemeSetting } from './view_theme';
-import { ChartTypeFileSetting } from './chart_type_file/chartTypeFile';
-import { ChartTypeDirectorySetting } from './chart_type_directory/chartTypeDirectory';
-import { DimensionMappingFileSetting } from './dimension_mapping_file/dimensionMappingFile';
-import { DimensionMappingDirectorySetting } from './dimension_mapping_directory/dimensionMappingDirectory';
-import { AutoAnalysisDelaySetting } from './auto_analysis_delay';
-import { AutoAnalysisEnabledSetting } from './auto_analysis_enabled';
-import { FilesByLanguageSortingSetting } from './files_by_language_sorting';
-import { ProfileConfigurationSetting } from './profile_configuration';
-import { AnalysisConfigurationStorage } from '../../../configuration/analysisConfigurationStorage';
+import { CodeAnalysisTreeItem } from '../../views/analysisItems';
+import { AnalysisFileSetting } from './analysis-file-mode/analysisFileMode';
+import { AnalysisDirectorySetting } from './analysis-directory-mode/analysisDirectoryMode';
+import { ViewThemeSetting } from './view-theme/viewTheme';
+import { ChartTypeFileSetting } from './chart-type-file/chartTypeFile';
+import { ChartTypeDirectorySetting } from './chart-type-directory/chartTypeDirectory';
+import { DimensionMappingFileSetting } from './dimension-mapping-file/dimensionMappingFile';
+import { DimensionMappingDirectorySetting } from './dimension-mapping-directory/dimensionMappingDirectory';
+import { AutoAnalysisDelaySetting } from './auto-analysis-delay/autoAnalysisDelay';
+import { AutoAnalysisEnabledSetting } from './auto-analysis-enabled/autoAnalysisEnabled';
+import { FilesByLanguageSortingSetting } from './files-by-language-sorting/filesByLanguageSorting';
+import { ProfileConfigurationSetting } from './profile-configuration/profileConfiguration';
+import { AnalysisConfigurationStorage } from '../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
export class AnalysisSettingsSubsectionProvider {
private analysisFileSetting: AnalysisFileSetting;
@@ -31,8 +34,8 @@ export class AnalysisSettingsSubsectionProvider {
private filesByLanguageSortingSetting: FilesByLanguageSortingSetting;
private profileConfigurationSetting: ProfileConfigurationSetting;
- constructor(private context: vscode.ExtensionContext) {
- console.log('ANALYSIS: Initializing Analysis Settings subsection provider');
+ constructor(context: vscode.ExtensionContext) {
+ logger.debug('Initializing Analysis Settings subsection provider');
// Initialize setting components
this.analysisFileSetting = new AnalysisFileSetting(context);
@@ -71,7 +74,7 @@ export class AnalysisSettingsSubsectionProvider {
* Get children items for Analysis Settings
*/
async getChildren(): Promise {
- console.log('ANALYSIS: Getting Analysis Settings children');
+ logger.debug('Getting Analysis Settings children');
try {
const children: CodeAnalysisTreeItem[] = [];
@@ -101,10 +104,10 @@ export class AnalysisSettingsSubsectionProvider {
children.push(dimensionMappingFileItem);
// Dimension Mapping (Directory) setting - NEW
- console.log('ANALYSIS: Getting Dimension Mapping Directory setting item');
+ logger.debug('Getting Dimension Mapping Directory setting item');
const dimensionMappingDirectoryItem = await this.dimensionMappingDirectorySetting.getSettingItem();
children.push(dimensionMappingDirectoryItem);
- console.log('ANALYSIS: Dimension Mapping Directory setting item added to children');
+ logger.debug('Dimension Mapping Directory setting item added to children');
// Auto Analysis Delay setting
const autoAnalysisDelayItem = await this.autoAnalysisDelaySetting.getSettingItem();
@@ -122,11 +125,11 @@ export class AnalysisSettingsSubsectionProvider {
const profileConfigurationItem = await this.profileConfigurationSetting.getSettingItem();
children.push(profileConfigurationItem);
- console.log(`ANALYSIS: Analysis Settings children count: ${children.length}`);
+ logger.debug(() => `Analysis Settings children count: ${children.length}`);
return children;
} catch (error) {
- console.error('ANALYSIS: Error getting Analysis Settings children:', error);
+ logger.error('Error getting Analysis Settings children:', error);
// Return error item
return [new CodeAnalysisTreeItem(
@@ -146,7 +149,7 @@ export class AnalysisSettingsSubsectionProvider {
* Get specific children for a setting item (for nested items like Dimension Mapping)
*/
async getSettingChildren(element: CodeAnalysisTreeItem): Promise {
- console.log(`ANALYSIS: Getting children for setting: ${element.contextValue}`);
+ logger.debug(() => `Getting children for setting: ${element.contextValue}`);
try {
switch (element.contextValue) {
@@ -167,11 +170,11 @@ export class AnalysisSettingsSubsectionProvider {
return await this.profileConfigurationSetting.getChildren();
default:
- console.log(`ANALYSIS: No children available for setting: ${element.contextValue}`);
+ logger.debug(() => `No children available for setting: ${element.contextValue}`);
return [];
}
} catch (error) {
- console.error(`ANALYSIS: Error getting children for setting ${element.contextValue}:`, error);
+ logger.error(`Error getting children for setting ${element.contextValue}:`, error);
return [];
}
}
@@ -180,7 +183,7 @@ export class AnalysisSettingsSubsectionProvider {
* Refresh all settings (can be called when configuration changes)
*/
async refresh(): Promise {
- console.log('ANALYSIS: Refreshing Analysis Settings subsection');
+ logger.debug('Refreshing Analysis Settings subsection');
// Settings will be refreshed automatically when getChildren() is called
}
diff --git a/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts b/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-delay/autoAnalysisDelay.ts
similarity index 82%
rename from src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-delay/autoAnalysisDelay.ts
index f122dd194..b24f70ca7 100644
--- a/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-delay/autoAnalysisDelay.ts
@@ -4,10 +4,14 @@
*/
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../../items/analysisItems';
-import { AnalysisConfigurationStorage, AutoAnalysisDelayConfig, AutoAnalysisDelay } from '../../../../configuration';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { AutoAnalysisDelayConfig, AutoAnalysisDelay } from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { getLogger } from '../../../../../platform/logging/sink';
-export { AutoAnalysisDelayConfig, AutoAnalysisDelay } from '../../../../configuration';
+const logger = getLogger('ANALYSIS');
+
+export { AutoAnalysisDelayConfig, AutoAnalysisDelay } from '../../../../../core/analysis/configuration/analysisConfiguration';
export class AutoAnalysisDelaySetting {
private currentDelayConfig: AutoAnalysisDelayConfig = { type: 'RealTime', autoAnalysisEnabled: true };
@@ -22,9 +26,9 @@ export class AutoAnalysisDelaySetting {
'10s': 10000
};
- constructor(private context: vscode.ExtensionContext) {
+ constructor(context: vscode.ExtensionContext) {
this.storage = AnalysisConfigurationStorage.getInstance(context);
- this.loadSavedDelay();
+ void this.loadSavedDelay();
}
/**
@@ -58,7 +62,7 @@ export class AutoAnalysisDelaySetting {
* Get display text for current delay
*/
private getDelayDisplayText(delayConfig?: AutoAnalysisDelayConfig): string {
- const configToUse = delayConfig || this.currentDelayConfig;
+ const configToUse = delayConfig ?? this.currentDelayConfig;
if (configToUse.type === 'Custom') {
const ms = configToUse.customMs || 0;
return `Custom: ${ms}ms`;
@@ -70,7 +74,7 @@ export class AutoAnalysisDelaySetting {
* Get appropriate icon for current delay
*/
private getDelayIcon(delayConfig?: AutoAnalysisDelayConfig): vscode.ThemeIcon {
- const configToUse = delayConfig || this.currentDelayConfig;
+ const configToUse = delayConfig ?? this.currentDelayConfig;
if (configToUse.type === 'RealTime') {
return new vscode.ThemeIcon('zap', new vscode.ThemeColor('charts.green'));
} else if (configToUse.type === 'Custom') {
@@ -100,7 +104,7 @@ export class AutoAnalysisDelaySetting {
autoAnalysisEnabled: this.currentDelayConfig.autoAnalysisEnabled
};
- console.log(`ANALYSIS: Auto-analysis delay cycled to ${this.currentDelayConfig.type}`);
+ logger.debug(() => `Auto-analysis delay cycled to ${this.currentDelayConfig.type}`);
await this.saveDelayToSettings();
@@ -120,7 +124,7 @@ export class AutoAnalysisDelaySetting {
autoAnalysisEnabled: this.currentDelayConfig.autoAnalysisEnabled
};
- console.log(`ANALYSIS: Auto-analysis delay set to custom ${clampedMs}ms`);
+ logger.debug(() => `Auto-analysis delay set to custom ${clampedMs}ms`);
await this.saveDelayToSettings();
@@ -163,9 +167,9 @@ export class AutoAnalysisDelaySetting {
try {
const savedDelay = await this.storage.getAutoAnalysisDelay();
this.currentDelayConfig = savedDelay;
- console.log(`ANALYSIS: Loaded auto-analysis delay from storage:`, savedDelay);
+ logger.debug(`Loaded auto-analysis delay from storage:`, savedDelay);
} catch (error) {
- console.error('ANALYSIS: Error loading saved delay, using default:', error);
+ logger.error('Error loading saved delay, using default:', error);
this.currentDelayConfig = { type: 'RealTime', autoAnalysisEnabled: true }; // Fallback to default
}
}
@@ -176,9 +180,9 @@ export class AutoAnalysisDelaySetting {
private async saveDelayToSettings(): Promise {
try {
await this.storage.setAutoAnalysisDelay(this.currentDelayConfig);
- console.log(`ANALYSIS: Saved auto-analysis delay to storage:`, this.currentDelayConfig);
+ logger.debug(`Saved auto-analysis delay to storage:`, this.currentDelayConfig);
} catch (error) {
- console.error('ANALYSIS: Error saving delay to storage:', error);
+ logger.error('Error saving delay to storage:', error);
}
}
}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-delay/autoAnalysisDelayCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-delay/autoAnalysisDelayCommands.ts
new file mode 100644
index 000000000..522c3e5c0
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-delay/autoAnalysisDelayCommands.ts
@@ -0,0 +1,177 @@
+/**
+ * Auto-Analysis Delay Commands
+ * Commands specific to the Auto-Analysis Delay setting
+ */
+
+import * as vscode from 'vscode';
+import { AutoAnalysisDelaySetting } from './autoAnalysisDelay';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { SessionWatcherManager } from '../../../../../core/analysis/watchers/sessionWatcherManager';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
+
+export class AutoAnalysisDelayCommands {
+
+ constructor(
+ private context: vscode.ExtensionContext,
+ private autoAnalysisDelaySetting: AutoAnalysisDelaySetting
+ ) {}
+
+ /**
+ * Get command registrations (don't register them yet)
+ * This follows the "nested dolls" architecture pattern
+ */
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ autoAnalysisDelaySetting: AutoAnalysisDelaySetting,
+ refreshCallback: () => void
+ ): CommandRegistration[] {
+ const commands = new AutoAnalysisDelayCommands(context, autoAnalysisDelaySetting);
+
+ return [
+ {
+ commandId: 'codeXR.analysis.selectAutoAnalysisDelay',
+ callback: () => commands.selectAutoAnalysisDelay(refreshCallback),
+ description: 'Select Auto-Analysis Delay from options'
+ }
+ ];
+ }
+
+ /**
+ * Select auto-analysis delay from QuickPick command handler
+ */
+ private async selectAutoAnalysisDelay(refreshCallback: () => void): Promise {
+ try {
+ const predefinedItems = [
+ {
+ label: 'Real Time (0s)',
+ description: 'Instant analysis as you type',
+ detail: 'No delay - immediate response',
+ value: 'RealTime' as const
+ },
+ {
+ label: '1 Second',
+ description: 'Short delay for quick feedback',
+ detail: '1000ms delay',
+ value: '1s' as const
+ },
+ {
+ label: '3 Seconds',
+ description: 'Balanced delay for most users',
+ detail: '3000ms delay',
+ value: '3s' as const
+ },
+ {
+ label: '5 Seconds',
+ description: 'Longer delay for complex analysis',
+ detail: '5000ms delay',
+ value: '5s' as const
+ },
+ {
+ label: '10 Seconds',
+ description: 'Maximum predefined delay',
+ detail: '10000ms delay',
+ value: '10s' as const
+ },
+ {
+ label: 'Custom Value...',
+ description: 'Set your own delay (0-20000ms)',
+ detail: 'Enter custom milliseconds',
+ value: 'Custom' as const
+ }
+ ];
+
+ const selectedItem = await vscode.window.showQuickPick(predefinedItems, {
+ placeHolder: 'Select auto-analysis delay timing',
+ title: 'Auto-Analysis Delay Configuration',
+ matchOnDescription: true,
+ matchOnDetail: true
+ });
+
+ if (!selectedItem) {
+ return;
+ }
+
+ if (selectedItem.value === 'Custom') {
+ await this.setCustomAutoAnalysisDelay(refreshCallback);
+ } else {
+ await this.setAutoAnalysisDelay(selectedItem.value, refreshCallback);
+ }
+ } catch (error) {
+ logger.error('Error selecting auto-analysis delay:', error);
+ void vscode.window.showErrorMessage(`Failed to select auto-analysis delay: ${error}`);
+ }
+ }
+
+ private async refreshActiveWatchers(): Promise {
+ await SessionWatcherManager.refreshActiveWatcherConfigurations(this.context);
+ }
+
+ /**
+ * Set custom auto-analysis delay command handler
+ */
+ private async setCustomAutoAnalysisDelay(refreshCallback: () => void): Promise {
+ try {
+ const input = await vscode.window.showInputBox({
+ prompt: 'Enter custom auto-analysis delay in milliseconds (0-20000)',
+ placeHolder: '1000',
+ validateInput: (value) => {
+ const num = parseInt(value);
+ if (isNaN(num)) {
+ return 'Please enter a valid number';
+ }
+ if (num < 0 || num > 20000) {
+ return 'Delay must be between 0 and 20000 milliseconds (20 seconds)';
+ }
+ return null;
+ }
+ });
+
+ if (input === undefined) {
+ return;
+ }
+
+ const customMs = parseInt(input);
+ await this.autoAnalysisDelaySetting.setCustomDelay(customMs);
+ await this.refreshActiveWatchers();
+
+ void vscode.window.showInformationMessage(
+ `Auto-analysis delay set to custom: ${customMs}ms`,
+ { modal: false }
+ );
+
+ refreshCallback();
+
+ logger.debug(() => `Command executed - Custom auto-analysis delay: ${customMs}ms`);
+ } catch (error) {
+ logger.error('Error setting custom auto-analysis delay:', error);
+ void vscode.window.showErrorMessage(`Failed to set custom auto-analysis delay: ${error}`);
+ }
+ }
+
+ /**
+ * Set specific auto-analysis delay command handler
+ */
+ private async setAutoAnalysisDelay(
+ delayType: 'RealTime' | '1s' | '3s' | '5s' | '10s',
+ refreshCallback: () => void
+ ): Promise {
+ try {
+ await this.autoAnalysisDelaySetting.setDelay(delayType);
+ await this.refreshActiveWatchers();
+
+ void vscode.window.showInformationMessage(
+ `Auto-analysis delay set to: ${delayType}`,
+ { modal: false }
+ );
+
+ refreshCallback();
+
+ logger.debug(() => `Command executed - Auto-analysis delay set to: ${delayType}`);
+ } catch (error) {
+ logger.error(`Error setting auto-analysis delay to ${delayType}:`, error);
+ void vscode.window.showErrorMessage(`Failed to set auto-analysis delay to ${delayType}: ${error}`);
+ }
+ }
+}
diff --git a/src/code_analysis/views/subsections/analysis_settings/auto_analysis_enabled/autoAnalysisEnabled.ts b/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-enabled/autoAnalysisEnabled.ts
similarity index 79%
rename from src/code_analysis/views/subsections/analysis_settings/auto_analysis_enabled/autoAnalysisEnabled.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-enabled/autoAnalysisEnabled.ts
index 5825e8a21..34d7bd778 100644
--- a/src/code_analysis/views/subsections/analysis_settings/auto_analysis_enabled/autoAnalysisEnabled.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-enabled/autoAnalysisEnabled.ts
@@ -4,17 +4,20 @@
*/
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../../items/analysisItems';
-import { AnalysisConfigurationStorage } from '../../../../configuration';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
export class AutoAnalysisEnabledSetting {
private currentEnabled: boolean = true; // Default enabled
private storage: AnalysisConfigurationStorage;
- constructor(private context: vscode.ExtensionContext) {
- console.log('ANALYSIS: Initializing Auto-Analysis Enabled setting');
+ constructor(context: vscode.ExtensionContext) {
+ logger.debug('Initializing Auto-Analysis Enabled setting');
this.storage = AnalysisConfigurationStorage.getInstance(context);
- this.loadSavedState();
+ void this.loadSavedState();
}
/**
@@ -75,7 +78,7 @@ export class AutoAnalysisEnabledSetting {
'Auto-Analysis enabled - watchers and debounce time are now active' :
'Auto-Analysis disabled - watchers and debounce time are paused';
- vscode.window.showInformationMessage(message);
+ void vscode.window.showInformationMessage(message);
}
/**
@@ -99,9 +102,9 @@ export class AutoAnalysisEnabledSetting {
try {
const savedState = await this.storage.getAutoAnalysisEnabled();
this.currentEnabled = savedState;
- console.log(`ANALYSIS: Loaded auto-analysis enabled state from storage: ${this.currentEnabled}`);
+ logger.debug(() => `Loaded auto-analysis enabled state from storage: ${this.currentEnabled}`);
} catch (error) {
- console.error('ANALYSIS: Error loading saved state, using default:', error);
+ logger.error('Error loading saved state, using default:', error);
this.currentEnabled = true; // Fallback to default (enabled)
}
}
@@ -112,9 +115,9 @@ export class AutoAnalysisEnabledSetting {
private async saveStateToSettings(): Promise {
try {
await this.storage.setAutoAnalysisEnabled(this.currentEnabled);
- console.log(`ANALYSIS: Saved auto-analysis enabled state to storage: ${this.currentEnabled}`);
+ logger.debug(() => `Saved auto-analysis enabled state to storage: ${this.currentEnabled}`);
} catch (error) {
- console.error('ANALYSIS: Error saving state to storage:', error);
+ logger.error('Error saving state to storage:', error);
}
}
}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-enabled/autoAnalysisEnabledCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-enabled/autoAnalysisEnabledCommands.ts
new file mode 100644
index 000000000..cc2e56dfa
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/auto-analysis-enabled/autoAnalysisEnabledCommands.ts
@@ -0,0 +1,63 @@
+/**
+ * Auto-Analysis Enabled Commands
+ * Commands specific to the Auto-Analysis Enabled setting
+ */
+
+import * as vscode from 'vscode';
+import { AutoAnalysisEnabledSetting } from './autoAnalysisEnabled';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { SessionWatcherManager } from '../../../../../core/analysis/watchers/sessionWatcherManager';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
+
+export class AutoAnalysisEnabledCommands {
+
+ constructor(
+ private context: vscode.ExtensionContext,
+ private autoAnalysisEnabledSetting: AutoAnalysisEnabledSetting
+ ) {}
+
+ /**
+ * Get command registrations (don't register them yet)
+ * This follows the "nested dolls" architecture pattern
+ */
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ autoAnalysisEnabledSetting: AutoAnalysisEnabledSetting,
+ refreshCallback: () => void
+ ): CommandRegistration[] {
+ const commands = new AutoAnalysisEnabledCommands(context, autoAnalysisEnabledSetting);
+
+ return [
+ {
+ commandId: 'codeXR.analysis.toggleAutoAnalysisEnabled',
+ callback: () => commands.toggleAutoAnalysisEnabled(refreshCallback),
+ description: 'Toggle Auto-Analysis Enabled/Disabled state'
+ }
+ ];
+ }
+
+ private async refreshActiveWatchers(): Promise {
+ await SessionWatcherManager.refreshActiveWatcherConfigurations(this.context);
+ }
+
+ /**
+ * Toggle auto-analysis enabled state command handler
+ */
+ private async toggleAutoAnalysisEnabled(refreshCallback: () => void): Promise {
+ try {
+ logger.debug('Toggling auto-analysis enabled state');
+
+ const newState = await this.autoAnalysisEnabledSetting.toggleEnabled();
+ await this.refreshActiveWatchers();
+ logger.debug(() => `Auto-analysis enabled toggled to: ${newState}`);
+
+ refreshCallback();
+
+ } catch (error) {
+ logger.error('Error toggling auto-analysis enabled state:', error);
+ void vscode.window.showErrorMessage(`Failed to toggle auto-analysis state: ${error}`);
+ }
+ }
+}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-directory/chartTypeDirectory.ts b/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-directory/chartTypeDirectory.ts
new file mode 100644
index 000000000..bf7708e6d
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-directory/chartTypeDirectory.ts
@@ -0,0 +1,108 @@
+/**
+ * Chart Type Directory Setting Item
+ * Manages the chart type configuration for directory analysis
+ */
+
+import * as vscode from 'vscode';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
+import type { ChartType, AnalysisDirectoryMode as AnalysisMode } from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { BabiaChartRegistry } from '../../../../../core/charts/chartRegistry';
+import {
+ ChartTypeInfo as SharedChartTypeInfo,
+ createChartTypeSettingItem,
+ showChartTypeSelection,
+ toChartTypeInfos,
+} from '../sharedChartTypeSettingCore';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('CHART_TYPE_DIRECTORY');
+
+export type { AnalysisMode, ChartType };
+export type ChartTypeInfo = SharedChartTypeInfo;
+
+const DIRECTORY_MODES: AnalysisMode[] = ['XR', 'XRDeep', 'LivePanel', 'LivePanelDeep'];
+
+export class ChartTypeDirectorySetting {
+ private storage: AnalysisConfigurationStorage;
+ private chartRegistry: BabiaChartRegistry;
+
+ constructor(context: vscode.ExtensionContext) {
+ this.storage = AnalysisConfigurationStorage.getInstance(context);
+ this.chartRegistry = BabiaChartRegistry.getInstance();
+ }
+
+ /**
+ * Get the tree item for this setting
+ */
+ async getSettingItem(): Promise {
+ const currentChartType = await this.getCurrentChartType();
+ const currentMode = await this.getCurrentAnalysisMode();
+
+ // Get chart metadata
+ const chartMetadata = this.chartRegistry.getChart(currentChartType);
+ const chartName = chartMetadata ? chartMetadata.name : 'Unknown Chart';
+
+ return createChartTypeSettingItem(
+ {
+ labelPrefix: 'Chart Type (Directory)',
+ commandId: 'codeXR.analysis.selectChartTypeDirectory',
+ commandTitle: 'Select Chart Type for Directory Analysis',
+ contextValue: 'chartTypeDirectorySetting',
+ },
+ chartName,
+ currentMode,
+ `${currentMode} Mode`,
+ );
+ }
+
+ /**
+ * Get current chart type for directory analysis
+ */
+ async getCurrentChartType(): Promise {
+ return await this.storage.getDirectoryChartType();
+ }
+
+ /**
+ * Set chart type for current mode
+ */
+ async setChartType(chartType: ChartType): Promise {
+ await this.storage.setDirectoryChartType(chartType);
+ logger.debug(() => `Set chart type: ${chartType}`);
+
+ // Clear all dimension mappings when chart type changes
+ await this.storage.setDimensionMappingDirectory({});
+ logger.debug(() => `Dimension mappings cleared for new chart type: ${chartType}`);
+ }
+
+ /**
+ * Get current analysis mode (directory mode)
+ */
+ private async getCurrentAnalysisMode(): Promise {
+ return await this.storage.getAnalysisDirectoryMode();
+ }
+
+ /**
+ * Get available chart types for the given mode
+ */
+ async getAvailableChartTypes(mode: AnalysisMode): Promise {
+ // All charts support all modes for directories
+ return toChartTypeInfos(this.chartRegistry.getAllCharts(), DIRECTORY_MODES)
+ .filter(chart => chart.supportsMode.includes(mode));
+ }
+
+ /**
+ * Show chart type selection dialog
+ */
+ async showChartTypeSelection(): Promise {
+ return showChartTypeSelection({
+ logPrefix: 'CHART_TYPE_DIRECTORY',
+ quickPickPlaceHolder: 'Select a chart type for directory analysis visualization',
+ quickPickTitle: (mode) => `Chart Type Selection for ${mode} Directory Analysis`,
+ confirmation: (chartName, mode) => `Chart type set to: ${chartName} for ${mode} directory analysis`,
+ getCurrentAnalysisMode: () => this.getCurrentAnalysisMode(),
+ getAvailableChartTypes: (mode) => this.getAvailableChartTypes(mode),
+ setChartType: (chartId) => this.setChartType(chartId as ChartType),
+ });
+ }
+}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-directory/chartTypeDirectoryCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-directory/chartTypeDirectoryCommands.ts
new file mode 100644
index 000000000..ce09b9458
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-directory/chartTypeDirectoryCommands.ts
@@ -0,0 +1,36 @@
+/**
+ * Chart Type Directory Commands
+ * Commands specific to the Chart Type (Directory) setting
+ */
+
+import * as vscode from 'vscode';
+import { ChartTypeDirectorySetting } from './chartTypeDirectory';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { createChartTypeCommands } from '../chartTypeCommandFactory';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('CHART_TYPE_DIRECTORY_COMMANDS');
+
+export class ChartTypeDirectoryCommands {
+ /**
+ * Get command registrations (don't register them yet)
+ * This follows the "nested dolls" architecture pattern
+ */
+ static getCommandRegistrations(
+ _context: vscode.ExtensionContext,
+ chartTypeDirectorySetting: ChartTypeDirectorySetting,
+ refreshCallback: () => void
+ ): CommandRegistration[] {
+ return createChartTypeCommands({
+ commandId: 'codeXR.analysis.selectChartTypeDirectory',
+ description: 'Select chart type for directory analysis visualization',
+ showSelection: () => chartTypeDirectorySetting.showChartTypeSelection(),
+ refreshCallback,
+ logger,
+ reportError: (error) => {
+ logger.error('Error in chart type selection:', error);
+ void vscode.window.showErrorMessage(`Failed to select chart type: ${error instanceof Error ? error.message : String(error)}`);
+ },
+ });
+ }
+}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-file/chartTypeFile.ts b/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-file/chartTypeFile.ts
new file mode 100644
index 000000000..71be59b1d
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-file/chartTypeFile.ts
@@ -0,0 +1,124 @@
+/**
+ * Chart Type File Setting Item
+ * Manages the chart type configuration for file analysis
+ */
+
+import * as vscode from 'vscode';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
+import type { ChartType, AnalysisFileMode as AnalysisMode } from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { BabiaChartRegistry } from '../../../../../core/charts/chartRegistry';
+import {
+ ChartTypeInfo as SharedChartTypeInfo,
+ createChartTypeSettingItem,
+ showChartTypeSelection,
+ toChartTypeInfos,
+} from '../sharedChartTypeSettingCore';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('CHART_TYPE_FILE');
+
+export type { AnalysisMode, ChartType };
+export type ChartTypeInfo = SharedChartTypeInfo;
+
+export class ChartTypeFileSetting {
+ private storage: AnalysisConfigurationStorage;
+ private chartRegistry: BabiaChartRegistry;
+
+ constructor(context: vscode.ExtensionContext) {
+ this.storage = AnalysisConfigurationStorage.getInstance(context);
+ this.chartRegistry = BabiaChartRegistry.getInstance();
+ }
+
+ /**
+ * Get the tree item for this setting
+ */
+ async getSettingItem(): Promise {
+ // Get current values from storage
+ const currentMode = await this.storage.getAnalysisMode();
+ const currentChartType = await this.storage.getChartTypeFile();
+
+ // Get chart metadata for better display
+ const chartMetadata = this.chartRegistry.getChart(currentChartType);
+ const chartName = chartMetadata ? chartMetadata.name : currentChartType;
+
+ return createChartTypeSettingItem(
+ {
+ labelPrefix: 'Chart Type (File)',
+ commandId: 'codeXR.analysis.selectChartTypeFile',
+ commandTitle: 'Select Chart Type for File Analysis',
+ contextValue: 'chartTypeFileSetting',
+ },
+ chartName,
+ currentMode,
+ `${chartName} for XR mode`,
+ );
+ }
+
+ /**
+ * Get current analysis mode
+ */
+ async getCurrentAnalysisMode(): Promise {
+ return this.storage.getAnalysisMode();
+ }
+
+ /**
+ * Get available chart types based on analysis mode
+ */
+ async getAvailableChartTypes(mode: AnalysisMode): Promise {
+ logger.debug(() => `Getting available charts for mode: ${mode}`);
+
+ // All charts support both modes
+ const chartTypeInfos = toChartTypeInfos(this.chartRegistry.getAllCharts(), ['XR', 'LivePanel']);
+
+ logger.debug(() => `Found ${chartTypeInfos.length} available charts`);
+ return chartTypeInfos;
+ }
+
+ /**
+ * Show chart type selection dialog
+ */
+ async showChartTypeSelection(): Promise {
+ return showChartTypeSelection({
+ logPrefix: 'CHART_TYPE_FILE',
+ quickPickPlaceHolder: 'Select a chart type for file analysis visualization',
+ quickPickTitle: (mode) => `Chart Type Selection for ${mode} Analysis`,
+ confirmation: (chartName, mode) => `Chart type set to: ${chartName} for ${mode} mode`,
+ getCurrentAnalysisMode: () => this.getCurrentAnalysisMode(),
+ getAvailableChartTypes: (mode) => this.getAvailableChartTypes(mode),
+ setChartType: (chartId) => this.setChartType(chartId),
+ });
+ }
+
+ /**
+ * Set chart type and intelligently clean dimension mappings
+ */
+ async setChartType(chartType: string): Promise {
+ logger.debug(() => `Setting chart type to: ${chartType}`);
+
+ // Validate chart type exists
+ if (!this.chartRegistry.hasChart(chartType)) {
+ throw new Error(`Invalid chart type: ${chartType}`);
+ }
+
+ // Get current dimension mappings before changing chart type
+ const currentMappings = await this.storage.getDimensionMappingFile();
+ logger.debug(`[DIMENSION_CLEANER] Current mappings before chart change:`, currentMappings);
+
+ // Save the new chart type
+ const validChartType = chartType as ChartType;
+ await this.storage.setChartTypeFile(validChartType);
+ logger.debug(() => `Chart type saved successfully: ${chartType}`);
+
+ // Clear all dimension mappings when chart type changes
+ await this.storage.setDimensionMappingFile({});
+ logger.debug(() => `Dimension mappings cleared for new chart type: ${chartType}`);
+ }
+
+ /**
+ * Get current chart type
+ */
+ async getCurrentChartType(): Promise {
+ return this.storage.getChartTypeFile();
+ }
+}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-file/chartTypeFileCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-file/chartTypeFileCommands.ts
new file mode 100644
index 000000000..910c37fdb
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/chart-type-file/chartTypeFileCommands.ts
@@ -0,0 +1,36 @@
+/**
+ * Chart Type File Commands
+ * Commands specific to the Chart Type (File) setting
+ */
+
+import * as vscode from 'vscode';
+import { ChartTypeFileSetting } from './chartTypeFile';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { createChartTypeCommands } from '../chartTypeCommandFactory';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('CHART_TYPE_FILE_COMMANDS');
+
+export class ChartTypeFileCommands {
+ /**
+ * Get command registrations (don't register them yet)
+ * This follows the "nested dolls" architecture pattern
+ */
+ static getCommandRegistrations(
+ _context: vscode.ExtensionContext,
+ chartTypeFileSetting: ChartTypeFileSetting,
+ refreshCallback: () => void
+ ): CommandRegistration[] {
+ return createChartTypeCommands({
+ commandId: 'codeXR.analysis.selectChartTypeFile',
+ description: 'Select chart type for file analysis visualization',
+ showSelection: () => chartTypeFileSetting.showChartTypeSelection(),
+ refreshCallback,
+ logger,
+ reportError: (error) => {
+ logger.error('Error selecting chart type:', error);
+ void vscode.window.showErrorMessage(`Failed to select chart type: ${error}`);
+ },
+ });
+ }
+}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/chartTypeCommandFactory.ts b/apps/vscode-extension/src/features/analysis/sections/settings/chartTypeCommandFactory.ts
new file mode 100644
index 000000000..adc28d77f
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/chartTypeCommandFactory.ts
@@ -0,0 +1,39 @@
+/**
+ * Chart Type Command Factory
+ * The one "select chart type" command shape shared by the file and
+ * directory settings. Each caller passes its own id, description, logger
+ * and error reporting, so the two error dialects stay as they were.
+ */
+
+import { CommandRegistration } from './analysis-file-mode/analysisFileModeCommands';
+import type { ScopedLogger } from '../../../../platform/logging/sink';
+
+export interface ChartTypeCommandOptions {
+ commandId: string;
+ description: string;
+ /** Opens the setting's chart-type quick pick. */
+ showSelection: () => Promise;
+ refreshCallback: () => void;
+ logger: ScopedLogger;
+ /** Logs and shows a failure of showSelection, in the caller's own words. */
+ reportError: (error: unknown) => void;
+}
+
+export function createChartTypeCommands(options: ChartTypeCommandOptions): CommandRegistration[] {
+ return [
+ {
+ commandId: options.commandId,
+ callback: async () => {
+ options.logger.debug('Chart type selection command executed');
+ try {
+ // Use the chart type setting's built-in selection dialog
+ await options.showSelection();
+ } catch (error) {
+ options.reportError(error);
+ }
+ options.refreshCallback();
+ },
+ description: options.description,
+ },
+ ];
+}
diff --git a/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_directory/dimensionMappingDirectory.ts b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-directory/dimensionMappingDirectory.ts
similarity index 93%
rename from src/code_analysis/views/subsections/analysis_settings/dimension_mapping_directory/dimensionMappingDirectory.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-directory/dimensionMappingDirectory.ts
index 9b7bfb909..a434b57ba 100644
--- a/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_directory/dimensionMappingDirectory.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-directory/dimensionMappingDirectory.ts
@@ -4,8 +4,8 @@
*/
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../../items/analysisItems';
-import { SharedDimensionMappingSettingCore } from '../dimension_mapping_shared/sharedDimensionMappingSettingCore';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { SharedDimensionMappingSettingCore } from '../sharedDimensionMappingSettingCore';
export class DimensionMappingDirectorySetting {
private readonly core: SharedDimensionMappingSettingCore;
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-directory/dimensionMappingDirectoryCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-directory/dimensionMappingDirectoryCommands.ts
new file mode 100644
index 000000000..eb2f9443f
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-directory/dimensionMappingDirectoryCommands.ts
@@ -0,0 +1,44 @@
+/**
+ * Dimension Mapping Directory Commands
+ * Commands specific to the Dimension Mapping (Directory) setting
+ */
+
+import * as vscode from 'vscode';
+import { DimensionMappingDirectorySetting } from './dimensionMappingDirectory';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('DIMENSION_MAPPING_DIRECTORY_COMMANDS');
+
+export class DimensionMappingDirectoryCommands {
+ constructor(private readonly dimensionMappingDirectorySetting: DimensionMappingDirectorySetting) {}
+
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ dimensionMappingDirectorySetting: DimensionMappingDirectorySetting,
+ refreshCallback: () => void,
+ ): CommandRegistration[] {
+ void context;
+ const commands = new DimensionMappingDirectoryCommands(dimensionMappingDirectorySetting);
+
+ return [
+ {
+ commandId: 'codeXR.analysis.selectDimensionMappingDirectory',
+ callback: async (dimensionName: string) => {
+ await commands.selectDimensionMapping(dimensionName);
+ refreshCallback();
+ },
+ description: 'Select dimension mapping for directory analysis visualization',
+ },
+ ];
+ }
+
+ private async selectDimensionMapping(dimensionName: string): Promise {
+ try {
+ await this.dimensionMappingDirectorySetting.showDimensionMappingSelection(dimensionName);
+ } catch (error) {
+ logger.error('Error in selectDimensionMapping:', error);
+ void vscode.window.showErrorMessage(`Failed to show dimension mapping selection: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+}
diff --git a/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_file/dimensionMappingFile.ts b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-file/dimensionMappingFile.ts
similarity index 93%
rename from src/code_analysis/views/subsections/analysis_settings/dimension_mapping_file/dimensionMappingFile.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-file/dimensionMappingFile.ts
index 61788dc3a..92f1efd4f 100644
--- a/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_file/dimensionMappingFile.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-file/dimensionMappingFile.ts
@@ -4,8 +4,8 @@
*/
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../../items/analysisItems';
-import { SharedDimensionMappingSettingCore } from '../dimension_mapping_shared/sharedDimensionMappingSettingCore';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { SharedDimensionMappingSettingCore } from '../sharedDimensionMappingSettingCore';
export class DimensionMappingFileSetting {
private readonly core: SharedDimensionMappingSettingCore;
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-file/dimensionMappingFileCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-file/dimensionMappingFileCommands.ts
new file mode 100644
index 000000000..a611e59d6
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-file/dimensionMappingFileCommands.ts
@@ -0,0 +1,44 @@
+/**
+ * Dimension Mapping File Commands
+ * Commands specific to the Dimension Mapping (File) setting.
+ */
+
+import * as vscode from 'vscode';
+import { DimensionMappingFileSetting } from './dimensionMappingFile';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('DIMENSION_MAPPING_FILE_COMMANDS');
+
+export class DimensionMappingFileCommands {
+ constructor(private readonly dimensionMappingSetting: DimensionMappingFileSetting) {}
+
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ dimensionMappingSetting: DimensionMappingFileSetting,
+ refreshCallback: () => void,
+ ): CommandRegistration[] {
+ void context;
+ const commands = new DimensionMappingFileCommands(dimensionMappingSetting);
+
+ return [
+ {
+ commandId: 'codeXR.analysis.selectDimensionMappingFile',
+ callback: async (dimensionName: string) => {
+ await commands.selectDimensionMapping(dimensionName);
+ refreshCallback();
+ },
+ description: 'Select dimension mapping for a specific chart dimension',
+ },
+ ];
+ }
+
+ private async selectDimensionMapping(dimensionName: string): Promise {
+ try {
+ await this.dimensionMappingSetting.showDimensionMappingSelection(dimensionName);
+ } catch (error) {
+ logger.error('Error selecting dimension mapping:', error);
+ void vscode.window.showErrorMessage(`Failed to select dimension mapping: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+}
diff --git a/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_file/dimensionMappingValidator.ts b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-file/dimensionMappingValidator.ts
similarity index 90%
rename from src/code_analysis/views/subsections/analysis_settings/dimension_mapping_file/dimensionMappingValidator.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-file/dimensionMappingValidator.ts
index 752d0f5ff..8c9493455 100644
--- a/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_file/dimensionMappingValidator.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/dimension-mapping-file/dimensionMappingValidator.ts
@@ -3,10 +3,13 @@
* Validates dimension mappings for conflicts, completeness, and data-type compatibility.
*/
-import { ChartMetadata } from '../../../../../babia_templates/models/chartModels';
-import { chartTemplates } from '../../../../../babia_templates/charts/templateCharts';
-import { DimensionMapping } from '../../../../configuration/models/analysisConfiguration';
-import { XRFieldTypeMap } from '../../../../services/xrFieldSchemaService';
+import { ChartMetadata } from '../../../../../core/charts/chartModels';
+import { chartTemplates } from '../../../../../core/charts/templateCharts';
+import { DimensionMapping } from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { XRFieldTypeMap } from '../../../../../core/analysis/python/xrFieldSchemaService';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('DIMENSION_MAPPING_VALIDATOR');
export interface DimensionValidationResult {
isValid: boolean;
@@ -41,8 +44,8 @@ export class DimensionMappingValidator {
currentMappings: DimensionMapping,
fieldTypes?: XRFieldTypeMap,
): DimensionValidationResult {
- console.log(`[DIMENSION_VALIDATOR] Validating mappings for chart: ${chartType}`);
- console.log(`[DIMENSION_VALIDATOR] Current mappings:`, currentMappings);
+ logger.debug(() => `[DIMENSION_VALIDATOR] Validating mappings for chart: ${chartType}`);
+ logger.debug(`[DIMENSION_VALIDATOR] Current mappings:`, currentMappings);
const chart = chartTemplates.find((candidate) => candidate.id === chartType);
if (!chart) {
@@ -98,7 +101,7 @@ export class DimensionMappingValidator {
errors,
};
- console.log('[DIMENSION_VALIDATOR] Validation result:', result);
+ logger.debug('[DIMENSION_VALIDATOR] Validation result:', result);
return result;
}
diff --git a/src/code_analysis/views/subsections/analysis_settings/files_by_language_sorting/filesByLanguageSorting.ts b/apps/vscode-extension/src/features/analysis/sections/settings/files-by-language-sorting/filesByLanguageSorting.ts
similarity index 92%
rename from src/code_analysis/views/subsections/analysis_settings/files_by_language_sorting/filesByLanguageSorting.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/files-by-language-sorting/filesByLanguageSorting.ts
index 9218520ee..868883e96 100644
--- a/src/code_analysis/views/subsections/analysis_settings/files_by_language_sorting/filesByLanguageSorting.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/files-by-language-sorting/filesByLanguageSorting.ts
@@ -4,15 +4,18 @@
*/
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../../items/analysisItems';
-import { AnalysisConfigurationStorage } from '../../../../configuration';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
import {
FilesByLanguageSortingConfig,
LanguageGroupSortBy,
LanguageGroupSortDirection,
FilesSortBy,
FilesSortDirection
-} from '../../../../configuration/models/analysisConfiguration';
+} from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('FILES_BY_LANGUAGE_SORTING');
export class FilesByLanguageSortingSetting {
private storage: AnalysisConfigurationStorage;
@@ -50,7 +53,7 @@ export class FilesByLanguageSortingSetting {
* Get children items (sorting options)
*/
async getChildren(): Promise {
- console.log('FILES_BY_LANGUAGE_SORTING: Getting children');
+ logger.debug('Getting children');
const children: CodeAnalysisTreeItem[] = [];
const currentConfig = await this.storage.getFilesByLanguageSorting();
@@ -107,7 +110,7 @@ export class FilesByLanguageSortingSetting {
'filesSorting'
));
- console.log(`FILES_BY_LANGUAGE_SORTING: Generated ${children.length} sorting options`);
+ logger.debug(() => `Generated ${children.length} sorting options`);
return children;
}
diff --git a/src/code_analysis/commands/subsections/analysis_settings/filesByLanguageSortingCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/files-by-language-sorting/filesByLanguageSortingCommands.ts
similarity index 84%
rename from src/code_analysis/commands/subsections/analysis_settings/filesByLanguageSortingCommands.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/files-by-language-sorting/filesByLanguageSortingCommands.ts
index 06887562c..a80bf7b2d 100644
--- a/src/code_analysis/commands/subsections/analysis_settings/filesByLanguageSortingCommands.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/files-by-language-sorting/filesByLanguageSortingCommands.ts
@@ -4,15 +4,18 @@
*/
import * as vscode from 'vscode';
-import { CommandRegistration } from './analysis_file_mode';
-import { FilesByLanguageSortingSetting } from '../../../views/subsections/analysis_settings/files_by_language_sorting';
-import { AnalysisConfigurationStorage } from '../../../configuration/analysisConfigurationStorage';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { FilesByLanguageSortingSetting } from './filesByLanguageSorting';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
import {
LanguageGroupSortBy,
LanguageGroupSortDirection,
FilesSortBy,
FilesSortDirection
-} from '../../../configuration/models/analysisConfiguration';
+} from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('ANALYSIS');
export class FilesByLanguageSortingCommands {
@@ -24,7 +27,7 @@ export class FilesByLanguageSortingCommands {
filesByLanguageSortingSetting: FilesByLanguageSortingSetting,
refreshCallback: () => void
): CommandRegistration[] {
- console.log('ANALYSIS: Collecting Files by Language Sorting command registrations');
+ logger.debug('Collecting Files by Language Sorting command registrations');
const commandRegistrations: CommandRegistration[] = [
// Language Group Primary Sorting
@@ -55,7 +58,7 @@ export class FilesByLanguageSortingCommands {
}
];
- console.log(`ANALYSIS: Collected ${commandRegistrations.length} Files by Language Sorting command registrations`);
+ logger.debug(() => `Collected ${commandRegistrations.length} Files by Language Sorting command registrations`);
return commandRegistrations;
}
@@ -67,7 +70,7 @@ export class FilesByLanguageSortingCommands {
setting: FilesByLanguageSortingSetting,
refreshCallback: () => void
): Promise {
- console.log('ANALYSIS: Showing language group primary sorting picker');
+ logger.debug('Showing language group primary sorting picker');
// Get current configuration to check for conflicts
const storage = AnalysisConfigurationStorage.getInstance(context);
@@ -92,14 +95,14 @@ export class FilesByLanguageSortingCommands {
// If secondary uses the same type as the new primary, reset secondary to None
if (currentSecondarySortBy && currentSecondarySortBy === newPrimarySortBy) {
- console.log('ANALYSIS: Primary conflicts with secondary, resetting secondary to None');
+ logger.debug('Primary conflicts with secondary, resetting secondary to None');
await setting.updateLanguageGroupSecondarySorting(undefined, undefined);
- vscode.window.showInformationMessage(`Secondary sorting reset to None to avoid conflict with primary sorting`);
+ void vscode.window.showInformationMessage(`Secondary sorting reset to None to avoid conflict with primary sorting`);
}
await setting.updateLanguageGroupPrimarySorting(picked.sortBy, picked.direction);
refreshCallback();
- vscode.window.showInformationMessage(`Language groups primary sorting changed to: ${picked.label}`);
+ void vscode.window.showInformationMessage(`Language groups primary sorting changed to: ${picked.label}`);
}
}
@@ -111,7 +114,7 @@ export class FilesByLanguageSortingCommands {
setting: FilesByLanguageSortingSetting,
refreshCallback: () => void
): Promise {
- console.log('ANALYSIS: Showing language group secondary sorting picker');
+ logger.debug('Showing language group secondary sorting picker');
// Get current configuration to determine what's available for secondary
const storage = AnalysisConfigurationStorage.getInstance(context);
@@ -147,7 +150,7 @@ export class FilesByLanguageSortingCommands {
const message = picked.sortBy ?
`Language groups secondary sorting changed to: ${picked.label}` :
'Language groups secondary sorting disabled';
- vscode.window.showInformationMessage(message);
+ void vscode.window.showInformationMessage(message);
}
}
@@ -158,7 +161,7 @@ export class FilesByLanguageSortingCommands {
setting: FilesByLanguageSortingSetting,
refreshCallback: () => void
): Promise {
- console.log('ANALYSIS: Showing files sorting picker');
+ logger.debug('Showing files sorting picker');
const options = [
{ label: 'Alphabetical Ascending', sortBy: 'alphabetical' as FilesSortBy, direction: 'ascending' as FilesSortDirection },
@@ -175,7 +178,7 @@ export class FilesByLanguageSortingCommands {
if (picked) {
await setting.updateFilesSorting(picked.sortBy, picked.direction);
refreshCallback();
- vscode.window.showInformationMessage(`Files sorting changed to: ${picked.label}`);
+ void vscode.window.showInformationMessage(`Files sorting changed to: ${picked.label}`);
}
}
}
diff --git a/src/code_analysis/utils/filesByLanguageSortingUtils.ts b/apps/vscode-extension/src/features/analysis/sections/settings/files-by-language-sorting/filesByLanguageSortingUtils.ts
similarity index 91%
rename from src/code_analysis/utils/filesByLanguageSortingUtils.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/files-by-language-sorting/filesByLanguageSortingUtils.ts
index 5f6cda476..bb35706ff 100644
--- a/src/code_analysis/utils/filesByLanguageSortingUtils.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/files-by-language-sorting/filesByLanguageSortingUtils.ts
@@ -8,11 +8,12 @@ import * as path from 'path';
import {
FilesByLanguageSortingConfig,
LanguageGroupSortBy,
- LanguageGroupSortDirection,
- FilesSortBy,
- FilesSortDirection
-} from '../configuration/models/analysisConfiguration';
-import { FilesByLanguage } from './workspaceFileScanner';
+ LanguageGroupSortDirection
+} from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { FilesByLanguage } from '../../../workspace/workspaceFileScanner';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('FILES_BY_LANGUAGE_SORTING_UTILS');
export interface LanguageGroupWithMetadata {
languageName: string;
@@ -94,7 +95,7 @@ export class FilesByLanguageSortingUtils {
const stat = await vscode.workspace.fs.stat(fileUri);
return { filePath, mtime: stat.mtime };
} catch (error) {
- console.warn(`Failed to get stat for file: ${filePath}`, error);
+ logger.warn(`Failed to get stat for file: ${filePath}`, error);
return { filePath, mtime: 0 };
}
})
diff --git a/src/code_analysis/views/subsections/analysis_settings/profile_configuration/profileConfiguration.ts b/apps/vscode-extension/src/features/analysis/sections/settings/profile-configuration/profileConfiguration.ts
similarity index 79%
rename from src/code_analysis/views/subsections/analysis_settings/profile_configuration/profileConfiguration.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/profile-configuration/profileConfiguration.ts
index c9eab1d1a..3f0aa7d99 100644
--- a/src/code_analysis/views/subsections/analysis_settings/profile_configuration/profileConfiguration.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/profile-configuration/profileConfiguration.ts
@@ -4,23 +4,26 @@
*/
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../../items/analysisItems';
-import { AnalysisConfigurationStorage } from '../../../../configuration/analysisConfigurationStorage';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('PROFILE_CONFIGURATION');
export class ProfileConfigurationSetting {
constructor(
- private context: vscode.ExtensionContext,
+ _context: vscode.ExtensionContext,
private storage: AnalysisConfigurationStorage
) {
- console.log('PROFILE_CONFIGURATION: Initializing Profile Configuration setting');
+ logger.debug('Initializing Profile Configuration setting');
}
/**
* Get the setting item (collapsible)
*/
async getSettingItem(): Promise {
- console.log('PROFILE_CONFIGURATION: Creating profile configuration setting item');
+ logger.debug('Creating profile configuration setting item');
return new CodeAnalysisTreeItem(
'Profile Configuration',
@@ -38,7 +41,7 @@ export class ProfileConfigurationSetting {
* Get children items for Profile Configuration
*/
async getChildren(): Promise {
- console.log('PROFILE_CONFIGURATION: Getting Profile Configuration children');
+ logger.debug('Getting Profile Configuration children');
const children: CodeAnalysisTreeItem[] = [];
@@ -106,7 +109,7 @@ export class ProfileConfigurationSetting {
'deleteProfile'
));
- console.log(`PROFILE_CONFIGURATION: Created ${children.length} profile configuration items`);
+ logger.debug(() => `Created ${children.length} profile configuration items`);
return children;
}
@@ -147,24 +150,11 @@ export class ProfileConfigurationSetting {
};
}
- /**
- * Detect user's VS Code theme
- */
- private detectVSCodeTheme(): 'light' | 'dark' | 'auto' {
- const colorTheme = vscode.window.activeColorTheme;
- if (colorTheme.kind === vscode.ColorThemeKind.Light) {
- return 'light';
- } else if (colorTheme.kind === vscode.ColorThemeKind.Dark || colorTheme.kind === vscode.ColorThemeKind.HighContrast) {
- return 'dark';
- }
- return 'dark'; // Default fallback
- }
-
/**
* Reset configuration to defaults
*/
async resetToDefaults(): Promise {
- console.log('PROFILE_CONFIGURATION: Resetting to default values');
+ logger.debug('Resetting to default values');
try {
const defaults = this.getDefaultConfiguration();
@@ -185,12 +175,12 @@ export class ProfileConfigurationSetting {
await this.storage.setFilesByLanguageSorting(defaults.filesByLanguageSorting);
await this.storage.setXRBabiaUiConfig(defaults.xrBabiaUi);
- console.log('PROFILE_CONFIGURATION: Successfully reset to defaults:', defaults);
- vscode.window.showInformationMessage('Analysis settings reset to default values');
+ logger.debug('Successfully reset to defaults:', defaults);
+ void vscode.window.showInformationMessage('Analysis settings reset to default values');
} catch (error) {
- console.error('PROFILE_CONFIGURATION: Error resetting to defaults:', error);
- vscode.window.showErrorMessage(`Failed to reset to defaults: ${error}`);
+ logger.error('Error resetting to defaults:', error);
+ void vscode.window.showErrorMessage(`Failed to reset to defaults: ${error}`);
throw error;
}
}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/profile-configuration/profileConfigurationCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/profile-configuration/profileConfigurationCommands.ts
new file mode 100644
index 000000000..cb4749f7f
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/profile-configuration/profileConfigurationCommands.ts
@@ -0,0 +1,330 @@
+/**
+ * Profile Configuration Commands
+ * Commands for managing analysis configuration profiles
+ */
+
+import * as vscode from 'vscode';
+import * as fs from 'fs';
+import * as path from 'path';
+import { ProfileConfigurationSetting } from './profileConfiguration';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('PROFILE_CONFIGURATION_COMMANDS');
+
+interface StoredProfileItem {
+ label: string;
+ description: string;
+ detail: string;
+ profilePath: string;
+}
+
+export class ProfileConfigurationCommands {
+
+ constructor(
+ private context: vscode.ExtensionContext,
+ private profileConfigurationSetting: ProfileConfigurationSetting
+ ) {}
+
+ /**
+ * Get command registrations (don't register them yet)
+ * This follows the "nested dolls" architecture pattern
+ */
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ profileConfigurationSetting: ProfileConfigurationSetting,
+ refreshCallback: () => void
+ ): CommandRegistration[] {
+ logger.debug('Creating command registrations');
+ const commands = new ProfileConfigurationCommands(context, profileConfigurationSetting);
+
+ const registrations = [
+ {
+ commandId: 'codeXR.analysis.resetToDefaults',
+ callback: async () => {
+ logger.debug(`Reset to defaults command TRIGGERED`);
+ await commands.resetToDefaults();
+ refreshCallback();
+ },
+ description: 'Reset analysis settings to default values'
+ },
+ {
+ commandId: 'codeXR.analysis.saveProfile',
+ callback: async () => {
+ logger.debug(`Save profile command TRIGGERED`);
+ await commands.saveProfile();
+ refreshCallback();
+ },
+ description: 'Save current configuration as a named profile'
+ },
+ {
+ commandId: 'codeXR.analysis.loadProfile',
+ callback: async () => {
+ logger.debug(`Load profile command TRIGGERED`);
+ await commands.loadProfile();
+ refreshCallback();
+ },
+ description: 'Load a previously saved configuration profile'
+ },
+ {
+ commandId: 'codeXR.analysis.deleteProfile',
+ callback: async () => {
+ logger.debug(`Delete profile command TRIGGERED`);
+ await commands.deleteProfile();
+ refreshCallback();
+ },
+ description: 'Delete a previously saved configuration profile'
+ }
+ ];
+
+ logger.debug(() => `Created ${registrations.length} command registrations`);
+ return registrations;
+ }
+
+ /**
+ * Reset to default values
+ */
+ private async resetToDefaults(): Promise {
+ logger.debug('Resetting to default values');
+
+ try {
+ const shouldReset = await vscode.window.showWarningMessage(
+ 'This will reset all analysis settings to their default values. Are you sure?',
+ 'Reset to Defaults', 'Cancel'
+ );
+
+ if (shouldReset !== 'Reset to Defaults') {
+ logger.debug('Reset cancelled by user');
+ return;
+ }
+
+ // Use the profile configuration setting to reset
+ await this.profileConfigurationSetting.resetToDefaults();
+
+ logger.debug('Reset to defaults completed successfully');
+
+ } catch (error) {
+ logger.error('Error resetting to defaults:', error);
+ void vscode.window.showErrorMessage(`Failed to reset to defaults: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ /**
+ * Save current configuration as a profile
+ */
+ private async saveProfile(): Promise {
+ logger.debug('Saving profile');
+
+ try {
+ // Ask user for profile name
+ const profileName = await vscode.window.showInputBox({
+ prompt: 'Enter a name for this configuration profile',
+ placeHolder: 'e.g., "My Custom Setup", "Project A Settings"',
+ validateInput: (value) => {
+ if (!value || value.trim().length === 0) {
+ return 'Profile name cannot be empty';
+ }
+ if (value.includes('/') || value.includes('\\') || value.includes(':')) {
+ return 'Profile name cannot contain special characters (/, \\, :)';
+ }
+ return null;
+ }
+ });
+
+ if (!profileName) {
+ logger.debug('Save profile cancelled - no name provided');
+ return;
+ }
+
+ // Get current configuration from AnalysisConfigurationStorage
+ const storage = AnalysisConfigurationStorage.getInstance(this.context);
+ const currentConfig = await storage.loadConfiguration();
+
+ logger.debug('Current config to save:', JSON.stringify(currentConfig, null, 2));
+
+ // Save to globalStorage
+ const profilesDir = path.join(this.context.globalStorageUri.fsPath, 'analysis_settings');
+
+ // Create directory if it doesn't exist
+ if (!fs.existsSync(profilesDir)) {
+ fs.mkdirSync(profilesDir, { recursive: true });
+ }
+
+ const profilePath = path.join(profilesDir, `${profileName.trim()}.json`);
+
+ // Check if profile already exists
+ if (fs.existsSync(profilePath)) {
+ const shouldOverwrite = await vscode.window.showWarningMessage(
+ `A profile named "${profileName}" already exists. Do you want to overwrite it?`,
+ 'Overwrite', 'Cancel'
+ );
+
+ if (shouldOverwrite !== 'Overwrite') {
+ logger.debug('Save profile cancelled - user chose not to overwrite');
+ return;
+ }
+ }
+
+ // Add metadata to the profile
+ const profileData = {
+ name: profileName.trim(),
+ savedAt: new Date().toISOString(),
+ version: '1.0',
+ configuration: currentConfig
+ };
+
+ // Save the profile
+ fs.writeFileSync(profilePath, JSON.stringify(profileData, null, 2));
+
+ logger.debug(() => `Profile "${profileName}" saved successfully`);
+ void vscode.window.showInformationMessage(`Configuration profile "${profileName}" saved successfully`);
+
+ } catch (error) {
+ logger.error('Error saving profile:', error);
+ void vscode.window.showErrorMessage(`Failed to save profile: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ /**
+ * Load a previously saved profile
+ */
+ private async loadProfile(): Promise {
+ logger.debug('Loading profile');
+
+ try {
+ const profileItems = this.listStoredProfiles();
+ if (!profileItems) {
+ return;
+ }
+
+ // Show profile selection
+ const selectedProfile = await vscode.window.showQuickPick(profileItems, {
+ placeHolder: 'Select a configuration profile to load',
+ title: 'Load Configuration Profile'
+ });
+
+ if (!selectedProfile) {
+ logger.debug('Load profile cancelled');
+ return;
+ }
+
+ // Confirm loading
+ const shouldLoad = await vscode.window.showWarningMessage(
+ `This will replace your current configuration with "${selectedProfile.label}". Are you sure?`,
+ 'Load Profile', 'Cancel'
+ );
+
+ if (shouldLoad !== 'Load Profile') {
+ logger.debug('Load profile cancelled by user');
+ return;
+ }
+
+ // Load the profile
+ const profileData = JSON.parse(fs.readFileSync(selectedProfile.profilePath, 'utf8'));
+
+ logger.debug('Loaded profile data:', JSON.stringify(profileData.configuration, null, 2));
+
+ // Update configuration using AnalysisConfigurationStorage
+ const storage = AnalysisConfigurationStorage.getInstance(this.context);
+ await storage.updateConfiguration(profileData.configuration);
+
+ logger.debug(() => `Profile "${selectedProfile.label}" loaded successfully`);
+ void vscode.window.showInformationMessage(`Configuration profile "${selectedProfile.label}" loaded successfully`);
+
+ } catch (error) {
+ logger.error('Error loading profile:', error);
+ void vscode.window.showErrorMessage(`Failed to load profile: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ /**
+ * Delete a saved profile
+ */
+ private async deleteProfile(): Promise {
+ logger.debug('Deleting profile');
+
+ try {
+ const profileItems = this.listStoredProfiles();
+ if (!profileItems) {
+ return;
+ }
+
+ // Show profile selection
+ const selectedProfile = await vscode.window.showQuickPick(profileItems, {
+ placeHolder: 'Select a configuration profile to delete',
+ title: 'Delete Configuration Profile'
+ });
+
+ if (!selectedProfile) {
+ logger.debug('Delete profile cancelled');
+ return;
+ }
+
+ // Confirm deletion
+ const shouldDelete = await vscode.window.showWarningMessage(
+ `Are you sure you want to delete the profile "${selectedProfile.label}"? This action cannot be undone.`,
+ 'Delete Profile', 'Cancel'
+ );
+
+ if (shouldDelete !== 'Delete Profile') {
+ logger.debug('Delete profile cancelled by user');
+ return;
+ }
+
+ // Delete the profile
+ fs.unlinkSync(selectedProfile.profilePath);
+
+ logger.debug(() => `Profile "${selectedProfile.label}" deleted successfully`);
+ void vscode.window.showInformationMessage(`Configuration profile "${selectedProfile.label}" deleted successfully`);
+
+ } catch (error) {
+ logger.error('Error deleting profile:', error);
+ void vscode.window.showErrorMessage(`Failed to delete profile: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ /**
+ * The saved profiles as quick-pick items (a corrupt file is listed as
+ * such), or undefined after telling the user there are none.
+ */
+ private listStoredProfiles(): StoredProfileItem[] | undefined {
+ const profilesDir = path.join(this.context.globalStorageUri.fsPath, 'analysis_settings');
+
+ // Check if profiles directory exists
+ if (!fs.existsSync(profilesDir)) {
+ void vscode.window.showInformationMessage('No saved profiles found');
+ return undefined;
+ }
+
+ // Get list of saved profiles
+ const profileFiles = fs.readdirSync(profilesDir).filter(file => file.endsWith('.json'));
+
+ if (profileFiles.length === 0) {
+ void vscode.window.showInformationMessage('No saved profiles found');
+ return undefined;
+ }
+
+ // Create quick pick items
+ return profileFiles.map(file => {
+ const profilePath = path.join(profilesDir, file);
+ try {
+ const profileData = JSON.parse(fs.readFileSync(profilePath, 'utf8'));
+ const savedDate = new Date(profileData.savedAt).toLocaleString();
+ return {
+ label: profileData.name || file.replace('.json', ''),
+ description: `Saved: ${savedDate}`,
+ detail: `Version: ${profileData.version || 'Unknown'}`,
+ profilePath: profilePath
+ };
+ } catch {
+ return {
+ label: file.replace('.json', ''),
+ description: 'Invalid profile data',
+ detail: 'This profile may be corrupted',
+ profilePath: profilePath
+ };
+ }
+ });
+ }
+}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/sharedChartTypeSettingCore.ts b/apps/vscode-extension/src/features/analysis/sections/settings/sharedChartTypeSettingCore.ts
new file mode 100644
index 000000000..3f512d6ca
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/sharedChartTypeSettingCore.ts
@@ -0,0 +1,116 @@
+/**
+ * What the file and directory chart-type settings share: the tree row and the
+ * quick-pick flow. Each setting keeps its own storage reads, its chart list
+ * and its save, which differ (see test/analysis/chartTypeSettings.test.cjs).
+ */
+
+import * as vscode from 'vscode';
+import { CodeAnalysisTreeItem } from '../../views/analysisItems';
+import { ChartMetadata } from '../../../../core/charts/chartModels';
+import { getLogger } from '../../../../platform/logging/sink';
+
+const logger = getLogger('SHARED_CHART_TYPE_SETTING_CORE');
+
+export interface ChartTypeInfo {
+ id: string;
+ name: string;
+ description: string;
+ category: string;
+ supportsMode: Mode[];
+}
+
+export interface ChartTypeRowSpec {
+ /** "Chart Type (File)" / "Chart Type (Directory)". */
+ labelPrefix: string;
+ commandId: string;
+ commandTitle: string;
+ contextValue: string;
+}
+
+export interface ChartTypeSelectionAdapter {
+ /** Console prefix, e.g. CHART_TYPE_FILE. */
+ logPrefix: string;
+ quickPickPlaceHolder: string;
+ quickPickTitle(mode: Mode): string;
+ confirmation(chartName: string, mode: Mode): string;
+ getCurrentAnalysisMode(): Promise;
+ getAvailableChartTypes(mode: Mode): Promise[]>;
+ setChartType(chartId: string): Promise;
+}
+
+export function toChartTypeInfos(charts: ChartMetadata[], supportsMode: Mode[]): ChartTypeInfo[] {
+ return charts.map((chart) => ({
+ id: chart.id,
+ name: chart.name,
+ description: chart.description,
+ category: chart.category,
+ supportsMode: [...supportsMode],
+ }));
+}
+
+export function createChartTypeSettingItem(
+ spec: ChartTypeRowSpec,
+ chartName: string,
+ mode: string,
+ description: string,
+): CodeAnalysisTreeItem {
+ // Always use purple color for chart type icons as requested
+ const iconPath = new vscode.ThemeIcon('graph', new vscode.ThemeColor('charts.purple'));
+
+ return new CodeAnalysisTreeItem(
+ `${spec.labelPrefix}: ${chartName}`,
+ vscode.TreeItemCollapsibleState.None,
+ 'subsection',
+ {
+ command: spec.commandId,
+ title: spec.commandTitle,
+ arguments: []
+ },
+ iconPath,
+ `Current chart type: ${chartName} for ${mode} mode. Click to change chart type.`,
+ description,
+ spec.contextValue
+ );
+}
+
+export async function showChartTypeSelection(adapter: ChartTypeSelectionAdapter): Promise {
+ const prefix = adapter.logPrefix;
+ logger.debug(() => `${prefix}: Opening chart type selection dialog`);
+
+ try {
+ const currentMode = await adapter.getCurrentAnalysisMode();
+ const availableCharts = await adapter.getAvailableChartTypes(currentMode);
+
+ if (availableCharts.length === 0) {
+ logger.error(`${prefix}: No chart types found`);
+ void vscode.window.showErrorMessage('No chart templates available');
+ return;
+ }
+
+ const quickPickItems: (vscode.QuickPickItem & { chart: ChartTypeInfo })[] = availableCharts.map(chart => ({
+ label: chart.name,
+ description: chart.description,
+ detail: `Category: ${chart.category} | Supports: ${chart.supportsMode.join(', ')}`,
+ chart: chart
+ }));
+
+ const selectedItem = await vscode.window.showQuickPick(quickPickItems, {
+ placeHolder: adapter.quickPickPlaceHolder,
+ title: adapter.quickPickTitle(currentMode),
+ canPickMany: false
+ });
+
+ if (selectedItem && selectedItem.chart) {
+ const selectedChart = selectedItem.chart;
+ await adapter.setChartType(selectedChart.id);
+
+ logger.debug(() => `${prefix}: Chart type selected: ${selectedChart.name} (${selectedChart.id})`);
+ void vscode.window.showInformationMessage(adapter.confirmation(selectedChart.name, currentMode));
+ } else {
+ logger.debug(() => `${prefix}: Chart type selection cancelled`);
+ }
+ } catch (error) {
+ logger.error(`${prefix}: Error in chart type selection:`, error);
+ void vscode.window.showErrorMessage(`Failed to select chart type: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
diff --git a/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts b/apps/vscode-extension/src/features/analysis/sections/settings/sharedDimensionMappingSettingCore.ts
similarity index 90%
rename from src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/sharedDimensionMappingSettingCore.ts
index 867b52ec2..5b98951b8 100644
--- a/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/sharedDimensionMappingSettingCore.ts
@@ -1,10 +1,10 @@
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../../items/analysisItems';
-import { AnalysisConfigurationStorage } from '../../../../configuration';
-import { chartTemplates } from '../../../../../babia_templates/charts/templateCharts';
-import { ChartDimension, ChartMetadata } from '../../../../../babia_templates/models/chartModels';
-import { DimensionMappingValidator } from '../dimension_mapping_file/dimensionMappingValidator';
-import { XRFieldDefinition, XRFieldSchemaService, XRSchemaTargetType } from '../../../../services/xrFieldSchemaService';
+import { CodeAnalysisTreeItem } from '../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { chartTemplates } from '../../../../core/charts/templateCharts';
+import { ChartDimension, ChartMetadata } from '../../../../core/charts/chartModels';
+import { DimensionMappingValidator } from './dimension-mapping-file/dimensionMappingValidator';
+import { XRFieldDefinition, XRFieldSchemaService, XRSchemaTargetType } from '../../../../core/analysis/python/xrFieldSchemaService';
export interface DimensionMappingSettingAdapter {
targetType: XRSchemaTargetType;
@@ -73,7 +73,7 @@ export class SharedDimensionMappingSettingCore {
}
const chart = this.getChartMetadata(chartType);
- if (!chart || !chart.dimensions) {
+ if (!chart?.dimensions) {
return [new CodeAnalysisTreeItem(
'No dimensions available',
vscode.TreeItemCollapsibleState.None,
@@ -100,13 +100,13 @@ export class SharedDimensionMappingSettingCore {
const chartType = await this.adapter.getChartType(this.storage);
const chart = chartType ? this.getChartMetadata(chartType) : undefined;
if (!chart) {
- vscode.window.showErrorMessage('Chart type not found. Please select a valid chart type first.');
+ void vscode.window.showErrorMessage('Chart type not found. Please select a valid chart type first.');
return;
}
const dimension = chart.dimensions.find((candidate) => candidate.name === dimensionName);
if (!dimension) {
- vscode.window.showErrorMessage(`Dimension ${dimensionName} not found in chart ${chartType}.`);
+ void vscode.window.showErrorMessage(`Dimension ${dimensionName} not found in chart ${chartType}.`);
return;
}
@@ -116,7 +116,7 @@ export class SharedDimensionMappingSettingCore {
true,
);
if (!availableFields) {
- vscode.window.showWarningMessage('Python Environment Not Ready. CodeXR could not load the XR field schema yet.');
+ void vscode.window.showWarningMessage('Python Environment Not Ready. Code-XR could not load the XR field schema yet.');
return;
}
@@ -152,7 +152,7 @@ export class SharedDimensionMappingSettingCore {
if (selection.fieldId === '') {
await this.clearDimensionMapping(dimension.name);
- vscode.window.showInformationMessage(`Cleared mapping for ${dimension.label}`);
+ void vscode.window.showInformationMessage(`Cleared mapping for ${dimension.label}`);
return;
}
@@ -175,7 +175,7 @@ export class SharedDimensionMappingSettingCore {
}
await this.setDimensionMapping(dimension.name, selection.fieldId);
- vscode.window.showInformationMessage(`Mapped ${dimension.label} → ${selection.label}`);
+ void vscode.window.showInformationMessage(`Mapped ${dimension.label} → ${selection.label}`);
}
async getCurrentMappings(): Promise> {
@@ -294,7 +294,7 @@ export class SharedDimensionMappingSettingCore {
'subsection',
undefined,
new vscode.ThemeIcon('warning', new vscode.ThemeColor('charts.yellow')),
- 'CodeXR could not load the XR field schema yet. Wait for the Python environment to finish initializing and reopen this setting.',
+ 'Code-XR could not load the XR field schema yet. Wait for the Python environment to finish initializing and reopen this setting.',
'XR field schema unavailable',
this.adapter.schemaUnavailableContextValue,
);
diff --git a/src/code_analysis/views/subsections/analysis_settings/view_theme/viewTheme.ts b/apps/vscode-extension/src/features/analysis/sections/settings/view-theme/viewTheme.ts
similarity index 77%
rename from src/code_analysis/views/subsections/analysis_settings/view_theme/viewTheme.ts
rename to apps/vscode-extension/src/features/analysis/sections/settings/view-theme/viewTheme.ts
index a9699b8ed..242476bb8 100644
--- a/src/code_analysis/views/subsections/analysis_settings/view_theme/viewTheme.ts
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/view-theme/viewTheme.ts
@@ -4,18 +4,22 @@
*/
import * as vscode from 'vscode';
-import { CodeAnalysisTreeItem } from '../../../items/analysisItems';
-import { AnalysisConfigurationStorage, ViewTheme } from '../../../../configuration';
+import { CodeAnalysisTreeItem } from '../../../views/analysisItems';
+import { AnalysisConfigurationStorage } from '../../../../../core/analysis/configuration/analysisConfigurationStorage';
+import { ViewTheme } from '../../../../../core/analysis/configuration/analysisConfiguration';
+import { getLogger } from '../../../../../platform/logging/sink';
-export { ViewTheme } from '../../../../configuration';
+const logger = getLogger('ANALYSIS');
+
+export { ViewTheme } from '../../../../../core/analysis/configuration/analysisConfiguration';
export class ViewThemeSetting {
private currentTheme: ViewTheme = 'Dark';
private storage: AnalysisConfigurationStorage;
- constructor(private context: vscode.ExtensionContext) {
+ constructor(context: vscode.ExtensionContext) {
this.storage = AnalysisConfigurationStorage.getInstance(context);
- this.loadSavedTheme();
+ void this.loadSavedTheme();
}
/**
@@ -67,7 +71,7 @@ export class ViewThemeSetting {
async toggleTheme(): Promise {
this.currentTheme = this.currentTheme === 'Dark' ? 'Light' : 'Dark';
- console.log(`ANALYSIS: View theme switched to ${this.currentTheme}`);
+ logger.debug(() => `View theme switched to ${this.currentTheme}`);
await this.saveThemeToSettings();
@@ -96,9 +100,9 @@ export class ViewThemeSetting {
try {
const savedTheme = await this.storage.getViewTheme();
this.currentTheme = savedTheme;
- console.log(`ANALYSIS: Loaded view theme from storage: ${this.currentTheme}`);
+ logger.debug(() => `Loaded view theme from storage: ${this.currentTheme}`);
} catch (error) {
- console.error('ANALYSIS: Error loading saved theme, using default:', error);
+ logger.error('Error loading saved theme, using default:', error);
this.currentTheme = 'Dark'; // Fallback to default
}
}
@@ -109,9 +113,9 @@ export class ViewThemeSetting {
private async saveThemeToSettings(): Promise {
try {
await this.storage.setViewTheme(this.currentTheme);
- console.log(`ANALYSIS: Saved view theme to storage: ${this.currentTheme}`);
+ logger.debug(() => `Saved view theme to storage: ${this.currentTheme}`);
} catch (error) {
- console.error('ANALYSIS: Error saving theme to storage:', error);
+ logger.error('Error saving theme to storage:', error);
}
}
}
diff --git a/apps/vscode-extension/src/features/analysis/sections/settings/view-theme/viewThemeCommands.ts b/apps/vscode-extension/src/features/analysis/sections/settings/view-theme/viewThemeCommands.ts
new file mode 100644
index 000000000..acca3ade2
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/sections/settings/view-theme/viewThemeCommands.ts
@@ -0,0 +1,67 @@
+/**
+ * View Theme Commands
+ * Commands specific to the View Theme setting
+ */
+
+import * as vscode from 'vscode';
+import { ViewThemeSetting } from './viewTheme';
+import { CommandRegistration } from '../analysis-file-mode/analysisFileModeCommands';
+import { getLogger } from '../../../../../platform/logging/sink';
+
+const logger = getLogger('VIEW_THEME_COMMAND');
+
+export class ViewThemeCommands {
+
+ constructor(
+ _context: vscode.ExtensionContext,
+ private viewThemeSetting: ViewThemeSetting
+ ) {}
+
+ /**
+ * Get command registrations (don't register them yet)
+ * This follows the "nested dolls" architecture pattern
+ */
+ static getCommandRegistrations(
+ context: vscode.ExtensionContext,
+ viewThemeSetting: ViewThemeSetting,
+ refreshCallback: () => void
+ ): CommandRegistration[] {
+ const commands = new ViewThemeCommands(context, viewThemeSetting);
+
+ return [
+ {
+ commandId: 'codeXR.analysis.toggleViewTheme',
+ callback: () => commands.toggleViewTheme(refreshCallback),
+ description: 'Toggle View Theme between Dark and Light'
+ }
+ ];
+ }
+
+ /**
+ * Toggle view theme command handler
+ */
+ private async toggleViewTheme(refreshCallback: () => void): Promise {
+ try {
+ logger.debug('Starting toggle view theme command');
+ const newTheme = await this.viewThemeSetting.toggleTheme();
+
+ // Show notification to user
+ void vscode.window.showInformationMessage(
+ `View theme switched to: ${newTheme}`,
+ { modal: false }
+ );
+
+ logger.debug('About to call refreshCallback');
+ // Refresh the tree view to show updated state
+ refreshCallback();
+ logger.debug('refreshCallback executed');
+
+ logger.debug(() => `ANALYSIS: Command executed - View theme: ${newTheme}`);
+
+ } catch (error) {
+ logger.error('ANALYSIS: Error toggling view theme:', error);
+ void vscode.window.showErrorMessage(`Failed to toggle view theme: ${error}`);
+ }
+ }
+}
+
diff --git a/apps/vscode-extension/src/features/analysis/services/serverWatcherIntegration.ts b/apps/vscode-extension/src/features/analysis/services/serverWatcherIntegration.ts
new file mode 100644
index 000000000..458f0fe14
--- /dev/null
+++ b/apps/vscode-extension/src/features/analysis/services/serverWatcherIntegration.ts
@@ -0,0 +1,171 @@
+/**
+ * Server-Watcher Integration Service
+ * Coordinates watcher cleanup when servers or analysis sessions are closed.
+ */
+
+import * as vscode from 'vscode';
+import { UnifiedSessionRegistry } from '../../../core/analysis/session/sessionRegistry';
+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';
+import type { UnifiedAnalysisSession } from '../../../core/analysis/session/analysisSession';
+
+const logger = getLogger('SERVER_WATCHER_INTEGRATION');
+
+export class ServerWatcherIntegration {
+ private static instance: ServerWatcherIntegration;
+ private context: vscode.ExtensionContext;
+ private sessionWatcherManager: SessionWatcherManager;
+
+ private constructor(context: vscode.ExtensionContext) {
+ this.context = context;
+ this.sessionWatcherManager = new SessionWatcherManager(context);
+ logger.debug('Initializing service');
+ this.setupServerEventListeners();
+ }
+
+ public static getInstance(context?: vscode.ExtensionContext): ServerWatcherIntegration {
+ if (!ServerWatcherIntegration.instance) {
+ if (!context) {
+ throw new Error('ServerWatcherIntegration: ExtensionContext required for first initialization');
+ }
+ ServerWatcherIntegration.instance = new ServerWatcherIntegration(context);
+ }
+ return ServerWatcherIntegration.instance;
+ }
+
+ private setupServerEventListeners(): void {
+ try {
+ const serverRegistry = getActiveServerRegistry();
+ serverRegistry.onRegistryChange((event: RegistryEvent) => {
+ if (event.type === 'serverRemoved') {
+ void this.handleServerRemoved(event.serverId!, event.server!);
+ }
+ });
+ } catch (error) {
+ logger.error('Error setting up server event listeners:', error);
+ }
+ }
+
+ private async handleServerRemoved(serverId: string, server: ActiveServer): Promise {
+ try {
+ const sessionRegistry = UnifiedSessionRegistry.getInstance(this.context);
+ // 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) {
+ await this.cleanupSessionAfterServerClosure(session.id, server.port);
+ }
+ } catch (error) {
+ logger.error('Error handling server removal:', error);
+ }
+ }
+
+ private async cleanupSessionAfterServerClosure(sessionId: string, serverPort: number): Promise {
+ try {
+ const sessionRegistry = UnifiedSessionRegistry.getInstance(this.context);
+ const session = sessionRegistry.getSession(sessionId);
+ // 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');
+
+ void vscode.window.showInformationMessage(
+ `Analysis cleaned up: ${session.targetName} - ${session.analysisMode} (server on port ${serverPort} was closed)`,
+ );
+ } catch (error) {
+ logger.error(`Error cleaning up session ${sessionId}:`, error);
+ }
+ }
+
+ private async stopFileWatcherForSession(sessionId: string, filePath: string): Promise {
+ try {
+ logger.debug(() => `Stopping watchers for session ${sessionId}, target: ${filePath}`);
+ const sessionWatcherStopped = await this.sessionWatcherManager.stopWatchingSession(sessionId);
+
+ if (sessionWatcherStopped) {
+ logger.debug(() => `Stopped session watcher for session ${sessionId}`);
+ } else {
+ logger.debug(() => `No active session watcher found for session ${sessionId}`);
+ }
+ } catch (error) {
+ logger.error(`Error stopping watcher for session ${sessionId}:`, error);
+ }
+ }
+
+ private async cleanupAnalysisFiles(outputPath: string): Promise {
+ try {
+ if (outputPath && fs.existsSync(outputPath)) {
+ logger.debug(() => `Cleaning up analysis files at: ${outputPath}`);
+ }
+ } catch (error) {
+ logger.error('Error cleaning up analysis files:', error);
+ }
+ }
+
+ public async triggerManualCleanup(sessionId: string): Promise {
+ try {
+ const sessionRegistry = UnifiedSessionRegistry.getInstance(this.context);
+ const session = sessionRegistry.getSession(sessionId);
+ if (!session) {
+ return false;
+ }
+
+ // 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');
+ } catch (error) {
+ logger.error('Error in manual cleanup:', error);
+ return false;
+ }
+ }
+
+ /**
+ * 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 matchingServer = serverRegistry.getAllServers()
+ .find((server: ActiveServer) => server.metadata?.sessionId === sessionId);
+ if (matchingServer) {
+ await ServerControl.stopServer(matchingServer.id, { silent: true });
+ }
+ } catch (error) {
+ logger.error(`Error stopping the server of session ${sessionId}:`, error);
+ }
+ }
+
+ public static initialize(context: vscode.ExtensionContext): void {
+ ServerWatcherIntegration.getInstance(context);
+ logger.debug('Service initialized');
+ }
+}
diff --git a/src/code_analysis/views/AnalysisSectionProvider.ts b/apps/vscode-extension/src/features/analysis/views/AnalysisSectionProvider.ts
similarity index 87%
rename from src/code_analysis/views/AnalysisSectionProvider.ts
rename to apps/vscode-extension/src/features/analysis/views/AnalysisSectionProvider.ts
index fb0b20cd6..c789ff769 100644
--- a/src/code_analysis/views/AnalysisSectionProvider.ts
+++ b/apps/vscode-extension/src/features/analysis/views/AnalysisSectionProvider.ts
@@ -4,18 +4,16 @@
*/
import * as vscode from 'vscode';
-import { SectionProvider } from '../../views/common/baseInterfaces';
-import { CodeAnalysisTreeItem } from './items/analysisItems';
-import { CodeAnalysisInteractionHandler } from './interactions/handleAnalysisClicks';
-import { UnifiedSessionRegistry } from '../engine/core/sessionRegistry';
-import {
- AnalysisSettingsSubsectionProvider,
- ProjectByLanguageSubsectionProvider,
- FilesByLanguageSubsectionProvider,
-} from './subsections';
-import { ActiveAnalysesDataService } from './subsections/active_analyses/services/activeAnalysesDataService';
-import { WorkspaceSnapshotService } from '../services/workspaceSnapshotService';
-import { CodeXRLogger } from '../../core/logging/logger';
+import { SectionProvider } from '../../../platform/tree/baseInterfaces';
+import { CodeAnalysisTreeItem } from './analysisItems';
+import { CodeAnalysisInteractionHandler } from './handleAnalysisClicks';
+import { UnifiedSessionRegistry } from '../../../core/analysis/session/sessionRegistry';
+import { AnalysisSettingsSubsectionProvider } from '../sections/settings/analysisSettingsSubsectionProvider';
+import { ProjectByLanguageSubsectionProvider } from '../sections/project-by-language/projectByLanguageSubsectionProvider';
+import { FilesByLanguageSubsectionProvider } from '../sections/files-by-language/filesByLanguageSubsectionProvider';
+import { ActiveAnalysesDataService } from '../sections/active-analyses/activeAnalysesDataService';
+import { WorkspaceSnapshotService } from '../workspace/workspaceSnapshotService';
+import { CodeXRLogger } from '../../../platform/logging/logger';
const logger = CodeXRLogger.getLogger('ANALYSIS');
@@ -31,7 +29,7 @@ export class AnalysisSectionProvider implements SectionProvider {
+ static async handleContextMenuAction(_action: string, _item: CodeAnalysisTreeItem): Promise {
// TODO: Implementation
}
/**
* TODO: Handle double-click actions
*/
- static async handleDoubleClick(item: CodeAnalysisTreeItem): Promise {
+ static async handleDoubleClick(_item: CodeAnalysisTreeItem): Promise {
// TODO: Implementation
}
/**
* TODO: Get hover information for item
*/
- static getHoverInfo(item: CodeAnalysisTreeItem): vscode.MarkdownString | undefined {
+ static getHoverInfo(_item: CodeAnalysisTreeItem): vscode.MarkdownString | undefined {
// TODO: Implementation
return undefined;
}
diff --git a/src/code_analysis/utils/workspaceFileScanner.ts b/apps/vscode-extension/src/features/analysis/workspace/workspaceFileScanner.ts
similarity index 96%
rename from src/code_analysis/utils/workspaceFileScanner.ts
rename to apps/vscode-extension/src/features/analysis/workspace/workspaceFileScanner.ts
index 5348d81f7..0b1cfb0ce 100644
--- a/src/code_analysis/utils/workspaceFileScanner.ts
+++ b/apps/vscode-extension/src/features/analysis/workspace/workspaceFileScanner.ts
@@ -4,8 +4,8 @@
*/
import * as vscode from 'vscode';
-import { getLanguageForFile, LanguageInfo } from '../../utils/languageMetadata';
-import { CodeXRLogger } from '../../core/logging/logger';
+import { getLanguageForFile, LanguageInfo } from '../../../core/analysis/languages/languageMetadata';
+import { CodeXRLogger } from '../../../platform/logging/logger';
const logger = CodeXRLogger.getLogger('WORKSPACE_FILE_SCANNER');
@@ -150,6 +150,7 @@ export class WorkspaceFileScanner {
'TTCN-3': 'ttcn3.svg',
'Vue': 'vuejs.svg',
'Zig': 'zig.svg',
+ 'Rust': 'rust.svg',
'HTML': 'html5.svg',
'GDScript': 'godot.svg',
};
diff --git a/src/code_analysis/services/workspaceSnapshotModel.ts b/apps/vscode-extension/src/features/analysis/workspace/workspaceSnapshotModel.ts
similarity index 100%
rename from src/code_analysis/services/workspaceSnapshotModel.ts
rename to apps/vscode-extension/src/features/analysis/workspace/workspaceSnapshotModel.ts
diff --git a/src/code_analysis/services/workspaceSnapshotService.ts b/apps/vscode-extension/src/features/analysis/workspace/workspaceSnapshotService.ts
similarity index 98%
rename from src/code_analysis/services/workspaceSnapshotService.ts
rename to apps/vscode-extension/src/features/analysis/workspace/workspaceSnapshotService.ts
index 3a442fa5c..88f72ade7 100644
--- a/src/code_analysis/services/workspaceSnapshotService.ts
+++ b/apps/vscode-extension/src/features/analysis/workspace/workspaceSnapshotService.ts
@@ -1,8 +1,8 @@
import * as path from 'path';
import * as vscode from 'vscode';
-import { getLanguageForFile } from '../../utils/languageMetadata';
-import { CodeXRLogger } from '../../core/logging/logger';
-import { FilesByLanguage } from '../utils/workspaceFileScanner';
+import { getLanguageForFile } from '../../../core/analysis/languages/languageMetadata';
+import { CodeXRLogger } from '../../../platform/logging/logger';
+import { FilesByLanguage } from './workspaceFileScanner';
import { shouldSkipWorkspaceEntry, sortWorkspaceEntries } from './workspaceSnapshotModel';
const SUMMARY_CACHE_KEY = 'codeXR.analysis.filesByLanguage.summaryCache';
diff --git a/src/commands/collaboration/collaborationCommands.ts b/apps/vscode-extension/src/features/collaboration/commands/collaborationCommands.ts
similarity index 89%
rename from src/commands/collaboration/collaborationCommands.ts
rename to apps/vscode-extension/src/features/collaboration/commands/collaborationCommands.ts
index fe5dae95a..ae893d06b 100644
--- a/src/commands/collaboration/collaborationCommands.ts
+++ b/apps/vscode-extension/src/features/collaboration/commands/collaborationCommands.ts
@@ -1,14 +1,9 @@
import * as vscode from 'vscode';
-import {
- AUTO_AVATAR_ID,
- AVATAR_ASSET,
- CollaborationProfileManager,
- COLLABORATION_AVATARS,
- sanitizeCollaborationName,
-} from '../../collaboration';
-import { formatDetailSections } from '../../utils/detailDialog';
-import { ExtensionCommandRegistration } from '../shared';
-import { RemoteAccessManager } from '../../remote_access';
+import { AUTO_AVATAR_ID, COLLABORATION_AVATARS, sanitizeCollaborationName } from '../../../core/collaboration/collaborationProfile';
+import { AVATAR_ASSET, CollaborationProfileManager } from '../../../core/collaboration/collaborationProfileManager';
+import { formatDetailSections } from '../../../platform/ui/detailDialog';
+import { ExtensionCommandRegistration } from '../../../platform/commands/commandRegistry';
+import { RemoteAccessManager } from '../../../core/remote-access/remoteAccessManager';
interface RefreshableTreeProvider {
refreshSection?(sectionName: string): void;
@@ -26,10 +21,10 @@ export function getCollaborationCommandRegistrations(
{
id: 'codeXR.collaboration.joinRemote',
module: 'COLLABORATION',
- description: 'Join a remote CodeXR session',
+ description: 'Join a remote Code-XR session',
handler: async () => {
const remoteAccess = RemoteAccessManager.getInstance()
- || RemoteAccessManager.initialize(context);
+ ?? RemoteAccessManager.initialize(context);
await remoteAccess.joinInvitation();
},
},
@@ -136,7 +131,7 @@ export function getCollaborationCommandRegistrations(
],
[
['Status', installed
- ? 'Bundled with the CodeXR extension — nothing is downloaded'
+ ? 'Bundled with the Code-XR extension — nothing is downloaded'
: 'Missing from this installation — the procedural avatar is used'],
],
]);
diff --git a/src/views/collaboration/CollaborationSectionProvider.ts b/apps/vscode-extension/src/features/collaboration/views/CollaborationSectionProvider.ts
similarity index 83%
rename from src/views/collaboration/CollaborationSectionProvider.ts
rename to apps/vscode-extension/src/features/collaboration/views/CollaborationSectionProvider.ts
index 566618ba7..12f8db5fc 100644
--- a/src/views/collaboration/CollaborationSectionProvider.ts
+++ b/apps/vscode-extension/src/features/collaboration/views/CollaborationSectionProvider.ts
@@ -1,7 +1,7 @@
import * as vscode from 'vscode';
-import { BaseSectionProvider } from '../common/baseInterfaces';
-import { CollaborationProfileManager } from '../../collaboration';
-import { CollaborationItemFactory, CollaborationTreeItem } from './items/collaborationItems';
+import { BaseSectionProvider } from '../../../platform/tree/baseInterfaces';
+import { CollaborationProfileManager } from '../../../core/collaboration/collaborationProfileManager';
+import { CollaborationItemFactory, CollaborationTreeItem } from './collaborationItems';
export class CollaborationSectionProvider extends BaseSectionProvider