From 68ede98894fa16702cbc602629ce7eabf01e15f6 Mon Sep 17 00:00:00 2001 From: Caleb Smith Date: Thu, 8 Oct 2026 09:49:41 -0400 Subject: [PATCH 1/4] feat(cli): focus a session from outside the TUI agent-manager focus and select bring a session forward in the running manager from any shell. The manager answers on a Unix socket beside its tmux server's socket. The command connects, sends the session id and whether to open it, and reads back on the same connection what the manager did. Nothing is signalled and no request is shared, so a request cannot be answered for another, and the exit status reports the manager's own outcome. On a request the manager unfolds the groups above the session, drops a status filter hiding it and moves the cursor. focus then runs what enter does on that row and answers once the open lands. Layers that hold nothing typed (help, messages, the search, the row menu, a lifted row, a divider drag) close the way esc closes them. A dialog that may hold unfinished input stays open with the cursor moved under it, and focus reports that it did not open the session. A select leaves focus even on the session it names. A clicked notification takes the same select path, so it reaches sessions in folded groups. focus_session exposes the focus command over MCP. Ported from #726 onto the package layout #735 introduced. Refs #725 --- docs/usage.md | 5 +- internal/cli/cli.go | 2 +- internal/cli/cli_test.go | 35 ++- internal/cli/session.go | 47 ++++ internal/cli/session_test.go | 26 +++ internal/mcpserver/focus.go | 23 ++ internal/mcpserver/mcpserver.go | 25 +-- internal/mcpserver/mcpserver_nocaller_test.go | 3 +- internal/mcpserver/mcpserver_test.go | 17 +- internal/mcpserver/tools.go | 30 +++ internal/sessioncmd/focus.go | 76 +++++++ internal/sessioncmd/focus_endpoint.go | 73 +++++++ internal/sessioncmd/focus_endpoint_test.go | 99 +++++++++ internal/sessioncmd/focus_test.go | 84 ++++++++ internal/tmux/platform_unix.go | 7 + internal/tmux/platform_windows.go | 6 + internal/ui/focus_adapter.go | 5 +- internal/ui/model.go | 2 + internal/ui/rail/policy.go | 35 +++ internal/ui/rail_adapter_forward.go | 165 ++++++++++++++ internal/ui/rail_adapter_forward_test.go | 204 ++++++++++++++++++ internal/ui/session_adapter.go | 6 + internal/ui/updates.go | 1 + internal/ui/workspace_adapter.go | 16 +- 24 files changed, 954 insertions(+), 38 deletions(-) create mode 100644 internal/mcpserver/focus.go create mode 100644 internal/mcpserver/tools.go create mode 100644 internal/sessioncmd/focus.go create mode 100644 internal/sessioncmd/focus_endpoint.go create mode 100644 internal/sessioncmd/focus_endpoint_test.go create mode 100644 internal/sessioncmd/focus_test.go create mode 100644 internal/ui/rail_adapter_forward.go create mode 100644 internal/ui/rail_adapter_forward_test.go diff --git a/docs/usage.md b/docs/usage.md index c80f435ac..b7541b884 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -275,6 +275,7 @@ Every session of an MCP-capable tool carries the agent-manager MCP server on spa | `list_sessions` | List every agent session with its id, CLI, group, directory, worktree branch and status | | `create_session` | Start another agent CLI on a named task, optionally in its own git worktree | | `read_session` | Read what another agent's screen currently shows | +| `focus_session` | Open a session in the user's manager window the way enter does, when the user asked to be taken there | | `send_session` | Queue a message for another agent, delivered once it is at rest | | `message_status` | Check whether a message is queued, held, delivered, dropped or answered | | `wait_for_session` | Park until another session stops working, instead of polling it | @@ -352,13 +353,15 @@ 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`, `focus`, `select`, `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: ```bash agent-manager spawn --tool claude --group "Sprint Manager" --worktree \ --name ticket-123 --prompt "Fix TICKET-123 and open a pull request" --json ``` +`agent-manager focus ` brings a session forward in the running manager from any shell, so a key in another tool (a PR dashboard, a launcher, a script in a `T` tab) can take you to it. The command reaches the manager on a socket beside its tmux server, so the manager acts at once rather than on its next poll and answers with what it did. It leaves focus on any other session, closes help, messages, the search and the row menu the way esc would, unfolds the groups above the session, puts the cursor on its row and opens it the way enter does. A dialog that may hold unfinished input, such as the new-session form or the quick prompt, stays open with the cursor moved under it, and the session is not opened over it. `agent-manager select ` stops at the cursor, and leaves focus even on the session it names. Both exit non-zero with the reason when the id is unknown, the session is archived, no manager is running, or the manager could not do what was asked, as when `focus` finds a dialog open, and `--json` prints that reason as an `error` object too. + `snapshot --json` prints this machine's whole list as one JSON document: every session and terminal, archived ones included, the groups, and whether a manager is running here to deliver queued messages. It is what another manager reads over an SSH connection. `send "" --from ` queues a message from a sender with no session on this machine, such as an agent on another machine sending over SSH. The name is up to 64 bytes with no control characters, and `--from` is refused from inside a session, which sends as itself. The delivered message names the sender as being on another machine and says a reply cannot reach it. diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 1ef609358..a4953effc 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, settings, focus and select 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, focus, select, 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") 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..3dd227cf8 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -31,6 +31,7 @@ type fakeSessions struct { timeout time.Duration messageID int64 archived bool + entered bool action string canceled bool groupPath string @@ -99,6 +100,11 @@ func (f *fakeSessions) ExpandSaved(name, text string) (string, error) { return "saved:" + name + "\n\n" + text, nil } +func (f *fakeSessions) Focus(targetID string, enter bool) (sessioncmd.Session, error) { + f.targetID, f.entered = targetID, enter + return f.session, f.failWith +} + func (f *fakeSessions) Read(sessionID, targetID string) (sessioncmd.SessionScreen, error) { f.callerID, f.targetID = sessionID, targetID return sessioncmd.SessionScreen{Session: f.session, Output: "screen text"}, f.failWith @@ -292,6 +298,8 @@ func TestALayerFailureReachesTheCaller(t *testing.T) { {"send --from", []string{"beef1234", "ship it", "--from", "laptop-agent"}, func(out io.Writer, args []string) error { return runSend(out, sessions, args, "") }}, {"type", []string{"beef1234", "ship it"}, func(out io.Writer, args []string) error { return runType(out, sessions, args, "") }}, {"read", []string{"beef1234"}, func(out io.Writer, args []string) error { return runRead(out, sessions, args, "cafe0001") }}, + {"focus", []string{"beef1234"}, func(out io.Writer, args []string) error { return runFocus(out, sessions, args) }}, + {"select", []string{"beef1234"}, func(out io.Writer, args []string) error { return runSelect(out, sessions, args) }}, {"wait", []string{"beef1234"}, func(out io.Writer, args []string) error { return runWait(out, sessions, args, "cafe0001") }}, {"message-status", []string{"7"}, func(out io.Writer, args []string) error { return runMessageStatus(out, sessions, args, "cafe0001") }}, {"kill", []string{"beef1234"}, func(out io.Writer, args []string) error { return runKill(out, sessions, args, "cafe0001") }}, @@ -335,6 +343,23 @@ func TestALayerFailureReachesTheCaller(t *testing.T) { } } +// A script asking for JSON reads stdout, so a refused focus says why there +// as well as failing. +func TestFocusJSONReportsARefusalAsAnObject(t *testing.T) { + failure := errors.New("no Agent Manager is running to bring the session forward") + out := &bytes.Buffer{} + err := runFocus(out, &fakeSessions{failWith: failure}, []string{"beef1234", "--json"}) + if !errors.Is(err, failure) { + t.Fatalf("error = %v, want the layer's own", err) + } + var reported struct { + Error string `json:"error"` + } + if jsonErr := json.Unmarshal(out.Bytes(), &reported); jsonErr != nil || reported.Error != failure.Error() { + t.Fatalf("focus --json printed %q (%v), want the refusal as an object", out.String(), jsonErr) + } +} + func TestJSONFlagPrintsTheRecord(t *testing.T) { out := &bytes.Buffer{} fake := &fakeSessions{session: sampleSession()} @@ -370,6 +395,12 @@ func TestMissingSessionIDIsAUsageError(t *testing.T) { "kill": func(out *bytes.Buffer, f *fakeSessions, args []string) error { return runKill(out, f, args, "cafe0001") }, + "focus": func(out *bytes.Buffer, f *fakeSessions, args []string) error { + return runFocus(out, f, args) + }, + "select": func(out *bytes.Buffer, f *fakeSessions, args []string) error { + return runSelect(out, f, args) + }, "delete": func(out *bytes.Buffer, f *fakeSessions, args []string) error { return runDelete(out, f, args, "cafe0001") }, @@ -558,7 +589,7 @@ func TestCommandsThatActAsNoSessionNeverResolveACaller(t *testing.T) { t.Fatal("the caller was resolved") return "" } - for _, name := range []string{"update", "issue", "feature", "settings", "prompts", "env"} { + for _, name := range []string{"update", "issue", "feature", "settings", "prompts", "env", "focus", "select"} { if err := table[name]([]string{"-h"}, resolve, t.TempDir()); !errors.Is(err, ErrUsageShown) { t.Fatalf("%s -h: %v", name, err) } @@ -568,7 +599,7 @@ 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", + "sessions", "snapshot", "spawn", "send", "type", "read", "focus", "select", "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", "rename", "review-repo", "review-base", "review-mode", "review-comment", "issue", "feature", "settings", "export", "import", "update", } diff --git a/internal/cli/session.go b/internal/cli/session.go index d317d8e38..e659305c9 100644 --- a/internal/cli/session.go +++ b/internal/cli/session.go @@ -6,6 +6,7 @@ import ( "flag" "fmt" "io" + "os" "path/filepath" "strconv" "time" @@ -22,6 +23,8 @@ const ( usageSend = `send [""] [--saved ] [--from ] [--json]` usageType = `type "" [--json]` usageRead = "read [--styled] [--json]" + usageFocus = "focus [--json]" + usageSelect = "select [--json]" usageWait = "wait [--until ] [--timeout ] [--json]" usageMessageStatus = "message-status [--json]" usageKill = "kill [--json]" @@ -46,6 +49,7 @@ type sessionCommands interface { ExpandSaved(name, text string) (string, error) Read(sessionID, targetID string) (sessioncmd.SessionScreen, error) ReadStyled(sessionID, targetID string) (sessioncmd.SessionScreen, error) + Focus(targetID string, enter bool) (sessioncmd.Session, error) Wait(ctx context.Context, sessionID, targetID string, until []string, timeout time.Duration) (sessioncmd.WaitResult, error) MessageStatus(sessionID string, messageID int64) (sessioncmd.MessageState, error) Kill(sessionID, targetID string) (sessioncmd.Session, error) @@ -106,6 +110,8 @@ func sessionSectionWith(open func(string) sessionCommands) section { {name: "send", usage: usageSend, about: "queue a message for another agent; it is typed in once that agent is at rest, so it never lands on an approval prompt", run: bind(open, runSend)}, {name: "type", usage: usageType, about: "type a prompt into an agent's pane and submit it now, as the user's quick bar does; only for a caller with no session here, such as a manager on another machine over SSH", run: bind(open, runType)}, {name: "read", usage: usageRead, about: "read what another agent's screen currently shows", run: bind(open, runRead)}, + {name: "focus", usage: usageFocus, about: "open a session in the running manager the way enter does, unfolding its groups first; a dialog holding input stays open and the cursor moves under it", run: callerless(open, runFocus)}, + {name: "select", usage: usageSelect, about: "move the running manager's cursor to a session's row without opening it, unfolding its groups first", run: callerless(open, runSelect)}, {name: "wait", usage: usageWait, about: "park until another session stops working, instead of reading its screen in a loop; exits non-zero when it timed out", run: bind(open, runWait)}, {name: "message-status", usage: usageMessageStatus, about: "check whether a message you sent is queued, held, delivered, dropped or answered", run: bind(open, runMessageStatus)}, {name: "kill", usage: usageKill, about: "stop another agent's process, ending whatever it is doing; its row keeps the last screen", run: bind(open, runKill)}, @@ -266,6 +272,47 @@ func runRead(out io.Writer, sessions sessionCommands, args []string, sessionID s return emit(out, *asJSON, screen, sessioncmd.FormatSessionScreen(screen)) } +// callerless binds a command that acts as no session, so it never asks tmux +// which pane started it. +func callerless(open func(string) sessionCommands, run func(io.Writer, sessionCommands, []string) error) Command { + return func(args []string, _ func() string, configDir string) error { + return run(os.Stdout, open(configDir), args) + } +} + +func runFocus(out io.Writer, sessions sessionCommands, args []string) error { + return runBringForward(out, sessions, args, usageFocus, true) +} + +func runSelect(out io.Writer, sessions sessionCommands, args []string) error { + return runBringForward(out, sessions, args, usageSelect, false) +} + +// runBringForward reports a refusal as a JSON object too when --json is +// given, so a script reading stdout sees why nothing moved. +func runBringForward(out io.Writer, sessions sessionCommands, args []string, usage string, enter bool) error { + set := newFlagSet(usage) + asJSON := jsonFlag(set) + operands, err := parseCommand(out, set, args, 1, 1) + if err != nil { + return err + } + target, err := sessions.Focus(operands[0], enter) + if err != nil { + if *asJSON { + if jsonErr := writeJSON(out, map[string]string{"error": err.Error()}); jsonErr != nil { + return jsonErr + } + } + return err + } + verb := "selected " + if enter { + verb = "focused " + } + return emit(out, *asJSON, target, verb+sessioncmd.FormatSession(target)) +} + // runWait exits non-zero when the session never reached an awaited state, so // `agent-manager wait && next-step` reads the outcome the way a shell // caller expects. The result still goes out first, JSON included. diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go index b81c4374c..2d4b7ead2 100644 --- a/internal/cli/session_test.go +++ b/internal/cli/session_test.go @@ -81,6 +81,32 @@ func TestSessionCommandsParseArgumentsAndPrintSentences(t *testing.T) { args: []string{"beef1234"}, want: "screen text", }, + { + name: "focus opens the session it names", + run: func(out *bytes.Buffer, f *fakeSessions, args []string) error { + return runFocus(out, f, args) + }, + args: []string{"beef1234"}, + want: "focused api-worker (id beef1234)", + inspect: func(t *testing.T, f *fakeSessions) { + if f.targetID != "beef1234" || !f.entered { + t.Fatalf("focus got target %q enter %v", f.targetID, f.entered) + } + }, + }, + { + name: "select only moves the cursor", + run: func(out *bytes.Buffer, f *fakeSessions, args []string) error { + return runSelect(out, f, args) + }, + args: []string{"beef1234"}, + want: "selected api-worker (id beef1234)", + inspect: func(t *testing.T, f *fakeSessions) { + if f.targetID != "beef1234" || f.entered { + t.Fatalf("select got target %q enter %v", f.targetID, f.entered) + } + }, + }, { name: "kill names what it stopped", run: func(out *bytes.Buffer, f *fakeSessions, args []string) error { diff --git a/internal/mcpserver/focus.go b/internal/mcpserver/focus.go new file mode 100644 index 000000000..534188c27 --- /dev/null +++ b/internal/mcpserver/focus.go @@ -0,0 +1,23 @@ +package mcpserver + +import ( + "context" + + "github.com/YoanWai/agent-manager/internal/sessioncmd" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func addFocusSession(server *mcp.Server, noCaller error, sessions sessionCommands) { + addTool(server, noCaller, &mcp.Tool{ + Name: "focus_session", + Description: "Open a session in the user's Agent Manager window the way the enter key does, so the user lands on it: the groups above the session unfold, and a dialog the user is typing into stays open with the cursor moved under it. " + + "It changes what the user is looking at, so call it only when the user asked to be taken to a session, such as one you handed their question to.", + Annotations: toolAnnotations(false, false, false), + }, func(ctx context.Context, req *mcp.CallToolRequest, args sessionTargetArgs) (*mcp.CallToolResult, sessioncmd.Session, error) { + focused, err := sessions.Focus(args.SessionID, true) + if err != nil { + return nil, sessioncmd.Session{}, err + } + return textContent("focused " + sessioncmd.FormatSession(focused)), focused, nil + }) +} diff --git a/internal/mcpserver/mcpserver.go b/internal/mcpserver/mcpserver.go index 23a16394c..13bcac717 100644 --- a/internal/mcpserver/mcpserver.go +++ b/internal/mcpserver/mcpserver.go @@ -200,6 +200,7 @@ type sessionCommands interface { Wait(ctx context.Context, sessionID, targetID string, until []string, timeout time.Duration) (sessioncmd.WaitResult, error) MessageStatus(sessionID string, messageID int64) (sessioncmd.MessageState, error) Read(sessionID, targetID string) (sessioncmd.SessionScreen, error) + Focus(targetID string, enter bool) (sessioncmd.Session, error) Revive(sessionID, targetID string) (sessioncmd.Session, error) Kill(sessionID, targetID string) (sessioncmd.Session, error) Delete(sessionID, targetID string) (sessioncmd.Deletion, error) @@ -451,6 +452,7 @@ func newServerWithMailbox(sessionID, version string, proactive bool, terminals t } return textContent(sessioncmd.FormatSessionScreen(screen)), screen, nil }) + addFocusSession(server, noCaller, sessions) addTool(server, noCaller, &mcp.Tool{ Name: "send_session", @@ -912,29 +914,6 @@ func newServerWithMailbox(sessionID, version string, proactive bool, terminals t // addTool registers a tool that refuses outright when the server has no // calling session, so no tool, present or future, opens the workspace to a // CLI running outside Agent Manager. -func addTool[In, Out any](server *mcp.Server, noCaller error, tool *mcp.Tool, handler mcp.ToolHandlerFor[In, Out]) { - mcp.AddTool(server, tool, func(ctx context.Context, req *mcp.CallToolRequest, args In) (*mcp.CallToolResult, Out, error) { - if noCaller != nil { - var none Out - return nil, none, noCaller - } - return handler(ctx, req, args) - }) -} - -func toolAnnotations(readOnly, destructive, openWorld bool) *mcp.ToolAnnotations { - return &mcp.ToolAnnotations{ - ReadOnlyHint: readOnly, - DestructiveHint: &destructive, - IdempotentHint: readOnly, - OpenWorldHint: &openWorld, - } -} - -func textContent(message string) *mcp.CallToolResult { - return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: message}}} -} - // applyFailure carries the declarations a review call already applied // into its error, so a caller that set several at once knows which took // effect before the failing one. diff --git a/internal/mcpserver/mcpserver_nocaller_test.go b/internal/mcpserver/mcpserver_nocaller_test.go index 2215ac7d7..ca57a9ea2 100644 --- a/internal/mcpserver/mcpserver_nocaller_test.go +++ b/internal/mcpserver/mcpserver_nocaller_test.go @@ -24,6 +24,7 @@ func TestServerWithNoCallerKeepsTheWorkspaceClosed(t *testing.T) { {"create_session", map[string]any{"name": "x", "host": "box"}}, {"read_session", map[string]any{"session_id": "a1"}}, {"read_session", map[string]any{"session_id": "box::a1"}}, + {"focus_session", map[string]any{"session_id": "a1"}}, {"send_session", map[string]any{"session_id": "a1", "message": "hi"}}, {"send_session", map[string]any{"session_id": "box::a1", "message": "hi"}}, {"message_status", map[string]any{"message_id": 7}}, @@ -76,7 +77,7 @@ func TestServerWithNoCallerKeepsTheWorkspaceClosed(t *testing.T) { t.Errorf("%s is not checked with no caller", tool.Name) } } - if terminals.sentID != "" || sessions.killedID != "" || sessions.revivedID != "" || sessions.archivedID != "" { + if terminals.sentID != "" || sessions.killedID != "" || sessions.focusedID != "" || sessions.revivedID != "" || sessions.archivedID != "" { t.Fatalf("a refused call still reached the workspace: sent %q, killed %q, revived %q, archived %q", terminals.sentID, sessions.killedID, sessions.revivedID, sessions.archivedID) } diff --git a/internal/mcpserver/mcpserver_test.go b/internal/mcpserver/mcpserver_test.go index fe6bbf600..8da0fff88 100644 --- a/internal/mcpserver/mcpserver_test.go +++ b/internal/mcpserver/mcpserver_test.go @@ -103,6 +103,8 @@ type fakeSessionCommands struct { reservations []sessioncmd.Reservation revivedID string killedID string + focusedID string + focusEntered bool deletedID string archivedID string archived bool @@ -156,6 +158,11 @@ func (f *fakeSessionCommands) MessageStatus(_ string, messageID int64) (sessionc return sessioncmd.MessageState{MessageID: messageID, SessionID: "a1b2c3d4", State: "delivered"}, f.err } +func (f *fakeSessionCommands) Focus(id string, enter bool) (sessioncmd.Session, error) { + f.focusedID, f.focusEntered = id, enter + return f.created, f.err +} + func (f *fakeSessionCommands) Read(_ string, id string) (sessioncmd.SessionScreen, error) { f.readID = id return f.screen, f.err @@ -777,7 +784,7 @@ func TestListsFleetTools(t *testing.T) { names[tool.Name] = true } for _, want := range []string{ - "list_sessions", "create_session", "read_session", "send_session", + "list_sessions", "create_session", "read_session", "focus_session", "send_session", "revive_session", "kill_session", "delete_session", "archive_session", "move_session", "archive_self", "kill_self", "list_groups", "create_group", "delete_group", "message_status", "wait_for_session", "task", @@ -859,6 +866,7 @@ func TestSessionDescriptionsTeachWhenAndHowToChainTools(t *testing.T) { "list_sessions": {"Call first", "create_session"}, "create_session": {"without waiting for the user", "worktree", "cannot see this conversation", "read_session"}, "read_session": {"after create_session", "current screen"}, + "focus_session": {"only when the user asked", "stays open"}, "send_session": {"self-contained instruction", "read_session", "at rest", "ordinary work", "five messages a minute"}, "message_status": {"delivered", "queued"}, "wait_for_session": {"instead of calling read_session in a loop", "timeout is a normal answer", "reached false"}, @@ -958,6 +966,13 @@ func TestSessionToolsExposeStructuredResultsAndForwardArguments(t *testing.T) { t.Fatalf("read_session = %q, isError=%v", text, isError) } + if text, isError := callText(t, session, "focus_session", map[string]any{"session_id": "a1b2c3d4"}); isError || !strings.HasPrefix(text, "focused ") { + t.Fatalf("focus_session = %q, isError=%v", text, isError) + } + if fake.focusedID != "a1b2c3d4" || !fake.focusEntered { + t.Fatalf("focus args = id %q enter %v", fake.focusedID, fake.focusEntered) + } + if text, isError := callText(t, session, "wait_for_session", map[string]any{ "session_id": "a1b2c3d4", "until": []string{"finished"}, "timeout_s": 30, }); isError || !strings.Contains(text, "finished") { diff --git a/internal/mcpserver/tools.go b/internal/mcpserver/tools.go new file mode 100644 index 000000000..3d86a8be9 --- /dev/null +++ b/internal/mcpserver/tools.go @@ -0,0 +1,30 @@ +package mcpserver + +import ( + "context" + + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func addTool[In, Out any](server *mcp.Server, noCaller error, tool *mcp.Tool, handler mcp.ToolHandlerFor[In, Out]) { + mcp.AddTool(server, tool, func(ctx context.Context, req *mcp.CallToolRequest, args In) (*mcp.CallToolResult, Out, error) { + if noCaller != nil { + var none Out + return nil, none, noCaller + } + return handler(ctx, req, args) + }) +} + +func toolAnnotations(readOnly, destructive, openWorld bool) *mcp.ToolAnnotations { + return &mcp.ToolAnnotations{ + ReadOnlyHint: readOnly, + DestructiveHint: &destructive, + IdempotentHint: readOnly, + OpenWorldHint: &openWorld, + } +} + +func textContent(message string) *mcp.CallToolResult { + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: message}}} +} diff --git a/internal/sessioncmd/focus.go b/internal/sessioncmd/focus.go new file mode 100644 index 000000000..6b3bd2393 --- /dev/null +++ b/internal/sessioncmd/focus.go @@ -0,0 +1,76 @@ +package sessioncmd + +import ( + "database/sql" + "encoding/json" + "errors" + "fmt" + "net" + "strings" + "time" +) + +// FocusRequest is what the focus endpoint reads from a connection, and +// FocusAnswer what it writes back on the same one once the manager acted. +type FocusRequest struct { + ID string `json:"id"` + Enter bool `json:"enter"` +} + +type FocusAnswer struct { + Error string `json:"error,omitempty"` +} + +// FocusAnswerWait bounds how long the manager has to act on a request. The +// endpoint drops a request it could not hand over in that time, so a caller +// told it timed out never sees the list move later. +const FocusAnswerWait = 5 * time.Second + +var errNoManager = errors.New("no Agent Manager is running to bring the session forward") + +// Focus brings a session forward in the running manager: the groups above +// it unfold and the cursor lands on its row, and with enter the session +// opens the way the enter key opens it. The manager answers with what it +// did. It acts as no session, so a script outside Agent Manager can run it. +func (s *Sessions) Focus(targetID string, enter bool) (Session, error) { + runtime, err := s.open() + if err != nil { + return Session{}, err + } + defer runtime.Close() + id := strings.TrimSpace(targetID) + if id == "" { + return Session{}, fmt.Errorf("session_id is empty; call %s to get one", runtime.words.ListSessions) + } + target, err := runtime.store.Get(id) + if errors.Is(err, sql.ErrNoRows) { + return Session{}, fmt.Errorf("session %s does not exist; call %s for current ids", id, runtime.words.ListSessions) + } + if err != nil { + return Session{}, err + } + if target.Archived { + return Session{}, fmt.Errorf("session %s is archived, so the list has no row for it; restore it with %s first", id, runtime.words.Restore) + } + // Nothing listening, or a socket a manager left behind when it exited, + // both mean no manager is there to answer. + conn, err := net.Dial("unix", runtime.driver.FocusEndpoint()) + if err != nil { + return Session{}, errNoManager + } + defer conn.Close() + if err := conn.SetDeadline(time.Now().Add(FocusAnswerWait + time.Second)); err != nil { + return Session{}, err + } + if err := json.NewEncoder(conn).Encode(FocusRequest{ID: target.ID, Enter: enter}); err != nil { + return Session{}, fmt.Errorf("send the request to Agent Manager: %w", err) + } + var answer FocusAnswer + if err := json.NewDecoder(conn).Decode(&answer); err != nil { + return Session{}, fmt.Errorf("Agent Manager did not answer: %w", err) + } + if answer.Error != "" { + return Session{}, errors.New(answer.Error) + } + return runtime.sessionInfo(target, runtime.driver.Exists(target.ID), false), nil +} diff --git a/internal/sessioncmd/focus_endpoint.go b/internal/sessioncmd/focus_endpoint.go new file mode 100644 index 000000000..2d7ba7a5e --- /dev/null +++ b/internal/sessioncmd/focus_endpoint.go @@ -0,0 +1,73 @@ +package sessioncmd + +import ( + "encoding/json" + "errors" + "net" + "os" + "time" +) + +// FocusDelivery is one request handed to the manager, with the channel the +// outcome goes back on. A delivery taken after Expires is dropped: its +// caller has already been told it timed out. +type FocusDelivery struct { + Request FocusRequest + Answer chan<- error + Expires time.Time +} + +// ListenFocus serves focus requests on path until the returned stop runs. +// Each connection carries one request and gets the outcome back on itself, +// so no request can be mistaken for another. A manager already answering on +// path keeps it; a socket left by one that exited is replaced. +func ListenFocus(path string, deliver func(FocusDelivery)) (stop func()) { + if conn, err := net.Dial("unix", path); err == nil { + conn.Close() + return func() {} + } + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return func() {} + } + listener, err := net.Listen("unix", path) + if err != nil { + return func() {} + } + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go answerFocus(conn, deliver) + } + }() + // Closing a listener Go created also unlinks its socket. + return func() { listener.Close() } +} + +func answerFocus(conn net.Conn, deliver func(FocusDelivery)) { + defer conn.Close() + expires := time.Now().Add(FocusAnswerWait) + if err := conn.SetDeadline(expires.Add(time.Second)); err != nil { + return + } + var request FocusRequest + if err := json.NewDecoder(conn).Decode(&request); err != nil { + return + } + answer := make(chan error, 1) + // The program stops taking messages while it is suspended in a full + // screen attach, so the hand-over must not hold up the reply. + go deliver(FocusDelivery{Request: request, Answer: answer, Expires: expires}) + var reply FocusAnswer + select { + case err := <-answer: + if err != nil { + reply.Error = err.Error() + } + case <-time.After(time.Until(expires)): + reply.Error = "Agent Manager did not act on the request in time; it does while a session is attached full screen only once you detach, and then drops it" + } + _ = json.NewEncoder(conn).Encode(reply) +} diff --git a/internal/sessioncmd/focus_endpoint_test.go b/internal/sessioncmd/focus_endpoint_test.go new file mode 100644 index 000000000..df49a1445 --- /dev/null +++ b/internal/sessioncmd/focus_endpoint_test.go @@ -0,0 +1,99 @@ +package sessioncmd + +import ( + "encoding/json" + "net" + "os" + "path/filepath" + "testing" +) + +// A Unix socket path stops near 104 bytes, past which t.TempDir's names run. +func focusSocketPath(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("", "amfocus") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + return filepath.Join(dir, "agentmgr.focus") +} + +func askFocus(t *testing.T, path string, request FocusRequest) <-chan FocusAnswer { + t.Helper() + answers := make(chan FocusAnswer, 1) + go func() { + var answer FocusAnswer + conn, err := net.Dial("unix", path) + if err != nil { + answer.Error = "dial: " + err.Error() + answers <- answer + return + } + defer conn.Close() + if err := json.NewEncoder(conn).Encode(request); err != nil { + answer.Error = "send: " + err.Error() + } else if err := json.NewDecoder(conn).Decode(&answer); err != nil { + answer.Error = "read: " + err.Error() + } + answers <- answer + }() + return answers +} + +// Each connection carries one request and reads back the outcome the +// manager handed back for that request, a refusal included. +func TestFocusEndpointAnswersEachRequestWithItsOutcome(t *testing.T) { + path := focusSocketPath(t) + deliveries := make(chan FocusDelivery, 1) + stop := ListenFocus(path, func(delivery FocusDelivery) { deliveries <- delivery }) + defer stop() + + answers := askFocus(t, path, FocusRequest{ID: "a", Enter: true}) + delivery := <-deliveries + if delivery.Request != (FocusRequest{ID: "a", Enter: true}) { + t.Fatalf("delivered %+v, want a entered", delivery.Request) + } + delivery.Answer <- nil + if answer := <-answers; answer.Error != "" { + t.Fatalf("answered %q, want success", answer.Error) + } + + answers = askFocus(t, path, FocusRequest{ID: "b"}) + delivery = <-deliveries + delivery.Answer <- os.ErrNotExist + if answer := <-answers; answer.Error != os.ErrNotExist.Error() { + t.Fatalf("answered %q, want the refusal", answer.Error) + } +} + +// One manager answers per tmux server: a second one leaves a live endpoint +// to its owner, and a socket left by a manager that exited is taken over. +func TestFocusEndpointKeepsALiveOwnerAndReplacesAStaleSocket(t *testing.T) { + path := focusSocketPath(t) + first := make(chan FocusDelivery, 1) + stopFirst := ListenFocus(path, func(delivery FocusDelivery) { first <- delivery }) + second := make(chan FocusDelivery, 1) + stopSecond := ListenFocus(path, func(delivery FocusDelivery) { second <- delivery }) + defer stopSecond() + askFocus(t, path, FocusRequest{ID: "a"}) + (<-first).Answer <- nil + if len(second) != 0 { + t.Fatal("the second manager took a request from the live endpoint") + } + stopFirst() + + stale, err := net.Listen("unix", path) + if err != nil { + t.Fatal(err) + } + stale.(*net.UnixListener).SetUnlinkOnClose(false) + stale.Close() + third := make(chan FocusDelivery, 1) + stopThird := ListenFocus(path, func(delivery FocusDelivery) { third <- delivery }) + defer stopThird() + askFocus(t, path, FocusRequest{ID: "b"}) + if delivery := <-third; delivery.Request.ID != "b" { + t.Fatalf("request = %+v, want b", delivery.Request) + } +} diff --git a/internal/sessioncmd/focus_test.go b/internal/sessioncmd/focus_test.go new file mode 100644 index 000000000..f46a2d13c --- /dev/null +++ b/internal/sessioncmd/focus_test.go @@ -0,0 +1,84 @@ +package sessioncmd + +import ( + "encoding/json" + "net" + "strings" + "testing" +) + +// fakeFocusManager answers one request on the harness server's endpoint +// with reply, hands over the request it read, and then stops listening. +func fakeFocusManager(t *testing.T, h *sessionHarness, reply FocusAnswer) <-chan FocusRequest { + t.Helper() + listener, err := net.Listen("unix", h.driver.FocusEndpoint()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { listener.Close() }) + requests := make(chan FocusRequest, 1) + go func() { + defer close(requests) + defer listener.Close() + conn, err := listener.Accept() + if err != nil { + return + } + defer conn.Close() + var request FocusRequest + if json.NewDecoder(conn).Decode(&request) == nil { + requests <- request + _ = json.NewEncoder(conn).Encode(reply) + } + }() + return requests +} + +// A request reaches only a manager that is listening, for a session the +// list can show; anything else is refused before anything is sent. +func TestFocusRefusesWhatTheManagerCannotShow(t *testing.T) { + h := newSessionHarness(t) + worker, err := h.sessions.Create(h.caller.ID, CreateSessionOptions{Name: "worker"}) + if err != nil { + t.Fatalf("Create: %v", err) + } + if _, err := h.sessions.Focus(worker.ID, true); err == nil || !strings.Contains(err.Error(), "no Agent Manager is running") { + t.Fatalf("Focus with no manager = %v", err) + } + if _, err := h.sessions.Focus("feedface", true); err == nil || !strings.Contains(err.Error(), "does not exist") { + t.Fatalf("Focus of an unknown id = %v", err) + } + if _, err := h.sessions.Archive(h.caller.ID, worker.ID, true); err != nil { + t.Fatalf("Archive: %v", err) + } + if _, err := h.sessions.Focus(worker.ID, true); err == nil || !strings.Contains(err.Error(), "archived") { + t.Fatalf("Focus of an archived session = %v", err) + } +} + +// The manager's answer is the result: success names the session, and a +// refusal comes back as the error, so the caller never reports more than +// the manager did. +func TestFocusReportsWhatTheManagerAnswered(t *testing.T) { + h := newSessionHarness(t) + worker, err := h.sessions.Create(h.caller.ID, CreateSessionOptions{Name: "worker"}) + if err != nil { + t.Fatalf("Create: %v", err) + } + requests := fakeFocusManager(t, h, FocusAnswer{}) + focused, err := h.sessions.Focus(worker.ID, true) + if err != nil || focused.ID != worker.ID { + t.Fatalf("Focus = %+v, %v; want the worker", focused, err) + } + if got := <-requests; got != (FocusRequest{ID: worker.ID, Enter: true}) { + t.Fatalf("manager read %+v, want the worker entered", got) + } + for range requests { + } + + refusal := "session " + worker.ID + " is selected under a dialog" + fakeFocusManager(t, h, FocusAnswer{Error: refusal}) + if _, err := h.sessions.Focus(worker.ID, true); err == nil || err.Error() != refusal { + t.Fatalf("Focus under a refusal = %v, want %q", err, refusal) + } +} diff --git a/internal/tmux/platform_unix.go b/internal/tmux/platform_unix.go index 47f0926c1..c1d5c8da3 100644 --- a/internal/tmux/platform_unix.go +++ b/internal/tmux/platform_unix.go @@ -135,6 +135,13 @@ func (d *Driver) SocketPath() string { return path } +// FocusEndpoint is the Unix socket the manager running this server answers +// focus requests on. It sits beside the server's own socket, so it is as +// private as that socket's directory and shares its short path. +func (d *Driver) FocusEndpoint() string { + return socketPathFromEnv(d.socket) + ".focus" +} + // socketPathFromEnv rebuilds what tmux resolves -L to, without asking a // server that may not be running. tmux reports the path with its symlinks // resolved, so this does too and the two agree once a server exists. diff --git a/internal/tmux/platform_windows.go b/internal/tmux/platform_windows.go index 223f01bc2..1dd6a1718 100644 --- a/internal/tmux/platform_windows.go +++ b/internal/tmux/platform_windows.go @@ -294,6 +294,12 @@ func (d *Driver) SocketPath() string { return path } +// FocusEndpoint is the Unix socket the manager running this namespace +// answers focus requests on, beside the registry psmux keeps for it. +func (d *Driver) FocusEndpoint() string { + return d.SocketPath() + ".focus" +} + // psmuxDir is where psmux keeps its registry: PSMUX_DATA_DIR when it is an // absolute path, else ~\.psmux, and \.psmux with no home, as psmux does. func psmuxDir() string { diff --git a/internal/ui/focus_adapter.go b/internal/ui/focus_adapter.go index 22784e766..3f5d3a6ab 100644 --- a/internal/ui/focus_adapter.go +++ b/internal/ui/focus_adapter.go @@ -410,7 +410,10 @@ func (m *Model) enterFocus(sess store.Session) tea.Cmd { // applyFocusEffect enters focus once the dead-pane probe has run. func (m *Model) applyFocusEffect(request focusruntime.ProbeRequest, err error) tea.Cmd { - return focusruntime.ApplyProbe(focusProbeHost{m}, request, err) + cmd := focusruntime.ApplyProbe(focusProbeHost{m}, request, err) + selected, ok := m.selected() + m.answerForward(request.SessionID, m.forwardOutcome(request.SessionID, m.focused() && ok && selected.ID == request.SessionID)) + return cmd } // applyDetachEffect opens what a session asked for before it detached. diff --git a/internal/ui/model.go b/internal/ui/model.go index 885c131a3..15e2943e9 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -100,6 +100,8 @@ type focusState struct { // imeCursor is the cell the input method opens beside, owned here // because the frame writer publishes into it. imeCursor *uiframe.CursorAnchor + // forward is the focus request waiting on its open. + forward pendingForward } type mouseCapture struct { diff --git a/internal/ui/rail/policy.go b/internal/ui/rail/policy.go index 95e85d230..b075fd722 100644 --- a/internal/ui/rail/policy.go +++ b/internal/ui/rail/policy.go @@ -440,6 +440,41 @@ func (m *Model) SetArchived(show bool) { m.rebuildRows() } +// RevealSession puts the cursor on a session's row for a request from +// outside the list: it unfolds the groups above the session, and drops a +// status filter only when that filter hides the row. found is false when +// the list still has no row for it. +func (m *Model) RevealSession(id, group string) (decision Decision, found bool) { + previous, previousOK := m.Selected() + collapsedChanged := false + for ancestor := group; ancestor != ""; ancestor = ParentGroup(ancestor) { + if m.collapsed[ancestor] { + delete(m.collapsed, ancestor) + collapsedChanged = true + } + } + m.rebuildRows() + found = m.FocusSession(id) + if !found && m.filter != statusFilterAll { + m.filter = statusFilterAll + m.rebuildRows() + found = m.FocusSession(id) + } + current, currentOK := m.Selected() + decision = Decision{ + Consumed: true, + SelectionChanged: previousOK != currentOK || previous != current, + Selection: current, + } + if decision.SelectionChanged { + decision.SelectionEffect = SelectionEffectPreview + } + if collapsedChanged { + decision.Mutations = []Mutation{m.saveFolds()} + } + return decision, found +} + func (m *Model) ForgetGroups(paths []string) Decision { changed := false for _, removed := range paths { diff --git a/internal/ui/rail_adapter_forward.go b/internal/ui/rail_adapter_forward.go new file mode 100644 index 000000000..74a626455 --- /dev/null +++ b/internal/ui/rail_adapter_forward.go @@ -0,0 +1,165 @@ +package ui + +import ( + "errors" + "fmt" + "time" + + "github.com/YoanWai/agent-manager/internal/sessioncmd" + uifocus "github.com/YoanWai/agent-manager/internal/ui/focus" + uigeometry "github.com/YoanWai/agent-manager/internal/ui/geometry" + uihelp "github.com/YoanWai/agent-manager/internal/ui/help" + uinotices "github.com/YoanWai/agent-manager/internal/ui/notices" + uisurface "github.com/YoanWai/agent-manager/internal/ui/surface" + tea "github.com/charmbracelet/bubbletea" +) + +// focusRequestMsg carries one request from the focus endpoint into Update. +type focusRequestMsg struct{ sessioncmd.FocusDelivery } + +// pendingForward is a focus request whose open runs on the effect lane: its +// caller hears back once the open lands or fails. +type pendingForward struct { + sessionID string + answer chan<- error +} + +// overlayLayers bounds the esc presses bringForward spends closing what +// covers the list. Each press closes at most one layer; the bound is for a +// layer whose esc does not close it, which would otherwise loop. +const overlayLayers = 8 + +func (m *Model) routeForwardMsg(msg tea.Msg) (tea.Model, tea.Cmd, bool) { + request, ok := msg.(focusRequestMsg) + if !ok { + return nil, nil, false + } + if time.Now().After(request.Expires) { + return routed(m, nil) + } + if m.effects.Quitting { + request.Answer <- errors.New("Agent Manager is quitting") + return routed(m, nil) + } + if pending := m.focus.forward.sessionID; pending != "" { + m.answerForward(pending, fmt.Errorf("session %s was selected but not opened: another request to bring a session forward took its place", pending)) + } + opening, jump, err := m.bringForward(request.Request.ID, request.Request.Enter) + if opening { + m.focus.forward = pendingForward{sessionID: request.Request.ID, answer: request.Answer} + } else { + request.Answer <- err + } + cmds := []tea.Cmd{jump} + if sess, ok := m.selected(); ok && sess.ID != m.workspace.procFor { + m.syncPollInput() + gen := m.focus.pane.MovePreview() + cmds = append(cmds, m.previewCmd(sess, gen), m.diffRefreshCmd()) + } + return routed(m, tea.Batch(cmds...)) +} + +// bringForward serves a request from another process: it unfolds the +// groups hiding the session, moves the cursor to its row and, when asked, +// opens it the way the enter key does. Layers that hold nothing the user +// typed (help, messages, the search, the row menu, a lifted row, a divider +// drag) close the way esc closes them. A dialog that may hold unfinished +// input stays open with the cursor moved under it, and the session is not +// opened over it. opening reports an open handed to the effect lane, whose +// completion answers the request; otherwise err is the answer. +func (m *Model) bringForward(id string, enter bool) (opening bool, cmd tea.Cmd, err error) { + sess, ok := m.sessionByID(id) + if !ok || (sess.Archived && !m.rail.ShowArchived()) { + return false, nil, fmt.Errorf("session %s has no row in Agent Manager's list yet", id) + } + cmds := m.closeInputFreeLayers() + if focused, ok := m.selected(); m.focused() && (!enter || !ok || focused.ID != sess.ID) { + if top, _ := m.top(); !isFocusSurface(top) { + return false, tea.Batch(cmds...), fmt.Errorf("a dialog is open over the session Agent Manager is in, and it is left as it is; close it to move to session %s", sess.ID) + } + // A select is a request to look at the list, and a focus on another + // session would leave the keyboard pinned to the one the user was in + // while the list claims a different row. + cmds = append(cmds, m.leaveFocus()) + cmds = append(cmds, m.closeInputFreeLayers()...) + } + if m.focused() { + return false, tea.Batch(cmds...), nil + } + decision, found := m.rail.RevealSession(sess.ID, sess.Group) + m.queueRail(decision.Mutations, 0, false) + if !found { + return false, tea.Batch(cmds...), fmt.Errorf("session %s has no row in Agent Manager's list", sess.ID) + } + if !enter { + return false, tea.Batch(cmds...), nil + } + if !m.listUncovered() { + return false, tea.Batch(cmds...), fmt.Errorf("session %s is selected under a dialog open in Agent Manager, which is left as it is; close it to open the session", sess.ID) + } + // Enter attaches instead when Settings swaps the pair. + open := m.focusSelected + if !m.enterFocuses() { + open = m.attachSelected + } + _, openCmd := open() + return true, tea.Batch(append(cmds, openCmd)...), nil +} + +func (m *Model) closeInputFreeLayers() []tea.Cmd { + var cmds []tea.Cmd + for presses := 0; presses < overlayLayers && m.inputFreeLayerOpen(); presses++ { + _, cmd := m.handleKey(tea.KeyMsg{Type: tea.KeyEsc}) + cmds = append(cmds, cmd) + } + return cmds +} + +// inputFreeLayerOpen reports whether a layer that holds nothing the user +// typed stands over the rows, so esc can close it without losing work. +// Focus is not one; esc there belongs to the pane. +func (m *Model) inputFreeLayerOpen() bool { + if top, ok := m.top(); ok { + switch top.(type) { + case *uihelp.Surface, *uinotices.Surface, *uigeometry.Surface: + return true + } + return false + } + return m.base == baseList && (m.rail.Busy() || m.rail.Search() != "") +} + +// listUncovered reports whether the list is on screen with nothing over it, +// which is where the enter key opens the selected row. +func (m *Model) listUncovered() bool { + return m.base == baseList && len(m.surfaces) == 0 && !m.inputFreeLayerOpen() +} + +func isFocusSurface(s uisurface.Surface) bool { + _, ok := s.(*uifocus.Surface) + return ok +} + +// answerForward settles the pending request for a session once its open +// landed or failed. +func (m *Model) answerForward(sessionID string, err error) { + pending := m.focus.forward + if pending.answer == nil || pending.sessionID != sessionID { + return + } + m.focus.forward = pendingForward{} + pending.answer <- err +} + +// forwardOutcome is what a pending request for a session hears once its +// open ran: nothing when it opened, else the reason the status bar holds. +func (m *Model) forwardOutcome(sessionID string, opened bool) error { + if opened { + return nil + } + reason := m.errBar.text + if reason == "" { + reason = "Agent Manager moved on before it opened" + } + return fmt.Errorf("session %s was selected but not opened: %s", sessionID, reason) +} diff --git a/internal/ui/rail_adapter_forward_test.go b/internal/ui/rail_adapter_forward_test.go new file mode 100644 index 000000000..e8eb537af --- /dev/null +++ b/internal/ui/rail_adapter_forward_test.go @@ -0,0 +1,204 @@ +package ui + +import ( + "strings" + "testing" + "time" + + "github.com/YoanWai/agent-manager/internal/sessioncmd" + "github.com/YoanWai/agent-manager/internal/store" +) + +// focusRequestModel lays out a root session and one filed two groups deep, +// with both groups folded so the deep one has no row until it is unfolded. +func focusRequestModel(t *testing.T) (*Model, store.Session) { + t.Helper() + m := buildModel(t) + if err := m.services.store.CreateGroup("backend/api", ""); err != nil { + t.Fatal(err) + } + m.applyCmd(t, m.refreshCmd()) + createSession(t, m, "top", t.TempDir(), "") + createSession(t, m, "deep", t.TempDir(), "backend/api") + var deep store.Session + for _, sess := range m.workspace.sessions { + if sess.Name == "deep" { + deep = sess + } + } + if deep.ID == "" { + t.Fatal("deep session missing") + } + m.rail.SetCollapsed("backend", true) + m.rail.SetCollapsed("backend/api", true) + m.selectSessionRow(t, "top") + return m, deep +} + +// serveFocusRequest hands the model a request the way the focus endpoint +// does, runs the open it starts, and returns the answer the endpoint would +// write back. +func (m *Model) serveFocusRequest(t *testing.T, id string, enter bool) error { + t.Helper() + answer := make(chan error, 1) + updated, cmd := m.Update(focusRequestMsg{sessioncmd.FocusDelivery{ + Request: sessioncmd.FocusRequest{ID: id, Enter: enter}, + Answer: answer, + Expires: time.Now().Add(time.Minute), + }}) + *m = *updated.(*Model) + if len(answer) == 0 && cmd != nil { + m.applyTestMsg(t, cmd()) + m.drainEffects(t) + } + select { + case err := <-answer: + return err + default: + t.Fatal("the request was not answered") + return nil + } +} + +// A focus request lands on the session from wherever the user is, closing +// the layers that hold no typed input the way esc would and unfolding the +// groups that hide the row, then opens it the way enter does. +func TestFocusRequestUnfoldsAndEntersFromEveryStartingState(t *testing.T) { + t.Parallel() + for _, start := range []struct { + name string + setup func(t *testing.T, m *Model) + }{ + {"list", func(t *testing.T, m *Model) {}}, + {"search hiding the row", func(t *testing.T, m *Model) { + m.rail.SetSearch("top", true) + }}, + {"help", func(t *testing.T, m *Model) { + m.openHelp() + }}, + {"focused on another session", func(t *testing.T, m *Model) { + _, cmd := m.focusSelected() + m.applyCmd(t, cmd) + if !m.focused() { + t.Fatalf("setup: not focused, err = %q", m.errBar.text) + } + }}, + } { + t.Run(start.name, func(t *testing.T) { + m, deep := focusRequestModel(t) + start.setup(t, m) + if err := m.serveFocusRequest(t, deep.ID, true); err != nil { + t.Fatalf("focus answered %v", err) + } + if !m.focused() { + t.Fatalf("screen = %v, err = %q; want focus", m.screenID(), m.errBar.text) + } + if sess, ok := m.selected(); !ok || sess.ID != deep.ID { + t.Fatalf("cursor is on %+v, want deep", sess) + } + if m.rail.IsCollapsed("backend") || m.rail.IsCollapsed("backend/api") { + t.Fatalf("groups above the session are still folded: %v", m.rail.Collapsed()) + } + if m.rail.Search() != "" || m.rail.Searching() { + t.Fatalf("search = %q (field open %v), want it cleared", m.rail.Search(), m.rail.Searching()) + } + }) + } +} + +// Without enter the request only selects, so a focused pane is left for the +// list even when it is the session asked for: staying would keep every key +// going to that agent while the request reported a selection. +func TestSelectRequestLeavesFocusAndStaysOnTheList(t *testing.T) { + t.Parallel() + for _, start := range []string{"top", "deep"} { + t.Run("focused on "+start, func(t *testing.T) { + m, deep := focusRequestModel(t) + if start == "deep" { + if err := m.serveFocusRequest(t, deep.ID, true); err != nil { + t.Fatalf("setup: focus answered %v", err) + } + } else { + _, cmd := m.focusSelected() + m.applyCmd(t, cmd) + } + if !m.focused() { + t.Fatalf("setup: not focused, err = %q", m.errBar.text) + } + if err := m.serveFocusRequest(t, deep.ID, false); err != nil { + t.Fatalf("select answered %v", err) + } + if !m.onList() { + t.Fatalf("screen = %v, want the list", m.screenID()) + } + if sess, ok := m.selected(); !ok || sess.ID != deep.ID { + t.Fatalf("cursor is on %+v, want deep", sess) + } + }) + } +} + +// A dialog may hold input the user has not finished, so a request never +// closes it: the cursor moves under it, as a clicked banner always did. A +// focus is answered with why the session was not opened over it. +func TestFocusRequestKeepsADialogHoldingInput(t *testing.T) { + t.Parallel() + for _, enter := range []bool{false, true} { + t.Run(map[bool]string{false: "select", true: "focus"}[enter], func(t *testing.T) { + m, deep := focusRequestModel(t) + m.openForm() + m.form().SetName("half typed") + err := m.serveFocusRequest(t, deep.ID, enter) + if enter != (err != nil && strings.Contains(err.Error(), "dialog")) { + t.Fatalf("answer = %v, want the dialog named only for a focus", err) + } + if m.form() == nil || m.form().Name() != "half typed" { + t.Fatalf("screen = %v; want the form kept with its text", m.screenID()) + } + if sess, ok := m.selected(); !ok || sess.ID != deep.ID { + t.Fatalf("cursor is on %+v, want deep under the form", sess) + } + }) + } +} + +// A status filter that hides the session is dropped rather than leaving the +// request with nowhere to land. +func TestFocusRequestDropsAStatusFilterHidingTheRow(t *testing.T) { + t.Parallel() + m, deep := focusRequestModel(t) + m.rail.SetCollapsed("backend", false) + m.rail.SetCollapsed("backend/api", false) + m.rail.SetFilteringAttention(true) + for _, sess := range m.sessionRows() { + if sess.ID == deep.ID { + t.Fatal("setup: the attention filter still shows the idle session") + } + } + if err := m.serveFocusRequest(t, deep.ID, false); err != nil { + t.Fatalf("select answered %v", err) + } + if sess, ok := m.selected(); !ok || sess.ID != deep.ID { + t.Fatalf("cursor is on %+v, want deep", sess) + } +} + +// A request the program could not take in time has already been answered +// as timed out, so it must not move the list when it finally arrives. +func TestExpiredFocusRequestIsDropped(t *testing.T) { + t.Parallel() + m, deep := focusRequestModel(t) + answer := make(chan error, 1) + updated, _ := m.Update(focusRequestMsg{sessioncmd.FocusDelivery{ + Request: sessioncmd.FocusRequest{ID: deep.ID, Enter: true}, + Answer: answer, + Expires: time.Now().Add(-time.Second), + }}) + m = updated.(*Model) + if sess, ok := m.selected(); !ok || sess.Name != "top" || !m.onList() { + t.Fatalf("an expired request moved the list: cursor %+v, screen %v", sess, m.screenID()) + } + if len(answer) != 0 { + t.Fatal("an expired request was answered a second time") + } +} diff --git a/internal/ui/session_adapter.go b/internal/ui/session_adapter.go index d67627912..758dab9a9 100644 --- a/internal/ui/session_adapter.go +++ b/internal/ui/session_adapter.go @@ -733,6 +733,12 @@ func (m *Model) reconcileListing(msg *refreshMsg) { // out. The fences are compared here, on the completion rather than the // request, because the user may have moved the screen while it waited. func (m *Model) applyAttachEffect(request uilifecycle.AttachRequest, result uilifecycle.AttachResult, err error) tea.Cmd { + cmd := m.startAttach(request, result, err) + m.answerForward(request.ID, m.forwardOutcome(request.ID, cmd != nil)) + return cmd +} + +func (m *Model) startAttach(request uilifecycle.AttachRequest, result uilifecycle.AttachResult, err error) tea.Cmd { if err != nil { m.reportErr(err.Error()) return nil diff --git a/internal/ui/updates.go b/internal/ui/updates.go index ea8844c93..1f50a1563 100644 --- a/internal/ui/updates.go +++ b/internal/ui/updates.go @@ -40,6 +40,7 @@ var messageRoutes = []func(*Model, tea.Msg) (tea.Model, tea.Cmd, bool){ (*Model).routeStartupMsg, (*Model).routePreviewMsg, (*Model).routeRefreshMsg, + (*Model).routeForwardMsg, (*Model).routeNoticesMsg, (*Model).routePasteMsg, (*Model).routeFocusMsg, diff --git a/internal/ui/workspace_adapter.go b/internal/ui/workspace_adapter.go index 5f06956ed..a38b6f13f 100644 --- a/internal/ui/workspace_adapter.go +++ b/internal/ui/workspace_adapter.go @@ -194,11 +194,17 @@ type refreshMsg struct { func (m *Model) StartPoller(ctx context.Context, send func(tea.Msg)) <-chan struct{} { m.focus.runtime.Watch = newFocusWatch(m.services.tmux, send) m.syncPollInput() + stopFocusEndpoint := sessioncmd.ListenFocus(m.services.tmux.FocusEndpoint(), func(delivery sessioncmd.FocusDelivery) { + send(focusRequestMsg{delivery}) + }) results := m.poller.results(ctx) done := make(chan struct{}) go func() { defer close(done) defer m.focus.runtime.Watch.Close() + // Removing the socket with the poller tells a later caller no + // manager is running, rather than one that never acts. + defer stopFocusEndpoint() for result := range results { send(pollMessage(result)) } @@ -374,14 +380,8 @@ func (m *Model) routeRefreshMsg(msg tea.Msg) (tea.Model, tea.Cmd, bool) { m.settleInstall() m.rebuildRows() if msg.focusID != "" { - focused, ok := m.selected() - // Moving the cursor under a focused pane would leave the - // keyboard pinned to the session the user was in while the - // list claims another. The click steps back to the list, and - // only once its session turns out to have a row to land on. - if m.focusSession(msg.focusID) && m.focused() && (!ok || focused.ID != msg.focusID) { - focusExit = m.leaveFocus() - } + _, jump, _ := m.bringForward(msg.focusID, false) + focusExit = tea.Batch(focusExit, jump) } reviewStatuses := m.reviewStatusesCmd() // A pass that ran with a stale selection (a session created this From d8c06fbaa1f2529db6cbf8a2b82e51bb791919b8 Mon Sep 17 00:00:00 2001 From: Yoan Wainmann <106609173+YoanWai@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:49:31 +0200 Subject: [PATCH 2/4] feat(cli): reach the one running manager and keep a click in focus Each manager window now listens on its own socket, named after its process, beside the tmux server's socket. The command connects to every one that answers. None answering means no window is running, and two or more means the request is refused naming their processes, since nothing says which window the user is looking at. A socket left by a manager that crashed refuses the connection, so it never stands in for a live one, and a manager starting up removes such sockets once they are a minute old. Nothing is ever signalled by a recorded process id. A manager that cannot listen now says so on the status bar instead of staying silently unreachable, and it creates the tmux socket directory the way tmux does when it starts before the tmux server. A clicked notification leaves the user in the session when that is the one it names, as it did before, and moves the cursor like a select otherwise. A request for a live session while the archive view is on switches back to the live list. Closes #725 --- docs/usage.md | 2 +- internal/sessioncmd/focus.go | 9 +- internal/sessioncmd/focus_endpoint.go | 112 ++++++++++++++++++-- internal/sessioncmd/focus_endpoint_test.go | 113 ++++++++++++++------- internal/sessioncmd/focus_test.go | 4 +- internal/ui/rail/policy.go | 11 +- internal/ui/rail_adapter_forward.go | 28 ++++- internal/ui/rail_adapter_forward_test.go | 78 ++++++++++++++ internal/ui/workspace_adapter.go | 10 +- 9 files changed, 305 insertions(+), 62 deletions(-) diff --git a/docs/usage.md b/docs/usage.md index b7541b884..dcbdb4ae9 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -360,7 +360,7 @@ agent-manager spawn --tool claude --group "Sprint Manager" --worktree \ --name ticket-123 --prompt "Fix TICKET-123 and open a pull request" --json ``` -`agent-manager focus ` brings a session forward in the running manager from any shell, so a key in another tool (a PR dashboard, a launcher, a script in a `T` tab) can take you to it. The command reaches the manager on a socket beside its tmux server, so the manager acts at once rather than on its next poll and answers with what it did. It leaves focus on any other session, closes help, messages, the search and the row menu the way esc would, unfolds the groups above the session, puts the cursor on its row and opens it the way enter does. A dialog that may hold unfinished input, such as the new-session form or the quick prompt, stays open with the cursor moved under it, and the session is not opened over it. `agent-manager select ` stops at the cursor, and leaves focus even on the session it names. Both exit non-zero with the reason when the id is unknown, the session is archived, no manager is running, or the manager could not do what was asked, as when `focus` finds a dialog open, and `--json` prints that reason as an `error` object too. +`agent-manager focus ` brings a session forward in the running manager from any shell, so a key in another tool (a PR dashboard, a launcher, a script in a `T` tab) can take you to it. The command reaches the manager on a socket beside its tmux server, so the manager acts at once rather than on its next poll and answers with what it did. It leaves focus on any other session, closes help, messages, the search and the row menu the way esc would, unfolds the groups above the session, drops a status filter or the archive view when that hides the row, puts the cursor on its row and opens it the way enter does, attaching instead when Settings swaps enter and attach. The command returns once the session is open, or with the reason it did not open. A dialog that may hold unfinished input, such as the new-session form or the quick prompt, stays open with the cursor moved under it, and the session is not opened over it. `agent-manager select ` stops at the cursor, and leaves focus even on the session it names. Both exit non-zero with the reason when the id is unknown, the session is archived, no manager window is running, or the manager could not do what was asked, as when `focus` finds a dialog open, and `--json` prints that reason as an `error` object too. Each manager window listens on its own socket, and when two windows run on the same tmux server the command refuses and names their processes rather than guess which one you are looking at. `agent-manager serve` has no window and does not answer. A clicked notification takes the same path as `select`, except that it leaves you in the session when that is the one it names. `snapshot --json` prints this machine's whole list as one JSON document: every session and terminal, archived ones included, the groups, and whether a manager is running here to deliver queued messages. It is what another manager reads over an SSH connection. diff --git a/internal/sessioncmd/focus.go b/internal/sessioncmd/focus.go index 6b3bd2393..95733b978 100644 --- a/internal/sessioncmd/focus.go +++ b/internal/sessioncmd/focus.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "net" "strings" "time" ) @@ -26,7 +25,7 @@ type FocusAnswer struct { // told it timed out never sees the list move later. const FocusAnswerWait = 5 * time.Second -var errNoManager = errors.New("no Agent Manager is running to bring the session forward") +var errNoManager = errors.New("no Agent Manager window is running to bring the session forward") // Focus brings a session forward in the running manager: the groups above // it unfold and the cursor lands on its row, and with enter the session @@ -52,11 +51,9 @@ func (s *Sessions) Focus(targetID string, enter bool) (Session, error) { if target.Archived { return Session{}, fmt.Errorf("session %s is archived, so the list has no row for it; restore it with %s first", id, runtime.words.Restore) } - // Nothing listening, or a socket a manager left behind when it exited, - // both mean no manager is there to answer. - conn, err := net.Dial("unix", runtime.driver.FocusEndpoint()) + conn, err := dialManager(runtime.driver.FocusEndpoint()) if err != nil { - return Session{}, errNoManager + return Session{}, err } defer conn.Close() if err := conn.SetDeadline(time.Now().Add(FocusAnswerWait + time.Second)); err != nil { diff --git a/internal/sessioncmd/focus_endpoint.go b/internal/sessioncmd/focus_endpoint.go index 2d7ba7a5e..196beffb8 100644 --- a/internal/sessioncmd/focus_endpoint.go +++ b/internal/sessioncmd/focus_endpoint.go @@ -3,8 +3,12 @@ package sessioncmd import ( "encoding/json" "errors" + "fmt" "net" "os" + "path/filepath" + "strconv" + "strings" "time" ) @@ -17,21 +21,34 @@ type FocusDelivery struct { Expires time.Time } -// ListenFocus serves focus requests on path until the returned stop runs. -// Each connection carries one request and gets the outcome back on itself, -// so no request can be mistaken for another. A manager already answering on -// path keeps it; a socket left by one that exited is replaced. -func ListenFocus(path string, deliver func(FocusDelivery)) (stop func()) { - if conn, err := net.Dial("unix", path); err == nil { - conn.Close() - return func() {} +// staleEndpointAge spares a socket another manager may have bound but not +// yet started listening on. +const staleEndpointAge = time.Minute + +// ListenFocus serves focus requests until the returned stop runs, on an +// endpoint of this process's own beside base, so every manager on one +// server stays reachable and a caller can tell when several are. Each +// connection carries one request and gets the outcome back on itself, so +// no request can be mistaken for another. +func ListenFocus(base string, deliver func(FocusDelivery)) (stop func(), err error) { + return listenFocusAs(base, os.Getpid(), deliver) +} + +func listenFocusAs(base string, pid int, deliver func(FocusDelivery)) (stop func(), err error) { + sweepStaleFocusEndpoints(base) + path := base + "." + strconv.Itoa(pid) + // tmux makes this directory with these permissions when its server + // starts, which may come after the manager does. + if err := os.MkdirAll(filepath.Dir(base), 0o700); err != nil { + return nil, err } + // A process that held this id before and crashed left its socket here. if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { - return func() {} + return nil, err } listener, err := net.Listen("unix", path) if err != nil { - return func() {} + return nil, err } go func() { for { @@ -43,7 +60,80 @@ func ListenFocus(path string, deliver func(FocusDelivery)) (stop func()) { } }() // Closing a listener Go created also unlinks its socket. - return func() { listener.Close() } + return func() { listener.Close() }, nil +} + +// focusEndpoints lists the sockets managers created beside base, live or +// left behind by one that crashed. +func focusEndpoints(base string) ([]string, error) { + dir, prefix := filepath.Dir(base), filepath.Base(base)+"." + entries, err := os.ReadDir(dir) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var paths []string + for _, entry := range entries { + pid, ok := strings.CutPrefix(entry.Name(), prefix) + if !ok { + continue + } + if _, err := strconv.Atoi(pid); err != nil { + continue + } + paths = append(paths, filepath.Join(dir, entry.Name())) + } + return paths, nil +} + +func sweepStaleFocusEndpoints(base string) { + paths, err := focusEndpoints(base) + if err != nil { + return + } + for _, path := range paths { + info, err := os.Stat(path) + if err != nil || time.Since(info.ModTime()) < staleEndpointAge { + continue + } + if conn, err := net.Dial("unix", path); err == nil { + conn.Close() + continue + } + os.Remove(path) + } +} + +// dialManager connects to the one manager answering beside base. A socket +// that refuses the connection belongs to a manager that exited. Several +// live ones leave no way to tell which window the caller is looking at. +func dialManager(base string) (net.Conn, error) { + paths, err := focusEndpoints(base) + if err != nil { + return nil, err + } + var live []net.Conn + var pids []string + for _, path := range paths { + conn, err := net.DialTimeout("unix", path, time.Second) + if err != nil { + continue + } + live = append(live, conn) + pids = append(pids, strings.TrimPrefix(filepath.Base(path), filepath.Base(base)+".")) + } + switch len(live) { + case 0: + return nil, errNoManager + case 1: + return live[0], nil + } + for _, conn := range live { + conn.Close() + } + return nil, fmt.Errorf("%d Agent Manager windows are running on this tmux server (processes %s), so it cannot tell which one to use (quit all but one)", len(live), strings.Join(pids, ", ")) } func answerFocus(conn net.Conn, deliver func(FocusDelivery)) { diff --git a/internal/sessioncmd/focus_endpoint_test.go b/internal/sessioncmd/focus_endpoint_test.go index df49a1445..0a0eb23d1 100644 --- a/internal/sessioncmd/focus_endpoint_test.go +++ b/internal/sessioncmd/focus_endpoint_test.go @@ -2,14 +2,17 @@ package sessioncmd import ( "encoding/json" + "errors" "net" "os" "path/filepath" + "strings" "testing" + "time" ) // A Unix socket path stops near 104 bytes, past which t.TempDir's names run. -func focusSocketPath(t *testing.T) string { +func focusSocketBase(t *testing.T) string { t.Helper() dir, err := os.MkdirTemp("", "amfocus") if err != nil { @@ -19,12 +22,39 @@ func focusSocketPath(t *testing.T) string { return filepath.Join(dir, "agentmgr.focus") } -func askFocus(t *testing.T, path string, request FocusRequest) <-chan FocusAnswer { +func listenFocusForTest(t *testing.T, base string, pid int) <-chan FocusDelivery { + t.Helper() + deliveries := make(chan FocusDelivery, 1) + stop, err := listenFocusAs(base, pid, func(delivery FocusDelivery) { deliveries <- delivery }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(stop) + return deliveries +} + +// staleFocusSocket leaves a socket file nobody listens on, the way a +// manager that crashed does. +func staleFocusSocket(t *testing.T, path string, age time.Duration) { + t.Helper() + listener, err := net.Listen("unix", path) + if err != nil { + t.Fatal(err) + } + listener.(*net.UnixListener).SetUnlinkOnClose(false) + listener.Close() + then := time.Now().Add(-age) + if err := os.Chtimes(path, then, then); err != nil { + t.Fatal(err) + } +} + +func askFocus(t *testing.T, base string, request FocusRequest) <-chan FocusAnswer { t.Helper() answers := make(chan FocusAnswer, 1) go func() { var answer FocusAnswer - conn, err := net.Dial("unix", path) + conn, err := dialManager(base) if err != nil { answer.Error = "dial: " + err.Error() answers <- answer @@ -44,12 +74,10 @@ func askFocus(t *testing.T, path string, request FocusRequest) <-chan FocusAnswe // Each connection carries one request and reads back the outcome the // manager handed back for that request, a refusal included. func TestFocusEndpointAnswersEachRequestWithItsOutcome(t *testing.T) { - path := focusSocketPath(t) - deliveries := make(chan FocusDelivery, 1) - stop := ListenFocus(path, func(delivery FocusDelivery) { deliveries <- delivery }) - defer stop() + base := focusSocketBase(t) + deliveries := listenFocusForTest(t, base, 100) - answers := askFocus(t, path, FocusRequest{ID: "a", Enter: true}) + answers := askFocus(t, base, FocusRequest{ID: "a", Enter: true}) delivery := <-deliveries if delivery.Request != (FocusRequest{ID: "a", Enter: true}) { t.Fatalf("delivered %+v, want a entered", delivery.Request) @@ -59,7 +87,7 @@ func TestFocusEndpointAnswersEachRequestWithItsOutcome(t *testing.T) { t.Fatalf("answered %q, want success", answer.Error) } - answers = askFocus(t, path, FocusRequest{ID: "b"}) + answers = askFocus(t, base, FocusRequest{ID: "b"}) delivery = <-deliveries delivery.Answer <- os.ErrNotExist if answer := <-answers; answer.Error != os.ErrNotExist.Error() { @@ -67,33 +95,50 @@ func TestFocusEndpointAnswersEachRequestWithItsOutcome(t *testing.T) { } } -// One manager answers per tmux server: a second one leaves a live endpoint -// to its owner, and a socket left by a manager that exited is taken over. -func TestFocusEndpointKeepsALiveOwnerAndReplacesAStaleSocket(t *testing.T) { - path := focusSocketPath(t) - first := make(chan FocusDelivery, 1) - stopFirst := ListenFocus(path, func(delivery FocusDelivery) { first <- delivery }) - second := make(chan FocusDelivery, 1) - stopSecond := ListenFocus(path, func(delivery FocusDelivery) { second <- delivery }) - defer stopSecond() - askFocus(t, path, FocusRequest{ID: "a"}) - (<-first).Answer <- nil - if len(second) != 0 { - t.Fatal("the second manager took a request from the live endpoint") +// Sockets left by managers that exited, and files that are not a +// manager's, never stand in for the one manager that is answering. +func TestDialManagerReachesTheLiveManagerPastStaleSockets(t *testing.T) { + base := focusSocketBase(t) + if _, err := dialManager(base); !errors.Is(err, errNoManager) { + t.Fatalf("dial with nothing there = %v, want no manager", err) } - stopFirst() - - stale, err := net.Listen("unix", path) - if err != nil { + staleFocusSocket(t, base+".7", 0) + if err := os.WriteFile(base+".x", nil, 0o600); err != nil { t.Fatal(err) } - stale.(*net.UnixListener).SetUnlinkOnClose(false) - stale.Close() - third := make(chan FocusDelivery, 1) - stopThird := ListenFocus(path, func(delivery FocusDelivery) { third <- delivery }) - defer stopThird() - askFocus(t, path, FocusRequest{ID: "b"}) - if delivery := <-third; delivery.Request.ID != "b" { - t.Fatalf("request = %+v, want b", delivery.Request) + if _, err := dialManager(base); !errors.Is(err, errNoManager) { + t.Fatalf("dial with only a stale socket = %v, want no manager", err) + } + deliveries := listenFocusForTest(t, base, 200) + askFocus(t, base, FocusRequest{ID: "a"}) + if delivery := <-deliveries; delivery.Request.ID != "a" { + t.Fatalf("request = %+v, want a", delivery.Request) + } +} + +// With two managers on one tmux server nothing says which window the +// caller means, so the request is refused naming both instead of guessing. +func TestDialManagerRefusesWhenSeveralManagersAnswer(t *testing.T) { + base := focusSocketBase(t) + listenFocusForTest(t, base, 301) + listenFocusForTest(t, base, 302) + _, err := dialManager(base) + if err == nil || !strings.Contains(err.Error(), "2 Agent Manager windows") || !strings.Contains(err.Error(), "301, 302") { + t.Fatalf("dial with two managers = %v, want a refusal naming both", err) + } +} + +// A manager starting up clears sockets crashed managers left long ago, and +// spares a fresh one another manager may be about to listen on. +func TestListenFocusSweepsOnlyOldStaleSockets(t *testing.T) { + base := focusSocketBase(t) + staleFocusSocket(t, base+".11", time.Hour) + staleFocusSocket(t, base+".12", 0) + listenFocusForTest(t, base, 400) + if _, err := os.Stat(base + ".11"); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("old stale socket still there: %v", err) + } + if _, err := os.Stat(base + ".12"); err != nil { + t.Fatalf("fresh socket was swept: %v", err) } } diff --git a/internal/sessioncmd/focus_test.go b/internal/sessioncmd/focus_test.go index f46a2d13c..9dbde17c4 100644 --- a/internal/sessioncmd/focus_test.go +++ b/internal/sessioncmd/focus_test.go @@ -11,7 +11,7 @@ import ( // with reply, hands over the request it read, and then stops listening. func fakeFocusManager(t *testing.T, h *sessionHarness, reply FocusAnswer) <-chan FocusRequest { t.Helper() - listener, err := net.Listen("unix", h.driver.FocusEndpoint()) + listener, err := net.Listen("unix", h.driver.FocusEndpoint()+".4242") if err != nil { t.Fatal(err) } @@ -42,7 +42,7 @@ func TestFocusRefusesWhatTheManagerCannotShow(t *testing.T) { if err != nil { t.Fatalf("Create: %v", err) } - if _, err := h.sessions.Focus(worker.ID, true); err == nil || !strings.Contains(err.Error(), "no Agent Manager is running") { + if _, err := h.sessions.Focus(worker.ID, true); err == nil || !strings.Contains(err.Error(), "no Agent Manager window is running") { t.Fatalf("Focus with no manager = %v", err) } if _, err := h.sessions.Focus("feedface", true); err == nil || !strings.Contains(err.Error(), "does not exist") { diff --git a/internal/ui/rail/policy.go b/internal/ui/rail/policy.go index b075fd722..707223222 100644 --- a/internal/ui/rail/policy.go +++ b/internal/ui/rail/policy.go @@ -442,8 +442,8 @@ func (m *Model) SetArchived(show bool) { // RevealSession puts the cursor on a session's row for a request from // outside the list: it unfolds the groups above the session, and drops a -// status filter only when that filter hides the row. found is false when -// the list still has no row for it. +// status filter or the archive view only when it hides the row. found is +// false when the list still has no row for it. func (m *Model) RevealSession(id, group string) (decision Decision, found bool) { previous, previousOK := m.Selected() collapsedChanged := false @@ -460,11 +460,18 @@ func (m *Model) RevealSession(id, group string) (decision Decision, found bool) m.rebuildRows() found = m.FocusSession(id) } + refresh := false + if !found && m.showArchived { + m.SetArchived(false) + refresh = true + found = m.FocusSession(id) + } current, currentOK := m.Selected() decision = Decision{ Consumed: true, SelectionChanged: previousOK != currentOK || previous != current, Selection: current, + Refresh: refresh, } if decision.SelectionChanged { decision.SelectionEffect = SelectionEffectPreview diff --git a/internal/ui/rail_adapter_forward.go b/internal/ui/rail_adapter_forward.go index 74a626455..f633abd02 100644 --- a/internal/ui/rail_adapter_forward.go +++ b/internal/ui/rail_adapter_forward.go @@ -24,6 +24,19 @@ type pendingForward struct { answer chan<- error } +// forwardKind is what bringing a session forward asks of the manager. +type forwardKind int + +const ( + // forwardSelect moves the cursor to the session on the list. + forwardSelect forwardKind = iota + // forwardOpen also opens it the way the enter key does. + forwardOpen + // forwardClick is a clicked notification. It moves the cursor like a + // select but leaves the user in the session when that is the one named. + forwardClick +) + // overlayLayers bounds the esc presses bringForward spends closing what // covers the list. Each press closes at most one layer; the bound is for a // layer whose esc does not close it, which would otherwise loop. @@ -44,7 +57,11 @@ func (m *Model) routeForwardMsg(msg tea.Msg) (tea.Model, tea.Cmd, bool) { if pending := m.focus.forward.sessionID; pending != "" { m.answerForward(pending, fmt.Errorf("session %s was selected but not opened: another request to bring a session forward took its place", pending)) } - opening, jump, err := m.bringForward(request.Request.ID, request.Request.Enter) + kind := forwardSelect + if request.Request.Enter { + kind = forwardOpen + } + opening, jump, err := m.bringForward(request.Request.ID, kind) if opening { m.focus.forward = pendingForward{sessionID: request.Request.ID, answer: request.Answer} } else { @@ -67,13 +84,13 @@ func (m *Model) routeForwardMsg(msg tea.Msg) (tea.Model, tea.Cmd, bool) { // input stays open with the cursor moved under it, and the session is not // opened over it. opening reports an open handed to the effect lane, whose // completion answers the request; otherwise err is the answer. -func (m *Model) bringForward(id string, enter bool) (opening bool, cmd tea.Cmd, err error) { +func (m *Model) bringForward(id string, kind forwardKind) (opening bool, cmd tea.Cmd, err error) { sess, ok := m.sessionByID(id) if !ok || (sess.Archived && !m.rail.ShowArchived()) { return false, nil, fmt.Errorf("session %s has no row in Agent Manager's list yet", id) } cmds := m.closeInputFreeLayers() - if focused, ok := m.selected(); m.focused() && (!enter || !ok || focused.ID != sess.ID) { + if focused, ok := m.selected(); m.focused() && (kind == forwardSelect || !ok || focused.ID != sess.ID) { if top, _ := m.top(); !isFocusSurface(top) { return false, tea.Batch(cmds...), fmt.Errorf("a dialog is open over the session Agent Manager is in, and it is left as it is; close it to move to session %s", sess.ID) } @@ -88,10 +105,13 @@ func (m *Model) bringForward(id string, enter bool) (opening bool, cmd tea.Cmd, } decision, found := m.rail.RevealSession(sess.ID, sess.Group) m.queueRail(decision.Mutations, 0, false) + if decision.Refresh { + m.requestRefresh() + } if !found { return false, tea.Batch(cmds...), fmt.Errorf("session %s has no row in Agent Manager's list", sess.ID) } - if !enter { + if kind != forwardOpen { return false, tea.Batch(cmds...), nil } if !m.listUncovered() { diff --git a/internal/ui/rail_adapter_forward_test.go b/internal/ui/rail_adapter_forward_test.go index e8eb537af..96b7bbadd 100644 --- a/internal/ui/rail_adapter_forward_test.go +++ b/internal/ui/rail_adapter_forward_test.go @@ -1,6 +1,7 @@ package ui import ( + "slices" "strings" "testing" "time" @@ -202,3 +203,80 @@ func TestExpiredFocusRequestIsDropped(t *testing.T) { t.Fatal("an expired request was answered a second time") } } + +// clickNotification delivers a clicked notification the way the poller +// does, on the next listing. +func (m *Model) clickNotification(t *testing.T, id string) { + t.Helper() + updated, cmd := m.Update(refreshMsg{ + sessions: slices.Clone(m.workspace.sessions), + listedAt: time.Now(), + focusID: id, + }) + *m = *updated.(*Model) + if cmd != nil { + m.applyCmd(t, cmd) + } +} + +// A click on the session the user is already in leaves them in it, as it +// did before requests from other shells shared this path. A click on +// another session steps back to the list with that row unfolded. +func TestNotificationClickStaysInTheSessionItNames(t *testing.T) { + t.Parallel() + m, deep := focusRequestModel(t) + if err := m.serveFocusRequest(t, deep.ID, true); err != nil { + t.Fatalf("setup: focus answered %v", err) + } + m.clickNotification(t, deep.ID) + if !m.focused() { + t.Fatalf("screen = %v after a click on the focused session, want focus kept", m.screenID()) + } + m.rail.SetCollapsed("backend", true) + var top store.Session + for _, sess := range m.workspace.sessions { + if sess.Name == "top" { + top = sess + } + } + m.clickNotification(t, top.ID) + if !m.onList() { + t.Fatalf("screen = %v after a click on another session, want the list", m.screenID()) + } + if sess, ok := m.selected(); !ok || sess.ID != top.ID { + t.Fatalf("cursor is on %+v, want top", sess) + } +} + +// A click while the New Session form is open moves the cursor under the +// form and keeps what was typed into it. +func TestNotificationClickKeepsTheNewSessionForm(t *testing.T) { + t.Parallel() + m, deep := focusRequestModel(t) + m.openForm() + m.form().SetName("half typed") + m.clickNotification(t, deep.ID) + if m.form() == nil || m.form().Name() != "half typed" { + t.Fatalf("screen = %v; want the form kept with its text", m.screenID()) + } + if sess, ok := m.selected(); !ok || sess.ID != deep.ID { + t.Fatalf("cursor is on %+v, want deep under the form", sess) + } +} + +// The archive view lists only archived sessions, so a request for a live +// one switches back to the live list. +func TestFocusRequestLeavesTheArchiveView(t *testing.T) { + t.Parallel() + m, deep := focusRequestModel(t) + m.rail.SetArchived(true) + if err := m.serveFocusRequest(t, deep.ID, false); err != nil { + t.Fatalf("select answered %v", err) + } + if m.rail.ShowArchived() { + t.Fatal("the archive view is still on") + } + if sess, ok := m.selected(); !ok || sess.ID != deep.ID { + t.Fatalf("cursor is on %+v, want deep", sess) + } +} diff --git a/internal/ui/workspace_adapter.go b/internal/ui/workspace_adapter.go index a38b6f13f..6862ad8bb 100644 --- a/internal/ui/workspace_adapter.go +++ b/internal/ui/workspace_adapter.go @@ -3,6 +3,7 @@ package ui import ( "context" "errors" + "fmt" "strings" "time" @@ -194,9 +195,14 @@ type refreshMsg struct { func (m *Model) StartPoller(ctx context.Context, send func(tea.Msg)) <-chan struct{} { m.focus.runtime.Watch = newFocusWatch(m.services.tmux, send) m.syncPollInput() - stopFocusEndpoint := sessioncmd.ListenFocus(m.services.tmux.FocusEndpoint(), func(delivery sessioncmd.FocusDelivery) { + stopFocusEndpoint, err := sessioncmd.ListenFocus(m.services.tmux.FocusEndpoint(), func(delivery sessioncmd.FocusDelivery) { send(focusRequestMsg{delivery}) }) + if err != nil { + stopFocusEndpoint = func() {} + // send blocks until the program runs, which starts after this returns. + go send(errMsg{fmt.Errorf("focus and select from other shells will not reach this window: %w", err)}) + } results := m.poller.results(ctx) done := make(chan struct{}) go func() { @@ -380,7 +386,7 @@ func (m *Model) routeRefreshMsg(msg tea.Msg) (tea.Model, tea.Cmd, bool) { m.settleInstall() m.rebuildRows() if msg.focusID != "" { - _, jump, _ := m.bringForward(msg.focusID, false) + _, jump, _ := m.bringForward(msg.focusID, forwardClick) focusExit = tea.Batch(focusExit, jump) } reviewStatuses := m.reviewStatusesCmd() From c20a312908658fa9ebaea9c4d3966d65946ea6ad Mon Sep 17 00:00:00 2001 From: Yoan Wainmann <106609173+YoanWai@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:56:58 +0200 Subject: [PATCH 3/4] fix(cli): start focus error strings in lower case Staticcheck ST1005 rejects error strings that open with a capital. --- internal/sessioncmd/focus.go | 2 +- internal/ui/rail_adapter_forward.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/sessioncmd/focus.go b/internal/sessioncmd/focus.go index 95733b978..fd7704c6a 100644 --- a/internal/sessioncmd/focus.go +++ b/internal/sessioncmd/focus.go @@ -64,7 +64,7 @@ func (s *Sessions) Focus(targetID string, enter bool) (Session, error) { } var answer FocusAnswer if err := json.NewDecoder(conn).Decode(&answer); err != nil { - return Session{}, fmt.Errorf("Agent Manager did not answer: %w", err) + return Session{}, fmt.Errorf("no answer from Agent Manager: %w", err) } if answer.Error != "" { return Session{}, errors.New(answer.Error) diff --git a/internal/ui/rail_adapter_forward.go b/internal/ui/rail_adapter_forward.go index f633abd02..11bce8565 100644 --- a/internal/ui/rail_adapter_forward.go +++ b/internal/ui/rail_adapter_forward.go @@ -51,7 +51,7 @@ func (m *Model) routeForwardMsg(msg tea.Msg) (tea.Model, tea.Cmd, bool) { return routed(m, nil) } if m.effects.Quitting { - request.Answer <- errors.New("Agent Manager is quitting") + request.Answer <- errors.New("the manager is quitting") return routed(m, nil) } if pending := m.focus.forward.sessionID; pending != "" { From 4d5553c2fdfc08a8cc814e6331b26e6082f2af08 Mon Sep 17 00:00:00 2001 From: Yoan Wainmann <106609173+YoanWai@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:13:51 +0200 Subject: [PATCH 4/4] test(cli): sweep stale focus sockets without setting their times Windows cannot set times on a Unix socket, so the sweep takes the current time and the test runs it as if an hour later. The sweep reads the socket with Lstat. --- internal/sessioncmd/focus_endpoint.go | 8 +++--- internal/sessioncmd/focus_endpoint_test.go | 30 ++++++++++++---------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/internal/sessioncmd/focus_endpoint.go b/internal/sessioncmd/focus_endpoint.go index 196beffb8..14aae150c 100644 --- a/internal/sessioncmd/focus_endpoint.go +++ b/internal/sessioncmd/focus_endpoint.go @@ -35,7 +35,7 @@ func ListenFocus(base string, deliver func(FocusDelivery)) (stop func(), err err } func listenFocusAs(base string, pid int, deliver func(FocusDelivery)) (stop func(), err error) { - sweepStaleFocusEndpoints(base) + sweepStaleFocusEndpoints(base, time.Now()) path := base + "." + strconv.Itoa(pid) // tmux makes this directory with these permissions when its server // starts, which may come after the manager does. @@ -88,14 +88,14 @@ func focusEndpoints(base string) ([]string, error) { return paths, nil } -func sweepStaleFocusEndpoints(base string) { +func sweepStaleFocusEndpoints(base string, now time.Time) { paths, err := focusEndpoints(base) if err != nil { return } for _, path := range paths { - info, err := os.Stat(path) - if err != nil || time.Since(info.ModTime()) < staleEndpointAge { + info, err := os.Lstat(path) + if err != nil || now.Sub(info.ModTime()) < staleEndpointAge { continue } if conn, err := net.Dial("unix", path); err == nil { diff --git a/internal/sessioncmd/focus_endpoint_test.go b/internal/sessioncmd/focus_endpoint_test.go index 0a0eb23d1..3496a0535 100644 --- a/internal/sessioncmd/focus_endpoint_test.go +++ b/internal/sessioncmd/focus_endpoint_test.go @@ -35,7 +35,7 @@ func listenFocusForTest(t *testing.T, base string, pid int) <-chan FocusDelivery // staleFocusSocket leaves a socket file nobody listens on, the way a // manager that crashed does. -func staleFocusSocket(t *testing.T, path string, age time.Duration) { +func staleFocusSocket(t *testing.T, path string) { t.Helper() listener, err := net.Listen("unix", path) if err != nil { @@ -43,10 +43,6 @@ func staleFocusSocket(t *testing.T, path string, age time.Duration) { } listener.(*net.UnixListener).SetUnlinkOnClose(false) listener.Close() - then := time.Now().Add(-age) - if err := os.Chtimes(path, then, then); err != nil { - t.Fatal(err) - } } func askFocus(t *testing.T, base string, request FocusRequest) <-chan FocusAnswer { @@ -102,7 +98,7 @@ func TestDialManagerReachesTheLiveManagerPastStaleSockets(t *testing.T) { if _, err := dialManager(base); !errors.Is(err, errNoManager) { t.Fatalf("dial with nothing there = %v, want no manager", err) } - staleFocusSocket(t, base+".7", 0) + staleFocusSocket(t, base+".7") if err := os.WriteFile(base+".x", nil, 0o600); err != nil { t.Fatal(err) } @@ -129,16 +125,22 @@ func TestDialManagerRefusesWhenSeveralManagersAnswer(t *testing.T) { } // A manager starting up clears sockets crashed managers left long ago, and -// spares a fresh one another manager may be about to listen on. -func TestListenFocusSweepsOnlyOldStaleSockets(t *testing.T) { +// spares a fresh one another manager may be about to listen on. Windows +// cannot set times on a socket, so the sweep is run as if later. +func TestSweepRemovesOnlyOldStaleSockets(t *testing.T) { base := focusSocketBase(t) - staleFocusSocket(t, base+".11", time.Hour) - staleFocusSocket(t, base+".12", 0) - listenFocusForTest(t, base, 400) - if _, err := os.Stat(base + ".11"); !errors.Is(err, os.ErrNotExist) { + staleFocusSocket(t, base+".11") + live := listenFocusForTest(t, base, 400) + sweepStaleFocusEndpoints(base, time.Now()) + if _, err := os.Lstat(base + ".11"); err != nil { + t.Fatalf("fresh socket was swept: %v", err) + } + sweepStaleFocusEndpoints(base, time.Now().Add(time.Hour)) + if _, err := os.Lstat(base + ".11"); !errors.Is(err, os.ErrNotExist) { t.Fatalf("old stale socket still there: %v", err) } - if _, err := os.Stat(base + ".12"); err != nil { - t.Fatalf("fresh socket was swept: %v", err) + askFocus(t, base, FocusRequest{ID: "a"}) + if delivery := <-live; delivery.Request.ID != "a" { + t.Fatalf("the sweep cut off the live manager: request %+v", delivery.Request) } }