gunk-dev/the-valley

agent_pane_test.go

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