fix(claude): list background commands and agents as running tasks
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
<task-notification> text or the SDK's task_notification message)
reports completion, with the exit code from its summary.
This commit is contained in:
@@ -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": "<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)
|
||||
}
|
||||
}
|
||||
@@ -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, "<task-notification>") {
|
||||
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)<task-notification>(.*?)</task-notification>`)
|
||||
taskToolUsePattern = regexp.MustCompile(`<tool-use-id>\s*([^<\s]+)\s*</tool-use-id>`)
|
||||
taskSummaryPattern = regexp.MustCompile(`(?s)<summary>(.*?)</summary>`)
|
||||
taskExitPattern = regexp.MustCompile(`exit code (-?\d+)`)
|
||||
)
|
||||
|
||||
// finishNotifiedTask handles the SDK's structured completion message for a
|
||||
// background task, the counterpart of the <task-notification> 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(
|
||||
"<task-notification><tool-use-id>%s</tool-use-id><status>%s</status><summary>%s</summary></task-notification>",
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user