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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions cmd/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ var connectCmd = &cobra.Command{
Long: `Connect to a running Vers VM via SSH. If no VM ID or alias is provided, uses the current HEAD.`,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
apiCtx, cancel := context.WithTimeout(context.Background(), application.Timeouts.APIMedium)
defer cancel()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very funny to me. That would almost certainly cause a forced disconnect after 30 seconds haha.

// Use a context without timeout for interactive SSH sessions.
// The SSH connection should stay open until the user exits.
ctx := context.Background()
target := ""
if len(args) > 0 {
target = args[0]
}
_, err := handlers.HandleConnect(apiCtx, application, handlers.ConnectReq{Target: target})
_, err := handlers.HandleConnect(ctx, application, handlers.ConnectReq{Target: target})
if err != nil {
return err
}
Expand Down
13 changes: 13 additions & 0 deletions internal/handlers/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handlers
import (
"context"
"fmt"
"os"
"os/exec"
"strings"

Expand All @@ -12,6 +13,7 @@ import (
vmSvc "github.com/hdresearch/vers-cli/internal/services/vm"
sshutil "github.com/hdresearch/vers-cli/internal/ssh"
"github.com/hdresearch/vers-cli/internal/utils"
"golang.org/x/term"
)

type ConnectReq struct{ Target string }
Expand Down Expand Up @@ -49,8 +51,19 @@ func HandleConnect(ctx context.Context, a *app.App, r ConnectReq) (presenters.Co
// Render connection info BEFORE running SSH so it displays before connecting
presenters.RenderConnect(a, view)

// Save terminal state before SSH so we can restore it if the connection
// exits abnormally (network drop, server crash, etc.)
fd := int(os.Stdin.Fd())
oldState, termErr := term.GetState(fd)

args := sshutil.SSHArgs(sshHost, sshPort, info.KeyPath)
err = a.Runner.Run(ctx, "ssh", args, runrt.Stdio{In: a.IO.In, Out: a.IO.Out, Err: a.IO.Err})

// Always restore terminal state after SSH exits, regardless of how it exited
if termErr == nil && oldState != nil {
_ = term.Restore(fd, oldState)
}

if err != nil {
if _, ok := err.(*exec.ExitError); !ok {
return view, fmt.Errorf("failed to run SSH command: %w", err)
Expand Down