All 22 apps

CandyVcr

Record + replay sugar-core sessions — and render .tape to GIF

inspired by charmbracelet/x/vcr cassettes jsonl + yaml replay cell-grid assert .tape → gif themes cli

CandyVcr code coverage

Tee every Msg + every byte a sugar-core Program emits into a cassette file, then drive a fresh Program through the same cassette and assert the output matches — byte-strict via ByteAssertion or cell-grid-strict via ScreenAssertion (powered by SugarVterm). The same frame pipeline also compiles .tape scripts into themed animated GIFs via render-tape/render-batch.

Install

composer require sugarcraft/candy-vcr

Record

use SugarCraft\Core\Program;
use SugarCraft\Vcr\Recorder;

$program = new Program($model);
$program->setRecorder(Recorder::open('/tmp/session.cas'));
$program->run();
// cassette is closed automatically when the loop ends.

Replay

use SugarCraft\Core\{Program, ProgramOptions};
use SugarCraft\Vcr\Player;
use SugarCraft\Vcr\Assert\ScreenAssertion;

$player = Player::open('/tmp/session.cas');
$result = $player->play(
    // The Player owns the streams and the loop; wire all three into ProgramOptions.
    programFactory: fn ($input, $output, $loop) => new Program(
        new MyModel(),
        new ProgramOptions(input: $input, output: $output, loop: $loop),
    ),
    assertion: new ScreenAssertion(80, 24),
);
if (!$result->ok) {
    echo $result->diffSummary();
    exit(1);
}

Cassette format

Cassettes are streaming JSONL — each line is a self-contained event with t (absolute timestamp in seconds) or dt (delta since previous event). See the full schema reference for all event types and the header structure. Record delta-time cassettes by opening the recorder with a relative-timestamped header — Recorder::open($path, new CassetteHeader(timestampMode: CassetteHeader::TIMESTAMP_MODE_RELATIVE)); withFormat() only confirms the encoding the header already selected and throws on a mismatch — it never flips one.

CLI

vendor/bin/candy-vcr record       --output session.cas -- bash -c 'echo hi'  # capture a real PTY session
vendor/bin/candy-vcr inspect      session.cas                                # list events
vendor/bin/candy-vcr replay       session.cas --speed=realtime               # stream output to stdout
vendor/bin/candy-vcr replay       session.cas --idle-trim=1.0                # clamp long gaps to 1s during replay
vendor/bin/candy-vcr diff         a.cas b.cas                                # structural diff
vendor/bin/candy-vcr stats        session.cas                                # show cassette statistics
vendor/bin/candy-vcr migrate      session.cas upgraded.cas                   # rewrite a v1 cassette as v2 (--dry-run to validate)
vendor/bin/candy-vcr render-tape  demo.tape                                  # render .tape to .gif
vendor/bin/candy-vcr render-batch demos/                                     # render all .tape files in directory

record subcommand

The record subcommand spawns a PTY session and captures all I/O to a cassette file:

vendor/bin/candy-vcr record --output session.cas --cols 132 --rows 40 -- bash -l
vendor/bin/candy-vcr record --no-ctty -- /bin/echo 'hello'   # non-interactive, no Ctrl+C wiring
vendor/bin/candy-vcr record --shell                          # spawn $SHELL -l
vendor/bin/candy-vcr record --env -- bash -c 'echo hi'         # capture filtered host env
vendor/bin/candy-vcr record --env-regex='/(SECRET|TOKEN)/i' -- bash -c 'echo hi'  # custom filter
vendor/bin/candy-vcr record --env-all -- bash -c 'echo $API_KEY'  # ⚠️ DANGEROUS — no filtering (--env-allow-secrets is the legacy alias)
vendor/bin/candy-vcr record --idle-trim 1.0 -- bash demo.sh  # compress idle gaps > 1s (asciinema-style)

replay subcommand

Stream a cassette's recorded output to stdout with optional timing control:

vendor/bin/candy-vcr replay  session.cas --speed=realtime          # honour recorded cadence
vendor/bin/candy-vcr replay  session.cas --idle-trim=1.0              # clamp gaps > 1s during replay
vendor/bin/candy-vcr replay  session.cas --no-trim                     # use original (uncompressed) timestamps

⚠️ --env-all (legacy alias --env-allow-secrets) disables all secret-key filtering. The cassette will contain credentials verbatim — record prints a stderr warning naming every captured variable, and the cassette file is created 0600 (owner-only), but only use this in fully isolated, trusted environments and never share the resulting cassette.

Frame renderer + GIF export

candy-vcr ships a Render layer and a TapeToGif pipeline: .tape scripts compile through Lexer → Parser → Compiler → Player → Terminal → Renderer → FrameStream → FrameDedup → Rasterizer → GifEncoder into an animated GIF. render-tape/render-batch expose it from the CLI with --theme (TokyoNight, TokyoNightLight, TokyoNightStorm, Dracula, SolarizedDark), --fps, --backend gd|imagick (GD default; imagick needs ext-imagick), and --encoder ffmpeg|php (ffmpeg with two-pass palette generation is the default; PhpGifEncoder is the pure-PHP fallback needing no external binaries). .tape is the only renderable input — a recorded cassette cannot be exported to GIF.

