# LibTmux.Server

- **Module:** LibTmux
- **Package:** LibTmux
- **Language:** C#
- **Kind:** class
- **Source:** https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/src/LibTmux/Server.cs#L9
- **Page:** https://libtmux.org/en/csharp/latest/reference/libtmux-server/

Represents an immutable server handle and snapshot.

Thread-safe: the handle is immutable once constructed and may be shared
freely, including as a singleton. Every mutating call answers a new handle
rather than changing this one.

## Examples

Distinguish an endpoint handle from a discovered server. Connection discovery returns an immutable replacement without capturing child relations. Use Linux or macOS with Git, tmux 3.2a or newer, .NET SDK 10.0.303, and the .NET 8 and 10 runtimes. In an empty directory, fetch the documented library revision:

```console
$ git clone https://github.com/libtmux/libtmux-dotnet.git libtmux-source && \
  git -C libtmux-source checkout --detach cf34b255c896d19a97e7d7fabea58609c916012d
```

Save this complete consumer setup as global.json:

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/global.json).

```json
{
  "sdk": {
    "version": "10.0.303",
    "rollForward": "disable",
    "allowPrerelease": false
  },
  "test": {
    "runner": "Microsoft.Testing.Platform"
  }
}
```

Save this complete consumer setup as NuGet.config:

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/examples/api/NuGet.config).

```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="libtmux-source" value="libtmux-source/artifacts/api-example-packages" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
  <packageSourceMapping>
    <clear />
    <packageSource key="libtmux-source">
      <package pattern="LibTmux" />
      <package pattern="LibTmux.*" />
    </packageSource>
    <packageSource key="nuget.org">
      <package pattern="*" />
    </packageSource>
  </packageSourceMapping>
</configuration>
```

Save this complete consumer setup as Example.csproj:

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/examples/api/csharp/Example.csproj).

```xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>net8.0;net10.0</TargetFrameworks>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <AnalysisLevel>10-recommended</AnalysisLevel>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <PackageReference Include="LibTmux" Version="[0.0.0-alpha.20]" />
  </ItemGroup>
</Project>
```

Save this complete program as Program.cs. It creates a private server; await using disposes its owned scopes after success, cancellation or failure. The complete file contains explicit imports, a top-level async entry point and a cancellation deadline.

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/examples/LibTmux.Examples/Programs/ServerConstruction.cs).

```csharp
using System;
using System.Threading;
using LibTmux;

if (OperatingSystem.IsWindows())
{
    throw new PlatformNotSupportedException("This example requires tmux on Linux or macOS.");
}

using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10));
CancellationToken token = deadline.Token;
string binary = Environment.GetEnvironmentVariable("LIBTMUX_TMUX") ?? "tmux";
string socketName = "csharp-serverconstruction-" + Guid.NewGuid().ToString("N");
ServerConnectionOptions options = new()
{
    SocketName = socketName,
    ConfigurationFile = "/dev/null",
    TmuxBinaryPath = binary,
};

// Open records the endpoint without running tmux or reading its state.
Server endpoint = Server.Open(options);
if (endpoint.IsMaterialized)
{
    throw new InvalidOperationException("Open must not discover a server.");
}

await using OwnedServerScope owned = await Server.CreateOwnedAsync(options, token);
await using OwnedSessionScope session = await owned.Value.CreateOwnedSessionAsync(
    new NewSessionRequest { Name = "demo", Command = "/bin/cat" }, token);

// Connect discovers the live daemon and returns a new materialized handle.
Server connected = await endpoint.ConnectAsync(token);
Server sameEndpoint = await Server.ConnectAsync(options, token);
if (!connected.IsMaterialized || !sameEndpoint.IsMaterialized || endpoint.IsMaterialized)
{
    throw new InvalidOperationException("Connecting must leave the original handle unchanged.");
}
if (connected.Generation != sameEndpoint.Generation || connected.Sessions.IsCaptured)
{
    throw new InvalidOperationException("Connection discovery must not capture the hierarchy.");
}

Console.WriteLine("Open records an endpoint; Connect discovers the running server.");
Console.WriteLine("The original handle stays unmaterialized; relations remain uncaptured.");
```

Build the exact source package and the saved consumer, then run both supported frameworks. The local package feed prevents an unrelated published package from satisfying the restore. Each program checks its result and exits unsuccessfully after an unhandled error:

```console
$ export NUGET_PACKAGES="$PWD/packages" && \
  dotnet restore libtmux-source/src/LibTmux/LibTmux.csproj --locked-mode && \
  dotnet pack libtmux-source/src/LibTmux/LibTmux.csproj \
    --configuration Release --no-restore -p:ContinuousIntegrationBuild=true \
    --output "$PWD/libtmux-source/artifacts/api-example-packages" && \
  dotnet restore Example.csproj --configfile NuGet.config && \
  dotnet build Example.csproj --configuration Release --no-restore --warnaserror && \
  export LIBTMUX_TMUX="$(command -v tmux)" && \
  export TMUX_TMPDIR=/tmp/libtmux-dotnet-dev && \
  mkdir -p "$TMUX_TMPDIR" && \
  unset TMUX TMUX_PANE && \
  dotnet bin/Release/net8.0/Example.dll && \
  dotnet bin/Release/net10.0/Example.dll
```

Expected program output from each framework:

```text
Open records an endpoint; Connect discovers the running server.
The original handle stays unmaterialized; relations remain uncaptured.
```

## Members

### Collections and queries

