gunk-dev/the-valley

session_test.go

source6a6791929c36main's published tip history
10.4 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 out, err := exec.Command("sh", "-c", dashboardPaneCommand("session-b")).CombinedOutput()
33 if err != nil {
34 t.Fatalf("%v: %s", err, out)
35 }
36 if want := "unset session-b dashboard"; string(out) != want {
37 t.Errorf("dashboard saw %q, want %q", out, want)
38 }
39 })
40
41 t.Run("coordinator", func(t *testing.T) {
42 environ := []string{"PATH=/bin", flowenv.SessionID.New + "=session-a", sessionIDEnv + "=session-a", flowenv.Backend.New + "=codex", flowenv.AgentBackend.New + "=codex"}
43 env := map[string]string{}
44 for _, kv := range coordinatorEnv(environ, "session-b", backend.Claude, backend.Agy) {
45 k, v, _ := strings.Cut(kv, "=")
46 if _, dup := env[k]; dup {
47 t.Errorf("coordinator environment sets %s twice", k)
48 }
49 env[k] = v
50 }
51 want := map[string]string{"PATH": "/bin", sessionIDEnv: "session-b", flowenv.Backend.Legacy: "claude", flowenv.AgentBackend.Legacy: "agy"}
52 if !reflect.DeepEqual(env, want) {
53 t.Errorf("coordinator environment = %v, want %v", env, want)
54 }
55 })
56}
57
58func TestNewSessionCmdRegistered(t *testing.T) {
59 // Verify 'new' subcommand is registered on root
60 found := false
61 for _, c := range rootCmd.Commands() {
62 if c.Use == "new" {
63 found = true
64 break
65 }
66 }
67 if !found {
68 t.Error("'new' subcommand not registered on root command")
69 }
70}
71
72func TestScaffoldCmdRegistered(t *testing.T) {
73 // Verify 'scaffold' subcommand is registered (renamed from 'new')
74 found := false
75 for _, c := range rootCmd.Commands() {
76 if c.Use == "scaffold <project-name>" {
77 found = true
78 break
79 }
80 }
81 if !found {
82 t.Error("'scaffold' subcommand not registered on root command")
83 }
84}
85
86func TestSessionDefaultResumesExisting(t *testing.T) {
87 // A sessions root with one session
88 home := t.TempDir()
89 t.Setenv("HOME", home)
90 sessDir := filepath.Join(home, ".klaus", "sessions", "session-20260401-1200-abcd")
91 store := run.NewHomeDirStoreFromPath(sessDir)
92 if err := store.EnsureDirs(); err != nil {
93 t.Fatal(err)
94 }
95 state := &run.State{
96 ID: "session-20260401-1200-abcd",
97 Type: "session",
98 Worktree: t.TempDir(), // point to a real dir
99 CreatedAt: "2026-04-01T12:00:00Z",
100 }
101 if err := store.Save(state); err != nil {
102 t.Fatal(err)
103 }
104
105 found, err := run.MostRecentSession()
106 if err != nil {
107 t.Fatalf("MostRecentSession: %v", err)
108 }
109 if found != "session-20260401-1200-abcd" {
110 t.Errorf("expected session-20260401-1200-abcd, got %s", found)
111 }
112}
113
114func TestSessionDefaultCreatesNewWhenNoneExist(t *testing.T) {
115 t.Setenv("HOME", t.TempDir())
116 // No sessions — should error
117 _, err := run.MostRecentSession()
118 if err == nil {
119 t.Error("expected error when no sessions exist")
120 }
121}
122
123func TestClaudeSessionIDPersistence(t *testing.T) {
124 // Create a JSONL log with a result event containing a session_id
125 tmpDir := t.TempDir()
126 logFile := filepath.Join(tmpDir, "test.jsonl")
127 resultEvent := map[string]interface{}{
128 "type": "result",
129 "session_id": "abc-123-def-456",
130 }
131 data, _ := json.Marshal(resultEvent)
132 if err := os.WriteFile(logFile, append(data, '\n'), 0o644); err != nil {
133 t.Fatal(err)
134 }
135
136 // ExtractClaudeSessionID should find it
137 got := ExtractClaudeSessionID(logFile)
138 if got != "abc-123-def-456" {
139 t.Errorf("ExtractClaudeSessionID = %q, want %q", got, "abc-123-def-456")
140 }
141}
142
143func TestClaudeSessionIDMissing(t *testing.T) {
144 // No log file — should return empty string
145 got := ExtractClaudeSessionID("/nonexistent/path.jsonl")
146 if got != "" {
147 t.Errorf("ExtractClaudeSessionID = %q, want empty", got)
148 }
149}
150
151func TestClaudeSessionIDInState(t *testing.T) {
152 // Verify ClaudeSessionID round-trips through save/load
153 tmpDir := t.TempDir()
154 store := run.NewHomeDirStoreFromPath(tmpDir)
155 if err := store.EnsureDirs(); err != nil {
156 t.Fatal(err)
157 }
158
159 csID := "session-uuid-789"
160 state := &run.State{
161 ID: "session-test",
162 Type: "session",
163 CreatedAt: "2026-04-01T12:00:00Z",
164 ClaudeSessionID: &csID,
165 }
166 if err := store.Save(state); err != nil {
167 t.Fatal(err)
168 }
169
170 loaded, err := store.Load("session-test")
171 if err != nil {
172 t.Fatal(err)
173 }
174 if loaded.ClaudeSessionID == nil {
175 t.Fatal("ClaudeSessionID should not be nil after round-trip")
176 }
177 if *loaded.ClaudeSessionID != "session-uuid-789" {
178 t.Errorf("ClaudeSessionID = %q, want %q", *loaded.ClaudeSessionID, "session-uuid-789")
179 }
180}
181
182func TestResumeClaudeArgs(t *testing.T) {
183 // Verify that claude args are constructed correctly for different resume scenarios
184 tests := []struct {
185 name string
186 resuming bool
187 claudeSessionID string
188 wantContains string
189 wantNotContain string
190 }{
191 {
192 name: "new session gets --session-id",
193 resuming: false,
194 claudeSessionID: "",
195 wantContains: "--session-id",
196 },
197 {
198 name: "resume with session ID",
199 resuming: true,
200 claudeSessionID: "uuid-123",
201 wantContains: "--resume",
202 },
203 {
204 name: "resume without session ID falls back to --continue",
205 resuming: true,
206 claudeSessionID: "",
207 wantContains: "--continue",
208 },
209 }
210
211 for _, tt := range tests {
212 t.Run(tt.name, func(t *testing.T) {
213 args := []string{
214 "--dangerously-skip-permissions",
215 "-n", "test-session",
216 "--append-system-prompt", "test prompt",
217 }
218 if tt.resuming && tt.claudeSessionID != "" {
219 args = append(args, "--resume", tt.claudeSessionID)
220 } else if tt.resuming {
221 args = append(args, "--continue")
222 } else {
223 csID := genUUIDv4()
224 if csID != "" {
225 args = append(args, "--session-id", csID)
226 }
227 }
228
229 argsStr := fmt.Sprintf("%v", args)
230 if tt.wantContains != "" {
231 found := false
232 for _, a := range args {
233 if a == tt.wantContains {
234 found = true
235 break
236 }
237 }
238 if !found {
239 t.Errorf("args %s should contain %q", argsStr, tt.wantContains)
240 }
241 }
242 if tt.wantNotContain != "" {
243 for _, a := range args {
244 if a == tt.wantNotContain {
245 t.Errorf("args %s should not contain %q", argsStr, tt.wantNotContain)
246 }
247 }
248 }
249 })
250 }
251}
252
253func TestCheckRunningAgents_ReturnsRunning(t *testing.T) {
254 tmpDir := t.TempDir()
255 store := run.NewHomeDirStoreFromPath(tmpDir)
256 if err := store.EnsureDirs(); err != nil {
257 t.Fatal(err)
258 }
259
260 pane1 := "%10"
261 pane2 := "%11"
262 // Agent 1: pane exists → running.
263 s1 := &run.State{
264 ID: "agent-running",
265 Type: "agent",
266 TmuxPane: &pane1,
267 CreatedAt: time.Now().Format(time.RFC3339),
268 }
269 // Agent 2: pane gone → not running.
270 s2 := &run.State{
271 ID: "agent-done",
272 Type: "agent",
273 TmuxPane: &pane2,
274 CreatedAt: time.Now().Format(time.RFC3339),
275 }
276 if err := store.Save(s1); err != nil {
277 t.Fatal(err)
278 }
279 if err := store.Save(s2); err != nil {
280 t.Fatal(err)
281 }
282
283 tc := &fakeTmux{runningPanes: map[string]bool{"%10": true}}
284 running := checkRunningAgents(context.Background(), store, tc)
285
286 if len(running) != 1 {
287 t.Fatalf("expected 1 running agent, got %d", len(running))
288 }
289 if running[0].ID != "agent-running" {
290 t.Errorf("expected agent-running, got %s", running[0].ID)
291 }
292}
293
294func TestCheckRunningAgents_NoAgents(t *testing.T) {
295 tmpDir := t.TempDir()
296 store := run.NewHomeDirStoreFromPath(tmpDir)
297 if err := store.EnsureDirs(); err != nil {
298 t.Fatal(err)
299 }
300
301 // Save a session (should be skipped).
302 state := &run.State{
303 ID: "session-skip",
304 Type: "session",
305 CreatedAt: time.Now().Format(time.RFC3339),
306 }
307 if err := store.Save(state); err != nil {
308 t.Fatal(err)
309 }
310
311 tc := &fakeTmux{}
312 running := checkRunningAgents(context.Background(), store, tc)
313
314 if len(running) != 0 {
315 t.Errorf("expected no running agents, got %d", len(running))
316 }
317}
318
319func TestCheckRunningAgents_SkipsSessions(t *testing.T) {
320 tmpDir := t.TempDir()
321 store := run.NewHomeDirStoreFromPath(tmpDir)
322 if err := store.EnsureDirs(); err != nil {
323 t.Fatal(err)
324 }
325
326 pane := "%20"
327 // A session with a live pane should not be counted as a running agent.
328 state := &run.State{
329 ID: "session-live",
330 Type: "session",
331 TmuxPane: &pane,
332 CreatedAt: time.Now().Format(time.RFC3339),
333 }
334 if err := store.Save(state); err != nil {
335 t.Fatal(err)
336 }
337
338 tc := &fakeTmux{runningPanes: map[string]bool{"%20": true}}
339 running := checkRunningAgents(context.Background(), store, tc)
340
341 if len(running) != 0 {
342 t.Errorf("expected no running agents (session should be skipped), got %d", len(running))
343 }
344}
345
346func TestCheckRunningAgents_NonBlocking(t *testing.T) {
347 // Verify checkRunningAgents returns immediately even with active agents.
348 tmpDir := t.TempDir()
349 store := run.NewHomeDirStoreFromPath(tmpDir)
350 if err := store.EnsureDirs(); err != nil {
351 t.Fatal(err)
352 }
353
354 pane := "%99"
355 state := &run.State{
356 ID: "agent-active",
357 Type: "agent",
358 TmuxPane: &pane,
359 CreatedAt: time.Now().Format(time.RFC3339),
360 }
361 if err := store.Save(state); err != nil {
362 t.Fatal(err)
363 }
364
365 tc := &fakeTmux{runningPanes: map[string]bool{"%99": true}}
366
367 done := make(chan struct{})
368 go func() {
369 checkRunningAgents(context.Background(), store, tc)
370 close(done)
371 }()
372
373 select {
374 case <-done:
375 // Good — returned immediately without blocking.
376 case <-time.After(2 * time.Second):
377 t.Fatal("checkRunningAgents blocked instead of returning immediately")
378 }
379}
380
381func TestGenUUIDv4(t *testing.T) {
382 id := genUUIDv4()
383 if len(id) != 36 {
384 t.Fatalf("UUID length = %d, want 36", len(id))
385 }
386 // Version nibble should be '4'
387 if id[14] != '4' {
388 t.Errorf("UUID version nibble = %c, want '4'", id[14])
389 }
390 // Variant nibble should be 8, 9, a, or b
391 v := id[19]
392 if v != '8' && v != '9' && v != 'a' && v != 'b' {
393 t.Errorf("UUID variant nibble = %c, want 8/9/a/b", v)
394 }
395 // Should have dashes in correct positions
396 for _, pos := range []int{8, 13, 18, 23} {
397 if id[pos] != '-' {
398 t.Errorf("UUID[%d] = %c, want '-'", pos, id[pos])
399 }
400 }
401}