diff --git a/config/common/.config/tmux/tmux.conf b/config/common/.config/tmux/tmux.conf index 35ca102f..6a1844d2 100644 --- a/config/common/.config/tmux/tmux.conf +++ b/config/common/.config/tmux/tmux.conf @@ -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 @@ -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" diff --git a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md new file mode 100644 index 00000000..261718ba --- /dev/null +++ b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md @@ -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. diff --git a/tools/cmd/tmux-session/launch.go b/tools/cmd/tmux-session/launch.go new file mode 100644 index 00000000..ed39d5c3 --- /dev/null +++ b/tools/cmd/tmux-session/launch.go @@ -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. + } +} diff --git a/tools/cmd/tmux-session/main.go b/tools/cmd/tmux-session/main.go index 9c92a6ce..8f2b15b5 100644 --- a/tools/cmd/tmux-session/main.go +++ b/tools/cmd/tmux-session/main.go @@ -1,18 +1,20 @@ -// Command tmux-session opens a local project in tmux. +// Command tmux-session opens a local or remote project in tmux. package main import ( "context" + "errors" "fmt" "os" "path/filepath" - "slices" "syscall" + "time" "github.com/spf13/cobra" "github.com/ddeville/scripts/tools/internal/cli" "github.com/ddeville/scripts/tools/internal/session" + "github.com/ddeville/scripts/tools/internal/sshmux" "github.com/ddeville/scripts/tools/internal/tmux" "github.com/ddeville/scripts/tools/internal/tui" ) @@ -23,19 +25,42 @@ func main() { func command() *cobra.Command { var ( - name string - noSwitch bool + name, host, retry string + launch, reply, closeTarget string + noSwitch bool ) cmd := &cobra.Command{ Use: "tmux-session ", Short: "Open a project in tmux, creating repo, editor, and Codex windows on first use", - Example: " tmux-session .\n tmux-session ~/src/project --name my-project\n tmux-session --no-switch . -n scratch", + Example: " tmux-session .\n tmux-session ~/src/project --name my-project\n tmux-session --no-switch . -n scratch\n tmux-session --host devbox work/api", Args: cobra.MaximumNArgs(1), SilenceErrors: true, SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 0 { + if retry != "" { + master, err := sshmux.ForSession(host, retry) + if err != nil { + return fmt.Errorf("find session connection: %w", err) + } + + return reconnect(cmd.Context(), master) + } + + if launch != "" { + code, err := attachPane(cmd.Context(), launch, reply) + if err != nil { + cmd.PrintErrln(tui.CleanLine(err.Error())) + } + + os.Exit(code) + } + + if closeTarget != "" { + return closePanes(cmd.Context(), closeTarget) + } + if err := cmd.Help(); err != nil { return fmt.Errorf("show help: %w", err) } @@ -43,22 +68,22 @@ func command() *cobra.Command { return nil } - directory, err := resolveDirectory(args[0]) - if err != nil { - return err + if cmd.Flags().Changed("name") && name == "" { + return fmt.Errorf("%w: session name cannot be empty", os.ErrInvalid) } - sessionName := filepath.Base(directory) - - if cmd.Flags().Changed("name") { - if name == "" { - return fmt.Errorf("%w: session name cannot be empty", os.ErrInvalid) - } + var ( + target tmux.Session + created bool + err error + ) - sessionName = name + if cmd.Flags().Changed("host") { + target, created, err = openRemote(cmd.Context(), host, args[0], name) + } else { + target, created, err = openSession(cmd.Context(), args[0], name) } - target, created, err := openSession(cmd.Context(), directory, sessionName) if err != nil { return fmt.Errorf("open session: %w", err) } @@ -68,7 +93,7 @@ func command() *cobra.Command { action = "Created" } - cmd.Printf("%s tmux session: %s\nWorkdir: %s\n", action, tui.CleanLine(target.Name), tui.CleanLine(directory)) + cmd.Printf("%s tmux session: %s\nWorkdir: %s\n", action, tui.CleanLine(target.Name), tui.CleanLine(target.Path)) if noSwitch { return nil @@ -78,8 +103,17 @@ func command() *cobra.Command { }, } cmd.SetOut(os.Stdout) + cmd.Flags().StringVar(&host, "host", "", "SSH destination (relative paths start in the remote home directory)") cmd.Flags().StringVarP(&name, "name", "n", "", "open a named workspace for this directory (defaults to the directory name)") cmd.Flags().BoolVar(&noSwitch, "no-switch", false, "find or create the session without switching or attaching") + cmd.Flags().StringVar(&launch, "remote-pane", "", "launch or resume one pane") + cmd.Flags().StringVar(&reply, "pane-reply", "", "report pane startup to the caller") + cmd.Flags().Lookup("pane-reply").Hidden = true + cmd.Flags().StringVar(&retry, "reconnect", "", "recover interrupted panes of a remote session") + cmd.Flags().Lookup("reconnect").Hidden = true + cmd.Flags().StringVar(&closeTarget, "remote-close", "", "close a pane or window by ID") + cmd.Flags().Lookup("remote-pane").Hidden = true + cmd.Flags().Lookup("remote-close").Hidden = true return cmd } @@ -108,32 +142,59 @@ func resolveDirectory(path string) (string, error) { } // lockOpen serializes lookup and layout creation, including the first tmux server startup. -func lockOpen() (*os.File, error) { - cache, err := os.UserCacheDir() +func lockOpen(ctx context.Context) (*os.File, error) { + dir, err := sshmux.CacheDir() if err != nil { - return nil, fmt.Errorf("locate cache directory: %w", err) + return nil, fmt.Errorf("locate tmux session cache: %w", err) } - lockDir := filepath.Join(cache, "tmux-session") - if err := os.MkdirAll(lockDir, 0o700); err != nil { - return nil, fmt.Errorf("create lock directory: %w", err) - } + return lockFile(ctx, filepath.Join(dir, "open.lock")) +} + +// Only one operation at a time may use the connection's management slot. +func lockMaster(ctx context.Context, master sshmux.Master) (*os.File, error) { + return lockFile(ctx, master.Socket+".lock") +} - lock, err := os.OpenFile(filepath.Join(lockDir, "open.lock"), os.O_CREATE|os.O_RDWR, 0o600) // #nosec G304 -- Fixed filename in the user's application cache. +func lockFile(ctx context.Context, filename string) (*os.File, error) { + lock, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0o600) // #nosec G304 -- Internal lock file in a private directory. if err != nil { return nil, fmt.Errorf("open session lock: %w", err) } - if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil { - _ = lock.Close() - return nil, fmt.Errorf("lock session creation: %w", err) + for ctx.Err() == nil { + err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if err == nil { + return lock, nil + } + + if !errors.Is(err, syscall.EWOULDBLOCK) { + _ = lock.Close() + return nil, fmt.Errorf("acquire session lock: %w", err) + } + + select { + case <-ctx.Done(): + case <-time.After(25 * time.Millisecond): + } } - return lock, nil + _ = lock.Close() + + return nil, fmt.Errorf("wait for session lock: %w", ctx.Err()) } -func openSession(ctx context.Context, directory, name string) (tmux.Session, bool, error) { - lock, err := lockOpen() +func openSession(ctx context.Context, path, name string) (tmux.Session, bool, error) { + directory, err := resolveDirectory(path) + if err != nil { + return tmux.Session{}, false, err + } + + if name == "" { + name = filepath.Base(directory) + } + + lock, err := lockOpen(ctx) if err != nil { return tmux.Session{}, false, err } @@ -146,13 +207,13 @@ func openSession(ctx context.Context, directory, name string) (tmux.Session, boo workspace := fmt.Sprintf("%q %q", directory, name) for _, s := range sessions { - if s.Workspace == workspace { + if s.Remote == "" && s.Workspace == workspace { return s, false, nil } } for _, s := range sessions { - if s.Workspace == "" && s.Path == directory && s.Name == name { + if s.Remote == "" && s.Workspace == "" && s.Path == directory && s.Name == name { if err := tmux.SetOption(ctx, s.ID, tmux.WorkspaceOption, workspace); err != nil { return tmux.Session{}, false, fmt.Errorf("identify existing workspace: %w", err) } @@ -161,15 +222,12 @@ func openSession(ctx context.Context, directory, name string) (tmux.Session, boo } } - displayName := name - for suffix := 2; slices.ContainsFunc(sessions, func(s tmux.Session) bool { return s.Name == displayName }); suffix++ { - displayName = fmt.Sprintf("%s-%d", name, suffix) - } + displayName := tmux.AvailableName(sessions, name) id, err := session.Create(ctx, session.Options{Name: displayName, Directory: directory, Workspace: workspace}) if err != nil { return tmux.Session{}, false, fmt.Errorf("create workspace: %w", err) } - return tmux.Session{ID: id, Name: displayName}, true, nil + return tmux.Session{ID: id, Name: displayName, Path: directory}, true, nil } diff --git a/tools/cmd/tmux-session/pane.go b/tools/cmd/tmux-session/pane.go new file mode 100644 index 00000000..d58e4663 --- /dev/null +++ b/tools/cmd/tmux-session/pane.go @@ -0,0 +1,296 @@ +package main + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "os" + "os/exec" + "path" + "slices" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "github.com/ddeville/scripts/tools/internal/sshmux" + "github.com/ddeville/scripts/tools/internal/tmux" + "github.com/ddeville/scripts/tools/internal/tui" +) + +const attach = `export ZMX_NO_DETACH_KEY=1 +# Reserve status 255 for lost or refused SSH sessions. +trap '[ "$?" != 255 ] || exit 1' EXIT +if [ "$1" = resume ]; then + zmx get "$2" >/dev/null + # If it exits between get and attach, zmx must never relaunch its program. + set -- "$2" /bin/sh -c 'exit 1' +else + cd -P -- "$3" + case "$1" in + editor) set -- "$2" sh -c "exec ${EDITOR:-nvim}" ;; + codex) set -- "$2" codex ;; + *) set -- "$2" ;; + esac +fi +printf '\000' +zmx attach "$@"` + +func attachPane(ctx context.Context, requested, reply string) (int, error) { + var ( + ready func() + conn net.Conn + ) + + // A raw respawn may replay a command whose caller has already left. + if reply != "" { + conn, _ = (&net.Dialer{}).DialContext(ctx, "unix", reply) + if conn != nil { + defer func() { _ = conn.Close() }() + + ready = func() { + _, _ = io.WriteString(conn, "+") + _ = conn.Close() + } + } + } + + status, err := runPane(ctx, requested, ready) + if err != nil { + if conn != nil { + _, _ = io.WriteString(conn, err.Error()) + } else { + _ = tmux.Notify(ctx, "tm: "+tui.CleanLine(err.Error())) + } + } + + return status, err +} + +func runPane(ctx context.Context, requested string, ready func()) (int, error) { + // Keep local setup failures retryable when reattaching an existing terminal. + failure := 1 + if terminalID.MatchString(requested) { + failure = 255 + } + + id := os.Getenv("TMUX_PANE") + + panes, err := tmux.Attachments(ctx, id) + if err != nil { + return failure, fmt.Errorf("find attachment: %w", err) + } + + p, ok := panes[id] + if !ok { + return failure, fmt.Errorf("%w: expected a tmux pane", os.ErrInvalid) + } + + mode, dir := "resume", "" + + if p.Terminal == "" { + var w workspace + if err := json.Unmarshal([]byte(os.Getenv(tmux.RemoteEnv)), &w); err != nil { + return failure, fmt.Errorf("read remote workspace: %w", err) + } + + p.Host, p.Connection, p.Terminal, dir = w.Host, w.Connection, requested, w.Path + if slices.Contains(roles, requested) { + mode = requested + p.Terminal = w.prefix() + mode + "-" + rand.Text()[:13] + } else if !strings.HasPrefix(p.Terminal, w.prefix()) { + return failure, fmt.Errorf("%w: terminal belongs to another workspace", os.ErrInvalid) + } + } + + if !terminalID.MatchString(p.Terminal) { + return failure, fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) + } + + master, err := sshmux.ForSession(p.Host, p.Connection) + if err != nil { + return failure, fmt.Errorf("find pane connection: %w", err) + } + + sshCtx, cancel := context.WithCancel(ctx) + defer cancel() + + timer := time.AfterFunc(15*time.Second, cancel) + defer timer.Stop() + + // Splits have no caller holding the management session for them. + if ready == nil { + lock, err := lockMaster(sshCtx, master) + if err != nil { + return failure, err + } + + m, err := openManagement(sshCtx, master, "") + if err != nil { + _ = lock.Close() + + if dir != "" { + _ = panes[id].CloseOnExit(ctx) + } + + return failure, fmt.Errorf("reserve management slot: %w", err) + } + + ready = sync.OnceFunc(func() { m.close(); _ = lock.Close() }) + defer ready() + } + + var project, reconnect string + + if dir != "" { + helper, err := os.Executable() + if err != nil { + return failure, fmt.Errorf("locate tmux-session: %w", err) + } + + project = displayName(path.Base(dir)) + reconnect = "exec " + quote(helper) + " --host " + quote(master.Host) + " --reconnect " + quote(master.ID) + } + + // Record before launching. An ambiguous failure can only reattach here. + if err := p.Record(sshCtx, project, reconnect); err != nil { + return failure, fmt.Errorf("record remote pane: %w", err) + } + + var stderr bytes.Buffer + + output := &paneOutput{opened: func() { timer.Stop(); ready() }} + cmd := exec.CommandContext(sshCtx, "ssh", master.Channel("-tt", remoteCommand(attach, mode, p.Terminal, dir))...) // #nosec G204 -- Pinned master and quoted arguments. + cmd.SysProcAttr = &syscall.SysProcAttr{Foreground: true} + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, output, io.MultiWriter(os.Stderr, &stderr) + cmd.WaitDelay = time.Second + + err = cmd.Run() + if err == nil { + return 0, nil + } + + exit, ok := errors.AsType[*exec.ExitError](err) + if !ok || sshCtx.Err() != nil { + return failure, fmt.Errorf("run SSH pane: %w", err) + } + + code := max(1, exit.ExitCode()) + if output.opened == nil { + return code, nil + } + + err = sshmux.CommandError(err, stderr.String()) + if errors.Is(err, sshmux.ErrChannelRefused) { + if dir != "" { + _ = p.CloseOnExit(ctx) + } + + return code, fmt.Errorf("%w on %s (one MaxSessions slot is reserved for management)", sshmux.ErrChannelRefused, p.Host) + } + + return code, fmt.Errorf("SSH %s: %w", p.Host, err) +} + +type paneOutput struct{ opened func() } + +func (w *paneOutput) Write(data []byte) (int, error) { + if w.opened != nil && bytes.IndexByte(data, 0) >= 0 { + w.opened() + w.opened = nil + } + + n, err := os.Stdout.Write(data) + if err != nil { + return n, fmt.Errorf("write terminal output: %w", err) + } + + return n, nil +} + +// A missing live terminal may still be starting. A missing dead one can be +// removed, including after a successful kill whose acknowledgement was lost. +const stop = `zmx kill "$1" >/dev/null || [ "$2" = true ] +` + listTerminals + +func stopTerminal(ctx context.Context, p tmux.Attachment) error { + if !terminalID.MatchString(p.Terminal) { + return fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) + } + + master, err := sshmux.ForSession(p.Host, p.Connection) + if err != nil { + return fmt.Errorf("find pane connection: %w", err) + } + + command := remoteCommand(stop, p.Terminal, strconv.FormatBool(p.Dead)) + + lock, err := lockMaster(ctx, master) + if err != nil { + return err + } + defer func() { _ = lock.Close() }() + + out, err := master.Query(ctx, command) + if err != nil { + return fmt.Errorf("stop terminal: %w", err) + } + + names, err := inventory(out) + if err != nil { + return err + } + + if names[p.Terminal] { + return fmt.Errorf("%w: terminal is still running", os.ErrInvalid) + } + + return nil +} + +func closePanes(ctx context.Context, target string) error { + panes, err := tmux.Attachments(ctx, target) + if err != nil { + return fmt.Errorf("find close target: %w", err) + } + + var local []tmux.Attachment + + remote := false + + for _, p := range panes { + if p.ID != target && p.WindowID != target { + continue + } + + if p.Terminal != "" { + if err := stopTerminal(ctx, p); err != nil { + return fmt.Errorf("could not confirm remote close for %s: %w", p.ID, err) + } + + remote = true + } + + if p.Dead || p.Terminal == "" { + local = append(local, p) + } + } + + if !remote { + return fmt.Errorf("%w: no remote terminal at %s", os.ErrInvalid, target) + } + + for _, p := range local { + if err := p.KillPane(ctx); err != nil { + return fmt.Errorf("close pane %s: %w", p.ID, err) + } + } + + return nil +} diff --git a/tools/cmd/tmux-session/reconnect.go b/tools/cmd/tmux-session/reconnect.go new file mode 100644 index 00000000..963e31c2 --- /dev/null +++ b/tools/cmd/tmux-session/reconnect.go @@ -0,0 +1,132 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "syscall" + "time" + + "github.com/ddeville/scripts/tools/internal/sshmux" + "github.com/ddeville/scripts/tools/internal/tmux" + "github.com/ddeville/scripts/tools/internal/tui" +) + +// tmux runs this on pane-died. A dropped master can interrupt many panes at +// once. Elect one recovery job under the session lock, and release it under +// that same lock so a new failure during the last attempt is never missed. +func reconnect(ctx context.Context, master sshmux.Master) error { + lock, err := lockMaster(ctx, master) + if err != nil { + return err + } + defer func() { _ = lock.Close() }() + + job, err := os.OpenFile(master.Socket+".retry", os.O_RDWR|os.O_CREATE, 0o600) // #nosec G304 -- Private SSH socket directory. + if err != nil { + return fmt.Errorf("open recovery lock: %w", err) + } + defer func() { _ = job.Close() }() + + if err := syscall.Flock(int(job.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + if errors.Is(err, syscall.EWOULDBLOCK) { + return nil + } + + return fmt.Errorf("lock recovery: %w", err) + } + + for delay := time.Second; ; delay = min(delay*2, 30*time.Second) { + err := recoverPanes(ctx, master, lock) + if err == nil || errors.Is(err, sshmux.ErrSignIn) { + _ = os.Remove(job.Name()) // Job locks are opened only while the session lock is held. + return nil + } + + _ = lock.Close() + + if delay == 4*time.Second { + _ = tmux.Notify(ctx, "tm: retrying recovery for "+master.Host+" · "+tui.CleanLine(err.Error())) + } + + select { + case <-ctx.Done(): + return nil + case <-time.After(delay): + } + + lock, err = lockMaster(ctx, master) + if err != nil { + return err + } + } +} + +func recoverPanes(ctx context.Context, master sshmux.Master, lock *os.File) error { + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + + panes, err := tmux.Attachments(ctx, "") + if err != nil { + return fmt.Errorf("inspect interrupted panes: %w", err) + } + + if len(interrupted(panes, master)) == 0 { + return nil + } + + agent, err := io.ReadAll(lock) + if err != nil { + return fmt.Errorf("read SSH agent socket: %w", err) + } + + connectErr := master.Connect(ctx, string(agent)) + if connectErr != nil && !errors.Is(connectErr, sshmux.ErrSignIn) { + return fmt.Errorf("restore connection: %w", connectErr) + } + + // Other panes may have moved or lost their connection during the login. + panes, err = tmux.Attachments(ctx, "") + if err != nil { + return fmt.Errorf("inspect interrupted panes: %w", err) + } + + failed := interrupted(panes, master) + if connectErr != nil { + for _, p := range failed { + _ = p.RequireSignIn(ctx) + } + + return fmt.Errorf("restore connection: %w", connectErr) + } + + m, err := openManagement(ctx, master, "") + if err != nil { + return fmt.Errorf("open management session: %w", err) + } + defer m.close() + + resume := make([]window, 0, len(failed)) + for _, p := range failed { + resume = append(resume, window{role: p.ID, terminal: p.Terminal, pane: p}) + } + + _, err = startPanes(ctx, master, nil, resume) + + return err +} + +func interrupted(panes map[string]tmux.Attachment, master sshmux.Master) []tmux.Attachment { + var failed []tmux.Attachment + + for _, p := range panes { + if p.Dead && p.ExitStatus == "255" && !p.NeedsSignIn && + p.Connection == master.ID && p.Host == master.Host && terminalID.MatchString(p.Terminal) { + failed = append(failed, p) + } + } + + return failed +} diff --git a/tools/cmd/tmux-session/remote.go b/tools/cmd/tmux-session/remote.go new file mode 100644 index 00000000..0904b242 --- /dev/null +++ b/tools/cmd/tmux-session/remote.go @@ -0,0 +1,457 @@ +package main + +import ( + "bufio" + "bytes" + "cmp" + "context" + "crypto/rand" + "crypto/sha256" + "encoding/json" + "fmt" + "os" + "os/exec" + "path" + "path/filepath" + "regexp" + "slices" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/ddeville/scripts/tools/internal/sshmux" + "github.com/ddeville/scripts/tools/internal/tmux" + "github.com/ddeville/scripts/tools/internal/tui" +) + +type workspace struct { + Host string `json:"host"` + Path string `json:"path"` + Name string `json:"name"` + Request string `json:"request"` + Connection string `json:"connection"` +} + +// Terminal names survive the loss of a local session and its connection ID. +func (w workspace) prefix() string { + sum := sha256.Sum256([]byte(w.Host + "\x00" + w.Path + "\x00" + w.Name)) + return fmt.Sprintf("tm-%x.", sum[:10]) +} + +// tmux expands session names as formats, even when passed as separate arguments. +func displayName(s string) string { + return strings.Map(func(r rune) rune { + if unicode.IsLetter(r) || unicode.IsDigit(r) || strings.ContainsRune("@/_- ", r) { + return r + } + + return '_' + }, s) +} + +var ( + roles = []string{"repo", "editor", "codex", "shell"} + terminalID = regexp.MustCompile(`^tm-[0-9a-f]{20}\.(repo|editor|codex|shell)-[A-Z2-7]{13}$`) +) + +type window struct { + role, terminal string + pane tmux.Attachment +} + +const listTerminals = `zmx list +printf '\000'` + +// The full listing also includes unresponsive sessions. --short hides those, +// so an outage could look like a fresh workspace or a successful close. +func inventory(out string) (map[string]bool, error) { + list, ok := strings.CutSuffix(out, "\x00") + if !ok { + return nil, fmt.Errorf("%w: incomplete zmx listing", os.ErrInvalid) + } + + names := make(map[string]bool) + + for line := range strings.Lines(list) { + field, _, tab := strings.Cut(strings.TrimSpace(line), "\t") + + name, ok := strings.CutPrefix(field, "name=") + if !tab || !ok || name == "" { + return nil, fmt.Errorf("%w: unexpected zmx listing", os.ErrInvalid) + } + + names[name] = true + } + + return names, nil +} + +// SSH passes a single command string to the login shell. Quote backslashes outside +// single quotes so both fish and POSIX shells pass them through literally. +func quote(s string) string { + return "'" + strings.NewReplacer("'", "'\\''", "\\", "'\\\\'").Replace(s) + "'" +} + +func remoteCommand(script string, args ...string) string { + // A login's XDG_RUNTIME_DIR can disappear when the connection drops. + const setup = `set -eu +unset ZMX_SESSION ZMX_SESSION_PREFIX +export ZMX_DIR="${ZMX_DIR:-$HOME/.cache/tm-zmx}" ZMX_DIR_MODE=0700 ZMX_LOG_MODE=0600 +` + + var command strings.Builder + command.WriteString("exec sh -c " + quote(setup+script) + " sh") + + for _, arg := range args { + command.WriteByte(' ') + command.WriteString(quote(arg)) + } + + return command.String() +} + +const inspect = `unset CDPATH +command -v zmx >/dev/null || { echo 'Install zmx on the SSH host first' >&2; exit 1; } +cd -P -- "$HOME" +cd -P -- "$1" +printf '%s\000' "$PWD" +` + listTerminals + +type management struct { + dir, listing string + close func() +} + +// Keep discovery's session open until sshd accepts or refuses the panes. +// Splits and reconnects need the slot but have nothing to discover. +func openManagement(ctx context.Context, master sshmux.Master, request string) (management, error) { + script := inspect + if request == "" { + script = `printf '\000\000'` + } + + command := remoteCommand(script+"\nread -r done || :", request) + cmd := exec.CommandContext(ctx, "ssh", master.Channel("-T", command)...) // #nosec G204 -- Pinned master and quoted arguments. + cmd.WaitDelay = time.Second + + var stderr bytes.Buffer + + cmd.Stderr = &stderr + + in, err := cmd.StdinPipe() + if err != nil { + return management{}, fmt.Errorf("open management stdin: %w", err) + } + + out, err := cmd.StdoutPipe() + if err != nil { + _ = in.Close() + return management{}, fmt.Errorf("open management stdout: %w", err) + } + + if err := cmd.Start(); err != nil { + return management{}, fmt.Errorf("start management session: %w", err) + } + + stop := context.AfterFunc(ctx, func() { _ = out.Close() }) + defer stop() + + reader := bufio.NewReader(out) + + var fields [2]string + for i := range fields { + fields[i], err = reader.ReadString(0) + if err != nil { + _ = in.Close() + + if waitErr := cmd.Wait(); waitErr != nil { + return management{}, fmt.Errorf("%s: %w", master.Host, sshmux.CommandError(waitErr, stderr.String())) + } + + return management{}, fmt.Errorf("read management reply: %w", err) + } + } + + return management{ + dir: strings.TrimSuffix(fields[0], "\x00"), listing: fields[1], + close: func() { _ = in.Close(); _ = cmd.Wait() }, + }, nil +} + +type remoteSession struct { + target tmux.Session + info workspace +} + +// For a given host and requested name, the resolved directory selects the session. +func matchingSessions(sessions []tmux.Session, host, name string) map[string]remoteSession { + known := make(map[string]remoteSession) + + for _, s := range sessions { + var w workspace + if s.Remote != "" && json.Unmarshal([]byte(s.Remote), &w) == nil && + w.Host == host && w.Name == cmp.Or(name, path.Base(w.Path)) { + known[w.Path] = remoteSession{s, w} + } + } + + return known +} + +// A new path spelling may be a symlink to an open workspace. Use a live +// candidate for discovery so resolving that alias doesn't require a login. +func discoverySession(ctx context.Context, known map[string]remoteSession, request string) remoteSession { + if s, ok := known[request]; ok { + return s + } + + for _, s := range known { + if s.info.Request == request { + return s + } + } + + for _, s := range known { + master, err := sshmux.ForSession(s.info.Host, s.info.Connection) + if err == nil && master.Running(ctx) { + return s + } + } + + return remoteSession{} +} + +func openRemote(ctx context.Context, host, request, name string) (tmux.Session, bool, error) { + if host == "" || request == "" { + return tmux.Session{}, false, fmt.Errorf("%w: expected an SSH host and remote path", os.ErrInvalid) + } + + if request == "~" { + request = "." + } + + if !path.IsAbs(request) { + request = "./" + strings.TrimPrefix(strings.TrimPrefix(request, "~/"), "./") + } + + // Concurrent opens can resolve to the same workspace. Serialize lookup + // without blocking local opens or other sessions' splits and reconnects. + dir, err := sshmux.CacheDir() + if err != nil { + return tmux.Session{}, false, fmt.Errorf("locate session cache: %w", err) + } + + sum := sha256.Sum256([]byte(host)) + + lookup, err := lockFile(ctx, filepath.Join(dir, fmt.Sprintf("open-%x.lock", sum[:10]))) + if err != nil { + return tmux.Session{}, false, err + } + + defer func() { _ = lookup.Close() }() + + sessions, err := tmux.ListSessions(ctx) + if err != nil { + return tmux.Session{}, false, fmt.Errorf("list sessions: %w", err) + } + + ctx, cancel := context.WithTimeout(ctx, 50*time.Second) + defer cancel() + + known := matchingSessions(sessions, host, name) + candidate := discoverySession(ctx, known, request) + + // Switch to the actual owner before opening any panes. A second mismatch + // means the directory changed while we were opening it. + for range 2 { + id := candidate.info.Connection + if candidate.target.ID == "" { + id = rand.Text() + } + + master, err := sshmux.ForSession(host, id) + if err != nil { + return tmux.Session{}, false, fmt.Errorf("find session connection: %w", err) + } + + lock, err := lockMaster(ctx, master) + if err != nil { + return tmux.Session{}, false, err + } + + if err := master.Connect(ctx, os.Getenv("SSH_AUTH_SOCK")); err != nil { + _ = lock.Close() + return tmux.Session{}, false, fmt.Errorf("SSH: %w", err) + } + + m, err := openManagement(ctx, master, request) + if err != nil { + _ = lock.Close() + return tmux.Session{}, false, fmt.Errorf("inspect workspace: %w", err) + } + + owner := known[m.dir] + if owner == candidate { + defer func() { _ = lock.Close() }() + defer m.close() + + return owner.open(ctx, master, lock, m, request, name) + } + + m.close() + + if candidate.target.ID == "" { + master.Stop(ctx) + } + + _ = lock.Close() + candidate = owner + } + + return tmux.Session{}, false, fmt.Errorf("%w: remote workspace changed while opening %s", os.ErrInvalid, request) +} + +func (s remoteSession) open(ctx context.Context, master sshmux.Master, lock *os.File, m management, request, name string) (tmux.Session, bool, error) { + if !path.IsAbs(m.dir) || !utf8.ValidString(m.dir) { + return tmux.Session{}, false, fmt.Errorf("%w: invalid remote directory", os.ErrInvalid) + } + + names, err := inventory(m.listing) + if err != nil { + return tmux.Session{}, false, err + } + + target, w := s.target, s.info + + created := target.ID == "" + if created { + w = workspace{Host: master.Host, Path: m.dir, Name: cmp.Or(name, path.Base(m.dir)), Request: request, Connection: master.ID} + + meta, err := json.Marshal(w) + if err != nil { + return tmux.Session{}, false, fmt.Errorf("encode workspace: %w", err) + } + + target = tmux.Session{Name: displayName(w.Host + "/" + w.Name), Remote: string(meta)} + } + + target.Path = w.Path + if err := w.attach(ctx, master, &target, names); err != nil { + return tmux.Session{}, false, err + } + + // tmux may still have an older agent in its environment after a reopen. + if err := lock.Truncate(0); err != nil { + return tmux.Session{}, false, fmt.Errorf("update SSH agent socket: %w", err) + } + + if _, err := lock.WriteString(os.Getenv("SSH_AUTH_SOCK")); err != nil { + return tmux.Session{}, false, fmt.Errorf("save SSH agent socket: %w", err) + } + + return target, created, nil +} + +// Pane names and positions are mutable. Only a terminal ID can identify a +// survivor or show that it already has a pane, possibly in another session. +func (w workspace) windows(names map[string]bool, panes map[string]tmux.Attachment, fresh bool) ([]window, error) { + prefix := w.prefix() + attached := make(map[string]bool) + + for _, p := range panes { + if p.Host == w.Host && strings.HasPrefix(p.Terminal, prefix) { + attached[p.Terminal] = true + } + } + + var windows []window + + for id := range names { + if !strings.HasPrefix(id, prefix) || attached[id] { + continue + } + + match := terminalID.FindStringSubmatch(id) + if match == nil { + return nil, fmt.Errorf("%w: invalid remote terminal ID", os.ErrInvalid) + } + + windows = append(windows, window{role: match[1], terminal: id}) + } + + if fresh && len(windows) == 0 { + if len(attached) != 0 { + return []window{{role: "shell"}}, nil + } + + return []window{{role: "repo"}, {role: "editor"}, {role: "codex"}}, nil + } + + slices.SortFunc(windows, func(a, b window) int { + return cmp.Or(cmp.Compare(slices.Index(roles, a.role), slices.Index(roles, b.role)), cmp.Compare(a.terminal, b.terminal)) + }) + + return windows, nil +} + +func (w workspace) attach(ctx context.Context, master sshmux.Master, target *tmux.Session, names map[string]bool) error { + panes, err := tmux.Attachments(ctx, "") + if err != nil { + return fmt.Errorf("find existing remote panes: %w", err) + } + + created := target.ID == "" + + windows, err := w.windows(names, panes, created) + if err != nil { + return err + } + + for _, p := range panes { + if p.Host == w.Host && p.Connection == w.Connection && p.Dead && names[p.Terminal] && terminalID.MatchString(p.Terminal) { + windows = append(windows, window{role: p.ID, terminal: p.Terminal, pane: p}) + } + } + + started, err := startPanes(ctx, master, target, windows) + if err != nil { + if created && started == 0 { + return err + } + + var missing []string + for _, win := range windows[started:] { + missing = append(missing, win.role) + } + + message := tui.CleanLine(fmt.Sprintf("tm: could not open %s: %v", strings.Join(missing, ", "), err)) + _, _ = fmt.Fprintln(os.Stderr, message) + _ = tmux.Notify(ctx, message) + } + + return nil +} + +func createRemote(ctx context.Context, target *tmux.Session, role string, command ...string) error { + // Only allocating a session name and starting tmux require the local lock. + lock, err := lockOpen(ctx) + if err != nil { + return err + } + defer func() { _ = lock.Close() }() + + sessions, err := tmux.ListSessions(ctx) + if err != nil { + return fmt.Errorf("list sessions: %w", err) + } + + target.Name = tmux.AvailableName(sessions, target.Name) + + target.ID, err = tmux.NewRemoteSession(ctx, *target, role, "exec "+quote(command[0])+" --remote-pane shell", command...) + if err != nil { + return fmt.Errorf("create remote session: %w", err) + } + + return nil +} diff --git a/tools/cmd/tmux-session/remote_test.go b/tools/cmd/tmux-session/remote_test.go new file mode 100644 index 00000000..12a607f6 --- /dev/null +++ b/tools/cmd/tmux-session/remote_test.go @@ -0,0 +1,194 @@ +package main + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/ddeville/scripts/tools/internal/sshmux" + "github.com/ddeville/scripts/tools/internal/tmux" +) + +func TestDiscoveryKeepsItsSlotUntilPanesStart(t *testing.T) { + dir := t.TempDir() + t.Chdir(dir) + t.Setenv("PATH", dir+":"+os.Getenv("PATH")) + + const ssh = `#!/bin/sh +case " $* " in *" -oProxyCommand=false "*) ;; *) exit 1 ;; esac +mkdir slot 2>/dev/null || { echo "Session open refused by peer" >&2; exit 255; } +trap 'rmdir slot' EXIT +for arg do command=$arg; done +sh -c "$command" +` + if err := os.WriteFile("ssh", []byte(ssh), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private test directory. + t.Fatal(err) + } + + dest := sshmux.Master{Host: "devbox", Socket: filepath.Join(dir, "master")} + + if err := os.WriteFile("zmx", []byte("#!/bin/sh\necho 'name=term\tclients=0'\n"), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private test directory. + t.Fatal(err) + } + + m, err := openManagement(t.Context(), dest, dir) + if err != nil { + t.Fatal(err) + } + + _, err = dest.Query(t.Context(), "true") + + m.close() + + if m.listing != "name=term\tclients=0\n\x00" { + t.Fatalf("unexpected zmx listing %q", m.listing) + } + + if !errors.Is(err, sshmux.ErrChannelRefused) { + t.Fatalf("expected refusal while session held, got %v", err) + } + + if _, err := dest.Query(t.Context(), "true"); err != nil { + t.Fatalf("session not released: %v", err) + } +} + +func TestRestoreOnlyUnattachedSurvivors(t *testing.T) { + t.Parallel() + + w := workspace{Host: "devbox", Path: "/work/api", Name: "api", Request: "./api", Connection: "old"} + other := workspace{Host: "devbox", Path: "/personal/api", Name: "api"} + moved := w.prefix() + "editor-AAAAAAAAAAAAA" + first := w.prefix() + "shell-AAAAAAAAAAAAA" + second := w.prefix() + "shell-BBBBBBBBBBBBB" + names := map[string]bool{moved: true, second: true, first: true, other.prefix() + "repo-AAAAAAAAAAAAA": true} + panes := map[string]tmux.Attachment{"%4": {Host: w.Host, Terminal: moved, Dead: true}} + + // A replacement session may have a new master and a different path spelling. + w.Connection, w.Request = "new", w.Path + + got, err := w.windows(names, panes, true) + if err != nil { + t.Fatal(err) + } + + want := []window{{role: "shell", terminal: first}, {role: "shell", terminal: second}} + if !slices.Equal(got, want) { + t.Fatalf("restored windows = %v, want %v", got, want) + } +} + +func TestReopenSelectsTheSessionEvenAfterRename(t *testing.T) { + t.Parallel() + + sessions := []tmux.Session{ + {ID: "$1", Name: "renamed", Remote: `{"host":"dev","path":"/work/api","name":"api","request":"./api","connection":"a"}`}, + {ID: "$2", Remote: `{"host":"dev","path":"/work/api","name":"scratch","request":"./api","connection":"b"}`}, + {ID: "$3", Remote: `{"host":"dev","path":"/other/api","name":"api","request":"./other/api","connection":"c"}`}, + } + + for _, tc := range []struct{ dir, name, connection string }{ + {"./api", "", "a"}, + {"/work/api", "api", "a"}, + {"./api", "scratch", "b"}, + {"./other/api", "", "c"}, + } { + known := matchingSessions(sessions, "dev", tc.name) + if s := discoverySession(t.Context(), known, tc.dir); s.info.Connection != tc.connection { + t.Errorf("reopen %s %q selected %q, want %q", tc.dir, tc.name, s.info.Connection, tc.connection) + } + } +} + +func TestDiscoveryDistinguishesUnreachableFromGone(t *testing.T) { + t.Parallel() + + const listing = " name=term\terr=Timeout\tstatus=unreachable\n" + + names, err := inventory(listing + "\x00") + if err != nil || !names["term"] { + t.Fatalf("lost unresponsive terminal: %v, %v", names, err) + } + + for _, out := range []string{"", listing, "unexpected output\x00"} { + if _, err := inventory(out); err == nil { + t.Errorf("accepted invalid inventory %q", out) + } + } +} + +func TestRecoveryOnlyRetriesSSHFailuresOnThisConnection(t *testing.T) { + t.Parallel() + + const terminal = "tm-1234567890abcdef1234.shell-AAAAAAAAAAAAA" + + panes := map[string]tmux.Attachment{ + "%1": {ID: "%1", Host: "dev", Connection: "a", Terminal: terminal, Dead: true, ExitStatus: "255"}, + "%2": {ID: "%2", Host: "dev", Connection: "a", Terminal: terminal, Dead: true, ExitStatus: "1"}, + "%3": {ID: "%3", Host: "dev", Connection: "a", Terminal: terminal}, + "%4": {ID: "%4", Host: "dev", Connection: "b", Terminal: terminal, Dead: true, ExitStatus: "255"}, + "%5": {ID: "%5", Host: "dev", Connection: "a", Dead: true, ExitStatus: "255"}, + "%6": {ID: "%6", Host: "dev", Connection: "a", Terminal: terminal, Dead: true, ExitStatus: "255", NeedsSignIn: true}, + } + + retry := interrupted(panes, sshmux.Master{Host: "dev", ID: "a"}) + if !slices.Equal(retry, []tmux.Attachment{panes["%1"]}) { + t.Fatalf("retry = %v", retry) + } +} + +func TestRemoteExit255DoesNotTriggerReconnect(t *testing.T) { + t.Parallel() + + cmd := exec.CommandContext(t.Context(), "sh", "-ec", "zmx() { return 255; }\n"+attach, "sh", "repo", "terminal", "/") + if exit, ok := errors.AsType[*exec.ExitError](cmd.Run()); !ok || exit.ExitCode() != 1 { + t.Fatalf("zmx exit 255 was not reported as a program failure: %v", cmd.ProcessState) + } +} + +func TestFailedPaneLookupKeepsReattachmentRetryable(t *testing.T) { + t.Setenv("PATH", t.TempDir()) // tmux is unavailable before the helper can record a new connection. + + const terminal = "tm-1234567890abcdef1234.shell-AAAAAAAAAAAAA" + for request, want := range map[string]int{terminal: 255, "shell": 1} { + code, err := attachPane(t.Context(), request, "") + if err == nil || code != want { + t.Fatalf("attachPane(%s) = %d, %v, want status %d", request, code, err, want) + } + } +} + +func TestReconnectRetriesLookupAndExitsWithServer(t *testing.T) { + dir := t.TempDir() + t.Chdir(dir) + t.Setenv("PATH", dir) + + const script = `#!/bin/sh +if [ -f failed ]; then + : > stopped + echo "no server running on /test" >&2 +fi +: > failed +exit 1 +` + if err := os.WriteFile("tmux", []byte(script), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private test directory. + t.Fatal(err) + } + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + + dest := sshmux.Master{Host: "dev", ID: "abc", Socket: filepath.Join(dir, "ssh")} + if err := reconnect(ctx, dest); err != nil || ctx.Err() != nil { + t.Fatalf("reconnect = %v, context = %v", err, ctx.Err()) + } + + if _, err := os.Stat("stopped"); err != nil { + t.Fatal("reconnect did not retry the failed lookup") + } +} diff --git a/tools/internal/sshmux/ssh.go b/tools/internal/sshmux/ssh.go new file mode 100644 index 00000000..4fc4d0bd --- /dev/null +++ b/tools/internal/sshmux/ssh.go @@ -0,0 +1,178 @@ +// Package sshmux manages a private OpenSSH master for a tmux session. +package sshmux + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "syscall" + "time" +) + +// Master identifies the connection used by the panes of one local session. +type Master struct { + Host, ID, Socket string +} + +var ( + sshHost = regexp.MustCompile(`^[a-zA-Z0-9_@.%+:/\[\]-]+$`) + // ErrChannelRefused indicates that the master cannot open another session. + ErrChannelRefused = errors.New("SSH session refused") + // ErrSignIn stops automatic retries until the user explicitly runs tm again. + ErrSignIn = errors.New("SSH requires attention") +) + +// ForSession resolves the private control socket without opening a connection. +func ForSession(host, id string) (Master, error) { + if !sshHost.MatchString(host) || strings.HasPrefix(host, "-") { + return Master{}, fmt.Errorf("%w: invalid SSH destination %q", os.ErrInvalid, host) + } + + if id == "" { + return Master{}, fmt.Errorf("%w: missing SSH connection ID", os.ErrInvalid) + } + + dir, err := CacheDir() + if err != nil { + return Master{}, err + } + + sum := sha256.Sum256([]byte(host + "\x00" + id)) + + return Master{Host: host, ID: id, Socket: filepath.Join(dir, fmt.Sprintf("ssh-%x", sum[:10]))}, nil +} + +// Running checks only the local control socket. +func (d Master) Running(ctx context.Context) bool { + return exec.CommandContext(ctx, "ssh", "-S", d.Socket, "-O", "check", "--", d.Host).Run() == nil // #nosec G204 -- The validated destination follows --. +} + +// Connect starts or reuses the master under the session lock. Let OpenSSH +// select the agent and identities from the caller's environment and config. +func (d Master) Connect(ctx context.Context, agent string) error { + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + + if d.Running(ctx) { + return nil + } + + cmd := exec.CommandContext(ctx, "ssh", // #nosec G204 -- The validated destination follows --. + "-S", d.Socket, "-fN", "-oControlMaster=auto", "-oControlPersist=60", + "-oRemoteCommand=none", "-oConnectTimeout=10", "-oServerAliveInterval=5", "-oServerAliveCountMax=2", + "-oBatchMode=yes", "-oStrictHostKeyChecking=yes", "--", d.Host) + // A ProxyCommand starts before ssh backgrounds itself. Let it outlive tm. + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + + if agent != os.Getenv("SSH_AUTH_SOCK") { + cmd.Env = append(cmd.Environ(), "SSH_AUTH_SOCK="+agent) + } + + // A proxy can keep stderr open after ssh backgrounds the master. + cmd.WaitDelay = time.Second + if _, err := cmd.Output(); err != nil && !errors.Is(err, exec.ErrWaitDelay) { + if ctx.Err() != nil { + return fmt.Errorf("connect to %s: %w", d.Host, ctx.Err()) + } + + var exit *exec.ExitError + if errors.As(err, &exit) && len(exit.Stderr) != 0 { + detail := strings.TrimSpace(string(exit.Stderr)) + if needsSignIn(detail) { + err = ErrSignIn + } + + return fmt.Errorf("connect to %s: %w: %s", d.Host, err, detail) + } + + return fmt.Errorf("connect to %s: %w", d.Host, err) + } + + return nil +} + +// Stop discards a provisional master that did not acquire any panes. +func (d Master) Stop(ctx context.Context) { + _ = exec.CommandContext(ctx, "ssh", "-S", d.Socket, "-O", "exit", "--", d.Host).Run() // #nosec G204 -- The validated destination follows --. +} + +func needsSignIn(message string) bool { + return strings.Contains(message, "Permission denied") || + strings.Contains(message, "Host key verification failed") || + strings.Contains(message, "Too many authentication failures") +} + +// Channel returns ssh arguments for an existing master only. +// ControlMaster=no alone allows a direct connection if the socket is gone or the master refuses a channel. +func (d Master) Channel(tty, command string) []string { + return []string{ + "-S", d.Socket, "-oControlMaster=no", "-oProxyCommand=false", "-oBatchMode=yes", + "-oClearAllForwardings=yes", "-oStdinNull=no", "-oRemoteCommand=none", "-oLogLevel=ERROR", "-e", "none", tty, "--", d.Host, command, + } +} + +// Query runs one non-interactive command with a deadline. +func (d Master) Query(ctx context.Context, command string) (string, error) { + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + + cmd := exec.CommandContext(ctx, "ssh", d.Channel("-T", command)...) // #nosec G204 -- Fixed scripts with quoted arguments over the private master. + cmd.WaitDelay = time.Second + + out, err := cmd.Output() + if err != nil { + return "", fmt.Errorf("SSH %s: %w", d.Host, CommandError(err, "")) + } + + return string(out), nil +} + +// CommandError distinguishes a rejected session from a broken connection. +func CommandError(err error, stderr string) error { + if exit, ok := errors.AsType[*exec.ExitError](err); ok { + if stderr == "" { + stderr = string(exit.Stderr) + } + + if exit.ExitCode() == 255 && strings.Contains(stderr, "Session open refused") { + return fmt.Errorf("%w (check sshd MaxSessions)", ErrChannelRefused) + } + } + + if stderr != "" { + return fmt.Errorf("%w: %s", err, strings.TrimSpace(stderr)) + } + + return err +} + +// CacheDir locates the user’s session cache. +func CacheDir() (string, error) { + cache, err := os.UserCacheDir() + if err != nil { + return "", fmt.Errorf("locate cache directory: %w", err) + } + + dir := filepath.Join(cache, "tmux-session") + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", fmt.Errorf("create session cache: %w", err) + } + + info, err := os.Lstat(dir) + if err != nil { + return "", fmt.Errorf("inspect SSH socket directory: %w", err) + } + + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok || !info.IsDir() || int(stat.Uid) != os.Geteuid() || info.Mode().Perm()&0o077 != 0 { + return "", fmt.Errorf("%w: SSH socket directory %s must be private", os.ErrPermission, dir) + } + + return dir, nil +} diff --git a/tools/internal/sshmux/ssh_test.go b/tools/internal/sshmux/ssh_test.go new file mode 100644 index 00000000..a20b0a1f --- /dev/null +++ b/tools/internal/sshmux/ssh_test.go @@ -0,0 +1,63 @@ +package sshmux_test + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/ddeville/scripts/tools/internal/sshmux" +) + +func TestSessionControlsWhichMasterPanesUse(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", dir) + t.Setenv("XDG_CACHE_HOME", dir) + + socket := func(host, session string) string { + t.Helper() + + master, err := sshmux.ForSession(host, session) + if err != nil { + t.Fatal(err) + } + + return master.Socket + } + + first := socket("devbox", "a") + if first != socket("devbox", "a") || first == socket("devbox", "b") || first == socket("other", "a") { + t.Fatal("only panes of the same session and host should use the same master") + } + + if _, err := sshmux.ForSession("devbox", ""); err == nil { + t.Fatal("a missing session ID must not select a shared master") + } +} + +func TestConnectUsesCurrentAgentAndRefusesUntrustedHost(t *testing.T) { + dir := t.TempDir() + + const ssh = `#!/bin/sh +case " $* " in *" -O check "*) exit 1 ;; esac +[ "$SSH_AUTH_SOCK" = /new-agent ] || exit 2 +case " $* " in *" -oBatchMode=yes "*) ;; *) exit 3 ;; esac +case " $* " in *" -oStrictHostKeyChecking=yes "*) ;; *) exit 4 ;; esac +echo 'Host key verification failed.' >&2 +exit 255 +` + if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte(ssh), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private test directory. + t.Fatal(err) + } + + t.Setenv("PATH", dir) + t.Setenv("SSH_AUTH_SOCK", "/old-agent") + + master := sshmux.Master{Host: "devbox", Socket: filepath.Join(dir, "master")} + + err := master.Connect(t.Context(), "/new-agent") + if !errors.Is(err, sshmux.ErrSignIn) || !strings.Contains(err.Error(), "Host key verification failed") { + t.Fatalf("expected an actionable host key failure that stops retries, got %v", err) + } +} diff --git a/tools/internal/tmux/command.go b/tools/internal/tmux/command.go index 3231ac27..01f4092c 100644 --- a/tools/internal/tmux/command.go +++ b/tools/internal/tmux/command.go @@ -32,6 +32,38 @@ esac return append([]string{"/bin/sh", "-c", script, "sh"}, command...) } +// tmux treats a trailing semicolon as a command separator even in argv. +func literalArg(value string) string { + if prefix, ok := strings.CutSuffix(value, ";"); ok { + return prefix + `\;` + } + + return value +} + +// Insert literal '#' characters after tmux parses the format. +func literalFormat(value string) string { + return strings.ReplaceAll(literalArg(value), "#", "#{a:35}") +} + +func appendCommand(args, command []string) []string { + for _, arg := range command { + args = append(args, literalArg(arg)) + } + + return args +} + +// commandLine quotes arguments for tmux's command parser inside if-shell -F. +func commandLine(args ...string) string { + quoted := make([]string, 0, len(args)) + for _, arg := range args { + quoted = append(quoted, "'"+strings.ReplaceAll(arg, "'", "'\\''")+"'") + } + + return strings.Join(quoted, " ") +} + func run(ctx context.Context, args ...string) (string, error) { cmd := exec.CommandContext(ctx, "tmux", args...) // #nosec G204 G702 -- Arguments are separate; callers explicitly supply any window shell command. cmd.WaitDelay = time.Second diff --git a/tools/internal/tmux/remote.go b/tools/internal/tmux/remote.go new file mode 100644 index 00000000..0997e230 --- /dev/null +++ b/tools/internal/tmux/remote.go @@ -0,0 +1,151 @@ +package tmux + +import ( + "context" + "fmt" + "os" + "strings" + "time" +) + +// RemoteEnv identifies a remote session and supplies the workspace to new panes. +const RemoteEnv = "TM_REMOTE_WORKSPACE" + +// NewRemoteSession sets the command for future windows and splits in the same +// queue that creates the session. Its local working directory is the user's home. +func NewRemoteSession(ctx context.Context, s Session, window, defaultCommand string, command ...string) (string, error) { + args := []string{ + "new-session", "-d", "-P", "-F", "#{session_id}", "-s", literalFormat(s.Name), "-c", "#{HOME}", + "-e", literalArg(RemoteEnv + "=" + s.Remote), "-n", literalFormat(window), + } + args = appendCommand(args, command) + args = append(args, ";", "set-option", "-t", "="+s.Name+":", "default-command", literalArg(defaultCommand)) + + out, err := run(ctx, args...) + if err != nil { + return "", err + } + + return strings.TrimSpace(out), nil +} + +// Attachment identifies a local pane and the remote terminal it owns, if any. +type Attachment struct { + ID, WindowID string + Host, Connection, Terminal string + Dead, NeedsSignIn bool + ExitStatus string + server string +} + +// Attachments returns each pane once, even if its window is linked to multiple +// sessions. A pane or window ID limits the lookup to that window. +func Attachments(ctx context.Context, target string) (map[string]Attachment, error) { + const format = "#{pane_id}\t#{window_id}\t#{pane_dead}\t#{@tm_host}\t#{@tm_connection}\t#{@tm_terminal}\t#{pid}\t#{pane_dead_status}\t#{@tm_sign_in}" + + args := []string{"-u", "list-panes", "-F", format} + if target == "" { + args = append(args, "-a") + } else { + args = append(args, "-t", literalArg(target)) + } + + out, err := run(ctx, args...) + if err != nil { + if target == "" && (noServer(out) || out == "no current target") { + return map[string]Attachment{}, nil + } + + return nil, fmt.Errorf("list pane attachments: %w", err) + } + + panes := make(map[string]Attachment) + + for line := range strings.Lines(out) { + fields := strings.Split(strings.TrimSuffix(line, "\n"), "\t") + if len(fields) != 9 { + return nil, fmt.Errorf("%w: invalid pane record", os.ErrInvalid) + } + + p := Attachment{ + ID: fields[0], WindowID: fields[1], Dead: fields[2] == "1", Host: fields[3], + Connection: fields[4], Terminal: fields[5], server: fields[6], ExitStatus: fields[7], + NeedsSignIn: fields[8] == "1", + } + panes[p.ID] = p + } + + return panes, nil +} + +// Notify displays a literal message on a local client. +func Notify(ctx context.Context, message string) error { + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + + _, err := run(ctx, "display-message", "-d", "5000", "-l", literalArg(message)) + + return err +} + +// Record pins a terminal to this pane, even across moves and respawns. +func (p Attachment) Record(ctx context.Context, project, reconnect string) error { + const message = "#{?#{==:#{pane_dead_status},255},SSH disconnected · rerun tm for #{@tm_host} if recovery stalls,Remote terminal exited or unavailable}" + + args := []string{ + "set-option", "-pu", "-t", p.ID, "@tm_sign_in", ";", + "set-option", "-p", "-t", p.ID, "remain-on-exit", "failed", ";", + "set-option", "-p", "-t", p.ID, "remain-on-exit-format", message, + } + + if project != "" { + retry := commandLine("run-shell", "-b", literalFormat(reconnect)) + hook := commandLine("if-shell", "-F", "#{==:#{pane_dead_status},255}", retry) + + args = append(args, ";", "set-option", "-p", "-t", p.ID, "@tm_host", literalArg(p.Host), ";", + "set-option", "-p", "-t", p.ID, "@tm_connection", literalArg(p.Connection), ";", + "set-option", "-p", "-t", p.ID, "@tm_project", literalArg(project), ";", + "set-option", "-p", "-t", p.ID, "@tm_terminal", literalArg(p.Terminal), ";", + "set-hook", "-p", "-t", p.ID, "pane-died", hook) + } + + _, err := run(ctx, args...) + + return err +} + +// RequireSignIn leaves a notice in the status line until the next attachment. +func (p Attachment) RequireSignIn(ctx context.Context) error { + return p.change(ctx, "set-option -p -t "+p.ID+" @tm_sign_in 1") +} + +// CloseOnExit discards a rejected split even if tmux normally retains exits. +func (p Attachment) CloseOnExit(ctx context.Context) error { + return p.change(ctx, "set-option -p -t "+p.ID+" remain-on-exit off") +} + +// Resume replaces a dead client and its input queue. A live pane is left alone. +func (p Attachment) Resume(ctx context.Context, command ...string) error { + return p.change(ctx, "respawn-pane -t "+p.ID+" "+commandLine(command...)) +} + +// KillPane removes this pane from its local window. +func (p Attachment) KillPane(ctx context.Context) error { + return p.change(ctx, "kill-pane -t "+p.ID) +} + +// A window can change or the server can restart while a close is in flight. +func (p Attachment) change(ctx context.Context, command string) error { + same := "#{==:#{pid}/#{window_id}/#{@tm_terminal}," + p.server + "/" + p.WindowID + "/" + p.Terminal + "}" + + out, err := run(ctx, "if-shell", "-F", "-t", p.ID, same, command, "display-message -p changed") + if err != nil { + return err + } + + if out != "" { + return fmt.Errorf("%w: pane %s changed", os.ErrInvalid, p.ID) + } + + return nil +} diff --git a/tools/internal/tmux/sessions.go b/tools/internal/tmux/sessions.go index 3b4f16f1..6c98e7c5 100644 --- a/tools/internal/tmux/sessions.go +++ b/tools/internal/tmux/sessions.go @@ -22,6 +22,7 @@ type Session struct { Name string `json:"name,omitempty"` Path string `json:"path,omitempty"` Workspace string `json:"-"` + Remote string `json:"-"` } // ListSessions returns sessions sorted by name, or none when no server is running. @@ -29,9 +30,9 @@ func ListSessions(ctx context.Context) ([]Session, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() - output, err := run(ctx, "list-sessions", "-F", "#{session_id}\t#{"+WorkspaceOption+"}\t#{session_name}\t#{session_path}") + output, err := run(ctx, "-u", "list-sessions", "-F", "#{session_id}\t#{"+RemoteEnv+"}\t#{"+WorkspaceOption+"}\t#{session_name}\t#{session_path}") if err != nil { - if errors.Is(err, exec.ErrNotFound) || strings.Contains(output, "no server running") || strings.Contains(output, "No such file or directory") { + if errors.Is(err, exec.ErrNotFound) || noServer(output) { return nil, nil } @@ -41,17 +42,17 @@ func ListSessions(ctx context.Context) ([]Session, error) { var sessions []Session for line := range strings.SplitSeq(strings.TrimSuffix(output, "\n"), "\n") { - fields := strings.SplitN(line, "\t", 4) - if len(fields) != 4 { + fields := strings.SplitN(line, "\t", 5) + if len(fields) != 5 { continue } - path := fields[3] + path := fields[4] if resolved, err := filepath.EvalSymlinks(path); err == nil { path = resolved } - sessions = append(sessions, Session{ID: fields[0], Workspace: fields[1], Name: fields[2], Path: filepath.Clean(path)}) + sessions = append(sessions, Session{ID: fields[0], Remote: fields[1], Workspace: fields[2], Name: fields[3], Path: filepath.Clean(path)}) } slices.SortFunc(sessions, func(a, b Session) int { return cmp.Compare(a.Name, b.Name) }) @@ -59,12 +60,27 @@ func ListSessions(ctx context.Context) ([]Session, error) { return sessions, nil } +func noServer(output string) bool { + return strings.HasPrefix(output, "no server running on ") || + (strings.HasPrefix(output, "error connecting to ") && strings.HasSuffix(output, "(No such file or directory)")) +} + +// AvailableName adds a numeric suffix if a session already uses name. +func AvailableName(sessions []Session, name string) string { + display := name + for suffix := 2; slices.ContainsFunc(sessions, func(s Session) bool { return s.Name == display }); suffix++ { + display = fmt.Sprintf("%s-%d", name, suffix) + } + + return display +} + // NewSession creates a detached session with one window and returns its ID. // The initial program waits until a client attaches. func NewSession(ctx context.Context, name, window, path string) (string, error) { - args := append([]string{"new-session", "-d", "-P", "-F", "#{session_id}", "-s", name, "-n", window, "-c", path}, attachedCommand()...) + args := []string{"new-session", "-d", "-P", "-F", "#{session_id}", "-s", literalFormat(name), "-n", literalFormat(window), "-c", literalFormat(path)} - output, err := run(ctx, args...) + output, err := run(ctx, appendCommand(args, attachedCommand())...) if err != nil { return "", err } @@ -74,15 +90,24 @@ func NewSession(ctx context.Context, name, window, path string) (string, error) // SetOption sets an option on a session. func SetOption(ctx context.Context, session, option, value string) error { - _, err := run(ctx, "set-option", "-t", session, option, value) + _, err := run(ctx, "set-option", "-t", session, option, literalArg(value)) return err } // NewWindow creates a window without selecting it. The command waits until the // session has an attached client. Multiple command arguments bypass shell parsing. func NewWindow(ctx context.Context, session, name, path string, command ...string) error { - args := append([]string{"new-window", "-d", "-t", session + ":", "-n", name, "-c", path}, attachedCommand(command...)...) - _, err := run(ctx, args...) + return StartWindow(ctx, session, name, path, attachedCommand(command...)...) +} + +// StartWindow runs the command immediately, even in a detached session. +func StartWindow(ctx context.Context, session, name, path string, command ...string) error { + args := []string{"new-window", "-d", "-t", session + ":", "-n", literalFormat(name)} + if path != "" { + args = append(args, "-c", literalFormat(path)) + } + + _, err := run(ctx, appendCommand(args, command)...) return err } diff --git a/tools/internal/worktree/manage.go b/tools/internal/worktree/manage.go index b9d7c5cf..d4967a17 100644 --- a/tools/internal/worktree/manage.go +++ b/tools/internal/worktree/manage.go @@ -224,7 +224,7 @@ func PlanRemovalWithBranchOptions(ctx context.Context, item Info, keepBranch, fo } for _, session := range sessions { - if session.Path == item.Path { + if session.Remote == "" && session.Path == item.Path { plan.Sessions = append(plan.Sessions, session) } } diff --git a/tools/internal/worktree/manage_test.go b/tools/internal/worktree/manage_test.go index a3feae2f..29a478d6 100644 --- a/tools/internal/worktree/manage_test.go +++ b/tools/internal/worktree/manage_test.go @@ -150,13 +150,18 @@ func removalFixture(t *testing.T, detached bool) (string, string) { } // Only session discovery is expected; never operate on the user's tmux server. - if err := os.WriteFile(filepath.Join(bin, "tmux"), []byte("#!/bin/sh\n[ \"$1\" = list-sessions ] || exit 99\n"), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private temporary directory. + const tmuxFixture = `#!/bin/sh +[ "$1" = -u ] && [ "$2" = list-sessions ] || exit 99 +printf '$1\tremote\t\tdevbox\t%s\n' "$FIXTURE_CHECKOUT" +` + if err := os.WriteFile(filepath.Join(bin, "tmux"), []byte(tmuxFixture), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private temporary directory. t.Fatal(err) } t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) main, path := filepath.Join(root, "main"), filepath.Join(root, "checkout") + t.Setenv("FIXTURE_CHECKOUT", path) fixtureGit(t, root, "init", "--template=", "--initial-branch=main", main) fixtureGit(t, main, "commit", "--allow-empty", "-m", "Initial commit") diff --git a/tools/internal/worktree/sessions.go b/tools/internal/worktree/sessions.go index 94346f70..2fc5c870 100644 --- a/tools/internal/worktree/sessions.go +++ b/tools/internal/worktree/sessions.go @@ -3,7 +3,6 @@ package worktree import ( "context" "fmt" - "slices" "strings" "time" @@ -26,7 +25,7 @@ func MatchSession(item Info, sessions []tmux.Session) tmux.Session { var match tmux.Session for _, candidate := range sessions { - if candidate.Path == item.Path { + if candidate.Remote == "" && candidate.Path == item.Path { if match.ID == "" || candidate.Name == sessionName(item) { match = candidate } @@ -58,10 +57,7 @@ func ensureSession(ctx context.Context, item Info, options sessionOptions) (stri return existing.ID, nil } - name := sessionName(item) - for suffix := 2; slices.ContainsFunc(sessions, func(s tmux.Session) bool { return s.Name == name }); suffix++ { - name = fmt.Sprintf("%s-%d", sessionName(item), suffix) - } + name := tmux.AvailableName(sessions, sessionName(item)) command := []string{"codex"}