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:
@@ -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]})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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 (
|
||||
|
||||
Reference in New Issue
Block a user