Skip to content

Commit 03aa8f2

Browse files
adalundheclaude
andcommitted
fix(session): name the busy-Session send refusal
The gateway now sends reason KAGENT_SESSION_BUSY in the ErrorInfo metadata when an open turn or a checkpoint holds the Session. The refusal keeps its code and message. Chat offers Recover for that reason only, so other A2A refusals keep the plain error with Retry. Move the send-refusal reasons and predicates to ApiError, beside isNotFound, so the transcript depends only on @/api. Keep the push-store comment beside the prop it describes, and document every refusal that offers Recover. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Ada Lundhe <[email protected]>
1 parent f5cd6ee commit 03aa8f2

10 files changed

Lines changed: 84 additions & 54 deletions

File tree

‎docs/architecture/runtime-and-lifecycle.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -289,8 +289,9 @@ send refused as `KAGENT_SEND_NOT_ACCEPTED` with the same message ID, doubling
289289
the wait up to two seconds for 30 seconds, and then offers Recover, which calls
290290
`RevertSession`. A crash during a turn leaves that turn active, so with the
291291
setting off the next send is refused outright as a conflict while the Session
292-
still reads READY. Chat offers Recover for that refusal too, because nothing
293-
else observes the crash. Chat also offers Recover while a recovery is pending,
292+
still reads READY. The gateway names that refusal `KAGENT_SESSION_BUSY` in its
293+
ErrorInfo metadata, and chat offers Recover for it too, because nothing else
294+
observes the crash. Other refusals keep a plain error. Chat also offers Recover while a recovery is pending,
294295
because a recovery whose attempt failed stays FAILED/REVERT until a client
295296
retries it.
296297
Recover returns a healthy runtime unchanged and records a lost one, so it is

‎go/core/internal/a2agateway/routing_test.go‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package a2agateway
22

33
import (
44
"context"
5+
"errors"
56
"testing"
67

78
a2a "github.com/a2aproject/a2a-go/v2/a2a"
@@ -148,10 +149,11 @@ func TestSendRecoveryDisabled(t *testing.T) {
148149
name string
149150
pending, busy, refused bool
150151
want error
152+
reason string
151153
}{
152154
{name: "an admitted recovery", pending: true, want: a2a.ErrUnsupportedOperation},
153-
{name: "an active turn", busy: true, want: a2a.ErrUnsupportedOperation},
154-
{name: "a runtime refusal", refused: true, want: sessionsvc.ErrSendNotAccepted},
155+
{name: "an active turn", busy: true, want: a2a.ErrUnsupportedOperation, reason: "KAGENT_SESSION_BUSY"},
156+
{name: "a runtime refusal", refused: true, want: sessionsvc.ErrSendNotAccepted, reason: "KAGENT_SEND_NOT_ACCEPTED"},
155157
} {
156158
t.Run("Given automatic recovery is disabled, when a send encounters "+scenario.name+", assert that it refuses without reverting", func(t *testing.T) {
157159
session := gatewayTestSession()
@@ -171,13 +173,21 @@ func TestSendRecoveryDisabled(t *testing.T) {
171173
gateway := New(interactions, &gatewayTestDialer{client: gatewayTestClient(t, runtime)}, gatewayTestURL)
172174
_, err := gateway.SendMessage(gatewayTestContext(), gatewayTestRequest())
173175
require.ErrorIs(t, err, scenario.want)
174-
if !scenario.refused {
175-
require.NotErrorIs(t, err, sessionsvc.ErrSendNotAccepted)
176-
}
176+
require.Equal(t, scenario.reason, errorInfoReason(err))
177177
require.Zero(t, store.reverts)
178178
if scenario.busy {
179179
require.Equal(t, 1, store.reserveCalls)
180180
}
181181
})
182182
}
183183
}
184+
185+
// errorInfoReason is the kagent reason a refusal carries in its ErrorInfo metadata.
186+
func errorInfoReason(err error) string {
187+
refusal, ok := errors.AsType[*a2a.Error](err)
188+
if !ok {
189+
return ""
190+
}
191+
meta, _ := refusal.ErrorInfo().Value["metadata"].(map[string]string)
192+
return meta["reason"]
193+
}

‎go/core/internal/service/session/interactions.go‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ func (s *InteractionService) PrepareSend(ctx context.Context, agent types.Namesp
177177
}
178178
}
179179
if errors.Is(err, database.ErrConflict) {
180-
err = interactionStoreError(ctx, err)
180+
err = errSessionBusy(err)
181181
}
182182
if errors.Is(err, database.ErrMessageAccepted) {
183183
var historyLength *int
@@ -257,6 +257,15 @@ func (s *InteractionService) reserveDispatch(ctx context.Context, sessionID, ini
257257
}
258258
}
259259

