Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,42 @@ jobs:
vsix-listing.txt
retention-days: 14
if-no-files-found: error

vsix-in-ide:
name: Code-XR extension in the IDE (ubuntu-latest)
# #262: the .vsix the package job built installs from file in the built
# IDE, activates, and shows its Code-XR tree (apps/ide/scripts/vsixE2e.mjs,
# Playwright against the real window); any vscode API it uses at start-up
# that the IDE's extension host lacks fails the job.
needs: package
if: github.event_name != 'push'
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: '0'
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm

- name: Install
run: npm ci

- name: Download the VSIX
uses: actions/download-artifact@v4
with:
name: code-xr-vsix
path: vsix

- name: Allow the Chromium sandbox
run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0

- name: Build the IDE
run: npm run ide:build

- name: Install and run the extension (virtual display)
run: xvfb-run -a node apps/ide/scripts/vsixE2e.mjs "$(ls vsix/apps/vscode-extension/artifacts/*.vsix | head -n 1)"
5 changes: 3 additions & 2 deletions apps/ide/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ Technology choices for the scaffold:

`src/main/analysis/analysisService.ts` runs the extension's own pipeline (`AnalysisOrchestrator`) with a `CoreContext` built from the IDE's host; the workspace storage VS Code would give is a folder per project under `<userData>/core/workspaces/<hash>`. The IDE registers its own `LaunchNotifier`, so a finished launch opens in the window that asked instead of a browser, and its server settings use the core's `lateralPanel` open mode: scenes are served over plain HTTP on loopback (a secure context, so WebXR still works) with no self-signed certificate to accept.

The scene is a `WebContentsView` laid over the slot the renderer reserves (`analysis/sceneView.ts`), never an `<iframe>` in the app's page, so the app's CSP keeps `frame-src 'none'` and the scene, served over the network, can never reach `window.codexr`:
The scene is a `WebContentsView` laid over the slot the renderer reserves (`analysis/sceneView.ts`), never an `<iframe>` in the app's page, so the app's CSP frames only extensions' webviews (`frame-src codexr-webview:`, #261) and the scene, served over the network, can never reach `window.codexr`:

