Current section

Files

Jump to
libtmux docs owned-program-concept.md
Raw

docs/owned-program-concept.md

# Owned programs in tmux panes

Use `Program.run/4` when the caller owns the application's lifetime. Run
this example from the checkout on Linux with tmux 3.8 and `printf` installed.

```console
$ mix run examples/run_application.exs
```

The example checks the application status and rendered screen and confirms
the pane was removed. [Complete program](../examples/run_application.exs)

<!-- example: examples/run_application.exs#run -->

```elixir
{:ok, _report} = Program.capabilities(server, target)
argv = ["/usr/bin/printf", "application complete\n"]

{:ok, %{exit: {:status, 0}, screen: screen, pane_cleanup: :removed}} =
  Program.run(server, target, argv)

true = String.contains?(screen, "application complete")
IO.puts("exit=0 screen=application complete pane=removed")
```

<!-- /example -->

## Send terminal input to an application

```console
$ mix run examples/interact_with_application.exs
```

The byte counter consumes four literal bytes and a newline through its PTY.
The example sends EOF on a fresh line and verifies the result before closing
the accepted pane. [Complete program](../examples/interact_with_application.exs)

<!-- example: examples/interact_with_application.exs#input -->

```elixir
{:ok, _report} = Program.capabilities(server, target)
{:ok, application} = Program.start(server, target, ["/usr/bin/wc", "-c"])

:ok = Program.send_text(application, "pine")
:ok = Program.send_keys(application, ["Enter", "C-d"])

{:ok, %{exit: {:status, 0}, screen: screen}} =
  Program.await(application, 3_000)

true = "5" in String.split(screen, "\n", trim: true)
{:ok, %{pane_cleanup: :removed}} = Program.close(application, 3_000)
IO.puts("exit=0 input_bytes=5 pane=removed")
```

<!-- /example -->

## Wait for and cancel independent workers

The concept runs two SHA-256 workers in separate panes. The left worker
finishes while the right worker waits for a writer on a FIFO. The caller
can retain and verify the left digest, stop waiting for the right worker,
then cancel and join that worker.

Run the example from a checkout of this concept. Use Linux, the
repository's Elixir and OTP toolchain, a C11 compiler and Linux headers,
tmux 3.8, and the `sha256sum` and `mkfifo` commands. Fetch the checkout's
development dependencies with `mix deps.get`. Put tmux 3.8 on `PATH`.

```console
$ mix run examples/compare_program_files.exs
```

The left line includes `exit=0` and a verified SHA-256 digest. The right
line reports `signal=15 cleanup=retired`. The program checks the left
result again after cancellation and verifies the owned socket was removed.
The complete example is in
[compare_program_files.exs](../examples/compare_program_files.exs).

<!-- example: examples/compare_program_files.exs#workers -->

```elixir
{:ok, _report} = Program.capabilities(server, target)
{:ok, right} = Program.start(server, target, [hash, "--", right_path])
{:ok, left} = Program.start(server, target, [hash, "--", left_path])

{:ok, %{exit: {:status, 0}, screen: screen}} = Program.await(left, 3_000)
digest = Base.encode16(:crypto.hash(:sha256, input), case: :lower)
true = String.contains?(screen, digest)
IO.puts("left exit=0 sha256=#{digest}")

{:error, %{kind: :program_timeout}} = Program.await(right, 50)

{:ok, %{exit: {:signal, 15}, cleanup: :retired}} =
  Program.cancel(right, 3_000)

IO.puts("right signal=15 cleanup=retired")
{:ok, %{exit: {:status, 0}, screen: ^screen}} = Program.await(left, 3_000)
```

<!-- /example -->

## Application evidence

`LibTmux.Program.start/4` splits an exact pane on a private server started
with `Server.with_owned/2` or `Server.start/1` and the default empty
configuration. `Program.capabilities/2` checks the answering daemon's
exact 3.8 release, named requirements, advertised command names and
target reference before creating a socket or splitting.

Each start reserves one of 16 supervised slots for the application.
The slot covers startup, the running application and its retained pane.
Recoverable startup handles keep the slot until they are closed.
Admission at capacity returns `:program_capacity` before creating a
listener or submitting a split. An expired admission cannot start after
the supervisor resumes.