- `Sessions` (property): Gets the sessions this handle captured.
- `Windows` (property): Gets the windows this handle captured, across every session.
- `Panes` (property): Gets the panes this handle captured, across every window.
- `Clients` (property): Gets the clients this handle captured.
- `GetCommandsAsync` (method): Reads the commands this tmux knows.
- `GetSessionsAsync` (method): Reads every session on this server.
- `GetWindowsAsync` (method): Reads every window on this server.
- `GetPanesAsync` (method): Reads every pane on this server.
- `GetClientsAsync` (method): Reads the clients attached to this server.
- `Buffers` (property): Gets the paste buffers of this server.
- `CaptureSnapshotAsync` (method): Reads the server and answers a handle carrying what it found.
- `SearchPanesAsync` (method): Runs a tmux-side filter over every pane.
- `SearchSessionsAsync` (method): Runs a tmux-side filter over every session.
- `SearchWindowsAsync` (method): Runs a tmux-side filter over every window.

### Common operations

- `CreateSessionAsync` (method): Creates a session.
- `KillAsync` (method): Stops the tmux server.
- `SourceFileAsync` (method): Reads a tmux configuration file.
- `Options` (property): Gets the options of this server.
- `Hooks` (property): Gets the hooks of this server.
- `IsAliveAsync` (method): Reports whether a tmux server is answering.
- `Environment` (property): Gets the environment new sessions inherit from.
- `RunShellAsync` (method): Runs a shell command and reports what it printed.
- `HasSessionAsync` (method): Reports whether a session exists.
- `WaitForAsync` (method): Waits on, signals, locks, or unlocks a tmux channel.
- `AttachSessionAsync` (method): Attaches a client to a session on this server.
- `IfShellAsync` (method): Runs one tmux command or another depending on a shell command.
- `GetPromptHistoryAsync` (method): Reads what has been typed at command prompts.
- `ClearPromptHistoryAsync` (method): Forgets what has been typed at command prompts.
- `LockAsync` (method): Locks every client attached to this server.
- `ThrowIfDeadAsync` (method): Throws unless a tmux server is answering.
- `StartServerAsync` (method): Starts the tmux server without creating a session.
- `Version` (property): Gets the verified tmux client executable version.
- `GetSessionAsync` (method): Reads one session by identifier, throwing when it is absent.
- `GetWindowAsync` (method): Reads one window by identifier, throwing when it is absent.
- `GetPaneAsync` (method): Reads one pane by identifier, throwing when it is absent.
- `GetMessagesAsync` (method): Reads what the server has been logging.
- `ShowCommandPromptAsync` (method): Asks a client for input and runs a command with the answer.
- `DisplayMessageAsync` (method): Shows a message on a client.
- `DetachClientAsync` (method): Detaches one client.
- `KillSessionAsync` (method): Stops one session.
- `Chain` (method): Begins a chain that runs its commands in one tmux invocation.
- `FromEnvironment` (method): Returns the server whose pane this process was spawned in.
- `GetAttachedSessionsAsync` (method): Reads every session with at least one attached client.
- `ConfirmBeforeAsync` (method): Asks a client to confirm before running a command.
- `DetachAllClientsAsync` (method): Detaches every client except one.
- `LockClientAsync` (method): Locks one client.
- `SuspendClientAsync` (method): Suspends one client.
- `RefreshClientAsync` (method): Redraws one client.
- `SwitchClientAsync` (method): Switches the caller's client to another session.
- `CreateOwnedAsync` (method): Starts a server and takes ownership of it.
- `EnterControlModeAsync` (method): Starts a tmux control client and keeps it running.
- `OpenWaitChannel` (method): Opens a wait on a channel that survives a timed attempt.
- `ConnectAsync` (method): Connects to a configured tmux endpoint.
- `CreateOwnedSessionAsync` (method): Creates a session and takes ownership of it.
- `FindSessionAsync` (method): Reads one session by identifier, returning null when it is absent.
- `Open` (method): Opens an unmaterialized server connection handle.

### Other members

- `BuildGuardedCommandLine` (method): Builds the argument vector for a raw tmux invocation that only takes effect while the named server generation is still current.
- `ConfigureAccessAsync` (method): Grants or withdraws another user's access to this server.
- `ConnectionOptions` (property): Gets the connection options.
- `CreateSessionWithReceiptAsync` (method): Creates a session and returns its initial window and pane identities.
- `DaemonVersion` (property): Gets the daemon version read by inspection, or null when it was not acquired.
- `EndpointArguments` (property): Gets the endpoint selection arguments -- <c>-L</c>, <c>-S</c>, or a configuration file flag -- this handle's connection resolved.
- `Equals` (method)
- `ExecuteCommandAsync` (method): Executes one raw tmux command.
- `FindPaneAsync` (method): Reads one pane by identifier, returning null when it is absent.
- `FindWindowAsync` (method): Reads one window by identifier, returning null when it is absent.
- `Generation` (property): Gets the materialized server generation.
- `GetHashCode` (method)
- `InspectAsync` (method): Reads the live endpoint identity without running its initializer.
- `IsMaterialized` (property): Gets whether this handle has discovered a live server.
- `IsValidLayoutCandidate` (method): Checks a layout's syntax without contacting a server.
- `Keys` (property): Gets the key bindings of this server.
- `SearchClientsAsync` (method): Runs a tmux-side filter over every attached client.
- `ShowMenuAsync` (method): Shows a menu on a client.
- `SnapshotMetadata` (property): Gets acquisition metadata, or null when this handle was not captured.
- `ValidateLayoutsAsync` (method): Checks layouts before a workspace changes the server.
- `Within` (method): Returns this server with every command bounded by a timeout of the caller's choosing.
