hosts

package
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 24 Imported by: 0 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.

Documentation

Overview

Package hosts is the viewer's side of remote-host support: what a host is, how to reach it, and how to build the two SSH invocations that carry the two channels.

The transport shape here is deliberately identical to the one the Herdr remote-hosts plan recorded, because it is the piece both plans share and neither should own alone. A single multiplexed master connection per host, established once, with every subsequent channel riding it as a cheap session rather than a fresh TCP+TLS+auth handshake. That is what makes an in-band tmux command over SSH cost a round trip instead of a connection.

Index

Constants

View Source
const (
	DefaultStaleAfter = 90 * time.Second
	DefaultMinBackoff = 2 * time.Second
	DefaultMaxBackoff = 60 * time.Second
)

Client defaults. StaleAfter is deliberately generous: the serve loop drops to a 30-second cadence on a fully idle host, and marking such a host stale would be wrong — nothing is wrong with it.

View Source
const (
	// MaxRunOutputBytes caps a single invocation's stdout. Result objects are
	// hundreds of bytes; a megabyte is far past any of them and far short of
	// hurting.
	MaxRunOutputBytes = 1 << 20
	// MaxRunStderrBytes caps stderr, which is only ever read to explain a
	// failure. It matches the serve channel's stderr bound.
	MaxRunStderrBytes = 8 << 10
)

Run bounds. A remote pipe is not a trusted source: a host whose login profile loops, or whose verb dumps a repository, must not be able to grow the viewer's heap. These are the same reasoning as hostproto.MaxLineBytes, one layer out.

View Source
const (
	KeepaliveInterval = 15
	KeepaliveCountMax = 4
)

KeepaliveInterval and KeepaliveCountMax decide how fast a dropped link is noticed. Four missed 15-second probes is a one-minute detection floor, which is the right trade for a channel whose failure mode is a pane that silently stops updating: too aggressive and a busy link drops itself, too slow and a stale pane looks live.

View Source
const ControlPersistIdle = 5 * time.Minute

ControlPersistIdle is how long an idle master lingers. Long enough that closing and reopening a pane does not re-authenticate; short enough that a forgotten Sidecar leaves nothing behind for long.

View Source
const DefaultRunTimeout = 30 * time.Second

DefaultRunTimeout bounds an invocation whose caller supplied no deadline.

It exists because of td-052329: remote work that outlives the interaction that asked for it turns into a Bubble Tea command that never returns and, at shutdown, into a quit that visibly hangs. A caller running a verb that is legitimately slow (a worktree with a setup hook) should pass its own deadline; an unbounded call is never the right answer.

Variables

This section is empty.

Functions

func DisabledFromConfig

func DisabledFromConfig(cfg *config.Config) []string

DisabledFromConfig lists the hosts a user has registered but switched off.

They are returned separately because they must still be SEEN. `disabled` is for a machine that is off this week, and a host that simply vanished from the browser would be indistinguishable from one whose entry was deleted — which is the opposite of what the setting is for. The caller shows them as their own row state; no client is created and no connection is attempted.

func OriginNamesProject added in v1.12.0

func OriginNamesProject(originKey, projectKey string) bool

OriginNamesProject reports that a relayed request's origin project key names the same project as a bound destination's inventory key.

The two strings are not the same kind of identifier and rarely compare equal. A request's Origin.ProjectKey is the directory name the originating machine filed the project under in its own state tree ("sidecar"); an inventory key is canonical(root) on that machine ("/home/me/code/sidecar"). Matching by last path element is therefore the primary comparison, not a fallback — and it is the right one under the plan's rule that names join projects across machines while keys never do (docs/plans/active/remote-project-switcher.md, decision 10).

It is deliberately not the whole gate. Both callers additionally require the origin's tmux session to be present in that project's host inventory, which is what keeps two same-named projects on one host from claiming each other's requests.

func ProjectResults

func ProjectResults(hostID string, snapshot hostproto.Snapshot, stale bool) []workspaceinventory.ProjectResult

ProjectResults converts one host's snapshot into the same inventory type the local collector produces.

