Building a Pixel Pet Plugin for AI Coding Assistants
A practical, end-to-end guide to designing and implementing a decorative pixel pet plugin for terminal-based AI coding assistants. It explains a three-layer architecture (event, state, render), how to draw high-fidelity pixels in any terminal using half-block characters, how to detect terminal capabilities and degrade gracefully, and how to handle multi-tier layout, an event-to-emotion state machine, frame-based animation scheduling, and strict security boundaries. It also covers packaging and installation on both the terminal and desktop clients, plus a testing checklist and a list of common pitfalls. Readers will come away with a maintainable, testable, cross-platform design they can adapt to their own tools.
1. Where It Started: Nobody Uses “Serious” Tools, So Build a Pet
Most developers have lived through this scene: you pour effort into a “serious” command-line tool, the features are solid and the docs are complete, yet hardly any colleagues choose to use it on their own. Turn it into a little character that blinks and raises both arms to cheer when the tool finishes, and adoption spreads far faster. This shows that people’s willingness to use a CLI tool depends not only on its features but also on its perceptibility.
The key factor here is feedback. An AI coding assistant may run for tens of seconds or longer on a single multi-step task, and the terminal usually shows nothing but scrolling text. It’s hard for users to tell at a glance “what it’s thinking about” or “which step it’s on.”
Mapping the assistant’s state onto a pixel pet is essentially inserting a stable visual anchor into an extremely dense stream of text: question marks pop up above its head while it thinks, it breaks into a run when calling tools, and it droops its head when something goes wrong. This emotional expression lowers the cost of understanding and makes the wait less tedious. That said, a decorative extension is only a supplement to the experience and should never overshadow the main event. Using the pixel pet as a representative scenario, this article breaks down the design and implementation of this kind of extension in full.
2. Design Goals: First, Don’t Get in the Way
Before writing any code, settle on three design principles:
- Zero burden: Add no configuration cost. It works the moment it’s installed. The pet is only a bystander to the session, participates in no decisions, blocks nothing in the main flow, and has negligible CPU usage.
- Adaptive: Display correctly and degrade gracefully across the spectrum, from classic 80-column terminals to widescreen setups beyond 200 columns, and from modern terminal emulators with true color to single-color remote consoles.
- Disablable: Stop it at any time and restore the original interface, leaving no ghosting and polluting no session transcript.
On top of these, a pet can exist at three levels: a pixel figure in the terminal, a pixel-art figure in a desktop client, and a shared state machine reused across platforms. The rest of this article starts with the core piece: terminal rendering.
3. Overall Architecture: Three Layers
A typical pixel pet plugin splits into three layers:
- Event layer: Subscribes to the session and tool events the host exposes, translating changes in the outside world into internal state changes.
- State layer: Maintains the current mood, animation phase, and cooldown, deciding what to do and when.
- Render layer: Draws the state as a pixel image and chooses the output format based on terminal capabilities.
Host (AI coding assistant)├─ session start ─┐├─ thinking ─┤├─ tool call ─┤ event layer state layer render layer├─ tool end ─┼─▶ subscribe / ─▶ mood machine ─▶ pixel canvas├─ waiting input ─┤ filter ▲ │├─ permission ─┤ │ ┌────┴─────────┐└─ window resize ─┘ timer ▼ ▼(idle animation) terminal desktophalf-block pixel art
With this split, each part owns a single responsibility:
- The event layer only translates and doesn’t care what the picture looks like.
- The state layer is unaware of the specific terminal, so switching the rendering method requires no changes to it.
- The render layer handles no business logic; it only needs to answer “what should I draw right now.”
4. Rendering: Half-Block Characters and “Two Pixels per Character”
4.1 Why Not Plain ASCII Art
Patterns built from # and * have too low a resolution. The outlines are coarse and it’s hard to call them “cute.” Although some terminal emulators support inline image protocols, support is uneven and often breaks after terminal multiplexing or remote login. The half-block approach relies only on standard Unicode characters and ANSI escape sequences, so it’s far more compatible.
4.2 How Half-Block Characters Work
The method is as follows:
- Use U+2580 (▀, upper half block): the glyph itself draws only the upper half of the cell, so the foreground color represents the upper pixel and the background color represents the lower pixel.
- If the terminal supports true color, set the foreground and background separately with
ESC[38;2;R;G;BmandESC[48;2;R;G;Bm. - Each terminal cell therefore carries two independent logical pixels.
The core conversion logic looks like this (illustrative pseudocode; ESC stands for the escape character \x1b):
ESC = "\x1b" # escape characterdef rgb(color):return ";".join(str(v) for v in color)def to_half_block(pixels):# pixels: a 2D list where each row is a set of (r, g, b)# each element is one logical pixel; logical pixel size = 1 char wide × half char highout = []for y in range(0, len(pixels), 2):upper = pixels[y]lower = pixels[y + 1] if y + 1 < len(pixels) else [(0, 0, 0)] * len(upper)row = []for x, up in enumerate(upper):row.append(f"{ESC}[38;2;{rgb(up)};48;2;{rgb(lower[x])}m\u2580")out.append("".join(row) + f"{ESC}[0m") # reset at end of line so color doesn't "bleed" into the next rowreturn out
4.3 Why the Image Doesn’t Warp
In the vast majority of terminals, cells are “tall and thin,” with a height roughly twice the width. If you draw “pixels” directly as characters, the pattern gets stretched vertically. With half-block characters, the logical pixels come out close to square, so the proportions look correct.
Take a bust portrait as an example: a canvas 36 columns wide and 16 rows high corresponds to 36 × 32 logical pixels:
- If built from 4×4 logical-pixel blocks, the whole image is 9×8 “big pixels,” clearly recognizable with an obvious pixel-art feel.
- At the same time, the whole image takes up only 16 text rows, so it doesn’t stretch the session too long.
5. Terminal Detection: Being Picky About Nothing
5.1 Four Things to Detect
- Color capability: Read whether
COLORTERMistruecolor/24bit, whetherTERMcontains256color/color, and respect theNO_COLORconvention. Based on this, choose true color, 256-color indexed, or 16-color output. - Output target: If standard output is redirected to a file or pipe (for example, logging a session via
tee), every escape sequence turns into garbage. In that case, stay completely silent and draw nothing. - Terminal size: Prefer reading the
COLUMNSandLINESenvironment variables; when they’re absent, query the window size through the OS interface. - Graphical environment: A desktop client is a separate window unaffected by terminal size, but it must reuse the same state and animation logic to keep behavior consistent.
5.2 Degradation Strategy
stdout is not a terminal → don't draw, stay fully silentterminal has no color → fall back to plain character art or a single-line status textonly 16 / 256 colors → quantize the palette to the nearest colorwindow width < 36 columns → collapse to a "face + status" single-line badgewindow height < 16 rows → shorten the canvas or show only the headterminal multiplexer / remote → check whether color pass-through works; if not, reduce color precision
The detection logic itself must stay lightweight: run it once at session start, and simply re-evaluate the layout after a window resize. Don’t re-probe on every frame.
6. Layout Strategy: From Bust to Side Panel
6.1 Let “Content First” Decide How Big It Is
The canvas size should be determined by the character design, for example a bust designed at 36×16. The terminal layout only decides where it appears; it shouldn’t squeeze the character to fit.
6.2 Three Layout Tiers
# Example parameters; actual values follow the asset designBODY_COLS = 36 # bust takes 36 columns (logical pixels)BODY_ROWS = 16 # takes 16 text rowsSIDE_MIN_COLS = 144 # starting width for side-panel displaydef choose_layout(term_cols, term_rows):if term_cols >= SIDE_MIN_COLS and term_rows >= BODY_ROWS + 2:# terminal is wide enough: place in the right sidebar with room for a speech bubblereturn "side"if term_cols >= BODY_COLS and term_rows >= BODY_ROWS:# not wide enough for the sidebar: show the bust tight against the conversation areareturn "inline"# everything else: keep only a single-character face plus status textreturn "badge"
6.3 Wide Terminals: The Side Panel Appears Automatically
When the window reaches 144 columns or more, the pet can show up directly beside the screen, next to the conversation content:
╭────────────────────╮│ Running unit tests…│╰────────────────────╯▄▄▄▄▄▄█████████▄█████████████
Two things to watch with the side layout:
- The right-hand content width must be calculated dynamically; when remaining space runs short, fall back to inline mode proactively.
- Terminal characters are fixed-width, but font sizes differ across terminals, so measure actual footprint by column count.
6.4 Narrow Terminals: A Single-Line Badge as Fallback
When width is insufficient, keep only a single-character face and a short status, such as (•_•) thinking or (>_<) error. Use the kaomoji common in monospace contexts; they offer the best compatibility and introduce no ambiguous-width characters.
6.5 Avoiding “Edge Stickiness”
The pet shouldn’t hug the far right edge of the window, because some terminals auto-wrap and produce an extra line. Use \x1b[s / \x1b[u to save and restore the cursor, combined with \x1b[K which clears only to end of line, to avoid ghosting.
7. State Machine: Giving the Pet “Emotions”
7.1 State Mapping
Abstract the host events into a few semantic phases and map them to character states:
| Host event (semantic) | Pet state | Visual behavior |
|---|---|---|
| session start | entrance | hops in, waves |
| model thinking | thinking | blinks, question mark overhead |
| tool call begins | busy | breaks into a little run |
| tool succeeds | happy | raises both arms, little stars pop out |
| tool fails | downcast | head droops, little water drops appear |
| awaiting permission | puzzled | tilts head, points to the confirmation area |
| task done, awaiting input | idle | occasional blink, gentle breathing |
| session ends | exit | waves, fades out |
7.2 Four Keys to Event Handling
- Recognize semantics, not specific names: The host might call them
PreToolUse,PostToolUse, or it might call themtool_start,tool_end. The plugin should map event names into internal semantic events. - Debounce and throttle: When the same tool is called repeatedly, don’t repaint over and over within 100 milliseconds. Merge updates using a “latest state + timed refresh” approach.
- Priority and cooldown: Important states like waiting for confirmation and failure alerts have the highest priority; celebratory animations like happy and entrance need a cooldown so they don’t turn into “convulsions.”
- Recoverable: After an animation finishes, return to the idle state rather than freezing on the last frame.
8. Animation Scheduling: Lively Without Lag
8.1 Timer-Driven, Not Event-Driven
If every state change triggered a synchronous repaint, the pet would flicker during rapid output. A more robust approach is to maintain a “target state” and have a timer check at a fixed frequency (say 8–12 fps) whether a repaint is needed:
def tick(state, now):if now - state.last_draw < state.frame_interval:return # not the next frame yet, skipframe = state.idle_frame(now) # do blinks, breathing, and other micro-motions when idleif state.pending:frame = state.pending_framestate.pending = Nonerepaint(frame)state.last_draw = now
8.2 Keep the Repaint Scope Modest
- Use “save cursor → return to panel origin → overwrite line by line → restore cursor” for partial refresh, not a full-screen
clear. - Don’t use clear-screen sequences that wipe scrollback history (such as
ESC[3J). - When height is insufficient, refresh only the first few rows.
8.3 Draw Only in the Session Area
The area where the user types must never be overwritten at will, or the pet will “eat” the command the user is typing. Prefer the UI regions or card mechanisms the host provides; when none exist, draw once at session start or end, and pause the animation when the user starts typing.
8.4 Cross-Platform Reuse
The desktop client can reuse the same pixel art and state machine, driving the animation via requestAnimationFrame or an equivalent, using devicePixelRatio for high-DPI screens, and setting imageSmoothingEnabled = false to keep the pixel art sharp. That way, what you see in the terminal and on the desktop is “the same pet.”
9. Security and Boundaries: The “Three Don’ts” for a Decorative Extension
- Don’t block: Do all time-consuming work (loading image assets, render caching) during initialization or idle periods; the main loop only does O(1) state checks.
- Don’t overreach: The pet reads only the host’s public events and session state. It doesn’t read the user’s secrets, environment variables, or files outside the workspace, and it makes no network requests. When a local plugin does touch user data, state that clearly and let the user decide for themselves.
- Don’t leave traces: On disable or exit, restore the cursor and reset color attributes; don’t write control sequences into logs or session replays.
On top of this, such plugins are best kept dependency-free with purely local assets, which makes them easy to audit and easy to use in restricted network environments.
10. Distribution and Installation: From Local to Both Platforms
10.1 The Plugin Manifest
Each plugin typically needs a manifest file declaring metadata, the entry point, and subscribed events. A sample structure:
{"name": "pixel-pet","version": "1.0.0","description": "A pixel pet that lives in your terminal","entry": "./dist/pet.js","events": ["session.start", "tool.start", "tool.end", "permission.request", "turn.end"],"permissions": ["ui.panel"],"assets": ["./assets/sprites/*.png"]}
Manifest fields follow the host’s plugin spec; the above only illustrates the idea.
10.2 Terminal: Install in One Command
Most CLI-style AI coding assistants use a plugin mechanism similar to package management. You can host the plugin in a public code-hosting repository, then run the marketplace install command inside a terminal session with the repository address. Once installed, invoke it with a slash command like /<plugin-name>:
/plugin install <plugin-name> --marketplace <org>/<repo>/niang
Note: The host parses slash commands, and the install command must be entered in a session at the real input prompt. If the assistant itself runs inside an embedded terminal of another program, your keystrokes may be intercepted by the outer program.
10.3 Desktop Client: A Two-Step Graphical Install
Desktop clients usually don’t offer a way to run install commands in the chat box, so you go through the UI:
- Click the “+” next to the input box or open the menu and choose Plugins.
- First Add marketplace and enter the repository address; then Add plugin.
- Once installed, invoke it by typing a slash command in the chat box.
10.4 Publishing to a Public Marketplace: Let the Plugin “Grow on Its Own”
To register in an official marketplace, you generally submit a record to the marketplace’s plugin index with the name, repository address, and description. After review passes, other users can install it with a single command, and the pet “pops out on its own.”
If you truly need server-side support, you can lean on common cloud capabilities to keep the architecture simple and responsibilities clear:
- Object storage: Host the plugin packages and animation assets, managing releases through versioned paths.
- Logging service: Collect anonymized diagnostics with the user’s consent, making issues easier to trace.
- Monitoring and alerting: Notify maintainers promptly when the error-call volume for a given version spikes abnormally.
Data should be de-identified, and a clear opt-out switch should be provided.
11. Testing and Acceptance Checklist
- Width: Check at 80, 100, 120, 144, and 160 columns; confirm layouts switch correctly with no wrapping.
- Height: Confirm it degrades when the window height is insufficient.
- Color: Screenshot and compare across no-color, 16-color, 256-color, and true-color modes; confirm there’s no obvious color deviation.
- Non-interactive: After redirecting output, confirm the artifact contains no control characters.
- Window changes: After dragging the window to resize, confirm the canvas reflows with no ghosting.
- Interrupt recovery: Simulate Ctrl+C or an abnormal exit; confirm terminal attributes are restored.
- Input protection: Confirm the pet never covers what the user is typing.
- Performance: Confirm idle CPU usage is close to zero.
12. Common Pitfalls and Lessons
- Unicode width: Characters whose
East Asian Widthis Wide (W) or Ambiguous (A) occupy two columns in most terminals, and the slightest slip in width calculation throws everything out of alignment. A pixel pet should use only half-block characters and standard ASCII. - Color bleed: If one line isn’t reset, the next line inherits the previous line’s color. Always reset attributes at the end of every line.
- Reaching for
clear: It wipes the entire session window, which is very disruptive. - Ignoring terminal multiplexers and remote sessions: Many users work through terminal multiplexers daily, and when color pass-through fails the pet becomes a block of solid colors, so a degradation mode is a must.
- The pet ending up in logs: In CI or log-collection scenarios, control sequences interfere with parsing, so “silent on non-terminal output” is mandatory.
13. Conclusion
Behind the line “nobody uses serious tools, so build a pet” lies a very down-to-earth engineering question: how to let users perceive the state of a tool.
Architecturally, a good pixel pet has a few defining traits: a semantic event layer, a state layer decoupled from the render layer, automatic terminal capability detection, multi-tier layout degradation, and strict security boundaries.
- In the terminal: It’s a bust built from half-block characters, 36 columns wide and 16 rows high.
- In a wide terminal: Once the window exceeds 144 columns, it appears on its own in the side panel.
- In the desktop client: It’s a full-body pixel image, installed via “+” → Plugins.
Behind all these forms is the same maintainable, testable, reusable engineering implementation. A decorative feature may not be a “serious requirement,” but carefully polished experience details are often the first step toward a tool actually being used.
