| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | |
| 10 | "the-valley/flow/internal/config" |
| 11 | "the-valley/flow/internal/flowenv" |
| 12 | "the-valley/flow/internal/run" |
| 13 | "the-valley/flow/internal/tmux" |
| 14 | ) |
| 15 | |
| 16 | // agentsSessionName is the detached tmux session holding this klaus session's |
| 17 | // agent panes. It is per-klaus-session so concurrent coordinators never share |
| 18 | // windows, and it is owned by the tmux server — so agents survive the |
| 19 | // coordinator exiting. |
| 20 | // |
| 21 | // Careful: agent panes export KLAUS_SESSION_ID (see tmuxSessionEnvPrefix), so |
| 22 | // every process an agent starts inside its worktree — including `go test` — |
| 23 | // inherits the coordinator's session id and resolves this to the live agents |
| 24 | // session. Tests must never let a real tmux client see this name; use a fake |
| 25 | // tmux client and t.Setenv(sessionIDEnv, ...) to pin it. |
| 26 | func agentsSessionName() string { |
| 27 | id := sessionIDFromEnv() |
| 28 | if id == "" { |
| 29 | return "klaus-agents" |
| 30 | } |
| 31 | // tmux treats "." and ":" as target separators. |
| 32 | return "klaus-agents-" + strings.NewReplacer(".", "-", ":", "-").Replace(id) |
| 33 | } |
| 34 | |
| 35 | // workerDirs are a local worker's own directories, which launch creates. |
| 36 | type workerDirs struct { |
| 37 | tmux string // TMUX_TMPDIR (workerTmuxDir) |
| 38 | scratch string // flowenv.Scratch (workerScratchDir) |
| 39 | } |
| 40 | |
| 41 | // workerTmuxDir is the TMUX_TMPDIR a run's worker gets: the run's own, beside |
| 42 | // the store's logs/, where no server runs until the worker starts one. |
| 43 | func workerTmuxDir(store run.StateStore, runID string) string { |
| 44 | return filepath.Join(filepath.Dir(store.LogDir()), "tmux", runID) |
| 45 | } |
| 46 | |
| 47 | // workerScratchDir is where a run's worker puts build output and other |
| 48 | // scratch files, beside the store's logs/ and so outside the worktree, where |
| 49 | // finalize would salvage them into a commit. cleanupWorktree removes it with |
| 50 | // the worktree. |
| 51 | func workerScratchDir(store run.StateStore, runID string) string { |
| 52 | return filepath.Join(filepath.Dir(store.LogDir()), "scratch", runID) |
| 53 | } |
| 54 | |
| 55 | // workerEnv starts a local worker cut off from the tmux server its pane runs |
| 56 | // in, with dirs.scratch as its scratch directory (flowenv.Scratch). In a pane |
| 57 | // $TMUX names that server and overrides TMUX_TMPDIR, so a worker's |
| 58 | // `TMUX_TMPDIR=<test dir> tmux kill-server` once killed the shared server: the |
| 59 | // operator's session, the coordinator and every agent's pane. The worker gets |
| 60 | // no $TMUX or $TMUX_PANE, and dirs.tmux as TMUX_TMPDIR, so a bare tmux there |
| 61 | // finds no server. klaus commands the worker runs (_pre-review, status, logs) |
| 62 | // reach the shared server through flowenv.TmuxSocket instead, which holds the |
| 63 | // socket flow found or nothing. _finalize, budget pause included, runs after |
| 64 | // the worker in the pane's own shell and keeps the pane's $TMUX. |
| 65 | func workerEnv(dirs workerDirs) string { |
| 66 | env := "env -u TMUX -u TMUX_PANE TMUX_TMPDIR=" + shellQuote(dirs.tmux) + " " + flowenv.Scratch.EnvPrefix(dirs.scratch) |
| 67 | if sock := tmux.SocketPath(); sock != "" { |
| 68 | return env + flowenv.TmuxSocket.EnvPrefix(sock) |
| 69 | } |
| 70 | return env + flowenv.TmuxSocket.UnsetPrefix() |
| 71 | } |
| 72 | |
| 73 | // startAgentPane creates the tmux pane an agent runs in and applies the |
| 74 | // standard title/rename settings. |
| 75 | // |
| 76 | // In detached mode (the default) the pane is a window in the agents session, |
| 77 | // so the coordinator's window is left alone and splitFrom comes back empty. In |
| 78 | // "pane" mode the coordinator's window is split and splitFrom is the pane that |
| 79 | // was split, so the caller can re-pin its layout. |
| 80 | func startAgentPane(ctx context.Context, tc tmux.Client, mode, runID, dir, paneCmd, title string) (paneID, splitFrom string, err error) { |
| 81 | if mode == config.AgentDisplayPane { |
| 82 | splitFrom = os.Getenv("TMUX_PANE") |
| 83 | paneID, err = tc.SplitWindow(ctx, splitFrom, dir, paneCmd) |
| 84 | } else { |
| 85 | paneID, err = tc.NewDetachedWindow(ctx, agentsSessionName(), runID, dir, paneCmd) |
| 86 | } |
| 87 | if err != nil { |
| 88 | return "", "", fmt.Errorf("creating tmux pane: %w", err) |
| 89 | } |
| 90 | |
| 91 | if err := tc.SetPaneTitle(ctx, paneID, title); err != nil { |
| 92 | fmt.Fprintf(os.Stderr, "warning: failed to set pane title: %v\n", err) |
| 93 | } |
| 94 | if err := tc.SetWindowOption(ctx, paneID, "automatic-rename", "off"); err != nil { |
| 95 | fmt.Fprintf(os.Stderr, "warning: failed to disable automatic rename: %v\n", err) |
| 96 | } |
| 97 | if err := tc.LockPaneTitle(ctx, paneID); err != nil { |
| 98 | fmt.Fprintf(os.Stderr, "warning: failed to lock pane title: %v\n", err) |
| 99 | } |
| 100 | |
| 101 | if splitFrom != "" { |
| 102 | if err := tc.RebalanceLayout(ctx, splitFrom); err != nil { |
| 103 | return paneID, splitFrom, fmt.Errorf("rebalancing tmux layout: %w", err) |
| 104 | } |
| 105 | } |
| 106 | return paneID, splitFrom, nil |
| 107 | } |
| 108 | |
| 109 | // killEmptyAgentsSession drops the detached agents session once no remaining |
| 110 | // run holds a pane in it. tmux already destroys a session whose last window |
| 111 | // closes; this covers leftovers (e.g. a window whose command exited into a |
| 112 | // shell) so `klaus cleanup --all` leaves nothing behind. |
| 113 | // |
| 114 | // The store is only advisory — it can be stale, or belong to a different |
| 115 | // klaus session entirely — so the tmux server gets the final say: a session |
| 116 | // with any pane still running a command is never killed. |
| 117 | func killEmptyAgentsSession(ctx context.Context, store run.StateStore, tc tmux.Client) { |
| 118 | name := agentsSessionName() |
| 119 | panes, err := tc.SessionPanes(ctx, name) |
| 120 | if err != nil { |
| 121 | return // session does not exist — nothing to do |
| 122 | } |
| 123 | |
| 124 | // The tmux server is the truth: a pane whose command is still running |
| 125 | // belongs to a live agent, whatever the store says about it. |
| 126 | for _, p := range panes { |
| 127 | if tc.PaneExists(ctx, p) && !tc.PaneIsIdle(ctx, p) { |
| 128 | fmt.Printf(" keeping agents tmux session %s (pane %s still running)\n", name, p) |
| 129 | return |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | states, err := store.List() |
| 134 | if err != nil { |
| 135 | return |
| 136 | } |
| 137 | held := make(map[string]bool, len(states)) |
| 138 | for _, s := range states { |
| 139 | if s.TmuxPane != nil { |
| 140 | held[*s.TmuxPane] = true |
| 141 | } |
| 142 | } |
| 143 | for _, p := range panes { |
| 144 | if held[p] { |
| 145 | fmt.Printf(" keeping agents tmux session %s (pane %s still held by a run)\n", name, p) |
| 146 | return |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | if err := tc.KillSession(ctx, name); err == nil { |
| 151 | fmt.Printf(" killed agents tmux session %s\n", name) |
| 152 | } |
| 153 | } |