| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "os" |
| 6 | "os/exec" |
| 7 | "path/filepath" |
| 8 | "reflect" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | |
| 12 | "the-valley/flow/internal/backend" |
| 13 | "the-valley/flow/internal/flowenv" |
| 14 | "the-valley/flow/internal/location" |
| 15 | "the-valley/flow/internal/run" |
| 16 | ) |
| 17 | |
| 18 | // A local worker of every backend runs cut off from its pane's tmux server: no |
| 19 | // $TMUX or $TMUX_PANE, a TMUX_TMPDIR of its own, and the server's socket only |
| 20 | // in socketEnv, for klaus. It gets its scratch directory as |
| 21 | // KLAUS_SCRATCH. A new spelling of these the pane inherits, which readers |
| 22 | // would prefer, is gone. _finalize runs after it in the pane's shell and keeps |
| 23 | // $TMUX. Runs the real pane command with stand-in binaries; nothing here runs |
| 24 | // tmux. |
| 25 | func TestWorkerRunsOutOfTmuxReach(t *testing.T) { |
| 26 | dir := t.TempDir() |
| 27 | sock := filepath.Join(dir, "shared.sock") |
| 28 | paneTMUX := sock + ",4242,0" |
| 29 | t.Setenv("TMUX", paneTMUX) |
| 30 | t.Setenv("TMUX_PANE", "%7") |
| 31 | t.Setenv(socketEnv, "") |
| 32 | t.Setenv(sessionIDEnv, "") |
| 33 | stale := []flowenv.Var{flowenv.TmuxSocket, flowenv.Scratch, flowenv.Backend, flowenv.RunID} |
| 34 | for _, v := range stale { |
| 35 | t.Setenv(v.New, filepath.Join(dir, "stale")) |
| 36 | } |
| 37 | |
| 38 | finalized := filepath.Join(dir, "finalize.tmux") |
| 39 | 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}"` |
| 40 | for _, v := range stale { |
| 41 | report += ` "` + v.New + `=${` + v.New + `-unset}"` |
| 42 | } |
| 43 | stubs := map[string]string{ |
| 44 | "klaus": "#!/bin/sh\ncase \"$1\" in\n_format-stream) cat ;;\n_finalize) printf '%s' \"${TMUX-unset}\" > " + shellQuote(finalized) + " ;;\nesac\n", |
| 45 | } |
| 46 | kinds := []backend.Kind{backend.Claude, backend.Codex, backend.Agy} |
| 47 | for _, kind := range kinds { |
| 48 | stubs[string(kind)] = "#!/bin/sh\n" + report + "\n" |
| 49 | } |
| 50 | for name, script := range stubs { |
| 51 | if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o700); err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | } |
| 55 | t.Setenv("PATH", dir+":"+os.Getenv("PATH")) |
| 56 | worktree := filepath.Join(dir, "worktree") |
| 57 | promptPath := filepath.Join(dir, "prompt.md") |
| 58 | for _, p := range []error{os.Mkdir(worktree, 0o700), run.WritePromptFile(promptPath, "go")} { |
| 59 | if p != nil { |
| 60 | t.Fatal(p) |
| 61 | } |
| 62 | } |
| 63 | o := backend.Options{SystemPrompt: "sys", SystemPromptFile: filepath.Join(dir, "sys.md"), Prompt: "go", RunID: "r", Budget: "5"} |
| 64 | |
| 65 | for _, kind := range kinds { |
| 66 | t.Run(string(kind), func(t *testing.T) { |
| 67 | os.Remove(finalized) |
| 68 | dirs := workerDirs{tmux: filepath.Join(dir, "tmux dirs", string(kind)), scratch: filepath.Join(dir, "scratch dirs", string(kind))} |
| 69 | command, err := agentPaneCommand(kind, o, promptPath, "", worktree, filepath.Join(dir, "log.jsonl"), "", "r", dirs) |
| 70 | if err != nil { |
| 71 | t.Fatal(err) |
| 72 | } |
| 73 | out, err := exec.Command("sh", "-c", command).CombinedOutput() |
| 74 | if err != nil { |
| 75 | t.Fatalf("%v: %s", err, out) |
| 76 | } |
| 77 | wants := []string{"TMUX=unset", "TMUX_PANE=unset", "TMUX_TMPDIR=" + dirs.tmux, socketEnv + "=" + sock, "KLAUS_BACKEND=" + string(kind), scratchEnv + "=" + dirs.scratch, runIDEnv + "=r"} |
| 78 | for _, v := range stale { |
| 79 | wants = append(wants, v.New+"=unset") |
| 80 | } |
| 81 | for _, want := range wants { |
| 82 | if !strings.Contains(string(out), want+"\n") { |
| 83 | t.Errorf("worker environment lacks %q:\n%s", want, out) |
| 84 | } |
| 85 | } |
| 86 | if got, _ := os.ReadFile(finalized); string(got) != paneTMUX { |
| 87 | t.Errorf("_finalize saw TMUX=%q, want the pane's %q", got, paneTMUX) |
| 88 | } |
| 89 | }) |
| 90 | } |
| 91 | |
| 92 | // No directory would leave TMUX_TMPDIR empty: tmux's default, the |
| 93 | // shared server's likely home. An empty KLAUS_SCRATCH would put |
| 94 | // "$KLAUS_SCRATCH/<name>" at the root. |
| 95 | for _, dirs := range []workerDirs{{scratch: "/scratch/r"}, {tmux: "/tmux/r"}} { |
| 96 | if _, err := agentPaneCommand(backend.Claude, o, promptPath, "", worktree, "/l.jsonl", "", "r", dirs); err == nil { |
| 97 | t.Errorf("a local worker with directories %+v got a pane command", dirs) |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | // A 40KB brief, over three times tmux's command limit, reaches an agy worker |
| 103 | // whole on stdin, after the system prompt, locally and across the ssh hop. |
| 104 | // Runs the real pane command with stand-in binaries; nothing here runs tmux. |
| 105 | func TestAgyWorkerReadsLongBriefOnStdin(t *testing.T) { |
| 106 | dir := t.TempDir() |
| 107 | received := filepath.Join(dir, "agy.stdin") |
| 108 | for name, script := range map[string]string{ |
| 109 | "agy": "#!/bin/sh\ncat > " + shellQuote(received) + "\n", |
| 110 | "ssh": "#!/bin/sh\nshift\nexec sh -c \"$1\"\n", |
| 111 | "rsync": "#!/bin/sh\nexit 0\n", |
| 112 | "klaus": "#!/bin/sh\nif [ \"$1\" = _format-stream ]; then cat; fi\n", |
| 113 | } { |
| 114 | if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o700); err != nil { |
| 115 | t.Fatal(err) |
| 116 | } |
| 117 | } |
| 118 | t.Setenv("PATH", dir+":"+os.Getenv("PATH")) |
| 119 | t.Setenv(sessionIDEnv, "") |
| 120 | worktree := filepath.Join(dir, "worktree") |
| 121 | if err := os.Mkdir(worktree, 0o700); err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | brief := "a brief with 'quotes' and $(exit 17)\n" + strings.Repeat("a line of a long brief\n", 40*1024/23) |
| 125 | o := backend.Options{SystemPrompt: "the system prompt", Prompt: brief, RunID: "r"} |
| 126 | inputFile := filepath.Join(dir, "prompts", "r.input.md") |
| 127 | if err := run.WritePromptFile(inputFile, backend.Agy.Stdin(o.SystemPrompt, o.Prompt)); err != nil { |
| 128 | t.Fatal(err) |
| 129 | } |
| 130 | for _, host := range []string{"", "sandbox-0"} { |
| 131 | t.Run("host="+host, func(t *testing.T) { |
| 132 | os.Remove(received) |
| 133 | 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")}) |
| 134 | if err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | if out, err := exec.Command("sh", "-c", command).CombinedOutput(); err != nil { |
| 138 | t.Fatalf("%v: %s", err, out) |
| 139 | } |
| 140 | if got, _ := os.ReadFile(received); string(got) != "the system prompt\n\n"+brief { |
| 141 | t.Fatalf("agy read %d bytes on stdin, want the system prompt and the %d-byte brief", len(got), len(brief)) |
| 142 | } |
| 143 | }) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | // A sandbox worker's shell starts from the sandbox's environment. Under |
| 148 | // bridge the worker gets each flow variable flow sets for it (run ID, run |
| 149 | // events, backend) under both names, and every other one under neither, |
| 150 | // though the sandbox holds disagreeing spellings; under legacy the remote |
| 151 | // command is the legacy one. Runs the real pane command with stand-in |
| 152 | // binaries; nothing here runs tmux. |
| 153 | func TestSandboxWorkerEnvironment(t *testing.T) { |
| 154 | dir := t.TempDir() |
| 155 | seen := filepath.Join(dir, "agy.env") |
| 156 | report := "#!/bin/sh\n: > " + shellQuote(seen) + "\n" |
| 157 | for _, v := range flowenv.All { |
| 158 | for _, name := range []string{v.New, v.Legacy} { |
| 159 | report += "printf '%s\\n' \"" + name + "=${" + name + "-unset}\" >> " + shellQuote(seen) + "\n" |
| 160 | } |
| 161 | } |
| 162 | // ssh runs the remote command in the sandbox's own environment. |
| 163 | sandbox := "PATH=\"$PATH\" " + flowenv.AgentBackend.New + "=codex " + flowenv.AgentBackend.Legacy + "=claude " + |
| 164 | flowenv.SessionID.New + "=session-a " + flowenv.Scratch.Legacy + "=/scratch " + flowenv.RunID.Legacy + "=stale" |
| 165 | for name, script := range map[string]string{ |
| 166 | "agy": report, |
| 167 | "ssh": "#!/bin/sh\nshift\nexec env -i " + sandbox + " sh -c \"$1\"\n", |
| 168 | "rsync": "#!/bin/sh\nexit 0\n", |
| 169 | "klaus": "#!/bin/sh\nif [ \"$1\" = _format-stream ]; then cat; fi\n", |
| 170 | } { |
| 171 | if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o700); err != nil { |
| 172 | t.Fatal(err) |
| 173 | } |
| 174 | } |
| 175 | t.Setenv("PATH", dir+":"+os.Getenv("PATH")) |
| 176 | worktree := filepath.Join(dir, "worktree") |
| 177 | if err := os.Mkdir(worktree, 0o700); err != nil { |
| 178 | t.Fatal(err) |
| 179 | } |
| 180 | o := backend.Options{SystemPrompt: "sys", Prompt: "go", RunID: "r"} |
| 181 | inputFile := filepath.Join(dir, "r.input.md") |
| 182 | if err := run.WritePromptFile(inputFile, backend.Agy.Stdin(o.SystemPrompt, o.Prompt)); err != nil { |
| 183 | t.Fatal(err) |
| 184 | } |
| 185 | command := func(t *testing.T) string { |
| 186 | t.Helper() |
| 187 | cmd, err := agentPaneCommand(backend.Agy, o, inputFile, "sandbox-0", worktree, filepath.Join(dir, "log.jsonl"), "", "r", workerDirs{}) |
| 188 | if err != nil { |
| 189 | t.Fatal(err) |
| 190 | } |
| 191 | return cmd |
| 192 | } |
| 193 | |
| 194 | t.Run("legacy", func(t *testing.T) { |
| 195 | t.Setenv("HOME", t.TempDir()) |
| 196 | remote := "unset VALLEY_FLOW_RUN_ID; export KLAUS_RUN_ID='r'; unset VALLEY_FLOW_RUN_EVENTS; export KLAUS_RUN_EVENTS='output'; cd " + |
| 197 | shellQuote(worktree) + " && env -u VALLEY_FLOW_BACKEND KLAUS_BACKEND='agy' " + backend.ShellCommand(backend.Agy.Worker(o)) |
| 198 | if cmd := command(t); !strings.Contains(cmd, "ssh 'sandbox-0' "+shellQuote(remote)+" <") { |
| 199 | t.Errorf("legacy sandbox command %q does not run %q", cmd, remote) |
| 200 | } |
| 201 | }) |
| 202 | |
| 203 | t.Run("bridge", func(t *testing.T) { |
| 204 | bridgeHost(t) |
| 205 | if out, err := exec.Command("sh", "-c", command(t)).CombinedOutput(); err != nil { |
| 206 | t.Fatalf("%v: %s", err, out) |
| 207 | } |
| 208 | data, err := os.ReadFile(seen) |
| 209 | if err != nil { |
| 210 | t.Fatal(err) |
| 211 | } |
| 212 | got := map[string]string{} |
| 213 | for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { |
| 214 | k, v, _ := strings.Cut(line, "=") |
| 215 | got[k] = v |
| 216 | } |
| 217 | want := map[string]string{} |
| 218 | for _, v := range flowenv.All { |
| 219 | want[v.New], want[v.Legacy] = "unset", "unset" |
| 220 | } |
| 221 | for v, value := range map[flowenv.Var]string{flowenv.RunID: "r", flowenv.RunEvents: runEventsOutput, flowenv.Backend: "agy"} { |
| 222 | want[v.New], want[v.Legacy] = value, value |
| 223 | } |
| 224 | if !reflect.DeepEqual(got, want) { |
| 225 | t.Errorf("sandbox worker environment = %v, want %v", got, want) |
| 226 | } |
| 227 | }) |
| 228 | } |
| 229 | |
| 230 | func TestAgentsSessionName(t *testing.T) { |
| 231 | t.Run("uses KLAUS_SESSION_ID", func(t *testing.T) { |
| 232 | t.Setenv(sessionIDEnv, "session-20260907-1241-c0da2e6d") |
| 233 | if got, want := agentsSessionName(), "klaus-agents-session-20260907-1241-c0da2e6d"; got != want { |
| 234 | t.Errorf("agentsSessionName() = %q, want %q", got, want) |
| 235 | } |
| 236 | }) |
| 237 | |
| 238 | t.Run("replaces tmux target separators", func(t *testing.T) { |
| 239 | t.Setenv(sessionIDEnv, "a.b:c") |
| 240 | if got, want := agentsSessionName(), "klaus-agents-a-b-c"; got != want { |
| 241 | t.Errorf("agentsSessionName() = %q, want %q", got, want) |
| 242 | } |
| 243 | }) |
| 244 | |
| 245 | t.Run("falls back when unset", func(t *testing.T) { |
| 246 | t.Setenv(sessionIDEnv, "") |
| 247 | if got, want := agentsSessionName(), "klaus-agents"; got != want { |
| 248 | t.Errorf("agentsSessionName() = %q, want %q", got, want) |
| 249 | } |
| 250 | }) |
| 251 | } |
| 252 | |
| 253 | func TestKillEmptyAgentsSession(t *testing.T) { |
| 254 | t.Run("kills a session whose panes are all idle", func(t *testing.T) { |
| 255 | tc := isolatedTmux(t) |
| 256 | session := agentsSessionName() |
| 257 | tc.panes = map[string][]string{session: {"%1", "%2"}} |
| 258 | store := newFakeStore() |
| 259 | |
| 260 | out := captureStdout(t, func() { |
| 261 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 262 | }) |
| 263 | |
| 264 | if len(tc.killedSessions) != 1 || tc.killedSessions[0] != session { |
| 265 | t.Fatalf("expected KillSession(%q), got %v", session, tc.killedSessions) |
| 266 | } |
| 267 | if !contains(out, "killed agents tmux session "+session) { |
| 268 | t.Errorf("expected kill message, got: %s", out) |
| 269 | } |
| 270 | }) |
| 271 | |
| 272 | t.Run("keeps a session with a running pane even when the store is empty", func(t *testing.T) { |
| 273 | tc := isolatedTmux(t) |
| 274 | session := agentsSessionName() |
| 275 | tc.panes = map[string][]string{session: {"%1", "%2"}} |
| 276 | tc.runningPanes = map[string]bool{"%2": true} |
| 277 | // The store knows nothing about the panes — exactly the state a unit |
| 278 | // test's fake store is in (issue #295). tmux must still win. |
| 279 | store := newFakeStore() |
| 280 | |
| 281 | out := captureStdout(t, func() { |
| 282 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 283 | }) |
| 284 | |
| 285 | if len(tc.killedSessions) != 0 { |
| 286 | t.Fatalf("expected no KillSession calls, got %v", tc.killedSessions) |
| 287 | } |
| 288 | if !contains(out, "keeping agents tmux session "+session+" (pane %2 still running)") { |
| 289 | t.Errorf("expected skip message naming the live pane, got: %s", out) |
| 290 | } |
| 291 | }) |
| 292 | |
| 293 | t.Run("keeps a session whose panes are still held by a run", func(t *testing.T) { |
| 294 | tc := isolatedTmux(t) |
| 295 | session := agentsSessionName() |
| 296 | tc.panes = map[string][]string{session: {"%1"}} |
| 297 | pane := "%1" |
| 298 | store := newFakeStore(&run.State{ID: "run-1", TmuxPane: &pane}) |
| 299 | |
| 300 | captureStdout(t, func() { |
| 301 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 302 | }) |
| 303 | |
| 304 | if len(tc.killedSessions) != 0 { |
| 305 | t.Fatalf("expected no KillSession calls, got %v", tc.killedSessions) |
| 306 | } |
| 307 | }) |
| 308 | |
| 309 | // A run that recorded its tmux session is cleaned up by that name, the |
| 310 | // one flow gives the store's session, not one computed from this |
| 311 | // process's session ID; a run that recorded none by the computed legacy |
| 312 | // name. |
| 313 | t.Run("kills the session a run recorded", func(t *testing.T) { |
| 314 | tc := isolatedTmux(t) |
| 315 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session-other")) |
| 316 | legacy, recorded := agentsSessionName(), location.AgentsSession("session-other") |
| 317 | tc.panes = map[string][]string{legacy: {"%1"}, recorded: {"%2"}} |
| 318 | for _, s := range []*run.State{{ID: "run-1", TmuxSession: recorded}, {ID: "run-2"}} { |
| 319 | if err := store.Save(s); err != nil { |
| 320 | t.Fatal(err) |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | captureStdout(t, func() { |
| 325 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 326 | }) |
| 327 | |
| 328 | if want := []string{legacy, recorded}; !reflect.DeepEqual(tc.killedSessions, want) { |
| 329 | t.Fatalf("killed %v, want %v", tc.killedSessions, want) |
| 330 | } |
| 331 | }) |
| 332 | |
| 333 | // cleanup --all removes the runs first: the names come from them as they |
| 334 | // were. |
| 335 | t.Run("kills the session a removed run recorded", func(t *testing.T) { |
| 336 | tc := isolatedTmux(t) |
| 337 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session-other")) |
| 338 | recorded := location.AgentsSession("session-other") |
| 339 | tc.panes = map[string][]string{recorded: {"%2"}} |
| 340 | before := []*run.State{{ID: "run-1", TmuxSession: recorded}} |
| 341 | |
| 342 | captureStdout(t, func() { |
| 343 | killEmptyAgentsSession(context.Background(), before, store, tc) |
| 344 | }) |
| 345 | |
| 346 | if want := []string{recorded}; !reflect.DeepEqual(tc.killedSessions, want) { |
| 347 | t.Fatalf("killed %v, want %v", tc.killedSessions, want) |
| 348 | } |
| 349 | }) |
| 350 | |
| 351 | // A record can name any tmux session: one flow gives no agents session |
| 352 | // of the run's is never killed, however idle, and is warned about once. |
| 353 | t.Run("never kills a session flow did not name", func(t *testing.T) { |
| 354 | tc := isolatedTmux(t) |
| 355 | legacy := agentsSessionName() |
| 356 | tc.panes = map[string][]string{legacy: {"%1"}, "workstation": {"%2"}} |
| 357 | foreign := &run.State{ID: "run-1", TmuxSession: "workstation"} |
| 358 | |
| 359 | out := captureStdout(t, func() { |
| 360 | killEmptyAgentsSession(context.Background(), []*run.State{foreign}, newFakeStore(foreign), tc) |
| 361 | }) |
| 362 | |
| 363 | if want := []string{legacy}; !reflect.DeepEqual(tc.killedSessions, want) { |
| 364 | t.Fatalf("killed %v, want %v", tc.killedSessions, want) |
| 365 | } |
| 366 | var warnings []string |
| 367 | for _, line := range strings.Split(out, "\n") { |
| 368 | if strings.Contains(line, "warning") { |
| 369 | warnings = append(warnings, line) |
| 370 | } |
| 371 | } |
| 372 | if len(warnings) != 1 || !strings.Contains(warnings[0], "run-1") || !strings.Contains(warnings[0], "workstation") { |
| 373 | t.Errorf("want one warning naming run-1 and workstation, got %q", warnings) |
| 374 | } |
| 375 | }) |
| 376 | |
| 377 | t.Run("no-op when the session does not exist", func(t *testing.T) { |
| 378 | tc := isolatedTmux(t) |
| 379 | store := newFakeStore() |
| 380 | |
| 381 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 382 | |
| 383 | if len(tc.killedSessions) != 0 { |
| 384 | t.Fatalf("expected no KillSession calls, got %v", tc.killedSessions) |
| 385 | } |
| 386 | }) |
| 387 | } |