gunk-dev/the-valley

session_test.go

source4cbb5ec9c5dbmain's published tip history
18.5 KiB
1package cmd
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "reflect"
11 "strings"
12 "testing"
13 "time"
14
15 "the-valley/flow/internal/backend"
16 "the-valley/flow/internal/flowenv"
17 "the-valley/flow/internal/run"
18)
19
20// A session's dashboard pane and coordinator get the session's ID, though
21// they inherit another session's under the new spelling, which readers
22// prefer.
23func TestSessionChildrenGetTheirSessionID(t *testing.T) {
24 t.Run("dashboard pane", func(t *testing.T) {
25 dir := t.TempDir()
26 stub := "#!/bin/sh\nprintf '%s %s %s' \"${" + flowenv.SessionID.New + "-unset}\" \"${" + sessionIDEnv + "-unset}\" \"$*\"\n"
27 if err := os.WriteFile(filepath.Join(dir, "klaus"), []byte(stub), 0o700); err != nil {
28 t.Fatal(err)
29 }
30 t.Setenv("PATH", dir+":"+os.Getenv("PATH"))
31 t.Setenv(flowenv.SessionID.New, "session-a")
32 paneCmd, err := dashboardPaneCommand("session-b")
33 if err != nil {
34 t.Fatal(err)
35 }
36 out, err := exec.Command("sh", "-c", paneCmd).CombinedOutput()
37 if err != nil {
38 t.Fatalf("%v: %s", err, out)
39 }
40 if want := "unset session-b dashboard"; string(out) != want {
41 t.Errorf("dashboard saw %q, want %q", out, want)
42 }
43 })
44
45 t.Run("coordinator", func(t *testing.T) {
46 environ := []string{"PATH=/bin", flowenv.SessionID.New + "=session-a", sessionIDEnv + "=session-a", flowenv.Backend.New + "=codex", flowenv.AgentBackend.New + "=codex"}
47 env := map[string]string{}
48 for _, kv := range coordinatorEnv(environ, "session-b", backend.Claude, backend.Agy) {
49 k, v, _ := strings.Cut(kv, "=")
50 if _, dup := env[k]; dup {
51 t.Errorf("coordinator environment sets %s twice", k)
52 }
53 env[k] = v
54 }
55 want := map[string]string{"PATH": "/bin", sessionIDEnv: "session-b", flowenv.Backend.Legacy: "claude", flowenv.AgentBackend.Legacy: "agy"}
56 if !reflect.DeepEqual(env, want) {
57 t.Errorf("coordinator environment = %v, want %v", env, want)
58 }
59 })
60}
61
62func TestNewSessionCmdRegistered(t *testing.T) {
63 // Verify 'new' subcommand is registered on root
64 found := false
65 for _, c := range rootCmd.Commands() {
66 if c.Use == "new" {
67 found = true
68 break
69 }
70 }
71 if !found {
72 t.Error("'new' subcommand not registered on root command")
73 }
74}
75
76func TestScaffoldCmdRegistered(t *testing.T) {
77 // Verify 'scaffold' subcommand is registered (renamed from 'new')
78 found := false
79 for _, c := range rootCmd.Commands() {
80 if c.Use == "scaffold <project-name>" {
81 found = true
82 break
83 }
84 }
85 if !found {
86 t.Error("'scaffold' subcommand not registered on root command")
87 }
88}
89
90func TestSessionDefaultResumesExisting(t *testing.T) {
91 // A sessions root with one session
92 home := t.TempDir()
93 t.Setenv("HOME", home)
94 sessDir := filepath.Join(home, ".klaus", "sessions", "session-20260401-1200-abcd")
95 store := run.NewHomeDirStoreFromPath(sessDir)
96 if err := store.EnsureDirs(); err != nil {
97 t.Fatal(err)
98 }
99 state := &run.State{
100 ID: "session-20260401-1200-abcd",
101 Type: "session",
102 Worktree: t.TempDir(), // point to a real dir
103 CreatedAt: "2026-04-01T12:00:00Z",
104 }
105 if err := store.Save(state); err != nil {
106 t.Fatal(err)
107 }
108
109 found, err := run.MostRecentSession()
110 if err != nil {
111 t.Fatalf("MostRecentSession: %v", err)
112 }
113 if found != "session-20260401-1200-abcd" {
114 t.Errorf("expected session-20260401-1200-abcd, got %s", found)
115 }
116}
117
118func TestSessionDefaultCreatesNewWhenNoneExist(t *testing.T) {
119 t.Setenv("HOME", t.TempDir())
120 // No sessions — should error
121 _, err := run.MostRecentSession()
122 if err == nil {
123 t.Error("expected error when no sessions exist")
124 }
125}
126
127func TestClaudeSessionIDPersistence(t *testing.T) {
128 // Create a JSONL log with a result event containing a session_id
129 tmpDir := t.TempDir()
130 logFile := filepath.Join(tmpDir, "test.jsonl")
131 resultEvent := map[string]interface{}{
132 "type": "result",
133 "session_id": "abc-123-def-456",
134 }
135 data, _ := json.Marshal(resultEvent)
136 if err := os.WriteFile(logFile, append(data, '\n'), 0o644); err != nil {
137 t.Fatal(err)
138 }
139
140 // ExtractClaudeSessionID should find it
141 got := ExtractClaudeSessionID(logFile)
142 if got != "abc-123-def-456" {
143 t.Errorf("ExtractClaudeSessionID = %q, want %q", got, "abc-123-def-456")
144 }
145}
146
147func TestClaudeSessionIDMissing(t *testing.T) {
148 // No log file — should return empty string
149 got := ExtractClaudeSessionID("/nonexistent/path.jsonl")
150 if got != "" {
151 t.Errorf("ExtractClaudeSessionID = %q, want empty", got)
152 }
153}
154
155func TestClaudeSessionIDInState(t *testing.T) {
156 // Verify ClaudeSessionID round-trips through save/load
157 tmpDir := t.TempDir()
158 store := run.NewHomeDirStoreFromPath(tmpDir)
159 if err := store.EnsureDirs(); err != nil {
160 t.Fatal(err)
161 }
162
163 csID := "session-uuid-789"
164 state := &run.State{
165 ID: "session-test",
166 Type: "session",
167 CreatedAt: "2026-04-01T12:00:00Z",
168 ClaudeSessionID: &csID,
169 }
170 if err := store.Save(state); err != nil {
171 t.Fatal(err)
172 }
173
174 loaded, err := store.Load("session-test")
175 if err != nil {
176 t.Fatal(err)
177 }
178 if loaded.ClaudeSessionID == nil {
179 t.Fatal("ClaudeSessionID should not be nil after round-trip")
180 }
181 if *loaded.ClaudeSessionID != "session-uuid-789" {
182 t.Errorf("ClaudeSessionID = %q, want %q", *loaded.ClaudeSessionID, "session-uuid-789")
183 }
184}
185
186func TestResumeClaudeArgs(t *testing.T) {
187 // Verify that claude args are constructed correctly for different resume scenarios
188 tests := []struct {
189 name string
190 resuming bool
191 claudeSessionID string
192 wantContains string
193 wantNotContain string
194 }{
195 {
196 name: "new session gets --session-id",
197 resuming: false,
198 claudeSessionID: "",
199 wantContains: "--session-id",
200 },
201 {
202 name: "resume with session ID",
203 resuming: true,
204 claudeSessionID: "uuid-123",
205 wantContains: "--resume",
206 },
207 {
208 name: "resume without session ID falls back to --continue",
209 resuming: true,
210 claudeSessionID: "",
211 wantContains: "--continue",
212 },
213 }
214
215 for _, tt := range tests {
216 t.Run(tt.name, func(t *testing.T) {
217 args := []string{
218 "--dangerously-skip-permissions",
219 "-n", "test-session",
220 "--append-system-prompt", "test prompt",
221 }
222 if tt.resuming && tt.claudeSessionID != "" {
223 args = append(args, "--resume", tt.claudeSessionID)
224 } else if tt.resuming {
225 args = append(args, "--continue")
226 } else {
227 csID := genUUIDv4()
228 if csID != "" {
229 args = append(args, "--session-id", csID)
230 }
231 }
232
233 argsStr := fmt.Sprintf("%v", args)
234 if tt.wantContains != "" {
235 found := false
236 for _, a := range args {
237 if a == tt.wantContains {
238 found = true
239 break
240 }
241 }
242 if !found {
243 t.Errorf("args %s should contain %q", argsStr, tt.wantContains)
244 }
245 }
246 if tt.wantNotContain != "" {
247 for _, a := range args {
248 if a == tt.wantNotContain {
249 t.Errorf("args %s should not contain %q", argsStr, tt.wantNotContain)
250 }
251 }
252 }
253 })
254 }
255}
256
257func TestCheckRunningAgents_ReturnsRunning(t *testing.T) {
258 tmpDir := t.TempDir()
259 store := run.NewHomeDirStoreFromPath(tmpDir)
260 if err := store.EnsureDirs(); err != nil {
261 t.Fatal(err)
262 }
263
264 pane1 := "%10"
265 pane2 := "%11"
266 // Agent 1: pane exists → running.
267 s1 := &run.State{
268 ID: "agent-running",
269 Type: "agent",
270 TmuxPane: &pane1,
271 CreatedAt: time.Now().Format(time.RFC3339),
272 }
273 // Agent 2: pane gone → not running.
274 s2 := &run.State{
275 ID: "agent-done",
276 Type: "agent",
277 TmuxPane: &pane2,
278 CreatedAt: time.Now().Format(time.RFC3339),
279 }
280 if err := store.Save(s1); err != nil {
281 t.Fatal(err)
282 }
283 if err := store.Save(s2); err != nil {
284 t.Fatal(err)
285 }
286
287 tc := &fakeTmux{runningPanes: map[string]bool{"%10": true}}
288 running := checkRunningAgents(context.Background(), store, tc)
289
290 if len(running) != 1 {
291 t.Fatalf("expected 1 running agent, got %d", len(running))
292 }
293 if running[0].ID != "agent-running" {
294 t.Errorf("expected agent-running, got %s", running[0].ID)
295 }
296}
297
298func TestCheckRunningAgents_NoAgents(t *testing.T) {
299 tmpDir := t.TempDir()
300 store := run.NewHomeDirStoreFromPath(tmpDir)
301 if err := store.EnsureDirs(); err != nil {
302 t.Fatal(err)
303 }
304
305 // Save a session (should be skipped).
306 state := &run.State{
307 ID: "session-skip",
308 Type: "session",
309 CreatedAt: time.Now().Format(time.RFC3339),
310 }
311 if err := store.Save(state); err != nil {
312 t.Fatal(err)
313 }
314
315 tc := &fakeTmux{}
316 running := checkRunningAgents(context.Background(), store, tc)
317
318 if len(running) != 0 {
319 t.Errorf("expected no running agents, got %d", len(running))
320 }
321}
322
323func TestCheckRunningAgents_SkipsSessions(t *testing.T) {
324 tmpDir := t.TempDir()
325 store := run.NewHomeDirStoreFromPath(tmpDir)
326 if err := store.EnsureDirs(); err != nil {
327 t.Fatal(err)
328 }
329
330 pane := "%20"
331 // A session with a live pane should not be counted as a running agent.
332 state := &run.State{
333 ID: "session-live",
334 Type: "session",
335 TmuxPane: &pane,
336 CreatedAt: time.Now().Format(time.RFC3339),
337 }
338 if err := store.Save(state); err != nil {
339 t.Fatal(err)
340 }
341
342 tc := &fakeTmux{runningPanes: map[string]bool{"%20": true}}
343 running := checkRunningAgents(context.Background(), store, tc)
344
345 if len(running) != 0 {
346 t.Errorf("expected no running agents (session should be skipped), got %d", len(running))
347 }
348}
349
350func TestCheckRunningAgents_NonBlocking(t *testing.T) {
351 // Verify checkRunningAgents returns immediately even with active agents.
352 tmpDir := t.TempDir()
353 store := run.NewHomeDirStoreFromPath(tmpDir)
354 if err := store.EnsureDirs(); err != nil {
355 t.Fatal(err)
356 }
357
358 pane := "%99"
359 state := &run.State{
360 ID: "agent-active",
361 Type: "agent",
362 TmuxPane: &pane,
363 CreatedAt: time.Now().Format(time.RFC3339),
364 }
365 if err := store.Save(state); err != nil {
366 t.Fatal(err)
367 }
368
369 tc := &fakeTmux{runningPanes: map[string]bool{"%99": true}}
370
371 done := make(chan struct{})
372 go func() {
373 checkRunningAgents(context.Background(), store, tc)
374 close(done)
375 }()
376
377 select {
378 case <-done:
379 // Good — returned immediately without blocking.
380 case <-time.After(2 * time.Second):
381 t.Fatal("checkRunningAgents blocked instead of returning immediately")
382 }
383}
384
385func TestGenUUIDv4(t *testing.T) {
386 id := genUUIDv4()
387 if len(id) != 36 {
388 t.Fatalf("UUID length = %d, want 36", len(id))
389 }
390 // Version nibble should be '4'
391 if id[14] != '4' {
392 t.Errorf("UUID version nibble = %c, want '4'", id[14])
393 }
394 // Variant nibble should be 8, 9, a, or b
395 v := id[19]
396 if v != '8' && v != '9' && v != 'a' && v != 'b' {
397 t.Errorf("UUID variant nibble = %c, want 8/9/a/b", v)
398 }
399 // Should have dashes in correct positions
400 for _, pos := range []int{8, 13, 18, 23} {
401 if id[pos] != '-' {
402 t.Errorf("UUID[%d] = %c, want '-'", pos, id[pos])
403 }
404 }
405}
406
407// bridgeHost gives the test a HOME whose host config sets naming_generation
408// bridge.
409func bridgeHost(t *testing.T) string {
410 t.Helper()
411 home := t.TempDir()
412 t.Setenv("HOME", home)
413 if err := os.MkdirAll(filepath.Join(home, ".klaus"), 0o755); err != nil {
414 t.Fatal(err)
415 }
416 if err := os.WriteFile(filepath.Join(home, ".klaus", "config.json"), []byte(`{"naming_generation": "bridge"}`), 0o644); err != nil {
417 t.Fatal(err)
418 }
419 return home
420}
421
422// Under the bridge naming generation a session's coordinator and dashboard
423// pane get every flow variable under both names with one value: what the
424// session sets, else what the parent resolves, the new name first, and
425// under neither what the parent has under neither. _pre-review's check
426// names its command by the flow spelling.
427func TestSessionChildrenUnderBridge(t *testing.T) {
428 bridgeHost(t)
429 t.Run("coordinator", func(t *testing.T) {
430 environ := []string{"PATH=/bin", flowenv.SessionID.Legacy + "=session-a", flowenv.RunID.New + "=run-a", flowenv.RunID.Legacy + "=run-b", flowenv.Scratch.Legacy + "=/scratch", flowenv.TmuxSocket.New + "="}
431 env := map[string]string{}
432 for _, kv := range coordinatorEnv(environ, "session-b", backend.Claude, backend.Agy) {
433 k, v, _ := strings.Cut(kv, "=")
434 if _, dup := env[k]; dup {
435 t.Errorf("coordinator environment sets %s twice", k)
436 }
437 env[k] = v
438 }
439 want := map[string]string{"PATH": "/bin"}
440 for v, value := range map[flowenv.Var]string{flowenv.SessionID: "session-b", flowenv.Backend: "claude", flowenv.AgentBackend: "agy", flowenv.RunID: "run-a", flowenv.Scratch: "/scratch", flowenv.TmuxSocket: ""} {
441 want[v.New], want[v.Legacy] = value, value
442 }
443 if !reflect.DeepEqual(env, want) {
444 t.Errorf("coordinator environment = %v, want %v", env, want)
445 }
446 })
447
448 t.Run("dashboard pane", func(t *testing.T) {
449 dir := t.TempDir()
450 stub := "#!/bin/sh\nprintf '%s %s %s %s %s' \"${" + flowenv.SessionID.New + "-unset}\" \"${" + flowenv.SessionID.Legacy + "-unset}\" \"${" + flowenv.Backend.New + "-unset}\" \"${" + flowenv.Backend.Legacy + "-unset}\" \"$*\"\n"
451 if err := os.WriteFile(filepath.Join(dir, "klaus"), []byte(stub), 0o700); err != nil {
452 t.Fatal(err)
453 }
454 t.Setenv("PATH", dir+":"+os.Getenv("PATH"))
455 for _, v := range flowenv.All {
456 t.Setenv(v.New, "")
457 t.Setenv(v.Legacy, "")
458 os.Unsetenv(v.New)
459 os.Unsetenv(v.Legacy)
460 }
461 t.Setenv(flowenv.SessionID.New, "session-a")
462 // The pane's shell starts from the tmux server's environment, which
463 // may hold values flow doesn't.
464 paneCmd, err := dashboardPaneCommand("session-b")
465 if err != nil {
466 t.Fatal(err)
467 }
468 cmd := exec.Command("sh", "-c", paneCmd)
469 cmd.Env = append(os.Environ(), flowenv.Backend.Legacy+"=stale")
470 out, err := cmd.CombinedOutput()
471 if err != nil {
472 t.Fatalf("%v: %s", err, out)
473 }
474 if want := "session-b session-b unset unset dashboard"; string(out) != want {
475 t.Errorf("dashboard saw %q, want %q", out, want)
476 }
477 })
478
479 t.Run("pre-review check", func(t *testing.T) {
480 for _, v := range []flowenv.Var{flowenv.RunID, flowenv.RunEvents, flowenv.SessionID} {
481 t.Setenv(v.New, "")
482 t.Setenv(v.Legacy, "")
483 os.Unsetenv(v.New)
484 os.Unsetenv(v.Legacy)
485 }
486 if got := startPreReviewCheck().data["command"]; got != "valley flow _pre-review" {
487 t.Errorf("pre-review check command %q", got)
488 }
489 })
490}
491
492// Under bridge the dashboard's and the scaffolding agent's pane commands
493// carry flow's variables, so one too long for tmux fails, with launch's
494// message, before a session, a repository or a registration exists. Runs
495// outside any repository with a PATH of stand-ins only, so nothing reaches
496// git, tmux, GitHub or a backend.
497func TestOverlongPaneCommandsFailFirst(t *testing.T) {
498 home := bridgeHost(t)
499 t.Chdir(t.TempDir())
500 bin := t.TempDir()
501 ran := filepath.Join(bin, "gh-ran")
502 if err := os.WriteFile(filepath.Join(bin, "gh"), []byte("#!/bin/sh\n: > "+shellQuote(ran)+"\n"), 0o700); err != nil {
503 t.Fatal(err)
504 }
505 t.Setenv("PATH", bin)
506 t.Setenv("TMUX", filepath.Join(home, "no-server")+",1,0")
507 t.Setenv(flowenv.RunEvents.New, strings.Repeat("x", maxPaneCommandBytes))
508 overLimit := func(err error, what string) bool {
509 return err != nil && strings.HasPrefix(err.Error(), what+" pane command is ") &&
510 strings.HasSuffix(err.Error(), fmt.Sprintf(" bytes, over the %d-byte limit for a tmux command", maxPaneCommandBytes))
511 }
512
513 t.Run("session", func(t *testing.T) {
514 if err := runSession(sessionCmd, true); !overLimit(err, "dashboard") {
515 t.Fatalf("runSession = %v, want the dashboard pane command over tmux's limit", err)
516 }
517 for _, root := range []string{filepath.Join(home, ".klaus", "sessions"), filepath.Join(home, ".valley")} {
518 if _, err := os.Stat(root); !os.IsNotExist(err) {
519 t.Errorf("a session start that failed made %s: %v", root, err)
520 }
521 }
522 })
523
524 t.Run("scaffold", func(t *testing.T) {
525 setScaffoldFlags(t)
526 if err := runNew(scaffoldCmd, []string{"app"}); !overLimit(err, "agent") {
527 t.Fatalf("runNew = %v, want the agent pane command over tmux's limit", err)
528 }
529 if _, err := os.Stat(ran); !os.IsNotExist(err) {
530 t.Error("scaffold created the repository before failing")
531 }
532 })
533}
534
535// Under legacy flow hands tmux the scaffolding agent's pane command
536// unchecked, one over tmux's limit included: here from a clone path of
537// 3,004 bytes, in the default projects directory of a long home. The
538// stand-in tmux records the length of each argument and fails.
539func TestLegacyScaffoldPaneCommandGoesToTmux(t *testing.T) {
540 home := t.TempDir()
541 for len(home)+len("/src/app") < 3004 {
542 home = filepath.Join(home, strings.Repeat("d", min(200, 3004-len("/src/app")-len(home)-1)))
543 }
544 if err := os.MkdirAll(home, 0o755); err != nil {
545 t.Fatal(err)
546 }
547 t.Setenv("HOME", home)
548 t.Setenv("TMUX", filepath.Join(home, "no-server")+",1,0")
549 t.Chdir(t.TempDir())
550 mkdir, err := exec.LookPath("mkdir")
551 if err != nil {
552 t.Fatal(err)
553 }
554 bin := t.TempDir()
555 lengths := filepath.Join(bin, "tmux-arg-lengths")
556 for name, script := range map[string]string{
557 "gh": shellQuote(mkdir) + " -p \"$HOME/src/app\"\n",
558 "tmux": "for a; do printf '%s\\n' \"${#a}\"; done >> " + shellQuote(lengths) + "\nexit 1\n",
559 } {
560 if err := os.WriteFile(filepath.Join(bin, name), []byte("#!/bin/sh\n"+script), 0o700); err != nil {
561 t.Fatal(err)
562 }
563 }
564 t.Setenv("PATH", bin)
565 setScaffoldFlags(t)
566 runErr := runNew(scaffoldCmd, []string{"app"})
567 if runErr == nil {
568 t.Fatal("runNew succeeded with a tmux that fails")
569 }
570 recorded, err := os.ReadFile(lengths)
571 if err != nil {
572 t.Fatalf("runNew failed before reaching tmux: %v", runErr)
573 }
574 longest := 0
575 for _, field := range strings.Fields(string(recorded)) {
576 var n int
577 if _, err := fmt.Sscan(field, &n); err != nil {
578 t.Fatal(err)
579 }
580 longest = max(longest, n)
581 }
582 if longest <= maxPaneCommandBytes {
583 t.Errorf("longest argument tmux got is %d bytes, want the pane command over %d", longest, maxPaneCommandBytes)
584 }
585}
586
587// setScaffoldFlags gives scaffoldCmd a description, a type and the claude
588// backend for one test.
589func setScaffoldFlags(t *testing.T) {
590 t.Helper()
591 for flag, value := range map[string]string{"description": "a tool", "type": "cli", "backend": "claude", "budget": ""} {
592 old, _ := scaffoldCmd.Flags().GetString(flag)
593 if err := scaffoldCmd.Flags().Set(flag, value); err != nil {
594 t.Fatal(err)
595 }
596 t.Cleanup(func() { _ = scaffoldCmd.Flags().Set(flag, old) })
597 }
598}
599
600// Under bridge a coordinator's prompt names where its session's directory,
601// the host config and self-update's state are: a new session's under the
602// flow root, an earlier one's under the legacy root, the host config where
603// it is, and self-update's state where it goes.
604func TestPromptPlacesUnderBridge(t *testing.T) {
605 home := bridgeHost(t)
606 for root, want := range map[string]string{
607 filepath.Join(home, ".valley", "flow", "sessions"): "~/.valley/flow/sessions",
608 filepath.Join(home, ".klaus", "sessions"): "~/.klaus/sessions",
609 } {
610 sessions, hostConfig, selfUpdate := promptPlaces(run.NewHomeDirStoreFromPath(filepath.Join(root, "session-x")))
611 if sessions != want || hostConfig != "~/.klaus/config.json" || selfUpdate != "~/.valley/flow/self-update.json" {
612 t.Errorf("places for a session in %s = %q, %q, %q", root, sessions, hostConfig, selfUpdate)
613 }
614 }
615}