This is the join. A remote row becomes an ordinary workspaceinventory workspace carrying a HostID, so every projection downstream — the catalog, the board, the list, the lane grouping, the pin logic — works on it without knowing it came from another machine. The alternative, a parallel remote row type with its own rendering, is how two surfaces drift apart.

func ScopedKey

func ScopedKey(hostID, key string) string

ScopedKey namespaces a remote identifier by its host.

func SplitScopedKey

func SplitScopedKey(key string) (hostID, rest string, ok bool)

SplitScopedKey reverses ScopedKey, reporting whether the key was scoped.

Types

type Client

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

Client keeps one host's serve stream alive and exposes the current picture.

It owns the reconnect loop, so callers never see a connection — they see a host that is online or not, with rows that are current or stale. That division is deliberate: "degrade the host, not the app" is only achievable if the thing that can fail is entirely behind this boundary.

func NewClient

func NewClient(host Host, opts ClientOptions) *Client

NewClient builds a client for one host. It does not connect; call Run.

func OneShotClient

func OneShotClient(host Host, opts ClientOptions) *Client

OneShotClient builds a client for a single CLI invocation of RunSidecar.

The health gate in RunSidecar exists to protect the TUI: attempting a mutation on a host nothing has dialled means waiting out an ssh connect timeout inside whatever asked for it. A one-shot CLI process is the opposite situation. Nothing has dialled because nothing had the chance to, the user named the host explicitly on the command line, and waiting out a connect timeout is the correct behaviour rather than the hang. So this marks the client reachable and lets ssh itself decide, which turns "no stream is running" back into what it should be — an attempt that may fail with the transport's own reason, not a refusal before anything was tried.

It does not start a stream, so it observes nothing and must not be used where a Registry would do.

func (*Client) Close

func (c *Client) Close()

Close stops the client. Safe to call more than once.

func (*Client) ControlCommand

func (c *Client) ControlCommand(ctx context.Context, session string) *exec.Cmd

ControlCommand builds the ssh invocation that carries one remote tmux session's control channel — channel 1, the pane bytes.

It rides the same multiplexed master the serve stream uses, so opening a pane costs a round trip rather than a connection. Returning an *exec.Cmd rather than an opened channel keeps process lifetime with the caller, which is what tty.ControlSpawner expects.

func (*Client) Health

func (c *Client) Health() Health

Health returns the current health.

func (*Client) Host

func (c *Client) Host() Host

Host returns the host this client serves.

func (*Client) MarkStaleIfQuiet

func (c *Client) MarkStaleIfQuiet() bool

MarkStaleIfQuiet moves a connected host to stale when no data has arrived within the window, and reports whether anything changed.

It is a method the owner calls on a tick rather than an internal timer, because the owner is a Bubble Tea model that already has one: a second timer here would deliver transitions on a goroutine the model does not control.

func (*Client) Run

func (c *Client) Run(ctx context.Context)

Run drives connect, consume, and reconnect until ctx is cancelled or Close is called. It returns only when stopping, and never returns an error: a host that cannot be reached is a state to render, not a failure to propagate.

func (*Client) RunSidecar

func (c *Client) RunSidecar(ctx context.Context, args []string, out any) error

RunSidecar runs a sidecar verb on the host and decodes its --json result into out. Pass a nil out for a verb whose result does not matter.

It returns a *RunError for every failure, so a caller can render an actionable message without parsing text. The health gate is first and is not an optimisation: attempting a mutation on a host that is not connected means waiting out an ssh connect timeout inside whatever asked for it, which is the hang hostControlSpawner returns nil to avoid.

func (*Client) RunTmux added in v1.12.0

func (c *Client) RunTmux(ctx context.Context, args []string) ([]byte, error)

RunTmux runs a one-shot tmux argv on the host and returns its stdout.

func (*Client) SidecarCommand

func (c *Client) SidecarCommand(ctx context.Context, args ...string) (*exec.Cmd, error)

SidecarCommand builds the one-shot invocation of a sidecar verb on the host.

It rides the same multiplexed master as the serve stream and the pane channels — same control directory, same SSHArgs — so a mutation costs a round trip rather than a connection. Exposed separately from RunSidecar because "what command did it actually run" is the first question any remote failure raises, and answering it should not require running anything.

