diff --git a/docs/ssh-connections.md b/docs/ssh-connections.md index 66a632e0..c8354b32 100644 --- a/docs/ssh-connections.md +++ b/docs/ssh-connections.md @@ -26,8 +26,8 @@ The protocol is the remote host's own CLI, run over SSH as `agent-manager --json -- ` | | Answer an agent from the quick bar | `type --json -- ` | | Spawn | `spawn --json ...`, `terminal create --json ...` | -| Lifecycle | `kill`, `delete`, `revive`, `archive [--restore]`, `move`, `terminal close` | -| Groups | `create-group`, `delete-group` | +| Lifecycle | `kill`, `delete`, `revive`, `archive [--restore]`, `move`, `rename-session`, `terminal close` | +| Groups | `create-group`, `delete-group`, `rename-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,12 +38,13 @@ 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. +- `rename-session` and `rename-group` rename a row the way the user's rename key does, and are refused from inside a session, which names itself with `rename` through its manager. They write the host's store directly, as `kill` and `move` do. - `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. - `type` submits the user's quick bar prompt in an agent's pane at once, as the local quick bar does. It is refused from inside a session. It carries no envelope and no rate limit, so it sits outside the guardrail the other commands keep: anything that escapes caller detection can type into any agent as the user. Each pane's send holds a lock file beside the tmux socket, so a typed prompt and the host manager's own delivery never interleave. When the host's paste started before the send failed, `type` exits with status 3; that, or a call cut off after agent-manager started there, means the prompt may sit in the pane, so the quick bar drops it rather than type it again, as it does on this machine. -Tasks, file reservations, rename and review still need a calling session. +Tasks, file reservations, `rename` and review still need a calling session. ### SSH invocation @@ -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. +- Move, deleting a group, 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..40deeafa 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -365,6 +365,8 @@ agent-manager spawn --tool claude --group "Sprint Manager" --worktree \ `type ""` submits a prompt in an agent's pane at once, as you, the way quick prompt mode does: no envelope, no queue, no wait for the agent to be at rest. It is how another machine's quick prompt mode answers an agent here over SSH, and it is refused from inside a session, which sends instead. +`rename-session ""` renames an agent or a terminal the way `r` does, its worktree branch included, and `rename-group ""` renames a group where it stands, its subgroups and sessions moving with it, the way the name on the Edit Group card does. They are how another machine's `r` reaches a row here over SSH. Both are refused from inside a session, which names itself once with `rename`. + `terminal create` takes `--name`, the way `spawn` does, so a shell opened for a long job reads for that job instead of the session it hangs under. `terminal create`, `send`, `read` and `close` run with no caller too. There a new terminal hangs under no session, in the group `--group` names or the root, and only terminals opened that way can be driven: a terminal nested under a session stays that session's, and one you opened in the manager or a session opened stays out of reach. The commands that run with no caller are a convenience for a manager reaching this machine over SSH and for scripts, not an isolation boundary. Anything running as your user can call them, and an agent that drops its session environment is treated as a caller with no session. What they keep is a guardrail: such a caller cannot drive a terminal it did not open, and every `send --from` counts against one shared set of message limits, whatever name it gives. `type` is outside that guardrail: it speaks as you, with no envelope and no limit, so a process that escapes caller detection can type into any agent as you. It waits for a send already reaching the same pane, from this or another process, so the two never submit as one prompt. @@ -439,9 +441,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`. +- `r` types a new name into an agent's, terminal's or group's row, and the other machine renames it the way `r` does here: an agent's worktree branch follows its name, and a group keeps its parent while its subgroups and sessions move with it. The Edit Group card's other fields, the default path, worktree, base and environment, stay as that machine has them. - 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. +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. ## Status diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 68a8bbf3..8799e2ba 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -150,6 +150,18 @@ func (f *fakeSessions) Move(sessionID, targetID, group string) (sessioncmd.Sessi return moved, f.failWith } +func (f *fakeSessions) RenameGroup(sessionID, path, name string) (sessioncmd.Group, error) { + f.callerID, f.groupPath, f.message = sessionID, path, name + return sessioncmd.Group{Path: "renamed"}, f.failWith +} + +func (f *fakeSessions) RenameSession(sessionID, targetID, name string) (sessioncmd.Session, error) { + f.callerID, f.targetID, f.message = sessionID, targetID, name + renamed := f.session + renamed.Name = name + return renamed, f.failWith +} + func (f *fakeSessions) EndAfterTurn(sessionID, action string) (sessioncmd.AfterTurn, error) { f.callerID, f.action = sessionID, action return sessioncmd.AfterTurn{Pending: action, ManagerAwake: true}, f.failWith @@ -568,8 +580,8 @@ func TestCommandsThatActAsNoSessionNeverResolveACaller(t *testing.T) { func TestCommandsAndHelpCoverEverySection(t *testing.T) { table := Commands("dev", sampleSpecs) registered := []string{ - "sessions", "snapshot", "spawn", "send", "type", "read", "wait", "message-status", "kill", "delete", "revive", "archive", "move", "archive-self", "kill-self", "prompts", "env", - "groups", "create-group", "delete-group", "task", "reserve", "release-files", "reservations", "terminal", + "sessions", "snapshot", "spawn", "send", "type", "read", "wait", "message-status", "kill", "delete", "revive", "archive", "move", "rename-session", "archive-self", "kill-self", "prompts", "env", + "groups", "create-group", "delete-group", "rename-group", "task", "reserve", "release-files", "reservations", "terminal", "rename", "review-repo", "review-base", "review-mode", "review-comment", "issue", "feature", "settings", "export", "import", "update", } for _, name := range registered { diff --git a/internal/cli/session.go b/internal/cli/session.go index d317d8e3..8c32a978 100644 --- a/internal/cli/session.go +++ b/internal/cli/session.go @@ -29,11 +29,13 @@ const ( usageRevive = "revive [--json]" usageArchive = "archive [--restore] [--json]" usageMove = "move [--json]" + usageRenameSession = `rename-session "" [--json]` usageArchiveSelf = "archive-self [--cancel] [--json]" usageKillSelf = "kill-self [--cancel] [--json]" usageGroups = "groups [--json]" usageCreateGroup = "create-group [--directory ] [--json]" usageDeleteGroup = "delete-group [--json]" + usageRenameGroup = `rename-group "" [--json]` ) type sessionCommands interface { @@ -53,11 +55,13 @@ type sessionCommands interface { Revive(sessionID, targetID string) (sessioncmd.Session, error) Archive(sessionID, targetID string, archived bool) (sessioncmd.Session, error) Move(sessionID, targetID, group string) (sessioncmd.Session, error) + RenameSession(sessionID, targetID, name string) (sessioncmd.Session, error) EndAfterTurn(sessionID, action string) (sessioncmd.AfterTurn, error) CancelAfterTurn(sessionID string) (sessioncmd.AfterTurn, error) Groups(sessionID string) ([]sessioncmd.Group, error) CreateGroup(sessionID, path, directory string) (sessioncmd.Group, error) DeleteGroup(sessionID, path string) (sessioncmd.GroupRemoval, error) + RenameGroup(sessionID, path, name string) (sessioncmd.Group, error) } func newSessions(configDir string) sessionCommands { @@ -113,11 +117,13 @@ func sessionSectionWith(open func(string) sessionCommands) section { {name: "revive", usage: usageRevive, about: "bring a dead session back on its old row, resuming the conversation it held; an agent that quit inside a live pane comes back there", run: bind(open, runRevive)}, {name: "archive", usage: usageArchive, about: "file a finished session out of the active list, or restore it with --restore", run: bind(open, runArchive)}, {name: "move", usage: usageMove, about: "file a session under another existing group, the way the move key does; an empty group is the root, and a host::id moves it on that SSH connection", run: bind(func(configDir string) moveLayer { return moveLayer{open(configDir), storedHosts(configDir)} }, runMove)}, + {name: "rename-session", usage: usageRenameSession, about: "rename an agent or a terminal the way the rename key does, its worktree branch included; only for a caller with no session here, such as a manager on another machine over SSH", run: bind(open, runRenameSession)}, {name: "archive-self", usage: usageArchiveSelf, about: "archive this session once the current turn ends, the way the archive key does; --cancel withdraws a pending archive or kill", run: bind(open, runArchiveSelf)}, {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: "rename-group", usage: usageRenameGroup, about: "rename a group where it stands, its subgroups and sessions moving with it, the way the edit card's name does; only for a caller with no session here", run: bind(open, runRenameGroup)}, }, } } @@ -407,6 +413,20 @@ func moveOnHost(layer moveLayer, ref remote.Ref, group, sessionID string) (sessi return moved, nil } +func runRenameSession(out io.Writer, sessions sessionCommands, args []string, sessionID string) error { + set := newFlagSet(usageRenameSession) + asJSON := jsonFlag(set) + operands, err := parseCommand(out, set, args, 2, 2) + if err != nil { + return err + } + renamed, err := sessions.RenameSession(sessionID, operands[0], operands[1]) + if err != nil { + return err + } + return emit(out, *asJSON, renamed, "renamed "+sessioncmd.FormatSession(renamed)) +} + func runArchiveSelf(out io.Writer, sessions sessionCommands, args []string, sessionID string) error { return runEndSelf(out, sessions, args, sessionID, usageArchiveSelf, store.AfterTurnArchive) } @@ -476,3 +496,17 @@ func runDeleteGroup(out io.Writer, sessions sessionCommands, args []string, sess } return emit(out, *asJSON, removal, sessioncmd.FormatGroupRemoval(removal)) } + +func runRenameGroup(out io.Writer, sessions sessionCommands, args []string, sessionID string) error { + set := newFlagSet(usageRenameGroup) + asJSON := jsonFlag(set) + operands, err := parseCommand(out, set, args, 2, 2) + if err != nil { + return err + } + renamed, err := sessions.RenameGroup(sessionID, operands[0], operands[1]) + if err != nil { + return err + } + return emit(out, *asJSON, renamed, "renamed group "+operands[0]+" to "+renamed.Path) +} diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go index b81c4374..a4bcc068 100644 --- a/internal/cli/session_test.go +++ b/internal/cli/session_test.go @@ -413,6 +413,44 @@ func TestTypeReachesTheLayerWithItsPrompt(t *testing.T) { } } +// The SSH client's form, like type's: the id and the name after a bare --, +// so a name that starts with a dash stays the name. +func TestRenameSessionReachesTheLayerWithItsName(t *testing.T) { + out := &bytes.Buffer{} + fake := &fakeSessions{session: sampleSession()} + if err := runRenameSession(out, fake, []string{"--json", "--", "beef1234", "-new name"}, ""); err != nil { + t.Fatalf("rename-session --json -- id name: %v", err) + } + if fake.callerID != "" || fake.targetID != "beef1234" || fake.message != "-new name" { + t.Fatalf("rename-session reached the layer as caller=%q target=%q name=%q", fake.callerID, fake.targetID, fake.message) + } + var renamed sessioncmd.Session + if err := json.Unmarshal(out.Bytes(), &renamed); err != nil || renamed.ID != "beef1234" { + t.Fatalf("rename-session --json = %q (%v)", out.String(), err) + } + if err := runRenameSession(&bytes.Buffer{}, &fakeSessions{}, []string{"beef1234"}, ""); err == nil || err.Error() != "usage: agent-manager "+usageRenameSession { + t.Fatalf("rename-session without a name = %v, want the usage", err) + } +} + +func TestRenameGroupReachesTheLayerWithItsName(t *testing.T) { + out := &bytes.Buffer{} + fake := &fakeSessions{} + if err := runRenameGroup(out, fake, []string{"--json", "--", "-team/a", "b c"}, ""); err != nil { + t.Fatalf("rename-group --json -- path name: %v", err) + } + if fake.callerID != "" || fake.groupPath != "-team/a" || fake.message != "b c" { + t.Fatalf("rename-group reached the layer as caller=%q path=%q name=%q", fake.callerID, fake.groupPath, fake.message) + } + var renamed sessioncmd.Group + if err := json.Unmarshal(out.Bytes(), &renamed); err != nil || renamed.Path != "renamed" { + t.Fatalf("rename-group --json = %q (%v)", out.String(), err) + } + if err := runRenameGroup(&bytes.Buffer{}, &fakeSessions{}, []string{"web"}, ""); err == nil || err.Error() != "usage: agent-manager "+usageRenameGroup { + t.Fatalf("rename-group without a name = %v, want the usage", err) + } +} + func TestSnapshotPrintsOnlyJSON(t *testing.T) { fake := &fakeSessions{session: sampleSession()} err := runSnapshot(&bytes.Buffer{}, fake, nil, "") diff --git a/internal/execution/poller_test.go b/internal/execution/poller_test.go index 0eaba99b..07064a09 100644 --- a/internal/execution/poller_test.go +++ b/internal/execution/poller_test.go @@ -149,6 +149,76 @@ func TestPendingRenameForADeletedSessionDoesNotFailThePoll(t *testing.T) { } } +// A group renamed by another writer after this pass listed the sessions, +// such as rename-group over SSH, is the group the renamed pane's label shows. +func TestPendingRenameLabelsThePaneWithTheGroupAsStoredNow(t *testing.T) { + m := buildModel(t) + createSession(t, m, "worker", t.TempDir(), "web") + sess := m.sessionRows()[0] + if err := m.store.RenameGroup("web", "api"); err != nil { + t.Fatalf("rename group: %v", err) + } + writeName(t, m, sess.ID, "renamed") + + if err := m.poller.applyPendingRename(&sess); err != nil { + t.Fatalf("rename: %v", err) + } + out, err := exec.Command(tmux.Binary, "-L", m.tmux.SocketName(), "show-options", "-v", "-t", "am_"+sess.ID, "status-left").CombinedOutput() + if err != nil { + t.Fatalf("status-left: %v: %s", err, out) + } + if got := strings.TrimSpace(string(out)); got != sessioncmd.SessionLabel("api", "renamed") { + t.Fatalf("status-left = %q, want the group as stored now", got) + } +} + +// A rename-session that landed after this pass listed the sessions moved +// the branch; the agent's own rename starts from the branch that one left. +func TestPendingRenameStartsFromTheBranchAsStoredNow(t *testing.T) { + m := buildModel(t) + spawned := createWorktreeSession(t, m, "first", seedRepo(t)) + if _, err := sessioncmd.ApplyName(m.gitDrv, m.store, spawned.ID, "second"); err != nil { + t.Fatalf("rename meanwhile: %v", err) + } + writeName(t, m, spawned.ID, "third") + + sess := spawned + if err := m.poller.applyPendingRename(&sess); err != nil { + t.Fatalf("rename: %v", err) + } + stored, err := m.store.Get(spawned.ID) + if err != nil || stored.Name != "third" || stored.WorktreeBranch != "am/third" || sess.WorktreeBranch != "am/third" { + t.Fatalf("stored %+v, pass copy branch %q (%v); want both on am/third", stored, sess.WorktreeBranch, err) + } + if head := gitOutput(t, spawned.Cwd, "rev-parse", "--abbrev-ref", "HEAD"); head != "am/third" { + t.Fatalf("HEAD = %q, want am/third", head) + } +} + +// The agent asking for the name this pass read, after a rename-session gave +// the row another, still gets that name: the verdict says what is stored. +func TestPendingRenameToTheNameThePassReadStillApplies(t *testing.T) { + m := buildModel(t) + spawned := createWorktreeSession(t, m, "first", seedRepo(t)) + if _, err := sessioncmd.ApplyName(m.gitDrv, m.store, spawned.ID, "second"); err != nil { + t.Fatalf("rename meanwhile: %v", err) + } + request := writeName(t, m, spawned.ID, "first") + + sess := spawned + if err := m.poller.applyPendingRename(&sess); err != nil { + t.Fatalf("rename: %v", err) + } + stored, err := m.store.Get(spawned.ID) + if err != nil || stored.Name != "first" || stored.WorktreeBranch != "am/first" { + t.Fatalf("stored %+v (%v), want first on am/first", stored, err) + } + verdict, found, err := m.hooks.ReadNameResult(spawned.ID, request) + if err != nil || !found || verdict.Refusal != nil || verdict.Applied != "first" { + t.Fatalf("result = %+v, %v, %v; want first applied", verdict, found, err) + } +} + func TestPendingRenameKeepsTheWorktreeDirectory(t *testing.T) { m := buildModel(t) repo := seedRepo(t) diff --git a/internal/execution/pollmailbox.go b/internal/execution/pollmailbox.go index e7bf9d46..55d02998 100644 --- a/internal/execution/pollmailbox.go +++ b/internal/execution/pollmailbox.go @@ -2,7 +2,6 @@ package execution import ( "errors" - "fmt" "github.com/YoanWai/agent-manager/internal/sessioncmd" @@ -10,16 +9,15 @@ import ( ) // applyPendingRename picks up a name the session's agent left via the -// rename subcommand: the store row and tmux label update together here, -// keeping the manager the sole database writer. The file is consumed -// even when the name is unchanged so it never lingers, and the outcome -// is left in the result mailbox for the subcommand still waiting on it. -// A dead tmux session cannot take a label, which is fine; the label is -// rewritten on revive. A worktree session's branch follows the new name -// while its live directory stays fixed, and a name git cannot give the -// branch keeps the session on the one it has: the file is consumed either -// way, so the reason is reported once rather than on every poll from -// here on. +// rename subcommand: the store row and tmux label update together here. +// The file is consumed even when the name is unchanged so it never +// lingers, and the outcome is left in the result mailbox for the +// subcommand still waiting on it. A dead tmux session cannot take a label, +// which is fine; the label is rewritten on revive. A worktree session's +// branch follows the new name while its live directory stays fixed, and a +// name git cannot give the branch keeps the session on the one it has: the +// file is consumed either way, so the reason is reported once rather than +// on every poll from here on. func (p *Runner) applyPendingRename(sess *store.Session) error { request, name, found, err := p.hooks.ClaimName(sess.ID) if err != nil || !found { @@ -50,17 +48,15 @@ func (p *Runner) applyPendingRename(sess *store.Session) error { } func (p *Runner) renamePending(sess *store.Session, name string) error { - if name == "" || name == sess.Name { + if name == "" { return nil } - if err := sessioncmd.RenameWorktreeBranch(p.gitDrv, p.store, sess, name); err != nil { - return fmt.Errorf("worktree rename: %w", err) - } - if err := p.store.RenameSession(sess.ID, name); err != nil { + renamed, err := sessioncmd.ApplyName(p.gitDrv, p.store, sess.ID, name) + if err != nil { return err } - sess.Name = name - _ = p.tmux.SetLabel(sess.ID, sessioncmd.SessionLabel(sess.Group, name)) + sess.Name, sess.WorktreeBranch = renamed.Name, renamed.WorktreeBranch + _ = sessioncmd.Relabel(p.tmux, p.store, sess.ID) return nil } diff --git a/internal/remote/operations.go b/internal/remote/operations.go index 0c202f69..0b98e080 100644 --- a/internal/remote/operations.go +++ b/internal/remote/operations.go @@ -257,6 +257,12 @@ func (c *Client) Move(ctx context.Context, ref Ref, group string) (sessioncmd.Se return c.lifecycle(ctx, ref, []string{"move", "--json"}, group) } +// Rename names an agent or a terminal on its host, its managed branch +// included. +func (c *Client) Rename(ctx context.Context, ref Ref, name string) (sessioncmd.Session, error) { + return c.lifecycle(ctx, ref, []string{"rename-session", "--json"}, name) +} + func (c *Client) lifecycle(ctx context.Context, ref Ref, args []string, operands ...string) (sessioncmd.Session, error) { var session sessioncmd.Session if err := validRef(ref); err != nil { @@ -285,6 +291,14 @@ func (c *Client) DeleteGroup(ctx context.Context, host, path string) (sessioncmd return cleanRemoval(removal), err } +// RenameGroup renames the group at path where it stands on host; its +// subgroups and sessions move with it. +func (c *Client) RenameGroup(ctx context.Context, host, path, name string) (sessioncmd.Group, error) { + var renamed sessioncmd.Group + err := c.decode(ctx, host, callTimeout, &renamed, "rename-group", "--json", "--", path, name) + return cleanGroup(renamed), 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 05813995..f3d9dc96 100644 --- a/internal/remote/operations_test.go +++ b/internal/remote/operations_test.go @@ -130,6 +130,14 @@ func TestOperationArgv(t *testing.T) { _, err := c.Move(ctx, ref, "-team/a b") return err }, []string{"move", "--json", "--", "a1b2c3d4", "-team/a b"}}, + {"rename", func(ctx context.Context, c *Client) error { + _, err := c.Rename(ctx, ref, "-new name") + return err + }, []string{"rename-session", "--json", "--", "a1b2c3d4", "-new name"}}, + {"rename group", func(ctx context.Context, c *Client) error { + _, err := c.RenameGroup(ctx, "gpu", "-team/a", "b c") + return err + }, []string{"rename-group", "--json", "--", "-team/a", "b c"}}, {"create group", func(ctx context.Context, c *Client) error { _, err := c.CreateGroup(ctx, "gpu", "-team/a", "/srv/team") return err @@ -181,6 +189,8 @@ func TestUnsafeIDsNeverReachSSH(t *testing.T) { errs = append(errs, err) _, err = c.Move(ctx, bad, "work") errs = append(errs, err) + _, err = c.Rename(ctx, bad, "work") + errs = append(errs, err) for i, err := range errs { if err == nil { t.Errorf("call %d accepted an unsafe id", i) @@ -326,6 +336,12 @@ 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.Rename(context.Background(), Ref{Host: "gpu", ID: "a1"}, "api"); err == nil || err.Error() != "gpu: agent-manager there is too old for SSH connections; update agent-manager on that host" { + t.Fatalf("rename on a host that predates it = %v", err) + } + if _, err := c.RenameGroup(context.Background(), "gpu", "web", "api"); err == nil || err.Error() != "gpu: agent-manager there is too old for SSH connections; update agent-manager on that host" { + t.Fatalf("rename-group 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/sessioncmd/group.go b/internal/sessioncmd/group.go index 4dfb17ee..99bd5d38 100644 --- a/internal/sessioncmd/group.go +++ b/internal/sessioncmd/group.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/YoanWai/agent-manager/internal/store" + "github.com/YoanWai/agent-manager/internal/tmux" ) type Group struct { @@ -204,19 +205,81 @@ func (s *Sessions) Move(sessionID, targetID, group string) (Session, error) { return runtime.sessionInfo(moved, runtime.driver.Exists(moved.ID), moved.ID == sessionID), nil } -// relabel skips a dead pane, which takes its label when it is revived. +// RenameGroup gives a group a new last path part where it stands; its +// subgroups and every session filed under them follow, as the edit card's +// name change does. +func (s *Sessions) RenameGroup(sessionID, path, name string) (Group, error) { + if err := refuseRenameCaller(sessionID); err != nil { + return Group{}, err + } + path = strings.Trim(strings.TrimSpace(path), "/") + name = strings.TrimSpace(name) + switch { + case name == "": + return Group{}, errors.New("group name cannot be empty") + case strings.Contains(name, "/"): + return Group{}, errors.New("group name cannot contain /; it names the group where it stands") + } + runtime, err := s.open() + if err != nil { + return Group{}, err + } + defer runtime.Close() + groups, err := runtime.store.Groups() + if err != nil { + return Group{}, err + } + var target *store.Group + for i := range groups { + if groups[i].Name == path { + target = &groups[i] + break + } + } + if target == nil { + return Group{}, fmt.Errorf("group %q does not exist; call %s for the existing ones", path, runtime.words.ListGroups) + } + renamed := name + if parent := parentGroup(path); parent != "" { + renamed = parent + "/" + name + } + if err := runtime.store.RenameGroup(path, renamed); err != nil { + return Group{}, err + } + moved, err := runtime.store.SessionsInSubtree(renamed) + if err != nil { + return Group{}, fmt.Errorf("renamed %s, but could not read its sessions to update their status bars: %w", path, err) + } + ids := make([]string, len(moved)) + for i, sess := range moved { + ids[i] = sess.ID + } + if err := runtime.relabel(ids); err != nil { + return Group{}, fmt.Errorf("renamed %s, but could not update its status bars: %w", path, err) + } + target.Name = renamed + return runtime.groupRows([]store.Group{*target}, moved)[0], nil +} + func (r *runtime) relabel(ids []string) error { + return Relabel(r.driver, r.store, ids...) +} + +// Relabel writes each live pane's label from its stored row, so a group or a +// name another writer changed meanwhile is the one shown; a dead pane takes +// its label when it is revived. +func Relabel(driver *tmux.Driver, st *store.Store, ids ...string) error { var failed error for _, id := range ids { - if !r.driver.Exists(id) { + if !driver.Exists(id) { continue } - sess, err := r.store.Get(id) + sess, err := st.Get(id) if err != nil { failed = errors.Join(failed, err) continue } - failed = errors.Join(failed, r.driver.SetLabel(id, SessionLabel(sess.Group, sess.Name))) + failed = errors.Join(failed, driver.SetLabel(id, SessionLabel(sess.Group, sess.Name))) } return failed } diff --git a/internal/sessioncmd/group_test.go b/internal/sessioncmd/group_test.go index 853fdfe7..ffc99cde 100644 --- a/internal/sessioncmd/group_test.go +++ b/internal/sessioncmd/group_test.go @@ -2,6 +2,7 @@ package sessioncmd import ( "os/exec" + "slices" "strings" "testing" @@ -303,3 +304,64 @@ func statusLeft(t *testing.T, h *sessionHarness, id string) string { } return strings.TrimSpace(string(out)) } + +// The user's rename key on another machine renames a group where it stands, +// and its subgroups and every session filed under it follow, as the local +// edit card's name change does. +func TestRenameGroupMovesItsSubtreeWithNoCaller(t *testing.T) { + h := newSessionHarness(t) + for _, path := range []string{"fleet", "fleet/web", "fleet/web/jobs"} { + if _, err := h.sessions.CreateGroup("", path, ""); err != nil { + t.Fatalf("CreateGroup %s: %v", path, err) + } + } + group := "fleet/web/jobs" + worker, err := h.sessions.Create("", CreateSessionOptions{Name: "worker", Group: &group}) + if err != nil { + t.Fatalf("Create: %v", err) + } + renamed, err := h.sessions.RenameGroup("", "fleet/web", " gateway ") + if err != nil { + t.Fatalf("RenameGroup: %v", err) + } + if renamed.Path != "fleet/gateway" { + t.Fatalf("renamed = %+v", renamed) + } + groups, err := h.sessions.Groups("") + if err != nil { + t.Fatalf("Groups: %v", err) + } + var paths []string + for _, g := range groups { + paths = append(paths, g.Path) + } + if !slices.Contains(paths, "fleet/gateway/jobs") || slices.Contains(paths, "fleet/web") || slices.Contains(paths, "fleet/web/jobs") { + t.Fatalf("groups after the rename = %v", paths) + } + if stored, err := h.store.Get(worker.ID); err != nil || stored.Group != "fleet/gateway/jobs" { + t.Fatalf("worker after the rename = %+v (%v)", stored, err) + } + if got := statusLeft(t, h, worker.ID); !strings.Contains(got, "fleet/gateway/jobs") { + t.Fatalf("status-left = %q, want the new group", got) + } +} + +func TestRenameGroupRefusesACallerAndABadName(t *testing.T) { + h := newStoreSessionHarness(t) + for _, path := range []string{"fleet", "other"} { + if _, err := h.sessions.CreateGroup("", path, ""); err != nil { + t.Fatalf("CreateGroup %s: %v", path, err) + } + } + for _, tc := range []struct{ caller, path, name, want string }{ + {h.caller.ID, "fleet", "x", "agent-manager"}, + {"", "fleet", " ", "group name cannot be empty"}, + {"", "fleet", "a/b", "group name cannot contain /"}, + {"", "nosuch", "x", `group "nosuch" does not exist`}, + {"", "fleet", "other", "group other already exists"}, + } { + if _, err := h.sessions.RenameGroup(tc.caller, tc.path, tc.name); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("RenameGroup(%q, %q, %q) = %v, want %q", tc.caller, tc.path, tc.name, err, tc.want) + } + } +} diff --git a/internal/sessioncmd/session_rename.go b/internal/sessioncmd/session_rename.go new file mode 100644 index 00000000..671988ad --- /dev/null +++ b/internal/sessioncmd/session_rename.go @@ -0,0 +1,58 @@ +package sessioncmd + +import ( + "database/sql" + "errors" + "fmt" + "strings" + + "github.com/YoanWai/agent-manager/internal/git" +) + +// refuseRenameCaller keeps renaming another row the user's: a session names +// itself once, on a placeholder, through the manager. +func refuseRenameCaller(sessionID string) error { + if sessionID == "" { + return nil + } + return fmt.Errorf("renaming is for the user's rename key on another machine; session %s names itself with agent-manager rename", sessionID) +} + +// RenameSession names an agent or a terminal the way the rename key does, +// its managed branch included. +func (s *Sessions) RenameSession(sessionID, targetID, name string) (Session, error) { + if err := refuseRenameCaller(sessionID); err != nil { + return Session{}, err + } + name = strings.TrimSpace(name) + if name == "" { + return Session{}, errors.New("name cannot be empty") + } + runtime, err := s.open() + if err != nil { + return Session{}, err + } + defer runtime.Close() + targetID = strings.TrimSpace(targetID) + target, err := runtime.store.Get(targetID) + if errors.Is(err, sql.ErrNoRows) { + return Session{}, fmt.Errorf("session %s does not exist; call %s for current ids", targetID, runtime.words.ListSessions) + } + if err != nil { + return Session{}, err + } + var gitDriver *git.Driver + if target.WorktreeRepo != "" { + if gitDriver, err = s.newGit(); err != nil { + return Session{}, fmt.Errorf("cannot rename %s's branch: %w", target.Name, err) + } + } + renamed, err := ApplyName(gitDriver, runtime.store, target.ID, name) + if err != nil { + return Session{}, err + } + if err := runtime.relabel([]string{renamed.ID}); err != nil { + return Session{}, fmt.Errorf("renamed %s, but could not update its status bar: %w", renamed.ID, err) + } + return runtime.sessionInfo(renamed, runtime.driver.Exists(renamed.ID), false), nil +} diff --git a/internal/sessioncmd/session_rename_test.go b/internal/sessioncmd/session_rename_test.go new file mode 100644 index 00000000..3f16b280 --- /dev/null +++ b/internal/sessioncmd/session_rename_test.go @@ -0,0 +1,64 @@ +package sessioncmd + +import ( + "os/exec" + "strings" + "testing" +) + +// The user's rename key on another machine names an agent or a terminal on +// this one at any time, and a managed branch follows the name as it does +// for a local rename. +func TestRenameSessionNamesAnAgentOrATerminalWithNoCaller(t *testing.T) { + h := newSessionHarness(t) + repo := newGitRepo(t) + wanted := true + created, err := h.sessions.Create("", CreateSessionOptions{Name: "first-name", Directory: repo, Worktree: &wanted}) + if err != nil { + t.Fatalf("Create: %v", err) + } + renamed, err := h.sessions.RenameSession("", created.ID, " second name ") + if err != nil { + t.Fatalf("RenameSession: %v", err) + } + if renamed.ID != created.ID || renamed.Name != "second name" || renamed.Branch != "am/second-name" { + t.Fatalf("renamed = %+v", renamed) + } + stored, err := h.store.Get(created.ID) + if err != nil || stored.Name != "second name" || stored.WorktreeBranch != "am/second-name" { + t.Fatalf("stored row = %+v (%v)", stored, err) + } + if out, err := exec.Command("git", "-C", repo, "branch", "--list", "am/second-name").CombinedOutput(); err != nil || !strings.Contains(string(out), "am/second-name") { + t.Fatalf("git branch after the rename: %q (%v)", out, err) + } + if got := statusLeft(t, h, created.ID); !strings.Contains(got, "second name") { + t.Fatalf("status-left = %q, want the new name", got) + } + + terminal, err := h.terminals.Create("", CreateTerminalOptions{}) + if err != nil { + t.Fatalf("create terminal: %v", err) + } + if renamed, err := h.sessions.RenameSession("", terminal.ID, "logs"); err != nil || renamed.Name != "logs" { + t.Fatalf("rename a terminal = %+v (%v)", renamed, err) + } +} + +// A session names itself with rename, once, on a placeholder; renaming +// another one is the user's. +func TestRenameSessionRefusesACallerAndABadTarget(t *testing.T) { + h := newSessionHarness(t) + worker := h.addSessionRow(t, "worker") + if _, err := h.sessions.RenameSession(h.caller.ID, worker, "taken"); err == nil || !strings.Contains(err.Error(), "agent-manager rename") { + t.Fatalf("RenameSession from a session = %v, want it pointed at rename", err) + } + if _, err := h.sessions.RenameSession("", worker, " "); err == nil || err.Error() != "name cannot be empty" { + t.Fatalf("an empty name = %v", err) + } + if _, err := h.sessions.RenameSession("", "nosuch01", "x"); err == nil || !strings.Contains(err.Error(), "does not exist") { + t.Fatalf("a missing session = %v", err) + } + if stored, err := h.store.Get(worker); err != nil || stored.Name != "worker" { + t.Fatalf("worker after the refusals = %+v (%v)", stored, err) + } +} diff --git a/internal/sessioncmd/worktree_rename.go b/internal/sessioncmd/worktree_rename.go index 63fe5613..2fefd716 100644 --- a/internal/sessioncmd/worktree_rename.go +++ b/internal/sessioncmd/worktree_rename.go @@ -1,7 +1,10 @@ package sessioncmd import ( + "database/sql" + "errors" "fmt" + "github.com/YoanWai/agent-manager/internal/git" "github.com/YoanWai/agent-manager/internal/store" ) @@ -11,6 +14,29 @@ type worktreeRenameStore interface { RenameSessionWorktreeBranch(string, string) error } +// ApplyName names a session the way the manager does: its managed branch +// first, so a name git cannot give it leaves the session as it was, then its +// row. It starts from the row as stored, not a caller's earlier copy, since +// another rename or a group rename may have landed since, and returns it +// renamed. The caller relabels the pane. +func ApplyName(gitDrv *git.Driver, st *store.Store, id, name string) (store.Session, error) { + sess, err := st.Get(id) + if errors.Is(err, sql.ErrNoRows) { + return store.Session{}, fmt.Errorf("session %s: %w", id, store.ErrSessionGone) + } + if err != nil || name == sess.Name { + return sess, err + } + if err := RenameWorktreeBranch(gitDrv, st, &sess, name); err != nil { + return store.Session{}, fmt.Errorf("worktree rename: %w", err) + } + if err := st.RenameSession(id, name); err != nil { + return store.Session{}, err + } + sess.Name = name + return sess, nil +} + // RenameWorktreeBranch keeps a managed branch aligned with its // session's display name without moving the directory of a live process. func RenameWorktreeBranch(gitDrv *git.Driver, st worktreeRenameStore, sess *store.Session, name string) error { diff --git a/internal/ui/connections/call.go b/internal/ui/connections/call.go index c716e622..3857842e 100644 --- a/internal/ui/connections/call.go +++ b/internal/ui/connections/call.go @@ -41,22 +41,21 @@ type Call struct { // Refusals names the rail actions a connection's rows do not offer, as the // status line words them. 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", - uirail.OpenEditor: "the editor", - uirail.CopyReply: "copy reply", - uirail.MarkIdle: "mark idle", - uirail.CancelEnd: "cancel end", - uirail.KillAll: "kill all", - uirail.ReviveAll: "revive all", - uirail.Kill: "kill", - uirail.Revive: "revive", - uirail.Archive: "archive", - uirail.Restore: "restore", + uirail.MoveToGroup: "move", + uirail.Delete: "deleting a group", + 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", + uirail.Kill: "kill", + uirail.Revive: "revive", + uirail.Archive: "archive", + uirail.Restore: "restore", } var confirm = map[Op]struct { diff --git a/internal/ui/connections/link/call.go b/internal/ui/connections/link/call.go index d8c99c6f..2fd4eb57 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" + uirail "github.com/YoanWai/agent-manager/internal/ui/rail" tea "github.com/charmbracelet/bubbletea" ) @@ -21,6 +22,8 @@ const ( Restore CreateGroup Delete + Rename + RenameGroup ) type Call struct { @@ -76,6 +79,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 Rename: + result.Session, err = client.Rename(ctx, call.Ref, call.Text) + case RenameGroup: + _, err = client.RenameGroup(ctx, call.Host, call.Name, call.Text) } return result, err } @@ -121,6 +128,17 @@ 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 Rename: + root.CloseRename(call.ComposerGen, call.Text) + root.ReportDone("renamed " + call.Name + " to " + call.Text + on) + case RenameGroup: + root.CloseRename(call.ComposerGen, call.Text) + renamed := call.Text + if parent := uirail.ParentGroup(call.Name); parent != "" { + renamed = parent + "/" + call.Text + } + root.RailConnection(RailChange{GroupHost: call.Host, Group: call.Name, ToGroup: renamed}) + root.ReportDone("renamed group " + call.Name + " to " + renamed + 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..17b8d829 100644 --- a/internal/ui/connections/link/call_test.go +++ b/internal/ui/connections/link/call_test.go @@ -19,6 +19,8 @@ func TestRunTurnsEachCallIntoItsHostCommand(t *testing.T) { {Revive, []string{"revive", "--json", "--", "s1"}}, {Archive, []string{"archive", "--json", "--", "s1"}}, {Restore, []string{"archive", "--restore", "--json", "--", "s1"}}, + {Rename, []string{"rename-session", "--json", "--", "s1", "hello"}}, + {RenameGroup, []string{"rename-group", "--json", "--", "api", "hello"}}, } { fake := &ssh{} client := listedState(t, fake).Client @@ -99,6 +101,29 @@ func TestADeleteReportsTheHostsNotice(t *testing.T) { } } +// A rename closes the name field it was typed in once the host took it, and +// a group's folds here follow it to its new path. +func TestARenameClosesItsField(t *testing.T) { + state := listedState(t, &ssh{}) + call := Call{Op: Rename, Host: "box", Ref: remote.Ref{Host: "box", ID: "s1"}, Name: "api", Text: "gateway", ComposerGen: 6} + root := &recorder{} + state.ApplyCall(root, call, Result{}, nil) + if !equal(root.renamed, []string{"gateway"}) || len(root.rail) != 0 { + t.Fatalf("closed %q, rail %+v; want the field that sent gateway", root.renamed, root.rail) + } + if want := []string{"renamed api to gateway on box"}; !equal(root.done, want) { + t.Fatalf("status = %q, want %q", root.done, want) + } + root = &recorder{} + state.ApplyCall(root, Call{Op: RenameGroup, Host: "box", Name: "apps/web", Text: "frontend", ComposerGen: 7}, Result{}, nil) + if !equal(root.renamed, []string{"frontend"}) || !equal(root.done, []string{"renamed group apps/web to apps/frontend on box"}) { + t.Fatalf("group rename: closed %q status %q", root.renamed, root.done) + } + if want := (RailChange{GroupHost: "box", Group: "apps/web", ToGroup: "apps/frontend"}); len(root.rail) != 1 || root.rail[0] != want { + t.Fatalf("rail = %+v, want the folds carried %+v", root.rail, want) + } +} + func equal(left, right []string) bool { if len(left) != len(right) { return false diff --git a/internal/ui/connections/link/link.go b/internal/ui/connections/link/link.go index ff5d08a6..fb444373 100644 --- a/internal/ui/connections/link/link.go +++ b/internal/ui/connections/link/link.go @@ -42,6 +42,9 @@ type Root interface { // CloseAsker closes the form or card a completed call came from, when // it is still the one that asked. CloseAsker(gen int, asker Asker) + // CloseRename closes the name field a completed rename came from, when + // it still holds the name that was sent or names a group. + CloseRename(gen int, name string) // ClearAccepted clears the quick bar a send came from, when it still // holds that draft. ClearAccepted(composerGen int, draft string, closeAfterSend bool) diff --git a/internal/ui/connections/link/link_test.go b/internal/ui/connections/link/link_test.go index 9e67174a..46368bbb 100644 --- a/internal/ui/connections/link/link_test.go +++ b/internal/ui/connections/link/link_test.go @@ -80,6 +80,7 @@ type recorder struct { rail []RailChange answered []bool closed []Asker + renamed []string cleared int errs []string done []string @@ -95,6 +96,8 @@ func (r *recorder) AnswerSave(gen uint64, failed bool) { r.answered = append(r.a func (r *recorder) CloseAsker(gen int, asker Asker) { r.closed = append(r.closed, asker) } +func (r *recorder) CloseRename(gen int, name string) { r.renamed = append(r.renamed, name) } + func (r *recorder) ClearAccepted(composerGen int, draft string, closeAfterSend bool) { r.cleared++ } func (r *recorder) ReportErr(text string) { r.errs = append(r.errs, text) } diff --git a/internal/ui/connections/link/save.go b/internal/ui/connections/link/save.go index 49e5de16..49eb8e87 100644 --- a/internal/ui/connections/link/save.go +++ b/internal/ui/connections/link/save.go @@ -46,12 +46,15 @@ func Save(st Store, request SaveRequest) ([]store.Connection, error) { } // RailChange is what a saved list asks of the rail: the rename or removal -// the write made, and the connection to select. +// the write made, and the connection to select. A group a host renamed +// carries its folds here from Group to ToGroup. type RailChange struct { Rename string To string Forget string Focus string + + GroupHost, Group, ToGroup string } // ApplySave adopts the list the store returned after a save, or keeps the diff --git a/internal/ui/connections_adapter.go b/internal/ui/connections_adapter.go index 1320f9b7..4820fac3 100644 --- a/internal/ui/connections_adapter.go +++ b/internal/ui/connections_adapter.go @@ -58,6 +58,10 @@ func (m *Model) connectionIntent(intent uirail.Intent) (tea.Cmd, bool) { m.openGroupForm() return nil, true } + if intent.Kind == uirail.RenameAction { + m.openRemoteRename(row) + return nil, true + } if intent.Kind == uirail.NewTerminal { group := row.Group return m.queueRemote(newTerminalCall(row.Host, group)), true @@ -96,6 +100,25 @@ func (m *Model) remoteSessionIntent(row uiconnections.Row, call uiconnections.Ca return m.confirmRemote(request, call, row.Terminals), true } +// openRemoteRename types a remote agent's, terminal's or group's new name +// into its row, as r does here; an offline host refuses first. +func (m *Model) openRemoteRename(row uiconnections.Row) { + if refusal, offline := m.ssh.Offline(row.Host); offline { + m.reportErr(refusal) + return + } + m.gens.dialog++ + call := remoteCall(row.Host, row.Ref, row.Name) + call.Op, call.ComposerGen = uilink.Rename, int(m.gens.dialog) + rename := uidialogs.RenameRemote(row.Host, row.Ref.ID, row.Name) + if row.Kind == uiconnections.GroupRow { + call.Op, call.Name = uilink.RenameGroup, row.Group + rename = uidialogs.RenameRemoteGroup(row.Host, row.Group) + } + m.push(uidialogs.NewRenameSurface(remoteRenameRoot{m, call}, rename)) + m.clearErr() +} + // remoteOp is the call a remote row's lifecycle op makes. var remoteOp = map[uiconnections.Op]uilink.Op{ uiconnections.OpKill: uilink.Kill, @@ -142,12 +165,15 @@ func (m *Model) queueRemote(request uilink.Call) tea.Cmd { return m.nextEffectCmd() } -// remoteRepeat refuses a second enter on a composer whose prompt or spawn -// is still on its way to the host, as the local lane refuses one. +// remoteRepeat refuses a second enter on a composer or a name field whose +// prompt, spawn or rename is still on its way to the host, as the local lane +// refuses one. func (m *Model) remoteRepeat(request uilink.Call) (string, bool) { refusal, guarded := map[uilink.Op]string{ - uilink.Type: "this prompt is already being sent", - uilink.Spawn: "this spawn is already in progress", + uilink.Type: "this prompt is already being sent", + uilink.Spawn: "this spawn is already in progress", + uilink.Rename: "this rename is already on its way", + uilink.RenameGroup: "this rename is already on its way", }[request.Op] if !guarded { return "", false diff --git a/internal/ui/connections_adapter_rename_test.go b/internal/ui/connections_adapter_rename_test.go new file mode 100644 index 00000000..e34f07c2 --- /dev/null +++ b/internal/ui/connections_adapter_rename_test.go @@ -0,0 +1,168 @@ +package ui + +import ( + "slices" + "strings" + "testing" + "time" + + uirail "github.com/YoanWai/agent-manager/internal/ui/rail" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" +) + +// r on a remote agent or terminal types the new name into its row, as it +// does here, and the host renames it; nothing reaches the host before enter. +func TestRemoteRenameTypesTheNameIntoTheRowAndSendsIt(t *testing.T) { + for _, tc := range []struct{ id, old, name string }{{"s1", "api", "gateway"}, {"t1", "sh", "logs"}} { + fake := &fakeSSH{} + m := connectedModel(t, fake) + m.layout.width, m.layout.height = 120, 34 + m.rail.Focus(boxSession(tc.id)) + m.runRailIntent(uirail.Intent{Kind: uirail.RenameAction, Target: boxSession(tc.id)}) + if !renameOpen(m) || openRename(m).Name() != tc.old { + t.Fatalf("%s: rename open %v, status %q", tc.id, renameOpen(m), m.errBar.text) + } + if hints := openRename(m).Footer(); slices.ContainsFunc(hints, func(h [2]string) bool { return h[0] == "tab" }) { + t.Fatalf("%s: the remote field offers a tool: %q", tc.id, hints) + } + openRename(m).SetName(tc.name) + if view := ansi.Strip(preparedView(m)); !strings.Contains(view, tc.name) { + t.Fatalf("%s: the field is not drawn on the remote row:\n%s", tc.id, view) + } + if calls := fake.taken(); len(calls) != 0 { + t.Fatalf("%s: calls before enter = %q", tc.id, calls) + } + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m.runRemoteCmd(t, cmd) + if want := []string{"rename-session", "--json", "--", tc.id, tc.name}; !slices.ContainsFunc(fake.taken(), func(call []string) bool { return slices.Equal(call, want) }) { + t.Fatalf("%s: calls = %q, want %q", tc.id, fake.taken(), want) + } + if want := "renamed " + tc.old + " to " + tc.name + " on box"; m.errBar.text != want { + t.Fatalf("%s: status = %q, want %q", tc.id, m.errBar.text, want) + } + if renameOpen(m) { + t.Fatalf("%s: the field stayed open after the host renamed it", tc.id) + } + if len(m.workspace.sessions) != 0 { + t.Fatalf("%s: a remote rename reached the local list: %+v", tc.id, m.workspace.sessions) + } + } +} + +// A name the host refuses keeps the field open on it, as a local rename +// git refuses does. +func TestRemoteRenameTheHostRefusesKeepsTheField(t *testing.T) { + fake := &fakeSSH{} + m := connectedModel(t, fake) + m.runRailIntent(uirail.Intent{Kind: uirail.RenameAction, Target: boxSession("s1")}) + openRename(m).SetName("gateway") + fake.mu.Lock() + fake.stderr, fake.code = "agent-manager: worktree rename: branch am/gateway already exists\n", 1 + fake.mu.Unlock() + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m.runRemoteCmd(t, cmd) + if m.errBar.text != "box: worktree rename: branch am/gateway already exists" { + t.Fatalf("status = %q", m.errBar.text) + } + if !renameOpen(m) || openRename(m).Name() != "gateway" { + t.Fatalf("rename open %v after the refusal", renameOpen(m)) + } +} + +// r on a remote group types its last path part into the row, says its +// subtree moves with it, and the host renames the group in place. +func TestRemoteGroupRenameKeepsItsParentAndSaysTheSubtreeMoves(t *testing.T) { + fake := &fakeSSH{} + m := connectedModel(t, fake) + m.layout.width, m.layout.height = 120, 34 + m.rail.Focus(boxGroup) + m.runRailIntent(uirail.Intent{Kind: uirail.RenameAction, Target: boxGroup}) + if !renameOpen(m) || openRename(m).Name() != "web" { + t.Fatalf("rename open %v, status %q", renameOpen(m), m.errBar.text) + } + if hints := openRename(m).Footer(); !slices.Contains(hints, [2]string{"↵", "save; its subgroups and sessions move with it"}) { + t.Fatalf("footer = %q, want the subtree named", hints) + } + openRename(m).SetName("frontend") + if view := ansi.Strip(preparedView(m)); !strings.Contains(view, "frontend") { + t.Fatalf("the field is not drawn on the remote group:\n%s", view) + } + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m.runRemoteCmd(t, cmd) + if want := []string{"rename-group", "--json", "--", "web", "frontend"}; !slices.ContainsFunc(fake.taken(), func(call []string) bool { return slices.Equal(call, want) }) { + t.Fatalf("calls = %q, want %q", fake.taken(), want) + } + if m.errBar.text != "renamed group web to frontend on box" || renameOpen(m) { + t.Fatalf("status %q, rename open %v", m.errBar.text, renameOpen(m)) + } +} + +func TestRemoteRenameRefusesAnOfflineHost(t *testing.T) { + fake := &fakeSSH{} + m := connectedModel(t, fake) + 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) + for _, target := range []uirail.Selection{boxSession("s1"), boxGroup} { + m.clearErr() + m.runRailIntent(uirail.Intent{Kind: uirail.RenameAction, Target: target}) + if renameOpen(m) || m.errBar.text != "box: unreachable over SSH: connection refused" { + t.Fatalf("r on %+v of an offline host: open %v, status %q", target, renameOpen(m), m.errBar.text) + } + } + if calls := fake.taken(); len(calls) != 0 { + t.Fatalf("calls = %q, want none", calls) + } +} + +// A second enter while a rename is on its way sends nothing: a group's +// second call would name the path the first one changed. A session's field +// keeps a name typed after the sent one; a group's closes, its path gone. +func TestRemoteRenameSendsOneCallPerEnterOnItsWay(t *testing.T) { + for _, tc := range []struct { + target uirail.Selection + op string + stayOpen bool + }{{boxSession("s1"), "rename-session", true}, {boxGroup, "rename-group", false}} { + fake := &fakeSSH{} + m := connectedModel(t, fake) + m.runRailIntent(uirail.Intent{Kind: uirail.RenameAction, Target: tc.target}) + openRename(m).SetName("a") + _, first := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + openRename(m).SetName("ab") + _, second := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + if m.errBar.text != "this rename is already on its way" { + t.Fatalf("%s: second enter status = %q", tc.op, m.errBar.text) + } + m.runRemoteCmd(t, first) + m.runRemoteCmd(t, second) + var renames [][]string + for _, call := range fake.taken() { + if call[0] == tc.op { + renames = append(renames, call) + } + } + if len(renames) != 1 || renames[0][len(renames[0])-1] != "a" { + t.Fatalf("%s: calls = %q, want one rename to a", tc.op, renames) + } + if renameOpen(m) != tc.stayOpen || tc.stayOpen && openRename(m).Name() != "ab" { + t.Fatalf("%s: rename open %v after the host took a, want %v holding ab", tc.op, renameOpen(m), tc.stayOpen) + } + } +} + +// A group's folds here follow it to the path the host gave it, so the old +// path does not come back folded on a later group of that name. +func TestRemoteGroupRenameCarriesItsFolds(t *testing.T) { + fake := &fakeSSH{} + m := connectedModel(t, fake) + m.rail.RestoreHostFolds([]uirail.HostFold{{Host: "box", Path: "web"}}) + m.runRailIntent(uirail.Intent{Kind: uirail.RenameAction, Target: boxGroup}) + openRename(m).SetName("frontend") + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m.runRemoteCmd(t, cmd) + if want := []uirail.HostFold{{Host: "box", Path: "frontend"}}; !slices.Equal(m.rail.HostCollapsed(), want) { + t.Fatalf("folds = %+v, want %+v", m.rail.HostCollapsed(), want) + } +} diff --git a/internal/ui/connections_adapter_test.go b/internal/ui/connections_adapter_test.go index 64c287be..868d7471 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.MoveToGroup: "move", 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", diff --git a/internal/ui/connections_host.go b/internal/ui/connections_host.go index 4fcb9f89..070794ed 100644 --- a/internal/ui/connections_host.go +++ b/internal/ui/connections_host.go @@ -35,6 +35,8 @@ func (r linkRoot) RailConnection(change uilink.RailChange) { r.queueRail(r.rail.RenameHost(change.Rename, change.To).Mutations, 0, true) case change.Forget != "": r.queueRail(r.rail.ForgetHost(change.Forget).Mutations, 0, true) + case change.Group != "": + r.queueRail(r.rail.RenameGroup(change.GroupHost, change.Group, change.ToGroup).Mutations, 0, true) } if change.Focus != "" { r.rail.Focus(uirail.Selection{Kind: uirail.ConnectionRow, Host: change.Focus}) @@ -67,10 +69,31 @@ func (r linkRoot) CloseAsker(gen int, asker uilink.Asker) { } } +func (r linkRoot) CloseRename(gen int, name string) { + s, ok := surfaceOf[*uidialogs.RenameSurface](r.Model) + // A group field closes on any name: the path it names is gone once the + // host renamed it, and r on the new row opens it again. + if ok && uint64(gen) == r.gens.dialog && (s.Group() != "" || s.Name() == name) { + r.Pop() + } +} + func (r linkRoot) ClearAccepted(composerGen int, draft string, closeAfterSend bool) { r.clearAccepted(composerGen, draft, closeAfterSend) } +// remoteRenameRoot is the root as a remote row's rename field reaches it: +// the call it opened with, which a submit completes with the new name. +type remoteRenameRoot struct { + *Model + call uilink.Call +} + +func (r remoteRenameRoot) QueueRename(request uidialogs.RenameRequest) tea.Cmd { + r.call.Text = request.Name + return r.queueRemote(r.call) +} + // connectionsRoot is the root as the connection card reads it: the theme's // field painter, the card width, and the store write and status line. type connectionsRoot struct{ *Model } @@ -106,8 +129,9 @@ func (r connectionsRoot) Report(err error) tea.Cmd { } var ( - _ uilink.Root = linkRoot{} - _ uiconnections.Root = connectionsRoot{} + _ uilink.Root = linkRoot{} + _ uiconnections.Root = connectionsRoot{} + _ uidialogs.RenameRoot = remoteRenameRoot{} ) // routeConnectionMsg hands a routed connection result to the package, and diff --git a/internal/ui/dialogs/rename.go b/internal/ui/dialogs/rename.go index 51d3ea3c..7b401929 100644 --- a/internal/ui/dialogs/rename.go +++ b/internal/ui/dialogs/rename.go @@ -1,6 +1,8 @@ package dialogs import ( + "strings" + "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" ) @@ -10,9 +12,12 @@ import ( // rename on the effect lane and closes it from the fenced completion. type Rename struct { sessionID string - input textinput.Model - tools []string - toolIndex int + // host is the SSH connection a remote row belongs to, and group the path + // of a remote group, whose rename keeps its parent. + host, group string + input textinput.Model + tools []string + toolIndex int } func nameField(name string) textinput.Model { @@ -47,8 +52,28 @@ func RenameSession(id, name, tool string, tools []string) Rename { } } +// RenameRemote opens a rename of a row on an SSH connection: its name only, +// since the tools are the other machine's. +func RenameRemote(host, id, name string) Rename { + d := RenameSession(id, name, "", nil) + d.host = host + return d +} + +// RenameRemoteGroup opens a rename of a group on an SSH connection, typed as +// the last part of its path, which stays under its parent. +func RenameRemoteGroup(host, path string) Rename { + d := RenameRemote(host, "", path[strings.LastIndex(path, "/")+1:]) + d.group = path + return d +} + func (d Rename) SessionID() string { return d.sessionID } +func (d Rename) Host() string { return d.host } + +func (d Rename) Group() string { return d.group } + func (d Rename) Name() string { return cleanName(d.input.Value()) } func (d *Rename) SetName(name string) { d.input.SetValue(name) } @@ -134,6 +159,9 @@ func (d *Rename) submit() RenameKey { } func (d Rename) Hints() [][2]string { + if d.group != "" { + return [][2]string{{"↵", "save; its subgroups and sessions move with it"}, {"esc", "cancel"}} + } if tool := d.Tool(); tool != "" { return [][2]string{{"tab", "tool: " + tool}, {"↵", "save"}, {"esc", "cancel"}} } diff --git a/internal/ui/dialogs_adapter.go b/internal/ui/dialogs_adapter.go index 99822e53..6717d7c0 100644 --- a/internal/ui/dialogs_adapter.go +++ b/internal/ui/dialogs_adapter.go @@ -399,7 +399,7 @@ func (m *Model) applyRenameOutcome(job *uieffects.Job, result uiapply.Outcome, e m.workspace.groups, m.workspace.sessions = renamed.Groups, renamed.Sessions m.workspace.groupPaths, m.workspace.groupWorktrees = renamed.GroupPaths, renamed.GroupWorktrees m.workspace.groupBases, m.workspace.groupEnvs = renamed.GroupBases, renamed.GroupEnvs - m.queueRail(m.rail.RenameGroup(request.OldGroup, request.NewGroup).Mutations, 0, true) + m.queueRail(m.rail.RenameGroup("", request.OldGroup, request.NewGroup).Mutations, 0, true) } } else { m.workspace.sessions = inventory.RenamedSession(request.SessID, stages, request.Name, result.Branch, request.Tool) @@ -449,7 +449,7 @@ func (m *Model) renameGroupLocally(old, newPath, dir, worktree, base, env string m.workspace.groups, m.workspace.sessions = renamed.Groups, renamed.Sessions m.workspace.groupPaths, m.workspace.groupWorktrees = renamed.GroupPaths, renamed.GroupWorktrees m.workspace.groupBases, m.workspace.groupEnvs = renamed.GroupBases, renamed.GroupEnvs - m.queueRail(m.rail.RenameGroup(old, newPath).Mutations, 0, true) + m.queueRail(m.rail.RenameGroup("", old, newPath).Mutations, 0, true) } // openGroupForm opens the New Group card, seeded with the parent picker and diff --git a/internal/ui/help/catalog.go b/internal/ui/help/catalog.go index fa1c90da..d8d722f4 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 agents, terminals and groups: rename") 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 798158fd..7dc0e059 100644 --- a/internal/ui/rail/hosts_test.go +++ b/internal/ui/rail/hosts_test.go @@ -233,29 +233,37 @@ 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{"Move to group", "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, "Rename") { t.Errorf("remote session menu = %v", session) } // The host archives and revives 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) + if got := labels(Selection{Kind: SessionRow, SessionID: "shell", Group: "ops", Host: "box"}); !slices.Equal(got, []string{"Attach", "Rename", "Kill"}) { + t.Errorf("remote terminal menu = %v, want Attach, Rename and Kill", got) } 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, "Rename") { + t.Errorf("remote group menu = %v, want Rename", 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{"Rename", "Revive", "Archive", "Delete"}) { + t.Errorf("dead remote session menu = %v, want Rename, 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{"Rename", "Restore", "Delete"}) { + t.Errorf("archived remote session menu = %v, want Rename, Restore and Delete", got) + } + model.SetArchived(false) + model.Reconcile(Snapshot{Hosts: []Host{{Name: "box", State: HostOnline, Sessions: []Session{{ID: "far", Name: "far", Tool: "terminal", IsShell: true, Status: "dead"}}}}}) + if got := labels(Selection{Kind: SessionRow, SessionID: "far", Host: "box"}); !slices.Equal(got, []string{"Rename", "Kill"}) { + t.Errorf("dead remote terminal menu = %v, want Rename and Kill", got) } } diff --git a/internal/ui/rail/legend.go b/internal/ui/rail/legend.go index 9c98fcda..31d71c20 100644 --- a/internal/ui/rail/legend.go +++ b/internal/ui/rail/legend.go @@ -282,14 +282,14 @@ func (m Model) RemoteLegend(ctx LegendContext, row RemoteRow, collapsed bool) Le })} case GroupRow: return Legend{Title: "Group", Leads: leads, Pairs: boundPairs([][2]string{ - {k(keybind.Open), fold}, {k(keybind.Terminal), "terminal"}, {k(keybind.NewGroup), "group"}, + {k(keybind.Open), fold}, {k(keybind.Terminal), "terminal"}, {k(keybind.NewGroup), "group"}, {k(keybind.Rename), "rename"}, })} } title, kill := "Session", "kill" if row.Terminal { title, kill, leads = "Shell", "close", nil } - pairs := [][2]string{{k(keybind.Open, keybind.Attach), "attach over SSH"}, {k(keybind.Kill), kill}} + pairs := [][2]string{{k(keybind.Open, keybind.Attach), "attach over SSH"}, {k(keybind.Kill), kill}, {k(keybind.Rename), "rename"}} if !row.Terminal { pairs = append(pairs, [2]string{k(keybind.Delete), "delete"}) } diff --git a/internal/ui/rail/legend_test.go b/internal/ui/rail/legend_test.go index 305a97c4..d8d7d39f 100644 --- a/internal/ui/rail/legend_test.go +++ b/internal/ui/rail/legend_test.go @@ -84,3 +84,13 @@ func TestRemoteLegendOffersDeleteOnAnAgentOnly(t *testing.T) { t.Fatalf("a remote shell should leave delete to close, got %+v", shell.Pairs) } } + +func TestRemoteLegendOffersRenameOnAgentsShellsAndGroups(t *testing.T) { + model := rail.New(nil) + ctx := rail.LegendContext{ListKeys: keybind.DefaultList()} + for _, row := range []rail.RemoteRow{{Kind: rail.SessionRow, Host: "box"}, {Kind: rail.SessionRow, Host: "box", Terminal: true}, {Kind: rail.GroupRow, Host: "box"}} { + if legend := model.RemoteLegend(ctx, row, false); !slices.Contains(legend.Pairs, [2]string{"r", "rename"}) { + t.Fatalf("%s should offer rename, got %+v", legend.Title, legend.Pairs) + } + } +} diff --git a/internal/ui/rail/menu.go b/internal/ui/rail/menu.go index f607d04b..f2e4c224 100644 --- a/internal/ui/rail/menu.go +++ b/internal/ui/rail/menu.go @@ -106,33 +106,35 @@ func (m Model) rowMenuItems(row treeRow) []menuItem { // remote host's CLI. func remoteMenuItems(row treeRow, create []menuItem, connection menuItem) []menuItem { group := menuItem{label: "New group", action: NewGroup} + rename := []menuItem{{label: "Rename", action: RenameAction}} switch row.kind { case ConnectionRow: return menuSections(append(create, group), []menuItem{{label: "Edit connection", action: RenameAction}, connection}, []menuItem{{label: "Remove connection", action: Delete, danger: true}}) case GroupRow: - return append(create, group) + return menuSections(append(create, group), rename) } remove := menuItem{label: "Delete", action: Delete, danger: true} if row.sess.Archived { - return []menuItem{{label: "Restore", action: Restore}, remove} + return menuSections(rename, []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. if row.sess.Status == "dead" { - return []menuItem{kill} + return menuSections(rename, []menuItem{kill}) } - return menuSections([]menuItem{{label: "Attach", action: Attach}}, []menuItem{kill}) + return menuSections([]menuItem{{label: "Attach", action: Attach}}, rename, []menuItem{kill}) } archive := menuItem{label: "Archive", action: Archive} if row.sess.Status == "dead" { - return menuSections([]menuItem{{label: "Revive", action: Revive}}, []menuItem{archive, remove}) + return menuSections(rename, []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}}, + rename, []menuItem{archive, kill, remove}, ) } diff --git a/internal/ui/rail/policy.go b/internal/ui/rail/policy.go index 95e85d23..c004f816 100644 --- a/internal/ui/rail/policy.go +++ b/internal/ui/rail/policy.go @@ -457,14 +457,29 @@ func (m *Model) ForgetGroups(paths []string) Decision { return m.collapsedDecision() } -func (m *Model) RenameGroup(oldPath, newPath string) Decision { - for path, collapsed := range m.collapsed { +// RenameGroup carries the folds of a renamed group and its subgroups to the +// new path; host names the connection a remote group is on. +func (m *Model) RenameGroup(host, oldPath, newPath string) Decision { + renamed := func(path string) (string, bool) { if path != oldPath && !strings.HasPrefix(path, oldPath+"/") { - continue + return "", false + } + return newPath + strings.TrimPrefix(path, oldPath), true + } + if host != "" { + for fold, folded := range m.hostFolds { + if path, ok := renamed(fold.Path); ok && fold.Host == host { + delete(m.hostFolds, fold) + m.hostFolds[HostFold{Host: host, Path: path}] = folded + } + } + } else { + for path, collapsed := range m.collapsed { + if next, ok := renamed(path); ok { + delete(m.collapsed, path) + m.collapsed[next] = collapsed + } } - delete(m.collapsed, path) - renamed := newPath + strings.TrimPrefix(path, oldPath) - m.collapsed[renamed] = collapsed } m.rebuildRows() return m.collapsedDecision() diff --git a/internal/ui/rail_adapter.go b/internal/ui/rail_adapter.go index 49b77231..6353d642 100644 --- a/internal/ui/rail_adapter.go +++ b/internal/ui/rail_adapter.go @@ -207,9 +207,19 @@ func (m *Model) prepareRailFrame(width, height int) { } rename := uirail.Rename{} if s, ok := surfaceOf[*uidialogs.RenameSurface](m); ok { - rename.Target = uirail.Selection{Kind: uirail.SessionRow, SessionID: s.SessionID()} - if session, ok := m.sessionByID(s.SessionID()); ok { - rename.Target.Group = session.Group + switch { + case s.Group() != "": + rename.Target = uirail.Selection{Kind: uirail.GroupRow, Group: s.Group(), Host: s.Host()} + case s.Host() != "": + rename.Target = uirail.Selection{Kind: uirail.SessionRow, SessionID: s.SessionID(), Host: s.Host()} + if row, ok := m.ssh.Row(rename.Target); ok { + rename.Target.Group = row.Group + } + default: + rename.Target = uirail.Selection{Kind: uirail.SessionRow, SessionID: s.SessionID()} + if session, ok := m.sessionByID(s.SessionID()); ok { + rename.Target.Group = session.Group + } } fieldWidth := width - 4 for _, row := range m.rail.Rows() { diff --git a/internal/ui/rail_adapter_effect_test.go b/internal/ui/rail_adapter_effect_test.go index 387a6090..a2aafb47 100644 --- a/internal/ui/rail_adapter_effect_test.go +++ b/internal/ui/rail_adapter_effect_test.go @@ -212,7 +212,7 @@ func TestRailStateDecisionPreservesLatestCollapseSnapshot(t *testing.T) { m.queueRail([]uirail.Mutation{{Kind: uirail.SaveCollapsed, Collapsed: m.rail.Collapsed()}}, 0, false) var expected []string if scenario == "rename" { - m.queueRail(m.rail.RenameGroup("parent", "renamed").Mutations, 0, true) + m.queueRail(m.rail.RenameGroup("", "parent", "renamed").Mutations, 0, true) expected = []string{"renamed"} } else { m.queueRail(m.rail.RevealGroup("parent/child").Mutations, 0, true) diff --git a/tools/e2e/README.md b/tools/e2e/README.md index 3b124cb7..9daf984c 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, renames it and back and renames a remote group with `r`, checking each name in the host's store, 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. 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..8114238d 100644 --- a/tools/e2e/ssh_scenarios.py +++ b/tools/e2e/ssh_scenarios.py @@ -5,7 +5,7 @@ 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, +remote row offers: preview, rename, 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. """ @@ -32,6 +32,8 @@ CONNECTION = 'box' DOWN = 'down' REMOTE_AGENT = 'remote-agent' +RENAMED_AGENT = 'renamed-agent' +RENAMED_GROUP = 'frontend' REMOTE_GROUP = 'web' GROUPED_AGENT = 'api' REMOTE_NEW_GROUP = 'ops' @@ -227,6 +229,26 @@ def confirm(sandbox, name, question, done): frame(sandbox, name + '-done', done) +def rename(sandbox, remote, agent_id): + """r types the new name into the row and the host renames the agent, which goes back to its old name + for the steps after, then the group the other agent is filed in.""" + agent = f"SELECT name FROM sessions WHERE id = '{agent_id}'" + grouped = f"SELECT group_name FROM sessions WHERE name = '{GROUPED_AGENT}'" + for name, needle, before, after, done, query in ( + ('remote-rename', f'{REMOTE_AGENT} on {CONNECTION}', REMOTE_AGENT, RENAMED_AGENT, '', agent), + ('remote-rename-back', f'{RENAMED_AGENT} on {CONNECTION}', RENAMED_AGENT, REMOTE_AGENT, '', agent), + ('remote-group-rename', f'{REMOTE_GROUP} on {CONNECTION}', REMOTE_GROUP, RENAMED_GROUP, 'group ', grouped)): + select(sandbox, name, needle) + key(sandbox, 'r') + frame(sandbox, name + '-field', 'Rename') + key(sandbox, 'C-u') + sandbox.tmux('send-keys', '-l', '-t', 'scen:0.0', after) + key(sandbox, 'Enter') + frame(sandbox, name + '-done', f'renamed {done}{before} to {after} on {CONNECTION}') + sandbox.wait(name + '-stored', lambda query=query: str(remote.query(query)), + lambda value, after=after: value == str([(after,)])) + + def lifecycle(sandbox, remote, agent_id): """Kill, revive, archive and restore, each confirmed, each landing on the host.""" key(sandbox, 'x') @@ -345,8 +367,8 @@ def scenario(sandbox, remote, binary): select_remote_agent(sandbox) frame(sandbox, 'remote-preview', READY_MARKER) - key(sandbox, 'r') - frame(sandbox, 'remote-refusal', "rename isn't available on SSH connections yet") + rename(sandbox, remote, agent_id) + select_remote_agent(sandbox) key(sandbox, 'Space') sandbox.tmux('send-keys', '-l', '-t', 'scen:0.0', QUICK_TEXT) frame(sandbox, 'quick-typed', QUICK_TEXT)