diff --git a/docs/ssh-connections.md b/docs/ssh-connections.md index 66a632e0e..3af9a6ab0 100644 --- a/docs/ssh-connections.md +++ b/docs/ssh-connections.md @@ -27,7 +27,7 @@ The protocol is the remote host's own CLI, run over SSH as `agent-manager ` | | Spawn | `spawn --json ...`, `terminal create --json ...` | | Lifecycle | `kill`, `delete`, `revive`, `archive [--restore]`, `move`, `terminal close` | -| Groups | `create-group`, `delete-group` | +| Groups | `create-group`, `delete-group`, and `delete-group --with-sessions=` for `d` on a group | | Attach | `ssh -t ` running `tmux -L agentmgr attach-session -t `, then taking back any review or editor request the host's keys left on its tmux server | The snapshot envelope carries `version`. A remote that does not know `snapshot`, or answers with an older version, says to update agent-manager on that host. One that answers with a newer version says to update it on this machine. @@ -38,6 +38,7 @@ Once a connection is saved, every agent on this machine can reach that host thro An SSH call has no calling session on the remote host. The commands it uses run without one: - `kill`, `delete`, `revive`, `archive`, `move`, `create-group` and `delete-group` act as the user would. +- `delete-group --with-sessions=` deletes the group with every session in it, the way `d` does on that host, and runs only with no calling session. The ids are the sessions the confirm counted from the last snapshot, none for an empty group, and the host refuses when the sessions it now holds there are not exactly those. A host too old to know the flag refuses it, and the status line says to update agent-manager there. - `terminal create` opens a terminal that belongs to no session. `terminal send`, `read` and `close` drive only such terminals. A terminal nested under a session stays that session's. - Every SSH call is the same caller there, so the local MCP server tells them apart: it records which session's `create_terminal` opened a remote terminal, and `send_terminal` and `close_terminal` on a `host::id` refuse any other session before calling ssh. A terminal opened with `T` on the connection row has no such record, so only the user drives it. The record goes when the terminal is closed through MCP or its session is deleted. - `send --from` names the sender, at most 64 bytes. The delivered message says it came from another of the user's machines and that a reply cannot reach it. Every `--from` sender shares one rate limit per target. @@ -75,7 +76,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, move, deleting a group in the archived view, 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 493480161..9aca52d32 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -352,7 +352,7 @@ Registration is per tool. Claude gets a generated `--mcp-config` file. Codex get Pi does not include an MCP client. Its sessions reach the same workspace through the subcommands: `agent-manager --help` lists them, from `sessions`, `spawn`, `send` and `wait` to the shared task list, file reservations, terminals and the review declarations. `update` and `settings` need no caller at all, and `issue` and `feature` use only the session id the launch exported. Every other subcommand acts as the session or [terminal tab](#terminal-tabs) whose pane started it, so the same subcommands work from a shell you opened with `T`. A Claude Code conversation the manager launched keeps acting as its session after `/background`, `/fork` or the agent view moves it into Claude's daemon, since its startup hook reports the conversation as the session's own. A Claude started by hand in a pane and moved there has no caller. A `spawn` from a terminal tab with no `--tool` runs the CLI picked in Settings. `move` also takes a `host::id` from one of your [SSH connections](#ssh-connections) and moves that session there, as `move_session` does. -`sessions`, `groups`, `snapshot`, `spawn`, `read`, `wait`, `kill`, `delete`, `revive`, `archive`, `move`, `create-group` and `delete-group` also run with no caller at all (a `move` of a `host::id` excepted, which needs one the way the MCP tools do), so a script, a cron job or a CI step outside Agent Manager can open sessions that show up in your list. Such a `spawn` runs the CLI picked in Settings, in the root group and the directory the script runs in, unless `--tool`, `--group` or `--directory` says otherwise: +`sessions`, `groups`, `snapshot`, `spawn`, `read`, `wait`, `kill`, `delete`, `revive`, `archive`, `move`, `create-group` and `delete-group` also run with no caller at all (a `move` of a `host::id` excepted, which needs one the way the MCP tools do, and `delete-group --with-sessions=` runs only that way), so a script, a cron job or a CI step outside Agent Manager can open sessions that show up in your list. Such a `spawn` runs the CLI picked in Settings, in the root group and the directory the script runs in, unless `--tool`, `--group` or `--directory` says otherwise: ```bash agent-manager spawn --tool claude --group "Sprint Manager" --worktree \ @@ -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`. +- `d` on a group deletes it there with its subgroups and every session in them, archived ones and terminals included, the way it does here. It asks first with that machine's counts, and if the sessions there changed before you answer, the other machine refuses and nothing is deleted. - 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, move, deleting a group in the archived view, 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/cli/cli.go b/internal/cli/cli.go index 1ef609358..6f5645adb 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -119,7 +119,7 @@ func Help(version string, proactive bool) string { if !proactive { help.WriteString("Work with those other agents only when the user asks: on your own, do not list, message, spawn or wait on them, or create or claim shared tasks.\n") } - help.WriteString("update and settings need no caller, and issue and feature use only the exported session id. Every other command acts as the session or terminal whose pane started it, so run them from your own shell, not from a daemon or a process that outlived its pane. The exception is a Claude conversation Agent Manager launched that /background, /fork or the agent view moved out of its pane: it still acts as the session that launched it, while one started by hand has no caller. sessions, groups, snapshot, spawn, read, wait, kill, delete, revive, archive, move, create-group and delete-group also run from a script outside Agent Manager (a move of a host::id excepted), where spawn defaults to the CLI picked in settings, the root group and the script's directory. So do send with --from , whose message says no reply can reach the sender, and terminal create, send, read and close, which there open a terminal under no session and drive only terminals under none. type runs only there: it is the user's own quick bar prompt from another machine, so an agent never uses it.\n") + help.WriteString("update and settings need no caller, and issue and feature use only the exported session id. Every other command acts as the session or terminal whose pane started it, so run them from your own shell, not from a daemon or a process that outlived its pane. The exception is a Claude conversation Agent Manager launched that /background, /fork or the agent view moved out of its pane: it still acts as the session that launched it, while one started by hand has no caller. sessions, groups, snapshot, spawn, read, wait, kill, delete, revive, archive, move, create-group and delete-group also run from a script outside Agent Manager (a move of a host::id excepted, and delete-group --with-sessions runs only there), where spawn defaults to the CLI picked in settings, the root group and the script's directory. So do send with --from , whose message says no reply can reach the sender, and terminal create, send, read and close, which there open a terminal under no session and drive only terminals under none. type runs only there: it is the user's own quick bar prompt from another machine, so an agent never uses it.\n") for _, section := range sections(version, nil) { help.WriteString("\n" + section.title + "\n") help.WriteString(usageLines(section.commands)) diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 68a8bbf36..371966bad 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -45,6 +45,7 @@ type fakeSessions struct { ttl time.Duration deleted bool notice string + confirmed []string session sessioncmd.Session wait sessioncmd.WaitResult @@ -175,6 +176,11 @@ func (f *fakeSessions) DeleteGroup(sessionID, path string) (sessioncmd.GroupRemo return sessioncmd.GroupRemoval{Removed: []string{path}, Moved: []string{"beef1234"}}, f.failWith } +func (f *fakeSessions) DeleteGroupWithSessions(sessionID, path string, confirmed []string) (sessioncmd.GroupDeletion, error) { + f.callerID, f.groupPath, f.confirmed, f.deleted = sessionID, path, confirmed, true + return sessioncmd.GroupDeletion{Removed: []string{path, path + "/web"}, Deleted: confirmed, Notice: f.notice}, f.failWith +} + func (f *fakeSessions) Tasks(sessionID string) ([]sessioncmd.Task, error) { f.callerID = sessionID return []sessioncmd.Task{f.task}, f.failWith @@ -306,6 +312,7 @@ func TestALayerFailureReachesTheCaller(t *testing.T) { {"groups", nil, func(out io.Writer, args []string) error { return runGroups(out, sessions, args, "cafe0001") }}, {"create-group", []string{"api/web"}, func(out io.Writer, args []string) error { return runCreateGroup(out, sessions, args, "cafe0001") }}, {"delete-group", []string{"api/web"}, func(out io.Writer, args []string) error { return runDeleteGroup(out, sessions, args, "cafe0001") }}, + {"delete-group --with-sessions", []string{"api/web", "--with-sessions=a1,b2"}, func(out io.Writer, args []string) error { return runDeleteGroup(out, sessions, args, "") }}, {"task list", nil, func(out io.Writer, args []string) error { return runTaskList(out, sessions, args, "cafe0001") }}, {"task create", []string{"ship the api"}, func(out io.Writer, args []string) error { return runTaskCreate(out, sessions, args, "cafe0001") }}, {"task claim", nil, func(out io.Writer, args []string) error { return runTaskClaim(out, sessions, args, "cafe0001") }}, diff --git a/internal/cli/session.go b/internal/cli/session.go index d317d8e38..d8a09c351 100644 --- a/internal/cli/session.go +++ b/internal/cli/session.go @@ -8,6 +8,7 @@ import ( "io" "path/filepath" "strconv" + "strings" "time" "github.com/YoanWai/agent-manager/internal/remote" @@ -33,7 +34,7 @@ const ( usageKillSelf = "kill-self [--cancel] [--json]" usageGroups = "groups [--json]" usageCreateGroup = "create-group [--directory ] [--json]" - usageDeleteGroup = "delete-group [--json]" + usageDeleteGroup = "delete-group [--with-sessions=] [--json]" ) type sessionCommands interface { @@ -58,6 +59,7 @@ type sessionCommands interface { Groups(sessionID string) ([]sessioncmd.Group, error) CreateGroup(sessionID, path, directory string) (sessioncmd.Group, error) DeleteGroup(sessionID, path string) (sessioncmd.GroupRemoval, error) + DeleteGroupWithSessions(sessionID, path string, confirmed []string) (sessioncmd.GroupDeletion, error) } func newSessions(configDir string) sessionCommands { @@ -117,7 +119,7 @@ func sessionSectionWith(open func(string) sessionCommands) section { {name: "kill-self", usage: usageKillSelf, about: "stop this session's agent once the current turn ends, keeping its row for revive; --cancel withdraws a pending archive or kill", run: bind(open, runKillSelf)}, {name: "groups", usage: usageGroups, about: "list the groups sessions and terminals are filed under", run: bind(open, runGroups)}, {name: "create-group", usage: usageCreateGroup, about: "create a group so a fleet you spawn stays together in the user's list", run: bind(open, runCreateGroup)}, - {name: "delete-group", usage: usageDeleteGroup, about: "remove a group whose work is done; sessions still in it move to the root rather than stopping", run: bind(open, runDeleteGroup)}, + {name: "delete-group", usage: usageDeleteGroup, about: "remove a group whose work is done; sessions still in it move to the root rather than stopping, unless --with-sessions deletes them with it as the user's delete key does", run: bind(open, runDeleteGroup)}, }, } } @@ -465,11 +467,27 @@ func runCreateGroup(out io.Writer, sessions sessionCommands, args []string, sess func runDeleteGroup(out io.Writer, sessions sessionCommands, args []string, sessionID string) error { set := newFlagSet(usageDeleteGroup) + var withSessions bool + var confirmed []string + set.Func("with-sessions", "delete the sessions in the group too, as the delete key does; the ids are the ones the user confirmed, empty for none, and any other set there refuses", func(value string) error { + withSessions = true + if value != "" { + confirmed = strings.Split(value, ",") + } + return nil + }) asJSON := jsonFlag(set) operands, err := parseCommand(out, set, args, 1, 1) if err != nil { return err } + if withSessions { + deletion, err := sessions.DeleteGroupWithSessions(sessionID, operands[0], confirmed) + if err != nil { + return err + } + return emit(out, *asJSON, deletion, sessioncmd.FormatGroupDeletion(deletion)) + } removal, err := sessions.DeleteGroup(sessionID, operands[0]) if err != nil { return err diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go index b81c4374c..65efa5c59 100644 --- a/internal/cli/session_test.go +++ b/internal/cli/session_test.go @@ -219,6 +219,19 @@ func TestSessionCommandsParseArgumentsAndPrintSentences(t *testing.T) { } }, }, + { + name: "delete-group --with-sessions deletes them with the group", + run: func(out *bytes.Buffer, f *fakeSessions, args []string) error { + return runDeleteGroup(out, f, args, "") + }, + args: []string{"fleet", "--with-sessions=a1,b2,c3"}, + want: "deleted fleet, fleet/web and the 3 session(s) in them", + inspect: func(t *testing.T, f *fakeSessions) { + if !f.deleted || f.groupPath != "fleet" || !slices.Equal(f.confirmed, []string{"a1", "b2", "c3"}) { + t.Fatalf("delete-group --with-sessions got %q with %q, deleting %v", f.groupPath, f.confirmed, f.deleted) + } + }, + }, { name: "create-group takes a path and a directory", run: func(out *bytes.Buffer, f *fakeSessions, args []string) error { @@ -251,6 +264,20 @@ func TestSessionCommandsParseArgumentsAndPrintSentences(t *testing.T) { } } +// The flag itself opts in, so an empty value is a group the user confirmed +// holding nothing, not a plain delete-group that moves sessions to the root. +func TestDeleteGroupWithSessionsTakesTheConfirmedIDs(t *testing.T) { + fake := &fakeSessions{} + if err := runDeleteGroup(&bytes.Buffer{}, fake, []string{"fleet", "--with-sessions="}, ""); err != nil || !fake.deleted || len(fake.confirmed) != 0 { + t.Fatalf("--with-sessions= = %v, deleting %v with %q", err, fake.deleted, fake.confirmed) + } + fake = &fakeSessions{} + var out bytes.Buffer + if err := runDeleteGroup(&out, fake, []string{"fleet"}, ""); err != nil || fake.deleted || !strings.Contains(out.String(), "moved") { + t.Fatalf("delete-group without the flag = %v, deleting %v, printing %q", err, fake.deleted, out.String()) + } +} + // A delete that kept a shared worktree says so on its own line, and --json // carries the same notice for a script to read. func TestDeletePrintsTheNoticeAndTheRecord(t *testing.T) { diff --git a/internal/remote/operations.go b/internal/remote/operations.go index 0c202f69d..21358744d 100644 --- a/internal/remote/operations.go +++ b/internal/remote/operations.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "strconv" + "strings" "github.com/YoanWai/agent-manager/internal/sessioncmd" ) @@ -285,6 +286,26 @@ func (c *Client) DeleteGroup(ctx context.Context, host, path string) (sessioncmd return cleanRemoval(removal), err } +// DeleteGroupWithSessions deletes the group on its host with every session +// filed in it, the way the delete key does there. confirmed holds the ids of +// the sessions the user was asked about, and the host refuses when it holds +// another set. +func (c *Client) DeleteGroupWithSessions(ctx context.Context, host, path string, confirmed []string) (sessioncmd.GroupDeletion, error) { + for _, id := range confirmed { + if err := validID(id); err != nil { + return sessioncmd.GroupDeletion{}, &Error{Host: host, Err: err} + } + } + var deletion sessioncmd.GroupDeletion + // --json goes first: a host that predates --with-sessions then names the + // flag it does not know, which is the answer reworded below. + err := c.decode(ctx, host, callTimeout, &deletion, "delete-group", "--json", "--with-sessions="+strings.Join(confirmed, ","), "--", path) + if err != nil && strings.Contains(err.Error(), "flag provided but not defined: -with-sessions") { + return deletion, &Error{Host: host, Err: errors.New("agent-manager there is too old to delete a group with its sessions; update agent-manager on that host")} + } + return cleanDeletion(deletion), err +} + func validRef(ref Ref) error { if err := validID(ref.ID); err != nil { return &Error{Host: ref.Host, Err: err} diff --git a/internal/remote/operations_test.go b/internal/remote/operations_test.go index 05813995d..6727b65e8 100644 --- a/internal/remote/operations_test.go +++ b/internal/remote/operations_test.go @@ -142,6 +142,14 @@ func TestOperationArgv(t *testing.T) { _, err := c.DeleteGroup(ctx, "gpu", "--") return err }, []string{"delete-group", "--json", "--", "--"}}, + {"delete group with its sessions", func(ctx context.Context, c *Client) error { + _, err := c.DeleteGroupWithSessions(ctx, "gpu", "--", []string{"a1b2c3d4", "t9"}) + return err + }, []string{"delete-group", "--json", "--with-sessions=a1b2c3d4,t9", "--", "--"}}, + {"delete an empty group with its sessions", func(ctx context.Context, c *Client) error { + _, err := c.DeleteGroupWithSessions(ctx, "gpu", "web", nil) + return err + }, []string{"delete-group", "--json", "--with-sessions=", "--", "web"}}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -181,6 +189,10 @@ func TestUnsafeIDsNeverReachSSH(t *testing.T) { errs = append(errs, err) _, err = c.Move(ctx, bad, "work") errs = append(errs, err) + for _, ids := range [][]string{{"a1", bad.ID}, {"a1,b2"}, {""}} { + _, err = c.DeleteGroupWithSessions(ctx, "gpu", "web", ids) + errs = append(errs, err) + } for i, err := range errs { if err == nil { t.Errorf("call %d accepted an unsafe id", i) @@ -222,6 +234,11 @@ func TestOperationsDecodeTheRemoteJSON(t *testing.T) { if got, err := c.DeleteGroup(ctx, "gpu", "a"); err != nil || !reflect.DeepEqual(got, want) { t.Fatalf("DeleteGroup = %+v, %v", got, err) } + c, _ = recorder(t, `{"removed":["a","a/b\u001b[31m"],"deleted":["s1","s2; rm -rf ~"],"notice":"worktree kept (has work): /w\u001b[2J"}`) + deletion := sessioncmd.GroupDeletion{Removed: []string{"a", "a/b"}, Deleted: []string{"s1"}, Notice: "worktree kept (has work): /w"} + if got, err := c.DeleteGroupWithSessions(ctx, "gpu", "a", []string{"s1", "s2"}); err != nil || !reflect.DeepEqual(got, deletion) { + t.Fatalf("DeleteGroupWithSessions = %+v, %v", got, err) + } c, _ = recorder(t, "closed terminal a1\n") if err := c.TerminalClose(ctx, ref); err != nil { t.Fatalf("TerminalClose = %v", err) @@ -309,6 +326,25 @@ func TestLoginProfileOutputIsSkipped(t *testing.T) { } } +// A host that predates --with-sessions refuses the flag before it reads the +// path, having deleted nothing; the user is told to update it rather than +// shown the usage. Its own refusals pass through. +func TestDeleteGroupWithSessionsOnAnOlderHostSaysToUpdateIt(t *testing.T) { + for _, tc := range []struct{ stderr, want string }{ + {"agent-manager: flag provided but not defined: -with-sessions; usage: agent-manager delete-group [--json]\n", + "gpu: agent-manager there is too old to delete a group with its sessions; update agent-manager on that host"}, + {"agent-manager: sessions in web changed since confirmation; review them and try again\n", + "gpu: sessions in web changed since confirmation; review them and try again"}, + } { + c := newTestClient(t, func(context.Context, []string) ([]byte, []byte, error) { + return nil, []byte(tc.stderr), exitStatus(1) + }) + if _, err := c.DeleteGroupWithSessions(context.Background(), "gpu", "web", []string{"s1"}); err == nil || err.Error() != tc.want { + t.Fatalf("answer %q = %v, want %q", tc.stderr, err, tc.want) + } + } +} + // A command an older agent-manager does not know falls through to its // interactive manager, which fails without a terminal after printing escape // sequences. diff --git a/internal/remote/sanitize.go b/internal/remote/sanitize.go index aefdb2999..306b90261 100644 --- a/internal/remote/sanitize.go +++ b/internal/remote/sanitize.go @@ -126,3 +126,18 @@ func cleanRemoval(removal sessioncmd.GroupRemoval) sessioncmd.GroupRemoval { removal.Moved = moved return removal } + +func cleanDeletion(deletion sessioncmd.GroupDeletion) sessioncmd.GroupDeletion { + for i, path := range deletion.Removed { + deletion.Removed[i] = cleanText(path) + } + deleted := deletion.Deleted[:0] + for _, id := range deletion.Deleted { + if validID(id) == nil { + deleted = append(deleted, id) + } + } + deletion.Deleted = deleted + deletion.Notice = cleanText(deletion.Notice) + return deletion +} diff --git a/internal/sessioncmd/format.go b/internal/sessioncmd/format.go index ded35566e..ee16f9084 100644 --- a/internal/sessioncmd/format.go +++ b/internal/sessioncmd/format.go @@ -235,6 +235,16 @@ func FormatGroupRemoval(removal GroupRemoval) string { return line } +// FormatGroupDeletion names the groups a delete with their sessions removed +// and how many sessions went with them. +func FormatGroupDeletion(deletion GroupDeletion) string { + line := fmt.Sprintf("deleted %s and the %d session(s) in them", strings.Join(deletion.Removed, ", "), len(deletion.Deleted)) + if deletion.Notice != "" { + line += "\n" + deletion.Notice + } + return line +} + func FormatGroupList(groups []Group) string { if len(groups) == 0 { return "no groups; sessions live in the root" diff --git a/internal/sessioncmd/group.go b/internal/sessioncmd/group.go index 4dfb17ee5..f00ae6909 100644 --- a/internal/sessioncmd/group.go +++ b/internal/sessioncmd/group.go @@ -3,8 +3,10 @@ package sessioncmd import ( "errors" "fmt" + "slices" "strings" + "github.com/YoanWai/agent-manager/internal/git" "github.com/YoanWai/agent-manager/internal/store" ) @@ -146,6 +148,72 @@ func (s *Sessions) DeleteGroup(sessionID, path string) (GroupRemoval, error) { return GroupRemoval{Removed: removed, Moved: moved}, nil } +// GroupDeletion is what deleting a group with its sessions did: the groups +// removed and the ids of the sessions that went with them. +type GroupDeletion struct { + Removed []string `json:"removed"` + Deleted []string `json:"deleted"` + Notice string `json:"notice,omitempty"` +} + +// DeleteGroupWithSessions deletes a group, the groups nested under it and +// every session filed there, archived ones and terminals too, the way the +// delete key does. confirmed holds the ids the user was asked about; any +// other set there now refuses, as the key does when the list changed under +// its question. Only the user deletes what runs in a group, so a session +// may not. +func (s *Sessions) DeleteGroupWithSessions(sessionID, path string, confirmed []string) (GroupDeletion, error) { + if sessionID != "" { + return GroupDeletion{}, fmt.Errorf("deleting a group with its sessions is for the user; from session %s, delete-group without --with-sessions moves them to the root", sessionID) + } + path = strings.Trim(strings.TrimSpace(path), "/") + if path == "" { + return GroupDeletion{}, errors.New("group path is empty; the root group cannot be deleted") + } + runtime, err := s.open() + if err != nil { + return GroupDeletion{}, err + } + defer runtime.Close() + groups, err := runtime.store.Groups() + if err != nil { + return GroupDeletion{}, err + } + if !slices.ContainsFunc(groups, func(group store.Group) bool { return group.Name == path }) { + return GroupDeletion{}, fmt.Errorf("group %q does not exist; call %s for current paths", path, runtime.words.ListGroups) + } + selection, err := runtime.store.SessionsInSubtree(path) + if err != nil { + return GroupDeletion{}, err + } + expected := make([]store.Session, len(confirmed)) + for i, id := range confirmed { + expected[i].ID = id + } + if !SameSessionIDs(selection, expected) { + return GroupDeletion{}, fmt.Errorf("sessions in %s changed since confirmation; review them and try again", path) + } + var gitDriver *git.Driver + if slices.ContainsFunc(selection, func(sess store.Session) bool { return sess.WorktreeRepo != "" }) { + if gitDriver, err = s.newGit(); err != nil { + return GroupDeletion{}, fmt.Errorf("cannot clean up the worktrees in %s: %w", path, err) + } + } + lifecycle, err := s.lifecycle(runtime, gitDriver) + if err != nil { + return GroupDeletion{}, err + } + result, err := lifecycle.DeleteForHuman(DeleteSelection{Sessions: selection, GroupPath: path}) + if err != nil { + return GroupDeletion{}, err + } + deleted := make([]string, len(result.Deleted)) + for i, sess := range result.Deleted { + deleted[i] = sess.ID + } + return GroupDeletion{Removed: result.RemovedGroups, Deleted: deleted, Notice: result.Notice}, nil +} + // Move files an agent session under another existing group, the way the // manager's move key does; its nested terminals go with it. An empty group // is the root. diff --git a/internal/sessioncmd/group_test.go b/internal/sessioncmd/group_test.go index 853fdfe7d..684d3e8b6 100644 --- a/internal/sessioncmd/group_test.go +++ b/internal/sessioncmd/group_test.go @@ -1,7 +1,10 @@ package sessioncmd import ( + "os" "os/exec" + "path/filepath" + "slices" "strings" "testing" @@ -303,3 +306,159 @@ func statusLeft(t *testing.T, h *sessionHarness, id string) string { } return strings.TrimSpace(string(out)) } + +// The user's delete key over SSH takes the group with what runs in it: +// subgroups, agents, the terminals under them and archived rows, and a clean +// worktree with its branch; a worktree with unsaved work stays and the +// notice says so. Rows filed elsewhere stay. +func TestDeleteGroupWithSessionsTakesTheSubtreeTheWayTheDeleteKeyDoes(t *testing.T) { + h := newSessionHarness(t) + for _, path := range []string{"fleet", "fleet/backend"} { + if _, err := h.sessions.CreateGroup("", path, ""); err != nil { + t.Fatalf("CreateGroup %s: %v", path, err) + } + } + fleet, nested := "fleet", "fleet/backend" + repo := newGitRepo(t) + wanted := true + clean, err := h.sessions.Create(h.caller.ID, CreateSessionOptions{Name: "clean-worker", Group: &fleet, Directory: repo, Worktree: &wanted}) + if err != nil { + t.Fatalf("Create clean-worker: %v", err) + } + busy, err := h.sessions.Create(h.caller.ID, CreateSessionOptions{Name: "busy-worker", Group: &nested, Directory: repo, Worktree: &wanted}) + if err != nil { + t.Fatalf("Create busy-worker: %v", err) + } + if err := os.WriteFile(filepath.Join(busy.Directory, "work.txt"), []byte("draft"), 0o644); err != nil { + t.Fatal(err) + } + worker, err := h.sessions.Create(h.caller.ID, CreateSessionOptions{Name: "nested-worker", Group: &nested}) + if err != nil { + t.Fatalf("Create nested-worker: %v", err) + } + terminal, err := h.terminals.Create(worker.ID, CreateTerminalOptions{}) + if err != nil { + t.Fatalf("terminal Create: %v", err) + } + shelved, err := h.sessions.Create(h.caller.ID, CreateSessionOptions{Name: "shelved", Group: &fleet}) + if err != nil { + t.Fatalf("Create shelved: %v", err) + } + if _, err := h.sessions.Archive("", shelved.ID, true); err != nil { + t.Fatalf("Archive: %v", err) + } + + confirmed := []string{shelved.ID, terminal.ID, clean.ID, busy.ID, worker.ID} + deletion, err := h.sessions.DeleteGroupWithSessions("", "fleet", confirmed) + if err != nil { + t.Fatalf("DeleteGroupWithSessions: %v", err) + } + if want := "worktree kept (has work): " + busy.Directory; !slices.Equal(deletion.Removed, []string{"fleet", "fleet/backend"}) || deletion.Notice != want { + t.Fatalf("deletion = %+v, want both groups and the notice %q", deletion, want) + } + if got := slices.Sorted(slices.Values(deletion.Deleted)); !slices.Equal(got, slices.Sorted(slices.Values(confirmed))) { + t.Fatalf("deleted %q, want the confirmed %q", deletion.Deleted, confirmed) + } + for _, id := range confirmed { + if _, err := h.store.Get(id); err == nil { + t.Fatalf("%s still has a row", id) + } + if h.driver.Exists(id) { + t.Fatalf("%s still has a pane", id) + } + } + if _, err := os.Stat(clean.Directory); !os.IsNotExist(err) { + t.Fatalf("clean worktree still on disk: %v", err) + } + branch := exec.Command("git", "rev-parse", "--verify", "--quiet", "refs/heads/"+clean.Branch) + branch.Dir = repo + if branch.Run() == nil { + t.Fatalf("branch %s should be deleted", clean.Branch) + } + if _, err := os.Stat(filepath.Join(busy.Directory, "work.txt")); err != nil { + t.Fatalf("the unsaved work must stay: %v", err) + } + if _, err := h.store.Get(h.caller.ID); err != nil || !h.driver.Exists(h.caller.ID) { + t.Fatalf("a session in another group went with it: %v", err) + } + groups, err := h.sessions.Groups("") + if err != nil { + t.Fatal(err) + } + for _, group := range groups { + if strings.HasPrefix(group.Path, "fleet") { + t.Fatalf("group %s survived", group.Path) + } + } +} + +// The ids are what the user saw in the question. A session that arrived, +// left, or was swapped for another since then refuses the whole delete, as +// the delete key does, and so does an id the host never had. +func TestDeleteGroupWithSessionsRefusesSessionsThatChanged(t *testing.T) { + h := newSessionHarness(t) + if _, err := h.sessions.CreateGroup("", "fleet", ""); err != nil { + t.Fatal(err) + } + fleet := "fleet" + gone, err := h.sessions.Create(h.caller.ID, CreateSessionOptions{Name: "gone-worker", Group: &fleet}) + if err != nil { + t.Fatal(err) + } + if _, err := h.sessions.Delete("", gone.ID); err != nil { + t.Fatal(err) + } + late, err := h.sessions.Create(h.caller.ID, CreateSessionOptions{Name: "late-worker", Group: &fleet}) + if err != nil { + t.Fatal(err) + } + for name, confirmed := range map[string][]string{ + "added": nil, + "removed": {late.ID, gone.ID}, + "swapped": {gone.ID}, + "unknown": {"deadbeef"}, + "malformed": {late.ID + "; rm -rf ~"}, + "empty": {""}, + "twice": {late.ID, late.ID}, + "wrong group": {h.caller.ID}, + } { + if _, err := h.sessions.DeleteGroupWithSessions("", "fleet", confirmed); err == nil || err.Error() != "sessions in fleet changed since confirmation; review them and try again" { + t.Fatalf("%s %q = %v, want the refusal", name, confirmed, err) + } + } + if _, err := h.store.Get(late.ID); err != nil || !h.driver.Exists(late.ID) { + t.Fatalf("a refused delete must keep the session running: %v", err) + } + if groups, err := h.sessions.Groups(""); err != nil || !slices.ContainsFunc(groups, func(group Group) bool { return group.Path == "fleet" }) { + t.Fatalf("a refused delete must keep the group: %+v, %v", groups, err) + } + if _, err := h.sessions.DeleteGroupWithSessions("", "nowhere", nil); err == nil || !strings.Contains(err.Error(), `group "nowhere" does not exist`) { + t.Fatalf("a missing group = %v", err) + } +} + +// An empty group the user confirmed as empty goes with nothing else. +func TestDeleteGroupWithSessionsDeletesAnEmptyGroup(t *testing.T) { + h := newSessionHarness(t) + if _, err := h.sessions.CreateGroup("", "idle", ""); err != nil { + t.Fatal(err) + } + deletion, err := h.sessions.DeleteGroupWithSessions("", "idle", nil) + if err != nil || !slices.Equal(deletion.Removed, []string{"idle"}) || len(deletion.Deleted) != 0 { + t.Fatalf("deletion = %+v, %v", deletion, err) + } + if _, err := h.store.Get(h.caller.ID); err != nil || !h.driver.Exists(h.caller.ID) { + t.Fatalf("a session outside the group went with it: %v", err) + } +} + +// An agent tidying up deletes the group alone; what runs in it is the user's. +func TestDeleteGroupWithSessionsRefusesACallingSession(t *testing.T) { + h := newSessionHarness(t) + if _, err := h.sessions.DeleteGroupWithSessions(h.caller.ID, "backend", []string{h.caller.ID}); err == nil || !strings.Contains(err.Error(), "delete-group without --with-sessions") { + t.Fatalf("a session deleting its own group with it = %v, want a refusal", err) + } + if _, err := h.store.Get(h.caller.ID); err != nil || !h.driver.Exists(h.caller.ID) { + t.Fatalf("a refused delete must keep the caller running: %v", err) + } +} diff --git a/internal/sessioncmd/lifecycle.go b/internal/sessioncmd/lifecycle.go index 4c952ffbf..6e435b425 100644 --- a/internal/sessioncmd/lifecycle.go +++ b/internal/sessioncmd/lifecycle.go @@ -626,6 +626,25 @@ func (l *Lifecycle) DeleteForHuman(selection DeleteSelection) (DeleteResult, err return result, err } +// SameSessionIDs reports whether two selections hold the same sessions, so an +// action refuses rows that changed after the user confirmed them. +func SameSessionIDs(left, right []store.Session) bool { + if len(left) != len(right) { + return false + } + ids := make(map[string]bool, len(left)) + for _, sess := range left { + ids[sess.ID] = true + } + for _, sess := range right { + if !ids[sess.ID] { + return false + } + delete(ids, sess.ID) + } + return len(ids) == 0 +} + func deleteChildrenFirst(sessions []store.Session) []store.Session { ordered := make([]store.Session, 0, len(sessions)) for _, sess := range sessions { diff --git a/internal/ui/connections/call.go b/internal/ui/connections/call.go index c716e6227..b6013a8b7 100644 --- a/internal/ui/connections/call.go +++ b/internal/ui/connections/call.go @@ -43,7 +43,6 @@ type Call struct { var Refusals = map[uirail.ActionKind]string{ uirail.RenameAction: "rename", uirail.MoveToGroup: "move", - uirail.Delete: "deleting a group", uirail.Restart: "restart", uirail.Fork: "fork", uirail.OpenReview: "review", diff --git a/internal/ui/connections/link/call.go b/internal/ui/connections/link/call.go index d8c99c6f6..bfb72bba5 100644 --- a/internal/ui/connections/link/call.go +++ b/internal/ui/connections/link/call.go @@ -21,6 +21,7 @@ const ( Restore CreateGroup Delete + DeleteGroup ) type Call struct { @@ -34,6 +35,9 @@ type Call struct { // GroupDir is the directory a new group on the host defaults to; Name // carries its path. GroupDir string + // Sessions holds the ids of the sessions a group delete confirmed it + // takes. + Sessions []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 +80,10 @@ 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 DeleteGroup: + var deleted sessioncmd.GroupDeletion + deleted, err = client.DeleteGroupWithSessions(ctx, call.Host, call.Name, call.Sessions) + result.Notice = deleted.Notice } return result, err } @@ -106,11 +114,15 @@ func (s *State) ApplyCall(root Root, call Call, result Result, err error) tea.Cm root.ReportDone("opened terminal " + result.Session.Name + on) case Kill, CloseTerminal: root.ReportDone("killed " + call.Name + on) - case Delete: + case Delete, DeleteGroup: + deleted := "deleted " + call.Name + on + if call.Op == DeleteGroup { + deleted = "deleted group " + call.Name + on + } if result.Notice != "" { - root.ReportErr("deleted " + call.Name + on + "; " + result.Notice) + root.ReportErr(deleted + "; " + result.Notice) } else { - root.ReportDone("deleted " + call.Name + on) + root.ReportDone(deleted) } case Revive: root.ReportDone("revived " + call.Name + on) diff --git a/internal/ui/connections/link/call_test.go b/internal/ui/connections/link/call_test.go index fb6ada6e6..bf4ee2ff3 100644 --- a/internal/ui/connections/link/call_test.go +++ b/internal/ui/connections/link/call_test.go @@ -32,6 +32,23 @@ func TestRunTurnsEachCallIntoItsHostCommand(t *testing.T) { } } +// The deleted group's row stays until the next refresh, so a worktree the +// host kept is reported with the delete it came from and the host it is on. +func TestAGroupDeleteSaysWhatItDidAndWhatStayed(t *testing.T) { + state := listedState(t, &ssh{}) + call := Call{Op: DeleteGroup, Host: "box", Name: "web", Sessions: []string{"s1", "t1"}} + root := &recorder{} + state.ApplyCall(root, call, Result{}, nil) + if want := []string{"deleted group web on box"}; !equal(root.done, want) || len(root.errs) != 0 { + t.Fatalf("done %q errors %q, want done %q", root.done, root.errs, want) + } + root = &recorder{} + state.ApplyCall(root, call, Result{Notice: "worktree kept (has work): /srv/wt/api"}, nil) + if want := []string{"deleted group web on box; worktree kept (has work): /srv/wt/api"}; !equal(root.errs, want) || len(root.done) != 0 { + t.Fatalf("done %q errors %q, want errors %q", root.done, root.errs, want) + } +} + func TestRunSpawnsAndOpensTerminals(t *testing.T) { fake := &ssh{} client := listedState(t, fake).Client diff --git a/internal/ui/connections/rows.go b/internal/ui/connections/rows.go index 49ceffeb1..2444b12fd 100644 --- a/internal/ui/connections/rows.go +++ b/internal/ui/connections/rows.go @@ -1,6 +1,12 @@ package connections -import remote "github.com/YoanWai/agent-manager/internal/remote/value" +import ( + "slices" + "strings" + + remote "github.com/YoanWai/agent-manager/internal/remote/value" + uirail "github.com/YoanWai/agent-manager/internal/ui/rail" +) // Kind is which of a connection's rows a target names. type Kind uint8 @@ -61,6 +67,25 @@ func (c *Connections) Row(target Target) (Row, bool) { return Row{}, false } +// Subtree is what deleting a group on a host takes, from its last snapshot: +// how many groups are nested under it, and the ids of every agent and +// terminal filed in it or them, archived ones included, as the host's +// delete-group selects them. +func (c *Connections) Subtree(host, path string) (subgroups int, sessions []string) { + state := c.hosts[host] + for _, group := range state.Groups { + if strings.HasPrefix(group.Path, path+"/") { + subgroups++ + } + } + for _, sess := range slices.Concat(state.Sessions, state.Terminals) { + if uirail.InGroupSubtree(sess.Group, path) { + sessions = append(sessions, sess.ID) + } + } + return subgroups, sessions +} + func (r Row) of(sess Session, terminal bool) Row { r.Ref = remote.Ref{Host: r.Host, ID: sess.ID} r.Name, r.Status, r.Group, r.Archived = sess.Name, sess.Status, sess.Group, sess.Archived diff --git a/internal/ui/connections/rows_test.go b/internal/ui/connections/rows_test.go index 4f5939553..4cff6c695 100644 --- a/internal/ui/connections/rows_test.go +++ b/internal/ui/connections/rows_test.go @@ -1,6 +1,7 @@ package connections import ( + "slices" "testing" remote "github.com/YoanWai/agent-manager/internal/remote/value" @@ -30,6 +31,29 @@ func TestRowFindsAgentsAndTerminals(t *testing.T) { } } +// A group delete on the host takes every row filed under the group or a +// group nested in it, archived ones and terminals too, so the question +// counts them all and the call names them, from the host's last snapshot. +func TestSubtreeCountsWhatAGroupDeleteTakes(t *testing.T) { + var c Connections + c.SetList([]remote.Connection{box}) + c.Refreshed("box", c.Gen(), Host{ + OK: true, + Groups: []Group{{Path: "web"}, {Path: "web/ui"}, {Path: "web/ui/kit"}, {Path: "webby"}, {Path: "ops"}}, + Sessions: []Session{ + {ID: "s1", Group: "web"}, {ID: "s2", Group: "web/ui/kit", Archived: true}, + {ID: "s3", Group: "webby"}, {ID: "s4", Group: "ops"}, + }, + Terminals: []Session{{ID: "t1", Group: "web/ui", ParentID: "s9"}, {ID: "t2", Group: "ops"}}, + }) + if subgroups, sessions := c.Subtree("box", "web"); subgroups != 2 || !slices.Equal(sessions, []string{"s1", "s2", "t1"}) { + t.Fatalf("web holds %d subgroups and sessions %q, want 2 and s1, s2, t1", subgroups, sessions) + } + if subgroups, sessions := c.Subtree("box", "ops"); subgroups != 0 || !slices.Equal(sessions, []string{"s4", "t2"}) { + t.Fatalf("ops holds %d subgroups and sessions %q, want 0 and s4, t2", subgroups, sessions) + } +} + func TestTroubleLabels(t *testing.T) { for trouble, want := range map[remote.Trouble]string{ remote.TroubleUnreachable: "unreachable", diff --git a/internal/ui/connections_adapter.go b/internal/ui/connections_adapter.go index 1320f9b72..41932c9c8 100644 --- a/internal/ui/connections_adapter.go +++ b/internal/ui/connections_adapter.go @@ -62,6 +62,9 @@ func (m *Model) connectionIntent(intent uirail.Intent) (tea.Cmd, bool) { group := row.Group return m.queueRemote(newTerminalCall(row.Host, group)), true } + if row.Kind == uiconnections.GroupRow && intent.Kind == uirail.Delete { + return m.confirmRemoteGroupDelete(row), true + } if row.Kind == uiconnections.SessionRow { call := uiconnections.SessionCall(row, intent.Kind, m.listKeyHint) if cmd, ok := m.remoteSessionIntent(row, call); ok { @@ -126,6 +129,30 @@ func (m *Model) confirmRemote(request uilink.Call, call uiconnections.Call, term return nil } +// confirmRemoteGroupDelete asks before a group goes on its host with every +// session in it, counted from the snapshot the question shows; their ids go +// with the call, so the host refuses if that snapshot was stale. The +// archived view deletes only a group's archived rows, which the host has no +// call for. +func (m *Model) confirmRemoteGroupDelete(row uiconnections.Row) tea.Cmd { + if m.rail.ShowArchived() { + m.reportErr(uirail.RemoteRefusal("deleting a group from the archive")) + return nil + } + if refusal, offline := m.ssh.Offline(row.Host); offline { + m.reportErr(refusal) + return nil + } + subgroups, sessions := m.ssh.Subtree(row.Host, row.Group) + request := uilink.Call{Op: uilink.DeleteGroup, Host: row.Host, Name: row.Group, Sessions: sessions} + m.openConfirm(confirmTarget{ + prompt: uidialogs.Confirm{Action: uidialogs.ConfirmDelete, Group: true, + Label: uisession.GroupDeleteLabel(presentation.EscapeControlsInline(row.Group+" on "+row.Host), subgroups, len(sessions), "kills their tmux sessions there.")}, + remote: &request, + }) + return nil +} + // 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 64c287bef..4d3d28781 100644 --- a/internal/ui/connections_adapter_test.go +++ b/internal/ui/connections_adapter_test.go @@ -143,10 +143,6 @@ func TestUnsupportedRemoteActionsAreRefusedWithoutIO(t *testing.T) { t.Fatalf("kill on %+v: status %q", target, m.errBar.text) } } - m.clearErr() - 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) - } if calls := fake.taken(); len(calls) != 0 { t.Fatalf("calls = %q, want none", calls) } @@ -178,6 +174,10 @@ func TestOfflineHostRefusesCallsWithItsError(t *testing.T) { if m.errBar.text != "box: unreachable over SSH: connection refused" { t.Fatalf("status = %q", m.errBar.text) } + m.clearErr() + if _, cmd := m.runRailIntent(uirail.Intent{Kind: uirail.Delete, Target: boxGroup}); cmd != nil || confirmOpen(m) || m.errBar.text != "box: unreachable over SSH: connection refused" { + t.Fatalf("group delete on an offline host: confirm %v, status %q", confirmOpen(m), m.errBar.text) + } } func TestRemoteAttachBuildsTheSSHCommandOffTheUpdatePath(t *testing.T) { @@ -379,6 +379,44 @@ func TestRemoteDeleteConfirmCountsTheTerminalsItTakes(t *testing.T) { } } +// d on a remote group asks with that host's counts, worded like the local +// group delete, and the yes sends the ids of the sessions it counted, so the +// host refuses when its sessions changed since. +func TestRemoteGroupDeleteAsksWithTheHostsCountsAndSendsThem(t *testing.T) { + fake := &fakeSSH{} + m := listedModel(t, fake) + fake.snapshot.Groups = append(fake.snapshot.Groups, sessioncmd.Group{Path: "web/ui"}) + fake.snapshot.Sessions = append(fake.snapshot.Sessions, sessioncmd.Session{ID: "s4", Name: "ui", Tool: "claude", Group: "web/ui", Status: "idle", Running: true}) + setHost(m, "box", uilink.Facts(remote.HostState{OK: true, Snapshot: fake.snapshot})) + m.rail.Focus(boxGroup) + _, cmd := m.runRailIntent(uirail.Intent{Kind: uirail.Delete, Target: boxGroup}) + prompt := pendingConfirm(m).prompt + if want := "delete group web on box (1 subgroups, 5 sessions incl. archived)? kills their tmux sessions there."; !confirmOpen(m) || prompt.Label != want || !prompt.Group || prompt.Action != uidialogs.ConfirmDelete { + t.Fatalf("confirm %v = %+v, want %q", confirmOpen(m), prompt, want) + } + m.runRemoteCmd(t, m.answerRemote(t, fake, cmd, "y")) + if want := []string{"delete-group", "--json", "--with-sessions=s1,s2,s3,s4,t1", "--", "web"}; len(fake.taken()) != 1 || !slices.Equal(fake.taken()[0], want) { + t.Fatalf("calls = %q, want one %q", fake.taken(), want) + } + if m.errBar.text != "deleted group web on box" { + t.Fatalf("status = %q", m.errBar.text) + } +} + +// The archived view's d deletes only the archived rows under a group, which +// the host has no call for, so it refuses rather than delete the live ones. +func TestRemoteGroupDeleteInTheArchivedViewIsRefused(t *testing.T) { + fake := &fakeSSH{} + m := connectedModel(t, fake) + m.rail.SetArchived(true) + if _, cmd := m.runRailIntent(uirail.Intent{Kind: uirail.Delete, Target: boxGroup}); cmd != nil || confirmOpen(m) || m.errBar.text != "deleting a group from the archive isn't available on SSH connections yet" { + t.Fatalf("confirm %v, status %q", confirmOpen(m), m.errBar.text) + } + if calls := fake.taken(); len(calls) != 0 { + t.Fatalf("calls = %q, want none", calls) + } +} + func TestQuickBarRefusesWhenARefreshDropsItsRemoteTarget(t *testing.T) { fake := &fakeSSH{} m := connectedModel(t, fake) diff --git a/internal/ui/help/catalog.go b/internal/ui/help/catalog.go index fa1c90da7..f383db13f 100644 --- a/internal/ui/help/catalog.go +++ b/internal/ui/help/catalog.go @@ -136,6 +136,7 @@ func connectionRowHelpRows(list keybind.Table, mode presentation.GlyphMode) [][2 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.fixed("", "its agents: attach, prompt, kill, revive, archive, restore, delete") + h.fixed("", "its groups: delete there, with their subgroups and sessions") h.fixed("", "attach opens an SSH attach in this terminal") return h.rows } diff --git a/internal/ui/rail/hosts_test.go b/internal/ui/rail/hosts_test.go index 798158fd6..c643777b8 100644 --- a/internal/ui/rail/hosts_test.go +++ b/internal/ui/rail/hosts_test.go @@ -248,6 +248,9 @@ func TestConnectionMenusOfferOnlyRemoteActions(t *testing.T) { if got := labels(Selection{Kind: GroupRow}); !slices.Contains(got, "New connection") { t.Errorf("root menu = %v, want New connection", got) } + if got := labels(Selection{Kind: GroupRow, Group: "ops", Host: "box"}); !slices.Contains(got, "Delete") { + t.Errorf("remote group menu = %v, want Delete", 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) @@ -257,6 +260,12 @@ func TestConnectionMenusOfferOnlyRemoteActions(t *testing.T) { 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) } + // The archived view deletes only a group's archived rows, which the + // host has no call for. + model.Reconcile(Snapshot{Hosts: []Host{{Name: "box", State: HostOnline, Groups: []string{"ops"}, Sessions: []Session{{ID: "old", Name: "old", Tool: "claude", Group: "ops", Status: "dead", Archived: true}}}}}) + if got := labels(Selection{Kind: GroupRow, Group: "ops", Host: "box"}); len(got) == 0 || slices.Contains(got, "Delete") { + t.Errorf("archived remote group menu = %v, want one without Delete", got) + } } func TestHostFoldsFollowTheirConnection(t *testing.T) { diff --git a/internal/ui/rail/legend.go b/internal/ui/rail/legend.go index 9c98fcda7..b81dce1eb 100644 --- a/internal/ui/rail/legend.go +++ b/internal/ui/rail/legend.go @@ -281,9 +281,11 @@ func (m Model) RemoteLegend(ctx LegendContext, row RemoteRow, collapsed bool) Le {k(keybind.Open), fold}, {k(keybind.Terminal), "terminal"}, {k(keybind.NewGroup), "group"}, {k(keybind.Rename), "edit"}, {k(keybind.Delete), "remove"}, })} case GroupRow: - return Legend{Title: "Group", Leads: leads, Pairs: boundPairs([][2]string{ - {k(keybind.Open), fold}, {k(keybind.Terminal), "terminal"}, {k(keybind.NewGroup), "group"}, - })} + pairs := [][2]string{{k(keybind.Open), fold}, {k(keybind.Terminal), "terminal"}, {k(keybind.NewGroup), "group"}} + if !m.showArchived { + pairs = append(pairs, [2]string{k(keybind.Delete), "delete"}) + } + return Legend{Title: "Group", Leads: leads, Pairs: boundPairs(pairs)} } title, kill := "Session", "kill" if row.Terminal { diff --git a/internal/ui/rail/legend_test.go b/internal/ui/rail/legend_test.go index 305a97c4c..b3a39f09e 100644 --- a/internal/ui/rail/legend_test.go +++ b/internal/ui/rail/legend_test.go @@ -84,3 +84,17 @@ func TestRemoteLegendOffersDeleteOnAnAgentOnly(t *testing.T) { t.Fatalf("a remote shell should leave delete to close, got %+v", shell.Pairs) } } + +// d on a remote group deletes it there in the active view only; the +// archived view's delete has no host call. +func TestRemoteGroupLegendOffersDeleteOutsideTheArchive(t *testing.T) { + model := rail.New(nil) + ctx := rail.LegendContext{ListKeys: keybind.DefaultList()} + group := rail.RemoteRow{Kind: rail.GroupRow, Host: "box"} + if legend := model.RemoteLegendInView(ctx, group, false, false); !slices.Contains(legend.Pairs, [2]string{"d", "delete"}) { + t.Fatalf("a remote group should offer delete, got %+v", legend.Pairs) + } + if legend := model.RemoteLegendInView(ctx, group, false, true); slices.ContainsFunc(legend.Pairs, func(pair [2]string) bool { return pair[1] == "delete" }) { + t.Fatalf("a remote group in the archived view should not offer delete, got %+v", legend.Pairs) + } +} diff --git a/internal/ui/rail/menu.go b/internal/ui/rail/menu.go index f607d04b6..0c4f923f8 100644 --- a/internal/ui/rail/menu.go +++ b/internal/ui/rail/menu.go @@ -61,7 +61,7 @@ func (m Model) rowMenuItems(row treeRow) []menuItem { if m.showArchived { create = []menuItem{{label: "New session", action: NewSession}} } - return remoteMenuItems(row, create, connection) + return remoteMenuItems(row, create, connection, m.showArchived) } if m.showArchived { return menuSections(manage, []menuItem{{label: "Restore", action: Restore}, remove}) @@ -104,7 +104,7 @@ func (m Model) rowMenuItems(row treeRow) []menuItem { // remoteMenuItems offers on a connection's rows only what reaches the // remote host's CLI. -func remoteMenuItems(row treeRow, create []menuItem, connection menuItem) []menuItem { +func remoteMenuItems(row treeRow, create []menuItem, connection menuItem, archived bool) []menuItem { group := menuItem{label: "New group", action: NewGroup} switch row.kind { case ConnectionRow: @@ -112,7 +112,10 @@ func remoteMenuItems(row treeRow, create []menuItem, connection menuItem) []menu []menuItem{{label: "Edit connection", action: RenameAction}, connection}, []menuItem{{label: "Remove connection", action: Delete, danger: true}}) case GroupRow: - return append(create, group) + if archived { + return append(create, group) + } + return menuSections(append(create, group), []menuItem{{label: "Delete", action: Delete, danger: true}}) } remove := menuItem{label: "Delete", action: Delete, danger: true} if row.sess.Archived { diff --git a/internal/ui/session/dialogs/dialogs.go b/internal/ui/session/dialogs/dialogs.go index 2b26b8b80..17b83cec7 100644 --- a/internal/ui/session/dialogs/dialogs.go +++ b/internal/ui/session/dialogs/dialogs.go @@ -394,8 +394,7 @@ func wholeGroupDelete(groups []string, path string, subtree []store.Session) Car } return Card{ Group: true, - Label: fmt.Sprintf("delete group %s (%d subgroups, %d sessions incl. archived)? kills their tmux sessions.", - path, subgroups, len(subtree)), + Label: uisession.GroupDeleteLabel(path, subgroups, len(subtree), "kills their tmux sessions."), Target: uilifecycle.Target{ Action: uilifecycle.Remove, Path: path, diff --git a/internal/ui/session/dialogs/dialogs_test.go b/internal/ui/session/dialogs/dialogs_test.go index 7b571492c..5844781f5 100644 --- a/internal/ui/session/dialogs/dialogs_test.go +++ b/internal/ui/session/dialogs/dialogs_test.go @@ -114,8 +114,8 @@ func TestDeleteOfAGroupCountsItsSubgroupsAndRows(t *testing.T) { if len(intent.Card.Sessions) != 2 { t.Fatalf("group delete covers %d rows, want the subtree only", len(intent.Card.Sessions)) } - if !strings.Contains(intent.Card.Label, "1 subgroups, 2 sessions") { - t.Fatalf("label = %q", intent.Card.Label) + if want := "delete group work (1 subgroups, 2 sessions incl. archived)? kills their tmux sessions."; intent.Card.Label != want { + t.Fatalf("label = %q, want %q", intent.Card.Label, want) } } diff --git a/internal/ui/session/lifecycle/run.go b/internal/ui/session/lifecycle/run.go index 9d98a5d9c..40a1defbc 100644 --- a/internal/ui/session/lifecycle/run.go +++ b/internal/ui/session/lifecycle/run.go @@ -246,7 +246,7 @@ func validateSelection(st *store.Store, target Target) (Target, error) { if selection.Members != nil { expected = selection.Members } - if !sameSessionIDs(current, expected) { + if !sessioncmd.SameSessionIDs(current, expected) { return target, errors.New("sessions changed since confirmation; review the selection and try again") } if selection.Members != nil { @@ -277,23 +277,6 @@ func ActiveSessions(sessions []store.Session) []store.Session { return active } -func sameSessionIDs(left, right []store.Session) bool { - if len(left) != len(right) { - return false - } - ids := make(map[string]bool, len(left)) - for _, sess := range left { - ids[sess.ID] = true - } - for _, sess := range right { - if !ids[sess.ID] { - return false - } - delete(ids, sess.ID) - } - return len(ids) == 0 -} - func archivedSessions(sessions []store.Session) []store.Session { var archived []store.Session for _, sess := range sessions { diff --git a/internal/ui/session/text.go b/internal/ui/session/text.go index 621be31be..2b5b54c87 100644 --- a/internal/ui/session/text.go +++ b/internal/ui/session/text.go @@ -56,6 +56,13 @@ func DegradedResumeText(name string) string { return fmt.Sprintf("revived %s with --continue: no conversation id captured, may resume the wrong conversation", name) } +// GroupDeleteLabel asks to delete a group with everything under it, named by +// subject, counting the subgroups and every session that goes, archived ones +// included. +func GroupDeleteLabel(subject string, subgroups, sessions int, consequence string) string { + return fmt.Sprintf("delete group %s (%d subgroups, %d sessions incl. archived)? %s", subject, subgroups, sessions, consequence) +} + // FollowConfirmLabel asks to archive, restore, kill or delete one session and // its live children, naming how many terminals go with it. func FollowConfirmLabel(verb, name string, extra int, one, many string) string { diff --git a/tools/e2e/README.md b/tools/e2e/README.md index 3b124cb79..049d79981 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, 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 deletes that group with its agents, refused once because an agent arrived while the confirm was open and once because one was swapped for another, then for real, and checks the host kept or lost them. 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 879ec3980..126bbef59 100644 --- a/tools/e2e/ssh_scenarios.py +++ b/tools/e2e/ssh_scenarios.py @@ -6,7 +6,7 @@ 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 +delete, attach, quick spawn, a new terminal, and deleting a group with its agent. A second connection whose host refuses shows as unreachable and is removed. Every process it started is ended by PID. """ import argparse @@ -35,6 +35,9 @@ REMOTE_GROUP = 'web' GROUPED_AGENT = 'api' REMOTE_NEW_GROUP = 'ops' +GROUP_AGENT = 'ops-agent' +LATE_AGENT = 'ops-late' +SWAP_AGENT = 'ops-swap' QUICK_TEXT = 'ssh-quick-input' SPAWN_TEXT = 'ssh-spawn-prompt' @@ -313,6 +316,57 @@ def spawn_and_terminal(sandbox, remote): frame(sandbox, 'remote-group-row', REMOTE_NEW_GROUP) +def delete_group(sandbox, remote, manager): + """d on a remote group deletes it on the host with the agents filed in it, as d does here. + + The confirm counts the sessions from the last snapshot and the host checks + their ids, so an agent started there while the question is open, or one + swapped for another, refuses the delete and nothing goes. + """ + def spawn(name): + remote.run(sandbox, [str(manager), 'spawn', '--json', '--name=' + name, '--tool=' + FAKE_CLI, + '--directory=' + str(remote.home / 'work'), '--group=' + REMOTE_NEW_GROUP]) + return remote.query(f"SELECT id FROM sessions WHERE name = '{name}'")[0][0] + + def left(): + return str(remote.query(f"SELECT name FROM groups WHERE name = '{REMOTE_NEW_GROUP}' UNION ALL " + f"SELECT name FROM sessions WHERE group_name = '{REMOTE_NEW_GROUP}' ORDER BY 1")) + + agents = [spawn(GROUP_AGENT)] + frame(sandbox, 'group-agent-row', GROUP_AGENT) + select(sandbox, 'remote-new-group', f'{REMOTE_NEW_GROUP} on {CONNECTION}') + key(sandbox, 'd') + frame(sandbox, 'remote-group-delete-stale-confirm', f'delete group {REMOTE_NEW_GROUP} on {CONNECTION} (0 subgroups, 1 sessions') + agents.append(spawn(LATE_AGENT)) + key(sandbox, 'y') + frame(sandbox, 'remote-group-delete-refused', 'changed since') + if left() != str(sorted([(REMOTE_NEW_GROUP,), (GROUP_AGENT,), (LATE_AGENT,)])): + raise AssertionError(f'a refused group delete changed the host: {left()}') + + frame(sandbox, 'late-agent-row', LATE_AGENT) + select(sandbox, 'remote-new-group-again', f'{REMOTE_NEW_GROUP} on {CONNECTION}') + key(sandbox, 'd') + frame(sandbox, 'remote-group-delete-swap-confirm', f'delete group {REMOTE_NEW_GROUP} on {CONNECTION} (0 subgroups, 2 sessions') + remote.run(sandbox, [str(manager), 'delete', '--json', '--', agents[0]]) + agents.append(spawn(SWAP_AGENT)) + key(sandbox, 'y') + # The first refusal's line stays until the yes clears it; only a frame + # without the question can hold the second one. + frame(sandbox, 'remote-group-delete-swap-refused', 'changed since', '(0 subgroups, 2 sessions') + if left() != str(sorted([(REMOTE_NEW_GROUP,), (LATE_AGENT,), (SWAP_AGENT,)])): + raise AssertionError(f'a swap under the question changed the host: {left()}') + + frame(sandbox, 'swap-agent-row', SWAP_AGENT) + select(sandbox, 'remote-new-group-last', f'{REMOTE_NEW_GROUP} on {CONNECTION}') + key(sandbox, 'd') + confirm(sandbox, 'remote-group-delete', f'delete group {REMOTE_NEW_GROUP} on {CONNECTION} (0 subgroups, 2 sessions', + f'deleted group {REMOTE_NEW_GROUP} on {CONNECTION}') + sandbox.wait('remote-group-deleted', left, lambda value: value == '[]') + for agent_id in agents: + sandbox.wait('group-agent-pane-gone-' + agent_id, lambda: remote_pane_code(sandbox, remote, agent_id), + lambda code: code != '0') + + def offline_connection(sandbox): """A host ssh cannot reach says unreachable with ssh's error, refuses actions, and comes out.""" add_connection(sandbox, DOWN) @@ -366,6 +420,7 @@ def scenario(sandbox, remote, binary): lifecycle(sandbox, remote, agent_id) attach(sandbox, remote, agent_id) spawn_and_terminal(sandbox, remote) + delete_group(sandbox, remote, manager) offline_connection(sandbox) local = sqlite3.connect(str(profile_dir(sandbox) / 'state.db'), timeout=5) try: