Files
pipelines/internal/claude/background_tasks_test.go

202 lines
7.0 KiB
Go

package claude
import (
"context"
"encoding/json"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func backgroundSession(t *testing.T) (*Chat, *session) {
t.Helper()
chat := New(context.Background())
return chat, chat.sessionFor("ses_bg", t.TempDir())
}
func line(t *testing.T, value any) []byte {
t.Helper()
raw, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
return raw
}
func toolUse(t *testing.T, id, name string, input map[string]any) []byte {
return line(t, map[string]any{
"type": "assistant",
"message": map[string]any{
"id": "msg_" + id, "role": "assistant",
"content": []any{map[string]any{"type": "tool_use", "id": id, "name": name, "input": input}},
},
})
}
func toolResult(t *testing.T, id, text string) []byte {
return line(t, map[string]any{
"type": "user",
"message": map[string]any{
"role": "user",
"content": []any{map[string]any{"type": "tool_result", "tool_use_id": id, "content": text}},
},
})
}
func running(t *testing.T, chat *Chat) []protocol.ChatShell {
t.Helper()
shells, err := chat.Shells(context.Background(), "ses_bg")
if err != nil {
t.Fatal(err)
}
return shells
}
func TestBackgroundBashStaysRunningUntilItsNotification(t *testing.T) {
chat, s := backgroundSession(t)
s.handleLine(nil, toolUse(t, "toolu_bg", "Bash", map[string]any{"command": "pipelines wait 191", "run_in_background": true}))
s.handleLine(nil, toolResult(t, "toolu_bg", "Command running in background with ID: b123. Output is being written to: /tmp/b123.output"))
shells := running(t, chat)
if len(shells) != 1 || shells[0].Command != "pipelines wait 191" {
t.Fatalf("a background command must stay listed while it runs, got %+v", shells)
}
s.handleLine(nil, line(t, map[string]any{
"type": "user",
"message": map[string]any{
"role": "user",
"content": "<task-notification>\n<task-id>b123</task-id>\n<tool-use-id>toolu_bg</tool-use-id>\n" +
"<status>completed</status>\n<summary>Background command \"Wait\" completed (exit code 3)</summary>\n</task-notification>",
},
}))
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("a notified task must leave the running list, got %+v", shells)
}
s.mu.Lock()
exit := s.shells["toolu_bg"].shell.Exit
s.mu.Unlock()
if exit == nil || *exit != 3 {
t.Fatalf("the notification's exit code is recorded, got %v", exit)
}
}
func TestBackgroundAgentFinishesFromTheStructuredNotice(t *testing.T) {
chat, s := backgroundSession(t)
s.handleLine(nil, toolUse(t, "toolu_agent", "Agent", map[string]any{"description": "Review the lists", "prompt": "…"}))
s.handleLine(nil, toolResult(t, "toolu_agent", "Async agent launched successfully."))
shells := running(t, chat)
if len(shells) != 1 || shells[0].Command != "Agent: Review the lists" {
t.Fatalf("a background agent is listed by its description, got %+v", shells)
}
s.handleLine(nil, line(t, map[string]any{
"type": "system", "subtype": "task_notification",
"task_id": "a1", "tool_use_id": "toolu_agent", "status": "completed", "summary": "Agent finished",
}))
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("the structured notice finishes the agent, got %+v", shells)
}
}
func TestForegroundCommandsAndAgentsFinishWithTheirResult(t *testing.T) {
chat, s := backgroundSession(t)
s.handleLine(nil, toolUse(t, "toolu_fg", "Bash", map[string]any{"command": "ls"}))
s.handleLine(nil, toolUse(t, "toolu_sync", "Agent", map[string]any{"description": "Quick look"}))
if shells := running(t, chat); len(shells) != 2 {
t.Fatalf("both are running while their calls are open, got %+v", shells)
}
s.handleLine(nil, toolResult(t, "toolu_fg", "file.txt"))
s.handleLine(nil, toolResult(t, "toolu_sync", "Here is what I found."))
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("a foreground command or agent finishes with its result, got %+v", shells)
}
// A stray notification for an unknown or finished task changes nothing.
s.finishBackgroundTasks("<task-notification><tool-use-id>toolu_fg</tool-use-id><status>completed</status></task-notification>")
s.finishBackgroundTasks("<task-notification><tool-use-id>toolu_unknown</tool-use-id></task-notification>")
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("stray notifications list nothing, got %+v", shells)
}
}
// Background commands and subagents run inside the CLI process, so a process
// that exits (crash, idle release, interrupt) ends them: each is reported as
// exited instead of staying "running" with nothing left to report its end.
func TestProcessExitEndsBackgroundTasks(t *testing.T) {
chat, s := backgroundSession(t)
s.handleLine(nil, toolUse(t, "toolu_bg", "Bash", map[string]any{"command": "sleep 600", "run_in_background": true}))
s.handleLine(nil, toolResult(t, "toolu_bg", "Command running in background with ID: b9. Output is being written to: /tmp/b9.output"))
if shells := running(t, chat); len(shells) != 1 {
t.Fatalf("the background command must be running first, got %+v", shells)
}
subs := attachTestSubs(s, 1)
defer detachTestSubs(s, subs)
proc := &process{session: s}
s.mu.Lock()
s.proc = proc
s.mu.Unlock()
s.processExit(proc, nil)
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("a process exit must end its background tasks, got %+v", shells)
}
select {
case frame := <-subs[0]:
if frame.Kind != protocol.ChatEventShell || frame.Shell == nil || frame.Shell.Status != protocol.ChatShellExited || frame.Shell.Command != "sleep 600" {
t.Fatalf("the exit is published as a shell exit, got %+v", frame)
}
default:
t.Fatal("no shell exit was published")
}
}
func TestObserverReleaseDoesNotForgetOrReapRunningNativeTasks(t *testing.T) {
chat, s := backgroundSession(t)
defer chat.Close()
s.handleLine(nil, toolUse(t, "toolu_bg", "Bash", map[string]any{"command": "quiet background work", "run_in_background": true}))
s.handleLine(nil, toolResult(t, "toolu_bg", "Command running in background with ID: native-bg"))
s.handleLine(nil, toolUse(t, "toolu_done", "Bash", map[string]any{"command": "completed foreground"}))
s.handleLine(nil, toolResult(t, "toolu_done", "done"))
proc := newProcess(s, "")
proc.markReady()
s.mu.Lock()
s.proc = proc
s.running = false
s.lastUsed = time.Now().Add(-time.Hour)
s.mu.Unlock()
chat.ReleaseShells(s.id)
if shells := running(t, chat); len(shells) != 1 || shells[0].ID != shellID("toolu_bg") {
t.Fatalf("observer expiry lost task identity: %+v", shells)
}
chat.reapIdleAt(time.Now())
s.mu.Lock()
same := s.proc == proc
s.proc = nil
s.mu.Unlock()
if !same {
t.Fatal("idle cache eviction stopped active background work")
}
}
func TestLegacyHostRemainsAttachedDuringIdleCacheEviction(t *testing.T) {
chat, s := backgroundSession(t)
defer chat.Close()
proc := newProcess(s, "")
proc.markReady()
proc.link = &hostLink{} // No authoritative task snapshot capability.
s.mu.Lock()
s.proc = proc
s.lastUsed = time.Now().Add(-time.Hour)
s.mu.Unlock()
chat.reapIdleAt(time.Now())
s.mu.Lock()
same := s.proc == proc
s.proc = nil
s.mu.Unlock()
if !same {
t.Fatal("legacy host was detached despite unknown background liveness")
}
}