================ CODE SNIPPETS ================ TITLE: Scaffold Theia Monorepo with Yeoman Generator DESCRIPTION: This snippet shows the commands to install the Yeoman generator for Theia extensions and use it to scaffold a new Theia monorepo project, including a 'Hello World' example extension. It sets up the basic directory structure and prompts for configuration. SOURCE: https://theia-ide.org/docs/composing_applications LANGUAGE: Shell CODE: ``` npm install -g yo generator-theia-extension mkdir my-theia-app cd my-theia-app yo theia-extension # select the 'Hello World' option and complete the prompts ``` -------------------------------- TITLE: Build and Start Theia Electron Application DESCRIPTION: These commands are used to build and then start the Theia application configured for the Electron desktop environment. `yarn build:electron` compiles the application, and `yarn start:electron` launches the desktop application. SOURCE: https://theia-ide.org/docs/composing_applications LANGUAGE: bash CODE: ``` yarn build:electron yarn start:electron ``` -------------------------------- TITLE: Build and Start Theia Browser Application DESCRIPTION: These commands are used to build and then start the Theia application configured for the browser environment. `yarn build:browser` compiles the application, and `yarn start:browser` launches it, typically accessible via `http://localhost:3000`. SOURCE: https://theia-ide.org/docs/composing_applications LANGUAGE: bash CODE: ``` yarn build:browser yarn start:browser ``` -------------------------------- TITLE: Using onStart for Actions on Every Application Startup DESCRIPTION: This example illustrates how to use the `onStart` method of `FrontendApplicationContribution` to execute logic every time the application starts, regardless of stored layout state. It also demonstrates injecting `FrontendApplicationStateService` to wait for the application to reach a 'ready' state before performing actions like opening a view. SOURCE: https://theia-ide.org/docs/frontend_application_contribution LANGUAGE: TypeScript CODE: ``` @injectable() export class MyViewContribution extends AbstractViewContribution implements FrontendApplicationContribution { … @inject(FrontendApplicationStateService) protected readonly stateService: FrontendApplicationStateService; … async onStart(app: FrontendApplication): Promise { this.stateService.reachedState('ready').then( () => this.openView({ reveal: true }) ); } } ``` -------------------------------- TITLE: Configure Theia Browser Application package.json DESCRIPTION: This `package.json` defines a Theia browser application, specifying its name, version, dependencies (including core Theia modules and custom extensions like 'hello-world'), development dependencies, and scripts for bundling, rebuilding, starting, and watching. It targets the browser environment. SOURCE: https://theia-ide.org/docs/composing_applications LANGUAGE: json CODE: ``` { "private": true, "name": "browser-app", "version": "0.0.0", "dependencies": { "@theia/core": "latest", "@theia/editor": "latest", "@theia/filesystem": "latest", "@theia/markers": "latest", "@theia/messages": "latest", "@theia/monaco": "latest", "@theia/navigator": "latest", "@theia/preferences": "latest", "@theia/process": "latest", "@theia/terminal": "latest", "@theia/workspace": "latest", "hello-world": "0.0.0" }, "devDependencies": { "@theia/cli": "latest" }, "scripts": { "bundle": "yarn rebuild && theia build --mode development", "rebuild": "theia rebuild:browser --cacheRoot ..", "start": "theia start", "watch": "yarn rebuild && theia build --watch --mode development" }, "theia": { "target": "browser" } } ``` -------------------------------- TITLE: Run Yarn Install with Pre-Downloaded Node Headers DESCRIPTION: This command provides a workaround for `node-gyp` proxy issues by setting the `npm_config_tarball` environment variable to the local path of the manually downloaded Node.js headers, allowing `yarn install` to proceed successfully. SOURCE: https://theia-ide.org/docs/composing_applications LANGUAGE: Shell CODE: ``` npm_config_tarball=/path/to/node-v8.15.0-headers.tar.gz yarn install ``` -------------------------------- TITLE: Generate and Package a VS Code Hello World Extension DESCRIPTION: This snippet demonstrates how to install the necessary tools (VS Code Extension Generator and CLI tooling) and then use them to generate a basic 'Hello World' VS Code extension and package it into a .vsix file. It outlines the steps from setup to final packaging. SOURCE: https://theia-ide.org/docs/authoring_vscode_extensions LANGUAGE: shell CODE: ``` npm install -g yo generator-code # install the VS Code Extension Generator npm install -g vsce # install VS Code Extension CLI tooling yo code # generate an extension # take a look at the generated package.json defining a command "Hello World" # take a look at the src/extension.ts registering a command handler # make changes to the README and the code, if you like vsce package # package your VS Code extension ``` -------------------------------- TITLE: Root package.json Configuration for Theia Monorepo DESCRIPTION: This JSON snippet illustrates the root package.json file for a Theia monorepo, defining private status, engine requirements (yarn, node), build and start scripts for browser and Electron apps, development dependencies (lerna), and workspace definitions for the custom applications and extensions. SOURCE: https://theia-ide.org/docs/composing_applications LANGUAGE: JSON CODE: ``` { "private": true, "engines": { "yarn": ">=1.7.0 <2", "node": ">=18" }, "scripts": { "build:browser": "yarn --cwd browser-app bundle", "build:electron": "yarn --cwd electron-app bundle", "prepare": "lerna run prepare", "postinstall": "theia check:theia-version", "start:browser": "yarn --cwd browser-app start", "start:electron": "yarn --cwd electron-app start", "watch:browser": "lerna run --parallel watch --ignore electron-app", "watch:electron": "lerna run --parallel watch --ignore browser-app" }, "devDependencies": { "lerna": "2.4.0" }, "workspaces": [ "hello-world", "browser-app", "electron-app" ] } ``` -------------------------------- TITLE: Prompt Example for Using Tool Functions DESCRIPTION: This prompt snippet demonstrates how to reference available tool functions within an LLM request, allowing the agent to decide whether to use them. SOURCE: https://theia-ide.org/docs/theia_ai LANGUAGE: Prompt CODE: ``` Use the following functions to access the workspace: - ~{getWorkspaceFileList} - ~{getFileContent}. ``` -------------------------------- TITLE: Configure Theia Electron Application package.json Target DESCRIPTION: This snippet shows the key differences in the `package.json` for an Electron-based Theia application compared to a browser one. The `name` property is set to 'electron-app', and crucially, the `theia.target` property is set to 'electron' to specify the desktop environment. SOURCE: https://theia-ide.org/docs/composing_applications LANGUAGE: json CODE: ``` { "name": "electron-app", ... "theia": { "target": "electron" } } ``` -------------------------------- TITLE: TaskServer Client Setup and Return (TypeScript) DESCRIPTION: This function block is passed as a parameter to the `RpcConnectionHandler`. It retrieves the `TaskServer` instance from the container, sets the provided `client` (RPC proxy) on it for asynchronous notifications, and returns the `taskServer` itself to be exposed over RPC. SOURCE: https://theia-ide.org/docs/json_rpc LANGUAGE: TypeScript CODE: ``` client => { const taskServer = ctx.container.get(TaskServer); taskServer.setClient(client); return taskServer; } ``` -------------------------------- TITLE: Example Prompt Template Using Agent-Specific Variable DESCRIPTION: This example illustrates how an agent-specific variable, 'command-ids', can be embedded directly into a prompt template. The `{{command-ids}}` placeholder will be replaced with the resolved list of commands, enabling the LLM to access and utilize this information for tasks like identifying and executing commands within the IDE. SOURCE: https://theia-ide.org/docs/theia_ai LANGUAGE: text CODE: ``` You are a service that helps users find commands to execute in an IDE. These are the available commands: Begin List: {{command-ids}} End List ``` -------------------------------- TITLE: Example Theia Preferences JSON Configuration DESCRIPTION: This JSON snippet illustrates a sample `.theia/settings.json` file. It demonstrates how to set common preferences like Monaco editor line numbers and tab width, and how to exclude paths from the file system watcher. Comments are included to explain each setting. SOURCE: https://theia-ide.org/docs/preferences LANGUAGE: JSON CODE: ``` { // Enable/Disable the line numbers in the monaco editor "monaco.lineNumbers": "off", // Tab width in the editor "monaco.tabWidth": 4, "fs.watcherExcludes": "path/to/file" } ``` -------------------------------- TITLE: Implementing initializeLayout for Initial View Setup DESCRIPTION: This code shows how a `MyViewContribution` can implement the `initializeLayout` method from `FrontendApplicationContribution`. This method is invoked after the application shell layout is initialized, but only if no previously stored workbench layout exists, making it suitable for defining initial default layouts. SOURCE: https://theia-ide.org/docs/frontend_application_contribution LANGUAGE: TypeScript CODE: ``` @injectable() export class MyViewContribution extends AbstractViewContribution implements FrontendApplicationContribution { … async initializeLayout(app: FrontendApplication): Promise { await this.openView(); } … } ``` -------------------------------- TITLE: Configure HTTP GET Endpoint with Express.js DESCRIPTION: This snippet demonstrates how to define a basic HTTP GET endpoint using the Express.js framework. It shows a simple route definition for '/myendpoint' that can handle incoming requests. SOURCE: https://theia-ide.org/docs/backend_application_contribution LANGUAGE: JavaScript CODE: ``` app.get('/myendpoint', (request, response) => { … }); ``` -------------------------------- TITLE: Example: Bind Filesystem Preference Schema with Inversify DESCRIPTION: This example demonstrates how to implement the `PreferenceContribution` by defining a `filesystemPreferenceSchema` (a JSON schema) and then binding it using Inversify's `bind` method. This specific schema defines a `files.watcherExclude` property for excluding paths from the filesystem watcher, illustrating a practical application of the preference contribution mechanism. SOURCE: https://theia-ide.org/docs/preferences LANGUAGE: TypeScript CODE: ``` export const filesystemPreferenceSchema: PreferenceSchema = { "type": "object", "properties": { "files.watcherExclude": { "description": "List of paths to exclude from the filesystem watcher", "additionalProperties": { "type": "boolean" } } } }; bind(PreferenceContribution).toConstantValue( { schema: filesystemPreferenceSchema }); ``` -------------------------------- TITLE: Integrate Theia Plugins Location into package.json Startup Script DESCRIPTION: This `package.json` snippet illustrates how to embed the `--plugins` command-line option directly into the `start` script of a Theia browser or Electron application. This ensures that the plugins directory is automatically configured every time the application is launched. SOURCE: https://theia-ide.org/docs/authoring_vscode_extensions LANGUAGE: json CODE: ``` { ... "name": "browser-app", ... "scripts": { ... "start": "theia start --plugins=local-dir:../plugins" }, "theia": { "target": "browser" } } ``` -------------------------------- TITLE: Prompt Template for Structured Command Output DESCRIPTION: This prompt template instructs an LLM to respond with a stringified JSON object containing a Theia command ID and its arguments. It includes an example JSON structure and a placeholder for dynamically populated command IDs. SOURCE: https://theia-ide.org/docs/theia_ai LANGUAGE: Prompt CODE: ``` You are a service that helps users find commands to execute in an IDE. You reply with stringified JSON Objects that tell the user which command to execute and its arguments, if any. Example: ```json { "type": "theia-command", "commandId": "workbench.action.selectIconTheme" } ``` Here are the known Theia commands: Begin List: {{command-ids}} End List ``` -------------------------------- TITLE: Defining a System Prompt Template for Theia AI Chat Agent DESCRIPTION: This snippet demonstrates how to define a system prompt template for a Theia AI chat agent. The template acts as the foundational instruction set for guiding the agent's interaction with the Large Language Model (LLM), setting its initial behavior or persona. In this specific example, the agent is configured to always respond with a fixed test string. SOURCE: https://theia-ide.org/docs/theia_ai LANGUAGE: TypeScript CODE: ``` export const commandPromptTemplate: PromptTemplate = { id = 'command-chat-agent-system-prompt-template'; template = `Always respond with: “I am the command agent`; } ``` -------------------------------- TITLE: Configure Theia Plugins Location with Command Line Option DESCRIPTION: This snippet demonstrates how to set the plugins location when starting Theia using the `--plugins` command-line option. This allows Theia to load VS Code extensions from a specified directory during startup. SOURCE: https://theia-ide.org/docs/authoring_vscode_extensions LANGUAGE: shell CODE: ``` theia start --plugins=local-dir:../plugins ``` -------------------------------- TITLE: Configuring Custom HTTP Endpoint in Theia Backend DESCRIPTION: This partial code snippet demonstrates how to extend the Theia backend's HTTP server by adding a custom endpoint. It shows the necessary imports and the start of a class implementing `BackendApplicationContribution` to use the `configure` method for Express.js application setup. SOURCE: https://theia-ide.org/docs/backend_application_contribution LANGUAGE: TypeScript CODE: ``` import { injectable } from '@theia/core/shared/inversify'; import { json } from 'body-parser'; import { Application, Router } from '@theia/core/shared/express'; import { BackendApplicationContribution } from '@theia/core/lib/node/backend-application'; @injectable() export class MyCustomEndpoint implements BackendApplicationContribution { configure(app: Application): void { ``` -------------------------------- TITLE: Build and Package Theia IDE Desktop Applications DESCRIPTION: These shell commands, executed from the repository root, manage the lifecycle of a Theia IDE desktop application. They cover dependency installation, running the application for development, packaging into executables for the current OS, generating unpackaged content for preview, and deploying the current version. Packaging is typically OS-specific. SOURCE: https://theia-ide.org/docs/blueprint_documentation LANGUAGE: Shell CODE: ``` yarn ``` LANGUAGE: Shell CODE: ``` yarn electron start ``` LANGUAGE: Shell CODE: ``` yarn electron package ``` LANGUAGE: Shell CODE: ``` yarn electron package:preview ``` LANGUAGE: Shell CODE: ``` yarn electron deploy ``` -------------------------------- TITLE: Node-gyp Build Error Stack Behind Proxy DESCRIPTION: This code block shows the typical error output when `node-gyp` fails to download Node.js headers due to proxy restrictions, resulting in an `ECONNRESET` error during the `rebuild` process. SOURCE: https://theia-ide.org/docs/composing_applications LANGUAGE: Shell CODE: ``` [4/4] Building fresh packages... [1/9] XXXXX [2/9] XXXXX [3/9] XXXXX [4/9] XXXXX error /theiaide/node_modules/XXXXX: Command failed. Exit code: 1 Command: node-gyp rebuild Arguments: Directory: /theiaide/node_modules/XXXXX Output: gyp info it worked if it ends with ok gyp info using node-gyp@3.8.0 gyp info using node@8.15.0 | linux | x64 gyp http GET https://nodejs.org/download/release/v8.15.0/node-v8.15.0-headers.tar.gz gyp WARN install got an error, rolling back install gyp ERR! configure error gyp ERR! stack Error: read ECONNRESET gyp ERR! stack at TLSWrap.onread (net.js:622:25) gyp ERR! System Linux 3.10.0-862.11.6.el7.x86_64 gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" gyp ERR! cwd /theiaide/node_modules/XXXXX gyp ERR! node -v v8.15.0 ``` -------------------------------- TITLE: Define and bind FileSystemPreferences proxy DESCRIPTION: Provides a concrete example of defining a `FileSystemConfiguration` interface and a `FileSystemPreferences` type using the generic `PreferenceProxy`. It also shows how to create and bind this specific preference proxy within the dependency injection system, associating it with a schema. SOURCE: https://theia-ide.org/docs/preferences LANGUAGE: TypeScript CODE: ``` export interface FileSystemConfiguration { 'files.watcherExclude': { [globPattern: string]: boolean } } export const FileSystemPreferences = Symbol('FileSystemPreferences'); export type FileSystemPreferences = PreferenceProxy; export function createFileSystemPreferences(preferences: PreferenceService): FileSystemPreferences { return createPreferenceProxy(preferences, defaultFileSystemConfiguration, filesystemPreferenceSchema); } export function bindFileSystemPreferences(bind: interfaces.Bind): void { bind(FileSystemPreferences).toDynamicValue(ctx => { const preferences = ctx.container.get(PreferenceService); return createFileSystemPreferences(preferences); }); bind(PreferenceContribution).toConstantValue({ schema: filesystemPreferenceSchema }); } ``` -------------------------------- TITLE: Extracted Localization Keys JSON (Flat Structure) DESCRIPTION: Example of the JSON output generated by the `theia nls-extract` command, showing a flat structure for localization keys extracted from `nls.localize` calls. SOURCE: https://theia-ide.org/docs/i18n LANGUAGE: JSON CODE: ``` { "bye": "Bye", "hello": "Hello", "greetings": "Greetings" } ``` -------------------------------- TITLE: Define Business Model Interface and Example Data DESCRIPTION: This snippet defines the 'Item' interface, representing the underlying business model for tree data. It includes properties for name, children (for container nodes), quantity (for leaf nodes), and a boolean for back-ordered status. An example static data structure, 'EXAMPLE_DATA', is provided to illustrate the business model's hierarchical organization. SOURCE: https://theia-ide.org/docs/tree_widget LANGUAGE: TypeScript CODE: ``` export interface Item { name: string; children?: Item[]; // only for category/container nodes quantity?: number; // only for concrete items backOrdered?: boolean; // will be used for a later feature below } const EXAMPLE_DATA: Item[] = [{ name: 'Fruits', children: [ { name: 'Apples', children: [{ name: 'Golden Delicious', quantity: 4 }, // ... more properties }, // ... more children ] }, // ... more elements ]; ``` -------------------------------- TITLE: Get PreferenceService from container DESCRIPTION: Demonstrates how to obtain an instance of the `PreferenceService` by injecting it from the application's dependency injection container. This service is the primary entry point for interacting with user preferences. SOURCE: https://theia-ide.org/docs/preferences LANGUAGE: TypeScript CODE: ``` const preferences = ctx.container.get(PreferenceService); ``` -------------------------------- TITLE: RpcServer Interface Definition and Client Assignment DESCRIPTION: Provides the definition for the `RpcServer` interface, which extends `Disposable` and includes methods for managing a client object that handles RPC messages from a remote server. It also shows an example of how to explicitly set a client on a created proxy. SOURCE: https://theia-ide.org/docs/json_rpc LANGUAGE: APIDOC CODE: ``` export type RpcServer = Disposable & { /** * If this server is a proxy to a remote server then * a client is used as a local object * to handle RPC messages from the remote server. */ setClient(client: Client | undefined): void; getClient?(): Client | undefined; }; export interface TaskServer extends RpcServer { // ... } const serverProxy = connection.createProxy("/services/task"); const client = taskWatcher.getTaskClient(); serverProxy.setClient(client); ``` -------------------------------- TITLE: Example Theia Backend Memory Usage Log Output DESCRIPTION: This snippet shows a sample log output generated by the `MemoryTracker` contribution. It illustrates how the backend logs its process ID (PID) and memory usage, along with changes, at regular intervals. SOURCE: https://theia-ide.org/docs/backend_application_contribution LANGUAGE: Log CODE: ``` root INFO Theia app listening on http://localhost:3000. root INFO Configuration directory URI: 'file:///home/foobar/.theia' root INFO [Fri, 20 Aug 2021 12:20:43 GMT] PID 46590 uses 18.14 MB (+18.14) root INFO [Fri, 20 Aug 2021 12:20:47 GMT] PID 46590 uses 18.94 MB (+0.80) root INFO [Fri, 20 Aug 2021 12:20:51 GMT] PID 46590 uses 15.25 MB (-3.69) root INFO [Fri, 20 Aug 2021 12:21:07 GMT] PID 46590 uses 15.36 MB (+0.11) root INFO [Fri, 20 Aug 2021 12:21:21 GMT] PID 46590 uses 15.47 MB (+0.11) root INFO [Fri, 20 Aug 2021 12:21:41 GMT] PID 46590 uses 15.6 MB (+0.13) root INFO [Fri, 20 Aug 2021 12:21:59 GMT] PID 46590 uses 15.71 MB (+0.11) ``` -------------------------------- TITLE: Reporting Incremental Progress for Operations DESCRIPTION: This example demonstrates how to use the `showProgress` method to display an ongoing operation's progress. It shows how to incrementally update the progress bar and message, and how to signal completion using `progress.cancel()`. SOURCE: https://theia-ide.org/docs/message_service LANGUAGE: TypeScript CODE: ``` this.messageService .showProgress({ text: `Doing something`, }) .then((progress) => { // Do something progress.report({ message: "First step completed", work: { done: 10, total: 100 }, }); // Do something progress.report({ message: "Next step completed", work: { done: 80, total: 100 }, }); // Do something progress.report({ message: "Complete", work: { done: 100, total: 100 }, }); progress.cancel(); }) ``` -------------------------------- TITLE: Register Response Content Matcher for LLM Output DESCRIPTION: This example illustrates how to register a response content matcher within a Theia chat agent. The matcher defines `start` and `end` regular expressions to identify specific sections of an LLM response (e.g., text within `` tags). The `contentFactory` then transforms the matched content into a dedicated `QuestionResponseContentImpl` object, allowing for customized UI rendering of different response parts, such as interactive questions or highlighted code. SOURCE: https://theia-ide.org/docs/theia_ai LANGUAGE: TypeScript CODE: ``` @postConstruct() addContentMatchers(): void { this.contentMatchers.push({ start: /^.*$/m, end: /^<\/question>$/m, contentFactory: (content: string, request: ChatRequestModelImpl) => { const question = content.replace(/^\n|<\/question>$/g, ''); const parsedQuestion = JSON.parse(question); return new QuestionResponseContentImpl(parsedQuestion.question, parsedQuestion.options, request, selectedOption => { this.handleAnswer(selectedOption, request); }); } }); } ``` -------------------------------- TITLE: Set Theia Default Plugins Environment Variable DESCRIPTION: This snippet demonstrates how to set the `THEIA_DEFAULT_PLUGINS` environment variable. This variable tells Theia where to find local plugins, serving as an alternative to passing the `--plugins` switch directly to the `theia start` command. SOURCE: https://theia-ide.org/docs/authoring_vscode_extensions LANGUAGE: Shell CODE: ``` export THEIA_DEFAULT_PLUGINS=local-dir:plugins ``` -------------------------------- TITLE: Configure LlamaFile LLM Models in Theia IDE DESCRIPTION: This snippet demonstrates how to configure LlamaFile LLM models in the Theia IDE's settings. It specifies the model name, URI to the `.llamafile`, and the port for the LlamaFile server. It also mentions convenience commands for starting and stopping LlamaFiles. SOURCE: https://theia-ide.org/docs/user_ai LANGUAGE: JSON CODE: ``` { "ai-features.llamafile.llamafiles": [ { "name": "modelname", "uri": "file:///home/.../YourModel.llamafile", "port": 30000 } ] } ``` -------------------------------- TITLE: Adding Theia Extension as Dependency in package.json DESCRIPTION: This JSON configuration illustrates how to declare a custom Theia extension (e.g., 'hello-world') as a dependency in a Theia browser or Electron application's `package.json` file. It also includes common scripts for bundling, rebuilding, starting, and watching the application, ensuring the extension is properly integrated. SOURCE: https://theia-ide.org/docs/authoring_extensions LANGUAGE: JSON CODE: ``` { "private": true, "name": "browser-app", "version": "0.0.0", "dependencies": { "@theia/core": "latest", "...": "", "hello-world": "0.0.0" }, "devDependencies": { "@theia/cli": "latest" }, "scripts": { "bundle": "yarn rebuild && theia build --mode development", "rebuild": "theia rebuild:browser --cacheRoot ..", "start": "theia start", "watch": "yarn rebuild && theia build --watch --mode development" }, "theia": { "target": "browser" } } ``` -------------------------------- TITLE: Illustrating Breadcrumbs Priority Ordering DESCRIPTION: This example demonstrates how breadcrumbs contributions are ordered based on their assigned priority. Contributions with lower priority values appear before those with higher values in the final aggregated list. SOURCE: https://theia-ide.org/docs/breadcrumbs LANGUAGE: plaintext CODE: ``` Contribution A with a priority of 10 returns [a, b] Contribution B with a priority of 20 returns [c, d] Contribution C with a priority of 30 returns [e, f] => [a, b, c, d, e, f] ``` -------------------------------- TITLE: Register a Theia Command Contribution DESCRIPTION: This snippet shows how to implement `CommandContribution` to register the previously defined example command. The `registerCommands` method is used to add the `TO_BE_FILTERED` command to the `CommandRegistry`, making it available in the Theia application. SOURCE: https://theia-ide.org/docs/contribution_filter LANGUAGE: TypeScript CODE: ``` import { CommandContribution, CommandRegistry } from '@theia/core/lib/common'; import { injectable } from 'inversify'; @injectable() export class SampleFilteredCommandContribution implements CommandContribution { registerCommands(commands: CommandRegistry): void { commands.registerCommand(SampleFilteredCommand.TO_BE_FILTERED, { execute: () => { } }); } } ``` -------------------------------- TITLE: Configure Theia Application to Support VS Code Extensions DESCRIPTION: This JSON snippet demonstrates how to modify the `package.json` file of a Theia application to include the `@theia/vsx-registry` dependency. Adding this dependency enables the 'Extensions' view, allowing users to install VS Code extensions at runtime from an OpenVSX registry. SOURCE: https://theia-ide.org/docs/authoring_vscode_extensions LANGUAGE: JSON CODE: ``` { ... "name": "browser-app", "dependencies": { "@theia/core": "latest", ... "@theia/vsx-registry": "latest" }, "theia": { "target": "browser" } } ``` -------------------------------- TITLE: Add Command-Based Chat Suggestions in Theia AI DESCRIPTION: This snippet illustrates how to add command-based suggestions to a Theia AI chat model. These suggestions, when clicked, trigger predefined Theia commands, such as starting a new chat window or a new chat with context. SOURCE: https://theia-ide.org/docs/theia_ai LANGUAGE: TypeScript CODE: ``` model.setSuggestions([ new MarkdownStringImpl(`Keep chats short and focused. [Start a new chat](command:${AI_CHAT_NEW_CHAT_WINDOW_COMMAND.id})` + ` or [start a new chat with a summary of this one](command:${ChatCommands.AI_CHAT_NEW_WITH_TASK_CONTEXT.id}).`) ]); ``` -------------------------------- TITLE: Accessing Theia-Specific Custom API in VS Code Extensions DESCRIPTION: This code demonstrates how a VS Code extension can conditionally import and utilize a custom API provided by Eclipse Theia. The API is imported asynchronously and used only when the extension detects it's running within a Theia application (identified by `vscode.env.appName`), preventing errors in standard VS Code environments. It shows examples of getting a message handler and responding to message requests. SOURCE: https://theia-ide.org/docs/tips LANGUAGE: TypeScript CODE: ``` if (vscode.env.appName === MY_THEIA_APP_NAME) { // Implement Theia API const api = await import('@mytheiaextension/mycustomapi'); // After importing the custom API, it can be used as any other API. The following lines are using an example API. api.host.getMessageHandler(() => getMessage()); api.host.onRequestMessage((actor: string) => { const message = getMessage(actor); api.host.showMessage(message); }); } ``` -------------------------------- TITLE: Implementing MyTaskResolver to Enhance Task Configuration DESCRIPTION: This `MyTaskResolver` class implements the `TaskResolver` interface. Its `resolveTask` method takes a `TaskConfiguration` and returns a new configuration, in this example, by adding a static `myCustomValue` property. In a real scenario, it would handle default values or variable resolution. SOURCE: https://theia-ide.org/docs/tasks LANGUAGE: TypeScript CODE: ``` class MyTaskResolver implements TaskResolver { async resolveTask(taskConfig: TaskConfiguration):Promise { return {...taskConfig, myCustomValue: 42 } } } ``` -------------------------------- TITLE: Example Theia Package Version Adjustment in package.json DESCRIPTION: Illustrates how to manually modify `package.json` files within the Theia codebase. Any Theia package dependencies referencing a newer version (e.g., 1.44.0) must be downgraded to the target hotfix version (e.g., 1.43.0) to prevent build errors. SOURCE: https://theia-ide.org/docs/consume_theia_fixes_master LANGUAGE: json CODE: ``` "dependencies": { "@theia/core": "1.44.0", ... } ``` -------------------------------- TITLE: Binding a Contribution in Theia's Container Module DESCRIPTION: Illustrates how to register a contribution's implementation within a Theia ContainerModule. This example binds HelloworldCommandContribution to the CommandContribution interface, allowing the DI container to provide the correct implementation when the contribution point is resolved. SOURCE: https://theia-ide.org/docs/services_and_contributions LANGUAGE: TypeScript CODE: ``` export default new ContainerModule(bind => { // add your contribution bindings here bind(CommandContribution).to(HelloworldCommandContribution); //... }); ``` -------------------------------- TITLE: Displaying Messages with an Automatic Timeout DESCRIPTION: This example shows how to configure a message to automatically close after a specified duration. By providing a `timeout` option, the toast notification will disappear without requiring user interaction. SOURCE: https://theia-ide.org/docs/message_service LANGUAGE: TypeScript CODE: ``` this.messageService.info('Say Hello with timeout',{timeout: 3000}) ``` -------------------------------- TITLE: Define Custom Icon Styles via CSS for Theia Label Provider DESCRIPTION: Provides an example of defining custom CSS styles for an icon. It includes base styles and specific background images for both light and dark themes, allowing the `getIcon` function to reference a unique visual asset for custom file types. SOURCE: https://theia-ide.org/docs/label_provider LANGUAGE: CSS CODE: ``` .my-icon { background-repeat: no-repeat; background-size: 12px; width: 13px; height: 13px; } .light-plus .my-icon{ background-image: url('./custom_icon_black_18dp.png'); } .dark-plus .my-icon{ background-image: url('./custom_icon_white_18dp.png'); } ``` -------------------------------- TITLE: Registering Theia AI Chat Agent via Dependency Injection DESCRIPTION: This example shows how to register the custom `CommandChatAgent` with Theia AI using dependency injection. By binding it as both an 'Agent' and a 'ChatAgent', it becomes available in the default chat UI and can be invoked using '@Command'. SOURCE: https://theia-ide.org/docs/theia_ai LANGUAGE: TypeScript CODE: ``` bind(Agent).toService(CommandChatAgent); bind(ChatAgent).toService(CommandChatAgent); ``` -------------------------------- TITLE: Proposing File Modifications with Theia AI Change Sets DESCRIPTION: This example demonstrates how AI agents can propose file modifications using Theia AI's change set mechanism. It illustrates the creation of a change set, adding different types of file elements (add, modify, delete), and associating the proposed changes with the chat session for user review. This functionality is also utilized by the Theia Coder agent for LLM-driven modifications. SOURCE: https://theia-ide.org/docs/theia_ai LANGUAGE: TypeScript CODE: ``` override async invoke(request: ChatRequestModelImpl): Promise { // ... const fileToAdd = root.resource.resolve('hello/new-file.txt'); const fileToChange = // some file to change const fileToDelete = // Some file to delete const chatSessionId = request.session.id; const changeSet = new ChangeSetImpl('My Test Change Set'); changeSet.addElement( this.fileChangeFactory({ uri: fileToAdd, type: 'add', state: 'pending', targetState: 'Hello World!', changeSet, chatSessionId }) ); if (fileToChange && fileToChange.resource) { changeSet.addElement( this.fileChangeFactory({ uri: fileToChange.resource, type: 'modify', state: 'pending', targetState: await this.computeTargetState(fileToChange.resource), changeSet, chatSessionId }) ); } if (fileToDelete && fileToDelete.resource) { changeSet.addElement( this.fileChangeFactory({ uri: fileToDelete.resource, type: 'delete', state: 'pending', changeSet, chatSessionId }) ); } request.session.setChangeSet(changeSet); request.response.complete(); } ``` -------------------------------- TITLE: Initialize Tree Model with Root Node ID DESCRIPTION: This snippet shows the initial definition of the 'TreeViewExampleModel' class, which extends 'TreeModelImpl'. It also defines a constant 'ROOT_NODE_ID' used to identify the root node of the tree view, indicating the starting point for building the tree structure. SOURCE: https://theia-ide.org/docs/tree_widget LANGUAGE: TypeScript CODE: ``` export const ROOT_NODE_ID = 'treeview-example-root'; @injectable() export class TreeViewExampleModel extends TreeModelImpl { ``` -------------------------------- TITLE: Define LoggerWatcher Class with Event Emitter DESCRIPTION: This class demonstrates the core structure for handling events in Theia using an `Emitter`. It defines a `LoggerWatcher` class that manages log level changes, exposing methods to get a client and register/fire events. SOURCE: https://theia-ide.org/docs/events LANGUAGE: TypeScript CODE: ``` @injectable() export class LoggerWatcher { getLoggerClient(): ILoggerClient { const emitter = this.onLogLevelChangedEmitter return { onLogLevelChanged(event: ILogLevelChangedEvent) { emitter.fire(event) } } } private onLogLevelChangedEmitter = new Emitter(); get onLogLevelChanged(): Event { return this.onLogLevelChangedEmitter.event; } } ``` -------------------------------- TITLE: Update Application Node Modules with Local Theia Packages DESCRIPTION: Run `yarn install` with `--check-files` and `--ignore-scripts` flags in your application directory. This command ensures that `node_modules` is correctly updated with the locally resolved Theia packages, skipping unnecessary optimizations and lifecycle scripts. This step must be repeated if the local Theia packages are further modified. SOURCE: https://theia-ide.org/docs/consume_theia_fixes_master LANGUAGE: bash CODE: ``` yarn install --check-files --ignore-scripts ``` -------------------------------- TITLE: Define a Command to be Filtered in Theia DESCRIPTION: This snippet defines a `Command` object within the `SampleFilteredCommand` namespace. It specifies an `id`, `category`, and `label` for a command intended to be filtered out later. This command serves as an example for demonstrating the contribution filtering mechanism. SOURCE: https://theia-ide.org/docs/contribution_filter LANGUAGE: TypeScript CODE: ``` import { Command } from '@theia/core/lib/common'; export namespace SampleFilteredCommand { const EXAMPLE_CATEGORY = 'Examples'; export const TO_BE_FILTERED: Command = { id: 'example_command.filtered', category: EXAMPLE_CATEGORY, label: 'This command should be filtered out' }; } ``` -------------------------------- TITLE: Register a Theia Contribution Filter DESCRIPTION: This snippet demonstrates how to implement `FilterContribution` to register a filter that removes specific contributions. The `registerContributionFilters` method adds a filter scoped to `CommandContribution` that excludes instances of `SampleFilteredCommandContribution`, effectively filtering out the example command. SOURCE: https://theia-ide.org/docs/contribution_filter LANGUAGE: TypeScript CODE: ``` import { FilterContribution, ContributionFilterRegistry, CommandContribution } from '@theia/core/lib/common'; import { injectable } from 'inversify'; @injectable() export class SampleFilterContribution implements FilterContribution { registerContributionFilters(registry: ContributionFilterRegistry): void { registry.addFilters([CommandContribution], [ contrib => !(contrib instanceof SampleFilteredCommandContribution) ]); } } ``` -------------------------------- TITLE: VS Code Extension package.json for Theia Integration and Symlinking DESCRIPTION: Modifies the `package.json` of a VS Code extension to integrate it into a Theia monorepo. It adds `symlink-dir` as a dev dependency and defines a `symlink` script, which is executed during the `prepare` phase to link the built extension into the Theia application's plugins location for automatic installation. SOURCE: https://theia-ide.org/docs/authoring_vscode_extensions LANGUAGE: json CODE: ``` { "scripts": { "compile": "tsc -p ./", "watch": "tsc -watch -p ./", "prepare": "yarn run clean && yarn run build && yarn symlink", "symlink": "symlink-dir . ../../plugins/your-vs-code-extension" }, "devDependencies": { "@types/vscode": "^1.32.0", "symlink-dir": "latest" } } ``` -------------------------------- TITLE: Implement Tree Node Factory from Business Model DESCRIPTION: This code defines the 'TreeViewExampleTreeItemFactory' class, responsible for converting 'Item' business model objects into appropriate 'ExampleTreeNode' or 'ExampleTreeLeaf' instances. The 'toTreeNode' method determines the node type based on the presence of children. A private 'toTreeNodeId' method ensures unique IDs for each tree node, using a name-to-counter map since the example business model lacks inherent primary keys. SOURCE: https://theia-ide.org/docs/tree_widget LANGUAGE: TypeScript CODE: ``` @injectable() export class TreeViewExampleTreeItemFactory { private readonly idCounter = new Map(); public toTreeNode(item: Item): ExampleTreeNode | ExampleTreeLeaf { if (item.children) { return { id: this.toTreeNodeId(item), data: item, children: [], parent: undefined, type: 'node' }; } else { return { id: this.toTreeNodeId(item), data: item, parent: undefined, type: 'leaf', }; } } private toTreeNodeId(item: Item): string { const key = item.name; let count: number; if (this.idCounter.has(key)) { count = this.idCounter.get(key)!; } else { count = 0; } this.idCounter.set(key, count + 1); return `${key}-${count}`; } } ``` -------------------------------- TITLE: Console Output: Custom Task Execution Log DESCRIPTION: This snippet displays the console output generated during the execution of the custom task. It shows the 'Start running custom task' and 'Finished running custom task' messages, along with the custom value, confirming the task's lifecycle and data processing. SOURCE: https://theia-ide.org/docs/tasks LANGUAGE: text CODE: ``` root INFO Start running custom task: 42 root INFO Finished running custom task: 42 ``` -------------------------------- TITLE: Configure Mistral Models via OpenAI API in Theia IDE DESCRIPTION: This JSON configuration provides an example of how to integrate Mistral models, including 'mistral-large-latest' and 'codestral-latest', into Theia IDE using the OpenAI API compatibility. It specifies the model, URL, ID, API key, and developer message settings for each Mistral model. SOURCE: https://theia-ide.org/docs/user_ai LANGUAGE: JSON CODE: ``` "ai-features.openAiCustom.customOpenAiModels": [ { "model": "mistral-large-latest", "url": "https://api.mistral.ai/v1", "id": "Mistral", "apiKey": "YourAPIKey", "developerMessageSettings": "system" }, { "model": "codestral-latest", "url": "https://codestral.mistral.ai/v1", "id": "Codestral", "apiKey": "YourAPIKey", "developerMessageSettings": "system" } ] ``` -------------------------------- TITLE: Add and Update Progress Messages in Chat Response (TypeScript) DESCRIPTION: This TypeScript example shows how to add a progress message to a chat response using `request.response.addProgressMessage`. It also illustrates how to update an existing progress message with new status or content using `request.response.updateProgressMessage`. The `show` property controls the visibility duration of the message. SOURCE: https://theia-ide.org/docs/theia_ai LANGUAGE: TypeScript CODE: ``` const progressMessage = request.response.addProgressMessage({ content: 'Analyzing your request...', show: 'whileIncomplete' }); // do your work // if you are done, you can update the message request.response.updateProgressMessage({ ...progressMessage, show: 'whileIncomplete', status: 'completed' }); ``` -------------------------------- TITLE: Implement Interactive Breadcrumb Popup Content in Theia DESCRIPTION: This example demonstrates how to implement the `attachPopupContent` method of the `BreadcrumbsContribution` interface. This method is invoked when a user clicks on a breadcrumb, allowing the contribution to add arbitrary HTML content to a popup, providing interactive functionality. The method can return a `Disposable` to clean up resources when the popup closes. SOURCE: https://theia-ide.org/docs/breadcrumbs LANGUAGE: typescript CODE: ``` @injectable() export class CustomBreadcrumbsContribution implements BreadcrumbsContribution { // ... attachPopupContent(breadcrumb: Breadcrumb, parent: HTMLElement): Promise { parent.innerHTML = '