func (*Client) Snapshot

func (c *Client) Snapshot() (hostproto.Snapshot, bool)

Snapshot returns the most recent snapshot, and whether there is one. A copy: callers render from it on another goroutine.

func (*Client) TmuxCommand added in v1.12.0

func (c *Client) TmuxCommand(ctx context.Context, args ...string) (*exec.Cmd, error)

TmuxCommand builds the one-shot tmux invocation on the host.

func (*Client) Updates

func (c *Client) Updates() <-chan Update

Updates yields a value whenever the host's health or data changes.

The channel is buffered and lossy by design: a consumer that falls behind gets the newest state on its next read, not a backlog of superseded ones. Nothing downstream benefits from replaying a health transition that has already been overtaken.

type ClientOptions

type ClientOptions struct {
	Dial Dialer
	// Invoke replaces the runner used by RunSidecar. Leave nil in production.
	Invoke     Invoker
	Now        func() time.Time
	StaleAfter time.Duration
	MinBackoff time.Duration
	MaxBackoff time.Duration
	// ControlDir is where the ssh ControlMaster socket lives when the default
	// dialer is used.
	ControlDir string
}

ClientOptions configures a Client. Every field is optional.

type Conn

type Conn struct {
	Stdout io.Reader
	// Stderr is read for diagnosis when the stream fails. It is a function
	// rather than a reader because it is only consulted after the fact.
	Stderr func() string
	Close  func()
}

Conn is one open connection to a host's serve process.

type Dialer

type Dialer func(ctx context.Context) (*Conn, error)

Dialer opens a connection to a host. Injectable so the client's reconnect, backoff, event application and health transitions can all be tested without ssh, a network, or a second machine.

type Failure

type Failure string

Failure names why a remote invocation did not produce a result.

The values are what a viewer switches on. They exist for the same reason hostproto's error codes do: a caller that has to string-match a message to decide whether to offer "retry" or "update Sidecar there" will get it wrong the first time the wording changes.

const (
	// FailUnavailable means the call was never attempted: the host is not
	// connected, or is not registered at all. Nothing ran on the remote side.
	FailUnavailable Failure = "unavailable"
	// FailTransport means ssh itself failed — it could not start, could not
	// connect, or the channel died before the command reported a status.
	FailTransport Failure = "transport"
	// FailNoSidecar means ssh ran but no sidecar binary did.
	FailNoSidecar Failure = "no-sidecar"
	// FailTimeout means the invocation exceeded its deadline.
	FailTimeout Failure = "timeout"
	// FailCanceled means the caller cancelled it — a closed modal, a quit.
	FailCanceled Failure = "canceled"
	// FailRefused is exit 1: the remote sidecar ran, understood the verb, and
	// declined. The message is the remote's own refusal and is worth showing
	// verbatim, because it was written for exactly this reader.
	FailRefused Failure = "refused"
	// FailUnsupported is exit 2: the command as written is not usable — an
	// unknown flag, a missing required flag, a flag combination the verb does
	// not offer. The viewer builds the SHAPE of every argument list itself, so
	// a host that cannot parse the shape means the two Sidecars disagree about
	// the verb, which is a version-skew story with its own fix.
	//
	// It deliberately does not cover a rejected value: the viewer does not
	// invent branch names or display names, the user supplies them, and telling
	// that user to update a binary because a name is already taken is a wrong
	// answer to a question they can fix themselves. That is FailRejected.
	FailUnsupported Failure = "unsupported"
	// FailRejected is exit 5: the remote sidecar parsed the command and refused
	// a value inside it — a display name already in use, a branch that exists,
	// a base ref that machine does not have. The remote's own sentence is the
	// whole answer; nothing here needs updating.
	FailRejected Failure = "rejected"
	// FailNoTarget is exit 3 from a target-taking verb: the host does not own
	// the workspace the action addressed. A row that has gone away on the other
	// machine, or one this Sidecar can see but that one does not manage.
	FailNoTarget Failure = "no-target"
	// FailExit is any other non-zero status.
	FailExit Failure = "exit"
	// FailNotResult means the command exited 0 but stdout was not the result.
	// Overwhelmingly this is a login profile writing to stdout.
	FailNotResult Failure = "not-result"
)

