diff --git a/docs/cli/run.md b/docs/cli/run.md index 2129095362..f24422d02a 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -111,6 +111,12 @@ cases fail earlier: See [pi § Per-persona model configuration](../runtimes/pi.md#per-persona-model-configuration). +## Live progress + +Progress display depends on the selected runtime. See +[Claude Workflow progress](../runtimes/claude.md#live-claude-workflow-progress) +for Claude background tasks, agent lifecycle metadata and display limits. + ## Output artifacts Each run produces artifacts in the output directory. Relative `--output-dir` diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index 27e43cdd91..a8c60eb31d 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -10,6 +10,12 @@ fullsend run triage --model opus --effort high Choosing between runtimes is in [Agent runtimes](../runtimes.md). Selection, precedence and the config keys live there too. +Background Workflow phase/agent changes and runtime lifecycle/status notices +are displayed from Claude's structured event stream. See +[live Workflow progress](#live-claude-workflow-progress) +for the display behavior and its limits; it does not include full nested tool +stdout/stderr. + ## Models Pass an alias or a model id. fullsend resolves `opus`, `sonnet` and `haiku` itself and passes the @@ -324,6 +330,110 @@ These are the places Claude Code differs from pi — useful when comparing a run hook wiring is passed explicitly with `--settings` so it loads regardless, but repo-supplied hooks are a separate exposure to be aware of. +## Live Claude Workflow progress + +When Claude Code emits background task and Workflow progress, `fullsend run` +prints task identity, agent labels, attributed phases, state changes, and +available tool names/context. For example: + +```console + ⚙ Task wf-example / agent #1 (reader) [Read]: read input — running (attempt 1) + ⚙ Task wf-example / agent #1 (reader) [Read]: read input — completed (attempt 1) + ⚙ Task wf-example / agent #2 (creator) [Create]: strategy-create — running (tool: Bash: python3 create.py) (attempt 1) +``` + +Unchanged snapshots and counter-only updates do not repeat the same display +line. Text is sanitized, credential-redacted, and bounded before display or +retention in the bounded display cache. Progress text uses Unicode cleanup: +bidirectional overrides, invisible format characters and Unicode tags are +removed, and compatibility characters are normalized. The CLI applies the +same cleanup to credential literals before matching. +A dedicated reconciler owns lifecycle and deduplication; the renderer prints +its safe messages. Parser/`OnEvent` callbacks and captured stream bytes keep +their original snapshot content. + +Concurrent tasks and agents retain +separate identities. Task tool/status fields retain omitted values; +explicit empty strings clear them. Pausing hides the last summary until the +task resumes; a terminal state or new run clears it. Partial lifecycle +patches retain known task labels and state; explicit starts can reset an +identity. Late running snapshots do not reopen known terminal tasks or +agents. Sparse agent snapshots retain known +labels, phases and tool context. Error, blocked and cached metadata persists +within a state; state changes clear omitted transient metadata. Explicit +empty strings and false flags also clear their corresponding fields. + +Task visibility, terminal state and run watermarks are retained separately +from agent display rows. New runs and terminal task states retire old agent +rows. Tracking admits up to 1,024 task identities and 1,024 agents per task, +with a shared 16,384-row threshold for admitting new agent rows. At a limit, +new identities or agent rows are suppressed; tracked rows and task guards +remain. +Agent-row capacity becomes available when tasks finish or open new runs. +Task-identity slots stay reserved for the renderer's lifetime. + +Run IDs follow the Agent SDK opening order; late frames from superseded +runs are ignored, so they cannot steal later updates without a run ID. +Visibility belongs to each run: promoting its first late run ID preserves +its hidden classification, while a distinct named run does not inherit an +older run's visibility. Hook names and event attribution survive sparse +progress/completion messages for the same hook ID. + +Workflow agent wire states are only `start`, `progress`, `done` and `error`. +A `start` record with `queuedAt` and no `startedAt` is queued; a record with +`startedAt` is executing. Started agents display their one-based `attempt` +when supplied. A retry start has an `attempt` greater than one; its display +includes `attempt` and the supplied `lastAttemptReason` +(`stalled`, `throttled` or `user-retry`). Later progress is running, with the +attempt retained, and each new attempt is visible even when its label and +tool are unchanged. `error` plus `skipped: true` is skipped, not failed. +Older records without timing metadata retain the best-effort running display. +These derived statuses do not assume extra values in the agent wire enum. + +The display handles these structured Claude events when the runtime emits +them. Task progress shapes were checked against Claude Code 2.1.296 capture +and the embedded 2.1.312 emitter/schema; this is version-bound compatibility, +not a promise of a stable public protocol. In particular, `workflow_progress` +(including `workflow_agent` metadata) and `system/task_summary` are +**undocumented internal Claude Code extensions**, not public Agent SDK +contracts in the inspected version. They may change or disappear without +notice in any Claude patch release. Support is best-effort; unsupported +shapes are ignored for display and raw events remain available for diagnosis. +A newly recorded live 2.1.312 Workflow stream has not been qualified here. + +Workflow agents use their positive index as stable identity within a task/run. +A late `agentId` is retained as display attribution, and learning it alone +does not add another progress line. If the index is absent, the agent ID is +the identity fallback. + +| Event | Console behavior | +| --- | --- | +| `task_started` | Task identity and description; ambient/hidden starts suppress subsequent progress while tracked. | +| `task_progress` | Task description, last tool and progress summary; best-effort decoding of the undocumented internal `workflow_progress` agent metadata. | +| `task_updated` | Pending, running, paused, completed, failed and killed states; description-only patches and bounded errors. | +| `task_notification` | Completion, failure or stop, including a worker-restart cause when supplied; full result summary excluded. | +| `task_summary` | Undocumented internal mid-turn summary; best-effort display, with null/empty values clearing deduplication silently. | +| `background_tasks_changed` | Count of reported non-ambient background tasks; membership is not execution or completion evidence. | +| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. Fullsend launches Claude without `--include-hook-events`, and the inspected Claude 2.1.312 producer emits only SessionStart and Setup hook events in that mode, so those are the only hook rows real runs produce; the decoder still renders other hook events if a future launch enables them. | +| `permission_denied` | Tool/agent identity and bounded decision reason; tool-result body excluded. | +| `status`, `session_state_changed` | Compaction, session state and action-required transitions; per-request status chatter excluded. | +| `informational`, `notification` | Salient notices, suggestions, warnings and text notifications; unkeyed occurrences repeat, transcript-only info excluded. | +| `rate_limit_event` | Warnings, rejection, supplied reset time and subsequent recovery; routine initial allowed status suppressed. | + +Declared `workflow_phase` records do not prove live advancement and are not +rendered as phase starts. Internal `workflow_log` entries are filtered out +of SDK progress by the inspected Claude 2.1.312 producer; Fullsend cannot +display records absent from its input stream. This is not a stream of full +nested tool stdout/stderr, prompts, result bodies or hook output. Unknown +message kinds/states and malformed records are ignored for display; raw +events remain in `output.jsonl` for diagnosis and future compatibility work. + +Task completion and session idle are distinct from the run's validated +business result. Progress counters do not add to token/cost totals. The +periodic `Agent running (...)` heartbeat still reports elapsed time rather +than proving progress. The display is advisory, not a durable task registry; +very large sessions can evict cached identity and deduplication state. + ## Troubleshooting **The model is not what you asked for.** Check `metrics.json`: `requested_model` is what was handed diff --git a/internal/cli/progress_redaction_test.go b/internal/cli/progress_redaction_test.go new file mode 100644 index 0000000000..e7de43e623 --- /dev/null +++ b/internal/cli/progress_redaction_test.go @@ -0,0 +1,55 @@ +package cli + +import ( + "bytes" + "strings" + "testing" + + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" + "github.com/fullsend-ai/fullsend/internal/security" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +func TestRedactProgressSecretLiterals(t *testing.T) { + for _, tc := range []struct{ name, secret, input string }{ + {"split tab", "opaque\trunner credential", "opaque\trun\x1b[31mner credential"}, + {"split markers", "opaque::runner%0Acredential", "opaque:\x1b[31m:runner%0Acredential"}, + {"Unicode literal", "opaque-\u200bcredential", "opaque-\u200bcred\u2066ential"}, + {"compatibility literal", "opaque-credential", "opaque-cred\u202eential"}, + {"short normalized value", "opaque\x1b[31m", "opaque"}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + r := agentruntime.NewEventRenderer(ui.New(&out)) + r.RedactProgress = func(s string) string { return redactProgressSecretLiterals(s, map[string]string{"X_TOKEN": tc.secret}) } + r.Handle(agentruntime.TaskProgressEvent{TaskID: "wf", State: agentruntime.TaskRunning, Label: tc.input}) + if strings.Contains(out.String(), "opaque") || !strings.Contains(out.String(), "[REDACTED") { + t.Fatalf("normalized credential escaped: %q", out.String()) + } + }) + } + const longer = "opaque-prefix-shortsecret-tail" + env := map[string]string{"LONG_TOKEN": longer, "SHORT_TOKEN": "shortsecret", "EMPTY_TOKEN": "\x1b[31m\x1b[0m"} + var out bytes.Buffer + r := agentruntime.NewEventRenderer(ui.New(&out)) + r.RedactProgress = func(s string) string { return redactProgressSecretLiterals(s, env) } + r.Handle(agentruntime.TaskProgressEvent{TaskID: "wf", State: agentruntime.TaskRunning, Label: "opaque-prefix-\x1b[31mshortsecret-tail"}) + if strings.Contains(out.String(), "opaque") || strings.Contains(out.String(), "-tail") { + t.Fatalf("nested literal leaked: %q", out.String()) + } + // Empty normalized literals must not inject replacements everywhere. + if got := redactProgressSecretLiterals("ordinary", env); got != "ordinary" { + t.Fatalf("empty normalization matched text: %q", got) + } + t.Setenv("GH_WORKFLOW_TOKEN", "provider\tcredential-for-test") + if got := redactProgressSecretLiterals("provider credential-for-test", nil); strings.Contains(got, "provider") { + t.Fatalf("provider alias unredacted: %q", got) + } + const registered = "registered\tcredential-for-progress-test" + if !security.RegisterRuntimeSecret(registered) { + t.Fatal("register fake runtime secret") + } + if got := redactProgressSecretLiterals("registered credential-for-progress-test", nil); got != "***" { + t.Fatalf("registered alias unredacted: %q", got) + } +} diff --git a/internal/cli/run.go b/internal/cli/run.go index 774cd82f0c..22c1e8b92f 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -2768,6 +2768,10 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep collector.attachInput(agentSpan, agentPrompt, promptHidesAlterations(validationFeedback, promptSanitized)) toolSpans := newToolSpanTracker(tracer, agentCtx) toolSpans.runnerEnv = h.RunnerEnv + renderer := agentruntime.NewEventRenderer(printer) + renderer.RedactProgress = func(text string) string { + return redactProgressSecretLiterals(text, h.RunnerEnv) + } var metrics agentruntime.RunMetrics hooksSettings := "" if h.SecurityEnabled() { @@ -2792,7 +2796,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep Forge: forgePlatform, ModelAliases: configModelAliases, ForgeClient: playbackForgeClient, - OnEvent: iterationEventHandler(agentruntime.NewEventRenderer(printer).Handle, collector, toolSpans), + OnEvent: iterationEventHandler(renderer.Handle, collector, toolSpans), }, printer, agentStart, &metrics) close(heartbeatDone) lastIterElapsed = time.Since(agentStart) @@ -4308,6 +4312,16 @@ func preScriptLogResult(res prescript.Result, runnerEnv map[string]string) presc // (runner secrets among them). Unlike redactFeedback it runs no pattern // scan, so text that merely looks like a secret is left alone. func redactSecretLiterals(feedback string, runnerEnv map[string]string) string { + return redactSecretLiteralsWithNormalizer(feedback, runnerEnv, nil) +} + +// redactProgressSecretLiterals masks both literal forms because progress +// cleanup can alter a secret itself. +func redactProgressSecretLiterals(feedback string, runnerEnv map[string]string) string { + return redactSecretLiteralsWithNormalizer(feedback, runnerEnv, agentruntime.NormalizeProgressText) +} + +func redactSecretLiteralsWithNormalizer(feedback string, runnerEnv map[string]string, normalize func(string) string) string { // All exact literals are replaced in one pass, longest first, so a // value that is a substring of another never leaves part of the longer // one visible, whichever source each came from. envLiterals covers @@ -4318,9 +4332,19 @@ func redactSecretLiterals(feedback string, runnerEnv map[string]string) string { var literals []literal seen := map[string]bool{} add := func(value, mask string) { - if len(value) >= minRedactableSecretLen && !seen[value] { - seen[value] = true - literals = append(literals, literal{value, mask}) + if len(value) < minRedactableSecretLen { + return + } + values := []string{value} + if normalize != nil { + values = append(values, normalize(value)) + } + for _, value := range values { + // An eligible original may normalize to a short sensitive value. + if value != "" && !seen[value] { + seen[value] = true + literals = append(literals, literal{value, mask}) + } } } for _, l := range envLiterals(runnerEnv) { diff --git a/internal/cli/workflow_progress_test.go b/internal/cli/workflow_progress_test.go new file mode 100644 index 0000000000..0e7b9f5574 --- /dev/null +++ b/internal/cli/workflow_progress_test.go @@ -0,0 +1,33 @@ +package cli + +import ( + "strings" + "testing" + + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" + "github.com/fullsend-ai/fullsend/internal/ui" + "github.com/stretchr/testify/assert" +) + +func TestIterationEventHandler_WorkflowProgressIsDisplayOnly(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "") + const secret = "opaque-workflow-runner-secret-for-test" + const provider = "opaque-workflow-provider-secret-for-test" + t.Setenv("GH_WORKFLOW_TOKEN", provider) + var output strings.Builder + renderer := agentruntime.NewEventRenderer(ui.New(&output)) + renderer.RedactProgress = func(s string) string { return redactSecretLiterals(s, map[string]string{"PUSH_TOKEN": secret}) } + collector := newContentCollector(4096) + tracker, _, agent := toolSpanFixture(t) + defer agent.End() + handler := iterationEventHandler(renderer.Handle, collector, tracker) + handler(agentruntime.TaskProgressEvent{TaskID: "workflow", State: agentruntime.TaskPaused, Label: secret, Detail: provider}) + handler(agentruntime.StatusProgressEvent{Kind: "notice", Label: "Hook", Detail: secret + " " + provider}) + assert.Contains(t, output.String(), "paused") + assert.Contains(t, output.String(), "Hook") + assert.NotContains(t, output.String(), secret) + assert.NotContains(t, output.String(), provider) + assert.Empty(t, collector.parts, "status metadata must not become model output") + assert.Zero(t, tracker.created, "status metadata must not fabricate tool spans") + assert.Empty(t, tracker.open) +} diff --git a/internal/runtime/claude_pr_review_test.go b/internal/runtime/claude_pr_review_test.go new file mode 100644 index 0000000000..7e544ef8d8 --- /dev/null +++ b/internal/runtime/claude_pr_review_test.go @@ -0,0 +1,138 @@ +package runtime + +import ( + "bytes" + "strings" + "testing" +) + +func TestClaudeReviewHookCompletionRetainsIdentity(t *testing.T) { + stream := `{"type":"system","subtype":"hook_started","hook_id":"guard-1","hook_name":"guard","hook_event":"PreToolUse"} +{"type":"system","subtype":"hook_progress","hook_id":"guard-1","stdout":"PRIVATE"} +{"type":"system","subtype":"hook_response","hook_id":"guard-1","outcome":"success","exit_code":0,"output":"PRIVATE"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Hook guard [PreToolUse]") != 2 || strings.Count(out.String(), "running") != 1 || !strings.Contains(out.String(), "Hook guard [PreToolUse] — completed: exit 0") || strings.Contains(out.String(), "PRIVATE") { + t.Fatal(out.String()) + } +} + +func TestClaudeReviewAgentCounterSnapshotRetainsContext(t *testing.T) { + detailed := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","label":"Create","phaseTitle":"Build","lastToolName":"Bash","lastToolSummary":"run checks","error":"access refused","blocked":true,"cached":true}]}` + "\n" + sparse := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","tokens":20,"toolCalls":3}]}` + "\n" + clear := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","label":"","phaseTitle":"","lastToolName":"","lastToolSummary":"","error":"","blocked":false,"cached":false}]}` + "\n" + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(detailed+sparse), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Task one") != 1 { + t.Fatal("counter update erased context: " + out.String()) + } + for _, want := range []string{"[Build]", "Create", "Bash: run checks", "access refused", "(blocked)", "(cached)"} { + if !strings.Contains(out.String(), want) { + t.Fatalf("missing %s: %s", want, out.String()) + } + } + if err := parseClaudeStream(strings.NewReader(clear+sparse), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Task one") != 2 || !strings.HasSuffix(out.String(), "Task one / agent #1 — failed\n") { + t.Fatal("explicit clears not retained: " + out.String()) + } +} + +func TestClaudeReviewDistinctRunDoesNotInheritHiddenParent(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"r1","ambient":true,"description":"PRIVATE"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r2","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"New worker"}]} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r2","description":"Visible new run"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r1","description":"PRIVATE"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "New worker — completed") || !strings.Contains(out.String(), "Visible new run — running") || strings.Contains(out.String(), "PRIVATE") { + t.Fatal(out.String()) + } +} + +func TestClaudeReviewAgentToolChangeDoesNotKeepOldSummary(t *testing.T) { + stream := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","lastToolName":"Bash","lastToolSummary":"OLD COMMAND"}]} +{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"progress","lastToolName":"Read"}]} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "(tool: Read)") || strings.Contains(out.String(), "Read: OLD COMMAND") { + t.Fatal(out.String()) + } +} + +func TestClaudeReviewHookIdentityExplicitClear(t *testing.T) { + stream := `{"type":"system","subtype":"hook_started","hook_id":"one","hook_name":"guard","hook_event":"PreToolUse"} +{"type":"system","subtype":"hook_progress","hook_id":"one","hook_name":"","hook_event":""} +{"type":"system","subtype":"hook_response","hook_id":"one","hook_name":null,"hook_event":null,"outcome":"success"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "guard") != 1 || !strings.HasSuffix(out.String(), "Hook — completed\n") { + t.Fatal(out.String()) + } +} + +func TestClaudeReviewAgentRecoveryClearsTransientMetadata(t *testing.T) { + stream := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","startedAt":100,"attempt":2,"lastAttemptReason":"throttled","label":"Create","error":"rate limited","blocked":true,"cached":true}]} +{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"progress","startedAt":100,"attempt":2,"label":"Create","lastToolName":"Bash"}]} +{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","startedAt":100,"attempt":2,"label":"Create"}]} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + for _, transient := range []string{"(blocked)", "(cached)", "rate limited"} { + if strings.Count(out.String(), transient) != 1 { + t.Fatalf("%s survived recovery: %s", transient, out.String()) + } + } + if !strings.Contains(out.String(), "Create — running (tool: Bash)") || !strings.Contains(out.String(), "Create — completed (tool: Bash)") { + t.Fatal(out.String()) + } +} + +// The internal 2.1.312 producer keys Workflow entries by type:index. This +// reduced sequence models its queued/start/done shapes; it is not a newly +// recorded live 2.1.312 run. +func TestClaudeReviewLateAgentIDUsesOneIndexedRow(t *testing.T) { + stream := `{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","queuedAt":100,"label":"read","phaseTitle":"Read"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a1","state":"start","queuedAt":100,"startedAt":101,"attempt":1,"label":"read","phaseTitle":"Read"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","queuedAt":100,"startedAt":101,"attempt":1,"label":"read","phaseTitle":"Read"}]} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "— running") != 1 || strings.Count(out.String(), "— completed") != 1 || len(r.progress.taskProgressSeen) != 1 { + t.Fatal("late ID split agent row: " + out.String()) + } + for _, row := range r.progress.taskProgressSeen { + if row.event.AgentID != "a1" || row.event.State != TaskCompleted || row.event.AgentIndex != 1 { + t.Fatalf("lost agent identity or completion: %+v", row.event) + } + } + if !strings.Contains(out.String(), "a1") { + t.Fatal("known agent ID missing from completion display") + } +} diff --git a/internal/runtime/claude_progress.go b/internal/runtime/claude_progress.go index f09798dd87..3570c37e6f 100644 --- a/internal/runtime/claude_progress.go +++ b/internal/runtime/claude_progress.go @@ -9,7 +9,6 @@ import ( "strings" "unicode/utf8" - "github.com/fullsend-ai/fullsend/internal/security" "github.com/fullsend-ai/fullsend/internal/ui" ) @@ -338,6 +337,16 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error { continue } switch se.Subtype { + case "task_started", "task_progress", "task_updated", "task_notification": + for _, progress := range decodeClaudeTaskProgress(line, se.Subtype) { + onEvent(progress) + } + case "hook_started", "hook_progress", "hook_response", "task_summary", + "informational", "notification", "status", "session_state_changed", + "permission_denied", "background_tasks_changed": + if progress, ok := decodeClaudeStatusProgress(line, se.Subtype); ok { + onEvent(progress) + } case "init": onEvent(InitEvent{ Model: se.Model, @@ -362,6 +371,11 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error { }) } + case "rate_limit_event": + if progress, ok := decodeClaudeRateLimit(line); ok { + onEvent(progress) + } + case "stream_event": seenStreamEvent = true var wrapper streamEventWrapper @@ -689,9 +703,6 @@ func recordClaudeMetrics(metrics *RunMetrics, evt AgentEvent) { } } -// progressRedactor scrubs secrets from tool context strings before display. -var progressRedactor = security.NewSecretRedactor() - // extractSafeContext returns a safe, non-secret string for progress display. // The result is run through SecretRedactor to scrub tokens, keys, and // credentials before anything reaches the terminal or CI annotations. diff --git a/internal/runtime/claude_progress_review_test.go b/internal/runtime/claude_progress_review_test.go new file mode 100644 index 0000000000..0a80e41e10 --- /dev/null +++ b/internal/runtime/claude_progress_review_test.go @@ -0,0 +1,175 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +func TestWorkflowReviewTerminalNotificationKeepsContext(t *testing.T) { + for _, state := range []string{"completed", "failed", "stopped"} { + t.Run(state, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + stream := fmt.Sprintf(`{"type":"system","subtype":"task_started","task_id":"one","description":"Work"} +{"type":"system","subtype":"task_progress","task_id":"one","description":"Work","last_tool_name":"Bash"} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":%q,"error":"context retained"}} +{"type":"system","subtype":"task_notification","task_id":"one","status":%q,"summary":"PRIVATE"} +`, state, state) + stderr := captureStderr(t, func() { + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + }) + if strings.Count(out.String(), "— "+state) != 1 || strings.Count(stderr, "— "+state) != 1 { + t.Fatalf("terminal message duplicated: %s", out.String()) + } + if !strings.Contains(out.String(), "context retained") || strings.Contains(out.String(), "PRIVATE") { + t.Fatal(out.String()) + } + // A supplied worker-restart cause is new information and must replace + // the prior detail, rather than being swallowed by the partial merge. + if state == "stopped" { + r.isCI = false + if err := parseClaudeStream(strings.NewReader(`{"type":"system","subtype":"task_notification","task_id":"one","status":"stopped","reason":"worker_restart"}`+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "worker restarted") { + t.Fatal(out.String()) + } + } + }) + } +} + +func TestWorkflowReviewUnkeyedWarningsAreOccurrences(t *testing.T) { + for _, subtype := range []string{"informational", "permission_denied", "notification"} { + t.Run(subtype, func(t *testing.T) { + line := fmt.Sprintf(`{"type":"system","subtype":%q,"level":"warning","content":"Retry required","tool_name":"Bash","decision_reason":"Retry required","text":"Retry required"}`, subtype) + "\n" + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(line+line), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Retry required") != 2 { + t.Fatalf("lost repeated %s: %s", subtype, out.String()) + } + }) + } +} + +func TestWorkflowReviewRequestCyclesStayQuiet(t *testing.T) { + cycle := `{"type":"system","subtype":"status","status":"requesting"} +{"type":"system","subtype":"status","status":null} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(strings.Repeat(cycle, 20)), r.Handle); err != nil { + t.Fatal(err) + } + if out.Len() != 0 { + t.Fatal("per-request status chatter: " + out.String()) + } + if err := parseClaudeStream(strings.NewReader(`{"type":"system","subtype":"status","status":"compacting"}`+"\n"+cycle+cycle), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "compacting") != 1 || strings.Count(out.String(), "ready") != 1 { + t.Fatal(out.String()) + } +} + +func TestWorkflowReviewRunIDPromotionPreservesHiddenAndTerminal(t *testing.T) { + for _, hidden := range []bool{false, true} { + t.Run(fmt.Sprint(hidden), func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + stream := fmt.Sprintf(`{"type":"system","subtype":"task_started","task_id":"one","description":"Initial","ambient":%t} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"completed"}} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"run1","description":"STALE"} +{"type":"system","subtype":"task_notification","task_id":"one","run_id":"run1","status":"completed"} +`, hidden) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "STALE") { + t.Fatal("promotion lost terminal guard: " + out.String()) + } + if hidden && out.Len() != 0 { + t.Fatal("promotion exposed ambient task: " + out.String()) + } + if !hidden && strings.Count(out.String(), "completed") != 1 { + t.Fatal("promotion lost terminal identity: " + out.String()) + } + }) + } +} + +func TestWorkflowReviewNewRunWithoutStartReceivesOptionalCompletion(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"r1","description":"Old"} +{"type":"system","subtype":"task_notification","task_id":"one","run_id":"r1","status":"completed"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r2","description":"New"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r1","description":"LATE OLD"} +{"type":"system","subtype":"task_notification","task_id":"one","status":"completed"} +` + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "New — completed") || strings.Contains(out.String(), "LATE OLD") { + t.Fatal(out.String()) + } +} + +func TestWorkflowReviewSubtypeFieldsDecodeIndependently(t *testing.T) { + line := `{"type":"system","subtype":"informational","level":"warning","content":"Still useful","hook_id":42,"status":{},"tasks":false}` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(line+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "Still useful") { + t.Fatal("unrelated optional fields discarded notice") + } +} + +func TestWorkflowReviewNewStartResetsAgents(t *testing.T) { + for _, run := range []string{"", ` ,"run_id":"run1"`} { + t.Run(run, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + started := `{"type":"system","subtype":"task_started","task_id":"one"` + run + `}` + "\n" + finished := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"Read"}]}` + "\n" + restart := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"Fresh agent"}]}` + "\n" + if err := parseClaudeStream(strings.NewReader(started+finished+started+restart), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "Fresh agent — running") { + t.Fatal("new start did not reset agent guard: " + out.String()) + } + }) + } +} + +func TestWorkflowReviewRestartWithoutRunIDKeepsOldRunHistory(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + stream := `{"type":"system","subtype":"task_started","task_id":"one","description":"Old"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"A","description":"Old"} +{"type":"system","subtype":"task_notification","task_id":"one","run_id":"A","status":"completed"} +{"type":"system","subtype":"task_started","task_id":"one","description":"New"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"A","description":"STALE"} +{"type":"system","subtype":"task_notification","task_id":"one","run_id":"A","status":"completed"} +{"type":"system","subtype":"task_progress","task_id":"one","description":"Current work"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"B","description":"Current work"} +{"type":"system","subtype":"task_notification","task_id":"one","status":"completed"} +` + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "STALE") || strings.Count(out.String(), "completed") != 2 || strings.Count(out.String(), "Current work — running") != 1 || !strings.Contains(out.String(), "Current work — completed") { + t.Fatal("old run stole restarted task: " + out.String()) + } +} diff --git a/internal/runtime/claude_run_order_test.go b/internal/runtime/claude_run_order_test.go new file mode 100644 index 0000000000..346ea845f8 --- /dev/null +++ b/internal/runtime/claude_run_order_test.go @@ -0,0 +1,133 @@ +package runtime + +import ( + "bytes" + "strings" + "testing" +) + +func TestClaudeTaskLateUnseenRunCannotBecomeCurrent(t *testing.T) { + for _, late := range []string{ + `{"type":"system","subtype":"task_notification","task_id":"t1","run_id":"r1","status":"completed"}`, + `{"type":"system","subtype":"task_progress","task_id":"t1","run_id":"r1","description":"STALE"}`, + `{"type":"system","subtype":"task_updated","task_id":"t1","run_id":"r1","patch":{"description":"STALE","status":"failed"}}`, + `{"type":"system","subtype":"task_progress","task_id":"t1","run_id":"r1","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"STALE"}]}`, + } { + t.Run(late, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + stream := `{"type":"system","subtype":"task_started","task_id":"t1","run_id":"r2","description":"Current"}` + "\n" + late + "\n" + `{"type":"system","subtype":"task_updated","task_id":"t1","patch":{"status":"failed"}}` + "\n" + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "completed") || strings.Contains(out.String(), "STALE") || !strings.HasSuffix(out.String(), "Task t1: Current — failed\n") || strings.Count(out.String(), "Task t1") != 2 { + t.Fatal("late run hijacked display: " + out.String()) + } + }) + } +} + +func TestTaskRunOrderForwardAndAnonymousWatermark(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r2", Started: true, State: TaskRunning, Label: "Prior"}) + r.Handle(TaskProgressEvent{TaskID: "one", Started: true, State: TaskRunning, Label: "Anonymous"}) + before := out.String() + for _, e := range []TaskProgressEvent{ + {TaskID: "one", RunID: "r1", State: TaskCompleted}, + {TaskID: "one", RunID: "r2", State: TaskCompleted}, + {TaskID: "one", RunID: "r1", Started: true, State: TaskRunning, Label: "STALE"}, + {TaskID: "one", RunID: "r2", Started: true, State: TaskRunning, Label: "STALE"}, + } { + r.Handle(e) + } + if out.String() != before { + t.Fatal("older run took anonymous generation: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r3", State: TaskRunning, ToolName: "Bash"}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskCompleted, Update: true}) + if !strings.HasSuffix(out.String(), "Anonymous — completed (tool: Bash)\n") { + t.Fatal("newer name lost current context: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r4", State: TaskRunning, Label: "Forward"}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskFailed, Update: true}) + if !strings.HasSuffix(out.String(), "Forward — failed\n") { + t.Fatal("newer unseen name not adopted: " + out.String()) + } +} + +func TestTaskRunOrderPlainStringAndKnownOldRuns(t *testing.T) { + for _, tc := range []struct{ old, current string }{ + {"r1", "r2"}, {"r10", "r2"}, {"r", "r1"}, {"\U00010000", "\ue000"}, + } { + t.Run(tc.current, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: tc.old, Started: true, State: TaskRunning, Label: "Old"}) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: tc.current, Started: true, State: TaskRunning, Label: "Current"}) + before := out.String() + r.Handle(TaskProgressEvent{TaskID: "one", RunID: tc.old, State: TaskCompleted}) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: tc.old, State: TaskRunning, Label: "STALE"}) + if out.String() != before { + t.Fatal("known superseded run rendered: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskFailed, Update: true}) + if !strings.HasSuffix(out.String(), "Current — failed\n") { + t.Fatal(out.String()) + } + }) + } +} + +func TestTaskRunOrderUnsafeIDsNeedExplicitStart(t *testing.T) { + for _, id := range []string{"opaque-run-order-secret-for-test", strings.Repeat("z", maxTaskRunOrderBytes+1), "bad\nrun", string([]byte{0xff})} { + t.Run(id[:min(len(id), 24)], func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, "opaque-run-order-secret-for-test", "[REDACTED]") } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r2", Started: true, State: TaskRunning, Label: "Current"}) + before := out.String() + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, State: TaskCompleted}) + if out.String() != before { + t.Fatal("unorderable unseen frame replaced current: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, Started: true, State: TaskRunning, Label: "Explicit"}) + for _, run := range r.progress.taskProgressRuns { + if run.order != "" { + t.Fatalf("retained unsafe order text: %q", run.order) + } + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r3", State: TaskCompleted}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskFailed, Update: true}) + if !strings.HasSuffix(out.String(), "Explicit — failed\n") { + t.Fatal("unorderable state stole implicit updates: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", Started: true, Hidden: true, State: TaskRunning, Label: "PRIVATE"}) + before = out.String() + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, Started: true, State: TaskRunning, Label: "STALE"}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "PRIVATE"}) + if out.String() != before { + t.Fatal("unorderable prior name exposed anonymous generation: " + out.String()) + } + + }) + } +} + +func TestClaudeTaskLateStartCannotExposeAnonymousRestart(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"t1","run_id":"r2","description":"Visible prior"} +{"type":"system","subtype":"task_started","task_id":"t1","ambient":true,"description":"PRIVATE"} +{"type":"system","subtype":"task_started","task_id":"t1","run_id":"r2","description":"STALE"} +{"type":"system","subtype":"task_progress","task_id":"t1","description":"PRIVATE"} +{"type":"system","subtype":"task_progress","task_id":"t1","run_id":"r3","description":"PRIVATE"} +{"type":"system","subtype":"task_notification","task_id":"t1","status":"completed"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "STALE") || strings.Contains(out.String(), "PRIVATE") || strings.Count(out.String(), "Task t1") != 1 { + t.Fatal("old start exposed anonymous run: " + out.String()) + } +} diff --git a/internal/runtime/claude_sparse_lifecycle_test.go b/internal/runtime/claude_sparse_lifecycle_test.go new file mode 100644 index 0000000000..70c9f17608 --- /dev/null +++ b/internal/runtime/claude_sparse_lifecycle_test.go @@ -0,0 +1,100 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +func TestClaudeWorkflowSparseLifecycle(t *testing.T) { + for _, tc := range []struct { + name, first, sparse string + want TaskState + }{ + {"queued", `"state":"start","queuedAt":100`, `"state":"start","tokens":20`, TaskQueued}, + {"retry", `"state":"start","startedAt":200,"attempt":2,"lastAttemptReason":"stalled"`, `"state":"start","tokens":20`, TaskRetrying}, + {"skipped", `"state":"error","skipped":true`, `"state":"error","tokens":20`, TaskSkipped}, + {"legacy fallback", `"state":"start"`, `"state":"start","tokens":20`, TaskRunning}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, fields := range []string{tc.first, tc.sparse, tc.sparse} { + raw := fmt.Sprintf(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,%s}]}`+"\n", fields) + if err := parseClaudeStream(strings.NewReader(raw), r.Handle); err != nil { + t.Fatal(err) + } + } + if strings.Count(out.String(), "Task wf") != 1 { + t.Fatalf("sparse snapshot fabricated transition: %s", out.String()) + } + for _, row := range r.progress.taskProgressSeen { + if row.event.State != tc.want { + t.Fatalf("state %s, want %s", row.event.State, tc.want) + } + } + }) + } +} + +func TestClaudeWorkflowSparseLifecycleTransitions(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, step := range []struct { + fields string + want TaskState + }{ + {`"state":"start","queuedAt":100`, TaskQueued}, + {`"state":"start","queuedAt":100,"tokens":20`, TaskQueued}, + {`"state":"start","startedAt":200,"attempt":1`, TaskRunning}, + {`"state":"progress","tokens":30`, TaskRunning}, + {`"state":"error","skipped":true`, TaskSkipped}, + {`"state":"error","tokens":40`, TaskSkipped}, + {`"state":"error","skipped":false`, TaskFailed}, + {`"state":"start","startedAt":300,"attempt":2,"lastAttemptReason":"throttled"`, TaskRetrying}, + {`"state":"start","tokens":50`, TaskRetrying}, + {`"state":"progress","tokens":60`, TaskRunning}, + {`"state":"error"`, TaskFailed}, // previous skipped flag must not leak + {`"state":"start","queuedAt":400`, TaskQueued}, // fresh quota queue drops old startedAt + {`"state":"start","tokens":70`, TaskQueued}, + {`"state":"start","startedAt":500,"attempt":2,"lastAttemptReason":""`, TaskRetrying}, + {`"state":"done"`, TaskCompleted}, + } { + raw := fmt.Sprintf(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,%s}]}`+"\n", step.fields) + if err := parseClaudeStream(strings.NewReader(raw), r.Handle); err != nil { + t.Fatal(err) + } + for _, row := range r.progress.taskProgressSeen { + if row.event.State != step.want { + t.Fatalf("%s: state %s, want %s; output: %s", step.fields, row.event.State, step.want, out.String()) + } + } + } +} + +func TestClaudeWorkflowSparseLifecycleClosedGuards(t *testing.T) { + for _, tc := range []struct{ name, terminal string }{ + {"parent", `{"type":"system","subtype":"task_notification","task_id":"wf","status":"completed"}`}, + {"completed agent", `{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done"}]}`}, + {"skipped agent", `{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","skipped":true}]}`}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + parse := func(raw string) { + t.Helper() + if err := parseClaudeStream(strings.NewReader(raw+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + } + parse(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","startedAt":100,"attempt":1}]}`) + parse(tc.terminal) + before := out.String() + parse(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","startedAt":200,"attempt":2}]}`) + if out.String() != before { + t.Fatalf("reopened closed work: %s", out.String()) + } + }) + } +} diff --git a/internal/runtime/claude_status_progress.go b/internal/runtime/claude_status_progress.go new file mode 100644 index 0000000000..e50fc988c9 --- /dev/null +++ b/internal/runtime/claude_status_progress.go @@ -0,0 +1,247 @@ +package runtime + +import ( + "encoding/json" + "fmt" + "strings" + "time" +) + +// decodeClaudeStatusProgress applies an explicit display allowlist. In +// particular hook stdout/stderr/output, prompts, terminal summaries, and +// arbitrary future payloads must stay out of console/CI annotations. +func decodeClaudeStatusProgress(line []byte, subtype string) (StatusProgressEvent, bool) { + e := StatusProgressEvent{Kind: subtype} + switch subtype { + case "hook_started", "hook_progress", "hook_response": + var wire struct { + HookID string `json:"hook_id"` + HookName *string `json:"hook_name"` + HookEvent *string `json:"hook_event"` + Outcome string `json:"outcome"` + ExitCode *int `json:"exit_code"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + if strings.TrimSpace(wire.HookID) == "" { + return e, false + } + e.Kind = "hook" + e.ID = wire.HookID + e.Label = "Hook" + if wire.HookName != nil { + e.Subject = *wire.HookName + e.SubjectSet = true + } + if wire.HookEvent != nil { + e.Context = *wire.HookEvent + e.ContextSet = true + } + e.State = "running" + if subtype == "hook_response" { + switch wire.Outcome { + case "success": + e.State = "completed" + case "error": + e.State = "failed" + case "cancelled": + e.State = "stopped" + default: + return e, false + } + if wire.ExitCode != nil { + e.Detail = fmt.Sprintf("exit %d", *wire.ExitCode) + } + } + case "task_summary": + // Undocumented internal Claude Code message from the inspected 2.1.312 + // embedded schema, not a public Agent SDK contract. It may change or + // disappear in any patch release; unknown display shapes are ignored. + var wire struct { + Detail *string `json:"detail"` + Summary *string `json:"summary"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + e.Label = "Task summary" + if wire.Detail != nil { + e.Detail = *wire.Detail + } else if wire.Summary != nil { + e.Detail = *wire.Summary + } + e.Clear = strings.TrimSpace(e.Detail) == "" + case "informational": + var wire struct { + Level string `json:"level"` + Content string `json:"content"` + ToolUseID string `json:"tool_use_id"` + PreventContinuation bool `json:"prevent_continuation"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + // Claude marks info as transcript-only. Keep salient console levels. + switch wire.Level { + case "notice", "suggestion", "warning": + default: + return e, false + } + if strings.TrimSpace(wire.Content) == "" { + return e, false + } + e.ID = wire.ToolUseID + e.Occurrence = strings.TrimSpace(e.ID) == "" + e.Label = "Claude " + wire.Level + e.Detail = wire.Content + if wire.PreventContinuation { + e.State = "continuation stopped" + } + case "notification": + var wire struct { + Key string `json:"key"` + Text string `json:"text"` + Priority string `json:"priority"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + if strings.TrimSpace(wire.Text) == "" { + return e, false + } + e.ID = wire.Key + e.Occurrence = strings.TrimSpace(e.ID) == "" + e.Label = "Claude notification" + e.State = wire.Priority + e.Detail = wire.Text + case "status": + var wire struct { + Status *string `json:"status"` + CompactResult string `json:"compact_result"` + CompactError string `json:"compact_error"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + e.Label = "Claude status" + if wire.Status == nil { + if wire.CompactResult == "failed" { + e.State = "compaction failed" + e.Detail = wire.CompactError + } else { + e.State = "ready" + e.Recovery = true + } + } else { + switch *wire.Status { + case "compacting": + e.State = *wire.Status + default: + return e, false + } + } + case "session_state_changed": + var wire struct { + State string `json:"state"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + e.Label = "Session" + switch wire.State { + case "idle", "running", "requires_action": + e.State = strings.ReplaceAll(wire.State, "_", " ") + default: + return e, false + } + case "permission_denied": + var wire struct { + ToolUseID string `json:"tool_use_id"` + ToolName string `json:"tool_name"` + AgentID string `json:"agent_id"` + DecisionReason string `json:"decision_reason"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + if wire.ToolName == "" { + return e, false + } + e.ID = wire.ToolUseID + e.Occurrence = strings.TrimSpace(e.ID) == "" + e.Label = "Permission denied: " + wire.ToolName + if wire.AgentID != "" { + e.Label += " / agent " + wire.AgentID + } + e.Detail = wire.DecisionReason + // message is a tool_result body, deliberately not forwarded. + case "background_tasks_changed": + var wire struct { + Tasks json.RawMessage `json:"tasks"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + var tasks []json.RawMessage + if len(wire.Tasks) == 0 || string(wire.Tasks) == "null" || json.Unmarshal(wire.Tasks, &tasks) != nil { + return e, false + } + count := 0 + for _, raw := range tasks { + var task struct { + TaskID string `json:"task_id"` + Ambient bool `json:"ambient"` + } + if json.Unmarshal(raw, &task) == nil && strings.TrimSpace(task.TaskID) != "" && !task.Ambient { + count++ + } + } + e.Label = "Background tasks" + e.Detail = fmt.Sprintf("%d reported (membership only)", count) + default: + return e, false + } + return e, true +} + +func decodeClaudeRateLimit(line []byte) (StatusProgressEvent, bool) { + var wire struct { + Info struct { + Status string `json:"status"` + Limit string `json:"rateLimitType"` + ResetsAt int64 `json:"resetsAt"` + } `json:"rate_limit_info"` + } + if json.Unmarshal(line, &wire) != nil { + return StatusProgressEvent{}, false + } + e := StatusProgressEvent{Kind: "rate_limit", Label: "Rate limit"} + switch wire.Info.Status { + case "allowed": + e.State = "allowed" + e.Recovery = true + case "allowed_warning": + e.State = "approaching limit" + case "rejected": + e.State = "rejected" + default: + return e, false + } + e.Detail = wire.Info.Limit + if wire.Info.ResetsAt > 0 { + if e.Detail != "" { + e.Detail += "; " + } + e.Detail += "resets " + time.Unix(wire.Info.ResetsAt, 0).UTC().Format(time.RFC3339) + } + return e, true +} diff --git a/internal/runtime/claude_status_progress_test.go b/internal/runtime/claude_status_progress_test.go new file mode 100644 index 0000000000..5836493375 --- /dev/null +++ b/internal/runtime/claude_status_progress_test.go @@ -0,0 +1,130 @@ +package runtime + +import ( + "bytes" + "io" + "strings" + "testing" +) + +// Shapes below are reduced from the embedded SDK schemas/emitter in Claude +// 2.1.312. Raw output/prompt/result fields are included to prove exclusion. +// Fullsend launches Claude without --include-hook-events, and the SDK emits +// only SessionStart and Setup hook events in that mode, so the hook fixtures +// use SessionStart to match the producer configuration real runs use; the +// decoder itself accepts any hook_event value. +func TestClaudeStatusProgressShapes(t *testing.T) { + cases := []struct{ name, line, want string }{ + {"hook start", `{"type":"system","subtype":"hook_started","hook_id":"h1","hook_name":"guard","hook_event":"SessionStart"}`, "Hook guard [SessionStart] — running"}, + {"hook start other events", `{"type":"system","subtype":"hook_started","hook_id":"h2","hook_name":"guard","hook_event":"PreToolUse"}`, "Hook guard [PreToolUse] — running"}, + {"hook progress", `{"type":"system","subtype":"hook_progress","hook_id":"h1","hook_name":"guard","stdout":"PRIVATE","stderr":"PRIVATE","output":"PRIVATE"}`, "Hook guard — running"}, + {"hook success", `{"type":"system","subtype":"hook_response","hook_id":"h1","hook_name":"guard","outcome":"success","exit_code":0,"output":"PRIVATE"}`, "completed: exit 0"}, + {"hook failed", `{"type":"system","subtype":"hook_response","hook_id":"h1","hook_name":"guard","outcome":"error","exit_code":2}`, "failed: exit 2"}, + {"hook cancelled", `{"type":"system","subtype":"hook_response","hook_id":"h1","outcome":"cancelled"}`, "stopped"}, + {"summary", `{"type":"system","subtype":"task_summary","detail":"Refining strategy"}`, "Task summary: Refining strategy"}, + {"older summary", `{"type":"system","subtype":"task_summary","summary":"Reviewing change"}`, "Task summary: Reviewing change"}, + {"notice", `{"type":"system","subtype":"informational","level":"notice","content":"Retrying a phase"}`, "Claude notice: Retrying a phase"}, + {"suggestion", `{"type":"system","subtype":"informational","level":"suggestion","content":"Check access"}`, "Claude suggestion: Check access"}, + {"stopped continuation", `{"type":"system","subtype":"informational","level":"warning","content":"Hook blocked continuation","prevent_continuation":true}`, "continuation stopped: Hook blocked continuation"}, + {"notification", `{"type":"system","subtype":"notification","key":"budget","text":"Budget nearly used","priority":"high"}`, "Claude notification — high: Budget nearly used"}, + {"compacting", `{"type":"system","subtype":"status","status":"compacting","compact_output_chars":27}`, "Claude status — compacting"}, + {"compaction failure", `{"type":"system","subtype":"status","status":null,"compact_result":"failed","compact_error":"provider refused"}`, "compaction failed: provider refused"}, + {"session running", `{"type":"system","subtype":"session_state_changed","state":"running"}`, "Session — running"}, + {"session idle", `{"type":"system","subtype":"session_state_changed","state":"idle"}`, "Session — idle"}, + {"requires action", `{"type":"system","subtype":"session_state_changed","state":"requires_action"}`, "Session — requires action"}, + {"permission", `{"type":"system","subtype":"permission_denied","tool_name":"Bash","tool_use_id":"t1","agent_id":"a1","decision_reason":"policy denied","message":"PRIVATE tool result"}`, "Permission denied: Bash / agent a1: policy denied"}, + {"background membership", `{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"one"},{"task_id":"ambient","ambient":true},null,42,{"task_id":""}]}`, "Background tasks: 1 reported (membership only)"}, + {"empty membership", `{"type":"system","subtype":"background_tasks_changed","tasks":[]}`, "Background tasks: 0 reported (membership only)"}, + {"rate warning", `{"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","rateLimitType":"five_hour","resetsAt":1700000000}}`, "Rate limit — approaching limit: five_hour; resets 2023-11-14T22:13:20Z"}, + {"rate rejected", `{"type":"rate_limit_event","rate_limit_info":{"status":"rejected"}}`, "Rate limit — rejected"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(tc.line+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), tc.want) { + t.Fatalf("missing %q in %q", tc.want, out.String()) + } + if strings.Contains(out.String(), "PRIVATE") { + t.Fatal("private output exposed") + } + }) + } +} + +func TestClaudeStatusIgnoresNonDisplayAndMalformed(t *testing.T) { + lines := []string{ + `{broken`, + `{"type":"system","subtype":"hook_started"}`, + `{"type":"system","subtype":"hook_response","hook_id":"one","outcome":"future"}`, + `{"type":"system","subtype":"informational","level":"info","content":"transcript only"}`, + `{"type":"system","subtype":"informational","level":"warning","content":" "}`, + `{"type":"system","subtype":"notification","text":" "}`, + `{"type":"system","subtype":"task_summary","detail":null}`, + `{"type":"system","subtype":"status","status":null}`, + `{"type":"system","subtype":"status","status":"future"}`, + `{"type":"system","subtype":"status","status":"requesting"}`, + `{"type":"system","subtype":"session_state_changed","state":"future"}`, + `{"type":"system","subtype":"permission_denied"}`, + `{"type":"system","subtype":"background_tasks_changed"}`, + `{"type":"system","subtype":"background_tasks_changed","tasks":null}`, + `{"type":"system","subtype":"background_tasks_changed","tasks":42}`, + `{"type":"system","subtype":"future_display","content":"PRIVATE"}`, + `{"type":"rate_limit_event","rate_limit_info":{"status":"future"}}`, + `{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"}}`, + `{"type":"rate_limit_event","rate_limit_info":42}`, + } + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(strings.Join(lines, "\n")+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if out.Len() != 0 { + t.Fatalf("unexpected output: %q", out.String()) + } + if _, ok := decodeClaudeStatusProgress([]byte(`{"hook_id":42}`), "hook_started"); ok { + t.Fatal("invalid fields accepted") + } + if _, ok := decodeClaudeStatusProgress([]byte(`{}`), "future"); ok { + t.Fatal("unknown subtype accepted") + } + if _, ok := decodeClaudeRateLimit([]byte(`{broken`)); ok { + t.Fatal("invalid rate event accepted") + } +} + +func TestClaudeStatusTransitionsAndDedup(t *testing.T) { + stream := `{"type":"system","subtype":"status","status":"compacting"} +{"type":"system","subtype":"status","status":"compacting","compact_output_chars":500} +{"type":"system","subtype":"status","status":null} +{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"}} +{"type":"rate_limit_event","rate_limit_info":{"status":"rejected"}} +{"type":"rate_limit_event","rate_limit_info":{"status":"rejected"}} +{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"}} +{"type":"system","subtype":"task_summary","detail":"Reviewing"} +{"type":"system","subtype":"task_summary","detail":"Reviewing"} +{"type":"system","subtype":"task_summary","detail":null} +{"type":"system","subtype":"task_summary","detail":"Reviewing"} +` + var raw, out bytes.Buffer + metrics := &RunMetrics{} + r := newTestRenderer(&out) + err := parseClaudeStream(io.TeeReader(strings.NewReader(stream), &raw), func(e AgentEvent) { recordClaudeMetrics(metrics, e); r.Handle(e) }) + if err != nil { + t.Fatal(err) + } + for text, count := range map[string]int{"compacting": 1, "ready": 1, "rejected": 1, "allowed": 1, "Reviewing": 2} { + if got := strings.Count(out.String(), text); got != count { + t.Errorf("%s count=%d want=%d: %s", text, got, count, out.String()) + } + } + if raw.String() != stream { + t.Fatal("raw events changed") + } + if metrics.InputTokens != 0 || metrics.OutputTokens != 0 || metrics.ToolCalls.Load() != 0 || metrics.TotalCostUSD != 0 { + t.Fatal("advisories altered metrics") + } +} diff --git a/internal/runtime/claude_task_cache_test.go b/internal/runtime/claude_task_cache_test.go new file mode 100644 index 0000000000..4029c39522 --- /dev/null +++ b/internal/runtime/claude_task_cache_test.go @@ -0,0 +1,111 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" + "testing" +) + +func TestClaudeTaskSparseToolAndSummary(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, fields := range []string{ + `"description":"Build","last_tool_name":"Bash","summary":"Running tests"`, + `"description":"Build","usage":{"total_tokens":20,"tool_uses":1}`, + `"usage":{"total_tokens":30,"tool_uses":1}`, + `"description":"Build","last_tool_name":null,"summary":null`, + } { + raw := `{"type":"system","subtype":"task_progress","task_id":"one",` + fields + "}\n" + if err := parseClaudeStream(strings.NewReader(raw), r.Handle); err != nil { + t.Fatal(err) + } + } + if strings.Count(out.String(), "Task one") != 1 || !strings.Contains(out.String(), "tool: Bash") || !strings.Contains(out.String(), "Running tests") { + t.Fatal("sparse task erased progress: " + out.String()) + } + for _, row := range r.progress.taskProgressSeen { + if row.event.ToolName != "Bash" || row.event.Summary != "Running tests" { + t.Fatalf("sparse cache erased metadata: %+v", row.event) + } + } +} + +func TestClaudeWorkflowLargeSnapshotsDoNotReprint(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + parse := func(raw string) { + t.Helper() + if err := parseClaudeStream(strings.NewReader(raw+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + } + frame := func(task string, count int) string { + entries := make([]map[string]any, count) + for i := range entries { + entries[i] = map[string]any{"type": "workflow_agent", "index": i + 1, "state": "progress", "label": "Worker"} + } + raw, err := json.Marshal(map[string]any{"type": "system", "subtype": "task_progress", "task_id": task, "run_id": "r2", "workflow_progress": entries}) + if err != nil { + t.Fatal(err) + } + return string(raw) + } + a, b := frame("one", 1000), frame("two", 500) + stderr := captureStderr(t, func() { + parse(`{"type":"system","subtype":"task_started","task_id":"hidden","ambient":true,"description":"PRIVATE"}`) + for _, task := range []string{"one", "two"} { + parse(fmt.Sprintf(`{"type":"system","subtype":"task_started","task_id":%q,"run_id":"r2","description":%q}`, task, task)) + } + for range 20 { + parse(a) + parse(b) + } + parse(`{"type":"system","subtype":"task_progress","task_id":"hidden","description":"PRIVATE"}`) + parse(`{"type":"system","subtype":"task_notification","task_id":"one","run_id":"r1","status":"completed"}`) + }) + if got := strings.Count(out.String(), " / agent #"); got != 1500 { + t.Fatalf("unchanged snapshots printed %d agent lines, want1500", got) + } + if strings.Count(stderr, "::notice::") != 1502 || strings.Contains(out.String(), "PRIVATE") || strings.Contains(out.String(), "completed") { + t.Fatal("cache pressure lost dedup/hidden/run guards") + } +} + +func TestClaudeTaskExplicitClearsAndPauseResume(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + parse := func(raw string) { + t.Helper() + if err := parseClaudeStream(strings.NewReader(raw+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + } + parse(`{"type":"system","subtype":"task_progress","task_id":"one","description":"Build","last_tool_name":"Bash","summary":"Running tests"}`) + parse(`{"type":"system","subtype":"task_progress","task_id":"one","description":"Renamed","last_tool_name":{},"summary":42}`) + if !strings.HasSuffix(out.String(), "Renamed — running (tool: Bash) — Running tests\n") { + t.Fatal("malformed optional fields erased context: " + out.String()) + } + parse(`{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"paused"}}`) + if !strings.HasSuffix(out.String(), "Renamed — paused (tool: Bash)\n") { + t.Fatal("paused task displayed active summary") + } + parse(`{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"running"}}`) + if !strings.HasSuffix(out.String(), "Renamed — running (tool: Bash) — Running tests\n") { + t.Fatal("resume lost once-per-change status") + } + parse(`{"type":"system","subtype":"task_progress","task_id":"one","summary":""}`) + parse(`{"type":"system","subtype":"task_progress","task_id":"one","last_tool_name":""}`) + before := out.String() + parse(`{"type":"system","subtype":"task_progress","task_id":"one","description":"Renamed","usage":{"total_tokens":30}}`) + if out.String() != before || !strings.HasSuffix(before, "Renamed — running\n") { + t.Fatal("empty fields not retained across sparse snapshot: " + out.String()) + } + parse(`{"type":"system","subtype":"task_notification","task_id":"one","status":"completed","summary":"PRIVATE result"}`) + parse(`{"type":"system","subtype":"task_started","task_id":"one","run_id":"r2","description":"Fresh"}`) + if strings.Contains(out.String(), "PRIVATE") || !strings.HasSuffix(out.String(), "Fresh — running\n") { + t.Fatal("new generation inherited old context/result: " + out.String()) + } +} diff --git a/internal/runtime/claude_task_progress.go b/internal/runtime/claude_task_progress.go new file mode 100644 index 0000000000..2df621bc1b --- /dev/null +++ b/internal/runtime/claude_task_progress.go @@ -0,0 +1,228 @@ +package runtime + +import ( + "encoding/json" + "strings" +) + +// Optional snapshots remain raw so malformed entries cannot discard a useful +// lifecycle event. Prompt/result bodies and terminal summaries are not decoded. +type claudeTaskProgress struct { + TaskID string `json:"task_id"` + RunID string `json:"run_id"` + Description string `json:"description"` + Status string `json:"status"` + LastToolName json.RawMessage `json:"last_tool_name"` + Summary json.RawMessage `json:"summary"` + Reason string `json:"reason"` + Ambient bool `json:"ambient"` + SkipTranscript bool `json:"skip_transcript"` + Patch json.RawMessage `json:"patch"` + // WorkflowProgress is an undocumented internal Claude Code payload, not + // a public Agent SDK contract. It may change or disappear without notice + // in any patch release; decoding is best-effort and raw capture is retained. + WorkflowProgress json.RawMessage `json:"workflow_progress"` +} + +type claudeWorkflowAgentProgress struct { + Type string `json:"type"` + Index int `json:"index"` + AgentID string `json:"agentId"` + Label *string `json:"label"` + PhaseTitle *string `json:"phaseTitle"` + State string `json:"state"` + LastToolName *string `json:"lastToolName"` + LastToolSummary *string `json:"lastToolSummary"` + Error *string `json:"error"` + Blocked *bool `json:"blocked"` + Cached *bool `json:"cached"` + QueuedAt *float64 `json:"queuedAt"` + StartedAt *float64 `json:"startedAt"` + Attempt *int `json:"attempt"` + LastAttemptReason *string `json:"lastAttemptReason"` + Skipped *bool `json:"skipped"` +} + +func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { + var task claudeTaskProgress + if json.Unmarshal(line, &task) != nil || strings.TrimSpace(task.TaskID) == "" { + return nil + } + event := TaskProgressEvent{TaskID: task.TaskID, RunID: task.RunID, Label: task.Description} + switch subtype { + case "task_started": + event.State = TaskRunning + event.Started = true + event.Hidden = task.Ambient || task.SkipTranscript + case "task_progress": + event.State = TaskRunning + event.ToolName, event.ToolNameSet = claudeProgressString(task.LastToolName) + event.Summary, event.SummarySet = claudeProgressString(task.Summary) + case "task_updated": + var patch struct { + Status *string `json:"status"` + Description *string `json:"description"` + Error *string `json:"error"` + } + if len(task.Patch) > 0 { + if json.Unmarshal(task.Patch, &patch) != nil { + return nil + } + if patch.Status != nil { + task.Status = *patch.Status + } + if patch.Description != nil { + event.Label = *patch.Description + event.LabelSet = true + } + if patch.Error != nil { + event.Detail = *patch.Error + event.DetailSet = true + } + } + event.State = claudeTaskState(task.Status) + event.Update = true + case "task_notification": + event.Update = true + event.State = claudeTaskState(task.Status) + // summary is a possibly complete result, unlike task_progress.summary. + if task.Reason == "worker_restart" { + event.Detail = "worker restarted" + event.DetailSet = true + } + default: + return nil + } + var events []TaskProgressEvent + useful := event.ToolNameSet || event.SummarySet || event.LabelSet || event.DetailSet || event.Detail != "" || event.ToolName != "" || event.Summary != "" + if (event.State != "" || useful) && (subtype != "task_progress" || task.Description != "" || useful) { + events = append(events, event) + } + if subtype != "task_progress" { + return events + } + var entries []json.RawMessage + if json.Unmarshal(task.WorkflowProgress, &entries) != nil { + return events + } + for _, entry := range entries { + var agent claudeWorkflowAgentProgress + if json.Unmarshal(entry, &agent) != nil || agent.Type != "workflow_agent" || (agent.AgentID == "" && agent.Index <= 0) { + continue + } + state := claudeWorkflowAgentState(agent) + if state == "" { + continue + } + event := TaskProgressEvent{TaskID: task.TaskID, RunID: task.RunID, AgentID: agent.AgentID, AgentIndex: agent.Index, State: state, AgentState: agent.State} + if agent.QueuedAt != nil && *agent.QueuedAt >= 0 { + event.QueuedAt = *agent.QueuedAt + event.QueuedAtSet = true + } + if agent.StartedAt != nil && *agent.StartedAt >= 0 { + event.StartedAt = *agent.StartedAt + event.StartedAtSet = true + } + if agent.Attempt != nil && *agent.Attempt > 0 { + event.Attempt = *agent.Attempt + event.AttemptSet = true + } + if agent.LastAttemptReason != nil { + event.LastAttemptReasonSet = true + switch *agent.LastAttemptReason { + case "stalled", "throttled", "user-retry": + event.LastAttemptReason = *agent.LastAttemptReason + } + } + if agent.Skipped != nil { + event.Skipped = *agent.Skipped + event.SkippedSet = true + } + if agent.Label != nil { + event.Label = *agent.Label + event.LabelSet = true + } + if agent.PhaseTitle != nil { + event.Phase = *agent.PhaseTitle + event.PhaseSet = true + } + if agent.LastToolName != nil { + event.ToolName = *agent.LastToolName + event.ToolNameSet = true + } + if agent.LastToolSummary != nil { + event.ToolSummary = *agent.LastToolSummary + event.ToolSummarySet = true + } + if agent.Error != nil { + event.Detail = *agent.Error + event.DetailSet = true + } + if agent.Blocked != nil { + event.Blocked = *agent.Blocked + event.BlockedSet = true + } + if agent.Cached != nil { + event.Cached = *agent.Cached + event.CachedSet = true + } + events = append(events, event) + } + return events +} + +// claudeWorkflowAgentState follows the internal four-value producer enum. +// Queue/retry/skip are metadata, not additional workflow_agent.state values. +func claudeWorkflowAgentState(agent claudeWorkflowAgentProgress) TaskState { + switch agent.State { + case "start": + if agent.QueuedAt != nil && *agent.QueuedAt >= 0 && agent.StartedAt == nil { + return TaskQueued + } + if agent.StartedAt != nil && *agent.StartedAt >= 0 && agent.Attempt != nil && *agent.Attempt > 1 { + return TaskRetrying + } + return TaskRunning + case "progress": + return TaskRunning + case "done": + return TaskCompleted + case "error": + if agent.Skipped != nil && *agent.Skipped { + return TaskSkipped + } + return TaskFailed + default: + return "" + } +} + +// claudeTaskState maps task lifecycle statuses, not workflow_agent states. +func claudeTaskState(state string) TaskState { + switch state { + case "start", "started", "progress", "running": + return TaskRunning + case "done", "completed": + return TaskCompleted + case "error", "failed": + return TaskFailed + case "killed", "stopped", "cancelled", "canceled": + return TaskStopped + case "pending": + return TaskPending + case "paused": + return TaskPaused + default: + return "" + } +} + +// claudeProgressString treats null/malformed metadata as absent; empty strings +// clear prior progress without discarding the rest of a valid snapshot. +func claudeProgressString(raw json.RawMessage) (string, bool) { + var value *string + if json.Unmarshal(raw, &value) != nil || value == nil { + return "", false + } + return *value, true +} diff --git a/internal/runtime/claude_task_updates_test.go b/internal/runtime/claude_task_updates_test.go new file mode 100644 index 0000000000..2175a1afc1 --- /dev/null +++ b/internal/runtime/claude_task_updates_test.go @@ -0,0 +1,105 @@ +package runtime + +import ( + "bytes" + "strings" + "testing" +) + +func TestClaudeTaskPartialUpdatesAndResume(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"run1","description":"Initial"} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"pending","description":"Waiting for gate"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"paused"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"description":"Resume authorized"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"running"}} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"run1","description":"Working","last_tool_name":"Bash","summary":"Testing the patch"} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"failed","error":"provider refused"}} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"run1","description":"STALE progress"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"run1","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"STALE child"}]} +{"type":"system","subtype":"task_notification","task_id":"one","status":"failed","summary":"PRIVATE full result"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + for _, want := range []string{"Waiting for gate — pending", "Waiting for gate — paused", "Resume authorized — paused", "Resume authorized — running", "tool: Bash", "Testing the patch", "failed", "provider refused"} { + if !strings.Contains(out.String(), want) { + t.Errorf("missing %q: %s", want, out.String()) + } + } + for _, bad := range []string{"PRIVATE", "STALE"} { + if strings.Contains(out.String(), bad) { + t.Errorf("unexpected %q", bad) + } + } + // A real new start may reuse a task ID. Missing run IDs inherit only the + // current run, and a second explicit run does not merge the old label. + if err := parseClaudeStream(strings.NewReader(`{"type":"system","subtype":"task_started","task_id":"one","run_id":"run2","description":"Fresh run"}`+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "Fresh run — running") { + t.Fatal("new start was suppressed") + } +} + +func TestClaudeWorkflowAgentDetails(t *testing.T) { + line := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","blocked":true,"error":"schema refused","label":"Create"},{"type":"workflow_agent","index":2,"state":"done","cached":true,"label":"Read","resultPreview":"PRIVATE"},{"type":"workflow_agent","index":3,"state":"start","queuedAt":1,"label":"Review"}]}` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(line+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + for _, want := range []string{"failed (blocked)", "schema refused", "completed (cached)", "Review — queued"} { + if !strings.Contains(out.String(), want) { + t.Errorf("missing %q: %s", want, out.String()) + } + } + if strings.Contains(out.String(), "PRIVATE") { + t.Fatal("result leaked") + } +} + +func TestClaudeAmbientTasksStayHidden(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"ambient","ambient":true,"description":"PRIVATE"} +{"type":"system","subtype":"task_progress","task_id":"ambient","description":"PRIVATE","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"PRIVATE"}]} +{"type":"system","subtype":"task_updated","task_id":"ambient","patch":{"status":"completed"}} +{"type":"system","subtype":"task_notification","task_id":"ambient","status":"completed"} +{"type":"system","subtype":"task_started","task_id":"skip","skip_transcript":true,"description":"PRIVATE"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if out.Len() != 0 { + t.Fatalf("ambient tasks leaked: %s", out.String()) + } +} + +func TestClaudeTaskErrorOnlyAndExplicitEmptyLabel(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"one","description":"Old title"} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"description":""}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"error":"Details changed"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"failed"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"error":""}} +{"type":"system","subtype":"task_updated","task_id":"unknown","patch":{"description":"Orphan patch"}} +{"type":"system","subtype":"task_notification","task_id":"orphan","status":"stopped","reason":"worker_restart","summary":"PRIVATE"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Old title") != 1 || !strings.Contains(out.String(), "Task one — running — Details changed") || !strings.Contains(out.String(), "Task one — failed — Details changed") || !strings.Contains(out.String(), "Task one — failed\n") || !strings.Contains(out.String(), "Orphan patch — updated") || !strings.Contains(out.String(), "worker restarted") { + t.Fatal(out.String()) + } + if strings.Contains(out.String(), "PRIVATE") { + t.Fatal("terminal summary leaked") + } + for _, state := range []string{"pending", "paused"} { + if string(claudeTaskState(state)) != state { + t.Fatalf("state %s missing", state) + } + } +} diff --git a/internal/runtime/claude_workflow_progress_test.go b/internal/runtime/claude_workflow_progress_test.go new file mode 100644 index 0000000000..a383013043 --- /dev/null +++ b/internal/runtime/claude_workflow_progress_test.go @@ -0,0 +1,161 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "io" + "reflect" + "strings" + "testing" + + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// Reduced from the Claude 2.1.296 stream attached to #8908. The phase +// inventory is static; the agent transitions and description carry progress. +const claudeWorkflowProgressFixture = `{"type":"system","subtype":"task_started","task_id":"wf-example","run_id":"run-example","task_type":"local_workflow","description":"Strategy pipeline"} +{"type":"system","subtype":"task_progress","task_id":"wf-example","run_id":"run-example","description":"Read: read input","usage":{"total_tokens":0,"tool_uses":0},"workflow_progress":[{"type":"workflow_phase","index":1,"title":"Read"},{"type":"workflow_phase","index":2,"title":"Create"},{"type":"workflow_phase","index":3,"title":"Not reached"},{"type":"workflow_agent","index":1,"agentId":"reader","label":"read input","phaseTitle":"Read","state":"start"}]} +{"type":"system","subtype":"task_progress","task_id":"wf-example","run_id":"run-example","description":"Create: strategy-create","usage":{"total_tokens":14434,"tool_uses":2},"workflow_progress":[{"type":"workflow_phase","index":1,"title":"Read"},{"type":"workflow_phase","index":2,"title":"Create"},{"type":"workflow_phase","index":3,"title":"Not reached"},{"type":"workflow_agent","index":1,"agentId":"reader","label":"read input","phaseTitle":"Read","state":"done","tokens":14434,"toolCalls":2,"durationMs":7194},{"type":"workflow_agent","index":2,"agentId":"creator","label":"strategy-create","phaseTitle":"Create","state":"start","lastToolName":"Bash","lastToolSummary":"python3 create.py"}]} +{"type":"system","subtype":"task_updated","task_id":"wf-example","run_id":"run-example","patch":{"status":"completed"}} +{"type":"system","subtype":"task_notification","task_id":"wf-example","run_id":"run-example","status":"completed","summary":"Strategy pipeline complete"} +` + +func TestClaudeWorkflowProgressConsole(t *testing.T) { + var raw, console bytes.Buffer + metrics := &RunMetrics{} + err := progressParser(io.TeeReader(strings.NewReader(claudeWorkflowProgressFixture), &raw), ui.New(&console), metrics) + if err != nil { + t.Fatal(err) + } + output := console.String() + for _, want := range []string{"wf-example", "Read", "read input", "Create", "strategy-create", "Bash", "completed"} { + if !strings.Contains(output, want) { + t.Errorf("console missing %q: %s", want, output) + } + } + if strings.Contains(output, "Not reached") { + t.Error("predeclared phase must not be rendered as live progress") + } + if raw.String() != claudeWorkflowProgressFixture { + t.Error("raw stream capture changed") + } + if metrics.InputTokens != 0 || metrics.OutputTokens != 0 || metrics.ToolCalls.Load() != 0 || metrics.TotalCostUSD != 0 { + t.Errorf("task progress must not change usage accounting: %+v", metrics) + } +} + +func TestClaudeTaskLifecycle(t *testing.T) { + tests := []struct { + name, line string + want TaskState + }{ + {"start", `{"type":"system","subtype":"task_started","task_id":"one","description":"Pipeline"}`, TaskRunning}, + {"progress without snapshot", `{"type":"system","subtype":"task_progress","task_id":"one","description":"Read: input"}`, TaskRunning}, + {"completed update", `{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"completed"}}`, TaskCompleted}, + {"failed notification", `{"type":"system","subtype":"task_notification","task_id":"one","status":"failed","summary":"DO NOT PRINT full result"}`, TaskFailed}, + {"stopped update", `{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"killed"}}`, TaskStopped}, + {"top level status", `{"type":"system","subtype":"task_updated","task_id":"one","status":"running"}`, TaskRunning}, + {"unknown subtype", `{"type":"system","subtype":"future_task_event","task_id":"one","status":"completed"}`, ""}, + {"unknown state", `{"type":"system","subtype":"task_notification","task_id":"one","status":"future-state"}`, ""}, + {"empty id", `{"type":"system","subtype":"task_progress","description":"input"}`, ""}, + {"blank id", `{"type":"system","subtype":"task_started","task_id":" "}`, ""}, + {"invalid id", `{"type":"system","subtype":"task_started","task_id":42}`, ""}, + {"broken patch", `{"type":"system","subtype":"task_updated","task_id":"one","patch":[]}`, ""}, + {"nonstatus patch", `{"type":"system","subtype":"task_updated","task_id":"one","patch":{"elapsed":1}}`, ""}, + {"wrong status type", `{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":42}}`, ""}, + {"snapshot only static", `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_phase","index":1,"title":"Not started"}]}`, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var events []AgentEvent + if err := parseClaudeStream(strings.NewReader(tt.line+"\n"), func(e AgentEvent) { events = append(events, e) }); err != nil { + t.Fatal(err) + } + if tt.want == "" { + if len(events) != 0 { + t.Fatalf("unexpected events: %+v", events) + } + return + } + if len(events) != 1 { + t.Fatalf("want one event, got %+v", events) + } + e, ok := events[0].(TaskProgressEvent) + if !ok || e.TaskID != "one" || e.State != tt.want { + t.Fatalf("wrong event: %+v", events[0]) + } + if strings.Contains(e.Label, "DO NOT PRINT") { + t.Fatal("notification result summary must not become progress text") + } + }) + } + if got := decodeClaudeTaskProgress([]byte(`{broken`), "task_progress"); len(got) != 0 { + t.Fatalf("malformed JSON yielded events: %+v", got) + } +} + +func TestClaudeWorkflowProgressToleratesMalformedEntries(t *testing.T) { + line := `{"type":"system","subtype":"task_progress","task_id":"task-one","run_id":"run-one","workflow_progress":[null,42,{"type":"workflow_phase","title":"Not started"},{"type":"workflow_agent","state":"start"},{"type":"workflow_agent","index":4,"state":"future-state"},{"type":"workflow_agent","index":3,"state":"done","label":"first","phaseTitle":"Read","lastToolName":"Read","lastToolSummary":"input.json"},{"type":"workflow_agent","agentId":"child","state":"start","queuedAt":1,"label":"second"}]}` + got := decodeClaudeTaskProgress([]byte(line), "task_progress") + want := []TaskProgressEvent{ + {TaskID: "task-one", RunID: "run-one", AgentIndex: 3, AgentState: "done", Label: "first", Phase: "Read", State: TaskCompleted, ToolName: "Read", ToolSummary: "input.json", LabelSet: true, PhaseSet: true, ToolNameSet: true, ToolSummarySet: true}, + {TaskID: "task-one", RunID: "run-one", AgentID: "child", AgentState: "start", Label: "second", State: TaskQueued, LabelSet: true, QueuedAt: 1, QueuedAtSet: true}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %+v, want %+v", got, want) + } + for _, snapshot := range []string{`{}`, `"wrong"`, `null`} { + line := `{"task_id":"one","description":"still running","workflow_progress":` + snapshot + `}` + got := decodeClaudeTaskProgress([]byte(line), "task_progress") + if len(got) != 1 || got[0].Label != "still running" { + t.Errorf("bad optional snapshot must not drop task description: %+v", got) + } + } +} + +func TestClaudeTaskStates(t *testing.T) { + for _, pair := range []struct { + wire string + want TaskState + }{ + {"start", TaskRunning}, {"started", TaskRunning}, {"progress", TaskRunning}, {"running", TaskRunning}, + {"done", TaskCompleted}, {"completed", TaskCompleted}, {"error", TaskFailed}, {"failed", TaskFailed}, + {"killed", TaskStopped}, {"stopped", TaskStopped}, {"cancelled", TaskStopped}, {"canceled", TaskStopped}, + {"queued", ""}, {"retrying", ""}, {"skipped", ""}, {"unknown", ""}, + } { + if got := claudeTaskState(pair.wire); got != pair.want { + t.Errorf("%s = %s, want %s", pair.wire, got, pair.want) + } + } +} + +func TestClaudeWorkflowProgressMetricsUnchanged(t *testing.T) { + // Task usage is an aggregate snapshot of overlapping/nested agents, not + // another incremental TokensEvent or ResultEvent to add to the counters. + line := `{"type":"result","num_turns":3,"total_cost_usd":0.25,"usage":{"input_tokens":11,"output_tokens":22,"cache_read_input_tokens":33,"cache_creation_input_tokens":44}}` + "\n" + var metrics RunMetrics + err := parseClaudeStream(strings.NewReader(claudeWorkflowProgressFixture+line+claudeWorkflowProgressFixture), func(e AgentEvent) { + recordClaudeMetrics(&metrics, e) + }) + if err != nil { + t.Fatal(err) + } + if metrics.NumTurns != 3 || metrics.TotalCostUSD != 0.25 || metrics.InputTokens != 11 || + metrics.OutputTokens != 22 || metrics.CacheReadInputTokens != 33 || metrics.CacheCreationInputTokens != 44 || metrics.ToolCalls.Load() != 0 { + t.Fatalf("progress altered authoritative accounting: %+v", &metrics) + } +} + +func TestTaskProgressDoesNotExposeExtraFields(t *testing.T) { + var console bytes.Buffer + line := `{"type":"system","subtype":"task_progress","task_id":"one","description":"Review","prompt":"PRIVATE PROMPT","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"review","resultPreview":"PRIVATE RESULT","promptPreview":"PRIVATE PROMPT"}]}` + if !json.Valid([]byte(line)) { + t.Fatal("invalid test fixture") + } + if err := progressParser(strings.NewReader(line), ui.New(&console), &RunMetrics{}); err != nil { + t.Fatal(err) + } + if strings.Contains(console.String(), "PRIVATE") { + t.Errorf("prompt/result content reached progress display: %s", console.String()) + } +} diff --git a/internal/runtime/claude_workflow_state_test.go b/internal/runtime/claude_workflow_state_test.go new file mode 100644 index 0000000000..1fa8ea0dd5 --- /dev/null +++ b/internal/runtime/claude_workflow_state_test.go @@ -0,0 +1,129 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +// Reduced from the inspected Claude Code 2.1.312 bundled schema/emitter, +// not a newly recorded live run. The wire state enum has only four values. +func TestClaudeWorkflowAgentProducerStates(t *testing.T) { + cases := []struct { + name, agent string + want TaskState + }{ + {"queued", `"state":"start","queuedAt":0`, TaskQueued}, + {"started", `"state":"start","queuedAt":0,"startedAt":0,"attempt":1`, TaskRunning}, + {"retry start", `"state":"start","startedAt":20,"attempt":2,"lastAttemptReason":"stalled"`, TaskRetrying}, + {"retry progress", `"state":"progress","startedAt":20,"attempt":2,"lastAttemptReason":"stalled"`, TaskRunning}, + {"completed", `"state":"done","attempt":2`, TaskCompleted}, + {"skipped", `"state":"error","skipped":true,"error":"skipped by user"`, TaskSkipped}, + {"failed", `"state":"error","skipped":false`, TaskFailed}, + {"blocked", `"state":"error","blocked":true`, TaskFailed}, + {"older start without times", `"state":"start"`, TaskRunning}, + {"not an agent queued enum", `"state":"queued"`, ""}, + {"not an agent retry enum", `"state":"retrying"`, ""}, + {"not an agent skip enum", `"state":"skipped"`, ""}, + {"not an agent pause enum", `"state":"paused"`, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + raw := fmt.Sprintf(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"label":"read",%s}]}`, tc.agent) + events := decodeClaudeTaskProgress([]byte(raw), "task_progress") + if tc.want == "" { + if len(events) != 0 { + t.Fatalf("unsupported agent enum accepted: %+v", events) + } + return + } + if len(events) != 1 || events[0].State != tc.want { + t.Fatalf("got %+v, want state %s", events, tc.want) + } + }) + } +} + +func TestClaudeWorkflowAgentRetriesAndSkipsRender(t *testing.T) { + stream := `{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"label":"Read","state":"start","queuedAt":100}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a1","label":"Read","state":"start","queuedAt":100,"startedAt":101,"attempt":1}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a1","label":"Read","state":"error","queuedAt":100,"startedAt":101,"attempt":1,"error":"stalled"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a2","label":"Read","state":"start","queuedAt":100,"startedAt":201,"attempt":2,"lastAttemptReason":"stalled"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a2","label":"Read","state":"start","queuedAt":100,"startedAt":201,"attempt":2,"lastAttemptReason":"stalled","tokens":200}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a2","label":"Read","state":"error","queuedAt":100,"startedAt":201,"attempt":2,"lastAttemptReason":"stalled","error":"retry requested"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a3","label":"Read","state":"start","queuedAt":100,"startedAt":301,"attempt":3,"lastAttemptReason":"user-retry"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a3","label":"Read","state":"done","queuedAt":100,"startedAt":301,"attempt":3,"lastAttemptReason":"user-retry"},{"type":"workflow_agent","index":2,"label":"Other","state":"error","skipped":true,"error":"skipped by user"}]} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "— queued") != 1 || strings.Count(out.String(), "— retrying") != 2 { + t.Fatal("missing queue/retry transitions: " + out.String()) + } + for _, want := range []string{"attempt 2; retry: stalled", "attempt 3; retry: user-retry", "Other — skipped"} { + if !strings.Contains(out.String(), want) { + t.Fatalf("missing %s: %s", want, out.String()) + } + } + if strings.Contains(out.String(), "Other — failed") { + t.Fatal("skip reported as failure") + } +} + +func TestClaudeWorkflowAgentQuotaWaitAndStaleSnapshots(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, fields := range []string{ + `"state":"start","queuedAt":10,"startedAt":100,"attempt":1`, + `"state":"start","queuedAt":10`, // stale initial queue + `"state":"error","queuedAt":10,"startedAt":100,"attempt":1,"error":"quota"`, + `"state":"start","queuedAt":200`, // quota wait has no attempt/startedAt + `"state":"start","queuedAt":10,"startedAt":100,"attempt":1`, // stale running during wait + `"state":"start","queuedAt":10`, // stale queue during wait + `"state":"error","queuedAt":200,"error":"quota wait failed"`, + `"state":"start","queuedAt":10,"startedAt":100,"attempt":1`, // stale after wait failure + `"state":"error","queuedAt":10,"startedAt":100,"attempt":1`, // stale failure + `"state":"start","queuedAt":200,"startedAt":300,"attempt":1`, + `"state":"error","queuedAt":200,"startedAt":300,"attempt":1`, + `"state":"start","queuedAt":200,"attempt":2,"lastAttemptReason":"throttled"`, + `"state":"start","queuedAt":200,"startedAt":400,"attempt":2,"lastAttemptReason":"throttled"`, + `"state":"done","queuedAt":200,"startedAt":300,"attempt":1`, // stale completion + `"state":"done","queuedAt":200,"startedAt":400,"attempt":2`, + } { + raw := fmt.Sprintf(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"label":"Read",%s}]}`+"\n", fields) + if err := parseClaudeStream(strings.NewReader(raw), r.Handle); err != nil { + t.Fatal(err) + } + } + if strings.Count(out.String(), "— queued") != 2 || strings.Count(out.String(), "— completed") != 1 || !strings.Contains(out.String(), "attempt 2; retry: throttled") { + t.Fatal(out.String()) + } + for _, row := range r.progress.taskProgressSeen { + if row.event.State != TaskCompleted || row.event.Attempt != 2 { + t.Fatalf("stale attempt changed final state: %+v", row.event) + } + } +} + +func TestClaudeWorkflowAgentRetryDoesNotReopenClosedWork(t *testing.T) { + for _, parent := range []bool{false, true} { + t.Run(fmt.Sprint("parent=", parent), func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "wf", AgentIndex: 1, State: TaskFailed, Attempt: 1, AttemptSet: true}) + if parent { + r.Handle(TaskProgressEvent{TaskID: "wf", State: TaskCompleted}) + } else { + r.Handle(TaskProgressEvent{TaskID: "wf", AgentIndex: 1, State: TaskCompleted, Attempt: 1, AttemptSet: true}) + } + before := out.String() + r.Handle(TaskProgressEvent{TaskID: "wf", AgentIndex: 1, State: TaskRetrying, Attempt: 2, AttemptSet: true}) + if out.String() != before { + t.Fatal("retry reopened closed work: " + out.String()) + } + }) + } +} diff --git a/internal/runtime/event.go b/internal/runtime/event.go index c3f2158646..aec8cb087b 100644 --- a/internal/runtime/event.go +++ b/internal/runtime/event.go @@ -160,3 +160,106 @@ type PluginErrorEvent struct { } func (PluginErrorEvent) agentEvent() {} + +// TaskState describes task/agent progress, not validated business completion. +type TaskState string + +const ( + TaskPending TaskState = "pending" + TaskPaused TaskState = "paused" + TaskRunning TaskState = "running" + TaskCompleted TaskState = "completed" + TaskFailed TaskState = "failed" + TaskStopped TaskState = "stopped" + TaskQueued TaskState = "queued" + TaskRetrying TaskState = "retrying" + TaskSkipped TaskState = "skipped" +) + +// TaskProgressEvent carries live background task or Workflow agent metadata. +// An empty AgentID and zero AgentIndex describe the task itself. A positive +// AgentIndex is the stable Workflow row identity within a task/run; AgentID +// is optional display attribution and is the identity fallback only when +// index is absent. Learning an ID alone is not a new display transition. +// Phase is agent attribution, never an inventory of declared phases. +// Progress does not update token/cost accounting and carries no prompts or +// tool result bodies. +// Consumers receive repeated snapshots and partial patches, not reconciled +// transitions. A display reconciler merges snapshots after caller-specific +// credential redaction; custom OnEvent consumers must reconcile their own +// state. Nonempty values are supplied values; the Set flags distinguish an +// explicitly empty string/false flag from absent optional metadata. Agent +// error/blocked/cached fields are state-relative: omitted values survive +// repeated snapshots of the same state, but not a state transition. +type TaskProgressEvent struct { + TaskID string + RunID string + AgentID string + AgentIndex int + Label string + Phase string + State TaskState + // AgentState preserves the Workflow producer's four-value lifecycle + // (start/progress/done/error). State is a per-snapshot approximation; + // renderers reconcile optional metadata before deriving display state. + AgentState string + Skipped bool + SkippedSet bool + ToolName string + ToolSummary string + Summary string + Detail string + Blocked bool + Cached bool + // Workflow attempts are one-based. Timestamps are producer epoch-ms + // metadata used only for lifecycle reconciliation, never usage accounting. + Attempt int + LastAttemptReason string + QueuedAt float64 + StartedAt float64 + AttemptSet bool + LastAttemptReasonSet bool + QueuedAtSet bool + StartedAtSet bool + // Update is a task lifecycle patch; it retains prior tool context. + // Label/Detail/ToolName/ToolSummary Set flags apply to task and agent + // metadata; SummarySet applies to task snapshots. Phase/Blocked/Cached/ + // Skipped Set flags apply only to agents. Started is task-level. + Update bool + LabelSet bool + DetailSet bool + PhaseSet bool + ToolNameSet bool + SummarySet bool + ToolSummarySet bool + BlockedSet bool + CachedSet bool + Started bool + Hidden bool +} + +func (TaskProgressEvent) agentEvent() {} + +// StatusProgressEvent is advisory runtime display metadata. It carries no +// tool output, prompts, result bodies, or authoritative run/usage outcomes. +type StatusProgressEvent struct { + Kind string + ID string + Label string + State string + Detail string + // Subject/Context attribute a status, such as a hook name and event. + // Set flags permit clearing; omitted fields retain sanitized prior values. + Subject string + Context string + SubjectSet bool + ContextSet bool + // Clear resets the row silently. Recovery is displayed only after a + // prior status, avoiding a routine initial "allowed" rate-limit message. + Clear bool + Recovery bool + // Occurrence is an unkeyed one-off message, not a state snapshot. + Occurrence bool +} + +func (StatusProgressEvent) agentEvent() {} diff --git a/internal/runtime/event_test.go b/internal/runtime/event_test.go index 42ff2afb81..4535089603 100644 --- a/internal/runtime/event_test.go +++ b/internal/runtime/event_test.go @@ -6,6 +6,9 @@ func TestAgentEventInterfaceSatisfied(t *testing.T) { // Compile-time verification that all concrete types satisfy AgentEvent. var events []AgentEvent events = append(events, + TaskProgressEvent{TaskID: "task", State: TaskRunning}, + StatusProgressEvent{Kind: "hook", Label: "Hook"}, + ModelFallbackEvent{From: "old", To: "new"}, InitEvent{Model: "claude-opus-4-6", Version: "1.0.0"}, ThinkingEvent{Text: "thinking..."}, TextEvent{Text: "hello"}, @@ -17,7 +20,7 @@ func TestAgentEventInterfaceSatisfied(t *testing.T) { ToolResultEvent{ID: "toolu_01abc", Result: "file contents"}, PluginErrorEvent{Plugin: "demo@inline", Type: "path-not-found", Path: "/plugins/demo", Message: "not found"}, ) - if len(events) != 10 { - t.Errorf("expected 10 event types, got %d", len(events)) + if len(events) != 13 { + t.Errorf("expected 13 event types, got %d", len(events)) } } diff --git a/internal/runtime/progress_allocation_test.go b/internal/runtime/progress_allocation_test.go new file mode 100644 index 0000000000..99dd481ff9 --- /dev/null +++ b/internal/runtime/progress_allocation_test.go @@ -0,0 +1,45 @@ +package runtime + +import ( + "bytes" + "fmt" + "runtime" + "strings" + "testing" +) + +func TestProgressCacheOwnsNormalizedStrings(t *testing.T) { + padded := strings.Repeat(" ", 1<<20) + "x" + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + check := func(s string) { + t.Helper() + if s != "x" { + t.Fatalf("unexpected normalized value %q", s) + } + } + check(taskProgressText(padded, 80)) + var out bytes.Buffer + r := newTestRenderer(&out) + for i := range 32 { + r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(i), Label: padded, State: TaskRunning}) + r.Handle(StatusProgressEvent{Kind: "hook", ID: fmt.Sprint(i), Label: "Hook", Subject: padded, Context: padded}) + } + for _, row := range r.progress.taskProgressSeen { + check(row.event.Label) + } + for _, row := range r.progress.statusProgressSeen { + check(row.subject) + check(row.context) + } + runtime.GC() + runtime.ReadMemStats(&after) + runtime.KeepAlive(r) + runtime.KeepAlive(padded) + // 32 rows retain 96 one-byte values. Allow ample GC/runtime noise but + // reject the roughly 96 MiB retained by padded backing allocations. + if after.HeapAlloc > before.HeapAlloc+(8<<20) { + t.Fatalf("tiny cached fields retained %d bytes", after.HeapAlloc-before.HeapAlloc) + } +} diff --git a/internal/runtime/progress_pattern_test.go b/internal/runtime/progress_pattern_test.go new file mode 100644 index 0000000000..d75f93f7c4 --- /dev/null +++ b/internal/runtime/progress_pattern_test.go @@ -0,0 +1,235 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/fullsend-ai/fullsend/internal/security" +) + +func TestProgressPatternRedactionBeforeUnicodeComposition(t *testing.T) { + // Repetitive synthetic fixtures exercise patterns; never authenticate. + tokens := []string{strings.Join([]string{"gh", "p_"}, "") + strings.Repeat("a", 35) + "e", strings.Join([]string{"AK", "IA"}, "") + strings.Repeat("A", 15) + "E"} + for index, token := range tokens { + for _, withCallback := range []bool{false, true} { + t.Run(fmt.Sprintf("pattern%d/callback=%t", index, withCallback), func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + if withCallback { + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, "caller-owned-placeholder", "[REDACTED]") } + } + stderr := captureStderr(t, func() { + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: " \t" + token + "\u0301 \n"}) + r.Handle(StatusProgressEvent{Kind: "notice", ID: "one", Label: "Notice", Detail: " \t" + token + "\u0301 \n"}) + }) + check := func(where, s string) { + t.Helper() + if strings.Contains(s, token[:len(token)-1]) { + t.Fatalf("pattern credential prefix exposed in %s", where) + } + } + check("console", out.String()) + check("CI", stderr) + for _, row := range r.progress.taskProgressSeen { + check("task cache", fmt.Sprintf("%+v", row.event)) + } + for _, row := range r.progress.statusProgressSeen { + check("status cache", fmt.Sprintf("%+v", row)) + } + }) + } + } +} + +func TestProgressRegisteredUnicodeLiteralWithoutCallback(t *testing.T) { + const secret = "opaque-\u202eruntime-progress-for-test" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: secret}) + if strings.Contains(out.String(), "opaque-") || !strings.Contains(out.String(), "***") { + t.Fatal("registered literal escaped normalization") + } +} + +func TestProgressPatternPaddingKeepsExactRegisteredMatches(t *testing.T) { + const secret = "\t opaque-padded-runtime-progress-only \n" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic padded literal") + } + if got := scanProgressSecrets(secret); strings.Contains(got, "opaque-padded") { + t.Fatal("padding optimization lost exact registered match") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "padded", State: TaskRunning, Label: secret}) + if strings.Contains(out.String(), "opaque-padded") || !strings.Contains(out.String(), "***") { + t.Fatal("nil-callback padded registered literal escaped") + } + const ordinary = " \tordinary status \n" + if got := scanProgressSecrets(ordinary); got != ordinary { + t.Fatal("nonsecret raw text changed before normalization") + } + if got := scanProgressSecrets(" \t \n"); got != " \t \n" { + t.Fatal("empty scanner candidate changed raw text") + } +} + +func TestProgressFallbackRedactsNormalizedRuntimeSecret(t *testing.T) { + // A registered credential containing whitespace variants (here a tab) + // normalizes to different text than the registered literal. Without a + // RedactProgress callback the fallback must still mask the normalized + // literal, or the reconstructed credential is displayed and retained. + const secret = "opaque-runtime-secret \twith-tab-for-test" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + cleaned := NormalizeProgressText(secret) + if cleaned == secret || !strings.Contains(cleaned, "with-tab-for-test") { + t.Fatalf("setup: secret did not normalize differently: %q", cleaned) + } + if got := scanProgressSecrets("progress " + cleaned + " done"); strings.Contains(got, "opaque-runtime-secret") || !strings.Contains(got, "***") { + t.Fatalf("normalized registered literal escaped the fallback: %q", got) + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "progress " + cleaned + " done"}) + if strings.Contains(out.String(), "opaque-runtime-secret") || !strings.Contains(out.String(), "***") { + t.Fatalf("normalized registered literal escaped rendering: %q", out.String()) + } +} + +// A registered credential whose normalized form is shorter than the +// registration floor must still be masked: the original literal passed the +// floor at registration, so every non-empty normalized derivative stays an +// authenticated secret. No RedactProgress callback is set, exercising the +// renderer fallback. +func TestProgressFallbackRedactsShortNormalizedRuntimeSecret(t *testing.T) { + const secret = "zz\x1b[32m\x1b[0mtok" // raw length 14 bytes; normalizes to "zztok" (5) + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + cleaned := NormalizeProgressText(secret) + if cleaned != "zztok" { + t.Fatalf("setup: unexpected normalized form %q", cleaned) + } + if got := scanProgressSecrets("status " + cleaned + " done"); strings.Contains(got, "zztok") || !strings.Contains(got, "***") { + t.Fatalf("short normalized registered literal escaped the fallback: %q", got) + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "status " + cleaned + " done"}) + if strings.Contains(out.String(), "zztok") || !strings.Contains(out.String(), "***") { + t.Fatalf("short normalized registered literal escaped rendering: %q", out.String()) + } +} + +func TestProgressFallbackMaskingOrderKeepsOverlappingCredentials(t *testing.T) { + // A secret with a longer raw value can normalize shorter than another + // secret's normalized form. Masking in registry (raw-length) order + // would replace the shorter literal first and leave the longer + // overlapping credential's suffix visible. No callback is set. + long := "containment-long\x1b[32m\x1b[0m" // raw 25 bytes, normalizes to "containment-long" + short := "containment-long-suffix" // raw 23 bytes, normalizes to itself + if !security.RegisterRuntimeSecret(long) || !security.RegisterRuntimeSecret(short) { + t.Fatal("register synthetic literals") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "status containment-long-suffix done"}) + if strings.Contains(out.String(), "containment-long") || !strings.Contains(out.String(), "***") { + t.Fatalf("overlapping normalized credential leaked: %q", out.String()) + } +} + +func TestProgressFallbackMergesCrossingOverlaps(t *testing.T) { + // One secret's end overlapping another's start defeats every + // sequential replacement order; the merged span must be masked whole. + a := "crossing-alpha-start" + b := "start-crossing-beta" + if !security.RegisterRuntimeSecret(a) || !security.RegisterRuntimeSecret(b) { + t.Fatal("register synthetic literals") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "prefix crossing-alpha-start-crossing-beta suffix"}) + if strings.Contains(out.String(), "crossing-alpha") || strings.Contains(out.String(), "crossing-beta") { + t.Fatalf("crossing overlap leaked a fragment: %q", out.String()) + } + if !strings.Contains(out.String(), "***") { + t.Fatalf("crossing overlap was not masked: %q", out.String()) + } +} + +func TestTaskProgressToolOnlyFramesDoNotPrint(t *testing.T) { + // Subagent tool calls already arrive as ToolUseEvents; a task_progress + // frame that only changes last_tool_name must not print a second line. + lines := `{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Subagent work","last_tool_name":"Read"}` + "\n" + + `{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Subagent work","last_tool_name":"Bash"}` + "\n" + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(lines), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Task sub1") != 1 { + t.Fatalf("tool-only task_progress printed more than once: %q", out.String()) + } + if strings.Contains(out.String(), "tool: Bash") { + t.Fatalf("tool-only change printed a second row: %q", out.String()) + } +} + +func TestTaskProgressToolLifecyclePrintsRealTransitions(t *testing.T) { + // Tool swaps are attribution churn and do not print, but a tool + // appearing or disappearing changes the row, and a later real + // transition prints the latest retained tool name. Frames carry + // usage counters like real SDK snapshots to prove they do not churn. + parse := func(raw string, r *EventRenderer) { + t.Helper() + if err := parseClaudeStream(strings.NewReader(raw+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + } + var out bytes.Buffer + r := newTestRenderer(&out) + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","usage":{"total_tokens":10,"tool_uses":1}}`, r) + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","last_tool_name":"Read","usage":{"total_tokens":20,"tool_uses":2}}`, r) + if !strings.Contains(out.String(), "tool: Read") { + t.Fatalf("tool appearance did not print: %q", out.String()) + } + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","last_tool_name":"Bash","usage":{"total_tokens":30,"tool_uses":3}}`, r) + if strings.Contains(out.String(), "tool: Bash") { + t.Fatalf("tool swap printed a row: %q", out.String()) + } + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","summary":"Halfway","last_tool_name":"Bash","usage":{"total_tokens":40,"tool_uses":4}}`, r) + if !strings.Contains(out.String(), "tool: Bash") || !strings.Contains(out.String(), "Halfway") { + t.Fatalf("real transition lost the retained tool name: %q", out.String()) + } + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","last_tool_name":"","summary":""}`, r) + if !strings.HasSuffix(strings.TrimRight(out.String(), "\n"), "— running") { + t.Fatalf("explicit tool and summary clear did not print: %q", out.String()) + } +} + +func TestTaskProgressJoinCannotReconstructCredential(t *testing.T) { + // A credential split across TaskID and Label reconstructs in the + // assembled row; the joined message must be masked before display. + const secret = "taskrow-split: cred" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "taskrow-split", Label: "cred", State: TaskRunning}) + if strings.Contains(out.String(), "cred") || strings.Contains(out.String(), "taskrow-split: cred") { + t.Fatalf("joined task-row credential leaked: %q", out.String()) + } + if !strings.Contains(out.String(), "***") { + t.Fatalf("joined task-row credential was not masked: %q", out.String()) + } +} diff --git a/internal/runtime/progress_reconciler.go b/internal/runtime/progress_reconciler.go new file mode 100644 index 0000000000..55c161f76c --- /dev/null +++ b/internal/runtime/progress_reconciler.go @@ -0,0 +1,12 @@ +package runtime + +import "crypto/sha256" + +// progressReconciler owns bounded lifecycle, visibility, run-order and dedup +// state independently of printer/CI output. Callers supply credential redaction +// before any retained display metadata. Parser callbacks remain raw snapshots. +type progressReconciler struct { + taskProgressSeen map[taskProgressKey]taskProgressDisplay + taskProgressRuns map[[sha256.Size]byte]taskProgressRun + statusProgressSeen map[[sha256.Size]byte]statusProgressDisplay +} diff --git a/internal/runtime/progress_redaction_test.go b/internal/runtime/progress_redaction_test.go new file mode 100644 index 0000000000..8c98e1c732 --- /dev/null +++ b/internal/runtime/progress_redaction_test.go @@ -0,0 +1,72 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +func TestProgressCallerRedactionAfterCleanup(t *testing.T) { + for _, tc := range []struct{ name, secret, input string }{ + {"ANSI split", "opaque-runner-credential-for-test", "opaque-runner-\x1b[31mcredential-for-test"}, + {"OSC split", "opaque-runner-credential-for-test", "opaque-runner-\x1b]0;hidden\x07credential-for-test"}, + {"whitespace", "opaque runner credential for test", "opaque\t runner\n credential for test"}, + {"encoded whitespace", "opaque runner credential for test", "opaque%0Arunner%0Dcredential for test"}, + {"raw whitespace literal", "opaque\trunner credential for test", "opaque\trunner credential for test"}, + {"split whitespace literal", "opaque\trunner credential for test", "opaque\trun\x1b[31mner credential for test"}, + {"split rewritten markers", "opaque::runner%0Acredential", "opaque:\x1b[31m:runner%0Acredential"}, + {"Unicode split", "opaque-runner-credential-for-test", "opaque-runner-\u202ecredential-for-test"}, + {"Unicode literal", "opaque-\u200bcredential", "opaque-\u200bcred\u2066ential"}, + {"compatibility split", "opaque-runner-credential-for-test", "opaque-runner-credential-for-test"}, + {"before truncation", "opaque-" + strings.Repeat("long-credential", 30), "opaque-\x1b[31m" + strings.Repeat("long-credential", 30)}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + r.RedactProgress = func(s string) string { + return strings.ReplaceAll(strings.ReplaceAll(s, tc.secret, "[REDACTED]"), NormalizeProgressText(tc.secret), "[REDACTED]") + } + stderr := captureStderr(t, func() { + r.Handle(TaskProgressEvent{TaskID: "task", AgentIndex: 1, AgentID: tc.input, Label: tc.input, Phase: tc.input, State: TaskRunning, ToolName: tc.input, ToolSummary: tc.input, Summary: tc.input, Detail: tc.input, LastAttemptReason: tc.input}) + r.Handle(StatusProgressEvent{Kind: "hook", ID: "id", Label: tc.input, State: tc.input, Detail: tc.input, Subject: tc.input, Context: tc.input}) + }) + check := func(where, s string) { + t.Helper() + if strings.Contains(s, "opaque") || strings.Contains(s, "long-credential") { + t.Fatalf("secret exposed in %s: %q", where, s) + } + } + check("console", out.String()) + check("CI", stderr) + if !strings.Contains(out.String(), "[REDACTED]") || !strings.Contains(stderr, "[REDACTED]") { + t.Fatal("missing redaction marker") + } + for _, row := range r.progress.taskProgressSeen { + check("task cache", fmt.Sprintf("%+v", row.event)) + } + for _, row := range r.progress.statusProgressSeen { + check("status cache", fmt.Sprintf("%+v", row)) + } + }) + } +} + +func TestProgressCallerRedactionDifferentSpans(t *testing.T) { + const longer = "opaque-prefix-shortsecret-tail" + const shorter = "shortsecret" + redact := func(s string) string { return strings.NewReplacer(longer, "[LONG]", shorter, "[SHORT]").Replace(s) } + r := newTestRenderer(&bytes.Buffer{}) + r.RedactProgress = redact + // The raw pass masks the inner secret, the independent normalized pass + // sees the outer secret. Do not print the remnants of either candidate. + if got := redactProgressText("context opaque-prefix-\x1b[31mshortsecret-tail", 160, r.RedactProgress); got != "[REDACTED]" { + t.Fatalf("conflicting redaction left residual text: %q", got) + } + // A raw-only match must still protect a literal that cleanup would alter. + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, "opaque\tcredential", "[REDACTED]") } + if got := redactProgressText("opaque\tcredential", 160, r.RedactProgress); got != "[REDACTED]" { + t.Fatalf("lost raw-only masking: %q", got) + } +} diff --git a/internal/runtime/progress_text.go b/internal/runtime/progress_text.go new file mode 100644 index 0000000000..33ca569939 --- /dev/null +++ b/internal/runtime/progress_text.go @@ -0,0 +1,167 @@ +package runtime + +import ( + "slices" + "strings" + "unicode/utf8" + + "github.com/fullsend-ai/fullsend/internal/security" +) + +var progressRedactor = security.NewSecretRedactor() +var progressUnicodeNormalizer = security.NewUnicodeNormalizer() + +func taskProgressText(s string, limit int) string { + return redactProgressText(s, limit, nil) +} + +// redactProgressText redacts complete raw literals before cleanup, then +// repeats after cleanup: removing ANSI and normalizing whitespace can +// reconstruct an opaque secret. Both passes precede truncation and cache +// retention. The caller's redactor uses display-safe replacement markers, +// such as [REDACTED] or ***. +func redactProgressText(s string, limit int, redact func(string) string) string { + // Pattern and registered-secret matching must also see the raw text: + // Unicode composition can otherwise destroy a recognizable token prefix. + pass := func(text string) string { + if redact != nil { + text = redact(text) + } + return scanProgressSecrets(text) + } + normalized := NormalizeProgressText(s) + raw := pass(s) + cleanedRaw := NormalizeProgressText(raw) + cleaned := raw + if normalized != s { + cleaned = pass(normalized) + } + switch { + case raw != s && cleaned != normalized && cleanedRaw != cleaned: + // Different passes masked different spans; suppress residual text. + s = "[REDACTED]" + case cleaned != normalized: + s = cleaned + default: + s = cleanedRaw + } + s = scanProgressSecrets(s) + if utf8.RuneCountInString(s) > limit { + s = string([]rune(s)[:limit]) + "…" + } + // strings.Fields/Join can return a short slice of the sanitizer's large + // allocation. Cache only storage proportional to the bounded final value. + return strings.Clone(s) +} + +// scanProgressSecrets applies pattern and registered-literal protection. +// Empty fields cannot match either class and need no scanner allocation. +func scanProgressSecrets(s string) string { + if s == "" { + return "" + } + // Token patterns do not need outer padding, but exact registered values + // may contain it. Preserve their full-input match before shortening the + // scanner input; return the original text when no redaction occurred. + candidate := s + if trimmed := strings.TrimSpace(s); len(trimmed) != len(s) { + registered := false + for _, secret := range security.RuntimeSecrets() { + if strings.Contains(s, secret) { + registered = true + break + } + } + if !registered { + candidate = trimmed + } + } + if candidate == "" { + return s + } + masked := maskRuntimeSecretLiterals(candidate) + text := masked + if result := progressRedactor.Scan(masked); !result.Safe { + text = result.Sanitized + } + if text != candidate { + return text + } + return s +} + +// maskRuntimeSecretLiterals masks registered runtime secrets and their +// normalized forms in one rewrite. Match ranges for every literal are +// collected against the original text and their union is masked, because +// no sequential replacement order survives crossing overlaps: one +// secret's end overlapping another's start leaves a fragment of one +// visible whichever is replaced first, and a self-overlapping literal +// must not re-match its own replacement. The registry orders by raw +// length, but normalization can reverse that order, so ordering alone +// was never sufficient. Pattern redaction runs after the literal pass. +// The original literal passed the registration length floor, so every +// non-empty normalized form is a derivative of an authenticated +// credential and is masked, mirroring redactSecretLiteralsWithNormalizer +// in the CLI. +func maskRuntimeSecretLiterals(s string) string { + var literals []string + for _, secret := range security.RuntimeSecrets() { + literals = append(literals, secret) + if normalized := NormalizeProgressText(secret); normalized != "" && normalized != secret { + literals = append(literals, normalized) + } + } + if len(literals) == 0 { + return s + } + covered := make([]bool, len(s)) + for _, literal := range literals { + if literal == "" { + continue + } + // Advance one byte past each match so overlapping occurrences of + // the same literal are all collected. + for offset := 0; offset+len(literal) <= len(s); { + i := strings.Index(s[offset:], literal) + if i < 0 { + break + } + start := offset + i + for j := start; j < start+len(literal); j++ { + covered[j] = true + } + offset = start + 1 + } + } + if !slices.Contains(covered, true) { + return s + } + var b strings.Builder + for i := 0; i < len(s); { + if covered[i] { + b.WriteString("***") + for i < len(s) && covered[i] { + i++ + } + continue + } + b.WriteByte(s[i]) + i++ + } + return b.String() +} + +// NormalizeProgressText applies the same cleanup to display text and caller +// credential literals. Redactors must match both original and normalized +// values, because cleanup can rewrite whitespace, escapes and CI markers. +func NormalizeProgressText(s string) string { + // Plain ASCII cannot contain Unicode format/compatibility characters. + // NUL and ESC still need the normalizer's stronger terminal cleanup. + for i := 0; i < len(s); i++ { + if s[i] >= utf8.RuneSelf || s[i] == 0 || s[i] == 0x1b { + s = progressUnicodeNormalizer.Scan(s).Sanitized + break + } + } + return strings.Join(strings.Fields(sanitizeOutput(s)), " ") +} diff --git a/internal/runtime/progress_unicode_test.go b/internal/runtime/progress_unicode_test.go new file mode 100644 index 0000000000..77c111e3bd --- /dev/null +++ b/internal/runtime/progress_unicode_test.go @@ -0,0 +1,78 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "strings" + "testing" +) + +func TestProgressUnicodeControlsRemovedFromDisplayAndCaches(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + controls := "\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069\u200b\ufeff\U000e0061" + label := "Visible" + controls + " café 漢字 العربية" + var out bytes.Buffer + r := newTestRenderer(&out) + stderr := captureStderr(t, func() { + r.Handle(TaskProgressEvent{TaskID: "task", RunID: "r1", AgentIndex: 1, AgentID: "worker" + controls, Label: label, Phase: label, State: TaskRunning, ToolName: label, ToolSummary: label, Summary: label, Detail: label, LastAttemptReason: label}) + r.Handle(StatusProgressEvent{Kind: "hook", ID: "one", Label: label, Subject: label, Context: label, State: label, Detail: label}) + }) + check := func(where, text string) { + t.Helper() + if strings.ContainsAny(text, controls) { + t.Fatalf("unsafe Unicode in %s", where) + } + } + check("console", out.String()) + check("CI", stderr) + for _, row := range r.progress.taskProgressSeen { + check("task cache", fmt.Sprintf("%+v", row.event)) + } + for _, row := range r.progress.statusProgressSeen { + check("status cache", fmt.Sprintf("%+v", row)) + } + if !strings.Contains(out.String(), "café 漢字 العربية") { + t.Fatal("ordinary Unicode content changed") + } + if got := NormalizeProgressText("::error:: injected"); strings.Contains(got, "::") { + t.Fatal("compatibility normalization recreated CI command") + } +} + +func TestClaudeProgressCallbacksStayRawWhileDisplayReconciles(t *testing.T) { + label := "Working\u202e" + raw, err := json.Marshal(map[string]any{"type": "system", "subtype": "task_progress", "task_id": "task", "description": label}) + if err != nil { + t.Fatal(err) + } + stream := strings.Repeat(string(raw)+"\n", 3) + `{"type":"result","num_turns":3,"total_cost_usd":0.25}` + "\n" + var console, capture bytes.Buffer + r := newTestRenderer(&console) + var labels []string + var metrics RunMetrics + if err := parseClaudeStream(io.TeeReader(strings.NewReader(stream), &capture), func(e AgentEvent) { + recordClaudeMetrics(&metrics, e) + r.Handle(e) + if task, ok := e.(TaskProgressEvent); ok { + labels = append(labels, task.Label) + } + }); err != nil { + t.Fatal(err) + } + if capture.String() != stream || len(labels) != 3 { + t.Fatal("raw stream/event contract changed") + } + for _, got := range labels { + if got != label { + t.Fatal("renderer changed caller event") + } + } + if strings.Count(console.String(), "Task task") != 1 || strings.Contains(console.String(), "\u202e") { + t.Fatal("display did not reconcile/sanitize independently") + } + if metrics.NumTurns != 3 || metrics.TotalCostUSD != 0.25 { + t.Fatal("progress changed accounting") + } +} diff --git a/internal/runtime/renderer.go b/internal/runtime/renderer.go index b22f011101..db1235d7d5 100644 --- a/internal/runtime/renderer.go +++ b/internal/runtime/renderer.go @@ -12,11 +12,19 @@ import ( // It tracks block state (text/thinking) so transitions between event // types produce clean output boundaries. type EventRenderer struct { + // RedactProgress removes caller-owned credential literals from progress + // metadata before and after normalization, before truncation. The callback + // must match original and NormalizeProgressText-normalized literals and + // use display-safe replacement markers. Pattern and registered + // runtime-secret redaction apply even when this callback is nil. + RedactProgress func(string) string + printer *ui.Printer isCI bool inText bool inThinking bool seenInit bool + progress progressReconciler } // NewEventRenderer creates a renderer that writes to the given printer. @@ -34,6 +42,14 @@ var ( // Handle dispatches a single AgentEvent to the appropriate rendering method. func (r *EventRenderer) Handle(evt AgentEvent) { switch e := evt.(type) { + case StatusProgressEvent: + if msg, show := r.progress.status(e, r.RedactProgress); show { + r.printProgress(msg) + } + case TaskProgressEvent: + if msg, show := r.progress.task(e, r.RedactProgress); show { + r.printProgress(msg) + } case InitEvent: if r.seenInit { return @@ -165,3 +181,11 @@ func (r *EventRenderer) endBlock() { r.inThinking = false } } + +func (r *EventRenderer) printProgress(msg string) { + r.endBlock() + if r.isCI { + fmt.Fprintf(os.Stderr, "::notice::%s\n", msg) + } + r.printer.ToolProgress(msg) +} diff --git a/internal/runtime/status_progress.go b/internal/runtime/status_progress.go new file mode 100644 index 0000000000..8171a4990b --- /dev/null +++ b/internal/runtime/status_progress.go @@ -0,0 +1,80 @@ +package runtime + +import "crypto/sha256" + +type statusProgressDisplay struct { + message string + subject string + context string +} + +// maxStatusProgressEntries bounds the status-event display cache. It shares +// the task-progress scale because both caches retain one row per active key. +const maxStatusProgressEntries = maxTaskProgressEntries + +func (r *progressReconciler) status(e StatusProgressEvent, redact func(string) string) (string, bool) { + if e.Kind == "" { + return "", false + } + key := sha256.Sum256([]byte(e.Kind + "\x00" + e.ID)) + previous, keyPresent := r.statusProgressSeen[key] + if e.Clear { + delete(r.statusProgressSeen, key) + return "", false + } + if e.Recovery && previous.message == "" { + return "", false + } + msg := redactProgressText(e.Label, 120, redact) + if msg == "" { + return "", false + } + subject := redactProgressText(e.Subject, 120, redact) + context := redactProgressText(e.Context, 80, redact) + if subject == "" && !e.SubjectSet { + subject = previous.subject + } + if context == "" && !e.ContextSet { + context = previous.context + } + if subject != "" { + msg += " " + subject + } + if context != "" { + msg += " [" + context + "]" + } + if state := redactProgressText(e.State, 60, redact); state != "" { + msg += " — " + state + } + if detail := redactProgressText(e.Detail, 240, redact); detail != "" { + msg += ": " + detail + } + msg = sanitizeOutput(msg) + // Fields are redacted individually; the joins can reconstruct a + // credential (a tab-containing secret normalizes to the exact text a + // label/subject join produces). The caller's callback runs first: it + // owns literals the fallback scanner cannot know, such as + // environment-derived credentials. Mask the joined row before dedup + // comparison, retention and display. Retained subject/context stay + // per-field masked; fragments appearing across separate rows are the + // same exposure as printing the pieces separately and are accepted. + if redact != nil { + msg = redact(msg) + } + msg = scanProgressSecrets(msg) + if !e.Occurrence && previous.message == msg { + return "", false + } + if !e.Occurrence { + if r.statusProgressSeen == nil { + r.statusProgressSeen = make(map[[sha256.Size]byte]statusProgressDisplay) + } + // Only a new key needs a free slot: updating an existing key at + // capacity must not discard the retained state of every other key. + if !keyPresent && len(r.statusProgressSeen) >= maxStatusProgressEntries { + clear(r.statusProgressSeen) + } + r.statusProgressSeen[key] = statusProgressDisplay{message: msg, subject: subject, context: context} + } + return msg, true +} diff --git a/internal/runtime/status_progress_test.go b/internal/runtime/status_progress_test.go new file mode 100644 index 0000000000..8c682e36c6 --- /dev/null +++ b/internal/runtime/status_progress_test.go @@ -0,0 +1,119 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/fullsend-ai/fullsend/internal/security" +) + +func TestStatusProgressRendererSafetyAndBounds(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + const secret = "opaque-status-secret-for-test" + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, secret, "[REDACTED]") } + e := StatusProgressEvent{Kind: "notification", ID: "one", Label: secret + "\n::error::", State: "\x1b[31mwarning\x1b[0m", Detail: secret + strings.Repeat("界", 500)} + stderr := captureStderr(t, func() { r.Handle(TextEvent{Text: "before"}); r.Handle(e); r.Handle(e) }) + if strings.Contains(out.String(), secret) || strings.Contains(stderr, secret) || strings.Contains(stderr, "::error::") || strings.Contains(out.String(), "\x1b") { + t.Fatal("unsafe status display") + } + if strings.Count(stderr, "::notice::") != 1 || !strings.Contains(out.String(), "before\n") { + t.Fatal("bad CI/block boundary") + } + if len([]rune(out.String())) > 500 { + t.Fatal("unbounded status") + } + r.Handle(StatusProgressEvent{}) + r.Handle(StatusProgressEvent{Kind: "empty"}) + r.isCI = false + for i := range maxTaskProgressEntries + 1 { + r.Handle(StatusProgressEvent{Kind: "row", ID: fmt.Sprint(i), Label: "row"}) + } + if len(r.progress.statusProgressSeen) > maxTaskProgressEntries { + t.Fatal("unbounded status cache") + } +} + +func TestWorkflowReviewJoiningFieldsCannotRecreateCommands(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "task:", Label: "label", State: TaskRunning}) + r.Handle(StatusProgressEvent{Kind: "warning", Label: "warning:", Detail: "detail"}) + if strings.Contains(out.String(), "::") { + t.Fatal("field joins recreated command delimiter: " + out.String()) + } +} + +func TestStatusProgressAttributionRedactedBeforeRetention(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + const secret = "opaque-hook-attribution-secret-for-test" + var out bytes.Buffer + r := newTestRenderer(&out) + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, secret, "[REDACTED]") } + stderr := captureStderr(t, func() { + r.Handle(StatusProgressEvent{Kind: "hook", ID: "one", Label: "Hook", State: "running", Subject: secret + strings.Repeat("界", 200), Context: secret + "\n::error::", SubjectSet: true, ContextSet: true}) + r.Handle(StatusProgressEvent{Kind: "hook", ID: "one", Label: "Hook", State: "completed"}) + }) + if strings.Contains(out.String(), secret) || strings.Contains(stderr, secret) || strings.Contains(stderr, "::error::") || strings.Count(stderr, "::notice::") != 2 { + t.Fatal("unsafe hook attribution") + } + for _, display := range r.progress.statusProgressSeen { + if strings.Contains(display.subject+display.context+display.message, secret) || len([]rune(display.subject)) > 121 || len([]rune(display.context)) > 81 { + t.Fatal("unsafe or unbounded cached attribution") + } + } + if strings.Count(out.String(), "[REDACTED]") != 4 { + t.Fatal("sparse completion lost redacted attribution: " + out.String()) + } +} + +func TestStatusProgressCapacityUpdateKeepsExistingEntries(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + // Fill the status cache to capacity with distinct keys carrying subjects. + for i := range maxStatusProgressEntries { + r.Handle(StatusProgressEvent{Kind: "row", ID: fmt.Sprint(i), Label: "row " + fmt.Sprint(i), Subject: "subject " + fmt.Sprint(i), SubjectSet: true}) + } + if len(r.progress.statusProgressSeen) != maxStatusProgressEntries { + t.Fatalf("setup: want %d entries, got %d", maxStatusProgressEntries, len(r.progress.statusProgressSeen)) + } + out.Reset() + // Updating an existing key at capacity must not wipe the cache. + r.Handle(StatusProgressEvent{Kind: "row", ID: "0", Label: "row 0 updated"}) + if len(r.progress.statusProgressSeen) != maxStatusProgressEntries { + t.Fatalf("existing-key update at capacity wiped the cache: %d entries remain", len(r.progress.statusProgressSeen)) + } + // Retained state of other keys must survive: a changed label on another + // key still merges its retained subject, printing the new row exactly + // once. (An unchanged resend is deduplicated and proves nothing: it + // prints nothing whether or not the cache was wiped.) + r.Handle(StatusProgressEvent{Kind: "row", ID: "1", Label: "row 1 changed"}) + if msg := out.String(); !strings.Contains(msg, "row 1 changed subject 1") { + t.Fatalf("retained subject lost after capacity update: %q", msg) + } + if strings.Count(out.String(), "row 1 changed subject 1") != 1 { + t.Fatalf("capacity update row printed more than once: %q", out.String()) + } +} + +func TestStatusProgressJoinCannotReconstructCredential(t *testing.T) { + // A tab-containing credential normalizes to the exact text a + // label/subject join can produce when the credential is split across + // fields. The joined row must be masked before display and retention. + const secret = "opaque-join-runtime-secret \tfor-test" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + if NormalizeProgressText(secret) != "opaque-join-runtime-secret for-test" { + t.Fatalf("setup: unexpected normalized form %q", NormalizeProgressText(secret)) + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(StatusProgressEvent{Kind: "hook", ID: "one", Label: "opaque-join-runtime-secret", Subject: "for-test", SubjectSet: true}) + if strings.Contains(out.String(), "for-test") || strings.Contains(out.String(), "opaque-join-runtime-secret") { + t.Fatalf("joined credential leaked: %q", out.String()) + } +} diff --git a/internal/runtime/task_progress_cache.go b/internal/runtime/task_progress_cache.go new file mode 100644 index 0000000000..db79fdd84c --- /dev/null +++ b/internal/runtime/task_progress_cache.go @@ -0,0 +1,42 @@ +package runtime + +import "crypto/sha256" + +// retireTaskProgressRows removes rows without discarding authoritative run and +// visibility control. A completed task needs no agent rows: all subsequent +// agent frames are blocked by its retained terminal parent state. +func (r *progressReconciler) retireTaskProgressRows(task [sha256.Size]byte, agentsOnly bool) { + parentAgent := sha256.Sum256(nil) + for key := range r.taskProgressSeen { + if key.task == task && (!agentsOnly || key.index > 0 || key.agent != parentAgent) { + delete(r.taskProgressSeen, key) + } + } +} + +func (r *progressReconciler) storeTaskProgress(key taskProgressKey, display taskProgressDisplay, isAgent bool) { + if !isAgent { + control := r.taskProgressRuns[key.task] + control.parent = display + if terminalTaskState(display.event.State) && control.agents > 0 { + r.retireTaskProgressRows(key.task, true) + control.agents = 0 + } + r.taskProgressRuns[key.task] = control + } + r.taskProgressSeen[key] = display +} + +// mergeTaskProgress retains status emitted only on change (not on every usage +// snapshot). Empty supplied fields clear; omitted or malformed fields retain. +func mergeTaskProgress(e *TaskProgressEvent, old TaskProgressEvent) { + if !e.ToolNameSet && e.ToolName == "" { + e.ToolName = old.ToolName + } + if !e.ToolSummarySet && e.ToolSummary == "" && e.ToolName == old.ToolName { + e.ToolSummary = old.ToolSummary + } + if !e.SummarySet && e.Summary == "" { + e.Summary = old.Summary + } +} diff --git a/internal/runtime/task_progress_cache_test.go b/internal/runtime/task_progress_cache_test.go new file mode 100644 index 0000000000..ba0284c1a7 --- /dev/null +++ b/internal/runtime/task_progress_cache_test.go @@ -0,0 +1,92 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +func TestTaskProgressCacheAdmissionRetainsGuardsAndDedup(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "hidden", Started: true, Hidden: true, State: TaskRunning, Label: "PRIVATE"}) + r.Handle(TaskProgressEvent{TaskID: "anchor", RunID: "r2", Started: true, State: TaskRunning, Label: "Anchor"}) + for task := range 17 { + id := fmt.Sprintf("task-%d", task) + r.Handle(TaskProgressEvent{TaskID: id, RunID: "r2", Started: true, State: TaskRunning, Label: id}) + for index := range maxTaskProgressAgentsPerTask + 10 { + r.Handle(TaskProgressEvent{TaskID: id, RunID: "r2", AgentIndex: index + 1, State: TaskRunning, Label: "Worker"}) + } + } + if len(r.progress.taskProgressSeen) > maxTaskProgressRows+maxTaskProgressEntries || len(r.progress.taskProgressRuns) > maxTaskProgressEntries { + t.Fatal("unbounded cache/control state") + } + before := out.String() + for _, row := range r.progress.taskProgressSeen { + if row.event.AgentIndex > 0 { + r.Handle(row.event) + } + } + r.Handle(TaskProgressEvent{TaskID: "hidden", State: TaskRunning, Label: "PRIVATE"}) + r.Handle(TaskProgressEvent{TaskID: "anchor", RunID: "r1", State: TaskCompleted}) + if out.String() != before { + t.Fatal("row admission pressure erased dedup/visibility/run controls") + } + r.Handle(TaskProgressEvent{TaskID: "anchor", State: TaskFailed, Update: true}) + if !strings.HasSuffix(out.String(), "Anchor — failed\n") { + t.Fatal("runless update lost label") + } + // Terminal parents release agents, keep their guards, and free admission + // for an existing task whose agents could not fit previously. + r.Handle(TaskProgressEvent{TaskID: "task-0", State: TaskCompleted, Update: true}) + before = out.String() + for range 100 { + r.Handle(TaskProgressEvent{TaskID: "task-0", State: TaskCompleted, Update: true}) + } + r.Handle(TaskProgressEvent{TaskID: "task-0", AgentIndex: 1, State: TaskCompleted, Label: "STALE"}) + r.Handle(TaskProgressEvent{TaskID: "task-0", AgentIndex: 2, State: TaskRunning, Label: "STALE"}) + if out.String() != before { + t.Fatal("terminal cleanup admitted late agents") + } + r.Handle(TaskProgressEvent{TaskID: "task-16", AgentIndex: 1, State: TaskRunning, Label: "Admitted"}) + if !strings.HasSuffix(out.String(), "Admitted — running\n") { + t.Fatal("terminal rows did not free capacity") + } +} + +func TestTaskProgressRelaunchRetiresSupersededRows(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for run := 1; run <= 4; run++ { + id := fmt.Sprintf("r%d", run) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, Started: true, State: TaskRunning, Label: "Current"}) + if len(r.progress.taskProgressSeen) != 1 { + t.Fatal("new generation retained superseded rows") + } + for index := range 1000 { + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, AgentIndex: index + 1, State: TaskRunning, Label: "Worker"}) + } + before := out.String() + for index := range 1000 { + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, AgentIndex: index + 1, State: TaskRunning, Label: "Worker"}) + } + if out.String() != before || len(r.progress.taskProgressSeen) != 1001 { + t.Fatal("relaunched workflow lost dedup") + } + } +} + +func TestTaskControlAdmissionNeverFlushesExistingTasks(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "hidden", Started: true, Hidden: true, State: TaskRunning, Label: "PRIVATE"}) + for index := range maxTaskProgressEntries + 10 { + r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(index), State: TaskRunning}) + } + before := out.String() + r.Handle(TaskProgressEvent{TaskID: "hidden", State: TaskRunning, Label: "PRIVATE"}) + if out.String() != before || len(r.progress.taskProgressRuns) != maxTaskProgressEntries { + t.Fatal("task admission evicted hidden control") + } +} diff --git a/internal/runtime/task_progress_message.go b/internal/runtime/task_progress_message.go new file mode 100644 index 0000000000..dcd55b8bab --- /dev/null +++ b/internal/runtime/task_progress_message.go @@ -0,0 +1,60 @@ +package runtime + +import "fmt" + +// taskProgressMessage formats only already-redacted, bounded display fields. +func taskProgressMessage(e TaskProgressEvent) string { + msg := "Task " + e.TaskID + if e.AgentIndex > 0 { + msg += fmt.Sprintf(" / agent #%d", e.AgentIndex) + if e.AgentID != "" { + msg += " (" + e.AgentID + ")" + } + } else if e.AgentID != "" { + msg += " / agent " + e.AgentID + } + if e.Phase != "" { + msg += " [" + e.Phase + "]" + } + if e.Label != "" { + msg += ": " + e.Label + } + if e.State != "" { + msg += " — " + string(e.State) + } else { + msg += " — updated" + } + if e.Blocked { + msg += " (blocked)" + } + if e.Cached { + msg += " (cached)" + } + if e.ToolName != "" { + msg += " (tool: " + e.ToolName + if e.ToolSummary != "" { + msg += ": " + e.ToolSummary + } + msg += ")" + } + if e.Attempt > 0 || e.LastAttemptReason != "" { + msg += " (" + if e.Attempt > 0 { + msg += fmt.Sprintf("attempt %d", e.Attempt) + } + if e.LastAttemptReason != "" { + if e.Attempt > 0 { + msg += "; " + } + msg += "retry: " + e.LastAttemptReason + } + msg += ")" + } + if e.Summary != "" && e.State == TaskRunning { + msg += " — " + e.Summary + } + if e.Detail != "" { + msg += " — " + e.Detail + } + return sanitizeOutput(msg) +} diff --git a/internal/runtime/task_progress_reconciler.go b/internal/runtime/task_progress_reconciler.go new file mode 100644 index 0000000000..d3c2fc0e16 --- /dev/null +++ b/internal/runtime/task_progress_reconciler.go @@ -0,0 +1,366 @@ +package runtime + +import ( + "crypto/sha256" + "slices" + "unicode/utf16" + "unicode/utf8" +) + +// Bound retained display state even if a runtime sends unlimited identities. +// Hashing IDs also avoids retaining arbitrarily large sandbox strings as keys. +const maxTaskProgressEntries = 1024 + +// Task controls outlive row retention. Overflow rows/tasks are not admitted; +// already tracked state is never flushed by an oversized snapshot. +const maxTaskProgressAgentsPerTask = 1024 +const maxTaskProgressRows = 16 * 1024 + +// Retain ordering text only when bounded and unchanged by sanitization and +// credential redaction. Non-comparable IDs cannot implicitly replace a run. +const maxTaskRunOrderBytes = 1024 + +type taskProgressRun struct { + watermark [sha256.Size]byte + hash [sha256.Size]byte + order string + named bool + agents int + parent taskProgressDisplay +} + +type taskProgressKey struct { + task, run, agent [sha256.Size]byte + index int +} + +type taskProgressDisplay struct { + event TaskProgressEvent + fingerprint [sha256.Size]byte +} + +func (r *progressReconciler) task(e TaskProgressEvent, redact func(string) string) (string, bool) { + if e.TaskID == "" || (e.State == "" && !e.Update) { + return "", false + } + key, accepted := r.taskProgressIdentity(&e, redact) + if !accepted { + return "", false + } + taskHash := key.task + current := r.taskProgressRuns[taskHash] + previous := r.taskProgressSeen[key] + parent := current.parent.event + isAgent := e.AgentID != "" || e.AgentIndex > 0 + if !isAgent { + previous = current.parent + } + // Parent lifecycle/visibility lives outside the agent dedup row budget. + if isAgent && terminalTaskState(parent.State) { + return "", false + } + if isAgent && staleAgentSnapshot(e, previous.event) { + return "", false + } + if isAgent && e.AgentState != "" { + reconcileAgentLifecycle(&e, previous.event) + } + resumable := isAgent && previous.event.State == TaskFailed && agentExecutionAdvanced(e, previous.event) + if !e.Started && (parent.Hidden || previous.event.Hidden || (e.State != "" && !terminalTaskState(e.State) && (terminalTaskState(parent.State) || (terminalTaskState(previous.event.State) && !resumable)))) { + return "", false + } + if isAgent { + if _, exists := r.taskProgressSeen[key]; !exists { + if current.agents >= maxTaskProgressAgentsPerTask || len(r.taskProgressSeen) >= maxTaskProgressRows { + return "", false + } + current.agents++ + r.taskProgressRuns[taskHash] = current + } + } + // Sanitize before retaining metadata, not just before printing it. This + // cache contains bounded display fields and hashed raw identities only. + e.TaskID = redactProgressText(e.TaskID, 80, redact) + e.RunID = redactProgressText(e.RunID, 80, redact) + e.AgentID = redactProgressText(e.AgentID, 80, redact) + e.Label = redactProgressText(e.Label, 160, redact) + e.Phase = redactProgressText(e.Phase, 80, redact) + e.ToolName = redactProgressText(e.ToolName, 50, redact) + e.ToolSummary = redactProgressText(e.ToolSummary, 160, redact) + e.Summary = redactProgressText(e.Summary, 200, redact) + e.Detail = redactProgressText(e.Detail, 200, redact) + e.LastAttemptReason = redactProgressText(e.LastAttemptReason, 60, redact) + e.State = TaskState(redactProgressText(string(e.State), 40, redact)) + e.AgentState = redactProgressText(e.AgentState, 40, redact) + if !e.Started { + old := previous.event + if e.Label == "" && !e.LabelSet { + e.Label = old.Label + } + if e.State == "" { + e.State = old.State + } + if e.Update && !e.DetailSet { + e.Detail = old.Detail + } + if e.AgentID != "" || e.AgentIndex > 0 { + mergeAgentProgress(&e, old) + } else { + mergeTaskProgress(&e, old) + } + if e.RunID == "" { + e.RunID = old.RunID + } + } + if terminalTaskState(e.State) || (isAgent && e.State != "" && e.State != TaskRunning) { + e.Summary = "" + } + if e.Hidden { + r.storeTaskProgress(key, taskProgressDisplay{event: e}, isAgent) + return "", false + } + msg := taskProgressMessage(e) + comparison := msg + if e.AgentIndex > 0 { + // An ID arriving late is attribution, not a second progress transition. + indexed := e + indexed.AgentID = "" + comparison = taskProgressMessage(indexed) + } else if e.AgentID == "" { + // A parent-task tool swap is attribution, not a progress + // transition: subagent tool calls already print as ToolUseEvents, + // so the row must not churn once per tool. Compare on tool + // presence rather than name; the retained event keeps the latest + // tool name for the next row that prints for a real reason. + toolless := e + toolless.ToolSummary = "" + if toolless.ToolName != "" { + toolless.ToolName = "tool" + } + comparison = taskProgressMessage(toolless) + } + // The assembled row can reconstruct a credential split across fields + // (fields are redacted individually; the joins are not), so the caller + // callback and the fallback scanner run on the joined text before the + // fingerprint and display, mirroring the status rows. + if redact != nil { + msg = redact(msg) + comparison = redact(comparison) + } + msg = scanProgressSecrets(msg) + comparison = scanProgressSecrets(comparison) + fingerprint := sha256.Sum256([]byte(comparison)) + r.storeTaskProgress(key, taskProgressDisplay{event: e, fingerprint: fingerprint}, isAgent) + if previous.fingerprint == fingerprint { + return "", false + } + return msg, true +} + +// Resolve optional run IDs. SDK 0.3.314 orders a task's run IDs by plain +// JavaScript string comparison. Reject superseded frames before changing any +// identity, visibility or dedup state. Anonymous restarts retain the previous +// named watermark until a newer name adopts the anonymous generation's rows. +func (r *progressReconciler) taskProgressIdentity(e *TaskProgressEvent, redact func(string) string) (taskProgressKey, bool) { + if r.taskProgressSeen == nil { + r.taskProgressSeen = make(map[taskProgressKey]taskProgressDisplay) + r.taskProgressRuns = make(map[[sha256.Size]byte]taskProgressRun) + } + task := sha256.Sum256([]byte(e.TaskID)) + if _, exists := r.taskProgressRuns[task]; !exists && len(r.taskProgressRuns) >= maxTaskProgressEntries { + return taskProgressKey{}, false + } + current := r.taskProgressRuns[task] + run := current.hash + zero := [sha256.Size]byte{} + order := "" + if e.RunID != "" { + run = sha256.Sum256([]byte(e.RunID)) + // Even an unorderable name cannot reclaim a newer anonymous run when + // its hash identifies the prior named generation exactly. + if current.named && current.hash == zero && run == current.watermark { + return taskProgressKey{}, false + } + order = r.taskRunOrder(e.RunID, redact) + if current.named && run != current.hash { + comparable := order != "" && current.order != "" + comparison := compareTaskRunIDs(order, current.order) + if (!e.Started && (!comparable || comparison <= 0)) || + (e.Started && comparable && (comparison < 0 || (current.hash == zero && comparison == 0))) { + return taskProgressKey{}, false + } + } + } + if e.Started { + r.retireTaskProgressRows(task, false) + current.parent = taskProgressDisplay{} + current.agents = 0 + if e.RunID == "" { + run = zero + current.hash = zero + } else { + current = taskProgressRun{hash: run, watermark: run, order: order, named: true} + } + } else if e.RunID != "" && current.hash != run { + if current.hash == zero { + // The first late ID promotes only this anonymous generation's rows. + for key, display := range r.taskProgressSeen { + if key.task == task && key.run == zero { + delete(r.taskProgressSeen, key) + key.run = run + r.taskProgressSeen[key] = display + } + } + } else { + r.retireTaskProgressRows(task, false) + current.parent = taskProgressDisplay{} + current.agents = 0 + } + current.hash = run + current.watermark = run + current.order = order + current.named = true + } + r.taskProgressRuns[task] = current + // Workflow entries are keyed by type:index in the producer. agentId is + // absent while queued and can also be omitted in subsequent snapshots. + agent := sha256.Sum256(nil) + index := e.AgentIndex + if index <= 0 { + index = 0 + agent = sha256.Sum256([]byte(e.AgentID)) + } + return taskProgressKey{task: task, run: run, agent: agent, index: index}, true +} + +func (r *progressReconciler) taskRunOrder(id string, redact func(string) string) string { + if len(id) > maxTaskRunOrderBytes || !utf8.ValidString(id) { + return "" + } + clean := redactProgressText(id, maxTaskRunOrderBytes, redact) + if clean != id { + return "" + } + return clean +} + +func compareTaskRunIDs(a, b string) int { + // Go compares UTF-8 bytes; the SDK's producer uses UTF-16 code units. + return slices.Compare(utf16.Encode([]rune(a)), utf16.Encode([]rune(b))) +} + +// mergeAgentProgress retains already-sanitized optional metadata when a +// snapshot only changes counters. Explicit empty/false fields can clear it. +// Error/blocked/cached metadata is state-relative: a transition drops omitted +// transient values instead of describing a recovered agent as still blocked. +func mergeAgentProgress(e *TaskProgressEvent, old TaskProgressEvent) { + advanced := agentExecutionAdvanced(*e, old) + if e.AgentState == "" { + mergeAgentLifecycle(e, old, advanced) + } + if e.AgentID == "" && !advanced { + e.AgentID = old.AgentID + } + if !e.PhaseSet && e.Phase == "" { + e.Phase = old.Phase + } + if !e.ToolNameSet && e.ToolName == "" && !advanced { + e.ToolName = old.ToolName + } + if !e.ToolSummarySet && e.ToolSummary == "" && e.ToolName == old.ToolName && !advanced { + e.ToolSummary = old.ToolSummary + } + sameState := e.State == old.State && !advanced + if !e.DetailSet && e.Detail == "" && sameState { + e.Detail = old.Detail + } + if !e.BlockedSet && !e.Blocked && sameState { + e.Blocked = old.Blocked + } + if !e.CachedSet && !e.Cached && sameState { + e.Cached = old.Cached + } +} + +// reconcileAgentLifecycle merges presence-aware lifecycle metadata before +// deriving display state. Fresh executions do not inherit prior-attempt data. +func reconcileAgentLifecycle(e *TaskProgressEvent, old TaskProgressEvent) { + advanced := agentExecutionAdvanced(*e, old) + mergeAgentLifecycle(e, old, advanced) + if !e.SkippedSet && !advanced && e.AgentState == old.AgentState { + e.Skipped = old.Skipped + } + switch e.AgentState { + case "start": + switch { + case e.QueuedAtSet && !e.StartedAtSet: + e.State = TaskQueued + case e.StartedAtSet && e.Attempt > 1: + e.State = TaskRetrying + default: + e.State = TaskRunning + } + case "progress": + e.State = TaskRunning + case "done": + e.State = TaskCompleted + case "error": + e.State = TaskFailed + if e.Skipped { + e.State = TaskSkipped + } + } +} + +// mergeAgentLifecycle retains optional numeric/retry metadata within one +// execution; callers determine advancement before filling omitted fields. +func mergeAgentLifecycle(e *TaskProgressEvent, old TaskProgressEvent, advanced bool) { + if !e.AttemptSet { + e.Attempt = old.Attempt + e.AttemptSet = old.AttemptSet + } + if !e.LastAttemptReasonSet && !advanced { + e.LastAttemptReason = old.LastAttemptReason + } + if !e.QueuedAtSet && !advanced { + e.QueuedAt = old.QueuedAt + e.QueuedAtSet = old.QueuedAtSet + } + if !e.StartedAtSet && e.State != TaskQueued && !advanced { + e.StartedAt = old.StartedAt + e.StartedAtSet = old.StartedAtSet + } +} + +// agentExecutionAdvanced permits an intermediate failed attempt to resume, +// while completed/skipped tasks and terminal parent workflows remain closed. +// The producer can also emit a fresh queue while waiting out a quota limit. +func agentExecutionAdvanced(e, old TaskProgressEvent) bool { + if e.AttemptSet && e.Attempt > 1 && e.Attempt > old.Attempt { + return true + } + if e.StartedAtSet && (old.StartedAtSet && e.StartedAt > old.StartedAt || !old.StartedAtSet && old.State == TaskFailed) { + return true + } + return e.State == TaskQueued && e.QueuedAtSet && (!old.QueuedAtSet || e.QueuedAt > old.QueuedAt) && (!old.StartedAtSet || e.QueuedAt > old.StartedAt) +} + +// staleAgentSnapshot rejects prior-attempt deliveries and a queued snapshot +// that predates the known execution. An index stays stable across attempts. +func staleAgentSnapshot(e, old TaskProgressEvent) bool { + if e.AttemptSet && old.AttemptSet && e.Attempt < old.Attempt { + return true + } + higherAttempt := e.AttemptSet && e.Attempt > old.Attempt + if old.QueuedAtSet && !old.StartedAtSet && !higherAttempt && ((e.QueuedAtSet && e.QueuedAt < old.QueuedAt) || (e.StartedAtSet && e.StartedAt < old.QueuedAt)) { + return true + } + if e.State == TaskQueued && e.QueuedAtSet && old.StartedAtSet && e.QueuedAt <= old.StartedAt && !higherAttempt { + return true + } + return e.StartedAtSet && old.StartedAtSet && e.StartedAt < old.StartedAt && !(e.AttemptSet && e.Attempt > old.Attempt) +} + +func terminalTaskState(state TaskState) bool { + return state == TaskCompleted || state == TaskFailed || state == TaskStopped || state == TaskSkipped +} diff --git a/internal/runtime/task_progress_test.go b/internal/runtime/task_progress_test.go new file mode 100644 index 0000000000..cffae5f1a6 --- /dev/null +++ b/internal/runtime/task_progress_test.go @@ -0,0 +1,174 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" + "unicode/utf8" + + "github.com/fullsend-ai/fullsend/internal/security" +) + +func TestTaskProgressRendererDeduplicates(t *testing.T) { + var console bytes.Buffer + r := newTestRenderer(&console) + e := TaskProgressEvent{TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "refine", Phase: "Refine", State: TaskRunning, ToolName: "Read"} + for range 135 { + r.Handle(e) + } + if lines := strings.Count(console.String(), "Task task-one"); lines != 1 { + t.Fatalf("repeated snapshots rendered %d times", lines) + } + e.ToolName = "Bash" + r.Handle(e) + e.State = TaskCompleted + r.Handle(e) + r.Handle(e) + if lines := strings.Count(console.String(), "Task task-one"); lines != 3 { + t.Fatalf("tool/state transitions should render exactly once: %s", console.String()) + } +} + +func TestTaskProgressRendererIdentityAndLifecycle(t *testing.T) { + var console bytes.Buffer + r := newTestRenderer(&console) + for _, e := range []TaskProgressEvent{ + {TaskID: "one", RunID: "first-run", AgentID: "worker", Label: "review", State: TaskRunning}, + {TaskID: "two", AgentID: "worker", Label: "review", State: TaskRunning}, + {TaskID: "one", AgentID: "different", Label: "review", State: TaskRunning}, + {TaskID: "one", AgentIndex: 1, Label: "review", State: TaskQueued}, + {TaskID: "one", AgentIndex: 2, Label: "review", State: TaskQueued}, + {TaskID: "one", AgentID: "worker", RunID: "second-run", Label: "review", State: TaskRunning}, + {TaskID: "one", State: TaskFailed}, + {TaskID: "two", State: TaskStopped}, + } { + r.Handle(e) + } + if lines := strings.Count(console.String(), "Task "); lines != 8 { + t.Fatalf("concurrent identities/statuses were lost: %s", console.String()) + } + for _, want := range []string{"agent #1", "agent #2", "failed", "stopped"} { + if !strings.Contains(console.String(), want) { + t.Errorf("missing %q: %s", want, console.String()) + } + } + before := console.String() + r.Handle(TaskProgressEvent{State: TaskRunning}) + r.Handle(TaskProgressEvent{TaskID: "one"}) + if console.String() != before { + t.Error("incomplete events must not render") + } +} + +func TestTaskProgressRendererBoundedState(t *testing.T) { + var console bytes.Buffer + r := newTestRenderer(&console) + for i := range maxTaskProgressEntries + 1 { + r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(i), State: TaskRunning}) + } + if len(r.progress.taskProgressSeen) > maxTaskProgressEntries || len(r.progress.taskProgressRuns) > maxTaskProgressEntries { + t.Fatalf("unbounded task/parent state: %d rows, %d controls", len(r.progress.taskProgressSeen), len(r.progress.taskProgressRuns)) + } +} + +func TestTaskProgressRendererRedactsAndSanitizes(t *testing.T) { + const opaque = "opaque-progress-credential-for-test" + security.RegisterRuntimeSecret(opaque) + // Generate a scanner-shaped dummy; no stored credential fixture. + token := "ghp_" + strings.Repeat("0", 36) + var console bytes.Buffer + r := newTestRenderer(&console) + r.Handle(TaskProgressEvent{ + TaskID: "id\n::error::" + opaque, + AgentID: token, Phase: "\x1b[31mCreate\x1b[0m", Label: "hello%0Aworld\r\n::warning::", + State: TaskRunning, ToolName: "Bash", ToolSummary: "token=" + token + " secret=" + opaque, + }) + output := console.String() + for _, forbidden := range []string{opaque, token, "\x1b", "::", "%0A", "\r"} { + if strings.Contains(output, forbidden) { + t.Errorf("unsafe field %q escaped sanitization: %q", forbidden, output) + } + } + if lines := strings.Count(output, "\n"); lines != 1 { + t.Errorf("sandbox text injected extra console lines: %q", output) + } + long := strings.Repeat("界", 200) + got := taskProgressText(long, 80) + if !utf8.ValidString(got) || utf8.RuneCountInString(got) != 81 || !strings.HasSuffix(got, "…") { + t.Errorf("invalid UTF-8 truncation: %q", got) + } + if got := taskProgressText(token, 10); strings.Contains(got, token[:10]) { + t.Errorf("credential was truncated before redaction: %q", got) + } +} + +func TestTaskProgressRendererCIAndBlockBoundary(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var console bytes.Buffer + r := newTestRenderer(&console) + r.Handle(TextEvent{Text: "before"}) + e := TaskProgressEvent{TaskID: "one", Label: "Create\n::error:: injected", State: TaskRunning} + stderr := captureStderr(t, func() { + r.Handle(e) + r.Handle(e) + }) + if strings.Count(stderr, "::notice::") != 1 || strings.Contains(stderr, "::error::") { + t.Errorf("expected one safe CI notice: %q", stderr) + } + if !strings.Contains(console.String(), "before\n") { + t.Errorf("task progress did not close the streaming block: %q", console.String()) + } +} + +func TestTaskProgressRendererCallerRedaction(t *testing.T) { + const secret = "opaque-runner-credential-for-test" + var console bytes.Buffer + r := newTestRenderer(&console) + r.RedactProgress = func(text string) string { + return strings.ReplaceAll(text, secret, "[REDACTED]") + } + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, + Label: secret + strings.Repeat("界", 200), ToolName: "Bash", ToolSummary: secret}) + if strings.Contains(console.String(), secret) || !strings.Contains(console.String(), "[REDACTED]") { + t.Errorf("caller-owned secret escaped redaction: %q", console.String()) + } +} + +func TestTaskProgressHiddenAgentCannotReplaceParent(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", AgentIndex: 1, State: TaskCompleted, Hidden: true, Label: "PRIVATE"}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "Visible parent"}) + r.Handle(TaskProgressEvent{TaskID: "one", AgentIndex: 1, State: TaskRunning, Label: "PRIVATE"}) + if strings.Contains(out.String(), "PRIVATE") || !strings.Contains(out.String(), "Visible parent — running") { + t.Fatal(out.String()) + } +} + +func TestTaskProgressIndexIdentityScopesAndIDFallback(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, e := range []TaskProgressEvent{ + {TaskID: "one", RunID: "first", AgentIndex: 1, AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "first", AgentIndex: 2, AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "two", RunID: "first", AgentIndex: 1, AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "second", AgentIndex: 1, AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "second", AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "second", AgentID: "fallback-a", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "second", AgentID: "fallback-b", Label: "Work", State: TaskRunning}, + } { + r.Handle(e) + } + if len(r.progress.taskProgressSeen) != 5 || strings.Count(out.String(), "— running") != 7 { + t.Fatal("distinct active slots/tasks/fallback IDs collapsed: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "second", AgentIndex: 1, AgentID: "learned", Label: "Work", State: TaskRunning}) + if len(r.progress.taskProgressSeen) != 5 || strings.Count(out.String(), "— running") != 7 { + t.Fatal("ID-only indexed change created another row") + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "second", AgentIndex: 1, Label: "Work", State: TaskCompleted}) + if !strings.Contains(out.String(), "agent #1 (learned): Work — completed") { + t.Fatal("known display ID was lost: " + out.String()) + } +}