From ef07c95b0c3dbcea071b7624775fb3407cdc1256 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 00:16:06 +0000 Subject: [PATCH] fix(claude): list background commands and agents as running tasks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Bash call with run_in_background and an Agent call return at once ('Command running in background…' / 'Async agent launched…'), so the chat's task list counted them finished immediately and showed 0 tasks. They now stay running until Claude Code's task notification (the text or the SDK's task_notification message) reports completion, with the exit code from its summary. --- internal/claude/background_tasks_test.go | 120 +++++++++++++++++++++ internal/claude/translate.go | 129 ++++++++++++++++++++++- 2 files changed, 245 insertions(+), 4 deletions(-) create mode 100644 internal/claude/background_tasks_test.go diff --git a/internal/claude/background_tasks_test.go b/internal/claude/background_tasks_test.go new file mode 100644 index 00000000..793c1334 --- /dev/null +++ b/internal/claude/background_tasks_test.go @@ -0,0 +1,120 @@ +package claude + +import ( + "context" + "encoding/json" + "testing" + + "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": "\nb123\ntoolu_bg\n" + + "completed\nBackground command \"Wait\" completed (exit code 3)\n", + }, + })) + 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("toolu_fgcompleted") + s.finishBackgroundTasks("toolu_unknown") + if shells := running(t, chat); len(shells) != 0 { + t.Fatalf("stray notifications list nothing, got %+v", shells) + } +} diff --git a/internal/claude/translate.go b/internal/claude/translate.go index 3f1af387..125ed14f 100644 --- a/internal/claude/translate.go +++ b/internal/claude/translate.go @@ -109,6 +109,10 @@ func (s *session) handleLine(p *process, line []byte) { case "result": s.handleResult(envelope) case "system": + if envelope.Subtype == "task_notification" { + s.finishNotifiedTask(line) + return + } s.handleSystem(envelope) } } @@ -377,10 +381,23 @@ func (s *session) handleAssistant(envelope lineEnvelope) { }, }, }) - if block.Name == "Bash" { - if shell := s.recordShellLocked(block.ID, bashCommand(input)); shell != nil { - frames = append(frames, protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: shell}) + var shell *protocol.ChatShell + switch block.Name { + case "Bash": + shell = s.recordShellLocked(block.ID, bashCommand(input)) + if shell != nil && backgroundRequested(input) { + s.shells[block.ID].background = true } + case "Agent", "Task": + // A subagent usually runs in the background; its immediate + // result says so, and a foreground one simply finishes. + shell = s.recordShellLocked(block.ID, agentLabel(input)) + if shell != nil { + s.shells[block.ID].background = true + } + } + if shell != nil { + frames = append(frames, protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: shell}) } } } @@ -400,6 +417,11 @@ func (s *session) handleUser(envelope lineEnvelope) { return } blocks := decodeBlocks(body.Content) + for _, block := range blocks { + if block.Type == "text" && strings.Contains(block.Text, "") { + s.finishBackgroundTasks(block.Text) + } + } for _, block := range blocks { if block.Type != "tool_result" || block.ToolUseID == "" { continue @@ -447,7 +469,12 @@ func (s *session) handleUser(envelope lineEnvelope) { if shell != nil { var frame *protocol.ChatShell s.mu.Lock() - if snapshot, ok := s.shells[block.ToolUseID]; ok { + if snapshot, ok := s.shells[block.ToolUseID]; ok && snapshot.background && launchedInBackground(text) { + // Started, not finished: it stays running until Claude Code + // reports the task's completion. + snapshot.output = text + snapshot.size = int64(len(text)) + } else if ok { snapshot.shell.Status = protocol.ChatShellExited snapshot.shell.Exit = exit if text != "" && len(text) >= len(snapshot.output) { @@ -630,6 +657,100 @@ type shellSnapshot struct { output string size int64 order uint64 + // background marks a command or subagent that may outlive its tool call: + // its immediate result only says it started. + background bool +} + +// backgroundRequested reports a Bash call asked to run in the background. +func backgroundRequested(input json.RawMessage) bool { + var parsed struct { + Background bool `json:"run_in_background"` + } + return json.Unmarshal(input, &parsed) == nil && parsed.Background +} + +// agentLabel names a subagent the way the operator recognises it. +func agentLabel(input json.RawMessage) string { + var parsed struct { + Description string `json:"description"` + Type string `json:"subagent_type"` + } + _ = json.Unmarshal(input, &parsed) + label := strings.TrimSpace(parsed.Description) + if label == "" { + label = strings.TrimSpace(parsed.Type) + } + if label == "" { + return "Agent" + } + return "Agent: " + label +} + +// launchedInBackground recognises Claude Code's immediate result for a task +// that keeps running after its tool call returns. +func launchedInBackground(text string) bool { + return strings.Contains(text, "running in background with ID") || + strings.HasPrefix(strings.TrimSpace(text), "Async agent launched") +} + +var ( + taskNotificationPattern = regexp.MustCompile(`(?s)(.*?)`) + taskToolUsePattern = regexp.MustCompile(`\s*([^<\s]+)\s*`) + taskSummaryPattern = regexp.MustCompile(`(?s)(.*?)`) + taskExitPattern = regexp.MustCompile(`exit code (-?\d+)`) +) + +// finishNotifiedTask handles the SDK's structured completion message for a +// background task, the counterpart of the text. +func (s *session) finishNotifiedTask(line []byte) { + var notice struct { + ToolUseID string `json:"tool_use_id"` + Status string `json:"status"` + Summary string `json:"summary"` + } + if json.Unmarshal(line, ¬ice) != nil || notice.ToolUseID == "" { + return + } + s.finishBackgroundTasks(fmt.Sprintf( + "%s%s%s", + notice.ToolUseID, notice.Status, notice.Summary, + )) +} + +// finishBackgroundTasks marks the tasks a Claude Code task notification +// reports as finished, and publishes each one's final state. +func (s *session) finishBackgroundTasks(text string) { + var frames []*protocol.ChatShell + s.mu.Lock() + for _, match := range taskNotificationPattern.FindAllStringSubmatch(text, -1) { + toolID := taskToolUsePattern.FindStringSubmatch(match[1]) + if toolID == nil { + continue + } + snapshot, ok := s.shells[toolID[1]] + if !ok || snapshot.shell.Status != protocol.ChatShellRunning { + continue + } + snapshot.shell.Status = protocol.ChatShellExited + if summary := taskSummaryPattern.FindStringSubmatch(match[1]); summary != nil { + line := strings.TrimSpace(summary[1]) + if code := taskExitPattern.FindStringSubmatch(line); code != nil { + if exit, err := strconv.Atoi(code[1]); err == nil { + snapshot.shell.Exit = &exit + } + } + if line != "" { + snapshot.output = strings.TrimRight(snapshot.output, "\n") + "\n" + line + snapshot.size = int64(len(snapshot.output)) + } + } + frames = append(frames, &protocol.ChatShell{ID: snapshot.shell.ID, Status: snapshot.shell.Status, Command: snapshot.shell.Command, Exit: snapshot.shell.Exit}) + } + s.mu.Unlock() + for _, frame := range frames { + s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: frame}) + } } func shellID(toolID string) string {