Part 2 of 2 gotmucks: tmux Control in Go

Inside gotmucks: tmux Control Mode and Testing in Go

How a Go library handles persistent tmux connections, asynchronous events, and testing against the real tmux executable.

• 8 min read

In the previous article, I introduced gotmucks, an open-source Go library for controlling tmux programmatically.

The library supports two ways of interacting with tmux:

  • One-shot commands: Execute tmux operations to create sessions, send keys, capture output, and manage options.
  • Control mode: Maintain a persistent connection to tmux, execute commands, and receive live terminal output and asynchronous notifications.

The second capability is particularly useful for applications that need to monitor long-running terminal processes.

This article covers how gotmucks handles control mode and how the library is tested.

1. How tmux Control Mode Works

tmux provides a control-mode interface through tmux -C.

Unlike executing individual tmux commands, control mode maintains a persistent connection using standard input and output.

An application can send commands through the connection while receiving responses and notifications from tmux.

flowchart TD
    A["Go Application"] <--> B["gotmucks"]
    B <-->|"Commands / Replies / Events"| C["tmux -C"]
    C <--> D["tmux Server"]
    D --> E["Sessions / Windows / Panes"]

The important detail is that replies and asynchronous events share the same output stream.

For example, tmux might produce:

%begin ...
session-created
%end ...
%output %1 Hello from tmux
%session-changed $0 mysession

The first three lines represent a command response. The remaining lines are asynchronous notifications.

A control-mode client needs to distinguish them correctly, even when several commands are outstanding or terminal output arrives simultaneously.

2. Connecting from Go

gotmucks exposes control mode through ControlClient.

ctx := context.Background()

cc, err := gotmucks.Connect(
    ctx,
    gotmucks.WithSocketName("myapp"),
)
if err != nil {
    log.Fatal(err)
}
defer cc.Close()

The connection remains active until explicitly closed or until tmux exits.

To attach to an existing session instead of creating a new one:

cc, err := gotmucks.Connect(
    ctx,
    gotmucks.WithSocketName("myapp"),
    gotmucks.WithAttach(sessionID),
)

The session ID is obtained from tmux, rather than relying on a session name that might change.

Once connected, the application can issue commands and consume events.

3. Handling Commands and Asynchronous Events

A control-mode connection involves two different kinds of communication.

Command responses belong to requests initiated by the application.

Asynchronous events originate from tmux and may arrive independently of any pending request.

gotmucks uses a single reader goroutine to process the incoming stream and dispatch messages appropriately.

flowchart TD
    A["tmux control-mode stream"] --> B["Reader goroutine"]
    B --> C{"Message classification"}
    C -->|"Command block"| D["Pending command reply"]
    C -->|"Notification"| E["Event dispatcher"]
    E --> F["Events()"]
    E --> G["Per-pane Output()"]

Multiple goroutines can call ControlClient.Do concurrently.

Because tmux command numbers aren’t predictable or contiguous, gotmucks associates responses with commands according to the order in which commands were sent.

This also requires guarding against input that could accidentally execute multiple tmux commands.

For commands containing application-provided values, DoArgs quotes the arguments before sending them to tmux.

Receiving live events

Applications can consume notifications through the Events() channel.

for ev := range cc.Events() {
    switch e := ev.(type) {
    case gotmucks.PaneOutput:
        os.Stdout.Write(e.Data)

    case gotmucks.SubscriptionChanged:
        log.Printf(
            "%s %s = %s",
            e.Pane, e.Name, e.Value,
        )

    case gotmucks.Exited:
        return
    }
}

Applications can use this to monitor terminal output, track changes to pane state, or react when the control connection exits.

Handling slow consumers

A common problem with streaming systems is what happens when an application cannot process incoming events quickly enough.

gotmucks uses buffered event channels. The reader does not block when a consumer falls behind, because blocking it would also prevent command replies and other notifications from being processed.

Instead, the library records dropped events and exposes that information to callers.

It also supports tmux’s own flow-control mechanism through PauseAfter and Resume.

This lets applications choose between buffered event consumption and tmux-managed output flow control.

4. Testing the Command Interface

The command interface needs to generate the correct arguments, invoke tmux, and parse its results.

For these tests, gotmucks uses a stand-in tmux executable.

The executable records the arguments it receives and returns predetermined responses.

This makes it possible to verify behaviour without installing or running a real tmux server.