- sandboxed, context isolation, its own in-memory session `codexr-scene` that grants no permission;
- one preload of its own (`src/scenePreload`, not the app's), exposing a single call: `CodeXRHostBridge.openInEditor({ path, line? })`. The templates use it when present (the dependency graph's **Open in editor** button on a file or symbol card, a LivePanel row) and behave as before without it, in a browser or in VS Code. The same button works in the VS Code extension and in a scene opened in a browser: without the bridge, a page served on loopback sends `open-in-editor` over the collaboration room, and the shared analysis server (`core/server/analysis/editorNavigation.ts`) answers it for a peer on this machine only (no tunnel, no LAN) by calling the host's `openInEditor`, which the IDE implements too (`openInWindowEditor`). The main process accepts the bridge's message only from a scene view's main frame, resolves the path against the analysed folder (`analysis/sceneEditorTarget.ts`), drops anything outside the window's open folder, and sends the window's renderer the workspace path to open (`codexr:analysis:open-in-editor`); the contract is `shared/sceneBridge.ts`;
Expand Down Expand Up @@ -174,6 +174,7 @@ Following Electron's [security checklist](https://www.electronjs.org/docs/latest
| No navigation away from the app, no `window.open`, no `<webview>` | `src/main/hardening.ts` | Unit tests for the URL policy; smoke tries both from inside the page. |
| No permission granted (camera, microphone, XR, notifications...) | `src/main/hardening.ts` | Each later story allow-lists only what it needs. The one exception so far: the scene view grants XR for 15 s after **Enter XR**, to that scene only (`sceneXrPolicy.ts`, unit-tested). |
| The renderer reaches files only inside the open folder, by workspace-relative path | `src/main/workspace/` (`parseWorkspacePath`, `Workspace`), one folder per window | Unit tests for `..`, absolute paths, drive letters, `\\`, NUL and symlinks that lead out; smoke reads a file and tries `../`. |
| Extensions' webviews (#261): each in an `<iframe>` on its own origin `codexr-webview://<random id>/`, sandboxed (no popups, no top navigation), no preload, no permission; files only from its `localResourceRoots`; `command:` links only as `enableCommandUris` allows | `src/main/extensions/webviewRegistry.ts`, `webviewServer.ts`, `src/shared/extensionWebviewProtocol.ts`, `will-frame-navigate` in `src/main/hardening.ts`, `frame-src codexr-webview:` in the CSP | Unit tests (`test/extensionWebviews.test.ts`: roots, encoded `..`, links out of a root, other windows' webviews, event checks); checked in Electron that a page sees no `window.codexr`, cannot reach its parent or open a popup. |
| IPC only on allow-listed channels, only from trusted frames | `IPC_CHANNELS` in `src/shared/api.ts`, `src/main/ipc.ts` | Unit tests; startup check that every channel has a handler. |
| Typed, frozen preload API, the only path from renderer to Node | `src/preload/index.ts`, `CodeXRApi` in `src/shared/api.ts` | Lint forbids `electron`, `node:*` and main/preload imports in the renderer; smoke checks the API is frozen and answers. |
| The renderer cannot start a process: a terminal starts only from a detected or user-saved profile, named by id, and only the window that created it can write to it or read it | `src/main/terminal/` (`ProfileRegistry.resolve`, `TerminalService`) | Unit tests (unknown ids, foreign windows, bad sizes and input); smoke opens a terminal and reads its output. |
Expand Down Expand Up @@ -234,7 +235,7 @@ PDFs and images open in an editor tab instead of being refused as binary files.
- **Security**
- The bytes come from the main process through a read that stays inside the folder and is size-capped (`workspace.readDocument` / `readImage`).
- PDF.js parses them in its own worker, bundled with the app.
- The CSP is unchanged: no frames, no objects, no remote fetches.
- The CSP is unchanged by the viewers: no objects, no remote fetches (frames are for extensions' webviews only, #261).
- Viewing is read-only, so it works in Restricted Mode.
- **Custom editor tabs**
- The viewers are the first users of a generic seam in `renderer/editor/customEditor.ts`. `editorGroup.openCustom(input)` opens a tab whose content is a DOM element of its own, and `registerCustomEditor(resolver)` turns an id (a file being opened, or a tab of a saved session) into such a tab.
Expand Down
94 changes: 94 additions & 0 deletions apps/ide/scripts/vsixE2e.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// #262: the Code-XR VS Code extension, installed from its .vsix, runs inside
// the built IDE. Launches the IDE with Playwright on a throw-away profile and
// folder, installs the package through the real install path (only the file
// dialog is answered by the script), then checks that the Code-XR activity
// bar container shows its tree, and that no vscode API the extension used at
// start-up is missing from the host.
//
// Usage: node scripts/vsixE2e.mjs <path to code-xr-<version>.vsix>
// (after `node scripts/build.mjs`; on Linux CI under xvfb-run).
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { _electron } from 'playwright';
import { IDE_ROOT } from './viteConfigs.mjs';
import { electronBinary, launchFlags } from './electronBinary.mjs';

const vsix = process.argv[2] ? path.resolve(process.argv[2]) : '';
if (!vsix || !fs.existsSync(vsix)) {
console.error(`[vsix-e2e] no .vsix at '${process.argv[2] ?? ''}'.`);
process.exit(2);
}

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-vsix-e2e-profile-'));
const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-vsix-e2e-folder-'));
fs.writeFileSync(path.join(folder, 'main.py'), 'def add(a, b):\n return a + b\n');

const failures = [];
const app = await _electron.launch({
executablePath: electronBinary(),
args: [...launchFlags(), IDE_ROOT, `--folder=${folder}`],
// XDG_CONFIG_HOME isolates the profile on Linux; APPDATA on Windows; macOS uses HOME.
env: { ...process.env, CODEXR_IDE_DEV_SERVER_URL: '', XDG_CONFIG_HOME: profile, APPDATA: profile, HOME: process.platform === 'darwin' ? profile : process.env.HOME },
timeout: 60_000,
});
try {
// Native questions: install the package (yes); the IDE's own Python environment (no, it is not what this checks).
await app.evaluate(({ dialog }, file) => {
dialog.showMessageBox = async (first, second) => {
const options = second ?? first;
const python = /python|virtual environment/i.test(`${options.message ?? ''} ${options.detail ?? ''}`);
return { response: python ? options.cancelId ?? 1 : 0, checkboxChecked: false };
};
dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [file] });
}, vsix);
const win = await app.firstWindow();
await win.waitForSelector('[data-testid="welcome"]', { timeout: 60_000 });
// Extensions with code run in a trusted folder only (Restricted Mode keeps them off).
await win.evaluate(() => window.codexr.workspace.setTrust('folder'));

const installed = await win.evaluate(() => window.codexr.extensions.installVsix());
if (!installed.ok) {
throw new Error(`install failed: ${installed.error}`);
}
console.log(`[vsix-e2e] installed ${installed.extension.id} ${installed.extension.version}`);

const item = await win.waitForSelector('.activity-item[data-view="ext:codexr"]', { timeout: 30_000 });
await item.click();
let rows = [];
for (let attempt = 0; attempt < 60 && rows.length === 0; attempt++) {
await wait(500);
rows = await win.$$eval('[data-testid="ext-tree-codexrTree"] .ext-tree-row', (elements) => elements.map((row) => row.getAttribute('aria-label') ?? ''));
}
console.log(`[vsix-e2e] tree: ${rows.join(' | ')}`);
for (const section of ['SERVERS', 'ANALYSIS']) {
if (!rows.some((row) => row.startsWith(section))) {
failures.push(`the Code-XR tree has no ${section} section`);
}
}