260+
// errSessionBusy refuses a send while an open turn or a checkpoint holds the
261+
// Session. A runtime that crashed mid-turn leaves its turn open, so with recovery
262+
// on send disabled this is also how a crash reaches the client; the reason lets a
263+
// client offer RevertSession for this refusal and no other.
264+
func errSessionBusy(err error) error {
265+
return a2atype.NewError(a2atype.ErrUnsupportedOperation, err.Error()).
266+
WithErrorInfoMeta(map[string]string{"reason": "KAGENT_SESSION_BUSY"})
267+
}
268+
260269
// ErrSendNotAccepted tells callers they may retry this input because no dispatch
261270
// occurred, or an unused dispatch was revoked before the runtime persisted it.
262271
var ErrSendNotAccepted = a2atype.NewError(a2atype.ErrUnsupportedOperation, "input was not accepted; retry after the session becomes available").

‎ui/src/api/ApiError.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,32 @@ export function isNotFound(error: unknown): boolean {
8888
return isApiError(error) && error.status === 404;
8989
}
9090

91+
/**
92+
* `ApiError.reason` of a send the gateway kept refusing as not accepted until chat's
93+
* retry window ran out. The runtime may have crashed.
94+
*/
95+
export const SEND_NOT_ACCEPTED = "KAGENT_SEND_NOT_ACCEPTED";
96+
97+
/**
98+
* `ApiError.reason` of a send refused because an open turn or a checkpoint holds the
99+
* Session. A runtime that crashed mid-turn leaves its turn open, so unless the
100+
* controller recovers on send, this refusal is the only sign of the crash.
101+
*/
102+
export const SESSION_BUSY = "KAGENT_SESSION_BUSY";
103+
104+
/** Whether `error` is a send the gateway never accepted, after every retry. */
105+
export function isSendNotAccepted(error: unknown): boolean {
106+
return isApiError(error) && error.reason === SEND_NOT_ACCEPTED;
107+
}
108+
109+
/**
110+
* Whether chat should offer a revert after `error`. `RevertSession` returns a
111+
* healthy runtime unchanged, so a refusal that only might mean a crash is enough.
112+
*/
113+
export function mayNeedRecovery(error: unknown): boolean {
114+
return isApiError(error) && (error.reason === SEND_NOT_ACCEPTED || error.reason === SESSION_BUSY);
115+
}
116+
91117
/**
92118
* The status each gRPC code stands for, from the Connect protocol's own table.
93119
*

‎ui/src/api/chat/a2aGrpcChatClient.test.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ import {
2525
} from "@/generated/a2a_pb";
2626
import { ErrorInfoSchema } from "@/generated/google/rpc/error_details_pb";
2727
import { setApiTransport } from "../transport";
28-
import { A2AGrpcChatClient, isSendNotAccepted, mayNeedRecovery, SEND_NOT_ACCEPTED, SEND_REFUSED } from "./a2aGrpcChatClient";
28+
import { A2AGrpcChatClient } from "./a2aGrpcChatClient";
29+
import { isSendNotAccepted, mayNeedRecovery, SEND_NOT_ACCEPTED, SESSION_BUSY } from "../ApiError";
2930
import { LinkFile } from "./attachments";
3031
import { A2A_METADATA } from "./a2aMetadata";
3132
import type { ChatEvent, ChatMessage } from "./types";
@@ -2191,8 +2192,9 @@ describe("A2AGrpcChatClient.send, when the gateway did not accept the message",
21912192
});
21922193

21932194
it.each([
2194-
["another metadata reason", notAccepted({ reason: "SOMETHING_ELSE" }), SEND_REFUSED],
2195-
["no metadata, as for an earlier turn that is still open", notAccepted({}), SEND_REFUSED],
2195+
["an open turn or checkpoint holding the Session", notAccepted({ reason: SESSION_BUSY }), SESSION_BUSY],
2196+
["another metadata reason", notAccepted({ reason: "SOMETHING_ELSE" }), undefined],
2197+
["no metadata, as for a runtime that cannot be recovered", notAccepted({}), undefined],
21962198
["another gRPC code", notAccepted(undefined, Code.Unavailable), undefined],
21972199
["no ErrorInfo", new ConnectError("Session runtime cannot be recovered; start another conversation", Code.FailedPrecondition), undefined],
21982200
])("does not re-send for %s", async (_, refusal, reason) => {
@@ -2207,14 +2209,14 @@ describe("A2AGrpcChatClient.send, when the gateway did not accept the message",
22072209
expect(requests).toHaveLength(1);
22082210
});
22092211

2210-
it("keeps the gateway's words for an outright refusal", async () => {
2212+
it("keeps the gateway's words for a busy Session", async () => {
22112213
const { error } = await run(async function* () {
22122214
yield* [];
22132215
throw new ConnectError("resource conflict", Code.FailedPrecondition, undefined, [
2214-
{ desc: ErrorInfoSchema, value: { reason: "UNSUPPORTED_OPERATION", domain: "a2a-protocol.org", metadata: {} } },
2216+
{ desc: ErrorInfoSchema, value: { reason: "UNSUPPORTED_OPERATION", domain: "a2a-protocol.org", metadata: { reason: SESSION_BUSY } } },
22152217
]);
22162218
});
2217-
expect(error).toMatchObject({ message: "resource conflict", code: "FailedPrecondition", reason: SEND_REFUSED });
2219+
expect(error).toMatchObject({ message: "resource conflict", code: "FailedPrecondition", reason: SESSION_BUSY });
22182220
});
22192221

22202222
it("doubles the wait between re-sends, up to two seconds", async () => {

‎ui/src/api/chat/a2aGrpcChatClient.ts‎

Lines changed: 5 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ import {
6060
type TaskStatus,
6161
} from "@/generated/a2a_pb";
6262
import { ErrorInfoSchema } from "@/generated/google/rpc/error_details_pb";
63-
import { ApiError, fromConnectError, rethrowIfAborted } from "../ApiError";
63+
import { ApiError, fromConnectError, rethrowIfAborted, SEND_NOT_ACCEPTED, SESSION_BUSY } from "../ApiError";
6464
import { A2A_METADATA, metadataString } from "./a2aMetadata";
6565
import {
6666
HITL_EXTENSION_HEADER,
@@ -131,33 +131,6 @@ const UNACCEPTED_SEND_RETRY_MS = 100;
131131
*/
132132
const UNACCEPTED_SEND_MAX_RETRY_MS = 2_000;
133133

