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
2 changes: 1 addition & 1 deletion devspace.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version: v2beta1

vars:
AGYN_NAMESPACE: platform
AGYN_NAMESPACE: agyn-platform
DEV_IMAGE: ghcr.io/agynio/devcontainer-go:1

dev:
Expand Down
2 changes: 1 addition & 1 deletion gen/agynio/api/egress/v1/egress.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion gen/agynio/api/gateway/v1/egress.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion gen/agynio/api/gateway/v1/groups.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion gen/agynio/api/gateway/v1/networks.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion gen/agynio/api/groups/v1/groups.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion gen/agynio/api/networks/v1/networks.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 21 additions & 6 deletions internal/cmd/sandbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,13 @@ type sandboxOutput struct {

type sandboxArgs struct {
organizationID string
environment string
name string
all bool
terminated bool
// shell names which shell to return to; newShell forces a fresh one.
shell string
newShell bool
environment string
name string
all bool
terminated bool
// idleTimeout overrides the profile default for this invocation only.
idleTimeout string
// sync composes start, sync, and shell attach in one invocation. The
Expand All @@ -61,6 +64,7 @@ func newSandboxCmd() *cobra.Command {
cmd.AddCommand(newSandboxStartCmd())
cmd.AddCommand(newSandboxConnectCmd())
cmd.AddCommand(newSandboxListCmd())
cmd.AddCommand(newSandboxTabsCmd())
cmd.AddCommand(newSandboxStopCmd())
cmd.AddCommand(newSandboxDeleteCmd())
cmd.AddCommand(newSandboxCpCmd())
Expand Down Expand Up @@ -124,7 +128,11 @@ func newSandboxStartCmd() *cobra.Command {
}
sandbox = running
}
return attachToSandbox(ctx, clients, sandbox)
shellID, shellCwd, err := resolveShell(ctx, clients, sandbox.GetMeta().GetId(), "", true)
if err != nil {
return err
}
return attachToSandbox(ctx, clients, sandbox, shellID, shellCwd)
},
}
cmd.Flags().StringVar(&args.organizationID, "organization-id", "", "Organization ID (defaults to the selected organization)")
Expand Down Expand Up @@ -168,10 +176,17 @@ func newSandboxConnectCmd() *cobra.Command {
if err != nil {
return err
}
return attachToSandbox(ctx, clients, ensured.Msg.GetSandbox())
target := ensured.Msg.GetSandbox()
shellID, shellCwd, err := resolveShell(ctx, clients, target.GetMeta().GetId(), args.shell, args.newShell)
if err != nil {
return err
}
return attachToSandbox(ctx, clients, target, shellID, shellCwd)
},
}
cmd.Flags().StringVar(&args.organizationID, "organization-id", "", "Organization ID (defaults to the selected organization)")
cmd.Flags().StringVar(&args.shell, "tab", "", "Shell to attach to, by number or id (defaults to the one you were last in)")
cmd.Flags().BoolVar(&args.newShell, "new", false, "Open a new shell instead of returning to one")
return cmd
}

Expand Down
4 changes: 3 additions & 1 deletion internal/cmd/sandbox_attach.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func (e *exitCodeError) ExitCode() int { return e.code }

// attachToSandbox waits for the workload to run, requests a terminal ticket and
// streams the session until the shell exits.
func attachToSandbox(ctx context.Context, clients *sandboxClients, sandbox *agentsv1.Sandbox) error {
func attachToSandbox(ctx context.Context, clients *sandboxClients, sandbox *agentsv1.Sandbox, shellID, shellCwd string) error {
if !terminal.IsTerminal(os.Stdin) || !terminal.IsTerminal(os.Stdout) {
return fmt.Errorf("a TTY is required; `agyn sandbox` has no non-interactive mode")
}
Expand All @@ -50,6 +50,8 @@ func attachToSandbox(ctx context.Context, clients *sandboxClients, sandbox *agen
WorkloadId: workloadID,
ContainerName: sandboxMainContainer,
Kind: terminalproxyv1.SessionKind_SESSION_KIND_SHELL,
ShellId: shellID,
ShellCwd: shellCwd,
}))
if err != nil {
return err
Expand Down
174 changes: 174 additions & 0 deletions internal/cmd/sandbox_shells.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
package cmd

import (
"context"
"fmt"
"regexp"
"sort"
"strings"

"connectrpc.com/connect"
agentsv1 "github.com/agynio/agyn-cli/gen/agynio/api/agents/v1"
"github.com/google/uuid"
"github.com/spf13/cobra"
"google.golang.org/protobuf/types/known/timestamppb"
)

// A shell the CLI attaches to is the same shell the browser opens as a tab:
// both name one through the sandbox layout, so work started in a terminal is
// picked up in a tab and the other way round.
//
// Whether the shell survives the connection is the environment's answer, not
// this command's. Naming one costs nothing where it does not.

var cliShellIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)

