package claudehost import ( "encoding/json" "regexp" "strings" "unicode/utf8" ) // The host owns the real CLI even with no Pipelines connection. Foreground // result messages do not end background tools; only their native completion // notifications do. Keep this lifecycle state independently of spool acks. func (h *host) trackTasksLocked(line []byte) { var event struct { Type string `json:"type"` Subtype string `json:"subtype"` ToolUseID string `json:"tool_use_id"` TaskID string `json:"task_id"` Status string `json:"status"` Description string `json:"description"` TaskType string `json:"task_type"` Timestamp string `json:"timestamp"` Tasks []struct { TaskID string `json:"task_id"` } `json:"tasks"` Message struct { Content json.RawMessage `json:"content"` } `json:"message"` } if json.Unmarshal(line, &event) != nil { return } if h.tasks == nil { h.tasks = map[string]string{} } if h.taskOrigins == nil { h.taskOrigins = map[string]Task{} } if h.taskCalls == nil || len(h.taskCalls) > maxTaskMarks { h.taskCalls = map[string]bool{} } if h.taskEnded == nil || len(h.taskEnded) > maxTaskMarks { h.taskEnded = map[string]bool{} } // end removes a finished tool call or native task for good: a progress // line or a launch acknowledgement that arrives after its completion // notification (the CLI does not order them) must not revive it. end := func(key string) { taskID := h.tasks[key] delete(h.tasks, key) delete(h.taskOrigins, key) h.taskEnded[key] = true if strings.HasPrefix(key, "task:") { h.taskEnded[key[len("task:"):]] = true } if taskID != "" { h.taskEnded[taskID] = true delete(h.tasks, "task:"+taskID) delete(h.taskOrigins, "task:"+taskID) } } switch event.Subtype { case "task_started", "task_progress": id := event.ToolUseID if id == "" { for key, task := range h.tasks { if event.TaskID != "" && task == event.TaskID { id = key break } } if id == "" { id = "task:" + event.TaskID } } if id != "task:" && !h.taskEnded[id] && !(event.TaskID != "" && h.taskEnded[event.TaskID]) { if event.ToolUseID != "" && event.TaskID != "" { fallback := "task:" + event.TaskID if prior, exists := h.taskOrigins[fallback]; exists { if _, recorded := h.taskOrigins[id]; !recorded { h.taskOrigins[id] = prior } delete(h.tasks, fallback) delete(h.taskOrigins, fallback) } } if _, exists := h.tasks[id]; !exists || event.TaskID != "" { h.tasks[id] = event.TaskID } origin := h.taskOrigins[id] if event.ToolUseID != "" { origin.ToolUseID = event.ToolUseID } if event.TaskID != "" { origin.TaskID = event.TaskID } if event.Description != "" { origin.Description = taskText(event.Description, 2048) } if event.TaskType != "" { origin.TaskType = taskText(event.TaskType, 128) } if origin.Timestamp == "" { origin.Timestamp = event.Timestamp } h.taskOrigins[id] = origin } case "task_notification": if event.Status == "completed" || event.Status == "failed" || event.Status == "stopped" { for key, task := range h.tasks { if key == event.ToolUseID || (event.TaskID != "" && (task == event.TaskID || key == "task:"+event.TaskID)) { end(key) } } if event.ToolUseID != "" { h.taskEnded[event.ToolUseID] = true } if event.TaskID != "" { h.taskEnded[event.TaskID] = true } } case "background_tasks_changed": // The CLI's own list of every running background task (subagents' // included). A task it no longer lists has ended, whatever we missed. listed := make(map[string]bool, len(event.Tasks)) for _, task := range event.Tasks { listed[task.TaskID] = true } for key, taskID := range h.tasks { if taskID == "" && strings.HasPrefix(key, "task:") { taskID = key[len("task:"):] } if taskID != "" && !listed[taskID] { end(key) } } } if event.Type == "result" { for key := range h.taskOrigins { if _, running := h.tasks[key]; !running { delete(h.taskOrigins, key) } } } var blocks []taskBlock if json.Unmarshal(event.Message.Content, &blocks) != nil { var text string if json.Unmarshal(event.Message.Content, &text) != nil { return } blocks = []taskBlock{{Type: "text", Text: text}} } finishText := func(text string) { for _, match := range completedTaskNotice.FindAllStringSubmatch(text, -1) { end(match[1]) } } for _, block := range blocks { switch block.Type { case "tool_use": if block.ID != "" && (block.Name == "Agent" || block.Name == "Task" || block.Name == "Bash") { h.taskCalls[block.ID] = true if block.Input.Background && !h.taskEnded[block.ID] { if _, exists := h.tasks[block.ID]; !exists { h.tasks[block.ID] = "" } } origin := h.taskOrigins[block.ID] origin.ToolUseID, origin.Name = block.ID, block.Name origin.Command = taskText(block.Input.Command, 64<<10) if block.Input.Description != "" { origin.Description = taskText(block.Input.Description, 2048) } if origin.TaskType == "" { if block.Name == "Bash" { origin.TaskType = "shell" } else { origin.TaskType = "agent" } } if origin.Timestamp == "" { origin.Timestamp = event.Timestamp } h.taskOrigins[block.ID] = origin } case "tool_result": var text string if json.Unmarshal(block.Content, &text) != nil { var parts []struct { Text string `json:"text"` } _ = json.Unmarshal(block.Content, &parts) for _, part := range parts { text += part.Text + "\n" } } call := h.taskCalls[block.ToolUseID] delete(h.taskCalls, block.ToolUseID) // Only a Bash/Agent/Task call's own acknowledgement starts a // background task. Any other output (a foreground command that // prints a file quoting the acknowledgement) finishes the call. if call && LaunchedInBackground(text) { if block.ToolUseID != "" && !h.taskEnded[block.ToolUseID] { if _, exists := h.tasks[block.ToolUseID]; !exists { h.tasks[block.ToolUseID] = "" } } } else if _, running := h.tasks[block.ToolUseID]; running { end(block.ToolUseID) } else { delete(h.taskOrigins, block.ToolUseID) } // A tool's output is not a harness notification: only a text // block (below) or a structured task_notification ends a task. case "text": finishText(block.Text) } } } // maxTaskMarks bounds the bookkeeping sets; a reset only forgets marks for // calls that never received a result or tasks finished long ago. const maxTaskMarks = 8192 // LaunchedInBackground recognises Claude Code's immediate result for a tool // call that keeps running after it returns: the acknowledgement is the // result's first line, never text quoted somewhere inside other output. func LaunchedInBackground(text string) bool { first := strings.TrimSpace(text) if i := strings.IndexByte(first, '\n'); i >= 0 { first = first[:i] } return strings.Contains(first, "running in background with ID") || strings.HasPrefix(first, "Async agent launched") } var completedTaskNotice = regexp.MustCompile(`(?s).*?\s*([^<\s]+)\s*.*?`) // Native stream-json message content can be an array or a plain notification. type taskBlock struct { Type string `json:"type"` ID string `json:"id"` ToolUseID string `json:"tool_use_id"` Name string `json:"name"` Input struct { Background bool `json:"run_in_background"` Command string `json:"command"` Description string `json:"description"` } `json:"input"` Text string `json:"text"` Content json.RawMessage `json:"content"` } func taskText(s string, limit int) string { if len(s) <= limit { return s } for limit > 0 && !utf8.ValidString(s[:limit]) { limit-- } return s[:limit] }