134-
/**
135-
* `ApiError.reason` of a send the gateway kept refusing as not accepted until the
136-
* retry window ran out. The runtime may have crashed; `RevertSession` is safe to
137-
* offer, because it returns a healthy Session unchanged.
138-
*/
139-
export const SEND_NOT_ACCEPTED = "KAGENT_SEND_NOT_ACCEPTED";
140-
141-
/** Whether `error` is a send the gateway never accepted, after every retry. */
142-
export function isSendNotAccepted(error: unknown): boolean {
143-
return error instanceof ApiError && error.reason === SEND_NOT_ACCEPTED;
144-
}
145-
146-
/**
147-
* `ApiError.reason` of a send the gateway refused outright, before accepting it.
148-
*
149-
* A runtime that crashed mid-turn leaves that turn open, and an open turn refuses
150-
* every send as a conflict. Unless the controller recovers on send, nothing then
151-
* observes the crash, so the refusal is the only sign of it. A busy, healthy runtime
152-
* is refused the same way; `RevertSession` leaves it alone.
153-
*/
154-
export const SEND_REFUSED = "SEND_REFUSED";
155-
156-
/** Whether chat should offer a revert after `error`. */
157-
export function mayNeedRecovery(error: unknown): boolean {
158-
return error instanceof ApiError && (error.reason === SEND_NOT_ACCEPTED || error.reason === SEND_REFUSED);
159-
}
160-
161134
/** `ErrorInfo.domain` of every error the A2A server writes (`a2a.ProtocolDomain`). */
162135
const A2A_PROTOCOL_DOMAIN = "a2a-protocol.org";
163136