// resolveShell decides which shell this attach names, and records it.
//
// The default is the most recently attached one -- "put me back where I was",
// which is what tmux's own attach does and what someone reconnecting means.
func resolveShell(
ctx context.Context,
clients *sandboxClients,
sandboxID string,
requested string,
forceNew bool,
) (shellID string, shellCwd string, err error) {
layout, err := clients.agents.GetSandboxLayout(ctx, connect.NewRequest(&agentsv1.GetSandboxLayoutRequest{
SandboxId: sandboxID,
}))
if err != nil {
// A layout the platform could not give us is not a reason to refuse a
// shell. Attaching without an id yields an ordinary one.
return "", "", nil
}

tabs := layout.Msg.GetLayout().GetTabs()
version := layout.Msg.GetLayout().GetVersion()

requested = strings.TrimSpace(requested)
if requested != "" && !forceNew {
for _, tab := range tabs {
if tab.GetShellId() == requested || fmt.Sprint(tab.GetNumber()) == requested {
return tab.GetShellId(), tab.GetCwd(), recordAttach(ctx, clients, sandboxID, version, tabs, tab.GetShellId())
}
}
return "", "", fmt.Errorf("no shell %q in this sandbox; `agyn sandbox tabs` lists them", requested)
}

if !forceNew {
if newest := mostRecentlyAttached(tabs); newest != nil {
return newest.GetShellId(), newest.GetCwd(), recordAttach(ctx, clients, sandboxID, version, tabs, newest.GetShellId())
}
}

// Nothing to return to, or --new: open one and record it so the browser
// shows it as a tab.
created := uuid.NewString()
number := int32(1)
for _, tab := range tabs {
if tab.GetNumber() >= number {
number = tab.GetNumber() + 1
}
}
tabs = append(tabs, &agentsv1.SandboxTab{ShellId: created, Number: number})
return created, "", recordAttach(ctx, clients, sandboxID, version, tabs, created)
}

// recordAttach writes the layout back with last_attached_at moved to the shell
// being entered, which is what makes "the one I was just in" mean anything.
//
// A failed write is not fatal: losing the record costs the tab list on the next
// visit, not the shell in front of you.
func recordAttach(
ctx context.Context,
clients *sandboxClients,
sandboxID string,
version int64,
tabs []*agentsv1.SandboxTab,
shellID string,
) error {
now := timestamppb.Now()
for _, tab := range tabs {
if tab.GetShellId() == shellID {
tab.LastAttachedAt = now
}
}
_, _ = clients.agents.SetSandboxLayout(ctx, connect.NewRequest(&agentsv1.SetSandboxLayoutRequest{
SandboxId: sandboxID,
Version: version,
Tabs: tabs,
}))
return nil
}

func mostRecentlyAttached(tabs []*agentsv1.SandboxTab) *agentsv1.SandboxTab {
var newest *agentsv1.SandboxTab
for _, tab := range tabs {
if !cliShellIDPattern.MatchString(tab.GetShellId()) {
continue
}
if newest == nil {
newest = tab
continue
}
if tab.GetLastAttachedAt().AsTime().After(newest.GetLastAttachedAt().AsTime()) {
newest = tab
}
}
return newest
}

func newSandboxTabsCmd() *cobra.Command {
var args struct{ organizationID string }

cmd := &cobra.Command{
Use: "tabs [NAME]",
Short: "List your shells in a sandbox",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, positional []string) error {
clients, err := sandboxGatewayClients(cmd)
if err != nil {
return err
}
ctx := cmd.Context()
organizationID, err := clients.resolveOrganizationID(ctx, args.organizationID)
if err != nil {
return err
}
var name string
if len(positional) == 1 {
name = positional[0]
}
sandbox, err := clients.resolveSandbox(ctx, organizationID, name)
if err != nil {
return err
}
layout, err := clients.agents.GetSandboxLayout(ctx, connect.NewRequest(&agentsv1.GetSandboxLayoutRequest{
SandboxId: sandbox.GetMeta().GetId(),
}))
if err != nil {
return err
}
tabs := layout.Msg.GetLayout().GetTabs()
sort.SliceStable(tabs, func(i, j int) bool { return tabs[i].GetNumber() < tabs[j].GetNumber() })

out := cmd.OutOrStdout()
fmt.Fprintln(out, "NUMBER\tSHELL\tDIRECTORY\tLAST_ATTACHED")
for _, tab := range tabs {
last := "-"
if tab.GetLastAttachedAt() != nil {
last = tab.GetLastAttachedAt().AsTime().Local().Format("2006-01-02 15:04")
}
cwd := tab.GetCwd()
if cwd == "" {
cwd = "-"
}
fmt.Fprintf(out, "%d\t%s\t%s\t%s\n", tab.GetNumber(), tab.GetShellId(), cwd, last)
}
return nil
},
}
cmd.Flags().StringVar(&args.organizationID, "organization-id", "", "Organization ID (defaults to the selected organization)")
return cmd
}
Loading