From 774d2013ed2a92f12e578d7b71c6a81c64adf67c Mon Sep 17 00:00:00 2001 From: Andreas Spannagel Date: Mon, 16 Nov 2026 23:20:20 +0100 Subject: [PATCH 1/2] feat(ui): move a session to another group on an SSH connection --- docs/ssh-connections.md | 2 +- docs/usage.md | 3 +- internal/remote/operations_test.go | 3 + internal/ui/connections/call.go | 7 +- internal/ui/connections/call_test.go | 3 + internal/ui/connections/link/call.go | 9 +++ internal/ui/connections/link/call_test.go | 3 +- internal/ui/connections_adapter.go | 51 +++++++++++++ internal/ui/connections_adapter_test.go | 91 +++++++++++++++++++++-- internal/ui/help/catalog.go | 1 + internal/ui/help/catalog_test.go | 21 ++++++ internal/ui/rail/hosts_test.go | 31 ++++++-- internal/ui/rail/legend.go | 3 + internal/ui/rail/legend_test.go | 22 ++++++ internal/ui/rail/menu.go | 11 ++- tools/e2e/README.md | 2 +- tools/e2e/ssh_scenarios.py | 20 ++++- 17 files changed, 257 insertions(+), 26 deletions(-) diff --git a/docs/ssh-connections.md b/docs/ssh-connections.md index 66a632e0..6e4f838d 100644 --- a/docs/ssh-connections.md +++ b/docs/ssh-connections.md @@ -75,7 +75,7 @@ The local machine can be Linux, macOS or Windows. The remote host must be Linux ## Not in scope These are refused on a remote row with a message naming the gap: -- Rename, move, deleting a group, restart and fork. +- Rename, moving or deleting a group, moving or nesting a terminal, restart and fork. - Diff review. - The editor. - Copying a reply, marking idle, cancelling an after-turn end, reordering. diff --git a/docs/usage.md b/docs/usage.md index 49348016..5f84a68e 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -439,9 +439,10 @@ On a connection's rows: - `enter` and `A` attach over SSH in this terminal; detaching returns to the manager. A remote pane is never embedded. - Quick prompt mode types into a remote agent's pane as you, the way it does on this machine, or starts a new agent on the CLI, model, effort and profile the bar shows when a connection or remote group is selected. `n` starts one there too; the directory and the worktree default are the other machine's unless you set them. - `T` opens a terminal there and `g` creates a group there, under the selected one; `x` kills an agent or closes a terminal, `v` revives, `a` and `u` archive and restore. `d` deletes an agent there the way it does here, its worktree included when clean, and asks first; on a terminal it closes it, like `x`. +- `m` on an agent moves it to another group on the same host: the picker lists that host's groups and its root, never this machine's. It leaves out the archived groups the host refuses, apart from the agent's own and the groups above it, so enter leaves an archived agent where it is. Its terminals go with it. - On the connection row itself, `r` edits it and `d` removes it. Removing asks first; its sessions keep running on that host. -Rename, move, deleting a group, restart, fork, review, the editor, copying a reply, reordering, marking idle, cancelling an after-turn end and kill all or revive all are refused on a remote row with a message naming the gap. A failed call shows the other machine's error. Nothing from a connection is written to this machine's store. See [SSH connections](ssh-connections.md) for the protocol. +Rename, moving or deleting a group, moving or nesting a terminal, restart, fork, review, the editor, copying a reply, reordering, marking idle, cancelling an after-turn end and kill all or revive all are refused on a remote row with a message naming the gap. A failed call shows the other machine's error. Nothing from a connection is written to this machine's store. See [SSH connections](ssh-connections.md) for the protocol. ## Status diff --git a/internal/remote/operations_test.go b/internal/remote/operations_test.go index 05813995..d91bb9b8 100644 --- a/internal/remote/operations_test.go +++ b/internal/remote/operations_test.go @@ -326,6 +326,9 @@ func TestUnknownCommandIsTooOldNotUnreadable(t *testing.T) { if _, err := c.Delete(context.Background(), Ref{Host: "gpu", ID: "a1"}); err == nil || err.Error() != "gpu: agent-manager there is too old for SSH connections; update agent-manager on that host" { t.Fatalf("delete on a host that predates it = %v", err) } + if _, err := c.Move(context.Background(), Ref{Host: "gpu", ID: "a1"}, "ops"); err == nil || err.Error() != "gpu: agent-manager there is too old for SSH connections; update agent-manager on that host" { + t.Fatalf("move on a host that predates it = %v", err) + } c = newTestClient(t, func(context.Context, []string) ([]byte, []byte, error) { return []byte("closed terminal a1\n"), nil, nil }) diff --git a/internal/ui/connections/call.go b/internal/ui/connections/call.go index c716e622..70aba6fc 100644 --- a/internal/ui/connections/call.go +++ b/internal/ui/connections/call.go @@ -19,6 +19,7 @@ const ( OpArchive OpRestore OpDelete + OpMove ) // Call is the lifecycle call a rail action makes on a remote session or @@ -42,7 +43,7 @@ type Call struct { // status line words them. var Refusals = map[uirail.ActionKind]string{ uirail.RenameAction: "rename", - uirail.MoveToGroup: "move", + uirail.MoveToGroup: "moving a group", uirail.Delete: "deleting a group", uirail.Restart: "restart", uirail.Fork: "fork", @@ -90,6 +91,10 @@ func SessionCall(row Row, kind uirail.ActionKind, hint KeyHint) Call { return Call{Op: OpAttach, Answered: true} case row.Terminal && (kind == uirail.Revive || kind == uirail.Archive || kind == uirail.Restore): return Call{Refusal: "a terminal on " + row.Host + " is not archived or revived" + hint(keybind.Kill, " - %s closes it"), Answered: true} + case kind == uirail.MoveToGroup && row.Terminal: + return Call{Refusal: uirail.RemoteRefusal("moving or nesting a terminal"), Answered: true} + case kind == uirail.MoveToGroup: + return Call{Op: OpMove, Answered: true} case (kind == uirail.Kill || kind == uirail.Delete) && row.Terminal: return asking(OpCloseTerminal, false, hint) case kind == uirail.Delete: diff --git a/internal/ui/connections/call_test.go b/internal/ui/connections/call_test.go index 82990771..923c7653 100644 --- a/internal/ui/connections/call_test.go +++ b/internal/ui/connections/call_test.go @@ -44,6 +44,9 @@ func TestSessionCallAnswersEveryRemoteAction(t *testing.T) { Call{Answered: true, Refusal: "terminal sh has exited on box - x closes it"}}, {"a terminal is not archived", Row{Kind: SessionRow, Host: "box", Name: "sh", Terminal: true}, uirail.Archive, Call{Answered: true, Refusal: "a terminal on box is not archived or revived - x closes it"}}, + {"move picks a group on the host", row, uirail.MoveToGroup, Call{Op: OpMove, Answered: true}}, + {"a terminal is not moved or nested", Row{Kind: SessionRow, Host: "box", Name: "sh", Terminal: true}, uirail.MoveToGroup, + Call{Answered: true, Refusal: "moving or nesting a terminal isn't available on SSH connections yet"}}, {"a local action stays local", row, uirail.OpenReview, Call{}}, } for _, tc := range cases { diff --git a/internal/ui/connections/link/call.go b/internal/ui/connections/link/call.go index d8c99c6f..ceb2381d 100644 --- a/internal/ui/connections/link/call.go +++ b/internal/ui/connections/link/call.go @@ -5,6 +5,7 @@ import ( "github.com/YoanWai/agent-manager/internal/remote" "github.com/YoanWai/agent-manager/internal/sessioncmd" + uiframe "github.com/YoanWai/agent-manager/internal/ui/frame" tea "github.com/charmbracelet/bubbletea" ) @@ -21,6 +22,7 @@ const ( Restore CreateGroup Delete + Move ) type Call struct { @@ -34,6 +36,9 @@ type Call struct { // GroupDir is the directory a new group on the host defaults to; Name // carries its path. GroupDir string + // Group is the host's group a move files the session under, empty for + // its root. + Group string // Draft and ComposerGen let a send or spawn from the quick bar, or a // spawn from the New Session form, clear what asked for it. Draft string @@ -76,6 +81,8 @@ func Run(ctx context.Context, client *remote.Client, openers remote.Openers, cal result.Session, err = client.Archive(ctx, call.Ref, call.Op == Restore) case CreateGroup: _, err = client.CreateGroup(ctx, call.Host, call.Name, call.GroupDir) + case Move: + result.Session, err = client.Move(ctx, call.Ref, call.Group) } return result, err } @@ -121,6 +128,8 @@ func (s *State) ApplyCall(root Root, call Call, result Result, err error) tea.Cm case CreateGroup: root.CloseAsker(call.ComposerGen, GroupFormAsker) root.ReportDone("created group " + call.Name + on) + case Move: + root.ReportDone("moved " + call.Name + " to " + uiframe.DisplayGroup(call.Group) + on) } return s.PollHost(call.Host) } diff --git a/internal/ui/connections/link/call_test.go b/internal/ui/connections/link/call_test.go index fb6ada6e..951dcd5d 100644 --- a/internal/ui/connections/link/call_test.go +++ b/internal/ui/connections/link/call_test.go @@ -19,10 +19,11 @@ func TestRunTurnsEachCallIntoItsHostCommand(t *testing.T) { {Revive, []string{"revive", "--json", "--", "s1"}}, {Archive, []string{"archive", "--json", "--", "s1"}}, {Restore, []string{"archive", "--restore", "--json", "--", "s1"}}, + {Move, []string{"move", "--json", "--", "s1", "ops"}}, } { fake := &ssh{} client := listedState(t, fake).Client - call := Call{Op: tc.op, Host: "box", Ref: remote.Ref{Host: "box", ID: "s1"}, Name: "api", Text: "hello"} + call := Call{Op: tc.op, Host: "box", Ref: remote.Ref{Host: "box", ID: "s1"}, Name: "api", Text: "hello", Group: "ops"} if _, err := Run(context.Background(), client, nil, call); err != nil { t.Fatalf("%v: %v", tc.op, err) } diff --git a/internal/ui/connections_adapter.go b/internal/ui/connections_adapter.go index 1320f9b7..7b453cdc 100644 --- a/internal/ui/connections_adapter.go +++ b/internal/ui/connections_adapter.go @@ -7,6 +7,7 @@ import ( "github.com/YoanWai/agent-manager/internal/config" "github.com/YoanWai/agent-manager/internal/remote" "github.com/YoanWai/agent-manager/internal/sessioncmd" + "github.com/YoanWai/agent-manager/internal/store" uiconnections "github.com/YoanWai/agent-manager/internal/ui/connections" uilink "github.com/YoanWai/agent-manager/internal/ui/connections/link" uidialogs "github.com/YoanWai/agent-manager/internal/ui/dialogs" @@ -52,6 +53,9 @@ func (m *Model) connectionIntent(intent uirail.Intent) (tea.Cmd, bool) { case uirail.Delete: m.confirmRemoveConnection(row.Host) return nil, true + case uirail.MoveToGroup: + m.reportErr(row.Host + " is a connection, not a group to move") + return nil, true } } if intent.Kind == uirail.NewGroup { @@ -87,6 +91,10 @@ func (m *Model) remoteSessionIntent(row uiconnections.Row, call uiconnections.Ca if call.Op == uiconnections.OpAttach { return m.attachRemote(row), true } + if call.Op == uiconnections.OpMove { + m.openRemoteMove(row) + return nil, true + } if call.Op == uiconnections.OpNone { return nil, true } @@ -126,6 +134,49 @@ func (m *Model) confirmRemote(request uilink.Call, call uiconnections.Call, term return nil } +// openRemoteMove opens the move card on a remote agent with the groups of +// its own host, since a move never crosses machines. The host refuses an +// archived group, so the card leaves those out but the agent's own, where +// enter leaves it in place as it does here. +func (m *Model) openRemoteMove(row uiconnections.Row) { + if refusal, offline := m.ssh.Offline(row.Host); offline { + m.reportErr(refusal) + return + } + host, _ := m.ssh.Host(row.Host) + var groups []string + archived := map[string]bool{} + for _, group := range host.Groups { + groups = append(groups, group.Path) + archived[group.Path] = group.Archived + } + hidden := func(path string) bool { + return store.EffectivelyArchived(archived, path) && !uirail.InGroupSubtree(row.Group, path) + } + options, index := spawn.Options(groups, nil, hidden, row.Group) + m.gens.dialog++ + m.push(uidialogs.NewMoveSurface(remoteMoveRoot{moveRoot{m}, row}, uidialogs.MoveSession(row.Ref.ID), spawn.Picker{Groups: options, GroupIndex: index}, m.prefs.glyphMode)) + m.clearErr() +} + +// remoteMoveRoot is the root as the move card on a remote agent reaches it: +// the pick goes to the host, and the card closes as it does. +type remoteMoveRoot struct { + moveRoot + row uiconnections.Row +} + +func (r remoteMoveRoot) PlaceMove(_ uidialogs.Move, picker *spawn.Picker) tea.Cmd { + r.Pop() + group := picker.GroupPath() + if group == r.row.Group { + return nil + } + request := remoteCall(r.row.Host, r.row.Ref, r.row.Name) + request.Op, request.Group = uilink.Move, group + return r.queueRemote(request) +} + // queueRemote puts a call on the remote lane, unless the host's last // refresh could not reach it. func (m *Model) queueRemote(request uilink.Call) tea.Cmd { diff --git a/internal/ui/connections_adapter_test.go b/internal/ui/connections_adapter_test.go index 64c287be..020b9c77 100644 --- a/internal/ui/connections_adapter_test.go +++ b/internal/ui/connections_adapter_test.go @@ -119,8 +119,7 @@ func TestRemoteActionsAlreadyInPlaceDoNothing(t *testing.T) { func TestUnsupportedRemoteActionsAreRefusedWithoutIO(t *testing.T) { refused := map[uirail.ActionKind]string{ - uirail.RenameAction: "rename", uirail.MoveToGroup: "move", - uirail.Restart: "restart", uirail.Fork: "fork", uirail.OpenReview: "review", + uirail.RenameAction: "rename", uirail.Restart: "restart", uirail.Fork: "fork", uirail.OpenReview: "review", uirail.OpenEditor: "the editor", uirail.CopyReply: "copy reply", uirail.MarkIdle: "mark idle", uirail.CancelEnd: "cancel end", uirail.KillAll: "kill all", uirail.ReviveAll: "revive all", @@ -147,11 +146,84 @@ func TestUnsupportedRemoteActionsAreRefusedWithoutIO(t *testing.T) { if _, cmd := m.runRailIntent(uirail.Intent{Kind: uirail.Delete, Target: boxGroup}); cmd != nil || confirmOpen(m) || m.errBar.text != "deleting a group isn't available on SSH connections yet" { t.Fatalf("delete on a remote group: status %q", m.errBar.text) } + for target, want := range map[uirail.Selection]string{ + boxRow: "box is a connection, not a group to move", + boxGroup: "moving a group isn't available on SSH connections yet", + boxSession("t1"): "moving or nesting a terminal isn't available on SSH connections yet", + } { + m.clearErr() + if _, cmd := m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: target}); cmd != nil || moveOpen(m) || m.errBar.text != want { + t.Fatalf("move on %+v: status %q, want %q", target, m.errBar.text, want) + } + } if calls := fake.taken(); len(calls) != 0 { t.Fatalf("calls = %q, want none", calls) } } +// A move on a remote agent picks from that host's groups alone, which may +// take it, and the host files it there. +func TestRemoteMovePicksAmongTheHostsGroups(t *testing.T) { + fake := &fakeSSH{} + m := listedModel(t, fake) + m.workspace.groups = []string{"local-only"} + fake.snapshot.Groups = append(fake.snapshot.Groups, sessioncmd.Group{Path: "ops"}, sessioncmd.Group{Path: "ops/db"}, + sessioncmd.Group{Path: "shelf", Archived: true}, sessioncmd.Group{Path: "shelf/inner"}) + fake.snapshot.Sessions = append(fake.snapshot.Sessions, + sessioncmd.Session{ID: "s4", Name: "stored", Tool: "claude", Group: "shelf/inner", Status: "dead", Archived: true}) + setHost(m, "box", uilink.Facts(remote.HostState{OK: true, Snapshot: fake.snapshot})) + picked := func() (paths []string, cursor string) { + card, ok := surfaceOf[*uidialogs.MoveSurface](m) + if !ok { + t.Fatalf("no move card, status %q", m.errBar.text) + } + for _, option := range card.Picker().Groups { + paths = append(paths, option.Path) + } + return paths, card.Picker().GroupPath() + } + press := func(msg tea.KeyMsg) { + _, cmd := m.Update(msg) + m.runRemoteCmd(t, cmd) + } + + // The host refuses an archived group, so the card offers none but the + // agent's own. + m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: boxSession("s1")}) + if paths, cursor := picked(); !slices.Equal(paths, []string{"", "web", "ops", "ops/db"}) || cursor != "web" { + t.Fatalf("targets %q on %q, want the host's open groups on web", paths, cursor) + } + press(tea.KeyMsg{Type: tea.KeyEnter}) + if calls := fake.taken(); moveOpen(m) || len(calls) != 0 { + t.Fatalf("enter on its own group: open %v, calls %q", moveOpen(m), calls) + } + + m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: boxSession("s1")}) + press(tea.KeyMsg{Type: tea.KeyDown}) + press(tea.KeyMsg{Type: tea.KeyEnter}) + if calls := fake.taken(); moveOpen(m) || len(calls) == 0 || !slices.Equal(calls[0], []string{"move", "--json", "--", "s1", "ops"}) { + t.Fatalf("calls = %q, want the move to ops first", calls) + } + if m.errBar.text != "moved api to ops on box" { + t.Fatalf("status = %q", m.errBar.text) + } + + // An archived agent in an archived group opens on its own group, and + // enter leaves it there, as the local card does. + fake.mu.Lock() + fake.calls = nil + fake.mu.Unlock() + m.clearErr() + m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: uirail.Selection{Kind: uirail.SessionRow, SessionID: "s4", Group: "shelf/inner", Host: "box"}}) + if paths, cursor := picked(); !slices.Equal(paths, []string{"", "web", "ops", "ops/db", "shelf", "shelf/inner"}) || cursor != "shelf/inner" { + t.Fatalf("targets %q on %q, want its own archived group kept and selected", paths, cursor) + } + press(tea.KeyMsg{Type: tea.KeyEnter}) + if calls := fake.taken(); moveOpen(m) || len(calls) != 0 || m.errBar.text != "" { + t.Fatalf("enter on its own archived group: open %v, calls %q, status %q", moveOpen(m), calls, m.errBar.text) + } +} + func TestRemoteCallReportsTheHostsError(t *testing.T) { fake := &fakeSSH{} m := connectedModel(t, fake) @@ -171,12 +243,15 @@ func TestOfflineHostRefusesCallsWithItsError(t *testing.T) { state := hostState(m, "box") state.OK, state.Failures, state.Attempted, state.Err = false, 1, time.Now(), "box: unreachable over SSH: connection refused" setHost(m, "box", state) - _, cmd := m.runRailIntent(uirail.Intent{Kind: uirail.Kill, Target: boxSession("s1")}) - if cmd != nil || !m.remoteIdle() || len(fake.taken()) != 0 { - t.Fatal("a call to an offline host went out") - } - if m.errBar.text != "box: unreachable over SSH: connection refused" { - t.Fatalf("status = %q", m.errBar.text) + for name, kind := range map[string]uirail.ActionKind{"kill": uirail.Kill, "move": uirail.MoveToGroup} { + m.clearErr() + _, cmd := m.runRailIntent(uirail.Intent{Kind: kind, Target: boxSession("s1")}) + if cmd != nil || !m.remoteIdle() || len(fake.taken()) != 0 || moveOpen(m) { + t.Fatalf("%s on an offline host went out or opened a card", name) + } + if m.errBar.text != "box: unreachable over SSH: connection refused" { + t.Fatalf("%s: status = %q", name, m.errBar.text) + } } } diff --git a/internal/ui/help/catalog.go b/internal/ui/help/catalog.go index fa1c90da..8c72340b 100644 --- a/internal/ui/help/catalog.go +++ b/internal/ui/help/catalog.go @@ -135,6 +135,7 @@ func connectionRowHelpRows(list keybind.Table, mode presentation.GlyphMode) [][2 h.action("edit its name and SSH destination", keybind.Rename) h.action("remove it; its sessions keep running on that host", keybind.Delete) h.action("new session or terminal on that host", keybind.NewSession, keybind.Terminal) + h.action("move one of its agents to another group there", keybind.Move) h.fixed("", "its agents: attach, prompt, kill, revive, archive, restore, delete") h.fixed("", "attach opens an SSH attach in this terminal") return h.rows diff --git a/internal/ui/help/catalog_test.go b/internal/ui/help/catalog_test.go index 910ae3d8..f305a906 100644 --- a/internal/ui/help/catalog_test.go +++ b/internal/ui/help/catalog_test.go @@ -287,3 +287,24 @@ func TestSessionKeyMapNamesTheDivider(t *testing.T) { t.Fatal("the default resize key remains after the session binding moved") } } + +// A connection's agents move among that host's groups, under whatever key +// move is bound to. +func TestCatalogNamesTheMoveKeyOnAConnection(t *testing.T) { + for key, keys := range map[string]keybind.Table{ + "m": keybind.DefaultList(), + "M": keybind.DefaultList().With(keybind.Move, bindingOf(t, "M")), + } { + ctx := testContext(84) + ctx.ListKeys = keys + found := false + for _, section := range helpSections(ctx) { + for _, row := range section.rows { + found = found || section.title == "SSH connection under the cursor" && row == [2]string{key, "move one of its agents to another group there"} + } + } + if !found { + t.Errorf("no move row on %s for a connection", key) + } + } +} diff --git a/internal/ui/rail/hosts_test.go b/internal/ui/rail/hosts_test.go index 798158fd..6ee5d424 100644 --- a/internal/ui/rail/hosts_test.go +++ b/internal/ui/rail/hosts_test.go @@ -1,6 +1,7 @@ package rail import ( + "regexp" "slices" "strings" "testing" @@ -233,15 +234,31 @@ func TestConnectionMenusOfferOnlyRemoteActions(t *testing.T) { t.Errorf("connection menu = %v", got) } session := labels(Selection{Kind: SessionRow, SessionID: "far", Host: "box"}) - for _, refused := range []string{"Rename", "Move to group", "Fork", "Review changes", "Open in editor", "Restart"} { + for _, refused := range []string{"Rename", "Fork", "Review changes", "Open in editor", "Restart"} { if slices.Contains(session, refused) { t.Errorf("remote session menu offers %s: %v", refused, session) } } - if !slices.Contains(session, "Kill") || !slices.Contains(session, "Attach") || !slices.Contains(session, "Delete") { + if !slices.Contains(session, "Kill") || !slices.Contains(session, "Attach") || !slices.Contains(session, "Delete") || !slices.Contains(session, "Move to group") { t.Errorf("remote session menu = %v", session) } - // The host archives and revives agents only. + remapped, err := keybind.Parse("M") + if err != nil { + t.Fatal(err) + } + // Move remapped to M: the menu names M and M picks it. + keys := keybind.DefaultList().With(keybind.Move, keybind.Keys(remapped)) + far := Selection{Kind: SessionRow, SessionID: "far", Host: "box"} + model.openMenu(far, 0, 0, false) + ctx := hostsContext(48, 14) + ctx.ListKeys = keys + if menu := ansi.Strip(strings.Join(renderer{model: model, ctx: ctx, palette: newPalette(ctx.Theme)}.renderMenu(), "\n")); !regexp.MustCompile(`Move to group +M `).MatchString(menu) { + t.Errorf("remote session menu with move on M:\n%s", menu) + } + if decision := model.menuKey(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("M")}, KeyContext{ListKeys: keys}); decision.Intent != (Intent{Kind: MoveToGroup, Target: far}) { + t.Errorf("M in the remote session menu = %+v", decision.Intent) + } + // The host archives, revives and moves agents only. if got := labels(Selection{Kind: SessionRow, SessionID: "shell", Group: "ops", Host: "box"}); !slices.Equal(got, []string{"Attach", "Kill"}) { t.Errorf("remote terminal menu = %v, want Attach and Kill", got) } @@ -249,13 +266,13 @@ func TestConnectionMenusOfferOnlyRemoteActions(t *testing.T) { t.Errorf("root menu = %v, want New connection", got) } model.Reconcile(Snapshot{Hosts: []Host{{Name: "box", State: HostOnline, Sessions: []Session{{ID: "far", Name: "far", Tool: "claude", Status: "dead"}}}}}) - if got := labels(Selection{Kind: SessionRow, SessionID: "far", Host: "box"}); !slices.Equal(got, []string{"Revive", "Archive", "Delete"}) { - t.Errorf("dead remote session menu = %v, want Revive, Archive and Delete", got) + if got := labels(Selection{Kind: SessionRow, SessionID: "far", Host: "box"}); !slices.Equal(got, []string{"Move to group", "Revive", "Archive", "Delete"}) { + t.Errorf("dead remote session menu = %v, want Move to group, Revive, Archive and Delete", got) } model.SetArchived(true) model.Reconcile(Snapshot{Hosts: []Host{{Name: "box", State: HostOnline, Sessions: []Session{{ID: "far", Name: "far", Tool: "claude", Status: "dead", Archived: true}}}}}) - if got := labels(Selection{Kind: SessionRow, SessionID: "far", Host: "box"}); !slices.Equal(got, []string{"Restore", "Delete"}) { - t.Errorf("archived remote session menu = %v, want Restore and Delete", got) + if got := labels(Selection{Kind: SessionRow, SessionID: "far", Host: "box"}); !slices.Equal(got, []string{"Move to group", "Restore", "Delete"}) { + t.Errorf("archived remote session menu = %v, want Move to group, Restore and Delete", got) } } diff --git a/internal/ui/rail/legend.go b/internal/ui/rail/legend.go index 9c98fcda..9d61feb2 100644 --- a/internal/ui/rail/legend.go +++ b/internal/ui/rail/legend.go @@ -296,6 +296,9 @@ func (m Model) RemoteLegend(ctx LegendContext, row RemoteRow, collapsed bool) Le if row.Dead { pairs = append(pairs, [2]string{k(keybind.Revive), "revive"}) } + if !row.Terminal { + pairs = append(pairs, [2]string{k(keybind.Move), "move"}) + } pairs = append(pairs, m.archiveRestoreLegend(ctx)) return Legend{Title: title + " on " + row.Host, Leads: leads, Pairs: boundPairs(pairs)} } diff --git a/internal/ui/rail/legend_test.go b/internal/ui/rail/legend_test.go index 305a97c4..c4416e9b 100644 --- a/internal/ui/rail/legend_test.go +++ b/internal/ui/rail/legend_test.go @@ -84,3 +84,25 @@ func TestRemoteLegendOffersDeleteOnAnAgentOnly(t *testing.T) { t.Fatalf("a remote shell should leave delete to close, got %+v", shell.Pairs) } } + +func TestRemoteLegendOffersMoveOnAnAgentOnly(t *testing.T) { + model := rail.New(nil) + remapped, err := keybind.Parse("M") + if err != nil { + t.Fatal(err) + } + for key, keys := range map[string]keybind.Table{ + "m": keybind.DefaultList(), + "M": keybind.DefaultList().With(keybind.Move, keybind.Keys(remapped)), + } { + ctx := rail.LegendContext{ListKeys: keys} + agent := model.RemoteLegend(ctx, rail.RemoteRow{Kind: rail.SessionRow, Host: "box"}, false) + if !slices.Contains(agent.Pairs, [2]string{key, "move"}) { + t.Fatalf("a remote agent should offer move on %s, got %+v", key, agent.Pairs) + } + shell := model.RemoteLegend(ctx, rail.RemoteRow{Kind: rail.SessionRow, Host: "box", Terminal: true}, false) + if slices.ContainsFunc(shell.Pairs, func(pair [2]string) bool { return pair[1] == "move" }) { + t.Fatalf("a remote shell is neither moved nor nested there, got %+v", shell.Pairs) + } + } +} diff --git a/internal/ui/rail/menu.go b/internal/ui/rail/menu.go index f607d04b..7bb32123 100644 --- a/internal/ui/rail/menu.go +++ b/internal/ui/rail/menu.go @@ -115,12 +115,16 @@ func remoteMenuItems(row treeRow, create []menuItem, connection menuItem) []menu return append(create, group) } remove := menuItem{label: "Delete", action: Delete, danger: true} + var move []menuItem + if !row.sess.IsShell { + move = []menuItem{{label: "Move to group", action: MoveToGroup}} + } if row.sess.Archived { - return []menuItem{{label: "Restore", action: Restore}, remove} + return menuSections(move, []menuItem{{label: "Restore", action: Restore}, remove}) } kill := menuItem{label: "Kill", action: Kill, danger: true} if row.sess.IsShell { - // The host archives and revives agents only. + // The host archives, revives and moves agents only. if row.sess.Status == "dead" { return []menuItem{kill} } @@ -128,11 +132,12 @@ func remoteMenuItems(row treeRow, create []menuItem, connection menuItem) []menu } archive := menuItem{label: "Archive", action: Archive} if row.sess.Status == "dead" { - return menuSections([]menuItem{{label: "Revive", action: Revive}}, []menuItem{archive, remove}) + return menuSections(move, []menuItem{{label: "Revive", action: Revive}}, []menuItem{archive, remove}) } return menuSections( []menuItem{{label: "Attach", action: Attach}}, []menuItem{{label: "Quick prompt mode", action: Prompt}, {label: "New terminal", action: NewTerminal}}, + move, []menuItem{archive, kill, remove}, ) } diff --git a/tools/e2e/README.md b/tools/e2e/README.md index 3b124cb7..d062d2d7 100644 --- a/tools/e2e/README.md +++ b/tools/e2e/README.md @@ -164,6 +164,6 @@ or the Linux/SSH platform matrix. python3 tools/e2e/ssh_scenarios.py --binary /tmp/agent-manager-e2e ``` -A fixture `ssh` first on PATH drops every argument but the remote command and runs it with `/bin/sh -c` under a second disposable HOME and its own short tmux socket directory, so the "host" is a real agent-manager with its own profile and no network, keys or `~/.ssh`. A copy of the binary, first on PATH at a path unique to the run, serves both sides. The scenario seeds an agent on the host through its CLI, adds the connection through the `C` dialog, waits for the remote row, answers it from the quick bar and checks the prompt reached the host's pane with nothing queued in its inbox, kills it and checks its tmux session is gone on the host. It then revives, archives and restores it, deletes a second agent and checks the host's store no longer has it, attaches to the first and detaches, and starts an agent, a terminal and a group there. It requires that the local store holds the connection and no sessions. A second connection whose ssh fails shows as unreachable. The first refresh starts the host's headless manager. +A fixture `ssh` first on PATH drops every argument but the remote command and runs it with `/bin/sh -c` under a second disposable HOME and its own short tmux socket directory, so the "host" is a real agent-manager with its own profile and no network, keys or `~/.ssh`. A copy of the binary, first on PATH at a path unique to the run, serves both sides. The scenario seeds an agent on the host through its CLI, adds the connection through the `C` dialog, waits for the remote row, answers it from the quick bar and checks the prompt reached the host's pane with nothing queued in its inbox, moves the grouped agent to the host's root with `m` and checks the host filed it there, kills the first and checks its tmux session is gone on the host. It then revives, archives and restores it, deletes a second agent and checks the host's store no longer has it, attaches to the first and detaches, and starts an agent, a terminal and a group there. It requires that the local store holds the connection and no sessions. A second connection whose ssh fails shows as unreachable. The first refresh starts the host's headless manager. Cleanup ends every process by PID: the binary copy's processes (the host's `serve` among them) and the tmux servers on the run's own sockets, listed in `ended-processes.json`. No `kill-server` is sent. diff --git a/tools/e2e/ssh_scenarios.py b/tools/e2e/ssh_scenarios.py index 879ec398..b0fb7319 100644 --- a/tools/e2e/ssh_scenarios.py +++ b/tools/e2e/ssh_scenarios.py @@ -5,9 +5,9 @@ runs it with /bin/sh under a second disposable profile, so the manager talks to a real agent-manager "host" without a network or the user's ~/.ssh. The scenario adds a connection through the dialog and drives every action a -remote row offers: preview, quick send, kill, revive, archive, restore, -delete, attach, quick spawn and a new terminal. A second connection whose host -refuses shows as unreachable and is removed. Every process it started is ended by PID. +remote row offers: preview, quick send, move, kill, revive, archive, +restore, delete, attach, quick spawn and a new terminal. A second connection +whose host refuses shows as unreachable and is removed. Every process it started is ended by PID. """ import argparse import hashlib @@ -227,6 +227,18 @@ def confirm(sandbox, name, question, done): frame(sandbox, name + '-done', done) +def move(sandbox, remote): + """m on a remote agent picks among the host's groups, and the host files it there.""" + select(sandbox, 'grouped-agent', f'{GROUPED_AGENT} on {CONNECTION}') + key(sandbox, 'm') + frame(sandbox, 'remote-move', 'Move') + key(sandbox, 'Up') + key(sandbox, 'Enter') + frame(sandbox, 'remote-moved', f'moved {GROUPED_AGENT} to root on {CONNECTION}') + sandbox.wait('remote-move-landed', lambda: str(remote.query(f"SELECT group_name FROM sessions WHERE name = '{GROUPED_AGENT}'")), + lambda value: value == "[('',)]") + + def lifecycle(sandbox, remote, agent_id): """Kill, revive, archive and restore, each confirmed, each landing on the host.""" key(sandbox, 'x') @@ -363,6 +375,8 @@ def scenario(sandbox, remote, binary): key(sandbox, 'Escape') frame(sandbox, 'quick-closed', f'{REMOTE_AGENT} on {CONNECTION}', 'Quick prompt mode') + move(sandbox, remote) + select_remote_agent(sandbox) lifecycle(sandbox, remote, agent_id) attach(sandbox, remote, agent_id) spawn_and_terminal(sandbox, remote) From 678afe3cbfb967359a7da528df8522eccea414d2 Mon Sep 17 00:00:00 2001 From: Andreas Spannagel Date: Tue, 17 Nov 2026 00:54:14 +0100 Subject: [PATCH 2/2] fix(ui): weigh a remote move against the agent's current group The move card compared the pick with the group the agent was in when the card opened. An agent the host moved meanwhile could then not be moved back: enter on its old group closed the card with no call. The pick is now compared with the agent's row in the host's latest snapshot. The remote move tests get their own file, so connections_adapter_test.go stops growing. --- internal/ui/connections_adapter.go | 6 +- internal/ui/connections_adapter_move_test.go | 101 +++++++++++++++++++ internal/ui/connections_adapter_test.go | 63 ------------ 3 files changed, 106 insertions(+), 64 deletions(-) create mode 100644 internal/ui/connections_adapter_move_test.go diff --git a/internal/ui/connections_adapter.go b/internal/ui/connections_adapter.go index 7b453cdc..ea6d8900 100644 --- a/internal/ui/connections_adapter.go +++ b/internal/ui/connections_adapter.go @@ -169,7 +169,11 @@ type remoteMoveRoot struct { func (r remoteMoveRoot) PlaceMove(_ uidialogs.Move, picker *spawn.Picker) tea.Cmd { r.Pop() group := picker.GroupPath() - if group == r.row.Group { + current := r.row.Group + if now, ok := r.ssh.Row(uirail.Selection{Kind: uirail.SessionRow, SessionID: r.row.Ref.ID, Host: r.row.Host}); ok { + current = now.Group + } + if group == current { return nil } request := remoteCall(r.row.Host, r.row.Ref, r.row.Name) diff --git a/internal/ui/connections_adapter_move_test.go b/internal/ui/connections_adapter_move_test.go new file mode 100644 index 00000000..89a75bac --- /dev/null +++ b/internal/ui/connections_adapter_move_test.go @@ -0,0 +1,101 @@ +package ui + +import ( + "slices" + "testing" + + "github.com/YoanWai/agent-manager/internal/remote" + "github.com/YoanWai/agent-manager/internal/sessioncmd" + uilink "github.com/YoanWai/agent-manager/internal/ui/connections/link" + uidialogs "github.com/YoanWai/agent-manager/internal/ui/dialogs" + uirail "github.com/YoanWai/agent-manager/internal/ui/rail" + tea "github.com/charmbracelet/bubbletea" +) + +// A move on a remote agent picks from that host's groups alone, which may +// take it, and the host files it there. +func TestRemoteMovePicksAmongTheHostsGroups(t *testing.T) { + fake := &fakeSSH{} + m := listedModel(t, fake) + m.workspace.groups = []string{"local-only"} + fake.snapshot.Groups = append(fake.snapshot.Groups, sessioncmd.Group{Path: "ops"}, sessioncmd.Group{Path: "ops/db"}, + sessioncmd.Group{Path: "shelf", Archived: true}, sessioncmd.Group{Path: "shelf/inner"}) + fake.snapshot.Sessions = append(fake.snapshot.Sessions, + sessioncmd.Session{ID: "s4", Name: "stored", Tool: "claude", Group: "shelf/inner", Status: "dead", Archived: true}) + setHost(m, "box", uilink.Facts(remote.HostState{OK: true, Snapshot: fake.snapshot})) + picked := func() (paths []string, cursor string) { + card, ok := surfaceOf[*uidialogs.MoveSurface](m) + if !ok { + t.Fatalf("no move card, status %q", m.errBar.text) + } + for _, option := range card.Picker().Groups { + paths = append(paths, option.Path) + } + return paths, card.Picker().GroupPath() + } + press := func(msg tea.KeyMsg) { + _, cmd := m.Update(msg) + m.runRemoteCmd(t, cmd) + } + + // The host refuses an archived group, so the card offers none but the + // agent's own. + m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: boxSession("s1")}) + if paths, cursor := picked(); !slices.Equal(paths, []string{"", "web", "ops", "ops/db"}) || cursor != "web" { + t.Fatalf("targets %q on %q, want the host's open groups on web", paths, cursor) + } + press(tea.KeyMsg{Type: tea.KeyEnter}) + if calls := fake.taken(); moveOpen(m) || len(calls) != 0 { + t.Fatalf("enter on its own group: open %v, calls %q", moveOpen(m), calls) + } + + m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: boxSession("s1")}) + press(tea.KeyMsg{Type: tea.KeyDown}) + press(tea.KeyMsg{Type: tea.KeyEnter}) + if calls := fake.taken(); moveOpen(m) || len(calls) == 0 || !slices.Equal(calls[0], []string{"move", "--json", "--", "s1", "ops"}) { + t.Fatalf("calls = %q, want the move to ops first", calls) + } + if m.errBar.text != "moved api to ops on box" { + t.Fatalf("status = %q", m.errBar.text) + } + + // An archived agent in an archived group opens on its own group, and + // enter leaves it there, as the local card does. + fake.mu.Lock() + fake.calls = nil + fake.mu.Unlock() + m.clearErr() + m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: uirail.Selection{Kind: uirail.SessionRow, SessionID: "s4", Group: "shelf/inner", Host: "box"}}) + if paths, cursor := picked(); !slices.Equal(paths, []string{"", "web", "ops", "ops/db", "shelf", "shelf/inner"}) || cursor != "shelf/inner" { + t.Fatalf("targets %q on %q, want its own archived group kept and selected", paths, cursor) + } + press(tea.KeyMsg{Type: tea.KeyEnter}) + if calls := fake.taken(); moveOpen(m) || len(calls) != 0 || m.errBar.text != "" { + t.Fatalf("enter on its own archived group: open %v, calls %q, status %q", moveOpen(m), calls, m.errBar.text) + } +} + +// A pick is weighed against the group the agent is in now, not the one it +// was in when the card opened. +func TestRemoteMoveComparesWithTheGroupTheAgentIsInNow(t *testing.T) { + fake := &fakeSSH{} + m := listedModel(t, fake) + fake.snapshot.Groups = append(fake.snapshot.Groups, sessioncmd.Group{Path: "ops"}) + setHost(m, "box", uilink.Facts(remote.HostState{OK: true, Snapshot: fake.snapshot})) + m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: boxSession("s1")}) + + moved := fake.snapshot + moved.Sessions = slices.Clone(moved.Sessions) + for i := range moved.Sessions { + if moved.Sessions[i].ID == "s1" { + moved.Sessions[i].Group = "ops" + } + } + setHost(m, "box", uilink.Facts(remote.HostState{OK: true, Snapshot: moved})) + + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m.runRemoteCmd(t, cmd) + if calls := fake.taken(); len(calls) == 0 || !slices.Equal(calls[0], []string{"move", "--json", "--", "s1", "web"}) { + t.Fatalf("calls = %q, want the move back to web", calls) + } +} diff --git a/internal/ui/connections_adapter_test.go b/internal/ui/connections_adapter_test.go index 020b9c77..10c99fb0 100644 --- a/internal/ui/connections_adapter_test.go +++ b/internal/ui/connections_adapter_test.go @@ -161,69 +161,6 @@ func TestUnsupportedRemoteActionsAreRefusedWithoutIO(t *testing.T) { } } -// A move on a remote agent picks from that host's groups alone, which may -// take it, and the host files it there. -func TestRemoteMovePicksAmongTheHostsGroups(t *testing.T) { - fake := &fakeSSH{} - m := listedModel(t, fake) - m.workspace.groups = []string{"local-only"} - fake.snapshot.Groups = append(fake.snapshot.Groups, sessioncmd.Group{Path: "ops"}, sessioncmd.Group{Path: "ops/db"}, - sessioncmd.Group{Path: "shelf", Archived: true}, sessioncmd.Group{Path: "shelf/inner"}) - fake.snapshot.Sessions = append(fake.snapshot.Sessions, - sessioncmd.Session{ID: "s4", Name: "stored", Tool: "claude", Group: "shelf/inner", Status: "dead", Archived: true}) - setHost(m, "box", uilink.Facts(remote.HostState{OK: true, Snapshot: fake.snapshot})) - picked := func() (paths []string, cursor string) { - card, ok := surfaceOf[*uidialogs.MoveSurface](m) - if !ok { - t.Fatalf("no move card, status %q", m.errBar.text) - } - for _, option := range card.Picker().Groups { - paths = append(paths, option.Path) - } - return paths, card.Picker().GroupPath() - } - press := func(msg tea.KeyMsg) { - _, cmd := m.Update(msg) - m.runRemoteCmd(t, cmd) - } - - // The host refuses an archived group, so the card offers none but the - // agent's own. - m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: boxSession("s1")}) - if paths, cursor := picked(); !slices.Equal(paths, []string{"", "web", "ops", "ops/db"}) || cursor != "web" { - t.Fatalf("targets %q on %q, want the host's open groups on web", paths, cursor) - } - press(tea.KeyMsg{Type: tea.KeyEnter}) - if calls := fake.taken(); moveOpen(m) || len(calls) != 0 { - t.Fatalf("enter on its own group: open %v, calls %q", moveOpen(m), calls) - } - - m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: boxSession("s1")}) - press(tea.KeyMsg{Type: tea.KeyDown}) - press(tea.KeyMsg{Type: tea.KeyEnter}) - if calls := fake.taken(); moveOpen(m) || len(calls) == 0 || !slices.Equal(calls[0], []string{"move", "--json", "--", "s1", "ops"}) { - t.Fatalf("calls = %q, want the move to ops first", calls) - } - if m.errBar.text != "moved api to ops on box" { - t.Fatalf("status = %q", m.errBar.text) - } - - // An archived agent in an archived group opens on its own group, and - // enter leaves it there, as the local card does. - fake.mu.Lock() - fake.calls = nil - fake.mu.Unlock() - m.clearErr() - m.runRailIntent(uirail.Intent{Kind: uirail.MoveToGroup, Target: uirail.Selection{Kind: uirail.SessionRow, SessionID: "s4", Group: "shelf/inner", Host: "box"}}) - if paths, cursor := picked(); !slices.Equal(paths, []string{"", "web", "ops", "ops/db", "shelf", "shelf/inner"}) || cursor != "shelf/inner" { - t.Fatalf("targets %q on %q, want its own archived group kept and selected", paths, cursor) - } - press(tea.KeyMsg{Type: tea.KeyEnter}) - if calls := fake.taken(); moveOpen(m) || len(calls) != 0 || m.errBar.text != "" { - t.Fatalf("enter on its own archived group: open %v, calls %q, status %q", moveOpen(m), calls, m.errBar.text) - } -} - func TestRemoteCallReportsTheHostsError(t *testing.T) { fake := &fakeSSH{} m := connectedModel(t, fake)