### Example Test Script - Application Testing Source: https://github.com/fcoury/termwright/blob/master/README.md An example bash script demonstrating how to use the reusable test library to automate testing of a terminal application, including setup, running tests, and assertions. ```bash # test_my_app.sh source "$(dirname "$0")/lib.sh" SOCK="/tmp/test-$$.sock" termwright daemon --socket "$SOCK" -- ./my-app & while [ ! -S "$SOCK" ]; do sleep 0.1; done # Wait for app to initialize wait_idle "$SOCK" > /dev/null # Run tests assert_contains "$SOCK" "Main Menu" "App shows main menu" press "$SOCK" "Enter" wait_idle "$SOCK" > /dev/null assert_contains "$SOCK" "Settings" "Enter opens settings" ctrl "$SOCK" "q" echo "All tests passed!" ``` -------------------------------- ### Hotkey Examples Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/protocol-reference.md Examples demonstrating different modifier key combinations for the 'hotkey' method. ```json {"ctrl": true, "ch": "c"} ``` ```json {"alt": true, "ch": "x"} ``` ```json {"ctrl": true, "alt": true, "ch": "d"} ``` -------------------------------- ### Complete Example Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md A full example of a Termwright step file demonstrating various configurations and steps. ```APIDOC ## Complete Example ```yaml # test-vim-editing.yaml session: command: vim args: [test.txt] cols: 120 rows: 40 env: TERM: xterm-256color steps: # Wait for vim to load - waitForText: {text: "VIM", timeoutMs: 5000} # Enter insert mode - press: {key: i} - waitForText: {text: "-- INSERT --"} # Type content - type: {text: "Hello, Termwright!"} # Exit insert mode - press: {key: Escape} # Verify content - expectText: {text: "Hello, Termwright!", timeoutMs: 3000} # Take screenshot - screenshot: {name: vim-with-content} # Save and quit - type: {text: ":wq"} - press: {key: Enter} artifacts: mode: always dir: ./test-output ``` ``` -------------------------------- ### Complete Example: Vim Editing Test Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md A comprehensive example demonstrating a test case for editing a file in Vim using `termwright`. It includes session setup, waiting for UI elements, inputting text, assertions, and saving artifacts. ```yaml # test-vim-editing.yaml session: command: vim args: [test.txt] cols: 120 rows: 40 env: TERM: xterm-256color steps: # Wait for vim to load - waitForText: {text: "VIM", timeoutMs: 5000} # Enter insert mode - press: {key: i} - waitForText: {text: "-- INSERT --"} # Type content - type: {text: "Hello, Termwright!"} # Exit insert mode - press: {key: Escape} # Verify content - expectText: {text: "Hello, Termwright!", timeoutMs: 3000} # Take screenshot - screenshot: {name: vim-with-content} # Save and quit - type: {text: ":wq"} - press: {key: Enter} artifacts: mode: always dir: ./test-output ``` -------------------------------- ### Command Format: String Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md Example of specifying the command and arguments as separate string and array. ```yaml command: vim args: [test.txt] # Equivalent to: vim test.txt ``` -------------------------------- ### Termwright Step File Example Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing-focused/SKILL.md An example YAML file defining a TUI testing workflow for Vim. It includes session configuration, a sequence of steps like waiting for text, typing, and assertions, and artifact saving behavior. ```yaml session: command: ["vim", "test.txt"] cols: 120 rows: 40 steps: - waitForText: {text: "VIM", timeoutMs: 5000} - press: {key: i} - type: {text: "Hello"} - press: {key: Escape} - expectText: {text: "Hello"} - notExpectText: {text: "ERROR"} - screenshot: {name: "vim-content"} artifacts: mode: onFailure dir: ./termwright-artifacts ``` -------------------------------- ### Start Daemon with Default Socket Source: https://context7.com/fcoury/termwright/llms.txt Start the Termwright daemon in the foreground, printing the socket path. ```bash # Start daemon (foreground, prints socket path) termwright daemon -- vim test.txt ``` -------------------------------- ### Install Termwright CLI Source: https://github.com/fcoury/termwright/blob/master/README.md Install the Termwright command-line interface using Cargo. ```bash cargo install termwright ``` -------------------------------- ### YAML Steps: Wait for App Startup Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/SKILL.md This YAML snippet demonstrates waiting for the application to become idle and then for specific text to appear, ensuring the app has started correctly. ```yaml steps: - waitForIdle: {idleMs: 1000, timeoutMs: 10000} - waitForText: {text: "Ready", timeoutMs: 5000} ``` -------------------------------- ### Connect and Send Messages Example Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/protocol-reference.md Demonstrates connecting to the Termwright daemon via a Unix domain socket and sending various commands. ```bash # Connect and send messages $ echo '{"id":1,"method":"handshake","params":null}' | nc -U /tmp/termwright-123.sock {"id":1,"result":{"protocol_version":1,"termwright_version":"0.1.1","pid":12345},"error":null} $ echo '{"id":2,"method":"wait_for_text","params":{"text":"Ready","timeout_ms":5000}}' | nc -U /tmp/termwright-123.sock {"id":2,"result":null,"error":null} $ echo '{"id":3,"method":"press","params":{"key":"Enter"}}' | nc -U /tmp/termwright-123.sock {"id":3,"result":null,"error":null} $ echo '{"id":4,"method":"screen","params":{"format":"text"}}' | nc -U /tmp/termwright-123.sock {"id":4,"result":"Welcome to the app\n> ","error":null} ``` -------------------------------- ### Basic Termwright Test Script Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/examples.md This bash script demonstrates a basic Termwright test workflow. It starts a Termwright daemon in the background, sets up a trap for cleanup, and then uses `termwright exec` to interact with the application (handshake, wait for text, type, press keys, get screen content, and take a screenshot). This script is suitable for simple, sequential TUI testing. ```bash #!/bin/bash set -euo pipefail # Start daemon in background SOCK=$(termwright daemon --background -- ./my-app) echo "Started daemon with socket: $SOCK" # Cleanup on exit trap "termwright exec --socket '$SOCK' --method close 2>/dev/null || true" EXIT # Wait for socket to be available while ! [ -S "$SOCK" ]; do sleep 0.1; done # Helper function tw() { termwright exec --socket "$SOCK" --method "$1" --params "${2:-null}" } # Run tests echo "Testing..." # 1. Handshake tw handshake echo "Handshake OK" # 2. Wait for app ready tw wait_for_text '{"text":"Ready","timeout_ms":10000}' echo "App ready" # 3. Interact tw press '{"key":"Enter"}' tw type '{"text":"hello"}' tw press '{"key":"Enter"}' # 4. Verify SCREEN=$(tw screen '{"format":"text"}' | jq -r '.result') if echo "$SCREEN" | grep -q "hello"; then echo "PASS: Text found" else echo "FAIL: Expected text not found" echo "Screen content:" echo "$SCREEN" exit 1 fi # 5. Screenshot tw screenshot | jq -r '.result.png_base64' | base64 -d > result.png echo "Screenshot saved to result.png" echo "All tests passed!" ``` -------------------------------- ### Shell Scripting with Termwright Daemon Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/SKILL.md Custom test scripts can be created using bash, interacting with the termwright daemon. This example demonstrates starting a daemon, executing commands, and capturing output. ```bash #!/bin/bash set -euo pipefail # Start daemon SOCK=$(termwright daemon --background -- htop) trap "termwright exec --socket '$SOCK' --method close 2>/dev/null || true" EXIT # Wait for socket while ! [ -S "$SOCK" ]; do sleep 0.1; done # Helper tw() { termwright exec --socket "$SOCK" --method "$1" --params "${2:-null}" } # Test sequence tw handshake tw wait_for_idle '{"idle_ms":1000,"timeout_ms":10000}' # Verify content SCREEN=$(tw screen '{"format":"text"}' | jq -r '.result') if echo "$SCREEN" | grep -q "CPU"; then echo "PASS: htop loaded" else echo "FAIL: CPU info not found" exit 1 fi # Screenshot tw screenshot | jq -r '.result.png_base64' | base64 -d > htop.png echo "Screenshot saved to htop.png" ``` -------------------------------- ### Start Termwright Hub with Custom Dimensions Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/cli-reference.md Starts Termwright hub sessions with specified counts and dimensions. Use this to initialize multiple Termwright daemons with custom terminal sizes. ```bash termwright hub start --count 3 --cols 120 --rows 40 -- vim ``` -------------------------------- ### Screen Response (JSON Compact Format) Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/protocol-reference.md Example response for the 'screen' method when requesting 'json_compact' format, providing screen size and lines as strings. ```json { "size": {"cols": 80, "rows": 24}, "cursor": {"row": 0, "col": 0}, "lines": ["line 1", "line 2", ...] } ``` -------------------------------- ### Install Helper Tools for Shell Scripting Source: https://github.com/fcoury/termwright/blob/master/README.md Installs necessary helper tools like socat and jq for interacting with the Termwright daemon from shell scripts. Commands are provided for macOS and Ubuntu/Debian. ```bash # Install termwright cargo install termwright # Install helper tools brew install socat jq # macOS # or: sudo apt-get install socat jq # Ubuntu/Debian ``` -------------------------------- ### termwright hub start Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/cli-reference.md Start multiple Termwright daemon sessions concurrently. ```APIDOC ## termwright hub start Start multiple daemon sessions. ### Usage ```bash termwright hub start [OPTIONS] -- [ARGS...] ``` ### Options | Option | Default | Description | |--------|---------|-------------| | `--count ` | 1 | Number of sessions | | `--cols ` | 80 | Terminal width | | `--rows ` | 24 | Terminal height | | `--output ` | - | Write session info to JSON | ### Output JSON array of session entries. ### Examples ```bash # Start 5 parallel sessions termwright hub start --count 5 --output sessions.json -- ./my-app ``` ``` -------------------------------- ### Start Daemon with Custom Terminal Size Source: https://context7.com/fcoury/termwright/llms.txt Configure the terminal size (columns and rows) for a daemon session. ```bash # Custom terminal size termwright daemon --cols 120 --rows 40 -- htop ``` -------------------------------- ### Command Format: Array Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md Example of specifying the command as an array, where arguments are included within the array itself. The `args` field is ignored in this format. ```yaml command: ["sh", "-c", "echo hello && vim"] # args is ignored when command is array ``` -------------------------------- ### Shell Script Automation Example Source: https://context7.com/fcoury/termwright/llms.txt Example of automating terminal interactions using a shell script and Termwright daemon with JSON-RPC. ```bash # Shell script automation example SOCK=$(termwright daemon --background -- ./my-app) tw() { echo "$1" | socat - UNIX-CONNECT:"$SOCK"; } tw '{"id":1,"method":"wait_for_text","params":{"text":"Ready","timeout_ms":5000}}' tw '{"id":2,"method":"type","params":{"text":"hello"}}' tw '{"id":3,"method":"press","params":{"key":"Enter"}}' tw '{"id":4,"method":"screen","params":{"format":"text"}}' | jq -r '.result' tw '{"id":5,"method":"close","params":null}' ``` -------------------------------- ### Start multiple daemon sessions Source: https://github.com/fcoury/termwright/blob/master/README.md Use `termwright hub start` to launch parallel agent sessions. Specify the number of sessions, terminal dimensions, and the command to run. ```bash termwright hub start --count [--cols ] [--rows ] [--output ] -- [ARGS]... ``` -------------------------------- ### Start Hub Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/cli-reference.md Initiate multiple daemon sessions concurrently. Useful for running parallel tests or managing multiple terminal applications. Can output session information to a JSON file. ```bash termwright hub start [OPTIONS] -- [ARGS...] ``` ```bash # Start 5 parallel sessions termwright hub start --count 5 --output sessions.json -- ./my-app ``` -------------------------------- ### YAML Test Steps Definition Source: https://context7.com/fcoury/termwright/llms.txt Example of a YAML file defining a test session, environment, artifacts, and sequential steps for terminal automation. ```yaml # test-steps.yaml session: command: ["./my-app", "--config", "test.json"] cols: 80 rows: 24 env: DEBUG: "1" artifacts: mode: onFailure dir: ./test-artifacts steps: - waitForText: text: "Welcome" timeoutMs: 5000 - type: text: "admin" - press: key: Tab - type: text: "password123" - press: key: Enter - waitForText: text: "Dashboard" timeoutMs: 10000 - expectText: text: "Logged in as admin" - notExpectText: text: "Error" - screenshot: name: "dashboard" - hotkey: ctrl: true ch: q - waitForIdle: idleMs: 500 timeoutMs: 5000 ``` -------------------------------- ### Start Daemon with Custom Socket Path Source: https://context7.com/fcoury/termwright/llms.txt Launch the Termwright daemon and specify a custom path for the Unix socket. ```bash # Start with custom socket path termwright daemon --socket /tmp/my-app.sock -- ./my-app ``` -------------------------------- ### Build and spawn a terminal process Source: https://github.com/fcoury/termwright/blob/master/README.md Use `Terminal::builder()` to configure and spawn a terminal process. Control size, command, and arguments. Includes examples for input, screen access, wait conditions, and screenshots. ```rust let term = Terminal::builder() .size(80, 24) .spawn("vim", &["file.txt"]) .await?; // Input term.type_str("hello").await?; term.send_key(Key::Enter).await?; term.enter().await?; // Shorthand for Enter key // Screen access let screen = term.screen().await; // Wait conditions term.expect("Ready").timeout(Duration::from_secs(5)).await?; term.wait_exit().await?; // Screenshots term.screenshot().await.save("output.png")?; ``` -------------------------------- ### Termwright YAML Step File Example Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/SKILL.md A sample YAML file defining a Termwright test session. It includes session configuration (command, arguments, dimensions), a sequence of steps (waiting for text, typing, asserting, capturing screenshots), and artifact configuration for saving test outputs. ```yaml session: command: vim args: [test.txt] cols: 120 rows: 40 steps: - waitForText: {text: "VIM", timeoutMs: 5000} - press: {key: i} - type: {text: "Hello, world!"} - press: {key: Escape} - expectText: {text: "Hello, world!"} - screenshot: {name: vim-content} - type: {text: ":q!"} - press: {key: Enter} artifacts: mode: always dir: ./test-artifacts ``` -------------------------------- ### Example Output of `termwright fonts` Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/cli-reference.md Example output showing a list of monospace font names. These are the fonts that Termwright can utilize for rendering text in screenshots. ```text $ termwright fonts Menlo Monaco SF Mono JetBrains Mono Fira Code ``` -------------------------------- ### Screen Response (JSON Format) Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/protocol-reference.md Example response for the 'screen' method when requesting 'json' format, detailing screen size, cursor position, and cell content. ```json { "size": {"cols": 80, "rows": 24}, "cursor": {"row": 0, "col": 0}, "cells": [ [ { "char": "H", "fg": {"type": "Default"}, "bg": {"type": "Indexed", "value": 0}, "attrs": { "bold": false, "italic": false, "underline": false, "inverse": false } } ] ] } ``` -------------------------------- ### Termwright Hub Start Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/cli-reference.md Starts Termwright daemon sessions. You can specify the number of sessions, columns, and rows. Optionally, you can specify a terminal emulator like 'vim'. ```APIDOC ## termwright hub start ### Description Starts Termwright daemon sessions. ### Method CLI Command ### Endpoint N/A ### Parameters #### Query Parameters - **count** (integer) - Optional - Number of sessions to start. - **cols** (integer) - Optional - Number of columns for the terminal. - **rows** (integer) - Optional - Number of rows for the terminal. - **vim** (flag) - Optional - Use vim as the terminal emulator. ### Request Example ```bash termwright hub start --count 3 --cols 120 --rows 40 -- vim ``` ### Response #### Success Response (200) Returns a JSON array of session objects, each containing a socket path and PID. #### Response Example ```json [ {"socket": "/tmp/termwright-12345.sock", "pid": 12345}, {"socket": "/tmp/termwright-12346.sock", "pid": 12346} ] ``` ``` -------------------------------- ### Start Termwright Daemon and Execute Commands Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/SKILL.md Start the Termwright daemon in the background and capture its socket path. Then, use 'termwright exec' to send various commands to the daemon, including handshake, waiting for text, pressing keys, typing text, capturing the screen, and closing the daemon. ```bash SOCK=$(termwright daemon --background -- vim test.txt) ``` ```bash termwright exec --socket "$SOCK" --method handshake ``` ```bash termwright exec --socket "$SOCK" --method wait_for_text --params '{"text":"VIM","timeout_ms":5000}' ``` ```bash termwright exec --socket "$SOCK" --method press --params '{"key":"i"}' ``` ```bash termwright exec --socket "$SOCK" --method type --params '{"text":"Hello"}' ``` ```bash termwright exec --socket "$SOCK" --method screen --params '{"format":"text"}' ``` ```bash termwright exec --socket "$SOCK" --method close ``` -------------------------------- ### JSON-RPC: Get Screen Content (Text) Source: https://context7.com/fcoury/termwright/llms.txt Retrieve the current terminal screen content as plain text. ```bash # screen - Get screen content tw '{"id":2,"method":"screen","params":{"format":"text"}}' # Response: {"id":2,"result":"Screen content here..."} ``` -------------------------------- ### Termwright Daemon Protocol Request Example Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/SKILL.md Example of a JSON request sent to the Termwright daemon via a Unix socket. This specific request is for retrieving screen content in text format. ```json {"id": 1, "method": "screen", "params": {"format": "text"}} ``` -------------------------------- ### Conventional Commit Example: Feature Source: https://github.com/fcoury/termwright/blob/master/AGENTS.md Use this format for new features. Specify the affected area in the scope. ```git feat(ui): add project explorer folder interactions ``` -------------------------------- ### Conventional Commit Example: Fix Source: https://github.com/fcoury/termwright/blob/master/AGENTS.md Use this format for bug fixes. Specify the component in the scope. ```git fix(ghostty): correct HiDPI mouse coordinates in embedded terminal ``` -------------------------------- ### JSON-RPC: Handshake Source: https://context7.com/fcoury/termwright/llms.txt Initiate a handshake with the daemon to get protocol and version information. ```bash # handshake - Get daemon info tw '{"id":1,"method":"handshake","params":null}' # Response: {"id":1,"result":{"protocol_version":1,"termwright_version":"0.2.0","pid":12345}} ``` -------------------------------- ### GitHub Actions Workflow for Termwright Tests Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/examples.md This GitHub Actions workflow demonstrates how to install Termwright, build an application, and run TUI end-to-end tests using `termwright run-steps`. ```yaml # .github/workflows/tui-tests.yml name: TUI Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Termwright run: cargo install termwright - name: Build app run: cargo build --release - name: Run TUI tests run: termwright run-steps --trace tests/e2e.yaml - name: Upload artifacts on failure if: failure() uses: actions/upload-artifact@v4 with: name: tui-test-artifacts path: termwright-artifacts/ ``` -------------------------------- ### Conventional Commit Example: Chore Source: https://github.com/fcoury/termwright/blob/master/AGENTS.md Use this format for maintenance tasks or build process changes. Specify the relevant system in the scope. ```git chore(tauri): enable MCP debug capability ``` -------------------------------- ### Start Parallel Daemon Sessions Source: https://context7.com/fcoury/termwright/llms.txt Launch multiple Termwright daemon sessions in parallel and save their socket information. ```bash # Start 5 parallel sessions termwright hub start --count 5 --output sessions.json -- ./my-app ``` -------------------------------- ### Basic Shell Scripting Pattern for TUI Testing Source: https://github.com/fcoury/termwright/blob/master/README.md A comprehensive shell script demonstrating the workflow for E2E testing TUI applications using Termwright's daemon mode, including starting the daemon, sending commands, reading output, and taking screenshots. ```bash #!/bin/bash set -euo pipefail # 1. Start the daemon with your TUI app SOCK="/tmp/my-test-$$.sock" termwright daemon --socket "$SOCK" --cols 80 --rows 24 -- ./my-tui-app & # Wait for socket while [ ! -S "$SOCK" ]; do sleep 0.1; done # 2. Helper function to send commands tw() { echo "$1" | socat - UNIX-CONNECT:"$SOCK" } # 3. Wait for app to be ready tw '{"id":1,"method":"wait_for_text","params":{"text":"Welcome","timeout_ms":5000}}' # 4. Interact with the app tw '{"id":2,"method":"press","params":{"key":"Enter"}}' tw '{"id":3,"method":"type","params":{"text":"hello world"}}' tw '{"id":4,"method":"hotkey","params":{"ctrl":true,"ch":"s"}}' # Ctrl+S # 5. Read screen content SCREEN=$(tw '{"id":5,"method":"screen","params":{"format":"text"}}' | jq -r '.result') echo "$SCREEN" # 6. Take a screenshot RESULT=$(tw '{"id":6,"method":"screenshot","params":{}}') echo "$RESULT" | jq -r '.result.png_base64' | base64 -d > screenshot.png # 7. Clean up tw '{"id":99,"method":"close","params":null}' ``` -------------------------------- ### Termwright JSON Configuration Example Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md This JSON defines a terminal session, including the command to run, arguments, terminal dimensions, a sequence of steps to execute, and artifact collection settings. Use this format to script terminal interactions. ```json { "session": { "command": "vim", "args": ["test.txt"], "cols": 120, "rows": 40 }, "steps": [ {"waitForText": {"text": "VIM", "timeoutMs": 5000}}, {"press": {"key": "i"}}, {"type": {"text": "Hello"}}, {"press": {"key": "Escape"}}, {"expectText": {"text": "Hello"}}, {"screenshot": {"name": "result"}} ], "artifacts": { "mode": "always", "dir": "./output" } } ``` -------------------------------- ### Execute One-off Commands with Termwright Daemon Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing-focused/SKILL.md Interact with a running application via the Termwright daemon. This example starts Vim in the background, executes a `screen` method to capture its state, and then closes the daemon socket. ```bash SOCK=$(termwright daemon --background -- vim test.txt) termwright exec --socket "$SOCK" --method screen --params '{"format":"text"}' termwright exec --socket "$SOCK" --method close ``` -------------------------------- ### Basic Library Usage with Vim Source: https://github.com/fcoury/termwright/blob/master/README.md Demonstrates spawning Vim, interacting with it via keyboard input, querying screen state, and taking a screenshot using Termwright's library API. ```rust use termwright::prelude::*; #[tokio::main] async fn main() -> Result<()> { // Spawn a terminal application let term = Terminal::builder() .size(80, 24) .spawn("vim", &["test.txt"]) .await?; // Wait for the application to be ready term.expect("VIM") .timeout(Duration::from_secs(5)) .await?; // Send input term.send_key(Key::Char('i')).await?; term.type_str("Hello, world!").await?; term.send_key(Key::Escape).await?; // Query screen state let screen = term.screen().await; assert!(screen.contains("Hello, world!")); // Get structured output for AI agents println!("{}", screen.to_json()?); // Take a screenshot term.screenshot().await.save("vim.png")?; // Quit the application term.type_str(":q!").await?; term.enter().await?; term.wait_exit().await?; Ok(()) } ``` -------------------------------- ### YAML Steps: Navigation and Selection Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/SKILL.md This YAML snippet demonstrates navigating through a list using the 'Down' key, selecting an item with 'Enter', and then expecting specific text to confirm the selection. ```yaml steps: - press: {key: "Down"} - press: {key: "Down"} - press: {key: "Enter"} - expectText: {text: "Selected item"} ``` -------------------------------- ### Run Steps Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/cli-reference.md Execute a sequence of commands defined in a YAML or JSON file. Supports connecting to an existing daemon and tracing execution. ```bash termwright run-steps [OPTIONS] ``` ```bash # Run step file termwright run-steps test.yaml ``` ```bash # Run with trace output termwright run-steps --trace integration-test.yaml ``` ```bash # Connect to existing daemon termwright run-steps --connect /tmp/termwright-123.sock steps.yaml ``` -------------------------------- ### Run Steps File with Trace Source: https://context7.com/fcoury/termwright/llms.txt Execute a steps file and enable trace output for debugging. ```bash # Run with trace output termwright run-steps --trace test-steps.yaml ``` -------------------------------- ### Execute Screen Method with Compact JSON Output Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/examples.md Use this command to execute the 'screen' method and capture compact JSON output, including cursor position. Requires jq to parse the result. ```bash termwright exec --socket "$SOCK" --method screen \ --params '{"format":"json_compact"}' | jq '.result' ``` -------------------------------- ### Start Termwright Daemon in Background Source: https://github.com/fcoury/termwright/blob/master/README.md Starts a Termwright daemon session in the background, allowing the script to continue execution immediately. The socket path is captured into a variable. ```bash SOCK=$(termwright daemon --background -- vim test.txt) echo "$SOCK" ``` -------------------------------- ### Execute Screen Method with Full JSON Output Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/examples.md Use this command to execute the 'screen' method and capture the full JSON output. Requires jq to parse the result. ```bash termwright exec --socket "$SOCK" --method screen \ --params '{"format":"json"}' | jq '.result' > screen.json ``` -------------------------------- ### Execute Screen Method with Plain Text Output Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/examples.md Use this command to execute the 'screen' method and capture the output as plain text. Requires jq to extract the result. ```bash termwright exec --socket "$SOCK" --method screen \ --params '{"format":"text"}' | jq -r '.result' ``` -------------------------------- ### Input Steps Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md Steps that simulate user input, such as typing or pressing keys. ```APIDOC ## Input Steps ### `press` Press a single key. ```yaml - press: {key: Enter} - press: {key: Escape} - press: {key: Tab} - press: {key: F1} - press: {key: Down} ``` **Valid keys:** - Navigation: `Up`, `Down`, `Left`, `Right`, `Home`, `End`, `PageUp`, `PageDown` - Special: `Enter`, `Tab`, `Escape`, `Backspace`, `Delete`, `Insert` - Function: `F1` - `F12` - Characters: `a`, `A`, `1`, `@`, etc. ### `type` Type a text string. ```yaml - type: {text: "Hello, world!"} - type: {text: ":wq"} ``` ### `hotkey` Send modifier key combination. ```yaml - hotkey: {ctrl: true, ch: c} # Ctrl+C - hotkey: {alt: true, ch: x} # Alt+X - hotkey: {ctrl: true, alt: true, ch: d} # Ctrl+Alt+D ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `ctrl` | boolean | false | Hold Ctrl | | `alt` | boolean | false | Hold Alt | | `ch` | string | Required | Single character | ``` -------------------------------- ### Start and Stop Termwright Parallel Sessions Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing-focused/SKILL.md Manage multiple parallel TUI sessions using Termwright Hub. Start a specified number of sessions, outputting their configurations, and later stop them using an input file. ```bash termwright hub start --count 3 --output sessions.json -- ./my-app termwright hub stop --input sessions.json ``` -------------------------------- ### Termwright Daemon Protocol Response Example Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/SKILL.md Example of a JSON response received from the Termwright daemon. It includes an ID to match the request, a 'result' field containing the data (e.g., screen content), or an 'error' field if the operation failed. ```json {"id": 1, "result": "screen content...", "error": null} ``` -------------------------------- ### Basic Screenshot Source: https://context7.com/fcoury/termwright/llms.txt Take a PNG screenshot of a terminal application and save it to a file. ```bash # Basic screenshot termwright screenshot -o app.png -- ./my-app ``` -------------------------------- ### termwright daemon Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/cli-reference.md Start a long-lived Termwright daemon process. ```APIDOC ## termwright daemon Start a long-lived daemon. ### Usage ```bash termwright daemon [OPTIONS] -- [ARGS...] ``` ### Options | Option | Default | Description | |--------|---------|-------------| | `--cols ` | 80 | Terminal width | | `--rows ` | 24 | Terminal height | | `--socket ` | auto | Unix socket path | | `--background` | false | Run in background | ### Output Prints socket path to stdout. ### Examples ```bash # Start daemon in foreground termwright daemon -- vim test.txt # Socket path printed, daemon runs until Ctrl+C # Start in background SOCK=$(termwright daemon --background -- vim test.txt) echo "Socket: $SOCK" # Custom dimensions termwright daemon --cols 120 --rows 40 --background -- htop # Specify socket path termwright daemon --socket /tmp/my-session.sock -- ./my-app ``` ``` -------------------------------- ### Run Steps File Source: https://context7.com/fcoury/termwright/llms.txt Execute a sequence of terminal automation steps defined in a YAML file. ```bash # Run steps file termwright run-steps test-steps.yaml ``` -------------------------------- ### Build and Spawn Terminals with Termwright Source: https://context7.com/fcoury/termwright/llms.txt Demonstrates creating terminal instances with default and custom configurations, including size, environment variables, and working directory. Use this to set up your terminal environment before interaction. ```rust use termwright::prelude::*; use std::time::Duration; #[tokio::main] async fn main() -> Result<()> { // Basic terminal spawn with default 80x24 size let term = Terminal::builder() .spawn("vim", &["test.txt"]) .await?; // Custom size terminal let term = Terminal::builder() .size(120, 40) .spawn("htop", &[]) .await?; // Terminal with environment variables and working directory let term = Terminal::builder() .size(80, 24) .env("EDITOR", "vim") .env("LANG", "en_US.UTF-8") .working_dir("/tmp") .timeout(Duration::from_secs(60)) .spawn("bash", &["-c", "echo $EDITOR"]) .await?; // Disable default TERM/COLORTERM injection let term = Terminal::builder() .no_default_env() .no_osc_emulation() .spawn("my-app", &[]) .await?; Ok(()) } ``` -------------------------------- ### Start Daemon in Background Source: https://context7.com/fcoury/termwright/llms.txt Run the Termwright daemon in the background and capture its socket path for later use. ```bash # Start in background (returns immediately) SOCK=$(termwright daemon --background -- vim test.txt) echo "Socket: $SOCK" ``` -------------------------------- ### Send Keyboard Input to Terminal Source: https://context7.com/fcoury/termwright/llms.txt Shows how to send various keystrokes, including regular text, special keys, and control sequences, to a terminal instance. Use these methods for simulating user input. ```rust use termwright::prelude::*; #[tokio::main] async fn main() -> Result<()> { let term = Terminal::builder() .size(80, 24) .spawn("vim", &["test.txt"]) .await?; // Type regular text term.type_str("Hello, world!").await?; // Send individual keys term.send_key(Key::Enter).await?; term.send_key(Key::Escape).await?; term.send_key(Key::Tab).await?; // Shorthand methods term.enter().await?; // Press Enter term.escape().await?; // Press Escape // Arrow keys and navigation term.send_key(Key::Up).await?; term.send_key(Key::Down).await?; term.send_key(Key::Left).await?; term.send_key(Key::Right).await?; term.send_key(Key::Home).await?; term.send_key(Key::End).await?; term.send_key(Key::PageUp).await?; term.send_key(Key::PageDown).await?; // Function keys term.send_key(Key::F(1)).await?; term.send_key(Key::F(12)).await?; // Control and Alt combinations term.send_key(Key::Ctrl('c')).await?; // Ctrl+C term.send_key(Key::Ctrl('z')).await?; // Ctrl+Z term.send_key(Key::Alt('x')).await?; // Alt+X // Send raw bytes for custom escape sequences term.send_raw(b"\x1b[?25h").await?; // Show cursor Ok(()) } ``` -------------------------------- ### Capture Steps Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md Steps used to capture output, such as screenshots. ```APIDOC ## Capture Steps ### `screenshot` Capture PNG screenshot to artifacts directory. ```yaml - screenshot: {} # Auto-named: step-001-screenshot.png - screenshot: {name: "final-result"} # Named: final-result.png ``` ``` -------------------------------- ### JSON-RPC: Press Key Source: https://context7.com/fcoury/termwright/llms.txt Simulate pressing a specific key on the keyboard. ```bash # press - Press a key tw '{"id":6,"method":"press","params":{"key":"Enter"}}' tw '{"id":7,"method":"press","params":{"key":"Escape"}}' tw '{"id":8,"method":"press","params":{"key":"F1"}}' tw '{"id":9,"method":"press","params":{"key":"Up"}}' ``` -------------------------------- ### Session Configuration Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md Defines the session settings for running steps, including the command to execute and its arguments. ```APIDOC ## Session Configuration ```yaml session: command: vim # Required: string or array args: [test.txt] # Optional: arguments cols: 120 # Optional: width (default: 80) rows: 40 # Optional: height (default: 24) env: # Optional: environment TERM: xterm-256color EDITOR: vim cwd: /home/user # Optional: working directory ``` ### Fields | Field | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | `command` | string/array | Yes | - | Command to run | | `args` | array | No | `[]` | Arguments (ignored if command is array) | | `cols` | integer | No | 80 | Terminal width | | `rows` | integer | No | 24 | Terminal height | | `env` | object | No | `{}` | Environment variables | | `cwd` | string | No | current | Working directory | ### Command Formats **String format:** ```yaml command: vim args: [test.txt] # Equivalent to: vim test.txt ``` **Array format:** ```yaml command: ["sh", "-c", "echo hello && vim"] # args is ignored when command is array ``` ``` -------------------------------- ### Test htop with Termwright Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/examples.md This YAML configuration demonstrates testing the `htop` process viewer using Termwright. It includes steps to wait for `htop` to load, open and close the help screen, switch to the tree view, and quit the application. Use this to automate `htop` interactions and verify its state. ```yaml # test-htop.yaml session: command: htop cols: 120 rows: 40 steps: # Wait for htop to load - waitForIdle: {idleMs: 1000, timeoutMs: 10000} - expectText: {text: "CPU", timeoutMs: 5000} - screenshot: {name: "htop-loaded"} # Open help - press: {key: "?"} - waitForText: {text: "Help", timeoutMs: 2000} - screenshot: {name: "htop-help"} # Close help - press: {key: Escape} - waitForIdle: {idleMs: 500} # Open tree view - press: {key: "t"} - waitForIdle: {idleMs: 500} - screenshot: {name: "htop-tree"} # Quit - press: {key: "q"} artifacts: mode: always dir: ./htop-test ``` -------------------------------- ### Start Daemon Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/cli-reference.md Launch a long-lived Termwright daemon process. The daemon runs in the foreground by default and prints its socket path. Can be run in the background. ```bash termwright daemon [OPTIONS] -- [ARGS...] ``` ```bash # Start daemon in foreground termwright daemon -- vim test.txt # Socket path printed, daemon runs until Ctrl+C ``` ```bash # Start in background SOCK=$(termwright daemon --background -- vim test.txt) echo "Socket: $SOCK" ``` ```bash # Custom dimensions termwright daemon --cols 120 --rows 40 --background -- htop ``` ```bash # Specify socket path termwright daemon --socket /tmp/my-session.sock -- ./my-app ``` -------------------------------- ### Session Configuration Options Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md Specifies how to configure the terminal session, including the command to run, arguments, dimensions, and environment variables. ```yaml session: command: vim # Required: string or array args: [test.txt] # Optional: arguments cols: 120 # Optional: width (default: 80) rows: 40 # Optional: height (default: 24) env: TERM: xterm-256color EDITOR: vim cwd: /home/user # Optional: working directory ``` -------------------------------- ### YAML Steps: Form Input Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/SKILL.md This YAML snippet illustrates how to input text into form fields, using 'type' for text entry and 'press' with 'Tab' to move between fields. ```yaml steps: - waitForText: {text: "Username:"} - type: {text: "admin"} - press: {key: "Tab"} - type: {text: "password123"} - press: {key: "Enter"} ``` -------------------------------- ### Termwright Daemon Commands Source: https://github.com/fcoury/termwright/blob/master/README.md Available commands for interacting with the Termwright daemon, including getting daemon info, screen content, screenshots, and sending input. ```bash termwright daemon --socket "$SOCK" -- ./my-app & ``` -------------------------------- ### Basic Step File Structure Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/step-schema.md Defines the top-level structure of a step file, including session, steps, and artifacts. ```yaml session: # Session configuration steps: # List of test steps artifacts: # Output configuration ``` -------------------------------- ### Termwright Negative Assertions Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing-focused/SKILL.md Examples of negative assertions in Termwright step files. These check for the absence of specific text, patterns, or the disappearance of elements within a timeout. ```yaml steps: - notExpectText: {text: "ERROR"} - notExpectPattern: {pattern: "fail|crash"} - waitForTextGone: {text: "Loading...", timeoutMs: 5000} ``` -------------------------------- ### Resize Method Parameters Source: https://github.com/fcoury/termwright/blob/master/skills/termwright-tui-testing/references/protocol-reference.md Parameters for the 'resize' method to set the terminal dimensions. ```json { "cols": 120, "rows": 40 } ``` -------------------------------- ### CLI Reference Source: https://github.com/fcoury/termwright/blob/master/README.md Command-line interface tools for running and capturing terminal output. ```APIDOC ## CLI Reference ### Global Options Global options apply to any command that spawns a terminal: - `--no-default-env`: Disable default terminal env handling (`TERM`/`COLORTERM` injection and clearing inherited `NO_COLOR`). - `--no-osc-emulation`: Disable OSC 10/11/12 color query emulation. Terminal query emulation defaults to on for OSC 10/11/12 and CSI 6n/?6n cursor-position requests. ### `termwright fonts` List available font families on the system (helpful for selecting a monospace font for screenshots). ```bash termwright fonts ``` ### `termwright run` Run a command and capture its output. ```bash termwright run [OPTIONS] -- [ARGS]... Options: --cols Terminal width [default: 80] --rows Terminal height [default: 24] --wait-for Wait for this text to appear before capturing --delay Delay in milliseconds before capturing [default: 500] --format Output format: text, json, json-compact [default: text] --timeout Timeout for wait conditions [default: 30] ``` ### `termwright screenshot` Take a PNG screenshot of a terminal application. ```bash termwright screenshot [OPTIONS] -- [ARGS]... Options: --cols Terminal width [default: 80] --rows Terminal height [default: 24] --wait-for Wait for this text to appear before capturing --delay Delay in milliseconds before capturing [default: 500] -o, --output Output file path (defaults to stdout) --font Font name for rendering --font-size Font size in pixels [default: 14] --timeout Timeout for wait conditions [default: 30] ``` ``` -------------------------------- ### JSON-RPC: Get Screen Content (JSON) Source: https://context7.com/fcoury/termwright/llms.txt Retrieve the current terminal screen content in a structured JSON format, including size, cursor, and cell data. ```bash tw '{"id":3,"method":"screen","params":{"format":"json"}}' # Response: {"id":3,"result":{"size":{"cols":80,"rows":24},"cursor":{"row":0,"col":0},"cells":[...]}} ```