⚠ A .tape file is a program: the Set Shell directive, --shell=<sh>, or --exec put the renderer into exec mode — every typed keystroke runs in a real PTY-hosted shell. Review third-party tapes before rendering them.

Playback, the terminal, and assistive tech

Replay is environment-blind: it streams the recorded bytes verbatim — it does not read NO_COLOR, does not degrade on TERM=dumb, and does not follow live resizes beyond the header's recorded size. Assistive tech therefore sees exactly what the original session emitted rather than a re-adapted stream; for a non-visual outcome signal, replay prints a completion summary to stderr (candy-vcr replay: played N of M events (… output bytes, … s of recorded time)) so a stdout capture stays byte-clean. Interactive replay also guards the host terminal — cursor and alternate-buffer state are saved and restored (CSI ? 1049) and signal dispositions are reinstated on exit — while record arms a raw-mode rescue net (a /tmp/candy-vcr-rescue.<pid>.<rand> marker naming the affected tty) so a crashed child leaves the user's shell recoverable with stty sane.

What's in the box

Cassette formatFive shipped codecs — JSONL (absolute t, .cas/.jsonl/.cassette), gzip JSONL (.cas.gz), RelativeFormat (delta dt, asciinema-cast style), YAML (.yaml/.yml, hand-written fixtures), and a read-only asciinema importer (.cast, v2/v3); .tape files compile into cassettes through the tape compiler. All decode into the same Cassette value object; Player::open() picks JSONL vs RelativeFormat by content-sniffing (a .gz name routes straight to the gzip codec), while Player::loadAny() dispatches by extension.
Recorder hookProgram::setRecorder() tees input bytes, output bytes (renderer + RawMsg + PrintMsg + cursor / title / mode), resize, and quit events.
Tape rendererRender\Renderer + FrameDedup + TapeToGif turn .tape scripts into themed animated GIFs — render-tape/render-batch, GD/imagick rasterizers, ffmpeg/pure-PHP encoders. Recorded cassettes are replay-assert only, not GIF-exportable.
Msg serializers17 builtin Msg types (KeyMsg, MouseClickMsg/MouseMotionMsg/MouseWheelMsg/MouseReleaseMsg, WindowSizeMsg, FocusGainedMsg/FocusLostMsg/BlurMsg, FocusInMsg/FocusOutMsg, PasteMsg×3, BackgroundColorMsg, ForegroundColorMsg, CursorPositionMsg) + JsonSerializable catch-all + extensible Registry. FocusInMsg/FocusOutMsg are sugar-vterm CSI I/O focus events that round-trip through VCR.
PlayerDrives a fresh Program through a cassette. INSTANT mode for fast tests, REALTIME for visual demos. Supports both raw input bytes and Msg envelope payloads.
ByteAssertionStrict byte-equality with hex+printable diff window starting at the first divergence offset.
ScreenAssertionCell-grid equality via SugarVterm. Tolerates ANSI-level reordering (redundant SGR, equivalent cursor moves, partial vs full repaints) — the recommended choice for round-trip tests.

Use it for

  • Bug repro from user reports — user runs candy-vcr record --output bug.cas -- <cmd>, ships the cassette, maintainer replays locally.
  • Regression tests in CI — record a known-good session, replay against the current build, fail the build on cell-grid divergence.
  • Demos & documentation — alternative to VHS for headless / scriptable recordings; runs in the PHP unit-test process, no Docker.
  • Fuzzing seeds — record real sessions, mutate Msgs, replay to find edge cases.

Source & demos

Try the quickstart →

API

ClassMethodDescription
Recorderopen(path, header)Open a cassette for recording (file created 0600, owner-only)
RecorderwithFormat(format)Confirm the timestamp encoding the header already selected (e.g. new RelativeFormat() for delta-time) — throws on a mismatch, never flips
Recorderclose()Close and finalize cassette
Playeropen(path)Open a cassette for replay — sniffs t vs dt on the first event line; a .gz name selects the gzip codec without sniffing
PlayerloadAny(path)Load by extension: .cast, .yaml/.yml, .tape, .gz, .cas/.jsonl/.cassette; unknown extensions content-sniff
PlayerwithIdleTrim(?float $seconds)Fluent idle-gap threshold for SPEED_REALTIME playback (clamp pauses > N seconds)
Playerplay(factory, assertion)Replay session with assertion
ByteAssertionnew()Strict byte-equality assertion
ScreenAssertionnew(cols, rows)Cell-grid equality assertion
Render\Rendererrender(player, terminal, fps)Produce a FrameStream of Snapshot frames at the given cadence
Render\FrameDedupdedup(stream)Collapse identical adjacent frames (typical recordings run 80–95% duplicates)
Encode\TapeToGifcreate(options)Full .tape → .gif pipeline — options select theme, fps, backend (gd default | imagick), encoder (ffmpeg default | php)
RelativeFormatnew()Delta-time (dt) format — the style asciinema casts use; easier manual editing
CassetteeventCount()Number of recorded events; the events themselves ride the readonly $events property