Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): make cursor stream protocol drift loud instead of silent (MUL-5434) (#6089)
Multica Evede3e0ae55668
diff --git a/server/pkg/agent/cursor.go b/server/pkg/agent/cursor.goindex 68846607a9..bc9e19197c 100644--- a/server/pkg/agent/cursor.go+++ b/server/pkg/agent/cursor.go@@ -115,12 +115,23 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptinvalidEventCount := 0assistantEventCount := 0toolUseCount := 0- // unknownSubtypeCount tracks thinking/tool_call events whose subtype we+ // unhandledSubtypeCount tracks thinking/tool_call events whose subtype we// don't recognize. They are ignored (never synthesized into a message)// and surfaced once as a bounded, content-free diagnostic so an upstream// protocol addition is visible instead of silent.- unknownSubtypeCount := 0+ unhandledSubtypeCount := 0+ // unhandledTypes tracks top-level event types the switch below does not+ // handle. See cursorUnhandledTypeTally: it makes a dropped event+ // observable, and documents what the count does and does not establish+ // (MUL-5434).+ var unhandledTypes cursorUnhandledTypeTallylastEventType := "none"+ // assistantBytes counts only model-authored streamed text. It is kept+ // separate from `output` because the result event also writes into+ // `output`, which made the reported last_assistant_bytes equal to+ // result_bytes on a run where the assistant streamed nothing at all —+ // hiding the exact signal needed to tell those two cases apart.+ assistantBytes := 0// stepUsage accumulates per-step token counts from "step_finish" events.// resultUsage holds authoritative session totals from "result" events.// If the result event includes usage, we use resultUsage exclusively;@@ -167,7 +178,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptcase "assistant":assistantEventCount++- b.handleCursorAssistant(&evt, msgCh, &output)+ assistantBytes += b.handleCursorAssistant(&evt, msgCh, &output)case "thinking":// Reasoning is a top-level event streamed as deltas, not a@@ -185,7 +196,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptcase "completed":thinking.complete()default:- unknownSubtypeCount+++ unhandledSubtypeCount++}case "tool_call":@@ -215,7 +226,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptOutput: call.Result,})default:- unknownSubtypeCount+++ unhandledSubtypeCount++}case "tool_use":@@ -272,6 +283,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOpt_ = json.Unmarshal(evt.Part, &part)if part.Text != "" {output.WriteString(part.Text)+ assistantBytes += len(part.Text)trySend(msgCh, Message{Type: MessageText, Content: part.Text})}}@@ -287,6 +299,26 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptu.CacheReadTokens += int64(part.Tokens.Cache.Read)stepUsage[model] = u}++ default:+ // A top-level type this parser does not handle. Falling through+ // here used to be completely silent, and that silence is the+ // bug: if the CLI renames `tool_call` or `thinking`, every tool+ // and reasoning row vanishes while the run still reports+ // success and tool_use_count=0, with no diagnostic to+ // distinguish that from a tool-free run (MUL-5434).+ //+ // Counting makes the drop observable. It does not identify the+ // cause on its own — see cursorUnhandledTypeTally for what a+ // non-zero and a zero tally each do and do not establish.+ //+ // Counting is also all we do. An unrecognized event is never+ // coerced into a tool or reasoning message: guessing at+ // upstream additions is the failure mode MUL-5231 already+ // fixed once.+ if !cursorNonTranscriptEventType(evt.Type) {+ unhandledTypes.observe(evt.Type)+ }}}scanErr := scanner.Err()@@ -363,27 +395,41 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}logStreamProtocolObservation(b.cfg.Logger, streamProtocolObservation{- provider: "cursor-agent",- cliVersion: b.cfg.CLIVersion,- model: opts.Model,- exitCode: streamProcessExitCode(exitErr),- eventCount: eventCount,- invalidEventCount: invalidEventCount,- assistantEventCount: assistantEventCount,- toolUseCount: toolUseCount,- sawResult: resultSeen,- resultIsError: resultIsError,- resultBytes: resultBytes,- lastAssistantBytes: output.Len(),- scannerError: scanErr != nil && !resultSeen,- lastEventType: lastEventType,+ provider: "cursor-agent",+ cliVersion: b.cfg.CLIVersion,+ model: opts.Model,+ exitCode: streamProcessExitCode(exitErr),+ eventCount: eventCount,+ invalidEventCount: invalidEventCount,+ assistantEventCount: assistantEventCount,+ toolUseCount: toolUseCount,+ sawResult: resultSeen,+ resultIsError: resultIsError,+ resultBytes: resultBytes,+ lastAssistantBytes: assistantBytes,+ scannerError: scanErr != nil && !resultSeen,+ lastEventType: lastEventType,+ unhandledEventTypeCount: unhandledTypes.total,+ unhandledEventTypes: unhandledTypes.summary(),+ unhandledSubtypeCount: unhandledSubtypeCount,})- if unknownSubtypeCount > 0 {+ if unhandledSubtypeCount > 0 {// Content-free and emitted once per run: signals that the CLI sent a// thinking/tool_call subtype we chose to ignore, so a protocol// addition is diagnosable without the parser having guessed at it.- b.cfg.Logger.Warn("cursor-agent ignored unknown event subtypes", "count", unknownSubtypeCount)+ b.cfg.Logger.Warn("cursor-agent ignored unhandled event subtypes", "count", unhandledSubtypeCount)+ }++ if unhandledTypes.total > 0 {+ // Same contract one level up, and the broader signal of the two: an+ // unhandled top-level type means whole events never reached the+ // transcript. What was in them is not decided here — the type names+ // are the starting point for that, not the conclusion.+ b.cfg.Logger.Warn("cursor-agent ignored unhandled event types",+ "count", unhandledTypes.total,+ "types", unhandledTypes.summary(),+ )}b.cfg.Logger.Info("cursor-agent finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())@@ -443,25 +489,124 @@ func observedCursorEventType(value string) string {return value}-func (b *cursorBackend) handleCursorAssistant(evt *cursorStreamEvent, ch chan<- Message, output *strings.Builder) {+// cursorNonTranscriptEventTypes are top-level events that are known to exist,+// carry nothing the transcript needs, and are therefore NOT reported as+// protocol drift. Dropping them is the behaviour that already shipped; listing+// them here only keeps them out of the diagnostic, because a warning that fires+// on every task is a warning nobody reads.+//+// Provenance differs per entry and matters when revisiting this list:+// - `user` — the CLI echoing our own prompt back. Confirmed present in the+// recorded 2026.07.20 stream, i.e. in every real run.+// - `connection`, `retry` — transport/control frames reported on newer CLI+// builds (MUL-5434 review). Not reproduced locally, so they are listed+// defensively: if a build does not emit them the entry is inert, and if it+// does we must not call a known control frame an unhandled protocol event.+//+// An entry here is a claim that the type carries no transcript content. Do not+// add a type merely to silence the warning.+var cursorNonTranscriptEventTypes = map[string]struct{}{+ "user": {},+ "connection": {},+ "retry": {},+}++func cursorNonTranscriptEventType(eventType string) bool {+ _, ok := cursorNonTranscriptEventTypes[strings.TrimSpace(eventType)]+ return ok+}++// cursorUnhandledTypeCardinalityCap bounds how many distinct type names the+// tally retains. A stream emitting novel type names (or garbage that still+// parses as JSON) must not grow the map without limit inside a long-running+// daemon; names past the cap collapse into one overflow bucket.+const cursorUnhandledTypeCardinalityCap = 16++// cursorUnhandledTypeOverflowKey holds the counts that exceeded the cardinality+// cap. The parentheses cannot collide with a real type name: observedCursorEventType+// only ever returns identifier characters, "unknown", or "invalid".+const cursorUnhandledTypeOverflowKey = "(overflow)"++// cursorUnhandledTypeTally counts top-level event types this parser does not+// handle, so that dropping them stops being silent. Before it existed a renamed+// `tool_call` fell through the type switch and the run reported success with+// tool_use_count=0 and no diagnostic whatsoever (MUL-5434).+//+// Read it as evidence, not as a verdict — in both directions:+//+// - A non-zero tally shows the stream carried top-level events we do not+// handle. Which events, and whether they are what the transcript lost,+// still has to be established from the type names, invalid_event_count and+// ultimately a captured stream.+// - A zero tally shows only that no unhandled top-level type was observed. It+// does NOT establish that the model used no tools: the CLI may have executed+// tools without handing the updates to its stream serializer at all, a new+// shape may be nested inside an event type we already recognize (e.g. an+// assistant content block), or the events may have been lost to invalid+// framing or a scanner boundary. Those branches are open on #6071.+//+// Only normalized identifiers and counts are retained, never payload content,+// so the tally is safe to log beside the rest of the protocol summary.+type cursorUnhandledTypeTally struct {+ total int+ counts map[string]int+}++func (t *cursorUnhandledTypeTally) observe(eventType string) {+ t.total+++ if t.counts == nil {+ t.counts = make(map[string]int, 4)+ }+ key := observedCursorEventType(eventType)+ if _, seen := t.counts[key]; !seen && len(t.counts) >= cursorUnhandledTypeCardinalityCap {+ key = cursorUnhandledTypeOverflowKey+ }+ t.counts[key]+++}++// summary renders the tally as a stable, sorted "name=count" list (e.g.+// "reasoning=9,tool_calls=6") so it can be grepped and diffed across runs.+func (t *cursorUnhandledTypeTally) summary() string {+ if len(t.counts) == 0 {+ return ""+ }+ keys := make([]string, 0, len(t.counts))+ for key := range t.counts {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ parts := make([]string, 0, len(keys))+ for _, key := range keys {+ parts = append(parts, fmt.Sprintf("%s=%d", key, t.counts[key]))+ }+ return strings.Join(parts, ",")+}++// handleCursorAssistant forwards one assistant event's content blocks and+// returns how many bytes of model-authored text it appended to output. The+// caller tracks that separately from output.Len(), which also absorbs the+// terminal result text.+func (b *cursorBackend) handleCursorAssistant(evt *cursorStreamEvent, ch chan<- Message, output *strings.Builder) int {if evt.Message == nil {- return+ return 0}var content cursorAssistantMessageif err := json.Unmarshal(evt.Message, &content); err != nil {- return+ return 0}// Note: per-message usage in assistant events is intentionally ignored.// Token usage is taken exclusively from "result" events (session totals)// to avoid double-counting.+ written := 0for _, block := range content.Content {switch block.Type {case "output_text", "text":if block.Text != "" {output.WriteString(block.Text)+ written += len(block.Text)trySend(ch, Message{Type: MessageText, Content: block.Text})}case "thinking":@@ -481,6 +626,7 @@ func (b *cursorBackend) handleCursorAssistant(evt *cursorStreamEvent, ch chan<-})}}+ return written}// cursorThinkingStream turns the CLI's `thinking` event sequence into thediff --git a/server/pkg/agent/cursor_stream_fixture_unix_test.go b/server/pkg/agent/cursor_stream_fixture_unix_test.goindex e0c0154c11..20d6d0601f 100644--- a/server/pkg/agent/cursor_stream_fixture_unix_test.go+++ b/server/pkg/agent/cursor_stream_fixture_unix_test.go@@ -3,6 +3,7 @@package agentimport (+ "bytes""fmt""log/slog""path/filepath"@@ -249,3 +250,203 @@ func TestCursorExecuteIgnoresUnknownSubtypes(t *testing.T) {func shellSingleQuote(s string) string {return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"}++// runCursorStreamLines replays the given NDJSON lines through the real cursor+// backend and returns the messages, the result, and everything the backend+// logged.+func runCursorStreamLines(t *testing.T, lines []string) ([]Message, Result, string) {+ t.Helper()++ script := "#!/bin/sh\n"+ for _, line := range lines {+ script += fmt.Sprintf("printf '%%s\\n' %s\n", shellSingleQuote(line))+ }++ fakePath := filepath.Join(t.TempDir(), "cursor-agent")+ writeTestExecutable(t, fakePath, []byte(script))++ var logBuf bytes.Buffer+ logger := slog.New(slog.NewTextHandler(&logBuf, nil))++ backend, err := New("cursor", Config{ExecutablePath: fakePath, Logger: logger})+ if err != nil {+ t.Fatalf("New(cursor): %v", err)+ }+ session, err := backend.Execute(t.Context(), "hello", ExecOptions{Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }++ var messages []Message+ done := make(chan struct{})+ go func() {+ defer close(done)+ for msg := range session.Messages {+ messages = append(messages, msg)+ }+ }()+ result := <-session.Result+ <-done++ return messages, result, logBuf.String()+}++func countCursorMessageTypes(messages []Message) map[MessageType]int {+ counts := make(map[MessageType]int)+ for _, msg := range messages {+ counts[msg.Type]+++ }+ return counts+}++// TestCursorExecuteReportsUnhandledTopLevelTypes is the MUL-5434 regression.+//+// Reported symptom: a Cursor run that demonstrably used tools produced a single+// blob of agent text, tools=0, no reasoning — and not one diagnostic. This test+// reproduces that exact stream shape by renaming only the top-level event types+// (`thinking`→`reasoning`, `tool_call`→`tool_calls`) and leaving every nested+// field untouched, which is what an upstream protocol rename looks like.+//+// The parser must still refuse to guess: no tool or reasoning message may be+// synthesized from an event it does not recognize. What it must NOT do is stay+// silent — a silent drop leaves no trace at all, which is what made the original+// report impossible to triage from logs.+//+// This asserts only that the signal exists and that nothing is fabricated. The+// tally is deliberately not treated as a verdict on WHY the transcript is empty;+// see cursorUnhandledTypeTally for the branches it cannot rule out.+func TestCursorExecuteReportsUnhandledTopLevelTypes(t *testing.T) {+ t.Parallel()++ lines := []string{+ `{"type":"system","subtype":"init","session_id":"sess-drift"}`,+ `{"type":"reasoning","subtype":"delta","text":"reasoning under a renamed type"}`,+ `{"type":"tool_calls","subtype":"started","call_id":"call-y","tool_call":{"readToolCall":{"args":{"path":"/y"}},"toolCallId":"call-y"}}`,+ `{"type":"tool_calls","subtype":"completed","call_id":"call-y","tool_call":{"readToolCall":{"args":{"path":"/y"},"result":{"success":{}}},"toolCallId":"call-y"}}`,+ `{"type":"toolCall","subtype":"started","call_id":"call-z","tool_call":{"readToolCall":{"args":{"path":"/z"}},"toolCallId":"call-z"}}`,+ `{"type":"result","subtype":"success","is_error":false,"result":"single blob","session_id":"sess-drift"}`,+ }++ messages, result, logs := runCursorStreamLines(t, lines)++ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed; error=%q", result.Status, result.Error)+ }++ // Unrecognized events are never coerced into transcript rows.+ counts := countCursorMessageTypes(messages)+ if counts[MessageToolUse] != 0 || counts[MessageToolResult] != 0 {+ t.Errorf("unhandled types synthesized tool rows: tool_use=%d tool_result=%d",+ counts[MessageToolUse], counts[MessageToolResult])+ }+ if counts[MessageThinking] != 0 {+ t.Errorf("unhandled type folded into reasoning: thinking=%d", counts[MessageThinking])+ }++ // ...but the drop is now observable, and names the events that were dropped.+ if !strings.Contains(logs, "cursor-agent ignored unhandled event types") {+ t.Fatalf("no unhandled-type warning emitted; logs:\n%s", logs)+ }+ for _, want := range []string{`count=4`, `reasoning=1`, `toolCall=1`, `tool_calls=2`} {+ if !strings.Contains(logs, want) {+ t.Errorf("warning/summary missing %q; logs:\n%s", want, logs)+ }+ }++ // The tally is also on the structured summary line, next to the other+ // protocol counters an operator has to weigh alongside it.+ if !strings.Contains(logs, "unhandled_event_type_count=4") {+ t.Errorf("protocol summary missing unhandled_event_type_count=4; logs:\n%s", logs)+ }+ if !strings.Contains(logs, "tool_use_count=0") {+ t.Errorf("protocol summary missing tool_use_count=0; logs:\n%s", logs)+ }+}++// TestCursorExecuteDoesNotWarnOnHealthyStream guards the other half of the fix:+// the warning has to stay quiet on a run with nothing wrong with it. Top-level+// `user` (the CLI echoing our prompt, present in every recorded run) and the+// `connection` / `retry` control frames carry no transcript content and are+// dropped by design — if those counted as drift the warning would fire on every+// task and stop meaning anything.+func TestCursorExecuteDoesNotWarnOnHealthyStream(t *testing.T) {+ t.Parallel()++ lines := []string{+ `{"type":"system","subtype":"init","session_id":"sess-ok"}`,+ `{"type":"user","message":{"role":"user","content":[{"type":"text","text":"hello"}]}}`,+ `{"type":"connection","subtype":"reconnecting"}`,+ `{"type":"retry","subtype":"scheduled"}`,+ `{"type":"thinking","subtype":"delta","text":"thinking"}`,+ `{"type":"thinking","subtype":"completed"}`,+ `{"type":"tool_call","subtype":"started","call_id":"call-a","tool_call":{"readToolCall":{"args":{"path":"/a"}},"toolCallId":"call-a"}}`,+ `{"type":"tool_call","subtype":"completed","call_id":"call-a","tool_call":{"readToolCall":{"args":{"path":"/a"},"result":{"success":{}}},"toolCallId":"call-a"}}`,+ `{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"sess-ok"}`,+ }++ messages, result, logs := runCursorStreamLines(t, lines)++ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed; error=%q", result.Status, result.Error)+ }+ if strings.Contains(logs, "cursor-agent ignored unhandled event types") {+ t.Errorf("unhandled-type warning fired on a healthy stream; logs:\n%s", logs)+ }+ if !strings.Contains(logs, "unhandled_event_type_count=0") {+ t.Errorf("protocol summary should report unhandled_event_type_count=0; logs:\n%s", logs)+ }+ // Suppressing the warning must not have suppressed the real rows: the+ // known-good `thinking` / `tool_call` events still reach the transcript.+ counts := countCursorMessageTypes(messages)+ if counts[MessageToolUse] != 1 || counts[MessageToolResult] != 1 || counts[MessageThinking] != 1 {+ t.Errorf("healthy stream lost rows: tool_use=%d tool_result=%d thinking=%d",+ counts[MessageToolUse], counts[MessageToolResult], counts[MessageThinking])+ }+}++// TestCursorLastAssistantBytesExcludesResultText pins the second half of+// MUL-5434's diagnostic gap. The result event writes its text into the same+// builder as assistant text, so the summary used to report+// last_assistant_bytes == result_bytes even when the assistant streamed+// nothing — erasing the one signal that says "no incremental output arrived,+// only the final answer", which is precisely the reported failure.+func TestCursorLastAssistantBytesExcludesResultText(t *testing.T) {+ t.Parallel()++ t.Run("result only", func(t *testing.T) {+ t.Parallel()+ _, result, logs := runCursorStreamLines(t, []string{+ `{"type":"system","subtype":"init","session_id":"sess-blob"}`,+ `{"type":"result","subtype":"success","is_error":false,"result":"0123456789","session_id":"sess-blob"}`,+ })+ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed; error=%q", result.Status, result.Error)+ }+ if !strings.Contains(logs, "result_bytes=10") {+ t.Errorf("summary missing result_bytes=10; logs:\n%s", logs)+ }+ if !strings.Contains(logs, "last_assistant_bytes=0") {+ t.Errorf("assistant streamed nothing, so last_assistant_bytes must be 0; logs:\n%s", logs)+ }+ })++ t.Run("assistant text counted", func(t *testing.T) {+ t.Parallel()+ _, result, logs := runCursorStreamLines(t, []string{+ `{"type":"system","subtype":"init","session_id":"sess-text"}`,+ `{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"abcde"}]}}`,+ `{"type":"result","subtype":"success","is_error":false,"result":"0123456789","session_id":"sess-text"}`,+ })+ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed; error=%q", result.Status, result.Error)+ }+ // The result text is NOT appended (output is already non-empty), and the+ // assistant's own 5 bytes are what gets reported.+ if !strings.Contains(logs, "last_assistant_bytes=5") {+ t.Errorf("summary should report the assistant's 5 bytes; logs:\n%s", logs)+ }+ if result.Output != "abcde" {+ t.Errorf("output = %q, want %q", result.Output, "abcde")+ }+ })+}diff --git a/server/pkg/agent/cursor_test.go b/server/pkg/agent/cursor_test.goindex a144948821..6151765b25 100644--- a/server/pkg/agent/cursor_test.go+++ b/server/pkg/agent/cursor_test.go@@ -2,6 +2,7 @@ package agentimport ("encoding/json"+ "fmt""log/slog""strings""testing"@@ -841,3 +842,111 @@ func TestCursorToolPayloadKeyIsDeterministic(t *testing.T) {t.Fatalf("key without a tool payload = %q, want empty", got)}}++// TestCursorUnhandledTypeTallySummary pins the rendering the daemon log depends+// on: sorted so it diffs cleanly across runs, and "name=count" so an operator+// can see at a glance which event went missing and how often.+func TestCursorUnhandledTypeTallySummary(t *testing.T) {+ t.Parallel()++ var tally cursorUnhandledTypeTally+ if got := tally.summary(); got != "" {+ t.Errorf("empty tally summary = %q, want %q", got, "")+ }+ if tally.total != 0 {+ t.Errorf("empty tally total = %d, want 0", tally.total)+ }++ for _, eventType := range []string{"tool_calls", "reasoning", "tool_calls", "reasoning", "tool_calls"} {+ tally.observe(eventType)+ }+ if want := "reasoning=2,tool_calls=3"; tally.summary() != want {+ t.Errorf("summary = %q, want %q", tally.summary(), want)+ }+ if tally.total != 5 {+ t.Errorf("total = %d, want 5", tally.total)+ }+}++// TestCursorUnhandledTypeTallyNormalizesKeys keeps the tally content-free: a type+// value carrying punctuation or arbitrary length must not be copied into daemon+// logs verbatim, it collapses to the same bounded labels observedCursorEventType+// produces everywhere else.+func TestCursorUnhandledTypeTallyNormalizesKeys(t *testing.T) {+ t.Parallel()++ var tally cursorUnhandledTypeTally+ tally.observe("")+ tally.observe(" ")+ tally.observe("tool call with spaces")+ tally.observe(strings.Repeat("x", 65))++ if want := "invalid=2,unknown=2"; tally.summary() != want {+ t.Errorf("summary = %q, want %q", tally.summary(), want)+ }+}++// TestCursorUnhandledTypeTallyBoundsCardinality guards the daemon against a+// stream that emits an unbounded set of novel type names: the map must stop+// growing at the cap and fold the rest into the overflow bucket, while the+// total still counts every event.+func TestCursorUnhandledTypeTallyBoundsCardinality(t *testing.T) {+ t.Parallel()++ var tally cursorUnhandledTypeTally+ const extra = 50+ for i := 0; i < cursorUnhandledTypeCardinalityCap+extra; i++ {+ tally.observe(fmt.Sprintf("type-%03d", i))+ }++ if len(tally.counts) != cursorUnhandledTypeCardinalityCap+1 {+ t.Errorf("distinct keys = %d, want %d (cap + overflow bucket)",+ len(tally.counts), cursorUnhandledTypeCardinalityCap+1)+ }+ if got := tally.counts[cursorUnhandledTypeOverflowKey]; got != extra {+ t.Errorf("overflow bucket = %d, want %d", got, extra)+ }+ if tally.total != cursorUnhandledTypeCardinalityCap+extra {+ t.Errorf("total = %d, want %d", tally.total, cursorUnhandledTypeCardinalityCap+extra)+ }+ // A capped key already in the map keeps accumulating under its own name.+ tally.observe("type-000")+ if got := tally.counts["type-000"]; got != 2 {+ t.Errorf("known key count = %d, want 2", got)+ }+ // The overflow label cannot be produced by normalizing a real type name, so+ // a stream cannot forge counts into the bucket.+ if observedCursorEventType(cursorUnhandledTypeOverflowKey) != "invalid" {+ t.Errorf("overflow key %q is collidable with a real type name", cursorUnhandledTypeOverflowKey)+ }+}++// TestCursorNonTranscriptEventType pins which unhandled types must stay silent.+// `user` is the CLI echoing our own prompt and appears in every run; `connection`+// and `retry` are transport control frames. None carry transcript content, so+// tallying them would make the warning fire always, which is the same as never.+func TestCursorNonTranscriptEventType(t *testing.T) {+ t.Parallel()++ for _, eventType := range []string{"user", "connection", "retry"} {+ if !cursorNonTranscriptEventType(eventType) {+ t.Errorf("%q must be non-transcript; it carries nothing the transcript needs", eventType)+ }+ }+ for _, eventType := range []string{"tool_calls", "reasoning", "toolCall", ""} {+ if cursorNonTranscriptEventType(eventType) {+ t.Errorf("%q must NOT be suppressed — it has to be reported as unhandled", eventType)+ }+ }+ // The suppression list must never shadow a type the parser actually handles,+ // otherwise silencing the diagnostic would silence the transcript too.+ handled := []string{+ "system", "assistant", "thinking", "tool_call", "tool_use",+ "tool_result", "result", "error", "text", "step_finish",+ }+ for _, eventType := range handled {+ if cursorNonTranscriptEventType(eventType) {+ t.Errorf("%q is handled by the parser and must not be in the suppression list", eventType)+ }+ }+}diff --git a/server/pkg/agent/stream_json_result.go b/server/pkg/agent/stream_json_result.goindex 43cd7e9ccb..51b31e7950 100644--- a/server/pkg/agent/stream_json_result.go+++ b/server/pkg/agent/stream_json_result.go@@ -102,6 +102,21 @@ type streamProtocolObservation struct {scannerError boollastEventType stringanthropicBaseURLConfigured bool+ // unhandledEventTypeCount / unhandledEventTypes / unhandledSubtypeCount+ // report stream events the parser did not turn into messages. They belong on+ // this line rather than only in a separate warning so they can be read+ // together with toolUseCount and invalidEventCount.+ //+ // They are evidence, not a verdict. A non-zero count means the stream+ // carried events we do not handle and is the starting point for identifying+ // a protocol change; a zero count means only that none were observed at the+ // top level, and does not establish that the agent used no tools — a CLI can+ // execute tools without serializing the updates at all, and a new shape can+ // be nested inside a type we already recognize. Set by providers that track+ // them; zero elsewhere.+ unhandledEventTypeCount int+ unhandledEventTypes string+ unhandledSubtypeCount int}// logStreamProtocolObservation records only protocol metadata. It deliberately@@ -124,6 +139,9 @@ func logStreamProtocolObservation(logger *slog.Logger, obs streamProtocolObserva"last_assistant_bytes", obs.lastAssistantBytes,"scanner_error", obs.scannerError,"last_event_type", obs.lastEventType,+ "unhandled_event_type_count", obs.unhandledEventTypeCount,+ "unhandled_event_types", obs.unhandledEventTypes,+ "unhandled_subtype_count", obs.unhandledSubtypeCount,"anthropic_base_url_configured", obs.anthropicBaseURLConfigured,)}