diff --git a/apps/ide/README.md b/apps/ide/README.md index 14dfed7b..ac5de5a1 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -180,7 +180,7 @@ Following Electron's [security checklist](https://www.electronjs.org/docs/latest | No network request unless the person asks: the update check runs from Help > Check for Updates…, or at start-up only if `update.checkOnStartup` is turned on (off by default); it reads the public GitHub releases list, downloads nothing and only opens the release page in the browser | `src/main/updates/` (`updateRelease.ts` pure, `updateCheck.ts`) | Unit tests (`test/updateCheck.test.ts`: tags, drafts, pre-releases, versions); never run in the smoke run. | | 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); only workbench activation events are accepted from the renderer | `src/extensionHost/`, `src/main/extensions/extensionHostManager.ts` | Unit tests (`test/extensionHost.test.ts`, with a real host process). | +| 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). | | 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. @@ -365,7 +365,7 @@ The parsers (`statusParser.ts`, `blameParser.ts`) are pure and unit-tested on st ## VS Code extensions (stream `ide-extensions`, epic #251) -The Extensions view (activity bar, puzzle icon, `Ctrl/Cmd+Shift+X`) installs VS Code extensions from **Open VSX** (never the Visual Studio Marketplace, whose terms only allow Microsoft products; ADR [0002](../../adr/0002-vscode-extensions-in-the-ide.md)) or from a `.vsix` file, and enables, disables and uninstalls them. Colour themes, languages, TextMate grammars and snippets apply at once; extensions with code run in an extension host process per window (`src/extensionHost/`, #259), with their commands in the palette and their messages, pickers, progress and status bar items in the workbench. Design, state and how to try it: [`docs/ide/extensions.md`](../../docs/ide/extensions.md). +The Extensions view (activity bar, puzzle icon, `Ctrl/Cmd+Shift+X`) installs VS Code extensions from **Open VSX** (never the Visual Studio Marketplace, whose terms only allow Microsoft products; ADR [0002](../../adr/0002-vscode-extensions-in-the-ide.md)) or from a `.vsix` file, and enables, disables and uninstalls them. Colour themes, languages, TextMate grammars and snippets apply at once; extensions with code run in an extension host process per window (`src/extensionHost/`, #259), with their commands in the palette and their messages, pickers, progress and status bar items in the workbench; they see the editor's documents and active editor, and their language features (diagnostics, completion, hover, definitions, code actions, formatting, rename... including language clients built on `vscode-languageclient`) work in Monaco (#260). Design, state and how to try it: [`docs/ide/extensions.md`](../../docs/ide/extensions.md). ## AI agent hub (stream `ai-agents`) diff --git a/apps/ide/src/extensionHost/api.ts b/apps/ide/src/extensionHost/api.ts index 299224cc..00b02583 100644 --- a/apps/ide/src/extensionHost/api.ts +++ b/apps/ide/src/extensionHost/api.ts @@ -3,6 +3,7 @@ import fsp from 'node:fs/promises'; import path from 'node:path'; import { MAIN_METHODS, type DialogRequest, type QuickPickItemData, type StatusBarItemData } from '../shared/extensionHostProtocol.ts'; import { HOST_VSCODE_API_VERSION, type ExtensionId } from '../shared/extensions.ts'; +import { TextEditorImpl } from './documents.ts'; import { matchGlob } from './glob.ts'; import type { ExtensionHost, ExtensionRecord } from './host.ts'; import { missingNamespace, withFallback } from './inert.ts'; @@ -17,8 +18,9 @@ import { CancellationTokenNone, Disposable, EventEmitter, FileSystemError, FileT * Code; the rest is reported once and replaced by an inert stand-in * (inert.ts), so an extension keeps running with that feature missing. * - * #260 adds the documents of the editor and the language features, #261 the - * tree views and webviews. + * The editor's documents and the language features are shared by every + * extension (documents.ts, languageFeatures.ts, #260); #261 adds the tree + * views and webviews. */ type Item = string | { title: string; isCloseAffordance?: boolean }; @@ -77,12 +79,15 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u const commands = withFallback('commands', { registerCommand: (id: string, callback: (...args: unknown[]) => unknown, thisArg?: unknown) => host.registerCommand(extensionId, id, callback, thisArg), registerTextEditorCommand: (id: string, callback: (...args: unknown[]) => unknown, thisArg?: unknown) => host.registerCommand(extensionId, id, (...args: unknown[]) => { - const editor = window.activeTextEditor; + const editor = host.documentsAndEditors.activeTextEditor; if (!editor) { - host.log({ level: 'warn', extensionId, message: `Command ${id} needs an active text editor; none is known to extensions yet.` }); + host.log({ level: 'warn', extensionId, message: `Command ${id} needs an active text editor.` }); return undefined; } - return callback.call(thisArg, editor, { replace: () => undefined, insert: () => undefined, delete: () => undefined, setEndOfLine: () => undefined }, ...args); + // As in VS Code: the builder's edits are applied once the callback returns. + return editor.edit((builder) => { + callback.call(thisArg, editor, builder, ...args); + }); }), executeCommand: (id: string, ...args: unknown[]): Promise => host.executeCommand(id, args) as Promise, getCommands: async (filterInternal = false): Promise => { @@ -704,10 +709,6 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u }; const workspaceEvents = { - onDidOpenTextDocument: new EventEmitter(), - onDidCloseTextDocument: new EventEmitter(), - onDidChangeTextDocument: new EventEmitter(), - onDidSaveTextDocument: new EventEmitter(), onWillSaveTextDocument: new EventEmitter(), onDidChangeWorkspaceFolders: new EventEmitter(), onDidCreateFiles: new EventEmitter(), @@ -756,16 +757,12 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u } }); }, - applyEdit: () => { - // #260: edits go through the editor so unsaved text and undo stay right. - report('workspace.applyEdit'); - return Promise.resolve(false); - }, + applyEdit: (edit: types.WorkspaceEdit) => host.documentsAndEditors.applyEdit(edit), saveAll: () => Promise.resolve(false), - onDidOpenTextDocument: workspaceEvents.onDidOpenTextDocument.event, - onDidCloseTextDocument: workspaceEvents.onDidCloseTextDocument.event, - onDidChangeTextDocument: workspaceEvents.onDidChangeTextDocument.event, - onDidSaveTextDocument: workspaceEvents.onDidSaveTextDocument.event, + onDidOpenTextDocument: host.documentsAndEditors.onDidOpenTextDocument.event, + onDidCloseTextDocument: host.documentsAndEditors.onDidCloseTextDocument.event, + onDidChangeTextDocument: host.documentsAndEditors.onDidChangeTextDocument.event, + onDidSaveTextDocument: host.documentsAndEditors.onDidSaveTextDocument.event, onWillSaveTextDocument: workspaceEvents.onWillSaveTextDocument.event, onDidChangeWorkspaceFolders: workspaceEvents.onDidChangeWorkspaceFolders.event, onDidCreateFiles: workspaceEvents.onDidCreateFiles.event, @@ -781,10 +778,6 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u /* ------------------------------ window ------------------------------ */ const windowEvents = { - onDidChangeActiveTextEditor: new EventEmitter(), - onDidChangeVisibleTextEditors: new EventEmitter(), - onDidChangeTextEditorSelection: new EventEmitter(), - onDidChangeTextEditorVisibleRanges: new EventEmitter(), onDidChangeTextEditorOptions: new EventEmitter(), onDidChangeTextEditorViewColumn: new EventEmitter(), onDidChangeWindowState: new EventEmitter(), @@ -795,33 +788,19 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u onDidChangeTerminalState: new EventEmitter(), }; - function editorFor(document: TextDocumentModel) { - const selection = new types.Selection(0, 0, 0, 0); - return { - document, - selection, - selections: [selection], - visibleRanges: [] as types.Range[], - options: { tabSize: 4, insertSpaces: true }, - viewColumn: types.ViewColumn.One, - edit: () => { - report('TextEditor.edit'); - return Promise.resolve(false); - }, - insertSnippet: () => { - report('TextEditor.insertSnippet'); - return Promise.resolve(false); - }, - setDecorations: () => undefined, - revealRange: () => undefined, - show: () => undefined, - hide: () => undefined, - }; + /** The active editor when it shows `document`, else an editor object for it (edits still go through the workbench). */ + function editorFor(document: TextDocumentModel): TextEditorImpl { + const active = host.documentsAndEditors.activeTextEditor; + return active?.document === document ? active : new TextEditorImpl(host, document, null); } const window = withFallback('window', { - activeTextEditor: undefined as unknown, - visibleTextEditors: [] as unknown[], + get activeTextEditor() { + return host.documentsAndEditors.activeTextEditor; + }, + get visibleTextEditors() { + return host.documentsAndEditors.visibleTextEditors; + }, activeTerminal: undefined, terminals: [], state: { focused: true, active: true }, @@ -877,10 +856,10 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u withScmProgress: (task: (progress: { report(value: unknown): void }) => PromiseLike) => task({ report: () => undefined }), createTextEditorDecorationType: () => ({ key: host.nextKey(extensionId), dispose: () => undefined }), registerUriHandler: () => new Disposable(() => undefined), - onDidChangeActiveTextEditor: windowEvents.onDidChangeActiveTextEditor.event, - onDidChangeVisibleTextEditors: windowEvents.onDidChangeVisibleTextEditors.event, - onDidChangeTextEditorSelection: windowEvents.onDidChangeTextEditorSelection.event, - onDidChangeTextEditorVisibleRanges: windowEvents.onDidChangeTextEditorVisibleRanges.event, + onDidChangeActiveTextEditor: host.documentsAndEditors.onDidChangeActiveTextEditor.event, + onDidChangeVisibleTextEditors: host.documentsAndEditors.onDidChangeVisibleTextEditors.event, + onDidChangeTextEditorSelection: host.documentsAndEditors.onDidChangeTextEditorSelection.event, + onDidChangeTextEditorVisibleRanges: host.documentsAndEditors.onDidChangeTextEditorVisibleRanges.event, onDidChangeTextEditorOptions: windowEvents.onDidChangeTextEditorOptions.event, onDidChangeTextEditorViewColumn: windowEvents.onDidChangeTextEditorViewColumn.event, onDidChangeWindowState: windowEvents.onDidChangeWindowState.event, @@ -889,13 +868,7 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u onDidCloseTerminal: windowEvents.onDidCloseTerminal.event, onDidChangeActiveTerminal: windowEvents.onDidChangeActiveTerminal.event, onDidChangeTerminalState: windowEvents.onDidChangeTerminalState.event, - tabGroups: { - all: [], - activeTabGroup: { tabs: [], isActive: true, viewColumn: 1, activeTab: undefined }, - onDidChangeTabGroups: new EventEmitter().event, - onDidChangeTabs: new EventEmitter().event, - close: () => Promise.resolve(false), - }, + tabGroups: host.documentsAndEditors.tabGroups, }, report); /* ------------------------------ env ------------------------------ */ @@ -942,41 +915,40 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u onDidChange: host.onDidChangeExtensions.event, }, report); - /* ------------------------------ languages (#260 adds the providers) ------------------------------ */ + /* ------------------------------ languages (#260) ------------------------------ */ - function createDiagnosticCollection(name = `${extensionId}.diagnostics`) { - const entries = new Map(); - const collection = { - name, - set(uriOrEntries: Uri | [Uri, unknown[] | undefined][], diagnostics?: unknown[]) { - if (Array.isArray(uriOrEntries)) { - for (const [uri, list] of uriOrEntries) { - collection.set(uri, list ?? []); - } - return; - } - if (!diagnostics || diagnostics.length === 0) { - entries.delete(uriOrEntries.toString()); - } else { - entries.set(uriOrEntries.toString(), [uriOrEntries, [...diagnostics]]); - } - }, - delete: (uri: Uri) => void entries.delete(uri.toString()), - clear: () => entries.clear(), - forEach: (callback: (uri: Uri, diagnostics: readonly unknown[], collection: unknown) => void, thisArg?: unknown) => { - for (const [uri, list] of entries.values()) { - callback.call(thisArg, uri, list, collection); - } - }, - get: (uri: Uri) => entries.get(uri.toString())?.[1], - has: (uri: Uri) => entries.has(uri.toString()), - dispose: () => entries.clear(), - [Symbol.iterator]: function* iterate() { - yield* [...entries.values()]; - }, - }; - return collection; - } + const createDiagnosticCollection = (name?: string): unknown => host.languageFeatures.createDiagnosticCollection(extensionId, name ?? `${extensionId}.diagnostics`); + const features = host.languageFeatures; + const register = (kind: Parameters[1], extra: Parameters[4] = {}) => (selector: unknown, provider: unknown) => features.register(extensionId, kind, selector, provider, extra); + const triggers = (values: readonly unknown[]): string[] => values.filter((value): value is string => typeof value === 'string' && value.length > 0); + const providers = { + registerHoverProvider: register('hover'), + registerCompletionItemProvider: (selector: unknown, provider: { resolveCompletionItem?: unknown }, ...triggerCharacters: unknown[]) => features.register(extensionId, 'completion', selector, provider, { + triggerCharacters: triggers(triggerCharacters), resolves: typeof provider?.resolveCompletionItem === 'function', + }), + registerDefinitionProvider: register('definition'), + registerDeclarationProvider: register('declaration'), + registerTypeDefinitionProvider: register('typeDefinition'), + registerImplementationProvider: register('implementation'), + registerReferenceProvider: register('references'), + registerDocumentSymbolProvider: (selector: unknown, provider: unknown, metadata?: { label?: string }) => features.register(extensionId, 'documentSymbol', selector, provider, metadata?.label ? { label: metadata.label } : {}), + registerDocumentHighlightProvider: register('documentHighlight'), + registerSignatureHelpProvider: (selector: unknown, provider: unknown, first?: unknown, ...rest: unknown[]) => { + const metadata = typeof first === 'object' && first !== null ? first as { triggerCharacters?: unknown[]; retriggerCharacters?: unknown[] } : { triggerCharacters: [first, ...rest] }; + return features.register(extensionId, 'signatureHelp', selector, provider, { triggerCharacters: triggers(metadata.triggerCharacters ?? []), retriggerCharacters: triggers(metadata.retriggerCharacters ?? []) }); + }, + registerDocumentFormattingEditProvider: register('formatting'), + registerDocumentRangeFormattingEditProvider: register('rangeFormatting'), + registerOnTypeFormattingEditProvider: (selector: unknown, provider: unknown, first: unknown, ...more: unknown[]) => features.register(extensionId, 'onTypeFormatting', selector, provider, { triggerCharacters: triggers([first, ...more]) }), + registerCodeActionsProvider: (selector: unknown, provider: unknown, metadata?: { providedCodeActionKinds?: readonly { value?: unknown }[] }) => features.register(extensionId, 'codeAction', selector, provider, { + providedCodeActionKinds: (metadata?.providedCodeActionKinds ?? []).map((kind) => String(kind?.value ?? '')), + }), + registerCodeLensProvider: (selector: unknown, provider: { resolveCodeLens?: unknown; onDidChangeCodeLenses?: unknown }) => features.register(extensionId, 'codeLens', selector, provider, { resolves: typeof provider?.resolveCodeLens === 'function' }), + registerRenameProvider: register('rename'), + registerFoldingRangeProvider: register('foldingRange'), + registerInlayHintsProvider: register('inlayHints'), + registerDocumentLinkProvider: register('documentLink'), + }; const matchSelector = (selector: unknown, document: { languageId: string; uri: Uri }): number => { const selectors = Array.isArray(selector) ? selector : [selector]; @@ -1008,8 +980,9 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u const languages = withFallback('languages', { getLanguages: () => Promise.resolve(host.allLanguages()), createDiagnosticCollection, - getDiagnostics: () => [], - onDidChangeDiagnostics: new EventEmitter().event, + getDiagnostics: (uri?: Uri) => features.getDiagnostics(uri), + onDidChangeDiagnostics: features.onDidChangeDiagnostics.event, + ...providers, match: matchSelector, setTextDocumentLanguage: (document: TextDocumentModel, languageId: string) => { document.languageId = languageId; diff --git a/apps/ide/src/extensionHost/documents.ts b/apps/ide/src/extensionHost/documents.ts new file mode 100644 index 00000000..dc361027 --- /dev/null +++ b/apps/ide/src/extensionHost/documents.ts @@ -0,0 +1,426 @@ +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import type { DocumentEvent, EditorStateData, RangeData, SelectionData } from '../shared/extensionLanguageProtocol.ts'; +import { MAX_DOCUMENT_EVENTS } from '../shared/extensionLanguageProtocol.ts'; +import type { ExtensionHost } from './host.ts'; +import { TextDocumentModel } from './textDocument.ts'; +import { EventEmitter, Position, Range, Selection, SnippetString, TabInputText, TextEdit, TextEditorSelectionChangeKind, Uri, WorkspaceEdit } from './types.ts'; + +/** + * The editor's documents and its active editor as extensions see them + * (#260): `workspace.textDocuments` and its events, `window.activeTextEditor` + * and its events. The renderer reports every change (documentSync.ts); this + * keeps one `TextDocument` per open file, shared by every extension, and + * applies each change in order, so a document's text is the editor's. + * + * Edits go the other way through the workbench (`applyEdit`), never to disk + * directly, so unsaved text and undo stay right; the change then comes back + * as an ordinary change event before `applyEdit` resolves. + */ + +export interface TextDocumentChangeEvent { + readonly document: TextDocumentModel; + readonly contentChanges: readonly { readonly range: Range; readonly rangeOffset: number; readonly rangeLength: number; readonly text: string }[]; + readonly reason: undefined; +} + +const toRange = (data: RangeData): Range => new Range(data[0], data[1], data[2], data[3]); +const toSelection = (data: SelectionData): Selection => new Selection(data.anchor[0], data.anchor[1], data.active[0], data.active[1]); +export const rangeData = (range: Range): RangeData => [range.start.line, range.start.character, range.end.line, range.end.character]; + +/** `TextEditor.edit`'s builder: collects the edits, applied together once the callback returns. */ +class EditBuilder { + readonly edits: TextEdit[] = []; + + replace(location: Position | Range | Selection, value: string): void { + const range = location instanceof Position ? new Range(location, location) : location; + this.edits.push(new TextEdit(range, String(value))); + } + insert(location: Position, value: string): void { + this.edits.push(new TextEdit(new Range(location, location), String(value))); + } + delete(location: Range | Selection): void { + this.edits.push(new TextEdit(location, '')); + } + setEndOfLine(): void { + // The workbench changes line endings from its status bar; an extension cannot yet. + } +} + +export class TextEditorImpl { + readonly document: TextDocumentModel; + selections: Selection[]; + visibleRanges: Range[]; + options: { tabSize: number; insertSpaces: boolean }; + readonly viewColumn = 1; + private readonly host: ExtensionHost; + + constructor(host: ExtensionHost, document: TextDocumentModel, state: EditorStateData | null) { + this.host = host; + this.document = document; + this.selections = state && state.selections.length > 0 ? state.selections.map(toSelection) : [new Selection(0, 0, 0, 0)]; + this.visibleRanges = state ? state.visibleRanges.map(toRange) : []; + this.options = { tabSize: state?.tabSize ?? 4, insertSpaces: state?.insertSpaces ?? true }; + } + + get selection(): Selection { + return this.selections[0] as Selection; + } + set selection(value: Selection) { + this.selections = [value]; + } + + async edit(callback: (builder: EditBuilder) => void): Promise { + const builder = new EditBuilder(); + callback(builder); + if (builder.edits.length === 0) { + return true; + } + const edit = new WorkspaceEdit(); + edit.set(this.document.uri, builder.edits); + return this.host.documentsAndEditors.applyEdit(edit); + } + + async insertSnippet(snippet: SnippetString | string, location?: Position | Range | readonly (Position | Range)[]): Promise { + const value = snippet instanceof SnippetString ? snippet.value : String(snippet); + const locations = location === undefined ? undefined : Array.isArray(location) ? location : [location]; + const ranges = locations?.map((item) => rangeData(item instanceof Position ? new Range(item, item) : item as Range)); + if (this.document.uri.scheme !== 'file') { + return false; + } + const answer = await this.host.ui({ kind: 'insertSnippet', path: this.document.uri.fsPath, snippet: value, ...(ranges ? { ranges } : {}) }); + return answer === true; + } + + setDecorations(): void { + // Decorations need styles the renderer does not take from extensions yet (#260 follow-up). + } + + revealRange(range: Range): void { + if (this.document.uri.scheme === 'file') { + void this.host.ui({ kind: 'openFile', path: this.document.uri.fsPath, preview: false, line: range.start.line + 1, column: range.start.character + 1 }).catch(() => undefined); + } + } + + show(): void { + this.revealRange(this.selection); + } + + hide(): void { + // The workbench owns its tabs. + } +} + +export class DocumentsAndEditors { + readonly onDidOpenTextDocument = new EventEmitter(); + readonly onDidCloseTextDocument = new EventEmitter(); + readonly onDidChangeTextDocument = new EventEmitter(); + readonly onDidSaveTextDocument = new EventEmitter(); + readonly onDidChangeActiveTextEditor = new EventEmitter(); + readonly onDidChangeVisibleTextEditors = new EventEmitter(); + readonly onDidChangeTextEditorSelection = new EventEmitter<{ textEditor: TextEditorImpl; selections: readonly Selection[]; kind: number | undefined }>(); + readonly onDidChangeTextEditorVisibleRanges = new EventEmitter<{ textEditor: TextEditorImpl; visibleRanges: readonly Range[] }>(); + readonly onDidChangeTabs = new EventEmitter<{ opened: readonly unknown[]; closed: readonly unknown[]; changed: readonly unknown[] }>(); + readonly onDidChangeTabGroups = new EventEmitter<{ opened: readonly unknown[]; closed: readonly unknown[]; changed: readonly unknown[] }>(); + /** Uris (as strings) of the documents the editor has open. */ + private readonly editorDocuments = new Set(); + /** + * `window.tabGroups`: one group whose tabs are the editor's open + * documents (each tab has a model). Language clients use it to know which + * documents are visible (pull diagnostics). + */ + readonly tabGroups = this.createTabGroups(); + private active: TextEditorImpl | undefined; + private readonly host: ExtensionHost; + + constructor(host: ExtensionHost) { + this.host = host; + } + + private tabOf(key: string, group: unknown): Record | null { + const document = this.host.documents.get(key); + if (!document) { + return null; + } + const owner = this; + return { + label: document.uri.path.split('/').pop() ?? '', + group, + input: new TabInputText(document.uri), + get isActive() { + return owner.active?.document === document; + }, + get isDirty() { + return document.isDirty; + }, + isPinned: false, + isPreview: false, + }; + } + + private createTabGroups(): unknown { + const owner = this; + const group = { + isActive: true, + viewColumn: 1, + get tabs() { + return [...owner.editorDocuments].map((key) => owner.tabOf(key, group)).filter((tab) => tab !== null); + }, + get activeTab() { + const document = owner.active?.document; + return document ? owner.tabOf(document.uri.toString(), group) ?? undefined : undefined; + }, + }; + return { + get all() { + return [group]; + }, + activeTabGroup: group, + onDidChangeTabs: this.onDidChangeTabs.event, + onDidChangeTabGroups: this.onDidChangeTabGroups.event, + close: () => Promise.resolve(false), + }; + } + + get activeTextEditor(): TextEditorImpl | undefined { + return this.active; + } + + get visibleTextEditors(): TextEditorImpl[] { + return this.active ? [this.active] : []; + } + + /** A document the editor has open (by absolute path), if any. */ + editorDocument(file: string): TextDocumentModel | undefined { + const key = Uri.file(file).toString(); + return this.editorDocuments.has(key) ? this.host.documents.get(key) : undefined; + } + + accept(events: readonly DocumentEvent[]): void { + for (const event of events.slice(0, MAX_DOCUMENT_EVENTS)) { + try { + this.acceptOne(event); + } catch (error) { + this.host.log({ level: 'warn', extensionId: null, message: `A document event could not be applied: ${error instanceof Error ? error.message : String(error)}` }); + } + } + } + + private acceptOne(event: DocumentEvent): void { + if (event.kind === 'editor') { + this.setActiveEditor(event.editor); + return; + } + const uri = Uri.file(event.path); + const key = uri.toString(); + const document = this.host.documents.get(key); + switch (event.kind) { + case 'open': { + this.editorDocuments.add(key); + if (document && !document.isClosed) { + // An extension had read it from disk: the editor's text wins, the object stays the same. + document.setText(event.text); + document.version = event.version; + document.languageId = event.languageId; + return; + } + const opened = new TextDocumentModel(uri, event.languageId, event.version, event.text, (doc) => this.save(doc)); + this.host.documents.set(key, opened); + this.onDidOpenTextDocument.fire(opened); + this.onDidChangeTabs.fire({ opened: [this.tabOf(key, undefined)], closed: [], changed: [] }); + return; + } + case 'change': { + if (!document || !this.editorDocuments.has(key)) { + return; + } + const contentChanges = event.changes.map((change) => { + const range = document.validateRange(toRange(change.range)); + const rangeOffset = document.offsetAt(range.start); + const rangeLength = document.offsetAt(range.end) - rangeOffset; + document.applyChange(range, change.text); + return { range, rangeOffset, rangeLength, text: change.text }; + }); + document.version = event.version; + document.isDirty = true; + this.onDidChangeTextDocument.fire({ document, contentChanges, reason: undefined }); + return; + } + case 'language': { + if (document && document.languageId !== event.languageId) { + // VS Code closes and reopens a document whose language changes. + this.onDidCloseTextDocument.fire(document); + document.languageId = event.languageId; + this.onDidOpenTextDocument.fire(document); + } + return; + } + case 'save': { + if (document) { + document.isDirty = false; + this.onDidSaveTextDocument.fire(document); + } + return; + } + case 'close': { + this.editorDocuments.delete(key); + if (document) { + document.isClosed = true; + this.host.documents.delete(key); + if (this.active?.document === document) { + this.setActiveEditor(null); + } + this.onDidCloseTextDocument.fire(document); + this.onDidChangeTabs.fire({ opened: [], closed: [{ label: '', input: new TabInputText(uri) }], changed: [] }); + } + return; + } + } + } + + private setActiveEditor(state: EditorStateData | null): void { + const document = state ? this.host.documents.get(Uri.file(state.path).toString()) : undefined; + if (!state || !document) { + if (this.active) { + this.active = undefined; + this.onDidChangeActiveTextEditor.fire(undefined); + this.onDidChangeVisibleTextEditors.fire([]); + } + return; + } + if (this.active?.document === document) { + const editor = this.active; + const selections = state.selections.map(toSelection); + const selectionChanged = selections.length !== editor.selections.length || selections.some((selection, index) => { + const previous = editor.selections[index] as Selection; + return !selection.anchor.isEqual(previous.anchor) || !selection.active.isEqual(previous.active); + }); + const visibleRanges = state.visibleRanges.map(toRange); + const visibleChanged = visibleRanges.length !== editor.visibleRanges.length || visibleRanges.some((range, index) => !range.isEqual(editor.visibleRanges[index] as Range)); + editor.options = { tabSize: state.tabSize, insertSpaces: state.insertSpaces }; + if (selections.length > 0 && selectionChanged) { + editor.selections = selections; + this.onDidChangeTextEditorSelection.fire({ textEditor: editor, selections, kind: TextEditorSelectionChangeKind.Keyboard }); + } + if (visibleChanged) { + editor.visibleRanges = visibleRanges; + this.onDidChangeTextEditorVisibleRanges.fire({ textEditor: editor, visibleRanges }); + } + return; + } + this.active = new TextEditorImpl(this.host, document, state); + this.onDidChangeActiveTextEditor.fire(this.active); + this.onDidChangeVisibleTextEditors.fire([this.active]); + } + + private async save(document: TextDocumentModel): Promise { + if (!this.editorDocuments.has(document.uri.toString())) { + return false; + } + const saved = await this.host.ui({ kind: 'saveFile', path: document.uri.fsPath }); + return saved === true; + } + + /** + * `workspace.applyEdit`: file operations first (on disk, in order), then + * the text edits through the workbench. Text edits of documents only an + * extension opened (untitled, or read from disk and not in the editor) + * are applied to those documents here. + */ + async applyEdit(edit: WorkspaceEdit): Promise { + try { + for (const operation of edit.operations()) { + if (operation.kind === 'create') { + await createFile(operation.uri, operation.options); + } else if (operation.kind === 'delete') { + await deleteFile(operation.uri, operation.options); + } else if (operation.kind === 'rename' && operation.newUri) { + await renameFile(operation.uri, operation.newUri, operation.options); + } + } + } catch (error) { + this.host.log({ level: 'warn', extensionId: null, message: `workspace.applyEdit: ${error instanceof Error ? error.message : String(error)}` }); + return false; + } + const forEditor: { path: string; edits: { range: RangeData; text: string }[] }[] = []; + for (const [uri, edits] of edit.entries()) { + const local = this.host.documents.get(uri.toString()); + if (uri.scheme === 'file' && (!local || this.editorDocuments.has(uri.toString()))) { + forEditor.push({ path: uri.fsPath, edits: edits.map((item) => ({ range: rangeData(item.range), text: item.newText })) }); + } else if (local) { + applyLocally(local, edits); + } else { + return false; + } + } + if (forEditor.length === 0) { + return true; + } + const answer = await this.host.ui({ kind: 'applyEdit', edit: { edits: forEditor } }); + return answer === true; + } +} + +/** Applies edits to a document the editor does not have, last first so earlier ranges stay valid. */ +function applyLocally(document: TextDocumentModel, edits: readonly TextEdit[]): void { + const sorted = [...edits].sort((a, b) => b.range.start.compareTo(a.range.start)); + for (const edit of sorted) { + document.applyChange(edit.range, edit.newText); + } + document.version++; + document.isDirty = true; +} + +interface FileOptions { + overwrite?: boolean; + ignoreIfExists?: boolean; + ignoreIfNotExists?: boolean; + recursive?: boolean; + contents?: Uint8Array; +} + +async function exists(file: string): Promise { + return fsp.stat(file).then(() => true, () => false); +} + +async function createFile(uri: Uri, options: Readonly> = {}): Promise { + const { overwrite, ignoreIfExists, contents } = options as FileOptions; + if (uri.scheme !== 'file') { + throw new Error(`cannot create ${uri.toString()}`); + } + if (await exists(uri.fsPath)) { + if (ignoreIfExists && !overwrite) { + return; + } + if (!overwrite) { + throw new Error(`${uri.fsPath} already exists`); + } + } + await fsp.mkdir(path.dirname(uri.fsPath), { recursive: true }); + await fsp.writeFile(uri.fsPath, contents ?? new Uint8Array()); +} + +async function deleteFile(uri: Uri, options: Readonly> = {}): Promise { + const { ignoreIfNotExists, recursive } = options as FileOptions; + if (!(await exists(uri.fsPath))) { + if (ignoreIfNotExists) { + return; + } + throw new Error(`${uri.fsPath} does not exist`); + } + await fsp.rm(uri.fsPath, { recursive: recursive === true }); +} + +async function renameFile(from: Uri, to: Uri, options: Readonly> = {}): Promise { + const { overwrite, ignoreIfExists } = options as FileOptions; + if (await exists(to.fsPath)) { + if (ignoreIfExists && !overwrite) { + return; + } + if (!overwrite) { + throw new Error(`${to.fsPath} already exists`); + } + } + await fsp.mkdir(path.dirname(to.fsPath), { recursive: true }); + await fsp.rename(from.fsPath, to.fsPath); +} diff --git a/apps/ide/src/extensionHost/host.ts b/apps/ide/src/extensionHost/host.ts index 2bb8b912..5989f5f4 100644 --- a/apps/ide/src/extensionHost/host.ts +++ b/apps/ide/src/extensionHost/host.ts @@ -6,6 +6,8 @@ import { } from '../shared/extensionHostProtocol.ts'; import type { ExtensionActivation, ExtensionId } from '../shared/extensions.ts'; import { createVscodeApi } from './api.ts'; +import { DocumentsAndEditors } from './documents.ts'; +import { LanguageFeatures } from './languageFeatures.ts'; import { ConfigurationModel } from './configuration.ts'; import { FileMemento } from './memento.ts'; import type { TextDocumentModel } from './textDocument.ts'; @@ -69,6 +71,9 @@ export class ExtensionHost { readonly onDidGrantWorkspaceTrust = new EventEmitter(); readonly onDidChangeExtensions = new EventEmitter(); readonly contentProviders = new Map(); + /** #260: the editor's documents and active editor, and the extensions' language features. */ + readonly documentsAndEditors: DocumentsAndEditors; + readonly languageFeatures: LanguageFeatures; private readonly reported = new Set(); private readonly firedEvents = new Set(); private moduleHooked = false; @@ -77,6 +82,8 @@ export class ExtensionHost { constructor(rpc: RpcEndpoint) { this.rpc = rpc; + this.documentsAndEditors = new DocumentsAndEditors(this); + this.languageFeatures = new LanguageFeatures(this); this.configuration = new ConfigurationModel((key, value, target) => this.rpc.request(MAIN_METHODS.updateConfiguration, key, toWire(value), target).then(() => undefined)); } @@ -93,6 +100,11 @@ export class ExtensionHost { this.learnLanguages(json); } this.hookRequire(); + // The editor's state before any extension activates, so `*` extensions see the open files. + this.documentsAndEditors.accept([ + ...(data.documents ?? []).map((document) => ({ kind: 'open' as const, ...document })), + { kind: 'editor' as const, editor: data.activeEditor ?? null }, + ]); this.log({ level: 'info', extensionId: null, message: `Extension host started (pid ${process.pid}) with ${data.extensions.length} extension(s) with code.` }); } @@ -480,6 +492,11 @@ export class ExtensionHost { } const command = this.commands.get(id); if (!command) { + // #260: a code action or lens may run a built-in `vscode.*` command (never a workbench one: that would loop back). + const builtin = await this.builtinCommand(id, fromWire(args) as unknown[]); + if (builtin.handled) { + return toWire(builtin.result); + } throw new Error(`command '${id}' not found`); } const result: unknown = await command.callback.apply(command.thisArg, (fromWire(args) as unknown[])); diff --git a/apps/ide/src/extensionHost/index.ts b/apps/ide/src/extensionHost/index.ts index 9beaf6ae..8225f5ca 100644 --- a/apps/ide/src/extensionHost/index.ts +++ b/apps/ide/src/extensionHost/index.ts @@ -1,4 +1,5 @@ import { HOST_METHODS, RpcEndpoint, type HostInitData, type RpcMessage } from '../shared/extensionHostProtocol.ts'; +import type { DocumentEvent, ProvideRequest } from '../shared/extensionLanguageProtocol.ts'; import { ExtensionHost } from './host.ts'; /** @@ -25,6 +26,8 @@ rpc.handle(HOST_METHODS.executeCommand, (id, args) => host.executeFromWorkbench( rpc.handle(HOST_METHODS.registeredCommands, () => [...host.commands.keys()]); rpc.handle(HOST_METHODS.configurationChanged, (values) => host.configurationChanged((values ?? {}) as Record)); rpc.handle(HOST_METHODS.trustChanged, (trusted) => host.trustChanged(trusted === true)); +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.shutdown, async () => { await host.shutdown(); setTimeout(() => process.exit(0), 50); diff --git a/apps/ide/src/extensionHost/languageFeatures.ts b/apps/ide/src/extensionHost/languageFeatures.ts new file mode 100644 index 00000000..db951359 --- /dev/null +++ b/apps/ide/src/extensionHost/languageFeatures.ts @@ -0,0 +1,657 @@ +import path from 'node:path'; +import { + type CodeActionData, type CodeLensData, type CommandData, type CompletionItemData, type DiagnosticData, type DiagnosticsUpdate, type DocumentFilterData, type DocumentSymbolData, + type LocationData, type ProvideRequest, type ProviderKind, type ProviderRegistration, type RangeData, type TextChangeData, type WorkspaceEditData, +} from '../shared/extensionLanguageProtocol.ts'; +import { MAIN_METHODS } from '../shared/extensionHostProtocol.ts'; +import type { ExtensionId } from '../shared/extensions.ts'; +import { rangeData } from './documents.ts'; +import type { ExtensionHost } from './host.ts'; +import type { TextDocumentModel } from './textDocument.ts'; +import { + CancellationTokenSource, CodeActionKind, Diagnostic, DiagnosticSeverity, Disposable, EventEmitter, Location, Position, Range, SnippetString, Uri, WorkspaceEdit, +} from './types.ts'; +import { toWire } from './wire.ts'; + +/** + * The language features of extensions (#260): the providers they register + * with `vscode.languages.register*Provider` and their diagnostic + * collections, shared by every extension of the host. + * + * A registration is announced to the workbench, which registers a Monaco + * provider of the same kind that asks back through `provide` with the + * document's path and a position; the answer travels as plain data + * (extensionLanguageProtocol.ts). Lists whose items resolve later + * (completion items, code lenses) are kept for a while under a cache id. + */ + +interface ProviderEntry { + readonly kind: ProviderKind; + readonly extensionId: ExtensionId; + readonly provider: Record unknown) | undefined>; +} + +const MAX_CACHED_LISTS = 20; +const MAX_DIAGNOSTICS_PER_FILE = 1000; + +type Markdownish = string | { value?: unknown; language?: unknown } | null | undefined; + +function markdown(value: Markdownish): string { + if (typeof value === 'string') { + return value; + } + if (typeof value === 'object' && value !== null && typeof value.value === 'string') { + return typeof value.language === 'string' ? `\`\`\`${value.language}\n${value.value}\n\`\`\`` : value.value; + } + return ''; +} + +function isRange(value: unknown): value is Range { + return Range.isRange(value); +} + +function asRange(value: unknown): RangeData | undefined { + return isRange(value) ? rangeData(value as Range) : undefined; +} + +function commandData(command: unknown): CommandData | undefined { + if (typeof command !== 'object' || command === null) { + return undefined; + } + const { command: id, title, tooltip, arguments: args } = command as { command?: unknown; title?: unknown; tooltip?: unknown; arguments?: unknown }; + if (typeof id !== 'string' || id === '') { + return undefined; + } + return { + id, + title: typeof title === 'string' ? title : '', + ...(typeof tooltip === 'string' ? { tooltip } : {}), + ...(Array.isArray(args) ? { args: toWire(args) as unknown[] } : {}), + }; +} + +function textChanges(edits: unknown): TextChangeData[] { + if (!Array.isArray(edits)) { + return []; + } + const result: TextChangeData[] = []; + for (const edit of edits as { range?: unknown; newText?: unknown }[]) { + const range = asRange(edit?.range); + if (range && typeof edit.newText === 'string') { + result.push({ range, text: edit.newText }); + } + } + return result; +} + +export function workspaceEditData(edit: unknown): WorkspaceEditData | undefined { + if (!(edit instanceof WorkspaceEdit) && !(typeof edit === 'object' && edit !== null && typeof (edit as { entries?: unknown }).entries === 'function')) { + return undefined; + } + const entries = (edit as WorkspaceEdit).entries(); + return { + edits: entries.filter(([uri]) => uri.scheme === 'file').map(([uri, edits]) => ({ path: uri.fsPath, edits: textChanges(edits) })), + }; +} + +/** `Location`, `LocationLink` or a list of either, as plain data (file URIs only). */ +export function locationData(value: unknown): LocationData[] { + const list = Array.isArray(value) ? value : value ? [value] : []; + const result: LocationData[] = []; + for (const item of list as Record[]) { + if (typeof item !== 'object' || item === null) { + continue; + } + if (item['targetUri'] instanceof Uri || typeof item['targetUri'] === 'object') { + const uri = item['targetUri'] as Uri; + const range = asRange(item['targetRange']); + if (uri?.scheme === 'file' && range) { + const selection = asRange(item['targetSelectionRange']); + const origin = asRange(item['originSelectionRange']); + result.push({ path: uri.fsPath, range, ...(selection ? { targetSelectionRange: selection } : {}), ...(origin ? { originRange: origin } : {}) }); + } + continue; + } + const uri = item['uri'] as Uri | undefined; + const range = asRange(item['range']); + if (uri?.scheme === 'file' && range) { + result.push({ path: uri.fsPath, range }); + } + } + return result; +} + +export function diagnosticData(diagnostic: Diagnostic): DiagnosticData | null { + const range = asRange(diagnostic?.range); + if (!range) { + return null; + } + const code = diagnostic.code; + const codeText = typeof code === 'string' || typeof code === 'number' ? String(code) : typeof code === 'object' && code !== null ? String(code.value) : undefined; + const related = (diagnostic.relatedInformation ?? []).flatMap((info) => { + const location = info?.location; + const relatedRange = asRange(location?.range); + return location?.uri?.scheme === 'file' && relatedRange ? [{ path: location.uri.fsPath, range: relatedRange, message: String(info.message) }] : []; + }); + return { + range, + message: typeof diagnostic.message === 'string' ? diagnostic.message : String(diagnostic.message), + severity: typeof diagnostic.severity === 'number' ? diagnostic.severity : DiagnosticSeverity.Error, + ...(diagnostic.source ? { source: String(diagnostic.source) } : {}), + ...(codeText !== undefined ? { code: codeText } : {}), + ...(diagnostic.tags && diagnostic.tags.length > 0 ? { tags: [...diagnostic.tags] } : {}), + ...(related.length > 0 ? { relatedInformation: related } : {}), + }; +} + +function fromDiagnosticData(data: DiagnosticData): Diagnostic { + const diagnostic = new Diagnostic(new Range(data.range[0], data.range[1], data.range[2], data.range[3]), data.message, data.severity as DiagnosticSeverity); + if (data.source) { + diagnostic.source = data.source; + } + if (data.code !== undefined) { + diagnostic.code = data.code; + } + return diagnostic; +} + +export function completionItemData(item: Record): CompletionItemData { + const label = item['label']; + const insert = item['insertText']; + const range = item['range']; + const command = commandData(item['command']); + const documentation = markdown(item['documentation'] as Markdownish); + let rangeValue: CompletionItemData['range']; + if (isRange(range)) { + rangeValue = rangeData(range); + } else if (typeof range === 'object' && range !== null && isRange((range as { inserting?: unknown }).inserting) && isRange((range as { replacing?: unknown }).replacing)) { + rangeValue = { inserting: rangeData((range as { inserting: Range }).inserting), replacing: rangeData((range as { replacing: Range }).replacing) }; + } + const additional = textChanges(item['additionalTextEdits']); + const labelValue = typeof label === 'string' ? label : typeof label === 'object' && label !== null + ? { + label: String((label as { label?: unknown }).label ?? ''), + ...(typeof (label as { detail?: unknown }).detail === 'string' ? { detail: (label as { detail: string }).detail } : {}), + ...(typeof (label as { description?: unknown }).description === 'string' ? { description: (label as { description: string }).description } : {}), + } + : String(label); + return { + label: labelValue, + ...(typeof item['kind'] === 'number' ? { kind: item['kind'] } : {}), + ...(Array.isArray(item['tags']) && item['tags'].length > 0 ? { tags: (item['tags'] as unknown[]).filter((tag): tag is number => typeof tag === 'number') } : {}), + ...(typeof item['detail'] === 'string' ? { detail: item['detail'] } : {}), + ...(documentation ? { documentation } : {}), + ...(typeof item['sortText'] === 'string' ? { sortText: item['sortText'] } : {}), + ...(typeof item['filterText'] === 'string' ? { filterText: item['filterText'] } : {}), + ...(item['preselect'] === true ? { preselect: true } : {}), + ...(insert instanceof SnippetString ? { insertText: insert.value, isSnippet: true } : typeof insert === 'string' ? { insertText: insert } : {}), + ...(rangeValue ? { range: rangeValue } : {}), + ...(Array.isArray(item['commitCharacters']) ? { commitCharacters: (item['commitCharacters'] as unknown[]).map(String) } : {}), + ...(additional.length > 0 ? { additionalTextEdits: additional } : {}), + ...(command ? { command } : {}), + }; +} + +function symbolData(items: unknown): DocumentSymbolData[] { + if (!Array.isArray(items)) { + return []; + } + return (items as Record[]).flatMap((item): DocumentSymbolData[] => { + if (typeof item !== 'object' || item === null) { + return []; + } + const tags = Array.isArray(item['tags']) && item['tags'].length > 0 ? { tags: item['tags'] as number[] } : {}; + if (item['location'] instanceof Location || (typeof item['location'] === 'object' && item['location'] !== null)) { + // SymbolInformation: flat, with a container name. + const range = asRange((item['location'] as Location).range); + return range ? [{ name: String(item['name']), detail: '', kind: Number(item['kind'] ?? 0), range, selectionRange: range, children: [], ...(typeof item['containerName'] === 'string' && item['containerName'] ? { containerName: item['containerName'] } : {}), ...tags }] : []; + } + const range = asRange(item['range']); + const selectionRange = asRange(item['selectionRange']) ?? range; + return range && selectionRange ? [{ name: String(item['name']), detail: typeof item['detail'] === 'string' ? item['detail'] : '', kind: Number(item['kind'] ?? 0), range, selectionRange, children: symbolData(item['children']), ...tags }] : []; + }); +} + +function codeActionData(item: Record): CodeActionData | null { + if (typeof item !== 'object' || item === null || typeof item['title'] !== 'string') { + return null; + } + if (typeof item['command'] === 'string') { + // A bare Command. + const command = commandData(item); + return command ? { title: item['title'], command } : null; + } + const kind = item['kind'] instanceof CodeActionKind ? item['kind'].value : typeof (item['kind'] as { value?: unknown } | undefined)?.value === 'string' ? (item['kind'] as { value: string }).value : undefined; + const edit = workspaceEditData(item['edit']); + const command = commandData(item['command']); + const diagnostics = Array.isArray(item['diagnostics']) ? (item['diagnostics'] as Diagnostic[]).map(diagnosticData).filter((d): d is DiagnosticData => d !== null) : []; + const disabled = item['disabled'] as { reason?: unknown } | undefined; + return { + title: item['title'], + ...(kind !== undefined ? { kind } : {}), + ...(item['isPreferred'] === true ? { isPreferred: true } : {}), + ...(diagnostics.length > 0 ? { diagnostics } : {}), + ...(edit ? { edit } : {}), + ...(command ? { command } : {}), + ...(disabled && typeof disabled.reason === 'string' ? { disabled: disabled.reason } : {}), + }; +} + +function lensData(lens: Record): CodeLensData | null { + const range = asRange(lens?.['range']); + if (!range) { + return null; + } + const command = commandData(lens['command']); + return { range, ...(command ? { command } : {}) }; +} + +/** A `DocumentSelector` as plain filters (patterns become globs over the workspace path). */ +export function selectorData(selector: unknown, rawRoot: string | null): DocumentFilterData[] { + // Compared in `Uri.fsPath`'s spelling (a lower-case drive letter on Windows), the one of the bases. + const workspaceRoot = rawRoot ? Uri.file(rawRoot).fsPath : null; + const list = Array.isArray(selector) ? selector as unknown[] : [selector]; + const result: DocumentFilterData[] = []; + for (const item of list) { + if (typeof item === 'string') { + result.push({ language: item }); + continue; + } + if (typeof item !== 'object' || item === null) { + continue; + } + const filter = item as { language?: unknown; scheme?: unknown; pattern?: unknown; notebookType?: unknown }; + if (filter.notebookType !== undefined) { + continue; // Notebooks are not supported: the filter matches nothing. + } + let pattern: string | undefined; + if (typeof filter.pattern === 'string') { + pattern = filter.pattern.split(path.sep).join('/'); + } else if (typeof filter.pattern === 'object' && filter.pattern !== null) { + const relative = filter.pattern as { baseUri?: Uri; base?: string; pattern?: unknown }; + const base = relative.baseUri?.fsPath ?? relative.base; + const glob = typeof relative.pattern === 'string' ? relative.pattern : '**'; + if (base && workspaceRoot && (base === workspaceRoot || base.startsWith(workspaceRoot + path.sep))) { + const prefix = path.relative(workspaceRoot, base).split(path.sep).join('/'); + pattern = prefix ? `${prefix}/${glob}` : glob; + } else { + continue; // A base outside the folder matches none of its files. + } + } + const data: DocumentFilterData = { + ...(typeof filter.language === 'string' ? { language: filter.language } : {}), + ...(typeof filter.scheme === 'string' ? { scheme: filter.scheme } : {}), + ...(pattern !== undefined ? { pattern } : {}), + }; + if (Object.keys(data).length > 0) { + result.push(data); + } + } + return result; +} + +interface CollectionState { + readonly owner: string; + readonly entries: Map; + pending: Set; + cleared: boolean; + scheduled: boolean; +} + +export class LanguageFeatures { + readonly onDidChangeDiagnostics = new EventEmitter<{ readonly uris: readonly Uri[] }>(); + private readonly host: ExtensionHost; + private readonly providers = new Map(); + private readonly caches = new Map(); + private readonly collections = new Set(); + private readonly owners = new Set(); + private nextHandle = 1; + private nextCache = 1; + + constructor(host: ExtensionHost) { + this.host = host; + } + + /* ------------------------------ providers ------------------------------ */ + + register(extensionId: ExtensionId, kind: ProviderKind, selector: unknown, provider: unknown, extra: Omit, 'handle' | 'kind' | 'extensionId' | 'selector'> = {}): Disposable { + if (typeof provider !== 'object' || provider === null) { + throw new Error(`Invalid ${kind} provider`); + } + const handle = this.nextHandle++; + this.providers.set(handle, { kind, extensionId, provider: provider as ProviderEntry['provider'] }); + const registration: ProviderRegistration = { handle, kind, extensionId, selector: selectorData(selector, this.host.data.workspaceFolder ? Uri.file(this.host.data.workspaceFolder).fsPath : null), ...extra }; + this.host.rpc.notify(MAIN_METHODS.registerProvider, registration); + return new Disposable(() => { + if (this.providers.delete(handle)) { + this.host.rpc.notify(MAIN_METHODS.unregisterProvider, handle); + } + }); + } + + private cache(items: unknown[]): number { + const id = this.nextCache++; + this.caches.set(id, items); + if (this.caches.size > MAX_CACHED_LISTS) { + const oldest = this.caches.keys().next().value; + if (oldest !== undefined) { + this.caches.delete(oldest); + } + } + return id; + } + + private document(file: string): TextDocumentModel | undefined { + return this.host.documentsAndEditors.editorDocument(file) ?? this.host.documents.get(Uri.file(file).toString()); + } + + async provide(request: ProvideRequest): Promise { + const entry = this.providers.get(request.handle); + if (!entry) { + return null; + } + const { provider } = entry; + const call = async (method: string, ...args: unknown[]): Promise => { + const fn = provider[method]; + return typeof fn === 'function' ? fn.apply(provider, args) : undefined; + }; + const token = new CancellationTokenSource().token; + const { args } = request; + const cached = (): unknown => (args.cacheId !== undefined && args.index !== undefined ? this.caches.get(args.cacheId)?.[args.index] : undefined); + if (request.kind === 'resolveCompletion') { + const item = cached(); + if (!item) { + return null; + } + const resolved = (await call('resolveCompletionItem', item, token)) ?? item; + return completionItemData(resolved as Record); + } + if (request.kind === 'resolveCodeLens') { + const lens = cached(); + if (!lens) { + return null; + } + const resolved = (await call('resolveCodeLens', lens, token)) ?? lens; + return lensData(resolved as Record); + } + const document = this.document(request.path); + if (!document) { + return null; + } + const position = args.position ? new Position(args.position[0], args.position[1]) : new Position(0, 0); + const range = args.range ? new Range(args.range[0], args.range[1], args.range[2], args.range[3]) : new Range(0, 0, 0, 0); + const options = { tabSize: args.options?.tabSize ?? 4, insertSpaces: args.options?.insertSpaces ?? true }; + switch (request.kind) { + case 'hover': { + const hover = await call('provideHover', document, position, token) as { contents?: unknown; range?: unknown } | null | undefined; + if (!hover) { + return null; + } + const contents = (Array.isArray(hover.contents) ? hover.contents : [hover.contents]).map((item) => markdown(item as Markdownish)).filter((text) => text !== ''); + const hoverRange = asRange(hover.range); + return contents.length > 0 ? { contents, ...(hoverRange ? { range: hoverRange } : {}) } : null; + } + case 'completion': { + const result = await call('provideCompletionItems', document, position, token, { triggerKind: args.triggerKind ?? 0, triggerCharacter: args.triggerCharacter }); + const items = (Array.isArray(result) ? result : (result as { items?: unknown } | null)?.items ?? []) as Record[]; + const incomplete = !Array.isArray(result) && (result as { isIncomplete?: unknown } | null)?.isIncomplete === true; + const resolves = typeof provider['resolveCompletionItem'] === 'function'; + return { items: items.filter((item) => typeof item === 'object' && item !== null).map(completionItemData), incomplete, ...(resolves ? { cacheId: this.cache(items) } : {}) }; + } + case 'definition': + return locationData(await call('provideDefinition', document, position, token)); + case 'declaration': + return locationData(await call('provideDeclaration', document, position, token)); + case 'typeDefinition': + return locationData(await call('provideTypeDefinition', document, position, token)); + case 'implementation': + return locationData(await call('provideImplementation', document, position, token)); + case 'references': + return locationData(await call('provideReferences', document, position, { includeDeclaration: args.includeDeclaration !== false }, token)); + case 'documentSymbol': + return symbolData(await call('provideDocumentSymbols', document, token)); + case 'documentHighlight': { + const highlights = await call('provideDocumentHighlights', document, position, token); + return Array.isArray(highlights) ? highlights.flatMap((item: { range?: unknown; kind?: unknown }) => { + const highlightRange = asRange(item?.range); + return highlightRange ? [{ range: highlightRange, kind: typeof item.kind === 'number' ? item.kind : 0 }] : []; + }) : []; + } + case 'signatureHelp': { + const help = await call('provideSignatureHelp', document, position, token, { + triggerKind: args.triggerKind ?? 1, triggerCharacter: args.triggerCharacter, isRetrigger: args.isRetrigger === true, activeSignatureHelp: undefined, + }) as { signatures?: unknown; activeSignature?: unknown; activeParameter?: unknown } | null | undefined; + if (!help || !Array.isArray(help.signatures)) { + return null; + } + return { + signatures: (help.signatures as Record[]).map((signature) => ({ + label: String(signature['label'] ?? ''), + ...(markdown(signature['documentation'] as Markdownish) ? { documentation: markdown(signature['documentation'] as Markdownish) } : {}), + parameters: (Array.isArray(signature['parameters']) ? signature['parameters'] as Record[] : []).map((parameter) => ({ + label: Array.isArray(parameter['label']) ? [Number(parameter['label'][0]), Number(parameter['label'][1])] as const : String(parameter['label'] ?? ''), + ...(markdown(parameter['documentation'] as Markdownish) ? { documentation: markdown(parameter['documentation'] as Markdownish) } : {}), + })), + ...(typeof signature['activeParameter'] === 'number' ? { activeParameter: signature['activeParameter'] } : {}), + })), + activeSignature: typeof help.activeSignature === 'number' ? help.activeSignature : 0, + activeParameter: typeof help.activeParameter === 'number' ? help.activeParameter : 0, + }; + } + case 'formatting': + return textChanges(await call('provideDocumentFormattingEdits', document, options, token)); + case 'rangeFormatting': + return textChanges(await call('provideDocumentRangeFormattingEdits', document, range, options, token)); + case 'onTypeFormatting': + return textChanges(await call('provideOnTypeFormattingEdits', document, position, args.triggerCharacter ?? '', options, token)); + case 'codeAction': { + const diagnostics = (args.diagnostics ?? []).map(fromDiagnosticData); + const actions = await call('provideCodeActions', document, range, { + diagnostics, only: args.only ? new CodeActionKind(args.only) : undefined, triggerKind: args.triggerKind ?? 1, + }, token); + return Array.isArray(actions) ? (actions as Record[]).map(codeActionData).filter((action): action is CodeActionData => action !== null) : []; + } + case 'codeLens': { + const lenses = await call('provideCodeLenses', document, token); + if (!Array.isArray(lenses)) { + return { lenses: [] }; + } + const resolves = typeof provider['resolveCodeLens'] === 'function'; + return { lenses: (lenses as Record[]).map(lensData).map((lens) => lens ?? { range: [0, 0, 0, 0] }), ...(resolves ? { cacheId: this.cache(lenses) } : {}) }; + } + case 'prepareRename': { + if (typeof provider['prepareRename'] !== 'function') { + const word = document.getWordRangeAtPosition(position); + return word ? { range: rangeData(word), text: document.getText(word) } : null; + } + const prepared = await call('prepareRename', document, position, token) as Range | { range?: unknown; placeholder?: unknown } | null | undefined; + if (!prepared) { + return null; + } + if (isRange(prepared)) { + return { range: rangeData(prepared), text: document.getText(prepared) }; + } + const preparedRange = asRange(prepared.range); + return preparedRange ? { range: preparedRange, text: String(prepared.placeholder ?? '') } : null; + } + case 'rename': + return workspaceEditData(await call('provideRenameEdits', document, position, args.newName ?? '', token)) ?? null; + case 'foldingRange': { + const ranges = await call('provideFoldingRanges', document, {}, token); + return Array.isArray(ranges) ? ranges.flatMap((item: { start?: unknown; end?: unknown; kind?: unknown }) => (typeof item?.start === 'number' && typeof item.end === 'number' ? [{ start: item.start, end: item.end, ...(typeof item.kind === 'number' ? { kind: item.kind } : {}) }] : [])) : []; + } + case 'inlayHints': { + const hints = await call('provideInlayHints', document, range, token); + return Array.isArray(hints) ? hints.flatMap((hint: { position?: unknown; label?: unknown; kind?: unknown; tooltip?: unknown; paddingLeft?: unknown; paddingRight?: unknown }) => { + if (!(hint?.position instanceof Position)) { + return []; + } + const label = typeof hint.label === 'string' ? hint.label : Array.isArray(hint.label) ? hint.label.map((part: { value?: unknown }) => String(part?.value ?? '')).join('') : ''; + const tooltip = markdown(hint.tooltip as Markdownish); + return [{ + position: [hint.position.line, hint.position.character] as const, label, + ...(typeof hint.kind === 'number' ? { kind: hint.kind } : {}), + ...(tooltip ? { tooltip } : {}), + ...(hint.paddingLeft === true ? { paddingLeft: true } : {}), + ...(hint.paddingRight === true ? { paddingRight: true } : {}), + }]; + }) : []; + } + case 'documentLink': { + const links = await call('provideDocumentLinks', document, token); + return Array.isArray(links) ? links.flatMap((link: { range?: unknown; target?: unknown; tooltip?: unknown }) => { + const linkRange = asRange(link?.range); + const target = link?.target as Uri | undefined; + const url = target && ['http', 'https', 'mailto'].includes(target.scheme) ? target.toString(true) : undefined; + return linkRange && url ? [{ range: linkRange, url, ...(typeof link.tooltip === 'string' ? { tooltip: link.tooltip } : {}) }] : []; + }) : []; + } + } + return null; + } + + /* ------------------------------ diagnostics ------------------------------ */ + + createDiagnosticCollection(extensionId: ExtensionId, name: string): unknown { + let owner = `${extensionId}:${name}`; + for (let index = 2; this.owners.has(owner); index++) { + owner = `${extensionId}:${name}#${index}`; + } + this.owners.add(owner); + const state: CollectionState = { owner, entries: new Map(), pending: new Set(), cleared: false, scheduled: false }; + this.collections.add(state); + const changed = (keys: readonly string[], cleared = false): void => { + if (cleared) { + state.cleared = true; + state.pending.clear(); + } + for (const key of keys) { + state.pending.add(key); + } + this.schedule(state); + }; + let disposed = false; + const collection = { + name, + set: (uriOrEntries: Uri | readonly [Uri, readonly Diagnostic[] | undefined][], diagnostics?: readonly Diagnostic[]): void => { + if (disposed) { + return; + } + if (Array.isArray(uriOrEntries)) { + // Entries for the same file add up, as in VS Code; an undefined list clears what came before it. + const merged = new Map(); + for (const [uri, list] of uriOrEntries as [Uri, readonly Diagnostic[] | undefined][]) { + const key = uri.toString(); + if (!list) { + merged.set(key, [uri, []]); + } else { + const bucket = merged.get(key) ?? [uri, []]; + bucket[1].push(...list); + merged.set(key, bucket); + } + } + for (const [key, [uri, list]] of merged) { + this.setEntry(state, key, uri, list); + } + changed([...merged.keys()]); + return; + } + const uri = uriOrEntries as Uri; + this.setEntry(state, uri.toString(), uri, diagnostics ? [...diagnostics] : []); + changed([uri.toString()]); + }, + delete: (uri: Uri): void => { + if (state.entries.delete(uri.toString())) { + changed([uri.toString()]); + } + }, + clear: (): void => { + const keys = [...state.entries.keys()]; + state.entries.clear(); + changed(keys, true); + }, + forEach: (callback: (uri: Uri, diagnostics: readonly Diagnostic[], collection: unknown) => void, thisArg?: unknown): void => { + for (const [uri, list] of [...state.entries.values()]) { + callback.call(thisArg, uri, list, collection); + } + }, + get: (uri: Uri): readonly Diagnostic[] | undefined => { + const list = state.entries.get(uri.toString())?.[1]; + return list ? Object.freeze([...list]) : undefined; + }, + has: (uri: Uri): boolean => state.entries.has(uri.toString()), + dispose: (): void => { + if (!disposed) { + collection.clear(); + disposed = true; + this.owners.delete(owner); + this.collections.delete(state); + } + }, + [Symbol.iterator]: function* iterate(): Generator<[Uri, readonly Diagnostic[]]> { + yield* [...state.entries.values()]; + }, + }; + return collection; + } + + private setEntry(state: CollectionState, key: string, uri: Uri, list: Diagnostic[]): void { + if (list.length === 0) { + state.entries.delete(key); + } else { + state.entries.set(key, [uri, list.slice(0, MAX_DIAGNOSTICS_PER_FILE)]); + } + } + + private schedule(state: CollectionState): void { + if (state.scheduled) { + return; + } + state.scheduled = true; + // Many `set` calls in one turn (a linter going over a folder) go out as one update. + setTimeout(() => this.flush(state), 0); + } + + private flush(state: CollectionState): void { + state.scheduled = false; + const keys = [...state.pending]; + const clear = state.cleared; + state.pending.clear(); + state.cleared = false; + const uris: Uri[] = []; + const entries: { path: string; diagnostics: DiagnosticData[] }[] = []; + for (const key of keys) { + const uri = Uri.parse(key); + uris.push(uri); + if (uri.scheme !== 'file') { + continue; + } + const list = state.entries.get(key)?.[1] ?? []; + entries.push({ path: uri.fsPath, diagnostics: list.map(diagnosticData).filter((item): item is DiagnosticData => item !== null) }); + } + if (entries.length > 0 || clear) { + const update: DiagnosticsUpdate = { owner: state.owner, entries, ...(clear ? { clear: true } : {}) }; + this.host.rpc.notify(MAIN_METHODS.diagnostics, update); + } + if (uris.length > 0) { + this.onDidChangeDiagnostics.fire({ uris }); + } + } + + /** `languages.getDiagnostics`: every collection's, for one file or all. */ + getDiagnostics(uri?: Uri): unknown { + if (uri) { + const key = uri.toString(); + return [...this.collections].flatMap((state) => state.entries.get(key)?.[1] ?? []); + } + const byFile = new Map(); + for (const state of this.collections) { + for (const [key, [entryUri, list]] of state.entries) { + const bucket = byFile.get(key) ?? [entryUri, []]; + bucket[1].push(...list); + byFile.set(key, bucket); + } + } + return [...byFile.values()]; + } +} diff --git a/apps/ide/src/extensionHost/types.ts b/apps/ide/src/extensionHost/types.ts index 28002880..9d4a9006 100644 --- a/apps/ide/src/extensionHost/types.ts +++ b/apps/ide/src/extensionHost/types.ts @@ -792,12 +792,12 @@ export class ColorPresentation { export class InlayHint { position: Position; - label: string; + label: string | InlayHintLabelPart[]; kind?: InlayHintKind; tooltip?: string | MarkdownString; paddingLeft?: boolean; paddingRight?: boolean; - constructor(position: Position, label: string, kind?: InlayHintKind) { + constructor(position: Position, label: string | InlayHintLabelPart[], kind?: InlayHintKind) { this.position = position; this.label = label; if (kind !== undefined) { @@ -819,6 +819,201 @@ export class SelectionRange { } } +/* ------- hierarchies, inline values and completions: the classes vscode-languageclient extends at load ------- */ + +export class CallHierarchyItem { + kind: SymbolKind; + name: string; + detail?: string; + uri: Uri; + range: Range; + selectionRange: Range; + tags?: SymbolTag[]; + constructor(kind: SymbolKind, name: string, detail: string, uriValue: Uri, range: Range, selectionRange: Range) { + this.kind = kind; + this.name = name; + this.detail = detail; + this.uri = uriValue; + this.range = range; + this.selectionRange = selectionRange; + } +} +export class CallHierarchyIncomingCall { + from: CallHierarchyItem; + fromRanges: Range[]; + constructor(from: CallHierarchyItem, fromRanges: Range[]) { + this.from = from; + this.fromRanges = fromRanges; + } +} +export class CallHierarchyOutgoingCall { + to: CallHierarchyItem; + fromRanges: Range[]; + constructor(to: CallHierarchyItem, fromRanges: Range[]) { + this.to = to; + this.fromRanges = fromRanges; + } +} +export class TypeHierarchyItem { + kind: SymbolKind; + name: string; + detail?: string; + uri: Uri; + range: Range; + selectionRange: Range; + tags?: SymbolTag[]; + constructor(kind: SymbolKind, name: string, detail: string, uriValue: Uri, range: Range, selectionRange: Range) { + this.kind = kind; + this.name = name; + this.detail = detail; + this.uri = uriValue; + this.range = range; + this.selectionRange = selectionRange; + } +} +export class InlayHintLabelPart { + value: string; + tooltip?: string | MarkdownString; + location?: Location; + command?: Command; + constructor(value: string) { + this.value = value; + } +} +export class InlineCompletionItem { + insertText: string | SnippetString; + filterText?: string; + range?: Range; + command?: Command; + constructor(insertText: string | SnippetString, range?: Range, command?: Command) { + this.insertText = insertText; + if (range) { + this.range = range; + } + if (command) { + this.command = command; + } + } +} +export class InlineCompletionList { + items: InlineCompletionItem[]; + constructor(items: InlineCompletionItem[]) { + this.items = items; + } +} +export class InlineValueText { + readonly range: Range; + readonly text: string; + constructor(range: Range, text: string) { + this.range = range; + this.text = text; + } +} +export class InlineValueVariableLookup { + readonly range: Range; + readonly variableName?: string; + readonly caseSensitiveLookup: boolean; + constructor(range: Range, variableName?: string, caseSensitiveLookup = true) { + this.range = range; + if (variableName !== undefined) { + this.variableName = variableName; + } + this.caseSensitiveLookup = caseSensitiveLookup; + } +} +export class InlineValueEvaluatableExpression { + readonly range: Range; + readonly expression?: string; + constructor(range: Range, expression?: string) { + this.range = range; + if (expression !== undefined) { + this.expression = expression; + } + } +} +export class EvaluatableExpression { + readonly range: Range; + readonly expression?: string; + constructor(range: Range, expression?: string) { + this.range = range; + if (expression !== undefined) { + this.expression = expression; + } + } +} +export class LinkedEditingRanges { + readonly ranges: Range[]; + readonly wordPattern?: RegExp; + constructor(ranges: Range[], wordPattern?: RegExp) { + this.ranges = ranges; + if (wordPattern) { + this.wordPattern = wordPattern; + } + } +} +export class SemanticTokensEdit { + readonly start: number; + readonly deleteCount: number; + readonly data?: Uint32Array; + constructor(start: number, deleteCount: number, data?: Uint32Array) { + this.start = start; + this.deleteCount = deleteCount; + if (data) { + this.data = data; + } + } +} +export class SemanticTokensEdits { + readonly resultId?: string; + readonly edits: SemanticTokensEdit[]; + constructor(edits: SemanticTokensEdit[], resultId?: string) { + this.edits = edits; + if (resultId !== undefined) { + this.resultId = resultId; + } + } +} + +/* ------------------------------ tabs (window.tabGroups) ------------------------------ */ + +export class TabInputText { + readonly uri: Uri; + constructor(uriValue: Uri) { + this.uri = uriValue; + } +} +export class TabInputTextDiff { + readonly original: Uri; + readonly modified: Uri; + constructor(original: Uri, modified: Uri) { + this.original = original; + this.modified = modified; + } +} +export class TabInputCustom { + readonly uri: Uri; + readonly viewType: string; + constructor(uriValue: Uri, viewType: string) { + this.uri = uriValue; + this.viewType = viewType; + } +} +export class TabInputWebview { + readonly viewType: string; + constructor(viewType: string) { + this.viewType = viewType; + } +} +export class TabInputNotebook { + readonly uri: Uri; + readonly notebookType: string; + constructor(uriValue: Uri, notebookType: string) { + this.uri = uriValue; + this.notebookType = notebookType; + } +} +export class TabInputTerminal {} + export class SemanticTokensLegend { readonly tokenTypes: string[]; readonly tokenModifiers: string[]; diff --git a/apps/ide/src/main/extensions/documentMirror.ts b/apps/ide/src/main/extensions/documentMirror.ts new file mode 100644 index 00000000..c20d9066 --- /dev/null +++ b/apps/ide/src/main/extensions/documentMirror.ts @@ -0,0 +1,226 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { + MAX_DOCUMENT_EVENTS, MAX_SYNCED_DOCUMENT_LENGTH, rewritePaths, type DocumentEvent, type EditorStateData, type PositionData, type RangeData, type SelectionData, type TextChangeData, +} from '../../shared/extensionLanguageProtocol.ts'; +import { TextDocumentModel } from '../../extensionHost/textDocument.ts'; +import { Range, Uri } from '../../extensionHost/types.ts'; +import { isInside, parseWorkspacePath } from '../workspace/workspacePath.ts'; + +/** + * The main process's copy of a window's editor documents (#260). The + * renderer reports every change of the files it has open; this checks each + * event (the renderer is untrusted: paths go through the workspace path + * rules), keeps the text, and hands the events on with absolute paths. A host + * that starts later gets the documents from here, so `*` extensions see the + * open files before the renderer could say anything. + */ + +const MAX_LANGUAGE_ID = 128; +const MAX_CHANGES_PER_EVENT = 10_000; +const MAX_SELECTIONS = 1000; + +const isCount = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 0x7fffffff; + +function position(value: unknown): PositionData { + if (!Array.isArray(value) || value.length !== 2 || !value.every(isCount)) { + throw new Error('Invalid position.'); + } + return [value[0] as number, value[1] as number]; +} + +function range(value: unknown): RangeData { + if (!Array.isArray(value) || value.length !== 4 || !value.every(isCount)) { + throw new Error('Invalid range.'); + } + return [value[0] as number, value[1] as number, value[2] as number, value[3] as number]; +} + +function languageId(value: unknown): string { + if (typeof value !== 'string' || value === '' || value.length > MAX_LANGUAGE_ID) { + throw new Error('Invalid language id.'); + } + return value; +} + +/** Converts between the renderer's workspace paths and absolute paths of one folder. */ +export class FolderPaths { + readonly root: string; + private readonly realRoot: string; + + constructor(root: string) { + this.root = root; + let real = root; + try { + real = fs.realpathSync(root); + } catch { + // The folder went away: only its own spelling matches. + } + this.realRoot = real; + } + + /** The absolute path of a workspace path from the renderer; throws on anything else. */ + toAbsolute(workspacePath: unknown): string { + const segments = parseWorkspacePath(workspacePath); + if (segments.length === 0) { + throw new Error('The folder itself is not a document.'); + } + return path.join(this.root, ...segments); + } + + /** The workspace path of an absolute path, or null when it is outside the folder. */ + toWorkspace(absolute: string): string | null { + for (const root of this.root === this.realRoot ? [this.root] : [this.root, this.realRoot]) { + if (isInside(root, absolute)) { + const relative = path.relative(root, absolute); + return relative === '' ? null : relative.split(path.sep).join('/'); + } + } + return null; + } + + /** `rewritePaths` towards the renderer. */ + outward(value: unknown): unknown { + return rewritePaths(value, (absolute) => (path.isAbsolute(absolute) ? this.toWorkspace(absolute) : null)); + } + + /** `rewritePaths` towards the host. */ + inward(value: unknown): unknown { + return rewritePaths(value, (workspacePath) => { + try { + return this.toAbsolute(workspacePath); + } catch { + return null; + } + }); + } +} + +export class DocumentMirror { + private readonly documents = new Map(); + private editor: EditorStateData | null = null; + + /** Drops everything (the folder changed: the editor closes every tab). */ + reset(): void { + this.documents.clear(); + this.editor = null; + } + + /** + * Checks and applies the renderer's events; returns them with absolute + * paths for the host. An invalid event is dropped (and so is a change to + * a document that was never opened). + */ + accept(raw: unknown, paths: FolderPaths): DocumentEvent[] { + if (!Array.isArray(raw)) { + return []; + } + const accepted: DocumentEvent[] = []; + for (const item of raw.slice(0, MAX_DOCUMENT_EVENTS)) { + try { + const event = this.acceptOne(item, paths); + if (event) { + accepted.push(event); + } + } catch { + // The renderer sent something it should not have: ignore that event. + } + } + return accepted; + } + + private acceptOne(item: unknown, paths: FolderPaths): DocumentEvent | null { + if (typeof item !== 'object' || item === null) { + return null; + } + const event = item as Record; + if (event['kind'] === 'editor') { + this.editor = this.editorState(event['editor']); + return { kind: 'editor', editor: this.editor ? { ...this.editor, path: paths.toAbsolute(this.editor.path) } : null }; + } + const workspacePath = parseWorkspacePath(event['path']).join('/'); + const absolute = paths.toAbsolute(workspacePath); + const document = this.documents.get(workspacePath); + switch (event['kind']) { + case 'open': { + const text = event['text']; + if (typeof text !== 'string' || text.length > MAX_SYNCED_DOCUMENT_LENGTH || !isCount(event['version'])) { + return null; + } + const opened = new TextDocumentModel(Uri.file(absolute), languageId(event['languageId']), event['version'], text); + this.documents.set(workspacePath, opened); + return { kind: 'open', path: absolute, languageId: opened.languageId, version: opened.version, text }; + } + case 'change': { + const changes = event['changes']; + if (!document || !Array.isArray(changes) || changes.length > MAX_CHANGES_PER_EVENT || !isCount(event['version'])) { + return null; + } + const checked: TextChangeData[] = changes.map((change: unknown) => { + const { range: changeRange, text } = (change ?? {}) as { range?: unknown; text?: unknown }; + if (typeof text !== 'string') { + throw new Error('Invalid change.'); + } + return { range: range(changeRange), text }; + }); + for (const change of checked) { + const [startLine, startCharacter, endLine, endCharacter] = change.range; + document.applyChange(new Range(startLine, startCharacter, endLine, endCharacter), change.text); + } + if (document.getText().length > MAX_SYNCED_DOCUMENT_LENGTH) { + // Grew past the limit: the host stops following it. + this.documents.delete(workspacePath); + return { kind: 'close', path: absolute }; + } + document.version = event['version']; + return { kind: 'change', path: absolute, version: document.version, changes: checked }; + } + case 'language': { + if (!document) { + return null; + } + document.languageId = languageId(event['languageId']); + return { kind: 'language', path: absolute, languageId: document.languageId }; + } + case 'save': + return document ? { kind: 'save', path: absolute } : null; + case 'close': + if (!document) { + return null; + } + this.documents.delete(workspacePath); + if (this.editor?.path === workspacePath) { + this.editor = null; + } + return { kind: 'close', path: absolute }; + default: + return null; + } + } + + private editorState(value: unknown): EditorStateData | null { + if (value === null || typeof value !== 'object') { + return null; + } + const state = value as Record; + const workspacePath = parseWorkspacePath(state['path']).join('/'); + if (!this.documents.has(workspacePath)) { + return null; + } + const selections = Array.isArray(state['selections']) ? state['selections'].slice(0, MAX_SELECTIONS).map((selection: unknown): SelectionData => { + const { anchor, active } = (selection ?? {}) as { anchor?: unknown; active?: unknown }; + return { anchor: position(anchor), active: position(active) }; + }) : []; + const visibleRanges = Array.isArray(state['visibleRanges']) ? state['visibleRanges'].slice(0, MAX_SELECTIONS).map(range) : []; + const tabSize = isCount(state['tabSize']) && state['tabSize'] > 0 && state['tabSize'] <= 64 ? state['tabSize'] : 4; + return { path: workspacePath, selections, visibleRanges, tabSize, insertSpaces: state['insertSpaces'] !== false }; + } + + /** The documents and the active editor with absolute paths, for a host that starts now. */ + snapshot(paths: FolderPaths): { documents: { path: string; languageId: string; version: number; text: string }[]; activeEditor: EditorStateData | null } { + const documents = [...this.documents.entries()].map(([workspacePath, document]) => ({ + path: paths.toAbsolute(workspacePath), languageId: document.languageId, version: document.version, text: document.getText(), + })); + return { documents, activeEditor: this.editor ? { ...this.editor, path: paths.toAbsolute(this.editor.path) } : null }; + } +} diff --git a/apps/ide/src/main/extensions/extensionHostManager.ts b/apps/ide/src/main/extensions/extensionHostManager.ts index 8cfc2655..67179a4d 100644 --- a/apps/ide/src/main/extensions/extensionHostManager.ts +++ b/apps/ide/src/main/extensions/extensionHostManager.ts @@ -8,6 +8,7 @@ import { activationEventsOf, HOST_METHODS, MAIN_METHODS, RpcEndpoint, type DialogRequest, type HostActivationEvent, type HostInitData, type HostLogLine, type HostUiEvent, type UiNotification, type UiRequest, } from '../../shared/extensionHostProtocol.ts'; +import { isProviderKind, type DiagnosticsUpdate, type ProvideRequest, type ProviderRegistration, type WorkspaceEditData } from '../../shared/extensionLanguageProtocol.ts'; import { EXTENSION_IPC_CHANNELS, EXTENSION_IPC_EVENTS, isWorkbenchActivationEvent, type ExtensionActivation, type ExtensionId } from '../../shared/extensions.ts'; import { KeyVault } from '../agents/keyVault.ts'; import { electronCipher } from '../agents/electronCipher.ts'; @@ -17,6 +18,7 @@ import { isOpenableExternalLink } from '../security.ts'; import { addTrustChangeListener, isWorkspaceTrusted } from '../trust/workspaceTrust.ts'; import { addFolderChangeListener, workspaceOrNull } from '../workspace/workspaceWindows.ts'; import { matchGlob } from '../../extensionHost/glob.ts'; +import { DocumentMirror, FolderPaths } from './documentMirror.ts'; import { ExtensionSettingsStore } from './extensionSettings.ts'; import type { ActivationSource, ExtensionsService } from './extensionsService.ts'; import type { LoadedExtension } from './extensionStore.ts'; @@ -63,6 +65,8 @@ export class ExtensionHostManager implements ActivationSource { /** Windows whose workbench said it is ready: only they get a host (and its UI requests). */ private readonly readyWindows = new Set(); private readonly crashes = new Map(); + /** #260: each window's editor documents, so a host that starts later gets them too. */ + private readonly mirrors = new Map(); private readonly settingsStore: ExtensionSettingsStore; private readonly secrets: KeyVault; private readonly machineId: string; @@ -80,6 +84,8 @@ export class ExtensionHostManager implements ActivationSource { this.service.setActivationSource(this); this.service.onDidChange(() => this.restartAll('the installed extensions changed')); addFolderChangeListener((contents) => { + // The editor closes every tab of the old folder; its open events follow for the new one. + this.mirrors.get(contents.id)?.reset(); if (this.readyWindows.has(contents.id)) { void this.restart(contents, 'the folder changed'); } @@ -157,6 +163,8 @@ export class ExtensionHostManager implements ActivationSource { }; this.hosts.set(contents.id, connection); this.wire(connection); + // A new host has none of the previous one's providers or diagnostics. + this.sendUi(contents, { type: 'notify', notification: { kind: 'providersReset' } }); child.on('message', (message) => rpc.receive(message)); for (const stream of [child.stdout, child.stderr]) { if (stream) { @@ -212,6 +220,7 @@ export class ExtensionHostManager implements ActivationSource { version: app.getVersion(), }, isDevelopment: this.isDevelopment, + ...(folder ? this.mirror(contents).snapshot(new FolderPaths(folder)) : { documents: [], activeEditor: null }), }; } @@ -286,6 +295,9 @@ export class ExtensionHostManager implements ActivationSource { for (const resolve of connection.pendingUi.values()) { resolve(null); } + if (!connection.contents.isDestroyed()) { + this.sendUi(connection.contents, { type: 'notify', notification: { kind: 'providersReset' } }); + } } async restart(contents: WebContents, reason: string): Promise { @@ -309,8 +321,24 @@ export class ExtensionHostManager implements ActivationSource { } } + private mirror(contents: WebContents): DocumentMirror { + let mirror = this.mirrors.get(contents.id); + if (!mirror) { + mirror = new DocumentMirror(); + this.mirrors.set(contents.id, mirror); + contents.once('destroyed', () => this.mirrors.delete(contents.id)); + } + return mirror; + } + + private folderPaths(contents: WebContents): FolderPaths | null { + const root = workspaceOrNull(contents)?.root; + return root ? new FolderPaths(root) : null; + } + private exited(connection: HostConnection, code: number | null, signal: string | null): void { connection.rpc.dispose(); + this.sendUi(connection.contents, { type: 'notify', notification: { kind: 'providersReset' } }); for (const resolve of connection.pendingUi.values()) { resolve(null); } @@ -433,6 +461,22 @@ export class ExtensionHostManager implements ActivationSource { const { response } = win ? await dialog.showMessageBox(win, options) : await dialog.showMessageBox(options); return response < request.items.length ? response : null; } + if (request.kind === 'applyEdit') { + // Every file of the edit must be in the folder, or none of it is applied. + const paths = this.folderPaths(contents); + const edits = request.edit.edits; + const relative = paths ? edits.map((entry) => ({ path: paths.toWorkspace(entry.path), edits: entry.edits })) : []; + if (!paths || relative.some((entry) => entry.path === null)) { + extLog.warn('An extension tried to edit a file outside the folder; the edit was not applied.'); + return false; + } + const edit: WorkspaceEditData = { edits: relative as { path: string; edits: WorkspaceEditData['edits'][number]['edits'] }[] }; + return this.askRenderer(connection, { kind: 'applyEdit', edit }); + } + if (request.kind === 'saveFile' || request.kind === 'insertSnippet') { + const workspacePath = this.folderPaths(contents)?.toWorkspace(request.path) ?? null; + return workspacePath === null ? false : this.askRenderer(connection, { ...request, path: workspacePath }); + } if (request.kind === 'openFile') { const folder = workspaceOrNull(contents)?.root; if (!folder || !(request.path === folder || request.path.startsWith(folder + path.sep))) { @@ -444,6 +488,25 @@ export class ExtensionHostManager implements ActivationSource { return this.askRenderer(connection, request); }); rpc.handle(MAIN_METHODS.uiNotify, (notification) => this.sendUi(contents, { type: 'notify', notification: notification as UiNotification })); + rpc.handle(MAIN_METHODS.diagnostics, (raw) => { + const paths = this.folderPaths(contents); + const update = raw as DiagnosticsUpdate; + if (!paths || typeof update?.owner !== 'string') { + return; + } + this.sendUi(contents, { type: 'notify', notification: { kind: 'diagnostics', update: paths.outward(update) as DiagnosticsUpdate } }); + }); + rpc.handle(MAIN_METHODS.registerProvider, (raw) => { + const registration = raw as ProviderRegistration; + if (typeof registration?.handle === 'number' && isProviderKind(registration.kind)) { + this.sendUi(contents, { type: 'notify', notification: { kind: 'providerRegistered', registration } }); + } + }); + rpc.handle(MAIN_METHODS.unregisterProvider, (handle) => { + if (typeof handle === 'number') { + this.sendUi(contents, { type: 'notify', notification: { kind: 'providerUnregistered', handle } }); + } + }); } private broadcastConfiguration(): void { @@ -494,6 +557,30 @@ export class ExtensionHostManager implements ActivationSource { await connection.rpc.request(HOST_METHODS.activateByEvent, activationEvent); } }); + handle(EXTENSION_IPC_CHANNELS.extensionsDocuments, (event, events) => { + const paths = this.folderPaths(event.sender); + if (!paths) { + return; + } + const accepted = this.mirror(event.sender).accept(events, paths); + // Forwarded at once, so the host has a change before any request the renderer sends after it. + if (accepted.length > 0) { + this.hosts.get(event.sender.id)?.rpc.notify(HOST_METHODS.documents, accepted); + } + }); + handle(EXTENSION_IPC_CHANNELS.extensionsProvide, async (event, raw) => { + const request = raw as ProvideRequest; + const paths = this.folderPaths(event.sender); + const connection = this.hosts.get(event.sender.id); + const kindOk = isProviderKind(request?.kind) || request?.kind === 'resolveCompletion' || request?.kind === 'resolveCodeLens' || request?.kind === 'prepareRename'; + if (!paths || !connection || !kindOk || typeof request.handle !== 'number' || typeof request.args !== 'object' || request.args === null) { + return null; + } + const inward: ProvideRequest = { handle: request.handle, kind: request.kind, path: paths.toAbsolute(request.path), args: paths.inward(request.args) as ProvideRequest['args'] }; + await connection.ready; + const result = await connection.rpc.request(HOST_METHODS.provide, inward); + return paths.outward(result); + }); handle(EXTENSION_IPC_CHANNELS.extensionsHostReply, (event, id, result) => { const connection = this.hosts.get(event.sender.id); const resolve = typeof id === 'number' ? connection?.pendingUi.get(id) : undefined; diff --git a/apps/ide/src/preload/index.ts b/apps/ide/src/preload/index.ts index 8b8d47a9..e336a009 100644 --- a/apps/ide/src/preload/index.ts +++ b/apps/ide/src/preload/index.ts @@ -8,6 +8,7 @@ import { GIT_IPC_CHANNELS, GIT_IPC_EVENTS } from '../shared/git.ts'; import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentChatEvent, type AgentProfileInput, type ApprovalDecision, type EditReviewResult, type ChatAttachment, type McpServerInput, type ModelPrice, type BudgetSettings, type ProviderInput } from '../shared/agents.ts'; import { TASK_IPC_CHANNELS, TASK_IPC_EVENTS, type TaskFinished } from '../shared/tasks.ts'; import type { HostUiEvent } from '../shared/extensionHostProtocol.ts'; +import type { DocumentEvent, ProvideRequest } from '../shared/extensionLanguageProtocol.ts'; import { EXTENSION_IPC_CHANNELS, EXTENSION_IPC_EVENTS, type ExtensionsChangedEvent, type ExtensionLogEvent, type GalleryQuery } from '../shared/extensions.ts'; import { DEBUG_IPC_CHANNELS, DEBUG_IPC_EVENTS, type DebugEvent, type DebugStepKind } from '../shared/debug.ts'; import { LSP_IPC_CHANNELS, LSP_IPC_EVENTS, type LspDiagnosticsEvent, type LspLanguage, type LspRequestMethod } from '../shared/lsp.ts'; @@ -139,6 +140,8 @@ const api: CodeXRApi = Object.freeze({ activateByEvent: (event: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsActivateByEvent, event), hostReply: (id: number, result: unknown) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsHostReply, id, result), onHostUi: (listener: (event: HostUiEvent) => void) => subscribe(EXTENSION_IPC_EVENTS.extensionsHostUi, listener), + documentEvents: (events: readonly DocumentEvent[]) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsDocuments, events), + provide: (request: ProvideRequest) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsProvide, request), }), app: Object.freeze({ getInfo: () => ipcRenderer.invoke(IPC_CHANNELS.appGetInfo), diff --git a/apps/ide/src/renderer/editor/editorGroup.ts b/apps/ide/src/renderer/editor/editorGroup.ts index 3bb84509..97b7ffb7 100644 --- a/apps/ide/src/renderer/editor/editorGroup.ts +++ b/apps/ide/src/renderer/editor/editorGroup.ts @@ -273,6 +273,8 @@ export function createEditorGroup( showFunctionProblems?(path: string, name: string): void; /** #172: a tab's text matches the disk again (saved, reloaded, or undone back): its outline may be measured again. */ onFileClean?(path: string): void; + /** #260: a file was written to disk (extensions hear `onDidSaveTextDocument`). */ + onDidSave?(path: string): void; /** #178: "Reveal in XR Scene" from the editor's context menu, on the active file. */ revealInScene?(path: string): void; /** #175: the files' text at HEAD and their blame, from the main process (null when Git has nothing to say). */ @@ -949,6 +951,7 @@ export function createEditorGroup( doc.mtimeMs = result.mtimeMs; doc.diskState = 'same'; refreshDoc(doc); + callbacks.onDidSave?.(doc.path); if (reason === 'explicit') { callbacks.onStatus(`Saved ${doc.path}`); } diff --git a/apps/ide/src/renderer/extensions/documentSync.ts b/apps/ide/src/renderer/extensions/documentSync.ts new file mode 100644 index 00000000..efade06a --- /dev/null +++ b/apps/ide/src/renderer/extensions/documentSync.ts @@ -0,0 +1,200 @@ +import type { DocumentEvent, EditorStateData } from '../../shared/extensionLanguageProtocol.ts'; +import { MAX_SYNCED_DOCUMENT_LENGTH } from '../../shared/extensionLanguageProtocol.ts'; +import type { ExtensionsApi } from '../../shared/extensions.ts'; +import { monaco } from '../editor/monaco.ts'; +import { workspacePathOf } from '../lsp/lspConvert.ts'; +import { changesOf, fromMonacoPosition, fromMonacoRange } from './languageBridgeModel.ts'; + +/** + * Tells the extension host what the editor has open (#260): every Monaco + * model of a workspace file (`codexr-file:` URIs) is announced when it is + * created, each content change as Monaco reports it, and its closing; and + * which editor is active, with its selections. Events go out in order, + * batched once per task; `flush` sends what is waiting right away (a + * provider request must not overtake the change it depends on). + */ + +export const FILE_SCHEME = 'codexr-file'; +const EDITOR_STATE_DELAY_MS = 60; + +export interface DocumentSync { + /** Sends the waiting events now. */ + flush(): void; + /** The editor showing a workspace file that was focused last, if any. */ + activeEditor(): monaco.editor.ICodeEditor | null; + /** The document at `path` was saved (the editor group says so). */ + saved(path: string): void; + /** The workspace path of a model the host follows, or null. */ + pathOf(model: monaco.editor.ITextModel): string | null; + dispose(): void; +} + +export function installDocumentSync(extensions: ExtensionsApi): DocumentSync { + const followed = new Map(); + let queue: DocumentEvent[] = []; + let scheduled = false; + let active: monaco.editor.ICodeEditor | null = null; + let editorTimer: ReturnType | undefined; + const disposables: monaco.IDisposable[] = []; + + function flush(): void { + scheduled = false; + if (queue.length === 0) { + return; + } + const events = queue; + queue = []; + extensions.documentEvents(events).catch(() => undefined); + } + + function push(event: DocumentEvent): void { + queue.push(event); + if (!scheduled) { + scheduled = true; + queueMicrotask(flush); + } + } + + function follow(model: monaco.editor.ITextModel): void { + if (model.uri.scheme !== FILE_SCHEME || followed.has(model) || model.getValueLength() > MAX_SYNCED_DOCUMENT_LENGTH) { + return; + } + const path = workspacePathOf(model.uri.path); + if (path === '') { + return; + } + const subscription = model.onDidChangeContent((event) => { + push({ kind: 'change', path, version: model.getVersionId(), changes: changesOf(event.changes) }); + }); + followed.set(model, { path, subscription }); + push({ kind: 'open', path, languageId: model.getLanguageId(), version: model.getVersionId(), text: model.getValue() }); + } + + function unfollow(model: monaco.editor.ITextModel): void { + const entry = followed.get(model); + if (!entry) { + return; + } + entry.subscription.dispose(); + followed.delete(model); + push({ kind: 'close', path: entry.path }); + if (active?.getModel() === model) { + setActive(null); + } + } + + function editorState(editor: monaco.editor.ICodeEditor | null): EditorStateData | null { + const model = editor?.getModel(); + const entry = model ? followed.get(model) : undefined; + if (!editor || !model || !entry) { + return null; + } + const options = model.getOptions(); + return { + path: entry.path, + selections: (editor.getSelections() ?? []).map((selection) => ({ + anchor: fromMonacoPosition({ lineNumber: selection.selectionStartLineNumber, column: selection.selectionStartColumn }), + active: fromMonacoPosition(selection.getPosition()), + })), + visibleRanges: editor.getVisibleRanges().map((range) => fromMonacoRange(range)), + tabSize: options.tabSize, + insertSpaces: options.insertSpaces, + }; + } + + function sendEditor(): void { + clearTimeout(editorTimer); + editorTimer = undefined; + push({ kind: 'editor', editor: editorState(active) }); + } + + /** Selections and scrolling move often: the host hears about them a little later, once. */ + function editorChangedSoon(): void { + if (editorTimer === undefined) { + editorTimer = setTimeout(sendEditor, EDITOR_STATE_DELAY_MS); + } + } + + function setActive(editor: monaco.editor.ICodeEditor | null): void { + const model = editor?.getModel(); + const next = editor && model && followed.has(model) ? editor : null; + if (next === active && next === null) { + return; + } + active = next; + sendEditor(); + } + + function watchEditor(editor: monaco.editor.ICodeEditor): void { + const subscriptions = [ + editor.onDidFocusEditorText(() => setActive(editor)), + editor.onDidChangeModel(() => { + const model = editor.getModel(); + if (model) { + follow(model); + } + // A tab switch: the editor showing it is the one the person works in. + if (editor === active || (model && model.uri.scheme === FILE_SCHEME)) { + setActive(editor); + } + }), + editor.onDidChangeCursorSelection(() => { + if (editor === active) { + editorChangedSoon(); + } + }), + editor.onDidScrollChange((event) => { + if (editor === active && event.scrollTopChanged) { + editorChangedSoon(); + } + }), + ]; + editor.onDidDispose(() => { + subscriptions.forEach((subscription) => subscription.dispose()); + if (editor === active) { + setActive(null); + } + }); + if (!active) { + setActive(editor); + } + } + + monaco.editor.getModels().forEach(follow); + disposables.push( + monaco.editor.onDidCreateModel(follow), + monaco.editor.onWillDisposeModel(unfollow), + monaco.editor.onDidChangeModelLanguage(({ model }) => { + const entry = followed.get(model); + if (entry) { + push({ kind: 'language', path: entry.path, languageId: model.getLanguageId() }); + } + }), + monaco.editor.onDidCreateEditor(watchEditor), + ); + monaco.editor.getEditors().forEach(watchEditor); + + return { + flush() { + if (editorTimer !== undefined) { + sendEditor(); + } + flush(); + }, + activeEditor: () => active, + saved(path) { + if ([...followed.values()].some((entry) => entry.path === path)) { + push({ kind: 'save', path }); + } + }, + pathOf: (model) => followed.get(model)?.path ?? null, + dispose() { + disposables.forEach((disposable) => disposable.dispose()); + for (const entry of followed.values()) { + entry.subscription.dispose(); + } + followed.clear(); + clearTimeout(editorTimer); + }, + }; +} diff --git a/apps/ide/src/renderer/extensions/extensionsWiring.ts b/apps/ide/src/renderer/extensions/extensionsWiring.ts index 840fb627..43f58389 100644 --- a/apps/ide/src/renderer/extensions/extensionsWiring.ts +++ b/apps/ide/src/renderer/extensions/extensionsWiring.ts @@ -1,4 +1,5 @@ import type { CodeXRApi } from '../../shared/api.ts'; +import type { UiRequest } from '../../shared/extensionHostProtocol.ts'; import type { ContributedTheme, InstalledExtension } from '../../shared/extensions.ts'; import type { CommandRegistry } from '../commands/commandRegistry.ts'; import type { QuickInputProvider } from '../commands/quickInput.ts'; @@ -6,6 +7,8 @@ import type { NotificationCenter } from '../notifications.ts'; import { createContributionsController, type ContributionsController } from './contributionsController.ts'; import { createExtensionsView, type ExtensionsView } from './extensionsView.ts'; import { createHostBridge } from './hostBridge.ts'; +import type { DocumentSync } from './documentSync.ts'; +import type { LanguageBridge } from './languageBridge.ts'; import './extensions.css'; /** @@ -19,8 +22,14 @@ export interface ExtensionsWorkbench { readonly contributions: ContributionsController; /** The colour themes of the enabled extensions, for the theme picker. */ themes(): readonly ContributedTheme[]; - /** #259: Monaco is loaded: fire `onLanguage:` for every model's language from now on. */ + /** + * #259, #260: Monaco is loaded: fire `onLanguage:` for every model's + * language from now on, follow the editor's documents for the extension + * host, and bridge the extensions' language features. + */ watchEditorLanguages(): void; + /** #260: the editor group saved `path`. */ + documentSaved(path: string): void; } export interface ExtensionsWorkbenchDeps { @@ -40,6 +49,8 @@ export interface ExtensionsWorkbenchDeps { openQuickInput(value: string, provider: QuickInputProvider): void; /** Opens a file of the folder (relative path), at a 1-based line and column when given. */ openFile(path: string, line?: number, column?: number): Promise; + /** #260: saves an open file of the folder (an extension's `TextDocument.save()`). */ + saveFile(path: string): Promise; } export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWorkbench { @@ -69,6 +80,31 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork }, }); + // #260: the language bridge needs Monaco, which loads with the first editor; what comes before waits. + type LanguageNotification = Parameters[0]['languageNotification']>[0]; + let languages: { bridge: LanguageBridge; sync: DocumentSync } | null = null; + const earlyNotifications: LanguageNotification[] = []; + let languagesReady: (value: { bridge: LanguageBridge; sync: DocumentSync }) => void = () => undefined; + const whenLanguages = new Promise<{ bridge: LanguageBridge; sync: DocumentSync }>((resolve) => { + languagesReady = resolve; + }); + const languageNotification = (notification: LanguageNotification, bridge: LanguageBridge): void => { + switch (notification.kind) { + case 'diagnostics': + bridge.diagnostics(notification.update); + return; + case 'providerRegistered': + bridge.registered(notification.registration); + return; + case 'providerUnregistered': + bridge.unregistered(notification.handle); + return; + case 'providersReset': + bridge.reset(); + return; + } + }; + // #259: the extension host's requests, status bar items and the palette's commands. const bridge = createHostBridge({ extensions: api.extensions, @@ -83,6 +119,29 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork deps.showView(); view.focusSearch(query); }, + languageNotification(notification) { + if (languages) { + languageNotification(notification, languages.bridge); + } else if (notification.kind === 'providersReset') { + earlyNotifications.length = 0; + } else { + earlyNotifications.push(notification); + } + }, + async languageRequest(request: Extract) { + if (request.kind === 'saveFile') { + return deps.saveFile(request.path); + } + if (request.kind === 'applyEdit' && !languages) { + // An edit before any editor exists: opening the first file loads Monaco. + const first = request.edit.edits[0]; + if (first) { + await deps.openFile(first.path); + } + } + const ready = languages ?? await whenLanguages; + return request.kind === 'applyEdit' ? ready.bridge.applyEdit(request.edit) : ready.bridge.insertSnippet(request.path, request.snippet, request.ranges); + }, }); let installed: readonly InstalledExtension[] = []; const refresh = async (): Promise => { @@ -130,6 +189,32 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork themes: () => contributions.current().themes, watchEditorLanguages() { void import('./monacoContributions.ts').then((part) => part.watchModelLanguages(fireLanguage)); + if (languages) { + return; + } + void Promise.all([import('./documentSync.ts'), import('./languageBridge.ts')]).then(([syncModule, bridgeModule]) => { + if (languages) { + return; + } + const sync = syncModule.installDocumentSync(api.extensions); + const languageBridge = bridgeModule.createLanguageBridge({ + extensions: api.extensions, + sync, + openFile: deps.openFile, + saveFile: deps.saveFile, + runCommand: (id, args) => { + api.extensions.executeCommand(id, args).catch((error: unknown) => deps.notify('error', `Command '${id}' failed: ${error instanceof Error ? error.message : String(error)}`)); + }, + }); + languages = { bridge: languageBridge, sync }; + for (const notification of earlyNotifications.splice(0)) { + languageNotification(notification, languageBridge); + } + languagesReady(languages); + }).catch((error: unknown) => deps.notify('error', `Extensions' language features could not start: ${String(error)}`)); + }, + documentSaved(path) { + languages?.sync.saved(path); }, }; } diff --git a/apps/ide/src/renderer/extensions/hostBridge.ts b/apps/ide/src/renderer/extensions/hostBridge.ts index 1591fa97..116e76ef 100644 --- a/apps/ide/src/renderer/extensions/hostBridge.ts +++ b/apps/ide/src/renderer/extensions/hostBridge.ts @@ -27,6 +27,10 @@ export interface HostBridgeDeps { setStatus(message: string): void; /** Shows the Extensions view with a search (`workbench.extensions.search`). */ searchExtensions(query: string): void; + /** #260: the language features' notifications (providers, diagnostics), for the language bridge. */ + languageNotification(notification: Extract): void; + /** #260: the host's edits and saves of the editor's documents. */ + languageRequest(request: Extract): Promise; } export interface HostBridge { @@ -133,6 +137,10 @@ export function createHostBridge(deps: HostBridgeDeps): HostBridge { return true; case 'command': return runWorkbenchCommand(request.id, request.args); + case 'applyEdit': + case 'saveFile': + case 'insertSnippet': + return deps.languageRequest(request); } } @@ -207,6 +215,12 @@ export function createHostBridge(deps: HostBridgeDeps): HostBridge { case 'contextKey': context.set(notification.key, notification.value); return; + case 'diagnostics': + case 'providerRegistered': + case 'providerUnregistered': + case 'providersReset': + deps.languageNotification(notification); + return; case 'hostStopped': deps.notifications.notify('error', notification.reason, { actions: [{ label: 'Restart Extension Host', run: () => void extensions.restartHost() }], diff --git a/apps/ide/src/renderer/extensions/languageBridge.ts b/apps/ide/src/renderer/extensions/languageBridge.ts new file mode 100644 index 00000000..e2d12fad --- /dev/null +++ b/apps/ide/src/renderer/extensions/languageBridge.ts @@ -0,0 +1,534 @@ +import type { + CodeActionData, CodeLensListData, CommandData, CompletionItemData, CompletionListData, DiagnosticData, DiagnosticsUpdate, DocumentLinkData, DocumentSymbolData, FoldingRangeData, + HoverData, InlayHintData, LocationData, ProvideRequest, ProviderRegistration, RangeData, RenameLocationData, SignatureHelpData, TextChangeData, WorkspaceEditData, +} from '../../shared/extensionLanguageProtocol.ts'; +import { selectorMatches } from '../../shared/extensionLanguageProtocol.ts'; +import type { ExtensionsApi } from '../../shared/extensions.ts'; +import { monaco } from '../editor/monaco.ts'; +import { FILE_SCHEME, type DocumentSync } from './documentSync.ts'; +import { completionKindName, diagnosticSeverity, foldingKind, fromMonacoPosition, fromMonacoRange, markerSeverity, monacoLanguages, toMonacoPosition, toMonacoRange } from './languageBridgeModel.ts'; + +/** + * The Monaco side of the extensions' language features (#260). For each + * provider an extension registers, a Monaco provider of the same kind asks + * the host with the document's path; diagnostics become markers (owner + * `ext::`, listed by the Problems panel like the + * others); and the host's edits are applied to the editor's models as one + * undoable step each. + * + * Text from an extension reaches Monaco as Markdown or plain strings, which + * Monaco renders without HTML (its Markdown renderer is sanitized). + */ + +export interface LanguageBridgeDeps { + readonly extensions: ExtensionsApi; + readonly sync: DocumentSync; + openFile(path: string, line?: number, column?: number): Promise; + saveFile(path: string): Promise; + runCommand(id: string, args: readonly unknown[]): void; +} + +export interface LanguageBridge { + registered(registration: ProviderRegistration): void; + unregistered(handle: number): void; + diagnostics(update: DiagnosticsUpdate): void; + /** A host started or stopped: drops every provider and marker of extensions. */ + reset(): void; + applyEdit(edit: WorkspaceEditData): Promise; + saveFile(path: string): Promise; + insertSnippet(path: string, snippet: string, ranges?: readonly RangeData[]): boolean; + dispose(): void; +} + +const RUN_COMMAND = 'codexr.extensions.runCommand'; +const MARKER_PREFIX = 'ext:'; + +const uriOf = (path: string): monaco.Uri => monaco.Uri.from({ scheme: FILE_SCHEME, path: `/${path}` }); +const range = (data: RangeData): monaco.IRange => toMonacoRange(data); + +function warn(error: unknown): void { + console.warn('[code-xr-ide] extension language feature:', error); +} + +export function createLanguageBridge(deps: LanguageBridgeDeps): LanguageBridge { + const { extensions, sync } = deps; + const providers = new Map(); + /** owner -> path -> markers */ + const markers = new Map>(); + const completionOrigins = new WeakMap(); + const lensOrigins = new WeakMap(); + + const toCommand = (command: CommandData | undefined): monaco.languages.Command | undefined => (command ? { + id: RUN_COMMAND, title: command.title, ...(command.tooltip ? { tooltip: command.tooltip } : {}), arguments: [command.id, command.args ?? []], + } : undefined); + + const disposables: monaco.IDisposable[] = [ + monaco.editor.registerCommand(RUN_COMMAND, (_accessor: unknown, id: unknown, args: unknown) => { + if (typeof id === 'string') { + deps.runCommand(id, Array.isArray(args) ? args : []); + } + }), + monaco.editor.onDidCreateModel((model) => applyMarkers(model)), + // Go to definition into another file: Monaco has one editor per group, so the workbench opens the tab. + monaco.editor.registerEditorOpener({ + openCodeEditor(_source, resource, selectionOrPosition) { + if (resource.scheme !== FILE_SCHEME) { + return false; + } + const start = selectionOrPosition && 'startLineNumber' in selectionOrPosition ? { line: selectionOrPosition.startLineNumber, column: selectionOrPosition.startColumn } + : selectionOrPosition ? { line: selectionOrPosition.lineNumber, column: selectionOrPosition.column } : { line: 1, column: 1 }; + void deps.openFile(decodeURIComponent(resource.path.replace(/^\//, '')), start.line, start.column).catch(warn); + return true; + }, + }), + ]; + + /* ------------------------------ asking the host ------------------------------ */ + + async function ask(registration: ProviderRegistration, model: monaco.editor.ITextModel, kind: ProvideRequest['kind'], args: ProvideRequest['args']): Promise { + const path = sync.pathOf(model); + if (!path || !selectorMatches(registration.selector, { languageId: model.getLanguageId(), path })) { + return null; + } + sync.flush(); + try { + return (await extensions.provide({ handle: registration.handle, kind, path, args })) as T | null; + } catch (error) { + warn(error); + return null; + } + } + + async function resolve(origin: { handle: number; path: string; cacheId: number; index: number }, kind: ProvideRequest['kind']): Promise { + try { + return (await extensions.provide({ handle: origin.handle, kind, path: origin.path, args: { cacheId: origin.cacheId, index: origin.index } })) as T | null; + } catch (error) { + warn(error); + return null; + } + } + + const toLocations = (locations: readonly LocationData[] | null): monaco.languages.LocationLink[] => (locations ?? []).map((location) => ({ + uri: uriOf(location.path), + range: range(location.range), + ...(location.targetSelectionRange ? { targetSelectionRange: range(location.targetSelectionRange) } : {}), + ...(location.originRange ? { originSelectionRange: range(location.originRange) } : {}), + })); + + const toTextEdits = (edits: readonly TextChangeData[] | null): monaco.languages.TextEdit[] => (edits ?? []).map((edit) => ({ range: range(edit.range), text: edit.text })); + + const toWorkspaceEdit = (edit: WorkspaceEditData | null | undefined): monaco.languages.WorkspaceEdit => ({ + edits: (edit?.edits ?? []).flatMap((entry) => entry.edits.map((textEdit) => ({ resource: uriOf(entry.path), textEdit: { range: range(textEdit.range), text: textEdit.text }, versionId: undefined }))), + }); + + const toMarkerData = (diagnostic: DiagnosticData): monaco.editor.IMarkerData => ({ + ...range(diagnostic.range), + severity: markerSeverity(diagnostic.severity) as monaco.MarkerSeverity, + message: diagnostic.message, + ...(diagnostic.source ? { source: diagnostic.source } : {}), + ...(diagnostic.code !== undefined ? { code: diagnostic.code } : {}), + ...(diagnostic.tags ? { tags: diagnostic.tags.filter((tag) => tag === 1 || tag === 2) as monaco.MarkerTag[] } : {}), + ...(diagnostic.relatedInformation ? { relatedInformation: diagnostic.relatedInformation.map((info) => ({ resource: uriOf(info.path), message: info.message, ...range(info.range) })) } : {}), + }); + + const fromMarker = (marker: monaco.editor.IMarkerData): DiagnosticData => ({ + range: fromMonacoRange(marker), + message: marker.message, + severity: diagnosticSeverity(marker.severity), + ...(marker.source ? { source: marker.source } : {}), + ...(typeof marker.code === 'string' ? { code: marker.code } : {}), + }); + + const toSuggestion = (item: CompletionItemData, model: monaco.editor.ITextModel, position: monaco.Position): monaco.languages.CompletionItem => { + const word = model.getWordUntilPosition(position); + const fallback = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn); + const itemRange = !item.range ? fallback : Array.isArray(item.range) ? range(item.range as RangeData) + : { insert: range((item.range as { inserting: RangeData }).inserting), replace: range((item.range as { replacing: RangeData }).replacing) }; + const label = typeof item.label === 'string' ? item.label : { label: item.label.label, ...(item.label.detail ? { detail: item.label.detail } : {}), ...(item.label.description ? { description: item.label.description } : {}) }; + const command = toCommand(item.command); + return { + label, + kind: monaco.languages.CompletionItemKind[completionKindName(item.kind)], + insertText: item.insertText ?? (typeof item.label === 'string' ? item.label : item.label.label), + range: itemRange, + ...(item.isSnippet ? { insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet } : {}), + ...(item.detail ? { detail: item.detail } : {}), + ...(item.documentation ? { documentation: { value: item.documentation } } : {}), + ...(item.sortText ? { sortText: item.sortText } : {}), + ...(item.filterText ? { filterText: item.filterText } : {}), + ...(item.preselect ? { preselect: true } : {}), + ...(item.commitCharacters ? { commitCharacters: [...item.commitCharacters] } : {}), + ...(item.tags?.includes(1) ? { tags: [monaco.languages.CompletionItemTag.Deprecated] } : {}), + ...(item.additionalTextEdits ? { additionalTextEdits: toTextEdits(item.additionalTextEdits) } : {}), + ...(command ? { command } : {}), + }; + }; + + const toSymbols = (symbols: readonly DocumentSymbolData[]): monaco.languages.DocumentSymbol[] => symbols.map((symbol) => ({ + name: symbol.name, + detail: symbol.detail, + kind: symbol.kind as monaco.languages.SymbolKind, + tags: (symbol.tags ?? []) as monaco.languages.SymbolTag[], + range: range(symbol.range), + selectionRange: range(symbol.selectionRange), + children: toSymbols(symbol.children), + ...(symbol.containerName ? { containerName: symbol.containerName } : {}), + })); + + /* ------------------------------ one Monaco provider per registration ------------------------------ */ + + function register(registration: ProviderRegistration): monaco.IDisposable[] { + const languages = monacoLanguages(registration.selector); + if (languages !== null && languages.length === 0) { + return []; + } + const selector: monaco.languages.LanguageSelector = languages === null ? [{ scheme: FILE_SCHEME }] : languages.map((language) => ({ language, scheme: FILE_SCHEME })); + const r = registration; + const L = monaco.languages; + switch (registration.kind) { + case 'hover': + return [L.registerHoverProvider(selector, { + async provideHover(model, position) { + const hover = await ask(r, model, 'hover', { position: fromMonacoPosition(position) }); + return hover ? { contents: hover.contents.map((value) => ({ value })), ...(hover.range ? { range: range(hover.range) } : {}) } : null; + }, + })]; + case 'completion': + return [L.registerCompletionItemProvider(selector, { + triggerCharacters: [...(r.triggerCharacters ?? [])], + async provideCompletionItems(model, position, context) { + const list = await ask(r, model, 'completion', { + position: fromMonacoPosition(position), + // Monaco: Invoke 0, TriggerCharacter 1, TriggerForIncompleteCompletions 2, as in VS Code. + triggerKind: context.triggerKind, + ...(context.triggerCharacter ? { triggerCharacter: context.triggerCharacter } : {}), + }); + const path = sync.pathOf(model); + const suggestions = (list?.items ?? []).map((item, index) => { + const suggestion = toSuggestion(item, model, position); + if (list?.cacheId !== undefined && path) { + completionOrigins.set(suggestion, { handle: r.handle, path, cacheId: list.cacheId, index }); + } + return suggestion; + }); + return { suggestions, incomplete: list?.incomplete === true }; + }, + ...(r.resolves ? { + async resolveCompletionItem(suggestion: monaco.languages.CompletionItem) { + const origin = completionOrigins.get(suggestion); + const resolved = origin ? await resolve(origin, 'resolveCompletion') : null; + if (!resolved) { + return suggestion; + } + const command = toCommand(resolved.command); + return { + ...suggestion, + ...(resolved.detail ? { detail: resolved.detail } : {}), + ...(resolved.documentation ? { documentation: { value: resolved.documentation } } : {}), + ...(resolved.additionalTextEdits ? { additionalTextEdits: toTextEdits(resolved.additionalTextEdits) } : {}), + ...(command ? { command } : {}), + }; + }, + } : {}), + })]; + case 'definition': + return [L.registerDefinitionProvider(selector, { provideDefinition: async (model, position) => toLocations(await ask(r, model, 'definition', { position: fromMonacoPosition(position) })) })]; + case 'declaration': + return [L.registerDeclarationProvider(selector, { provideDeclaration: async (model, position) => toLocations(await ask(r, model, 'declaration', { position: fromMonacoPosition(position) })) })]; + case 'typeDefinition': + return [L.registerTypeDefinitionProvider(selector, { provideTypeDefinition: async (model, position) => toLocations(await ask(r, model, 'typeDefinition', { position: fromMonacoPosition(position) })) })]; + case 'implementation': + return [L.registerImplementationProvider(selector, { provideImplementation: async (model, position) => toLocations(await ask(r, model, 'implementation', { position: fromMonacoPosition(position) })) })]; + case 'references': + return [L.registerReferenceProvider(selector, { + provideReferences: async (model, position, context) => toLocations(await ask(r, model, 'references', { position: fromMonacoPosition(position), includeDeclaration: context.includeDeclaration })), + })]; + case 'documentSymbol': + return [L.registerDocumentSymbolProvider(selector, { + displayName: r.label ?? r.extensionId, + provideDocumentSymbols: async (model) => toSymbols(await ask(r, model, 'documentSymbol', {}) ?? []), + })]; + case 'documentHighlight': + return [L.registerDocumentHighlightProvider(selector, { + async provideDocumentHighlights(model, position) { + const highlights = await ask<{ range: RangeData; kind: number }[]>(r, model, 'documentHighlight', { position: fromMonacoPosition(position) }); + return (highlights ?? []).map((highlight) => ({ range: range(highlight.range), kind: highlight.kind as monaco.languages.DocumentHighlightKind })); + }, + })]; + case 'signatureHelp': + return [L.registerSignatureHelpProvider(selector, { + signatureHelpTriggerCharacters: [...(r.triggerCharacters ?? [])], + signatureHelpRetriggerCharacters: [...(r.retriggerCharacters ?? [])], + async provideSignatureHelp(model, position, _token, context) { + const help = await ask(r, model, 'signatureHelp', { + position: fromMonacoPosition(position), triggerKind: context.triggerKind, isRetrigger: context.isRetrigger, + ...(context.triggerCharacter ? { triggerCharacter: context.triggerCharacter } : {}), + }); + if (!help || help.signatures.length === 0) { + return null; + } + return { + value: { + signatures: help.signatures.map((signature) => ({ + label: signature.label, + ...(signature.documentation ? { documentation: { value: signature.documentation } } : {}), + parameters: signature.parameters.map((parameter) => ({ + label: typeof parameter.label === 'string' ? parameter.label : [parameter.label[0], parameter.label[1]] as [number, number], + ...(parameter.documentation ? { documentation: { value: parameter.documentation } } : {}), + })), + ...(signature.activeParameter !== undefined ? { activeParameter: signature.activeParameter } : {}), + })), + activeSignature: help.activeSignature, + activeParameter: help.activeParameter, + }, + dispose: () => undefined, + }; + }, + })]; + case 'formatting': + return [L.registerDocumentFormattingEditProvider(selector, { + displayName: r.extensionId, + provideDocumentFormattingEdits: async (model, options) => toTextEdits(await ask(r, model, 'formatting', { options: { tabSize: options.tabSize, insertSpaces: options.insertSpaces } })), + })]; + case 'rangeFormatting': + return [L.registerDocumentRangeFormattingEditProvider(selector, { + displayName: r.extensionId, + provideDocumentRangeFormattingEdits: async (model, formatRange, options) => toTextEdits(await ask(r, model, 'rangeFormatting', { + range: fromMonacoRange(formatRange), options: { tabSize: options.tabSize, insertSpaces: options.insertSpaces }, + })), + })]; + case 'onTypeFormatting': + return (r.triggerCharacters ?? []).length === 0 ? [] : [L.registerOnTypeFormattingEditProvider(selector, { + autoFormatTriggerCharacters: [...(r.triggerCharacters ?? [])], + provideOnTypeFormattingEdits: async (model, position, ch, options) => toTextEdits(await ask(r, model, 'onTypeFormatting', { + position: fromMonacoPosition(position), triggerCharacter: ch, options: { tabSize: options.tabSize, insertSpaces: options.insertSpaces }, + })), + })]; + case 'codeAction': + return [L.registerCodeActionProvider(selector, { + async provideCodeActions(model, actionRange, context) { + const actions = await ask(r, model, 'codeAction', { + range: fromMonacoRange(actionRange), + diagnostics: context.markers.map(fromMarker), + triggerKind: context.trigger, + ...(context.only ? { only: context.only } : {}), + }); + return { + actions: (actions ?? []).map((action) => { + const command = toCommand(action.command); + return { + title: action.title, + ...(action.kind !== undefined ? { kind: action.kind } : {}), + ...(action.isPreferred ? { isPreferred: true } : {}), + ...(action.diagnostics ? { diagnostics: action.diagnostics.map(toMarkerData) } : {}), + ...(action.edit ? { edit: toWorkspaceEdit(action.edit) } : {}), + ...(command ? { command } : {}), + ...(action.disabled ? { disabled: action.disabled } : {}), + }; + }), + dispose: () => undefined, + }; + }, + }, { providedCodeActionKinds: [...(r.providedCodeActionKinds ?? [])].filter((kind) => kind !== '') })]; + case 'codeLens': + return [L.registerCodeLensProvider(selector, { + async provideCodeLenses(model) { + const list = await ask(r, model, 'codeLens', {}); + const path = sync.pathOf(model); + const lenses = (list?.lenses ?? []).map((lens, index) => { + const command = toCommand(lens.command); + const result: monaco.languages.CodeLens = { range: range(lens.range), ...(command ? { command } : {}) }; + if (list?.cacheId !== undefined && path) { + lensOrigins.set(result, { handle: r.handle, path, cacheId: list.cacheId, index }); + } + return result; + }); + return { lenses, dispose: () => undefined }; + }, + ...(r.resolves ? { + async resolveCodeLens(_model: monaco.editor.ITextModel, lens: monaco.languages.CodeLens) { + const origin = lensOrigins.get(lens); + const resolved = origin ? await resolve<{ range: RangeData; command?: CommandData }>(origin, 'resolveCodeLens') : null; + const command = toCommand(resolved?.command); + return command ? { ...lens, command } : lens; + }, + } : {}), + })]; + case 'rename': + return [L.registerRenameProvider(selector, { + provideRenameEdits: async (model, position, newName) => toWorkspaceEdit(await ask(r, model, 'rename', { position: fromMonacoPosition(position), newName })), + async resolveRenameLocation(model, position) { + const location = await ask(r, model, 'prepareRename', { position: fromMonacoPosition(position) }); + return location ? { range: range(location.range), text: location.text } : { range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column), text: '', rejectReason: 'This element cannot be renamed.' }; + }, + })]; + case 'foldingRange': + return [L.registerFoldingRangeProvider(selector, { + async provideFoldingRanges(model) { + const ranges = await ask(r, model, 'foldingRange', {}); + return (ranges ?? []).map((fold) => { + const kind = foldingKind(fold.kind); + return { start: fold.start + 1, end: fold.end + 1, ...(kind ? { kind: new L.FoldingRangeKind(kind) } : {}) }; + }); + }, + })]; + case 'inlayHints': + return [L.registerInlayHintsProvider(selector, { + async provideInlayHints(model, hintRange) { + const hints = await ask(r, model, 'inlayHints', { range: fromMonacoRange(hintRange) }); + return { + hints: (hints ?? []).map((hint) => ({ + position: toMonacoPosition(hint.position), + label: hint.label, + ...(hint.kind !== undefined ? { kind: hint.kind as monaco.languages.InlayHintKind } : {}), + ...(hint.tooltip ? { tooltip: { value: hint.tooltip } } : {}), + ...(hint.paddingLeft ? { paddingLeft: true } : {}), + ...(hint.paddingRight ? { paddingRight: true } : {}), + })), + dispose: () => undefined, + }; + }, + })]; + case 'documentLink': + return [L.registerLinkProvider(selector, { + async provideLinks(model) { + const links = await ask(r, model, 'documentLink', {}); + return { links: (links ?? []).flatMap((link) => (link.url ? [{ range: range(link.range), url: link.url, ...(link.tooltip ? { tooltip: link.tooltip } : {}) }] : [])) }; + }, + })]; + } + return []; + } + + /* ------------------------------ diagnostics ------------------------------ */ + + function applyMarkers(model: monaco.editor.ITextModel): void { + if (model.uri.scheme !== FILE_SCHEME) { + return; + } + const path = decodeURIComponent(model.uri.path.replace(/^\//, '')); + for (const [owner, byPath] of markers) { + const list = byPath.get(path); + if (list) { + monaco.editor.setModelMarkers(model, owner, list); + } + } + } + + function clearOwner(owner: string): void { + const byPath = markers.get(owner); + if (!byPath) { + return; + } + for (const path of byPath.keys()) { + const model = monaco.editor.getModel(uriOf(path)); + if (model) { + monaco.editor.setModelMarkers(model, owner, []); + } + } + markers.delete(owner); + } + + /* ------------------------------ edits from the host ------------------------------ */ + + async function modelFor(path: string): Promise { + const uri = uriOf(path); + let model = monaco.editor.getModel(uri); + if (!model) { + await deps.openFile(path); + model = monaco.editor.getModel(uri); + } + return model; + } + + return { + registered(registration) { + if (providers.has(registration.handle)) { + return; + } + try { + providers.set(registration.handle, register(registration)); + } catch (error) { + warn(error); + } + }, + unregistered(handle) { + providers.get(handle)?.forEach((disposable) => disposable.dispose()); + providers.delete(handle); + }, + diagnostics(update) { + const owner = `${MARKER_PREFIX}${update.owner}`; + if (update.clear) { + clearOwner(owner); + } + let byPath = markers.get(owner); + if (!byPath) { + byPath = new Map(); + markers.set(owner, byPath); + } + for (const entry of update.entries) { + const list = entry.diagnostics.map(toMarkerData); + if (list.length === 0) { + byPath.delete(entry.path); + } else { + byPath.set(entry.path, list); + } + const model = monaco.editor.getModel(uriOf(entry.path)); + if (model) { + monaco.editor.setModelMarkers(model, owner, list); + } + } + }, + reset() { + for (const handle of [...providers.keys()]) { + providers.get(handle)?.forEach((disposable) => disposable.dispose()); + } + providers.clear(); + for (const owner of [...markers.keys()]) { + clearOwner(owner); + } + }, + async applyEdit(edit) { + for (const entry of edit.edits) { + const model = await modelFor(entry.path); + if (!model) { + return false; + } + const operations = entry.edits.map((change) => ({ range: range(change.range), text: change.text, forceMoveMarkers: true })); + model.pushStackElement(); + model.pushEditOperations([], operations, () => null); + model.pushStackElement(); + } + // The changes are queued for the host; send them before the answer, so they arrive first. + sync.flush(); + return true; + }, + async saveFile(path) { + return deps.saveFile(path); + }, + insertSnippet(path, snippet, ranges) { + const editor = sync.activeEditor(); + const model = editor?.getModel(); + if (!editor || !model || sync.pathOf(model) !== path) { + return false; + } + if (ranges && ranges.length > 0) { + editor.setSelections(ranges.map((item) => { + const r = range(item); + return new monaco.Selection(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn); + })); + } + const controller = editor.getContribution('snippetController2') as { insert(template: string): void } | null; + if (!controller) { + return false; + } + controller.insert(snippet); + sync.flush(); + return true; + }, + dispose() { + this.reset(); + disposables.forEach((disposable) => disposable.dispose()); + }, + }; +} diff --git a/apps/ide/src/renderer/extensions/languageBridgeModel.ts b/apps/ide/src/renderer/extensions/languageBridgeModel.ts new file mode 100644 index 00000000..90af5613 --- /dev/null +++ b/apps/ide/src/renderer/extensions/languageBridgeModel.ts @@ -0,0 +1,79 @@ +import { COMPLETION_KIND_NAMES, type DocumentFilterData, type PositionData, type RangeData, type TextChangeData } from '../../shared/extensionLanguageProtocol.ts'; + +/** + * Pure parts of the language bridge (#260), unit-tested in Node: Monaco's + * 1-based positions against VS Code's 0-based ones, kinds and severities + * between the two enums, and which Monaco languages a selector needs. + */ + +export interface MonacoRangeLike { + readonly startLineNumber: number; + readonly startColumn: number; + readonly endLineNumber: number; + readonly endColumn: number; +} + +export function toMonacoRange(range: RangeData): MonacoRangeLike { + return { startLineNumber: range[0] + 1, startColumn: range[1] + 1, endLineNumber: range[2] + 1, endColumn: range[3] + 1 }; +} + +export function fromMonacoRange(range: MonacoRangeLike): RangeData { + return [range.startLineNumber - 1, range.startColumn - 1, range.endLineNumber - 1, range.endColumn - 1]; +} + +export function fromMonacoPosition(position: { readonly lineNumber: number; readonly column: number }): PositionData { + return [position.lineNumber - 1, position.column - 1]; +} + +export function toMonacoPosition(position: PositionData): { lineNumber: number; column: number } { + return { lineNumber: position[0] + 1, column: position[1] + 1 }; +} + +/** A Monaco content change event's changes, in VS Code's form (applied in order, as Monaco emits them). */ +export function changesOf(changes: readonly { readonly range: MonacoRangeLike; readonly text: string }[]): TextChangeData[] { + return changes.map((change) => ({ range: fromMonacoRange(change.range), text: change.text })); +} + +/** VS Code's `CompletionItemKind` as the name Monaco's enum also has. */ +export function completionKindName(kind: number | undefined): (typeof COMPLETION_KIND_NAMES)[number] { + return (kind !== undefined ? COMPLETION_KIND_NAMES[kind] : undefined) ?? 'Text'; +} + +/** VS Code's `DiagnosticSeverity` (Error 0 ... Hint 3) as Monaco's `MarkerSeverity` (Error 8 ... Hint 1). */ +export function markerSeverity(severity: number): 1 | 2 | 4 | 8 { + switch (severity) { + case 0: return 8; + case 1: return 4; + case 2: return 2; + default: return 1; + } +} + +/** Monaco's `MarkerSeverity` back to VS Code's `DiagnosticSeverity`. */ +export function diagnosticSeverity(severity: number): number { + return severity >= 8 ? 0 : severity >= 4 ? 1 : severity >= 2 ? 2 : 3; +} + +/** VS Code's `FoldingRangeKind` (1 comment, 2 imports, 3 region) as Monaco's kind value. */ +export function foldingKind(kind: number | undefined): 'comment' | 'imports' | 'region' | undefined { + return kind === 1 ? 'comment' : kind === 2 ? 'imports' : kind === 3 ? 'region' : undefined; +} + +/** + * The Monaco languages to register a provider for: the selector's named + * languages, or null when a filter matches any language (pattern or scheme + * only, or `*`). The provider still checks the full selector on each call. + */ +export function monacoLanguages(selector: readonly DocumentFilterData[]): string[] | null { + const languages = new Set(); + for (const filter of selector) { + if (filter.language === undefined || filter.language === '*') { + if (filter.scheme !== undefined && filter.scheme !== '*' && filter.scheme !== 'file') { + continue; // matches none of the editor's files + } + return null; + } + languages.add(filter.language); + } + return [...languages]; +} diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 067ec7ce..425976f2 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -124,6 +124,7 @@ function editorGroup(): Promise { onMarkersChange: () => problemsView.setEditorProblems(editors?.editorProblems() ?? []), showFunctionProblems: (path, name) => problemsView.filterTo(`'${name}' ${path}`), onFileClean: (path) => outline?.fileClean(path), + onDidSave: (path) => extensions.documentSaved(path), revealInScene: (path) => revealInScene(path), }); editors.setSceneShown(!workbench.sceneArea.hidden); @@ -719,6 +720,12 @@ const extensions = installExtensions({ statusRight: workbench.extensionStatusRight, openQuickInput: (value, provider) => quickInput.open(value, provider), openFile: (path, line, column) => editorGroup().then((group) => (line === undefined ? group.open(path) : group.openAt(path, line, column ?? 1, 0))), + saveFile: async (path) => { + const group = await editorGroup(); + await group.open(path); + await group.save(); + return !group.dirtyPaths().includes(path); + }, }); registerDebugCommands(registry, debug, () => folderIsOpen, () => (editors?.activeLineCount() ?? null) !== null, () => workbench.showView('debug')); registerAgentCommands(registry, { showAgents: () => workbench.showView('agents'), addProvider: () => agentsView.addProvider(), newChat: () => void agentsView.newChat() }); diff --git a/apps/ide/src/shared/extensionHostProtocol.ts b/apps/ide/src/shared/extensionHostProtocol.ts index f4e3e579..a0d8d01e 100644 --- a/apps/ide/src/shared/extensionHostProtocol.ts +++ b/apps/ide/src/shared/extensionHostProtocol.ts @@ -11,6 +11,7 @@ * Shared by main, the host and the renderer: no Node, Electron or DOM import. */ +import type { DiagnosticsUpdate, EditorStateData, ProviderRegistration, RangeData, WorkspaceEditData } from './extensionLanguageProtocol.ts'; import type { ExtensionActivation, ExtensionId } from './extensions.ts'; export type RpcMessage = @@ -207,6 +208,9 @@ export interface HostInitData { readonly version: string; }; readonly isDevelopment: boolean; + /** #260: the editor's open documents (absolute paths) and its active editor when the host starts. */ + readonly documents: readonly { readonly path: string; readonly languageId: string; readonly version: number; readonly text: string }[]; + readonly activeEditor: EditorStateData | null; } export const HOST_METHODS = { @@ -224,6 +228,10 @@ export const HOST_METHODS = { trustChanged: 'trustChanged', /** () -> void. Deactivates every extension, then the host exits. */ shutdown: 'shutdown', + /** #260 (DocumentEvent[]) notification: the editor's documents and active editor changed (absolute paths). */ + documents: 'documents', + /** #260 (ProvideRequest) -> the provider's answer as plain data (extensionLanguageProtocol.ts). */ + provide: 'provide', } as const; /* ------------------------------------------------------------------ */ @@ -274,6 +282,12 @@ export const MAIN_METHODS = { ui: 'ui', /** (UiNotification) notification: status bar items, progress, status messages. */ uiNotify: 'uiNotify', + /** #260 (DiagnosticsUpdate) notification, absolute paths. */ + diagnostics: 'diagnostics', + /** #260 (ProviderRegistration) notification. */ + registerProvider: 'registerProvider', + /** #260 (handle) notification. */ + unregisterProvider: 'unregisterProvider', } as const; /* ------------------------------------------------------------------ */ @@ -310,7 +324,13 @@ export type UiRequest = | { readonly kind: 'inputBox'; readonly extensionId: ExtensionId; readonly value?: string; readonly prompt?: string; readonly placeHolder?: string; readonly title?: string; readonly password: boolean } | { readonly kind: 'openFile'; readonly path: string; readonly line?: number; readonly column?: number; readonly preview: boolean } /** A command no extension registered: the workbench's own, or a built-in `vscode.*` one it maps. Args went through the host's wire format. */ - | { readonly kind: 'command'; readonly id: string; readonly args: readonly unknown[] }; + | { readonly kind: 'command'; readonly id: string; readonly args: readonly unknown[] } + /** #260: text edits for the editor's models (opening the files that are not open); answered with true when all applied. */ + | { readonly kind: 'applyEdit'; readonly edit: WorkspaceEditData } + /** #260: `TextDocument.save()` of a document the editor has open. */ + | { readonly kind: 'saveFile'; readonly path: string } + /** #260: `TextEditor.insertSnippet` on the active editor, at its selections or at `ranges`. */ + | { readonly kind: 'insertSnippet'; readonly path: string; readonly snippet: string; readonly ranges?: readonly RangeData[] }; export interface StatusBarItemData { /** Unique per host: `/`. */ @@ -334,7 +354,13 @@ export type UiNotification = | { readonly kind: 'progress'; readonly key: string; readonly title: string; readonly message?: string; readonly percent?: number } | { readonly kind: 'progressEnd'; readonly key: string } | { readonly kind: 'contextKey'; readonly key: string; readonly value: unknown } - | { readonly kind: 'hostStopped'; readonly reason: string }; + | { readonly kind: 'hostStopped'; readonly reason: string } + /** #260: language features. Paths are workspace paths by the time they reach the renderer. */ + | { readonly kind: 'diagnostics'; readonly update: DiagnosticsUpdate } + | { readonly kind: 'providerRegistered'; readonly registration: ProviderRegistration } + | { readonly kind: 'providerUnregistered'; readonly handle: number } + /** A host started or stopped: every provider and diagnostic of the previous one is gone. */ + | { readonly kind: 'providersReset' }; /** Main -> renderer: one UI request of the host (answer with `extensionsHostReply`), or a notification. */ export type HostUiEvent = diff --git a/apps/ide/src/shared/extensionLanguageProtocol.ts b/apps/ide/src/shared/extensionLanguageProtocol.ts new file mode 100644 index 00000000..6b6a2682 --- /dev/null +++ b/apps/ide/src/shared/extensionLanguageProtocol.ts @@ -0,0 +1,384 @@ +/** + * The editor's documents and the language features of extensions (#260): + * what the renderer tells the extension host about the open files and the + * active editor, and what crosses back from the providers extensions + * register (hover, completion, definitions, diagnostics, edits...). + * + * Positions and ranges are 0-based (VS Code's), never Monaco's 1-based ones: + * the renderer converts at its edge. A `path` field names a file: a + * workspace path (`src/a.ts`) between the renderer and the main process, an + * absolute path between the main process and the host. The main process + * rewrites every `path` field on the way through (`rewritePaths`) and drops + * whatever names a file outside the open folder, so the renderer never sees + * an absolute path and the host never gets one it did not ask about. + * + * Shared by main, the host and the renderer: no Node, Electron or DOM import. + */ + +import type { ExtensionId } from './extensions.ts'; + +/** `[line, character]`, 0-based. */ +export type PositionData = readonly [number, number]; +/** `[startLine, startCharacter, endLine, endCharacter]`, 0-based. */ +export type RangeData = readonly [number, number, number, number]; + +export interface TextChangeData { + readonly range: RangeData; + readonly text: string; +} + +export interface SelectionData { + readonly anchor: PositionData; + readonly active: PositionData; +} + +export interface EditorStateData { + readonly path: string; + readonly selections: readonly SelectionData[]; + readonly visibleRanges: readonly RangeData[]; + readonly tabSize: number; + readonly insertSpaces: boolean; +} + +/** What happened to a document of the editor, or to the active editor. */ +export type DocumentEvent = + | { readonly kind: 'open'; readonly path: string; readonly languageId: string; readonly version: number; readonly text: string } + /** The changes apply one after the other, each to the text the previous one left. */ + | { readonly kind: 'change'; readonly path: string; readonly version: number; readonly changes: readonly TextChangeData[] } + | { readonly kind: 'language'; readonly path: string; readonly languageId: string } + | { readonly kind: 'save'; readonly path: string } + | { readonly kind: 'close'; readonly path: string } + /** The active text editor (null: none, or not a file of the folder). */ + | { readonly kind: 'editor'; readonly editor: EditorStateData | null }; + +/** The most documents (and the largest text) the editor tells the host about, as VS Code's own limit does. */ +export const MAX_SYNCED_DOCUMENT_LENGTH = 50 * 1024 * 1024; +export const MAX_DOCUMENT_EVENTS = 5000; + +/* ------------------------------ diagnostics ------------------------------ */ + +/** VS Code's `DiagnosticSeverity`: Error 0, Warning 1, Information 2, Hint 3. */ +export interface DiagnosticData { + readonly range: RangeData; + readonly message: string; + readonly severity: number; + readonly source?: string; + readonly code?: string; + /** 1 unnecessary, 2 deprecated. */ + readonly tags?: readonly number[]; + readonly relatedInformation?: readonly { readonly path: string; readonly range: RangeData; readonly message: string }[]; +} + +export interface DiagnosticsUpdate { + /** The collection's owner: `:`. */ + readonly owner: string; + /** Files whose list changed; an empty list clears the file. */ + readonly entries: readonly { readonly path: string; readonly diagnostics: readonly DiagnosticData[] }[]; + /** The whole collection was cleared first (`clear()` or `dispose()`). */ + readonly clear?: boolean; +} + +/* ------------------------------ providers ------------------------------ */ + +export const PROVIDER_KINDS = [ + 'hover', 'completion', 'definition', 'declaration', 'typeDefinition', 'implementation', 'references', + 'documentSymbol', 'documentHighlight', 'signatureHelp', 'formatting', 'rangeFormatting', 'onTypeFormatting', + 'codeAction', 'codeLens', 'rename', 'foldingRange', 'inlayHints', 'documentLink', +] as const; +export type ProviderKind = (typeof PROVIDER_KINDS)[number]; + +export function isProviderKind(value: unknown): value is ProviderKind { + return typeof value === 'string' && (PROVIDER_KINDS as readonly string[]).includes(value); +} + +/** A `DocumentFilter`; `pattern` is a glob over the workspace path (`**` and `*`). */ +export interface DocumentFilterData { + readonly language?: string; + readonly scheme?: string; + readonly pattern?: string; +} + +export interface ProviderRegistration { + /** Unique per host. */ + readonly handle: number; + readonly kind: ProviderKind; + readonly extensionId: ExtensionId; + readonly selector: readonly DocumentFilterData[]; + readonly triggerCharacters?: readonly string[]; + readonly retriggerCharacters?: readonly string[]; + /** The display name (document symbols, code actions). */ + readonly label?: string; + /** Code actions: the kinds the provider offers. */ + readonly providedCodeActionKinds?: readonly string[]; + /** The provider resolves items lazily (completion items, code lenses). */ + readonly resolves?: boolean; +} + +/** The renderer asks a provider. `args` depend on the kind (see `ProvideArgs`). */ +export interface ProvideRequest { + readonly handle: number; + readonly kind: ProviderKind | 'resolveCompletion' | 'resolveCodeLens' | 'prepareRename'; + readonly path: string; + readonly args: ProvideArgs; +} + +export interface FormattingOptionsData { + readonly tabSize: number; + readonly insertSpaces: boolean; +} + +export interface ProvideArgs { + readonly position?: PositionData; + readonly range?: RangeData; + readonly triggerKind?: number; + readonly triggerCharacter?: string; + readonly options?: FormattingOptionsData; + readonly newName?: string; + readonly includeDeclaration?: boolean; + readonly only?: string; + readonly diagnostics?: readonly DiagnosticData[]; + /** A completion item or a code lens to resolve: from a previous result. */ + readonly cacheId?: number; + readonly index?: number; + readonly isRetrigger?: boolean; +} + +export interface CommandData { + readonly id: string; + readonly title: string; + readonly tooltip?: string; + /** In the host's wire format. */ + readonly args?: readonly unknown[]; +} + +export interface LocationData { + readonly path: string; + readonly range: RangeData; + /** A `LocationLink`'s origin. */ + readonly originRange?: RangeData; + readonly targetSelectionRange?: RangeData; +} + +export interface WorkspaceEditData { + readonly edits: readonly { readonly path: string; readonly edits: readonly TextChangeData[] }[]; +} + +export interface HoverData { + readonly contents: readonly string[]; + readonly range?: RangeData; +} + +export interface CompletionItemData { + readonly label: string | { readonly label: string; readonly detail?: string; readonly description?: string }; + /** VS Code's `CompletionItemKind`. */ + readonly kind?: number; + readonly tags?: readonly number[]; + readonly detail?: string; + readonly documentation?: string; + readonly sortText?: string; + readonly filterText?: string; + readonly preselect?: boolean; + readonly insertText?: string; + readonly isSnippet?: boolean; + readonly range?: RangeData | { readonly inserting: RangeData; readonly replacing: RangeData }; + readonly commitCharacters?: readonly string[]; + readonly additionalTextEdits?: readonly TextChangeData[]; + readonly command?: CommandData; +} + +export interface CompletionListData { + readonly items: readonly CompletionItemData[]; + readonly incomplete: boolean; + /** Resolve an item with this id and its index. */ + readonly cacheId?: number; +} + +export interface DocumentSymbolData { + readonly name: string; + readonly detail: string; + /** VS Code's `SymbolKind` (Monaco's has the same numbers). */ + readonly kind: number; + readonly range: RangeData; + readonly selectionRange: RangeData; + readonly children: readonly DocumentSymbolData[]; + readonly containerName?: string; + readonly tags?: readonly number[]; +} + +export interface SignatureHelpData { + readonly signatures: readonly { + readonly label: string; + readonly documentation?: string; + readonly parameters: readonly { readonly label: string | readonly [number, number]; readonly documentation?: string }[]; + readonly activeParameter?: number; + }[]; + readonly activeSignature: number; + readonly activeParameter: number; +} + +export interface CodeActionData { + readonly title: string; + readonly kind?: string; + readonly isPreferred?: boolean; + readonly diagnostics?: readonly DiagnosticData[]; + readonly edit?: WorkspaceEditData; + readonly command?: CommandData; + readonly disabled?: string; +} + +export interface CodeLensData { + readonly range: RangeData; + readonly command?: CommandData; +} + +export interface CodeLensListData { + readonly lenses: readonly CodeLensData[]; + readonly cacheId?: number; +} + +export interface FoldingRangeData { + readonly start: number; + readonly end: number; + /** VS Code's `FoldingRangeKind`: 1 comment, 2 imports, 3 region. */ + readonly kind?: number; +} + +export interface InlayHintData { + readonly position: PositionData; + readonly label: string; + readonly kind?: number; + readonly tooltip?: string; + readonly paddingLeft?: boolean; + readonly paddingRight?: boolean; +} + +export interface DocumentLinkData { + readonly range: RangeData; + /** http, https or mailto only. */ + readonly url?: string; + readonly tooltip?: string; +} + +export interface RenameLocationData { + readonly range: RangeData; + readonly text: string; +} + +/* ------------------------------ helpers ------------------------------ */ + +/** `*` and `**` globs over a workspace path, as `DocumentFilter.pattern`; `{a,b}` alternatives too. */ +export function documentGlob(pattern: string): RegExp { + let source = ''; + for (let index = 0; index < pattern.length; index++) { + const char = pattern[index] as string; + if (char === '*') { + if (pattern[index + 1] === '*') { + index++; + if (pattern[index + 1] === '/') { + index++; + source += '(?:.*/)?'; + } else { + source += '.*'; + } + } else { + source += '[^/]*'; + } + } else if (char === '?') { + source += '[^/]'; + } else if (char === '{') { + const close = pattern.indexOf('}', index); + if (close === -1) { + source += '\\{'; + } else { + source += `(?:${pattern.slice(index + 1, close).split(',').map((part) => part.replace(/[.+^$()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')).join('|')})`; + index = close; + } + } else { + source += char.replace(/[.+^$()|[\]\\}]/g, '\\$&'); + } + } + return new RegExp(`^${source}$`); +} + +/** + * Whether a document matches a provider's selector, VS Code's way: a filter + * matches when every field it has matches. The renderer only follows files + * of the folder, whose scheme is `file`. + */ +export function selectorMatches(selector: readonly DocumentFilterData[], document: { readonly languageId: string; readonly path: string }): boolean { + return selector.some((filter) => { + if (filter.language !== undefined && filter.language !== '*' && filter.language !== document.languageId) { + return false; + } + if (filter.scheme !== undefined && filter.scheme !== '*' && filter.scheme !== 'file') { + return false; + } + if (filter.pattern !== undefined) { + const regex = documentGlob(filter.pattern); + if (!regex.test(document.path) && !documentGlob(`**/${filter.pattern}`).test(document.path)) { + return false; + } + } + return filter.language !== undefined || filter.scheme !== undefined || filter.pattern !== undefined; + }); +} + +/** Keys whose values are an extension's own data, never rewritten (command arguments). */ +const OPAQUE_KEYS = new Set(['args', 'command']); + +/** + * Rewrites every `path` field of `value` with `convert` (see the file's + * comment). An object whose path `convert` refuses (null) is dropped: from + * an array it is removed, elsewhere it becomes null. Command arguments are + * left alone. + */ +export function rewritePaths(value: unknown, convert: (path: string) => string | null): unknown { + if (Array.isArray(value)) { + const result: unknown[] = []; + for (const item of value) { + const rewritten = rewriteObject(item, convert); + if (rewritten !== DROPPED) { + result.push(rewritten); + } + } + return result; + } + const rewritten = rewriteObject(value, convert); + return rewritten === DROPPED ? null : rewritten; +} + +const DROPPED = Symbol('dropped'); + +function rewriteObject(value: unknown, convert: (path: string) => string | null): unknown { + if (Array.isArray(value)) { + return rewritePaths(value, convert); + } + if (typeof value !== 'object' || value === null || ArrayBuffer.isView(value)) { + return value; + } + const result: Record = {}; + for (const [key, item] of Object.entries(value as Record)) { + if (key === 'path' && typeof item === 'string') { + const converted = convert(item); + if (converted === null) { + return DROPPED; + } + result[key] = converted; + } else if (OPAQUE_KEYS.has(key)) { + result[key] = item; + } else { + const rewritten = rewriteObject(item, convert); + result[key] = rewritten === DROPPED ? null : rewritten; + } + } + return result; +} + +/** + * The completion kind's name in VS Code's enum, which Monaco also has (in a + * different order): the renderer maps through the name. + */ +export const COMPLETION_KIND_NAMES = [ + 'Text', 'Method', 'Function', 'Constructor', 'Field', 'Variable', 'Class', 'Interface', 'Module', 'Property', 'Unit', 'Value', 'Enum', + 'Keyword', 'Snippet', 'Color', 'File', 'Reference', 'Folder', 'EnumMember', 'Constant', 'Struct', 'Event', 'Operator', 'TypeParameter', 'User', 'Issue', +] as const; diff --git a/apps/ide/src/shared/extensions.ts b/apps/ide/src/shared/extensions.ts index fefaedc3..8842a8f6 100644 --- a/apps/ide/src/shared/extensions.ts +++ b/apps/ide/src/shared/extensions.ts @@ -10,6 +10,7 @@ */ import type { HostUiEvent } from './extensionHostProtocol.ts'; +import type { DocumentEvent, ProvideRequest } from './extensionLanguageProtocol.ts'; /** `publisher.name`, lower-cased: VS Code compares extension ids without case. */ export type ExtensionId = string; @@ -278,6 +279,10 @@ export interface ExtensionsApi { /** Answers a request of the host (`onHostUi`'s `request`), with its result or null when dismissed. */ hostReply(id: number, result: unknown): Promise; onHostUi(listener: (event: HostUiEvent) => void): () => void; + /** #260: the editor's documents and active editor changed (workspace paths). */ + documentEvents(events: readonly DocumentEvent[]): Promise; + /** #260: asks an extension's language feature provider; the answer is plain data (extensionLanguageProtocol.ts). */ + provide(request: ProvideRequest): Promise; } /** Activation events the renderer may fire (the others are the main process's or the host's own). */ @@ -304,6 +309,8 @@ export const EXTENSION_IPC_CHANNELS = { extensionsExecuteCommand: 'codexr:extensions:execute-command', extensionsActivateByEvent: 'codexr:extensions:activate-by-event', extensionsHostReply: 'codexr:extensions:host-reply', + extensionsDocuments: 'codexr:extensions:documents', + extensionsProvide: 'codexr:extensions:provide', } as const; export const EXTENSION_IPC_EVENTS = { diff --git a/apps/ide/test/extensionHost.test.ts b/apps/ide/test/extensionHost.test.ts index e72223b2..dc86654c 100644 --- a/apps/ide/test/extensionHost.test.ts +++ b/apps/ide/test/extensionHost.test.ts @@ -407,6 +407,8 @@ describe('the extension host process (#259)', () => { 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); }); diff --git a/apps/ide/test/extensionLanguages.test.ts b/apps/ide/test/extensionLanguages.test.ts new file mode 100644 index 00000000..4a6f8edf --- /dev/null +++ b/apps/ide/test/extensionLanguages.test.ts @@ -0,0 +1,393 @@ +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, type UiRequest } from '../src/shared/extensionHostProtocol.ts'; +import { + documentGlob, rewritePaths, selectorMatches, type CodeActionData, type CodeLensListData, type CompletionItemData, type CompletionListData, type DiagnosticsUpdate, + type DocumentSymbolData, type HoverData, type LocationData, type ProviderRegistration, +} from '../src/shared/extensionLanguageProtocol.ts'; +import { locationData, selectorData, workspaceEditData } from '../src/extensionHost/languageFeatures.ts'; +import { Location, Position, Range, RelativePattern, Uri, WorkspaceEdit } from '../src/extensionHost/types.ts'; +import { DocumentMirror, FolderPaths } from '../src/main/extensions/documentMirror.ts'; +import { changesOf, completionKindName, diagnosticSeverity, foldingKind, fromMonacoRange, markerSeverity, monacoLanguages, toMonacoRange } from '../src/renderer/extensions/languageBridgeModel.ts'; + +const HOST_ENTRY = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'extensionHost', 'index.ts'); + +let tmp = ''; +before(() => { + tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-lang-test-'))); +}); +after(() => { + fs.rmSync(tmp, { recursive: true, force: true }); +}); + +describe('language features: shared helpers (#260)', () => { + it('matches globs over workspace paths', () => { + assert.ok(documentGlob('**/*.ts').test('src/a.ts')); + assert.ok(documentGlob('**/*.ts').test('a.ts')); + assert.ok(!documentGlob('*.ts').test('src/a.ts')); + assert.ok(documentGlob('src/**').test('src/deep/a.md')); + assert.ok(documentGlob('**/*.{js,ts}').test('x/y.js')); + assert.ok(!documentGlob('**/*.{js,ts}').test('x/y.md')); + }); + + it('matches selectors the way VS Code does', () => { + const doc = { languageId: 'python', path: 'src/app.py' }; + assert.ok(selectorMatches([{ language: 'python' }], doc)); + assert.ok(!selectorMatches([{ language: 'go' }], doc)); + assert.ok(selectorMatches([{ language: 'python', scheme: 'file' }], doc)); + assert.ok(!selectorMatches([{ language: 'python', scheme: 'untitled' }], doc)); + assert.ok(selectorMatches([{ pattern: '**/*.py' }], doc)); + assert.ok(selectorMatches([{ pattern: '*.py' }], doc), 'a bare pattern matches at any depth'); + assert.ok(!selectorMatches([{ language: 'python', pattern: '**/*.txt' }], doc), 'every field of a filter must match'); + assert.ok(selectorMatches([{ language: '*' }], doc)); + assert.ok(!selectorMatches([], doc)); + assert.ok(!selectorMatches([{}], doc), 'an empty filter matches nothing'); + }); + + it('rewrites every path, drops what falls outside, and leaves command arguments alone', () => { + const value = { + locations: [{ path: '/w/a.ts', range: [0, 0, 0, 1] }, { path: '/elsewhere/b.ts', range: [0, 0, 0, 1] }], + command: { id: 'x', title: 'X', args: [{ path: '/elsewhere/keep' }] }, + nested: { path: '/elsewhere/c.ts' }, + }; + const rewritten = rewritePaths(value, (p) => (p.startsWith('/w/') ? p.slice(3) : null)) as Record; + assert.deepEqual(rewritten['locations'], [{ path: 'a.ts', range: [0, 0, 0, 1] }]); + assert.deepEqual(rewritten['command'], value.command); + assert.equal(rewritten['nested'], null); + assert.deepEqual(rewritePaths([{ path: '/elsewhere' }], () => null), []); + }); + + it('converts between Monaco and VS Code positions, kinds and severities', () => { + assert.deepEqual(toMonacoRange([0, 0, 2, 5]), { startLineNumber: 1, startColumn: 1, endLineNumber: 3, endColumn: 6 }); + assert.deepEqual(fromMonacoRange({ startLineNumber: 1, startColumn: 1, endLineNumber: 3, endColumn: 6 }), [0, 0, 2, 5]); + assert.deepEqual(changesOf([{ range: { startLineNumber: 2, startColumn: 3, endLineNumber: 2, endColumn: 3 }, text: 'x' }]), [{ range: [1, 2, 1, 2], text: 'x' }]); + assert.equal(completionKindName(0), 'Text'); + assert.equal(completionKindName(1), 'Method'); + assert.equal(completionKindName(14), 'Snippet'); + assert.equal(completionKindName(99), 'Text'); + assert.deepEqual([0, 1, 2, 3].map(markerSeverity), [8, 4, 2, 1]); + assert.deepEqual([8, 4, 2, 1].map(diagnosticSeverity), [0, 1, 2, 3]); + assert.deepEqual([1, 2, 3, undefined].map(foldingKind), ['comment', 'imports', 'region', undefined]); + assert.deepEqual(monacoLanguages([{ language: 'python' }, { language: 'python', scheme: 'file' }, { language: 'go' }]), ['python', 'go']); + assert.equal(monacoLanguages([{ pattern: '**/*.x' }]), null); + assert.deepEqual(monacoLanguages([{ scheme: 'untitled' }]), []); + }); + + it('turns selectors, locations and edits into plain data', () => { + const root = path.join(tmp, 'w'); + assert.deepEqual(selectorData(['python', { scheme: 'file', language: 'go' }, { notebookType: 'jupyter' }], root), [{ language: 'python' }, { scheme: 'file', language: 'go' }]); + assert.deepEqual(selectorData({ pattern: new RelativePattern(Uri.file(path.join(root, 'src')), '**/*.ts') }, root), [{ pattern: 'src/**/*.ts' }]); + assert.deepEqual(selectorData({ pattern: new RelativePattern(Uri.file(path.join(tmp, 'other')), '*.ts') }, root), []); + const file = Uri.file(path.join(root, 'a.ts')); + const loc = locationData([new Location(file, new Position(1, 2)), { targetUri: file, targetRange: new Range(0, 0, 3, 0), targetSelectionRange: new Range(0, 4, 0, 7) }, new Location(Uri.parse('untitled:x'), new Position(0, 0))]); + assert.deepEqual(loc, [ + { path: file.fsPath, range: [1, 2, 1, 2] }, + { path: file.fsPath, range: [0, 0, 3, 0], targetSelectionRange: [0, 4, 0, 7] }, + ]); + const edit = new WorkspaceEdit(); + edit.replace(file, new Range(0, 0, 0, 1), 'X'); + edit.insert(file, new Position(2, 0), 'Y'); + assert.deepEqual(workspaceEditData(edit), { edits: [{ path: file.fsPath, edits: [{ range: [0, 0, 0, 1], text: 'X' }, { range: [2, 0, 2, 0], text: 'Y' }] }] }); + }); +}); + +describe('the main process copy of the editor documents (#260)', () => { + it('follows open, change and close, with absolute paths for the host', () => { + const root = path.join(tmp, 'mirror'); + fs.mkdirSync(root, { recursive: true }); + const paths = new FolderPaths(root); + const mirror = new DocumentMirror(); + const opened = mirror.accept([{ kind: 'open', path: 'src/a.ts', languageId: 'typescript', version: 1, text: 'let a = 1;\n' }], paths); + assert.deepEqual(opened, [{ kind: 'open', path: path.join(root, 'src', 'a.ts'), languageId: 'typescript', version: 1, text: 'let a = 1;\n' }]); + mirror.accept([ + { kind: 'change', path: 'src/a.ts', version: 2, changes: [{ range: [0, 4, 0, 5], text: 'b' }] }, + { kind: 'editor', editor: { path: 'src/a.ts', selections: [{ anchor: [0, 0], active: [0, 3] }], visibleRanges: [[0, 0, 1, 0]], tabSize: 2, insertSpaces: true } }, + ], paths); + const snapshot = mirror.snapshot(paths); + assert.equal(snapshot.documents[0]?.text, 'let b = 1;\n'); + assert.equal(snapshot.documents[0]?.version, 2); + assert.equal(snapshot.activeEditor?.path, path.join(root, 'src', 'a.ts')); + assert.equal(snapshot.activeEditor?.tabSize, 2); + assert.deepEqual(mirror.accept([{ kind: 'close', path: 'src/a.ts' }], paths), [{ kind: 'close', path: path.join(root, 'src', 'a.ts') }]); + assert.deepEqual(mirror.snapshot(paths), { documents: [], activeEditor: null }); + }); + + it('drops what the renderer should not send', () => { + const paths = new FolderPaths(path.join(tmp, 'mirror')); + const mirror = new DocumentMirror(); + const events = mirror.accept([ + { kind: 'open', path: '../outside.txt', languageId: 'plaintext', version: 1, text: 'x' }, + { kind: 'open', path: '/etc/passwd', languageId: 'plaintext', version: 1, text: 'x' }, + { kind: 'change', path: 'never-opened.txt', version: 2, changes: [] }, + { kind: 'open', path: 'ok.txt', languageId: '', version: 1, text: 'x' }, + { kind: 'open', path: 'ok.txt', languageId: 'plaintext', version: -1, text: 'x' }, + { kind: 'editor', editor: { path: 'not-open.txt', selections: [], visibleRanges: [], tabSize: 4, insertSpaces: true } }, + 'junk', + ], paths); + assert.deepEqual(events, [{ kind: 'editor', editor: null }]); + assert.equal(paths.toWorkspace(path.join(tmp, 'elsewhere', 'a.txt')), null); + assert.equal(paths.toWorkspace(path.join(tmp, 'mirror', 'd', 'a.txt')), 'd/a.txt'); + }); +}); + +const LANG_JS = String.raw` +const vscode = require('vscode'); +exports.activate = function (context) { + const selector = { language: 'plaintext', scheme: 'file' }; + const diagnostics = vscode.languages.createDiagnosticCollection('todo'); + const seen = { opened: [], changed: 0, active: [] }; + const lint = (doc) => { + if (doc.languageId !== 'plaintext') return; + const list = []; + doc.getText().split('\n').forEach((line, i) => { + const at = line.indexOf('TODO'); + if (at >= 0) { + const d = new vscode.Diagnostic(new vscode.Range(i, at, i, at + 4), 'A TODO is left', vscode.DiagnosticSeverity.Warning); + d.source = 'todo'; + list.push(d); + } + }); + diagnostics.set(doc.uri, list); + }; + vscode.workspace.textDocuments.forEach(lint); + context.subscriptions.push( + vscode.workspace.onDidOpenTextDocument((doc) => { seen.opened.push(vscode.workspace.asRelativePath(doc.uri)); lint(doc); }), + vscode.workspace.onDidChangeTextDocument((event) => { seen.changed++; lint(event.document); }), + vscode.window.onDidChangeActiveTextEditor((editor) => seen.active.push(editor ? vscode.workspace.asRelativePath(editor.document.uri) : null)), + vscode.languages.registerHoverProvider(selector, { + provideHover(doc, position) { + const range = doc.getWordRangeAtPosition(position); + return range ? new vscode.Hover(new vscode.MarkdownString('**' + doc.getText(range) + '**'), range) : undefined; + }, + }), + vscode.languages.registerCompletionItemProvider(selector, { + provideCompletionItems() { + const item = new vscode.CompletionItem('hello', vscode.CompletionItemKind.Keyword); + item.insertText = new vscode.SnippetString('hello \${1:name}'); + return [item, new vscode.CompletionItem('world')]; + }, + resolveCompletionItem(item) { + item.documentation = new vscode.MarkdownString('Says *hello*'); + return item; + }, + }, '.'), + vscode.languages.registerDefinitionProvider(selector, { + provideDefinition(doc) { return new vscode.Location(doc.uri, new vscode.Position(0, 0)); }, + }), + vscode.languages.registerDocumentSymbolProvider(selector, { + provideDocumentSymbols() { + const symbol = new vscode.DocumentSymbol('Top', 'detail', vscode.SymbolKind.Class, new vscode.Range(0, 0, 1, 0), new vscode.Range(0, 0, 0, 3)); + symbol.children.push(new vscode.DocumentSymbol('inner', '', vscode.SymbolKind.Method, new vscode.Range(1, 0, 1, 2), new vscode.Range(1, 0, 1, 2))); + return [symbol]; + }, + }), + vscode.languages.registerCodeActionsProvider(selector, { + provideCodeActions(doc, range, context) { + return context.diagnostics.filter((d) => d.source === 'todo').map((d) => { + const action = new vscode.CodeAction('Mark as DONE', vscode.CodeActionKind.QuickFix); + action.edit = new vscode.WorkspaceEdit(); + action.edit.replace(doc.uri, d.range, 'DONE'); + action.diagnostics = [d]; + return action; + }); + }, + }, { providedCodeActionKinds: [vscode.CodeActionKind.QuickFix] }), + vscode.languages.registerCodeLensProvider(selector, { + provideCodeLenses() { return [new vscode.CodeLens(new vscode.Range(0, 0, 0, 0))]; }, + resolveCodeLens(lens) { lens.command = { command: 'lang.state', title: 'Show state', arguments: [1] }; return lens; }, + }), + vscode.commands.registerCommand('lang.state', () => { + const editor = vscode.window.activeTextEditor; + return { + seen, + active: editor ? vscode.workspace.asRelativePath(editor.document.uri) : null, + selection: editor ? [editor.selection.active.line, editor.selection.active.character] : null, + texts: vscode.workspace.textDocuments.map((doc) => vscode.workspace.asRelativePath(doc.uri) + '@' + doc.version + ':' + doc.getText()), + diagnostics: vscode.languages.getDiagnostics().map(([uri, list]) => vscode.workspace.asRelativePath(uri) + ':' + list.length), + }; + }), + vscode.commands.registerTextEditorCommand('lang.shout', (editor, edit) => { + edit.replace(new vscode.Range(0, 0, 0, 3), editor.document.getText(new vscode.Range(0, 0, 0, 3)).toUpperCase()); + }), + vscode.commands.registerCommand('lang.apply', () => { + const edit = new vscode.WorkspaceEdit(); + edit.insert(vscode.window.activeTextEditor.document.uri, new vscode.Position(0, 0), '>> '); + return vscode.workspace.applyEdit(edit); + }), + vscode.commands.registerCommand('lang.save', () => vscode.window.activeTextEditor.document.save()), + ); +}; +`; + +describe('language features in the extension host (#260)', () => { + let child: ChildProcess; + let main: RpcEndpoint; + const ui: UiRequest[] = []; + const registrations: ProviderRegistration[] = []; + const diagnostics: DiagnosticsUpdate[] = []; + let workspace = ''; + let file = ''; + + const waitFor = async (probe: () => T | undefined, what: string): Promise => { + for (let attempt = 0; attempt < 100; attempt++) { + const value = probe(); + if (value !== undefined) { + return value; + } + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error(`Timed out waiting for ${what}`); + }; + const handleOf = (kind: string): number => { + const found = registrations.find((registration) => registration.kind === kind); + assert.ok(found, `a ${kind} provider`); + return found.handle; + }; + + before(async () => { + workspace = path.join(tmp, 'lang-ws'); + fs.mkdirSync(workspace, { recursive: true }); + // In `Uri.fsPath`'s spelling (a lower-case drive letter on Windows), the one the host answers with. + file = Uri.file(path.join(workspace, 'notes.txt')).fsPath; + const extensionFolder = path.join(tmp, 'extensions', 'acme.lang-1.0.0'); + fs.mkdirSync(extensionFolder, { recursive: true }); + const packageJSON = { publisher: 'acme', name: 'lang', version: '1.0.0', main: 'index.js', engines: { vscode: '^1.80.0' }, activationEvents: ['*'] }; + fs.writeFileSync(path.join(extensionFolder, 'package.json'), JSON.stringify(packageJSON)); + fs.writeFileSync(path.join(extensionFolder, 'index.js'), LANG_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)); + main.handle(MAIN_METHODS.log, () => undefined); + main.handle(MAIN_METHODS.activation, () => undefined); + main.handle(MAIN_METHODS.notImplemented, () => undefined); + main.handle(MAIN_METHODS.uiNotify, () => undefined); + main.handle(MAIN_METHODS.registerProvider, (registration) => registrations.push(registration as ProviderRegistration)); + main.handle(MAIN_METHODS.diagnostics, (update) => diagnostics.push(update as DiagnosticsUpdate)); + main.handle(MAIN_METHODS.ui, (request) => { + const typed = request as UiRequest; + ui.push(typed); + if (typed.kind === 'applyEdit') { + // What the editor does: apply the edit, then report the change before answering. + const entry = typed.edit.edits[0]; + main.notify(HOST_METHODS.documents, [{ kind: 'change', path: entry?.path, version: 10 + ui.length, changes: entry?.edits ?? [] }]); + return true; + } + if (typed.kind === 'saveFile') { + main.notify(HOST_METHODS.documents, [{ kind: 'save', path: typed.path }]); + return true; + } + return null; + }); + const init: HostInitData = { + extensions: [{ id: 'acme.lang', location: extensionFolder, main: 'index.js', packageJSON, activationEvents: ['*'], extensionDependencies: [] }], + passive: [], + workspaceFolder: workspace, + trusted: true, + configuration: {}, + globalStorageRoot: path.join(tmp, 'lang-storage'), + workspaceStorageRoot: null, + logRoot: path.join(tmp, 'lang-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: [{ path: file, languageId: 'plaintext', version: 1, text: 'one TODO here\nsecond line\n' }], + activeEditor: { path: file, selections: [{ anchor: [0, 0], active: [0, 0] }], visibleRanges: [], tabSize: 4, insertSpaces: true }, + }; + await main.request(HOST_METHODS.init, init); + await main.request(HOST_METHODS.activateByEvent, '*'); + }); + + after(() => { + if (child.exitCode === null) { + child.kill(); + } + }); + + it('announces each provider with its selector and trigger characters', () => { + assert.deepEqual(registrations.map((registration) => registration.kind), ['hover', 'completion', 'definition', 'documentSymbol', 'codeAction', 'codeLens']); + const completion = registrations.find((registration) => registration.kind === 'completion'); + assert.deepEqual(completion?.selector, [{ language: 'plaintext', scheme: 'file' }]); + assert.deepEqual(completion?.triggerCharacters, ['.']); + assert.equal(completion?.resolves, true); + assert.deepEqual(registrations.find((registration) => registration.kind === 'codeAction')?.providedCodeActionKinds, ['quickfix']); + }); + + it('sees the documents the editor had open when it started, and their diagnostics', async () => { + const update = await waitFor(() => diagnostics[0], 'diagnostics'); + assert.equal(update.owner, 'acme.lang:todo'); + assert.deepEqual(update.entries, [{ path: file, diagnostics: [{ range: [0, 4, 0, 8], message: 'A TODO is left', severity: 1, source: 'todo' }] }]); + const state = await main.request>(HOST_METHODS.executeCommand, 'lang.state', []); + assert.equal(state['active'], 'notes.txt'); + assert.deepEqual(state['texts'], ['notes.txt@1:one TODO here\nsecond line\n']); + assert.deepEqual(state['diagnostics'], ['notes.txt:1']); + }); + + it('answers hover, completion (and its resolve), definition, symbols, code actions and lenses', async () => { + const provide = (kind: string, args: Record, requestKind = kind): Promise => main.request(HOST_METHODS.provide, { handle: handleOf(kind), kind: requestKind, path: file, args }); + assert.deepEqual(await provide('hover', { position: [0, 5] }), { contents: ['**TODO**'], range: [0, 4, 0, 8] }); + const list = await provide('completion', { position: [1, 0], triggerKind: 0 }); + assert.deepEqual(list.items.map((item) => [item.label, item.kind, item.insertText, item.isSnippet]), [['hello', 13, 'hello ${1:name}', true], ['world', undefined, undefined, undefined]]); + assert.equal(typeof list.cacheId, 'number'); + const resolved = await main.request(HOST_METHODS.provide, { handle: handleOf('completion'), kind: 'resolveCompletion', path: file, args: { cacheId: list.cacheId, index: 0 } }); + assert.equal(resolved.documentation, 'Says *hello*'); + assert.deepEqual(await provide('definition', { position: [1, 1] }), [{ path: file, range: [0, 0, 0, 0] }]); + const symbols = await provide('documentSymbol', {}); + assert.equal(symbols[0]?.name, 'Top'); + assert.equal(symbols[0]?.children[0]?.name, 'inner'); + const actions = await provide('codeAction', { range: [0, 4, 0, 8], diagnostics: [{ range: [0, 4, 0, 8], message: 'A TODO is left', severity: 1, source: 'todo' }], triggerKind: 1 }); + assert.equal(actions[0]?.title, 'Mark as DONE'); + assert.equal(actions[0]?.kind, 'quickfix'); + assert.deepEqual(actions[0]?.edit, { edits: [{ path: file, edits: [{ range: [0, 4, 0, 8], text: 'DONE' }] }] }); + const lenses = await provide('codeLens', {}); + assert.equal(lenses.lenses[0]?.command, undefined); + const lens = await main.request<{ command?: { id: string; args?: unknown[] } }>(HOST_METHODS.provide, { handle: handleOf('codeLens'), kind: 'resolveCodeLens', path: file, args: { cacheId: lenses.cacheId, index: 0 } }); + assert.deepEqual(lens.command, { id: 'lang.state', title: 'Show state', args: [1] }); + assert.equal(await main.request(HOST_METHODS.provide, { handle: 999, kind: 'hover', path: file, args: {} }), null, 'an unknown provider answers nothing'); + }); + + it('applies the editor changes in order and fires the events, diagnostics included', async () => { + const before = diagnostics.length; + main.notify(HOST_METHODS.documents, [ + { kind: 'change', path: file, version: 2, changes: [{ range: [0, 4, 0, 8], text: 'DONE' }, { range: [1, 0, 1, 0], text: 'TODO ' }] }, + { kind: 'editor', editor: { path: file, selections: [{ anchor: [1, 2], active: [1, 3] }], visibleRanges: [], tabSize: 4, insertSpaces: true } }, + ]); + const update = await waitFor(() => diagnostics[before], 'new diagnostics'); + assert.deepEqual(update.entries[0]?.diagnostics.map((diagnostic) => diagnostic.range), [[1, 0, 1, 4]]); + const state = await main.request<{ texts: string[]; selection: number[]; seen: { changed: number } }>(HOST_METHODS.executeCommand, 'lang.state', []); + assert.deepEqual(state.texts, ['notes.txt@2:one DONE here\nTODO second line\n']); + assert.deepEqual(state.selection, [1, 3]); + assert.equal(state.seen.changed, 1); + }); + + it('edits through the workbench: TextEditor.edit, workspace.applyEdit, save', async () => { + assert.equal(await main.request(HOST_METHODS.executeCommand, 'lang.shout', []), true); + const shout = ui.find((request) => request.kind === 'applyEdit'); + assert.ok(shout && shout.kind === 'applyEdit'); + assert.deepEqual(shout.edit, { edits: [{ path: file, edits: [{ range: [0, 0, 0, 3], text: 'ONE' }] }] }); + assert.equal(await main.request(HOST_METHODS.executeCommand, 'lang.apply', []), true); + const state = await main.request<{ texts: string[] }>(HOST_METHODS.executeCommand, 'lang.state', []); + assert.match(state.texts[0] ?? '', /^notes\.txt@\d+:>> ONE DONE here/); + assert.equal(await main.request(HOST_METHODS.executeCommand, 'lang.save', []), true); + assert.ok(ui.some((request) => request.kind === 'saveFile' && request.path === file)); + }); + + it('closes documents, clears the active editor, and opens new ones', async () => { + const other = path.join(workspace, 'b.txt'); + main.notify(HOST_METHODS.documents, [ + { kind: 'close', path: file }, + { kind: 'open', path: other, languageId: 'plaintext', version: 1, text: 'TODO' }, + { kind: 'editor', editor: { path: other, selections: [], visibleRanges: [], tabSize: 4, insertSpaces: true } }, + ]); + const state = await main.request<{ active: string | null; texts: string[]; seen: { opened: string[]; active: (string | null)[] } }>(HOST_METHODS.executeCommand, 'lang.state', []); + assert.equal(state.active, 'b.txt'); + assert.deepEqual(state.texts, ['b.txt@1:TODO']); + assert.deepEqual(state.seen.opened, ['b.txt']); + assert.deepEqual(state.seen.active, [null, 'b.txt']); + }); +}); diff --git a/docs/ide/extensions.md b/docs/ide/extensions.md index a656ae21..288f900d 100644 --- a/docs/ide/extensions.md +++ b/docs/ide/extensions.md @@ -12,7 +12,7 @@ Epic #251. Decision: [ADR 0002](../../adr/0002-vscode-extensions-in-the-ide.md). | Colour themes (JSON, JSON with comments, `include` chains, `.tmTheme`) | Done | #257 | | Languages, `language-configuration.json`, TextMate grammars (with injections and embedded languages), snippets | Done | #258 | | Extensions with code: the extension host, commands in the palette, messages, quick picks and input boxes, progress, status bar items, output channels, configuration, state and secrets, files and `findFiles` | Done | #259 | -| Documents of the editor, diagnostics, language features (completion, hover, definitions...) | Next | #260 | +| Documents of the editor, the active editor, diagnostics, language features (completion, hover, definitions, references, symbols, signature help, formatting, code actions, code lenses, rename, folding, inlay hints, links), `applyEdit`, language clients (`vscode-languageclient`) | Done | #260 | | Tree views, view containers, webviews | Planned | #261 | | The Code-XR extension itself | Planned | #262 | | File icon themes, product icon themes | Not yet: listed in the details page | — | @@ -28,6 +28,8 @@ extensions/contributionsController.ts ├─ extensionStore.ts ------------> extensions/monacoContributions.ts ├─ vsix.ts (yauzl) .-/ extensions/textmate.ts (+ onig.wasm) ├─ openVsx.ts ---- https ----> Open VSX registry extensions/hostBridge.ts <--IPC--> ├─ contributions.ts (themes, grammars, snippets, commands) +extensions/documentSync.ts ├─ documentMirror.ts (the editor's documents, checked) +extensions/languageBridge.ts │ ├─ manifest.ts, plist.ts (pure) └─ extensionHostManager.ts settings.json, secrets.json, │ fork, Node IPC .storage/, .logs/, machine-id @@ -62,6 +64,24 @@ The main process reads the files the manifest names, always through `resolveInEx - **Extension settings** live in `/extensions/settings.json` (JSON with comments, editable by hand), apart from the IDE's own settings, whose schema only knows the IDE's keys. - **Palette.** Each enabled extension's `contributes.commands` appear in the palette (*Category: Title*), except those `menus.commandPalette` hides with `"when": "false"`. `when` clauses and `contributes.keybindings` are not applied yet. +## Documents and language features (#260) + +``` +Monaco model (codexr-file:/src/a.py) main process extension host + documentSync.ts -- open/change/close, active editor --> documentMirror.ts -- absolute paths --> documents.ts + languageBridge.ts <-- providerRegistered / diagnostics -- (paths rewritten) <-- languageFeatures.ts + Monaco provider -- provide(handle, path, position) --> --> the extension's provider +``` + +- **Documents.** Every Monaco model of a file of the folder is announced to the host when it opens, each content change as Monaco reports it (applied in order, so the host's text is the editor's, unsaved edits included), its language changes, saves and closing. The host keeps one `TextDocument` per open file for every extension (`workspace.textDocuments`, `onDidOpen/Change/Save/CloseTextDocument`). The main process keeps a checked copy (`documentMirror.ts`: paths through the workspace rules, ranges and sizes bounded, documents over 50 MB not followed), so a host that starts or restarts later is handed the open documents before any extension activates. +- **Active editor.** `window.activeTextEditor` is the editor last focused or switched to, with its selections, visible ranges and indentation (`onDidChangeActiveTextEditor`, `onDidChangeTextEditorSelection`, `onDidChangeTextEditorVisibleRanges`). `window.tabGroups` lists the open documents as one group of text tabs (language clients use it to know which documents to pull diagnostics for). +- **Edits.** `TextEditor.edit`, `registerTextEditorCommand`, `workspace.applyEdit` and `TextEditor.insertSnippet` go through the workbench: each file's edits are one undoable step in its model (a file that is not open is opened first), and the change comes back to the host before `applyEdit` resolves. File operations in a `WorkspaceEdit` (create, delete, rename) are done by the host on disk first. An edit that names a file outside the folder is refused whole. `TextDocument.save()` saves through the editor. +- **Language features.** Each `languages.register*Provider` is announced to the workbench, which registers a Monaco provider of the same kind for the selector's languages; when Monaco asks, it sends the document's path and position, the host calls the extension's provider and answers with plain data (`shared/extensionLanguageProtocol.ts`). Supported: hover, completion (with `resolveCompletionItem`, snippets, commands), definition, declaration, type definition, implementation, references, document symbols, document highlights, signature help, document/range/on-type formatting, code actions (edits and commands; *Quick Fix* on a diagnostic), code lenses (with `resolveCodeLens`), rename (with `prepareRename`), folding ranges, inlay hints and document links (http, https, mailto). Commands of code actions, lenses and completion items run in the host. +- **Diagnostics.** `languages.createDiagnosticCollection` sends its changes, batched per turn, as Monaco markers of owner `ext::`, so they show as squiggles and in the Problems panel like the IDE's own; diagnostics of files that are not open are kept and appear when the file opens. `languages.getDiagnostics` and `onDidChangeDiagnostics` work across the extensions. +- **Language clients.** Extensions built on `vscode-languageclient` (most language extensions) start their server as a child process of the host and work through the above: checked with Microsoft's *lsp-sample* (pull diagnostics while typing, completion). +- **Paths.** The renderer only ever names workspace paths; the main process turns them into absolute paths for the host and every `path` in the host's answers back, dropping whatever points outside the folder. +- **Not yet.** Decorations (`setDecorations`), semantic tokens (the TextMate grammars colour the code), call and type hierarchies, inline completions, colour pickers, selection ranges, linked editing and workspace symbols are accepted and reported in the *Extensions* output as missing; `when` clauses do not filter code actions. + ## Security - CSP: `script-src 'self' 'wasm-unsafe-eval'` (WebAssembly only; `eval` and `new Function` stay blocked, which the smoke run checks). @@ -79,6 +99,6 @@ The main process reads the files the manifest names, always through `resolveInEx 5. Disable or uninstall from the row; the theme falls back to the OS one. 6. Extensions with code: trust the folder, install an extension with commands (for example a `.vsix` of one of Microsoft's [extension samples](https://github.com/microsoft/vscode-extension-samples), or anything from Open VSX), then run its commands from the palette (F1). Messages, pickers, progress and status bar items appear in the workbench; *View: Output* > *Extensions* shows what each extension logs and the API it is missing. -The unit tests are `apps/ide/test/extensions.test.ts` (manifest, VSIX reader with zip-slip and symlink archives, store, contributions, Open VSX client against a fake registry), `apps/ide/test/extensionsRenderer.test.ts` (theme conversion, language configuration, the view model) and `apps/ide/test/extensionHost.test.ts` (the RPC, the API's values, configuration, documents, and a real host process running three test extensions: activation by event, by command and through dependencies, a failed activation, messages, configuration writes, state on disk, workbench commands, missing API, `findFiles`, `deactivate`). +The unit tests are `apps/ide/test/extensions.test.ts` (manifest, VSIX reader with zip-slip and symlink archives, store, contributions, Open VSX client against a fake registry), `apps/ide/test/extensionsRenderer.test.ts` (theme conversion, language configuration, the view model) `apps/ide/test/extensionHost.test.ts` (the RPC, the API's values, configuration, documents, and a real host process running three test extensions: activation by event, by command and through dependencies, a failed activation, messages, configuration writes, state on disk, workbench commands, missing API, `findFiles`, `deactivate`) and `apps/ide/test/extensionLanguages.test.ts` (#260: selectors and globs, path rewriting, the Monaco conversions, the main process's document copy refusing bad input, and a real host running a language extension: documents at start-up, diagnostics, hover, completion and its resolve, definition, symbols, code actions, code lenses, changes in order, the active editor, `TextEditor.edit`, `applyEdit` and save). -Checked in the real IDE (Electron under xvfb) with five of Microsoft's extension samples compiled from source: *helloworld-minimal* (palette command and message), *progress* (`*` activation, progress notification), *statusbar* (status bar item), *configuration* (two quick picks, then `getConfiguration().update`) and *quickinput* (`showQuickPick` and its follow-up messages). +Checked in the real IDE (Electron under xvfb) with six of Microsoft's extension samples compiled from source: *helloworld-minimal* (palette command and message), *progress* (`*` activation, progress notification), *statusbar* (status bar item), *configuration* (two quick picks, then `getConfiguration().update`), *quickinput* (`showQuickPick` and its follow-up messages) and *lsp-sample* (a `vscode-languageclient` extension with its language server: diagnostics in the editor and the Problems panel, updated while typing, and completion).