func RunFailure

func RunFailure(err error) Failure

RunFailure reports the classification of any error returned by RunSidecar, or "" for an error from somewhere else. It saves every call site an errors.As dance.

type Health

type Health struct {
	State  State
	Detail string
	// Since is when the current state began, so a row can say how long a host
	// has been unreachable rather than only that it is.
	Since time.Time
	// Hello is the last successful handshake, retained across a drop so a
	// disconnected host can still say which Sidecar it was running.
	Hello *hostproto.Hello
	// Attempts counts consecutive failed connections. It drives the backoff
	// and tells a reader whether this is a blip or a habit.
	Attempts int
}

Health is everything a row needs to render a host's condition.

func (Health) Fix

func (h Health) Fix() string

Fix is the actionable line for this health.

type Host

type Host struct {
	// ID is the local name for this host. It scopes remote workspace IDs and
	// is what a row is grouped under in the Sessions browser.
	ID string
	// Target is the ssh destination: anything ssh_config resolves, which is
	// the point — the user's existing ssh setup is the configuration surface,
	// and Sidecar adds no second one.
	Target string
	// RemoteBinary is an explicit path to sidecar on the host. Empty means
	// resolve it through a login shell, which is required more often than not:
	// a non-interactive `ssh host sidecar` gets a PATH without Homebrew on it,
	// so the binary that is plainly installed appears missing.
	RemoteBinary string
	// RemoteConfig is an optional -config path passed to the remote sidecar.
	RemoteConfig string
	// Env is extra environment for the remote process, as KEY=VALUE. It is how
	// a proof run pins the remote to an isolated tmux server and state tree.
	Env []string
}

Host is a registered remote machine.

Env is a slice, so Host is not comparable with ==; use Host.Same to ask whether two registrations describe the same connection.

func FromConfig

func FromConfig(cfg *config.Config) []Host

FromConfig reads the registered hosts.

It returns nothing at all when the feature is off. That is the rollback guarantee stated as code rather than as a promise: with the flag off there is no host, so there is no client, no ssh child, and no remote row — the local path cannot differ because nothing else is reachable from here.

func (Host) Same

func (h Host) Same(other Host) bool

Same reports whether two registrations describe the same connection, so a config reload can leave an unchanged host's stream alone instead of reconnecting it. A host whose rows blink out because an unrelated setting moved is a worse experience than a slightly slower reload.

type Invoker

type Invoker func(ctx context.Context, cmd *exec.Cmd) (Output, error)

Invoker runs one prepared invocation and reports what it wrote and how it exited. It returns an error only when there is no status to report: a non-zero exit is a result, not a failure of the invoker.

Injectable for the same reason Dialer is: the deadline discipline, the exit classification and the JSON decoding are all things that must be tested, and none of them should need ssh, a network, or a second machine to test.

type Output

type Output struct {
	Stdout []byte
	Stderr []byte
	// ExitCode is the remote status, or -1 when the process did not exit on
	// its own — never started, or killed because the context ended.
	ExitCode int
	// Truncated marks output that hit the byte caps above.
	Truncated bool
}

Output is what one remote invocation produced.

type Registry

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

Registry owns the set of live host clients.

Its job is to make "which machines are we watching" a single answer that survives a config reload: Sync computes the difference and starts or stops only what changed, so a host whose settings did not move keeps its stream and its rows rather than blinking out and reconnecting.

func NewRegistry

func NewRegistry(opts ClientOptions) *Registry

NewRegistry builds an empty registry. opts is applied to every client; leave it zero for production defaults.

func (*Registry) Client

func (r *Registry) Client(id string) (*Client, bool)

Client returns one host's client.

func (*Registry) Clients

func (r *Registry) Clients() []*Client

Clients returns the live clients, ordered by host ID.

func (*Registry) Incarnation

func (r *Registry) Incarnation(id string) (uint64, bool)

Incarnation returns the concrete running client identity for id.

func (*Registry) MarkStaleIfQuiet

func (r *Registry) MarkStaleIfQuiet() bool

MarkStaleIfQuiet ages every connected host, returning true if any moved.

