Files
Reims-Go/internal/app/ssh_flow.go
T
NwflowerandClaude Opus 5.5 c0f08be124 feat: per-VM CPU affinity, disk snapshots, SSH helpers and VM window actions
Backend
- Per-VM CPU affinity (vmstart/affinity.go, affinity_flow.go): modes auto /
  all / P-cores / non-LP-E / custom, saved in the VM folder, applied to the
  QEMU process on start (GUI and CLI) and live via SetVMAffinity; copied on
  clone. Start summary logs the resolved mapping. Host report gains CPU
  topology helpers (mask <-> CPU list).
- Offline qcow2 restore points via qemu-img (driver/reims/snapshot.go,
  snapshot_flow.go): list / create / restore / delete.
- SSH helpers (ssh_flow.go): remembered user, open a terminal, write an
  ~/.ssh/config entry, open VS Code Remote-SSH.
- FocusVMWindow brings the QEMU window forward (restoring it if minimized);
  CopyVMScreenshot copies a full-resolution frame to the clipboard.
- DeliverPathsToGuest copies dropped host files into the shared folder;
  main.go enables Wails file drop on elements marked --wails-drop-target.
- VM note (.reims-go-note) and a storage breakdown (extras_flow.go).

Frontend
- VM page: running state's "Show Window" and the screen preview use
  FocusVMWindow; camera button and More-menu item copy a screenshot;
  editable note under the name; SSH row shows the saved user with
  Terminal / config / VS Code actions; restore-point list; install guide
  steps can be ticked off; drop files onto the page to send them.
- Sidebar right-click menu per VM (start, show window, screenshot, stop,
  restart, settings, folders, clone, delete); double-click and Ctrl+Enter
  still run the main action.
- AffinityDialog opened from the VM menu and VM settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:00:48 -07:00

204 lines
6.0 KiB
Go

