### Install Web Terminal Plugin Manually Source: https://github.com/cloudcli-ai/cloudcli-plugin-terminal/blob/main/README.md Use this command to manually clone the plugin repository, install dependencies, and build the project. Restart CloudCLI UI after completion. ```bash git clone --depth 1 https://github.com/cloudcli-ai/cloudcli-plugin-terminal.git \ ~/.claude-code-ui/plugins/web-terminal cd ~/.claude-code-ui/plugins/web-terminal npm install npm run build ``` -------------------------------- ### Initialize and Manage Terminal Session Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Demonstrates creating a new terminal session with specified options and outlines common session management methods. Ensure all required addons and preferences are provided during initialization. ```typescript interface SessionOptions { id: string; label: string; Terminal: any; FitAddon: any; WebLinksAddon: any; WebglAddon: any; ClipboardAddon: any; Unicode11Addon: any; prefs: Prefs; onChange: (id: string, status: string) => void; } // Create a new terminal session const session = new TerminalSession({ id: 't1', label: 'shell 1', Terminal: mods.Terminal, FitAddon: mods.FitAddon, WebLinksAddon: mods.WebLinksAddon, WebglAddon: mods.WebglAddon, ClipboardAddon: mods.ClipboardAddon, Unicode11Addon: mods.Unicode11Addon, prefs: { theme: 'VS Dark', fontSize: 14 }, onChange: (id, status) => console.log(`Session ${id}: ${status}`) }); // Session methods session.show(); // Display terminal pane and connect session.hide(); // Hide terminal pane (keeps connection alive) session.clear(); // Clear terminal screen session.copySelection(); // Copy selected text to clipboard session.reconnect(); // Force reconnection session.updateFontSize(16); // Change font size session.updateTheme('Dracula'); // Change color theme session.sendKey('\x1b[A'); // Send key sequence (arrow up) session.attachTo(panesContainer); // Attach to DOM container session.detach(); // Remove from DOM (preserves session) session.destroy(); // Full cleanup, close WebSocket and PTY ``` -------------------------------- ### Plugin Mount API Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt The `mount` function initializes the terminal UI within a specified container element. It handles loading necessary modules, setting up the toolbar, and establishing WebSocket connections for terminal sessions. ```APIDOC ## Plugin Mount API ### Description Initializes the terminal UI within a container element, loads xterm.js modules, creates the toolbar, and establishes WebSocket connections for terminal sessions. ### Method `mount(container: HTMLElement, api: PluginAPI): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import type { PluginAPI } from './types.js'; // Mount the terminal plugin into a container export async function mount(container: HTMLElement, api: PluginAPI): Promise; // Example: CloudCLI UI calls mount when activating the terminal tab const container = document.getElementById('plugin-container'); const api: PluginAPI = { context: { theme: 'dark', project: { name: 'my-project', path: '/workspace/my-project' }, session: { id: 'sess-123', title: 'Main Session' } }, onContextChange: (callback) => { // Subscribe to theme/project/session changes return () => {}; // unsubscribe function }, rpc: async (method, path, body) => { // Call plugin backend through host proxy return fetch(`/plugin-api/web-terminal${path}`, { method, body: body ? JSON.stringify(body) : undefined }).then(r => r.json()); } }; await mount(container, api); ``` ### Response #### Success Response (200) None (The function returns a Promise that resolves when the terminal is mounted). #### Response Example None ``` -------------------------------- ### Spawn and Manage PTY Process Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Shows how to spawn a native pseudo-terminal process using node-pty, configuring environment variables for color and Unicode support. It also includes handling data flow, exit events, and input/resize operations. ```typescript import { spawn } from 'node-pty'; // Determine shell based on platform function getShell(): string { if (process.platform === 'win32') return 'powershell.exe'; return process.env.SHELL || '/bin/bash'; } // Spawn PTY on WebSocket connection const ptyProc = spawn(getShell(), [], { name: 'xterm-256color', cols: 80, rows: 24, cwd: process.env.HOME || os.homedir(), env: { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor', TERM_PROGRAM: 'web-terminal' } }); // Handle PTY data with flow control ptyProc.onData((chunk: string) => { ptyProc.pause(); ws.send(chunk, () => ptyProc.resume()); }); // Handle PTY exit ptyProc.onExit(({ exitCode, signal }) => { ws.send(JSON.stringify({ type: 'exit', exitCode, signal })); ws.close(1000, 'shell exited'); }); // Handle input from WebSocket ptyProc.write('ls -la\n'); // Handle resize from WebSocket ptyProc.resize(120, 40); ``` -------------------------------- ### Define and Apply Terminal Themes Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Illustrates the structure of a terminal theme object and how to set preferences, including theme and font size, which are persisted to localStorage. Ensure all required color properties are defined for a complete theme. ```typescript interface TerminalTheme { background: string; foreground: string; cursor: string; cursorAccent: string; selectionBackground: string; selectionForeground?: string; black: string; red: string; green: string; yellow: string; blue: string; magenta: string; cyan: string; white: string; brightBlack: string; brightRed: string; brightGreen: string; brightYellow: string; brightBlue: string; brightMagenta: string; brightCyan: string; brightWhite: string; } // Available themes const THEMES: Record = { 'VS Dark': { background: '#1e1e1e', foreground: '#d4d4d4', /* ... */ }, 'One Dark': { background: '#282c34', foreground: '#abb2bf', /* ... */ }, 'Dracula': { background: '#282a36', foreground: '#f8f8f2', /* ... */ }, 'Solarized Dark': { background: '#002b36', foreground: '#839496', /* ... */ }, 'Light': { background: '#ffffff', foreground: '#383a42', /* ... */ } }; // Theme selection persists to localStorage const PREFS_KEY = 'web-terminal-prefs'; localStorage.setItem(PREFS_KEY, JSON.stringify({ theme: 'Dracula', fontSize: 14 })); ``` -------------------------------- ### Mount CloudCLI Terminal Plugin Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Initializes the terminal UI within a specified container element and establishes WebSocket connections. Requires a container HTMLElement and a PluginAPI object for context and RPC calls. ```typescript import type { PluginAPI } from './types.js'; // Mount the terminal plugin into a container export async function mount(container: HTMLElement, api: PluginAPI): Promise; // Example: CloudCLI UI calls mount when activating the terminal tab const container = document.getElementById('plugin-container'); const api: PluginAPI = { context: { theme: 'dark', project: { name: 'my-project', path: '/workspace/my-project' }, session: { id: 'sess-123', title: 'Main Session' } }, onContextChange: (callback) => { // Subscribe to theme/project/session changes return () => {}; // unsubscribe function }, rpc: async (method, path, body) => { // Call plugin backend through host proxy return fetch(`/plugin-api/web-terminal${path}`, { method, body: body ? JSON.stringify(body) : undefined }).then(r => r.json()); } }; await mount(container, api); ``` -------------------------------- ### Backend HTTP Endpoints for Web Terminal Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Provides HTTP endpoints for server information and health checks. The server binds to localhost only for security. ```bash # Get server information curl http://127.0.0.1:PORT/info # Response: {"name":"web-terminal","sessions":2,"platform":"linux","shell":"/bin/bash"} # Health check endpoint curl http://127.0.0.1:PORT/health # Response: {"ok":true} # Server startup output (stdout JSON) # {"ready":true,"port":54321} ``` -------------------------------- ### Handle New Tab Keyboard Shortcut Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Listens for Ctrl+Shift+T or Cmd+Shift+T to create a new tab. Prevents default browser behavior for this key combination. ```typescript // Desktop keyboard shortcut: Ctrl+Shift+T or Cmd+Shift+T to create new tab document.addEventListener('keydown', (e: KeyboardEvent) => { if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 't') { e.preventDefault(); createTab(); } }); ``` -------------------------------- ### CloudCLI Plugin Manifest Configuration Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Defines the metadata for the CloudCLI Terminal plugin in `manifest.json`, specifying its name, version, entry points, and permissions required for loading and display within the CloudCLI UI. ```json { "name": "web-terminal", "displayName": "Terminal", "version": "1.0.1", "description": "Full-featured web terminal with multi-tab support, powered by xterm.js", "author": "CloudCLI UI", "icon": "icon.svg", "type": "module", "slot": "tab", "entry": "dist/index.js", "server": "dist/server.js", "permissions": [] } ``` -------------------------------- ### Define Mobile Key Sequences Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Defines an array of objects representing mobile-friendly keys. Each object can specify a label for display, a modifier ('ctrl' or 'alt') to toggle, or a specific key sequence (seq) to send. ```typescript // Mobile key sequences const MOBILE_KEYS = [ { label: 'ESC', seq: '\x1b' }, { label: 'TAB', seq: '\t' }, { label: 'CTRL', modifier: 'ctrl' }, // Toggle modifier { label: 'ALT', modifier: 'alt' }, // Toggle modifier { seq: '\x1b[A' }, // Arrow up { seq: '\x1b[B' }, // Arrow down { seq: '\x1b[D' }, // Arrow left { seq: '\x1b[C' }, // Arrow right ]; ``` -------------------------------- ### Backend HTTP Server Endpoints Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Exposes HTTP endpoints for health checks and server information. The server binds to localhost only for security. ```APIDOC ## Backend HTTP Server Endpoints ### Description The backend server exposes HTTP endpoints for health checks and server information. The server binds to localhost only (127.0.0.1) for security. ### Method GET ### Endpoint `http://127.0.0.1:PORT/info` `http://127.0.0.1:PORT/health` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash # Get server information curl http://127.0.0.1:PORT/info # Health check endpoint curl http://127.0.0.1:PORT/health ``` ### Response #### Success Response (200) - **/info**: - **name** (string) - The name of the web terminal service. - **sessions** (integer) - The number of active terminal sessions. - **platform** (string) - The operating system platform (e.g., "linux"). - **shell** (string) - The default shell used (e.g., "/bin/bash"). - **/health**: - **ok** (boolean) - Indicates if the server is healthy (true) or not (false). #### Response Example ```json { "name": "web-terminal", "sessions": 2, "platform": "linux", "shell": "/bin/bash" } ``` ```json { "ok": true } ``` ``` -------------------------------- ### WebSocket Connection Protocol Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Details the protocol for real-time communication between the terminal frontend and backend server using WebSockets. Covers message types for input, resizing, heartbeats, and session events. ```APIDOC ## WebSocket Connection Protocol ### Description The terminal frontend establishes WebSocket connections to the backend server for real-time PTY communication. Messages are JSON-encoded with type-based routing for input, resize, and ping/pong heartbeats. ### Method WebSocket ### Endpoint `ws:///plugin-ws/web-terminal?token=` or `wss:///plugin-ws/web-terminal?token=` ### Parameters #### Path Parameters None #### Query Parameters - **token** (string) - Optional - Authentication token for the WebSocket connection. #### Request Body Messages are JSON-encoded strings with a `type` field. ### Request Example ```typescript // WebSocket URL construction (frontend) function buildWsUrl(): string { const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; const token = localStorage.getItem('auth-token') || ''; const qs = token ? '?token=' + encodeURIComponent(token) : ''; return proto + '//' + location.host + '/plugin-ws/web-terminal' + qs; } // Message types sent from frontend to backend: // Send terminal input ws.send(JSON.stringify({ type: 'input', data: 'ls -la\n' })); // Resize terminal ws.send(JSON.stringify({ type: 'resize', cols: 120, rows: 40 })); // Ping for keepalive (sent every 25 seconds) ws.send(JSON.stringify({ type: 'ping' })); ``` ### Response #### Success Response (200) Messages received from the backend are either JSON objects or raw strings. - **JSON Message Types**: - `{ type: 'ready', sessionId: 's1', shell: '/bin/bash', cwd: '/home/user' }` - `{ type: 'exit', sessionId: 's1', exitCode: 0, signal: undefined }` - `{ type: 'error', message: 'Failed to spawn shell' }` - `{ type: 'pong', sessionId: 's1' }` - **Raw Terminal Output**: String data without JSON wrapper. #### Response Example ```json { "type": "ready", "sessionId": "s1", "shell": "/bin/bash", "cwd": "/home/user" } ``` ```json { "type": "exit", "sessionId": "s1", "exitCode": 0, "signal": undefined } ``` ``` Raw terminal output string ``` ``` -------------------------------- ### WebSocket Protocol for Terminal Communication Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Defines the WebSocket URL construction and message types for real-time terminal I/O between the frontend and backend. Includes input, resize, ping/pong, and session status messages. ```typescript // WebSocket URL construction (frontend) function buildWsUrl(): string { const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; const token = localStorage.getItem('auth-token') || ''; const qs = token ? '?token=' + encodeURIComponent(token) : ''; return proto + '//' + location.host + '/plugin-ws/web-terminal' + qs; } // Message types sent from frontend to backend: // Send terminal input ws.send(JSON.stringify({ type: 'input', data: 'ls -la\n' })); // Resize terminal ws.send(JSON.stringify({ type: 'resize', cols: 120, rows: 40 })); // Ping for keepalive (sent every 25 seconds) ws.send(JSON.stringify({ type: 'ping' })); // Message types received from backend: // { type: 'ready', sessionId: 's1', shell: '/bin/bash', cwd: '/home/user' } // { type: 'exit', sessionId: 's1', exitCode: 0, signal: undefined } // { type: 'error', message: 'Failed to spawn shell' } // { type: 'pong', sessionId: 's1' } // Raw terminal output (string data without JSON wrapper) ``` -------------------------------- ### Custom Key Event Handler for Copy/Paste Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Attaches a custom key event handler to manage copy (Ctrl+C/Cmd+C) and paste (Ctrl+V/Cmd+V) operations. It uses the navigator.clipboard API for reading and writing text and prevents default browser actions for these shortcuts. ```typescript // Copy/Paste handling with Ctrl+C/Ctrl+V (or Cmd on Mac) terminal.attachCustomKeyEventHandler((e: KeyboardEvent) => { const mod = e.ctrlKey || e.metaKey; if (mod && e.key.toLowerCase() === 'c' && terminal.hasSelection()) { navigator.clipboard.writeText(terminal.getSelection()); return false; // Prevent default } if (mod && e.key.toLowerCase() === 'v') { navigator.clipboard.readText().then(text => ws.send(JSON.stringify({ type: 'input', data: text }))); return false; } return true; // Allow default handling }); ``` -------------------------------- ### Plugin Unmount API Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt The `unmount` function cleans up the terminal UI when the plugin is unloaded. It detaches terminal sessions, removes event listeners, and cleans up DOM elements, while preserving sessions for potential re-mount. ```APIDOC ## Plugin Unmount API ### Description Cleans up the terminal UI when the plugin tab is closed or the plugin is unloaded. It detaches terminal sessions (preserving them for re-mount), removes event listeners, and cleans up DOM elements. ### Method `unmount(container: HTMLElement): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Unmount the terminal plugin, preserving sessions for later re-mount export function unmount(container: HTMLElement): void; // Example: CloudCLI UI calls unmount when switching away from terminal tab unmount(container); // Sessions remain in memory - calling mount() again will restore them await mount(container, api); // Sessions restored with existing WebSocket connections ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Unmount CloudCLI Terminal Plugin Source: https://context7.com/cloudcli-ai/cloudcli-plugin-terminal/llms.txt Cleans up the terminal UI and detaches sessions when the plugin is unloaded. Sessions are preserved for re-mount, maintaining WebSocket connections and PTY processes. ```typescript // Unmount the terminal plugin, preserving sessions for later re-mount export function unmount(container: HTMLElement): void; // Example: CloudCLI UI calls unmount when switching away from terminal tab unmount(container); // Sessions remain in memory - calling mount() again will restore them await mount(container, api); // Sessions restored with existing WebSocket connections ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.