gunk-dev/the-valley

working_test.go

sourced9c8073fd613main's published tip history
20.0 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "os"
7 "path/filepath"
8 "strings"
9 "testing"
10 "time"
11
12 "the-valley/flow/internal/run"
13)
14
15// TestDashboardGroupsRunsByChange runs the real dashboard and klaus status
16// while a follow-up run of a valley change is running. The change's runs
17// share one row, as a PR's do: with the agents, naming the follow-up, and
18// without an approve command. The same change ID in another repo is another
19// row, a draft change with no running run reads DRAFT, and a run without a
20// change ID keeps its own row. Once the follow-up exits, the change's row is
21// the operator's again, reading READY with its command.
22func TestDashboardGroupsRunsByChange(t *testing.T) {
23 t.Parallel()
24 h := NewHarness(t)
25 h.installValleyStub()
26 h.AmendRepoConfig(map[string]any{
27 "dashboard": map[string]any{"approve_command": "cd ~/hack/{repo} && valley approve {handle} --head {head}"},
28 })
29 sha := func(c byte) string { return strings.Repeat(string(c), 40) }
30 ago := func(m int) time.Time { return time.Now().Add(-time.Duration(m) * time.Minute) }
31
32 ready := h.valleyRun("20261013-0900-0001", "prompt one", "nxvp", "Add a health check", 1, sha('1'), ago(10))
33 // The same change ID in another repo: not the change the follow-up
34 // continues.
35 other := h.valleyRun("20261013-0900-0002", "prompt two", "nxvpk", "Port the health check", 1, sha('2'), ago(5))
36 other.ChangeID, other.TargetRepo, other.Valley.Repo = ready.ChangeID, strPtrE2E("acme/gadget"), "gadget"
37 h.SeedState(other)
38 draft := h.valleyRun("20261013-0900-0004", "prompt four", "drft", "Tune the cache", 1, sha('4'), ago(20))
39 // A run from before change IDs.
40 loneSHA := h.pushBranch("agent/lone", "lone.txt")
41 h.seedPushed("20261013-0900-0005", "lone prompt", "agent/lone", loneSHA, ago(30))
42
43 // The follow-up: not finalized, on a live pane, so it is running.
44 pane := strings.TrimSpace(h.tmux("new-window", "-d", "-P", "-F", "#{pane_id}", "sleep 600"))
45 follow := &run.State{
46 ID: "20261013-0900-0003", Type: "launch", Prompt: "tidy the health check", TargetRepo: strPtrE2E("acme/widget"),
47 Branch: "agent/tidy", Worktree: "/wt", TmuxPane: &pane, ChangeID: ready.ChangeID,
48 CreatedAt: ago(1).Format(time.RFC3339),
49 }
50 h.SeedState(follow)
51
52 otherChange := change(other, "ready", 1, version(1, sha('2'), "Port the health check", "not-landed"))
53 h.writeValleyChanges(map[string]any{
54 "schema": "valley-changes/v1",
55 "host": "valley-host",
56 "repos": []any{
57 map[string]any{"repo": "widget", "url": "git@valley-host:widget.git", "error": nil, "branches": []any{},
58 "changes": []any{
59 change(ready, "ready", 1, version(1, sha('1'), "Add a health check", "not-landed")),
60 change(draft, "draft", 1, version(1, sha('4'), "Tune the cache", "not-landed")),
61 }},
62 map[string]any{"repo": "gadget", "url": "git@valley-host:gadget.git", "error": nil, "branches": []any{},
63 "changes": []any{otherChange}},
64 },
65 })
66
67 tmuxPane, screen := h.startDashboard(170)
68 running := "agent:" + follow.ID[len(follow.ID)-4:] + " running"
69 s := screen("3 yours", "1 agents", running, "DRAFT")
70 if row := rowOf(t, s, "nxvp"); !strings.Contains(row, "Add a health check") || !strings.Contains(row, running) {
71 t.Errorf("the change's row should show its title and the running follow-up: %q", row)
72 }
73 if n := strings.Count(s, "tidy the health check") + strings.Count(s, "agent:0003 "); n != 0 {
74 t.Errorf("the follow-up should have no row of its own:\n%s", s)
75 }
76 if row := rowOf(t, s, "nxvpk"); !strings.HasPrefix(strings.TrimPrefix(row, "> "), "gadget") || !strings.Contains(row, "READY v1@2222222") {
77 t.Errorf("the same change ID in another repo should be its own row, reading READY: %q", row)
78 }
79 if row := rowOf(t, s, "drft"); !strings.Contains(row, "DRAFT v1@4444444") {
80 t.Errorf("a draft change with no running run should read DRAFT: %q", row)
81 }
82 if !strings.Contains(s, "agent:0005") || !strings.Contains(s, "SUBMIT agent/lone@"+loneSHA[:7]) {
83 t.Errorf("a run without a change ID should keep its own SUBMIT row:\n%s", s)
84 }
85 // Yours first, most recent first, then the change the follow-up is
86 // running on, which is last: four rows for five runs.
87 var order []string
88 for _, line := range strings.Split(s, "\n") {
89 if f := strings.Fields(strings.TrimPrefix(line, ">")); len(f) > 1 && (f[0] == "widget" || f[0] == "gadget") {
90 order = append(order, f[1])
91 }
92 }
93 if want := []string{"nxvpk", "drft", "agent:0005", "nxvp"}; strings.Join(order, ",") != strings.Join(want, ",") {
94 t.Errorf("rows in order %v, want %v:\n%s", order, want, s)
95 }
96
97 // The DRAFT row offers no approve command.
98 h.tmux("send-keys", "-t", tmuxPane, "j")
99 s = screen("> widget drft")
100 if strings.Contains(s, "approve:") {
101 t.Errorf("a DRAFT row should offer no approve command:\n%s", s)
102 }
103 // Nor does the change a follow-up is running on; the footer names it.
104 h.tmux("send-keys", "-t", tmuxPane, "G")
105 s = screen("> widget nxvp ", "agent:0003 is working on this change")
106 if strings.Contains(s, "approve:") {
107 t.Errorf("a change with a running follow-up should offer no approve command:\n%s", s)
108 }
109
110 res := h.RunKlaus("status")
111 if res.ExitCode != 0 {
112 t.Fatalf("status exited %d; stderr: %s", res.ExitCode, res.Stderr)
113 }
114 for _, tc := range []struct {
115 st *run.State
116 status, change string
117 }{
118 {ready, "working", "nxvp"},
119 {follow, "running", "nxvp"},
120 {other, "awaiting-approval", "nxvpk"},
121 {draft, "draft", "drft"},
122 } {
123 if got := statusOf(t, res.Stdout, tc.st.ID); got != tc.status {
124 t.Errorf("%s: status %q, want %q", tc.st.ID, got, tc.status)
125 }
126 if got := changeColumn(t, res.Stdout, tc.st.ID); got != tc.change {
127 t.Errorf("%s: CHANGE %q, want %q", tc.st.ID, got, tc.change)
128 }
129 }
130
131 // The follow-up exits: the change's row is the operator's again, with
132 // its command.
133 h.tmux("kill-pane", "-t", pane)
134 cost, dur := 0.5, int64(1000)
135 follow.TmuxPane, follow.CostUSD, follow.DurationMS = nil, &cost, &dur
136 h.SeedState(follow)
137 s = screen("4 yours", "approve: cd ~/hack/widget && valley approve nxvp --head "+sha('1'))
138 if row := rowOf(t, s, "nxvp"); !strings.HasPrefix(row, "> ") || !strings.Contains(row, "READY v1@1111111") {
139 t.Errorf("after the follow-up exits the change's row should be selected and read READY: %q\n%s", row, s)
140 }
141 if strings.Contains(s, " running") || strings.Contains(s, "tidy the health check") {
142 t.Errorf("nothing should be running, and the follow-up should still have no row:\n%s", s)
143 }
144}
145
146// TestFollowUpLaunchUnreadiesValleyChange launches a --resume-from follow-up
147// of a valley change and lets the real finalize run, against a fake valley:
148// when valley lists unready, launch returns the change to draft before the
149// agent starts and finalize marks the pushed head ready again; without the
150// verb launch never runs it; and a refused unready is recorded and warned
151// about without failing the launch.
152func TestFollowUpLaunchUnreadiesValleyChange(t *testing.T) {
153 for _, tc := range []struct {
154 name string
155 unready bool
156 refuse string
157 }{
158 {name: "valley lists unready", unready: true},
159 {name: "valley without unready"},
160 {name: "unready refused", unready: true, refuse: "valley: refused: nxvp has a pending request\n"},
161 } {
162 t.Run(tc.name, func(t *testing.T) {
163 t.Parallel()
164 h := NewHarness(t)
165 h.installValleyStub()
166 h.joinValley()
167 if tc.unready {
168 if err := os.WriteFile(filepath.Join(h.E2EDir, "valley.has-unready"), nil, 0o644); err != nil {
169 t.Fatal(err)
170 }
171 }
172 if tc.refuse != "" {
173 if err := os.WriteFile(filepath.Join(h.E2EDir, "valley.unready-refuse"), []byte(tc.refuse), 0o644); err != nil {
174 t.Fatal(err)
175 }
176 }
177 prior := h.valleyRun("20261013-0900-0001", "add a health check", "nxvp", "Add a health check", 1,
178 strings.Repeat("1", 40), time.Now().Add(-time.Hour))
179 h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"11111111-2222-4333-8444-555555555555"}` + "\n")
180
181 res := h.RunKlaus("launch", "--resume-from", prior.ID, "tidy the health check")
182 if res.ExitCode != 0 {
183 t.Fatalf("launch exited %d\nstdout:\n%s\nstderr:\n%s", res.ExitCode, res.Stdout, res.Stderr)
184 }
185 var st *run.State
186 for _, id := range h.RunIDs() {
187 if id != prior.ID {
188 st, _ = h.ReadState(id)
189 }
190 }
191 if st == nil || st.ChangeID != prior.ChangeID {
192 t.Fatalf("follow-up state %+v, want change %s\nstdout:\n%s", st, prior.ChangeID, res.Stdout)
193 }
194 if st.ChangeRepo != "widget" {
195 t.Errorf("follow-up recorded change repo %q, want the prior run's %q", st.ChangeRepo, "widget")
196 }
197 h.WaitForClaudeStart(30 * time.Second)
198
199 calls := h.valleyCalls("unready")
200 switch {
201 case !tc.unready:
202 if len(calls) != 0 || st.Unready != nil {
203 t.Errorf("a valley without unready must not be asked to unready: calls %q, recorded %+v", calls, st.Unready)
204 }
205 case tc.refuse != "":
206 want := "valley unready: valley: refused: nxvp has a pending request"
207 if st.Unready == nil || st.Unready.Error != want || st.Unready.Handle != "" {
208 t.Errorf("refusal recorded as %+v, want error %q", st.Unready, want)
209 }
210 if !strings.Contains(res.Stderr, "warning: could not return the change to draft: "+want) {
211 t.Errorf("launch should warn about the refusal:\n%s", res.Stderr)
212 }
213 default:
214 want := st.Worktree + ": unready " + prior.ChangeID
215 if len(calls) != 1 || calls[0] != want {
216 t.Errorf("valley unready calls = %q, want [%q]", calls, want)
217 }
218 if st.Unready == nil || *st.Unready != (run.Unready{ChangeID: prior.ChangeID, Repo: "widget", Handle: "nxvp"}) {
219 t.Errorf("recorded unready = %+v", st.Unready)
220 }
221 if !strings.Contains(res.Stdout, "valley: widget nxvp is a draft until the agent pushes") {
222 t.Errorf("launch should say the change is a draft:\n%s", res.Stdout)
223 }
224 }
225 if _, err := os.Stat(filepath.Join(h.E2EDir, "valley.unready-late")); err == nil {
226 t.Error("valley unready ran after the agent started")
227 }
228
229 // The agent pushes; finalize marks the head ready again.
230 if err := os.WriteFile(filepath.Join(st.Worktree, "health.go"), []byte("package health\n"), 0o644); err != nil {
231 t.Fatal(err)
232 }
233 h.git(st.Worktree, "add", "-A")
234 h.git(st.Worktree, "commit", "-qm", "Tidy the health check")
235 h.git(st.Worktree, "push", "-q", "origin", st.Branch)
236 head := h.GitOutput(st.Worktree, "rev-parse", "HEAD")
237 worktree := st.Worktree
238 h.ReleaseClaude()
239 h.WaitForState(st.ID, func(s *run.State) bool {
240 return s.DurationMS != nil && s.TmuxPane == nil && s.Worktree == ""
241 }, 60*time.Second)
242 want := worktree + ": ready --change " + prior.ChangeID + " --head " + head + " " + st.Branch
243 if calls := h.valleyCalls("ready"); len(calls) != 1 || calls[0] != want {
244 t.Errorf("valley ready calls = %q, want [%q]", calls, want)
245 }
246 })
247 }
248}
249
250// TestFollowUpOfRenamedRepoSharesItsRow launches a --resume-from follow-up
251// of a valley change from a target repo, acme/source, that the valley calls
252// widget, as the prior run recorded, against a valley that can't unready: the
253// follow-up records the repo of the run it continues, so it runs on the
254// change's row, and the prior run reads working in klaus status.
255func TestFollowUpOfRenamedRepoSharesItsRow(t *testing.T) {
256 t.Parallel()
257 h := NewHarness(t)
258 h.installValleyStub()
259 h.joinValley()
260 // Registered as the project "source", which --repo names.
261 h.RegisterProject("acme/source", h.RepoDir)
262 sha := strings.Repeat("1", 40)
263 prior := h.valleyRun("20261013-0900-0001", "add a health check", "nxvp", "Add a health check", 1, sha,
264 time.Now().Add(-time.Hour))
265 prior.TargetRepo = strPtrE2E("acme/source")
266 h.SeedState(prior)
267 h.writeValleyChanges(map[string]any{
268 "schema": "valley-changes/v1",
269 "host": "valley-host",
270 "repos": []any{
271 map[string]any{"repo": "widget", "url": "git@valley-host:widget.git", "error": nil, "branches": []any{},
272 "changes": []any{change(prior, "ready", 1, version(1, sha, "Add a health check", "not-landed"))}},
273 },
274 })
275 h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"11111111-2222-4333-8444-555555555555"}` + "\n")
276
277 res := h.RunKlaus("launch", "--repo", "source", "--resume-from", prior.ID, "tidy the health check")
278 if res.ExitCode != 0 {
279 t.Fatalf("launch exited %d\nstdout:\n%s\nstderr:\n%s", res.ExitCode, res.Stdout, res.Stderr)
280 }
281 var st *run.State
282 for _, id := range h.RunIDs() {
283 if id != prior.ID {
284 st, _ = h.ReadState(id)
285 }
286 }
287 if st == nil || st.ChangeID != prior.ChangeID {
288 t.Fatalf("follow-up state %+v, want change %s\nstdout:\n%s", st, prior.ChangeID, res.Stdout)
289 }
290 if st.TargetRepo == nil || *st.TargetRepo != "source" || st.Unready != nil || len(h.valleyCalls("unready")) != 0 {
291 t.Fatalf("follow-up should target source without unready: target %v, unready %+v, calls %q",
292 st.TargetRepo, st.Unready, h.valleyCalls("unready"))
293 }
294 if st.ChangeRepo != "widget" {
295 t.Errorf("follow-up recorded change repo %q, want the prior run's %q", st.ChangeRepo, "widget")
296 }
297 h.WaitForClaudeStart(30 * time.Second)
298
299 _, screen := h.startDashboard(170)
300 running := "agent:" + st.ID[len(st.ID)-4:] + " running"
301 s := screen("1 agents", running)
302 if row := rowOf(t, s, "nxvp"); !strings.Contains(row, "READY "+running+" v1@1111111") {
303 t.Errorf("the follow-up should run on the change's row: %q\n%s", row, s)
304 }
305 if strings.Contains(s, "tidy the health check") {
306 t.Errorf("the follow-up should have no row of its own:\n%s", s)
307 }
308 status := h.RunKlaus("status")
309 if got := statusOf(t, status.Stdout, prior.ID); got != "working" {
310 t.Errorf("prior: status %q, want working", got)
311 }
312
313 // Finalize records the duration before it salvages and pushes the
314 // worktree to origin; wait for it to clean up, so the temp dirs aren't
315 // removed under that push.
316 h.ReleaseClaude()
317 h.WaitForState(st.ID, func(s *run.State) bool {
318 return s.DurationMS != nil && s.TmuxPane == nil && s.Worktree == ""
319 }, 60*time.Second)
320}
321
322// TestStatusJudgesPanesAsTheDashboardDoes runs the real klaus status while a
323// follow-up of a valley change keeps its pane but no longer runs: the pane is
324// dead (its command exited and tmux kept it), or the run finalized and its
325// pane sits idle at a shell. Status judges panes as the dashboard does, so
326// the follow-up isn't running and the change's own run is the operator's
327// again, not working.
328func TestStatusJudgesPanesAsTheDashboardDoes(t *testing.T) {
329 for _, tc := range []struct {
330 name string
331 finalized bool
332 }{
333 {name: "dead pane"},
334 {name: "idle pane after finalize", finalized: true},
335 } {
336 t.Run(tc.name, func(t *testing.T) {
337 t.Parallel()
338 h := NewHarness(t)
339 h.installValleyStub()
340 sha := strings.Repeat("1", 40)
341 ready := h.valleyRun("20261013-0900-0001", "prompt one", "nxvp", "Add a health check", 1, sha,
342 time.Now().Add(-10*time.Minute))
343 h.writeValleyChanges(map[string]any{
344 "schema": "valley-changes/v1",
345 "host": "valley-host",
346 "repos": []any{
347 map[string]any{"repo": "widget", "url": "git@valley-host:widget.git", "error": nil, "branches": []any{},
348 "changes": []any{change(ready, "ready", 1, version(1, sha, "Add a health check", "not-landed"))}},
349 },
350 })
351
352 pane := strings.TrimSpace(h.tmux("new-window", "-d", "-P", "-F", "#{pane_id}", "sleep 600"))
353 // Until the pane's shell has started sleep, the pane reads idle.
354 waitForPane(t, h, pane, "#{pane_current_command}", "sleep")
355 follow := &run.State{
356 ID: "20261013-0900-0002", Type: "launch", Prompt: "tidy the health check", TargetRepo: strPtrE2E("acme/widget"),
357 Branch: "agent/tidy", Worktree: "/wt", TmuxPane: &pane, ChangeID: ready.ChangeID,
358 CreatedAt: time.Now().Add(-time.Minute).Format(time.RFC3339),
359 }
360 if tc.finalized {
361 cost, dur := 0.5, int64(1000)
362 follow.CostUSD, follow.DurationMS = &cost, &dur
363 }
364 h.SeedState(follow)
365 statuses := func() (string, string) {
366 t.Helper()
367 res := h.RunKlaus("status")
368 if res.ExitCode != 0 {
369 t.Fatalf("status exited %d; stderr: %s", res.ExitCode, res.Stderr)
370 }
371 return statusOf(t, res.Stdout, follow.ID), statusOf(t, res.Stdout, ready.ID)
372 }
373 // While the pane's command runs, the follow-up is running.
374 if f, r := statuses(); f != "running" || r != "working" {
375 t.Fatalf("with the pane busy: follow-up %q, change %q; want running, working", f, r)
376 }
377
378 if tc.finalized {
379 // A shell waiting at its prompt.
380 h.tmux("respawn-pane", "-k", "-t", pane, "exec bash --noprofile --norc")
381 waitForPane(t, h, pane, "#{pane_current_command}", "bash")
382 } else {
383 h.tmux("set-option", "-w", "-t", pane, "remain-on-exit", "on")
384 h.tmux("respawn-pane", "-k", "-t", pane, "true")
385 waitForPane(t, h, pane, "#{pane_dead}", "1")
386 }
387 if !h.PaneExists(pane) {
388 t.Fatalf("pane %s should still exist", pane)
389 }
390 if f, r := statuses(); f != "exited" || r != "awaiting-approval" {
391 t.Errorf("follow-up %q, change %q; want exited, awaiting-approval", f, r)
392 }
393 })
394 }
395}
396
397// TestStatusNamesEveryRunOfAChangeAlike runs the real klaus status over a
398// valley change, its running follow-up, and a follow-up running on a change
399// the valley doesn't list. Every run of a change shows the same CHANGE: the
400// valley listing's handle; else, as when the valley can't be asked, the
401// handle a run of the change recorded, from finalize's ready or launch's
402// unready. A running run has no handle of its own until it pushes.
403func TestStatusNamesEveryRunOfAChangeAlike(t *testing.T) {
404 t.Parallel()
405 h := NewHarness(t)
406 h.installValleyStub()
407 sha := strings.Repeat("1", 40)
408 ready := h.valleyRun("20261013-0900-0001", "prompt one", "nxvp", "Add a health check", 1, sha,
409 time.Now().Add(-10*time.Minute))
410 h.writeValleyChanges(map[string]any{
411 "schema": "valley-changes/v1",
412 "host": "valley-host",
413 "repos": []any{
414 map[string]any{"repo": "widget", "url": "git@valley-host:widget.git", "error": nil, "branches": []any{},
415 "changes": []any{change(ready, "ready", 1, version(1, sha, "Add a health check", "not-landed"))}},
416 },
417 })
418 followUp := func(id, changeID string, unready *run.Unready) *run.State {
419 pane := strings.TrimSpace(h.tmux("new-window", "-d", "-P", "-F", "#{pane_id}", "sleep 600"))
420 waitForPane(t, h, pane, "#{pane_current_command}", "sleep")
421 st := &run.State{
422 ID: id, Type: "launch", Prompt: "follow up " + id, TargetRepo: strPtrE2E("acme/widget"),
423 Branch: "agent/" + id, Worktree: "/wt", TmuxPane: &pane, ChangeID: changeID, ChangeRepo: "widget",
424 Unready: unready, CreatedAt: time.Now().Add(-time.Minute).Format(time.RFC3339),
425 }
426 h.SeedState(st)
427 return st
428 }
429 // Launch couldn't unready it, so it recorded no handle.
430 follow := followUp("20261013-0900-0002", ready.ChangeID, &run.Unready{Error: "valley unready: refused"})
431 // Launch unreadied a change no run here pushed and the valley doesn't
432 // list.
433 other := followUp("20261013-0900-0003", "unrdkkkkkkkkkkkkkkkkkkkkkkkkkkkk", &run.Unready{Repo: "widget", Handle: "unrd"})
434
435 check := func(step string, want map[*run.State][2]string) {
436 t.Helper()
437 res := h.RunKlaus("status")
438 if res.ExitCode != 0 {
439 t.Fatalf("%s: status exited %d; stderr: %s", step, res.ExitCode, res.Stderr)
440 }
441 for st, w := range want {
442 if got := statusOf(t, res.Stdout, st.ID); got != w[0] {
443 t.Errorf("%s: %s: status %q, want %q", step, st.ID, got, w[0])
444 }
445 if got := changeColumn(t, res.Stdout, st.ID); got != w[1] {
446 t.Errorf("%s: %s: CHANGE %q, want %q", step, st.ID, got, w[1])
447 }
448 }
449 }
450 want := map[*run.State][2]string{
451 ready: {"working", "nxvp"},
452 follow: {"running", "nxvp"},
453 other: {"running", "unrd"},
454 }
455 check("valley listing", want)
456 // The valley goes down: the handles recorded on the changes' runs.
457 for _, f := range []string{"valley.changes.json", "valley.changes.checks.json"} {
458 if err := os.Remove(filepath.Join(h.E2EDir, f)); err != nil {
459 t.Fatal(err)
460 }
461 }
462 check("valley down", want)
463}
464
465// waitForPane waits until format, displayed for pane, reads want.
466func waitForPane(t *testing.T, h *Harness, pane, format, want string) {
467 t.Helper()
468 var got string
469 for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
470 if got = strings.TrimSpace(h.tmux("display-message", "-p", "-t", pane, format)); got == want {
471 return
472 }
473 }
474 t.Fatalf("pane %s: %s is %q, want %q", pane, format, got, want)
475}