func (*Registry) RunSidecar

func (r *Registry) RunSidecar(ctx context.Context, hostID string, args []string, out any) error

RunSidecar runs a sidecar verb on one registered host, decoding its --json result into out. See Client.RunSidecar; this only resolves the host, so that "there is no such host" and "that host is not connected" are one refusal shape rather than two unrelated ones at the call site.

func (*Registry) RunTmux added in v1.12.0

func (r *Registry) RunTmux(ctx context.Context, hostID string, args []string) ([]byte, error)

RunTmux runs a one-shot tmux argv on one registered host.

func (*Registry) Stop

func (r *Registry) Stop()

Stop shuts every client down.

func (*Registry) Sync

func (r *Registry) Sync(ctx context.Context, hosts []Host)

Sync reconciles the running clients against the registered hosts.

func (*Registry) Updates

func (r *Registry) Updates() <-chan Update

Updates is the merged stream from every host.

type ResultValidator

type ResultValidator interface {
	// ValidRemoteResult reports whether the decoded value carries the fields
	// that make it this verb's result.
	ValidRemoteResult() bool
}

ResultValidator is implemented by a result type that can recognise its own verb's result.

It exists because JSON decoding cannot: Go ignores unknown fields and tolerates missing ones, so almost any object "decodes" into any struct and comes back all-zero with a nil error. Tolerating unknown fields is real forward compatibility and must survive — a host one version ahead adds fields, and that is not an error — so the answer is not DisallowUnknownFields but a per-type statement of which fields make the value this verb's answer.

Implement it on any type passed as RunSidecar's out. Without it the decoder still refuses an all-zero value, which is the floor; with it, a result that happens to share one field name with a log line is refused too.

type RunError

type RunError struct {
	// Failure is the classification. Switch on this, not on the message.
	Failure Failure
	// HostID is the host the invocation was addressed to.
	HostID string
	// Args is the sidecar verb and its arguments, as given to RunSidecar.
	Args []string
	// ExitCode is the remote status, or -1 when the command never exited on
	// its own (never started, or killed by cancellation).
	ExitCode int
	// Stderr is the remote's stderr, bounded and trimmed.
	Stderr string
	// Detail is the sentence to show. It prefers the remote's own words.
	Detail string
	// contains filtered or unexported fields
}

RunError is a failed remote invocation, with everything a row needs to say what happened and what to do about it.

func (*RunError) Error

func (e *RunError) Error() string

func (*RunError) Fix

func (e *RunError) Fix() string

Fix names what to do about a failure, in the imperative, the way State.Fix does. Empty when there is nothing useful to say.

func (*RunError) Unwrap

func (e *RunError) Unwrap() error

type State

type State string

State is a host's health, as a row in the Sessions browser shows it.

Every value below is something a user can act on, and each has exactly one fix. That is the whole design rule: "offline" with no reason is a state that makes someone go and investigate, which is the work this feature is supposed to remove.

const (
	// StateConnecting is the first attempt, before anything is known. It is
	// distinct from unreachable because a host that is merely slow must not be
	// reported as broken.
	StateConnecting State = "connecting"
	// StateOnline means the stream is live and the data is current.
	StateOnline State = "online"
	// StateStale means the connection is up but no snapshot has arrived
	// recently. The rows are still shown, marked stale, because last-known
	// state is more useful than a blank host — as long as it says so.
	StateStale State = "stale"
	// StateUnreachable means ssh could not connect.
	StateUnreachable State = "unreachable"
	// StateNoSidecar means ssh connected but no sidecar binary ran.
	StateNoSidecar State = "no-sidecar"
	// StateProtocol means both ends ran but speak different protocol versions.
	StateProtocol State = "protocol-mismatch"
	// StateNoTmux means sidecar is there but tmux is not, so the host has no
	// sessions to observe.
	StateNoTmux State = "no-tmux"
	// StateNotProtocol means something came back that is not the protocol —
	// almost always a login shell writing to stdout.
	StateNotProtocol State = "not-protocol"
	// StateDisabled is a registered host the user has switched off.
	StateDisabled State = "disabled"
)

func (State) Fix

func (s State) Fix() string

