Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions config/common/.config/tmux/tmux.conf
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ set-window-option -g pane-base-index 1
bind-key s split-window -h
bind-key v split-window -v

# Only deliberate close commands end a remote terminal. Losing the local pane detaches.
bind-key x confirm-before -p "kill-pane #P? (y/n)" {
if-shell -F "#{@tm_terminal}" { run-shell -b '#{q:HOME}/.local/bin/tmux-session --remote-close #{pane_id} 2>&1' } { kill-pane }
}
bind-key & confirm-before -p "kill-window #{window_name}? (y/n)" {
if-shell -F "#{P:#{@tm_terminal}}" { run-shell -b '#{q:HOME}/.local/bin/tmux-session --remote-close #{window_id} 2>&1' } { kill-window }
}

# move between panes with prefix h, j, k, l
bind-key h select-pane -L
bind-key j select-pane -D
Expand Down Expand Up @@ -137,8 +145,8 @@ set-option -g status-left " [#{?@display_name,#{@display_name},#{session_name}}]
set-option -g status-right-length 150
set-option -g status-right '\
#{prefix_highlight} \
#[fg=green] #{b:pane_current_path} \
#[fg=terminal] | #[fg=yellow]#{host_short} \
#[fg=green] #{?@tm_sign_in,Check SSH · rerun tm,#{?@tm_host,#{@tm_project},#{b:pane_current_path}}} \
#[fg=terminal] | #[fg=yellow]#{?@tm_host,#{@tm_host},#{host_short}} \
#[default] %l:%M %p '

set-option -g pane-active-border-style "fg=cyan"
Expand Down
56 changes: 56 additions & 0 deletions tools/cmd/tmux-session/REMOTE-WORKSPACES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Remote workspaces in tm

```sh
tm --host devbox work/api
tm --host devbox work/api --name scratch
```

Relative paths start in the remote home directory. The SSH destination, resolved
directory and workspace name identify a session even after you rename it in tmux.

The picker, copy mode and key bindings stay local. The devbox runs the shell,
`$EDITOR` (default `nvim`) and `codex` under zmx. New windows and splits start in
the project directory.

Each remote workspace in local tmux gets its own OpenSSH connection. The two sessions
above have independent connections and pane limits. Renaming a session or
moving a pane keeps its original connection. To resolve an unfamiliar path
that might point to an open workspace, `tm` can use a live connection to the
same SSH destination for discovery.

Each pane uses one of sshd's `MaxSessions` slots. `tm` reserves one slot per
connection for workspace discovery and closing terminals. With a limit of 10,
each session can have nine remote panes.
Discovery keeps its SSH session open while the windows start. Splits and
reconnects briefly occupy the same slot. sshd enforces the limit.
A fresh workspace tries `repo`, `editor`, then `codex`. On refusal,
it keeps the windows that opened and names the ones it skipped. If none fit,
the open fails. Start skipped programs manually in a new window or split when
there's room. A refused split closes with a tmux message. A refusal never
triggers a second login.

- **Connect** with a trusted SSH host key and a working agent. `tm` opens the
master before creating panes. OpenSSH manages the connection and closes it
after 60 seconds without a client. Logins use batch mode and strict host-key
checking. For a new host, verify its key with ordinary `ssh` first. OpenSSH
honors `IdentityAgent`. Each successful open saves the current `SSH_AUTH_SOCK`
path in the private connection lock file. Login does not require forwarding.
- **Reconnect** happens automatically. When a pane loses SSH, a tmux
`pane-died` hook starts recovery for its connection. One job retries with
backoff and reattaches surviving terminals in place, including moved panes.
It exits when recovery is done. If fewer slots are available,
remaining panes wait for room. Input typed into a dead pane is discarded.
Programs that ended stay closed. If SSH needs attention, fix the agent or
host key and rerun `tm --host …` from a local shell.
- **Recover after losing the local tmux server** by reopening each workspace.
Each surviving terminal gets a window named for its role. Custom titles, order
and split layouts survive only while the local server does.
- **End a terminal** with prefix `x`, or a whole window with prefix `&`. These
bindings report unconfirmed closes. Raw tmux kill commands only detach remote
terminals. Exiting a program on the devbox ends its terminal.

Use tmux 3.8+ locally. Zmx must be on the devbox's SSH command path. Its sockets live in
`~/.cache/tm-zmx` unless the SSH environment sets `ZMX_DIR`. Forwarded agent
sockets in surviving programs can go stale after reconnecting.

The agent popup and status feed show local conversations only.
87 changes: 87 additions & 0 deletions tools/cmd/tmux-session/launch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package main

import (
"cmp"
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"

"github.com/ddeville/scripts/tools/internal/sshmux"
"github.com/ddeville/scripts/tools/internal/tmux"
)

// Give sshd the real requests in order, with the management slot occupied.
func startPanes(ctx context.Context, master sshmux.Master, target *tmux.Session, windows []window) (int, error) {
if len(windows) == 0 {
return 0, nil
}

helper, err := os.Executable()
if err != nil {
return 0, fmt.Errorf("locate tmux-session: %w", err)
}

for i, win := range windows {
reply := filepath.Join(filepath.Dir(master.Socket), "open-"+rand.Text()[:16])
if err := win.start(ctx, target, helper, reply); err != nil {
return i, err
}
}

return len(windows), nil
}

// tmux returns as soon as it forks the helper. Read its one-time startup
// result before proceeding or releasing the management session.
func (w window) start(ctx context.Context, target *tmux.Session, helper, reply string) error {
listener, err := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: reply})
if err != nil {
return fmt.Errorf("listen for pane startup: %w", err)
}
defer func() { _ = listener.Close() }()

command := []string{helper, "--remote-pane", cmp.Or(w.terminal, w.role), "--pane-reply", reply}
switch {
case w.pane.ID != "":
err = w.pane.Resume(ctx, command...)
case target.ID == "":
err = createRemote(ctx, target, w.role, command...)
default:
err = tmux.StartWindow(ctx, target.ID, w.role, "", command...)
}

if err != nil {
return fmt.Errorf("start %s: %w", w.role, err)
}

stop := context.AfterFunc(ctx, func() { _ = listener.Close() })
defer stop()

conn, err := listener.Accept()
if err != nil {
return fmt.Errorf("wait for %s: %w", w.role, err)
}
defer func() { _ = conn.Close() }()

stop = context.AfterFunc(ctx, func() { _ = conn.Close() })
defer stop()

result, err := io.ReadAll(conn)
if err != nil {
return fmt.Errorf("read pane startup: %w", err)
}

switch string(result) {
case "+":
return nil
case "":
return fmt.Errorf("pane startup: %w", io.ErrUnexpectedEOF)
default:
return errors.New(string(result)) //nolint:err113 // The pane sends its startup error.
}
}
Loading
Loading