const lines = await win.evaluate(() => window.codexr.output.lines('extensions'));
const activated = lines.some((line) => line.includes('[amontesl.code-xr] Activated'));
if (!activated) {
failures.push('the extension did not activate');
}
const missing = lines.filter((line) => line.includes('which the Code-XR IDE does not implement yet'));
for (const line of missing) {
failures.push(`missing API: ${line.replace(/^.*uses /, '')}`);
}
const failed = lines.filter((line) => /Activation of .* failed|failed to activate/i.test(line));
failures.push(...failed);
} catch (error) {
failures.push(error instanceof Error ? error.message : String(error));
} finally {
await app.close().catch(() => undefined);
fs.rmSync(profile, { recursive: true, force: true });
fs.rmSync(folder, { recursive: true, force: true });
}

if (failures.length > 0) {
console.error(`[vsix-e2e] FAILED:\n- ${failures.join('\n- ')}`);
process.exit(1);
}
console.log('[vsix-e2e] OK: the Code-XR extension installed from its .vsix, activated, and its tree view shows in the IDE.');
7 changes: 7 additions & 0 deletions apps/ide/src/extensionHost/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,13 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u
// #261: tree views.
createTreeView: (viewId: string, options: { treeDataProvider?: unknown; showCollapseAll?: boolean; canSelectMany?: boolean; manageCheckboxStateManually?: boolean }) => host.treeViews.create(extensionId, viewId, options),
registerTreeDataProvider: (viewId: string, provider: unknown) => host.treeViews.register(extensionId, viewId, provider),
// #261: webviews. Panels are not restored after a restart: serializers are accepted and never called.
createWebviewPanel: (viewType: string, title: string, showOptions: unknown, options?: Record<string, unknown>) => host.webviews.createPanel(extensionId, viewType, title, showOptions, options),
registerWebviewViewProvider: (viewId: string, provider: unknown) => host.webviews.registerViewProvider(extensionId, viewId, provider),
registerWebviewPanelSerializer: () => {
report('window.registerWebviewPanelSerializer (panels are not restored after a restart)');
return new Disposable(() => undefined);
},
}, report);

/* ------------------------------ env ------------------------------ */
Expand Down
3 changes: 3 additions & 0 deletions apps/ide/src/extensionHost/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { TextDocumentModel } from './textDocument.ts';
import { BUILTIN_LANGUAGES } from './textDocument.ts';
import { Disposable, EventEmitter, Uri } from './types.ts';
import { TreeViews } from './treeViews.ts';
import { Webviews } from './webviews.ts';
import { fromWire, toWire } from './wire.ts';

/**
Expand Down Expand Up @@ -77,6 +78,7 @@ export class ExtensionHost {
readonly languageFeatures: LanguageFeatures;
/** #261: the extensions' tree views. */
readonly treeViews: TreeViews;
readonly webviews: Webviews;
private readonly reported = new Set<string>();
private readonly firedEvents = new Set<string>();
private moduleHooked = false;
Expand All @@ -88,6 +90,7 @@ export class ExtensionHost {
this.documentsAndEditors = new DocumentsAndEditors(this);
this.languageFeatures = new LanguageFeatures(this);
this.treeViews = new TreeViews(this);
this.webviews = new Webviews(this);
this.configuration = new ConfigurationModel((key, value, target) => this.rpc.request(MAIN_METHODS.updateConfiguration, key, toWire(value), target).then(() => undefined));
}

Expand Down
2 changes: 2 additions & 0 deletions apps/ide/src/extensionHost/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { HOST_METHODS, RpcEndpoint, type HostInitData, type RpcMessage } from '../shared/extensionHostProtocol.ts';
import type { DocumentEvent, ProvideRequest } from '../shared/extensionLanguageProtocol.ts';
import type { ViewRequest } from '../shared/extensionViewsProtocol.ts';
import type { WebviewWorkbenchEvent } from '../shared/extensionWebviewProtocol.ts';
import { ExtensionHost } from './host.ts';

/**
Expand Down Expand Up @@ -30,6 +31,7 @@ rpc.handle(HOST_METHODS.trustChanged, (trusted) => host.trustChanged(trusted ===
rpc.handle(HOST_METHODS.documents, (events) => host.documentsAndEditors.accept(Array.isArray(events) ? events as DocumentEvent[] : []));
rpc.handle(HOST_METHODS.provide, (request) => host.languageFeatures.provide(request as ProvideRequest));
rpc.handle(HOST_METHODS.view, (request) => host.treeViews.request(request as ViewRequest));
rpc.handle(HOST_METHODS.webview, (event) => host.webviews.request(event as WebviewWorkbenchEvent));
rpc.handle(HOST_METHODS.shutdown, async () => {
await host.shutdown();
setTimeout(() => process.exit(0), 50);
Expand Down
Loading
Loading