termoscope

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

termoscope

Proof of what a terminal program showed. termoscope runs a binary under a headless pseudo-terminal inside go test, lets you wait for and assert on screen cells, and leaves a PNG, a static SVG, an animated SVG and an animated GIF of every run. The same files are the evidence a reviewer or a coding agent looks at when a test fails, and the demo you put in your README.

countdown emoji emoji as GIF

  • Nothing to install but Go. No ffmpeg, no ttyd, no browser, no system fonts. One go get, and it runs the same on a laptop and a bare CI runner.
  • Identical pixels everywhere, color emoji included. JetBrains Mono, Twemoji and Noto Emoji are embedded, so a PNG or GIF rendered on CI matches one rendered on a Mac, skin tones, flags and ZWJ sequences included.
  • The test run is the demo. Every go test rewrites its recordings, and one task example or CI step re-records README media with the same renderer, so demos are regenerated from the code instead of hand-captured.
  • Real PTY via charmbracelet/x/xpty, screen via the pure Go x/vt emulator. Cell-level reads of text, colors and width. Waits that block on screen state instead of sleeping, with the current screen in every timeout error.
  • Canvas sized in cells, not pixels: MinCols/MinRows fit the content or pin one size across all recordings.
  • Artifacts under test/results/<dateTimeISO>-<testName>/, plus a termoscope record CLI for recording outside a test.

How it compares

Real PTY and screen Assert from Go code PNG, SVG, GIF output External tools
termoscope yes yes, cell-level (WaitFor, CellAt) yes, fonts embedded none
teatest no, in-process Bubble Tea only yes, model-level text goldens none
tuitest yes yes, text-level text goldens none
VHS yes no, tape scripts only GIF, MP4, WebM ttyd, ffmpeg, Chromium
asciinema + agg yes no GIF agg, system fonts

Use teatest for fast unit tests of a Bubble Tea model. Use VHS for scripted demos with typing animation and window chrome. Use termoscope when the test that proves the screen should also leave the picture.

Install

go get github.com/dimmkirr/termoscope
go install github.com/dimmkirr/termoscope/cmd/termoscope@latest

Requires Go 1.26 and a Unix-like OS that can open PTYs.

Quick start

This is test/e2e/example_countdown_test.go, which drives examples/countdown:

func TestExample_Countdown(t *testing.T) {
	bin := buildCountdown(t) // go build -o <tmp> ../../examples/countdown
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	tm, err := termoscope.Start(ctx, 40, 4, bin, "-pace=120ms")
	if err != nil {
		t.Fatal(err)
	}
	termoscope.Record(t, tm) // recording.svg written on cleanup

	if _, err := tm.WaitFor(ctx, "Countdown"); err != nil {
		t.Fatal(err)
	}
	termoscope.SavePNG(t, tm, "start")

	if _, err := tm.WaitFor(ctx, "Liftoff"); err != nil {
		t.Fatal(err)
	}
	if err := tm.Wait(); err != nil {
		t.Fatalf("countdown exited with %v", err)
	}
	termoscope.SavePNG(t, tm, "liftoff")
	termoscope.SaveSVG(t, tm, "liftoff")

	for _, x := range []int{11, 13, 15} {
		c := tm.CellAt(x, 0)
		if c == nil || c.Content != "▄" || !isGreen(c.Style.Fg) {
			t.Errorf("cell (%d,0) should be a green tile, got %+v", x, c)
		}
	}
}

Run it and look at the evidence:

