gunk-dev/the-valley

session_test.go

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