Fix names what to do about a state, in the imperative. Empty for the states that need nothing done.

func (State) Healthy

func (s State) Healthy() bool

Healthy reports whether rows from this state should be trusted as current.

func (State) Shows

func (s State) Shows() bool

Shows reports whether rows should be displayed at all. A stale host still shows its last-known rows; a host that never connected has none to show.

type Transport

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

Transport owns one host's multiplexed SSH connection.

The master is started lazily and torn down explicitly. ControlPersist is set to a bounded lifetime rather than `yes`: a master that outlives Sidecar is a process the user did not ask for and cannot see, and the cost of re-establishing it after a few idle minutes is paid once.

func NewTransport

func NewTransport(host Host, dir string) (*Transport, error)

NewTransport prepares a transport. dir must be a private directory; the control socket is created inside it.

func (*Transport) Close

func (t *Transport) Close() error

Close tears the master connection down. Leaving it to ControlPersist would also work, but an explicit exit means quitting Sidecar leaves no ssh process behind at all, which is the behaviour a user expects and can verify.

func (*Transport) Command

func (t *Transport) Command(ctx context.Context, remote string) *exec.Cmd

Command builds an ssh invocation running remote on the host.

remote is expected to already be a login-shell wrapper — SidecarCommand and ControlCommand both build one through RemoteShell, unconditionally, even when the binary path is absolute. That is not redundant: an absolute path starts the right binary, but the binary then shells out to tmux and git BY NAME, and a non-login ssh shell has no /opt/homebrew/bin on PATH. The failure reads as "tmux is not installed" on a machine where it plainly is. Observed on a real host during the Phase 0 spike, not anticipated.

func (*Transport) ControlCommand

func (t *Transport) ControlCommand(session string) string

ControlCommand is the channel-1 invocation: the remote tmux's own control protocol, which the local terminal stack already consumes verbatim.

`-f ignore-size` is not optional. Without it this attach becomes a sizing client on the remote server and shrinks the session to whatever the viewer's pane happens to be — visibly resizing the window under a human sitting at that machine. It is the same flag the local attach uses, for the same reason.

func (*Transport) Host

func (t *Transport) Host() Host

Host returns the host this transport serves.

func (*Transport) RemoteShell

func (t *Transport) RemoteShell(command string) string

RemoteShell wraps a command so it runs under the remote user's login shell, with any host Env applied.

func (*Transport) SSHArgs

func (t *Transport) SSHArgs() []string

SSHArgs returns the ssh option prefix, without the target or the remote command. Exposed so a caller can see exactly what will run — the transport is meant to be inspectable, since "what ssh command did it actually build" is the first question every failure raises.

func (*Transport) ServeCommand

func (t *Transport) ServeCommand() string

ServeCommand is the channel-2 invocation: a headless, ephemeral, read-only serve process that dies with the connection.

func (*Transport) SidecarCommand

func (t *Transport) SidecarCommand(args ...string) string

SidecarCommand renders the remote sidecar invocation for a subcommand.

func (*Transport) TmuxCommand added in v1.12.0

func (t *Transport) TmuxCommand(args ...string) string

TmuxCommand is a one-shot tmux invocation on the host, wrapped in the same login shell as SidecarCommand so tmux is found on PATH.

type Update

type Update struct {
	HostID string
	// Incarnation identifies one concrete registry client for HostID. It is
	// stamped by Registry, not the remote host, so a queued update from an old
	// SSH target cannot be mistaken for the replacement using the same ID.
	Incarnation uint64
	Health      Health
	Snapshot    *hostproto.Snapshot
	// Notify carries the typed notification events this update brought, in
	// arrival order. They are data, not state: nothing here is folded into the
	// snapshot, and nothing in the snapshot can produce one. A consumer that
	// wants them adapts them into its own notification model; the ssh side of
	// this feature ends at this field.
	Notify []hostproto.NotifyEvent
	// UIRequest carries host-side open/layout request announcements. Same
	// rules as Notify: not snapshot state, not replayed on reconnect, and
	// preserved across a dropped update because the agent is blocked on an ack.
	UIRequest []hostproto.UIRequest
}

Update is one change to a host's observable state.

Jump to

Keyboard shortcuts

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