go test ./test/e2e/... -count=1 -v
ls test/results/*/
# liftoff.png  liftoff.svg  recording.gif  recording.svg  start.png

Packages

A test imports only the root package. The renderers are separate packages for programs that want images without go test or files. They are pure and take any Screen (Width, Height, CellAt), so a program with its own screen source can render through them without forking.

Package Purpose
termoscope Start, Terminal (Screen, Line, CellAt, Send, SendLine, WaitFor, WaitUntil, Done, Wait, Close), StripANSI, test helpers Dir, SavePNG, SaveSVG, Record, RecordWith with Options, SetResultsRoot
raster screen to *image.RGBA at 2x, pure
svg static and animated SVG from recorded frames, pure
gif animated GIF from recorded frames, pure

Full API: https://pkg.go.dev/github.com/dimmkirr/termoscope

RecordWith(t, tm, termoscope.Options{Hold: 3 * time.Second, MinCols: 20, MinRows: 4, EmbedEmoji: true}) sets the sampling interval, the hold on the last frame, the minimum canvas and emoji embedding once for both the SVG and the GIF.

Terminal is safe to read from any goroutine while the program writes. CellAt returns a copy. WaitUntil errors include the current screen, so a failing wait shows what the user would have seen.

Artifacts land under the module root of the test being run, found by walking up from the working directory to go.mod. SetResultsRoot overrides that. Add test/results/ to .gitignore.

Recorder CLI

termoscope record -o demo.svg -png last.png -gif demo.gif -cols 80 -rows 24 -- ./myapp --flag

Flags: -sample (40ms), -hold (2s before the loop restarts), -timeout (2m), -font-size (16), -embed-emoji (off), -min-cols/-min-rows (0, fit content; the canvas and background grow to at least this many cells). The exit code is the child's, and the recording is written either way.

SVG rendering

Geometry derives from the font: a cell is one glyph advance wide and two tall. Block glyphs (▄ ▀ █) become rounded cap-height squares, the rule ─ becomes a thin bar, and text keeps its native spacing. Frames switch with a CSS keyframe animation, which GitHub renders inside <img>. The font is embedded as a woff2 data URI; browsers honor it, librsvg does not.

GIF rendering

Record also writes recording.gif, and termoscope record -gif out.gif does the same from the CLI. Output is hi-DPI (2x) by default; -gif-scale 1 or gif.Options{Scale: 1} halves it for smaller files. Like the SVG, the canvas is cropped to the content cells and padded by one cell height on every side, and so is every PNG from SavePNG or -png (gif.Options.Padding, -padding, in 2x pixels; -1 disables). The blank screen sampled before the program printed is dropped so static previews of the GIF show content. Frames are rasterized with the bundled fonts and encoded with the standard library, so the result is pixel-exact on every viewer, no browser or system font involved. The trade-offs against SVG: fixed resolution and a palette of at most 256 colors (exact when the screen uses few colors, quantized to a 6x6x6 cube plus the 40 most common colors otherwise).

Emoji

The emulator gives emoji two columns, and all renderers keep the grid: text after an emoji lands on its true column.

The bundled fonts and Twemoji pictures add about 5 MB to the binary.

  • PNG and GIF draw emoji in color from the bundled Twemoji pictures, looked up by the cell's whole grapheme cluster, so skin tones, flags and ZWJ sequences (👍🏽 🇨🇿 👨‍👩‍👧) render correctly with no text shaping and no system font. A cell counts as emoji when it is two columns wide, contains U+FE0F, or JetBrains Mono lacks its first code point, so #, * and © stay text. raster.Options{MonoEmoji: true}, gif.Options{MonoEmoji: true} or -mono-emoji switch to the monochrome Noto Emoji face tinted with the cell's foreground; it is also the fallback for anything Twemoji has no picture for.
  • SVG emits each emoji as its own centered <text> and lists the platform color emoji fonts after JetBrains Mono: Twemoji Mozilla (Firefox), Apple Color Emoji (macOS, iOS), Segoe UI Emoji and Segoe UI Symbol (Windows), Noto Color Emoji (Android, ChromeOS, Linux), EmojiOne Color and Android Emoji (legacy). Browsers only consult them for glyphs JetBrains Mono lacks, so a README on GitHub shows the viewer's native color emoji. For a render that is identical everywhere, set svg.Options{EmbedEmoji: true} or pass -embed-emoji: the monochrome Noto Emoji is embedded as a woff data URI, adding about 750 KB.

Testing

CC=cc go test -race ./...   # nix: cgo needs the clang wrapper
golangci-lint run ./...

svg has two browser tests that render SVGs with headless Chromium to prove the embedded fonts (JetBrains Mono, and Noto Emoji with EmbedEmoji) are what the browser draws. They skip when no Chromium or Chrome is on PATH.

Not yet

Known gaps, so a missing feature is read as a backlog item rather than a design choice. Each names the package to touch; see CONTRIBUTING.md for setup, and CHANGELOG.md for what landed when.

Gap Status
Bold, italic, underline, strikethrough, reverse Dropped by raster and svg; only fg and bg color are rendered. Planned.
Cursor Not drawn in any artifact. Planned as an option in raster and svg.
Scrollback Only the visible screen is kept; Terminal reads the emulator's current grid.
Mouse No helper; Send writes raw bytes, so SGR mouse sequences work by hand.
Windows Untested. xpty has ConPTY support, the rest of the code assumes Unix.
GIF colors At most 256 per recording, quantized above that (gif).
Video (MP4, WebM), typing animation, window chrome Out of scope; use VHS.

Consumers

License

MIT. JetBrains Mono and Noto Emoji are bundled under the SIL Open Font License 1.1, see internal/fonts/OFL.txt and internal/fonts/OFL-NotoEmoji.txt. Emoji pictures are Twemoji 17.0.3 graphics, licensed under CC-BY 4.0, see internal/twemoji/LICENSE-GRAPHICS.

Documentation

Overview

Package termoscope tests terminal (TUI) programs: it runs a binary under a headless pseudo-terminal so a test can read the screen cell by cell, wait for screen states, and keep PNG, static SVG, animated SVG and animated GIF evidence of every checked screen. Fonts and color emoji are embedded, so the images are identical on a laptop and on CI with nothing installed but Go.

A typical test builds its binary, calls Start, registers Record so recording.svg and recording.gif land beside the screenshots, waits with Terminal.WaitFor or Terminal.WaitUntil, and calls SavePNG and SaveSVG at each assertion point. Artifacts go to test/results/<dateTimeISO>-<testName>/ under the module root of the test being run. See the Examples below and test/e2e in the repository.

Not yet supported: text attributes other than foreground and background color (bold, italic, underline are dropped by the renderers), the cursor, scrollback, and Windows. The scope and the list of planned work are in README.md; CONTRIBUTING.md explains where each piece lives. The renderers are small, and small pull requests usually land within a day.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Dir

func Dir(t *testing.T) string

Dir returns test/results/<dateTimeISO>-<testName>, creating it. The timestamp is fixed for the whole test binary run.

func Record

func Record(t *testing.T, tm *Terminal)

Record samples the terminal until it exits and writes <Dir>/<dateTimeISO>-recording.svg and <Dir>/<dateTimeISO>-recording.gif when the test ends. Call it right after Start. The terminal is closed during cleanup, so a still-running program is killed and the recording ends there. The SVG stays crisp at any zoom and shows the viewer's color emoji; the GIF is pixel-exact with the bundled fonts and needs nothing from the viewer.

Example

ExampleRecord is the test flow, a copy of test/e2e/example_countdown_test.go in the repository: the body of a TestXxx that records every frame and leaves <dateTimeISO>-start.png, <dateTimeISO>-liftoff.png, <dateTimeISO>-liftoff.svg, <dateTimeISO>-recording.svg and <dateTimeISO>-recording.gif under test/results/<dateTimeISO>-<testName>/.

package main

import (
	"context"
	"testing"
	"time"

	"github.com/dimmkirr/termoscope"
)

func main() {
	testCountdown := func(t *testing.T) {
		bin := "./countdown" // normally built into t.TempDir() with go build
		ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
		defer cancel()

		tm, err := termoscope.Start(ctx, 40, 4, bin, "-pace=120ms")
		if err != nil {
			t.Fatal(err)
		}
		termoscope.Record(t, tm) // <dateTimeISO>-recording.svg and .gif on cleanup

		if _, err := tm.WaitFor(ctx, "Countdown"); err != nil {
			t.Fatal(err)
		}
		termoscope.SavePNG(t, tm, "start")

		if _, err := tm.WaitFor(ctx, "Liftoff"); err != nil {
			t.Fatal(err)
		}
		if err := tm.Wait(); err != nil {
			t.Fatalf("countdown exited with %v", err)
		}
		termoscope.SavePNG(t, tm, "liftoff")
		termoscope.SaveSVG(t, tm, "liftoff")

		for _, x := range []int{11, 13, 15} {
			c := tm.CellAt(x, 0)
			if c == nil || c.Content != "▄" {
				t.Errorf("cell (%d,0) should be a tile, got %+v", x, c)
			}
		}
	}
	_ = testCountdown
}

func RecordWith

func RecordWith(t *testing.T, tm *Terminal, opts Options)

RecordWith is Record with Options: sampling interval, hold, minimum canvas size and emoji embedding. The SVG and the GIF share them.

func SavePNG

func SavePNG(t *testing.T, s raster.Screen, name string) string

SavePNG renders the screen to <Dir>/<dateTimeISO>-<name>.png and returns the path. Like the SVG, the image is cropped to the cells holding content and padded by one cell height (raster.Margin) on every side, at 2x.

func SaveSVG

func SaveSVG(t *testing.T, s svg.Screen, name string) string

SaveSVG writes a static SVG of the screen to <Dir>/<dateTimeISO>-<name>.svg and returns the path.

func SetResultsRoot

func SetResultsRoot(dir string)

SetResultsRoot overrides the directory that holds test/results. Empty restores auto-detection: walk up from the working directory to go.mod.

func StripANSI

func StripANSI(s string) string

StripANSI removes CSI escape sequences from s.

Types

type Options added in v0.3.0

type Options struct {
	Interval   time.Duration // sampling interval, default 40ms
	Hold       time.Duration // how long the last frame stays before looping, default 2s
	MinCols    int           // minimum canvas width in cells; the canvas still grows to fit content
	MinRows    int           // minimum canvas height in cells; the canvas still grows to fit content
	EmbedEmoji bool          // embed the monochrome Noto Emoji face in the SVG (about 750 KB) for a render that is identical everywhere
}

Options tunes what RecordWith records and renders. The zero value is what Record uses. Fields that apply to both the SVG and the GIF are set once here so the two recordings always agree. A new knob that both recordings should share belongs here, mapped onto svg.Options and gif.Options below, rather than in one renderer's options alone.

type Terminal

type Terminal struct {
	// contains filtered or unexported fields
}

Terminal is a running child process with its screen.

func Start

func Start(ctx context.Context, width, height int, name string, args ...string) (*Terminal, error)

Start launches name with args in a width×height PTY. The environment advertises a truecolor xterm so colors are emitted.

Example

ExampleStart drives a program outside go test: start it in a 40x4 PTY, wait for a screen state, read cells, and wait for exit. The renderer packages raster, svg and gif turn the same *Terminal into images.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/dimmkirr/termoscope"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	tm, err := termoscope.Start(ctx, 40, 4, "./countdown", "-pace=120ms")
	if err != nil {
		panic(err)
	}
	defer tm.Close()

	if _, err := tm.WaitFor(ctx, "Liftoff"); err != nil {
		panic(err) // the error carries the current screen
	}
	if err := tm.Wait(); err != nil {
		panic(err)
	}
	if c := tm.CellAt(11, 0); c != nil {
		fmt.Println(c.Content, c.Style.Fg)
	}
	fmt.Println(tm.Line(1))
}

func (*Terminal) CellAt

func (t *Terminal) CellAt(x, y int) *uv.Cell

CellAt returns a copy of one screen cell, or nil outside the screen. A copy is returned because the emulator keeps writing while tests read.

func (*Terminal) Close

func (t *Terminal) Close()

Close releases the PTY and kills the process if still running.

func (*Terminal) Done

func (t *Terminal) Done() <-chan struct{}

Done is closed when the process has exited. Safe for multiple waiters.

func (*Terminal) Height

func (t *Terminal) Height() int

Height reports the emulator height in cells.

func (*Terminal) Line

func (t *Terminal) Line(y int) string

Line returns the text of screen row y, right-trimmed.

func (*Terminal) Screen

func (t *Terminal) Screen() string

Screen returns the visible text without escape codes.

func (*Terminal) Send

func (t *Terminal) Send(s string) error

Send writes raw bytes to the child's stdin.

func (*Terminal) SendLine

func (t *Terminal) SendLine(s string) error

SendLine writes s followed by Enter.

func (*Terminal) Wait

func (t *Terminal) Wait() error

Wait blocks until the process exits and returns its error. It may be called more than once.

func (*Terminal) WaitFor

func (t *Terminal) WaitFor(ctx context.Context, substr string) (string, error)

WaitFor polls the screen until it contains substr or ctx expires.

func (*Terminal) WaitUntil

func (t *Terminal) WaitUntil(ctx context.Context, pred func(*Terminal) bool) error

WaitUntil polls until pred reports true or ctx expires. The error on timeout includes the current screen.

func (*Terminal) Width

func (t *Terminal) Width() int

Width reports the emulator width in cells.

Directories

Path Synopsis
cmd
termoscope command
Command termoscope records a program running under a headless pseudo-terminal and writes an animated SVG, optionally with a PNG of the final screen.
Command termoscope records a program running under a headless pseudo-terminal and writes an animated SVG, optionally with a PNG of the final screen.
examples
countdown command
Command countdown is a tiny in-place updating TUI used by termoscope's own tests and README.
Command countdown is a tiny in-place updating TUI used by termoscope's own tests and README.
emoji command
Command emoji is a tiny in-place updating TUI used by termoscope's own tests and README to prove wide emoji cells render and align.
Command emoji is a tiny in-place updating TUI used by termoscope's own tests and README to prove wide emoji cells render and align.
Package gif encodes recorded terminal frames as an animated GIF.
Package gif encodes recorded terminal frames as an animated GIF.
internal
fonts
Package fonts embeds the typefaces used for screenshots and README animations so renders look the same on every machine: JetBrains Mono Regular for text and Noto Emoji Regular (monochrome) for emoji glyphs JetBrains Mono lacks.
Package fonts embeds the typefaces used for screenshots and README animations so renders look the same on every machine: JetBrains Mono Regular for text and Noto Emoji Regular (monochrome) for emoji glyphs JetBrains Mono lacks.
twemoji
Package twemoji embeds the Twemoji 72x72 PNG set (jdecked/twemoji, graphics CC-BY 4.0, see LICENSE-GRAPHICS) and resolves a grapheme cluster to its image.
Package twemoji embeds the Twemoji 72x72 PNG set (jdecked/twemoji, graphics CC-BY 4.0, see LICENSE-GRAPHICS) and resolves a grapheme cluster to its image.
Package raster rasterizes a headless terminal screen into a hi-DPI RGBA image: JetBrains Mono at 2x for text, Twemoji PNGs for color emoji, and monochrome Noto Emoji as the fallback.
Package raster rasterizes a headless terminal screen into a hi-DPI RGBA image: JetBrains Mono at 2x for text, Twemoji PNGs for color emoji, and monochrome Noto Emoji as the fallback.
Package svg records a headless terminal screen over time and renders the frames as a self-contained animated SVG suitable for README files.
Package svg records a headless terminal screen over time and renders the frames as a self-contained animated SVG suitable for README files.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址