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
+136
View File
@@ -1,8 +1,14 @@
package claude
import (
"bufio"
"bytes"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"git.a-wan.net/alan/pipelines/internal/claudehost"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -14,10 +20,14 @@ func (s *session) reconcileHostTasks(tasks *[]claudehost.Task) {
if tasks == nil {
return
}
finished := s.finishedHostTasks(*tasks)
s.mu.Lock()
present := make(map[string]bool, len(*tasks))
var frames []protocol.ChatShell
for _, task := range *tasks {
if finished[task.ToolUseID] {
continue
}
id := task.ToolUseID
if id == "" && task.TaskID != "" {
id = "task:" + task.TaskID
@@ -109,3 +119,129 @@ func (s *session) resolveHostedTaskLine(line []byte) []byte {
}
return normalized
}
// finishedHostTasks checks host-reported tasks the CLI never identified (no
// native task id) against the session's transcripts, the main one and every
// subagent's. Hosts built before launch detection was strict count a
// foreground Bash whose output merely quotes "running in background with ID"
// (a subagent reading fake-claude.py, say) as a background task, and keep a
// subagent's background command whose completion preceded its launch result;
// neither ever ends. A tool call whose result is not a launch acknowledgement,
// or whose completion notification is recorded, is finished.
func (s *session) finishedHostTasks(tasks []claudehost.Task) map[string]bool {
wanted := map[string]bool{}
for _, task := range tasks {
if task.TaskID == "" && task.ToolUseID != "" {
wanted[task.ToolUseID] = true
}
}
if len(wanted) == 0 {
return nil
}
path := findTranscriptFile(s.id)
if path == "" {
return nil
}
files := []string{path}
if agents, err := filepath.Glob(filepath.Join(strings.TrimSuffix(path, ".jsonl"), "subagents", "*.jsonl")); err == nil {
files = append(files, agents...)
}
finished := map[string]bool{}
for _, file := range files {
scanFinishedToolCalls(file, wanted, finished)
if len(finished) == len(wanted) {
break
}
}
return finished
}
// scanFinishedToolCalls reads the newest maxTranscriptBytes of one transcript
// and marks each wanted tool call that finished there. Errors only end the scan.
func scanFinishedToolCalls(path string, wanted, finished map[string]bool) {
file, err := os.Open(path)
if err != nil {
return
}
defer file.Close()
partial := false
if info, err := file.Stat(); err == nil && info.Size() > maxTranscriptBytes {
if _, err := file.Seek(info.Size()-maxTranscriptBytes, io.SeekStart); err != nil {
return
}
partial = true
}
scanner := bufio.NewScanner(&io.LimitedReader{R: file, N: maxTranscriptBytes})
scanner.Buffer(make([]byte, 0, 64<<10), maxLineBytes)
resultMarker := []byte(`"tool_result"`)
noticeMarker := []byte("<task-notification>")
for scanner.Scan() {
line := scanner.Bytes()
if partial {
partial = false // the first line read from mid-file is a fragment
continue
}
if bytes.Contains(line, resultMarker) {
var entry transcriptEntry
parsed := false
for id := range wanted {
if finished[id] || !bytes.Contains(line, []byte(id)) {
continue
}
if !parsed {
if json.Unmarshal(line, &entry) != nil {
break
}
parsed = true
}
for _, block := range decodeBlocks(entry.Message.Content) {
if block.Type != "tool_result" || block.ToolUseID != id {
continue
}
if text, _ := toolResultContent(block.Content); !launchedInBackground(text) {
finished[id] = true
}
}
}
continue
}
if bytes.Contains(line, noticeMarker) {
for id := range wanted {
if !finished[id] && bytes.Contains(line, []byte("<tool-use-id>"+id+"</tool-use-id>")) {
finished[id] = true
}
}
}
}
}
// settleUnlistedTasks applies the CLI's background_tasks_changed event: the
// complete set of background tasks still running, subagents' included. A
// tracked task with a native id the CLI no longer lists has ended.
func (s *session) settleUnlistedTasks(line []byte) {
var event struct {
Tasks []struct {
TaskID string `json:"task_id"`
} `json:"tasks"`
}
if json.Unmarshal(line, &event) != nil {
return
}
listed := make(map[string]bool, len(event.Tasks))
for _, task := range event.Tasks {
listed[task.TaskID] = true
}
var frames []protocol.ChatShell
s.mu.Lock()
for _, snapshot := range s.shells {
if snapshot.taskID == "" || listed[snapshot.taskID] || snapshot.shell.Status != protocol.ChatShellRunning {
continue
}
snapshot.shell.Status = protocol.ChatShellExited
frames = append(frames, snapshot.shell)
}
s.mu.Unlock()
for i := range frames {
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: &frames[i]})
}
}
+124
View File
@@ -0,0 +1,124 @@
package claude
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/claudehost"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Seen live: a subagent's foreground `sed -n 1,230p fake-claude.py` printed
// the fixture's "Command running in background with ID" line, so the host
// listed it as a background task forever ("Running 1d 20h, no output yet").
// The fake CLI streams a background subagent whose own calls (that sed, and a
// background command completed before its launch result) are sidechain lines.
func TestSubagentToolCallsAreNotOperatorBackgroundTasks(t *testing.T) {
fixture := hostedSetup(t)
first := hostedChat(t)
session := newCreatedChat(t, first)
frames := subscribe(t, first, session.ID)
if err := first.Prompt(context.Background(), session.ID, "subagent please"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
onlyAgent := func(shells []protocol.ChatShell, err error) bool {
return err == nil && len(shells) == 1 && shells[0].ID == shellID("toolu_agent_fake")
}
if shells, err := first.Shells(context.Background(), session.ID); !onlyAgent(shells, err) {
t.Fatalf("the background agent alone is running: %+v %v", shells, err)
}
record := onlyRecord(t, fixture)
first.Detach()
control, status, err := claudehost.Attach(record.Socket, 0, hostAttachTimeout)
if err != nil {
t.Fatal(err)
}
_ = control.Close()
if status.Tasks == nil || len(*status.Tasks) != 1 || (*status.Tasks)[0].ToolUseID != "toolu_agent_fake" {
t.Fatalf("host lists subagent tool calls as running tasks: %+v", status.Tasks)
}
second := hostedChat(t)
if shells, err := second.Shells(context.Background(), session.ID); !onlyAgent(shells, err) {
t.Fatalf("reattached task list changed: %+v %v", shells, err)
}
frames = subscribe(t, second, session.ID)
if err := second.Prompt(context.Background(), session.ID, "agent-done"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
if shells, err := second.Shells(context.Background(), session.ID); err != nil || len(shells) != 0 {
t.Fatalf("finished agent still listed: %+v %v", shells, err)
}
}
// Hosts already running an older build keep phantom entries (no native task
// id). Reattaching settles each from the transcripts — the main one and the
// subagents' — while a genuine background command still shows until it ends.
func TestReattachSettlesLegacyPhantomTasksFromTranscripts(t *testing.T) {
config := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", config)
chat, s := backgroundSession(t)
t.Cleanup(chat.Close)
project := filepath.Join(config, "projects", "-repo")
write := func(path string, lines ...string) {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
t.Fatal(err)
}
}
write(filepath.Join(project, s.id+".jsonl"),
`{"type":"assistant","isSidechain":false,"message":{"content":[{"type":"tool_use","id":"main-bg","name":"Bash","input":{"command":"sleep 600","run_in_background":true}}]}}`,
`{"type":"user","isSidechain":false,"message":{"content":[{"type":"tool_result","tool_use_id":"main-bg","content":"Command running in background with ID: b9. Output is being written to: /tmp/b9.output"}]}}`,
`{"type":"assistant","isSidechain":false,"message":{"content":[{"type":"tool_use","id":"main-cat","name":"Bash","input":{"command":"cat translate.go"}}]}}`,
`{"type":"user","isSidechain":false,"message":{"content":[{"type":"tool_result","tool_use_id":"main-cat","content":[{"type":"text","text":"func launched() {\n\treturn \"running in background with ID\"\n}"}]}]}}`,
)
write(filepath.Join(project, s.id, "subagents", "agent-a1.jsonl"),
`{"type":"assistant","isSidechain":true,"message":{"content":[{"type":"tool_use","id":"sub-sed","name":"Bash","input":{"command":"sed -n 1,230p internal/claude/testdata/fake-claude.py"}}]}}`,
`{"type":"user","isSidechain":true,"message":{"content":[{"type":"tool_result","tool_use_id":"sub-sed","content":"#!/usr/bin/env python3\n\"content\": \"Command running in background with ID: b1.\""}]}}`,
`{"type":"user","isSidechain":true,"message":{"content":[{"type":"tool_result","tool_use_id":"sub-xvfb","content":"Command running in background with ID: bz. Output is being written to: /tmp/bz.output"}]}}`,
`{"type":"attachment","isSidechain":true,"attachment":{"type":"queued_command","prompt":"<task-notification>\n<task-id>bz</task-id>\n<tool-use-id>sub-xvfb</tool-use-id>\n<status>completed</status>\n</task-notification>"}}`,
)
legacy := []claudehost.Task{
{ToolUseID: "main-bg", Name: "Bash", Command: "sleep 600"},
{ToolUseID: "main-cat", Name: "Bash", Command: "cat translate.go"},
{ToolUseID: "sub-sed", Name: "Bash", Command: "sed -n 1,230p internal/claude/testdata/fake-claude.py"},
{ToolUseID: "sub-xvfb", Name: "Bash", Command: "Xvfb :99 &"},
}
s.reconcileHostTasks(&legacy)
shells := running(t, chat)
if len(shells) != 1 || shells[0].ID != shellID("main-bg") {
t.Fatalf("only the genuine background command is running: %+v", shells)
}
}
func TestBackgroundTasksChangedSettlesUnlistedTasks(t *testing.T) {
chat, s := backgroundSession(t)
t.Cleanup(chat.Close)
for _, id := range []string{"a", "b"} {
s.handleLine(nil, toolUse(t, "tool-"+id, "Bash", map[string]any{"command": "sleep 600", "run_in_background": true}))
s.handleLine(nil, []byte(`{"type":"system","subtype":"task_started","task_id":"native-`+id+`","tool_use_id":"tool-`+id+`"}`))
s.handleLine(nil, toolResult(t, "tool-"+id, "Command running in background with ID: native-"+id))
}
s.handleLine(nil, []byte(`{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"native-b"}]}`))
if shells := running(t, chat); len(shells) != 1 || shells[0].ID != shellID("tool-b") {
t.Fatalf("unlisted task still running: %+v", shells)
}
}
// A foreground subagent's report (its tool_result) may quote a launch
// acknowledgement; only the result's first line acknowledges a launch.
func TestForegroundAgentReportQuotingLaunchFinishes(t *testing.T) {
chat, s := backgroundSession(t)
t.Cleanup(chat.Close)
s.handleLine(nil, toolUse(t, "sync-agent", "Agent", map[string]any{"description": "Review"}))
s.handleLine(nil, toolResult(t, "sync-agent", "Root cause: the host matched\n\"Command running in background with ID\" anywhere in output."))
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("finished foreground agent still running: %+v", shells)
}
}
+58
View File
@@ -76,6 +76,13 @@ def user_message(text):
if "gate" in text:
gated(message_id)
return
if "subagent" in text:
subagent(message_id)
return
if "agent-done" in text:
send({"type": "system", "subtype": "task_notification", "task_id": "afake",
"tool_use_id": "toolu_agent_fake", "status": "completed", "summary": "Agent finished"})
send({"type": "system", "subtype": "background_tasks_changed", "tasks": []})
if "background" in text:
background(message_id)
return
@@ -191,6 +198,57 @@ def background(message_id):
finish(message_id)
def subagent(message_id):
"""Launches a background subagent whose own tool calls stream as a sidechain
(parent_tool_use_id), as Claude Code 2.1 sends them: a foreground Bash whose
output quotes a background acknowledgement mid-text, and a background Bash
the CLI reports complete before the tool_result acknowledging its launch.
Neither is the operator's background task; only the agent is, until a later
"agent-done" turn ends it."""
agent = "toolu_agent_fake"
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test", "content": [
{"type": "tool_use", "id": agent, "name": "Agent",
"input": {"description": "Investigate", "prompt": "look", "run_in_background": True}}]}})
send({"type": "system", "subtype": "task_started", "task_id": "afake", "tool_use_id": agent,
"description": "Investigate", "task_type": "local_agent", "is_backgrounded": True})
send({"type": "user", "message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": agent, "content": "Async agent launched successfully.\nagentId: afake"}]}})
send({"type": "system", "subtype": "background_tasks_changed",
"tasks": [{"task_id": "afake", "task_type": "local_agent"}]})
sidechain = []
sed = "toolu_sub_sed"
sidechain.append({"type": "assistant", "message": {"id": "msg_sub_1", "role": "assistant", "model": "claude-test", "content": [
{"type": "tool_use", "id": sed, "name": "Bash", "input": {"command": "sed -n 1,230p internal/claude/testdata/fake-claude.py"}}]}})
sidechain.append({"type": "user", "message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": sed, "content":
"#!/usr/bin/env python3\n block = {\"content\": \"Command running in background with ID: b1. Output is being written to: /tmp/b1.output\"}\n"}]}})
xvfb = "toolu_sub_xvfb"
sidechain.append({"type": "assistant", "message": {"id": "msg_sub_2", "role": "assistant", "model": "claude-test", "content": [
{"type": "tool_use", "id": xvfb, "name": "Bash", "input": {"command": "Xvfb :99 &", "run_in_background": True}}]}})
for entry in sidechain:
send(dict(entry, parent_tool_use_id=agent))
send({"type": "system", "subtype": "task_started", "task_id": "bz", "tool_use_id": xvfb,
"owned_by_subagent": True, "is_backgrounded": True, "task_type": "local_bash"})
send({"type": "system", "subtype": "background_tasks_changed",
"tasks": [{"task_id": "afake", "task_type": "local_agent"}, {"task_id": "bz", "task_type": "local_bash"}]})
send({"type": "system", "subtype": "task_notification", "task_id": "bz", "tool_use_id": xvfb,
"owned_by_subagent": True, "status": "completed", "summary": "Background command completed"})
send({"type": "system", "subtype": "background_tasks_changed",
"tasks": [{"task_id": "afake", "task_type": "local_agent"}]})
ack = {"type": "user", "message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": xvfb, "content": "Command running in background with ID: bz. Output is being written to: /tmp/bz.output"}]}}
sidechain.append(ack)
send(dict(ack, parent_tool_use_id=agent))
send({"type": "system", "subtype": "task_progress", "task_id": "bz", "tool_use_id": xvfb})
# The CLI keeps each subagent's transcript beside the session's.
directory = os.path.join(transcript_path()[:-len(".jsonl")], "subagents")
os.makedirs(directory, exist_ok=True)
with open(os.path.join(directory, "agent-afake.jsonl"), "a", encoding="utf-8") as file:
for entry in sidechain:
file.write(json.dumps(dict(entry, isSidechain=True, agentId="afake", timestamp=stamp())) + "\n")
finish(message_id)
def refused(message_id):
"""A turn refused for a usage limit, as Claude Code 2.1 ends one: a rejected
rate_limit_event, a synthetic assistant API-error message and an is_error
+7 -3
View File
@@ -138,6 +138,10 @@ func (s *session) handleLine(p *process, line []byte) {
s.finishNotifiedTask(line)
return
}
if envelope.Subtype == "background_tasks_changed" {
s.settleUnlistedTasks(line)
return
}
s.handleSystem(envelope)
}
}
@@ -832,10 +836,10 @@ func agentLabel(input json.RawMessage) string {
}
// launchedInBackground recognises Claude Code's immediate result for a task
// that keeps running after its tool call returns.
// that keeps running after its tool call returns (its first line only: a
// foreground result may quote the acknowledgement anywhere).
func launchedInBackground(text string) bool {
return strings.Contains(text, "running in background with ID") ||
strings.HasPrefix(strings.TrimSpace(text), "Async agent launched")
return claudehost.LaunchedInBackground(text)
}
var (
+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)
}
}