The startup task owns a private Unix listener in the server directory. It
monitors the creator and daemon while a separate worker submits the split.
The launcher connects to that listener. The owner verifies Unix peer
credentials before releasing the application. Losing the creator closes
and unlinks the listener even when startup has no pane receipt.
When startup has acknowledged the split, the task attempts bounded removal
of that generation. Without the receipt, the exact pane is unknown.
Startup shares one deadline across those steps. After an acknowledged
split, a failed setup gets a separate pane-removal budget. The error keeps
its original cause, the pane ID and removal evidence. If removal remains
unproved, pass the error's startup handle to `Program.close/2` to retry it.
That retry reports pane removal separately from the unavailable application
outcome.

The pane launcher uses the native helper selected by the owned server.
The worker receives an absolute executable, literal argv, an optional
absolute working directory and up to 16 environment overrides. The
controlling terminal remains the new pane. The caller can choose split
axis and size. Startup observes the fork. A failed exec or directory change
reports an errno independently from the application's own exit. Expiry after
release can leave startup and cleanup unknown.

`Program.await/2` preserves separate variants for a normal status and a
terminating signal. Concurrent callers can wait on the same retained result
with independent deadlines. Each caller uses its remaining budget for the
final screen capture. A timed-out wait sends no cancellation.
`Program.cancel/2` requests SIGTERM through the private connection,
escalates to SIGKILL after 250 ms and waits within the caller's budget.
The supervisor signals its unreaped child and reports the actual `waitpid`
outcome after reaping it and the descendants it adopts. It also retires that
tree if the owner socket, launcher or pane PTY closes.
After supervisor loss, a surviving launcher can prove tree retirement
without an application status. `Program.close/2` can remove that pane
while preserving the missing-status error.
`cleanup: :retired` records this application-tree evidence.
Launcher exit and pane removal have separate evidence.
Cancellation can race a natural exit. A cancellation timeout can mean
the launcher is still terminating the application. Await the retained
result or retry cancellation on the same handle. The worker has a
120-second native lifetime. A caller can choose a shorter owning wait.

`Program.run/4` waits under its operation deadline, then uses a separate
cleanup budget. It returns the application outcome and pane removal
evidence. If it times out, it keeps the wait failure and includes the cleanup
result. Incomplete cleanup retains the accepted handle. `Program.close/2`
joins an accepted handle and removes that generation's pane.
If slot retirement times out after pane removal, the error still includes
the confirmed removal and any application outcome.

Application stdin, stdout and stderr use the pane's PTY. `send_text/2`
and `send_keys/2` submit input to the accepted live pane. A native
`pane-created` hook invalidates a pane-local generation mark on respawn.
Input, capture and removal check that mark in the same tmux queue as the
action. A replacement keeps its own screen and process. The program and
its terminal settings determine how input is interpreted.

The concept uses a silent retained pane for a separate rendered screen
observation, capped at 64 KiB. `Program.screen/2` captures the current
rendering. `Program.await/2` waits for tmux to mark the pane dead before
capturing. Both return retained and discarded history-row counts separately
from the visible bytes. These counts describe tmux's history grid. Terminal
redraw can replace text without adding a history row. The result keeps the
child outcome when screen capture fails. Losing the creator or private
completion owner triggers guarded pane cleanup. The scoped server teardown
clears panes left after an unproved cleanup attempt.

## Qualification limits

This prototype assumes exclusive use of an owned, empty-config daemon and
trusted executables. Keep the reserved pane-local hook and option intact
and native commands unaliased. The independent one-shot connection still
depends on the owned daemon directory. The same-queue guard covers pane
replacement within that daemon.

The native fixtures exercise exit 143, signal 15, SIGKILL escalation,
exec failure, terminal input, premature owner exit and launcher loss.
They verify isolation from a surviving sibling. A replacement injected
at dispatch receives no input from the old handle. The pressure fixture
retains an unterminated final row after 125,000 output rows.

The fixtures cover loss of the creator before split, after the split
receipt and during a run. Arbitrary concurrent tmux clients, cancellation
at every setup phase and simultaneous loss of both native owners remain
outside this qualification. Descendant retirement depends on a surviving
subreaper and Linux process state.
The application has the caller's filesystem and network access.

Program checks the [connected daemon's capabilities](capabilities.md) and
requires tmux 3.8 for this release. For a lookup against upstream source,
use the [release map](api-examples.md#choose-a-native-release).