' + breadcrumb.label + '

We can show arbitrary content here and react to clicks.

'; return Promise.resolve(undefined); } } ``` -------------------------------- TITLE: Configure Theia package.json for Pre-installing VS Code Extensions DESCRIPTION: This `package.json` configuration enables the automatic download and pre-installation of VS Code extensions during the Theia application build process. It defines a `theiaPluginsDir` for the download location and `theiaPlugins` to list extensions with their download URLs, along with a `download:plugins` script. SOURCE: https://theia-ide.org/docs/authoring_vscode_extensions LANGUAGE: json CODE: ``` { ... "scripts": { "prepare": "yarn run clean && yarn build && yarn run download:plugins", "download:plugins": "theia download:plugins", ... }, "theiaPluginsDir": "plugins", "theiaPlugins": { "my-hello-world-extension": "https://", "vscode.git": "https://open-vsx.org/api/vscode/git/1.52.1/file/vscode.git-1.52.1.vsix", ... } } ``` -------------------------------- TITLE: Style Theia Tab Preview Content Elements with CSS DESCRIPTION: This CSS example shows how to style the internal components of the Theia tab bar preview, including the outer box, title, and caption. It demonstrates setting fixed width, font styles, and ensuring text wraps within boundaries using `word-wrap: break-word` for `.theia-horizontal-tabBar-hover-div`, `.theia-horizontal-tabBar-hover-title`, and `.theia-horizontal-tabBar-hover-caption` classes. SOURCE: https://theia-ide.org/docs/enhanced_tab_bar_preview LANGUAGE: css CODE: ``` .theia-horizontal-tabBar-hover-div { margin: 0px 4px; width: 100px; } .theia-horizontal-tabBar-hover-title { font-weight: bolder; font-size: medium; margin: 0px 0px; max-width: 100px; word-wrap: break-word } .theia-horizontal-tabBar-hover-caption { font-size: small; margin: 0px 0px; margin-top: 4px; max-width: 100px; word-wrap: break-word } ``` -------------------------------- TITLE: WebSocketConnectionProvider createProxy Method Implementation DESCRIPTION: Details the internal implementation of the `createProxy` method within `WebSocketConnectionProvider`. This method sets up a WebSocket listener for a specified path and returns an `RpcProxy`, abstracting the underlying connection and factory creation. SOURCE: https://theia-ide.org/docs/json_rpc LANGUAGE: typescript CODE: ``` createProxy(path: string, arg?: object): RpcProxy { const factory = arg instanceof RpcProxyFactory ? arg : new RpcProxyFactory(arg); this.listen({ path, onConnection: c => factory.listen(c) }); return factory.createProxy(); } ``` -------------------------------- TITLE: Register and Implement Custom Breadcrumbs Contribution in Theia DESCRIPTION: This code shows how to register a custom breadcrumbs contribution using a `ContainerModule` and implement the `BreadcrumbsContribution` interface. The `computeBreadcrumbs` method defines the array of `Breadcrumb` objects to be displayed for a specific URI scheme, in this case, 'resource' URIs, providing a hardcoded example for simplicity. SOURCE: https://theia-ide.org/docs/breadcrumbs LANGUAGE: typescript CODE: ``` export default new ContainerModule(bind => { bind(CustomBreadcrumbsContribution).toSelf().inSingletonScope(); bind(BreadcrumbsContribution).toService(CustomBreadcrumbsContribution); }); @injectable() export class CustomBreadcrumbsContribution implements BreadcrumbsContribution { type: symbol = CustomBreadcrumbType; priority: number = 100; protected readonly onDidChangeBreadcrumbsEmitter = new Emitter(); get onDidChangeBreadcrumbs(): Event { return this.onDidChangeBreadcrumbsEmitter.event; } computeBreadcrumbs(uri: URI): MaybePromise { if (uri.scheme !== 'resource') { return []; } // uri is 'resources://project-a/component-b/config-c' for our widget above // but let's just hard code breadcrumbs as an example for the sake of simplicity return [ { id: 'project', label: 'Project A', longLabel: 'The project', iconClass: 'codicon codicon-folder default-folder-icon file-icon', type: CustomBreadcrumbType }, { id: 'component', label: 'Component B', longLabel: 'A component within a project', iconClass: 'codicon codicon-file default-file-icon file-icon', type: CustomBreadcrumbType }, { id: 'config', label: 'Configuration C', longLabel: 'A configuration within a component', iconClass: 'markdown-icon medium-blue theia-file-icons-js file-icon', type: CustomBreadcrumbType } ]; } // ... } ``` -------------------------------- TITLE: Configure Hugging Face AI Models in Theia IDE DESCRIPTION: Instructions for enabling Hugging Face as an AI provider in Theia IDE. It covers creating an API key, entering it in settings, and notes on secure storage via `HUGGINGFACE_API_KEY` environment variable. It also highlights the use of OpenAI compatible API for many Hugging Face models and usage limits. SOURCE: https://theia-ide.org/docs/user_ai LANGUAGE: APIDOC CODE: ``` Hugging Face AI Configuration: API Key Setup: - Create API key in Hugging Face account. - Enter key in Theia IDE settings: AI-features => Hugging Face - Security Note: Key stored in clear text if not using environment variable. - Secure Storage: Use environment variable `HUGGINGFACE_API_KEY`. Model Configuration: - Add or remove desired Hugging Face models from the list of available models. Compatibility Note: - Many Hugging Face models support OpenAI compatible API; use Theia AI provider for OpenAI Compatible Models in such cases. - Hugging Face provider currently supports only text generation for non-OpenAI compatible models. Usage Note: - Monitor usage for paid/free-tier options and usage limits to avoid unexpected costs. ``` -------------------------------- TITLE: Override Theia Tab Bar Preview Content Rendering with TypeScript DESCRIPTION: This TypeScript snippet illustrates how to extend the `TabBarRenderer` class and override its `renderExtendedTabBarPreview` method. This allows developers to fully customize the HTML content displayed within the tab bar hover preview. The example demonstrates rendering only the title label within a custom div. SOURCE: https://theia-ide.org/docs/enhanced_tab_bar_preview LANGUAGE: typescript CODE: ``` export class CustomTabBarRenderer extends TabBarRenderer { protected override renderExtendedTabBarPreview = (title: Title) => { const hoverBox = document.createElement('div'); hoverBox.classList.add('theia-horizontal-tabBar-hover-div'); const labelElement = document.createElement('p'); labelElement.classList.add('theia-horizontal-tabBar-hover-title'); labelElement.textContent = title.label; hoverBox.append(labelElement); return hoverBox; }; } ```