Expose recorded background task timing and progress metadata
This commit is contained in:
@@ -634,6 +634,7 @@ func (c *Chat) Shells(ctx context.Context, id string) ([]protocol.ChatShell, err
|
||||
return []protocol.ChatShell{}, nil
|
||||
}
|
||||
s.awaitReady(ctx)
|
||||
s.enrichShellStarts()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
result := []protocol.ChatShell{}
|
||||
|
||||
@@ -316,11 +316,18 @@ type session struct {
|
||||
// shown once in the next turn.
|
||||
envNotices []string
|
||||
|
||||
subs map[chan protocol.ChatEventFrame]struct{}
|
||||
approvals map[string]*pendingApproval
|
||||
forms map[string]*pendingForm
|
||||
shells map[string]*shellSnapshot
|
||||
shellOrder []string
|
||||
subs map[chan protocol.ChatEventFrame]struct{}
|
||||
approvals map[string]*pendingApproval
|
||||
forms map[string]*pendingForm
|
||||
shells map[string]*shellSnapshot
|
||||
shellOrder []string
|
||||
shellMetadataMu sync.Mutex
|
||||
shellLookupAfter time.Time
|
||||
shellScanAfter time.Time
|
||||
shellTranscriptPath string
|
||||
shellTranscriptSize int64
|
||||
shellTranscriptMtime int64
|
||||
shellTranscriptTargets map[string]bool
|
||||
|
||||
usage *protocol.ChatEventFrame
|
||||
compaction *protocol.ChatEventFrame
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func applyToolMetadata(shell *protocol.ChatShell, name string, input json.RawMessage, timestamp string) {
|
||||
if shell.StartedAt == 0 {
|
||||
if stamp, ok := transcriptTime(timestamp); ok && stamp > 0 {
|
||||
shell.StartedAt = stamp
|
||||
}
|
||||
}
|
||||
if shell.TaskType == "" {
|
||||
if name == "Bash" {
|
||||
shell.TaskType = "shell"
|
||||
} else {
|
||||
shell.TaskType = "agent"
|
||||
}
|
||||
}
|
||||
var fields struct {
|
||||
Description string `json:"description"`
|
||||
}
|
||||
if json.Unmarshal(input, &fields) == nil && fields.Description != "" && shell.Description == "" {
|
||||
shell.Description = boundedText(fields.Description, 2048)
|
||||
}
|
||||
}
|
||||
|
||||
// SDK task events identify the initiating tool use, then task_id correlates
|
||||
// progress messages which omit tool_use_id. They do not all carry a timestamp.
|
||||
// Missing event times stay absent: replay wall time is not task creation time.
|
||||
func (s *session) handleTaskMetadata(raw []byte) {
|
||||
var event struct {
|
||||
TaskID string `json:"task_id"`
|
||||
ToolUseID string `json:"tool_use_id"`
|
||||
TaskType string `json:"task_type"`
|
||||
Description string `json:"description"`
|
||||
Summary string `json:"summary"`
|
||||
LastTool string `json:"last_tool_name"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Usage struct {
|
||||
DurationMS *int64 `json:"duration_ms"`
|
||||
Tools *int64 `json:"tool_uses"`
|
||||
Tokens *int64 `json:"total_tokens"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
if json.Unmarshal(raw, &event) != nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
snapshot := s.shells[event.ToolUseID]
|
||||
if snapshot == nil && event.TaskID != "" {
|
||||
for _, candidate := range s.shells {
|
||||
if candidate.taskID == event.TaskID {
|
||||
snapshot = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if snapshot == nil {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if event.TaskID != "" {
|
||||
snapshot.taskID = event.TaskID
|
||||
}
|
||||
// Out-of-order readback/progress must not replace newer recorded progress.
|
||||
if event.Usage.DurationMS != nil && snapshot.shell.DurationMS != nil && *event.Usage.DurationMS < *snapshot.shell.DurationMS {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
shell := &snapshot.shell
|
||||
if event.TaskType != "" {
|
||||
shell.TaskType = boundedText(event.TaskType, 128)
|
||||
}
|
||||
if event.Description != "" {
|
||||
shell.Description = boundedText(event.Description, 2048)
|
||||
}
|
||||
if event.Summary != "" {
|
||||
shell.Progress = boundedText(event.Summary, 2048)
|
||||
}
|
||||
if event.LastTool != "" {
|
||||
shell.LastTool = boundedText(event.LastTool, 256)
|
||||
}
|
||||
if stamp, ok := transcriptTime(event.Timestamp); ok && stamp > shell.UpdatedAt {
|
||||
shell.UpdatedAt = stamp
|
||||
}
|
||||
keepCounter := func(target **int64, value *int64) {
|
||||
if value != nil && *value >= 0 && (*target == nil || *value >= **target) {
|
||||
copy := *value
|
||||
*target = ©
|
||||
}
|
||||
}
|
||||
keepCounter(&shell.DurationMS, event.Usage.DurationMS)
|
||||
keepCounter(&shell.ToolCount, event.Usage.Tools)
|
||||
keepCounter(&shell.TokenCount, event.Usage.Tokens)
|
||||
copy := *shell
|
||||
s.mu.Unlock()
|
||||
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: ©})
|
||||
}
|
||||
|
||||
// The durable transcript records the timestamp of each initiating tool call.
|
||||
// Enrich known tasks only; historical tool calls do not establish membership.
|
||||
// The size/mtime key avoids repeatedly scanning an unchanged transcript when
|
||||
// an older task has no recorded initiating message. Reads keep the existing
|
||||
// transcript byte/line limits and never fail the primary task-list request.
|
||||
func (s *session) enrichShellStarts() {
|
||||
// A separate lock serializes optional metadata IO without holding the chat
|
||||
// state lock. The clock below schedules retries only, never a task timestamp.
|
||||
s.shellMetadataMu.Lock()
|
||||
defer s.shellMetadataMu.Unlock()
|
||||
s.mu.Lock()
|
||||
wanted := map[string]bool{}
|
||||
for id, snapshot := range s.shells {
|
||||
if snapshot.shell.Status == protocol.ChatShellRunning && snapshot.shell.StartedAt == 0 {
|
||||
wanted[id] = true
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if len(wanted) == 0 {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if now.Before(s.shellScanAfter) {
|
||||
return
|
||||
}
|
||||
s.shellScanAfter = now.Add(5 * time.Second)
|
||||
path := s.shellTranscriptPath
|
||||
if path == "" {
|
||||
if now.Before(s.shellLookupAfter) {
|
||||
return
|
||||
}
|
||||
s.shellLookupAfter = now.Add(30 * time.Second)
|
||||
path = findTranscriptFile(s.id)
|
||||
if path == "" {
|
||||
return
|
||||
}
|
||||
s.shellTranscriptPath = path
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
if !now.Before(s.shellLookupAfter) {
|
||||
s.shellTranscriptPath = ""
|
||||
}
|
||||
return
|
||||
}
|
||||
covered := true
|
||||
for id := range wanted {
|
||||
if !s.shellTranscriptTargets[id] {
|
||||
covered = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if covered && s.shellTranscriptSize == info.Size() && s.shellTranscriptMtime == info.ModTime().UnixNano() {
|
||||
return
|
||||
}
|
||||
// Cache failures too: an oversized/malformed unchanged file is not scanned
|
||||
// again on every list refresh. A changed file gets another bounded attempt.
|
||||
s.shellTranscriptSize, s.shellTranscriptMtime = info.Size(), info.ModTime().UnixNano()
|
||||
s.shellTranscriptTargets = wanted
|
||||
if info.Size() > maxTranscriptBytes {
|
||||
return
|
||||
}
|
||||
records, err := readShellStartRecords(path, wanted)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for id, record := range records {
|
||||
if snapshot := s.shells[id]; snapshot != nil {
|
||||
applyToolMetadata(&snapshot.shell, record.name, record.input, record.timestamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type shellStartRecord struct {
|
||||
name string
|
||||
input json.RawMessage
|
||||
timestamp string
|
||||
}
|
||||
|
||||
// Retain only the targeted tool-call metadata, not an entire conversation.
|
||||
func readShellStartRecords(path string, wanted map[string]bool) (map[string]shellStartRecord, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
bounded := &io.LimitedReader{R: file, N: maxTranscriptBytes + 1}
|
||||
scanner := bufio.NewScanner(bounded)
|
||||
scanner.Buffer(make([]byte, 0, 64<<10), maxLineBytes)
|
||||
records := map[string]shellStartRecord{}
|
||||
for scanner.Scan() {
|
||||
var entry transcriptEntry
|
||||
if json.Unmarshal(scanner.Bytes(), &entry) != nil || entry.Type != "assistant" || entry.IsSidechain {
|
||||
continue
|
||||
}
|
||||
for _, block := range decodeBlocks(entry.Message.Content) {
|
||||
if block.Type != "tool_use" || !wanted[block.ID] {
|
||||
continue
|
||||
}
|
||||
if _, seen := records[block.ID]; seen {
|
||||
continue
|
||||
}
|
||||
if stamp, ok := transcriptTime(entry.Timestamp); !ok || stamp <= 0 {
|
||||
continue
|
||||
}
|
||||
records[block.ID] = shellStartRecord{name: block.Name, input: truncateJSON(block.Input, 64<<10), timestamp: entry.Timestamp}
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bounded.N <= 0 {
|
||||
return nil, errors.New("Claude task transcript exceeded read limit")
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestTaskProgressPreservesRecordedMetadataAndExit(t *testing.T) {
|
||||
chat, s := backgroundSession(t)
|
||||
source := toolUse(t, "toolu_meta", "Agent", map[string]any{"description": "Review release", "run_in_background": true})
|
||||
var start map[string]any
|
||||
json.Unmarshal(source, &start)
|
||||
start["timestamp"] = "2026-11-05T09:18:00Z"
|
||||
s.handleLine(nil, line(t, start))
|
||||
s.handleLine(nil, line(t, map[string]any{"type": "system", "subtype": "task_started", "task_id": "task-meta", "tool_use_id": "toolu_meta", "task_type": "local_agent", "description": "Review release"}))
|
||||
progress := map[string]any{"type": "system", "subtype": "task_progress", "task_id": "task-meta", "description": "Reviewing changes", "summary": "Checking focused tests", "last_tool_name": "Bash", "timestamp": "2026-11-05T09:20:00Z", "usage": map[string]any{"duration_ms": 120000, "tool_uses": 4, "total_tokens": 1500}}
|
||||
s.handleLine(nil, line(t, progress))
|
||||
tasks := running(t, chat)
|
||||
if len(tasks) != 1 {
|
||||
t.Fatalf("tasks=%+v", tasks)
|
||||
}
|
||||
task := tasks[0]
|
||||
if task.StartedAt != 1793870280000 || task.UpdatedAt != 1793870400000 || task.TaskType != "local_agent" || task.Description != "Reviewing changes" || task.Progress != "Checking focused tests" || task.LastTool != "Bash" || *task.ToolCount != 4 || *task.TokenCount != 1500 || *task.DurationMS != 120000 {
|
||||
t.Fatalf("metadata=%+v", task)
|
||||
}
|
||||
// A duplicate initiating message must not reset the progress snapshot.
|
||||
s.handleLine(nil, line(t, start))
|
||||
progress["usage"] = map[string]any{"duration_ms": 1000, "tool_uses": 1, "total_tokens": 1}
|
||||
progress["summary"] = "stale"
|
||||
s.handleLine(nil, line(t, progress))
|
||||
task = running(t, chat)[0]
|
||||
if task.StartedAt != 1793870280000 || task.Progress != "Checking focused tests" || *task.ToolCount != 4 || task.TaskType != "local_agent" || task.Description != "Reviewing changes" {
|
||||
t.Fatalf("regressed metadata=%+v", task)
|
||||
}
|
||||
s.handleLine(nil, line(t, map[string]any{"type": "system", "subtype": "task_notification", "tool_use_id": "toolu_meta", "status": "completed", "summary": "Review complete", "usage": map[string]any{"duration_ms": 180000, "tool_uses": 5, "total_tokens": 2000}}))
|
||||
if len(running(t, chat)) != 0 {
|
||||
t.Fatal("task did not exit")
|
||||
}
|
||||
s.mu.Lock()
|
||||
ended := s.shells["toolu_meta"].shell
|
||||
s.mu.Unlock()
|
||||
if ended.Status != protocol.ChatShellExited || ended.StartedAt != task.StartedAt || *ended.DurationMS != 180000 || ended.Progress != "Review complete" {
|
||||
t.Fatalf("ended=%+v", ended)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskStartRecoveredFromTranscriptAcrossReplay(t *testing.T) {
|
||||
config := t.TempDir()
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", config)
|
||||
dir := filepath.Join(config, "projects", "fixture")
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := toolUse(t, "toolu_replay", "Bash", map[string]any{"command": "sleep 30", "run_in_background": true})
|
||||
var entry map[string]any
|
||||
json.Unmarshal(source, &entry)
|
||||
entry["timestamp"] = "2026-11-05T09:18:00Z"
|
||||
raw := line(t, entry)
|
||||
if err := os.WriteFile(filepath.Join(dir, "ses_bg.jsonl"), append(raw, '\n'), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 2 {
|
||||
chat, s := backgroundSession(t)
|
||||
s.silent = true // Reattached hosts reconstruct from the same original lines.
|
||||
s.handleLine(nil, source) // CLI stream itself has no timestamp.
|
||||
task := running(t, chat)[0]
|
||||
if task.StartedAt != 1793870280000 || task.TaskType != "shell" {
|
||||
t.Fatalf("transcript start=%+v", task)
|
||||
}
|
||||
again := running(t, chat)[0]
|
||||
if task.StartedAt != again.StartedAt {
|
||||
t.Fatal("read reset start")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingTaskTimingAndInvalidCountersStayUnknown(t *testing.T) {
|
||||
chat, s := backgroundSession(t)
|
||||
s.handleLine(nil, toolUse(t, "toolu_unknown", "Agent", map[string]any{"description": "Unknown timing"}))
|
||||
s.handleLine(nil, line(t, map[string]any{"type": "system", "subtype": "task_progress", "tool_use_id": "toolu_unknown", "timestamp": "invalid", "summary": strings.Repeat("p", 4000), "usage": map[string]any{"duration_ms": -1, "tool_uses": -2, "total_tokens": -3}}))
|
||||
task := running(t, chat)[0]
|
||||
if task.StartedAt != 0 || task.UpdatedAt != 0 || task.DurationMS != nil || task.ToolCount != nil || task.TokenCount != nil || len(task.Progress) > 2100 {
|
||||
t.Fatalf("invented/unbounded metadata=%+v", task)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionalTranscriptLookupBacksOffAndCachesOversizedFiles(t *testing.T) {
|
||||
config := t.TempDir()
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", config)
|
||||
chat, s := backgroundSession(t)
|
||||
s.handleLine(nil, toolUse(t, "toolu_cache", "Bash", map[string]any{"command": "sleep 30", "run_in_background": true}))
|
||||
if task := running(t, chat)[0]; task.StartedAt != 0 {
|
||||
t.Fatal("invented missing transcript time")
|
||||
}
|
||||
if s.shellLookupAfter.IsZero() || s.shellScanAfter.IsZero() {
|
||||
t.Fatal("missing lookup has no retry backoff")
|
||||
}
|
||||
dir := filepath.Join(config, "projects", "fixture")
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "ses_bg.jsonl")
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = f.Truncate(maxTranscriptBytes + 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
s.shellLookupAfter = time.Time{}
|
||||
s.shellScanAfter = time.Time{}
|
||||
running(t, chat)
|
||||
if s.shellTranscriptSize != maxTranscriptBytes+1 || s.shellTranscriptMtime == 0 {
|
||||
t.Fatal("oversized read did not cache fingerprint")
|
||||
}
|
||||
// A repaired/changed source is read on the next retry; a prior failure is
|
||||
// neither a fabricated start nor a permanent inability to enrich the task.
|
||||
raw := toolUse(t, "toolu_cache", "Bash", map[string]any{"command": "sleep 30"})
|
||||
var entry map[string]any
|
||||
json.Unmarshal(raw, &entry)
|
||||
entry["timestamp"] = "2026-11-05T09:18:00Z"
|
||||
if err := os.WriteFile(path, append(line(t, entry), '\n'), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.shellScanAfter = time.Time{}
|
||||
if task := running(t, chat)[0]; task.StartedAt != 1793870280000 {
|
||||
t.Fatalf("repaired source not read: %+v", task)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
// ---- CLI line envelope -----------------------------------------------------
|
||||
|
||||
type lineEnvelope struct {
|
||||
Timestamp string `json:"timestamp"`
|
||||
Type string `json:"type"`
|
||||
Subtype string `json:"subtype"`
|
||||
UUID string `json:"uuid"`
|
||||
@@ -120,6 +121,10 @@ func (s *session) handleLine(p *process, line []byte) {
|
||||
case "rate_limit_event":
|
||||
s.handleRateLimit(envelope.RateLimitInfo)
|
||||
case "system":
|
||||
if envelope.Subtype == "task_started" || envelope.Subtype == "task_progress" {
|
||||
s.handleTaskMetadata(line)
|
||||
return
|
||||
}
|
||||
if envelope.Subtype == "task_notification" {
|
||||
s.finishNotifiedTask(line)
|
||||
return
|
||||
@@ -464,6 +469,10 @@ func (s *session) handleAssistant(envelope lineEnvelope) {
|
||||
}
|
||||
}
|
||||
if shell != nil {
|
||||
snapshot := s.shells[block.ID]
|
||||
applyToolMetadata(&snapshot.shell, block.Name, input, envelope.Timestamp)
|
||||
copy := snapshot.shell
|
||||
shell = ©
|
||||
frames = append(frames, protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: shell})
|
||||
}
|
||||
}
|
||||
@@ -556,7 +565,8 @@ func (s *session) handleUser(envelope lineEnvelope) {
|
||||
snapshot.output = snapshot.output[:commandOutputCap]
|
||||
}
|
||||
}
|
||||
frame = &protocol.ChatShell{ID: snapshot.shell.ID, Status: snapshot.shell.Status, Command: snapshot.shell.Command, Exit: snapshot.shell.Exit}
|
||||
copy := snapshot.shell
|
||||
frame = ©
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if frame != nil {
|
||||
@@ -738,6 +748,7 @@ type shellSnapshot struct {
|
||||
// background marks a command or subagent that may outlive its tool call:
|
||||
// its immediate result only says it started.
|
||||
background bool
|
||||
taskID string
|
||||
}
|
||||
|
||||
// backgroundRequested reports a Bash call asked to run in the background.
|
||||
@@ -782,6 +793,7 @@ var (
|
||||
// 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) {
|
||||
s.handleTaskMetadata(line)
|
||||
var notice struct {
|
||||
ToolUseID string `json:"tool_use_id"`
|
||||
Status string `json:"status"`
|
||||
@@ -807,7 +819,8 @@ func (s *session) endShellsLocked() []*protocol.ChatShell {
|
||||
continue
|
||||
}
|
||||
snapshot.shell.Status = protocol.ChatShellExited
|
||||
ended = append(ended, &protocol.ChatShell{ID: snapshot.shell.ID, Status: snapshot.shell.Status, Command: snapshot.shell.Command})
|
||||
copy := snapshot.shell
|
||||
ended = append(ended, ©)
|
||||
}
|
||||
sort.Slice(ended, func(i, j int) bool { return ended[i].ID < ended[j].ID })
|
||||
return ended
|
||||
@@ -840,7 +853,8 @@ func (s *session) finishBackgroundTasks(text string) {
|
||||
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})
|
||||
copy := snapshot.shell
|
||||
frames = append(frames, ©)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, frame := range frames {
|
||||
@@ -859,6 +873,13 @@ func (s *session) recordShellLocked(toolID, command string) *protocol.ChatShell
|
||||
if toolID == "" {
|
||||
return nil
|
||||
}
|
||||
if prior := s.shells[toolID]; prior != nil {
|
||||
if command != "" {
|
||||
prior.shell.Command = command
|
||||
}
|
||||
copy := prior.shell
|
||||
return ©
|
||||
}
|
||||
id := shellID(toolID)
|
||||
s.shellOrder = append(s.shellOrder, id)
|
||||
shell := protocol.ChatShell{ID: id, Status: protocol.ChatShellRunning, Command: command}
|
||||
|
||||
Reference in New Issue
Block a user