12 "github.com/charmbracelet/crush/internal/csync"
16 // MaxBackgroundJobs is the maximum number of concurrent background jobs allowed
17 MaxBackgroundJobs = 50
18 // CompletedJobRetentionMinutes is how long to keep completed jobs before auto-cleanup (8 hours)
19 CompletedJobRetentionMinutes = 8 * 60
22// BackgroundShell represents a shell running in the background.
23type BackgroundShell struct {
30 cancel context.CancelFunc
35 completedAt int64 // Unix timestamp when job completed (0 if still running)
38// BackgroundShellManager manages background shell instances.
39type BackgroundShellManager struct {
40 shells *csync.Map[string, *BackgroundShell]
44 backgroundManager *BackgroundShellManager
45 backgroundManagerOnce sync.Once
46 idCounter atomic.Uint64
49// GetBackgroundShellManager returns the singleton background shell manager.
50func GetBackgroundShellManager() *BackgroundShellManager {
51 backgroundManagerOnce.Do(func() {
52 backgroundManager = &BackgroundShellManager{
53 shells: csync.NewMap[string, *BackgroundShell](),
56 return backgroundManager
59// Start creates and starts a new background shell with the given command.
60func (m *BackgroundShellManager) Start(ctx context.Context, workingDir string, blockFuncs []BlockFunc, command string, description string) (*BackgroundShell, error) {
62 if m.shells.Len() >= MaxBackgroundJobs {
63 return nil, fmt.Errorf("maximum number of background jobs (%d) reached. Please terminate or wait for some jobs to complete", MaxBackgroundJobs)
66 id := fmt.Sprintf("%03X", idCounter.Add(1))
68 shell := NewShell(&Options{
69 WorkingDir: workingDir,
70 BlockFuncs: blockFuncs,
73 shellCtx, cancel := context.WithCancel(ctx)
75 bgShell := &BackgroundShell{
78 Description: description,
79 WorkingDir: workingDir,
83 stdout: &bytes.Buffer{},
84 stderr: &bytes.Buffer{},
85 done: make(chan struct{}),
88 m.shells.Set(id, bgShell)
91 defer close(bgShell.done)
93 err := shell.ExecStream(shellCtx, command, bgShell.stdout, bgShell.stderr)
96 atomic.StoreInt64(&bgShell.completedAt, time.Now().Unix())
102// Get retrieves a background shell by ID.
103func (m *BackgroundShellManager) Get(id string) (*BackgroundShell, bool) {
104 return m.shells.Get(id)
107// Remove removes a background shell from the manager without terminating it.
108// This is useful when a shell has already completed and you just want to clean up tracking.
109func (m *BackgroundShellManager) Remove(id string) error {
110 _, ok := m.shells.Take(id)
112 return fmt.Errorf("background shell not found: %s", id)
117// Kill terminates a background shell by ID.
118func (m *BackgroundShellManager) Kill(id string) error {
119 shell, ok := m.shells.Take(id)
121 return fmt.Errorf("background shell not found: %s", id)
129// BackgroundShellInfo contains information about a background shell.
130type BackgroundShellInfo struct {
136// List returns all background shell IDs.
137func (m *BackgroundShellManager) List() []string {
138 ids := make([]string, 0, m.shells.Len())
139 for id := range m.shells.Seq2() {
140 ids = append(ids, id)
145// Cleanup removes completed jobs that have been finished for more than the retention period
146func (m *BackgroundShellManager) Cleanup() int {
147 now := time.Now().Unix()
148 retentionSeconds := int64(CompletedJobRetentionMinutes * 60)
150 var toRemove []string
151 for shell := range m.shells.Seq() {
152 completedAt := atomic.LoadInt64(&shell.completedAt)
153 if completedAt > 0 && now-completedAt > retentionSeconds {
154 toRemove = append(toRemove, shell.ID)
158 for _, id := range toRemove {
165// KillAll terminates all background shells.
166func (m *BackgroundShellManager) KillAll() {
167 shells := slices.Collect(m.shells.Seq())
168 m.shells.Reset(map[string]*BackgroundShell{})
169 done := make(chan struct{}, 1)
171 var wg sync.WaitGroup
172 for _, shell := range shells {
185 case <-time.After(time.Second * 5):
190// GetOutput returns the current output of a background shell.
191func (bs *BackgroundShell) GetOutput() (stdout string, stderr string, done bool, err error) {
194 return bs.stdout.String(), bs.stderr.String(), true, bs.exitErr
196 return bs.stdout.String(), bs.stderr.String(), false, nil
200// IsDone checks if the background shell has finished execution.
201func (bs *BackgroundShell) IsDone() bool {
210// Wait blocks until the background shell completes.
211func (bs *BackgroundShell) Wait() {
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list