gunk-dev/the-valley

agent_pane_test.go

sourceb8e46aa6aaccmain's published tip history
8.7 KiB
1package cmd
2
3import (
4 "context"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10
11 "the-valley/flow/internal/backend"
12 "the-valley/flow/internal/flowenv"
13 "the-valley/flow/internal/run"
14)
15
16// A local worker of every backend runs cut off from its pane's tmux server: no
17// $TMUX or $TMUX_PANE, a TMUX_TMPDIR of its own, and the server's socket only
18// in socketEnv, for klaus. It gets its scratch directory as
19// KLAUS_SCRATCH. A new spelling of these the pane inherits, which readers
20// would prefer, is gone. _finalize runs after it in the pane's shell and keeps
21// $TMUX. Runs the real pane command with stand-in binaries; nothing here runs
22// tmux.
23func TestWorkerRunsOutOfTmuxReach(t *testing.T) {
24 dir := t.TempDir()
25 sock := filepath.Join(dir, "shared.sock")
26 paneTMUX := sock + ",4242,0"
27 t.Setenv("TMUX", paneTMUX)
28 t.Setenv("TMUX_PANE", "%7")
29 t.Setenv(socketEnv, "")
30 t.Setenv(sessionIDEnv, "")
31 stale := []flowenv.Var{flowenv.TmuxSocket, flowenv.Scratch, flowenv.Backend, flowenv.RunID}
32 for _, v := range stale {
33 t.Setenv(v.New, filepath.Join(dir, "stale"))
34 }
35
36 finalized := filepath.Join(dir, "finalize.tmux")
37 report := `printf '%s\n' "TMUX=${TMUX-unset}" "TMUX_PANE=${TMUX_PANE-unset}" "TMUX_TMPDIR=${TMUX_TMPDIR-unset}" "` + socketEnv + `=${` + socketEnv + `-unset}" "KLAUS_BACKEND=${KLAUS_BACKEND-unset}" "` + scratchEnv + `=${` + scratchEnv + `-unset}" "` + runIDEnv + `=${` + runIDEnv + `-unset}"`
38 for _, v := range stale {
39 report += ` "` + v.New + `=${` + v.New + `-unset}"`
40 }
41 stubs := map[string]string{
42 "klaus": "#!/bin/sh\ncase \"$1\" in\n_format-stream) cat ;;\n_finalize) printf '%s' \"${TMUX-unset}\" > " + shellQuote(finalized) + " ;;\nesac\n",
43 }
44 kinds := []backend.Kind{backend.Claude, backend.Codex, backend.Agy}
45 for _, kind := range kinds {
46 stubs[string(kind)] = "#!/bin/sh\n" + report + "\n"
47 }
48 for name, script := range stubs {
49 if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o700); err != nil {
50 t.Fatal(err)
51 }
52 }
53 t.Setenv("PATH", dir+":"+os.Getenv("PATH"))
54 worktree := filepath.Join(dir, "worktree")
55 promptPath := filepath.Join(dir, "prompt.md")
56 for _, p := range []error{os.Mkdir(worktree, 0o700), run.WritePromptFile(promptPath, "go")} {
57 if p != nil {
58 t.Fatal(p)
59 }
60 }
61 o := backend.Options{SystemPrompt: "sys", SystemPromptFile: filepath.Join(dir, "sys.md"), Prompt: "go", RunID: "r", Budget: "5"}
62
63 for _, kind := range kinds {
64 t.Run(string(kind), func(t *testing.T) {
65 os.Remove(finalized)
66 dirs := workerDirs{tmux: filepath.Join(dir, "tmux dirs", string(kind)), scratch: filepath.Join(dir, "scratch dirs", string(kind))}
67 command, err := agentPaneCommand(kind, o, promptPath, "", worktree, filepath.Join(dir, "log.jsonl"), "", "r", dirs)
68 if err != nil {
69 t.Fatal(err)
70 }
71 out, err := exec.Command("sh", "-c", command).CombinedOutput()
72 if err != nil {
73 t.Fatalf("%v: %s", err, out)
74 }
75 wants := []string{"TMUX=unset", "TMUX_PANE=unset", "TMUX_TMPDIR=" + dirs.tmux, socketEnv + "=" + sock, "KLAUS_BACKEND=" + string(kind), scratchEnv + "=" + dirs.scratch, runIDEnv + "=r"}
76 for _, v := range stale {
77 wants = append(wants, v.New+"=unset")
78 }
79 for _, want := range wants {
80 if !strings.Contains(string(out), want+"\n") {
81 t.Errorf("worker environment lacks %q:\n%s", want, out)
82 }
83 }
84 if got, _ := os.ReadFile(finalized); string(got) != paneTMUX {
85 t.Errorf("_finalize saw TMUX=%q, want the pane's %q", got, paneTMUX)
86 }
87 })
88 }
89
90 // No directory would leave TMUX_TMPDIR empty: tmux's default, the
91 // shared server's likely home. An empty KLAUS_SCRATCH would put
92 // "$KLAUS_SCRATCH/<name>" at the root.
93 for _, dirs := range []workerDirs{{scratch: "/scratch/r"}, {tmux: "/tmux/r"}} {
94 if _, err := agentPaneCommand(backend.Claude, o, promptPath, "", worktree, "/l.jsonl", "", "r", dirs); err == nil {
95 t.Errorf("a local worker with directories %+v got a pane command", dirs)
96 }
97 }
98}
99
100// A 40KB brief, over three times tmux's command limit, reaches an agy worker
101// whole on stdin, after the system prompt, locally and across the ssh hop.
102// Runs the real pane command with stand-in binaries; nothing here runs tmux.
103func TestAgyWorkerReadsLongBriefOnStdin(t *testing.T) {
104 dir := t.TempDir()
105 received := filepath.Join(dir, "agy.stdin")
106 for name, script := range map[string]string{
107 "agy": "#!/bin/sh\ncat > " + shellQuote(received) + "\n",
108 "ssh": "#!/bin/sh\nshift\nexec sh -c \"$1\"\n",
109 "rsync": "#!/bin/sh\nexit 0\n",
110 "klaus": "#!/bin/sh\nif [ \"$1\" = _format-stream ]; then cat; fi\n",
111 } {
112 if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o700); err != nil {
113 t.Fatal(err)
114 }
115 }
116 t.Setenv("PATH", dir+":"+os.Getenv("PATH"))
117 t.Setenv(sessionIDEnv, "")
118 worktree := filepath.Join(dir, "worktree")
119 if err := os.Mkdir(worktree, 0o700); err != nil {
120 t.Fatal(err)
121 }
122 brief := "a brief with 'quotes' and $(exit 17)\n" + strings.Repeat("a line of a long brief\n", 40*1024/23)
123 o := backend.Options{SystemPrompt: "the system prompt", Prompt: brief, RunID: "r"}
124 inputFile := filepath.Join(dir, "prompts", "r.input.md")
125 if err := run.WritePromptFile(inputFile, backend.Agy.Stdin(o.SystemPrompt, o.Prompt)); err != nil {
126 t.Fatal(err)
127 }
128 for _, host := range []string{"", "sandbox-0"} {
129 t.Run("host="+host, func(t *testing.T) {
130 os.Remove(received)
131 command, err := agentPaneCommand(backend.Agy, o, inputFile, host, worktree, filepath.Join(dir, "log.jsonl"), "", "r", workerDirs{tmux: filepath.Join(dir, "tmux"), scratch: filepath.Join(dir, "scratch")})
132 if err != nil {
133 t.Fatal(err)
134 }
135 if out, err := exec.Command("sh", "-c", command).CombinedOutput(); err != nil {
136 t.Fatalf("%v: %s", err, out)
137 }
138 if got, _ := os.ReadFile(received); string(got) != "the system prompt\n\n"+brief {
139 t.Fatalf("agy read %d bytes on stdin, want the system prompt and the %d-byte brief", len(got), len(brief))
140 }
141 })
142 }
143}
144
145func TestAgentsSessionName(t *testing.T) {
146 t.Run("uses KLAUS_SESSION_ID", func(t *testing.T) {
147 t.Setenv(sessionIDEnv, "session-20260907-1241-c0da2e6d")
148 if got, want := agentsSessionName(), "klaus-agents-session-20260907-1241-c0da2e6d"; got != want {
149 t.Errorf("agentsSessionName() = %q, want %q", got, want)
150 }
151 })
152
153 t.Run("replaces tmux target separators", func(t *testing.T) {
154 t.Setenv(sessionIDEnv, "a.b:c")
155 if got, want := agentsSessionName(), "klaus-agents-a-b-c"; got != want {
156 t.Errorf("agentsSessionName() = %q, want %q", got, want)
157 }
158 })
159
160 t.Run("falls back when unset", func(t *testing.T) {
161 t.Setenv(sessionIDEnv, "")
162 if got, want := agentsSessionName(), "klaus-agents"; got != want {
163 t.Errorf("agentsSessionName() = %q, want %q", got, want)
164 }
165 })
166}
167
168func TestKillEmptyAgentsSession(t *testing.T) {
169 t.Run("kills a session whose panes are all idle", func(t *testing.T) {
170 tc := isolatedTmux(t)
171 session := agentsSessionName()
172 tc.panes = map[string][]string{session: {"%1", "%2"}}
173 store := newFakeStore()
174
175 out := captureStdout(t, func() {
176 killEmptyAgentsSession(context.Background(), store, tc)
177 })
178
179 if len(tc.killedSessions) != 1 || tc.killedSessions[0] != session {
180 t.Fatalf("expected KillSession(%q), got %v", session, tc.killedSessions)
181 }
182 if !contains(out, "killed agents tmux session "+session) {
183 t.Errorf("expected kill message, got: %s", out)
184 }
185 })
186
187 t.Run("keeps a session with a running pane even when the store is empty", func(t *testing.T) {
188 tc := isolatedTmux(t)
189 session := agentsSessionName()
190 tc.panes = map[string][]string{session: {"%1", "%2"}}
191 tc.runningPanes = map[string]bool{"%2": true}
192 // The store knows nothing about the panes — exactly the state a unit
193 // test's fake store is in (issue #295). tmux must still win.
194 store := newFakeStore()
195
196 out := captureStdout(t, func() {
197 killEmptyAgentsSession(context.Background(), store, tc)
198 })
199
200 if len(tc.killedSessions) != 0 {
201 t.Fatalf("expected no KillSession calls, got %v", tc.killedSessions)
202 }
203 if !contains(out, "keeping agents tmux session "+session+" (pane %2 still running)") {
204 t.Errorf("expected skip message naming the live pane, got: %s", out)
205 }
206 })
207
208 t.Run("keeps a session whose panes are still held by a run", func(t *testing.T) {
209 tc := isolatedTmux(t)
210 session := agentsSessionName()
211 tc.panes = map[string][]string{session: {"%1"}}
212 pane := "%1"
213 store := newFakeStore(&run.State{ID: "run-1", TmuxPane: &pane})
214
215 captureStdout(t, func() {
216 killEmptyAgentsSession(context.Background(), store, tc)
217 })
218
219 if len(tc.killedSessions) != 0 {
220 t.Fatalf("expected no KillSession calls, got %v", tc.killedSessions)
221 }
222 })
223
224 t.Run("no-op when the session does not exist", func(t *testing.T) {
225 tc := isolatedTmux(t)
226 store := newFakeStore()
227
228 killEmptyAgentsSession(context.Background(), store, tc)
229
230 if len(tc.killedSessions) != 0 {
231 t.Fatalf("expected no KillSession calls, got %v", tc.killedSessions)
232 }
233 })
234}