Tests can check:

  • Correct command-line argument construction
  • Session, window, and pane identifiers
  • Parsing of structured tmux output
  • Error handling
  • Special characters and escaping

These tests are deterministic and run as part of the standard Go test suite.

go test ./...

However, a stand-in executable doesn’t establish whether real tmux will interpret those arguments the same way.

That’s where integration testing comes in.

5. Testing Against Real tmux

gotmucks includes integration tests that execute against an actual tmux installation.

These tests verify behaviour that cannot be established entirely from simulated responses, including command execution, control-mode communication, notifications, and option handling.

Each integration test uses a private tmux socket and cleans up its own server.

tmux -L gotmucks-t<pid>-<n>

This isolates the tests from any tmux sessions already running on the developer’s machine.

Run the integration suite with:

go test -tags integration ./...

The CI integration matrix covers tmux versions 3.2a, 3.4, and 3.5a.

Testing strategy

flowchart LR
    A["gotmucks Test Suite"] --> B["Unit Tests"]
    A --> C["Integration Tests"]
    A --> D["Fuzz Tests"]
    A --> E["Behaviour Probes"]

    B --> F["Stand-in tmux executable"]
    B --> G["In-memory protocol streams"]
    C --> H["Real tmux / private sockets"]
    D --> I["Escaping and argument handling"]
    E --> J["Actual tmux behaviour"]

Each test type addresses a different concern.

Test typePurpose
Unit testsVerify argument construction, parsing and application logic
Protocol testsVerify command-response and event-stream handling
Integration testsVerify actual behaviour against tmux
Fuzz testsExercise escaping and argument handling with arbitrary bytes
Behaviour probesVerify specific assumptions about tmux’s implementation

6. Verifying tmux Behaviour with Probe Scripts

The repository also includes shell scripts under scripts/ that investigate specific tmux behaviours.

For example, the probes check:

  • Whether tmux executes command vectors directly
  • Whether control mode works over pipes
  • Which notifications tmux emits
  • How values are escaped and returned
  • How many reply blocks a command produces
  • How options and hooks behave across versions

These scripts are executable assertions rather than informational reports. They exit with a non-zero status when the observed behaviour differs from what the library expects.

This is useful when adding support for another tmux version or investigating a compatibility issue.

Some implementation decisions in gotmucks came directly from these experiments.

For instance, tmux’s argument handling has cases where a trailing semicolon can act as a command separator even when supplied as part of an argument vector. The library explicitly handles that behaviour.

The probes help verify these less-obvious details rather than relying exclusively on documentation.

7. Testing Concurrent Behaviour

Control mode introduces concurrency concerns that don’t exist in quite the same form with one-shot commands.

Commands may be submitted simultaneously, events may arrive while replies are pending, and consumers may stop reading their channels.

gotmucks tests these interactions, including the handling of command responses and output streams.

The Go race detector provides another useful layer:

go test -race -short ./...

Alongside the unit and integration suites, this helps detect unsafe concurrent access within the library.

The tests also cover protocol escaping and command-line construction through fuzzing.

8. Where This Is Useful

A persistent tmux connection is useful when a Go application needs more than occasional command execution.

Some examples include:

AI coding agents. Run long-lived agents in tmux sessions, receive terminal output, and interact with them programmatically.

Remote development tools. Maintain terminal processes independently of SSH sessions while exposing their state to another application.

Terminal dashboards. Track multiple panes and receive updates without continuously invoking tmux commands.

Developer automation. Execute builds, tests, or other terminal workflows while monitoring their progress.

gotmucks provides the tmux integration layer for these applications. It doesn’t attempt to become an agent framework, workflow engine, or terminal emulator.

Conclusion

gotmucks combines two interfaces to tmux: a typed command API and a persistent control-mode client.

The command API handles ordinary tmux operations. Control mode provides bidirectional communication, live output, and asynchronous notifications.

Testing uses several complementary approaches: deterministic unit tests, protocol tests, fuzzing, executable behaviour probes, and integration tests against real tmux installations.

The result is a reusable Go library for applications that need programmatic access to tmux without implementing its command and control-mode interfaces themselves.

Project: https://github.com/counterflow/gotmucks
Documentation: https://pkg.go.dev/github.com/counterflow/gotmucks
Licence: MIT

✦ Counterflow

© 2026 Counterflow. All rights reserved.

GitHub LinkedIn