| 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 | func TestAgentsSessionName(t *testing.T) { |
| 148 | t.Run("uses KLAUS_SESSION_ID", func(t *testing.T) { |
| 149 | t.Setenv(sessionIDEnv, "session-20260907-1241-c0da2e6d") |
| 150 | if got, want := agentsSessionName(), "klaus-agents-session-20260907-1241-c0da2e6d"; got != want { |
| 151 | t.Errorf("agentsSessionName() = %q, want %q", got, want) |
| 152 | } |
| 153 | }) |
| 154 | |
| 155 | t.Run("replaces tmux target separators", func(t *testing.T) { |
| 156 | t.Setenv(sessionIDEnv, "a.b:c") |
| 157 | if got, want := agentsSessionName(), "klaus-agents-a-b-c"; got != want { |
| 158 | t.Errorf("agentsSessionName() = %q, want %q", got, want) |
| 159 | } |
| 160 | }) |
| 161 | |
| 162 | t.Run("falls back when unset", func(t *testing.T) { |
| 163 | t.Setenv(sessionIDEnv, "") |
| 164 | if got, want := agentsSessionName(), "klaus-agents"; got != want { |
| 165 | t.Errorf("agentsSessionName() = %q, want %q", got, want) |
| 166 | } |
| 167 | }) |
| 168 | } |
| 169 | |
| 170 | func TestKillEmptyAgentsSession(t *testing.T) { |
| 171 | t.Run("kills a session whose panes are all idle", func(t *testing.T) { |
| 172 | tc := isolatedTmux(t) |
| 173 | session := agentsSessionName() |
| 174 | tc.panes = map[string][]string{session: {"%1", "%2"}} |
| 175 | store := newFakeStore() |
| 176 | |
| 177 | out := captureStdout(t, func() { |
| 178 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 179 | }) |
| 180 | |
| 181 | if len(tc.killedSessions) != 1 || tc.killedSessions[0] != session { |
| 182 | t.Fatalf("expected KillSession(%q), got %v", session, tc.killedSessions) |
| 183 | } |
| 184 | if !contains(out, "killed agents tmux session "+session) { |
| 185 | t.Errorf("expected kill message, got: %s", out) |
| 186 | } |
| 187 | }) |
| 188 | |
| 189 | t.Run("keeps a session with a running pane even when the store is empty", func(t *testing.T) { |
| 190 | tc := isolatedTmux(t) |
| 191 | session := agentsSessionName() |
| 192 | tc.panes = map[string][]string{session: {"%1", "%2"}} |
| 193 | tc.runningPanes = map[string]bool{"%2": true} |
| 194 | // The store knows nothing about the panes — exactly the state a unit |
| 195 | // test's fake store is in (issue #295). tmux must still win. |
| 196 | store := newFakeStore() |
| 197 | |
| 198 | out := captureStdout(t, func() { |
| 199 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 200 | }) |
| 201 | |
| 202 | if len(tc.killedSessions) != 0 { |
| 203 | t.Fatalf("expected no KillSession calls, got %v", tc.killedSessions) |
| 204 | } |
| 205 | if !contains(out, "keeping agents tmux session "+session+" (pane %2 still running)") { |
| 206 | t.Errorf("expected skip message naming the live pane, got: %s", out) |
| 207 | } |
| 208 | }) |
| 209 | |
| 210 | t.Run("keeps a session whose panes are still held by a run", func(t *testing.T) { |
| 211 | tc := isolatedTmux(t) |
| 212 | session := agentsSessionName() |
| 213 | tc.panes = map[string][]string{session: {"%1"}} |
| 214 | pane := "%1" |
| 215 | store := newFakeStore(&run.State{ID: "run-1", TmuxPane: &pane}) |
| 216 | |
| 217 | captureStdout(t, func() { |
| 218 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 219 | }) |
| 220 | |
| 221 | if len(tc.killedSessions) != 0 { |
| 222 | t.Fatalf("expected no KillSession calls, got %v", tc.killedSessions) |
| 223 | } |
| 224 | }) |
| 225 | |
| 226 | // A run that recorded its tmux session is cleaned up by that name, the |
| 227 | // one flow gives the store's session, not one computed from this |
| 228 | // process's session ID; a run that recorded none by the computed legacy |
| 229 | // name. |
| 230 | t.Run("kills the session a run recorded", func(t *testing.T) { |
| 231 | tc := isolatedTmux(t) |
| 232 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session-other")) |
| 233 | legacy, recorded := agentsSessionName(), location.AgentsSession("session-other") |
| 234 | tc.panes = map[string][]string{legacy: {"%1"}, recorded: {"%2"}} |
| 235 | for _, s := range []*run.State{{ID: "run-1", TmuxSession: recorded}, {ID: "run-2"}} { |
| 236 | if err := store.Save(s); err != nil { |
| 237 | t.Fatal(err) |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | captureStdout(t, func() { |
| 242 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 243 | }) |
| 244 | |
| 245 | if want := []string{legacy, recorded}; !reflect.DeepEqual(tc.killedSessions, want) { |
| 246 | t.Fatalf("killed %v, want %v", tc.killedSessions, want) |
| 247 | } |
| 248 | }) |
| 249 | |
| 250 | // cleanup --all removes the runs first: the names come from them as they |
| 251 | // were. |
| 252 | t.Run("kills the session a removed run recorded", func(t *testing.T) { |
| 253 | tc := isolatedTmux(t) |
| 254 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session-other")) |
| 255 | recorded := location.AgentsSession("session-other") |
| 256 | tc.panes = map[string][]string{recorded: {"%2"}} |
| 257 | before := []*run.State{{ID: "run-1", TmuxSession: recorded}} |
| 258 | |
| 259 | captureStdout(t, func() { |
| 260 | killEmptyAgentsSession(context.Background(), before, store, tc) |
| 261 | }) |
| 262 | |
| 263 | if want := []string{recorded}; !reflect.DeepEqual(tc.killedSessions, want) { |
| 264 | t.Fatalf("killed %v, want %v", tc.killedSessions, want) |
| 265 | } |
| 266 | }) |
| 267 | |
| 268 | // A record can name any tmux session: one flow gives no agents session |
| 269 | // of the run's is never killed, however idle, and is warned about once. |
| 270 | t.Run("never kills a session flow did not name", func(t *testing.T) { |
| 271 | tc := isolatedTmux(t) |
| 272 | legacy := agentsSessionName() |
| 273 | tc.panes = map[string][]string{legacy: {"%1"}, "workstation": {"%2"}} |
| 274 | foreign := &run.State{ID: "run-1", TmuxSession: "workstation"} |
| 275 | |
| 276 | out := captureStdout(t, func() { |
| 277 | killEmptyAgentsSession(context.Background(), []*run.State{foreign}, newFakeStore(foreign), tc) |
| 278 | }) |
| 279 | |
| 280 | if want := []string{legacy}; !reflect.DeepEqual(tc.killedSessions, want) { |
| 281 | t.Fatalf("killed %v, want %v", tc.killedSessions, want) |
| 282 | } |
| 283 | var warnings []string |
| 284 | for _, line := range strings.Split(out, "\n") { |
| 285 | if strings.Contains(line, "warning") { |
| 286 | warnings = append(warnings, line) |
| 287 | } |
| 288 | } |
| 289 | if len(warnings) != 1 || !strings.Contains(warnings[0], "run-1") || !strings.Contains(warnings[0], "workstation") { |
| 290 | t.Errorf("want one warning naming run-1 and workstation, got %q", warnings) |
| 291 | } |
| 292 | }) |
| 293 | |
| 294 | t.Run("no-op when the session does not exist", func(t *testing.T) { |
| 295 | tc := isolatedTmux(t) |
| 296 | store := newFakeStore() |
| 297 | |
| 298 | killEmptyAgentsSession(context.Background(), nil, store, tc) |
| 299 | |
| 300 | if len(tc.killedSessions) != 0 { |
| 301 | t.Fatalf("expected no KillSession calls, got %v", tc.killedSessions) |
| 302 | } |
| 303 | }) |
| 304 | } |