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