### Run tmux-mobile from Source Source: https://github.com/dagshub/tmux-mobile/blob/main/README.md Installs project dependencies using npm and starts the tmux-mobile application from the local source code. This is suitable for development or customization. ```bash npm install npm start ``` -------------------------------- ### Run tmux-mobile Server (CLI) Source: https://context7.com/dagshub/tmux-mobile/llms.txt Quickly start the tmux-mobile server using npx. This command can be run directly without installation and supports various options for customization, such as port, password, session name, scrollback buffer size, and tunnel configuration. ```bash # Run without installation (recommended) npx tmux-mobile # Run with custom options npx tmux-mobile --port 8080 --password mypassword --session dev --scrollback 2000 # Run without cloudflared tunnel (local network only) npx tmux-mobile --no-tunnel # Disable password authentication for trusted networks npx tmux-mobile --no-require-password # Enable debug logging npx tmux-mobile --debug-log ./tmux-mobile.log ``` -------------------------------- ### GET /api/config Source: https://context7.com/dagshub/tmux-mobile/llms.txt Fetches the server configuration, including authentication requirements and default settings. ```APIDOC ## GET /api/config ### Description Fetches server configuration to determine authentication requirements and other settings before connecting. ### Method GET ### Endpoint /api/config ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://localhost:8767/api/config ``` ### Response #### Success Response (200) - **passwordRequired** (boolean) - Indicates if password authentication is required. - **scrollbackLines** (integer) - The default number of scrollback lines configured. - **pollIntervalMs** (integer) - The polling interval in milliseconds for certain client-side updates. #### Response Example ```json { "passwordRequired": true, "scrollbackLines": 1000, "pollIntervalMs": 2500 } ``` ``` -------------------------------- ### Manage Cloudflared Tunnels with CloudflaredManager Source: https://context7.com/dagshub/tmux-mobile/llms.txt Shows how to use the CloudflaredManager to automatically install and manage cloudflared tunnels. It covers ensuring installation, starting a tunnel on a specific local port, and gracefully stopping the tunnel on process termination. ```typescript import { CloudflaredManager } from './cloudflared/manager.js'; const manager = new CloudflaredManager(); // Ensure cloudflared is installed (auto-installs if needed) await manager.ensureInstalled(); // Start tunnel on local port const tunnel = await manager.start(8767); console.log('Public URL:', tunnel.publicUrl); // e.g., "https://random-words.trycloudflare.com" // Stop tunnel on shutdown process.on('SIGTERM', () => { manager.stop(); }); ``` -------------------------------- ### Integrate xterm.js Terminal UI in React Frontend Source: https://context7.com/dagshub/tmux-mobile/llms.txt Provides a complete React integration example using xterm.js for the terminal UI. It covers initializing the terminal, loading the fit addon, opening the terminal in a DOM element, and establishing WebSocket connections for control and terminal data, including authentication and resize handling. ```typescript import { Terminal } from '@xterm/xterm'; import { FitAddon } from '@xterm/addon-fit'; // Initialize terminal const terminal = new Terminal({ cursorBlink: true, fontFamily: "'MesloLGS NF', Menlo, Monaco, monospace", fontSize: 12, theme: { background: '#0d1117', foreground: '#d1e4ff', cursor: '#93c5fd' } }); const fitAddon = new FitAddon(); terminal.loadAddon(fitAddon); terminal.open(document.getElementById('terminal')); fitAddon.fit(); // Connect WebSockets const token = new URLSearchParams(window.location.search).get('token'); const wsOrigin = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}`; const controlSocket = new WebSocket(`${wsOrigin}/ws/control`); let terminalSocket; let clientId; controlSocket.onopen = () => { controlSocket.send(JSON.stringify({ type: 'auth', token })); }; controlSocket.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === 'auth_ok') { clientId = msg.clientId; terminalSocket = new WebSocket(`${wsOrigin}/ws/terminal`); terminalSocket.onopen = () => { terminalSocket.send(JSON.stringify({ type: 'auth', token, clientId })); terminalSocket.send(JSON.stringify({ type: 'resize', cols: terminal.cols, rows: terminal.rows })); }; terminalSocket.onmessage = (e) => terminal.write(e.data); } }; // Handle terminal input terminal.onData((data) => { terminalSocket?.send(data); }); // Handle window resize window.addEventListener('resize', () => { fitAddon.fit(); terminalSocket?.send(JSON.stringify({ type: 'resize', cols: terminal.cols, rows: terminal.rows })); }); ``` -------------------------------- ### Cloudflared Tunnel Command Source: https://github.com/dagshub/tmux-mobile/blob/main/SPEC.md Illustrates the command used to start a Cloudflared tunnel for exposing a local port. This is part of the Cloudflared integration feature to make the tmux-mobile server accessible remotely. ```bash cloudflared tunnel --url http://localhost: ``` -------------------------------- ### Start tmux-mobile in Development Mode Source: https://github.com/dagshub/tmux-mobile/blob/main/README.md Runs the tmux-mobile application in development mode, typically enabling features like hot-reloading and detailed debugging. This command is used during the development process. ```bash npm run dev ``` -------------------------------- ### Install tmux with Homebrew (macOS) Source: https://github.com/dagshub/tmux-mobile/blob/main/README.md Installs the tmux terminal multiplexer on macOS using the Homebrew package manager. This is a prerequisite for running tmux-mobile. ```bash brew install tmux ``` -------------------------------- ### Fetch tmux-mobile Server Configuration (HTTP API) Source: https://context7.com/dagshub/tmux-mobile/llms.txt Retrieve the current server configuration, including authentication requirements and polling intervals, by making an HTTP GET request to the /api/config endpoint. This is useful for clients to determine connection parameters. ```bash # Get server configuration curl http://localhost:8767/api/config # Response { "passwordRequired": true, "scrollbackLines": 1000, "pollIntervalMs": 2500 } ``` -------------------------------- ### Monitor Tmux State with TmuxStateMonitor (TypeScript) Source: https://context7.com/dagshub/tmux-mobile/llms.txt Demonstrates the usage of the `TmuxStateMonitor` class, which polls tmux state at a configurable interval and broadcasts changes to connected clients. It includes starting, stopping, and forcing state updates, along with error handling. ```typescript import { TmuxStateMonitor } from './state/state-monitor.js'; import { TmuxCliExecutor } from './tmux/cli-executor.js'; const monitor = new TmuxStateMonitor( new TmuxCliExecutor(), 2500, // Poll interval in ms (state) => { // Broadcast state to all connected clients for (const client of clients) { client.send(JSON.stringify({ type: 'tmux_state', state })); } }, (error) => { console.error('Monitor error:', error); } ); // Start polling await monitor.start(); // Force immediate state publish (after mutations) await monitor.forcePublish(); // Stop monitoring monitor.stop(); ``` -------------------------------- ### Run tmux-mobile without Cloning (Recommended) Source: https://github.com/dagshub/tmux-mobile/blob/main/README.md Executes tmux-mobile directly using npx, downloading and running the package without requiring a local clone. It outputs URLs for accessing the client and potentially a password. ```bash npx tmux-mobile ``` -------------------------------- ### Create Tmux-Mobile Server Programmatically (TypeScript) Source: https://context7.com/dagshub/tmux-mobile/llms.txt Illustrates how to create and configure the tmux-mobile server using the `createTmuxMobileServer` factory function. It shows the necessary configuration object and dependency injection for services like TmuxCliExecutor, NodePtyFactory, and AuthService. ```typescript import { createTmuxMobileServer } from './server.js'; import { TmuxCliExecutor } from './tmux/cli-executor.js'; import { NodePtyFactory } from './pty/node-pty-adapter.js'; import { AuthService } from './auth/auth-service.js'; const config = { port: 8767, host: '127.0.0.1', password: 'secret', tunnel: false, defaultSession: 'main', scrollbackLines: 1000, pollIntervalMs: 2500, token: 'generated-token', frontendDir: './dist/frontend' }; const server = createTmuxMobileServer(config, { tmux: new TmuxCliExecutor(), ptyFactory: new NodePtyFactory(), authService: new AuthService('secret', 'generated-token'), logger: console }); await server.start(); console.log(`Server running on ${config.host}:${config.port}`); // Graceful shutdown process.on('SIGTERM', async () => { await server.stop(); }); ``` -------------------------------- ### Execute Development and Testing Commands with npm Source: https://context7.com/dagshub/tmux-mobile/llms.txt Lists common npm scripts for development and testing within the project. This includes commands for running the development server with hot reload, executing unit and end-to-end tests, performing smoke tests with real tmux, type checking, and building the project for production. ```bash # Development mode (hot reload) npm run dev # Run unit tests npm test # Run end-to-end tests npm run test:e2e # Run smoke test with real tmux npm run test:smoke # Type checking npm run typecheck # Build for production npm run build ``` -------------------------------- ### Initialize and Use AuthService for WebSocket Authentication Source: https://context7.com/dagshub/tmux-mobile/llms.txt Demonstrates how to create an AuthService instance with or without a custom token, check password requirements, and verify credentials for WebSocket connections. It handles token and password-based authentication flows. ```typescript import { AuthService } from './auth/auth-service.js'; // Create with auto-generated token const auth = new AuthService('password123'); console.log('Token:', auth.token); // Random 32-char token // Create with specific token const auth2 = new AuthService('password', 'my-custom-token'); // Check if password is required const needsPassword = auth.requiresPassword(); // true // Verify credentials const result = auth.verify({ token: 'my-custom-token', password: 'password123' }); if (result.ok) { console.log('Authentication successful'); } else { console.log('Auth failed:', result.reason); // Reasons: "invalid token", "invalid password" } ``` -------------------------------- ### Use TmuxCliExecutor for Tmux Operations (TypeScript) Source: https://context7.com/dagshub/tmux-mobile/llms.txt Demonstrates how to instantiate and use the TmuxCliExecutor, a default implementation of the TmuxGateway, to perform common tmux operations. It shows configuration options for the tmux binary path, socket, and command timeouts. ```typescript import { TmuxCliExecutor } from './tmux/cli-executor.js'; const tmux = new TmuxCliExecutor({ socketName: 'my-socket', // Optional: tmux -L socketPath: '/tmp/tmux.sock', // Optional: tmux -S (mutually exclusive) tmuxBinary: '/usr/local/bin/tmux', // Optional: custom path timeoutMs: 5000 // Optional: command timeout }); const sessions = await tmux.listSessions(); await tmux.createSession('dev'); await tmux.splitWindow('%0', 'v'); const scrollback = await tmux.capturePane('%0', 500); ``` -------------------------------- ### Tmux State Query Commands Source: https://github.com/dagshub/tmux-mobile/blob/main/SPEC.md These commands are used to query the current state of tmux sessions, windows, and panes. They are essential for updating the UI, such as the left drawer, and for polling the server for changes. ```bash tmux list-sessions -F '#{session_name}:#{session_attached}:#{session_windows}' tmux list-windows -t -F '#{window_index}:#{window_name}:#{window_active}:#{window_panes}' tmux list-panes -t : -F '#{pane_index}:#{pane_id}:#{pane_current_command}:#{pane_active}:#{pane_width}x#{pane_height}' ``` -------------------------------- ### Toolbar Key Sequences Source: https://github.com/dagshub/tmux-mobile/blob/main/SPEC.md This table lists the key mappings and their corresponding tmux sequences for the toolbar buttons. It includes navigation, editing, and modifier keys, detailing their behavior and special sequences. ```markdown | Button | Key | Sequence | |---|---|---| | Esc | Escape | `\x1b` | | 1 | 1 | `1` | | 2 | 2 | `2` | | 3 | 3 | `3` | | Tab | Tab | `\t` | | / | / | `/` | | Del | Delete | `\x1b[3~` | | BS | Backspace | `\x7f` | | Hm | Home | `\x1b[H` | | Up | Arrow Up | `\x1b[A` | | Ed | End | `\x1b[F` | | Enter | Enter | `\r` | | Ctrl | Modifier | - | | Alt | Modifier | - | | Sft | Modifier | - | | ^D | Ctrl+D | `\x04` | | ^C | Ctrl+C | `\x03` | | ^L | Ctrl+L | `\x0c` | | ^R | Ctrl+R | `\x12` | | Paste | Clipboard | - | | Left | Arrow Left | `\x1b[D` | | Down | Arrow Down | `\x1b[B` | | Right | Arrow Right | `\x1b[C` | ``` -------------------------------- ### Run tmux-mobile Quality Gates Source: https://github.com/dagshub/tmux-mobile/blob/main/README.md Executes various quality assurance checks for the tmux-mobile project, including type checking, unit tests, end-to-end tests, and the build process. ```bash npm run typecheck npm test npm run test:e2e npm run build ``` -------------------------------- ### Tmux Mutation Commands for Drawer Actions Source: https://github.com/dagshub/tmux-mobile/blob/main/SPEC.md These tmux CLI commands are used to perform structural operations within tmux, triggered by user interactions with the application's drawer (e.g., creating a new session, splitting a pane). ```bash tmux new-session -d -s # Create session tmux kill-session -t # Kill session tmux switch-client -t # Switch session tmux new-window -t # New window tmux kill-window -t : # Kill window tmux select-window -t : # Switch window tmux split-window -h -t # Split horizontal tmux split-window -v -t # Split vertical tmux kill-pane -t # Close pane tmux select-pane -t # Switch pane ``` -------------------------------- ### Terminal Input and Resize API Source: https://context7.com/dagshub/tmux-mobile/llms.txt Send keyboard input and terminal resize events over the terminal WebSocket. ```APIDOC ## WebSocket Terminal Protocol - Input and Resize ### Description Send keyboard input and terminal resize events. ### Method Send data over WebSocket ### Endpoint `ws://:/ws/terminal` ### Parameters #### Input Data - **Raw Text/Binary** - For keyboard input. Include control characters like `\r` for carriage return. - **JSON Object** - For structured commands like resize. - **type** (string) - Must be `resize`. - **cols** (integer) - Required - Number of columns for the terminal. - **rows** (integer) - Required - Number of rows for the terminal. ### Request Example ```javascript // Send keyboard input (raw text or binary) terminalSocket.send('ls -la\r'); // Text with carriage return // Send terminal resize terminalSocket.send(JSON.stringify({ type: 'resize', cols: 120, rows: 40 })); // Send control characters terminalSocket.send('\x03'); // Ctrl+C (interrupt) terminalSocket.send('\x04'); // Ctrl+D (EOF) terminalSocket.send('\x1b'); // Escape terminalSocket.send('\x1b[A'); // Arrow Up ``` ### Response No specific success response defined for these operations, typically indicated by subsequent terminal output or absence of errors. ``` -------------------------------- ### Configure tmux Mouse Mode Source: https://github.com/dagshub/tmux-mobile/blob/main/README.md Enables mouse support in tmux, allowing users to switch panes by tapping in the tmux-mobile UI. This configuration is added to the ~/.tmux.conf file and then sourced. ```bash echo 'set -g mouse on' >> ~/.tmux.conf tmux source-file ~/.tmux.conf ``` -------------------------------- ### Configure tmux-mobile Server via Environment Variables (Bash) Source: https://context7.com/dagshub/tmux-mobile/llms.txt Configure tmux-mobile server behavior using environment variables before execution. This allows for advanced settings like tmux socket isolation, explicit socket paths, debug logging, and PTY fallback mechanisms. ```bash # Use a dedicated tmux socket name for isolation export TMUX_MOBILE_SOCKET_NAME=mobile-tmux npx tmux-mobile # Use an explicit tmux socket path export TMUX_MOBILE_SOCKET_PATH=/tmp/my-tmux-socket npx tmux-mobile # Alternative way to enable debug logging export TMUX_MOBILE_DEBUG_LOG=/var/log/tmux-mobile.log npx tmux-mobile # Force the Unix script(1) PTY fallback export TMUX_MOBILE_FORCE_SCRIPT_PTY=1 npx tmux-mobile # Enable verbose debug output export TMUX_MOBILE_VERBOSE_DEBUG=1 npx tmux-mobile # Trace all tmux CLI commands export TMUX_MOBILE_TRACE_TMUX=1 npx tmux-mobile ``` -------------------------------- ### Manage PTY Processes with TerminalRuntime (TypeScript) Source: https://context7.com/dagshub/tmux-mobile/llms.txt Shows how to use the `TerminalRuntime` class to manage Pseudo-Terminal (PTY) processes for attaching to tmux sessions. It covers listening for terminal output, attachment events, PTY exit, sending input, resizing, and session management. ```typescript import { TerminalRuntime } from './pty/terminal-runtime.js'; import { NodePtyFactory } from './pty/node-pty-adapter.js'; const runtime = new TerminalRuntime(new NodePtyFactory()); // Listen for terminal output runtime.on('data', (chunk) => { websocket.send(chunk); }); // Listen for attachment confirmation runtime.on('attach', (session) => { console.log(`Attached to session: ${session}`); }); // Listen for PTY exit runtime.on('exit', (code) => { console.log(`PTY exited with code: ${code}`); }); // Attach to a tmux session runtime.attachToSession('main'); // Send input to terminal runtime.write('echo hello\r'); // Resize terminal runtime.resize(120, 40); // Get current session const session = runtime.currentSession(); // Cleanup runtime.shutdown(); ``` -------------------------------- ### Window Operations API Source: https://context7.com/dagshub/tmux-mobile/llms.txt Perform operations on tmux windows, including creation, selection, and deletion. ```APIDOC ## WebSocket Control Protocol - Window Operations ### Description Create, select, and kill tmux windows within sessions. ### Method POST (via WebSocket message) ### Endpoint `ws://:/ws/control` ### Parameters #### Request Body - **type** (string) - Required - The type of window operation. Possible values: `new_window`, `select_window`, `kill_window`. - **session** (string) - Required - The name of the session the window belongs to. - **windowIndex** (integer) - Optional (required for `select_window`, `kill_window`) - The index of the window. - **stickyZoom** (boolean) - Optional (for `select_window`) - Enables sticky zoom for the selected window. ### Request Example ```json // Create a new window in the attached session { "type": "new_window", "session": "main" } // Select a window by index { "type": "select_window", "session": "main", "windowIndex": 2, "stickyZoom": true } // Kill a window { "type": "kill_window", "session": "main", "windowIndex": 1 } ``` ### Response No specific success response defined for these operations, typically indicated by absence of error messages and subsequent state updates. ``` -------------------------------- ### Run Optional Real tmux Smoke Test Source: https://github.com/dagshub/tmux-mobile/blob/main/README.md Executes a smoke test that interacts with a real tmux environment to verify core functionalities. This is an optional step for more comprehensive testing. ```bash npm run test:smoke ``` -------------------------------- ### Manage Tmux Windows via WebSocket Control Source: https://context7.com/dagshub/tmux-mobile/llms.txt Perform window operations such as creating new windows, selecting existing ones by index, and killing windows within a tmux session using the WebSocket control protocol. ```javascript // Create a new window in the attached session controlSocket.send(JSON.stringify({ type: 'new_window', session: 'main' })); // Select a window by index (with optional sticky zoom for mobile) controlSocket.send(JSON.stringify({ type: 'select_window', session: 'main', windowIndex: 2, stickyZoom: true // Auto-zoom the active pane (mobile-friendly) })); // Kill a window controlSocket.send(JSON.stringify({ type: 'kill_window', session: 'main', windowIndex: 1 })); ``` -------------------------------- ### CLI Flags for tmux-mobile Source: https://github.com/dagshub/tmux-mobile/blob/main/SPEC.md Defines the command-line interface flags available for configuring the tmux-mobile application. These options control aspects like port, authentication, tunneling, session management, and scrollback. ```bash npx tmux-mobile [options] Options: -p, --port Local port (default: 8767) --password Require password authentication --no-tunnel Don't start cloudflared tunnel (localhost only) --session Default tmux session name (default: "main") --scrollback Default scrollback capture lines (default: 1000) ``` -------------------------------- ### Send Composed Commands via WebSocket Control Source: https://context7.com/dagshub/tmux-mobile/llms.txt Utilize the 'send_compose' command to send complete command strings to tmux, with automatic carriage return handling for a seamless mobile text input experience. ```javascript // Send a composed command controlSocket.send(JSON.stringify({ type: 'send_compose', text: 'git status' // Carriage return added automatically })); ``` -------------------------------- ### Send Input and Resize Terminal via WebSocket Source: https://context7.com/dagshub/tmux-mobile/llms.txt Send raw keyboard input, including text and control characters, and terminal resize events to the tmux session through the terminal WebSocket connection. ```javascript // Send keyboard input (raw text or binary) terminalSocket.send('ls -la\r'); // Text with carriage return // Send terminal resize terminalSocket.send(JSON.stringify({ type: 'resize', cols: 120, rows: 40 })); // Send control characters terminalSocket.send('\x03'); // Ctrl+C (interrupt) terminalSocket.send('\x04'); // Ctrl+D (EOF) terminalSocket.send('\x1b'); // Escape terminalSocket.send('\x1b[A'); // Arrow Up ``` -------------------------------- ### Compose Mode API Source: https://context7.com/dagshub/tmux-mobile/llms.txt Send complete command strings with automatic carriage return for mobile-friendly text input. ```APIDOC ## WebSocket Control Protocol - Compose Mode ### Description Send complete command strings with automatic carriage return (mobile-friendly text input). ### Method POST (via WebSocket message) ### Endpoint `ws://:/ws/control` ### Parameters #### Request Body - **type** (string) - Required - Must be `send_compose`. - **text** (string) - Required - The command string to send. A carriage return is added automatically. ### Request Example ```json // Send a composed command { "type": "send_compose", "text": "git status" } ``` ### Response No specific success response defined for this operation, typically indicated by absence of error messages and subsequent terminal output. ``` -------------------------------- ### Terminal Connection API Source: https://context7.com/dagshub/tmux-mobile/llms.txt Establish a WebSocket connection for real-time terminal input/output after control authentication. ```APIDOC ## WebSocket Terminal Protocol - Connection ### Description Connect to the terminal WebSocket for real-time terminal I/O after control authentication. ### Method WebSocket Connection ### Endpoint `ws://:/ws/terminal` ### Parameters #### Request Body (on `open` event) - **type** (string) - Required - Must be `auth`. - **token** (string) - Required - Authentication token. - **password** (string) - Required - Authentication password. - **clientId** (string) - Required - Client ID received from the control WebSocket `auth_ok` response. ### Request Example ```javascript const terminalSocket = new WebSocket('ws://localhost:8767/ws/terminal'); terminalSocket.onopen = () => { // Authenticate with same credentials plus clientId terminalSocket.send(JSON.stringify({ type: 'auth', token: 'abc123', password: 'mypassword', clientId: 'client-xyz789' // From control auth_ok response })); }; ``` ### Response #### On Message (Terminal Output) - **event.data** (string/binary) - Raw terminal output. #### Response Example ```javascript terminalSocket.onmessage = (event) => { terminal.write(event.data); // Write to xterm.js }; ``` ``` -------------------------------- ### Scrollback Capture API Source: https://context7.com/dagshub/tmux-mobile/llms.txt Request and receive terminal scrollback history for a specific pane. ```APIDOC ## WebSocket Control Protocol - Scrollback Capture ### Description Capture terminal scrollback history for viewing in a mobile-friendly overlay. ### Method POST (via WebSocket message) ### Endpoint `ws://:/ws/control` ### Parameters #### Request Body - **type** (string) - Required - Must be `capture_scrollback`. - **paneId** (string) - Required - The ID of the pane from which to capture scrollback. - **lines** (integer) - Optional - The number of lines to capture. Defaults to server configuration. ### Request Example ```json // Request scrollback capture { "type": "capture_scrollback", "paneId": "%0", "lines": 1000 } ``` ### Response #### Success Response - **type** (string) - Will be `scrollback`. - **paneId** (string) - The ID of the pane for which scrollback was captured. - **lines** (integer) - The number of lines captured. - **text** (string) - The captured scrollback content. #### Response Example ```json { "type": "scrollback", "paneId": "%0", "lines": 1000, "text": "...scrollback content..." } ``` ``` -------------------------------- ### Authenticate WebSocket Connection (JavaScript) Source: https://context7.com/dagshub/tmux-mobile/llms.txt Establish a connection to the control WebSocket and authenticate using a token and optional password. Upon successful authentication, the server provides a clientId necessary for subsequent terminal WebSocket connections. ```javascript // Connect to control WebSocket const controlSocket = new WebSocket('ws://localhost:8767/ws/control'); controlSocket.onopen = () => { // Send authentication message (token from URL query parameter) controlSocket.send(JSON.stringify({ type: 'auth', token: 'abc123', // Required: URL token password: 'mypassword' // Optional: if password protection enabled })); }; controlSocket.onmessage = (event) => { const message = JSON.parse(event.data); if (message.type === 'auth_ok') { console.log('Authenticated, clientId:', message.clientId); // message.requiresPassword indicates if password was needed } if (message.type === 'auth_error') { console.error('Auth failed:', message.reason); // Reasons: "invalid token", "invalid password" } }; ``` -------------------------------- ### Connect to Tmux Terminal WebSocket Source: https://context7.com/dagshub/tmux-mobile/llms.txt Establish a connection to the terminal WebSocket after successful control authentication. This enables real-time terminal input and output handling. ```javascript // Connect after receiving clientId from control auth_ok const terminalSocket = new WebSocket('ws://localhost:8767/ws/terminal'); terminalSocket.onopen = () => { // Authenticate with same credentials plus clientId terminalSocket.send(JSON.stringify({ type: 'auth', token: 'abc123', password: 'mypassword', clientId: 'client-xyz789' // From control auth_ok response })); }; // Receive terminal output as raw text terminalSocket.onmessage = (event) => { terminal.write(event.data); // Write to xterm.js }; ``` -------------------------------- ### Local Server Binding (TypeScript) Source: https://github.com/dagshub/tmux-mobile/blob/main/SECURITY.md Configures the backend server to bind to localhost (127.0.0.1) by default. This limits direct network exposure, enhancing security in local development and trusted environments. ```TypeScript import http from 'http'; import { WebSocketServer } from 'ws'; // ... const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('tmux-mobile server is running.\n'); }); const wss = new WebSocketServer({ server }); const PORT = process.env.PORT || 8080; const HOST = '127.0.0.1'; // Binds to localhost by default server.listen(PORT as number, HOST, () => { console.log(`Server listening on http://${HOST}:${PORT}`); }); // WebSocket handling logic follows... ``` -------------------------------- ### Define TmuxGateway Interface (TypeScript) Source: https://context7.com/dagshub/tmux-mobile/llms.txt Defines the core interface for interacting with tmux operations, including session, window, and pane management. Implementations can be custom backends or testing mocks. It returns promises for asynchronous operations and specifies expected data structures. ```typescript interface TmuxSessionSummary {} interface TmuxWindowState {} interface TmuxPaneState {} interface TmuxGateway { // Session operations listSessions(): Promise; createSession(name: string): Promise; createGroupedSession(name: string, targetSession: string): Promise; killSession(name: string): Promise; switchClient(session: string): Promise; // Window operations listWindows(session: string): Promise[]>; newWindow(session: string): Promise; killWindow(session: string, windowIndex: number): Promise; selectWindow(session: string, windowIndex: number): Promise; // Pane operations listPanes(session: string, windowIndex: number): Promise; splitWindow(paneId: string, orientation: 'h' | 'v'): Promise; killPane(paneId: string): Promise; selectPane(paneId: string): Promise; zoomPane(paneId: string): Promise; isPaneZoomed(paneId: string): Promise; capturePane(paneId: string, lines: number): Promise; } ``` -------------------------------- ### Session Management API Source: https://context7.com/dagshub/tmux-mobile/llms.txt Manage tmux sessions by creating, selecting, and receiving state updates through the control WebSocket. ```APIDOC ## WebSocket Control Protocol - Session Management ### Description Create, select, and manage tmux sessions through the control WebSocket. ### Method POST (via WebSocket message) ### Endpoint `ws://:/ws/control` ### Parameters #### Request Body - **type** (string) - Required - The type of session operation. Possible values: `select_session`, `new_session`. - **session** (string) - Optional (required for `select_session`) - The name of the session to select. - **name** (string) - Optional (required for `new_session`) - The name for the new session. ### Request Example ```json // Select an existing session { "type": "select_session", "session": "main" } // Create a new session { "type": "new_session", "name": "dev-environment" } ``` ### Response #### Success Response (200) - **type** (string) - Indicates the type of server response. Possible values: `attached`, `session_picker`, `tmux_state`. - **session** (string) - The name of the attached session (if `type` is `attached`). - **sessions** (array) - A list of available sessions with their status (if `type` is `session_picker` or `tmux_state`). - **state** (object) - The current tmux state (if `type` is `tmux_state`). #### Response Example ```json // On successful attachment { "type": "attached", "session": "tmux-mobile-client-abc123" } // When multiple sessions exist (prompts selection) { "type": "session_picker", "sessions": [ { "name": "main", "attached": true, "windows": 3 }, { "name": "dev", "attached": false, "windows": 1 } ] } // Periodic state updates { "type": "tmux_state", "state": { "capturedAt": "2024-01-15T10:30:00.000Z", "sessions": [ { "name": "main", "attached": true, "windows": 2, "windowStates": [ { "index": 0, "name": "bash", "active": true, "paneCount": 2, "panes": [ { "index": 0, "id": "%0", "currentCommand": "vim", "active": true, "width": 120, "height": 40, "zoomed": false } ] } ] } ] } } ``` ``` -------------------------------- ### Manage Tmux Sessions via WebSocket Control Source: https://context7.com/dagshub/tmux-mobile/llms.txt Control tmux sessions by creating, selecting, and managing them through the WebSocket control interface. This includes handling server responses for session attachment and selection prompts. ```javascript // Select an existing session controlSocket.send(JSON.stringify({ type: 'select_session', session: 'main' })); // Create a new session controlSocket.send(JSON.stringify({ type: 'new_session', name: 'dev-environment' })); // Server responses: // On successful attachment // { type: 'attached', session: 'tmux-mobile-client-abc123' } // When multiple sessions exist (prompts selection) // { type: 'session_picker', sessions: [ // { name: 'main', attached: true, windows: 3 }, // { name: 'dev', attached: false, windows: 1 } // ]} // Periodic state updates (every 2.5s) // { type: 'tmux_state', state: { // capturedAt: '2024-01-15T10:30:00.000Z', // sessions: [{ // name: 'main', // attached: true, // windows: 2, // windowStates: [{ // index: 0, // name: 'bash', // active: true, // paneCount: 2, // panes: [{ // index: 0, // id: '%0', // currentCommand: 'vim', // active: true, // width: 120, // height: 40, // zoomed: false // }] // }] // }] // }} ``` -------------------------------- ### Pane Operations API Source: https://context7.com/dagshub/tmux-mobile/llms.txt Control tmux panes by selecting, splitting, zooming, and killing them. ```APIDOC ## WebSocket Control Protocol - Pane Operations ### Description Select, split, zoom, and kill tmux panes. ### Method POST (via WebSocket message) ### Endpoint `ws://:/ws/control` ### Parameters #### Request Body - **type** (string) - Required - The type of pane operation. Possible values: `select_pane`, `split_pane`, `zoom_pane`, `kill_pane`. - **paneId** (string) - Required - The ID of the pane to operate on (e.g., `%0`). - **stickyZoom** (boolean) - Optional (for `select_pane`) - Enables sticky zoom for the selected pane. - **orientation** (string) - Optional (required for `split_pane`) - The orientation for splitting the pane. Values: `h` (horizontal), `v` (vertical). ### Request Example ```json // Select a pane by ID { "type": "select_pane", "paneId": "%3", "stickyZoom": true } // Split pane horizontally { "type": "split_pane", "paneId": "%0", "orientation": "h" } // Toggle zoom on a pane { "type": "zoom_pane", "paneId": "%0" } // Kill a pane { "type": "kill_pane", "paneId": "%2" } ``` ### Response No specific success response defined for these operations, typically indicated by absence of error messages and subsequent state updates. ``` -------------------------------- ### WebSocket Control Protocol - Authentication Source: https://context7.com/dagshub/tmux-mobile/llms.txt Establishes an authenticated connection to the control WebSocket. The server provides a client ID upon successful authentication. ```APIDOC ## WebSocket Control Protocol - Authentication ### Description Authenticate with the control WebSocket to establish a session. The server responds with a client ID needed for terminal WebSocket authentication. ### Method WebSocket Connection ### Endpoint /ws/control ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (for initial auth message) - **type** (string) - Must be 'auth'. - **token** (string) - Required: The authentication token obtained from the URL query parameter. - **password** (string) - Optional: The password, if password protection is enabled on the server. ### Request Example ```javascript // Connect to control WebSocket const controlSocket = new WebSocket('ws://localhost:8767/ws/control'); controlSocket.onopen = () => { // Send authentication message (token from URL query parameter) controlSocket.send(JSON.stringify({ type: 'auth', token: 'abc123', // Required: URL token password: 'mypassword' // Optional: if password protection enabled })); }; ``` ### Response #### Success Response (onmessage event) - **type** (string) - 'auth_ok' upon successful authentication. - **clientId** (string) - A unique identifier for the authenticated client. - **requiresPassword** (boolean) - Indicates if a password was actually needed for this authentication. #### Error Response (onmessage event) - **type** (string) - 'auth_error' if authentication fails. - **reason** (string) - The reason for authentication failure (e.g., "invalid token", "invalid password"). #### Response Example (Success) ```json { "type": "auth_ok", "clientId": "unique-client-id-123", "requiresPassword": true } ``` #### Response Example (Error) ```json { "type": "auth_error", "reason": "invalid password" } ``` ``` -------------------------------- ### Manage Tmux Panes via WebSocket Control Source: https://context7.com/dagshub/tmux-mobile/llms.txt Manipulate tmux panes, including selecting by ID, splitting horizontally or vertically, toggling zoom, and killing panes, all through the WebSocket control interface. ```javascript // Select a pane by ID controlSocket.send(JSON.stringify({ type: 'select_pane', paneId: '%3', stickyZoom: true // Auto-zoom if not already zoomed })); // Split pane horizontally controlSocket.send(JSON.stringify({ type: 'split_pane', paneId: '%0', orientation: 'h' // 'h' for horizontal, 'v' for vertical })); // Toggle zoom on a pane controlSocket.send(JSON.stringify({ type: 'zoom_pane', paneId: '%0' })); // Kill a pane controlSocket.send(JSON.stringify({ type: 'kill_pane', paneId: '%2' })); ``` -------------------------------- ### Tmux Scrollback Capture Command Source: https://github.com/dagshub/tmux-mobile/blob/main/SPEC.md This command captures the scrollback buffer of a specific tmux pane. It is used by the custom scrollback viewer to retrieve historical terminal output for display on the client. ```bash tmux capture-pane -t -p -S - # Capture last N lines ``` -------------------------------- ### Capture Tmux Scrollback via WebSocket Control Source: https://context7.com/dagshub/tmux-mobile/llms.txt Request and capture terminal scrollback history for a specific pane using the WebSocket control protocol. This is useful for displaying terminal content in a mobile-friendly overlay. ```javascript // Request scrollback capture controlSocket.send(JSON.stringify({ type: 'capture_scrollback', paneId: '%0', lines: 1000 // Optional: defaults to server config })); // Server response // { type: 'scrollback', paneId: '%0', lines: 1000, text: '...' } ``` -------------------------------- ### WebSocket Authentication - Control Socket (TypeScript) Source: https://github.com/dagshub/tmux-mobile/blob/main/SECURITY.md Handles the initial authentication message on the control WebSocket. It expects a JSON object with 'type', 'token', and 'password'. Rejects invalid messages with 'auth_error'. ```TypeScript import { WebSocket } from 'ws'; // ... const controlSocket = new WebSocket('ws://localhost:8080/ws/control'); controlSocket.onopen = () => { const authMessage = { type: "auth", token: "your_token_here", password: "your_password_here" }; controlSocket.send(JSON.stringify(authMessage)); }; controlSocket.onmessage = (event) => { const message = JSON.parse(event.data as string); if (message.type === "auth_ok") { console.log("Control socket authenticated successfully."); } else if (message.type === "auth_error") { console.error("Control socket authentication failed."); } }; controlSocket.onerror = (error) => { console.error('Control socket error:', error); }; ``` -------------------------------- ### Generate Random Password (TypeScript) Source: https://github.com/dagshub/tmux-mobile/blob/main/SECURITY.md Auto-generates a random password if one is not provided. This password uses 128 bits of entropy and is used for authentication. It is stored in process memory. ```TypeScript import crypto from "crypto"; // ... const password = crypto.randomBytes(16).toString("base64url"); console.log(password); // Example output: XyZwVbUqRtPsOnMlKj ``` -------------------------------- ### Generate Random Token (TypeScript) Source: https://github.com/dagshub/tmux-mobile/blob/main/SECURITY.md Generates a secure random token using Node.js crypto module. This token is used for authentication in tmux-mobile. The default size provides 144 bits of entropy. ```TypeScript import crypto from "crypto"; // ... const token = crypto.randomBytes(18).toString("base64url"); console.log(token); // Example output: aBcDeFgHiJkLmNoPqRs ```