| 1 | //go:build e2e |
| 2 | |
| 3 | package e2e |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "the-valley/flow/internal/config" |
| 8 | "the-valley/flow/internal/run" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | func TestBackendWorkerLifecycle(t *testing.T) { |
| 17 | for _, kind := range []string{"codex", "agy"} { |
| 18 | for _, failed := range []bool{false, true} { |
| 19 | t.Run(fmt.Sprintf("%s/failure=%t", kind, failed), func(t *testing.T) { |
| 20 | t.Parallel() |
| 21 | h := NewHarness(t) |
| 22 | // A PR run, so finalize takes the PR URL the worker reports. |
| 23 | h.UseGitHubOrigin() |
| 24 | output := `{"type":"thread.started","thread_id":"codex-thread"} |
| 25 | {"type":"item.completed","item":{"type":"agent_message","text":"https://github.com/acme/widget/pull/42"}} |
| 26 | {"type":"turn.completed","usage":{"input_tokens":7,"output_tokens":3}}` |
| 27 | sessionID := "codex-thread" |
| 28 | if kind == "agy" { |
| 29 | sessionID = "agy-conversation" |
| 30 | output = `{"event":"init","conversation_id":"agy-conversation","init":{"model":"test"}} |
| 31 | {"event":"step_update","step_update":{"step_type":"agent_response","text_delta":"Done","state":"DONE"}} |
| 32 | {"event":"result","result":{"conversation_id":"agy-conversation","status":"SUCCESS","response":"https://github.com/acme/widget/pull/42","duration_seconds":1}}` |
| 33 | } |
| 34 | status := 0 |
| 35 | if failed { |
| 36 | output = "" |
| 37 | status = 7 |
| 38 | } |
| 39 | h.WriteStub(kind, h.claudeStubScript()+fmt.Sprintf("\nexit %d\n", status)) |
| 40 | if err := os.WriteFile(filepath.Join(h.E2EDir, "claude.output.jsonl"), []byte(output+"\n"), 0600); err != nil { |
| 41 | t.Fatal(err) |
| 42 | } |
| 43 | res := h.RunKlaus("launch", "--backend", kind, "--model", "test-model", "task 'quoted' $(false)") |
| 44 | if res.ExitCode != 0 { |
| 45 | t.Fatalf("launch: %s%s", res.Stdout, res.Stderr) |
| 46 | } |
| 47 | ids := h.RunIDs() |
| 48 | if len(ids) != 1 { |
| 49 | t.Fatalf("runs: %v", ids) |
| 50 | } |
| 51 | h.WaitForClaudeStart(15 * time.Second) |
| 52 | argv := h.ClaudeArgv() |
| 53 | if kind == "agy" && !strings.Contains(argv, "--add-dir\n.\n") { |
| 54 | t.Fatal("agy worker missing explicit workspace") |
| 55 | } |
| 56 | if strings.Contains(argv, "--max-budget-usd") || !strings.Contains(argv, "test-model") { |
| 57 | t.Fatalf("bad args: %s", argv) |
| 58 | } |
| 59 | // Both read the prompt on stdin. |
| 60 | if !strings.Contains(h.ClaudeStdin(), "task 'quoted' $(false)") || strings.Contains(argv, "task 'quoted'") { |
| 61 | t.Fatalf("prompt not delivered on stdin alone: argv %q stdin %q", argv, h.ClaudeStdin()) |
| 62 | } |
| 63 | releaseBackendWorkers(t, h) |
| 64 | st := h.WaitForState(ids[0], func(s *run.State) bool { return s.DurationMS != nil }, 15*time.Second) |
| 65 | if st.Backend != kind || st.Budget != nil || st.CostUSD != nil { |
| 66 | t.Fatalf("incorrect backend/budget/cost: %+v", st) |
| 67 | } |
| 68 | if failed { |
| 69 | if st.FailureReason == nil || !strings.Contains(*st.FailureReason, "status 7") { |
| 70 | t.Fatalf("missing failure: %+v", st) |
| 71 | } |
| 72 | } else { |
| 73 | if st.FailureReason != nil || st.PRURL == nil || *st.PRURL != "https://github.com/acme/widget/pull/42" { |
| 74 | t.Fatalf("incorrect completion: %+v", st) |
| 75 | } |
| 76 | if st.BackendSessionID == nil || *st.BackendSessionID != sessionID { |
| 77 | t.Fatalf("lost conversation identity: %+v", st) |
| 78 | } |
| 79 | if st.ClaudeSessionID != nil { |
| 80 | t.Fatal("non-Claude identity stored as Claude") |
| 81 | } |
| 82 | } |
| 83 | }) |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | // A brief far over tmux's command limit reaches an agy worker whole, on stdin |
| 89 | // after the system prompt, which agy has no flag for. |
| 90 | func TestAgyWorkerReadsLongPrompt(t *testing.T) { |
| 91 | t.Parallel() |
| 92 | h := NewHarness(t) |
| 93 | h.WriteStub("agy", h.claudeStubScript()) |
| 94 | prompt := "a brief with 'quotes', $(false) and #{pane_id}\n" + strings.Repeat("a line of a long brief\n", 40*1024/23) + "the brief's last line\n" |
| 95 | promptFile := filepath.Join(h.E2EDir, "brief.md") |
| 96 | if err := os.WriteFile(promptFile, []byte(prompt), 0o600); err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | res := h.RunKlaus("launch", "--backend", "agy", "--prompt-file", promptFile) |
| 100 | if res.ExitCode != 0 { |
| 101 | t.Fatalf("launch: %s%s", res.Stdout, res.Stderr) |
| 102 | } |
| 103 | h.WaitForClaudeStart(15 * time.Second) |
| 104 | if stdin := h.ClaudeStdin(); !strings.HasSuffix(stdin, config.WorkerRules+"\n\n"+prompt) { |
| 105 | t.Fatalf("agy got %d bytes on stdin, not the system prompt and the %d-byte brief", len(stdin), len(prompt)) |
| 106 | } |
| 107 | if argv := h.ClaudeArgv(); strings.Contains(argv, "a line of a long brief") || strings.Contains(argv, "\n--print\n") { |
| 108 | t.Fatalf("brief in agy's argv: %.300s", argv) |
| 109 | } |
| 110 | releaseBackendWorkers(t, h) |
| 111 | } |
| 112 | |
| 113 | func TestCoordinatorBackendSelection(t *testing.T) { |
| 114 | for _, kind := range []string{"claude", "codex", "agy"} { |
| 115 | t.Run(kind, func(t *testing.T) { |
| 116 | t.Parallel() |
| 117 | h := NewHarness(t) |
| 118 | argsFile := filepath.Join(h.E2EDir, "coordinator.args") |
| 119 | h.WriteStub(kind, fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' \"$@\" > %q\n", argsFile)) |
| 120 | res := h.RunKlausIn(h.E2EDir, "new", "--backend", kind, "--agent-backend", "agy") |
| 121 | if res.ExitCode != 0 { |
| 122 | t.Fatalf("coordinator: %s%s", res.Stdout, res.Stderr) |
| 123 | } |
| 124 | entries, err := os.ReadDir(filepath.Join(h.Home, ".klaus", "sessions")) |
| 125 | if err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | var session *run.State |
| 129 | for _, e := range entries { |
| 130 | store := run.NewHomeDirStoreFromPath(filepath.Join(h.Home, ".klaus", "sessions", e.Name())) |
| 131 | st, err := store.Load(e.Name()) |
| 132 | if err == nil && st.Type == "session" { |
| 133 | session = st |
| 134 | break |
| 135 | } |
| 136 | } |
| 137 | if session == nil || session.Backend != kind || session.AgentBackend != "agy" { |
| 138 | t.Fatalf("session selection not saved: %+v", session) |
| 139 | } |
| 140 | argv, err := os.ReadFile(argsFile) |
| 141 | if err != nil { |
| 142 | t.Fatal(err) |
| 143 | } |
| 144 | if kind == "agy" && !strings.Contains(string(argv), "--add-dir\n.\n") { |
| 145 | t.Fatal("agy coordinator missing explicit workspace") |
| 146 | } |
| 147 | if !strings.Contains(string(argv), "valley flow launch") { |
| 148 | t.Fatalf("coordinator instructions missing: %s", argv) |
| 149 | } |
| 150 | // Resume must keep the saved backend, even though the configured default is Claude. |
| 151 | res = h.RunKlausIn(h.E2EDir, "session") |
| 152 | if res.ExitCode != 0 { |
| 153 | t.Fatalf("resume: %s%s", res.Stdout, res.Stderr) |
| 154 | } |
| 155 | argv, err = os.ReadFile(argsFile) |
| 156 | if err != nil { |
| 157 | t.Fatal(err) |
| 158 | } |
| 159 | if kind == "codex" && !strings.Contains(string(argv), "resume\n--last") { |
| 160 | t.Fatalf("not resuming codex: %s", argv) |
| 161 | } |
| 162 | // The worker selection is independent of the coordinator and is |
| 163 | // read from saved session state by a separate process (as in CI dispatch). |
| 164 | h.SessionID = session.ID |
| 165 | h.WriteStub("agy", h.claudeStubScript()) |
| 166 | res = h.RunKlaus("launch", "worker selected by session") |
| 167 | if res.ExitCode != 0 { |
| 168 | t.Fatalf("worker launch: %s%s", res.Stdout, res.Stderr) |
| 169 | } |
| 170 | h.WaitForClaudeStart(15 * time.Second) |
| 171 | found := false |
| 172 | for _, id := range h.RunIDs() { |
| 173 | st, err := h.ReadState(id) |
| 174 | if err == nil && st.Type != "session" { |
| 175 | found = true |
| 176 | if st.Backend != "agy" { |
| 177 | t.Fatalf("worker backend = %s", st.Backend) |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | if !found { |
| 182 | t.Fatal("worker state missing") |
| 183 | } |
| 184 | releaseBackendWorkers(t, h) |
| 185 | |
| 186 | }) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | func TestBackendDefaultsAndValidation(t *testing.T) { |
| 191 | for _, kind := range []string{"codex", "agy"} { |
| 192 | t.Run(kind, func(t *testing.T) { |
| 193 | t.Parallel() |
| 194 | h := NewHarness(t) |
| 195 | h.AmendRepoConfig(map[string]any{ |
| 196 | "default_budget": "", |
| 197 | "default_agent_backend": kind, |
| 198 | "default_agent_model": "claude-only-model", |
| 199 | "default_agent_effort": "max", |
| 200 | "backends": map[string]any{kind: map[string]any{"model": "backend-model", "effort": "medium"}}, |
| 201 | }) |
| 202 | for _, flags := range [][]string{{"--budget", "2"}, {"--replay"}, {"--effort", "max"}, {"--backend", "typo"}} { |
| 203 | args := append([]string{"launch", "task"}, flags...) |
| 204 | res := h.RunKlaus(args...) |
| 205 | if res.ExitCode == 0 { |
| 206 | t.Fatalf("expected validation error for %v", flags) |
| 207 | } |
| 208 | if len(h.RunIDs()) != 0 { |
| 209 | t.Fatalf("invalid options created runs: %v", flags) |
| 210 | } |
| 211 | } |
| 212 | h.WriteStub(kind, h.claudeStubScript()) |
| 213 | res := h.RunKlaus("launch", "task") |
| 214 | if res.ExitCode != 0 { |
| 215 | t.Fatalf("launch: %s%s", res.Stdout, res.Stderr) |
| 216 | } |
| 217 | if strings.Contains(res.Stderr, "default_budget does not apply") { |
| 218 | t.Fatal("warned about an empty default budget") |
| 219 | } |
| 220 | h.WaitForClaudeStart(15 * time.Second) |
| 221 | args := h.ClaudeArgv() |
| 222 | if strings.Contains(args, "claude-only-model") || strings.Contains(args, "\nmax\n") || !strings.Contains(args, "backend-model") { |
| 223 | t.Fatalf("wrong backend defaults: %s", args) |
| 224 | } |
| 225 | releaseBackendWorkers(t, h) |
| 226 | }) |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | func TestCoordinatorFailureStillTearsDown(t *testing.T) { |
| 231 | for _, kind := range []string{"claude", "codex", "agy"} { |
| 232 | t.Run(kind, func(t *testing.T) { |
| 233 | t.Parallel() |
| 234 | h := NewHarness(t) |
| 235 | h.WriteStub(kind, "#!/bin/sh\nexit 7\n") |
| 236 | res := h.RunKlausIn(h.E2EDir, "new", "--backend", kind) |
| 237 | if res.ExitCode == 0 || !strings.Contains(res.Stderr, "exit status 7") { |
| 238 | t.Fatalf("missing exit error: %+v", res) |
| 239 | } |
| 240 | if !strings.Contains(res.Stdout, "No agents running.") || !strings.Contains(res.Stdout, "To clean up:") { |
| 241 | t.Fatalf("teardown skipped: %+v", res) |
| 242 | } |
| 243 | if panes := h.ListPanes(); len(panes) != 1 { |
| 244 | t.Fatalf("orphaned dashboard: %v", panes) |
| 245 | } |
| 246 | }) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | // Wait through the entire finalizer, not just its first state update: it still |
| 251 | // syncs git refs and removes the worktree after recording duration. Letting |
| 252 | // TempDir cleanup race those writes can fail with "directory not empty". |
| 253 | func releaseBackendWorkers(t *testing.T, h *Harness) { |
| 254 | t.Helper() |
| 255 | var workers []*run.State |
| 256 | for _, id := range h.RunIDs() { |
| 257 | st, err := h.ReadState(id) |
| 258 | if err != nil { |
| 259 | t.Fatal(err) |
| 260 | } |
| 261 | if st.Type != "session" && st.TmuxPane != nil { |
| 262 | workers = append(workers, st) |
| 263 | } |
| 264 | } |
| 265 | if len(workers) == 0 { |
| 266 | t.Fatal("no worker panes to release") |
| 267 | } |
| 268 | if err := os.WriteFile(filepath.Join(h.E2EDir, "claude.release"), nil, 0600); err != nil { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | for _, st := range workers { |
| 272 | h.WaitForState(st.ID, func(s *run.State) bool { return s.DurationMS != nil && s.TmuxPane == nil && s.Worktree == "" }, 30*time.Second) |
| 273 | waitPaneGone(t, h, *st.TmuxPane, 30*time.Second) |
| 274 | } |
| 275 | } |