-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathinstance.go
More file actions
569 lines (496 loc) · 15.6 KB
/
instance.go
File metadata and controls
569 lines (496 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
package session
import (
"claude-squad/log"
"claude-squad/session/git"
"claude-squad/session/tmux"
"path/filepath"
"fmt"
"os"
"strings"
"time"
"github.com/atotto/clipboard"
)
type Status int
const (
// Running is the status when the instance is running and claude is working.
Running Status = iota
// Ready is if the claude instance is ready to be interacted with (waiting for user input).
Ready
// Loading is if the instance is loading (if we are starting it up or something).
Loading
// Paused is if the instance is paused (worktree removed but branch preserved).
Paused
)
// Instance is a running instance of claude code.
type Instance struct {
// Title is the title of the instance.
Title string
// Path is the path to the workspace.
Path string
// Branch is the branch of the instance.
Branch string
// Status is the status of the instance.
Status Status
// Program is the program to run in the instance.
Program string
// Height is the height of the instance.
Height int
// Width is the width of the instance.
Width int
// CreatedAt is the time the instance was created.
CreatedAt time.Time
// UpdatedAt is the time the instance was last updated.
UpdatedAt time.Time
// AutoYes is true if the instance should automatically press enter when prompted.
AutoYes bool
// Prompt is the initial prompt to pass to the instance on startup
Prompt string
// DiffStats stores the current git diff statistics
diffStats *git.DiffStats
// The below fields are initialized upon calling Start().
started bool
// tmuxSession is the tmux session for the instance.
tmuxSession *tmux.TmuxSession
// gitWorktree is the git worktree for the instance.
gitWorktree *git.GitWorktree
}
// ToInstanceData converts an Instance to its serializable form
func (i *Instance) ToInstanceData() InstanceData {
data := InstanceData{
Title: i.Title,
Path: i.Path,
Branch: i.Branch,
Status: i.Status,
Height: i.Height,
Width: i.Width,
CreatedAt: i.CreatedAt,
UpdatedAt: time.Now(),
Program: i.Program,
AutoYes: i.AutoYes,
}
// Only include worktree data if gitWorktree is initialized
if i.gitWorktree != nil {
data.Worktree = GitWorktreeData{
RepoPath: i.gitWorktree.GetRepoPath(),
WorktreePath: i.gitWorktree.GetWorktreePath(),
SessionName: i.Title,
BranchName: i.gitWorktree.GetBranchName(),
BaseCommitSHA: i.gitWorktree.GetBaseCommitSHA(),
}
}
// Only include diff stats if they exist
if i.diffStats != nil {
data.DiffStats = DiffStatsData{
Added: i.diffStats.Added,
Removed: i.diffStats.Removed,
Content: i.diffStats.Content,
}
}
return data
}
// FromInstanceData creates a new Instance from serialized data
func FromInstanceData(data InstanceData) (*Instance, error) {
instance := &Instance{
Title: data.Title,
Path: data.Path,
Branch: data.Branch,
Status: data.Status,
Height: data.Height,
Width: data.Width,
CreatedAt: data.CreatedAt,
UpdatedAt: data.UpdatedAt,
Program: data.Program,
gitWorktree: git.NewGitWorktreeFromStorage(
data.Worktree.RepoPath,
data.Worktree.WorktreePath,
data.Worktree.SessionName,
data.Worktree.BranchName,
data.Worktree.BaseCommitSHA,
),
diffStats: &git.DiffStats{
Added: data.DiffStats.Added,
Removed: data.DiffStats.Removed,
Content: data.DiffStats.Content,
},
}
if instance.Paused() {
instance.started = true
instance.tmuxSession = tmux.NewTmuxSession(instance.Title, instance.Program)
} else {
if err := instance.Start(false); err != nil {
return nil, err
}
}
return instance, nil
}
// Options for creating a new instance
type InstanceOptions struct {
// Title is the title of the instance.
Title string
// Path is the path to the workspace.
Path string
// Program is the program to run in the instance (e.g. "claude", "aider --model ollama_chat/gemma3:1b")
Program string
// If AutoYes is true, then
AutoYes bool
}
func NewInstance(opts InstanceOptions) (*Instance, error) {
t := time.Now()
// Convert path to absolute
absPath, err := filepath.Abs(opts.Path)
if err != nil {
return nil, fmt.Errorf("failed to get absolute path: %w", err)
}
return &Instance{
Title: opts.Title,
Status: Ready,
Path: absPath,
Program: opts.Program,
Height: 0,
Width: 0,
CreatedAt: t,
UpdatedAt: t,
AutoYes: false,
}, nil
}
func (i *Instance) RepoName() (string, error) {
if !i.started {
return "", fmt.Errorf("cannot get repo name for instance that has not been started")
}
return i.gitWorktree.GetRepoName(), nil
}
func (i *Instance) SetStatus(status Status) {
i.Status = status
}
// firstTimeSetup is true if this is a new instance. Otherwise, it's one loaded from storage.
func (i *Instance) Start(firstTimeSetup bool) error {
if i.Title == "" {
return fmt.Errorf("instance title cannot be empty")
}
var tmuxSession *tmux.TmuxSession
if i.tmuxSession != nil {
// Use existing tmux session (useful for testing)
tmuxSession = i.tmuxSession
} else {
// Create new tmux session
tmuxSession = tmux.NewTmuxSession(i.Title, i.Program)
}
i.tmuxSession = tmuxSession
if firstTimeSetup {
gitWorktree, branchName, err := git.NewGitWorktree(i.Path, i.Title)
if err != nil {
return fmt.Errorf("failed to create git worktree: %w", err)
}
i.gitWorktree = gitWorktree
i.Branch = branchName
}
// Setup error handler to cleanup resources on any error
var setupErr error
defer func() {
if setupErr != nil {
if cleanupErr := i.Kill(); cleanupErr != nil {
setupErr = fmt.Errorf("%v (cleanup error: %v)", setupErr, cleanupErr)
}
} else {
i.started = true
}
}()
if !firstTimeSetup {
// Reuse existing session
if err := tmuxSession.Restore(); err != nil {
setupErr = fmt.Errorf("failed to restore existing session: %w", err)
return setupErr
}
} else {
// Setup git worktree first
if err := i.gitWorktree.Setup(); err != nil {
setupErr = fmt.Errorf("failed to setup git worktree: %w", err)
return setupErr
}
// Create new session
if err := i.tmuxSession.Start(i.gitWorktree.GetWorktreePath()); err != nil {
// Cleanup git worktree if tmux session creation fails
if cleanupErr := i.gitWorktree.Cleanup(); cleanupErr != nil {
err = fmt.Errorf("%v (cleanup error: %v)", err, cleanupErr)
}
setupErr = fmt.Errorf("failed to start new session: %w", err)
return setupErr
}
}
i.SetStatus(Running)
return nil
}
// Kill terminates the instance and cleans up all resources
func (i *Instance) Kill() error {
if !i.started {
// If instance was never started, just return success
return nil
}
var errs []error
// Always try to cleanup both resources, even if one fails
// Clean up tmux session first since it's using the git worktree
if i.tmuxSession != nil {
if err := i.tmuxSession.Close(); err != nil {
errs = append(errs, fmt.Errorf("failed to close tmux session: %w", err))
}
}
// Then clean up git worktree
if i.gitWorktree != nil {
if err := i.gitWorktree.Cleanup(); err != nil {
errs = append(errs, fmt.Errorf("failed to cleanup git worktree: %w", err))
}
}
return i.combineErrors(errs)
}
// combineErrors combines multiple errors into a single error
func (i *Instance) combineErrors(errs []error) error {
if len(errs) == 0 {
return nil
}
if len(errs) == 1 {
return errs[0]
}
errMsg := "multiple cleanup errors occurred:"
for _, err := range errs {
errMsg += "\n - " + err.Error()
}
return fmt.Errorf("%s", errMsg)
}
func (i *Instance) Preview() (string, error) {
if !i.started || i.Status == Paused {
return "", nil
}
return i.tmuxSession.CapturePaneContent()
}
func (i *Instance) HasUpdated() (updated bool, hasPrompt bool) {
if !i.started {
return false, false
}
return i.tmuxSession.HasUpdated()
}
// TapEnter sends an enter key press to the tmux session if AutoYes is enabled.
func (i *Instance) TapEnter() {
if !i.started || !i.AutoYes {
return
}
if err := i.tmuxSession.TapEnter(); err != nil {
log.ErrorLog.Printf("error tapping enter: %v", err)
}
}
func (i *Instance) Attach() (chan struct{}, error) {
if !i.started {
return nil, fmt.Errorf("cannot attach instance that has not been started")
}
return i.tmuxSession.Attach()
}
func (i *Instance) SetPreviewSize(width, height int) error {
if !i.started || i.Status == Paused {
return fmt.Errorf("cannot set preview size for instance that has not been started or " +
"is paused")
}
return i.tmuxSession.SetDetachedSize(width, height)
}
// GetGitWorktree returns the git worktree for the instance
func (i *Instance) GetGitWorktree() (*git.GitWorktree, error) {
if !i.started {
return nil, fmt.Errorf("cannot get git worktree for instance that has not been started")
}
return i.gitWorktree, nil
}
func (i *Instance) Started() bool {
return i.started
}
// SetTitle sets the title of the instance. Returns an error if the instance has started.
// We cant change the title once it's been used for a tmux session etc.
func (i *Instance) SetTitle(title string) error {
if i.started {
return fmt.Errorf("cannot change title of a started instance")
}
i.Title = title
return nil
}
func (i *Instance) Paused() bool {
return i.Status == Paused
}
// TmuxAlive returns true if the tmux session is alive. This is a sanity check before attaching.
func (i *Instance) TmuxAlive() bool {
return i.tmuxSession.DoesSessionExist()
}
// Pause stops the tmux session and removes the worktree, preserving the branch
func (i *Instance) Pause() error {
if !i.started {
return fmt.Errorf("cannot pause instance that has not been started")
}
if i.Status == Paused {
return fmt.Errorf("instance is already paused")
}
var errs []error
// Check if there are any changes to commit
if dirty, err := i.gitWorktree.IsDirty(); err != nil {
errs = append(errs, fmt.Errorf("failed to check if worktree is dirty: %w", err))
log.ErrorLog.Print(err)
} else if dirty {
// Commit changes locally (without pushing to GitHub)
commitMsg := fmt.Sprintf("[claudesquad] update from '%s' on %s (paused)", i.Title, time.Now().Format(time.RFC822))
if err := i.gitWorktree.CommitChanges(commitMsg); err != nil {
errs = append(errs, fmt.Errorf("failed to commit changes: %w", err))
log.ErrorLog.Print(err)
// Return early if we can't commit changes to avoid corrupted state
return i.combineErrors(errs)
}
}
// Detach from tmux session instead of closing to preserve session output
if err := i.tmuxSession.DetachSafely(); err != nil {
errs = append(errs, fmt.Errorf("failed to detach tmux session: %w", err))
log.ErrorLog.Print(err)
// Continue with pause process even if detach fails
}
// Check if worktree exists before trying to remove it
if _, err := os.Stat(i.gitWorktree.GetWorktreePath()); err == nil {
// Remove worktree but keep branch
if err := i.gitWorktree.Remove(); err != nil {
errs = append(errs, fmt.Errorf("failed to remove git worktree: %w", err))
log.ErrorLog.Print(err)
return i.combineErrors(errs)
}
// Only prune if remove was successful
if err := i.gitWorktree.Prune(); err != nil {
errs = append(errs, fmt.Errorf("failed to prune git worktrees: %w", err))
log.ErrorLog.Print(err)
return i.combineErrors(errs)
}
}
if err := i.combineErrors(errs); err != nil {
log.ErrorLog.Print(err)
return err
}
i.SetStatus(Paused)
_ = clipboard.WriteAll(i.gitWorktree.GetBranchName())
return nil
}
// Resume recreates the worktree and restarts the tmux session
func (i *Instance) Resume() error {
if !i.started {
return fmt.Errorf("cannot resume instance that has not been started")
}
if i.Status != Paused {
return fmt.Errorf("can only resume paused instances")
}
// Check if branch is checked out
if checked, err := i.gitWorktree.IsBranchCheckedOut(); err != nil {
log.ErrorLog.Print(err)
return fmt.Errorf("failed to check if branch is checked out: %w", err)
} else if checked {
return fmt.Errorf("cannot resume: branch is checked out, please switch to a different branch")
}
// Setup git worktree
if err := i.gitWorktree.Setup(); err != nil {
log.ErrorLog.Print(err)
return fmt.Errorf("failed to setup git worktree: %w", err)
}
// Check if tmux session still exists from pause, otherwise create new one
if i.tmuxSession.DoesSessionExist() {
// Session exists, just restore PTY connection to it
if err := i.tmuxSession.Restore(); err != nil {
log.ErrorLog.Print(err)
// If restore fails, fall back to creating new session
if err := i.tmuxSession.Start(i.gitWorktree.GetWorktreePath()); err != nil {
log.ErrorLog.Print(err)
// Cleanup git worktree if tmux session creation fails
if cleanupErr := i.gitWorktree.Cleanup(); cleanupErr != nil {
err = fmt.Errorf("%v (cleanup error: %v)", err, cleanupErr)
log.ErrorLog.Print(err)
}
return fmt.Errorf("failed to start new session: %w", err)
}
}
} else {
// Create new tmux session
if err := i.tmuxSession.Start(i.gitWorktree.GetWorktreePath()); err != nil {
log.ErrorLog.Print(err)
// Cleanup git worktree if tmux session creation fails
if cleanupErr := i.gitWorktree.Cleanup(); cleanupErr != nil {
err = fmt.Errorf("%v (cleanup error: %v)", err, cleanupErr)
log.ErrorLog.Print(err)
}
return fmt.Errorf("failed to start new session: %w", err)
}
}
i.SetStatus(Running)
return nil
}
// UpdateDiffStats updates the git diff statistics for this instance
func (i *Instance) UpdateDiffStats() error {
if !i.started {
i.diffStats = nil
return nil
}
if i.Status == Paused {
// Keep the previous diff stats if the instance is paused
return nil
}
stats := i.gitWorktree.Diff()
if stats.Error != nil {
if strings.Contains(stats.Error.Error(), "base commit SHA not set") {
// Worktree is not fully set up yet, not an error
i.diffStats = nil
return nil
}
return fmt.Errorf("failed to get diff stats: %w", stats.Error)
}
i.diffStats = stats
return nil
}
// ComputeDiff runs the expensive git diff I/O and returns the result without
// mutating instance state. Safe to call from a background goroutine.
func (i *Instance) ComputeDiff() *git.DiffStats {
if !i.started || i.Status == Paused {
return nil
}
return i.gitWorktree.Diff()
}
// SetDiffStats sets the diff statistics on the instance. Should be called from
// the main event loop to avoid data races with View.
func (i *Instance) SetDiffStats(stats *git.DiffStats) {
i.diffStats = stats
}
// GetDiffStats returns the current git diff statistics
func (i *Instance) GetDiffStats() *git.DiffStats {
return i.diffStats
}
// SendPrompt sends a prompt to the tmux session
func (i *Instance) SendPrompt(prompt string) error {
if !i.started {
return fmt.Errorf("instance not started")
}
if i.tmuxSession == nil {
return fmt.Errorf("tmux session not initialized")
}
if err := i.tmuxSession.SendKeys(prompt); err != nil {
return fmt.Errorf("error sending keys to tmux session: %w", err)
}
// Brief pause to prevent carriage return from being interpreted as newline
time.Sleep(100 * time.Millisecond)
if err := i.tmuxSession.TapEnter(); err != nil {
return fmt.Errorf("error tapping enter: %w", err)
}
return nil
}
// PreviewFullHistory captures the entire tmux pane output including full scrollback history
func (i *Instance) PreviewFullHistory() (string, error) {
if !i.started || i.Status == Paused {
return "", nil
}
return i.tmuxSession.CapturePaneContentWithOptions("-", "-")
}
// SetTmuxSession sets the tmux session for testing purposes
func (i *Instance) SetTmuxSession(session *tmux.TmuxSession) {
i.tmuxSession = session
}
// SendKeys sends keys to the tmux session
func (i *Instance) SendKeys(keys string) error {
if !i.started || i.Status == Paused {
return fmt.Errorf("cannot send keys to instance that has not been started or is paused")
}
return i.tmuxSession.SendKeys(keys)
}