Skip to content

Commit df828c0

Browse files
authored
Stop false stale-send guard after tool-call turns (#2115)
## Description The chat send guard falsely blocked the next message with "New messages loaded — please review before sending" on essentially every turn after the first — sending twice was needed each time. It surfaced first on a tool-call turn, but the root cause affects every agent response. ## Root cause A2A marks per-message `contextId`/`taskId` as optional — the `Task` is the canonical carrier, so persisted history messages routinely store them as empty strings. After a turn completes the UI keeps the locally-streamed message copies (it does not reload from the backend), and those carry the task's real `contextId`/`taskId`, so the send guard keys them as `["task", contextId, taskId, contentSignature]`. The backend-extracted copies, with empty ids, fall back to `["message", <id>]` instead — and for converted tool messages that id is even regenerated (`uuidv4`) on every extraction. So a persisted agent message never matches its locally-streamed counterpart, the guard counts the backend as ahead of the local view, and blocks the send. Every turn has an agent response, so every send after the first tripped it. ## Fix Carry `contextId`/`taskId` on agent messages so the streamed and persisted copies key identically. Two layers: - **UI** (`ui/src/lib/messageHandlers.ts`): when flattening `task.history`, backfill `contextId`/`taskId` from the task for **every** extracted agent message (text and tool), treating `""` as absent (`||`, not `??`). This is the complete fix on its own — it repairs already-persisted sessions and works regardless of which runtime produced them. - **Runtime** (source, defense-in-depth, helps new sessions): stamp `contextId`/`taskId` onto agent messages at emission time, in both producers — Python `kagent-adk` (`convert_event_to_a2a_message`) and the Go ADK executor, now the default declarative runtime (`go/adk/pkg/a2a/executor.go`, via a `newAgentStatusEvent` seam). A2A allows omission, and remote agents are out of our control, so the UI backfill stays regardless. Scope is limited to agent messages; user messages are keyed by `messageId` and already match. ## Reproduction <img width="402" height="301" alt="image (7)" src="https://github.com/user-attachments/assets/136d194d-c195-4ba7-8319-9fc729a5a59d" /> 1. Send a message that triggers a tool call. 2. Send another message → blocked by the stale-send banner with no actual change. --------- Signed-off-by: Jeremy Alvis <[email protected]>
1 parent e0f6664 commit df828c0

6 files changed

Lines changed: 235 additions & 21 deletions

File tree

‎go/adk/pkg/a2a/executor.go‎

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,33 @@ func (u *userIDInterceptor) Before(ctx context.Context, callCtx *a2asrv.CallCont
100100
return ctx, nil
101101
}
102102

103+
// newAgentMessage builds an agent message stamped with the request's context
104+
// and task ids. A2A allows omitting these (the task is the canonical carrier),
105+
// but stamping them lets consumers that flatten task.history into standalone
106+
// messages key each message to its task without backfilling. Mirrors the Python
107+
// kagent-adk event converter.
108+
func newAgentMessage(reqCtx *a2asrv.RequestContext, parts ...a2atype.Part) *a2atype.Message {
109+
msg := a2atype.NewMessage(a2atype.MessageRoleAgent, parts...)
110+
msg.ContextID = reqCtx.ContextID
111+
msg.TaskID = reqCtx.TaskID
112+
return msg
113+
}
114+
115+
// newAgentStatusEvent builds a working TaskStatusUpdateEvent whose agent message
116+
// carries the given parts, the given metadata, and the request's context/task
117+
// ids (via newAgentMessage). The message and event share the same metadata map,
118+
// matching the executor's emission paths. This is the per-event seam where a
119+
// streamed agent message is turned into an emitted (and persisted) event, so the
120+
// id stamping here is what the send guard relies on when it later flattens
121+
// task.history.
122+
func newAgentStatusEvent(reqCtx *a2asrv.RequestContext, parts a2atype.ContentParts, meta map[string]any) *a2atype.TaskStatusUpdateEvent {
123+
msg := newAgentMessage(reqCtx, parts...)
124+
msg.Metadata = meta
125+
statusEv := a2atype.NewStatusUpdateEvent(reqCtx, a2atype.TaskStateWorking, msg)
126+
statusEv.Metadata = meta
127+
return statusEv
128+
}
129+
103130
// Execute implements a2asrv.AgentExecutor.
104131
// It follows the Python _handle_request pattern: set up session, handle HITL,
105132
// convert inbound message, run the agent loop, and emit A2A events.
@@ -266,7 +293,7 @@ func (e *KAgentExecutor) Execute(ctx context.Context, reqCtx *a2asrv.RequestCont
266293
// Events with no content carry metadata only; still track invocationID/usage.
267294
// Check for LLM error.
268295
if adkEvent.ErrorCode != "" {
269-
errMsg := a2atype.NewMessage(a2atype.MessageRoleAgent,
296+
errMsg := newAgentMessage(reqCtx,
270297
a2atype.TextPart{Text: fmt.Sprintf("LLM error: %s %s", adkEvent.ErrorCode, adkEvent.ErrorMessage)})
271298
failed := a2atype.NewStatusUpdateEvent(reqCtx, a2atype.TaskStateFailed, errMsg)
272299
failed.Final = true
@@ -278,7 +305,7 @@ func (e *KAgentExecutor) Execute(ctx context.Context, reqCtx *a2asrv.RequestCont
278305

279306
// Check for LLM error (even with content present).
280307
if adkEvent.ErrorCode != "" {
281-
errMsg := a2atype.NewMessage(a2atype.MessageRoleAgent,
308+
errMsg := newAgentMessage(reqCtx,
282309
a2atype.TextPart{Text: fmt.Sprintf("LLM error: %s %s", adkEvent.ErrorCode, adkEvent.ErrorMessage)})
283310
failed := a2atype.NewStatusUpdateEvent(reqCtx, a2atype.TaskStateFailed, errMsg)
284311
failed.Final = true
@@ -326,10 +353,7 @@ func (e *KAgentExecutor) Execute(ctx context.Context, reqCtx *a2asrv.RequestCont
326353
if len(textOnly) > 0 {
327354
mirrorMeta := maps.Clone(eventMeta)
328355
mirrorMeta[adka2a.ToA2AMetaKey("partial")] = true
329-
msg := a2atype.NewMessage(a2atype.MessageRoleAgent, textOnly...)
330-
msg.Metadata = mirrorMeta
331-
statusEv := a2atype.NewStatusUpdateEvent(reqCtx, a2atype.TaskStateWorking, msg)
332-
statusEv.Metadata = mirrorMeta
356+
statusEv := newAgentStatusEvent(reqCtx, textOnly, mirrorMeta)
333357
if err := queue.Write(ctx, statusEv); err != nil {
334358
return fmt.Errorf("failed to write partial status event: %w", err)
335359
}
@@ -338,10 +362,7 @@ func (e *KAgentExecutor) Execute(ctx context.Context, reqCtx *a2asrv.RequestCont
338362
mirrorParts := a2aParts
339363
if len(hitlParts) == 0 {
340364
// Only mirror when not accumulating HITL parts (those go into input_required).
341-
msg := a2atype.NewMessage(a2atype.MessageRoleAgent, mirrorParts...)
342-
msg.Metadata = maps.Clone(eventMeta)
343-
statusEv := a2atype.NewStatusUpdateEvent(reqCtx, a2atype.TaskStateWorking, msg)
344-
statusEv.Metadata = maps.Clone(eventMeta)
365+
statusEv := newAgentStatusEvent(reqCtx, mirrorParts, maps.Clone(eventMeta))
345366
if err := queue.Write(ctx, statusEv); err != nil {
346367
return fmt.Errorf("failed to write mirror status event: %w", err)
347368
}
@@ -362,7 +383,7 @@ func (e *KAgentExecutor) Execute(ctx context.Context, reqCtx *a2asrv.RequestCont
362383
}
363384

364385
if runErr != nil {
365-
errMsg := a2atype.NewMessage(a2atype.MessageRoleAgent, a2atype.TextPart{Text: runErr.Error()})
386+
errMsg := newAgentMessage(reqCtx, a2atype.TextPart{Text: runErr.Error()})
366387
failed := a2atype.NewStatusUpdateEvent(reqCtx, a2atype.TaskStateFailed, errMsg)
367388
failed.Final = true
368389
failed.Metadata = finalMeta
@@ -371,7 +392,7 @@ func (e *KAgentExecutor) Execute(ctx context.Context, reqCtx *a2asrv.RequestCont
371392

372393
if len(hitlParts) > 0 {
373394
// input_required: the agent is waiting for HITL decisions.
374-
hitlMsg := a2atype.NewMessage(a2atype.MessageRoleAgent, hitlParts...)
395+
hitlMsg := newAgentMessage(reqCtx, hitlParts...)
375396
inputRequired := a2atype.NewStatusUpdateEvent(reqCtx, a2atype.TaskStateInputRequired, hitlMsg)
376397
inputRequired.Final = true
377398
inputRequired.Metadata = finalMeta

‎go/adk/pkg/a2a/executor_test.go‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package a2a
2+
3+
import (
4+
"testing"
5+
6+
a2atype "github.com/a2aproject/a2a-go/a2a"
7+
"github.com/a2aproject/a2a-go/a2asrv"
8+
)
9+
10+
// TestNewAgentMessage_StampsContextAndTaskID verifies agent messages carry the
11+
// request's context and task ids. A2A allows omitting them (the task is the
12+
// canonical carrier), but stamping them lets consumers that flatten task.history
13+
// key each message to its task without backfilling.
14+
func TestNewAgentMessage_StampsContextAndTaskID(t *testing.T) {
15+
reqCtx := &a2asrv.RequestContext{
16+
ContextID: "ctx-xyz",
17+
TaskID: a2atype.TaskID("task-xyz"),
18+
}
19+
20+
msg := newAgentMessage(reqCtx, a2atype.TextPart{Text: "hello"})
21+
22+
if msg.ContextID != "ctx-xyz" {
23+
t.Errorf("ContextID = %q, want %q", msg.ContextID, "ctx-xyz")
24+
}
25+
if msg.TaskID != a2atype.TaskID("task-xyz") {
26+
t.Errorf("TaskID = %q, want %q", msg.TaskID, a2atype.TaskID("task-xyz"))
27+
}
28+
if msg.Role != a2atype.MessageRoleAgent {
29+
t.Errorf("Role = %q, want %q", msg.Role, a2atype.MessageRoleAgent)
30+
}
31+
}
32+
33+
// TestNewAgentStatusEvent_MessageCarriesIDs verifies the per-event emission seam:
34+
// the working status event the executor writes (and that is persisted into
35+
// task.history) carries an agent message stamped with the request's context/task
36+
// ids. This is the property the send guard depends on — without it the persisted
37+
// message keys differently from its locally-streamed counterpart and falsely
38+
// blocks the next send. Mirrors the Python converter test.
39+
func TestNewAgentStatusEvent_MessageCarriesIDs(t *testing.T) {
40+
reqCtx := &a2asrv.RequestContext{
41+
ContextID: "ctx-xyz",
42+
TaskID: a2atype.TaskID("task-xyz"),
43+
}
44+
meta := map[string]any{"k": "v"}
45+
46+
ev := newAgentStatusEvent(reqCtx, a2atype.ContentParts{a2atype.TextPart{Text: "hi"}}, meta)
47+
48+
if ev.Status.State != a2atype.TaskStateWorking {
49+
t.Errorf("State = %q, want %q", ev.Status.State, a2atype.TaskStateWorking)
50+
}
51+
if ev.Status.Message == nil {
52+
t.Fatal("status message is nil")
53+
}
54+
if ev.Status.Message.ContextID != "ctx-xyz" {
55+
t.Errorf("message ContextID = %q, want %q", ev.Status.Message.ContextID, "ctx-xyz")
56+
}
57+
if ev.Status.Message.TaskID != a2atype.TaskID("task-xyz") {
58+
t.Errorf("message TaskID = %q, want %q", ev.Status.Message.TaskID, a2atype.TaskID("task-xyz"))
59+
}
60+
// The event itself also carries the ids (from reqCtx), matching the message.
61+
if ev.ContextID != "ctx-xyz" {
62+
t.Errorf("event ContextID = %q, want %q", ev.ContextID, "ctx-xyz")
63+
}
64+
if ev.TaskID != a2atype.TaskID("task-xyz") {
65+
t.Errorf("event TaskID = %q, want %q", ev.TaskID, a2atype.TaskID("task-xyz"))
66+
}
67+
}

‎python/packages/kagent-adk/src/kagent/adk/converters/event_converter.py‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ def convert_event_to_a2a_message(
161161
invocation_context: InvocationContext,
162162
role: Role = Role.agent,
163163
subagent_session_ids: Optional[Dict[str, str]] = None,
164+
task_id: Optional[str] = None,
165+
context_id: Optional[str] = None,
164166
) -> Optional[Message]:
165167
"""Converts an ADK event to an A2A message.
166168
@@ -171,6 +173,12 @@ def convert_event_to_a2a_message(
171173
subagent_session_ids: Optional mapping of tool name to pre-generated
172174
subagent session ID. When provided, function_call DataParts for
173175
matching tools will have the session ID stamped into their metadata.
176+
task_id: Optional task ID stamped onto the message so it carries the
177+
same identity as the enclosing task. A2A allows these to be omitted
178+
(the task is the canonical carrier), but stamping them lets consumers
179+
that flatten task.history into standalone messages key each message to
180+
its task without backfilling.
181+
context_id: Optional context ID stamped onto the message, as task_id.
174182
175183
Returns:
176184
An A2A Message if the event has content, None otherwise.
@@ -198,7 +206,14 @@ def convert_event_to_a2a_message(
198206

199207
if a2a_parts:
200208
message_metadata = _get_context_metadata(event, invocation_context)
201-
return Message(message_id=str(uuid.uuid4()), role=role, parts=a2a_parts, metadata=message_metadata)
209+
return Message(
210+
message_id=str(uuid.uuid4()),
211+
role=role,
212+
parts=a2a_parts,
213+
metadata=message_metadata,
214+
task_id=task_id,
215+
context_id=context_id,
216+
)
202217

203218
except Exception as e:
204219
logger.error("Failed to convert event to status message: %s", e)
@@ -342,7 +357,13 @@ def convert_event_to_a2a_events(
342357
a2a_events.append(error_event)
343358

344359
# Handle regular message content
345-
message = convert_event_to_a2a_message(event, invocation_context, subagent_session_ids=subagent_session_ids)
360+
message = convert_event_to_a2a_message(
361+
event,
362+
invocation_context,
363+
subagent_session_ids=subagent_session_ids,
364+
task_id=task_id,
365+
context_id=context_id,
366+
)
346367
if message:
347368
running_event = _create_status_update_event(message, invocation_context, event, task_id, context_id)
348369
a2a_events.append(running_event)

‎python/packages/kagent-adk/tests/unittests/converters/test_event_converter.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,3 +117,21 @@ def test_convert_event_to_a2a_events(self):
117117
error_code_key = get_kagent_metadata_key("error_code")
118118
assert error_code_key in error_event.metadata
119119
assert error_event.metadata[error_code_key] == str(genai_types.FinishReason.MALFORMED_FUNCTION_CALL)
120+
121+
def test_message_carries_task_and_context_ids(self):
122+
"""The converted message stamps task_id/context_id so consumers that
123+
flatten task.history can key it to its task without backfilling."""
124+
invocation_context = _create_mock_invocation_context()
125+
content = genai_types.Content(parts=[genai_types.Part(text="hello world")])
126+
event = _create_mock_event(content=content, invocation_id="test_invocation_ids")
127+
128+
result = convert_event_to_a2a_events(event, invocation_context, task_id="task-xyz", context_id="ctx-xyz")
129+
130+
working_events = [
131+
e for e in result if isinstance(e, TaskStatusUpdateEvent) and e.status.state == TaskState.working
132+
]
133+
assert len(working_events) == 1
134+
message = working_events[0].status.message
135+
assert message is not None
136+
assert message.task_id == "task-xyz"
137+
assert message.context_id == "ctx-xyz"

‎ui/src/components/chat/__tests__/ChatInterface.sendGuard.test.tsx‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,79 @@ describe("ChatInterface send guard", () => {
337337
expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
338338
});
339339

340+
it("does not block the next send after a same-tab tool-call turn is persisted", async () => {
341+
// Reproduces the false positive seen with tool calls: a same-tab turn that
342+
// makes a tool call streams a ToolCallRequestEvent locally (keyed by its
343+
// real contextId/taskId), but the backend persists agent messages with
344+
// EMPTY contextId/taskId. extractMessagesFromTasks leaves those empty
345+
// (`"" ?? task.contextId` is still "") and rebuilds the converted tool
346+
// message with a fresh uuidv4 messageId, so it keys on ["message", <random>]
347+
// — a different key on every extraction. The guard therefore can never match
348+
// the persisted tool message against the local one, counts the backend as
349+
// ahead, and falsely blocks the next send.
350+
mockBackendTasks([completedTask("task-initial", initialTurn)]);
351+
mockSendMessageStream
352+
.mockResolvedValueOnce(streamOf(completedToolCallStatusEvent("session-1", "task-streamed", "shared-call")))
353+
.mockResolvedValueOnce(streamOf(completedStatusEvent("next answer", "session-1", "task-next")));
354+
355+
renderExistingSession();
356+
357+
expect(await screen.findByText("initial answer")).toBeInTheDocument();
358+
359+
await sendText("tool question");
360+
await waitFor(() => expect(mockSendMessageStream).toHaveBeenCalledTimes(1));
361+
362+
// Backend now reflects exactly that same-tab tool turn. The persisted agent
363+
// tool message carries empty contextId/taskId, as the real backend stores it.
364+
mockBackendTasks([
365+
completedTask("task-initial", initialTurn),
366+
completedTask("task-streamed", [
367+
textMessage(sentMessage().messageId, "user", "tool question", "session-1", "task-streamed"),
368+
toolCallMessage("backend-tool", "", "", "shared-call"),
369+
]),
370+
]);
371+
await sendText("next question");
372+
373+
await waitFor(() => expect(mockSendMessageStream).toHaveBeenCalledTimes(2));
374+
expect(mockToastInfo).not.toHaveBeenCalledWith(staleToastMessage);
375+
});
376+
377+
it("does not block the next send after a same-tab text turn persisted with empty agent ids", async () => {
378+
// The general case behind "every message needs sending twice": the backend
379+
// persists AGENT messages with empty contextId/taskId (A2A optional fields;
380+
// the task is the canonical carrier). The locally-streamed agent message
381+
// carries the task's real ids, so it keys on ["task", ...] while the
382+
// backend-extracted copy — pushed as-is with empty ids — keys on
383+
// ["message", <persisted id>]. They never match, so every turn (each has an
384+
// agent text response) counts the backend as ahead and falsely blocks.
385+
mockBackendTasks([completedTask("task-initial", initialTurn)]);
386+
mockSendMessageStream
387+
.mockResolvedValueOnce(streamOf(completedStatusEvent("same tab answer", "session-1", "task-streamed")))
388+
.mockResolvedValueOnce(streamOf(completedStatusEvent("next answer", "session-1", "task-next")));
389+
390+
renderExistingSession();
391+
392+
expect(await screen.findByText("initial answer")).toBeInTheDocument();
393+
394+
await sendText("same tab question");
395+
await waitFor(() => expect(mockSendMessageStream).toHaveBeenCalledTimes(1));
396+
expect(await screen.findByText("same tab answer")).toBeInTheDocument();
397+
398+
// Backend reflects the turn, with the agent message persisted with empty
399+
// contextId/taskId (the user message keeps its contextId, as the client stamps it).
400+
mockBackendTasks([
401+
completedTask("task-initial", initialTurn),
402+
completedTask("task-streamed", [
403+
textMessage(sentMessage().messageId, "user", "same tab question", "session-1", ""),
404+
textMessage("same-tab-agent", "agent", "same tab answer", "", ""),
405+
]),
406+
]);
407+
await sendText("next question");
408+
409+
await waitFor(() => expect(mockSendMessageStream).toHaveBeenCalledTimes(2));
410+
expect(mockToastInfo).not.toHaveBeenCalledWith(staleToastMessage);
411+
});
412+
340413
it("still blocks when the backend has a cross-tab message not visible locally", async () => {
341414
mockBackendTasks([completedTask("task-initial", initialTurn)]);
342415

‎ui/src/lib/messageHandlers.ts‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,18 @@ export function extractMessagesFromTasks(tasks: Task[]): Message[] {
6060
// Agent messages: convert function_call / function_response DataParts to
6161
// the same ToolCallRequestEvent / ToolCallExecutionEvent format produced
6262
// by the live-stream handlers so the rendering component can display them.
63-
const msgContextId = historyItem.contextId ?? task.contextId;
64-
const msgTaskId = historyItem.taskId ?? task.id;
63+
//
64+
// Backfill contextId/taskId from the task when the history item omits them.
65+
// Persisted agent messages (both tool and text) frequently carry empty
66+
// strings here, and `??` would keep the empty string ("" is not nullish).
67+
// The locally-streamed copies of these messages carry the task's real ids,
68+
// so the send guard keys them on (contextId, taskId); without the backfill
69+
// the backend-extracted copies fall back to messageId and never match the
70+
// local ones, counting the backend as ahead and falsely blocking the next
71+
// send on every turn. Treat "" as absent so both copies get the task's
72+
// stable ids. Applied to every extracted agent message below.
73+
const msgContextId = historyItem.contextId || task.contextId;
74+
const msgTaskId = historyItem.taskId || task.id;
6575
const source = getSourceFromMetadata(historyItem.metadata as ADKMetadata | undefined, "assistant");
6676
const msgStats = getMessageTokenStats(historyItem.metadata as Record<string, unknown>);
6777

@@ -149,12 +159,16 @@ export function extractMessagesFromTasks(tasks: Task[]): Message[] {
149159
}
150160
}
151161

152-
// Text messages (or any message without data parts): push with tokenStats.
162+
// Text messages (or any message without data parts): push with tokenStats
163+
// and the backfilled contextId/taskId so they key the same way the
164+
// locally-streamed copy does.
153165
if (!hasConvertedParts) {
154-
messages.push(msgStats
155-
? { ...historyItem, metadata: { ...(historyItem.metadata as object || {}), tokenStats: msgStats } }
156-
: historyItem
157-
);
166+
messages.push({
167+
...historyItem,
168+
contextId: msgContextId,
169+
taskId: msgTaskId,
170+
...(msgStats ? { metadata: { ...(historyItem.metadata as object || {}), tokenStats: msgStats } } : {}),
171+
});
158172
}
159173
}
160174
}

0 commit comments

Comments
 (0)