@@ -183,7 +156,7 @@ function a2aRefusal(error: unknown) {
183156
*/
184157
function unacceptedSendRetryMs(error: unknown): number | undefined {
185158
const info = a2aRefusal(error);
186-
if (info?.metadata.reason !== "KAGENT_SEND_NOT_ACCEPTED") return undefined;
159+
if (info?.metadata.reason !== SEND_NOT_ACCEPTED) return undefined;
187160
const wait = Number.parseInt(info.metadata.retryAfterMs ?? "", 10);
188161
return Number.isFinite(wait) && wait >= 0 ? wait : UNACCEPTED_SEND_RETRY_MS;
189162
}
@@ -725,7 +698,9 @@ export class A2AGrpcChatClient implements ChatClient {
725698
source = client.sendStreamingMessage(request, options);
726699
continue;
727700
}
728-
if (!received && !signal?.aborted && a2aRefusal(error)) throw refusedSendError(error, SEND_REFUSED);
701+
if (!received && !signal?.aborted && a2aRefusal(error)?.metadata.reason === SESSION_BUSY) {
702+
throw refusedSendError(error, SESSION_BUSY);
703+
}
729704
if (progressed || Date.now() - opened >= REATTACH_HEALTHY_MS) failures = 0;
730705
failures += 1;
731706
const reattach = !signal?.aborted && taskId !== "" && !settled

‎ui/src/api/index.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,15 @@
77
* is still held over HTTP.
88
*/
99

10-
export { ApiError, isApiError, isNotFound } from "./ApiError";
10+
export {
11+
ApiError,
12+
isApiError,
13+
isNotFound,
14+
isSendNotAccepted,
15+
mayNeedRecovery,
16+
SEND_NOT_ACCEPTED,
17+
SESSION_BUSY,
18+
} from "./ApiError";
1119
export type { ApiErrorKind } from "./ApiError";
1220

1321
export { apiBaseUrl, apiMode, isMockMode, MOCK_API_BASE_URL } from "./config";

‎ui/src/components/chat/ChatTranscript.tsx‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@ import type { ReactNode } from "react";
33
import { Alert, Button, Empty, Skeleton, Tag, Tooltip } from "antd";
44
import { ChevronDown } from "lucide-react";
55
import { useTheme } from "@emotion/react";
6-
import type { ChatController, ChatTurnPhase, Checkpoint } from "@/api";
6+
import { isSendNotAccepted, mayNeedRecovery, type ChatController, type ChatTurnPhase, type Checkpoint } from "@/api";
77
import { AskUserPrompt } from "./AskUserPrompt";
88
import { ChatMessageItem } from "./ChatMessageItem";
99
import { CheckpointDivider } from "./CheckpointDivider";
1010
import { groupByCheckpoint } from "./messageCheckpoints";
1111
import { scrollbarStyles } from "@/components/agent/controlStyles";
12-
import { isSendNotAccepted, mayNeedRecovery } from "@/api/chat/a2aGrpcChatClient";
1312

1413
/** Stable, so a transcript with no boundaries does not regroup on every render. */
1514
const EMPTY_CHECKPOINTS: ReadonlyMap<string, string> = new Map();
@@ -87,8 +86,9 @@ export function ChatTranscript({
8786
/** Opens active callbacks for one A2A task. */
8887
onManageTaskPush?: (taskId: string) => void;
8988
/**
90-
* Reverts a runtime that may have crashed, offered when sends keep being refused
91-
* as not accepted. Absent when read-only.
89+
* Reverts a runtime that may have crashed, offered when a send is refused as not
90+
* accepted after every retry, or because an open turn holds the Session. Absent when
91+
* read-only.
9292
*/
9393
onRecover?: () => void;
9494
/** A revert from `onRecover` is in flight. */

‎ui/src/pages/AgentChatPage.recovery.test.tsx‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ import { SessionService } from "@/generated/kagent/api/v1/sessions_pb";
88
import { CheckpointService, CheckpointState } from "@/generated/kagent/api/v1/checkpoints_pb";
99
import { RuntimeOperation, RuntimeState } from "@/generated/kagent/api/v1/runtime_pb";
1010
import { setApiTransport } from "@/api/transport";
11-
import { ApiError, type ChatController } from "@/api";
12-
import { SEND_NOT_ACCEPTED, SEND_REFUSED } from "@/api/chat/a2aGrpcChatClient";
11+
import { ApiError, SEND_NOT_ACCEPTED, SESSION_BUSY, type ChatController } from "@/api";
1312
import { themeFor } from "@/theme/theme";
1413
import { AgentChatPage } from "./AgentChatPage";
1514

@@ -192,7 +191,7 @@ describe("a send the gateway never accepted", () => {
192191
// conflict while the Session still reads READY.
193192
lifecycle = READY;
194193
(chat as { turnError?: Error }).turnError = new ApiError("resource conflict", {
195-
kind: "http", code: "FailedPrecondition", reason: SEND_REFUSED, url: "A2AService/SendStreamingMessage",
194+
kind: "http", code: "FailedPrecondition", reason: SESSION_BUSY, url: "A2AService/SendStreamingMessage",
196195
});
197196
renderPage();
198197
const alert = await screen.findByTestId("chat-turn-error");

‎ui/src/pages/AgentChatPage.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -713,11 +713,11 @@ export function AgentChatPage() {
713713
onRenameCheckpoint={renameSnapshot}
714714
onFork={forkCheckpoint}
715715
onDeleteCheckpoint={deleteCheckpoint}
716-
// The mock chat client has no A2A push store; hide the control rather
717-
// than showing a backend error over an otherwise scripted transcript.
718716
// A conversation that is not ready has its own alert with Recover.
719717
onRecover={canSend ? () => void recover() : undefined}
720718
isRecovering={isRecovering}
719+
// The mock chat client has no A2A push store; hide the control rather
720+
// than showing a backend error over an otherwise scripted transcript.
721721
onManageTaskPush={isMockMode ? undefined : (taskId) => {
722722
if (conversation) setPushTask({ conversationId: conversation.id, taskId });
723723
}}

0 commit comments

Comments
 (0)