diff --git a/.eslintrc.cjs b/.eslintrc.cjs deleted file mode 100644 index c7a0f362..00000000 --- a/.eslintrc.cjs +++ /dev/null @@ -1,35 +0,0 @@ -module.exports = { - root: true, - ignorePatterns: [ - '**/dist/**', - '**/.next/**', - '**/node_modules/**', - '**/out/**', - '**/coverage/**', - '**/build/**', - '**/.turbo/**', - ], - env: { - es2022: true, - node: true, - browser: true, - }, - parserOptions: { - ecmaVersion: 'latest', - sourceType: 'module', - }, - overrides: [ - { - files: ['**/*.ts', '**/*.tsx'], - parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint'], - extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'], - rules: { - '@typescript-eslint/no-unused-vars': [ - 'error', - { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }, - ], - }, - }, - ], -}; diff --git a/agents/agentd/cmd/agentd/main.go b/agents/agentd/cmd/agentd/main.go index 1dc849c8..38605cd3 100644 --- a/agents/agentd/cmd/agentd/main.go +++ b/agents/agentd/cmd/agentd/main.go @@ -48,6 +48,7 @@ type Agent struct { streamer *console.Streamer terminalManager *tmux.TerminalManager pipeMux *tmux.PipeMux + tmuxHooks *tmux.HookManager lastPruneAt time.Time orchestratorTmux TmuxRunner sendMessage func(string, any) error @@ -74,6 +75,14 @@ type Agent struct { launchTemplates *providers.LaunchTemplates commandExecutor *commands.Executor + + tmuxTopologyMu sync.Mutex + tmuxTopologyTimer *time.Timer + pendingTmuxTopology *protocol.TmuxTopologyPayload + pendingTmuxTopologyHash string + lastTmuxTopologyHash string + tmuxTopologyGeneration uint64 + tmuxTopologyStopped bool } type toolEventPending struct { @@ -405,6 +414,11 @@ func (a *Agent) Run() error { a.cfg.ControlPlane.ReconnectBackoffMs, ) a.wsClient.SetMessageHandler(a.handleMessage) + a.wsClient.SetOnDisconnect(func() { + if a.terminalManager != nil { + a.terminalManager.MarkChannelsStale() + } + }) a.wsClient.SetOnConnect(func() { if err := a.sendHello(); err != nil { log.Printf("Failed to send hello: %v", err) @@ -463,6 +477,20 @@ func (a *Agent) Run() error { // Initialize pipe mux for console + terminal output a.pipeMux = tmux.NewPipeMux(a.tmuxClient, a.cfg.Storage.StateDir+"/console") + // Register additive topology hooks when the host tmux supports them. The + // reconciliation poll remains active as the fallback and correctness pass. + // Skipped entirely while topology events are disabled: hooks would mutate + // the user's tmux server and trigger ListPanes for events that get dropped. + if a.cfg.Tmux.TopologyEvents { + a.tmuxHooks, err = a.tmuxClient.StartTopologyHooks(a.handleTmuxTopologyHook) + if err != nil { + log.Printf("tmux hooks unavailable; using poll-only topology: %v", err) + } else { + defer a.tmuxHooks.Close() + log.Printf("tmux topology hooks active") + } + } + // Connect to control plane if err := a.wsClient.Connect(); err != nil { return fmt.Errorf("failed to connect to control plane: %w", err) @@ -496,6 +524,10 @@ func (a *Agent) Run() error { if a.terminalManager != nil { a.terminalManager.Close() } + if a.tmuxHooks != nil { + a.tmuxHooks.Close() + } + a.stopTmuxTopology() a.claudeProvider.Stop() a.wsClient.Close() @@ -1740,6 +1772,8 @@ func (a *Agent) send(msgType string, payload any) error { var err error if a.sendMessage != nil { err = a.sendMessage(msgType, payload) + } else if msgType == protocol.TypeTmuxTopology { + err = a.wsClient.SendUnsequenced(msgType, payload) } else { err = a.wsClient.Send(msgType, payload) } @@ -1945,6 +1979,54 @@ func (a *Agent) executeCommand(cmd commands.Dispatch) (map[string]any, error) { break } err = a.executeRenameSession(session, cmd.Command.Payload) + case "new_window": + if !exists { + err = fmt.Errorf("session not found") + break + } + resultPayload, err = a.executeNewWindow(session, cmd.Command.Payload) + case "rename_window": + if !exists { + err = fmt.Errorf("session not found") + break + } + err = a.executeRenameWindow(session, cmd.Command.Payload) + case "kill_window": + if !exists { + err = fmt.Errorf("session not found") + break + } + err = a.executeKillWindow(session, cmd.Command.Payload) + case "select_window": + if !exists { + err = fmt.Errorf("session not found") + break + } + err = a.executeSelectWindow(session, cmd.Command.Payload) + case "split_pane": + if !exists { + err = fmt.Errorf("session not found") + break + } + resultPayload, err = a.executeSplitPane(session, cmd.Command.Payload) + case "select_pane": + if !exists { + err = fmt.Errorf("session not found") + break + } + err = a.executeSelectPane(session, cmd.Command.Payload) + case "resize_pane": + if !exists { + err = fmt.Errorf("session not found") + break + } + err = a.executeResizePane(session, cmd.Command.Payload) + case "zoom_pane": + if !exists { + err = fmt.Errorf("session not found") + break + } + err = a.executeZoomPane(session, cmd.Command.Payload) case "spawn_session": err = a.executeSpawnSession(cmd.SessionID, cmd.Command.Payload) case "spawn_job": @@ -2077,6 +2159,216 @@ func (a *Agent) executeSendKeys(session *SessionState, payload json.RawMessage) return a.tmuxClient.SendKeys(session.PaneID, p.Keys) } +func (a *Agent) executeNewWindow(session *SessionState, payload json.RawMessage) (map[string]any, error) { + if !a.cfg.Security.AllowSpawn { + return nil, fmt.Errorf("new_window not allowed by policy") + } + var p protocol.NewWindowPayload + if err := json.Unmarshal(payload, &p); err != nil { + return nil, err + } + tmuxSession := tmuxSessionFromTarget(session.TmuxTarget) + if tmuxSession == "" { + return nil, fmt.Errorf("session has no tmux target") + } + + a.topologyMu.Lock() + defer a.topologyMu.Unlock() + paneID, err := a.tmuxClient.NewWindow(tmuxSession, p.WindowName, p.CWD) + if err != nil { + return nil, err + } + return map[string]any{"pane_id": paneID}, nil +} + +func (a *Agent) executeRenameWindow(session *SessionState, payload json.RawMessage) error { + if !a.cfg.Security.AllowSendInput { + return fmt.Errorf("rename_window not allowed by policy") + } + var p protocol.RenameWindowPayload + if err := json.Unmarshal(payload, &p); err != nil { + return err + } + if p.WindowIndex == nil || *p.WindowIndex < 0 { + return fmt.Errorf("window_index is required") + } + if strings.TrimSpace(p.Name) == "" { + return fmt.Errorf("name is required") + } + target, err := tmuxWindowTarget(session, *p.WindowIndex) + if err != nil { + return err + } + + a.topologyMu.Lock() + defer a.topologyMu.Unlock() + return a.tmuxClient.RenameWindow(target, p.Name) +} + +func (a *Agent) executeKillWindow(session *SessionState, payload json.RawMessage) error { + if !a.cfg.Security.AllowKill { + return fmt.Errorf("kill_window not allowed by policy") + } + var p protocol.KillWindowPayload + if err := json.Unmarshal(payload, &p); err != nil { + return err + } + if p.WindowIndex == nil || *p.WindowIndex < 0 { + return fmt.Errorf("window_index is required") + } + target, err := tmuxWindowTarget(session, *p.WindowIndex) + if err != nil { + return err + } + + a.topologyMu.Lock() + defer a.topologyMu.Unlock() + return a.tmuxClient.KillWindow(target) +} + +func (a *Agent) executeSelectWindow(session *SessionState, payload json.RawMessage) error { + if !a.cfg.Security.AllowSendInput { + return fmt.Errorf("select_window not allowed by policy") + } + var p protocol.SelectWindowPayload + if err := json.Unmarshal(payload, &p); err != nil { + return err + } + if p.WindowIndex == nil || *p.WindowIndex < 0 { + return fmt.Errorf("window_index is required") + } + target, err := tmuxWindowTarget(session, *p.WindowIndex) + if err != nil { + return err + } + + a.topologyMu.Lock() + defer a.topologyMu.Unlock() + return a.tmuxClient.SelectWindow(target) +} + +func (a *Agent) executeSplitPane(session *SessionState, payload json.RawMessage) (map[string]any, error) { + if !a.cfg.Security.AllowSpawn { + return nil, fmt.Errorf("split_pane not allowed by policy") + } + var p protocol.SplitPanePayload + if err := json.Unmarshal(payload, &p); err != nil { + return nil, err + } + if p.Direction != "horizontal" && p.Direction != "vertical" { + return nil, fmt.Errorf("direction must be horizontal or vertical") + } + if p.Percent != nil && (*p.Percent < 1 || *p.Percent > 100) { + return nil, fmt.Errorf("percent must be between 1 and 100") + } + if session.PaneID == "" { + return nil, fmt.Errorf("session has no active pane") + } + + a.topologyMu.Lock() + defer a.topologyMu.Unlock() + created, err := a.tmuxClient.SplitPaneWithOptions(session.PaneID, p.Direction, p.Percent, p.CWD) + if err != nil { + return nil, err + } + return map[string]any{"pane_id": created.PaneID, "tmux_target": created.TmuxTarget}, nil +} + +func (a *Agent) executeSelectPane(session *SessionState, payload json.RawMessage) error { + if !a.cfg.Security.AllowSendInput { + return fmt.Errorf("select_pane not allowed by policy") + } + var p protocol.SelectPanePayload + if err := json.Unmarshal(payload, &p); err != nil { + return err + } + + a.topologyMu.Lock() + defer a.topologyMu.Unlock() + paneID, err := a.resolvePaneTarget(session, p.PaneID) + if err != nil { + return err + } + return a.tmuxClient.SelectPane(paneID) +} + +func (a *Agent) executeResizePane(session *SessionState, payload json.RawMessage) error { + if !a.cfg.Security.AllowSendInput { + return fmt.Errorf("resize_pane not allowed by policy") + } + var p protocol.ResizePanePayload + if err := json.Unmarshal(payload, &p); err != nil { + return err + } + if p.Width == nil && p.Height == nil { + return fmt.Errorf("at least one of width or height is required") + } + if (p.Width != nil && *p.Width <= 0) || (p.Height != nil && *p.Height <= 0) { + return fmt.Errorf("pane dimensions must be positive") + } + + a.topologyMu.Lock() + defer a.topologyMu.Unlock() + paneID, err := a.resolvePaneTarget(session, p.PaneID) + if err != nil { + return err + } + width, height := 0, 0 + if p.Width != nil { + width = *p.Width + } + if p.Height != nil { + height = *p.Height + } + return a.tmuxClient.ResizePane(paneID, width, height) +} + +func (a *Agent) executeZoomPane(session *SessionState, payload json.RawMessage) error { + if !a.cfg.Security.AllowSendInput { + return fmt.Errorf("zoom_pane not allowed by policy") + } + var p protocol.ZoomPanePayload + if err := json.Unmarshal(payload, &p); err != nil { + return err + } + + a.topologyMu.Lock() + defer a.topologyMu.Unlock() + paneID, err := a.resolvePaneTarget(session, p.PaneID) + if err != nil { + return err + } + return a.tmuxClient.ZoomPane(paneID) +} + +func (a *Agent) resolvePaneTarget(session *SessionState, paneID string) (string, error) { + if paneID == "" { + return "", fmt.Errorf("pane_id is required") + } + tmuxSession := tmuxSessionFromTarget(session.TmuxTarget) + if tmuxSession == "" { + return "", fmt.Errorf("session has no tmux target") + } + panes, err := a.tmuxClient.ListPanes() + if err != nil { + return "", err + } + for _, pane := range panes { + if pane.PaneID == paneID && pane.SessionName == tmuxSession { + return paneID, nil + } + } + return "", fmt.Errorf("pane is not in the tracked tmux session") +} + +func tmuxWindowTarget(session *SessionState, windowIndex int) (string, error) { + tmuxSession := tmuxSessionFromTarget(session.TmuxTarget) + if tmuxSession == "" { + return "", fmt.Errorf("session has no tmux target") + } + return fmt.Sprintf("%s:%d", tmuxSession, windowIndex), nil +} + func (a *Agent) executeKillSession(session *SessionState) error { if !a.cfg.Security.AllowKill { return fmt.Errorf("kill not allowed by policy") @@ -4619,23 +4911,42 @@ func (a *Agent) handleConsoleChunk(subscriptionID, sessionID string, data []byte } func (a *Agent) pollTmux() { + a.reconcileTmux("startup") + a.retryBufferedHooks() + ticker := time.NewTicker(time.Duration(a.cfg.Tmux.PollIntervalMs) * time.Millisecond) defer ticker.Stop() for range ticker.C { - a.topologyMu.Lock() - panes, err := a.tmuxClient.ListPanes() - if err != nil { - a.topologyMu.Unlock() - log.Printf("Failed to list tmux panes: %v", err) - continue - } + a.reconcileTmux("poll") + a.retryBufferedHooks() + } +} - procSnap := proc.TakeSnapshot() - a.syncPanes(panes, procSnap) +func (a *Agent) reconcileTmux(reason string) { + a.topologyMu.Lock() + panes, err := a.tmuxClient.ListPanes() + if err != nil { a.topologyMu.Unlock() - a.retryBufferedHooks() + log.Printf("Failed to list tmux panes: %v", err) + return } + + procSnap := proc.TakeSnapshot() + a.syncPanes(panes, procSnap) + a.topologyMu.Unlock() + a.queueTmuxTopology(reason, panes) +} + +func (a *Agent) handleTmuxTopologyHook(hookName string) { + a.topologyMu.Lock() + panes, err := a.tmuxClient.ListPanes() + a.topologyMu.Unlock() + if err != nil { + log.Printf("Failed to list tmux panes after hook %s: %v", hookName, err) + return + } + a.queueTmuxTopology("hook:"+hookName, panes) } func (a *Agent) syncPanes(panes []tmux.Pane, procSnap *proc.Snapshot) { @@ -4755,14 +5066,22 @@ func (a *Agent) syncPanes(panes []tmux.Pane, procSnap *proc.Snapshot) { session.Metadata = map[string]any{} } session.Metadata["tmux"] = map[string]any{ - "pane_id": pane.PaneID, - "target": pane.GetTmuxTarget(), - "pane_pid": pane.PanePID, - "current_command": pane.CurrentCommand, - "session_name": pane.SessionName, - "window_name": pane.WindowName, - "window_index": pane.WindowIndex, - "pane_index": pane.PaneIndex, + "pane_id": pane.PaneID, + "target": pane.GetTmuxTarget(), + "pane_pid": pane.PanePID, + "current_command": pane.CurrentCommand, + "session_name": pane.SessionName, + "window_name": pane.WindowName, + "window_index": pane.WindowIndex, + "pane_index": pane.PaneIndex, + "pane_active": pane.PaneActive, + "window_active": pane.WindowActive, + "window_zoomed_flag": pane.WindowZoomed, + "window_layout": pane.WindowLayout, + "pane_width": pane.PaneWidth, + "pane_height": pane.PaneHeight, + "window_bell_flag": pane.WindowBell, + "window_activity_flag": pane.WindowActivity, } session.Metadata["unmanaged"] = session.Unmanaged diff --git a/agents/agentd/cmd/agentd/main_terminal_test.go b/agents/agentd/cmd/agentd/main_terminal_test.go index 91dbe2e8..e78b044a 100644 --- a/agents/agentd/cmd/agentd/main_terminal_test.go +++ b/agents/agentd/cmd/agentd/main_terminal_test.go @@ -1,11 +1,19 @@ package main import ( + "encoding/json" + "net/http" + "net/http/httptest" "reflect" + "strings" + "sync" "testing" + "time" "github.com/agent-command/agentd/internal/protocol" "github.com/agent-command/agentd/internal/tmux" + "github.com/agent-command/agentd/internal/ws" + "github.com/gorilla/websocket" ) func TestTerminalOutputHandlerDoesNotReencodeFanoutChunk(t *testing.T) { @@ -58,3 +66,122 @@ func TestTerminalAuditHandlerEmitsAdditiveAuditEvent(t *testing.T) { t.Fatalf("message=(%q, %#v), want=(terminal.audit, %#v)", gotType, gotPayload, want) } } + +func TestTerminalAttachSupersedesStaleChannelAfterControlPlaneReconnect(t *testing.T) { + tmuxClient := newPrivateCommandTmux(t) + panes, err := tmuxClient.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial panes=%+v err=%v", panes, err) + } + paneID := panes[0].PaneID + + var connectionMu sync.Mutex + connectionCount := 0 + firstAttached := make(chan struct{}) + secondAttached := make(chan protocol.TerminalStatusPayload, 1) + serverDone := make(chan struct{}) + var resumeToken string + upgrader := websocket.Upgrader{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + + connectionMu.Lock() + connectionCount++ + current := connectionCount + connectionMu.Unlock() + if current > 2 { + return + } + + var hello protocol.AgentEnvelope + if err := conn.ReadJSON(&hello); err != nil || hello.Type != protocol.TypeAgentHello { + return + } + attach := protocol.TerminalAttachPayload{ + ChannelID: "channel-old", + PaneID: paneID, + SessionID: "session-1", + Cols: 120, + Rows: 40, + } + if current == 2 { + <-firstAttached + attach.ChannelID = "channel-new" + attach.ResumeToken = resumeToken + } + if err := conn.WriteJSON(protocol.ServerMessage[protocol.TerminalAttachPayload]{ + V: protocol.Version, Type: protocol.TypeTerminalAttach, + TS: time.Now().UTC().Format(time.RFC3339Nano), Payload: attach, + }); err != nil { + return + } + + for { + var envelope protocol.AgentEnvelope + if err := conn.ReadJSON(&envelope); err != nil { + return + } + if envelope.Type != protocol.TypeTerminalAttached { + continue + } + var status protocol.TerminalStatusPayload + if err := json.Unmarshal(envelope.Payload, &status); err != nil || status.ChannelID != attach.ChannelID { + continue + } + if current == 1 { + resumeToken = status.ResumeToken + close(firstAttached) + return + } + secondAttached <- status + <-serverDone + return + } + })) + defer server.Close() + defer close(serverDone) + + agent := &Agent{tmuxClient: tmuxClient} + manager := tmux.NewTerminalManager(tmuxClient, t.TempDir()) + manager.SetPerViewerPTY(true) + agent.terminalManager = manager + defer manager.Close() + + wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + wsClient := ws.NewClient(wsURL, "token", "host", []int{10}) + agent.wsClient = wsClient + wsClient.SetMessageHandler(agent.handleMessage) + wsClient.SetOnDisconnect(manager.MarkChannelsStale) + wsClient.SetOnConnect(func() { + if err := wsClient.ResendQueued(); err != nil { + return + } + _ = wsClient.SendHello(protocol.AgentHelloPayload{}) + }) + manager.SetOutputHandler(agent.handleTerminalOutput) + manager.SetStatusHandler(agent.handleTerminalStatus) + manager.SetAuditHandler(agent.handleTerminalAudit) + if err := wsClient.Connect(); err != nil { + t.Fatal(err) + } + defer wsClient.Close() + + select { + case status := <-secondAttached: + if status.Resumed == nil || !*status.Resumed || status.ResumeToken != resumeToken { + t.Fatalf("resumed terminal status=%+v token=%q", status, resumeToken) + } + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for resumed terminal.attach after reconnect") + } + if err := manager.SendInput("channel-old", "stale"); err == nil || !strings.Contains(err.Error(), "not found") { + t.Fatalf("old channel cleanup error=%v", err) + } + if !manager.IsPTYMode("channel-new") { + t.Fatal("new channel is not attached in PTY mode") + } +} diff --git a/agents/agentd/cmd/agentd/main_tmux_commands_test.go b/agents/agentd/cmd/agentd/main_tmux_commands_test.go new file mode 100644 index 00000000..d9195bc6 --- /dev/null +++ b/agents/agentd/cmd/agentd/main_tmux_commands_test.go @@ -0,0 +1,292 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/agent-command/agentd/internal/commands" + "github.com/agent-command/agentd/internal/config" + "github.com/agent-command/agentd/internal/protocol" + "github.com/agent-command/agentd/internal/tmux" +) + +func TestExecuteNewWindowAgainstPrivateTmux(t *testing.T) { + agent, client, _ := newPrivateCommandAgent(t) + + result, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{ + Type: "new_window", + Payload: []byte(fmt.Sprintf(`{"window_name":"scratch","cwd":%q}`, t.TempDir())), + }, + }) + if err != nil { + t.Fatalf("execute new_window: %v", err) + } + if result["pane_id"] == "" { + t.Fatalf("new_window result=%+v", result) + } + panes, err := client.ListPanes() + if err != nil { + t.Fatal(err) + } + if len(panes) != 2 || panes[1].WindowName != "scratch" { + t.Fatalf("panes after new_window=%+v", panes) + } +} + +func TestExecuteRenameWindowAgainstPrivateTmux(t *testing.T) { + agent, client, _ := newPrivateCommandAgent(t) + if _, err := client.NewWindow("command-test", "scratch", ""); err != nil { + t.Fatal(err) + } + windowIndex := 1 + payload, err := json.Marshal(protocol.RenameWindowPayload{WindowIndex: &windowIndex, Name: "builds"}) + if err != nil { + t.Fatal(err) + } + if _, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "rename_window", Payload: payload}, + }); err != nil { + t.Fatalf("execute rename_window: %v", err) + } + panes, err := client.ListPanes() + if err != nil { + t.Fatal(err) + } + for _, pane := range panes { + if pane.WindowIndex == 1 && pane.WindowName == "builds" { + return + } + } + t.Fatalf("renamed window not found: %+v", panes) +} + +func TestExecuteKillWindowAgainstPrivateTmux(t *testing.T) { + agent, client, _ := newPrivateCommandAgent(t) + if _, err := client.NewWindow("command-test", "disposable", ""); err != nil { + t.Fatal(err) + } + windowIndex := 1 + payload, err := json.Marshal(protocol.KillWindowPayload{WindowIndex: &windowIndex}) + if err != nil { + t.Fatal(err) + } + if _, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "kill_window", Payload: payload}, + }); err != nil { + t.Fatalf("execute kill_window: %v", err) + } + panes, err := client.ListPanes() + if err != nil { + t.Fatal(err) + } + for _, pane := range panes { + if pane.WindowIndex == 1 { + t.Fatalf("killed window still present: %+v", panes) + } + } +} + +func TestExecuteSelectWindowAgainstPrivateTmux(t *testing.T) { + agent, client, _ := newPrivateCommandAgent(t) + if _, err := client.NewWindow("command-test", "select-me", ""); err != nil { + t.Fatal(err) + } + windowIndex := 0 + payload, err := json.Marshal(protocol.SelectWindowPayload{WindowIndex: &windowIndex}) + if err != nil { + t.Fatal(err) + } + if _, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "select_window", Payload: payload}, + }); err != nil { + t.Fatalf("execute select_window: %v", err) + } + panes, err := client.ListPanes() + if err != nil { + t.Fatal(err) + } + for _, pane := range panes { + if pane.WindowIndex == 0 && pane.WindowActive { + return + } + } + t.Fatalf("selected window is not active: %+v", panes) +} + +func TestExecuteSplitPaneAgainstPrivateTmux(t *testing.T) { + agent, client, original := newPrivateCommandAgent(t) + percent := 40 + cwd := t.TempDir() + payload, err := json.Marshal(protocol.SplitPanePayload{ + Direction: "horizontal", + Percent: &percent, + CWD: cwd, + }) + if err != nil { + t.Fatal(err) + } + result, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "split_pane", Payload: payload}, + }) + if err != nil { + t.Fatalf("execute split_pane: %v", err) + } + createdPaneID, _ := result["pane_id"].(string) + if createdPaneID == "" { + t.Fatalf("split_pane result=%+v", result) + } + panes, err := client.ListPanes() + if err != nil { + t.Fatal(err) + } + for _, pane := range panes { + if pane.PaneID == createdPaneID { + if pane.WindowIndex != original.WindowIndex || pane.CurrentPath != cwd || pane.PaneWidth >= original.PaneWidth { + t.Fatalf("created split=%+v original=%+v", pane, original) + } + return + } + } + t.Fatalf("created pane %s not found: %+v", createdPaneID, panes) +} + +func TestExecuteSelectPaneAgainstPrivateTmux(t *testing.T) { + agent, client, original := newPrivateCommandAgent(t) + if _, err := client.SplitPaneWithOptions(original.PaneID, "horizontal", nil, ""); err != nil { + t.Fatal(err) + } + payload, err := json.Marshal(protocol.SelectPanePayload{PaneID: original.PaneID}) + if err != nil { + t.Fatal(err) + } + if _, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "select_pane", Payload: payload}, + }); err != nil { + t.Fatalf("execute select_pane: %v", err) + } + panes, err := client.ListPanes() + if err != nil { + t.Fatal(err) + } + for _, pane := range panes { + if pane.PaneID == original.PaneID && pane.PaneActive { + return + } + } + t.Fatalf("selected pane is not active: %+v", panes) +} + +func TestExecuteResizePaneAgainstPrivateTmux(t *testing.T) { + agent, client, original := newPrivateCommandAgent(t) + created, err := client.SplitPaneWithOptions(original.PaneID, "horizontal", nil, "") + if err != nil { + t.Fatal(err) + } + width := 50 + payload, err := json.Marshal(protocol.ResizePanePayload{PaneID: created.PaneID, Width: &width}) + if err != nil { + t.Fatal(err) + } + if _, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "resize_pane", Payload: payload}, + }); err != nil { + t.Fatalf("execute resize_pane: %v", err) + } + panes, err := client.ListPanes() + if err != nil { + t.Fatal(err) + } + for _, pane := range panes { + if pane.PaneID == created.PaneID { + if pane.PaneWidth != width { + t.Fatalf("resized pane width=%d, want %d", pane.PaneWidth, width) + } + return + } + } + t.Fatalf("resized pane %s not found: %+v", created.PaneID, panes) +} + +func TestExecuteZoomPaneAgainstPrivateTmux(t *testing.T) { + agent, client, original := newPrivateCommandAgent(t) + created, err := client.SplitPaneWithOptions(original.PaneID, "horizontal", nil, "") + if err != nil { + t.Fatal(err) + } + payload, err := json.Marshal(protocol.ZoomPanePayload{PaneID: created.PaneID}) + if err != nil { + t.Fatal(err) + } + if _, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "zoom_pane", Payload: payload}, + }); err != nil { + t.Fatalf("execute zoom_pane: %v", err) + } + panes, err := client.ListPanes() + if err != nil { + t.Fatal(err) + } + for _, pane := range panes { + if pane.PaneID == created.PaneID && pane.WindowZoomed { + return + } + } + t.Fatalf("pane window is not zoomed: %+v", panes) +} + +func newPrivateCommandAgent(t *testing.T) (*Agent, *tmux.Client, tmux.Pane) { + t.Helper() + client := newPrivateCommandTmux(t) + panes, err := client.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial panes=%+v err=%v", panes, err) + } + agent := &Agent{ + cfg: &config.Config{Security: config.SecurityConfig{ + AllowSpawn: true, + AllowKill: true, + AllowSendInput: true, + }}, + tmuxClient: client, + sessions: map[string]*SessionState{ + "session-1": {ID: "session-1", PaneID: panes[0].PaneID, TmuxTarget: panes[0].GetTmuxTarget()}, + }, + } + return agent, client, panes[0] +} + +func newPrivateCommandTmux(t *testing.T) *tmux.Client { + t.Helper() + tmuxBin, err := exec.LookPath("tmux") + if err != nil { + t.Skip("tmux is not installed") + } + label := fmt.Sprintf("ac-test-%d", time.Now().UnixNano()) + if output, err := exec.Command(tmuxBin, "-L", label, "new-session", "-d", "-x", "160", "-y", "50", "-s", "command-test", "sleep 30").CombinedOutput(); err != nil { + t.Fatalf("start private tmux: %v: %s", err, output) + } + t.Cleanup(func() { + _ = exec.Command(tmuxBin, "-L", label, "kill-server").Run() + }) + + wrapper := filepath.Join(t.TempDir(), "tmux-private") + script := fmt.Sprintf("#!/bin/sh\nexec %q -L %q \"$@\"\n", tmuxBin, label) + if err := os.WriteFile(wrapper, []byte(script), 0700); err != nil { + t.Fatal(err) + } + return tmux.NewClient(&config.TmuxConfig{Bin: wrapper}) +} diff --git a/agents/agentd/cmd/agentd/main_tmux_test.go b/agents/agentd/cmd/agentd/main_tmux_test.go new file mode 100644 index 00000000..a15ea706 --- /dev/null +++ b/agents/agentd/cmd/agentd/main_tmux_test.go @@ -0,0 +1,187 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "github.com/agent-command/agentd/internal/config" + "github.com/agent-command/agentd/internal/protocol" + "github.com/agent-command/agentd/internal/tmux" + "github.com/agent-command/agentd/internal/ws" + "github.com/gorilla/websocket" +) + +func TestSyncPanesIncludesExtendedTmuxMetadata(t *testing.T) { + var sent protocol.SessionsUpsertPayload + agent := &Agent{ + cfg: &config.Config{Tmux: config.TmuxConfig{OptionSessionID: "@ac_session_id"}}, + sessions: make(map[string]*SessionState), + snapshotHash: make(map[string]string), + providerUsageHash: make(map[string]string), + lastPruneAt: time.Now(), + sendMessage: func(messageType string, payload any) error { + if messageType == protocol.TypeSessionsUpsert { + sent = payload.(protocol.SessionsUpsertPayload) + } + return nil + }, + } + + agent.syncPanes([]tmux.Pane{{ + PaneID: "%7", + PanePID: 1234, + SessionID: "session-123", + SessionName: "agents", + WindowName: "worker", + WindowIndex: 2, + PaneIndex: 1, + CurrentCommand: "bash", + PaneActive: true, + WindowActive: false, + WindowZoomed: true, + WindowLayout: "tiled", + PaneWidth: 190, + PaneHeight: 45, + WindowBell: true, + WindowActivity: false, + }}, nil) + + if len(sent.Sessions) != 1 { + t.Fatalf("sessions.upsert count=%d, want 1", len(sent.Sessions)) + } + tmuxMetadata := sent.Sessions[0].Metadata.Tmux + if tmuxMetadata == nil { + t.Fatal("tmux metadata is nil") + } + if !tmuxMetadata.PaneActive || tmuxMetadata.WindowActive || !tmuxMetadata.WindowZoomedFlag || + tmuxMetadata.WindowLayout != "tiled" || tmuxMetadata.PaneWidth != 190 || tmuxMetadata.PaneHeight != 45 || + !tmuxMetadata.WindowBellFlag || tmuxMetadata.WindowActivityFlag { + t.Fatalf("extended tmux metadata=%+v", tmuxMetadata) + } +} + +func TestBuildTmuxTopologySortsSessionsWindowsAndPanes(t *testing.T) { + panes := []tmux.Pane{ + {SessionName: "zeta", SessionAttached: true, WindowIndex: 2, WindowName: "later", PaneID: "%9", PaneIndex: 1}, + {SessionName: "alpha", WindowIndex: 1, WindowName: "main", WindowActive: true, WindowZoomed: true, WindowLayout: "tiled", WindowBell: true, PaneID: "%2", PaneIndex: 1, PaneWidth: 90, PaneHeight: 30, PaneTitle: "second", CurrentCommand: "bash", CurrentPath: "/tmp/two"}, + {SessionName: "alpha", WindowIndex: 1, WindowName: "main", WindowActive: true, WindowZoomed: true, WindowLayout: "tiled", WindowBell: true, PaneID: "%1", PaneIndex: 0, PaneActive: true, PaneWidth: 100, PaneHeight: 30, PaneTitle: "first", CurrentCommand: "codex", CurrentPath: "/tmp/one"}, + {SessionName: "alpha", WindowIndex: 0, WindowName: "early", PaneID: "%0", PaneIndex: 0}, + } + + got := buildTmuxTopology("hook:window-renamed", panes) + if got.Reason != "hook:window-renamed" || len(got.TmuxSessions) != 2 { + t.Fatalf("topology header/sessions=%+v", got) + } + if names := []string{got.TmuxSessions[0].SessionName, got.TmuxSessions[1].SessionName}; !reflect.DeepEqual(names, []string{"alpha", "zeta"}) { + t.Fatalf("session order=%v", names) + } + alpha := got.TmuxSessions[0] + if alpha.Attached || len(alpha.Windows) != 2 || alpha.Windows[0].WindowIndex != 0 || alpha.Windows[1].WindowIndex != 1 { + t.Fatalf("alpha topology=%+v", alpha) + } + mainWindow := alpha.Windows[1] + if !mainWindow.Active || !mainWindow.Zoomed || mainWindow.Layout != "tiled" || !mainWindow.Bell || mainWindow.Activity { + t.Fatalf("window topology=%+v", mainWindow) + } + if paneIDs := []string{mainWindow.Panes[0].PaneID, mainWindow.Panes[1].PaneID}; !reflect.DeepEqual(paneIDs, []string{"%1", "%2"}) { + t.Fatalf("pane order=%v", paneIDs) + } + if !mainWindow.Panes[0].Active || mainWindow.Panes[0].Width != 100 || mainWindow.Panes[0].CurrentCommand != "codex" { + t.Fatalf("pane topology=%+v", mainWindow.Panes[0]) + } +} + +func TestQueueTmuxTopologyDebouncesHooksAndPollsOnlyOnDrift(t *testing.T) { + messages := make(chan protocol.TmuxTopologyPayload, 3) + agent := &Agent{cfg: &config.Config{Tmux: config.TmuxConfig{TopologyEvents: true}}, sendMessage: func(messageType string, payload any) error { + if messageType == protocol.TypeTmuxTopology { + messages <- payload.(protocol.TmuxTopologyPayload) + } + return nil + }} + defer agent.stopTmuxTopology() + + panes := []tmux.Pane{{SessionName: "agents", WindowIndex: 0, PaneID: "%1", PaneWidth: 80}} + agent.queueTmuxTopology("hook:after-split-window", panes) + time.Sleep(100 * time.Millisecond) + agent.queueTmuxTopology("hook:window-renamed", panes) + + select { + case message := <-messages: + t.Fatalf("topology emitted before 500ms debounce: %+v", message) + case <-time.After(450 * time.Millisecond): + } + + var first protocol.TmuxTopologyPayload + select { + case first = <-messages: + case <-time.After(250 * time.Millisecond): + t.Fatal("timed out waiting for debounced topology") + } + if first.Reason != "hook:window-renamed" { + t.Fatalf("coalesced reason=%q", first.Reason) + } + + agent.queueTmuxTopology("poll", panes) + select { + case message := <-messages: + t.Fatalf("unchanged poll emitted topology: %+v", message) + case <-time.After(550 * time.Millisecond): + } + + panes[0].PaneWidth = 120 + agent.queueTmuxTopology("poll", panes) + select { + case message := <-messages: + if message.Reason != "poll" || message.TmuxSessions[0].Windows[0].Panes[0].Width != 120 { + t.Fatalf("drift topology=%+v", message) + } + case <-time.After(750 * time.Millisecond): + t.Fatal("timed out waiting for poll drift topology") + } +} + +func TestQueueTmuxTopologyDefaultOffWritesNoWebSocketFrame(t *testing.T) { + messages := make(chan string, 1) + upgrader := websocket.Upgrader{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + for { + var message struct { + Type string `json:"type"` + } + if err := conn.ReadJSON(&message); err != nil { + return + } + messages <- message.Type + } + })) + defer server.Close() + + wsClient := ws.NewClient("ws"+strings.TrimPrefix(server.URL, "http"), "token", "host", []int{1}) + if err := wsClient.Connect(); err != nil { + t.Fatal(err) + } + defer wsClient.Close() + if err := wsClient.ResendQueued(); err != nil { + t.Fatal(err) + } + + agent := &Agent{cfg: &config.Config{}, wsClient: wsClient} + defer agent.stopTmuxTopology() + agent.queueTmuxTopology("startup", []tmux.Pane{{SessionName: "agents", WindowIndex: 0, PaneID: "%1"}}) + + select { + case messageType := <-messages: + t.Fatalf("default-off topology wrote websocket frame %q", messageType) + case <-time.After(tmuxTopologyDebounce + 150*time.Millisecond): + } +} diff --git a/agents/agentd/cmd/agentd/tmux_topology.go b/agents/agentd/cmd/agentd/tmux_topology.go new file mode 100644 index 00000000..332cb4e8 --- /dev/null +++ b/agents/agentd/cmd/agentd/tmux_topology.go @@ -0,0 +1,152 @@ +package main + +import ( + "encoding/json" + "log" + "sort" + "time" + + "github.com/agent-command/agentd/internal/protocol" + "github.com/agent-command/agentd/internal/tmux" +) + +const tmuxTopologyDebounce = 500 * time.Millisecond + +func buildTmuxTopology(reason string, panes []tmux.Pane) protocol.TmuxTopologyPayload { + type windowKey struct { + sessionName string + windowIndex int + } + + sessionsByName := make(map[string]*protocol.TmuxTopologySession) + windowsByKey := make(map[windowKey]int) + for _, pane := range panes { + session := sessionsByName[pane.SessionName] + if session == nil { + session = &protocol.TmuxTopologySession{ + SessionName: pane.SessionName, + Windows: []protocol.TmuxTopologyWindow{}, + } + sessionsByName[pane.SessionName] = session + } + session.Attached = session.Attached || pane.SessionAttached + + key := windowKey{sessionName: pane.SessionName, windowIndex: pane.WindowIndex} + windowIndex, exists := windowsByKey[key] + if !exists { + session.Windows = append(session.Windows, protocol.TmuxTopologyWindow{ + WindowIndex: pane.WindowIndex, + WindowName: pane.WindowName, + Active: pane.WindowActive, + Zoomed: pane.WindowZoomed, + Layout: pane.WindowLayout, + Bell: pane.WindowBell, + Activity: pane.WindowActivity, + Panes: []protocol.TmuxTopologyPane{}, + }) + windowIndex = len(session.Windows) - 1 + windowsByKey[key] = windowIndex + } + window := &session.Windows[windowIndex] + window.Panes = append(window.Panes, protocol.TmuxTopologyPane{ + PaneID: pane.PaneID, + PaneIndex: pane.PaneIndex, + Active: pane.PaneActive, + Width: pane.PaneWidth, + Height: pane.PaneHeight, + Title: pane.PaneTitle, + CurrentCommand: pane.CurrentCommand, + CurrentPath: pane.CurrentPath, + }) + } + + sessions := make([]protocol.TmuxTopologySession, 0, len(sessionsByName)) + for _, session := range sessionsByName { + sort.Slice(session.Windows, func(i, j int) bool { + return session.Windows[i].WindowIndex < session.Windows[j].WindowIndex + }) + for index := range session.Windows { + sort.Slice(session.Windows[index].Panes, func(i, j int) bool { + return session.Windows[index].Panes[i].PaneIndex < session.Windows[index].Panes[j].PaneIndex + }) + } + sessions = append(sessions, *session) + } + sort.Slice(sessions, func(i, j int) bool { + return sessions[i].SessionName < sessions[j].SessionName + }) + + return protocol.TmuxTopologyPayload{Reason: reason, TmuxSessions: sessions} +} + +func tmuxTopologyHash(payload protocol.TmuxTopologyPayload) string { + data, err := json.Marshal(payload.TmuxSessions) + if err != nil { + return "" + } + return hashString(string(data)) +} + +func (a *Agent) queueTmuxTopology(reason string, panes []tmux.Pane) { + if a.cfg == nil || !a.cfg.Tmux.TopologyEvents { + return + } + + payload := buildTmuxTopology(reason, panes) + hash := tmuxTopologyHash(payload) + + a.tmuxTopologyMu.Lock() + defer a.tmuxTopologyMu.Unlock() + if a.tmuxTopologyStopped { + return + } + if reason == "poll" && (hash == a.lastTmuxTopologyHash || hash == a.pendingTmuxTopologyHash) { + return + } + + a.pendingTmuxTopology = &payload + a.pendingTmuxTopologyHash = hash + a.tmuxTopologyGeneration++ + generation := a.tmuxTopologyGeneration + if a.tmuxTopologyTimer != nil { + a.tmuxTopologyTimer.Stop() + } + a.tmuxTopologyTimer = time.AfterFunc(tmuxTopologyDebounce, func() { + a.emitPendingTmuxTopology(generation) + }) +} + +func (a *Agent) emitPendingTmuxTopology(generation uint64) { + a.tmuxTopologyMu.Lock() + if a.tmuxTopologyStopped || generation != a.tmuxTopologyGeneration || a.pendingTmuxTopology == nil { + a.tmuxTopologyMu.Unlock() + return + } + payload := *a.pendingTmuxTopology + hash := a.pendingTmuxTopologyHash + a.pendingTmuxTopology = nil + a.pendingTmuxTopologyHash = "" + a.tmuxTopologyTimer = nil + a.tmuxTopologyMu.Unlock() + + if err := a.send(protocol.TypeTmuxTopology, payload); err != nil { + log.Printf("Failed to emit tmux topology (%s): %v", payload.Reason, err) + return + } + a.tmuxTopologyMu.Lock() + a.lastTmuxTopologyHash = hash + a.tmuxTopologyMu.Unlock() +} + +func (a *Agent) stopTmuxTopology() { + a.tmuxTopologyMu.Lock() + defer a.tmuxTopologyMu.Unlock() + a.tmuxTopologyStopped = true + a.tmuxTopologyGeneration++ + if a.tmuxTopologyTimer != nil { + a.tmuxTopologyTimer.Stop() + a.tmuxTopologyTimer = nil + } + a.pendingTmuxTopology = nil + a.pendingTmuxTopologyHash = "" +} diff --git a/agents/agentd/config.example.yaml b/agents/agentd/config.example.yaml index a75924fb..a759efea 100644 --- a/agents/agentd/config.example.yaml +++ b/agents/agentd/config.example.yaml @@ -13,6 +13,7 @@ control_plane: tmux: bin: "/usr/bin/tmux" socket: "" # Leave empty for default (if you use -L, set /tmp/tmux-UID/