Claude tasks: stop listing finished subagent/foreground calls as running

The host counted any tool_result containing "running in background with ID"
as a launch acknowledgement, so a subagent's foreground `sed` of
fake-claude.py (or translate.go) became a background task that never ends.
A subagent's background command whose completion notification preceded its
launch result was also revived. Both stayed "Running" in the chat for days.

- claudehost: only a Bash/Agent/Task call's own first-line acknowledgement
  starts a task; finished ids are never revived by late acks/progress;
  background_tasks_changed (the CLI's running set) ends unlisted tasks;
  tool output no longer counts as a task notification.
- claude: same strict acknowledgement; background_tasks_changed settles
  tracked tasks; on reattach, host tasks without a native id are checked
  against the main and subagent transcripts, so phantoms from hosts still
  running the old build disappear.
- Fake CLI "subagent" turn and regression tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 00:27:50 +00:00
parent accb9970b6
commit 64e51ee751
7 changed files with 449 additions and 20 deletions
+2
View File
@@ -87,6 +87,8 @@ type host struct {
// pending maps unanswered CLI control request ids to their offsets.
tasks map[string]string // running native background tools, independent of foreground busy
taskOrigins map[string]Task // native identity/metadata retained independently of spool compaction
taskCalls map[string]bool // Bash/Agent/Task tool calls still awaiting their tool_result
taskEnded map[string]bool // tool and native task ids already finished; late lines never revive them
pending map[string]int64
initID string
init json.RawMessage
+80 -17
View File
@@ -20,7 +20,10 @@ func (h *host) trackTasksLocked(line []byte) {
Description string `json:"description"`
TaskType string `json:"task_type"`
Timestamp string `json:"timestamp"`
Message struct {
Tasks []struct {
TaskID string `json:"task_id"`
} `json:"tasks"`
Message struct {
Content json.RawMessage `json:"content"`
} `json:"message"`
}
@@ -33,6 +36,29 @@ func (h *host) trackTasksLocked(line []byte) {
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
@@ -47,7 +73,7 @@ func (h *host) trackTasksLocked(line []byte) {
id = "task:" + event.TaskID
}
}
if id != "task:" {
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 {
@@ -83,10 +109,30 @@ func (h *host) trackTasksLocked(line []byte) {
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)) {
delete(h.tasks, key)
delete(h.taskOrigins, key)
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" {
@@ -107,21 +153,15 @@ func (h *host) trackTasksLocked(line []byte) {
finishText := func(text string) {
for _, match := range completedTaskNotice.FindAllStringSubmatch(text, -1) {
key := match[1]
taskID := h.tasks[key]
delete(h.tasks, key)
delete(h.taskOrigins, key)
if taskID != "" {
delete(h.tasks, "task:"+taskID)
delete(h.taskOrigins, "task:"+taskID)
}
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") {
if block.Input.Background {
h.taskCalls[block.ID] = true
if block.Input.Background && !h.taskEnded[block.ID] {
if _, exists := h.tasks[block.ID]; !exists {
h.tasks[block.ID] = ""
}
@@ -155,23 +195,46 @@ func (h *host) trackTasksLocked(line []byte) {
text += part.Text + "\n"
}
}
if strings.Contains(text, "running in background with ID") || strings.HasPrefix(strings.TrimSpace(text), "Async agent launched") {
if block.ToolUseID != "" {
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.tasks, block.ToolUseID)
delete(h.taskOrigins, block.ToolUseID)
}
finishText(text)
// 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)<task-notification>.*?<tool-use-id>\s*([^<\s]+)\s*</tool-use-id>.*?</task-notification>`)
// Native stream-json message content can be an array or a plain notification.
+42
View File
@@ -109,3 +109,45 @@ func TestDetachedBackgroundCLIIsNotReapedAsIdle(t *testing.T) {
t.Fatal("completed idle CLI was not released")
}
}
// A subagent's foreground Bash that prints source quoting the background
// acknowledgement (sed of fake-claude.py, seen live) is not a background task.
func TestForegroundOutputQuotingLaunchIsNotATask(t *testing.T) {
h := &host{}
h.trackTasksLocked([]byte(`{"type":"assistant","parent_tool_use_id":"agent","message":{"content":[{"type":"tool_use","id":"sed","name":"Bash","input":{"command":"sed -n 1,230p internal/claude/testdata/fake-claude.py"}}]}}`))
h.trackTasksLocked([]byte(`{"type":"user","parent_tool_use_id":"agent","message":{"content":[{"type":"tool_result","tool_use_id":"sed","content":"#!/usr/bin/env python3\n \"content\": \"Command running in background with ID: b1.\"\n<task-notification><tool-use-id>other</tool-use-id></task-notification>"}]}}`))
// A result for no known Bash/Agent call never starts a task either.
h.trackTasksLocked([]byte(`{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"unknown","content":"Command running in background with ID: b2."}]}}`))
if status := h.statusLocked(); len(*status.Tasks) != 0 {
t.Fatalf("foreground output registered a task: %+v", *status.Tasks)
}
}
// The CLI may report a subagent's background command complete before the
// tool_result acknowledging its launch; the late acknowledgement and progress
// must not revive it (seen live: Xvfb launched by a subagent).
func TestCompletionBeforeLaunchAcknowledgementStaysFinished(t *testing.T) {
h := &host{}
h.trackTasksLocked([]byte(`{"type":"assistant","parent_tool_use_id":"agent","message":{"content":[{"type":"tool_use","id":"xvfb","name":"Bash","input":{"command":"Xvfb :99 &","run_in_background":true}}]}}`))
h.trackTasksLocked([]byte(`{"type":"system","subtype":"task_started","task_id":"bz","tool_use_id":"xvfb","owned_by_subagent":true,"is_backgrounded":true}`))
h.trackTasksLocked([]byte(`{"type":"system","subtype":"task_notification","task_id":"bz","tool_use_id":"xvfb","status":"completed"}`))
h.trackTasksLocked([]byte(`{"type":"user","parent_tool_use_id":"agent","message":{"content":[{"type":"tool_result","tool_use_id":"xvfb","content":"Command running in background with ID: bz. Output is being written to: /tmp/bz.output"}]}}`))
h.trackTasksLocked([]byte(`{"type":"system","subtype":"task_progress","task_id":"bz","tool_use_id":"xvfb"}`))
if status := h.statusLocked(); len(*status.Tasks) != 0 {
t.Fatalf("finished task revived: %+v", *status.Tasks)
}
}
// background_tasks_changed is the CLI's full running set; a task it omits ended.
func TestBackgroundTasksChangedDropsUnlistedTasks(t *testing.T) {
h := &host{}
for _, id := range []string{"a", "b"} {
h.trackTasksLocked([]byte(`{"type":"assistant","message":{"content":[{"type":"tool_use","id":"tool-` + id + `","name":"Bash","input":{"command":"sleep 600","run_in_background":true}}]}}`))
h.trackTasksLocked([]byte(`{"type":"system","subtype":"task_started","task_id":"native-` + id + `","tool_use_id":"tool-` + id + `"}`))
}
h.trackTasksLocked([]byte(`{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"native-b","task_type":"local_bash"}]}`))
status := h.statusLocked()
if len(*status.Tasks) != 1 || (*status.Tasks)[0].ToolUseID != "tool-b" {
t.Fatalf("running set not reconciled: %+v", *status.Tasks)
}
}