diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 44751cf2..f6b1e213 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -290,3 +290,48 @@ jobs: - 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)" + + extensions-compat: + name: Popular extensions in the extension host (ubuntu-latest) + # #264: downloads popular extensions from Open VSX and runs each one in + # the IDE's extension host (apps/ide/scripts/extensionCompat.mjs): did it + # activate, and which vscode APIs did it use that the host lacks. A + # measurement for docs/ide/extensions-compatibility.md, not a gate: a + # third-party release must not turn the build red, so it never fails it. + if: github.event_name != 'push' + runs-on: ubuntu-latest + continue-on-error: true + 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: Probe the extensions + working-directory: apps/ide + run: | + node --experimental-strip-types --no-warnings scripts/extensionCompat.mjs --markdown --json compat.json --open-vsx \ + redhat.vscode-yaml esbenp.prettier-vscode dbaeumer.vscode-eslint eamodio.gitlens ms-python.python \ + rust-lang.rust-analyzer golang.Go streetsidesoftware.code-spell-checker usernamehw.errorlens \ + PKief.material-icon-theme vscodevim.vim christian-kohler.path-intellisense EditorConfig.EditorConfig \ + yzhang.markdown-all-in-one Gruntfuggly.todo-tree mechatroner.rainbow-csv formulahendry.code-runner \ + dracula-theme.theme-dracula GitHub.github-vscode-theme llvm-vs-code-extensions.vscode-clangd \ + Vue.volar svelte.svelte-vscode bradlc.vscode-tailwindcss hashicorp.terraform tamasfe.even-better-toml \ + James-Yu.latex-workshop oderwat.indent-rainbow ms-azuretools.vscode-docker redhat.java \ + MS-CEINTL.vscode-language-pack-es > compat.md || true + cat compat.md >> "$GITHUB_STEP_SUMMARY" + cat compat.md + + - name: Keep the results + uses: actions/upload-artifact@v4 + with: + name: extensions-compat + path: apps/ide/compat.json + if-no-files-found: ignore diff --git a/apps/ide/README.md b/apps/ide/README.md index 7fa636bb..a8fd61c8 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -184,6 +184,7 @@ Following Electron's [security checklist](https://www.electronjs.org/docs/latest | Extensions (#251) are unpacked only from checked archives: entries under `extension/` only, no `..`, absolute paths, drive letters or links, size limits; an Open VSX download must match the registry's SHA-256; a native dialog shows publisher, verification, licence and whether it runs code before anything is installed; nothing goes online unless the person searches or installs | `src/main/extensions/` (`vsix.ts`, `openVsx.ts`, `extensionsService.ts`) | Unit tests (`test/extensions.test.ts`: zip-slip, symlink and garbage archives, wrong and missing checksums, http downloads, tampered `extensions.json`). | | The renderer may compile WebAssembly (`'wasm-unsafe-eval'`) for the TextMate regex engine of extension grammars (#258); `eval` stays blocked | `buildContentSecurityPolicy` | Unit tests; smoke checks `eval` throws. | | Extensions' code (#259) runs only in the extension host, a separate Node process per window, never in the renderer or main; what it asks of main is checked there (files only inside the folder, links only http/https/mailto, secrets in the OS store per extension, edits refused whole when a file is outside the folder); only workbench activation events are accepted from the renderer, and the documents it reports (#260) go through the workspace path rules with bounded sizes | `src/extensionHost/`, `src/main/extensions/extensionHostManager.ts` | Unit tests (`test/extensionHost.test.ts`, `test/extensionLanguages.test.ts`, with a real host process). | +| Extensions respect workspace trust (#263): in Restricted Mode only those declaring `untrustedWorkspaces.supported` run; what is enabled lives in the user-data folder, never the project; `--disable-extensions` and **Disable All Installed Extensions** for recovery | `src/main/extensions/runState.ts`, `extensionsService.ts`, `extensionStore.ts` | Unit tests (`test/extensionTrust.test.ts`: the run-state rules, the manifest flag, `workspace.isTrusted` and `onDidGrantWorkspaceTrust` in a real host). | | The dev server URL is ignored in a packaged build | `src/main/index.ts` (`app.isPackaged`) | Code review. | Running as root (containers, some CI images) requires `--no-sandbox`, which the scripts add only in that case. It turns off Chromium's OS-level sandbox and `app.enableSandbox()`; the per-window `sandbox: true` preference and its assertion stay. @@ -192,7 +193,7 @@ Running as root (containers, some CI images) requires `--no-sandbox`, which the A folder can bring things that run: Git reads the repository's own hooks, filters and configuration, pyright runs the interpreter a project's config names, and tasks (#176) are commands the folder defines. So the first time a folder opens, a notification asks whether you trust its authors: **Trust Folder**, **Trust All in** its parent folder (every folder below a trusted one is trusted), or **Restricted Mode**. Until it is answered the folder is restricted, and a **Restricted Mode** shield sits at the start of the status bar; clicking it, or **Manage Workspace Trust** in the palette, changes the answer later. A folder can be put in Restricted Mode even inside a trusted parent. -In Restricted Mode the main process runs no Git in the folder (Source Control says why), starts no Python language server, and refuses tasks (Run Task and Run Current File say why and offer Manage Workspace Trust). Reading, editing, search, the terminal you open yourself, the IDE's own TypeScript server and the Code-XR analysis (it parses files, it never runs them) work either way. The decisions are stored in `workspace-trust.json` in the IDE's user-data folder, never in the project, so a folder cannot trust itself; paths compare without case on Windows and macOS (`main/trust/`, `renderer/trustView.ts`). The smoke run checks that a new folder starts restricted with Git off, and that trusting it turns Git on. +In Restricted Mode the main process runs no Git in the folder (Source Control says why), starts no Python language server, refuses tasks (Run Task and Run Current File say why and offer Manage Workspace Trust), and starts only the extensions whose manifest declares `capabilities.untrustedWorkspaces.supported` (`true` or `"limited"`, #263): the others show *Disabled in Restricted Mode* in the Extensions view, and trusting the folder restarts the extension host with them, without restarting the IDE. Extensions see the same trust (`workspace.isTrusted`, `onDidGrantWorkspaceTrust`). Which extensions are on is kept in `extensions.json` in the IDE's user-data folder, never in the project, so a folder cannot turn an extension on; `--disable-extensions` on the command line, or **Disable All Installed Extensions** in the palette, turns them all off for recovery. Reading, editing, search, the terminal you open yourself, the IDE's own TypeScript server and the Code-XR analysis (it parses files, it never runs them) work either way. The decisions are stored in `workspace-trust.json` in the IDE's user-data folder, never in the project, so a folder cannot trust itself; paths compare without case on Windows and macOS (`main/trust/`, `renderer/trustView.ts`). The smoke run checks that a new folder starts restricted with Git off, and that trusting it turns Git on. ## Tasks and Run Current File (#176) diff --git a/apps/ide/package.json b/apps/ide/package.json index faafd09b..92fc724c 100644 --- a/apps/ide/package.json +++ b/apps/ide/package.json @@ -15,6 +15,7 @@ "typecheck": "node scripts/coreTypes.mjs && node ../../node_modules/typescript/bin/tsc -p tsconfig.node.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.web.json", "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts eslint.config.mjs --max-warnings 0", "test:unit": "node --import ./scripts/testCoreAlias.mjs --test --experimental-strip-types \"test/**/*.test.ts\"", + "compat": "node --experimental-strip-types --no-warnings scripts/extensionCompat.mjs", "test": "npm run typecheck && npm run lint && npm run test:unit" }, "engines": { diff --git a/apps/ide/scripts/extensionCompat.mjs b/apps/ide/scripts/extensionCompat.mjs new file mode 100644 index 00000000..2e75ecb7 --- /dev/null +++ b/apps/ide/scripts/extensionCompat.mjs @@ -0,0 +1,85 @@ +// #264: the compatibility probe, from the command line. Installs each .vsix +// through the IDE's own install path, starts the real extension host on it +// in Node, fires its activation events, and prints what happened: activated +// or failed, and which vscode APIs it used that the host does not implement. +// +// Usage: +// node --experimental-strip-types scripts/extensionCompat.mjs [options] ... [--open-vsx ...] +// Options: +// --json also write the full results as JSON +// --markdown print the Markdown table of docs/ide/extensions-compatibility.md +// --open-vsx ... download these extensions from Open VSX first (the same client and SHA-256 check as the IDE) +// A folder stands for every .vsix directly inside it. Exit code 1 when an extension failed to install, activate or answer. +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const IDE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const { probeVsix, probeTable } = await import(path.join(IDE_ROOT, 'src/main/extensions/compatProbe.ts')); +const { OpenVsxClient } = await import(path.join(IDE_ROOT, 'src/main/extensions/openVsx.ts')); + +const args = process.argv.slice(2); +const files = []; +const fromOpenVsx = []; +let jsonOut = null; +let markdown = false; +let mode = 'files'; +for (let index = 0; index < args.length; index++) { + const arg = args[index]; + if (arg === '--json') { + jsonOut = path.resolve(args[++index] ?? 'compat.json'); + } else if (arg === '--markdown') { + markdown = true; + } else if (arg === '--open-vsx') { + mode = 'open-vsx'; + } else if (mode === 'open-vsx') { + fromOpenVsx.push(arg); + } else if (fs.existsSync(arg) && fs.statSync(arg).isDirectory()) { + files.push(...fs.readdirSync(arg).filter((name) => name.endsWith('.vsix')).sort().map((name) => path.resolve(arg, name))); + } else { + files.push(path.resolve(arg)); + } +} + +const downloads = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-compat-downloads-')); +const results = []; +try { + if (fromOpenVsx.length > 0) { + const client = new OpenVsxClient('https://open-vsx.org', (url, init) => fetch(url, init)); + for (const id of fromOpenVsx) { + try { + const vsix = await client.download(id); + const file = path.join(downloads, `${id}-${vsix.version}.vsix`); + fs.writeFileSync(file, vsix.bytes); + files.push(file); + console.error(`[compat] downloaded ${id} ${vsix.version}${vsix.verified ? ' (verified publisher)' : ''}`); + } catch (error) { + results.push({ file: id, id, version: null, outcome: 'not-installed', engineSupported: null, contributions: null, missingApi: [], errors: [], registeredCommands: 0, milliseconds: 0, detail: `Open VSX: ${error instanceof Error ? error.message : String(error)}` }); + } + } + } + if (files.length === 0 && results.length === 0) { + console.error('[compat] no .vsix given.'); + process.exit(2); + } + for (const file of files) { + const result = await probeVsix(file, { + hostEntry: path.join(IDE_ROOT, 'src/extensionHost/index.ts'), + execArgv: ['--experimental-strip-types', '--no-warnings'], + }); + results.push(result); + const missing = result.missingApi.length > 0 ? `; missing: ${result.missingApi.join(', ')}` : ''; + console.error(`[compat] ${result.id ?? path.basename(file)} ${result.version ?? ''}: ${result.outcome}${missing}${result.detail ? ` (${result.detail})` : ''}`); + } +} finally { + fs.rmSync(downloads, { recursive: true, force: true }); +} + +if (jsonOut) { + fs.writeFileSync(jsonOut, `${JSON.stringify(results, null, 2)}\n`); +} +if (markdown) { + console.log(probeTable(results)); +} +process.exit(results.some((result) => result.outcome === 'failed' || result.outcome === 'not-installed' || result.outcome === 'timeout') ? 1 : 0); diff --git a/apps/ide/src/extensionHost/host.ts b/apps/ide/src/extensionHost/host.ts index e3debc59..38020e1c 100644 --- a/apps/ide/src/extensionHost/host.ts +++ b/apps/ide/src/extensionHost/host.ts @@ -1,6 +1,7 @@ import fs from 'node:fs'; import Module from 'node:module'; import path from 'node:path'; +import { fileURLToPath } from 'node:url'; import { activationMatches, MAIN_METHODS, type HostActivationEvent, type HostExtensionDescription, type HostInitData, type HostLogLine, type HostPassiveExtension, type RpcEndpoint, type UiNotification, type UiRequest, } from '../shared/extensionHostProtocol.ts'; @@ -58,6 +59,28 @@ interface RegisteredCommand { type ModuleWithLoad = typeof Module & { _load(request: string, parent: { filename?: string } | null | undefined, isMain: boolean): unknown }; +/** `module.registerHooks` (Node 22.15+, Electron's Node 24): synchronous, in-thread module hooks. Not in this @types/node yet. */ +interface SyncModuleHooks { + resolve(specifier: string, context: { parentURL?: string | undefined }, next: (specifier: string, context: unknown) => unknown): unknown; + load(url: string, context: unknown, next: (url: string, context: unknown) => unknown): unknown; +} +type ModuleWithHooks = typeof Module & { registerHooks?: (hooks: SyncModuleHooks) => unknown }; + +/** The URL an ES module's `import 'vscode'` resolves to; the importing module's URL follows, encoded. */ +const ESM_VSCODE_URL = 'codexr-vscode:'; +/** Where the generated `vscode` ES module finds the API for the file that imported it. */ +const ESM_VSCODE_GLOBAL = Symbol.for('codexr.vscodeFor'); + +/** The source of the ES module `vscode` for one importer: a default export and one named export per member of the API. */ +export function esmVscodeSource(file: string, names: readonly string[]): string { + const exported = names.filter((name) => name !== 'default' && /^[A-Za-z_$][\w$]*$/.test(name)); + return [ + `const api = globalThis[Symbol.for('codexr.vscodeFor')](${JSON.stringify(file)});`, + 'export default api;', + ...exported.map((name, index) => `const _${index} = api[${JSON.stringify(name)}];\nexport { _${index} as ${name} };`), + ].join('\n'); +} + export class ExtensionHost { readonly rpc: RpcEndpoint; data!: HostInitData; @@ -106,6 +129,8 @@ export class ExtensionHost { for (const json of [...data.extensions, ...data.passive].map((ext) => ext.packageJSON)) { this.learnLanguages(json); } + // VS Code always sets it; some extensions JSON.parse it unguarded (yzhang.markdown-all-in-one). + process.env['VSCODE_NLS_CONFIG'] ??= JSON.stringify({ locale: data.env.language, osLocale: data.env.language, availableLanguages: {} }); this.hookRequire(); // The editor's state before any extension activates, so `*` extensions see the open files. this.documentsAndEditors.accept([ @@ -213,6 +238,15 @@ export class ExtensionHost { return record.api; } + /** The API for code in `file`: its extension's, or the first extension's for code outside every extension folder (a shared dependency hoisted elsewhere). */ + private apiForFile(file: string | undefined): unknown { + const record = this.extensionOfFile(file) ?? this.records.values().next().value; + if (!record) { + throw new Error('Cannot find module \'vscode\''); + } + return this.apiFor(record); + } + private hookRequire(): void { if (this.moduleHooked) { return; @@ -220,21 +254,27 @@ export class ExtensionHost { this.moduleHooked = true; const loader = Module as ModuleWithLoad; const original = loader._load.bind(loader); - loader._load = (request, parent, isMain) => { - if (request === 'vscode') { - const record = this.extensionOfFile(parent?.filename); - if (!record) { - // Code outside every extension (a shared dependency hoisted elsewhere): the first extension's view is the best guess. - const first = this.records.values().next().value; - if (!first) { - throw new Error('Cannot find module \'vscode\''); - } - return this.apiFor(first); + loader._load = (request, parent, isMain) => (request === 'vscode' ? this.apiForFile(parent?.filename) : original(request, parent, isMain)); + // #264: extensions shipped as ES modules (esbenp.prettier-vscode) `import ... from 'vscode'`, which `_load` never sees. + const registerHooks = (Module as ModuleWithHooks).registerHooks; + if (typeof registerHooks !== 'function') { + return; + } + (globalThis as Record)[ESM_VSCODE_GLOBAL] = (file: string) => this.apiForFile(file || undefined); + registerHooks.call(Module, { + resolve: (specifier, context, next) => (specifier === 'vscode' + ? { url: `${ESM_VSCODE_URL}${encodeURIComponent(context.parentURL ?? '')}`, shortCircuit: true } + : next(specifier, context)), + load: (url, context, next) => { + if (!url.startsWith(ESM_VSCODE_URL)) { + return next(url, context); } - return this.apiFor(record); - } - return original(request, parent, isMain); - }; + const parent = decodeURIComponent(url.slice(ESM_VSCODE_URL.length)); + const file = parent.startsWith('file:') ? fileURLToPath(parent) : ''; + const api = this.apiForFile(file || undefined) as object; + return { format: 'module', source: esmVscodeSource(file, Object.keys(api)), shortCircuit: true }; + }, + }); } /* ------------------------------ activation ------------------------------ */ diff --git a/apps/ide/src/extensionHost/types.ts b/apps/ide/src/extensionHost/types.ts index 9d4a9006..03c12d90 100644 --- a/apps/ide/src/extensionHost/types.ts +++ b/apps/ide/src/extensionHost/types.ts @@ -1313,4 +1313,43 @@ export type CommentThreadCollapsibleState = (typeof CommentThreadCollapsibleStat export const IndentAction = numericEnum({ None: 0, Indent: 1, IndentOutdent: 2, Outdent: 3 } as const); export type IndentAction = (typeof IndentAction)[EnumKeys]; +/* + * #264: enums of API areas the host does not implement (tests, debug, notebooks, comments, language models...). + * Extensions read them at start-up to build options (`TestRunProfileKind.Run`), so a missing one is a + * TypeError that fails the whole activation (ms-python.python, eamodio.gitlens), not just the feature. + * Values from vscode.d.ts. + */ +export const QuickInputButtonLocation = numericEnum({ Title: 1, Inline: 2, Input: 3 } as const); +export type QuickInputButtonLocation = (typeof QuickInputButtonLocation)[EnumKeys]; +export const TestRunProfileKind = numericEnum({ Run: 1, Debug: 2, Coverage: 3 } as const); +export type TestRunProfileKind = (typeof TestRunProfileKind)[EnumKeys]; +export const DebugConsoleMode = numericEnum({ Separate: 0, MergeWithParent: 1 } as const); +export type DebugConsoleMode = (typeof DebugConsoleMode)[EnumKeys]; +export const DebugConfigurationProviderTriggerKind = numericEnum({ Initial: 1, Dynamic: 2 } as const); +export type DebugConfigurationProviderTriggerKind = (typeof DebugConfigurationProviderTriggerKind)[EnumKeys]; +export const ShellQuoting = numericEnum({ Escape: 1, Strong: 2, Weak: 3 } as const); +export type ShellQuoting = (typeof ShellQuoting)[EnumKeys]; +export const InlineCompletionTriggerKind = numericEnum({ Invoke: 0, Automatic: 1 } as const); +export type InlineCompletionTriggerKind = (typeof InlineCompletionTriggerKind)[EnumKeys]; +export const SyntaxTokenType = numericEnum({ Other: 0, Comment: 1, String: 2, RegEx: 3 } as const); +export type SyntaxTokenType = (typeof SyntaxTokenType)[EnumKeys]; +export const NotebookEditorRevealType = numericEnum({ Default: 0, InCenter: 1, InCenterIfOutsideViewport: 2, AtTop: 3 } as const); +export type NotebookEditorRevealType = (typeof NotebookEditorRevealType)[EnumKeys]; +export const NotebookCellStatusBarAlignment = numericEnum({ Left: 1, Right: 2 } as const); +export type NotebookCellStatusBarAlignment = (typeof NotebookCellStatusBarAlignment)[EnumKeys]; +export const NotebookControllerAffinity = numericEnum({ Default: 1, Preferred: 2 } as const); +export type NotebookControllerAffinity = (typeof NotebookControllerAffinity)[EnumKeys]; +export const CommentMode = numericEnum({ Editing: 0, Preview: 1 } as const); +export type CommentMode = (typeof CommentMode)[EnumKeys]; +export const CommentThreadState = numericEnum({ Unresolved: 0, Resolved: 1 } as const); +export type CommentThreadState = (typeof CommentThreadState)[EnumKeys]; +export const TerminalShellExecutionCommandLineConfidence = numericEnum({ Low: 0, Medium: 1, High: 2 } as const); +export type TerminalShellExecutionCommandLineConfidence = (typeof TerminalShellExecutionCommandLineConfidence)[EnumKeys]; +export const LanguageModelChatMessageRole = numericEnum({ User: 1, Assistant: 2 } as const); +export type LanguageModelChatMessageRole = (typeof LanguageModelChatMessageRole)[EnumKeys]; +export const LanguageModelChatToolMode = numericEnum({ Auto: 1, Required: 2 } as const); +export type LanguageModelChatToolMode = (typeof LanguageModelChatToolMode)[EnumKeys]; +export const ChatResultFeedbackKind = numericEnum({ Unhelpful: 0, Helpful: 1 } as const); +export type ChatResultFeedbackKind = (typeof ChatResultFeedbackKind)[EnumKeys]; + export class Comment {} diff --git a/apps/ide/src/main/extensions/compatProbe.ts b/apps/ide/src/main/extensions/compatProbe.ts new file mode 100644 index 00000000..b688b5ca --- /dev/null +++ b/apps/ide/src/main/extensions/compatProbe.ts @@ -0,0 +1,245 @@ +import { fork } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + activationEventsOf, HOST_METHODS, MAIN_METHODS, RpcEndpoint, + type HostActivationEvent, type HostInitData, type HostLogLine, +} from '../../shared/extensionHostProtocol.ts'; +import { HOST_VSCODE_API_VERSION, type ContributionSummary, type ExtensionId } from '../../shared/extensions.ts'; +import { ExtensionStore, type LoadedExtension } from './extensionStore.ts'; +import { engineSupported, summarizeContributions } from './manifest.ts'; + +/** + * #264: the compatibility probe. Installs a .vsix through the IDE's own + * install path (ExtensionStore: the same unpack, manifest checks and + * folder layout as the Extensions view), starts the real extension host on + * it in a plain Node process, fires every activation event the extension + * declares, and records what happened: activated or failed, which vscode + * APIs it reached for that the host does not implement, the errors it + * logged, and the commands it registered. + * + * It answers "does the code start, and what API does it miss at start-up", + * not "does every feature work": a feature behind a command or a language + * request may still reach an unimplemented API later. No Electron import: + * `scripts/extensionCompat.mjs` runs it under Node. + */ + +export type ProbeOutcome = 'activated' | 'failed' | 'no-code' | 'not-installed' | 'timeout'; + +export interface ProbeResult { + readonly file: string; + readonly id: ExtensionId | null; + readonly version: string | null; + readonly outcome: ProbeOutcome; + /** The engine range is one the IDE's API version satisfies. */ + readonly engineSupported: boolean | null; + readonly contributions: ContributionSummary | null; + /** vscode API names the extension used and the host does not implement, in first-use order. */ + readonly missingApi: readonly string[]; + /** Error and warning lines the host or the extension logged. */ + readonly errors: readonly string[]; + readonly registeredCommands: number; + readonly milliseconds: number; + readonly detail: string | null; +} + +export interface ProbeOptions { + /** Absolute path of `src/extensionHost/index.ts` (or the built host). */ + readonly hostEntry: string; + /** Node flags for the host process (type stripping when it runs from source). */ + readonly execArgv?: readonly string[]; + /** A folder the host sees as the open workspace; a throw-away one when absent. */ + readonly workspaceFolder?: string; + readonly timeoutMs?: number; +} + +const DEFAULT_TIMEOUT_MS = 30_000; + +/** Every event worth firing at start-up: what the extension declares (and the implicit ones), with `*` and `onStartupFinished`. */ +export function probeEvents(extension: LoadedExtension, folder: string): string[] { + const events = new Set(['*', 'onStartupFinished']); + for (const event of activationEventsOf(extension.manifest.activationEvents, extension.manifest.contributes)) { + // workspaceContains: the IDE fires it after a folder walk finds a match; the probe fires it as if one had. + events.add(event); + } + if (fs.existsSync(folder)) { + events.add('onFileSystem:file'); + } + return [...events]; +} + +function withTimeout(promise: Promise, ms: number): Promise { + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise<'timeout'>((resolve) => { + timer = setTimeout(() => resolve('timeout'), ms); + }); + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); +} + +/** Probes one .vsix in a store of its own and a host of its own, so one extension cannot spoil the next one's result. */ +export async function probeVsix(file: string, options: ProbeOptions): Promise { + const started = Date.now(); + const scratch = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-compat-'))); + const base = { file, id: null, version: null, engineSupported: null, contributions: null, missingApi: [], errors: [], registeredCommands: 0, detail: null }; + try { + const store = new ExtensionStore(path.join(scratch, 'extensions')); + try { + await store.install(file, 'vsix'); + } catch (error) { + return { ...base, outcome: 'not-installed', milliseconds: Date.now() - started, detail: error instanceof Error ? error.message : String(error) }; + } + const installed = store.list(); + const extension = installed.at(-1); + if (!extension) { + return { ...base, outcome: 'not-installed', milliseconds: Date.now() - started, detail: 'The store lists nothing after the install.' }; + } + const described = { + ...base, + id: extension.manifest.id, + version: extension.manifest.version, + engineSupported: engineSupported(extension.manifest.engine, HOST_VSCODE_API_VERSION), + contributions: summarizeContributions(extension.manifest), + }; + if (!extension.manifest.main) { + return { ...described, outcome: 'no-code', milliseconds: Date.now() - started }; + } + const folder = options.workspaceFolder ?? path.join(scratch, 'workspace'); + fs.mkdirSync(folder, { recursive: true }); + const result = await runHost(extension, installed, folder, scratch, options); + return { ...described, ...result, milliseconds: Date.now() - started }; + } finally { + fs.rmSync(scratch, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); + } +} + +async function runHost( + extension: LoadedExtension, + installed: readonly LoadedExtension[], + folder: string, + scratch: string, + options: ProbeOptions, +): Promise> { + const missingApi: string[] = []; + const errors: string[] = []; + let activation: HostActivationEvent | null = null; + const child = fork(options.hostEntry, [], { + execArgv: [...(options.execArgv ?? [])], + stdio: ['ignore', 'pipe', 'pipe', 'ipc'], + serialization: 'advanced', + }); + child.stderr?.on('data', (chunk: Buffer) => { + const text = chunk.toString().trim(); + // Node's deprecation warnings (often from a language server the extension started) say nothing about the IDE. + if (text && !/DeprecationWarning|--trace-deprecation/.test(text)) { + errors.push(`[stderr] ${text.slice(0, 400)}`); + } + }); + const main = new RpcEndpoint((message) => child.send(message)); + child.on('message', (message) => main.receive(message)); + main.handle(MAIN_METHODS.log, (...params) => { + const line = params[0] as HostLogLine; + if (line.level === 'error' || line.level === 'warn') { + errors.push(line.message.slice(0, 400)); + } + return undefined; + }); + main.handle(MAIN_METHODS.notImplemented, (...params) => { + const api = String(params[1]); + if (!missingApi.includes(api)) { + missingApi.push(api); + } + return undefined; + }); + main.handle(MAIN_METHODS.activation, (...params) => { + const event = params[0] as HostActivationEvent; + if (event.id === extension.manifest.id && (event.state === 'active' || event.state === 'failed')) { + activation = event; + } + return undefined; + }); + // The workbench's side, answered the way a person who clicks nothing would. + for (const method of [MAIN_METHODS.uiNotify, MAIN_METHODS.webview, MAIN_METHODS.diagnostics, MAIN_METHODS.registerProvider, MAIN_METHODS.unregisterProvider, + MAIN_METHODS.updateConfiguration, MAIN_METHODS.secretStore, MAIN_METHODS.secretDelete, MAIN_METHODS.clipboardWrite]) { + main.handle(method, () => undefined); + } + main.handle(MAIN_METHODS.ui, () => null); + main.handle(MAIN_METHODS.secretGet, () => null); + main.handle(MAIN_METHODS.clipboardRead, () => ''); + main.handle(MAIN_METHODS.openExternal, () => false); + main.handle(MAIN_METHODS.showDialog, () => null); + main.handle(MAIN_METHODS.executeWorkbenchCommand, () => undefined); + const withCode = installed.filter((entry) => entry.manifest.main); + const init: HostInitData = { + extensions: withCode.map((entry) => ({ + id: entry.manifest.id, + location: entry.location, + main: entry.manifest.main as string, + packageJSON: entry.manifest.raw, + activationEvents: activationEventsOf(entry.manifest.activationEvents, entry.manifest.contributes), + extensionDependencies: entry.manifest.extensionDependencies, + })), + passive: installed.filter((entry) => !entry.manifest.main).map((entry) => ({ id: entry.manifest.id, location: entry.location, packageJSON: entry.manifest.raw })), + workspaceFolder: folder, + trusted: true, + configuration: {}, + globalStorageRoot: path.join(scratch, 'storage', 'global'), + workspaceStorageRoot: path.join(scratch, 'storage', 'workspace'), + logRoot: path.join(scratch, 'logs'), + env: { appName: 'Code-XR IDE', appRoot: scratch, appHost: 'desktop', language: 'en', machineId: 'compat-probe', sessionId: 'compat-probe', uriScheme: 'codexr', shell: '/bin/sh', version: '0.0.0' }, + isDevelopment: false, + documents: [], + activeEditor: null, + }; + const exited = new Promise((resolve) => child.on('exit', (code, signal) => resolve(`The host exited (${signal ?? code}).`))); + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; + try { + const run = async (): Promise => { + await main.request(HOST_METHODS.init, init); + for (const event of probeEvents(extension, folder)) { + await main.request(HOST_METHODS.activateByEvent, event); + } + const commands = await main.request(HOST_METHODS.registeredCommands); + return commands.length; + }; + const outcome = await withTimeout(Promise.race([run(), exited.then((reason) => Promise.reject(new Error(reason)))]), timeoutMs); + if (outcome === 'timeout') { + return { outcome: 'timeout', missingApi, errors, registeredCommands: 0, detail: `No answer within ${timeoutMs} ms.` }; + } + const settled = activation as HostActivationEvent | null; + if (!settled) { + return { outcome: 'failed', missingApi, errors, registeredCommands: outcome, detail: 'No activation event matched: the extension was never activated.' }; + } + return { outcome: settled.state === 'active' ? 'activated' : 'failed', missingApi, errors, registeredCommands: outcome, detail: settled.error ?? null }; + } catch (error) { + return { outcome: 'failed', missingApi, errors, registeredCommands: 0, detail: error instanceof Error ? error.message : String(error) }; + } finally { + if (child.exitCode === null && child.signalCode === null) { + await withTimeout(main.request(HOST_METHODS.shutdown).catch(() => undefined), 3000); + child.kill(); + // Windows keeps the files the process opened locked until it has exited: wait, so the scratch folder can go. + await withTimeout(exited, 5000); + } + main.dispose(); + } +} + +function cell(value: string): string { + return value.replace(/\|/g, '\\|').replace(/\n/g, ' '); +} + +/** The results as the Markdown table of docs/ide/extensions-compatibility.md. */ +export function probeTable(results: readonly ProbeResult[]): string { + const rows = ['| Extension | Version | Result | Missing vscode API at start-up | Notes |', '|---|---|---|---|---|']; + for (const result of results) { + const name = result.id ?? path.basename(result.file); + const notes = [ + result.engineSupported === false ? 'engine range above the IDE\'s API version' : '', + result.registeredCommands > 0 ? `${result.registeredCommands} commands registered` : '', + result.detail ?? '', + result.errors.length > 0 ? `${result.errors.length} error line(s): ${result.errors[0]}` : '', + ].filter(Boolean).join('; '); + rows.push(`| ${cell(name)} | ${cell(result.version ?? '')} | ${result.outcome} | ${cell(result.missingApi.join(', ') || 'none')} | ${cell(notes.slice(0, 300))} |`); + } + return rows.join('\n'); +} diff --git a/apps/ide/src/main/extensions/extensionsService.ts b/apps/ide/src/main/extensions/extensionsService.ts index 38625480..e5819008 100644 --- a/apps/ide/src/main/extensions/extensionsService.ts +++ b/apps/ide/src/main/extensions/extensionsService.ts @@ -13,6 +13,7 @@ import { ContributionIndex } from './contributions.ts'; import { ExtensionStore, resolveInExtension, type LoadedExtension } from './extensionStore.ts'; import { engineSupported, summarizeContributions, type ExtensionManifest } from './manifest.ts'; import { GalleryError, normalizeGalleryUrl, OpenVsxClient, type FetchLike } from './openVsx.ts'; +import { extensionRunState, mayRunCode } from './runState.ts'; type Handle = (channel: string, handler: (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown) => void; @@ -120,10 +121,7 @@ export class ExtensionsService { /** Whether an extension's code may run in this window (#263). */ mayRun(contents: WebContents | null, extension: LoadedExtension): boolean { - if (this.disabledByFlag || !extension.enabled) { - return false; - } - return extension.manifest.supportsUntrusted || contents === null || isWorkspaceTrusted(contents); + return mayRunCode({ enabled: extension.enabled, disabledByFlag: this.disabledByFlag, supportsUntrusted: extension.manifest.supportsUntrusted, trusted: contents === null ? null : isWorkspaceTrusted(contents) }); } describe(contents: WebContents | null, extension: LoadedExtension): InstalledExtension { @@ -132,7 +130,6 @@ export class ExtensionsService { if (!this.icons.has(manifest.id)) { this.icons.set(manifest.id, iconOf(extension)); } - const restricted = hasCode && !manifest.supportsUntrusted && contents !== null && !isWorkspaceTrusted(contents); const activation = hasCode && contents && this.activations ? this.activations.activation(contents, manifest.id) : { state: hasCode ? 'inactive' as const : 'none' as const }; return { id: manifest.id, @@ -146,7 +143,7 @@ export class ExtensionsService { repository: manifest.repository, icon: this.icons.get(manifest.id) ?? null, hasCode, - state: !extension.enabled || this.disabledByFlag ? 'disabled' : restricted ? 'restricted' : 'enabled', + state: extensionRunState({ enabled: extension.enabled, disabledByFlag: this.disabledByFlag, hasCode, supportsUntrusted: manifest.supportsUntrusted, trusted: contents === null ? null : isWorkspaceTrusted(contents) }), activation: activation.state, ...(activation.error ? { activationError: activation.error } : {}), engine: manifest.engine, diff --git a/apps/ide/src/main/extensions/runState.ts b/apps/ide/src/main/extensions/runState.ts new file mode 100644 index 00000000..011e120b --- /dev/null +++ b/apps/ide/src/main/extensions/runState.ts @@ -0,0 +1,31 @@ +import type { ExtensionRunState } from '../../shared/extensions.ts'; + +/** + * #263: whether an installed extension runs in a window, and why not. Pure, + * so the rules are unit-tested without Electron: + * - `--disable-extensions` or the person's choice (`extensions.json` in the + * user-data folder, never the project) turns it off; + * - in Restricted Mode, an extension with code runs only when its manifest + * declares `capabilities.untrustedWorkspaces.supported` (`true` or + * `"limited"`); declarative ones (themes, grammars) always run. + */ +export interface RunStateInput { + readonly enabled: boolean; + readonly disabledByFlag: boolean; + readonly hasCode: boolean; + readonly supportsUntrusted: boolean; + /** The window's folder trust; null when there is no window (nothing restricts then). */ + readonly trusted: boolean | null; +} + +export function extensionRunState(input: RunStateInput): ExtensionRunState { + if (!input.enabled || input.disabledByFlag) { + return 'disabled'; + } + return input.hasCode && !input.supportsUntrusted && input.trusted === false ? 'restricted' : 'enabled'; +} + +/** Whether its code may start in that window's extension host. */ +export function mayRunCode(input: Omit): boolean { + return extensionRunState({ ...input, hasCode: true }) === 'enabled'; +} diff --git a/apps/ide/src/renderer/trustChoices.ts b/apps/ide/src/renderer/trustChoices.ts index d68ab3b3..8a1141cf 100644 --- a/apps/ide/src/renderer/trustChoices.ts +++ b/apps/ide/src/renderer/trustChoices.ts @@ -1,7 +1,7 @@ /** #177: what the trust view shows and offers, apart from the DOM (unit-tested in Node). */ import type { WorkspaceTrustInfo } from '../shared/api.ts'; -export const RESTRICTED_SUMMARY = 'Restricted Mode keeps Git, the Python language server and tasks off, because they run what the folder defines. Reading, editing, the terminal and the Code-XR analysis work either way.'; +export const RESTRICTED_SUMMARY = 'Restricted Mode keeps Git, the Python language server, tasks and the extensions that do not support it off, because they run what the folder defines. Reading, editing, the terminal and the Code-XR analysis work either way.'; export type TrustChoice = 'folder' | 'parent' | 'restrict'; @@ -28,7 +28,7 @@ export function trustChoices(info: WorkspaceTrustInfo): TrustPickItem[] { items.push({ id: 'parent', label: `Trust every folder in ${lastSegment(info.parent)}`, description: info.parent }); } if (info.state !== 'restricted') { - items.push({ id: 'restrict', label: 'Open this folder in Restricted Mode', description: 'Git, the Python language server and tasks stay off' }); + items.push({ id: 'restrict', label: 'Open this folder in Restricted Mode', description: 'Git, the Python language server, tasks and most extensions stay off' }); } return items; } diff --git a/apps/ide/test/extensionCompat.test.ts b/apps/ide/test/extensionCompat.test.ts new file mode 100644 index 00000000..83eb9b44 --- /dev/null +++ b/apps/ide/test/extensionCompat.test.ts @@ -0,0 +1,79 @@ +import { after, before, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { probeTable, probeVsix, type ProbeOptions } from '../src/main/extensions/compatProbe.ts'; +import { vsix } from './helpers/zip.ts'; + +const HOST_ENTRY = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'extensionHost', 'index.ts'); +const OPTIONS: ProbeOptions = { hostEntry: HOST_ENTRY, execArgv: ['--experimental-strip-types', '--no-warnings'], timeoutMs: 20_000 }; +const manifest = (name: string, extra: Record = {}): Record => ({ publisher: 'acme', name, version: '1.0.0', engines: { vscode: '^1.80.0' }, ...extra }); + +describe('the compatibility probe (#264)', () => { + let tmp = ''; + const write = (name: string, data: Buffer): string => { + const file = path.join(tmp, name); + fs.writeFileSync(file, data); + return file; + }; + + before(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-compat-test-')); + }); + after(() => { + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + it('reports an extension that activates, with the commands it registered', async () => { + const file = write('ok.vsix', vsix(manifest('ok', { main: 'index.js', activationEvents: ['onCommand:ok.hi'], contributes: { commands: [{ command: 'ok.hi', title: 'Hi' }] } }), { + 'index.js': "exports.activate = (c) => c.subscriptions.push(require('vscode').commands.registerCommand('ok.hi', () => 1));", + })); + const result = await probeVsix(file, OPTIONS); + assert.equal(result.outcome, 'activated'); + assert.equal(result.id, 'acme.ok'); + assert.equal(result.registeredCommands, 1); + assert.deepEqual(result.missingApi, []); + }); + + it('runs an extension shipped as an ES module that imports vscode, as popular ones do', async () => { + const source = [ + "import * as vscode from 'vscode';", + "import api from 'vscode';", + 'export function activate(context) {', + ' const nls = JSON.parse(process.env.VSCODE_NLS_CONFIG);', + ' const kinds = [vscode.TestRunProfileKind.Run, vscode.QuickInputButtonLocation.Input, api.ViewColumn.One];', + " context.subscriptions.push(vscode.commands.registerCommand('esm.hi', () => [nls.locale, ...kinds]));", + '}', + ].join('\n'); + const file = write('esm.vsix', vsix(manifest('esm', { type: 'module', main: 'index.js', activationEvents: ['*'] }), { 'index.js': source })); + const result = await probeVsix(file, OPTIONS); + assert.equal(result.outcome, 'activated', result.detail ?? ''); + assert.equal(result.registeredCommands, 1); + assert.deepEqual(result.missingApi, []); + }); + + it('names the vscode API an extension reached for that the host lacks', async () => { + const file = write('gap.vsix', vsix(manifest('gap', { main: 'index.js', activationEvents: ['onStartupFinished'] }), { + 'index.js': "exports.activate = () => { require('vscode').window.registerCustomEditorProvider('gap.editor', {}); };", + })); + const result = await probeVsix(file, OPTIONS); + assert.equal(result.outcome, 'activated'); + assert.ok(result.missingApi.some((api) => api.includes('registerCustomEditorProvider')), result.missingApi.join(', ')); + }); + + it('reports a failed activation, a package without code, and one that does not install', async () => { + const failing = await probeVsix(write('bad.vsix', vsix(manifest('bad', { main: 'index.js', activationEvents: ['*'] }), { 'index.js': "exports.activate = () => { throw new Error('boom'); };" })), OPTIONS); + assert.equal(failing.outcome, 'failed'); + assert.match(failing.detail ?? '', /boom/); + const theme = await probeVsix(write('theme.vsix', vsix(manifest('theme', { contributes: { themes: [{ label: 'T', uiTheme: 'vs-dark', path: 't.json' }] } }), { 't.json': '{}' })), OPTIONS); + assert.equal(theme.outcome, 'no-code'); + assert.deepEqual(theme.contributions?.themes, ['T']); + const broken = await probeVsix(write('broken.vsix', Buffer.from('not a zip')), OPTIONS); + assert.equal(broken.outcome, 'not-installed'); + const table = probeTable([failing, theme, broken]); + assert.match(table, /\| acme\.bad \| 1\.0\.0 \| failed \|/); + assert.match(table, /\| broken\.vsix \| {2}\| not-installed \|/); + }); +}); diff --git a/apps/ide/test/extensionTrust.test.ts b/apps/ide/test/extensionTrust.test.ts new file mode 100644 index 00000000..d6b9973c --- /dev/null +++ b/apps/ide/test/extensionTrust.test.ts @@ -0,0 +1,105 @@ +import { after, before, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { fork, type ChildProcess } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { HOST_METHODS, MAIN_METHODS, RpcEndpoint, type HostInitData } from '../src/shared/extensionHostProtocol.ts'; +import { parseManifest } from '../src/main/extensions/manifest.ts'; +import { extensionRunState, mayRunCode } from '../src/main/extensions/runState.ts'; + +const HOST_ENTRY = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'extensionHost', 'index.ts'); + +describe('extensions and workspace trust (#263)', () => { + const base = { enabled: true, disabledByFlag: false, hasCode: true, supportsUntrusted: false, trusted: true }; + + it('keeps extensions with code off in Restricted Mode unless they declare support', () => { + assert.equal(extensionRunState(base), 'enabled'); + assert.equal(extensionRunState({ ...base, trusted: false }), 'restricted'); + assert.equal(extensionRunState({ ...base, trusted: false, supportsUntrusted: true }), 'enabled'); + assert.equal(extensionRunState({ ...base, trusted: false, hasCode: false }), 'enabled', 'a theme or a grammar runs no code'); + assert.equal(extensionRunState({ ...base, trusted: null }), 'enabled', 'no window, nothing restricts'); + assert.equal(mayRunCode({ ...base, trusted: false }), false); + assert.equal(mayRunCode({ ...base, trusted: false, supportsUntrusted: true }), true); + }); + + it('lets the person and --disable-extensions turn any extension off, trusted or not', () => { + assert.equal(extensionRunState({ ...base, enabled: false }), 'disabled'); + assert.equal(extensionRunState({ ...base, disabledByFlag: true }), 'disabled'); + assert.equal(extensionRunState({ ...base, disabledByFlag: true, supportsUntrusted: true, trusted: false }), 'disabled'); + assert.equal(mayRunCode({ ...base, disabledByFlag: true }), false); + }); + + it('reads untrustedWorkspaces.supported as VS Code does: true and "limited" support it', () => { + const manifest = (supported: unknown): boolean => parseManifest({ name: 'x', publisher: 'p', version: '1.0.0', engines: { vscode: '^1.80.0' }, capabilities: { untrustedWorkspaces: { supported } } }).supportsUntrusted; + assert.equal(manifest(true), true); + assert.equal(manifest('limited'), true); + assert.equal(manifest(false), false); + assert.equal(manifest('yes'), false); + assert.equal(parseManifest({ name: 'x', publisher: 'p', version: '1.0.0', engines: { vscode: '^1.80.0' } }).supportsUntrusted, false); + }); +}); + +const TRUST_JS = ` +const vscode = require('vscode'); +const seen = []; +exports.activate = (context) => { + seen.push('activated ' + vscode.workspace.isTrusted); + context.subscriptions.push(vscode.workspace.onDidGrantWorkspaceTrust(() => seen.push('granted ' + vscode.workspace.isTrusted))); + context.subscriptions.push(vscode.commands.registerCommand('trust.seen', () => seen.slice())); +}; +`; + +describe('workspace.isTrusted in the extension host (#263)', () => { + let tmp = ''; + let child: ChildProcess; + let main: RpcEndpoint; + + before(async () => { + tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-trust-test-'))); + const folder = path.join(tmp, 'ext'); + fs.mkdirSync(folder); + const packageJSON = { publisher: 'acme', name: 'trust', version: '1.0.0', main: 'index.js', engines: { vscode: '^1.80.0' }, capabilities: { untrustedWorkspaces: { supported: true } } }; + fs.writeFileSync(path.join(folder, 'package.json'), JSON.stringify(packageJSON)); + fs.writeFileSync(path.join(folder, 'index.js'), TRUST_JS); + child = fork(HOST_ENTRY, [], { execArgv: ['--experimental-strip-types', '--no-warnings'], stdio: ['ignore', 'pipe', 'pipe', 'ipc'], serialization: 'advanced' }); + child.stderr?.on('data', (chunk: Buffer) => process.stderr.write(`[host stderr] ${chunk.toString()}`)); + main = new RpcEndpoint((message) => child.send(message)); + child.on('message', (message) => main.receive(message)); + for (const method of [MAIN_METHODS.log, MAIN_METHODS.activation, MAIN_METHODS.notImplemented, MAIN_METHODS.uiNotify, MAIN_METHODS.webview]) { + main.handle(method, () => undefined); + } + main.handle(MAIN_METHODS.ui, () => null); + const init: HostInitData = { + extensions: [{ id: 'acme.trust', location: folder, main: 'index.js', packageJSON, activationEvents: ['*'], extensionDependencies: [] }], + passive: [], + workspaceFolder: tmp, + trusted: false, + configuration: {}, + globalStorageRoot: path.join(tmp, 'storage'), + workspaceStorageRoot: null, + logRoot: path.join(tmp, 'logs'), + env: { appName: 'Code-XR IDE', appRoot: tmp, appHost: 'desktop', language: 'en', machineId: 'm', sessionId: 's', uriScheme: 'codexr', shell: '/bin/sh', version: '0.0.0' }, + isDevelopment: false, + documents: [], + activeEditor: null, + }; + await main.request(HOST_METHODS.init, init); + }); + + after(() => { + if (child.exitCode === null) { + child.kill(); + } + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + it('follows the IDE: false in Restricted Mode, then onDidGrantWorkspaceTrust once the folder is trusted', async () => { + await main.request(HOST_METHODS.activateByEvent, '*'); + assert.deepEqual(await main.request(HOST_METHODS.executeCommand, 'trust.seen', []), ['activated false']); + main.notify(HOST_METHODS.trustChanged, true); + main.notify(HOST_METHODS.trustChanged, true); + assert.deepEqual(await main.request(HOST_METHODS.executeCommand, 'trust.seen', []), ['activated false', 'granted true'], 'granted once'); + }); +}); diff --git a/docs/ide/extensions-compatibility.md b/docs/ide/extensions-compatibility.md new file mode 100644 index 00000000..f1e5c66d --- /dev/null +++ b/docs/ide/extensions-compatibility.md @@ -0,0 +1,102 @@ +# Extension compatibility of the Code-XR IDE + +Story #264 of epic #251. Which VS Code extensions run in the IDE, measured rather than assumed, and how to measure a new one. The design is in [extensions.md](extensions.md). + +## How it is measured + +`apps/ide/scripts/extensionCompat.mjs` (logic in `apps/ide/src/main/extensions/compatProbe.ts`, tests in `apps/ide/test/extensionCompat.test.ts`) does, for each `.vsix`: + +1. Installs it through the IDE's own install path (`ExtensionStore`: the same unpack, zip-slip and symlink checks, manifest validation and folder layout as the *Extensions* view), in a throw-away store. +2. Starts the real extension host (`apps/ide/src/extensionHost/index.ts`) in a Node process of its own, with a trusted, empty folder open. +3. Fires every activation event the extension declares (and the implicit ones VS Code adds), plus `*` and `onStartupFinished`. +4. Records whether the extension activated or failed, every `vscode` API it used that the host does not implement (the same report the *Extensions* output shows), the errors it logged, and how many commands it registered. + +What it answers: *does the code start in the IDE, and what does it miss at start-up*. What it does not answer: whether every feature works. A feature behind a command or a language request can still reach a missing API later, which the *Extensions* output then names. Webviews and tree views are checked in the real window by the *Code-XR extension in the IDE* CI job and by hand (see below). + +Run it: + +```bash +cd apps/ide +npm run compat -- --markdown path/to/one.vsix path/to/a/folder/of/vsix +npm run compat -- --markdown --open-vsx redhat.vscode-yaml esbenp.prettier-vscode # downloads first (same client and SHA-256 check as the IDE) +``` + +`--json ` also writes the full results. The exit code is 1 when a package failed to install, activate or answer. + +The *Popular extensions in the extension host* job of `.github/workflows/ci.yml` runs it on about thirty popular extensions from Open VSX on every pull request and writes the table to the job summary. It is a measurement, never a gate: a third-party release must not turn the build red. + +## Results + +### Packages checked locally (2026-11-27) + +Microsoft's [extension samples](https://github.com/microsoft/vscode-extension-samples) built from source, VS Code's own built-in `ini`, `swift` and two themes packed as `.vsix`, two test extensions written for #261, and the Code-XR extension itself. + +| Extension | Version | Result | Missing vscode API at start-up | Notes | +|---|---|---|---|---| +| amontesl.code-xr | 1.2.1 | activated | none | 107 commands registered; also checked in the real window (tree, LivePanel in a webview, XR) | +| codexr-test.cat-coding | 0.0.1 | activated | none | Webview panel and view; checked in the real window | +| codexr-test.todo-tree-demo | 0.0.1 | activated | none | Tree view, menus, `when` clauses; checked in the real window | +| vscode-samples.configuration-sample | 0.0.1 | activated | none | | +| vscode-samples.helloworld-minimal-sample | 0.0.1 | activated | none | | +| vscode-samples.lsp-sample | 1.0.0 | activated | none | Language client and server; diagnostics and completion checked in the real window. The probe stops it while the client is still starting, which it logs as a `deactivate()` error | +| vscode-samples.progress-ts | 0.0.1 | activated | none | | +| vscode-samples.quickinput-sample | 0.0.1 | activated | none | | +| vscode-samples.status-ts | 0.0.1 | activated | none | | +| vscode.ini | 10.0.0 | no code | — | Language, grammar | +| vscode.swift | 10.0.0 | no code | — | Language, grammar, snippets | +| vscode.theme-monokai | 10.0.0 | no code | — | Colour theme | +| vscode.theme-solarized-light | 10.0.0 | no code | — | Colour theme | + +### Popular extensions from Open VSX (2026-11-27) + +Thirty popular extensions, latest Open VSX release, measured by the CI job (Linux, no folder content, nothing else installed). **23 activate, 4 have no code (themes, the Docker pack, the Spanish language pack), 2 fail and 1 does not answer within 30 s.** + +The first measurement had five failures. Three were fixed in the host from what the probe reported: extensions shipped as ES modules could not `import 'vscode'` (Prettier), enums of unimplemented areas were missing and reading them at start-up threw (`TestRunProfileKind`: Python; `QuickInputButtonLocation`: GitLens), and `VSCODE_NLS_CONFIG` was not set (Markdown All in One). What remains: + +- **vue.volar** reads `extensions.getExtension('vscode.typescript-language-features').isActive`: it is built on VS Code's built-in TypeScript extension, which the IDE does not have. +- **yzhang.markdown-all-in-one** gets past its `VSCODE_NLS_CONFIG` read now, then fails building its completion provider (`Object.entries` of undefined); it relies on VS Code's built-in Markdown support. +- **golang.go** does not finish activating within 30 s without the Go toolchain installed; it was not investigated further. + +"Missing vscode API" is what the extension touched and got a stub for: it keeps running without that feature (for example GitLens without its custom editors and terminal integration, Python without its test explorer and terminals). Error lines about a language server that could not start (rust-analyzer, Java) come from the runner having no such toolchain, not from the IDE. + +| Extension | Version | Result | Missing vscode API at start-up | Notes | +|---|---|---|---|---| +| redhat.vscode-yaml | 2.1.2026112008 | activated | languages.registerSelectionRangeProvider | 1 commands registered; 1 error line(s): (node:2379) [DEP0169] DeprecationWarning: `url.parse()` behavior is not standardized and prone to errors that have security implications. Use the WHATWG URL API instead. CVEs ar... | +| esbenp.prettier-vscode | 12.4.0 | activated | none | 3 commands registered | +| dbaeumer.vscode-eslint | 3.0.34 | activated | none | 6 commands registered | +| eamodio.gitlens | 2026.11.260409 | activated | workspace.registerFileSystemProvider, window.registerWebviewPanelSerializer (panels are not restored after a restart), window.onDidChangeTerminalShellIntegration, window.registerCustomEditorProvider, window.registerFileDecorationProvider, window.registerTerminalLinkProvider | 799 commands registered; 2 error line(s): TypeError: Cannot read properties of undefined (reading 'fsPath') [ 57 → 8a] GitProviderService.registrationComplete — failed [1ms] | +| ms-python.python | 2026.10.0 | activated | tests.createTestController, window.onDidWriteTerminalData, window.createTerminal, window.onDidStartTerminalShellExecution, window.registerTerminalLinkProvider, lm.registerTool | 33 commands registered; 1 error line(s): Dir "/tmp/codexr-compat-EMtJbf/workspace/.pixi/envs" is not watchable (directory does not exist) | +| rust-lang.rust-analyzer | 0.4.3134 | activated | none | 58 commands registered; 3 error line(s): /tmp/codexr-compat-J7VwN8/extensions/rust-lang.rust-analyzer-0.4.3134/server/rust-analyzer --version: { stdout: '', stderr: '', status: undefined, error: Error: spawn /... | +| golang.go | 0.58.0 | timeout | window.registerWebviewPanelSerializer (panels are not restored after a restart) | No answer within 30000 ms. | +| streetsidesoftware.code-spell-checker | 4.10.0 | activated | window.onDidChangeActiveNotebookEditor, window.registerTerminalProfileProvider, languages.registerInlineCompletionItemProvider | 79 commands registered | +| usernamehw.errorlens | 3.30.0 | activated | none | 20 commands registered | +| pkief.material-icon-theme | 5.40.0 | activated | none | 11 commands registered | +| vscodevim.vim | 1.32.4 | activated | none | 70 commands registered; 2 error line(s): Unhandled promise rejection in an extension: Error: ENOENT: no such file or directory, open '/tmp/codexr-compat-XoLvQb/storage/global/vscodevim.vim/.registers' | +| christian-kohler.path-intellisense | 2.8.0 | activated | none | | +| editorconfig.editorconfig | 0.18.2 | activated | none | 2 commands registered | +| yzhang.markdown-all-in-one | 3.6.2 | failed | none | 29 commands registered; Cannot convert undefined or null to object; 1 error line(s): Failed to activate: TypeError: Cannot convert undefined or null to object at Object.entries () at new MdCompletio... | +| gruntfuggly.todo-tree | 0.0.215 | activated | none | | +| mechatroner.rainbow-csv | 3.24.1 | activated | languages.registerDocumentRangeSemanticTokensProvider | 25 commands registered | +| formulahendry.code-runner | 0.12.2 | activated | none | 4 commands registered | +| dracula-theme.theme-dracula | 2.25.1 | no-code | none | | +| github.github-vscode-theme | 6.3.5 | no-code | none | | +| llvm-vs-code-extensions.vscode-clangd | 0.6.0 | activated | none | 3 commands registered | +| vue.volar | 3.3.14 | failed | none | Cannot read properties of undefined (reading 'isActive'); 1 error line(s): Failed to activate: TypeError: Cannot read properties of undefined (reading 'isActive') at Gr (/tmp/codexr-compat-EuPd4O/extensions/vue.vo... | +| svelte.svelte-vscode | 110.3.2 | activated | none | 10 commands registered | +| bradlc.vscode-tailwindcss | 0.16.0 | activated | none | 2 commands registered | +| hashicorp.terraform | 2.40.1 | activated | lm.registerMcpServerDefinitionProvider | 32 commands registered | +| tamasfe.even-better-toml | 0.21.2 | activated | languages.registerDocumentSemanticTokensProvider | 5 commands registered | +| james-yu.latex-workshop | 10.20.1 | activated | window.registerWebviewPanelSerializer (panels are not restored after a restart), window.registerCustomEditorProvider, languages.registerWorkspaceSymbolProvider, languages.registerColorProvider, languages.registerSelectionRangeProvider | 71 commands registered | +| oderwat.indent-rainbow | 8.3.1 | activated | none | | +| ms-azuretools.vscode-docker | 2.0.0 | no-code | none | | +| redhat.java | 1.59.2026112708 | activated | window.registerCustomEditorProvider | 29 commands registered; 5 error line(s): Language Support for Java (Syntax Server) client: couldn't create connection to server. Launching server using command /tmp/codexr-compat-hggjk7/extensions/redhat.java-1.59.202... | +| ms-ceintl.vscode-language-pack-es | 1.131.0 | no-code | none | | + +## Known limits + +- **Language packs** (`MS-CEINTL.vscode-language-pack-*`) install and are listed, and have no visible effect: the IDE's interface is its own and does not read VS Code's UI strings. +- **File icon themes and product icon themes** are listed in the details page but not applied yet. +- **Missing API** is reported, never fatal: the call returns a harmless stub (an empty disposable, `undefined`) and the *Extensions* output names it once. An extension that depends on it for a feature will lack that feature. +- **Webview permissions**: no webview gets camera, microphone, XR or popups. +- **Debuggers, tasks, authentication providers, notebooks, the test explorer, SCM providers, comments, chat participants, terminals created by extensions and custom editors** are among the larger API areas not implemented; [vscode-api-inventory.md](vscode-api-inventory.md) lists the surface. +- **The Visual Studio Marketplace** is not used (its terms allow only Microsoft products): extensions published only there are not installable from the view. A `.vsix` the person has the right to use installs from file. diff --git a/docs/ide/extensions.md b/docs/ide/extensions.md index cfc59c25..e02e1f0f 100644 --- a/docs/ide/extensions.md +++ b/docs/ide/extensions.md @@ -18,6 +18,7 @@ Epic #251. Decision: [ADR 0002](../../adr/0002-vscode-extensions-in-the-ide.md). | The Code-XR extension itself (`code-xr-.vsix`): its activity bar container and tree, its Python environment, file and folder analyses as LivePanel (in a webview panel or the browser) and in XR, servers and examples | Done, checked in CI | #262 | | File icon themes, product icon themes | Not yet: listed in the details page | — | | Language packs | Install, no visible effect (the IDE does not use VS Code's UI strings) | #264 | +| Compatibility measured: a probe installs a `.vsix` and runs it in the real host, reporting activation and missing API; CI runs it on ~30 popular Open VSX extensions | Done: [extensions-compatibility.md](extensions-compatibility.md) | #264 | ## Processes and files @@ -123,7 +124,7 @@ The extension's own `.vsix` installs from file (*Extensions* view, `...` > *Inst - CSP: `script-src 'self' 'wasm-unsafe-eval'` (WebAssembly only; `eval` and `new Function` stay blocked, which the smoke run checks); `frame-src codexr-webview:` (extensions' webviews only, #261). - Nothing an extension declares runs in the renderer: themes and grammars are data; snippets are text. -- Extensions with code run in the extension host process, never in the renderer or the main process. They have the rights of the person's account, as in VS Code: install only extensions you trust. In a folder in Restricted Mode only the extensions that declare `capabilities.untrustedWorkspaces.supported` run (#263 finishes that story). +- Extensions with code run in the extension host process, never in the renderer or the main process. They have the rights of the person's account, as in VS Code: install only extensions you trust. In a folder in Restricted Mode only the extensions that declare `capabilities.untrustedWorkspaces.supported` (`true` or `"limited"`) run; the others show *Disabled in Restricted Mode*, and trusting the folder restarts the host with them (#263). `workspace.isTrusted` and `onDidGrantWorkspaceTrust` follow the IDE's trust. What is enabled is kept in `extensions.json` in the IDE's user-data folder, never in the project, so a folder cannot turn an extension on. For recovery: start with `--disable-extensions`, or run **Disable All Installed Extensions**. - What the host asks of the main process is checked there: files open only inside the folder, external links only for http, https and mailto, settings keys are bounded, secrets are encrypted by the OS store (`safeStorage`) and kept per extension. - No telemetry: `env.isTelemetryEnabled` is false and `createTelemetryLogger` sends nothing.