package app
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
const sshUserFileName = ".reims-go-ssh-user"
var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
// sshHostAlias returns a stable ~/.ssh/config Host alias for a VM.
func sshHostAlias(vmName string) string {
var b strings.Builder
b.WriteString("reims-")
for _, r := range strings.ToLower(strings.TrimSpace(vmName)) {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
b.WriteRune(r)
} else {
b.WriteByte('-')
}
}
return b.String()
}
// GetVMSSHUser returns the remembered SSH login user for a VM (empty if unset).
func (a *App) GetVMSSHUser(name string) string {
d, err := a.GetVMDetail(name)
if err != nil || d.Directory == "" {
return ""
}
b, err := os.ReadFile(filepath.Join(d.Directory, sshUserFileName))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// SetVMSSHUser persists the preferred SSH login user for a VM.
func (a *App) SetVMSSHUser(name, user string) error {
user = strings.TrimSpace(user)
if user != "" && !safeSSHUserRe.MatchString(user) {
return fmt.Errorf("invalid SSH username %q", user)
}
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
if d.Directory == "" {
return fmt.Errorf("VM directory not found")
}
p := filepath.Join(d.Directory, sshUserFileName)
if user == "" {
_ = os.Remove(p)
return nil
}
return os.WriteFile(p, []byte(user+"\n"), 0o644)
}
// OpenSSHTerminal launches an interactive Windows Terminal (falling back to
// PowerShell) connected to the VM's forwarded SSH port.
func (a *App) OpenSSHTerminal(name, user string) error {
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
if !d.Network || d.SSHPort <= 0 {
return fmt.Errorf("SSH port forwarding is not enabled for %s", name)
}
user = strings.TrimSpace(user)
if user == "" {
user = a.GetVMSSHUser(name)
} else if !safeSSHUserRe.MatchString(user) {
return fmt.Errorf("invalid SSH username %q", user)
} else {
_ = a.SetVMSSHUser(name, user)
}
target := "127.0.0.1"
if user != "" {
target = user + "@127.0.0.1"
}
portStr := fmt.Sprintf("%d", d.SSHPort)
var cmd *exec.Cmd
if wt, err := exec.LookPath("wt.exe"); err == nil {
cmd = exec.Command(wt, "new-tab", "--title", name, "ssh", "-p", portStr, target)
} else if ps, err := exec.LookPath("powershell.exe"); err == nil {
cmd = exec.Command(ps, "-NoExit", "-Command", fmt.Sprintf("ssh -p %s %s", portStr, target))
} else {
return fmt.Errorf("neither Windows Terminal (wt.exe) nor powershell.exe was found")
}
if err := cmd.Start(); err != nil {
return fmt.Errorf("open SSH terminal: %w", err)
}
a.emitLog(name, fmt.Sprintf("Opened SSH terminal (%s -p %s)", target, portStr))
return nil
}
// WriteSSHConfig idempotently writes or updates a Host block for the VM in
// ~/.ssh/config and returns the configured Host alias (e.g. "reims-macos-tahoe").
func (a *App) WriteSSHConfig(name, user string) (string, error) {
d, err := a.GetVMDetail(name)
if err != nil {
return "", err
}
if !d.Network || d.SSHPort <= 0 {
return "", fmt.Errorf("SSH port forwarding is not enabled for %s", name)
}
user = strings.TrimSpace(user)
if user == "" {
user = a.GetVMSSHUser(name)
} else if !safeSSHUserRe.MatchString(user) {
return "", fmt.Errorf("invalid SSH username %q", user)
} else {
_ = a.SetVMSSHUser(name, user)
}
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("locate home directory: %w", err)
}
sshDir := filepath.Join(home, ".ssh")
if err := os.MkdirAll(sshDir, 0o700); err != nil {
return "", fmt.Errorf("create ~/.ssh: %w", err)
}
cfgPath := filepath.Join(sshDir, "config")
alias := sshHostAlias(name)
if err := upsertSSHConfigBlock(cfgPath, name, alias, d.SSHPort, user); err != nil {
return "", err
}
a.emitLog(name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (127.0.0.1:%d)", alias, d.SSHPort))
return alias, nil
}
// OpenVSCodeSSH ensures the VM's Host block is present in ~/.ssh/config and
// launches VS Code (falling back to Cursor) in Remote-SSH mode.
func (a *App) OpenVSCodeSSH(name, user string) error {
alias, err := a.WriteSSHConfig(name, user)
if err != nil {
return err
}
var bin string
for _, cand := range []string{"code.cmd", "code", "cursor.cmd", "cursor"} {
if p, err := exec.LookPath(cand); err == nil {
bin = p
break
}
}
if bin == "" {
return fmt.Errorf("VS Code or Cursor CLI not found on PATH (Host %s has been written to ~/.ssh/config)", alias)
}
cmd := exec.Command(bin, "--remote", "ssh-remote+"+alias)
if err := cmd.Start(); err != nil {
return fmt.Errorf("launch editor Remote-SSH: %w", err)
}
a.emitLog(name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias))
return nil
}
func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string) error {
startMark := fmt.Sprintf("# >>> reims-go:%s >>>", vmName)
endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName)
var block strings.Builder
block.WriteString(startMark + "\n")
block.WriteString(fmt.Sprintf("Host %s\n", alias))
block.WriteString(" HostName 127.0.0.1\n")
block.WriteString(fmt.Sprintf(" Port %d\n", port))
if user != "" {
block.WriteString(fmt.Sprintf(" User %s\n", user))
}
block.WriteString(" StrictHostKeyChecking accept-new\n")
block.WriteString(endMark + "\n")
existingBytes, err := os.ReadFile(cfgPath)
if err != nil && !os.IsNotExist(err) {
return err
}
content := strings.ReplaceAll(string(existingBytes), "\r\n", "\n")
var updated string
if si := strings.Index(content, startMark); si >= 0 {
if ei := strings.Index(content[si:], endMark); ei >= 0 {
endPos := si + ei + len(endMark)
if endPos < len(content) && content[endPos] == '\n' {
endPos++
}
updated = content[:si] + block.String() + content[endPos:]
}
}
if updated == "" {
if content != "" && !strings.HasSuffix(content, "\n") {
content += "\n"
}
if content != "" && !strings.HasSuffix(content, "\n\n") {
content += "\n"
}
updated = content + block.String()
}
return os.WriteFile(cfgPath, []byte(updated), 0o600)
}