Adding a Visual Companion Layer to Command-Line AI Tools
Learn how to add a lightweight visual companion to a command-line AI assistant without changing its core logic or disrupting its output. This article covers event-driven state management, terminal rendering isolation, streaming feedback, configurable timeouts, error recovery, and privacy safeguards.
Introduction: Why Add a Visual Companion?
Command-line output is usually transient: a user enters a command, the program runs, and the results appear. After that, the interface stops changing. Large language model–powered coding assistants introduce a different interaction pattern. A request may take several seconds—or tens of seconds—to complete, leaving users unsure whether the tool is working or has understood their request.
One developer addressed this by building a small desktop pet for a command-line assistant. While waiting for input, the pet stands holding a book. As the assistant responds, it flips through the pages. When the response finishes, it raises the book and smiles.
The project is lightweight, but it raises a useful engineering question: how can you add dynamic visual feedback to a text-based tool without changing its core logic or disrupting its existing output?
Rather than reproduce that project’s implementation, this article extracts the general approach. It explains how to choose a rendering strategy for your terminal environment, implement a working state machine, and handle timeouts and failures.
1. Set the Boundary: The Companion Is an Observer
Regardless of the underlying model or SDK, many command-line assistants interact through standard input (stdin) and standard output (stdout). The companion layer should remain an observer: it consumes events without intercepting data or modifying the assistant’s output byte stream.
That boundary shapes the rest of the design.
There are typically three event sources to observe:
- User input: Detect submission on
stdin, or wrap the tool’s own submission function. - Request lifecycle: Emit
request.startwhen a request begins,stream.endwhen it completes successfully, anderrorwhen it fails. - Streaming output: Collect read-only statistics through a side channel, such as counting incoming text chunks to adjust animation pacing.
2. Use a State Machine to Make Waiting Predictable
The pet’s behavior can be represented by five states: idle, listening, thinking, finished, and error. A transition table keeps the behavioral logic in one place.
const transitions = {idle: { 'input.submit': 'listening' },listening: { 'request.start': 'thinking', error: 'error', timeout: 'error' },thinking: { 'stream.end': 'finished', error: 'error', timeout: 'error' },finished: { 'input.submit': 'listening', timeout: 'idle' },error: { 'input.submit': 'listening', timeout: 'idle' },};class PetStateMachine {constructor({ transitions, initial = 'idle', timeouts = {}, onChange }) {this.transitions = transitions;this.state = initial;this.timeouts = timeouts;this.onChange = onChange;this.timer = null;this.armTimer();}dispatch(event) {const next = this.transitions[this.state]?.[event];if (!next) return false; // Ignore events not defined for this state.this.clearTimer();const prev = this.state;this.state = next;this.onChange(prev, next, event);this.armTimer();return true;}armTimer() {const ms = this.timeouts[this.state];if (!ms) return;this.timer = setTimeout(() => this.dispatch('timeout'), ms);this.timer.unref?.(); // Do not let the timer keep the process alive.}clearTimer() {clearTimeout(this.timer);this.timer = null;}}const pet = new PetStateMachine({transitions,timeouts: { listening: 5000, thinking: 30000, finished: 3000, error: 3000 },onChange: (from, to) => drawFrame(to),});pet.dispatch('input.submit');
Two design choices matter here.
First, events that are not listed for the current state are ignored. This prevents unsupported duplicate or late events from triggering inappropriate transitions.
Second, timeout values are supplied through timeouts rather than hard-coded inside the class. The 30-second thinking timeout is only an example. Choose a value based on typical model response times and network conditions, and allow overrides through a configuration file or an environment variable such as PET_THINKING_TIMEOUT_MS.
3. Isolate Rendering: Cursor Controls Do Not Create a Separate Region
The escape sequences \x1b7 and \x1b8, or \x1b[s and \x1b[u, only save and restore the cursor position. They do not create a dedicated display region or pin content to a location on the screen.
There are three common ways to reserve space for the companion:
- Scrolling region: Use
\x1b[{top};{bottom}rto exclude the bottom few rows from the scrolling area. Assistant output scrolls above them, while the pet occupies the reserved rows. Send\x1b[ron exit to restore the default scrolling region; otherwise, the terminal may remain in an altered state. - Alternate screen: Use
\x1b[?1049hto enter a full-screen alternate buffer, then restore the original screen on exit. This works well for full-screen interfaces, but normal scrollback is unavailable while the alternate screen is active, making it less suitable for CLIs whose output users need to review. - External split pane: Use tmux’s
split-windowto place the pet in a separate pane, communicating through a socket or state file. This provides the strongest isolation but requires tmux.
| Approach | Typical terminal support | Main trade-off |
|---|---|---|
| Scrolling region | Generally available in xterm, VTE-based terminals, iTerm2, and Windows Terminal | Reduces space for output; cramped in small terminals |
| Alternate screen | Widely supported | Normal scrollback is not visible while active |
| tmux split pane | Requires tmux | Needs an additional process and communication |
These are general guidelines. Test the actual behavior in your target terminals.
Keep each pet frame to a single line and redraw only when the displayed state changes to reduce flicker:
let lastFrame = '';function drawFrame(frameText, rows = process.stdout.rows) {if (!process.stdout.isTTY || frameText === lastFrame) return;lastFrame = frameText;// Save cursor -> move to reserved row -> clear and draw -> restore cursor.process.stdout.write(`\x1b7\x1b[${rows};1H\x1b[2K${frameText}\x1b8`);}
This drawing function assumes that the display row has already been reserved.
Companion rendering and assistant output can interleave, so their writes need coordination. One option is to send both through a shared write queue. Another is to render only when assistant output is idle.
Listen for process.stdout.on('resize') and recalculate the reserved rows when the terminal size changes. If isTTY is false, or the terminal is too short to accommodate the reserved area, disable rendering while allowing the state machine to continue running.
4. Add Semantic Feedback with Lightweight Scanning
When the model starts producing a code block, the pet can switch to a “focused” pose. A lightweight implementation scans each chunk for triple-backtick code fences.
The main complication is that a fence can span two chunks. Retaining the last two characters handles that boundary:
let carry = '';let inCodeBlock = false;function onStreamChunk(chunk, onToggle) {const buf = carry + chunk;let from = 0;let idx;while ((idx = buf.indexOf('```', from)) !== -1) {// Count only fences ending in new data to avoid counting them twice.if (idx + 3 > carry.length) {inCodeBlock = !inCodeBlock;onToggle(inCodeBlock);}from = idx + 1;}carry = buf.slice(-2);}
At the start of every request, clear carry and reset inCodeBlock to false.
This is a lightweight heuristic, not a full Markdown parser. It performs a linear scan of each chunk and retains only a two-character window between chunks, without requiring a tokenization library.
If rendering takes longer than the frame interval, drop intermediate frames and keep only the latest state.
5. Make Timeout and Error Recovery Visible—and Configurable
Timeouts are easy to overlook. If the model takes too long to respond and there is no timeout path, the companion can remain in thinking indefinitely.
The transition table above sends timeout to error, then returns to idle after a short pause. In the error state, the animation might show the pet tilting its head and waiting.
Late events also need predictable handling. Suppose the 30-second timeout has already moved the pet to error, and the model subsequently emits stream.end. Because error has no transition for that event, it is ignored rather than moving the pet back to finished.
Request cancellation should also emit error so the companion does not get stuck in an active state.
6. Privacy and Security
- Keep data collection minimal. The companion needs event types and timing, not stored code or conversation content. The semantic scanner retains only two characters between chunks in memory; clear that temporary state when it is no longer needed.
- Do not log streaming output. Keep response text out of logs and telemetry. For debugging, record only state-transition names.
- Keep credentials out of companion files. Configuration and cache files should not contain API keys. Continue loading credentials through environment variables or the system credential store.
- Render fixed text only. Do not redisplay intercepted output fragments in the companion’s reserved area.
7. Implementation Summary and Release Checklist
Build the companion layer in three stages:
- Define events: Identify lifecycle events for user input, requests, and streaming output.
- Map events to states: Define a finite set of states and all relevant transitions, including timeouts and errors.
- Isolate rendering: Use a scrolling region, alternate screen, or split pane so visual feedback does not interfere with assistant output.
Before release, verify the following:
- Run the tool in tmux, Windows Terminal, and iTerm2, and confirm that the reserved display area behaves correctly.
- Reduce the terminal height and verify that rendering disables itself or reflows correctly.
- Exit with Ctrl+C and confirm that
\x1b[ris sent to restore the default scrolling region. - Run in a non-TTY environment, such as a pipe or CI job, and confirm that rendering is disabled and program output remains unchanged.
- Simulate timeouts and network errors. Confirm that the pet returns to
idleand that late events do not disrupt the expected state transitions.
The key is to keep the visual layer separate from the assistant’s core behavior. A small event-driven state machine, an isolated rendering area, and explicit recovery paths can make waiting more understandable without compromising the command-line interface.
