gunk-dev/the-valley

agent_pane.go

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