From faf4964ce069145ff081ef6d3b9a19988705cd7b Mon Sep 17 00:00:00 2001 From: Damien Deville Date: Sun, 22 Nov 2026 21:46:37 -0800 Subject: [PATCH 1/6] Support remote tmux sessions in local tmux server --- config/common/.config/tmux/tmux.conf | 12 +- tools/cmd/tmux-session/REMOTE-WORKSPACES.md | 30 +++ tools/cmd/tmux-session/main.go | 96 +++++--- tools/cmd/tmux-session/pane.go | 179 ++++++++++++++ tools/cmd/tmux-session/remote.go | 260 ++++++++++++++++++++ tools/cmd/tmux-session/remote_test.go | 47 ++++ tools/cmd/tmux-session/ssh.go | 122 +++++++++ tools/internal/tmux/command.go | 22 ++ tools/internal/tmux/remote.go | 114 +++++++++ tools/internal/tmux/sessions.go | 40 ++- tools/internal/worktree/manage.go | 2 +- tools/internal/worktree/manage_test.go | 7 +- tools/internal/worktree/sessions.go | 8 +- 13 files changed, 887 insertions(+), 52 deletions(-) create mode 100644 tools/cmd/tmux-session/REMOTE-WORKSPACES.md create mode 100644 tools/cmd/tmux-session/pane.go create mode 100644 tools/cmd/tmux-session/remote.go create mode 100644 tools/cmd/tmux-session/remote_test.go create mode 100644 tools/cmd/tmux-session/ssh.go create mode 100644 tools/internal/tmux/remote.go diff --git a/config/common/.config/tmux/tmux.conf b/config/common/.config/tmux/tmux.conf index 35ca102f..3885160d 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_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..e3964504 --- /dev/null +++ b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md @@ -0,0 +1,30 @@ +# 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. Sessions using the same SSH destination share one OpenSSH +connection. Each pane uses one of the server's `MaxSessions` slots. Discovery +needs a free slot too. + +- **Reconnect** by rerunning `tm` from a local shell. This reconnects failed panes + across projects on that destination, including moved panes. Input typed into a + dead pane is discarded. Programs that ended while disconnected stay closed. +- **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. + +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 local agent +dashboard doesn't list remote agents yet. diff --git a/tools/cmd/tmux-session/main.go b/tools/cmd/tmux-session/main.go index 9c92a6ce..663d796f 100644 --- a/tools/cmd/tmux-session/main.go +++ b/tools/cmd/tmux-session/main.go @@ -1,4 +1,4 @@ -// Command tmux-session opens a local project in tmux. +// Command tmux-session opens a local or remote project in tmux. package main import ( @@ -6,7 +6,6 @@ import ( "fmt" "os" "path/filepath" - "slices" "syscall" "github.com/spf13/cobra" @@ -23,19 +22,28 @@ func main() { func command() *cobra.Command { var ( - name string - noSwitch bool + name, host string + launch, 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 launch != "" { + return attachPane(cmd.Context(), launch) + } + + if closeTarget != "" { + return closePanes(cmd.Context(), closeTarget) + } + if err := cmd.Help(); err != nil { return fmt.Errorf("show help: %w", err) } @@ -43,22 +51,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 +76,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 +86,13 @@ 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(&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 } @@ -107,19 +120,32 @@ func resolveDirectory(path string) (string, error) { return directory, nil } -// lockOpen serializes lookup and layout creation, including the first tmux server startup. -func lockOpen() (*os.File, error) { +func cacheDir() (string, error) { cache, err := os.UserCacheDir() if err != nil { - return nil, fmt.Errorf("locate cache directory: %w", err) + return "", fmt.Errorf("locate cache directory: %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) + dir := filepath.Join(cache, "tmux-session") + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", fmt.Errorf("create session cache: %w", err) } - 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. + return dir, nil +} + +// lockOpen serializes lookup and layout creation, including the first tmux server startup. +func lockOpen() (*os.File, error) { + dir, err := cacheDir() + if err != nil { + return nil, err + } + + return lockFile(filepath.Join(dir, "open.lock")) +} + +func lockFile(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) } @@ -132,7 +158,16 @@ func lockOpen() (*os.File, error) { return lock, nil } -func openSession(ctx context.Context, directory, name string) (tmux.Session, bool, error) { +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() if err != nil { return tmux.Session{}, false, err @@ -146,13 +181,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 +196,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..6d02cedf --- /dev/null +++ b/tools/cmd/tmux-session/pane.go @@ -0,0 +1,179 @@ +package main + +import ( + "context" + "crypto/rand" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path" + "slices" + "strconv" + "strings" + "syscall" + + "github.com/ddeville/scripts/tools/internal/tmux" +) + +const attach = `export ZMX_NO_DETACH_KEY=1 +if [ "$1" = resume ]; then + zmx get "$2" >/dev/null + # If it exits between get and attach, zmx must never relaunch its program. + exec zmx attach "$2" /bin/sh -c 'exit 1' +fi +cd -P -- "$3" +case "$1" in +editor) exec zmx attach "$2" sh -c "exec ${EDITOR:-nvim}" ;; +codex) exec zmx attach "$2" codex ;; +*) exec zmx attach "$2" ;; +esac` + +func attachPane(ctx context.Context, requested string) error { + id := os.Getenv("TMUX_PANE") + + panes, err := tmux.Attachments(ctx, id) + if err != nil { + return fmt.Errorf("find attachment: %w", err) + } + + p, ok := panes[id] + if !ok { + return 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 fmt.Errorf("read remote workspace: %w", err) + } + + p.Host, p.Terminal, dir = w.Host, 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 fmt.Errorf("%w: terminal belongs to another workspace", os.ErrInvalid) + } + } + + if !terminalID.MatchString(p.Terminal) { + return fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) + } + + dest, err := sshDestination(p.Host) + if err != nil { + return err + } + + if dir != "" { + // Record the target before launching. Even a manual respawn after + // an ambiguous SSH failure can now only reattach to this terminal. + if err := p.Record(ctx, displayName(path.Base(dir))); err != nil { + return fmt.Errorf("record remote pane: %w", err) + } + } + + ssh, err := exec.LookPath("ssh") + if err != nil { + return fmt.Errorf("find ssh: %w", err) + } + + args := dest.channel("-tt", remoteCommand(attach, mode, p.Terminal, dir)) + + return fmt.Errorf("start ssh: %w", syscall.Exec(ssh, append([]string{ssh}, args...), os.Environ())) // #nosec G204 -- Replace only with ssh and quote remote arguments. +} + +// 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) + } + + dest, err := sshDestination(p.Host) + if err != nil { + return err + } + + command := remoteCommand(stop, p.Terminal, strconv.FormatBool(p.Dead)) + + out, err := dest.query(ctx, command) + if errors.Is(err, errChannelRefused) && !p.Dead { + // At MaxSessions, free this attachment's slot for the close command. + if err := p.Disconnect(ctx); err != nil { + return fmt.Errorf("disconnect pane: %w", err) + } + + p.Dead = true + out, err = dest.query(ctx, command) + } + + if err != nil { + return 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 live, dead, local []tmux.Attachment + + for _, p := range panes { + if p.ID != target && p.WindowID != target { + continue + } + + switch { + case p.Terminal == "": + local = append(local, p) + case p.Dead: + dead = append(dead, p) + default: + live = append(live, p) + } + } + + if len(live)+len(dead) == 0 { + return fmt.Errorf("%w: no remote terminal at %s", os.ErrInvalid, target) + } + + // Live clients exit with zmx and can free channels for the remaining closes. + for _, p := range append(live, dead...) { + if err := stopTerminal(ctx, &p); err != nil { + return fmt.Errorf("could not confirm remote close for %s: %w", p.ID, err) + } + + if p.Dead { + local = append(local, p) + } + } + + 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/remote.go b/tools/cmd/tmux-session/remote.go new file mode 100644 index 00000000..2674a9cd --- /dev/null +++ b/tools/cmd/tmux-session/remote.go @@ -0,0 +1,260 @@ +package main + +import ( + "cmp" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "os" + "path" + "regexp" + "slices" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/ddeville/scripts/tools/internal/tmux" +) + +type workspace struct { + Host string `json:"host"` + Path string `json:"path"` + Name string `json:"name"` +} + +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 +} + +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 +} + +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 + +func openRemote(ctx context.Context, host, request, name string) (tmux.Session, bool, error) { + if request == "" { + return tmux.Session{}, false, fmt.Errorf("%w: empty remote path", os.ErrInvalid) + } + + dest, err := sshDestination(host) + if err != nil { + return tmux.Session{}, false, err + } + + lock, err := lockFile(dest.socket + ".lock") + if err != nil { + return tmux.Session{}, false, err + } + defer func() { _ = lock.Close() }() + + if err := dest.connect(ctx); err != nil { + return tmux.Session{}, false, err + } + + if request == "~" { + request = "." + } + + if !path.IsAbs(request) { + request = "./" + strings.TrimPrefix(request, "~/") + } + + out, err := dest.query(ctx, remoteCommand(inspect, request)) + if err != nil { + return tmux.Session{}, false, err + } + + dir, list, ok := strings.Cut(out, "\x00") + if !ok || !path.IsAbs(dir) || !utf8.ValidString(dir) { + return tmux.Session{}, false, fmt.Errorf("%w: invalid remote directory", os.ErrInvalid) + } + + names, err := inventory(list) + if err != nil { + return tmux.Session{}, false, err + } + + w := workspace{Host: host, Path: dir, Name: cmp.Or(name, path.Base(dir))} + + return w.open(ctx, names) +} + +// 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) open(ctx context.Context, names map[string]bool) (tmux.Session, bool, error) { + helper, err := os.Executable() + if err != nil { + return tmux.Session{}, false, fmt.Errorf("locate tmux-session: %w", err) + } + + meta, err := json.Marshal(w) + if err != nil { + return tmux.Session{}, false, fmt.Errorf("encode workspace: %w", err) + } + + // SSH authentication and discovery must never hold the local project lock. + lock, err := lockOpen() + if err != nil { + return tmux.Session{}, false, err + } + defer func() { _ = lock.Close() }() + + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + sessions, err := tmux.ListSessions(ctx) + if err != nil { + return tmux.Session{}, false, fmt.Errorf("list sessions: %w", err) + } + + var target tmux.Session + + for _, s := range sessions { + if s.Remote == string(meta) { + target = s + break + } + } + + var panes map[string]tmux.Attachment + if len(sessions) != 0 { + panes, err = tmux.Attachments(ctx, "") + if err != nil { + return tmux.Session{}, false, fmt.Errorf("find existing remote panes: %w", err) + } + } + + created := target.ID == "" + + windows, err := w.windows(names, panes, created) + if err != nil { + return tmux.Session{}, false, err + } + + // All workspaces on the destination lost the same connection. + for _, p := range panes { + if p.Host != w.Host || !p.Dead { + continue + } + + if err := p.Resume(ctx, helper, "--remote-pane", p.Terminal); err != nil { + return tmux.Session{}, false, fmt.Errorf("resume pane %s: %w", p.ID, err) + } + } + + if created { + target.Name = tmux.AvailableName(sessions, displayName(w.Host+"/"+w.Name)) + target.Remote = string(meta) + first := windows[0] + windows = windows[1:] + + target.ID, err = tmux.NewRemoteSession(ctx, target, first.role, "exec "+quote(helper)+" --remote-pane shell", + helper, "--remote-pane", cmp.Or(first.terminal, first.role)) + if err != nil { + return tmux.Session{}, false, fmt.Errorf("create remote session: %w", err) + } + } + + for _, win := range windows { + err := tmux.StartWindow(ctx, target.ID, win.role, "", helper, "--remote-pane", cmp.Or(win.terminal, win.role)) + if err != nil { + return tmux.Session{}, false, fmt.Errorf("create remote window: %w", err) + } + } + + target.Path = w.Path + + return target, created, 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..9211877a --- /dev/null +++ b/tools/cmd/tmux-session/remote_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "slices" + "testing" + + "github.com/ddeville/scripts/tools/internal/tmux" +) + +func TestRestoreOnlyUnattachedSurvivors(t *testing.T) { + t.Parallel() + + w := workspace{Host: "devbox", Path: "/work/api", Name: "api"} + 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}} + + 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 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) + } + } +} diff --git a/tools/cmd/tmux-session/ssh.go b/tools/cmd/tmux-session/ssh.go new file mode 100644 index 00000000..9dfbaa4c --- /dev/null +++ b/tools/cmd/tmux-session/ssh.go @@ -0,0 +1,122 @@ +package main + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "syscall" + "time" +) + +type destination struct { + host, socket string +} + +var ( + sshHost = regexp.MustCompile(`^[a-zA-Z0-9_@.%+:/\[\]-]+$`) + errChannelRefused = errors.New("SSH session channel refused (check sshd MaxSessions)") +) + +func sshDestination(host string) (destination, error) { + if !sshHost.MatchString(host) || strings.HasPrefix(host, "-") { + return destination{}, fmt.Errorf("%w: invalid SSH destination %q", os.ErrInvalid, host) + } + + dir, err := cacheDir() + if err != nil { + return destination{}, err + } + + info, err := os.Lstat(dir) + if err != nil { + return destination{}, 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 destination{}, fmt.Errorf("%w: SSH socket directory %s must be private", os.ErrPermission, dir) + } + + sum := sha256.Sum256([]byte(host)) + + return destination{host: host, socket: filepath.Join(dir, fmt.Sprintf("ssh-%x", sum[:10]))}, nil +} + +// Only tm opens a connection. OpenSSH retires the master after a minute with no open channels. +func (d destination) connect(ctx context.Context) error { + if exec.CommandContext(ctx, "ssh", "-S", d.socket, "-O", "check", "--", d.host).Run() == nil { // #nosec G204 -- The validated destination follows --. + return nil + } + + cmd := exec.CommandContext(ctx, "ssh", "-S", d.socket, "-fN", "-oControlMaster=auto", "-oControlPersist=60", // #nosec G204 -- The validated destination follows --. + "-oRemoteCommand=none", "-oConnectTimeout=10", "-oServerAliveInterval=5", "-oServerAliveCountMax=2", "--", d.host) + cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr + + if err := cmd.Run(); err != nil { + return fmt.Errorf("connect to %s: %w", d.host, err) + } + + return nil +} + +// ControlMaster=no alone allows a direct connection if the socket is gone or the master refuses a channel. +func (d destination) channel(tty, command string) []string { + return []string{ + "-S", d.socket, "-oControlMaster=no", "-oProxyCommand=false", "-oBatchMode=yes", + "-oClearAllForwardings=yes", "-oRemoteCommand=none", "-oLogLevel=ERROR", "-e", "none", tty, "--", d.host, command, + } +} + +func (d destination) 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 { + var exit *exec.ExitError + if errors.As(err, &exit) && len(exit.Stderr) != 0 { + if exit.ExitCode() == 255 && strings.Contains(string(exit.Stderr), "Session open refused") { + return "", fmt.Errorf("%w on %s", errChannelRefused, d.host) + } + + return "", fmt.Errorf("SSH %s: %w: %s", d.host, err, strings.TrimSpace(string(exit.Stderr))) + } + + return "", fmt.Errorf("SSH %s: %w", d.host, err) + } + + return string(out), 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() +} diff --git a/tools/internal/tmux/command.go b/tools/internal/tmux/command.go index 3231ac27..2829ded6 100644 --- a/tools/internal/tmux/command.go +++ b/tools/internal/tmux/command.go @@ -32,6 +32,28 @@ 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 +} + 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..9c7b2c18 --- /dev/null +++ b/tools/internal/tmux/remote.go @@ -0,0 +1,114 @@ +package tmux + +import ( + "context" + "fmt" + "os" + "strings" +) + +// 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, Terminal string + Dead bool + 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_terminal}\t#{pid}" + + args := []string{"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 { + 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) != 6 { + 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], Terminal: fields[4], server: fields[5]} + panes[p.ID] = p + } + + return panes, nil +} + +// Record pins a terminal to this pane, even across moves and respawns. +func (p Attachment) Record(ctx context.Context, project string) error { + const message = "#{?#{==:#{pane_dead_status},255},SSH disconnected · rerun tm for #{@tm_host},Remote terminal exited or unavailable}" + + _, err := run(ctx, "set-option", "-p", "-t", p.ID, "@tm_host", literalArg(p.Host), ";", + "set-option", "-p", "-t", p.ID, "@tm_project", literalArg(project), ";", + "set-option", "-p", "-t", p.ID, "@tm_terminal", literalArg(p.Terminal), ";", + "set-option", "-p", "-t", p.ID, "remain-on-exit", "failed", ";", + "set-option", "-p", "-t", p.ID, "remain-on-exit-format", message) + + return err +} + +// 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 { + _, err := run(ctx, appendCommand([]string{"respawn-pane", "-t", p.ID}, command)...) + return err +} + +// Disconnect stops just the local client and keeps the failed pane for retry. +func (p Attachment) Disconnect(ctx context.Context) error { + return p.change(ctx, "respawn-pane -k -t "+p.ID+" /bin/sh -c 'exit 255'") +} + +// 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 during close", os.ErrInvalid, p.ID) + } + + return nil +} diff --git a/tools/internal/tmux/sessions.go b/tools/internal/tmux/sessions.go index 3b4f16f1..68eb090a 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,7 +30,7 @@ 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") { 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,22 @@ func ListSessions(ctx context.Context) ([]Session, error) { return sessions, nil } +// 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 +85,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"} From 961a2ff29384edee0499ddda22aa8fca7a0c7f31 Mon Sep 17 00:00:00 2001 From: Damien Deville Date: Sun, 22 Nov 2026 23:05:18 -0800 Subject: [PATCH 2/6] Big improvements --- config/common/.config/tmux/tmux.conf | 2 +- tools/cmd/tmux-agent-status/agents/panes.go | 100 ++++++--- .../tmux-agent-status/agents/panes_test.go | 29 ++- tools/cmd/tmux-agent-status/agents/source.go | 58 +++++ tools/cmd/tmux-agent-status/agents/status.go | 127 ++++++----- tools/cmd/tmux-agent-status/open.go | 9 +- tools/cmd/tmux-agent-status/output.go | 7 +- .../cmd/tmux-agent-status/ui/agents/model.go | 112 +++++----- .../tmux-agent-status/ui/agents/sources.go | 131 +++++++++++ .../ui/agents/sources_test.go | 35 +++ tools/cmd/tmux-agent-status/ui/agents/view.go | 89 +++++--- tools/cmd/tmux-agent-status/ui/model.go | 108 ++++----- tools/cmd/tmux-session/REMOTE-WORKSPACES.md | 29 ++- tools/cmd/tmux-session/main.go | 27 +-- tools/cmd/tmux-session/pane.go | 33 +-- tools/cmd/tmux-session/remote.go | 48 +++- tools/cmd/tmux-session/remote_test.go | 23 ++ tools/cmd/tmux-session/ssh.go | 122 ---------- tools/cmd/tmux-session/supervisor.go | 210 ++++++++++++++++++ tools/internal/codex/client.go | 68 +++++- tools/internal/sshmux/ssh.go | 160 +++++++++++++ tools/internal/tmux/command.go | 10 + tools/internal/tmux/panes.go | 70 +++++- tools/internal/tmux/remote.go | 69 ++++-- 24 files changed, 1254 insertions(+), 422 deletions(-) create mode 100644 tools/cmd/tmux-agent-status/agents/source.go create mode 100644 tools/cmd/tmux-agent-status/ui/agents/sources.go create mode 100644 tools/cmd/tmux-agent-status/ui/agents/sources_test.go delete mode 100644 tools/cmd/tmux-session/ssh.go create mode 100644 tools/cmd/tmux-session/supervisor.go create mode 100644 tools/internal/sshmux/ssh.go diff --git a/config/common/.config/tmux/tmux.conf b/config/common/.config/tmux/tmux.conf index 3885160d..6a1844d2 100644 --- a/config/common/.config/tmux/tmux.conf +++ b/config/common/.config/tmux/tmux.conf @@ -145,7 +145,7 @@ 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] #{?@tm_host,#{@tm_project},#{b:pane_current_path}} \ +#[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 ' diff --git a/tools/cmd/tmux-agent-status/agents/panes.go b/tools/cmd/tmux-agent-status/agents/panes.go index 1446d1c9..abf8d609 100644 --- a/tools/cmd/tmux-agent-status/agents/panes.go +++ b/tools/cmd/tmux-agent-status/agents/panes.go @@ -7,6 +7,7 @@ import ( "regexp" "strings" + "github.com/ddeville/scripts/tools/internal/codex" "github.com/ddeville/scripts/tools/internal/tmux" ) @@ -15,48 +16,97 @@ var titleID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{ // ErrPaneMatch means a conversation could not be resolved to exactly one live pane. var ErrPaneMatch = errors.New("thread must be open in exactly one tmux pane") -// MatchPanes checks all loaded IDs so truncated titles cannot resolve ambiguously. -func MatchPanes(ctx context.Context, ids []string) (map[string][]string, error) { - panes, err := tmux.ListPanes(ctx) +var errPaneChanged = errors.New("this pane no longer displays the selected thread") + +// Open rechecks both the thread and the attachment. A pane ID survives moves, +// but a different process or a new conversation must never inherit a selection. +func (s *Source) Open(ctx context.Context, id string, target tmux.Pane, client string) error { + var ids []string + + err := s.use(ctx, func(server *codex.Client) error { + var err error + + ids, err = server.LoadedIDs(ctx) + if err != nil { + return fmt.Errorf("list threads: %w", err) + } + + return nil + }) if err != nil { - return nil, fmt.Errorf("match agent panes: %w", err) + return fmt.Errorf("refresh loaded threads: %w", err) + } + + if id == "" || s.Host != target.Host || !candidate(target) || displayedThread(target.Title, ids) != id { + return errPaneChanged } - return matchPanes(ids, panes), nil + if err := target.Switch(ctx, client, titleSuffix(target.Title)); err != nil { + return fmt.Errorf("open selected pane: %w", err) + } + + return nil } -func matchPanes(ids []string, panes []tmux.Pane) map[string][]string { - matches := map[string][]string{} +func matchPanes(host string, ids []string, panes []tmux.Pane) map[string][]tmux.Pane { + matches := map[string][]tmux.Pane{} - for _, pane := range panes { - if pane.Command != "codex" { + for _, p := range panes { + if p.Host != host || !candidate(p) { continue } - title := pane.Title - if i := strings.LastIndex(title, " | "); i >= 0 { - title = title[i+3:] + if id := displayedThread(p.Title, ids); id != "" { + matches[id] = append(matches[id], p) } + } - if !titleID.MatchString(title) { - continue - } + return matches +} - prefix := strings.TrimSuffix(title, "...") +func candidate(p tmux.Pane) bool { + if p.Dead { + return false + } - var candidates []string + if p.Host == "" { + return p.Command == "codex" + } + + return p.Terminal != "" && p.Command == "ssh" && titleID.MatchString(titleSuffix(p.Title)) +} + +func titleSuffix(title string) string { + if _, after, ok := strings.CutLast(title, " | "); ok { + return after + } + + return title +} - for _, id := range ids { - if strings.HasPrefix(id, prefix) { - candidates = append(candidates, id) - } +// Codex shortens the thread ID in the terminal title. Resolve against all +// loaded IDs on this host, never by directory or by the pane's initial role. +func displayedThread(title string, ids []string) string { + title = titleSuffix(title) + if !titleID.MatchString(title) { + return "" + } + + prefix := strings.TrimSuffix(title, "...") + + var match string + + for _, id := range ids { + if len(id) != 36 || !strings.HasPrefix(id, prefix) { + continue } - if len(candidates) == 1 { - id := candidates[0] - matches[id] = append(matches[id], pane.ID) + if match != "" { + return "" } + + match = id } - return matches + return match } diff --git a/tools/cmd/tmux-agent-status/agents/panes_test.go b/tools/cmd/tmux-agent-status/agents/panes_test.go index ae910802..e8aa73e8 100644 --- a/tools/cmd/tmux-agent-status/agents/panes_test.go +++ b/tools/cmd/tmux-agent-status/agents/panes_test.go @@ -24,8 +24,33 @@ func TestMatchPanesDoesNotGuess(t *testing.T) { {ID: "%6", Command: "codex", Title: unique[:8]}, } - want := map[string][]string{first: {"%1", "%2"}, unique: {"%4"}} - if got := matchPanes(ids, panes); !reflect.DeepEqual(got, want) { + want := map[string][]tmux.Pane{first: {panes[0], panes[1]}, unique: {panes[3]}} + if got := matchPanes("", ids, panes); !reflect.DeepEqual(got, want) { t.Fatalf("pane matches = %v, want %v; ambiguous titles must be ignored and duplicate panes preserved", got, want) } } + +func TestRemoteMatchesStayOnOneHost(t *testing.T) { + t.Parallel() + + const ( + id = "12345678-1234-1234-1234-123450000000" + title = "same project | 12345678-1234-1234-1234-12345..." + ) + + panes := []tmux.Pane{ + {ID: "%1", Command: "codex", Title: title}, + {ID: "%2", Host: "other", Terminal: "shell", Command: "ssh", Title: title}, + {ID: "%3", Host: "dev", Terminal: "shell", Command: "ssh", Title: title}, + {ID: "%4", Host: "dev", Terminal: "codex", Command: "ssh", Title: title, Dead: true}, + {ID: "%5", Host: "dev", Terminal: "shell", Command: "fish", Title: title}, + {ID: "%6", Host: "dev", Command: "ssh", Title: title}, + } + + for host, target := range map[string]tmux.Pane{"": panes[0], "other": panes[1], "dev": panes[2]} { + got := matchPanes(host, []string{id}, panes) + if !reflect.DeepEqual(got[id], []tmux.Pane{target}) { + t.Errorf("matches on %q = %v, want only %s", host, got, target.ID) + } + } +} diff --git a/tools/cmd/tmux-agent-status/agents/source.go b/tools/cmd/tmux-agent-status/agents/source.go new file mode 100644 index 00000000..022f30bd --- /dev/null +++ b/tools/cmd/tmux-agent-status/agents/source.go @@ -0,0 +1,58 @@ +package agents + +import ( + "context" + "errors" + "fmt" + "sync" + + "github.com/ddeville/scripts/tools/internal/codex" +) + +// Source shares one sequential app-server connection across status, activity, +// and navigation for a destination. Its zero value targets the local daemon. +type Source struct { + Host string + + mu sync.Mutex + client *codex.Client +} + +func (s *Source) use(ctx context.Context, read func(*codex.Client) error) error { + s.mu.Lock() + defer s.mu.Unlock() + + if err := ctx.Err(); err != nil { + return fmt.Errorf("read Codex: %w", err) + } + + if s.client == nil { + client, err := codex.Connect(ctx, s.Host) + if err != nil { + return fmt.Errorf("connect to app server: %w", err) + } + + s.client = client + } + + err := read(s.client) + + var rpcErr *codex.RPCError + if err != nil && !errors.As(err, &rpcErr) { + s.client.Close() + s.client = nil + } + + return err +} + +// Close releases the app-server connection and its SSH channel, if any. +func (s *Source) Close() { + s.mu.Lock() + defer s.mu.Unlock() + + if s.client != nil { + s.client.Close() + s.client = nil + } +} diff --git a/tools/cmd/tmux-agent-status/agents/status.go b/tools/cmd/tmux-agent-status/agents/status.go index 9e2133d0..3102182b 100644 --- a/tools/cmd/tmux-agent-status/agents/status.go +++ b/tools/cmd/tmux-agent-status/agents/status.go @@ -32,22 +32,22 @@ const ( // Agent describes a running conversation and its current status. type Agent struct { - ID string `json:"id"` - Type Type `json:"agent_type"` - Title string `json:"title"` - Cwd string `json:"cwd"` - Project string `json:"project"` - State string `json:"status"` - NeedsAttention bool `json:"needs_attention"` - Unread *bool `json:"unread"` - ActiveFlags []string `json:"active_flags"` - ParentID *string `json:"parent_id"` - Model *string `json:"model"` - UpdatedAt *int64 `json:"updated_at"` - Error *string `json:"error"` - Panes []string `json:"tmux_panes,omitempty"` - SessionNumber int `json:"-"` - Preview string `json:"preview"` + ID string `json:"id"` + Type Type `json:"agent_type"` + Title string `json:"title"` + Cwd string `json:"cwd"` + Project string `json:"project"` + State string `json:"status"` + NeedsAttention bool `json:"needs_attention"` + Unread *bool `json:"unread"` + ActiveFlags []string `json:"active_flags"` + ParentID *string `json:"parent_id"` + Model *string `json:"model"` + UpdatedAt *int64 `json:"updated_at"` + Error *string `json:"error"` + Panes []string `json:"tmux_panes,omitempty"` + Targets []tmux.Pane `json:"-"` + Preview string `json:"preview"` } // Snapshot contains the agents currently running in tmux and their status counts. @@ -142,7 +142,8 @@ func agentRecord(result codex.ReadResult) Agent { } // Collect reads loaded conversations with live tmux panes, ordered by path and pane ID. -func Collect(ctx context.Context) (data Snapshot) { +// Without a pane snapshot it reads one from the current tmux server. +func (s *Source) Collect(ctx context.Context, panes []tmux.Pane) (data Snapshot) { data = Snapshot{ SchemaVersion: 1, Source: "codex", Scope: "tmux", IDs: []string{}, Agents: []Agent{}, Counts: map[string]int{}, @@ -171,35 +172,37 @@ func Collect(ctx context.Context) (data Snapshot) { } }() - client, err := codex.Connect(ctx) - if err != nil { - data.Err = err + if panes != nil && !slices.ContainsFunc(panes, candidate) { + // The popup has no candidate views here. Leave the SSH slot free. + s.Close() return data } - defer client.Close() - ids, err := client.LoadedIDs(ctx) - if err != nil { - data.Err = err - return data + if panes == nil { + var err error + + panes, err = tmux.ListPanes(ctx) + if err != nil { + data.Err = fmt.Errorf("match agent panes: %w", err) + return data + } } - data.IDs = ids + data.Err = s.use(ctx, func(client *codex.Client) error { + return data.read(ctx, client, s.Host, panes) + }) + + return data +} - panes, err := tmux.ListPanes(ctx) +func (data *Snapshot) read(ctx context.Context, client *codex.Client, host string, panes []tmux.Pane) error { + ids, err := client.LoadedIDs(ctx) if err != nil { - data.Err = fmt.Errorf("match agent panes: %w", err) - return data + return fmt.Errorf("list loaded threads: %w", err) } - matches := matchPanes(ids, panes) - sessions := make(map[string]int, len(panes)) - - for _, pane := range panes { - if number, ok := sessions[pane.ID]; !ok || pane.SessionNumber < number { - sessions[pane.ID] = pane.SessionNumber - } - } + data.IDs = ids + matches := matchPanes(host, ids, panes) for _, id := range ids { matched := matches[id] @@ -207,33 +210,29 @@ func Collect(ctx context.Context) (data Snapshot) { continue } - sessionNumber := sessions[matched[0]] - for _, pane := range matched[1:] { - sessionNumber = min(sessionNumber, sessions[pane]) - } - result, err := client.ReadThread(ctx, id) + + record := agentRecord(result) if err != nil { var rpcErr *codex.RPCError if !errors.As(err, &rpcErr) { - data.Err = err - return data + return fmt.Errorf("read thread: %w", err) } - data.Agents = append(data.Agents, Agent{ + record = Agent{ ID: id, Type: Codex, Title: id, State: "error", NeedsAttention: true, - Error: &rpcErr.Message, Panes: matched, SessionNumber: sessionNumber, ActiveFlags: []string{}, - }) - + Error: &rpcErr.Message, ActiveFlags: []string{}, + } + } else if result.Thread.Status.Type == "notLoaded" || record.ID != id { continue } - if result.Thread.Status.Type == "notLoaded" { - continue + record.Targets = matched + + for _, pane := range matched { + record.Panes = append(record.Panes, pane.ID) } - record := agentRecord(result) - record.Panes, record.SessionNumber = matched, sessionNumber data.Agents = append(data.Agents, record) } @@ -245,7 +244,7 @@ func Collect(ctx context.Context) (data Snapshot) { ) }) - return data + return nil } // Details includes a conversation's status, initial prompt, and recent history. @@ -258,14 +257,22 @@ type Details struct { } // ReadDetails reads one conversation and its recent activity. -func ReadDetails(ctx context.Context, id string) (Details, error) { - data := Details{RecentItems: []json.RawMessage{}} +func (s *Source) ReadDetails(ctx context.Context, id string) (Details, error) { + var data Details - client, err := codex.Connect(ctx) - if err != nil { - return data, fmt.Errorf("read details for %s: %w", id, err) - } - defer client.Close() + err := s.use(ctx, func(client *codex.Client) error { + var err error + + data, err = readDetails(ctx, client, id) + + return err + }) + + return data, err +} + +func readDetails(ctx context.Context, client *codex.Client, id string) (Details, error) { + data := Details{RecentItems: []json.RawMessage{}} result, err := client.ReadThread(ctx, id) if err != nil { diff --git a/tools/cmd/tmux-agent-status/open.go b/tools/cmd/tmux-agent-status/open.go index c38bcbb8..9ec97e6e 100644 --- a/tools/cmd/tmux-agent-status/open.go +++ b/tools/cmd/tmux-agent-status/open.go @@ -22,7 +22,10 @@ func openThread(ctx context.Context, id string) error { return fmt.Errorf("open agent: %w", err) } - data := agents.Collect(ctx) + var local agents.Source + defer local.Close() + + data := local.Collect(ctx, nil) if data.Err != nil { return data.Err } @@ -32,12 +35,12 @@ func openThread(ctx context.Context, id string) error { return errThreadGone } - panes := data.Agents[index].Panes + panes := data.Agents[index].Targets if len(panes) != 1 { return fmt.Errorf("%w, found %d", agents.ErrPaneMatch, len(panes)) } - if err := tmux.SwitchPane(ctx, panes[0], client); err != nil { + if err := local.Open(ctx, id, panes[0], client); err != nil { return fmt.Errorf("open agent: %w", err) } diff --git a/tools/cmd/tmux-agent-status/output.go b/tools/cmd/tmux-agent-status/output.go index b602753c..f13c9e2c 100644 --- a/tools/cmd/tmux-agent-status/output.go +++ b/tools/cmd/tmux-agent-status/output.go @@ -13,6 +13,9 @@ import ( ) func runStatus(ctx context.Context, watch bool, interval time.Duration, output, detailID string) error { + var local agents.Source + defer local.Close() + for { started := time.Now() requestCtx, cancel := context.WithTimeout(ctx, 8*time.Second) @@ -23,9 +26,9 @@ func runStatus(ctx context.Context, watch bool, interval time.Duration, output, ) if detailID == "" { - data = agents.Collect(requestCtx) + data = local.Collect(requestCtx, nil) } else { - data, err = agents.ReadDetails(requestCtx, detailID) + data, err = local.ReadDetails(requestCtx, detailID) } cancel() diff --git a/tools/cmd/tmux-agent-status/ui/agents/model.go b/tools/cmd/tmux-agent-status/ui/agents/model.go index 7956cd28..e714e50b 100644 --- a/tools/cmd/tmux-agent-status/ui/agents/model.go +++ b/tools/cmd/tmux-agent-status/ui/agents/model.go @@ -19,7 +19,10 @@ import ( // Model owns agent snapshots, filtering, selection, and activity requests. type Model struct { Panel panel.Model - data agentdata.Snapshot + hosts map[string]*destination + choices map[string]Choice + initialHost string + scanErr error selected, initialPane, originPane, originThread string filter int activity activity @@ -31,54 +34,45 @@ type tickMsg struct{} // New starts the section with the originating pane as its initial selection. func New(pane string) Model { - return Model{Panel: panel.New(), initialPane: pane, originPane: pane} + return Model{Panel: panel.New(), initialPane: pane, originPane: pane, hosts: map[string]*destination{"": {}}} } -// Snapshot returns the last known agent data and connection state. -func (m *Model) Snapshot() agentdata.Snapshot { return m.data } - // OriginID returns the conversation found in the originating tmux pane. func (m *Model) OriginID() string { return m.originThread } // Init begins polling agent status. -func (m *Model) Init(ctx context.Context) tea.Cmd { return fetch(ctx) } - -func fetch(ctx context.Context) tea.Cmd { - return func() tea.Msg { - ctx, cancel := context.WithTimeout(ctx, 8*time.Second) - defer cancel() - - return agentdata.Collect(ctx) - } -} - -func tick() tea.Cmd { return tea.Tick(time.Second, func(time.Time) tea.Msg { return tickMsg{} }) } +func (m *Model) Init(ctx context.Context) tea.Cmd { return scan(ctx) } // Update handles section input and applies status and activity results. func (m *Model) Update(ctx context.Context, message tea.Msg) tea.Cmd { switch msg := message.(type) { - case agentdata.Snapshot: - if msg.Err != nil { - m.data.Err = msg.Err - return tick() - } - - for _, a := range msg.Agents { - if m.originThread == "" && slices.Contains(a.Panes, m.originPane) { - m.originThread = a.ID + case panesMsg: + return m.fetch(ctx, msg) + case StatusMsg: + dest := m.hosts[msg.Host] + dest.busy = false + + dest.data = msg.data + if msg.Host == "" && m.originThread == "" { + for _, a := range msg.data.Agents { + if slices.Contains(a.Panes, m.originPane) { + m.originThread = a.ID + } } } - m.data = msg - cmd := m.updateAgents(ctx) - if cmd == nil && m.selected != "" && m.activityCancel == nil { - cmd = m.refreshActivity(ctx) + if msg.Host == m.initialHost { + m.initialPane = "" + } + + if choice, ok := m.Find(m.selected); ok && choice.Pane.Host == msg.Host && cmd == nil && m.activityCancel == nil { + return m.refreshActivity(ctx) } - return tea.Batch(tick(), cmd) + return cmd case tickMsg: - return fetch(ctx) + return scan(ctx) case activity: if msg.ID == m.selected && msg.generation == m.activityGeneration { m.activity = msg @@ -86,6 +80,7 @@ func (m *Model) Update(ctx context.Context, message tea.Msg) tea.Cmd { m.updateAgentDetails() } case tea.KeyPressMsg: + m.initialPane = "" if key.Matches(msg, Keys.NextFilter, Keys.PreviousFilter, Keys.Attention) { return m.changeFilter(ctx, msg) } @@ -140,7 +135,9 @@ func (m *Model) refreshActivity(ctx context.Context) tea.Cmd { } m.activityGeneration++ - if m.selected == "" { + + choice, ok := m.Find(m.selected) + if !ok { return nil } @@ -151,16 +148,17 @@ func (m *Model) refreshActivity(ctx context.Context) tea.Cmd { return func() tea.Msg { defer cancel() - data, err := agentdata.ReadDetails(ctx, id) + data, err := choice.Source.ReadDetails(ctx, choice.Agent.ID) return activity{ID: id, generation: generation, Entries: activityEntries(data), Err: err} } } -func (m *Model) filtered(filter int) []agentdata.Agent { - var result []agentdata.Agent +func (m *Model) filtered(filter int) []Choice { + var result []Choice - for _, a := range m.data.Agents { + for _, c := range m.choices { + a := c.Agent match := false switch filter { @@ -177,7 +175,7 @@ func (m *Model) filtered(filter int) []agentdata.Agent { } if match { - result = append(result, a) + result = append(result, c) } } @@ -198,24 +196,38 @@ func (m *Model) selectAgent(ctx context.Context, id string) tea.Cmd { } func (m *Model) updateAgents(ctx context.Context) tea.Cmd { + m.choices = make(map[string]Choice) + for _, dest := range m.hosts { + for _, a := range dest.data.Agents { + for _, pane := range a.Targets { + c := Choice{Agent: a, Pane: pane, Source: &dest.source} + m.choices[c.key()] = c + } + } + } + filtered := m.filtered(m.filter) - slices.SortStableFunc(filtered, func(a, b agentdata.Agent) int { return cmp.Compare(a.SessionNumber, b.SessionNumber) }) + slices.SortFunc(filtered, func(a, b Choice) int { + return cmp.Or(cmp.Compare(a.Pane.SessionNumber, b.Pane.SessionNumber), + cmp.Compare(a.Pane.Host, b.Pane.Host), cmp.Compare(a.Agent.Cwd, b.Agent.Cwd), + cmp.Compare(len(a.Pane.ID), len(b.Pane.ID)), cmp.Compare(a.Pane.ID, b.Pane.ID)) + }) + + selected := m.selected items := make([]tui.ListItem, 0, len(filtered)) - for _, a := range filtered { - items = append(items, Row(a)) - } + for _, c := range filtered { + row := Row(c.Agent) - selected := m.selected - if m.initialPane != "" { - for _, a := range filtered { - if slices.Contains(a.Panes, m.initialPane) { - selected = a.ID - break - } + row.ID, row.Group = c.key(), c.location() + if len(c.Agent.Panes) > 1 { + row.Title = c.Pane.ID + " · " + row.Title } - m.initialPane = "" + items = append(items, row) + if c.Pane.ID == m.initialPane { + selected = row.ID + } } m.Panel.List.SetItems(items, selected) diff --git a/tools/cmd/tmux-agent-status/ui/agents/sources.go b/tools/cmd/tmux-agent-status/ui/agents/sources.go new file mode 100644 index 00000000..1a7e16f5 --- /dev/null +++ b/tools/cmd/tmux-agent-status/ui/agents/sources.go @@ -0,0 +1,131 @@ +package agents + +import ( + "context" + "errors" + "slices" + "time" + + tea "charm.land/bubbletea/v2" + + agentdata "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/agents" + "github.com/ddeville/scripts/tools/internal/tmux" +) + +// Each destination refreshes independently so an unreachable host cannot +// stall the local dashboard or other SSH destinations. +type destination struct { + source agentdata.Source + data agentdata.Snapshot + busy bool +} + +type panesMsg struct { + panes []tmux.Pane + err error +} + +// StatusMsg contains a new snapshot for one app server. +type StatusMsg struct { + Host string + data agentdata.Snapshot +} + +var errDisconnected = errors.New("SSH disconnected") + +func scan(ctx context.Context) tea.Cmd { + return func() tea.Msg { + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + + panes, err := tmux.ListPanes(ctx) + + return panesMsg{panes, err} + } +} + +func (m *Model) fetch(ctx context.Context, msg panesMsg) tea.Cmd { + cmds := []tea.Cmd{tea.Tick(time.Second, func(time.Time) tea.Msg { return tickMsg{} })} + + m.scanErr = msg.err + if msg.err != nil { + return tea.Batch(cmds...) + } + + groups := map[string][]tmux.Pane{"": {}} + + for _, p := range msg.panes { + if p.Host != "" && p.Terminal == "" { + continue + } + + groups[p.Host] = append(groups[p.Host], p) + if p.ID == m.initialPane { + m.initialHost = p.Host + } + } + + for host, dest := range m.hosts { + if _, ok := groups[host]; !ok && !dest.busy { + delete(m.hosts, host) + cmds = append(cmds, m.updateAgents(ctx)) + + dest.source.Close() + } + } + + for host, panes := range groups { + dest := m.hosts[host] + if dest == nil { + dest = &destination{source: agentdata.Source{Host: host}} + m.hosts[host] = dest + } + + if dest.busy { + continue + } + + dest.busy = true + + cmds = append(cmds, func() tea.Msg { + ctx, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + + if host != "" && !slices.ContainsFunc(panes, func(p tmux.Pane) bool { return !p.Dead }) { + dest.source.Close() + return StatusMsg{host, agentdata.Snapshot{At: time.Now(), Err: errDisconnected}} + } + + return StatusMsg{host, dest.source.Collect(ctx, panes)} + }) + } + + return tea.Batch(cmds...) +} + +// Close releases the popup's app-server connections. +func (m *Model) Close() { + for _, dest := range m.hosts { + dest.source.Close() + } +} + +// Local is the only source of thread IDs and paths for worktree operations. +func (m *Model) Local() agentdata.Snapshot { return m.hosts[""].data } + +// Choice identifies a specific local view of a conversation. +type Choice struct { + Agent agentdata.Agent + Pane tmux.Pane + Source *agentdata.Source +} + +func (c Choice) key() string { + return c.Pane.ID + "/" + c.Pane.Terminal + "/" + c.Pane.Host + "/" + c.Agent.ID +} + +// Find resolves an agent list row without guessing between duplicate views. +func (m *Model) Find(key string) (Choice, bool) { + c, ok := m.choices[key] + return c, ok +} diff --git a/tools/cmd/tmux-agent-status/ui/agents/sources_test.go b/tools/cmd/tmux-agent-status/ui/agents/sources_test.go new file mode 100644 index 00000000..14bea1e1 --- /dev/null +++ b/tools/cmd/tmux-agent-status/ui/agents/sources_test.go @@ -0,0 +1,35 @@ +//nolint:testpackage // Exercise asynchronous status updates without starting a tmux server. +package agents + +import ( + "testing" + + agentdata "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/agents" + "github.com/ddeville/scripts/tools/internal/tmux" +) + +func TestPaneChoicesKeepOriginAndWorktreesSeparate(t *testing.T) { + t.Parallel() + + local := tmux.Pane{ID: "%1"} + first := tmux.Pane{ID: "%2", Host: "dev", Terminal: "codex"} + origin := tmux.Pane{ID: "%3", Host: "dev", Terminal: "shell"} + + m := New(origin.ID) + m.Update(t.Context(), panesMsg{panes: []tmux.Pane{local, first, origin}}) + m.Update(t.Context(), StatusMsg{data: agentdata.Snapshot{Agents: []agentdata.Agent{{ + ID: "shared-id", Panes: []string{local.ID}, Targets: []tmux.Pane{local}, + }}}}) + m.Update(t.Context(), StatusMsg{Host: "dev", data: agentdata.Snapshot{Agents: []agentdata.Agent{{ + ID: "shared-id", Panes: []string{first.ID, origin.ID}, Targets: []tmux.Pane{first, origin}, + }}}}) + + selected, ok := m.Find(m.Panel.List.SelectedID()) + if !ok || selected.Pane != origin || m.Panel.List.Len() != 3 { + t.Fatalf("selected %v among %d choices, want the originating pane among three", selected.Pane, m.Panel.List.Len()) + } + + if m.OriginID() != "" || len(m.Local().Agents) != 1 || m.Local().Agents[0].Targets[0] != local { + t.Fatal("remote conversation exposed as a local worktree fork source") + } +} diff --git a/tools/cmd/tmux-agent-status/ui/agents/view.go b/tools/cmd/tmux-agent-status/ui/agents/view.go index d1b3746a..16cdfd9a 100644 --- a/tools/cmd/tmux-agent-status/ui/agents/view.go +++ b/tools/cmd/tmux-agent-status/ui/agents/view.go @@ -1,6 +1,7 @@ package agents import ( + "cmp" "encoding/json" "fmt" "slices" @@ -35,49 +36,55 @@ func stateStyle(state string) (lipgloss.Style, string, string) { // Summary describes agents that need attention. func (m *Model) Summary() string { - if m.data.Err != nil { - if m.data.At.IsZero() { - return tui.Red.Render("Agent status unavailable") - } - - return tui.Red.Render("Status unavailable · showing last known data") + if m.loading() { + return tui.Muted.Render("Loading agents…") } - if m.data.At.IsZero() { - return tui.Muted.Render("Loading agents…") + counts := map[string]int{} + + for _, dest := range m.hosts { + for state, count := range dest.data.Counts { + counts[state] += count + } } var parts []string for _, state := range []string{"approval", "input", "error", "ready"} { - if count := m.data.Counts[state]; count > 0 { + if count := counts[state]; count > 0 { style, label, _ := stateStyle(state) parts = append(parts, style.Render(fmt.Sprintf("%s %d", label, count))) } } if len(parts) == 0 { + if m.issue() != "" { + return tui.Yellow.Render("Some agent status is unavailable") + } + return tui.Muted.Render("Nothing needs your attention") } return "Needs you: " + strings.Join(parts, tui.Muted.Render(" · ")) } -func (m *Model) detailContent(width int) string { - index := slices.IndexFunc(m.data.Agents, func(a agentdata.Agent) bool { return a.ID == m.selected }) - if index < 0 { - return tui.Muted.Render("No conversation selected") +func (c Choice) location() string { + if c.Pane.Host != "" { + return tui.CleanLine(c.Pane.Host + " · " + cmp.Or(c.Agent.Cwd, "Unknown location")) } - a := m.data.Agents[index] + return cmp.Or(tui.ShortPath(c.Agent.Cwd), "Unknown location") +} - style, _, hint := stateStyle(a.State) - if len(a.Panes) > 1 { - style = tui.Yellow - hint = fmt.Sprintf("This thread is open in %d tmux panes. Close the extra Codex instance, then try again.", len(a.Panes)) +func (m *Model) detailContent(width int) string { + c, ok := m.Find(m.selected) + if !ok { + return tui.Muted.Render("No conversation selected") } - lines := panel.DetailHeader(a.Title, a.Cwd, style.Render(hint), "to open") + a := c.Agent + style, _, hint := stateStyle(a.State) + lines := panel.DetailHeader(a.Title, c.location(), style.Render(hint), "to open pane "+c.Pane.ID) if a.Error != nil { lines = append(lines, "", tui.Red.Render(tui.CleanText(*a.Error))) @@ -186,11 +193,11 @@ func activityEntries(data agentdata.Details) []entry { // View renders the agent list and selected conversation. func (m *Model) View() string { empty := "No conversations match this status" - if m.data.At.IsZero() { + if m.loading() { empty = "Loading agents…" } - if m.data.Err != nil { + if m.issue() != "" && len(m.choices) == 0 { empty = "Could not read agent status" } @@ -199,17 +206,49 @@ func (m *Model) View() string { // Message provides connection errors or the current app notice for the footer. func (m *Model) Message(notice string) string { - if m.data.Err != nil { - return tui.Red.Render("Agent status unavailable: " + tui.SingleLine(m.data.Err.Error())) - } - if notice != "" { return tui.Muted.Render(tui.CleanLine(notice)) } + if issue := m.issue(); issue != "" { + return tui.Red.Render(tui.SingleLine(issue)) + } + return "" } +func (m *Model) loading() bool { + if m.scanErr != nil || len(m.choices) != 0 { + return false + } + + for _, dest := range m.hosts { + if dest.data.At.IsZero() { + return true + } + } + + return false +} + +func (m *Model) issue() string { + if m.scanErr != nil { + return m.scanErr.Error() + } + + var issues []string + + for host, dest := range m.hosts { + if err := dest.data.Err; err != nil { + issues = append(issues, cmp.Or(host, "local")+" · "+err.Error()) + } + } + + slices.Sort(issues) + + return strings.Join(issues, " · ") +} + // Toolbar renders status filters and their counts. func (m *Model) Toolbar() string { tabs := make([]string, 0, len(filters)) diff --git a/tools/cmd/tmux-agent-status/ui/model.go b/tools/cmd/tmux-agent-status/ui/model.go index 965d9dbf..eac0eb75 100644 --- a/tools/cmd/tmux-agent-status/ui/model.go +++ b/tools/cmd/tmux-agent-status/ui/model.go @@ -3,7 +3,6 @@ package ui import ( "context" - "errors" "fmt" "path/filepath" "time" @@ -11,7 +10,6 @@ import ( "charm.land/bubbles/v2/key" tea "charm.land/bubbletea/v2" - "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/agents" agentui "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/ui/agents" "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/ui/panel" "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/ui/worktrees" @@ -37,26 +35,25 @@ type Options struct { } type model struct { - ctx context.Context //nolint:containedctx // Bubble Tea callbacks share the lifetime of the program. - tasks *tui.Tasks - area, returnArea Area - agents agentui.Model - worktrees worktrees.Model - width, height int - hasOrigin bool - notice string - quitting bool - operationCancel context.CancelFunc - targetPane, targetSession string + ctx context.Context //nolint:containedctx // Bubble Tea callbacks share the lifetime of the program. + tasks *tui.Tasks + area, returnArea Area + agents agentui.Model + worktrees worktrees.Model + width, height int + hasOrigin bool + selectionLost bool + notice string + quitting bool + operationCancel context.CancelFunc + client, targetSession string } type openMsg struct { - pane, session string - err error + session string + err error } -var errStaleStatus = errors.New("status is stale; wait for a fresh update") - func (m *model) Init() tea.Cmd { return tea.Batch(m.agents.Init(m.ctx), m.worktrees.Init(m.ctx)) } func (m *model) activePanel() *panel.Model { @@ -80,12 +77,19 @@ func (m *model) beginCreate() tea.Cmd { id := m.agents.OriginID() if m.area == AgentsArea { - id = m.agents.Panel.List.SelectedID() + if choice, ok := m.agents.Find(m.agents.Panel.List.SelectedID()); ok { + if choice.Pane.Host != "" { + m.notice = "Worktree creation is local. Choose a local conversation or worktree." + return nil + } + + id = choice.Agent.ID + } } else if selected, ok := m.worktrees.Selected(); ok { source = selected.Path } - data := m.agents.Snapshot() + data := m.agents.Local() pending := m.area == WorktreesArea && m.hasOrigin && data.At.IsZero() && data.Err == nil cmd := m.worktrees.BeginCreate(source, id, pending) @@ -106,26 +110,20 @@ func (m *model) openItem(id string) tea.Cmd { m.operationCancel = cancel if m.area == AgentsArea { - data := m.agents.Snapshot() + choice, ok := m.agents.Find(id) + if !ok { + cancel() - return m.tasks.Track(func() tea.Msg { - if data.Err != nil || time.Since(data.At) > 10*time.Second { - return openMsg{err: errStaleStatus} - } + m.operationCancel = nil - ctx, stop := context.WithTimeout(ctx, time.Second) - defer stop() - - panes, err := agents.MatchPanes(ctx, data.IDs) - if err != nil { - return openMsg{err: err} - } + return nil + } - if len(panes[id]) != 1 { - return openMsg{err: fmt.Errorf("%w, found %d", agents.ErrPaneMatch, len(panes[id]))} - } + return m.tasks.Track(func() tea.Msg { + ctx, stop := context.WithTimeout(ctx, 3*time.Second) + defer stop() - return openMsg{pane: panes[id][0]} + return openMsg{err: choice.Source.Open(ctx, choice.Agent.ID, choice.Pane, m.client)} }) } @@ -168,7 +166,7 @@ func (m *model) Update(message tea.Msg) (tea.Model, tea.Cmd) { //nolint:ireturn case msg.err != nil: m.notice = tui.SingleLine(msg.err.Error()) default: - m.targetPane, m.targetSession = msg.pane, msg.session + m.targetSession = msg.session cmd = tea.Quit } case worktrees.OpenSessionMsg: @@ -176,8 +174,8 @@ func (m *model) Update(message tea.Msg) (tea.Model, tea.Cmd) { //nolint:ireturn cmd = tea.Quit default: cmd = tea.Batch(m.agents.Update(m.ctx, msg), m.worktrees.Update(m.ctx, msg)) - if _, ok := msg.(agents.Snapshot); ok { - m.worktrees.SetAgents(m.agents.Snapshot(), m.agents.OriginID()) + if update, ok := msg.(agentui.StatusMsg); ok && update.Host == "" { + m.worktrees.SetAgents(m.agents.Local(), m.agents.OriginID()) } if m.quitting && !m.busy() { @@ -186,7 +184,14 @@ func (m *model) Update(message tea.Msg) (tea.Model, tea.Cmd) { //nolint:ireturn } if selected != m.agents.Panel.List.SelectedID() { - m.notice = "" + if _, input := message.(tea.KeyPressMsg); input { + m.selectionLost = false + m.notice = "" + } else if _, ok := m.agents.Find(selected); selected != "" && !ok { + // A refresh can remove the highlighted thread and select the first + // row. A pending Enter must not open that replacement. + m.selectionLost = true + } } return m, cmd @@ -242,6 +247,13 @@ func (m *model) handleKey(msg tea.KeyPressMsg) tea.Cmd { case key.Matches(msg, keys.refresh) && m.area == WorktreesArea: return m.worktrees.Reload(m.worktrees.Panel.List.SelectedID()) case key.Matches(msg, keys.open): + if m.area == AgentsArea && m.selectionLost { + m.selectionLost = false + m.notice = "The previous conversation disappeared. Choose a pane or press Enter again." + + return nil + } + return m.openItem(m.activePanel().List.SelectedID()) case key.Matches(msg, keys.jump): position := int(msg.String()[0] - '0') @@ -275,10 +287,12 @@ func Run(ctx context.Context, options Options) error { } initial := &model{ - ctx: uiCtx, tasks: tasks, area: options.Area, width: 100, height: 30, hasOrigin: options.Pane != "", + ctx: uiCtx, tasks: tasks, client: options.Client, area: options.Area, width: 100, height: 30, hasOrigin: options.Pane != "", agents: agentui.New(options.Pane), worktrees: worktrees.New(options.Root, source, tasks), } + defer initial.agents.Close() + initial.updatePanels() result, err := tea.NewProgram(initial, tea.WithContext(uiCtx), tea.WithoutSignalHandler()).Run() @@ -288,17 +302,9 @@ func Run(ctx context.Context, options Options) error { return fmt.Errorf("run status TUI: %w", err) } - if final, ok := result.(*model); ok { - if final.targetPane != "" { - if err := tmux.SwitchPane(ctx, final.targetPane, options.Client); err != nil { - return fmt.Errorf("open selected agent: %w", err) - } - } - - if final.targetSession != "" { - if err := tmux.SwitchSession(ctx, final.targetSession, options.Client); err != nil { - return fmt.Errorf("open worktree session: %w", err) - } + if final, ok := result.(*model); ok && final.targetSession != "" { + if err := tmux.SwitchSession(ctx, final.targetSession, options.Client); err != nil { + return fmt.Errorf("open worktree session: %w", err) } } diff --git a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md index e3964504..3a2b1f42 100644 --- a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md +++ b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md @@ -11,20 +11,33 @@ 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. Sessions using the same SSH destination share one OpenSSH -connection. Each pane uses one of the server's `MaxSessions` slots. Discovery -needs a free slot too. +connection. Use the same SSH alias across projects. Each pane uses one of sshd's +`MaxSessions` slots. Leave room for discovery and one channel per open agent +popup. A full connection never falls back to a second login. -- **Reconnect** by rerunning `tm` from a local shell. This reconnects failed panes - across projects on that destination, including moved panes. Input typed into a - dead pane is discarded. Programs that ended while disconnected stay closed. +- **Reconnect** happens automatically. The first `tm` can prompt for sign-in. + Each local tmux server runs one supervisor per destination. It retries a lost + connection with backoff and reattaches surviving terminals in place, including + moved panes. Input typed into a dead pane is discarded. Programs that ended + stay closed. If SSH needs attention or recovery stalls, rerun `tm --host …` + from a local shell. Automatic retries never prompt or accept new host keys. - **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. +- **Open Codex** with prefix `a`. The popup groups remote conversations by host + and directory, including Codex started manually in a split. Choose a pane + when a thread has multiple views. Enter rechecks the thread and pane before + switching the invoking client. Worktree actions and the CLI status feed stay local. -Zmx must be on the devbox's SSH command path. Its sockets live in +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 local agent -dashboard doesn't list remote agents yet. +sockets in surviving programs can go stale after reconnecting. + +Remote status requires a shared Codex app server, `codex app-server proxy` on +the SSH command path, and `thread-id` last in `tui.terminal_title`. The popup +uses the same title matching locally and remotely. A shortened ID must match +exactly one loaded thread on that host. A stale or forged title can misidentify +a conversation. The popup only queries each app server while open. diff --git a/tools/cmd/tmux-session/main.go b/tools/cmd/tmux-session/main.go index 663d796f..057f7d93 100644 --- a/tools/cmd/tmux-session/main.go +++ b/tools/cmd/tmux-session/main.go @@ -12,6 +12,7 @@ import ( "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" ) @@ -22,7 +23,7 @@ func main() { func command() *cobra.Command { var ( - name, host string + name, host, watch string launch, closeTarget string noSwitch bool ) @@ -36,6 +37,10 @@ func command() *cobra.Command { SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 0 { + if watch != "" { + return supervise(cmd.Context(), watch) + } + if launch != "" { return attachPane(cmd.Context(), launch) } @@ -90,6 +95,8 @@ func command() *cobra.Command { 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(&watch, "supervise", "", "supervise a remote connection") + cmd.Flags().Lookup("supervise").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 @@ -120,25 +127,11 @@ func resolveDirectory(path string) (string, error) { return directory, nil } -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) - } - - return dir, nil -} - // lockOpen serializes lookup and layout creation, including the first tmux server startup. func lockOpen() (*os.File, error) { - dir, err := cacheDir() + dir, err := sshmux.CacheDir() if err != nil { - return nil, err + return nil, fmt.Errorf("locate tmux session cache: %w", err) } return lockFile(filepath.Join(dir, "open.lock")) diff --git a/tools/cmd/tmux-session/pane.go b/tools/cmd/tmux-session/pane.go index 6d02cedf..ddf31e38 100644 --- a/tools/cmd/tmux-session/pane.go +++ b/tools/cmd/tmux-session/pane.go @@ -14,6 +14,7 @@ import ( "strings" "syscall" + "github.com/ddeville/scripts/tools/internal/sshmux" "github.com/ddeville/scripts/tools/internal/tmux" ) @@ -64,17 +65,21 @@ func attachPane(ctx context.Context, requested string) error { return fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) } - dest, err := sshDestination(p.Host) + dest, err := sshmux.ForHost(p.Host) if err != nil { - return err + return fmt.Errorf("find pane connection: %w", err) } + // Record before launching. An ambiguous failure can only reattach here. + p.Connection = dest.Generation() + + project := "" if dir != "" { - // Record the target before launching. Even a manual respawn after - // an ambiguous SSH failure can now only reattach to this terminal. - if err := p.Record(ctx, displayName(path.Base(dir))); err != nil { - return fmt.Errorf("record remote pane: %w", err) - } + project = displayName(path.Base(dir)) + } + + if err := p.Record(ctx, project); err != nil { + return fmt.Errorf("record remote pane: %w", err) } ssh, err := exec.LookPath("ssh") @@ -82,7 +87,7 @@ func attachPane(ctx context.Context, requested string) error { return fmt.Errorf("find ssh: %w", err) } - args := dest.channel("-tt", remoteCommand(attach, mode, p.Terminal, dir)) + args := dest.Channel("-tt", remoteCommand(attach, mode, p.Terminal, dir)) return fmt.Errorf("start ssh: %w", syscall.Exec(ssh, append([]string{ssh}, args...), os.Environ())) // #nosec G204 -- Replace only with ssh and quote remote arguments. } @@ -97,26 +102,26 @@ func stopTerminal(ctx context.Context, p *tmux.Attachment) error { return fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) } - dest, err := sshDestination(p.Host) + dest, err := sshmux.ForHost(p.Host) if err != nil { - return err + return fmt.Errorf("find pane connection: %w", err) } command := remoteCommand(stop, p.Terminal, strconv.FormatBool(p.Dead)) - out, err := dest.query(ctx, command) - if errors.Is(err, errChannelRefused) && !p.Dead { + out, err := dest.Query(ctx, command) + if errors.Is(err, sshmux.ErrChannelRefused) && !p.Dead { // At MaxSessions, free this attachment's slot for the close command. if err := p.Disconnect(ctx); err != nil { return fmt.Errorf("disconnect pane: %w", err) } p.Dead = true - out, err = dest.query(ctx, command) + out, err = dest.Query(ctx, command) } if err != nil { - return err + return fmt.Errorf("stop terminal: %w", err) } names, err := inventory(out) diff --git a/tools/cmd/tmux-session/remote.go b/tools/cmd/tmux-session/remote.go index 2674a9cd..95a097ab 100644 --- a/tools/cmd/tmux-session/remote.go +++ b/tools/cmd/tmux-session/remote.go @@ -15,6 +15,7 @@ import ( "unicode" "unicode/utf8" + "github.com/ddeville/scripts/tools/internal/sshmux" "github.com/ddeville/scripts/tools/internal/tmux" ) @@ -76,6 +77,30 @@ func inventory(out string) (map[string]bool, error) { 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" @@ -88,19 +113,19 @@ func openRemote(ctx context.Context, host, request, name string) (tmux.Session, return tmux.Session{}, false, fmt.Errorf("%w: empty remote path", os.ErrInvalid) } - dest, err := sshDestination(host) + dest, err := sshmux.ForHost(host) if err != nil { - return tmux.Session{}, false, err + return tmux.Session{}, false, fmt.Errorf("find connection: %w", err) } - lock, err := lockFile(dest.socket + ".lock") + lock, err := lockFile(dest.Socket + ".lock") if err != nil { return tmux.Session{}, false, err } defer func() { _ = lock.Close() }() - if err := dest.connect(ctx); err != nil { - return tmux.Session{}, false, err + if err := dest.Connect(ctx, true); err != nil { + return tmux.Session{}, false, fmt.Errorf("open connection: %w", err) } if request == "~" { @@ -111,9 +136,9 @@ func openRemote(ctx context.Context, host, request, name string) (tmux.Session, request = "./" + strings.TrimPrefix(request, "~/") } - out, err := dest.query(ctx, remoteCommand(inspect, request)) + out, err := dest.Query(ctx, remoteCommand(inspect, request)) if err != nil { - return tmux.Session{}, false, err + return tmux.Session{}, false, fmt.Errorf("inspect workspace: %w", err) } dir, list, ok := strings.Cut(out, "\x00") @@ -128,7 +153,12 @@ func openRemote(ctx context.Context, host, request, name string) (tmux.Session, w := workspace{Host: host, Path: dir, Name: cmp.Or(name, path.Base(dir))} - return w.open(ctx, names) + target, created, err := w.open(ctx, names) + if err == nil { + err = startSupervisor(ctx, dest) + } + + return target, created, err } // Pane names and positions are mutable. Only a terminal ID can identify a @@ -225,7 +255,7 @@ func (w workspace) open(ctx context.Context, names map[string]bool) (tmux.Sessio // All workspaces on the destination lost the same connection. for _, p := range panes { - if p.Host != w.Host || !p.Dead { + if p.Host != w.Host || !p.Dead || !terminalID.MatchString(p.Terminal) || !names[p.Terminal] { continue } diff --git a/tools/cmd/tmux-session/remote_test.go b/tools/cmd/tmux-session/remote_test.go index 9211877a..219ed558 100644 --- a/tools/cmd/tmux-session/remote_test.go +++ b/tools/cmd/tmux-session/remote_test.go @@ -45,3 +45,26 @@ func TestDiscoveryDistinguishesUnreachableFromGone(t *testing.T) { } } } + +func TestRecoveryOnlyRetriesSSHFailuresOnThisDestination(t *testing.T) { + t.Parallel() + + const terminal = "tm-1234567890abcdef1234.shell-AAAAAAAAAAAAA" + + panes := map[string]tmux.Attachment{ + "%1": {ID: "%1", Host: "dev", Terminal: terminal, Dead: true, ExitStatus: "255"}, + "%2": {ID: "%2", Host: "dev", Terminal: terminal, Dead: true, ExitStatus: "1"}, + "%3": {ID: "%3", Host: "dev", Terminal: terminal}, + "%4": {ID: "%4", Host: "other", Terminal: terminal, Dead: true, ExitStatus: "255"}, + "%5": {ID: "%5", Host: "dev", Dead: true, ExitStatus: "255"}, + } + + active, retry := interrupted(panes, "dev") + if !active || !slices.Equal(retry, []tmux.Attachment{panes["%1"]}) { + t.Fatalf("active = %t, retry = %v", active, retry) + } + + if active, _ := interrupted(panes, "gone"); active { + t.Fatal("supervisor should exit without panes") + } +} diff --git a/tools/cmd/tmux-session/ssh.go b/tools/cmd/tmux-session/ssh.go deleted file mode 100644 index 9dfbaa4c..00000000 --- a/tools/cmd/tmux-session/ssh.go +++ /dev/null @@ -1,122 +0,0 @@ -package main - -import ( - "context" - "crypto/sha256" - "errors" - "fmt" - "os" - "os/exec" - "path/filepath" - "regexp" - "strings" - "syscall" - "time" -) - -type destination struct { - host, socket string -} - -var ( - sshHost = regexp.MustCompile(`^[a-zA-Z0-9_@.%+:/\[\]-]+$`) - errChannelRefused = errors.New("SSH session channel refused (check sshd MaxSessions)") -) - -func sshDestination(host string) (destination, error) { - if !sshHost.MatchString(host) || strings.HasPrefix(host, "-") { - return destination{}, fmt.Errorf("%w: invalid SSH destination %q", os.ErrInvalid, host) - } - - dir, err := cacheDir() - if err != nil { - return destination{}, err - } - - info, err := os.Lstat(dir) - if err != nil { - return destination{}, 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 destination{}, fmt.Errorf("%w: SSH socket directory %s must be private", os.ErrPermission, dir) - } - - sum := sha256.Sum256([]byte(host)) - - return destination{host: host, socket: filepath.Join(dir, fmt.Sprintf("ssh-%x", sum[:10]))}, nil -} - -// Only tm opens a connection. OpenSSH retires the master after a minute with no open channels. -func (d destination) connect(ctx context.Context) error { - if exec.CommandContext(ctx, "ssh", "-S", d.socket, "-O", "check", "--", d.host).Run() == nil { // #nosec G204 -- The validated destination follows --. - return nil - } - - cmd := exec.CommandContext(ctx, "ssh", "-S", d.socket, "-fN", "-oControlMaster=auto", "-oControlPersist=60", // #nosec G204 -- The validated destination follows --. - "-oRemoteCommand=none", "-oConnectTimeout=10", "-oServerAliveInterval=5", "-oServerAliveCountMax=2", "--", d.host) - cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr - - if err := cmd.Run(); err != nil { - return fmt.Errorf("connect to %s: %w", d.host, err) - } - - return nil -} - -// ControlMaster=no alone allows a direct connection if the socket is gone or the master refuses a channel. -func (d destination) channel(tty, command string) []string { - return []string{ - "-S", d.socket, "-oControlMaster=no", "-oProxyCommand=false", "-oBatchMode=yes", - "-oClearAllForwardings=yes", "-oRemoteCommand=none", "-oLogLevel=ERROR", "-e", "none", tty, "--", d.host, command, - } -} - -func (d destination) 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 { - var exit *exec.ExitError - if errors.As(err, &exit) && len(exit.Stderr) != 0 { - if exit.ExitCode() == 255 && strings.Contains(string(exit.Stderr), "Session open refused") { - return "", fmt.Errorf("%w on %s", errChannelRefused, d.host) - } - - return "", fmt.Errorf("SSH %s: %w: %s", d.host, err, strings.TrimSpace(string(exit.Stderr))) - } - - return "", fmt.Errorf("SSH %s: %w", d.host, err) - } - - return string(out), 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() -} diff --git a/tools/cmd/tmux-session/supervisor.go b/tools/cmd/tmux-session/supervisor.go new file mode 100644 index 00000000..b1e3fec9 --- /dev/null +++ b/tools/cmd/tmux-session/supervisor.go @@ -0,0 +1,210 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "syscall" + "time" + + "github.com/ddeville/scripts/tools/internal/sshmux" + "github.com/ddeville/scripts/tools/internal/tmux" +) + +// The foreground open owns interactive authentication. Hand off the lifetime +// lock on stdin so the supervisor survives the caller without a PID file. +func startSupervisor(ctx context.Context, dest sshmux.Destination) error { + // Different local tmux servers share the master, but cannot see each + // other's panes or events. + socket, err := tmux.SocketPath(ctx) + if err != nil { + return fmt.Errorf("identify tmux server: %w", err) + } + + server := sha256.Sum256([]byte(socket)) + filename := fmt.Sprintf("%s.%x.watch", dest.Socket, server[:8]) + + lock, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0o600) // #nosec G304 -- Private per-destination directory. + if err != nil { + return fmt.Errorf("open supervisor lock: %w", err) + } + + defer func() { _ = lock.Close() }() + + err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if errors.Is(err, syscall.EWOULDBLOCK) { + return nil + } + + if err != nil { + return fmt.Errorf("lock supervisor: %w", err) + } + + helper, err := os.Executable() + if err != nil { + return fmt.Errorf("locate tmux-session: %w", err) + } + + cmd := exec.CommandContext(context.WithoutCancel(ctx), helper, "--supervise", dest.Host) // #nosec G204 -- Re-exec this binary with a validated destination. + cmd.Stdin = lock + + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + if err := cmd.Start(); err != nil { + return fmt.Errorf("start supervisor: %w", err) + } + + go func() { _ = cmd.Wait() }() + + return nil +} + +func supervise(ctx context.Context, host string) error { + dest, err := sshmux.ForHost(host) + if err != nil { + return fmt.Errorf("find connection: %w", err) + } + + helper, err := os.Executable() + if err != nil { + return fmt.Errorf("locate tmux-session: %w", err) + } + + backoff := time.Second + + for ctx.Err() == nil { + // Explicit opens and automatic retries must never start competing masters. + lock, err := lockFile(dest.Socket + ".lock") + if err != nil { + return err + } + + active, err := recoverPanes(ctx, dest, helper) + + done := !active || errors.Is(err, sshmux.ErrSignIn) + if done { + // Let a waiting interactive open start a new supervisor. + _ = os.Stdin.Close() + } + + _ = lock.Close() + + if done { + return err + } + + if err != nil { + select { + case <-ctx.Done(): + return nil + case <-time.After(backoff): + } + + backoff = min(backoff*2, 30*time.Second) + + continue + } + + backoff = time.Second + + if err := tmux.WaitPaneDeath(ctx); err != nil { + return fmt.Errorf("wait for failed panes: %w", err) + } + } + + return nil +} + +func recoverPanes(ctx context.Context, dest sshmux.Destination, helper string) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + + panes, err := tmux.Attachments(ctx, "") + if err != nil { + return false, fmt.Errorf("inspect remote panes: %w", err) + } + + active, failed := interrupted(panes, dest.Host) + + if !active { + // A new session exists before its panes finish recording their targets. + sessions, err := tmux.ListSessions(ctx) + if err != nil { + return false, fmt.Errorf("look for remote sessions: %w", err) + } + + for _, session := range sessions { + var w workspace + if session.Remote != "" && json.Unmarshal([]byte(session.Remote), &w) == nil && w.Host == dest.Host { + return true, nil + } + } + + return false, nil + } + + if len(failed) == 0 { + return true, nil + } + + connectErr := dest.Connect(ctx, false) + if connectErr != nil && !errors.Is(connectErr, sshmux.ErrSignIn) { + return true, fmt.Errorf("restore connection: %w", connectErr) + } + + // Other clients may have exited or moved during the handshake. + panes, err = tmux.Attachments(ctx, "") + if err != nil { + return false, fmt.Errorf("inspect remote panes: %w", err) + } + + _, failed = interrupted(panes, dest.Host) + if connectErr != nil { + for _, p := range failed { + _ = p.RequireSignIn(ctx) + } + + return true, fmt.Errorf("restore connection: %w", connectErr) + } + + generation := dest.Generation() + if generation == "" { + return true, fmt.Errorf("%w: missing SSH master", os.ErrNotExist) + } + + for _, p := range failed { + if p.Connection == generation { + // A channel can fail independently, e.g. at MaxSessions. + continue + } + + if err := p.Resume(ctx, helper, "--remote-pane", p.Terminal); err != nil { + return true, fmt.Errorf("resume pane %s: %w", p.ID, err) + } + } + + return true, nil +} + +func interrupted(panes map[string]tmux.Attachment, host string) (bool, []tmux.Attachment) { + active := false + + var failed []tmux.Attachment + + for _, p := range panes { + if p.Host != host || !terminalID.MatchString(p.Terminal) { + continue + } + + active = true + + if p.Dead && p.ExitStatus == "255" { + failed = append(failed, p) + } + } + + return active, failed +} diff --git a/tools/internal/codex/client.go b/tools/internal/codex/client.go index 608ee43c..b47e3236 100644 --- a/tools/internal/codex/client.go +++ b/tools/internal/codex/client.go @@ -1,18 +1,22 @@ -// Package codex provides a client for the local Codex app server. +// Package codex reads status and activity from a Codex app server. package codex import ( "context" "encoding/json" "fmt" + "io" "net" "net/http" "os" + "os/exec" "path/filepath" "time" "github.com/coder/websocket" "github.com/coder/websocket/wsjson" + + "github.com/ddeville/scripts/tools/internal/sshmux" ) // RPCError is an error returned by the app server. @@ -22,14 +26,13 @@ type RPCError struct { func (e *RPCError) Error() string { return e.Message } -// Client sends sequential requests over a local app-server connection. +// Client sends sequential requests over an app-server connection. type Client struct { conn *websocket.Conn id int } -// Connect opens and initializes an app-server connection. -func Connect(ctx context.Context) (*Client, error) { +func dialLocal(ctx context.Context) (net.Conn, error) { home := os.Getenv("CODEX_HOME") if home == "" { userHome, err := os.UserHomeDir() @@ -42,8 +45,59 @@ func Connect(ctx context.Context) (*Client, error) { socket := filepath.Join(home, "app-server-control", "app-server-control.sock") + conn, err := (&net.Dialer{}).DialContext(ctx, "unix", socket) + if err != nil { + return nil, fmt.Errorf("open control socket: %w", err) + } + + return conn, nil +} + +// Keep the full control socket off the local filesystem. Only this process +// holds the proxy channel, which carries the same WebSocket as the local socket. +func dialRemote(ctx context.Context, host string) (net.Conn, error) { + dest, err := sshmux.ForHost(host) + if err != nil { + return nil, fmt.Errorf("find SSH connection: %w", err) + } + + // The WebSocket can outlive the HTTP handshake. Closing the pipe ends ssh. + cmd := exec.CommandContext(context.WithoutCancel(ctx), "ssh", dest.Channel("-T", "exec codex app-server proxy")...) // #nosec G204 -- Fixed command on a validated, existing master. + + stdin, err := cmd.StdinPipe() + if err != nil { + return nil, fmt.Errorf("open proxy stdin: %w", err) + } + + local, peer := net.Pipe() + + cmd.Stdout = peer + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("start Codex proxy: %w", err) + } + + go func() { + _, _ = io.Copy(stdin, peer) + _ = stdin.Close() + _ = cmd.Process.Kill() + }() + + go func() { + _ = cmd.Wait() + _ = peer.Close() + }() + + return local, nil +} + +// Connect opens the local app server or the one on an existing SSH destination. +func Connect(ctx context.Context, host string) (*Client, error) { transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { - return (&net.Dialer{}).DialContext(ctx, "unix", socket) + if host != "" { + return dialRemote(ctx, host) + } + + return dialLocal(ctx) }} defer transport.CloseIdleConnections() @@ -54,6 +108,10 @@ func Connect(ctx context.Context) (*Client, error) { HTTPClient: &http.Client{Transport: transport}, }) if err != nil { + if host != "" { + return nil, fmt.Errorf("proxy unavailable (check Codex and SSH MaxSessions): %w", err) + } + return nil, fmt.Errorf("connect to Codex: %w", err) } diff --git a/tools/internal/sshmux/ssh.go b/tools/internal/sshmux/ssh.go new file mode 100644 index 00000000..bd0407dc --- /dev/null +++ b/tools/internal/sshmux/ssh.go @@ -0,0 +1,160 @@ +// Package sshmux shares a private OpenSSH master between tmux panes and agent queries. +package sshmux + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strconv" + "strings" + "syscall" + "time" +) + +// Destination identifies a master by its exact SSH destination. +type Destination struct { + Host, Socket string +} + +var ( + sshHost = regexp.MustCompile(`^[a-zA-Z0-9_@.%+:/\[\]-]+$`) + // ErrChannelRefused indicates that the master cannot open another session. + ErrChannelRefused = errors.New("SSH session channel refused (check sshd MaxSessions)") + // ErrSignIn stops automatic retries until the user explicitly runs tm again. + ErrSignIn = errors.New("SSH requires attention") +) + +// ForHost resolves the private control socket without opening a connection. +func ForHost(host string) (Destination, error) { + if !sshHost.MatchString(host) || strings.HasPrefix(host, "-") { + return Destination{}, fmt.Errorf("%w: invalid SSH destination %q", os.ErrInvalid, host) + } + + dir, err := CacheDir() + if err != nil { + return Destination{}, err + } + + info, err := os.Lstat(dir) + if err != nil { + return Destination{}, 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 Destination{}, fmt.Errorf("%w: SSH socket directory %s must be private", os.ErrPermission, dir) + } + + sum := sha256.Sum256([]byte(host)) + + return Destination{Host: host, Socket: filepath.Join(dir, fmt.Sprintf("ssh-%x", sum[:10]))}, nil +} + +// Generation distinguishes old attachments from channels refused by a healthy +// master. OpenSSH creates a new socket for each connection. +func (d Destination) Generation() string { + info, err := os.Stat(d.Socket) + if err != nil { + return "" + } + + return strconv.FormatInt(info.ModTime().UnixNano(), 10) +} + +// Connect must be serialized by destination. Only an explicit open can prompt +// for credentials or ask about a host key. +func (d Destination) Connect(ctx context.Context, interactive bool) error { + if exec.CommandContext(ctx, "ssh", "-S", d.Socket, "-O", "check", "--", d.Host).Run() == nil { // #nosec G204 -- The validated destination follows --. + return nil + } + + args := []string{ + "-S", d.Socket, "-fN", "-oControlMaster=auto", "-oControlPersist=60", + "-oRemoteCommand=none", "-oConnectTimeout=10", "-oServerAliveInterval=5", "-oServerAliveCountMax=2", + } + if !interactive { + args = append(args, "-oBatchMode=yes", "-oStrictHostKeyChecking=yes") + } + + cmd := exec.CommandContext(ctx, "ssh", append(args, "--", d.Host)...) // #nosec G204 -- The validated destination follows --. + if interactive { + cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("connect to %s: %w", d.Host, err) + } + + return nil + } + + cmd.WaitDelay = time.Second + if _, err := cmd.Output(); err != nil && !errors.Is(err, exec.ErrWaitDelay) { + var exit *exec.ExitError + if errors.As(err, &exit) && needsSignIn(string(exit.Stderr)) { + return fmt.Errorf("%w on %s", ErrSignIn, d.Host) + } + + return fmt.Errorf("connect to %s: %w", d.Host, err) + } + + return nil +} + +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 Destination) Channel(tty, command string) []string { + return []string{ + "-S", d.Socket, "-oControlMaster=no", "-oProxyCommand=false", "-oBatchMode=yes", + "-oClearAllForwardings=yes", "-oRemoteCommand=none", "-oLogLevel=ERROR", "-e", "none", tty, "--", d.Host, command, + } +} + +// Query runs one non-interactive command with a deadline. +func (d Destination) 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 { + var exit *exec.ExitError + if errors.As(err, &exit) && len(exit.Stderr) != 0 { + if exit.ExitCode() == 255 && strings.Contains(string(exit.Stderr), "Session open refused") { + return "", fmt.Errorf("%w on %s", ErrChannelRefused, d.Host) + } + + return "", fmt.Errorf("SSH %s: %w: %s", d.Host, err, strings.TrimSpace(string(exit.Stderr))) + } + + return "", fmt.Errorf("SSH %s: %w", d.Host, err) + } + + return string(out), nil +} + +// 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) + } + + return dir, nil +} diff --git a/tools/internal/tmux/command.go b/tools/internal/tmux/command.go index 2829ded6..01f4092c 100644 --- a/tools/internal/tmux/command.go +++ b/tools/internal/tmux/command.go @@ -54,6 +54,16 @@ func appendCommand(args, command []string) []string { 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/panes.go b/tools/internal/tmux/panes.go index 64355602..0b672b58 100644 --- a/tools/internal/tmux/panes.go +++ b/tools/internal/tmux/panes.go @@ -28,24 +28,32 @@ func SingleClient(ctx context.Context) (string, error) { // Pane describes a pane's session, foreground command, and terminal title. type Pane struct { - ID string - SessionNumber int - Command string - Title string + ID, PID string + Host, Terminal string + Dead bool + SessionNumber int + Command string + Title string } // ListPanes lists panes across all sessions in the current server. func ListPanes(ctx context.Context) ([]Pane, error) { - output, err := run(ctx, "-u", "list-panes", "-a", "-F", "#{pane_id}\t#{session_id}\t#{pane_current_command}\t#{pane_title}") + // Titles come from programs, including remote ones. Keep control characters + // out of the record delimiters before tmux writes the listing. + const format = "#{pane_id}\t#{session_id}\t#{pane_pid}\t#{pane_dead}\t#{@tm_host}\t#{@tm_terminal}\t#{pane_current_command}\t#{s/[\x01-\x1f]/_/:pane_title}" + + output, err := run(ctx, "-u", "list-panes", "-a", "-F", format) if err != nil { return nil, fmt.Errorf("read tmux panes: %w", err) } var panes []Pane - for line := range strings.SplitSeq(strings.TrimSpace(output), "\n") { - fields := strings.SplitN(line, "\t", 4) - if len(fields) != 4 { + seen := make(map[string]int) + + for line := range strings.Lines(output) { + fields := strings.Split(strings.TrimSuffix(line, "\n"), "\t") + if len(fields) != 8 { continue } @@ -54,13 +62,51 @@ func ListPanes(ctx context.Context) ([]Pane, error) { continue } - panes = append(panes, Pane{ID: fields[0], SessionNumber: sessionNumber, Command: fields[2], Title: fields[3]}) + if i, ok := seen[fields[0]]; ok { + panes[i].SessionNumber = min(panes[i].SessionNumber, sessionNumber) + continue + } + + seen[fields[0]] = len(panes) + panes = append(panes, Pane{ + ID: fields[0], SessionNumber: sessionNumber, PID: fields[2], Dead: fields[3] == "1", + Host: fields[4], Terminal: fields[5], Command: fields[6], Title: fields[7], + }) } return panes, nil } -// SwitchPane selects a pane for the given client, or the current client if empty. -func SwitchPane(ctx context.Context, pane, client string) error { - return switchClient(ctx, pane, client) +// Switch checks the process and final " | " title field in the same command +// queue that switches clients. Earlier fields can change with each TUI redraw. +func (p Pane) Switch(ctx context.Context, client, titleField string) error { + if client == "" { + var err error + + client, err = SingleClient(ctx) + if err != nil { + return err + } + } + + const view = "#{pane_id}\t#{pane_pid}\t#{pane_dead}\t#{@tm_host}\t#{@tm_terminal}\t#{pane_current_command}\t#{s/^.* [|] //:pane_title}" + + expected := strings.Join([]string{p.ID, p.PID, "0", p.Host, p.Terminal, p.Command, titleField}, "\t") + escape := strings.NewReplacer("#", "#{a:35}", ",", "#{a:44}", "}", "#{a:125}") + same := "#{==:" + view + "," + escape.Replace(expected) + "}" + + command := commandLine("switch-client", "-t", p.ID, "-c", client) + + out, err := run(ctx, "if-shell", "-F", "-t", p.ID, same, command, "display-message -p changed") + if err != nil { + return err + } + + if out != "" { + return errPaneChanged + } + + return nil } + +var errPaneChanged = errors.New("selected pane changed") diff --git a/tools/internal/tmux/remote.go b/tools/internal/tmux/remote.go index 9c7b2c18..08d5bdcd 100644 --- a/tools/internal/tmux/remote.go +++ b/tools/internal/tmux/remote.go @@ -5,11 +5,18 @@ import ( "fmt" "os" "strings" + "time" ) // RemoteEnv identifies a remote session and supplies the workspace to new panes. const RemoteEnv = "TM_REMOTE_WORKSPACE" +// SocketPath identifies the local server, even when opened from outside tmux. +func SocketPath(ctx context.Context) (string, error) { + out, err := run(ctx, "display-message", "-p", "#{socket_path}") + return strings.TrimSuffix(out, "\n"), err +} + // 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) { @@ -30,16 +37,17 @@ func NewRemoteSession(ctx context.Context, s Session, window, defaultCommand str // Attachment identifies a local pane and the remote terminal it owns, if any. type Attachment struct { - ID, WindowID string - Host, Terminal string - Dead bool - server string + ID, WindowID string + Host, Terminal string + Dead bool + ExitStatus, Connection 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_terminal}\t#{pid}" + const format = "#{pane_id}\t#{window_id}\t#{pane_dead}\t#{@tm_host}\t#{@tm_terminal}\t#{pid}\t#{pane_dead_status}\t#{@tm_connection}" args := []string{"list-panes", "-F", format} if target == "" { @@ -57,11 +65,14 @@ func Attachments(ctx context.Context, target string) (map[string]Attachment, err for line := range strings.Lines(out) { fields := strings.Split(strings.TrimSuffix(line, "\n"), "\t") - if len(fields) != 6 { + if len(fields) != 8 { 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], Terminal: fields[4], server: fields[5]} + p := Attachment{ + ID: fields[0], WindowID: fields[1], Dead: fields[2] == "1", Host: fields[3], + Terminal: fields[4], server: fields[5], ExitStatus: fields[6], Connection: fields[7], + } panes[p.ID] = p } @@ -70,26 +81,38 @@ func Attachments(ctx context.Context, target string) (map[string]Attachment, err // Record pins a terminal to this pane, even across moves and respawns. func (p Attachment) Record(ctx context.Context, project string) error { - const message = "#{?#{==:#{pane_dead_status},255},SSH disconnected · rerun tm for #{@tm_host},Remote terminal exited or unavailable}" + const message = "#{?#{==:#{pane_dead_status},255},SSH disconnected · rerun tm for #{@tm_host} if recovery stalls,Remote terminal exited or unavailable}" - _, err := run(ctx, "set-option", "-p", "-t", p.ID, "@tm_host", literalArg(p.Host), ";", - "set-option", "-p", "-t", p.ID, "@tm_project", literalArg(project), ";", - "set-option", "-p", "-t", p.ID, "@tm_terminal", literalArg(p.Terminal), ";", + args := []string{ + "set-option", "-p", "-t", p.ID, "@tm_connection", p.Connection, ";", + "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) + "set-option", "-p", "-t", p.ID, "remain-on-exit-format", message, + } + if project != "" { + args = append(args, ";", "set-option", "-p", "-t", p.ID, "@tm_host", literalArg(p.Host), ";", + "set-option", "-p", "-t", p.ID, "@tm_project", literalArg(project), ";", + "set-option", "-p", "-t", p.ID, "@tm_terminal", literalArg(p.Terminal)) + } + + _, 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") +} + // 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 { - _, err := run(ctx, appendCommand([]string{"respawn-pane", "-t", p.ID}, command)...) - return err + return p.change(ctx, "respawn-pane -t "+p.ID+" "+commandLine(command...)) } // Disconnect stops just the local client and keeps the failed pane for retry. func (p Attachment) Disconnect(ctx context.Context) error { - return p.change(ctx, "respawn-pane -k -t "+p.ID+" /bin/sh -c 'exit 255'") + return p.change(ctx, "respawn-pane -k -t "+p.ID+" /bin/sh -c 'exit 1'") } // KillPane removes this pane from its local window. @@ -107,8 +130,22 @@ func (p Attachment) change(ctx context.Context, command string) error { } if out != "" { - return fmt.Errorf("%w: pane %s changed during close", os.ErrInvalid, p.ID) + return fmt.Errorf("%w: pane %s changed", os.ErrInvalid, p.ID) } return nil } + +// WaitPaneDeath wakes on a retained pane exit or periodically to catch removed +// panes and events missed during recovery. No SSH probe is needed while idle. +func WaitPaneDeath(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + + _, err := run(ctx, "wait-for", "-E", "pane-died") + if ctx.Err() != nil { + return nil + } + + return err +} From e1123cb09114515b8a7148ae3483be01ccb0ba62 Mon Sep 17 00:00:00 2001 From: Damien Deville Date: Mon, 23 Nov 2026 21:37:23 -0800 Subject: [PATCH 3/6] Setup SSH connection in supervisor process --- tools/cmd/tmux-session/REMOTE-WORKSPACES.md | 17 +- tools/cmd/tmux-session/remote.go | 30 +--- tools/cmd/tmux-session/supervisor.go | 166 ++++++++++++++++---- tools/internal/sshmux/ssh.go | 41 ++--- tools/internal/sshmux/ssh_test.go | 37 +++++ 5 files changed, 208 insertions(+), 83 deletions(-) create mode 100644 tools/internal/sshmux/ssh_test.go diff --git a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md index 3a2b1f42..87108829 100644 --- a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md +++ b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md @@ -15,12 +15,17 @@ connection. Use the same SSH alias across projects. Each pane uses one of sshd's `MaxSessions` slots. Leave room for discovery and one channel per open agent popup. A full connection never falls back to a second login. -- **Reconnect** happens automatically. The first `tm` can prompt for sign-in. - Each local tmux server runs one supervisor per destination. It retries a lost - connection with backoff and reattaches surviving terminals in place, including - moved panes. Input typed into a dead pane is discarded. Programs that ended - stay closed. If SSH needs attention or recovery stalls, rerun `tm --host …` - from a local shell. Automatic retries never prompt or accept new host keys. +- **Connect** with a trusted SSH host key and a working agent. The supervisor + opens the first connection before creating any panes. All 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 + records the current `SSH_AUTH_SOCK` path in the private destination lock + file for future reconnects. Login does not require agent forwarding. +- **Reconnect** happens automatically. Each local tmux server keeps one + supervisor per destination. It retries with backoff and reattaches surviving + terminals in place, including moved panes. 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. diff --git a/tools/cmd/tmux-session/remote.go b/tools/cmd/tmux-session/remote.go index 95a097ab..0e837f5d 100644 --- a/tools/cmd/tmux-session/remote.go +++ b/tools/cmd/tmux-session/remote.go @@ -108,26 +108,7 @@ cd -P -- "$1" printf '%s\000' "$PWD" ` + listTerminals -func openRemote(ctx context.Context, host, request, name string) (tmux.Session, bool, error) { - if request == "" { - return tmux.Session{}, false, fmt.Errorf("%w: empty remote path", os.ErrInvalid) - } - - dest, err := sshmux.ForHost(host) - if err != nil { - return tmux.Session{}, false, fmt.Errorf("find connection: %w", err) - } - - lock, err := lockFile(dest.Socket + ".lock") - if err != nil { - return tmux.Session{}, false, err - } - defer func() { _ = lock.Close() }() - - if err := dest.Connect(ctx, true); err != nil { - return tmux.Session{}, false, fmt.Errorf("open connection: %w", err) - } - +func openWorkspace(ctx context.Context, dest sshmux.Destination, request, name string) (tmux.Session, bool, error) { if request == "~" { request = "." } @@ -151,14 +132,9 @@ func openRemote(ctx context.Context, host, request, name string) (tmux.Session, return tmux.Session{}, false, err } - w := workspace{Host: host, Path: dir, Name: cmp.Or(name, path.Base(dir))} - - target, created, err := w.open(ctx, names) - if err == nil { - err = startSupervisor(ctx, dest) - } + w := workspace{Host: dest.Host, Path: dir, Name: cmp.Or(name, path.Base(dir))} - return target, created, err + return w.open(ctx, names) } // Pane names and positions are mutable. Only a terminal ID can identify a diff --git a/tools/cmd/tmux-session/supervisor.go b/tools/cmd/tmux-session/supervisor.go index b1e3fec9..d51f6379 100644 --- a/tools/cmd/tmux-session/supervisor.go +++ b/tools/cmd/tmux-session/supervisor.go @@ -1,11 +1,13 @@ package main import ( + "bytes" "context" "crypto/sha256" "encoding/json" "errors" "fmt" + "io" "os" "os/exec" "syscall" @@ -15,14 +17,72 @@ import ( "github.com/ddeville/scripts/tools/internal/tmux" ) -// The foreground open owns interactive authentication. Hand off the lifetime -// lock on stdin so the supervisor survives the caller without a PID file. -func startSupervisor(ctx context.Context, dest sshmux.Destination) error { - // Different local tmux servers share the master, but cannot see each - // other's panes or events. +// A single reply covers SSH, discovery, layout and watcher election. No tmux +// server needs to exist until the remote directory has been verified. +type openResult struct { + Session tmux.Session `json:"session"` + Created bool `json:"created"` + Error string `json:"error,omitempty"` +} + +func openRemote(ctx context.Context, host, path, name string) (tmux.Session, bool, error) { + if host == "" || path == "" { + return tmux.Session{}, false, fmt.Errorf("%w: expected an SSH host and remote path", os.ErrInvalid) + } + + helper, err := os.Executable() + if err != nil { + return tmux.Session{}, false, fmt.Errorf("locate tmux-session: %w", err) + } + + request, err := json.Marshal(workspace{Path: path, Name: name}) + if err != nil { + return tmux.Session{}, false, fmt.Errorf("encode workspace request: %w", err) + } + + cmd := exec.CommandContext(context.WithoutCancel(ctx), helper, "--supervise="+host) // #nosec G204 -- Re-exec this binary. ForHost validates the destination before SSH. + cmd.Stdin = bytes.NewReader(request) + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + + reply, err := cmd.StdoutPipe() + if err != nil { + return tmux.Session{}, false, fmt.Errorf("open supervisor pipe: %w", err) + } + + if err := cmd.Start(); err != nil { + return tmux.Session{}, false, fmt.Errorf("start supervisor: %w", err) + } + + // Cancellation belongs to the caller until startup has completed. + stop := context.AfterFunc(ctx, func() { _ = cmd.Process.Signal(syscall.SIGTERM) }) + + var result openResult + + err = json.NewDecoder(reply).Decode(&result) + + stop() + + _ = reply.Close() + + go func() { _ = cmd.Wait() }() + + if err != nil { + return tmux.Session{}, false, fmt.Errorf("wait for supervisor: %w", err) + } + + if result.Error != "" { + return tmux.Session{}, false, errors.New(result.Error) //nolint:err113 // The child sends the original diagnostic. + } + + return result.Session, result.Created, nil +} + +// Only one process watches a given server and destination. Other explicit +// opens can reuse the master or retry immediately during backoff. +func watchLock(ctx context.Context, dest sshmux.Destination) (*os.File, error) { socket, err := tmux.SocketPath(ctx) if err != nil { - return fmt.Errorf("identify tmux server: %w", err) + return nil, fmt.Errorf("identify tmux server: %w", err) } server := sha256.Sum256([]byte(socket)) @@ -30,44 +90,83 @@ func startSupervisor(ctx context.Context, dest sshmux.Destination) error { lock, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0o600) // #nosec G304 -- Private per-destination directory. if err != nil { - return fmt.Errorf("open supervisor lock: %w", err) + return nil, fmt.Errorf("open supervisor lock: %w", err) } - defer func() { _ = lock.Close() }() + if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + _ = lock.Close() + return nil, fmt.Errorf("lock supervisor: %w", err) + } - err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) - if errors.Is(err, syscall.EWOULDBLOCK) { - return nil + return lock, nil +} + +func supervise(ctx context.Context, host string) error { + var result openResult + + dest, err := sshmux.ForHost(host) + + var watch *os.File + if err == nil { + watch, err = prepare(ctx, dest, &result) } if err != nil { - return fmt.Errorf("lock supervisor: %w", err) + result.Error = err.Error() } - helper, err := os.Executable() - if err != nil { - return fmt.Errorf("locate tmux-session: %w", err) + if err := json.NewEncoder(os.Stdout).Encode(result); err != nil { + return fmt.Errorf("notify caller: %w", err) } - cmd := exec.CommandContext(context.WithoutCancel(ctx), helper, "--supervise", dest.Host) // #nosec G204 -- Re-exec this binary with a validated destination. - cmd.Stdin = lock + if watch == nil { + return nil + } + defer func() { _ = watch.Close() }() - cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} - if err := cmd.Start(); err != nil { - return fmt.Errorf("start supervisor: %w", err) + return watchPanes(ctx, dest, watch) +} + +func prepare(ctx context.Context, dest sshmux.Destination, result *openResult) (*os.File, error) { + var w workspace + if err := json.NewDecoder(os.Stdin).Decode(&w); err != nil { + return nil, fmt.Errorf("read workspace request: %w", err) } - go func() { _ = cmd.Wait() }() + lock, err := lockFile(dest.Socket + ".lock") + if err != nil { + return nil, err + } + defer func() { _ = lock.Close() }() - return nil -} + agent := os.Getenv("SSH_AUTH_SOCK") + if err := dest.Connect(ctx, agent); err != nil { + return nil, fmt.Errorf("SSH: %w", err) + } -func supervise(ctx context.Context, host string) error { - dest, err := sshmux.ForHost(host) + result.Session, result.Created, err = openWorkspace(ctx, dest, w.Path, w.Name) if err != nil { - return fmt.Errorf("find connection: %w", err) + return nil, err + } + + // A successful open refreshes the agent path for the next reconnect. + if err := lock.Truncate(0); err != nil { + return nil, fmt.Errorf("update SSH agent socket: %w", err) + } + + if _, err := lock.WriteString(agent); err != nil { + return nil, fmt.Errorf("save SSH agent socket: %w", err) } + watch, err := watchLock(ctx, dest) + if errors.Is(err, syscall.EWOULDBLOCK) { + return nil, nil //nolint:nilnil // This open succeeded and another process owns the watcher. + } + + return watch, err +} + +func watchPanes(ctx context.Context, dest sshmux.Destination, watch *os.File) error { helper, err := os.Executable() if err != nil { return fmt.Errorf("locate tmux-session: %w", err) @@ -82,12 +181,12 @@ func supervise(ctx context.Context, host string) error { return err } - active, err := recoverPanes(ctx, dest, helper) + active, err := recoverPanes(ctx, dest, helper, lock) done := !active || errors.Is(err, sshmux.ErrSignIn) if done { - // Let a waiting interactive open start a new supervisor. - _ = os.Stdin.Close() + // Let the next open take over before releasing the destination lock. + _ = watch.Close() } _ = lock.Close() @@ -118,7 +217,7 @@ func supervise(ctx context.Context, host string) error { return nil } -func recoverPanes(ctx context.Context, dest sshmux.Destination, helper string) (bool, error) { +func recoverPanes(ctx context.Context, dest sshmux.Destination, helper string, lock *os.File) (bool, error) { ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() @@ -150,7 +249,12 @@ func recoverPanes(ctx context.Context, dest sshmux.Destination, helper string) ( return true, nil } - connectErr := dest.Connect(ctx, false) + agent, err := io.ReadAll(lock) + if err != nil { + return true, fmt.Errorf("read SSH agent socket: %w", err) + } + + connectErr := dest.Connect(ctx, string(agent)) if connectErr != nil && !errors.Is(connectErr, sshmux.ErrSignIn) { return true, fmt.Errorf("restore connection: %w", connectErr) } diff --git a/tools/internal/sshmux/ssh.go b/tools/internal/sshmux/ssh.go index bd0407dc..1bbc4e47 100644 --- a/tools/internal/sshmux/ssh.go +++ b/tools/internal/sshmux/ssh.go @@ -66,36 +66,39 @@ func (d Destination) Generation() string { return strconv.FormatInt(info.ModTime().UnixNano(), 10) } -// Connect must be serialized by destination. Only an explicit open can prompt -// for credentials or ask about a host key. -func (d Destination) Connect(ctx context.Context, interactive bool) error { +// Connect starts or reuses the master under the destination lock. Let OpenSSH +// select the agent and identities from the caller's environment and config. +func (d Destination) Connect(ctx context.Context, agent string) error { + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + if exec.CommandContext(ctx, "ssh", "-S", d.Socket, "-O", "check", "--", d.Host).Run() == nil { // #nosec G204 -- The validated destination follows --. return nil } - args := []string{ + 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", - } - if !interactive { - args = append(args, "-oBatchMode=yes", "-oStrictHostKeyChecking=yes") - } - - cmd := exec.CommandContext(ctx, "ssh", append(args, "--", d.Host)...) // #nosec G204 -- The validated destination follows --. - if interactive { - cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr - if err := cmd.Run(); err != nil { - return fmt.Errorf("connect to %s: %w", d.Host, err) - } - - return nil + "-oBatchMode=yes", "-oStrictHostKeyChecking=yes", "--", d.Host) + 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) && needsSignIn(string(exit.Stderr)) { - return fmt.Errorf("%w on %s", ErrSignIn, d.Host) + 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) diff --git a/tools/internal/sshmux/ssh_test.go b/tools/internal/sshmux/ssh_test.go new file mode 100644 index 00000000..020beea6 --- /dev/null +++ b/tools/internal/sshmux/ssh_test.go @@ -0,0 +1,37 @@ +package sshmux_test + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/ddeville/scripts/tools/internal/sshmux" +) + +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") + + dest := sshmux.Destination{Host: "devbox", Socket: filepath.Join(dir, "master")} + + err := dest.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) + } +} From 8ee4d5f3a6e5164e6e57fa992648b80af0419dbf Mon Sep 17 00:00:00 2001 From: Damien Deville Date: Tue, 24 Nov 2026 07:31:37 -0800 Subject: [PATCH 4/6] Reserve SSH capacity for tmux management and retry interrupted recovery --- tools/cmd/tmux-agent-status/agents/source.go | 70 ++++++++- tools/cmd/tmux-session/REMOTE-WORKSPACES.md | 19 ++- tools/cmd/tmux-session/launch.go | 151 +++++++++++++++++++ tools/cmd/tmux-session/main.go | 15 +- tools/cmd/tmux-session/pane.go | 91 +++++++++-- tools/cmd/tmux-session/remote.go | 98 ++++++++---- tools/cmd/tmux-session/remote_test.go | 113 ++++++++++++++ tools/cmd/tmux-session/supervisor.go | 51 +++++-- tools/internal/codex/client.go | 32 +++- tools/internal/sshmux/capacity.go | 107 +++++++++++++ tools/internal/sshmux/lock.go | 85 +++++++++++ tools/internal/sshmux/ssh.go | 25 ++- tools/internal/sshmux/ssh_test.go | 36 +++++ tools/internal/tmux/remote.go | 25 ++- tools/internal/tmux/sessions.go | 7 +- 15 files changed, 837 insertions(+), 88 deletions(-) create mode 100644 tools/cmd/tmux-session/launch.go create mode 100644 tools/internal/sshmux/capacity.go create mode 100644 tools/internal/sshmux/lock.go diff --git a/tools/cmd/tmux-agent-status/agents/source.go b/tools/cmd/tmux-agent-status/agents/source.go index 022f30bd..7d06d58a 100644 --- a/tools/cmd/tmux-agent-status/agents/source.go +++ b/tools/cmd/tmux-agent-status/agents/source.go @@ -4,9 +4,12 @@ import ( "context" "errors" "fmt" + "os" "sync" + "time" "github.com/ddeville/scripts/tools/internal/codex" + "github.com/ddeville/scripts/tools/internal/sshmux" ) // Source shares one sequential app-server connection across status, activity, @@ -16,6 +19,7 @@ type Source struct { mu sync.Mutex client *codex.Client + slot *os.File } func (s *Source) use(ctx context.Context, read func(*codex.Client) error) error { @@ -27,32 +31,84 @@ func (s *Source) use(ctx context.Context, read func(*codex.Client) error) error } if s.client == nil { - client, err := codex.Connect(ctx, s.Host) - if err != nil { - return fmt.Errorf("connect to app server: %w", err) + if err := s.connect(ctx); err != nil { + return err } - - s.client = client } err := read(s.client) var rpcErr *codex.RPCError if err != nil && !errors.As(err, &rpcErr) { - s.client.Close() - s.client = nil + s.close() } return err } +func (s *Source) connect(ctx context.Context) error { + if s.Host != "" { + dest, err := sshmux.ForHost(s.Host) + if err != nil { + return fmt.Errorf("find SSH connection: %w", err) + } + + s.slot, err = dest.ProxySlot(ctx) + if err != nil { + return fmt.Errorf("wait for SSH slot: %w", err) + } + + go s.yield(dest, s.slot) + } + + client, err := codex.Connect(ctx, s.Host) + if err != nil { + s.close() + return fmt.Errorf("connect to app server: %w", err) + } + + s.client = client + + return nil +} + +// Keep the proxy warm between refreshes until another caller needs the slot. +// The mutex lets a request in flight finish before we return the channel. +func (s *Source) yield(dest sshmux.Destination, slot *os.File) { + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + + for range ticker.C { + s.mu.Lock() + if s.slot == slot && dest.Waiting() { + s.close() + } + + done := s.slot != slot + s.mu.Unlock() + + if done { + return + } + } +} + // Close releases the app-server connection and its SSH channel, if any. func (s *Source) Close() { s.mu.Lock() defer s.mu.Unlock() + s.close() +} + +func (s *Source) close() { if s.client != nil { s.client.Close() s.client = nil } + + if s.slot != nil { + _ = s.slot.Close() + s.slot = nil + } } diff --git a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md index 87108829..817c116b 100644 --- a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md +++ b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md @@ -11,9 +11,15 @@ 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. Sessions using the same SSH destination share one OpenSSH -connection. Use the same SSH alias across projects. Each pane uses one of sshd's -`MaxSessions` slots. Leave room for discovery and one channel per open agent -popup. A full connection never falls back to a second login. +connection. Use the same SSH alias across projects. + +Each pane uses one of sshd's `MaxSessions` slots. `tm` reserves one slot per +connection for discovery, closes and the agent popup. With a limit of 10, up +to nine panes can share the connection across projects and local tmux servers. +Startup checks capacity with short-lived SSH commands. A fresh workspace needs +room for all three windows. A rejected split closes with a tmux message. +The popup yields the slot between requests. A full connection never falls back +to a second login. - **Connect** with a trusted SSH host key and a working agent. The supervisor opens the first connection before creating any panes. All logins use batch @@ -23,9 +29,10 @@ popup. A full connection never falls back to a second login. file for future reconnects. Login does not require agent forwarding. - **Reconnect** happens automatically. Each local tmux server keeps one supervisor per destination. It retries with backoff and reattaches surviving - terminals in place, including moved panes. 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. + terminals in place, including moved panes. 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. diff --git a/tools/cmd/tmux-session/launch.go b/tools/cmd/tmux-session/launch.go new file mode 100644 index 00000000..b1509456 --- /dev/null +++ b/tools/cmd/tmux-session/launch.go @@ -0,0 +1,151 @@ +package main + +import ( + "context" + "crypto/rand" + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "time" + + "github.com/ddeville/scripts/tools/internal/sshmux" +) + +var errPaneLimit = errors.New("SSH pane limit") + +func capacityError(dest sshmux.Destination, want, free int) error { + return fmt.Errorf("%s: %w (need %d, free %d, 1 reserved for management)", dest.Host, errPaneLimit, want, free) +} + +// The local tmux server forks pane helpers asynchronously. Hold the destination +// lock until each helper confirms that its SSH session opened. +func launch(ctx context.Context, dest sshmux.Destination, count int, layout func(string) error) error { + if count == 0 { + return nil + } + + token := rand.Text()[:16] + socket := filepath.Join(filepath.Dir(dest.Socket), "open-"+token) + + listener, err := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: socket}) + if err != nil { + return fmt.Errorf("listen for pane startup: %w", err) + } + defer func() { _ = listener.Close() }() + + if err := layout(token); err != nil { + return err + } + + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + + stop := context.AfterFunc(ctx, func() { _ = listener.Close() }) + defer stop() + + var panes []net.Conn + + for range count { + conn, err := listener.Accept() + if err != nil { + return fmt.Errorf("wait for local panes: %w", err) + } + + panes = append(panes, conn) + defer func() { _ = conn.Close() }() + } + + for _, conn := range panes { + if _, err := conn.Write([]byte{'+'}); err != nil { + return fmt.Errorf("start pane: %w", err) + } + } + + for _, conn := range panes { + if err := ready(ctx, conn); err != nil { + return fmt.Errorf("SSH pane did not start: %w", err) + } + } + + return nil +} + +func ready(ctx context.Context, conn net.Conn) error { + stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) + defer stop() + + var reply [1]byte + if _, err := io.ReadFull(conn, reply[:]); err != nil { + return fmt.Errorf("wait for startup: %w", err) + } + + if reply[0] != '+' { + return fmt.Errorf("%w: unexpected startup reply", os.ErrInvalid) + } + + return nil +} + +// A split or raw respawn has no supervisor waiting for it. Check capacity +// under the same lock, releasing it once SSH opens or the helper fails. +func admit(ctx context.Context, dest sshmux.Destination, token string) (func(bool), error) { + if token != "" && token == filepath.Base(token) { + socket := filepath.Join(filepath.Dir(dest.Socket), "open-"+token) + + hold, err := dest.Hold(ctx) + if err != nil { + return nil, fmt.Errorf("hold pane slot: %w", err) + } + + conn, err := (&net.Dialer{}).DialContext(ctx, "unix", socket) + if err != nil { + _ = hold.Close() + return nil, fmt.Errorf("contact pane supervisor: %w", err) + } + + if err := ready(ctx, conn); err != nil { + _ = hold.Close() + _ = conn.Close() + + return nil, err + } + + return func(open bool) { + _ = hold.Close() + + if open { + _, _ = conn.Write([]byte{'+'}) + } + + _ = conn.Close() + }, nil + } + + lock, err := dest.Lock(ctx) + if err != nil { + return nil, fmt.Errorf("lock destination: %w", err) + } + + if err := requireCapacity(ctx, dest, 1); err != nil { + _ = lock.Close() + return nil, err + } + + return func(bool) { _ = lock.Close() }, nil +} + +func requireCapacity(ctx context.Context, dest sshmux.Destination, want int) error { + free, err := dest.Capacity(ctx, want) + if err != nil { + return fmt.Errorf("check SSH capacity: %w", err) + } + + if free < want { + return capacityError(dest, want, free) + } + + return nil +} diff --git a/tools/cmd/tmux-session/main.go b/tools/cmd/tmux-session/main.go index 057f7d93..c7cf9d84 100644 --- a/tools/cmd/tmux-session/main.go +++ b/tools/cmd/tmux-session/main.go @@ -23,9 +23,9 @@ func main() { func command() *cobra.Command { var ( - name, host, watch string - launch, closeTarget string - noSwitch bool + name, host, watch string + launch, batch, closeTarget string + noSwitch bool ) cmd := &cobra.Command{ @@ -42,7 +42,12 @@ func command() *cobra.Command { } if launch != "" { - return attachPane(cmd.Context(), launch) + code, err := attachPane(cmd.Context(), launch, batch) + if err != nil { + cmd.PrintErrln(tui.CleanLine(err.Error())) + } + + os.Exit(code) } if closeTarget != "" { @@ -95,6 +100,8 @@ func command() *cobra.Command { 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(&batch, "pane-batch", "", "confirm startup with the supervisor") + cmd.Flags().Lookup("pane-batch").Hidden = true cmd.Flags().StringVar(&watch, "supervise", "", "supervise a remote connection") cmd.Flags().Lookup("supervise").Hidden = true cmd.Flags().StringVar(&closeTarget, "remote-close", "", "close a pane or window by ID") diff --git a/tools/cmd/tmux-session/pane.go b/tools/cmd/tmux-session/pane.go index ddf31e38..f4ae1790 100644 --- a/tools/cmd/tmux-session/pane.go +++ b/tools/cmd/tmux-session/pane.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "crypto/rand" "encoding/json" @@ -13,35 +14,46 @@ import ( "strconv" "strings" "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 if [ "$1" = resume ]; then zmx get "$2" >/dev/null + printf '\000' # If it exits between get and attach, zmx must never relaunch its program. exec zmx attach "$2" /bin/sh -c 'exit 1' fi cd -P -- "$3" +printf '\000' case "$1" in editor) exec zmx attach "$2" sh -c "exec ${EDITOR:-nvim}" ;; codex) exec zmx attach "$2" codex ;; *) exec zmx attach "$2" ;; esac` -func attachPane(ctx context.Context, requested string) error { +func attachPane(ctx context.Context, requested, batch string) (int, error) { + // Until an existing terminal can be reattached, keep a setup failure + // retryable on its original SSH generation. + failure := 1 + if terminalID.MatchString(requested) { + failure = 255 + } + id := os.Getenv("TMUX_PANE") panes, err := tmux.Attachments(ctx, id) if err != nil { - return fmt.Errorf("find attachment: %w", err) + return failure, fmt.Errorf("find attachment: %w", err) } p, ok := panes[id] if !ok { - return fmt.Errorf("%w: expected a tmux pane", os.ErrInvalid) + return failure, fmt.Errorf("%w: expected a tmux pane", os.ErrInvalid) } mode, dir := "resume", "" @@ -49,7 +61,7 @@ func attachPane(ctx context.Context, requested string) error { if p.Terminal == "" { var w workspace if err := json.Unmarshal([]byte(os.Getenv(tmux.RemoteEnv)), &w); err != nil { - return fmt.Errorf("read remote workspace: %w", err) + return failure, fmt.Errorf("read remote workspace: %w", err) } p.Host, p.Terminal, dir = w.Host, requested, w.Path @@ -57,19 +69,43 @@ func attachPane(ctx context.Context, requested string) error { mode = requested p.Terminal = w.prefix() + mode + "-" + rand.Text()[:13] } else if !strings.HasPrefix(p.Terminal, w.prefix()) { - return fmt.Errorf("%w: terminal belongs to another workspace", os.ErrInvalid) + return failure, fmt.Errorf("%w: terminal belongs to another workspace", os.ErrInvalid) } } if !terminalID.MatchString(p.Terminal) { - return fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) + return failure, fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) } dest, err := sshmux.ForHost(p.Host) if err != nil { - return fmt.Errorf("find pane connection: %w", err) + return failure, fmt.Errorf("find pane connection: %w", err) } + finish, err := admit(ctx, dest, batch) + if batch != "" && dir == "" && (errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ECONNREFUSED)) { + // respawn-pane can replay the original command after a batch ends. + finish, err = admit(ctx, dest, "") + } + + if err != nil { + if original := panes[id]; original.Terminal == "" && errors.Is(err, errPaneLimit) { + _ = original.CloseOnExit(ctx) + } + + _ = tmux.Notify(ctx, "tm: "+tui.CleanLine(err.Error())) + + return failure, err + } + + defer finish(false) + + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + timer := time.AfterFunc(15*time.Second, cancel) + defer timer.Stop() + // Record before launching. An ambiguous failure can only reattach here. p.Connection = dest.Generation() @@ -79,17 +115,40 @@ func attachPane(ctx context.Context, requested string) error { } if err := p.Record(ctx, project); err != nil { - return fmt.Errorf("record remote pane: %w", err) + return failure, fmt.Errorf("record remote pane: %w", err) } - ssh, err := exec.LookPath("ssh") - if err != nil { - return fmt.Errorf("find ssh: %w", err) + cmd := exec.CommandContext(ctx, "ssh", dest.Channel("-tt", remoteCommand(attach, mode, p.Terminal, dir))...) // #nosec G204 -- Pinned master and quoted arguments. + cmd.SysProcAttr = &syscall.SysProcAttr{Foreground: true} + cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr + cmd.Stdout = &paneOutput{opened: func() { timer.Stop(); finish(true) }} + cmd.WaitDelay = time.Second + + if err := cmd.Run(); err != nil { + if exit, ok := errors.AsType[*exec.ExitError](err); ok { + return max(1, exit.ExitCode()), nil + } + + return 1, fmt.Errorf("run SSH pane: %w", err) + } + + return 0, nil +} + +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 } - args := dest.Channel("-tt", remoteCommand(attach, mode, p.Terminal, dir)) + n, err := os.Stdout.Write(data) + if err != nil { + return n, fmt.Errorf("write terminal output: %w", err) + } - return fmt.Errorf("start ssh: %w", syscall.Exec(ssh, append([]string{ssh}, args...), os.Environ())) // #nosec G204 -- Replace only with ssh and quote remote arguments. + return n, nil } // A missing live terminal may still be starting. A missing dead one can be @@ -109,6 +168,12 @@ func stopTerminal(ctx context.Context, p *tmux.Attachment) error { command := remoteCommand(stop, p.Terminal, strconv.FormatBool(p.Dead)) + lock, err := dest.Lock(ctx) + if err != nil { + return fmt.Errorf("lock destination: %w", err) + } + defer func() { _ = lock.Close() }() + out, err := dest.Query(ctx, command) if errors.Is(err, sshmux.ErrChannelRefused) && !p.Dead { // At MaxSessions, free this attachment's slot for the close command. diff --git a/tools/cmd/tmux-session/remote.go b/tools/cmd/tmux-session/remote.go index 0e837f5d..1f8fefba 100644 --- a/tools/cmd/tmux-session/remote.go +++ b/tools/cmd/tmux-session/remote.go @@ -134,7 +134,7 @@ func openWorkspace(ctx context.Context, dest sshmux.Destination, request, name s w := workspace{Host: dest.Host, Path: dir, Name: cmp.Or(name, path.Base(dir))} - return w.open(ctx, names) + return w.open(ctx, dest, names) } // Pane names and positions are mutable. Only a terminal ID can identify a @@ -179,7 +179,7 @@ func (w workspace) windows(names map[string]bool, panes map[string]tmux.Attachme return windows, nil } -func (w workspace) open(ctx context.Context, names map[string]bool) (tmux.Session, bool, error) { +func (w workspace) open(ctx context.Context, dest sshmux.Destination, names map[string]bool) (tmux.Session, bool, error) { helper, err := os.Executable() if err != nil { return tmux.Session{}, false, fmt.Errorf("locate tmux-session: %w", err) @@ -190,14 +190,7 @@ func (w workspace) open(ctx context.Context, names map[string]bool) (tmux.Sessio return tmux.Session{}, false, fmt.Errorf("encode workspace: %w", err) } - // SSH authentication and discovery must never hold the local project lock. - lock, err := lockOpen() - if err != nil { - return tmux.Session{}, false, err - } - defer func() { _ = lock.Close() }() - - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() sessions, err := tmux.ListSessions(ctx) @@ -229,38 +222,83 @@ func (w workspace) open(ctx context.Context, names map[string]bool) (tmux.Sessio return tmux.Session{}, false, err } - // All workspaces on the destination lost the same connection. + var resume []tmux.Attachment + + prefix := w.prefix() for _, p := range panes { - if p.Host != w.Host || !p.Dead || !terminalID.MatchString(p.Terminal) || !names[p.Terminal] { - continue + if p.Host == w.Host && p.Dead && strings.HasPrefix(p.Terminal, prefix) && names[p.Terminal] && terminalID.MatchString(p.Terminal) { + resume = append(resume, p) } + } - if err := p.Resume(ctx, helper, "--remote-pane", p.Terminal); err != nil { - return tmux.Session{}, false, fmt.Errorf("resume pane %s: %w", p.ID, err) - } + want := len(windows) + len(resume) + + if err := requireCapacity(ctx, dest, want); err != nil { + return tmux.Session{}, false, err } - if created { - target.Name = tmux.AvailableName(sessions, displayName(w.Host+"/"+w.Name)) - target.Remote = string(meta) - first := windows[0] - windows = windows[1:] + err = launch(ctx, dest, want, func(token string) error { + if err := resumePanes(ctx, helper, token, resume); err != nil { + return err + } + + if created { + target.Name, target.Remote = displayName(w.Host+"/"+w.Name), string(meta) - target.ID, err = tmux.NewRemoteSession(ctx, target, first.role, "exec "+quote(helper)+" --remote-pane shell", - helper, "--remote-pane", cmp.Or(first.terminal, first.role)) - if err != nil { - return tmux.Session{}, false, fmt.Errorf("create remote session: %w", err) + if err := createRemote(ctx, &target, windows[0], helper, token); err != nil { + return err + } + + windows = windows[1:] } - } - for _, win := range windows { - err := tmux.StartWindow(ctx, target.ID, win.role, "", helper, "--remote-pane", cmp.Or(win.terminal, win.role)) - if err != nil { - return tmux.Session{}, false, fmt.Errorf("create remote window: %w", err) + for _, win := range windows { + if err := tmux.StartWindow(ctx, target.ID, win.role, "", helper, "--remote-pane", cmp.Or(win.terminal, win.role), "--pane-batch", token); err != nil { + return fmt.Errorf("create remote window: %w", err) + } } + + return nil + }) + if err != nil { + return tmux.Session{}, false, err } target.Path = w.Path return target, created, nil } + +func createRemote(ctx context.Context, target *tmux.Session, first window, helper, token string) error { + // Only allocating a session name and starting tmux require the local lock. + lock, err := lockOpen() + 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, first.role, "exec "+quote(helper)+" --remote-pane shell", + helper, "--remote-pane", cmp.Or(first.terminal, first.role), "--pane-batch", token) + if err != nil { + return fmt.Errorf("create remote session: %w", err) + } + + return nil +} + +func resumePanes(ctx context.Context, helper, token string, panes []tmux.Attachment) error { + for _, p := range panes { + if err := p.Resume(ctx, helper, "--remote-pane", p.Terminal, "--pane-batch", token); err != nil { + return fmt.Errorf("resume pane %s: %w", p.ID, err) + } + } + + return nil +} diff --git a/tools/cmd/tmux-session/remote_test.go b/tools/cmd/tmux-session/remote_test.go index 219ed558..0426c724 100644 --- a/tools/cmd/tmux-session/remote_test.go +++ b/tools/cmd/tmux-session/remote_test.go @@ -1,12 +1,67 @@ package main import ( + "context" + "errors" + "os" + "path/filepath" "slices" "testing" + "time" + "github.com/ddeville/scripts/tools/internal/sshmux" "github.com/ddeville/scripts/tools/internal/tmux" ) +func TestWorkspaceChecksAllPaneSlotsBeforeCreatingWindows(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 +for arg do command=$arg; done +for slot in 1 2 3; do + if mkdir "$slot" 2>/dev/null; then + trap 'rmdir "$slot"' EXIT + sh -c "$command" + exit $? + fi +done +echo 'Session open refused by peer' >&2 +exit 255 +` + if err := os.WriteFile("ssh", []byte(ssh), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private test directory. + t.Fatal(err) + } + + dest := sshmux.Destination{Host: "devbox", Socket: filepath.Join(dir, "master")} + + const tm = `#!/bin/sh +[ "$1" != -u ] || shift +if [ "$1" = list-sessions ]; then exit 0; fi +echo "$1" > unexpected +exit 1 +` + if err := os.WriteFile("tmux", []byte(tm), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private test directory. + t.Fatal(err) + } + + // Three slots are free, but one is needed for discovery, close and status. + w := workspace{Host: dest.Host, Path: "/project", Name: "project"} + if _, _, err := w.open(t.Context(), dest, nil); !errors.Is(err, errPaneLimit) { + t.Fatalf("expected refusal of a three-window workspace, got %v", err) + } + + if command, err := os.ReadFile("unexpected"); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("tmux command before capacity check: %q, %v", command, err) + } + + if err := requireCapacity(t.Context(), dest, 2); err != nil { + t.Fatalf("refused batch did not release its probes: %v", err) + } +} + func TestRestoreOnlyUnattachedSurvivors(t *testing.T) { t.Parallel() @@ -68,3 +123,61 @@ func TestRecoveryOnlyRetriesSSHFailuresOnThisDestination(t *testing.T) { t.Fatal("supervisor should exit without panes") } } + +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 TestWatcherSurvivesLookupFailureAndExitsWithServer(t *testing.T) { + dir := t.TempDir() + t.Chdir(dir) + t.Setenv("PATH", dir) + + const script = `#!/bin/sh +[ "$1" != -u ] || shift +if [ -f stopped ]; then + echo "no server running on /test" >&2 + exit 1 +fi +case "$1" in +list-panes) + if [ ! -f failed ]; then + : > failed + exit 1 + fi + printf '%%1\t@1\t0\tdev\ttm-1234567890abcdef1234.shell-AAAAAAAAAAAAA\t1\t\t1\n' + ;; +wait-for) : > stopped ;; +*) exit 1 ;; +esac +` + if err := os.WriteFile("tmux", []byte(script), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private test directory. + t.Fatal(err) + } + + watch, err := lockFile("watch") + if err != nil { + t.Fatal(err) + } + defer func() { _ = watch.Close() }() + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + + dest := sshmux.Destination{Host: "dev", Socket: filepath.Join(dir, "ssh")} + if err := watchPanes(ctx, dest, watch); err != nil || ctx.Err() != nil { + t.Fatalf("watchPanes = %v, context = %v", err, ctx.Err()) + } + + if _, err := os.Stat("stopped"); err != nil { + t.Fatal("watcher did not resume waiting for pane events") + } +} diff --git a/tools/cmd/tmux-session/supervisor.go b/tools/cmd/tmux-session/supervisor.go index d51f6379..708346f0 100644 --- a/tools/cmd/tmux-session/supervisor.go +++ b/tools/cmd/tmux-session/supervisor.go @@ -15,6 +15,7 @@ import ( "github.com/ddeville/scripts/tools/internal/sshmux" "github.com/ddeville/scripts/tools/internal/tmux" + "github.com/ddeville/scripts/tools/internal/tui" ) // A single reply covers SSH, discovery, layout and watcher election. No tmux @@ -133,9 +134,9 @@ func prepare(ctx context.Context, dest sshmux.Destination, result *openResult) ( return nil, fmt.Errorf("read workspace request: %w", err) } - lock, err := lockFile(dest.Socket + ".lock") + lock, err := dest.Lock(ctx) if err != nil { - return nil, err + return nil, fmt.Errorf("lock destination: %w", err) } defer func() { _ = lock.Close() }() @@ -173,17 +174,18 @@ func watchPanes(ctx context.Context, dest sshmux.Destination, watch *os.File) er } backoff := time.Second + notified := false for ctx.Err() == nil { // Explicit opens and automatic retries must never start competing masters. - lock, err := lockFile(dest.Socket + ".lock") + lock, err := dest.Lock(ctx) if err != nil { - return err + return fmt.Errorf("lock destination: %w", err) } active, err := recoverPanes(ctx, dest, helper, lock) - done := !active || errors.Is(err, sshmux.ErrSignIn) + done := (!active && err == nil) || errors.Is(err, sshmux.ErrSignIn) if done { // Let the next open take over before releasing the destination lock. _ = watch.Close() @@ -195,7 +197,15 @@ func watchPanes(ctx context.Context, dest sshmux.Destination, watch *os.File) er return err } + if err == nil { + err = tmux.WaitPaneDeath(ctx) + } + if err != nil { + if backoff >= 4*time.Second && !notified { + notified = tmux.Notify(ctx, "tm: retrying recovery for "+dest.Host+" · "+tui.CleanLine(err.Error())) == nil + } + select { case <-ctx.Done(): return nil @@ -208,10 +218,7 @@ func watchPanes(ctx context.Context, dest sshmux.Destination, watch *os.File) er } backoff = time.Second - - if err := tmux.WaitPaneDeath(ctx); err != nil { - return fmt.Errorf("wait for failed panes: %w", err) - } + notified = false } return nil @@ -279,15 +286,29 @@ func recoverPanes(ctx context.Context, dest sshmux.Destination, helper string, l return true, fmt.Errorf("%w: missing SSH master", os.ErrNotExist) } + var resume []tmux.Attachment + for _, p := range failed { - if p.Connection == generation { - // A channel can fail independently, e.g. at MaxSessions. - continue + if p.Connection != generation { + resume = append(resume, p) } + } - if err := p.Resume(ctx, helper, "--remote-pane", p.Terminal); err != nil { - return true, fmt.Errorf("resume pane %s: %w", p.ID, err) - } + free, err := dest.Capacity(ctx, len(resume)) + if err != nil { + return true, fmt.Errorf("check SSH capacity: %w", err) + } + + if err := launch(ctx, dest, free, func(token string) error { + return resumePanes(ctx, helper, token, resume[:free]) + }); err != nil { + return true, err + } + + // A replacement connection can have a lower limit. Leave the other panes + // untouched so they can resume as slots become available. + if free < len(resume) { + return true, capacityError(dest, len(resume), free) } return true, nil diff --git a/tools/internal/codex/client.go b/tools/internal/codex/client.go index b47e3236..0a544215 100644 --- a/tools/internal/codex/client.go +++ b/tools/internal/codex/client.go @@ -63,6 +63,7 @@ func dialRemote(ctx context.Context, host string) (net.Conn, error) { // The WebSocket can outlive the HTTP handshake. Closing the pipe ends ssh. cmd := exec.CommandContext(context.WithoutCancel(ctx), "ssh", dest.Channel("-T", "exec codex app-server proxy")...) // #nosec G204 -- Fixed command on a validated, existing master. + cmd.WaitDelay = time.Second stdin, err := cmd.StdinPipe() if err != nil { @@ -79,15 +80,42 @@ func dialRemote(ctx context.Context, host string) (net.Conn, error) { go func() { _, _ = io.Copy(stdin, peer) _ = stdin.Close() - _ = cmd.Process.Kill() }() + done := make(chan struct{}) + go func() { _ = cmd.Wait() _ = peer.Close() + + close(done) }() - return local, nil + return &proxyConn{Conn: local, process: cmd.Process, done: done}, nil +} + +// Wait for ssh to return the session slot before another command needs it. +type proxyConn struct { + net.Conn + + process *os.Process + done <-chan struct{} +} + +func (p *proxyConn) Close() error { + err := p.Conn.Close() + select { + case <-p.done: + case <-time.After(time.Second): + _ = p.process.Kill() + <-p.done + } + + if err != nil { + return fmt.Errorf("close Codex proxy: %w", err) + } + + return nil } // Connect opens the local app server or the one on an existing SSH destination. diff --git a/tools/internal/sshmux/capacity.go b/tools/internal/sshmux/capacity.go new file mode 100644 index 00000000..3969e75f --- /dev/null +++ b/tools/internal/sshmux/capacity.go @@ -0,0 +1,107 @@ +package sshmux + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "time" +) + +// Capacity checks room for up to want panes and one management channel. +// sshd does not advertise MaxSessions. Hold the probes simultaneously, and +// keep the destination locked until the real pane channels have opened. +func (d Destination) Capacity(ctx context.Context, want int) (int, error) { + if want == 0 { + return 0, nil + } + + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + + var ( + held []*probe + err error + ) + + for range want + 1 { + var p *probe + + p, err = d.probe(ctx) + if err != nil { + if errors.Is(err, ErrChannelRefused) && len(held) > 0 { + err = nil + } + + break + } + + held = append(held, p) + } + + for _, p := range held { + _, _ = io.WriteString(p.in, "\n") + _ = p.in.Close() + } + + for _, p := range held { + if waitErr := p.cmd.Wait(); waitErr != nil && err == nil { + err = d.commandError(waitErr, p.stderr.String()) + } + } + + if err != nil { + return 0, err + } + + return len(held) - 1, nil +} + +type probe struct { + cmd *exec.Cmd + in io.WriteCloser + stderr bytes.Buffer +} + +func (d Destination) probe(ctx context.Context) (*probe, error) { + // EOF before release makes read fail, so an early exit cannot inflate capacity. + cmd := exec.CommandContext(ctx, "ssh", d.Channel("-T", "exec sh -c 'printf +; read -r done'")...) // #nosec G204 -- Fixed command on the private master. + cmd.WaitDelay = time.Second + + in, err := cmd.StdinPipe() + if err != nil { + return nil, fmt.Errorf("open probe stdin: %w", err) + } + + out, err := cmd.StdoutPipe() + if err != nil { + _ = in.Close() + return nil, fmt.Errorf("open probe stdout: %w", err) + } + + p := &probe{cmd: cmd, in: in} + cmd.Stderr = &p.stderr + + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("start SSH probe: %w", err) + } + + stop := context.AfterFunc(ctx, func() { _ = out.Close() }) + defer stop() + + var ready [1]byte + if _, err := io.ReadFull(out, ready[:]); err != nil || ready[0] != '+' { + _ = in.Close() + + if err := cmd.Wait(); err != nil { + return nil, d.commandError(err, p.stderr.String()) + } + + return nil, fmt.Errorf("%w: missing SSH probe reply", os.ErrInvalid) + } + + return p, nil +} diff --git a/tools/internal/sshmux/lock.go b/tools/internal/sshmux/lock.go new file mode 100644 index 00000000..ce30a46d --- /dev/null +++ b/tools/internal/sshmux/lock.go @@ -0,0 +1,85 @@ +package sshmux + +import ( + "context" + "errors" + "fmt" + "os" + "syscall" + "time" +) + +// Lock serializes management and pane admission across all local tmux servers. +// Wait for proxies and already approved pane launches to release the slot. +func (d Destination) Lock(ctx context.Context) (*os.File, error) { + request, err := lock(ctx, d.Socket+".lock", syscall.LOCK_EX) + if err != nil { + return nil, err + } + + slot, err := lock(ctx, d.Socket+".slot", syscall.LOCK_EX) + if err != nil { + _ = request.Close() + return nil, err + } + + _ = slot.Close() + + return request, nil +} + +// Hold keeps subsequent operations out after the caller releases Lock. +// All helpers in a batch can hold it until SSH acknowledges their channels. +func (d Destination) Hold(ctx context.Context) (*os.File, error) { + return lock(ctx, d.Socket+".slot", syscall.LOCK_SH) +} + +// ProxySlot lets an idle proxy detect a waiting caller and yield to it. +func (d Destination) ProxySlot(ctx context.Context) (*os.File, error) { + request, err := d.Lock(ctx) + if err != nil { + return nil, err + } + defer func() { _ = request.Close() }() + + return d.Hold(ctx) +} + +// Waiting reports whether another operation needs the management slot. +func (d Destination) Waiting() bool { + f, err := os.Open(d.Socket + ".lock") // #nosec G304 -- Private destination lock. + if err != nil { + return true + } + defer func() { _ = f.Close() }() + + return syscall.Flock(int(f.Fd()), syscall.LOCK_SH|syscall.LOCK_NB) != nil +} + +func lock(ctx context.Context, path string, mode int) (*os.File, error) { + f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) // #nosec G304 -- Private destination lock. + if err != nil { + return nil, fmt.Errorf("open SSH lock: %w", err) + } + + for ctx.Err() == nil { + err := syscall.Flock(int(f.Fd()), mode|syscall.LOCK_NB) + if err == nil { + return f, nil + } + + if !errors.Is(err, syscall.EWOULDBLOCK) { + _ = f.Close() + return nil, fmt.Errorf("lock SSH destination: %w", err) + } + + select { + case <-ctx.Done(): + case <-time.After(25 * time.Millisecond): + } + } + + _ = f.Close() + + return nil, fmt.Errorf("wait for SSH destination: %w", ctx.Err()) +} diff --git a/tools/internal/sshmux/ssh.go b/tools/internal/sshmux/ssh.go index 1bbc4e47..060b242d 100644 --- a/tools/internal/sshmux/ssh.go +++ b/tools/internal/sshmux/ssh.go @@ -132,19 +132,28 @@ func (d Destination) Query(ctx context.Context, command string) (string, error) out, err := cmd.Output() if err != nil { - var exit *exec.ExitError - if errors.As(err, &exit) && len(exit.Stderr) != 0 { - if exit.ExitCode() == 255 && strings.Contains(string(exit.Stderr), "Session open refused") { - return "", fmt.Errorf("%w on %s", ErrChannelRefused, d.Host) - } + return "", d.commandError(err, "") + } - return "", fmt.Errorf("SSH %s: %w: %s", d.Host, err, strings.TrimSpace(string(exit.Stderr))) + return string(out), nil +} + +func (d Destination) commandError(err error, stderr string) error { + if exit, ok := errors.AsType[*exec.ExitError](err); ok { + if stderr == "" { + stderr = string(exit.Stderr) } - return "", fmt.Errorf("SSH %s: %w", d.Host, err) + if exit.ExitCode() == 255 && strings.Contains(stderr, "Session open refused") { + return fmt.Errorf("%w on %s", ErrChannelRefused, d.Host) + } } - return string(out), nil + if stderr != "" { + return fmt.Errorf("SSH %s: %w: %s", d.Host, err, strings.TrimSpace(stderr)) + } + + return fmt.Errorf("SSH %s: %w", d.Host, err) } // CacheDir locates the user’s session cache. diff --git a/tools/internal/sshmux/ssh_test.go b/tools/internal/sshmux/ssh_test.go index 020beea6..db92e2f5 100644 --- a/tools/internal/sshmux/ssh_test.go +++ b/tools/internal/sshmux/ssh_test.go @@ -1,15 +1,51 @@ package sshmux_test import ( + "context" "errors" "os" "path/filepath" "strings" "testing" + "time" "github.com/ddeville/scripts/tools/internal/sshmux" ) +func TestAdmissionWaitsForEveryApprovedPane(t *testing.T) { + t.Parallel() + + dest := sshmux.Destination{Host: "devbox", Socket: filepath.Join(t.TempDir(), "master")} + lock, err := dest.Lock(t.Context()) + if err != nil { + t.Fatal(err) + } + + pane, err := dest.Hold(t.Context()) + if err != nil { + t.Fatal(err) + } + + // The caller goes away before the pane has finished opening its channel. + _ = lock.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) + defer cancel() + + if _, err := dest.Lock(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("overlapped an approved launch: %v", err) + } + + _ = pane.Close() + + lock, err = dest.Lock(t.Context()) + if err != nil { + t.Fatal(err) + } + + _ = lock.Close() +} + func TestConnectUsesCurrentAgentAndRefusesUntrustedHost(t *testing.T) { dir := t.TempDir() diff --git a/tools/internal/tmux/remote.go b/tools/internal/tmux/remote.go index 08d5bdcd..ed9eb82a 100644 --- a/tools/internal/tmux/remote.go +++ b/tools/internal/tmux/remote.go @@ -49,7 +49,7 @@ type Attachment struct { 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_terminal}\t#{pid}\t#{pane_dead_status}\t#{@tm_connection}" - args := []string{"list-panes", "-F", format} + args := []string{"-u", "list-panes", "-F", format} if target == "" { args = append(args, "-a") } else { @@ -58,6 +58,10 @@ func Attachments(ctx context.Context, target string) (map[string]Attachment, err 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) } @@ -79,12 +83,21 @@ func Attachments(ctx context.Context, target string) (map[string]Attachment, err 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 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", "-p", "-t", p.ID, "@tm_connection", p.Connection, ";", "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, @@ -95,6 +108,9 @@ func (p Attachment) Record(ctx context.Context, project string) error { "set-option", "-p", "-t", p.ID, "@tm_terminal", literalArg(p.Terminal)) } + // Keep the previous generation retryable if setup fails partway through. + args = append(args, ";", "set-option", "-p", "-t", p.ID, "@tm_connection", p.Connection) + _, err := run(ctx, args...) return err @@ -105,6 +121,11 @@ 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...)) diff --git a/tools/internal/tmux/sessions.go b/tools/internal/tmux/sessions.go index 68eb090a..6c98e7c5 100644 --- a/tools/internal/tmux/sessions.go +++ b/tools/internal/tmux/sessions.go @@ -32,7 +32,7 @@ func ListSessions(ctx context.Context) ([]Session, error) { 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 } @@ -60,6 +60,11 @@ 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 From 3da850584b3422709bb586eb6aa51348bf402a47 Mon Sep 17 00:00:00 2001 From: Damien Deville Date: Thu, 26 Nov 2026 11:30:39 -0800 Subject: [PATCH 5/6] Simplify SSH session management and defer remote Codex status --- tools/cmd/tmux-agent-status/agents/panes.go | 100 +++------- .../tmux-agent-status/agents/panes_test.go | 29 +-- tools/cmd/tmux-agent-status/agents/source.go | 114 ----------- tools/cmd/tmux-agent-status/agents/status.go | 127 ++++++------ tools/cmd/tmux-agent-status/open.go | 9 +- tools/cmd/tmux-agent-status/output.go | 7 +- .../cmd/tmux-agent-status/ui/agents/model.go | 112 +++++------ .../tmux-agent-status/ui/agents/sources.go | 131 ------------ .../ui/agents/sources_test.go | 35 ---- tools/cmd/tmux-agent-status/ui/agents/view.go | 89 +++------ tools/cmd/tmux-agent-status/ui/model.go | 108 +++++----- tools/cmd/tmux-session/REMOTE-WORKSPACES.md | 23 +-- tools/cmd/tmux-session/launch.go | 158 +++++---------- tools/cmd/tmux-session/main.go | 45 +++-- tools/cmd/tmux-session/pane.go | 186 +++++++++++------- tools/cmd/tmux-session/remote.go | 167 +++++++++------- tools/cmd/tmux-session/remote_test.go | 59 +++--- tools/cmd/tmux-session/supervisor.go | 59 +++--- tools/internal/codex/client.go | 96 +-------- tools/internal/sshmux/capacity.go | 107 ---------- tools/internal/sshmux/lock.go | 85 -------- tools/internal/sshmux/ssh.go | 29 +-- tools/internal/sshmux/ssh_test.go | 36 ---- tools/internal/tmux/panes.go | 70 ++----- tools/internal/tmux/remote.go | 24 +-- 25 files changed, 606 insertions(+), 1399 deletions(-) delete mode 100644 tools/cmd/tmux-agent-status/agents/source.go delete mode 100644 tools/cmd/tmux-agent-status/ui/agents/sources.go delete mode 100644 tools/cmd/tmux-agent-status/ui/agents/sources_test.go delete mode 100644 tools/internal/sshmux/capacity.go delete mode 100644 tools/internal/sshmux/lock.go diff --git a/tools/cmd/tmux-agent-status/agents/panes.go b/tools/cmd/tmux-agent-status/agents/panes.go index abf8d609..1446d1c9 100644 --- a/tools/cmd/tmux-agent-status/agents/panes.go +++ b/tools/cmd/tmux-agent-status/agents/panes.go @@ -7,7 +7,6 @@ import ( "regexp" "strings" - "github.com/ddeville/scripts/tools/internal/codex" "github.com/ddeville/scripts/tools/internal/tmux" ) @@ -16,97 +15,48 @@ var titleID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{ // ErrPaneMatch means a conversation could not be resolved to exactly one live pane. var ErrPaneMatch = errors.New("thread must be open in exactly one tmux pane") -var errPaneChanged = errors.New("this pane no longer displays the selected thread") - -// Open rechecks both the thread and the attachment. A pane ID survives moves, -// but a different process or a new conversation must never inherit a selection. -func (s *Source) Open(ctx context.Context, id string, target tmux.Pane, client string) error { - var ids []string - - err := s.use(ctx, func(server *codex.Client) error { - var err error - - ids, err = server.LoadedIDs(ctx) - if err != nil { - return fmt.Errorf("list threads: %w", err) - } - - return nil - }) +// MatchPanes checks all loaded IDs so truncated titles cannot resolve ambiguously. +func MatchPanes(ctx context.Context, ids []string) (map[string][]string, error) { + panes, err := tmux.ListPanes(ctx) if err != nil { - return fmt.Errorf("refresh loaded threads: %w", err) - } - - if id == "" || s.Host != target.Host || !candidate(target) || displayedThread(target.Title, ids) != id { - return errPaneChanged + return nil, fmt.Errorf("match agent panes: %w", err) } - if err := target.Switch(ctx, client, titleSuffix(target.Title)); err != nil { - return fmt.Errorf("open selected pane: %w", err) - } - - return nil + return matchPanes(ids, panes), nil } -func matchPanes(host string, ids []string, panes []tmux.Pane) map[string][]tmux.Pane { - matches := map[string][]tmux.Pane{} +func matchPanes(ids []string, panes []tmux.Pane) map[string][]string { + matches := map[string][]string{} - for _, p := range panes { - if p.Host != host || !candidate(p) { + for _, pane := range panes { + if pane.Command != "codex" { continue } - if id := displayedThread(p.Title, ids); id != "" { - matches[id] = append(matches[id], p) + title := pane.Title + if i := strings.LastIndex(title, " | "); i >= 0 { + title = title[i+3:] } - } - - return matches -} - -func candidate(p tmux.Pane) bool { - if p.Dead { - return false - } - if p.Host == "" { - return p.Command == "codex" - } - - return p.Terminal != "" && p.Command == "ssh" && titleID.MatchString(titleSuffix(p.Title)) -} - -func titleSuffix(title string) string { - if _, after, ok := strings.CutLast(title, " | "); ok { - return after - } - - return title -} - -// Codex shortens the thread ID in the terminal title. Resolve against all -// loaded IDs on this host, never by directory or by the pane's initial role. -func displayedThread(title string, ids []string) string { - title = titleSuffix(title) - if !titleID.MatchString(title) { - return "" - } + if !titleID.MatchString(title) { + continue + } - prefix := strings.TrimSuffix(title, "...") + prefix := strings.TrimSuffix(title, "...") - var match string + var candidates []string - for _, id := range ids { - if len(id) != 36 || !strings.HasPrefix(id, prefix) { - continue + for _, id := range ids { + if strings.HasPrefix(id, prefix) { + candidates = append(candidates, id) + } } - if match != "" { - return "" + if len(candidates) == 1 { + id := candidates[0] + matches[id] = append(matches[id], pane.ID) } - - match = id } - return match + return matches } diff --git a/tools/cmd/tmux-agent-status/agents/panes_test.go b/tools/cmd/tmux-agent-status/agents/panes_test.go index e8aa73e8..ae910802 100644 --- a/tools/cmd/tmux-agent-status/agents/panes_test.go +++ b/tools/cmd/tmux-agent-status/agents/panes_test.go @@ -24,33 +24,8 @@ func TestMatchPanesDoesNotGuess(t *testing.T) { {ID: "%6", Command: "codex", Title: unique[:8]}, } - want := map[string][]tmux.Pane{first: {panes[0], panes[1]}, unique: {panes[3]}} - if got := matchPanes("", ids, panes); !reflect.DeepEqual(got, want) { + want := map[string][]string{first: {"%1", "%2"}, unique: {"%4"}} + if got := matchPanes(ids, panes); !reflect.DeepEqual(got, want) { t.Fatalf("pane matches = %v, want %v; ambiguous titles must be ignored and duplicate panes preserved", got, want) } } - -func TestRemoteMatchesStayOnOneHost(t *testing.T) { - t.Parallel() - - const ( - id = "12345678-1234-1234-1234-123450000000" - title = "same project | 12345678-1234-1234-1234-12345..." - ) - - panes := []tmux.Pane{ - {ID: "%1", Command: "codex", Title: title}, - {ID: "%2", Host: "other", Terminal: "shell", Command: "ssh", Title: title}, - {ID: "%3", Host: "dev", Terminal: "shell", Command: "ssh", Title: title}, - {ID: "%4", Host: "dev", Terminal: "codex", Command: "ssh", Title: title, Dead: true}, - {ID: "%5", Host: "dev", Terminal: "shell", Command: "fish", Title: title}, - {ID: "%6", Host: "dev", Command: "ssh", Title: title}, - } - - for host, target := range map[string]tmux.Pane{"": panes[0], "other": panes[1], "dev": panes[2]} { - got := matchPanes(host, []string{id}, panes) - if !reflect.DeepEqual(got[id], []tmux.Pane{target}) { - t.Errorf("matches on %q = %v, want only %s", host, got, target.ID) - } - } -} diff --git a/tools/cmd/tmux-agent-status/agents/source.go b/tools/cmd/tmux-agent-status/agents/source.go deleted file mode 100644 index 7d06d58a..00000000 --- a/tools/cmd/tmux-agent-status/agents/source.go +++ /dev/null @@ -1,114 +0,0 @@ -package agents - -import ( - "context" - "errors" - "fmt" - "os" - "sync" - "time" - - "github.com/ddeville/scripts/tools/internal/codex" - "github.com/ddeville/scripts/tools/internal/sshmux" -) - -// Source shares one sequential app-server connection across status, activity, -// and navigation for a destination. Its zero value targets the local daemon. -type Source struct { - Host string - - mu sync.Mutex - client *codex.Client - slot *os.File -} - -func (s *Source) use(ctx context.Context, read func(*codex.Client) error) error { - s.mu.Lock() - defer s.mu.Unlock() - - if err := ctx.Err(); err != nil { - return fmt.Errorf("read Codex: %w", err) - } - - if s.client == nil { - if err := s.connect(ctx); err != nil { - return err - } - } - - err := read(s.client) - - var rpcErr *codex.RPCError - if err != nil && !errors.As(err, &rpcErr) { - s.close() - } - - return err -} - -func (s *Source) connect(ctx context.Context) error { - if s.Host != "" { - dest, err := sshmux.ForHost(s.Host) - if err != nil { - return fmt.Errorf("find SSH connection: %w", err) - } - - s.slot, err = dest.ProxySlot(ctx) - if err != nil { - return fmt.Errorf("wait for SSH slot: %w", err) - } - - go s.yield(dest, s.slot) - } - - client, err := codex.Connect(ctx, s.Host) - if err != nil { - s.close() - return fmt.Errorf("connect to app server: %w", err) - } - - s.client = client - - return nil -} - -// Keep the proxy warm between refreshes until another caller needs the slot. -// The mutex lets a request in flight finish before we return the channel. -func (s *Source) yield(dest sshmux.Destination, slot *os.File) { - ticker := time.NewTicker(100 * time.Millisecond) - defer ticker.Stop() - - for range ticker.C { - s.mu.Lock() - if s.slot == slot && dest.Waiting() { - s.close() - } - - done := s.slot != slot - s.mu.Unlock() - - if done { - return - } - } -} - -// Close releases the app-server connection and its SSH channel, if any. -func (s *Source) Close() { - s.mu.Lock() - defer s.mu.Unlock() - - s.close() -} - -func (s *Source) close() { - if s.client != nil { - s.client.Close() - s.client = nil - } - - if s.slot != nil { - _ = s.slot.Close() - s.slot = nil - } -} diff --git a/tools/cmd/tmux-agent-status/agents/status.go b/tools/cmd/tmux-agent-status/agents/status.go index 3102182b..9e2133d0 100644 --- a/tools/cmd/tmux-agent-status/agents/status.go +++ b/tools/cmd/tmux-agent-status/agents/status.go @@ -32,22 +32,22 @@ const ( // Agent describes a running conversation and its current status. type Agent struct { - ID string `json:"id"` - Type Type `json:"agent_type"` - Title string `json:"title"` - Cwd string `json:"cwd"` - Project string `json:"project"` - State string `json:"status"` - NeedsAttention bool `json:"needs_attention"` - Unread *bool `json:"unread"` - ActiveFlags []string `json:"active_flags"` - ParentID *string `json:"parent_id"` - Model *string `json:"model"` - UpdatedAt *int64 `json:"updated_at"` - Error *string `json:"error"` - Panes []string `json:"tmux_panes,omitempty"` - Targets []tmux.Pane `json:"-"` - Preview string `json:"preview"` + ID string `json:"id"` + Type Type `json:"agent_type"` + Title string `json:"title"` + Cwd string `json:"cwd"` + Project string `json:"project"` + State string `json:"status"` + NeedsAttention bool `json:"needs_attention"` + Unread *bool `json:"unread"` + ActiveFlags []string `json:"active_flags"` + ParentID *string `json:"parent_id"` + Model *string `json:"model"` + UpdatedAt *int64 `json:"updated_at"` + Error *string `json:"error"` + Panes []string `json:"tmux_panes,omitempty"` + SessionNumber int `json:"-"` + Preview string `json:"preview"` } // Snapshot contains the agents currently running in tmux and their status counts. @@ -142,8 +142,7 @@ func agentRecord(result codex.ReadResult) Agent { } // Collect reads loaded conversations with live tmux panes, ordered by path and pane ID. -// Without a pane snapshot it reads one from the current tmux server. -func (s *Source) Collect(ctx context.Context, panes []tmux.Pane) (data Snapshot) { +func Collect(ctx context.Context) (data Snapshot) { data = Snapshot{ SchemaVersion: 1, Source: "codex", Scope: "tmux", IDs: []string{}, Agents: []Agent{}, Counts: map[string]int{}, @@ -172,37 +171,35 @@ func (s *Source) Collect(ctx context.Context, panes []tmux.Pane) (data Snapshot) } }() - if panes != nil && !slices.ContainsFunc(panes, candidate) { - // The popup has no candidate views here. Leave the SSH slot free. - s.Close() + client, err := codex.Connect(ctx) + if err != nil { + data.Err = err return data } + defer client.Close() - if panes == nil { - var err error - - panes, err = tmux.ListPanes(ctx) - if err != nil { - data.Err = fmt.Errorf("match agent panes: %w", err) - return data - } + ids, err := client.LoadedIDs(ctx) + if err != nil { + data.Err = err + return data } - data.Err = s.use(ctx, func(client *codex.Client) error { - return data.read(ctx, client, s.Host, panes) - }) - - return data -} + data.IDs = ids -func (data *Snapshot) read(ctx context.Context, client *codex.Client, host string, panes []tmux.Pane) error { - ids, err := client.LoadedIDs(ctx) + panes, err := tmux.ListPanes(ctx) if err != nil { - return fmt.Errorf("list loaded threads: %w", err) + data.Err = fmt.Errorf("match agent panes: %w", err) + return data } - data.IDs = ids - matches := matchPanes(host, ids, panes) + matches := matchPanes(ids, panes) + sessions := make(map[string]int, len(panes)) + + for _, pane := range panes { + if number, ok := sessions[pane.ID]; !ok || pane.SessionNumber < number { + sessions[pane.ID] = pane.SessionNumber + } + } for _, id := range ids { matched := matches[id] @@ -210,29 +207,33 @@ func (data *Snapshot) read(ctx context.Context, client *codex.Client, host strin continue } - result, err := client.ReadThread(ctx, id) + sessionNumber := sessions[matched[0]] + for _, pane := range matched[1:] { + sessionNumber = min(sessionNumber, sessions[pane]) + } - record := agentRecord(result) + result, err := client.ReadThread(ctx, id) if err != nil { var rpcErr *codex.RPCError if !errors.As(err, &rpcErr) { - return fmt.Errorf("read thread: %w", err) + data.Err = err + return data } - record = Agent{ + data.Agents = append(data.Agents, Agent{ ID: id, Type: Codex, Title: id, State: "error", NeedsAttention: true, - Error: &rpcErr.Message, ActiveFlags: []string{}, - } - } else if result.Thread.Status.Type == "notLoaded" || record.ID != id { + Error: &rpcErr.Message, Panes: matched, SessionNumber: sessionNumber, ActiveFlags: []string{}, + }) + continue } - record.Targets = matched - - for _, pane := range matched { - record.Panes = append(record.Panes, pane.ID) + if result.Thread.Status.Type == "notLoaded" { + continue } + record := agentRecord(result) + record.Panes, record.SessionNumber = matched, sessionNumber data.Agents = append(data.Agents, record) } @@ -244,7 +245,7 @@ func (data *Snapshot) read(ctx context.Context, client *codex.Client, host strin ) }) - return nil + return data } // Details includes a conversation's status, initial prompt, and recent history. @@ -257,23 +258,15 @@ type Details struct { } // ReadDetails reads one conversation and its recent activity. -func (s *Source) ReadDetails(ctx context.Context, id string) (Details, error) { - var data Details - - err := s.use(ctx, func(client *codex.Client) error { - var err error - - data, err = readDetails(ctx, client, id) - - return err - }) - - return data, err -} - -func readDetails(ctx context.Context, client *codex.Client, id string) (Details, error) { +func ReadDetails(ctx context.Context, id string) (Details, error) { data := Details{RecentItems: []json.RawMessage{}} + client, err := codex.Connect(ctx) + if err != nil { + return data, fmt.Errorf("read details for %s: %w", id, err) + } + defer client.Close() + result, err := client.ReadThread(ctx, id) if err != nil { return data, fmt.Errorf("read details for %s: %w", id, err) diff --git a/tools/cmd/tmux-agent-status/open.go b/tools/cmd/tmux-agent-status/open.go index 9ec97e6e..c38bcbb8 100644 --- a/tools/cmd/tmux-agent-status/open.go +++ b/tools/cmd/tmux-agent-status/open.go @@ -22,10 +22,7 @@ func openThread(ctx context.Context, id string) error { return fmt.Errorf("open agent: %w", err) } - var local agents.Source - defer local.Close() - - data := local.Collect(ctx, nil) + data := agents.Collect(ctx) if data.Err != nil { return data.Err } @@ -35,12 +32,12 @@ func openThread(ctx context.Context, id string) error { return errThreadGone } - panes := data.Agents[index].Targets + panes := data.Agents[index].Panes if len(panes) != 1 { return fmt.Errorf("%w, found %d", agents.ErrPaneMatch, len(panes)) } - if err := local.Open(ctx, id, panes[0], client); err != nil { + if err := tmux.SwitchPane(ctx, panes[0], client); err != nil { return fmt.Errorf("open agent: %w", err) } diff --git a/tools/cmd/tmux-agent-status/output.go b/tools/cmd/tmux-agent-status/output.go index f13c9e2c..b602753c 100644 --- a/tools/cmd/tmux-agent-status/output.go +++ b/tools/cmd/tmux-agent-status/output.go @@ -13,9 +13,6 @@ import ( ) func runStatus(ctx context.Context, watch bool, interval time.Duration, output, detailID string) error { - var local agents.Source - defer local.Close() - for { started := time.Now() requestCtx, cancel := context.WithTimeout(ctx, 8*time.Second) @@ -26,9 +23,9 @@ func runStatus(ctx context.Context, watch bool, interval time.Duration, output, ) if detailID == "" { - data = local.Collect(requestCtx, nil) + data = agents.Collect(requestCtx) } else { - data, err = local.ReadDetails(requestCtx, detailID) + data, err = agents.ReadDetails(requestCtx, detailID) } cancel() diff --git a/tools/cmd/tmux-agent-status/ui/agents/model.go b/tools/cmd/tmux-agent-status/ui/agents/model.go index e714e50b..7956cd28 100644 --- a/tools/cmd/tmux-agent-status/ui/agents/model.go +++ b/tools/cmd/tmux-agent-status/ui/agents/model.go @@ -19,10 +19,7 @@ import ( // Model owns agent snapshots, filtering, selection, and activity requests. type Model struct { Panel panel.Model - hosts map[string]*destination - choices map[string]Choice - initialHost string - scanErr error + data agentdata.Snapshot selected, initialPane, originPane, originThread string filter int activity activity @@ -34,45 +31,54 @@ type tickMsg struct{} // New starts the section with the originating pane as its initial selection. func New(pane string) Model { - return Model{Panel: panel.New(), initialPane: pane, originPane: pane, hosts: map[string]*destination{"": {}}} + return Model{Panel: panel.New(), initialPane: pane, originPane: pane} } +// Snapshot returns the last known agent data and connection state. +func (m *Model) Snapshot() agentdata.Snapshot { return m.data } + // OriginID returns the conversation found in the originating tmux pane. func (m *Model) OriginID() string { return m.originThread } // Init begins polling agent status. -func (m *Model) Init(ctx context.Context) tea.Cmd { return scan(ctx) } +func (m *Model) Init(ctx context.Context) tea.Cmd { return fetch(ctx) } + +func fetch(ctx context.Context) tea.Cmd { + return func() tea.Msg { + ctx, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + + return agentdata.Collect(ctx) + } +} + +func tick() tea.Cmd { return tea.Tick(time.Second, func(time.Time) tea.Msg { return tickMsg{} }) } // Update handles section input and applies status and activity results. func (m *Model) Update(ctx context.Context, message tea.Msg) tea.Cmd { switch msg := message.(type) { - case panesMsg: - return m.fetch(ctx, msg) - case StatusMsg: - dest := m.hosts[msg.Host] - dest.busy = false - - dest.data = msg.data - if msg.Host == "" && m.originThread == "" { - for _, a := range msg.data.Agents { - if slices.Contains(a.Panes, m.originPane) { - m.originThread = a.ID - } - } + case agentdata.Snapshot: + if msg.Err != nil { + m.data.Err = msg.Err + return tick() } - cmd := m.updateAgents(ctx) - if msg.Host == m.initialHost { - m.initialPane = "" + for _, a := range msg.Agents { + if m.originThread == "" && slices.Contains(a.Panes, m.originPane) { + m.originThread = a.ID + } } - if choice, ok := m.Find(m.selected); ok && choice.Pane.Host == msg.Host && cmd == nil && m.activityCancel == nil { - return m.refreshActivity(ctx) + m.data = msg + + cmd := m.updateAgents(ctx) + if cmd == nil && m.selected != "" && m.activityCancel == nil { + cmd = m.refreshActivity(ctx) } - return cmd + return tea.Batch(tick(), cmd) case tickMsg: - return scan(ctx) + return fetch(ctx) case activity: if msg.ID == m.selected && msg.generation == m.activityGeneration { m.activity = msg @@ -80,7 +86,6 @@ func (m *Model) Update(ctx context.Context, message tea.Msg) tea.Cmd { m.updateAgentDetails() } case tea.KeyPressMsg: - m.initialPane = "" if key.Matches(msg, Keys.NextFilter, Keys.PreviousFilter, Keys.Attention) { return m.changeFilter(ctx, msg) } @@ -135,9 +140,7 @@ func (m *Model) refreshActivity(ctx context.Context) tea.Cmd { } m.activityGeneration++ - - choice, ok := m.Find(m.selected) - if !ok { + if m.selected == "" { return nil } @@ -148,17 +151,16 @@ func (m *Model) refreshActivity(ctx context.Context) tea.Cmd { return func() tea.Msg { defer cancel() - data, err := choice.Source.ReadDetails(ctx, choice.Agent.ID) + data, err := agentdata.ReadDetails(ctx, id) return activity{ID: id, generation: generation, Entries: activityEntries(data), Err: err} } } -func (m *Model) filtered(filter int) []Choice { - var result []Choice +func (m *Model) filtered(filter int) []agentdata.Agent { + var result []agentdata.Agent - for _, c := range m.choices { - a := c.Agent + for _, a := range m.data.Agents { match := false switch filter { @@ -175,7 +177,7 @@ func (m *Model) filtered(filter int) []Choice { } if match { - result = append(result, c) + result = append(result, a) } } @@ -196,38 +198,24 @@ func (m *Model) selectAgent(ctx context.Context, id string) tea.Cmd { } func (m *Model) updateAgents(ctx context.Context) tea.Cmd { - m.choices = make(map[string]Choice) - for _, dest := range m.hosts { - for _, a := range dest.data.Agents { - for _, pane := range a.Targets { - c := Choice{Agent: a, Pane: pane, Source: &dest.source} - m.choices[c.key()] = c - } - } - } - filtered := m.filtered(m.filter) - slices.SortFunc(filtered, func(a, b Choice) int { - return cmp.Or(cmp.Compare(a.Pane.SessionNumber, b.Pane.SessionNumber), - cmp.Compare(a.Pane.Host, b.Pane.Host), cmp.Compare(a.Agent.Cwd, b.Agent.Cwd), - cmp.Compare(len(a.Pane.ID), len(b.Pane.ID)), cmp.Compare(a.Pane.ID, b.Pane.ID)) - }) - - selected := m.selected + slices.SortStableFunc(filtered, func(a, b agentdata.Agent) int { return cmp.Compare(a.SessionNumber, b.SessionNumber) }) items := make([]tui.ListItem, 0, len(filtered)) - for _, c := range filtered { - row := Row(c.Agent) + for _, a := range filtered { + items = append(items, Row(a)) + } - row.ID, row.Group = c.key(), c.location() - if len(c.Agent.Panes) > 1 { - row.Title = c.Pane.ID + " · " + row.Title + selected := m.selected + if m.initialPane != "" { + for _, a := range filtered { + if slices.Contains(a.Panes, m.initialPane) { + selected = a.ID + break + } } - items = append(items, row) - if c.Pane.ID == m.initialPane { - selected = row.ID - } + m.initialPane = "" } m.Panel.List.SetItems(items, selected) diff --git a/tools/cmd/tmux-agent-status/ui/agents/sources.go b/tools/cmd/tmux-agent-status/ui/agents/sources.go deleted file mode 100644 index 1a7e16f5..00000000 --- a/tools/cmd/tmux-agent-status/ui/agents/sources.go +++ /dev/null @@ -1,131 +0,0 @@ -package agents - -import ( - "context" - "errors" - "slices" - "time" - - tea "charm.land/bubbletea/v2" - - agentdata "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/agents" - "github.com/ddeville/scripts/tools/internal/tmux" -) - -// Each destination refreshes independently so an unreachable host cannot -// stall the local dashboard or other SSH destinations. -type destination struct { - source agentdata.Source - data agentdata.Snapshot - busy bool -} - -type panesMsg struct { - panes []tmux.Pane - err error -} - -// StatusMsg contains a new snapshot for one app server. -type StatusMsg struct { - Host string - data agentdata.Snapshot -} - -var errDisconnected = errors.New("SSH disconnected") - -func scan(ctx context.Context) tea.Cmd { - return func() tea.Msg { - ctx, cancel := context.WithTimeout(ctx, time.Second) - defer cancel() - - panes, err := tmux.ListPanes(ctx) - - return panesMsg{panes, err} - } -} - -func (m *Model) fetch(ctx context.Context, msg panesMsg) tea.Cmd { - cmds := []tea.Cmd{tea.Tick(time.Second, func(time.Time) tea.Msg { return tickMsg{} })} - - m.scanErr = msg.err - if msg.err != nil { - return tea.Batch(cmds...) - } - - groups := map[string][]tmux.Pane{"": {}} - - for _, p := range msg.panes { - if p.Host != "" && p.Terminal == "" { - continue - } - - groups[p.Host] = append(groups[p.Host], p) - if p.ID == m.initialPane { - m.initialHost = p.Host - } - } - - for host, dest := range m.hosts { - if _, ok := groups[host]; !ok && !dest.busy { - delete(m.hosts, host) - cmds = append(cmds, m.updateAgents(ctx)) - - dest.source.Close() - } - } - - for host, panes := range groups { - dest := m.hosts[host] - if dest == nil { - dest = &destination{source: agentdata.Source{Host: host}} - m.hosts[host] = dest - } - - if dest.busy { - continue - } - - dest.busy = true - - cmds = append(cmds, func() tea.Msg { - ctx, cancel := context.WithTimeout(ctx, 8*time.Second) - defer cancel() - - if host != "" && !slices.ContainsFunc(panes, func(p tmux.Pane) bool { return !p.Dead }) { - dest.source.Close() - return StatusMsg{host, agentdata.Snapshot{At: time.Now(), Err: errDisconnected}} - } - - return StatusMsg{host, dest.source.Collect(ctx, panes)} - }) - } - - return tea.Batch(cmds...) -} - -// Close releases the popup's app-server connections. -func (m *Model) Close() { - for _, dest := range m.hosts { - dest.source.Close() - } -} - -// Local is the only source of thread IDs and paths for worktree operations. -func (m *Model) Local() agentdata.Snapshot { return m.hosts[""].data } - -// Choice identifies a specific local view of a conversation. -type Choice struct { - Agent agentdata.Agent - Pane tmux.Pane - Source *agentdata.Source -} - -func (c Choice) key() string { - return c.Pane.ID + "/" + c.Pane.Terminal + "/" + c.Pane.Host + "/" + c.Agent.ID -} - -// Find resolves an agent list row without guessing between duplicate views. -func (m *Model) Find(key string) (Choice, bool) { - c, ok := m.choices[key] - return c, ok -} diff --git a/tools/cmd/tmux-agent-status/ui/agents/sources_test.go b/tools/cmd/tmux-agent-status/ui/agents/sources_test.go deleted file mode 100644 index 14bea1e1..00000000 --- a/tools/cmd/tmux-agent-status/ui/agents/sources_test.go +++ /dev/null @@ -1,35 +0,0 @@ -//nolint:testpackage // Exercise asynchronous status updates without starting a tmux server. -package agents - -import ( - "testing" - - agentdata "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/agents" - "github.com/ddeville/scripts/tools/internal/tmux" -) - -func TestPaneChoicesKeepOriginAndWorktreesSeparate(t *testing.T) { - t.Parallel() - - local := tmux.Pane{ID: "%1"} - first := tmux.Pane{ID: "%2", Host: "dev", Terminal: "codex"} - origin := tmux.Pane{ID: "%3", Host: "dev", Terminal: "shell"} - - m := New(origin.ID) - m.Update(t.Context(), panesMsg{panes: []tmux.Pane{local, first, origin}}) - m.Update(t.Context(), StatusMsg{data: agentdata.Snapshot{Agents: []agentdata.Agent{{ - ID: "shared-id", Panes: []string{local.ID}, Targets: []tmux.Pane{local}, - }}}}) - m.Update(t.Context(), StatusMsg{Host: "dev", data: agentdata.Snapshot{Agents: []agentdata.Agent{{ - ID: "shared-id", Panes: []string{first.ID, origin.ID}, Targets: []tmux.Pane{first, origin}, - }}}}) - - selected, ok := m.Find(m.Panel.List.SelectedID()) - if !ok || selected.Pane != origin || m.Panel.List.Len() != 3 { - t.Fatalf("selected %v among %d choices, want the originating pane among three", selected.Pane, m.Panel.List.Len()) - } - - if m.OriginID() != "" || len(m.Local().Agents) != 1 || m.Local().Agents[0].Targets[0] != local { - t.Fatal("remote conversation exposed as a local worktree fork source") - } -} diff --git a/tools/cmd/tmux-agent-status/ui/agents/view.go b/tools/cmd/tmux-agent-status/ui/agents/view.go index 16cdfd9a..d1b3746a 100644 --- a/tools/cmd/tmux-agent-status/ui/agents/view.go +++ b/tools/cmd/tmux-agent-status/ui/agents/view.go @@ -1,7 +1,6 @@ package agents import ( - "cmp" "encoding/json" "fmt" "slices" @@ -36,55 +35,49 @@ func stateStyle(state string) (lipgloss.Style, string, string) { // Summary describes agents that need attention. func (m *Model) Summary() string { - if m.loading() { - return tui.Muted.Render("Loading agents…") - } + if m.data.Err != nil { + if m.data.At.IsZero() { + return tui.Red.Render("Agent status unavailable") + } - counts := map[string]int{} + return tui.Red.Render("Status unavailable · showing last known data") + } - for _, dest := range m.hosts { - for state, count := range dest.data.Counts { - counts[state] += count - } + if m.data.At.IsZero() { + return tui.Muted.Render("Loading agents…") } var parts []string for _, state := range []string{"approval", "input", "error", "ready"} { - if count := counts[state]; count > 0 { + if count := m.data.Counts[state]; count > 0 { style, label, _ := stateStyle(state) parts = append(parts, style.Render(fmt.Sprintf("%s %d", label, count))) } } if len(parts) == 0 { - if m.issue() != "" { - return tui.Yellow.Render("Some agent status is unavailable") - } - return tui.Muted.Render("Nothing needs your attention") } return "Needs you: " + strings.Join(parts, tui.Muted.Render(" · ")) } -func (c Choice) location() string { - if c.Pane.Host != "" { - return tui.CleanLine(c.Pane.Host + " · " + cmp.Or(c.Agent.Cwd, "Unknown location")) - } - - return cmp.Or(tui.ShortPath(c.Agent.Cwd), "Unknown location") -} - func (m *Model) detailContent(width int) string { - c, ok := m.Find(m.selected) - if !ok { + index := slices.IndexFunc(m.data.Agents, func(a agentdata.Agent) bool { return a.ID == m.selected }) + if index < 0 { return tui.Muted.Render("No conversation selected") } - a := c.Agent + a := m.data.Agents[index] + style, _, hint := stateStyle(a.State) - lines := panel.DetailHeader(a.Title, c.location(), style.Render(hint), "to open pane "+c.Pane.ID) + if len(a.Panes) > 1 { + style = tui.Yellow + hint = fmt.Sprintf("This thread is open in %d tmux panes. Close the extra Codex instance, then try again.", len(a.Panes)) + } + + lines := panel.DetailHeader(a.Title, a.Cwd, style.Render(hint), "to open") if a.Error != nil { lines = append(lines, "", tui.Red.Render(tui.CleanText(*a.Error))) @@ -193,11 +186,11 @@ func activityEntries(data agentdata.Details) []entry { // View renders the agent list and selected conversation. func (m *Model) View() string { empty := "No conversations match this status" - if m.loading() { + if m.data.At.IsZero() { empty = "Loading agents…" } - if m.issue() != "" && len(m.choices) == 0 { + if m.data.Err != nil { empty = "Could not read agent status" } @@ -206,49 +199,17 @@ func (m *Model) View() string { // Message provides connection errors or the current app notice for the footer. func (m *Model) Message(notice string) string { - if notice != "" { - return tui.Muted.Render(tui.CleanLine(notice)) + if m.data.Err != nil { + return tui.Red.Render("Agent status unavailable: " + tui.SingleLine(m.data.Err.Error())) } - if issue := m.issue(); issue != "" { - return tui.Red.Render(tui.SingleLine(issue)) + if notice != "" { + return tui.Muted.Render(tui.CleanLine(notice)) } return "" } -func (m *Model) loading() bool { - if m.scanErr != nil || len(m.choices) != 0 { - return false - } - - for _, dest := range m.hosts { - if dest.data.At.IsZero() { - return true - } - } - - return false -} - -func (m *Model) issue() string { - if m.scanErr != nil { - return m.scanErr.Error() - } - - var issues []string - - for host, dest := range m.hosts { - if err := dest.data.Err; err != nil { - issues = append(issues, cmp.Or(host, "local")+" · "+err.Error()) - } - } - - slices.Sort(issues) - - return strings.Join(issues, " · ") -} - // Toolbar renders status filters and their counts. func (m *Model) Toolbar() string { tabs := make([]string, 0, len(filters)) diff --git a/tools/cmd/tmux-agent-status/ui/model.go b/tools/cmd/tmux-agent-status/ui/model.go index eac0eb75..965d9dbf 100644 --- a/tools/cmd/tmux-agent-status/ui/model.go +++ b/tools/cmd/tmux-agent-status/ui/model.go @@ -3,6 +3,7 @@ package ui import ( "context" + "errors" "fmt" "path/filepath" "time" @@ -10,6 +11,7 @@ import ( "charm.land/bubbles/v2/key" tea "charm.land/bubbletea/v2" + "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/agents" agentui "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/ui/agents" "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/ui/panel" "github.com/ddeville/scripts/tools/cmd/tmux-agent-status/ui/worktrees" @@ -35,25 +37,26 @@ type Options struct { } type model struct { - ctx context.Context //nolint:containedctx // Bubble Tea callbacks share the lifetime of the program. - tasks *tui.Tasks - area, returnArea Area - agents agentui.Model - worktrees worktrees.Model - width, height int - hasOrigin bool - selectionLost bool - notice string - quitting bool - operationCancel context.CancelFunc - client, targetSession string + ctx context.Context //nolint:containedctx // Bubble Tea callbacks share the lifetime of the program. + tasks *tui.Tasks + area, returnArea Area + agents agentui.Model + worktrees worktrees.Model + width, height int + hasOrigin bool + notice string + quitting bool + operationCancel context.CancelFunc + targetPane, targetSession string } type openMsg struct { - session string - err error + pane, session string + err error } +var errStaleStatus = errors.New("status is stale; wait for a fresh update") + func (m *model) Init() tea.Cmd { return tea.Batch(m.agents.Init(m.ctx), m.worktrees.Init(m.ctx)) } func (m *model) activePanel() *panel.Model { @@ -77,19 +80,12 @@ func (m *model) beginCreate() tea.Cmd { id := m.agents.OriginID() if m.area == AgentsArea { - if choice, ok := m.agents.Find(m.agents.Panel.List.SelectedID()); ok { - if choice.Pane.Host != "" { - m.notice = "Worktree creation is local. Choose a local conversation or worktree." - return nil - } - - id = choice.Agent.ID - } + id = m.agents.Panel.List.SelectedID() } else if selected, ok := m.worktrees.Selected(); ok { source = selected.Path } - data := m.agents.Local() + data := m.agents.Snapshot() pending := m.area == WorktreesArea && m.hasOrigin && data.At.IsZero() && data.Err == nil cmd := m.worktrees.BeginCreate(source, id, pending) @@ -110,20 +106,26 @@ func (m *model) openItem(id string) tea.Cmd { m.operationCancel = cancel if m.area == AgentsArea { - choice, ok := m.agents.Find(id) - if !ok { - cancel() - - m.operationCancel = nil - - return nil - } + data := m.agents.Snapshot() return m.tasks.Track(func() tea.Msg { - ctx, stop := context.WithTimeout(ctx, 3*time.Second) + if data.Err != nil || time.Since(data.At) > 10*time.Second { + return openMsg{err: errStaleStatus} + } + + ctx, stop := context.WithTimeout(ctx, time.Second) defer stop() - return openMsg{err: choice.Source.Open(ctx, choice.Agent.ID, choice.Pane, m.client)} + panes, err := agents.MatchPanes(ctx, data.IDs) + if err != nil { + return openMsg{err: err} + } + + if len(panes[id]) != 1 { + return openMsg{err: fmt.Errorf("%w, found %d", agents.ErrPaneMatch, len(panes[id]))} + } + + return openMsg{pane: panes[id][0]} }) } @@ -166,7 +168,7 @@ func (m *model) Update(message tea.Msg) (tea.Model, tea.Cmd) { //nolint:ireturn case msg.err != nil: m.notice = tui.SingleLine(msg.err.Error()) default: - m.targetSession = msg.session + m.targetPane, m.targetSession = msg.pane, msg.session cmd = tea.Quit } case worktrees.OpenSessionMsg: @@ -174,8 +176,8 @@ func (m *model) Update(message tea.Msg) (tea.Model, tea.Cmd) { //nolint:ireturn cmd = tea.Quit default: cmd = tea.Batch(m.agents.Update(m.ctx, msg), m.worktrees.Update(m.ctx, msg)) - if update, ok := msg.(agentui.StatusMsg); ok && update.Host == "" { - m.worktrees.SetAgents(m.agents.Local(), m.agents.OriginID()) + if _, ok := msg.(agents.Snapshot); ok { + m.worktrees.SetAgents(m.agents.Snapshot(), m.agents.OriginID()) } if m.quitting && !m.busy() { @@ -184,14 +186,7 @@ func (m *model) Update(message tea.Msg) (tea.Model, tea.Cmd) { //nolint:ireturn } if selected != m.agents.Panel.List.SelectedID() { - if _, input := message.(tea.KeyPressMsg); input { - m.selectionLost = false - m.notice = "" - } else if _, ok := m.agents.Find(selected); selected != "" && !ok { - // A refresh can remove the highlighted thread and select the first - // row. A pending Enter must not open that replacement. - m.selectionLost = true - } + m.notice = "" } return m, cmd @@ -247,13 +242,6 @@ func (m *model) handleKey(msg tea.KeyPressMsg) tea.Cmd { case key.Matches(msg, keys.refresh) && m.area == WorktreesArea: return m.worktrees.Reload(m.worktrees.Panel.List.SelectedID()) case key.Matches(msg, keys.open): - if m.area == AgentsArea && m.selectionLost { - m.selectionLost = false - m.notice = "The previous conversation disappeared. Choose a pane or press Enter again." - - return nil - } - return m.openItem(m.activePanel().List.SelectedID()) case key.Matches(msg, keys.jump): position := int(msg.String()[0] - '0') @@ -287,12 +275,10 @@ func Run(ctx context.Context, options Options) error { } initial := &model{ - ctx: uiCtx, tasks: tasks, client: options.Client, area: options.Area, width: 100, height: 30, hasOrigin: options.Pane != "", + ctx: uiCtx, tasks: tasks, area: options.Area, width: 100, height: 30, hasOrigin: options.Pane != "", agents: agentui.New(options.Pane), worktrees: worktrees.New(options.Root, source, tasks), } - defer initial.agents.Close() - initial.updatePanels() result, err := tea.NewProgram(initial, tea.WithContext(uiCtx), tea.WithoutSignalHandler()).Run() @@ -302,9 +288,17 @@ func Run(ctx context.Context, options Options) error { return fmt.Errorf("run status TUI: %w", err) } - if final, ok := result.(*model); ok && final.targetSession != "" { - if err := tmux.SwitchSession(ctx, final.targetSession, options.Client); err != nil { - return fmt.Errorf("open worktree session: %w", err) + if final, ok := result.(*model); ok { + if final.targetPane != "" { + if err := tmux.SwitchPane(ctx, final.targetPane, options.Client); err != nil { + return fmt.Errorf("open selected agent: %w", err) + } + } + + if final.targetSession != "" { + if err := tmux.SwitchSession(ctx, final.targetSession, options.Client); err != nil { + return fmt.Errorf("open worktree session: %w", err) + } } } diff --git a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md index 817c116b..7121a7d3 100644 --- a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md +++ b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md @@ -14,12 +14,15 @@ the project directory. Sessions using the same SSH destination share one OpenSSH connection. Use the same SSH alias across projects. Each pane uses one of sshd's `MaxSessions` slots. `tm` reserves one slot per -connection for discovery, closes and the agent popup. With a limit of 10, up +connection for workspace discovery and closing terminals. With a limit of 10, up to nine panes can share the connection across projects and local tmux servers. -Startup checks capacity with short-lived SSH commands. A fresh workspace needs -room for all three windows. A rejected split closes with a tmux message. -The popup yields the slot between requests. A full connection never falls back -to a second login. +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. The supervisor opens the first connection before creating any panes. All logins use batch @@ -39,17 +42,9 @@ to a second login. - **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. -- **Open Codex** with prefix `a`. The popup groups remote conversations by host - and directory, including Codex started manually in a split. Choose a pane - when a thread has multiple views. Enter rechecks the thread and pane before - switching the invoking client. Worktree actions and the CLI status feed stay local. 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. -Remote status requires a shared Codex app server, `codex app-server proxy` on -the SSH command path, and `thread-id` last in `tui.terminal_title`. The popup -uses the same title matching locally and remotely. A shortened ID must match -exactly one loaded thread on that host. A stale or forged title can misidentify -a conversation. The popup only queries each app server while open. +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 index b1509456..953f628c 100644 --- a/tools/cmd/tmux-session/launch.go +++ b/tools/cmd/tmux-session/launch.go @@ -1,6 +1,7 @@ package main import ( + "cmp" "context" "crypto/rand" "errors" @@ -9,143 +10,78 @@ import ( "net" "os" "path/filepath" - "time" "github.com/ddeville/scripts/tools/internal/sshmux" + "github.com/ddeville/scripts/tools/internal/tmux" ) -var errPaneLimit = errors.New("SSH pane limit") - -func capacityError(dest sshmux.Destination, want, free int) error { - return fmt.Errorf("%s: %w (need %d, free %d, 1 reserved for management)", dest.Host, errPaneLimit, want, free) -} - -// The local tmux server forks pane helpers asynchronously. Hold the destination -// lock until each helper confirms that its SSH session opened. -func launch(ctx context.Context, dest sshmux.Destination, count int, layout func(string) error) error { - if count == 0 { - return nil +// Give sshd the real requests in order, with the management slot occupied. +func startPanes(ctx context.Context, dest sshmux.Destination, target *tmux.Session, windows []window) (int, error) { + if len(windows) == 0 { + return 0, nil } - token := rand.Text()[:16] - socket := filepath.Join(filepath.Dir(dest.Socket), "open-"+token) - - listener, err := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: socket}) + helper, err := os.Executable() if err != nil { - return fmt.Errorf("listen for pane startup: %w", err) - } - defer func() { _ = listener.Close() }() - - if err := layout(token); err != nil { - return err - } - - ctx, cancel := context.WithTimeout(ctx, 15*time.Second) - defer cancel() - - stop := context.AfterFunc(ctx, func() { _ = listener.Close() }) - defer stop() - - var panes []net.Conn - - for range count { - conn, err := listener.Accept() - if err != nil { - return fmt.Errorf("wait for local panes: %w", err) - } - - panes = append(panes, conn) - defer func() { _ = conn.Close() }() + return 0, fmt.Errorf("locate tmux-session: %w", err) } - for _, conn := range panes { - if _, err := conn.Write([]byte{'+'}); err != nil { - return fmt.Errorf("start pane: %w", err) + for i, win := range windows { + reply := filepath.Join(filepath.Dir(dest.Socket), "open-"+rand.Text()[:16]) + if err := win.start(ctx, target, helper, reply); err != nil { + return i, err } } - for _, conn := range panes { - if err := ready(ctx, conn); err != nil { - return fmt.Errorf("SSH pane did not start: %w", err) - } - } - - return nil + return len(windows), nil } -func ready(ctx context.Context, conn net.Conn) error { - stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) - defer stop() - - var reply [1]byte - if _, err := io.ReadFull(conn, reply[:]); err != nil { - return fmt.Errorf("wait for startup: %w", err) - } - - if reply[0] != '+' { - return fmt.Errorf("%w: unexpected startup reply", os.ErrInvalid) +// 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() }() - return nil -} - -// A split or raw respawn has no supervisor waiting for it. Check capacity -// under the same lock, releasing it once SSH opens or the helper fails. -func admit(ctx context.Context, dest sshmux.Destination, token string) (func(bool), error) { - if token != "" && token == filepath.Base(token) { - socket := filepath.Join(filepath.Dir(dest.Socket), "open-"+token) - - hold, err := dest.Hold(ctx) - if err != nil { - return nil, fmt.Errorf("hold pane slot: %w", err) - } - - conn, err := (&net.Dialer{}).DialContext(ctx, "unix", socket) - if err != nil { - _ = hold.Close() - return nil, fmt.Errorf("contact pane supervisor: %w", err) - } - - if err := ready(ctx, conn); err != nil { - _ = hold.Close() - _ = conn.Close() - - return nil, err - } - - return func(open bool) { - _ = hold.Close() - - if open { - _, _ = conn.Write([]byte{'+'}) - } - - _ = conn.Close() - }, nil + 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...) } - lock, err := dest.Lock(ctx) if err != nil { - return nil, fmt.Errorf("lock destination: %w", err) + return fmt.Errorf("start %s: %w", w.role, err) } - if err := requireCapacity(ctx, dest, 1); err != nil { - _ = lock.Close() - return nil, 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() }() - return func(bool) { _ = lock.Close() }, nil -} + stop = context.AfterFunc(ctx, func() { _ = conn.Close() }) + defer stop() -func requireCapacity(ctx context.Context, dest sshmux.Destination, want int) error { - free, err := dest.Capacity(ctx, want) + result, err := io.ReadAll(conn) if err != nil { - return fmt.Errorf("check SSH capacity: %w", err) + return fmt.Errorf("read pane startup: %w", err) } - if free < want { - return capacityError(dest, want, free) + 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. } - - return nil } diff --git a/tools/cmd/tmux-session/main.go b/tools/cmd/tmux-session/main.go index c7cf9d84..8a54bcc1 100644 --- a/tools/cmd/tmux-session/main.go +++ b/tools/cmd/tmux-session/main.go @@ -3,10 +3,12 @@ package main import ( "context" + "errors" "fmt" "os" "path/filepath" "syscall" + "time" "github.com/spf13/cobra" @@ -24,7 +26,7 @@ func main() { func command() *cobra.Command { var ( name, host, watch string - launch, batch, closeTarget string + launch, reply, closeTarget string noSwitch bool ) @@ -42,7 +44,7 @@ func command() *cobra.Command { } if launch != "" { - code, err := attachPane(cmd.Context(), launch, batch) + code, err := attachPane(cmd.Context(), launch, reply) if err != nil { cmd.PrintErrln(tui.CleanLine(err.Error())) } @@ -100,8 +102,8 @@ func command() *cobra.Command { 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(&batch, "pane-batch", "", "confirm startup with the supervisor") - cmd.Flags().Lookup("pane-batch").Hidden = true + cmd.Flags().StringVar(&reply, "pane-reply", "", "report pane startup to the supervisor") + cmd.Flags().Lookup("pane-reply").Hidden = true cmd.Flags().StringVar(&watch, "supervise", "", "supervise a remote connection") cmd.Flags().Lookup("supervise").Hidden = true cmd.Flags().StringVar(&closeTarget, "remote-close", "", "close a pane or window by ID") @@ -135,27 +137,46 @@ func resolveDirectory(path string) (string, error) { } // lockOpen serializes lookup and layout creation, including the first tmux server startup. -func lockOpen() (*os.File, error) { +func lockOpen(ctx context.Context) (*os.File, error) { dir, err := sshmux.CacheDir() if err != nil { return nil, fmt.Errorf("locate tmux session cache: %w", err) } - return lockFile(filepath.Join(dir, "open.lock")) + return lockFile(ctx, filepath.Join(dir, "open.lock")) } -func lockFile(filename string) (*os.File, error) { +// All tmux servers sharing a master use the same management slot. +func lockDestination(ctx context.Context, dest sshmux.Destination) (*os.File, error) { + return lockFile(ctx, dest.Socket+".lock") +} + +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, path, name string) (tmux.Session, bool, error) { @@ -168,7 +189,7 @@ func openSession(ctx context.Context, path, name string) (tmux.Session, bool, er name = filepath.Base(directory) } - lock, err := lockOpen() + lock, err := lockOpen(ctx) if err != nil { return tmux.Session{}, false, err } diff --git a/tools/cmd/tmux-session/pane.go b/tools/cmd/tmux-session/pane.go index f4ae1790..edcb60c0 100644 --- a/tools/cmd/tmux-session/pane.go +++ b/tools/cmd/tmux-session/pane.go @@ -7,12 +7,15 @@ import ( "encoding/json" "errors" "fmt" + "io" + "net" "os" "os/exec" "path" "slices" "strconv" "strings" + "sync" "syscall" "time" @@ -22,23 +25,56 @@ import ( ) 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 - printf '\000' # If it exits between get and attach, zmx must never relaunch its program. - exec zmx attach "$2" /bin/sh -c 'exit 1' + 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 -cd -P -- "$3" printf '\000' -case "$1" in -editor) exec zmx attach "$2" sh -c "exec ${EDITOR:-nvim}" ;; -codex) exec zmx attach "$2" codex ;; -*) exec zmx attach "$2" ;; -esac` - -func attachPane(ctx context.Context, requested, batch string) (int, error) { - // Until an existing terminal can be reattached, keep a setup failure - // retryable on its original SSH generation. +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 supervisor 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 @@ -82,57 +118,77 @@ func attachPane(ctx context.Context, requested, batch string) (int, error) { return failure, fmt.Errorf("find pane connection: %w", err) } - finish, err := admit(ctx, dest, batch) - if batch != "" && dir == "" && (errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ECONNREFUSED)) { - // respawn-pane can replay the original command after a batch ends. - finish, err = admit(ctx, dest, "") - } - - if err != nil { - if original := panes[id]; original.Terminal == "" && errors.Is(err, errPaneLimit) { - _ = original.CloseOnExit(ctx) - } + sshCtx, cancel := context.WithCancel(ctx) + defer cancel() - _ = tmux.Notify(ctx, "tm: "+tui.CleanLine(err.Error())) + timer := time.AfterFunc(15*time.Second, cancel) + defer timer.Stop() - return failure, err - } + // Splits have no supervisor holding the management session for them. + if ready == nil { + lock, err := lockDestination(sshCtx, dest) + if err != nil { + return failure, err + } - defer finish(false) + m, err := openManagement(sshCtx, dest, "") + if err != nil { + _ = lock.Close() - ctx, cancel := context.WithCancel(ctx) - defer cancel() + if dir != "" { + _ = panes[id].CloseOnExit(ctx) + } - timer := time.AfterFunc(15*time.Second, cancel) - defer timer.Stop() + return failure, fmt.Errorf("reserve management slot: %w", err) + } - // Record before launching. An ambiguous failure can only reattach here. - p.Connection = dest.Generation() + ready = sync.OnceFunc(func() { m.close(); _ = lock.Close() }) + defer ready() + } project := "" if dir != "" { project = displayName(path.Base(dir)) } - if err := p.Record(ctx, project); err != nil { + // Record before launching. An ambiguous failure can only reattach here. + if err := p.Record(sshCtx, project); err != nil { return failure, fmt.Errorf("record remote pane: %w", err) } - cmd := exec.CommandContext(ctx, "ssh", dest.Channel("-tt", remoteCommand(attach, mode, p.Terminal, dir))...) // #nosec G204 -- Pinned master and quoted arguments. + var stderr bytes.Buffer + + output := &paneOutput{opened: func() { timer.Stop(); ready() }} + cmd := exec.CommandContext(sshCtx, "ssh", dest.Channel("-tt", remoteCommand(attach, mode, p.Terminal, dir))...) // #nosec G204 -- Pinned master and quoted arguments. cmd.SysProcAttr = &syscall.SysProcAttr{Foreground: true} - cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr - cmd.Stdout = &paneOutput{opened: func() { timer.Stop(); finish(true) }} + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, output, io.MultiWriter(os.Stderr, &stderr) cmd.WaitDelay = time.Second - if err := cmd.Run(); err != nil { - if exit, ok := errors.AsType[*exec.ExitError](err); ok { - return max(1, exit.ExitCode()), nil + 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 1, fmt.Errorf("run SSH pane: %w", err) + return code, fmt.Errorf("%w on %s (one MaxSessions slot is reserved for management)", sshmux.ErrChannelRefused, p.Host) } - return 0, nil + return code, fmt.Errorf("SSH %s: %w", p.Host, err) } type paneOutput struct{ opened func() } @@ -156,7 +212,7 @@ func (w *paneOutput) Write(data []byte) (int, error) { const stop = `zmx kill "$1" >/dev/null || [ "$2" = true ] ` + listTerminals -func stopTerminal(ctx context.Context, p *tmux.Attachment) error { +func stopTerminal(ctx context.Context, p tmux.Attachment) error { if !terminalID.MatchString(p.Terminal) { return fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) } @@ -168,23 +224,13 @@ func stopTerminal(ctx context.Context, p *tmux.Attachment) error { command := remoteCommand(stop, p.Terminal, strconv.FormatBool(p.Dead)) - lock, err := dest.Lock(ctx) + lock, err := lockDestination(ctx, dest) if err != nil { - return fmt.Errorf("lock destination: %w", err) + return err } defer func() { _ = lock.Close() }() out, err := dest.Query(ctx, command) - if errors.Is(err, sshmux.ErrChannelRefused) && !p.Dead { - // At MaxSessions, free this attachment's slot for the close command. - if err := p.Disconnect(ctx); err != nil { - return fmt.Errorf("disconnect pane: %w", err) - } - - p.Dead = true - out, err = dest.Query(ctx, command) - } - if err != nil { return fmt.Errorf("stop terminal: %w", err) } @@ -207,38 +253,32 @@ func closePanes(ctx context.Context, target string) error { return fmt.Errorf("find close target: %w", err) } - var live, dead, local []tmux.Attachment + var local []tmux.Attachment + + remote := false for _, p := range panes { if p.ID != target && p.WindowID != target { continue } - switch { - case p.Terminal == "": - local = append(local, p) - case p.Dead: - dead = append(dead, p) - default: - live = append(live, p) - } - } + if p.Terminal != "" { + if err := stopTerminal(ctx, p); err != nil { + return fmt.Errorf("could not confirm remote close for %s: %w", p.ID, err) + } - if len(live)+len(dead) == 0 { - return fmt.Errorf("%w: no remote terminal at %s", os.ErrInvalid, target) - } - - // Live clients exit with zmx and can free channels for the remaining closes. - for _, p := range append(live, dead...) { - 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 { + 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) diff --git a/tools/cmd/tmux-session/remote.go b/tools/cmd/tmux-session/remote.go index 1f8fefba..9b6ef1ad 100644 --- a/tools/cmd/tmux-session/remote.go +++ b/tools/cmd/tmux-session/remote.go @@ -1,12 +1,15 @@ package main import ( + "bufio" + "bytes" "cmp" "context" "crypto/sha256" "encoding/json" "fmt" "os" + "os/exec" "path" "regexp" "slices" @@ -48,6 +51,7 @@ var ( type window struct { role, terminal string + pane tmux.Attachment } const listTerminals = `zmx list @@ -108,7 +112,71 @@ cd -P -- "$1" printf '%s\000' "$PWD" ` + listTerminals -func openWorkspace(ctx context.Context, dest sshmux.Destination, request, name string) (tmux.Session, bool, error) { +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, dest sshmux.Destination, request string) (management, error) { + script := inspect + if request == "" { + script = `printf '\000\000'` + } + + command := remoteCommand(script+"\nread -r done || :", request) + cmd := exec.CommandContext(ctx, "ssh", dest.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", dest.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 +} + +func openWorkspace(ctx context.Context, dest sshmux.Destination, request, name string) (openResult, error) { + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + if request == "~" { request = "." } @@ -117,22 +185,22 @@ func openWorkspace(ctx context.Context, dest sshmux.Destination, request, name s request = "./" + strings.TrimPrefix(request, "~/") } - out, err := dest.Query(ctx, remoteCommand(inspect, request)) + m, err := openManagement(ctx, dest, request) if err != nil { - return tmux.Session{}, false, fmt.Errorf("inspect workspace: %w", err) + return openResult{}, fmt.Errorf("inspect workspace: %w", err) } + defer m.close() - dir, list, ok := strings.Cut(out, "\x00") - if !ok || !path.IsAbs(dir) || !utf8.ValidString(dir) { - return tmux.Session{}, false, fmt.Errorf("%w: invalid remote directory", os.ErrInvalid) + if !path.IsAbs(m.dir) || !utf8.ValidString(m.dir) { + return openResult{}, fmt.Errorf("%w: invalid remote directory", os.ErrInvalid) } - names, err := inventory(list) + names, err := inventory(m.listing) if err != nil { - return tmux.Session{}, false, err + return openResult{}, err } - w := workspace{Host: dest.Host, Path: dir, Name: cmp.Or(name, path.Base(dir))} + w := workspace{Host: dest.Host, Path: m.dir, Name: cmp.Or(name, path.Base(m.dir))} return w.open(ctx, dest, names) } @@ -179,26 +247,18 @@ func (w workspace) windows(names map[string]bool, panes map[string]tmux.Attachme return windows, nil } -func (w workspace) open(ctx context.Context, dest sshmux.Destination, names map[string]bool) (tmux.Session, bool, error) { - helper, err := os.Executable() - if err != nil { - return tmux.Session{}, false, fmt.Errorf("locate tmux-session: %w", err) - } - +func (w workspace) open(ctx context.Context, dest sshmux.Destination, names map[string]bool) (openResult, error) { meta, err := json.Marshal(w) if err != nil { - return tmux.Session{}, false, fmt.Errorf("encode workspace: %w", err) + return openResult{}, fmt.Errorf("encode workspace: %w", err) } - ctx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - sessions, err := tmux.ListSessions(ctx) if err != nil { - return tmux.Session{}, false, fmt.Errorf("list sessions: %w", err) + return openResult{}, fmt.Errorf("list sessions: %w", err) } - var target tmux.Session + target := tmux.Session{Name: displayName(w.Host + "/" + w.Name), Remote: string(meta)} for _, s := range sessions { if s.Remote == string(meta) { @@ -211,7 +271,7 @@ func (w workspace) open(ctx context.Context, dest sshmux.Destination, names map[ if len(sessions) != 0 { panes, err = tmux.Attachments(ctx, "") if err != nil { - return tmux.Session{}, false, fmt.Errorf("find existing remote panes: %w", err) + return openResult{}, fmt.Errorf("find existing remote panes: %w", err) } } @@ -219,59 +279,39 @@ func (w workspace) open(ctx context.Context, dest sshmux.Destination, names map[ windows, err := w.windows(names, panes, created) if err != nil { - return tmux.Session{}, false, err + return openResult{}, err } - var resume []tmux.Attachment - prefix := w.prefix() for _, p := range panes { if p.Host == w.Host && p.Dead && strings.HasPrefix(p.Terminal, prefix) && names[p.Terminal] && terminalID.MatchString(p.Terminal) { - resume = append(resume, p) + windows = append(windows, window{role: p.ID, terminal: p.Terminal, pane: p}) } } - want := len(windows) + len(resume) - - if err := requireCapacity(ctx, dest, want); err != nil { - return tmux.Session{}, false, err - } - - err = launch(ctx, dest, want, func(token string) error { - if err := resumePanes(ctx, helper, token, resume); err != nil { - return err - } - - if created { - target.Name, target.Remote = displayName(w.Host+"/"+w.Name), string(meta) - - if err := createRemote(ctx, &target, windows[0], helper, token); err != nil { - return err - } + target.Path = w.Path + result := openResult{Session: target, Created: created} - windows = windows[1:] + started, err := startPanes(ctx, dest, &result.Session, windows) + if err != nil { + if created && started == 0 { + return openResult{}, err } - for _, win := range windows { - if err := tmux.StartWindow(ctx, target.ID, win.role, "", helper, "--remote-pane", cmp.Or(win.terminal, win.role), "--pane-batch", token); err != nil { - return fmt.Errorf("create remote window: %w", err) - } + var missing []string + for _, win := range windows[started:] { + missing = append(missing, win.role) } - return nil - }) - if err != nil { - return tmux.Session{}, false, err + result.Warning = fmt.Sprintf("could not open %s: %v", strings.Join(missing, ", "), err) } - target.Path = w.Path - - return target, created, nil + return result, nil } -func createRemote(ctx context.Context, target *tmux.Session, first window, helper, token string) error { +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() + lock, err := lockOpen(ctx) if err != nil { return err } @@ -284,21 +324,10 @@ func createRemote(ctx context.Context, target *tmux.Session, first window, helpe target.Name = tmux.AvailableName(sessions, target.Name) - target.ID, err = tmux.NewRemoteSession(ctx, *target, first.role, "exec "+quote(helper)+" --remote-pane shell", - helper, "--remote-pane", cmp.Or(first.terminal, first.role), "--pane-batch", token) + 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 } - -func resumePanes(ctx context.Context, helper, token string, panes []tmux.Attachment) error { - for _, p := range panes { - if err := p.Resume(ctx, helper, "--remote-pane", p.Terminal, "--pane-batch", token); err != nil { - return fmt.Errorf("resume pane %s: %w", p.ID, err) - } - } - - return nil -} diff --git a/tools/cmd/tmux-session/remote_test.go b/tools/cmd/tmux-session/remote_test.go index 0426c724..1c7c3801 100644 --- a/tools/cmd/tmux-session/remote_test.go +++ b/tools/cmd/tmux-session/remote_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "os" + "os/exec" "path/filepath" "slices" "testing" @@ -13,23 +14,17 @@ import ( "github.com/ddeville/scripts/tools/internal/tmux" ) -func TestWorkspaceChecksAllPaneSlotsBeforeCreatingWindows(t *testing.T) { +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 -for slot in 1 2 3; do - if mkdir "$slot" 2>/dev/null; then - trap 'rmdir "$slot"' EXIT - sh -c "$command" - exit $? - fi -done -echo 'Session open refused by peer' >&2 -exit 255 +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) @@ -37,28 +32,29 @@ exit 255 dest := sshmux.Destination{Host: "devbox", Socket: filepath.Join(dir, "master")} - const tm = `#!/bin/sh -[ "$1" != -u ] || shift -if [ "$1" = list-sessions ]; then exit 0; fi -echo "$1" > unexpected -exit 1 -` - if err := os.WriteFile("tmux", []byte(tm), 0o700); err != nil { // #nosec G306 -- Executable fixture in a private test directory. + 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) } - // Three slots are free, but one is needed for discovery, close and status. - w := workspace{Host: dest.Host, Path: "/project", Name: "project"} - if _, _, err := w.open(t.Context(), dest, nil); !errors.Is(err, errPaneLimit) { - t.Fatalf("expected refusal of a three-window workspace, got %v", 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 command, err := os.ReadFile("unexpected"); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("tmux command before capacity check: %q, %v", command, err) + if !errors.Is(err, sshmux.ErrChannelRefused) { + t.Fatalf("expected refusal while session held, got %v", err) } - if err := requireCapacity(t.Context(), dest, 2); err != nil { - t.Fatalf("refused batch did not release its probes: %v", err) + if _, err := dest.Query(t.Context(), "true"); err != nil { + t.Fatalf("session not released: %v", err) } } @@ -124,6 +120,15 @@ func TestRecoveryOnlyRetriesSSHFailuresOnThisDestination(t *testing.T) { } } +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. @@ -153,7 +158,7 @@ list-panes) : > failed exit 1 fi - printf '%%1\t@1\t0\tdev\ttm-1234567890abcdef1234.shell-AAAAAAAAAAAAA\t1\t\t1\n' + printf '%%1\t@1\t0\tdev\ttm-1234567890abcdef1234.shell-AAAAAAAAAAAAA\t1\t\n' ;; wait-for) : > stopped ;; *) exit 1 ;; @@ -163,7 +168,7 @@ esac t.Fatal(err) } - watch, err := lockFile("watch") + watch, err := lockFile(t.Context(), "watch") if err != nil { t.Fatal(err) } diff --git a/tools/cmd/tmux-session/supervisor.go b/tools/cmd/tmux-session/supervisor.go index 708346f0..974303fd 100644 --- a/tools/cmd/tmux-session/supervisor.go +++ b/tools/cmd/tmux-session/supervisor.go @@ -23,6 +23,7 @@ import ( type openResult struct { Session tmux.Session `json:"session"` Created bool `json:"created"` + Warning string `json:"warning,omitempty"` Error string `json:"error,omitempty"` } @@ -75,6 +76,12 @@ func openRemote(ctx context.Context, host, path, name string) (tmux.Session, boo return tmux.Session{}, false, errors.New(result.Error) //nolint:err113 // The child sends the original diagnostic. } + if result.Warning != "" { + message := "tm: " + tui.CleanLine(result.Warning) + _, _ = fmt.Fprintln(os.Stderr, message) + _ = tmux.Notify(ctx, message) + } + return result.Session, result.Created, nil } @@ -134,9 +141,9 @@ func prepare(ctx context.Context, dest sshmux.Destination, result *openResult) ( return nil, fmt.Errorf("read workspace request: %w", err) } - lock, err := dest.Lock(ctx) + lock, err := lockDestination(ctx, dest) if err != nil { - return nil, fmt.Errorf("lock destination: %w", err) + return nil, err } defer func() { _ = lock.Close() }() @@ -145,7 +152,7 @@ func prepare(ctx context.Context, dest sshmux.Destination, result *openResult) ( return nil, fmt.Errorf("SSH: %w", err) } - result.Session, result.Created, err = openWorkspace(ctx, dest, w.Path, w.Name) + *result, err = openWorkspace(ctx, dest, w.Path, w.Name) if err != nil { return nil, err } @@ -168,22 +175,17 @@ func prepare(ctx context.Context, dest sshmux.Destination, result *openResult) ( } func watchPanes(ctx context.Context, dest sshmux.Destination, watch *os.File) error { - helper, err := os.Executable() - if err != nil { - return fmt.Errorf("locate tmux-session: %w", err) - } - backoff := time.Second notified := false for ctx.Err() == nil { // Explicit opens and automatic retries must never start competing masters. - lock, err := dest.Lock(ctx) + lock, err := lockDestination(ctx, dest) if err != nil { - return fmt.Errorf("lock destination: %w", err) + return err } - active, err := recoverPanes(ctx, dest, helper, lock) + active, err := recoverPanes(ctx, dest, lock) done := (!active && err == nil) || errors.Is(err, sshmux.ErrSignIn) if done { @@ -224,7 +226,7 @@ func watchPanes(ctx context.Context, dest sshmux.Destination, watch *os.File) er return nil } -func recoverPanes(ctx context.Context, dest sshmux.Destination, helper string, lock *os.File) (bool, error) { +func recoverPanes(ctx context.Context, dest sshmux.Destination, lock *os.File) (bool, error) { ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() @@ -281,37 +283,20 @@ func recoverPanes(ctx context.Context, dest sshmux.Destination, helper string, l return true, fmt.Errorf("restore connection: %w", connectErr) } - generation := dest.Generation() - if generation == "" { - return true, fmt.Errorf("%w: missing SSH master", os.ErrNotExist) - } - - var resume []tmux.Attachment - - for _, p := range failed { - if p.Connection != generation { - resume = append(resume, p) - } - } - - free, err := dest.Capacity(ctx, len(resume)) + m, err := openManagement(ctx, dest, "") if err != nil { - return true, fmt.Errorf("check SSH capacity: %w", err) + return true, fmt.Errorf("open management session: %w", err) } + defer m.close() - if err := launch(ctx, dest, free, func(token string) error { - return resumePanes(ctx, helper, token, resume[:free]) - }); err != nil { - return true, err + resume := make([]window, 0, len(failed)) + for _, p := range failed { + resume = append(resume, window{role: p.ID, terminal: p.Terminal, pane: p}) } - // A replacement connection can have a lower limit. Leave the other panes - // untouched so they can resume as slots become available. - if free < len(resume) { - return true, capacityError(dest, len(resume), free) - } + _, err = startPanes(ctx, dest, nil, resume) - return true, nil + return true, err } func interrupted(panes map[string]tmux.Attachment, host string) (bool, []tmux.Attachment) { diff --git a/tools/internal/codex/client.go b/tools/internal/codex/client.go index 0a544215..608ee43c 100644 --- a/tools/internal/codex/client.go +++ b/tools/internal/codex/client.go @@ -1,22 +1,18 @@ -// Package codex reads status and activity from a Codex app server. +// Package codex provides a client for the local Codex app server. package codex import ( "context" "encoding/json" "fmt" - "io" "net" "net/http" "os" - "os/exec" "path/filepath" "time" "github.com/coder/websocket" "github.com/coder/websocket/wsjson" - - "github.com/ddeville/scripts/tools/internal/sshmux" ) // RPCError is an error returned by the app server. @@ -26,13 +22,14 @@ type RPCError struct { func (e *RPCError) Error() string { return e.Message } -// Client sends sequential requests over an app-server connection. +// Client sends sequential requests over a local app-server connection. type Client struct { conn *websocket.Conn id int } -func dialLocal(ctx context.Context) (net.Conn, error) { +// Connect opens and initializes an app-server connection. +func Connect(ctx context.Context) (*Client, error) { home := os.Getenv("CODEX_HOME") if home == "" { userHome, err := os.UserHomeDir() @@ -45,87 +42,8 @@ func dialLocal(ctx context.Context) (net.Conn, error) { socket := filepath.Join(home, "app-server-control", "app-server-control.sock") - conn, err := (&net.Dialer{}).DialContext(ctx, "unix", socket) - if err != nil { - return nil, fmt.Errorf("open control socket: %w", err) - } - - return conn, nil -} - -// Keep the full control socket off the local filesystem. Only this process -// holds the proxy channel, which carries the same WebSocket as the local socket. -func dialRemote(ctx context.Context, host string) (net.Conn, error) { - dest, err := sshmux.ForHost(host) - if err != nil { - return nil, fmt.Errorf("find SSH connection: %w", err) - } - - // The WebSocket can outlive the HTTP handshake. Closing the pipe ends ssh. - cmd := exec.CommandContext(context.WithoutCancel(ctx), "ssh", dest.Channel("-T", "exec codex app-server proxy")...) // #nosec G204 -- Fixed command on a validated, existing master. - cmd.WaitDelay = time.Second - - stdin, err := cmd.StdinPipe() - if err != nil { - return nil, fmt.Errorf("open proxy stdin: %w", err) - } - - local, peer := net.Pipe() - - cmd.Stdout = peer - if err := cmd.Start(); err != nil { - return nil, fmt.Errorf("start Codex proxy: %w", err) - } - - go func() { - _, _ = io.Copy(stdin, peer) - _ = stdin.Close() - }() - - done := make(chan struct{}) - - go func() { - _ = cmd.Wait() - _ = peer.Close() - - close(done) - }() - - return &proxyConn{Conn: local, process: cmd.Process, done: done}, nil -} - -// Wait for ssh to return the session slot before another command needs it. -type proxyConn struct { - net.Conn - - process *os.Process - done <-chan struct{} -} - -func (p *proxyConn) Close() error { - err := p.Conn.Close() - select { - case <-p.done: - case <-time.After(time.Second): - _ = p.process.Kill() - <-p.done - } - - if err != nil { - return fmt.Errorf("close Codex proxy: %w", err) - } - - return nil -} - -// Connect opens the local app server or the one on an existing SSH destination. -func Connect(ctx context.Context, host string) (*Client, error) { transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { - if host != "" { - return dialRemote(ctx, host) - } - - return dialLocal(ctx) + return (&net.Dialer{}).DialContext(ctx, "unix", socket) }} defer transport.CloseIdleConnections() @@ -136,10 +54,6 @@ func Connect(ctx context.Context, host string) (*Client, error) { HTTPClient: &http.Client{Transport: transport}, }) if err != nil { - if host != "" { - return nil, fmt.Errorf("proxy unavailable (check Codex and SSH MaxSessions): %w", err) - } - return nil, fmt.Errorf("connect to Codex: %w", err) } diff --git a/tools/internal/sshmux/capacity.go b/tools/internal/sshmux/capacity.go deleted file mode 100644 index 3969e75f..00000000 --- a/tools/internal/sshmux/capacity.go +++ /dev/null @@ -1,107 +0,0 @@ -package sshmux - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "os" - "os/exec" - "time" -) - -// Capacity checks room for up to want panes and one management channel. -// sshd does not advertise MaxSessions. Hold the probes simultaneously, and -// keep the destination locked until the real pane channels have opened. -func (d Destination) Capacity(ctx context.Context, want int) (int, error) { - if want == 0 { - return 0, nil - } - - ctx, cancel := context.WithTimeout(ctx, 15*time.Second) - defer cancel() - - var ( - held []*probe - err error - ) - - for range want + 1 { - var p *probe - - p, err = d.probe(ctx) - if err != nil { - if errors.Is(err, ErrChannelRefused) && len(held) > 0 { - err = nil - } - - break - } - - held = append(held, p) - } - - for _, p := range held { - _, _ = io.WriteString(p.in, "\n") - _ = p.in.Close() - } - - for _, p := range held { - if waitErr := p.cmd.Wait(); waitErr != nil && err == nil { - err = d.commandError(waitErr, p.stderr.String()) - } - } - - if err != nil { - return 0, err - } - - return len(held) - 1, nil -} - -type probe struct { - cmd *exec.Cmd - in io.WriteCloser - stderr bytes.Buffer -} - -func (d Destination) probe(ctx context.Context) (*probe, error) { - // EOF before release makes read fail, so an early exit cannot inflate capacity. - cmd := exec.CommandContext(ctx, "ssh", d.Channel("-T", "exec sh -c 'printf +; read -r done'")...) // #nosec G204 -- Fixed command on the private master. - cmd.WaitDelay = time.Second - - in, err := cmd.StdinPipe() - if err != nil { - return nil, fmt.Errorf("open probe stdin: %w", err) - } - - out, err := cmd.StdoutPipe() - if err != nil { - _ = in.Close() - return nil, fmt.Errorf("open probe stdout: %w", err) - } - - p := &probe{cmd: cmd, in: in} - cmd.Stderr = &p.stderr - - if err := cmd.Start(); err != nil { - return nil, fmt.Errorf("start SSH probe: %w", err) - } - - stop := context.AfterFunc(ctx, func() { _ = out.Close() }) - defer stop() - - var ready [1]byte - if _, err := io.ReadFull(out, ready[:]); err != nil || ready[0] != '+' { - _ = in.Close() - - if err := cmd.Wait(); err != nil { - return nil, d.commandError(err, p.stderr.String()) - } - - return nil, fmt.Errorf("%w: missing SSH probe reply", os.ErrInvalid) - } - - return p, nil -} diff --git a/tools/internal/sshmux/lock.go b/tools/internal/sshmux/lock.go deleted file mode 100644 index ce30a46d..00000000 --- a/tools/internal/sshmux/lock.go +++ /dev/null @@ -1,85 +0,0 @@ -package sshmux - -import ( - "context" - "errors" - "fmt" - "os" - "syscall" - "time" -) - -// Lock serializes management and pane admission across all local tmux servers. -// Wait for proxies and already approved pane launches to release the slot. -func (d Destination) Lock(ctx context.Context) (*os.File, error) { - request, err := lock(ctx, d.Socket+".lock", syscall.LOCK_EX) - if err != nil { - return nil, err - } - - slot, err := lock(ctx, d.Socket+".slot", syscall.LOCK_EX) - if err != nil { - _ = request.Close() - return nil, err - } - - _ = slot.Close() - - return request, nil -} - -// Hold keeps subsequent operations out after the caller releases Lock. -// All helpers in a batch can hold it until SSH acknowledges their channels. -func (d Destination) Hold(ctx context.Context) (*os.File, error) { - return lock(ctx, d.Socket+".slot", syscall.LOCK_SH) -} - -// ProxySlot lets an idle proxy detect a waiting caller and yield to it. -func (d Destination) ProxySlot(ctx context.Context) (*os.File, error) { - request, err := d.Lock(ctx) - if err != nil { - return nil, err - } - defer func() { _ = request.Close() }() - - return d.Hold(ctx) -} - -// Waiting reports whether another operation needs the management slot. -func (d Destination) Waiting() bool { - f, err := os.Open(d.Socket + ".lock") // #nosec G304 -- Private destination lock. - if err != nil { - return true - } - defer func() { _ = f.Close() }() - - return syscall.Flock(int(f.Fd()), syscall.LOCK_SH|syscall.LOCK_NB) != nil -} - -func lock(ctx context.Context, path string, mode int) (*os.File, error) { - f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) // #nosec G304 -- Private destination lock. - if err != nil { - return nil, fmt.Errorf("open SSH lock: %w", err) - } - - for ctx.Err() == nil { - err := syscall.Flock(int(f.Fd()), mode|syscall.LOCK_NB) - if err == nil { - return f, nil - } - - if !errors.Is(err, syscall.EWOULDBLOCK) { - _ = f.Close() - return nil, fmt.Errorf("lock SSH destination: %w", err) - } - - select { - case <-ctx.Done(): - case <-time.After(25 * time.Millisecond): - } - } - - _ = f.Close() - - return nil, fmt.Errorf("wait for SSH destination: %w", ctx.Err()) -} diff --git a/tools/internal/sshmux/ssh.go b/tools/internal/sshmux/ssh.go index 060b242d..edd67ed1 100644 --- a/tools/internal/sshmux/ssh.go +++ b/tools/internal/sshmux/ssh.go @@ -1,4 +1,4 @@ -// Package sshmux shares a private OpenSSH master between tmux panes and agent queries. +// Package sshmux shares a private OpenSSH master between tmux workspaces. package sshmux import ( @@ -10,7 +10,6 @@ import ( "os/exec" "path/filepath" "regexp" - "strconv" "strings" "syscall" "time" @@ -24,7 +23,7 @@ type Destination struct { var ( sshHost = regexp.MustCompile(`^[a-zA-Z0-9_@.%+:/\[\]-]+$`) // ErrChannelRefused indicates that the master cannot open another session. - ErrChannelRefused = errors.New("SSH session channel refused (check sshd MaxSessions)") + ErrChannelRefused = errors.New("SSH session refused") // ErrSignIn stops automatic retries until the user explicitly runs tm again. ErrSignIn = errors.New("SSH requires attention") ) @@ -55,17 +54,6 @@ func ForHost(host string) (Destination, error) { return Destination{Host: host, Socket: filepath.Join(dir, fmt.Sprintf("ssh-%x", sum[:10]))}, nil } -// Generation distinguishes old attachments from channels refused by a healthy -// master. OpenSSH creates a new socket for each connection. -func (d Destination) Generation() string { - info, err := os.Stat(d.Socket) - if err != nil { - return "" - } - - return strconv.FormatInt(info.ModTime().UnixNano(), 10) -} - // Connect starts or reuses the master under the destination lock. Let OpenSSH // select the agent and identities from the caller's environment and config. func (d Destination) Connect(ctx context.Context, agent string) error { @@ -118,7 +106,7 @@ func needsSignIn(message string) bool { func (d Destination) Channel(tty, command string) []string { return []string{ "-S", d.Socket, "-oControlMaster=no", "-oProxyCommand=false", "-oBatchMode=yes", - "-oClearAllForwardings=yes", "-oRemoteCommand=none", "-oLogLevel=ERROR", "-e", "none", tty, "--", d.Host, command, + "-oClearAllForwardings=yes", "-oStdinNull=no", "-oRemoteCommand=none", "-oLogLevel=ERROR", "-e", "none", tty, "--", d.Host, command, } } @@ -132,28 +120,29 @@ func (d Destination) Query(ctx context.Context, command string) (string, error) out, err := cmd.Output() if err != nil { - return "", d.commandError(err, "") + return "", fmt.Errorf("SSH %s: %w", d.Host, CommandError(err, "")) } return string(out), nil } -func (d Destination) commandError(err error, stderr string) error { +// 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 on %s", ErrChannelRefused, d.Host) + return fmt.Errorf("%w (check sshd MaxSessions)", ErrChannelRefused) } } if stderr != "" { - return fmt.Errorf("SSH %s: %w: %s", d.Host, err, strings.TrimSpace(stderr)) + return fmt.Errorf("%w: %s", err, strings.TrimSpace(stderr)) } - return fmt.Errorf("SSH %s: %w", d.Host, err) + return err } // CacheDir locates the user’s session cache. diff --git a/tools/internal/sshmux/ssh_test.go b/tools/internal/sshmux/ssh_test.go index db92e2f5..020beea6 100644 --- a/tools/internal/sshmux/ssh_test.go +++ b/tools/internal/sshmux/ssh_test.go @@ -1,51 +1,15 @@ package sshmux_test import ( - "context" "errors" "os" "path/filepath" "strings" "testing" - "time" "github.com/ddeville/scripts/tools/internal/sshmux" ) -func TestAdmissionWaitsForEveryApprovedPane(t *testing.T) { - t.Parallel() - - dest := sshmux.Destination{Host: "devbox", Socket: filepath.Join(t.TempDir(), "master")} - lock, err := dest.Lock(t.Context()) - if err != nil { - t.Fatal(err) - } - - pane, err := dest.Hold(t.Context()) - if err != nil { - t.Fatal(err) - } - - // The caller goes away before the pane has finished opening its channel. - _ = lock.Close() - - ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) - defer cancel() - - if _, err := dest.Lock(ctx); !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("overlapped an approved launch: %v", err) - } - - _ = pane.Close() - - lock, err = dest.Lock(t.Context()) - if err != nil { - t.Fatal(err) - } - - _ = lock.Close() -} - func TestConnectUsesCurrentAgentAndRefusesUntrustedHost(t *testing.T) { dir := t.TempDir() diff --git a/tools/internal/tmux/panes.go b/tools/internal/tmux/panes.go index 0b672b58..64355602 100644 --- a/tools/internal/tmux/panes.go +++ b/tools/internal/tmux/panes.go @@ -28,32 +28,24 @@ func SingleClient(ctx context.Context) (string, error) { // Pane describes a pane's session, foreground command, and terminal title. type Pane struct { - ID, PID string - Host, Terminal string - Dead bool - SessionNumber int - Command string - Title string + ID string + SessionNumber int + Command string + Title string } // ListPanes lists panes across all sessions in the current server. func ListPanes(ctx context.Context) ([]Pane, error) { - // Titles come from programs, including remote ones. Keep control characters - // out of the record delimiters before tmux writes the listing. - const format = "#{pane_id}\t#{session_id}\t#{pane_pid}\t#{pane_dead}\t#{@tm_host}\t#{@tm_terminal}\t#{pane_current_command}\t#{s/[\x01-\x1f]/_/:pane_title}" - - output, err := run(ctx, "-u", "list-panes", "-a", "-F", format) + output, err := run(ctx, "-u", "list-panes", "-a", "-F", "#{pane_id}\t#{session_id}\t#{pane_current_command}\t#{pane_title}") if err != nil { return nil, fmt.Errorf("read tmux panes: %w", err) } var panes []Pane - seen := make(map[string]int) - - for line := range strings.Lines(output) { - fields := strings.Split(strings.TrimSuffix(line, "\n"), "\t") - if len(fields) != 8 { + for line := range strings.SplitSeq(strings.TrimSpace(output), "\n") { + fields := strings.SplitN(line, "\t", 4) + if len(fields) != 4 { continue } @@ -62,51 +54,13 @@ func ListPanes(ctx context.Context) ([]Pane, error) { continue } - if i, ok := seen[fields[0]]; ok { - panes[i].SessionNumber = min(panes[i].SessionNumber, sessionNumber) - continue - } - - seen[fields[0]] = len(panes) - panes = append(panes, Pane{ - ID: fields[0], SessionNumber: sessionNumber, PID: fields[2], Dead: fields[3] == "1", - Host: fields[4], Terminal: fields[5], Command: fields[6], Title: fields[7], - }) + panes = append(panes, Pane{ID: fields[0], SessionNumber: sessionNumber, Command: fields[2], Title: fields[3]}) } return panes, nil } -// Switch checks the process and final " | " title field in the same command -// queue that switches clients. Earlier fields can change with each TUI redraw. -func (p Pane) Switch(ctx context.Context, client, titleField string) error { - if client == "" { - var err error - - client, err = SingleClient(ctx) - if err != nil { - return err - } - } - - const view = "#{pane_id}\t#{pane_pid}\t#{pane_dead}\t#{@tm_host}\t#{@tm_terminal}\t#{pane_current_command}\t#{s/^.* [|] //:pane_title}" - - expected := strings.Join([]string{p.ID, p.PID, "0", p.Host, p.Terminal, p.Command, titleField}, "\t") - escape := strings.NewReplacer("#", "#{a:35}", ",", "#{a:44}", "}", "#{a:125}") - same := "#{==:" + view + "," + escape.Replace(expected) + "}" - - command := commandLine("switch-client", "-t", p.ID, "-c", client) - - out, err := run(ctx, "if-shell", "-F", "-t", p.ID, same, command, "display-message -p changed") - if err != nil { - return err - } - - if out != "" { - return errPaneChanged - } - - return nil +// SwitchPane selects a pane for the given client, or the current client if empty. +func SwitchPane(ctx context.Context, pane, client string) error { + return switchClient(ctx, pane, client) } - -var errPaneChanged = errors.New("selected pane changed") diff --git a/tools/internal/tmux/remote.go b/tools/internal/tmux/remote.go index ed9eb82a..c9689156 100644 --- a/tools/internal/tmux/remote.go +++ b/tools/internal/tmux/remote.go @@ -37,17 +37,17 @@ func NewRemoteSession(ctx context.Context, s Session, window, defaultCommand str // Attachment identifies a local pane and the remote terminal it owns, if any. type Attachment struct { - ID, WindowID string - Host, Terminal string - Dead bool - ExitStatus, Connection string - server string + ID, WindowID string + Host, Terminal string + Dead 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_terminal}\t#{pid}\t#{pane_dead_status}\t#{@tm_connection}" + const format = "#{pane_id}\t#{window_id}\t#{pane_dead}\t#{@tm_host}\t#{@tm_terminal}\t#{pid}\t#{pane_dead_status}" args := []string{"-u", "list-panes", "-F", format} if target == "" { @@ -69,13 +69,13 @@ func Attachments(ctx context.Context, target string) (map[string]Attachment, err for line := range strings.Lines(out) { fields := strings.Split(strings.TrimSuffix(line, "\n"), "\t") - if len(fields) != 8 { + if len(fields) != 7 { 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], - Terminal: fields[4], server: fields[5], ExitStatus: fields[6], Connection: fields[7], + Terminal: fields[4], server: fields[5], ExitStatus: fields[6], } panes[p.ID] = p } @@ -108,9 +108,6 @@ func (p Attachment) Record(ctx context.Context, project string) error { "set-option", "-p", "-t", p.ID, "@tm_terminal", literalArg(p.Terminal)) } - // Keep the previous generation retryable if setup fails partway through. - args = append(args, ";", "set-option", "-p", "-t", p.ID, "@tm_connection", p.Connection) - _, err := run(ctx, args...) return err @@ -131,11 +128,6 @@ func (p Attachment) Resume(ctx context.Context, command ...string) error { return p.change(ctx, "respawn-pane -t "+p.ID+" "+commandLine(command...)) } -// Disconnect stops just the local client and keeps the failed pane for retry. -func (p Attachment) Disconnect(ctx context.Context) error { - return p.change(ctx, "respawn-pane -k -t "+p.ID+" /bin/sh -c 'exit 1'") -} - // 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) From 4a1351824f18c6352b503d38e1ad947dee890cbc Mon Sep 17 00:00:00 2001 From: Damien Deville Date: Thu, 26 Nov 2026 12:55:49 -0800 Subject: [PATCH 6/6] Give each remote tmux session its own SSH connection and reconnect on demand --- tools/cmd/tmux-session/REMOTE-WORKSPACES.md | 32 +- tools/cmd/tmux-session/launch.go | 4 +- tools/cmd/tmux-session/main.go | 23 +- tools/cmd/tmux-session/pane.go | 31 +- tools/cmd/tmux-session/reconnect.go | 132 ++++++++ tools/cmd/tmux-session/remote.go | 228 ++++++++++---- tools/cmd/tmux-session/remote_test.go | 86 +++--- tools/cmd/tmux-session/supervisor.go | 320 -------------------- tools/internal/sshmux/ssh.go | 63 ++-- tools/internal/sshmux/ssh_test.go | 30 +- tools/internal/tmux/remote.go | 47 ++- 11 files changed, 493 insertions(+), 503 deletions(-) create mode 100644 tools/cmd/tmux-session/reconnect.go delete mode 100644 tools/cmd/tmux-session/supervisor.go diff --git a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md index 7121a7d3..261718ba 100644 --- a/tools/cmd/tmux-session/REMOTE-WORKSPACES.md +++ b/tools/cmd/tmux-session/REMOTE-WORKSPACES.md @@ -10,12 +10,17 @@ 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. Sessions using the same SSH destination share one OpenSSH -connection. Use the same SSH alias across projects. +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, up -to nine panes can share the connection across projects and local tmux servers. +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, @@ -24,15 +29,16 @@ 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. The supervisor - opens the first connection before creating any panes. All 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 - records the current `SSH_AUTH_SOCK` path in the private destination lock - file for future reconnects. Login does not require agent forwarding. -- **Reconnect** happens automatically. Each local tmux server keeps one - supervisor per destination. It retries with backoff and reattaches surviving - terminals in place, including moved panes. If fewer slots are available, +- **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. diff --git a/tools/cmd/tmux-session/launch.go b/tools/cmd/tmux-session/launch.go index 953f628c..ed39d5c3 100644 --- a/tools/cmd/tmux-session/launch.go +++ b/tools/cmd/tmux-session/launch.go @@ -16,7 +16,7 @@ import ( ) // Give sshd the real requests in order, with the management slot occupied. -func startPanes(ctx context.Context, dest sshmux.Destination, target *tmux.Session, windows []window) (int, error) { +func startPanes(ctx context.Context, master sshmux.Master, target *tmux.Session, windows []window) (int, error) { if len(windows) == 0 { return 0, nil } @@ -27,7 +27,7 @@ func startPanes(ctx context.Context, dest sshmux.Destination, target *tmux.Sessi } for i, win := range windows { - reply := filepath.Join(filepath.Dir(dest.Socket), "open-"+rand.Text()[:16]) + reply := filepath.Join(filepath.Dir(master.Socket), "open-"+rand.Text()[:16]) if err := win.start(ctx, target, helper, reply); err != nil { return i, err } diff --git a/tools/cmd/tmux-session/main.go b/tools/cmd/tmux-session/main.go index 8a54bcc1..8f2b15b5 100644 --- a/tools/cmd/tmux-session/main.go +++ b/tools/cmd/tmux-session/main.go @@ -25,7 +25,7 @@ func main() { func command() *cobra.Command { var ( - name, host, watch string + name, host, retry string launch, reply, closeTarget string noSwitch bool ) @@ -39,8 +39,13 @@ func command() *cobra.Command { SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 0 { - if watch != "" { - return supervise(cmd.Context(), watch) + 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 != "" { @@ -102,10 +107,10 @@ func command() *cobra.Command { 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 supervisor") + cmd.Flags().StringVar(&reply, "pane-reply", "", "report pane startup to the caller") cmd.Flags().Lookup("pane-reply").Hidden = true - cmd.Flags().StringVar(&watch, "supervise", "", "supervise a remote connection") - cmd.Flags().Lookup("supervise").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 @@ -146,9 +151,9 @@ func lockOpen(ctx context.Context) (*os.File, error) { return lockFile(ctx, filepath.Join(dir, "open.lock")) } -// All tmux servers sharing a master use the same management slot. -func lockDestination(ctx context.Context, dest sshmux.Destination) (*os.File, error) { - return lockFile(ctx, dest.Socket+".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") } func lockFile(ctx context.Context, filename string) (*os.File, error) { diff --git a/tools/cmd/tmux-session/pane.go b/tools/cmd/tmux-session/pane.go index edcb60c0..d58e4663 100644 --- a/tools/cmd/tmux-session/pane.go +++ b/tools/cmd/tmux-session/pane.go @@ -48,7 +48,7 @@ func attachPane(ctx context.Context, requested, reply string) (int, error) { conn net.Conn ) - // A raw respawn may replay a command whose supervisor has already left. + // A raw respawn may replay a command whose caller has already left. if reply != "" { conn, _ = (&net.Dialer{}).DialContext(ctx, "unix", reply) if conn != nil { @@ -100,7 +100,7 @@ func runPane(ctx context.Context, requested string, ready func()) (int, error) { return failure, fmt.Errorf("read remote workspace: %w", err) } - p.Host, p.Terminal, dir = w.Host, requested, w.Path + 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] @@ -113,7 +113,7 @@ func runPane(ctx context.Context, requested string, ready func()) (int, error) { return failure, fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) } - dest, err := sshmux.ForHost(p.Host) + master, err := sshmux.ForSession(p.Host, p.Connection) if err != nil { return failure, fmt.Errorf("find pane connection: %w", err) } @@ -124,14 +124,14 @@ func runPane(ctx context.Context, requested string, ready func()) (int, error) { timer := time.AfterFunc(15*time.Second, cancel) defer timer.Stop() - // Splits have no supervisor holding the management session for them. + // Splits have no caller holding the management session for them. if ready == nil { - lock, err := lockDestination(sshCtx, dest) + lock, err := lockMaster(sshCtx, master) if err != nil { return failure, err } - m, err := openManagement(sshCtx, dest, "") + m, err := openManagement(sshCtx, master, "") if err != nil { _ = lock.Close() @@ -146,20 +146,27 @@ func runPane(ctx context.Context, requested string, ready func()) (int, error) { defer ready() } - project := "" + 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); err != nil { + 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", dest.Channel("-tt", remoteCommand(attach, mode, p.Terminal, dir))...) // #nosec G204 -- Pinned master and quoted arguments. + 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 @@ -217,20 +224,20 @@ func stopTerminal(ctx context.Context, p tmux.Attachment) error { return fmt.Errorf("%w: invalid terminal ID", os.ErrInvalid) } - dest, err := sshmux.ForHost(p.Host) + 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 := lockDestination(ctx, dest) + lock, err := lockMaster(ctx, master) if err != nil { return err } defer func() { _ = lock.Close() }() - out, err := dest.Query(ctx, command) + out, err := master.Query(ctx, command) if err != nil { return fmt.Errorf("stop terminal: %w", err) } 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 index 9b6ef1ad..0904b242 100644 --- a/tools/cmd/tmux-session/remote.go +++ b/tools/cmd/tmux-session/remote.go @@ -5,12 +5,14 @@ import ( "bytes" "cmp" "context" + "crypto/rand" "crypto/sha256" "encoding/json" "fmt" "os" "os/exec" "path" + "path/filepath" "regexp" "slices" "strings" @@ -20,14 +22,18 @@ import ( "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"` + 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]) @@ -119,14 +125,14 @@ type management struct { // 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, dest sshmux.Destination, request string) (management, error) { +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", dest.Channel("-T", command)...) // #nosec G204 -- Pinned master and quoted arguments. + cmd := exec.CommandContext(ctx, "ssh", master.Channel("-T", command)...) // #nosec G204 -- Pinned master and quoted arguments. cmd.WaitDelay = time.Second var stderr bytes.Buffer @@ -160,7 +166,7 @@ func openManagement(ctx context.Context, dest sshmux.Destination, request string _ = in.Close() if waitErr := cmd.Wait(); waitErr != nil { - return management{}, fmt.Errorf("%s: %w", dest.Host, sshmux.CommandError(waitErr, stderr.String())) + return management{}, fmt.Errorf("%s: %w", master.Host, sshmux.CommandError(waitErr, stderr.String())) } return management{}, fmt.Errorf("read management reply: %w", err) @@ -173,36 +179,178 @@ func openManagement(ctx context.Context, dest sshmux.Destination, request string }, nil } -func openWorkspace(ctx context.Context, dest sshmux.Destination, request, name string) (openResult, error) { - ctx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() +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(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) } - m, err := openManagement(ctx, dest, request) + sum := sha256.Sum256([]byte(host)) + + lookup, err := lockFile(ctx, filepath.Join(dir, fmt.Sprintf("open-%x.lock", sum[:10]))) if err != nil { - return openResult{}, fmt.Errorf("inspect workspace: %w", err) + 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 } - defer m.close() + 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 openResult{}, fmt.Errorf("%w: invalid remote directory", os.ErrInvalid) + return tmux.Session{}, false, fmt.Errorf("%w: invalid remote directory", os.ErrInvalid) } names, err := inventory(m.listing) if err != nil { - return openResult{}, err + 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) } - w := workspace{Host: dest.Host, Path: m.dir, Name: cmp.Or(name, path.Base(m.dir))} + if _, err := lock.WriteString(os.Getenv("SSH_AUTH_SOCK")); err != nil { + return tmux.Session{}, false, fmt.Errorf("save SSH agent socket: %w", err) + } - return w.open(ctx, dest, names) + return target, created, nil } // Pane names and positions are mutable. Only a terminal ID can identify a @@ -247,55 +395,29 @@ func (w workspace) windows(names map[string]bool, panes map[string]tmux.Attachme return windows, nil } -func (w workspace) open(ctx context.Context, dest sshmux.Destination, names map[string]bool) (openResult, error) { - meta, err := json.Marshal(w) +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 openResult{}, fmt.Errorf("encode workspace: %w", err) - } - - sessions, err := tmux.ListSessions(ctx) - if err != nil { - return openResult{}, fmt.Errorf("list sessions: %w", err) - } - - target := tmux.Session{Name: displayName(w.Host + "/" + w.Name), Remote: string(meta)} - - for _, s := range sessions { - if s.Remote == string(meta) { - target = s - break - } - } - - var panes map[string]tmux.Attachment - if len(sessions) != 0 { - panes, err = tmux.Attachments(ctx, "") - if err != nil { - return openResult{}, fmt.Errorf("find existing remote panes: %w", err) - } + return fmt.Errorf("find existing remote panes: %w", err) } created := target.ID == "" windows, err := w.windows(names, panes, created) if err != nil { - return openResult{}, err + return err } - prefix := w.prefix() for _, p := range panes { - if p.Host == w.Host && p.Dead && strings.HasPrefix(p.Terminal, prefix) && names[p.Terminal] && terminalID.MatchString(p.Terminal) { + 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}) } } - target.Path = w.Path - result := openResult{Session: target, Created: created} - - started, err := startPanes(ctx, dest, &result.Session, windows) + started, err := startPanes(ctx, master, target, windows) if err != nil { if created && started == 0 { - return openResult{}, err + return err } var missing []string @@ -303,10 +425,12 @@ func (w workspace) open(ctx context.Context, dest sshmux.Destination, names map[ missing = append(missing, win.role) } - result.Warning = fmt.Sprintf("could not open %s: %v", strings.Join(missing, ", "), err) + 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 result, nil + return nil } func createRemote(ctx context.Context, target *tmux.Session, role string, command ...string) error { diff --git a/tools/cmd/tmux-session/remote_test.go b/tools/cmd/tmux-session/remote_test.go index 1c7c3801..12a607f6 100644 --- a/tools/cmd/tmux-session/remote_test.go +++ b/tools/cmd/tmux-session/remote_test.go @@ -30,7 +30,7 @@ sh -c "$command" t.Fatal(err) } - dest := sshmux.Destination{Host: "devbox", Socket: filepath.Join(dir, "master")} + 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) @@ -61,7 +61,7 @@ sh -c "$command" func TestRestoreOnlyUnattachedSurvivors(t *testing.T) { t.Parallel() - w := workspace{Host: "devbox", Path: "/work/api", Name: "api"} + 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" @@ -69,6 +69,9 @@ func TestRestoreOnlyUnattachedSurvivors(t *testing.T) { 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) @@ -80,6 +83,28 @@ func TestRestoreOnlyUnattachedSurvivors(t *testing.T) { } } +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() @@ -97,26 +122,23 @@ func TestDiscoveryDistinguishesUnreachableFromGone(t *testing.T) { } } -func TestRecoveryOnlyRetriesSSHFailuresOnThisDestination(t *testing.T) { +func TestRecoveryOnlyRetriesSSHFailuresOnThisConnection(t *testing.T) { t.Parallel() const terminal = "tm-1234567890abcdef1234.shell-AAAAAAAAAAAAA" panes := map[string]tmux.Attachment{ - "%1": {ID: "%1", Host: "dev", Terminal: terminal, Dead: true, ExitStatus: "255"}, - "%2": {ID: "%2", Host: "dev", Terminal: terminal, Dead: true, ExitStatus: "1"}, - "%3": {ID: "%3", Host: "dev", Terminal: terminal}, - "%4": {ID: "%4", Host: "other", Terminal: terminal, Dead: true, ExitStatus: "255"}, - "%5": {ID: "%5", Host: "dev", Dead: true, ExitStatus: "255"}, + "%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}, } - active, retry := interrupted(panes, "dev") - if !active || !slices.Equal(retry, []tmux.Attachment{panes["%1"]}) { - t.Fatalf("active = %t, retry = %v", active, retry) - } - - if active, _ := interrupted(panes, "gone"); active { - t.Fatal("supervisor should exit without panes") + retry := interrupted(panes, sshmux.Master{Host: "dev", ID: "a"}) + if !slices.Equal(retry, []tmux.Attachment{panes["%1"]}) { + t.Fatalf("retry = %v", retry) } } @@ -141,48 +163,32 @@ func TestFailedPaneLookupKeepsReattachmentRetryable(t *testing.T) { } } -func TestWatcherSurvivesLookupFailureAndExitsWithServer(t *testing.T) { +func TestReconnectRetriesLookupAndExitsWithServer(t *testing.T) { dir := t.TempDir() t.Chdir(dir) t.Setenv("PATH", dir) const script = `#!/bin/sh -[ "$1" != -u ] || shift -if [ -f stopped ]; then +if [ -f failed ]; then + : > stopped echo "no server running on /test" >&2 - exit 1 fi -case "$1" in -list-panes) - if [ ! -f failed ]; then - : > failed - exit 1 - fi - printf '%%1\t@1\t0\tdev\ttm-1234567890abcdef1234.shell-AAAAAAAAAAAAA\t1\t\n' - ;; -wait-for) : > stopped ;; -*) exit 1 ;; -esac +: > 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) } - watch, err := lockFile(t.Context(), "watch") - if err != nil { - t.Fatal(err) - } - defer func() { _ = watch.Close() }() - ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() - dest := sshmux.Destination{Host: "dev", Socket: filepath.Join(dir, "ssh")} - if err := watchPanes(ctx, dest, watch); err != nil || ctx.Err() != nil { - t.Fatalf("watchPanes = %v, context = %v", err, ctx.Err()) + 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("watcher did not resume waiting for pane events") + t.Fatal("reconnect did not retry the failed lookup") } } diff --git a/tools/cmd/tmux-session/supervisor.go b/tools/cmd/tmux-session/supervisor.go deleted file mode 100644 index 974303fd..00000000 --- a/tools/cmd/tmux-session/supervisor.go +++ /dev/null @@ -1,320 +0,0 @@ -package main - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "os/exec" - "syscall" - "time" - - "github.com/ddeville/scripts/tools/internal/sshmux" - "github.com/ddeville/scripts/tools/internal/tmux" - "github.com/ddeville/scripts/tools/internal/tui" -) - -// A single reply covers SSH, discovery, layout and watcher election. No tmux -// server needs to exist until the remote directory has been verified. -type openResult struct { - Session tmux.Session `json:"session"` - Created bool `json:"created"` - Warning string `json:"warning,omitempty"` - Error string `json:"error,omitempty"` -} - -func openRemote(ctx context.Context, host, path, name string) (tmux.Session, bool, error) { - if host == "" || path == "" { - return tmux.Session{}, false, fmt.Errorf("%w: expected an SSH host and remote path", os.ErrInvalid) - } - - helper, err := os.Executable() - if err != nil { - return tmux.Session{}, false, fmt.Errorf("locate tmux-session: %w", err) - } - - request, err := json.Marshal(workspace{Path: path, Name: name}) - if err != nil { - return tmux.Session{}, false, fmt.Errorf("encode workspace request: %w", err) - } - - cmd := exec.CommandContext(context.WithoutCancel(ctx), helper, "--supervise="+host) // #nosec G204 -- Re-exec this binary. ForHost validates the destination before SSH. - cmd.Stdin = bytes.NewReader(request) - cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} - - reply, err := cmd.StdoutPipe() - if err != nil { - return tmux.Session{}, false, fmt.Errorf("open supervisor pipe: %w", err) - } - - if err := cmd.Start(); err != nil { - return tmux.Session{}, false, fmt.Errorf("start supervisor: %w", err) - } - - // Cancellation belongs to the caller until startup has completed. - stop := context.AfterFunc(ctx, func() { _ = cmd.Process.Signal(syscall.SIGTERM) }) - - var result openResult - - err = json.NewDecoder(reply).Decode(&result) - - stop() - - _ = reply.Close() - - go func() { _ = cmd.Wait() }() - - if err != nil { - return tmux.Session{}, false, fmt.Errorf("wait for supervisor: %w", err) - } - - if result.Error != "" { - return tmux.Session{}, false, errors.New(result.Error) //nolint:err113 // The child sends the original diagnostic. - } - - if result.Warning != "" { - message := "tm: " + tui.CleanLine(result.Warning) - _, _ = fmt.Fprintln(os.Stderr, message) - _ = tmux.Notify(ctx, message) - } - - return result.Session, result.Created, nil -} - -// Only one process watches a given server and destination. Other explicit -// opens can reuse the master or retry immediately during backoff. -func watchLock(ctx context.Context, dest sshmux.Destination) (*os.File, error) { - socket, err := tmux.SocketPath(ctx) - if err != nil { - return nil, fmt.Errorf("identify tmux server: %w", err) - } - - server := sha256.Sum256([]byte(socket)) - filename := fmt.Sprintf("%s.%x.watch", dest.Socket, server[:8]) - - lock, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0o600) // #nosec G304 -- Private per-destination directory. - if err != nil { - return nil, fmt.Errorf("open supervisor lock: %w", err) - } - - if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { - _ = lock.Close() - return nil, fmt.Errorf("lock supervisor: %w", err) - } - - return lock, nil -} - -func supervise(ctx context.Context, host string) error { - var result openResult - - dest, err := sshmux.ForHost(host) - - var watch *os.File - if err == nil { - watch, err = prepare(ctx, dest, &result) - } - - if err != nil { - result.Error = err.Error() - } - - if err := json.NewEncoder(os.Stdout).Encode(result); err != nil { - return fmt.Errorf("notify caller: %w", err) - } - - if watch == nil { - return nil - } - defer func() { _ = watch.Close() }() - - return watchPanes(ctx, dest, watch) -} - -func prepare(ctx context.Context, dest sshmux.Destination, result *openResult) (*os.File, error) { - var w workspace - if err := json.NewDecoder(os.Stdin).Decode(&w); err != nil { - return nil, fmt.Errorf("read workspace request: %w", err) - } - - lock, err := lockDestination(ctx, dest) - if err != nil { - return nil, err - } - defer func() { _ = lock.Close() }() - - agent := os.Getenv("SSH_AUTH_SOCK") - if err := dest.Connect(ctx, agent); err != nil { - return nil, fmt.Errorf("SSH: %w", err) - } - - *result, err = openWorkspace(ctx, dest, w.Path, w.Name) - if err != nil { - return nil, err - } - - // A successful open refreshes the agent path for the next reconnect. - if err := lock.Truncate(0); err != nil { - return nil, fmt.Errorf("update SSH agent socket: %w", err) - } - - if _, err := lock.WriteString(agent); err != nil { - return nil, fmt.Errorf("save SSH agent socket: %w", err) - } - - watch, err := watchLock(ctx, dest) - if errors.Is(err, syscall.EWOULDBLOCK) { - return nil, nil //nolint:nilnil // This open succeeded and another process owns the watcher. - } - - return watch, err -} - -func watchPanes(ctx context.Context, dest sshmux.Destination, watch *os.File) error { - backoff := time.Second - notified := false - - for ctx.Err() == nil { - // Explicit opens and automatic retries must never start competing masters. - lock, err := lockDestination(ctx, dest) - if err != nil { - return err - } - - active, err := recoverPanes(ctx, dest, lock) - - done := (!active && err == nil) || errors.Is(err, sshmux.ErrSignIn) - if done { - // Let the next open take over before releasing the destination lock. - _ = watch.Close() - } - - _ = lock.Close() - - if done { - return err - } - - if err == nil { - err = tmux.WaitPaneDeath(ctx) - } - - if err != nil { - if backoff >= 4*time.Second && !notified { - notified = tmux.Notify(ctx, "tm: retrying recovery for "+dest.Host+" · "+tui.CleanLine(err.Error())) == nil - } - - select { - case <-ctx.Done(): - return nil - case <-time.After(backoff): - } - - backoff = min(backoff*2, 30*time.Second) - - continue - } - - backoff = time.Second - notified = false - } - - return nil -} - -func recoverPanes(ctx context.Context, dest sshmux.Destination, lock *os.File) (bool, error) { - ctx, cancel := context.WithTimeout(ctx, 20*time.Second) - defer cancel() - - panes, err := tmux.Attachments(ctx, "") - if err != nil { - return false, fmt.Errorf("inspect remote panes: %w", err) - } - - active, failed := interrupted(panes, dest.Host) - - if !active { - // A new session exists before its panes finish recording their targets. - sessions, err := tmux.ListSessions(ctx) - if err != nil { - return false, fmt.Errorf("look for remote sessions: %w", err) - } - - for _, session := range sessions { - var w workspace - if session.Remote != "" && json.Unmarshal([]byte(session.Remote), &w) == nil && w.Host == dest.Host { - return true, nil - } - } - - return false, nil - } - - if len(failed) == 0 { - return true, nil - } - - agent, err := io.ReadAll(lock) - if err != nil { - return true, fmt.Errorf("read SSH agent socket: %w", err) - } - - connectErr := dest.Connect(ctx, string(agent)) - if connectErr != nil && !errors.Is(connectErr, sshmux.ErrSignIn) { - return true, fmt.Errorf("restore connection: %w", connectErr) - } - - // Other clients may have exited or moved during the handshake. - panes, err = tmux.Attachments(ctx, "") - if err != nil { - return false, fmt.Errorf("inspect remote panes: %w", err) - } - - _, failed = interrupted(panes, dest.Host) - if connectErr != nil { - for _, p := range failed { - _ = p.RequireSignIn(ctx) - } - - return true, fmt.Errorf("restore connection: %w", connectErr) - } - - m, err := openManagement(ctx, dest, "") - if err != nil { - return true, 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, dest, nil, resume) - - return true, err -} - -func interrupted(panes map[string]tmux.Attachment, host string) (bool, []tmux.Attachment) { - active := false - - var failed []tmux.Attachment - - for _, p := range panes { - if p.Host != host || !terminalID.MatchString(p.Terminal) { - continue - } - - active = true - - if p.Dead && p.ExitStatus == "255" { - failed = append(failed, p) - } - } - - return active, failed -} diff --git a/tools/internal/sshmux/ssh.go b/tools/internal/sshmux/ssh.go index edd67ed1..4fc4d0bd 100644 --- a/tools/internal/sshmux/ssh.go +++ b/tools/internal/sshmux/ssh.go @@ -1,4 +1,4 @@ -// Package sshmux shares a private OpenSSH master between tmux workspaces. +// Package sshmux manages a private OpenSSH master for a tmux session. package sshmux import ( @@ -15,9 +15,9 @@ import ( "time" ) -// Destination identifies a master by its exact SSH destination. -type Destination struct { - Host, Socket string +// Master identifies the connection used by the panes of one local session. +type Master struct { + Host, ID, Socket string } var ( @@ -28,39 +28,38 @@ var ( ErrSignIn = errors.New("SSH requires attention") ) -// ForHost resolves the private control socket without opening a connection. -func ForHost(host string) (Destination, error) { +// 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 Destination{}, fmt.Errorf("%w: invalid SSH destination %q", os.ErrInvalid, host) + return Master{}, fmt.Errorf("%w: invalid SSH destination %q", os.ErrInvalid, host) } - dir, err := CacheDir() - if err != nil { - return Destination{}, err + if id == "" { + return Master{}, fmt.Errorf("%w: missing SSH connection ID", os.ErrInvalid) } - info, err := os.Lstat(dir) + dir, err := CacheDir() if err != nil { - return Destination{}, fmt.Errorf("inspect SSH socket directory: %w", err) + return Master{}, err } - stat, ok := info.Sys().(*syscall.Stat_t) - if !ok || !info.IsDir() || int(stat.Uid) != os.Geteuid() || info.Mode().Perm()&0o077 != 0 { - return Destination{}, fmt.Errorf("%w: SSH socket directory %s must be private", os.ErrPermission, dir) - } + sum := sha256.Sum256([]byte(host + "\x00" + id)) - sum := sha256.Sum256([]byte(host)) + return Master{Host: host, ID: id, Socket: filepath.Join(dir, fmt.Sprintf("ssh-%x", sum[:10]))}, nil +} - return Destination{Host: host, 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 destination lock. Let OpenSSH +// 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 Destination) Connect(ctx context.Context, agent string) error { +func (d Master) Connect(ctx context.Context, agent string) error { ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() - if exec.CommandContext(ctx, "ssh", "-S", d.Socket, "-O", "check", "--", d.Host).Run() == nil { // #nosec G204 -- The validated destination follows --. + if d.Running(ctx) { return nil } @@ -68,6 +67,9 @@ func (d Destination) Connect(ctx context.Context, agent string) error { "-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) } @@ -95,6 +97,11 @@ func (d Destination) Connect(ctx context.Context, agent string) error { 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") || @@ -103,7 +110,7 @@ func needsSignIn(message string) bool { // 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 Destination) Channel(tty, command string) []string { +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, @@ -111,7 +118,7 @@ func (d Destination) Channel(tty, command string) []string { } // Query runs one non-interactive command with a deadline. -func (d Destination) Query(ctx context.Context, command string) (string, error) { +func (d Master) Query(ctx context.Context, command string) (string, error) { ctx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() @@ -157,5 +164,15 @@ func CacheDir() (string, error) { 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 index 020beea6..a20b0a1f 100644 --- a/tools/internal/sshmux/ssh_test.go +++ b/tools/internal/sshmux/ssh_test.go @@ -10,6 +10,32 @@ import ( "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() @@ -28,9 +54,9 @@ exit 255 t.Setenv("PATH", dir) t.Setenv("SSH_AUTH_SOCK", "/old-agent") - dest := sshmux.Destination{Host: "devbox", Socket: filepath.Join(dir, "master")} + master := sshmux.Master{Host: "devbox", Socket: filepath.Join(dir, "master")} - err := dest.Connect(t.Context(), "/new-agent") + 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/remote.go b/tools/internal/tmux/remote.go index c9689156..0997e230 100644 --- a/tools/internal/tmux/remote.go +++ b/tools/internal/tmux/remote.go @@ -11,12 +11,6 @@ import ( // RemoteEnv identifies a remote session and supplies the workspace to new panes. const RemoteEnv = "TM_REMOTE_WORKSPACE" -// SocketPath identifies the local server, even when opened from outside tmux. -func SocketPath(ctx context.Context) (string, error) { - out, err := run(ctx, "display-message", "-p", "#{socket_path}") - return strings.TrimSuffix(out, "\n"), err -} - // 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) { @@ -37,17 +31,17 @@ func NewRemoteSession(ctx context.Context, s Session, window, defaultCommand str // Attachment identifies a local pane and the remote terminal it owns, if any. type Attachment struct { - ID, WindowID string - Host, Terminal string - Dead bool - ExitStatus string - server string + 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_terminal}\t#{pid}\t#{pane_dead_status}" + 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 == "" { @@ -69,13 +63,14 @@ func Attachments(ctx context.Context, target string) (map[string]Attachment, err for line := range strings.Lines(out) { fields := strings.Split(strings.TrimSuffix(line, "\n"), "\t") - if len(fields) != 7 { + 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], - Terminal: fields[4], server: fields[5], ExitStatus: fields[6], + Connection: fields[4], Terminal: fields[5], server: fields[6], ExitStatus: fields[7], + NeedsSignIn: fields[8] == "1", } panes[p.ID] = p } @@ -94,7 +89,7 @@ func Notify(ctx context.Context, message string) error { } // Record pins a terminal to this pane, even across moves and respawns. -func (p Attachment) Record(ctx context.Context, project string) error { +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{ @@ -102,10 +97,16 @@ func (p Attachment) Record(ctx context.Context, project string) error { "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-option", "-p", "-t", p.ID, "@tm_terminal", literalArg(p.Terminal), ";", + "set-hook", "-p", "-t", p.ID, "pane-died", hook) } _, err := run(ctx, args...) @@ -148,17 +149,3 @@ func (p Attachment) change(ctx context.Context, command string) error { return nil } - -// WaitPaneDeath wakes on a retained pane exit or periodically to catch removed -// panes and events missed during recovery. No SSH probe is needed while idle. -func WaitPaneDeath(ctx context.Context) error { - ctx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - - _, err := run(ctx, "wait-for", "-E", "pane-died") - if ctx.Err() != nil { - return nil - } - - return err -}