From 8b8ecd3bde8bad9a9e1504a14af2f013bbdda7dd Mon Sep 17 00:00:00 2001 From: Emmanuel Hugonnet Date: Wed, 18 Nov 2026 11:17:19 +0100 Subject: [PATCH 1/2] fix: improve server conformance and local ITK runs Validate message input modes across transports and correct REST and JSON-RPC wire formats, streaming responses, and push notification errors. Preserve opening messages in task history and distribute persisted task snapshots. Add a local ITK and ACTS launcher with Podman support and a results summary, along with regression coverage for server and transport behavior. Signed-off-by: Emmanuel Hugonnet --- .../org/a2aproject/sdk/common/MediaType.java | 2 +- .../AbstractA2AServerServerTest_v0_3.java | 32 ++- .../test/AgentExecutorProducer_v0_3.java | 6 + itk/run_itk.sh | 3 +- itk/run_itk_local.sh | 164 ++++++++++++ .../org/a2aproject/sdk/itk/ActsBehaviors.java | 8 + .../a2aproject/sdk/itk/AgentCardProducer.java | 2 +- itk/summarize_results.sh | 134 ++++++++++ .../server/apps/quarkus/A2AServerRoutes.java | 3 + .../server/rest/quarkus/A2AServerRoutes.java | 10 +- .../rest/quarkus/A2AServerRoutesTest.java | 9 +- .../rest/quarkus/QuarkusA2ARestTest.java | 81 ++++++ server-common/pom.xml | 5 + .../sdk/server/InputModeValidator.java | 188 ++++++++++++++ .../sdk/server/events/MainEventBus.java | 13 +- .../server/events/MainEventBusProcessor.java | 58 ++++- .../DefaultRequestHandler.java | 122 +++++---- .../sdk/server/tasks/AgentEmitter.java | 21 +- .../sdk/server/tasks/TaskManager.java | 12 +- .../sdk/server/InputModeValidatorTest.java | 161 ++++++++++++ .../events/MainEventBusTaskSnapshotTest.java | 119 +++++++++ .../DefaultRequestHandlerTest.java | 114 +++++++++ .../sdk/server/tasks/AgentEmitterTest.java | 60 ++++- .../sdk/server/tasks/TaskManagerTest.java | 35 +++ .../sdk/server/util/sse/SseFormatterTest.java | 37 +++ .../sdk/grpc/utils/JSONRPCUtils.java | 44 +++- .../sdk/grpc/utils/ProtoJsonUtils.java | 58 +++++ .../sdk/grpc/utils/JSONRPCUtilsTest.java | 80 ++++++ .../sdk/spec/A2AErrorCodesTest.java | 17 ++ .../jsonrpc/MultiVersionJSONRPCTest.java | 19 ++ .../rest/MultiVersionRestTest.java | 29 ++- .../rest/MultiVersion_v0_3_RestTest.java | 3 +- .../apps/common/AbstractA2AServerTest.java | 237 ++++++++++++++++-- .../apps/common/AgentExecutorProducer.java | 19 ++ .../transport/grpc/handler/GrpcHandler.java | 3 + .../jsonrpc/handler/JSONRPCHandler.java | 3 + .../transport/rest/handler/RestHandler.java | 35 ++- .../rest/handler/RestHandlerTest.java | 140 +++++++++-- 38 files changed, 1932 insertions(+), 154 deletions(-) create mode 100755 itk/run_itk_local.sh create mode 100755 itk/summarize_results.sh create mode 100644 server-common/src/main/java/org/a2aproject/sdk/server/InputModeValidator.java create mode 100644 server-common/src/test/java/org/a2aproject/sdk/server/InputModeValidatorTest.java create mode 100644 server-common/src/test/java/org/a2aproject/sdk/server/events/MainEventBusTaskSnapshotTest.java create mode 100644 server-common/src/test/java/org/a2aproject/sdk/server/util/sse/SseFormatterTest.java create mode 100644 spec/src/test/java/org/a2aproject/sdk/spec/A2AErrorCodesTest.java diff --git a/common/src/main/java/org/a2aproject/sdk/common/MediaType.java b/common/src/main/java/org/a2aproject/sdk/common/MediaType.java index 752fc468f..3258fc7d6 100644 --- a/common/src/main/java/org/a2aproject/sdk/common/MediaType.java +++ b/common/src/main/java/org/a2aproject/sdk/common/MediaType.java @@ -6,6 +6,6 @@ public interface MediaType { /** MIME type for JSON content: {@code application/json}. */ String APPLICATION_JSON = "application/json"; - /** MIME type accepted from HTTP+JSON clients alongside {@code application/json}: {@code application/a2a+json}. */ + /** MIME type for A2A HTTP+JSON content: {@code application/a2a+json}. */ String APPLICATION_A2A_JSON = "application/a2a+json"; } diff --git a/compat-0.3/server-conversion/src/test/java/org/a2aproject/sdk/compat03/conversion/AbstractA2AServerServerTest_v0_3.java b/compat-0.3/server-conversion/src/test/java/org/a2aproject/sdk/compat03/conversion/AbstractA2AServerServerTest_v0_3.java index 6cf582458..f35a24e6f 100644 --- a/compat-0.3/server-conversion/src/test/java/org/a2aproject/sdk/compat03/conversion/AbstractA2AServerServerTest_v0_3.java +++ b/compat-0.3/server-conversion/src/test/java/org/a2aproject/sdk/compat03/conversion/AbstractA2AServerServerTest_v0_3.java @@ -1968,14 +1968,14 @@ public void testMainQueueStaysOpenForNonFinalTasks() throws Exception { * 2. Task reaches COMPLETED state (final) * 3. ChildQueue closes after receiving final event * 4. MainQueue should close because task is finalized - * 5. Resubscription should fail with TaskNotFoundError + * 5. Resubscription should fail with UnsupportedOperationError */ @Test @Timeout(value = 2, unit = TimeUnit.MINUTES) public void testMainQueueClosesForFinalizedTasks() throws Exception { // Send a message without taskId - server generates one Message_v0_3 message = new Message_v0_3.Builder(MESSAGE) - .parts(new TextPart_v0_3("complete task")) + .parts(new TextPart_v0_3("queue-finalization:complete task")) .build(); CountDownLatch completionLatch = new CountDownLatch(1); @@ -1989,10 +1989,6 @@ public void testMainQueueClosesForFinalizedTasks() throws Exception { if (te.getTask().status().state().isFinal()) { completionLatch.countDown(); } - } else if (event instanceof MessageEvent_v0_3 me) { - // Message is considered a final event - capture taskId from the message - generatedTaskId.compareAndSet(null, me.getMessage().taskId()); - completionLatch.countDown(); } else if (event instanceof TaskUpdateEvent_v0_3 tue && tue.getUpdateEvent() instanceof TaskStatusUpdateEvent_v0_3 status) { generatedTaskId.compareAndSet(null, status.taskId()); @@ -2020,8 +2016,8 @@ public void testMainQueueClosesForFinalizedTasks() throws Exception { String taskId = generatedTaskId.get(); assertNotNull(taskId, "Should have captured server-generated taskId"); - // Give cleanup time to run after final event - Thread.sleep(2000); + assertTrue(waitForChildQueueCountToBe(taskId, -1, 15000), + "MainQueue should close after the task reaches a final state"); // Try to resubscribe to finalized task - should fail CountDownLatch errorLatch = new CountDownLatch(1); @@ -2051,24 +2047,24 @@ public void testMainQueueClosesForFinalizedTasks() throws Exception { Throwable error = resubErrorRef.get(); assertNotNull(error, "Resubscription should fail for finalized task"); - // Verify it's a TaskNotFoundError + // Verify it's an UnsupportedOperationError Throwable cause = error; - boolean foundTaskNotFound = false; - while (cause != null && !foundTaskNotFound) { - if (cause instanceof TaskNotFoundError_v0_3 || + boolean foundUnsupportedOperation = false; + while (cause != null && !foundUnsupportedOperation) { + if (cause instanceof UnsupportedOperationError_v0_3 || (cause instanceof A2AClientException_v0_3 && - ((A2AClientException_v0_3) cause).getCause() instanceof TaskNotFoundError_v0_3)) { - foundTaskNotFound = true; + ((A2AClientException_v0_3) cause).getCause() instanceof UnsupportedOperationError_v0_3)) { + foundUnsupportedOperation = true; } cause = cause.getCause(); } - assertTrue(foundTaskNotFound, - "Should receive TaskNotFoundError - MainQueue closed for finalized task"); + assertTrue(foundUnsupportedOperation, + "Should receive UnsupportedOperationError - finalized task rejects resubscription"); } catch (A2AClientException_v0_3 e) { // Exception might be thrown immediately instead of via error handler - assertInstanceOf(TaskNotFoundError_v0_3.class, e.getCause(), - "Should fail with TaskNotFoundError - MainQueue cleaned up for finalized task"); + assertInstanceOf(UnsupportedOperationError_v0_3.class, e.getCause(), + "Should fail with UnsupportedOperationError - finalized task rejects resubscription"); } } finally { diff --git a/compat-0.3/tests/server-common/src/main/java/org/a2aproject/sdk/compat03/conversion/test/AgentExecutorProducer_v0_3.java b/compat-0.3/tests/server-common/src/main/java/org/a2aproject/sdk/compat03/conversion/test/AgentExecutorProducer_v0_3.java index fae5412cb..c70c2d8bb 100644 --- a/compat-0.3/tests/server-common/src/main/java/org/a2aproject/sdk/compat03/conversion/test/AgentExecutorProducer_v0_3.java +++ b/compat-0.3/tests/server-common/src/main/java/org/a2aproject/sdk/compat03/conversion/test/AgentExecutorProducer_v0_3.java @@ -38,6 +38,12 @@ public void execute(RequestContext context, AgentEmitter agentEmitter) throws A2 return; } + if (input.startsWith("queue-finalization:")) { + agentEmitter.startWork(); + agentEmitter.complete(); + return; + } + // Local handling: creates a task with startWork() + addArtifact() + complete() if (input.startsWith("a2a-local:")) { String payload = input.substring("a2a-local:".length()); diff --git a/itk/run_itk.sh b/itk/run_itk.sh index c2ec2b88e..024924e0f 100755 --- a/itk/run_itk.sh +++ b/itk/run_itk.sh @@ -4,8 +4,7 @@ # Everything that used to live here (runtime detection, image build, container # start, readiness poll, POST /run, result reporting, nightly metrics) is now # in a2a-itk/scripts/run_itk_shared.sh, which all five SDK repos share — -# including the podman fallback this repo needs, which is why the shared -# driver has it. +# including support for Docker and Podman. # # Scenarios come from the shared role-based set in a2a-itk rather than a # scenarios.json in this repo — see a2a-itk/scenarios/traversal/. diff --git a/itk/run_itk_local.sh b/itk/run_itk_local.sh new file mode 100755 index 000000000..7a24bde3e --- /dev/null +++ b/itk/run_itk_local.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +# Local, debug-friendly entry point for the A2A ITK and ACTS suites. +# +# This delegates to run_itk.sh, the same launcher used in CI, while retaining +# its result files and (by default) enabling the ITK service's DEBUG logs under +# itk/logs/. +set -euo pipefail + +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +revision=${A2A_ITK_REVISION:-main} +acts_run=${ITK_ACTS_RUN:-0} +transports=${ITK_ACTS_TRANSPORTS:-jsonrpc,grpc,rest} +log_level=${ITK_LOG_LEVEL:-DEBUG} +scenario_file=${SCENARIO_FILE:-} +disable_selinux_labels=false + +usage() { + cat <<'EOF' +Usage: ./run_itk_local.sh [options] + +Run the Java SDK's local interoperability suite through the same launcher CI +uses. The default is the shared ITK PR scenario set with DEBUG service logs. + +Options: + --acts Run ACTS conformance tests instead of ITK traversal tests. + --transports LIST ACTS transports (comma-separated; default: jsonrpc,grpc,rest). + --scenario FILE Run an explicit ITK scenario YAML or JSON file (ITK only). + --revision REF a2a-itk revision to use (default: main). + --timeout SECONDS Maximum time for the ITK /run request. + --container-runtime NAME Use docker or podman (default: first working runtime). + --info Use INFO instead of DEBUG logging. + --selinux-mount-labels Relabel bind mounts with :Z (default for Podman; + changes labels on the checkout, cache, and logs). + --disable-selinux-labels Let a local Podman container read the bind mount + without SELinux container labels. Use only for a + local debugging run when a mounted file is denied. + -h, --help Show this help. + +Useful output after a run: + raw_results.json ITK traversal response + acts-report-*.json ACTS conformance reports + ./summarize_results.sh Readable summary of ACTS conformance reports + logs/ Service logs (when DEBUG logging is enabled) + +Examples: + ./itk/run_itk_local.sh + ./itk/run_itk_local.sh --scenario /tmp/failing-scenario.yaml + ./itk/run_itk_local.sh --acts --transports jsonrpc + ./itk/summarize_results.sh +EOF +} + +absolute_file() { + local file=$1 + if [[ ! -f $file ]]; then + echo "Scenario file does not exist: $file" >&2 + exit 2 + fi + cd "$(dirname "$file")" && printf '%s/%s\n' "$PWD" "$(basename "$file")" +} + +while (($#)); do + case $1 in + --acts) + acts_run=1 + ;; + --transports) + [[ $# -ge 2 ]] || { echo "--transports requires a value" >&2; exit 2; } + transports=$2 + shift + ;; + --scenario) + [[ $# -ge 2 ]] || { echo "--scenario requires a file" >&2; exit 2; } + scenario_file=$(absolute_file "$2") + shift + ;; + --revision) + [[ $# -ge 2 ]] || { echo "--revision requires a ref" >&2; exit 2; } + revision=$2 + shift + ;; + --timeout) + [[ $# -ge 2 && $2 =~ ^[1-9][0-9]*$ ]] || { + echo "--timeout requires a positive number of seconds" >&2 + exit 2 + } + export ITK_RUN_TIMEOUT=$2 + shift + ;; + --info) + log_level=INFO + ;; + --container-runtime) + [[ $# -ge 2 && ( $2 == docker || $2 == podman ) ]] || { + echo "--container-runtime requires docker or podman" >&2 + exit 2 + } + export ITK_CONTAINER_RT=$2 + shift + ;; + --selinux-mount-labels) + export ITK_SELINUX_MOUNT_LABEL=1 + ;; + --disable-selinux-labels) + disable_selinux_labels=true + ;; + -h|--help) + usage + exit 0 + ;; + *) + echo "Unknown option: $1" >&2 + usage >&2 + exit 2 + ;; + esac + shift +done + +if [[ -z ${ITK_CONTAINER_RT:-} ]]; then + for runtime in docker podman; do + if command -v "$runtime" >/dev/null 2>&1 && "$runtime" info >/dev/null 2>&1; then + export ITK_CONTAINER_RT=$runtime + break + fi + done + if [[ -z ${ITK_CONTAINER_RT:-} ]]; then + echo "No working Docker or Podman runtime found; check that it is running and accessible." >&2 + exit 1 + fi +fi + +# Podman on an SELinux-enforcing host cannot access ordinary bind mounts +# without a container label. The shared driver applies :Z to all its mounts. +# Honor an explicit environment setting or the opt-out below. +if [[ $ITK_CONTAINER_RT == podman && -z ${ITK_SELINUX_MOUNT_LABEL+x} ]] && ! $disable_selinux_labels; then + export ITK_SELINUX_MOUNT_LABEL=1 +fi + +export A2A_ITK_REVISION=$revision +export ITK_ACTS_RUN=$acts_run +export ITK_ACTS_TRANSPORTS=$transports +export ITK_LOG_LEVEL=$log_level +if [[ -n $scenario_file ]]; then + export SCENARIO_FILE=$scenario_file +fi + +# The shared driver deliberately accepts this as an array. Source its shim +# below so that the optional argument survives; Bash cannot export arrays to a +# child process. `label=disable` avoids altering the checkout's labels, unlike +# a :z/:Z bind-mount suffix, and is only enabled on explicit request. +if $disable_selinux_labels; then + export ITK_SELINUX_MOUNT_LABEL=0 + ITK_EXTRA_DOCKER_ARGS=(--security-opt label=disable) +fi + +cd "$script_dir" +if [[ $acts_run == 1 || ${acts_run^^} == TRUE ]]; then + suite=ACTS +else + suite=ITK +fi +echo "Running $suite with $ITK_CONTAINER_RT and a2a-itk revision '$A2A_ITK_REVISION' (logs: $ITK_LOG_LEVEL)" +source ./run_itk.sh diff --git a/itk/src/main/java/org/a2aproject/sdk/itk/ActsBehaviors.java b/itk/src/main/java/org/a2aproject/sdk/itk/ActsBehaviors.java index c99a6523e..748c5aa55 100644 --- a/itk/src/main/java/org/a2aproject/sdk/itk/ActsBehaviors.java +++ b/itk/src/main/java/org/a2aproject/sdk/itk/ActsBehaviors.java @@ -175,6 +175,14 @@ void run(RequestContext context, AgentEmitter emitter, String behavior) { return; } + // A multi-turn task is intentionally interrupted at the end of each turn. Emitting a + // transient WORKING update first makes a blocking send_message response race with the + // following INPUT_REQUIRED update, so return the requested state directly. + if ("tck-multi-turn".equals(behavior)) { + multiTurn(context, emitter); + return; + } + // Persists WORKING before anything blocks, so a concurrent cancel_task finds a non-final // task in the store and a blocking send_message is released by the first event. emitter.startWork(); diff --git a/itk/src/main/java/org/a2aproject/sdk/itk/AgentCardProducer.java b/itk/src/main/java/org/a2aproject/sdk/itk/AgentCardProducer.java index ce5e67d9c..f614ae868 100644 --- a/itk/src/main/java/org/a2aproject/sdk/itk/AgentCardProducer.java +++ b/itk/src/main/java/org/a2aproject/sdk/itk/AgentCardProducer.java @@ -62,7 +62,7 @@ public AgentCard agentCard() { .version("1.0.0") .supportedInterfaces(interfaces) .capabilities(capabilities()) - .defaultInputModes(List.of("text")) + .defaultInputModes(List.of("text", "application/x-protobuf")) .defaultOutputModes(List.of("text")) .skills(List.of(AgentSkill.builder() .id("itk_current") diff --git a/itk/summarize_results.sh b/itk/summarize_results.sh new file mode 100755 index 000000000..a81d853dc --- /dev/null +++ b/itk/summarize_results.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# Summarize JSON reports produced by the ITK ACTS test run. +# +# By default this reads itk/acts-report-*.json. Pass one or more report paths +# to summarize a particular run instead. +set -euo pipefail + +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) + +usage() { + cat <<'EOF' +Usage: ./itk/summarize_results.sh [REPORT.json ...] + +Summarize ACTS reports produced by ./itk/run_itk_local.sh --acts. + +With no arguments, reads itk/acts-report-*.json. The command exits with 1 +when a report contains failed or errored tests, so it can be used in CI. + +Examples: + ./itk/summarize_results.sh + ./itk/summarize_results.sh itk/acts-report-a2a-java-jsonrpc-*.json +EOF +} + +if [[ ${1:-} == '-h' || ${1:-} == '--help' ]]; then + usage + exit 0 +fi + +if ! command -v jq >/dev/null; then + echo 'jq is required to summarize ITK results.' >&2 + exit 2 +fi + +if (($#)); then + reports=("$@") +else + shopt -s nullglob + reports=("$script_dir"/acts-report-*.json) + shopt -u nullglob +fi + +if ((${#reports[@]} == 0)); then + echo 'No ACTS result reports found. Run ./itk/run_itk_local.sh --acts first.' >&2 + exit 2 +fi + +format_duration() { + local milliseconds=$1 + if ((milliseconds < 1000)); then + printf '%d ms' "$milliseconds" + else + awk -v milliseconds="$milliseconds" 'BEGIN { printf "%.1f s", milliseconds / 1000 }' + fi +} + +total=0 +passed=0 +failed=0 +skipped=0 +errors=0 +duration_ms=0 + +for report in "${reports[@]}"; do + if [[ ! -f $report ]]; then + echo "Report does not exist: $report" >&2 + exit 2 + fi + if ! jq -e '.summary and .suites and .transport' "$report" >/dev/null; then + echo "Not an ACTS result report: $report" >&2 + exit 2 + fi + + transport=$(jq -r '.transport' "$report") + generated_at=$(jq -r '.generated_at // "unknown"' "$report") + sdk=$(jq -r '.sdk.name // "unknown SDK"' "$report") + read -r report_total report_passed report_failed report_skipped report_errors report_duration < 1)); then + printf '\nCombined summary\n' + printf ' Total: %s Passed: %s Failed: %s Errors: %s Skipped: %s Duration: %s\n' \ + "$total" "$passed" "$failed" "$errors" "$skipped" "$(format_duration "$duration_ms")" +fi + +if ((failed > 0 || errors > 0)); then + exit 1 +fi diff --git a/reference/jsonrpc/src/main/java/org/a2aproject/sdk/server/apps/quarkus/A2AServerRoutes.java b/reference/jsonrpc/src/main/java/org/a2aproject/sdk/server/apps/quarkus/A2AServerRoutes.java index ce73b3b11..63b5b1ddb 100644 --- a/reference/jsonrpc/src/main/java/org/a2aproject/sdk/server/apps/quarkus/A2AServerRoutes.java +++ b/reference/jsonrpc/src/main/java/org/a2aproject/sdk/server/apps/quarkus/A2AServerRoutes.java @@ -729,6 +729,9 @@ private static String serializeResponse(A2AResponse response) { } // Convert domain response to protobuf message and serialize com.google.protobuf.MessageOrBuilder protoMessage = convertToProto(response); + if (response instanceof ListTasksResponse) { + return JSONRPCUtils.toJsonRPCListTasksResultResponse(response.getId(), protoMessage); + } return JSONRPCUtils.toJsonRPCResultResponse(response.getId(), protoMessage); } diff --git a/reference/rest/src/main/java/org/a2aproject/sdk/server/rest/quarkus/A2AServerRoutes.java b/reference/rest/src/main/java/org/a2aproject/sdk/server/rest/quarkus/A2AServerRoutes.java index bd9d23454..013003df7 100644 --- a/reference/rest/src/main/java/org/a2aproject/sdk/server/rest/quarkus/A2AServerRoutes.java +++ b/reference/rest/src/main/java/org/a2aproject/sdk/server/rest/quarkus/A2AServerRoutes.java @@ -83,7 +83,7 @@ * GET /{tenant}/tasks → listTasks() * GET /{tenant}/tasks/{taskId} → getTask() * POST /{tenant}/tasks/{taskId}:cancel → cancelTask() - * POST /{tenant}/tasks/{taskId}:subscribe → subscribeToTask() + * GET/POST /{tenant}/tasks/{taskId}:subscribe → subscribeToTask() * GET /.well-known/agent-card.json → getAgentCard() * GET /{tenant}/extendedAgentCard → getExtendedAgentCard() * @@ -206,7 +206,10 @@ void setupRouter(@Observes @Priority(10) Router router) { cancelTask(body, ctx); }), false); - // POST /{tenant}/tasks/{taskId}:subscribe - Subscribe to task updates (SSE) + // GET and POST /{tenant}/tasks/{taskId}:subscribe - Subscribe to task updates (SSE) + router.getWithRegex("^\\/(?[^\\/]*\\/?)tasks\\/(?[^/]+):subscribe$") + .order(1) + .blockingHandler(authenticatedStreaming(this::subscribeToTask), false); router.postWithRegex("^\\/(?[^\\/]*\\/?)tasks\\/(?[^/]+):subscribe$") .order(1) .blockingHandler(authenticatedStreaming(this::subscribeToTask), false); @@ -254,7 +257,6 @@ void setupRouter(@Observes @Priority(10) Router router) { // GET /{tenant}/extendedAgentCard - Extended agent card (auth required) router.getWithRegex("^\\/(?[^\\/]*\\/?)extendedAgentCard$") .order(1) - .produces(APPLICATION_JSON) .blockingHandler(authenticated(this::getExtendedAgentCard), false); } @@ -497,7 +499,7 @@ private void sendResponse(RoutingContext rc, @Nullable HTTPRestResponse response /** * Subscribes to task updates via Server-Sent Events. * - *

Maps {@code POST /{tenant}/tasks/{taskId}:subscribe} to {@link RestHandler#subscribeToTask}. + *

Maps GET and POST {@code /{tenant}/tasks/{taskId}:subscribe} to {@link RestHandler#subscribeToTask}. * Returns a stream of task events allowing clients to reconnect to ongoing tasks. * *

URL Pattern: {@code /tasks/{taskId}:subscribe} diff --git a/reference/rest/src/test/java/org/a2aproject/sdk/server/rest/quarkus/A2AServerRoutesTest.java b/reference/rest/src/test/java/org/a2aproject/sdk/server/rest/quarkus/A2AServerRoutesTest.java index 15d35c4a6..0d4b4edbc 100644 --- a/reference/rest/src/test/java/org/a2aproject/sdk/server/rest/quarkus/A2AServerRoutesTest.java +++ b/reference/rest/src/test/java/org/a2aproject/sdk/server/rest/quarkus/A2AServerRoutesTest.java @@ -1,5 +1,6 @@ package org.a2aproject.sdk.server.rest.quarkus; +import static org.a2aproject.sdk.common.MediaType.APPLICATION_A2A_JSON; import static org.a2aproject.sdk.common.MediaType.APPLICATION_JSON; import static org.a2aproject.sdk.spec.A2AMethods.CANCEL_TASK_METHOD; import static org.a2aproject.sdk.spec.A2AMethods.DELETE_TASK_PUSH_NOTIFICATION_CONFIG_METHOD; @@ -523,7 +524,7 @@ public void testSendMessage_UnsupportedProtocolVersion_ReturnsVersionNotSupporte public void testSendMessage_ForwardsTransportPolicyResponseWithoutRouteValidation() { HTTPRestResponse policyResponse = mock(HTTPRestResponse.class); when(policyResponse.getStatusCode()).thenReturn(422); - when(policyResponse.getContentType()).thenReturn(APPLICATION_JSON); + when(policyResponse.getContentType()).thenReturn(APPLICATION_A2A_JSON); when(policyResponse.getBody()).thenReturn("{\"error\":{\"code\":422,\"status\":\"INVALID_ARGUMENT\"}}"); when(mockRoutingContext.pathParam("tenant")).thenReturn("bad?tenant"); when(mockRestHandler.sendMessage(any(ServerCallContext.class), eq("bad?tenant"), anyString())) @@ -533,7 +534,7 @@ public void testSendMessage_ForwardsTransportPolicyResponseWithoutRouteValidatio verify(mockRestHandler).sendMessage(any(ServerCallContext.class), eq("bad?tenant"), eq("{}")); verify(mockResponse).setStatusCode(422); - verify(mockResponse).putHeader(io.vertx.core.http.HttpHeaders.CONTENT_TYPE, APPLICATION_JSON); + verify(mockResponse).putHeader(io.vertx.core.http.HttpHeaders.CONTENT_TYPE, APPLICATION_A2A_JSON); verify(mockResponse).end("{\"error\":{\"code\":422,\"status\":\"INVALID_ARGUMENT\"}}"); } @@ -574,7 +575,7 @@ private void assertValidationError(int status, String reason, String message) { private void assertValidationError(int status, String reason, String message, JsonObject metadata) { verify(mockResponse).setStatusCode(status); - verify(mockResponse).putHeader(io.vertx.core.http.HttpHeaders.CONTENT_TYPE, APPLICATION_JSON); + verify(mockResponse).putHeader(io.vertx.core.http.HttpHeaders.CONTENT_TYPE, APPLICATION_A2A_JSON); ArgumentCaptor body = ArgumentCaptor.forClass(String.class); verify(mockResponse).end(body.capture()); JsonObject expected = JsonParser.parseString(""" @@ -666,7 +667,7 @@ public void testListTasksRawQueryValidationOrder() { assertNull(params.getValue().historyLength()); assertEquals(raw == null || raw.isEmpty() ? null : Boolean.valueOf(raw), params.getValue().includeArtifacts()); verify(mockResponse).setStatusCode(200); - verify(mockResponse).putHeader(io.vertx.core.http.HttpHeaders.CONTENT_TYPE, APPLICATION_JSON); + verify(mockResponse).putHeader(io.vertx.core.http.HttpHeaders.CONTENT_TYPE, APPLICATION_A2A_JSON); } for (String field : List.of("status", "statusTimestampAfter")) { validationFixture("1.0", false, true); diff --git a/reference/rest/src/test/java/org/a2aproject/sdk/server/rest/quarkus/QuarkusA2ARestTest.java b/reference/rest/src/test/java/org/a2aproject/sdk/server/rest/quarkus/QuarkusA2ARestTest.java index fb8674219..385cfd75a 100644 --- a/reference/rest/src/test/java/org/a2aproject/sdk/server/rest/quarkus/QuarkusA2ARestTest.java +++ b/reference/rest/src/test/java/org/a2aproject/sdk/server/rest/quarkus/QuarkusA2ARestTest.java @@ -1,15 +1,26 @@ package org.a2aproject.sdk.server.rest.quarkus; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.concurrent.TimeUnit; import org.a2aproject.sdk.client.ClientBuilder; import org.a2aproject.sdk.server.apps.common.AbstractA2AServerTest; +import org.a2aproject.sdk.spec.Task; +import org.a2aproject.sdk.spec.TaskState; +import org.a2aproject.sdk.spec.TaskStatus; +import org.a2aproject.sdk.spec.TaskStatusUpdateEvent; import org.a2aproject.sdk.spec.TransportProtocol; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public abstract class QuarkusA2ARestTest extends AbstractA2AServerTest { @@ -30,6 +41,76 @@ protected String getTransportUrl() { @Override protected abstract void configureTransport(ClientBuilder builder); + @Test + @Timeout(value = 30, unit = TimeUnit.SECONDS) + public void testSubscribeToTaskWithGetOpensEventStream() throws Exception { + String taskId = "rest-subscribe-get-test"; + String contextId = "rest-subscribe-get-context"; + saveTaskInTaskStore(Task.builder().id(taskId).contextId(contextId) + .status(new TaskStatus(TaskState.TASK_STATE_WORKING)).build()); + try { + ensureQueueForTask(taskId); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(getTransportUrl() + "/tasks/" + taskId + ":subscribe")) + .timeout(Duration.ofSeconds(15)) + .header("Accept", "text/event-stream") + .header("A2A-Version", "1.0") + .GET().build(); + HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofInputStream()); + try (InputStream body = response.body()) { + Assertions.assertEquals(200, response.statusCode()); + Assertions.assertTrue(response.headers().firstValue("Content-Type").orElse("") + .startsWith("text/event-stream")); + BufferedReader reader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); + String line; + boolean initialEvent = false; + // The stream begins with an SSE comment frame; skip it and its blank separator. + while ((line = reader.readLine()) != null) { + if (line.startsWith("data:")) { + initialEvent = true; + break; + } + } + Assertions.assertTrue(initialEvent, "Expected an initial SSE task event"); + + enqueueEventOnServer(TaskStatusUpdateEvent.builder().taskId(taskId).contextId(contextId) + .status(new TaskStatus(TaskState.TASK_STATE_COMPLETED)).build()); + boolean completed = false; + while ((line = reader.readLine()) != null) { + if (line.startsWith("data:") && line.contains("TASK_STATE_COMPLETED")) { + completed = true; + break; + } + } + Assertions.assertTrue(completed, "Expected a completed task event"); + } + } finally { + deleteTaskInTaskStore(taskId); + } + } + + @Test + public void testRestResponsesUseA2aJsonContentType() throws Exception { + String taskId = "rest-content-type-test"; + saveTaskInTaskStore(Task.builder().id(taskId).contextId("rest-content-type-context") + .status(new TaskStatus(TaskState.TASK_STATE_WORKING)).build()); + try { + HttpClient client = HttpClient.newHttpClient(); + for (String id : new String[] { taskId, "missing-rest-content-type-test" }) { + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(getTransportUrl() + "/tasks/" + id)) + .header("A2A-Version", "1.0") + .GET().build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + Assertions.assertEquals(id.equals(taskId) ? 200 : 404, response.statusCode()); + Assertions.assertTrue(response.headers().firstValue("Content-Type").orElse("") + .startsWith("application/a2a+json")); + } + } finally { + deleteTaskInTaskStore(taskId); + } + } + @Test public void testSendMessageWithUnsupportedContentType() throws Exception { HttpClient client = HttpClient.newBuilder() diff --git a/server-common/pom.xml b/server-common/pom.xml index 4d2b1ffdf..fd970ce95 100644 --- a/server-common/pom.xml +++ b/server-common/pom.xml @@ -92,6 +92,11 @@ junit-jupiter-params test + + org.awaitility + awaitility + test + org.mockito mockito-core diff --git a/server-common/src/main/java/org/a2aproject/sdk/server/InputModeValidator.java b/server-common/src/main/java/org/a2aproject/sdk/server/InputModeValidator.java new file mode 100644 index 000000000..027376e88 --- /dev/null +++ b/server-common/src/main/java/org/a2aproject/sdk/server/InputModeValidator.java @@ -0,0 +1,188 @@ +package org.a2aproject.sdk.server; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import org.a2aproject.sdk.spec.AgentCard; +import org.a2aproject.sdk.spec.ContentTypeNotSupportedError; +import org.a2aproject.sdk.spec.DataPart; +import org.a2aproject.sdk.spec.FilePart; +import org.a2aproject.sdk.spec.Message; +import org.a2aproject.sdk.spec.Part; +import org.a2aproject.sdk.spec.TextPart; +import org.jspecify.annotations.Nullable; + +/** Validates declared media types in message parts against an agent card's input modes. */ +public final class InputModeValidator { + + private InputModeValidator() {} + + /** + * Rejects a declared part media type which is unsupported by every advertised skill. + * + *

An empty set of advertised modes means that the agent has not declared an input-mode + * restriction. Parts without an explicit media type are not constrained by this check. + * The aliases {@code text}, {@code audio}, {@code image}, and {@code video} match + * {@code text/plain}, {@code audio/*}, {@code image/*}, and {@code video/*}, respectively. + * + * @param message the incoming message + * @param agentCard the agent card selected for this request + * @throws ContentTypeNotSupportedError when a part declares an unsupported media type + */ + public static void validate(Message message, AgentCard agentCard) { + Set inputModes = new HashSet<>(agentCard.defaultInputModes()); + agentCard.skills().forEach(skill -> { + if (skill.inputModes() != null) { + inputModes.addAll(skill.inputModes()); + } + }); + if (inputModes.isEmpty()) { + return; + } + + List advertisedModes = new ArrayList<>(); + for (String mode : inputModes) { + MediaType parsed = parseMediaType(mode, true); + if (parsed != null) { + advertisedModes.add(parsed); + } + } + for (Part part : message.parts()) { + String mediaType = mediaType(part); + if (mediaType != null && !mediaType.isEmpty()) { + MediaType actual = parseMediaType(mediaType, false); + if (actual == null || advertisedModes.stream().noneMatch(mode -> matches(mode, actual))) { + throw new ContentTypeNotSupportedError(null, + "Input media type is not supported: " + mediaType, null); + } + } + } + } + + private record MediaType(String type, Map parameters) {} + + private static @Nullable MediaType parseMediaType(String value, boolean advertised) { + String[] parts = value.split(";", 2); + String type = parts[0].trim(); + if (advertised) { + type = switch (type.toLowerCase(Locale.ROOT)) { + case "text" -> "text/plain"; + case "audio", "image", "video" -> type + "/*"; + default -> type; + }; + } + Map parsedParameters = parameters(parts.length == 2 ? parts[1] : ""); + return parsedParameters == null ? null : new MediaType(type, parsedParameters); + } + + private static boolean matches(MediaType advertised, MediaType actual) { + String pattern = advertised.type(); + String type = actual.type(); + boolean matchesType = pattern.equalsIgnoreCase(type) + || (pattern.endsWith("/*") && type.regionMatches(true, 0, pattern, 0, pattern.length() - 1) + && type.length() > pattern.length() - 1) + || pattern.equals("*/*"); + if (!matchesType) { + return false; + } + for (Map.Entry entry : advertised.parameters().entrySet()) { + String value = actual.parameters().get(entry.getKey()); + if (value == null || !(entry.getKey().equals("charset") + ? entry.getValue().equalsIgnoreCase(value) : entry.getValue().equals(value))) { + return false; + } + } + return true; + } + + /** Parses semicolon-separated MIME parameters, including quoted values and escapes. */ + private static @Nullable Map parameters(String input) { + Map values = new HashMap<>(); + int index = 0; + while (index < input.length()) { + while (index < input.length() && Character.isWhitespace(input.charAt(index))) { + index++; + } + int equals = input.indexOf('=', index); + if (equals < 0) { + return null; + } + String name = input.substring(index, equals).trim().toLowerCase(Locale.ROOT); + if (name.isEmpty() || name.indexOf(';') >= 0) { + return null; + } + index = equals + 1; + while (index < input.length() && Character.isWhitespace(input.charAt(index))) { + index++; + } + String value; + if (index < input.length() && input.charAt(index) == '"') { + index++; + StringBuilder quoted = new StringBuilder(); + boolean closed = false; + while (index < input.length()) { + char c = input.charAt(index++); + if (c == '"') { + closed = true; + break; + } + if (c == '\\') { + if (index == input.length()) { + return null; + } + c = input.charAt(index++); + } + quoted.append(c); + } + if (!closed) { + return null; + } + value = quoted.toString(); + while (index < input.length() && Character.isWhitespace(input.charAt(index))) { + index++; + } + if (index < input.length() && input.charAt(index) != ';') { + return null; + } + } else { + int end = input.indexOf(';', index); + if (end < 0) { + end = input.length(); + } + value = input.substring(index, end).trim(); + index = end; + if (value.isEmpty()) { + return null; + } + } + if (values.putIfAbsent(name, value) != null) { + return null; + } + if (index < input.length()) { + index++; + if (index == input.length()) { + return null; + } + } + } + return values; + } + + private static @Nullable String mediaType(Part part) { + if (part instanceof TextPart textPart) { + return textPart.mediaType(); + } + if (part instanceof DataPart dataPart) { + return dataPart.mediaType(); + } + if (part instanceof FilePart filePart) { + return filePart.file().mimeType(); + } + return null; + } +} diff --git a/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBus.java b/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBus.java index 76d6258d1..c691f9320 100644 --- a/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBus.java +++ b/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBus.java @@ -11,7 +11,7 @@ @ApplicationScoped public class MainEventBus { private static final Logger LOGGER = LoggerFactory.getLogger(MainEventBus.class); - private final BlockingQueue queue; + private final BlockingQueue queue; public MainEventBus() { this.queue = new LinkedBlockingDeque<>(); @@ -28,11 +28,14 @@ void submit(String taskId, EventQueue.MainQueue mainQueue, EventQueueItem item) } } - MainEventBusContext take() throws InterruptedException { + void submit(Runnable action) { + queue.add(action); + } + + Object take() throws InterruptedException { LOGGER.debug("MainEventBus: Waiting to take event (current queue size: {})...", queue.size()); - MainEventBusContext context = queue.take(); - LOGGER.debug("MainEventBus: Took event for task {} (remaining queue size: {})", - context.taskId(), queue.size()); + Object context = queue.take(); + LOGGER.debug("MainEventBus: Took item (remaining queue size: {})", queue.size()); return context; } diff --git a/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java b/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java index 5a8e32cc7..5e6869b35 100644 --- a/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java +++ b/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java @@ -20,6 +20,7 @@ import org.a2aproject.sdk.spec.A2AError; import org.a2aproject.sdk.spec.Event; import org.a2aproject.sdk.spec.InternalError; +import org.a2aproject.sdk.spec.Message; import org.a2aproject.sdk.spec.StreamingEventKind; import org.a2aproject.sdk.spec.Task; import org.a2aproject.sdk.spec.TaskArtifactUpdateEvent; @@ -89,6 +90,13 @@ private record UpdateResult(boolean isFinal, @Nullable Task taskSnapshot) {} */ private final ConcurrentHashMap> pushNotificationChains = new ConcurrentHashMap<>(); + /** + * Initial client messages for tasks that have not emitted their first event yet. Event + * persistence creates its own TaskManager, so this preserves the message that opened a task + * when that first event creates the task in the TaskStore. + */ + private final ConcurrentHashMap initialMessages = new ConcurrentHashMap<>(); + private MainEventBus eventBus; private TaskStore taskStore; @@ -130,6 +138,21 @@ public void setCallback(MainEventBusProcessorCallback callback) { this.callback = callback != null ? callback : MainEventBusProcessorCallback.NOOP; } + /** + * Registers the message that opens a new task until its first event is persisted. + * + * @param taskId the new task identifier + * @param message the opening client message + */ + public void registerInitialMessage(String taskId, Message message) { + initialMessages.put(taskId, message); + } + + /** Remove a registration after all events already submitted by the agent are processed. */ + public void clearInitialMessageAfterEvents(String taskId) { + eventBus.submit(() -> initialMessages.remove(taskId)); + } + /** * Set a custom executor for push notifications (primarily for testing). *

@@ -198,10 +221,12 @@ public void run() { while (running) { try { LOGGER.debug("MainEventBusProcessor: Waiting for event from MainEventBus..."); - MainEventBusContext context = eventBus.take(); - LOGGER.debug("MainEventBusProcessor: Retrieved event for task {} from MainEventBus", - context.taskId()); - processEvent(context); + Object item = eventBus.take(); + if (item instanceof MainEventBusContext context) { + processEvent(context); + } else if (item instanceof Runnable action) { + action.run(); + } } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOGGER.info("MainEventBusProcessor interrupted, shutting down"); @@ -225,16 +250,23 @@ private void processEvent(MainEventBusContext context) { Event eventToDistribute = null; UpdateResult updateResult = null; + boolean persisted = false; boolean isReplicated = context.eventQueueItem().isReplicated(); try { // Step 1: Update TaskStore FIRST (persistence before clients see it) // If this throws, we distribute an error to ensure "persist before client visibility" try { - updateResult = updateTaskStore(taskId, event, isReplicated); + Message initialMessage = initialMessages.get(taskId); + updateResult = updateTaskStore(taskId, event, isReplicated, initialMessage); + if (event instanceof Task || event instanceof TaskStatusUpdateEvent + || event instanceof TaskArtifactUpdateEvent || event instanceof A2AError) { + initialMessages.remove(taskId); + } boolean isFinal = updateResult.isFinal(); - eventToDistribute = event; // Success - distribute original event + eventToDistribute = event instanceof Task && updateResult.taskSnapshot() != null + ? updateResult.taskSnapshot() : event; // Trigger replication AFTER successful persistence // SKIP replication if task is final - ReplicatedQueueManager handles this via TaskFinalizedEvent @@ -243,11 +275,13 @@ private void processEvent(MainEventBusContext context) { EventEnqueueHook hook = mainQueue.getEnqueueHook(); if (hook != null) { LOGGER.debug("Triggering replication hook for task {} after successful persistence", taskId); - hook.onEnqueue(context.eventQueueItem()); + hook.onEnqueue(eventToDistribute == event ? context.eventQueueItem() + : new LocalEventQueueItem(eventToDistribute)); } } else { LOGGER.debug("Task {} is final - skipping replication hook (handled by ReplicatedQueueManager)", taskId); } + persisted = true; } catch (InternalError e) { // Persistence failed - create error event to distribute instead LOGGER.error("Failed to persist event for task {}, distributing error to clients", taskId, e); @@ -263,7 +297,8 @@ private void processEvent(MainEventBusContext context) { // Skip push notifications for replicated events to avoid duplicate notifications in multi-instance deployments // Push notifications are sent for all StreamingEventKind events (Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) // per A2A spec section 4.3.3 - if (!isReplicated && eventToDistribute == event && event instanceof StreamingEventKind streamingEvent) { + if (!isReplicated && persisted && eventToDistribute instanceof StreamingEventKind streamingEvent + && (!(eventToDistribute instanceof Message message) || message.taskId() != null)) { // Send the streaming event directly - it will be wrapped in StreamResponse format by PushNotificationSender sendPushNotification(taskId, streamingEvent, updateResult != null ? updateResult.taskSnapshot() : null); } @@ -299,7 +334,7 @@ private void processEvent(MainEventBusContext context) { // Step 5: If this is a final event, notify task finalization // Only for successful persistence (not for errors) - if (eventToDistribute == event && isFinalEvent(event)) { + if (persisted && isFinalEvent(eventToDistribute)) { callback.onTaskFinalized(taskId); } } @@ -329,13 +364,14 @@ private void processEvent(MainEventBusContext context) { * @return true if the task reached a final state, false otherwise * @throws InternalError if persistence fails */ - private UpdateResult updateTaskStore(String taskId, Event event, boolean isReplicated) throws InternalError { + private UpdateResult updateTaskStore(String taskId, Event event, boolean isReplicated, + @Nullable Message initialMessage) throws InternalError { try { // Extract contextId from event (all relevant events have it) String contextId = extractContextId(event); // Create temporary TaskManager instance for this event - TaskManager taskManager = new TaskManager(taskId, contextId, taskStore, null); + TaskManager taskManager = new TaskManager(taskId, contextId, taskStore, initialMessage); // Use TaskManager.process() - handles all event types with existing logic AtomicReference taskSnapshot = new AtomicReference<>(); diff --git a/server-common/src/main/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandler.java b/server-common/src/main/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandler.java index 2bbc5a245..e9ceed2ae 100644 --- a/server-common/src/main/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandler.java +++ b/server-common/src/main/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandler.java @@ -819,34 +819,49 @@ public EventKind onMessageSend(MessageSendParams rawParams, ServerCallContext co mss.requestContext.getTaskId(), "TaskId must be non-null after RequestContext.build()"); LOGGER.debug("Queue taskId: {}", queueTaskId); - // Create queue with real taskId (no tempId parameter needed) - EventQueue queue = queueManager.createOrTap(queueTaskId); + boolean agentStarted = false; + EventQueue queue; + ResultAggregator resultAggregator; + EventConsumer consumer; + boolean blocking; final java.util.concurrent.atomic.AtomicReference<@NonNull String> taskId = new java.util.concurrent.atomic.AtomicReference<>(queueTaskId); - ResultAggregator resultAggregator = new ResultAggregator(mss.taskManager, null, executor, eventConsumerExecutor, - SECONDS.toNanos(reconciliationTimeoutSeconds)); + try { + if (mss.task() == null) { + mainEventBusProcessor.registerInitialMessage(queueTaskId, params.message()); + } + // Create queue with real taskId (no tempId parameter needed) + queue = queueManager.createOrTap(queueTaskId); + resultAggregator = new ResultAggregator(mss.taskManager, null, executor, eventConsumerExecutor, + SECONDS.toNanos(reconciliationTimeoutSeconds)); + + // Default to blocking per A2A spec (returnImmediately defaults to false, meaning wait for completion) + boolean returnImmediately = params.configuration() != null && Boolean.TRUE.equals(params.configuration().returnImmediately()); + blocking = !returnImmediately; + + // Log return behavior from client request + if (params.configuration() != null && params.configuration().returnImmediately() != null) { + LOGGER.debug("DefaultRequestHandler: Client requested returnImmediately={}, using blocking={} for task {}", + params.configuration().returnImmediately(), blocking, taskId.get()); + } else if (params.configuration() != null) { + LOGGER.debug("DefaultRequestHandler: Client sent configuration but returnImmediately=null, using default blocking={} for task {}", blocking, taskId.get()); + } else { + LOGGER.debug("DefaultRequestHandler: Client sent no configuration, using default blocking={} for task {}", blocking, taskId.get()); + } + LOGGER.debug("DefaultRequestHandler: Final blocking decision: {} for task {}", blocking, taskId.get()); - // Default to blocking per A2A spec (returnImmediately defaults to false, meaning wait for completion) - boolean returnImmediately = params.configuration() != null && Boolean.TRUE.equals(params.configuration().returnImmediately()); - boolean blocking = !returnImmediately; + // Create consumer BEFORE starting agent - callback is registered inside registerAndExecuteAgentAsync + consumer = new EventConsumer(queue, eventConsumerExecutor); - // Log return behavior from client request - if (params.configuration() != null && params.configuration().returnImmediately() != null) { - LOGGER.debug("DefaultRequestHandler: Client requested returnImmediately={}, using blocking={} for task {}", - params.configuration().returnImmediately(), blocking, taskId.get()); - } else if (params.configuration() != null) { - LOGGER.debug("DefaultRequestHandler: Client sent configuration but returnImmediately=null, using default blocking={} for task {}", blocking, taskId.get()); - } else { - LOGGER.debug("DefaultRequestHandler: Client sent no configuration, using default blocking={} for task {}", blocking, taskId.get()); + registerAndExecuteAgentAsync(queueTaskId, mss.requestContext, queue, consumer.createAgentRunnableDoneCallback()); + agentStarted = true; + } finally { + if (!agentStarted) { + mainEventBusProcessor.clearInitialMessageAfterEvents(queueTaskId); + } } - LOGGER.debug("DefaultRequestHandler: Final blocking decision: {} for task {}", blocking, taskId.get()); boolean interruptedOrNonBlocking = false; - // Create consumer BEFORE starting agent - callback is registered inside registerAndExecuteAgentAsync - EventConsumer consumer = new EventConsumer(queue, eventConsumerExecutor); - - EnhancedRunnable producerRunnable = registerAndExecuteAgentAsync(queueTaskId, mss.requestContext, queue, consumer.createAgentRunnableDoneCallback()); - ResultAggregator.EventTypeAndInterrupt etai = null; EventKind kind = null; // Declare outside try block so it's in scope for return try { @@ -1034,35 +1049,49 @@ public Flow.Publisher onMessageSendStream( mss.requestContext.getTaskId(), "TaskId must be non-null after RequestContext.build()"); final AtomicReference<@NonNull String> taskId = new AtomicReference<>(queueTaskId); - // Create queue with real taskId (no tempId parameter needed) - EventQueue queue = queueManager.createOrTap(queueTaskId); - LOGGER.debug("Created/tapped queue for task {}: {}", taskId.get(), queue); + boolean agentStarted = false; + EventQueue queue; + ResultAggregator resultAggregator; + EventConsumer consumer; + try { + if (mss.task() == null) { + mainEventBusProcessor.registerInitialMessage(queueTaskId, params.message()); + } + // Create queue with real taskId (no tempId parameter needed) + queue = queueManager.createOrTap(queueTaskId); + LOGGER.debug("Created/tapped queue for task {}: {}", taskId.get(), queue); - // Record ownership synchronously for new tasks before agent starts - if (mss.task() == null) { - recordOwnershipIfNeeded(context, queueTaskId, TaskOperation.MESSAGE_SEND_STREAM); - } + // Record ownership synchronously for new tasks before agent starts + if (mss.task() == null) { + recordOwnershipIfNeeded(context, queueTaskId, TaskOperation.MESSAGE_SEND_STREAM); + } - // Store push notification config SYNCHRONOUSLY for new tasks before agent starts - // This ensures config is available when MainEventBusProcessor sends push notifications - // For existing tasks, config is stored in initMessageSend() - if (mss.task() == null && shouldAddPushInfo(params)) { - // Satisfy Nullaway - Objects.requireNonNull(taskId.get(), "taskId was null"); - LOGGER.debug("Storing push notification config for new streaming task {} EARLY (original taskId from params: {})", - taskId.get(), params.message().taskId()); - String version = context != null ? context.getRequestedProtocolVersion() : null; - pushConfigStore.setInfo(TaskPushNotificationConfig.builder(params.configuration().taskPushNotificationConfig()) - .taskId(taskId.get()).build(), version); - } + // Store push notification config SYNCHRONOUSLY for new tasks before agent starts + // This ensures config is available when MainEventBusProcessor sends push notifications + // For existing tasks, config is stored in initMessageSend() + if (mss.task() == null && shouldAddPushInfo(params)) { + // Satisfy Nullaway + Objects.requireNonNull(taskId.get(), "taskId was null"); + LOGGER.debug("Storing push notification config for new streaming task {} EARLY (original taskId from params: {})", + taskId.get(), params.message().taskId()); + String version = context != null ? context.getRequestedProtocolVersion() : null; + pushConfigStore.setInfo(TaskPushNotificationConfig.builder(params.configuration().taskPushNotificationConfig()) + .taskId(taskId.get()).build(), version); + } - ResultAggregator resultAggregator = new ResultAggregator(mss.taskManager, null, executor, eventConsumerExecutor, - SECONDS.toNanos(reconciliationTimeoutSeconds)); + resultAggregator = new ResultAggregator(mss.taskManager, null, executor, eventConsumerExecutor, + SECONDS.toNanos(reconciliationTimeoutSeconds)); - // Create consumer BEFORE starting agent - callback is registered inside registerAndExecuteAgentAsync - EventConsumer consumer = new EventConsumer(queue, eventConsumerExecutor); + // Create consumer BEFORE starting agent - callback is registered inside registerAndExecuteAgentAsync + consumer = new EventConsumer(queue, eventConsumerExecutor); - EnhancedRunnable producerRunnable = registerAndExecuteAgentAsync(queueTaskId, mss.requestContext, queue, consumer.createAgentRunnableDoneCallback()); + registerAndExecuteAgentAsync(queueTaskId, mss.requestContext, queue, consumer.createAgentRunnableDoneCallback()); + agentStarted = true; + } finally { + if (!agentStarted) { + mainEventBusProcessor.clearInitialMessageAfterEvents(queueTaskId); + } + } // Store cancel callback in context for closeHandler to access // When client disconnects, closeHandler can call this to stop EventConsumer polling loop @@ -1213,7 +1242,7 @@ public TaskPushNotificationConfig onGetTaskPushNotificationConfig( ListTaskPushNotificationConfigsResult listTaskPushNotificationConfigsResult = pushConfigStore.getInfo(new ListTaskPushNotificationConfigsParams(params.taskId())); if (listTaskPushNotificationConfigsResult == null || listTaskPushNotificationConfigsResult.isEmpty()) { - throw new InternalError("No push notification config found"); + throw new TaskNotFoundError("No push notification config found", null); } String requestedConfigId = params.id(); @@ -1414,6 +1443,7 @@ public void run() { } // Queue lifecycle is managed by EventConsumer.consumeAll() // which closes the queue on final events. + mainEventBusProcessor.clearInitialMessageAfterEvents(taskId); logThreadStats("AGENT COMPLETE END"); runnable.invokeDoneCallbacks(); }); diff --git a/server-common/src/main/java/org/a2aproject/sdk/server/tasks/AgentEmitter.java b/server-common/src/main/java/org/a2aproject/sdk/server/tasks/AgentEmitter.java index 2f5dcad8a..89c6e7a7f 100644 --- a/server-common/src/main/java/org/a2aproject/sdk/server/tasks/AgentEmitter.java +++ b/server-common/src/main/java/org/a2aproject/sdk/server/tasks/AgentEmitter.java @@ -103,6 +103,7 @@ public class AgentEmitter { private final String taskId; private final String contextId; private final AtomicBoolean terminalStateReached = new AtomicBoolean(false); + private final AtomicBoolean taskAssociated; /** * Creates a new AgentEmitter for the given request context and event queue. @@ -114,6 +115,7 @@ public AgentEmitter(RequestContext context, EventQueue eventQueue) { this.eventQueue = eventQueue; this.taskId = context.getTaskId(); this.contextId = context.getContextId(); + this.taskAssociated = new AtomicBoolean(context.getTask() != null); } /** @@ -144,6 +146,7 @@ public void updateStatus(TaskState taskState, @Nullable Message message) { } else { eventQueue.enqueueEvent(event); } + taskAssociated.set(true); } private void enqueueTerminalEvent(Event event) { @@ -233,6 +236,7 @@ public void addArtifact(List> parts, @Nullable String artifactId, @Nulla .lastChunk(lastChunk) .build(); eventQueue.enqueueEvent(event); + taskAssociated.set(true); } /** @@ -524,22 +528,22 @@ public void sendMessage(List> parts) { /** * Sends a message with parts and metadata to the client. - * Creates an agent message with the current task and context IDs (if available) - * and enqueues it to the event queue. + * Creates an agent message with the current context ID and, if a task already exists + * or a task event has been emitted, the task ID. Enqueues it to the event queue. * * @param parts the message parts to send * @param metadata optional metadata to attach to the message */ public void sendMessage(List> parts, @Nullable Map metadata) { - Message message = newAgentMessage(parts, metadata); - eventQueue.enqueueEvent(message); + sendMessage(newAgentMessage(parts, metadata)); } /** * Sends an existing Message object directly to the client. *

* Use this when you need to forward or echo an existing message without creating a new one. - * The message is enqueued as-is, preserving its messageId, metadata, and all other fields. + * The message is enqueued preserving its fields, except that its task ID is omitted + * if no task exists or task event has been emitted. *

*

* Note: This is typically used for forwarding user messages or preserving specific @@ -566,7 +570,8 @@ public void sendMessage(Message message) { LOGGER.error("Message contextId mismatch: expected={}, actual={}", contextId, message.contextId()); throw new IllegalArgumentException("Message contextId does not match the emitter's contextId"); } - eventQueue.enqueueEvent(message); + eventQueue.enqueueEvent(!taskAssociated.get() && message.taskId() != null + ? Message.builder(message).taskId(null).build() : message); } /** @@ -597,6 +602,7 @@ public void sendMessage(Message message) { */ public void addTask(Task task) { eventQueue.enqueueEvent(task); + taskAssociated.set(true); } /** @@ -625,6 +631,9 @@ public void addTask(Task task) { */ public void emitEvent(Event event) { eventQueue.enqueueEvent(event); + if (event instanceof Task || event instanceof TaskStatusUpdateEvent || event instanceof TaskArtifactUpdateEvent) { + taskAssociated.set(true); + } } /** diff --git a/server-common/src/main/java/org/a2aproject/sdk/server/tasks/TaskManager.java b/server-common/src/main/java/org/a2aproject/sdk/server/tasks/TaskManager.java index 775975727..a35c84609 100644 --- a/server-common/src/main/java/org/a2aproject/sdk/server/tasks/TaskManager.java +++ b/server-common/src/main/java/org/a2aproject/sdk/server/tasks/TaskManager.java @@ -70,9 +70,19 @@ boolean saveTaskEvent(Task task, boolean isReplicated) throws A2AServerException boolean saveTaskEvent(Task task, boolean isReplicated, @Nullable AtomicReference taskSnapshot) throws A2AServerException { checkIdsAndUpdateIfNecessary(task.id(), task.contextId()); + Task current = getTask(); + if (current == null && initialMessage != null + && (task.history() == null || task.history().stream() + .noneMatch(message -> message.messageId().equals(initialMessage.messageId())))) { + List history = new ArrayList<>(); + history.add(initialMessage); + if (task.history() != null) { + history.addAll(task.history()); + } + task = Task.builder(task).history(history).build(); + } // Defensive state-machine check: a task that already reached a terminal state must // not be overwritten by a task snapshot carrying a different state. - Task current = getTask(); if (current != null && current.status() != null && current.status().state() != null && task.status() != null && task.status().state() != null) { validateStateTransition(current.status().state(), task.status().state(), task.id()); diff --git a/server-common/src/test/java/org/a2aproject/sdk/server/InputModeValidatorTest.java b/server-common/src/test/java/org/a2aproject/sdk/server/InputModeValidatorTest.java new file mode 100644 index 000000000..b1ee44112 --- /dev/null +++ b/server-common/src/test/java/org/a2aproject/sdk/server/InputModeValidatorTest.java @@ -0,0 +1,161 @@ +package org.a2aproject.sdk.server; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; +import java.util.Locale; + +import org.a2aproject.sdk.spec.AgentCapabilities; +import org.a2aproject.sdk.spec.AgentCard; +import org.a2aproject.sdk.spec.AgentInterface; +import org.a2aproject.sdk.spec.AgentSkill; +import org.a2aproject.sdk.spec.ContentTypeNotSupportedError; +import org.a2aproject.sdk.spec.FilePart; +import org.a2aproject.sdk.spec.FileWithUri; +import org.a2aproject.sdk.spec.Message; +import org.a2aproject.sdk.spec.TextPart; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; + +class InputModeValidatorTest { + + @Test + void acceptsDeclaredPartMediaType() { + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType("text/plain"), + card(List.of("text/plain"), List.of()))); + } + + @Test + void textInputModeAcceptsPlainTextButNotOtherTypes() { + AgentCard card = card(List.of("text"), List.of()); + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType("Text/Plain; charset=utf-8"), card)); + assertThrows(ContentTypeNotSupportedError.class, + () -> InputModeValidator.validate(messageWithMediaType("text/html"), card)); + assertThrows(ContentTypeNotSupportedError.class, + () -> InputModeValidator.validate(messageWithMediaType("application/json"), card)); + } + + @Test + void mediaInputModeAliasesAcceptTheirMediaTypeFamilies() { + for (String mode : List.of("audio", "image", "video")) { + AgentCard card = card(List.of(mode.toUpperCase(Locale.ROOT)), List.of()); + Message message = Message.builder().messageId("file").role(Message.Role.ROLE_USER) + .parts(new FilePart(new FileWithUri(mode + "/example", "file", "https://example.com/file"))) + .build(); + assertDoesNotThrow(() -> InputModeValidator.validate(message, card)); + assertThrows(ContentTypeNotSupportedError.class, + () -> InputModeValidator.validate(messageWithMediaType("application/json"), card)); + } + } + + @Test + void acceptsMediaInputModeAliasDeclaredByASkill() { + AgentSkill skill = AgentSkill.builder().id("audio").name("Audio").description("Handles audio") + .tags(List.of()).inputModes(List.of("audio")).build(); + + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType("audio/wav"), + card(List.of("text"), List.of(skill)))); + } + + @Test + void matchesMediaTypeCaseParametersAndRanges() { + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType("Text/Plain; charset=utf-8"), + card(List.of("text/plain"), List.of()))); + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType("image/png"), + card(List.of("IMAGE/*"), List.of()))); + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType("application/json"), + card(List.of("*/*"), List.of()))); + assertThrows(ContentTypeNotSupportedError.class, + () -> InputModeValidator.validate(messageWithMediaType("image/png"), + card(List.of("text/*"), List.of()))); + assertThrows(ContentTypeNotSupportedError.class, + () -> InputModeValidator.validate(messageWithMediaType("text/plain; charset=iso-8859-1"), + card(List.of("text/plain; charset=utf-8"), List.of()))); + } + + @Test + void comparesMimeParametersSemantically() { + AgentCard card = card(List.of("text/plain; charset=utf-8; format=flowed"), List.of()); + assertDoesNotThrow(() -> InputModeValidator.validate( + messageWithMediaType("Text/Plain; FORMAT=flowed; Charset=\"UTF-8\"; extra=value"), card)); + assertThrows(ContentTypeNotSupportedError.class, () -> InputModeValidator.validate( + messageWithMediaType("text/plain; charset=utf-8; format=FLOWED"), card)); + assertThrows(ContentTypeNotSupportedError.class, () -> InputModeValidator.validate( + messageWithMediaType("text/plain; charset=\"unterminated"), card)); + assertDoesNotThrow(() -> InputModeValidator.validate( + messageWithMediaType("application/example; key=\"a;b\""), + card(List.of("application/example; KEY=\"a;b\""), List.of()))); + } + + @Test + void validatesMultiplePartsAgainstParsedInputModes() { + AgentCard card = card(List.of("text/plain; charset=utf-8", "application/json", "invalid; key=\"broken"), List.of()); + Message message = Message.builder().messageId("multiple-parts").role(Message.Role.ROLE_USER) + .parts(List.of(new TextPart("first", null, "text/plain; Charset=\"UTF-8\""), + new TextPart("second", null, "application/json"))) + .build(); + assertDoesNotThrow(() -> InputModeValidator.validate(message, card)); + assertThrows(ContentTypeNotSupportedError.class, + () -> InputModeValidator.validate(messageWithMediaType("invalid"), card)); + } + + @Test + void rejectsUndeclaredPartMediaType() { + ContentTypeNotSupportedError error = assertThrows(ContentTypeNotSupportedError.class, + () -> InputModeValidator.validate(messageWithMediaType("image/png"), + card(List.of("text/plain"), List.of()))); + + assertEquals("Input media type is not supported: image/png", error.getMessage()); + } + + @Test + void acceptsMediaTypeDeclaredByASkill() { + AgentSkill imageSkill = AgentSkill.builder() + .id("image") + .name("Image analysis") + .description("Analyzes images") + .tags(List.of()) + .inputModes(List.of("image/png")) + .build(); + + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType("image/png"), + card(List.of("text/plain"), List.of(imageSkill)))); + } + + @Test + void acceptsExplicitAndOmittedMediaTypesWhenTheCardDeclaresNoInputModes() { + AgentCard card = card(List.of(), List.of()); + + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType("image/png"), card)); + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType(null), card)); + } + + @Test + void doesNotRejectPartWithoutAnExplicitMediaType() { + assertDoesNotThrow(() -> InputModeValidator.validate(messageWithMediaType(null), + card(List.of("text/plain"), List.of()))); + } + + private static Message messageWithMediaType(@Nullable String mediaType) { + return Message.builder() + .role(Message.Role.ROLE_USER) + .parts(new TextPart("hello", null, mediaType)) + .messageId("message-1") + .build(); + } + + private static AgentCard card(List inputModes, List skills) { + return AgentCard.builder() + .name("Input validator test agent") + .description("Input validator test agent") + .supportedInterfaces(List.of(new AgentInterface("HTTP+JSON", "https://example.com/a2a"))) + .version("1.0.0") + .capabilities(AgentCapabilities.builder().build()) + .defaultInputModes(inputModes) + .defaultOutputModes(List.of("text/plain")) + .skills(skills) + .build(); + } +} diff --git a/server-common/src/test/java/org/a2aproject/sdk/server/events/MainEventBusTaskSnapshotTest.java b/server-common/src/test/java/org/a2aproject/sdk/server/events/MainEventBusTaskSnapshotTest.java new file mode 100644 index 000000000..2798f931e --- /dev/null +++ b/server-common/src/test/java/org/a2aproject/sdk/server/events/MainEventBusTaskSnapshotTest.java @@ -0,0 +1,119 @@ +package org.a2aproject.sdk.server.events; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.a2aproject.sdk.server.tasks.InMemoryTaskStore; +import org.a2aproject.sdk.server.tasks.PushNotificationSender; +import org.a2aproject.sdk.spec.Artifact; +import org.a2aproject.sdk.spec.Event; +import org.a2aproject.sdk.spec.Message; +import org.a2aproject.sdk.spec.Task; +import org.a2aproject.sdk.spec.TaskArtifactUpdateEvent; +import org.a2aproject.sdk.spec.TaskState; +import org.a2aproject.sdk.spec.TaskStatus; +import org.a2aproject.sdk.spec.TaskStatusUpdateEvent; +import org.a2aproject.sdk.spec.TextPart; +import org.junit.jupiter.api.Test; + +class MainEventBusTaskSnapshotTest { + @Test + void firstStatusOrArtifactUpdatePreservesOpeningMessage() throws Exception { + InMemoryTaskStore store = new InMemoryTaskStore(); + MainEventBus bus = new MainEventBus(); + InMemoryQueueManager queues = new InMemoryQueueManager(store, bus); + MainEventBusProcessor processor = new MainEventBusProcessor(bus, store, PushNotificationSender.NOOP, queues); + EventQueueUtil.start(processor); + try { + Message opening = Message.builder().messageId("opening").role(Message.Role.ROLE_USER) + .parts(new TextPart("hello")).build(); + List events = List.of( + TaskStatusUpdateEvent.builder().taskId("status").contextId("context") + .status(new TaskStatus(TaskState.TASK_STATE_WORKING)).build(), + TaskArtifactUpdateEvent.builder().taskId("artifact").contextId("context") + .artifact(Artifact.builder().artifactId("output").parts(new TextPart("result")).build()) + .build()); + List ids = List.of("status", "artifact"); + for (int i = 0; i < ids.size(); i++) { + String id = ids.get(i); + processor.registerInitialMessage(id, opening); + EventQueue queue = EventQueueUtil.getEventQueueBuilder(bus).taskId(id).build().tap(); + queue.enqueueEvent(events.get(i)); + queue.dequeueEventItem(5000); + assertEquals(List.of(opening), store.get(id).history()); + } + } finally { + EventQueueUtil.stop(processor); + } + } + + @Test + void persistedTaskIsDispatchedReplicatedAndNotified() throws Exception { + String id = "task-snapshot"; + InMemoryTaskStore store = new InMemoryTaskStore(); + MainEventBus bus = new MainEventBus(); + InMemoryQueueManager queues = new InMemoryQueueManager(store, bus); + CountDownLatch delivered = new CountDownLatch(1); + AtomicReference notified = new AtomicReference<>(); + AtomicReference replicated = new AtomicReference<>(); + PushNotificationSender sender = (event, snapshot) -> { + notified.set((Task) event); + delivered.countDown(); + return true; + }; + MainEventBusProcessor processor = new MainEventBusProcessor(bus, store, sender, queues); + EventQueueUtil.start(processor); + try { + Message opening = Message.builder().messageId("opening").role(Message.Role.ROLE_USER) + .parts(new TextPart("hello")).build(); + processor.registerInitialMessage(id, opening); + EventQueue queue = EventQueueUtil.getEventQueueBuilder(bus).taskId(id) + .hook(item -> replicated.set((Task) item.getEvent())).build().tap(); + queue.enqueueEvent(Task.builder().id(id).contextId("context") + .status(new TaskStatus(TaskState.TASK_STATE_WORKING)).build()); + Event event = queue.dequeueEventItem(5000).getEvent(); + assertTrue(delivered.await(5, TimeUnit.SECONDS)); + Task stored = store.get(id); + assertEquals(List.of(opening), stored.history()); + assertEquals(stored, event); + assertEquals(stored, replicated.get()); + assertEquals(stored, notified.get()); + } finally { + EventQueueUtil.stop(processor); + } + } + @Test + void finalTaskSnapshotStillTriggersFinalizationCallback() throws Exception { + String id = "final-task-snapshot"; + InMemoryTaskStore store = new InMemoryTaskStore(); + MainEventBus bus = new MainEventBus(); + InMemoryQueueManager queues = new InMemoryQueueManager(store, bus); + MainEventBusProcessor processor = new MainEventBusProcessor(bus, store, PushNotificationSender.NOOP, queues); + CountDownLatch finalized = new CountDownLatch(1); + processor.setCallback(new MainEventBusProcessorCallback() { + public void onEventProcessed(String taskId, Event event) { + } + public void onTaskFinalized(String taskId) { + finalized.countDown(); + } + }); + EventQueueUtil.start(processor); + try { + Message opening = Message.builder().messageId("opening").role(Message.Role.ROLE_USER) + .parts(new TextPart("hello")).build(); + processor.registerInitialMessage(id, opening); + EventQueue queue = EventQueueUtil.getEventQueueBuilder(bus).taskId(id).build().tap(); + queue.enqueueEvent(Task.builder().id(id).contextId("context") + .status(new TaskStatus(TaskState.TASK_STATE_COMPLETED)).build()); + assertTrue(finalized.await(5, TimeUnit.SECONDS)); + assertEquals(List.of(opening), store.get(id).history()); + } finally { + EventQueueUtil.stop(processor); + } + } +} diff --git a/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandlerTest.java b/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandlerTest.java index 75bd43905..9136cf16d 100644 --- a/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandlerTest.java +++ b/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandlerTest.java @@ -1,5 +1,6 @@ package org.a2aproject.sdk.server.requesthandlers; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -991,6 +992,105 @@ void testSendMessage_WithBlankTaskId_TreatedAsNewTask(String taskId) throws Exce assertNull(taskStore.get(""), "No task should ever be stored under the empty-string id"); } + @Test + void streamingMessageBeforeTaskPreservesOpeningHistory() throws Exception { + CountDownLatch taskPersisted = new CountDownLatch(1); + AtomicReference taskId = new AtomicReference<>(); + mainEventBusProcessor.setCallback(new MainEventBusProcessorCallback() { + @Override + public void onEventProcessed(String id, Event event) { + if (event instanceof TaskStatusUpdateEvent) { + taskPersisted.countDown(); + } + } + @Override + public void onTaskFinalized(String id) { + } + }); + agentExecutorExecute = (context, emitter) -> { + taskId.set(context.getTaskId()); + emitter.sendMessage(List.of(new TextPart("first")), null); + emitter.complete(); + }; + Message opening = Message.builder().messageId("opening") + .role(Message.Role.ROLE_USER).parts(new TextPart("hello")).build(); + MessageSendParams params = MessageSendParams.builder().message(opening).build(); + CountDownLatch done = new CountDownLatch(1); + AtomicReference error = new AtomicReference<>(); + List events = new java.util.concurrent.CopyOnWriteArrayList<>(); + requestHandler.onMessageSendStream(params, contextWithEffectiveCard(true)).subscribe(new Flow.Subscriber<>() { + public void onSubscribe(Flow.Subscription subscription) { subscription.request(Long.MAX_VALUE); } + public void onNext(StreamingEventKind event) { events.add(event); } + public void onError(Throwable throwable) { error.set(throwable); done.countDown(); } + public void onComplete() { done.countDown(); } + }); + assertTrue(done.await(5, TimeUnit.SECONDS)); + assertNull(error.get()); + assertInstanceOf(Message.class, events.get(0)); + assertTrue(taskPersisted.await(5, TimeUnit.SECONDS)); + assertNotNull(taskId.get()); + assertEquals("opening", taskStore.get(taskId.get()).history().get(0).messageId()); + } + + @Test + void streamingFullTaskMatchesPersistedHistory() throws Exception { + Message reply = Message.builder().messageId("reply").role(Message.Role.ROLE_AGENT) + .parts(new TextPart("response")).build(); + agentExecutorExecute = (context, emitter) -> emitter.addTask(emitter.taskBuilder() + .status(new TaskStatus(TaskState.TASK_STATE_COMPLETED)).history(List.of(reply)).build()); + Message opening = Message.builder().messageId("opening").role(Message.Role.ROLE_USER) + .parts(new TextPart("hello")).build(); + CountDownLatch done = new CountDownLatch(1); + AtomicReference streamed = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + requestHandler.onMessageSendStream(MessageSendParams.builder().message(opening).build(), + contextWithEffectiveCard(true)).subscribe(new Flow.Subscriber<>() { + public void onSubscribe(Flow.Subscription subscription) { subscription.request(Long.MAX_VALUE); } + public void onNext(StreamingEventKind event) { + if (event instanceof Task task) { + streamed.set(task); + } + } + public void onError(Throwable throwable) { error.set(throwable); done.countDown(); } + public void onComplete() { done.countDown(); } + }); + assertTrue(done.await(5, TimeUnit.SECONDS)); + assertNull(error.get()); + Task task = streamed.get(); + assertNotNull(task); + assertEquals(List.of("opening", "reply"), task.history().stream().map(Message::messageId).toList()); + assertEquals(taskStore.get(task.id()), task); + } + + @Test + void initialMessageIsClearedWhenAgentEmitsNothing() throws Exception { + CountDownLatch finished = new CountDownLatch(1); + agentExecutorExecute = (context, emitter) -> finished.countDown(); + MessageSendParams params = MessageSendParams.builder().message(Message.builder() + .messageId("no-event").role(Message.Role.ROLE_USER).parts(new TextPart("hello")).build()).build(); + requestHandler.onMessageSendStream(params, contextWithEffectiveCard(true)); + assertTrue(finished.await(5, TimeUnit.SECONDS)); + assertInitialMessagesEventuallyEmpty(); + } + + @Test + void initialMessageIsClearedWhenExecutorSetupFails() throws Exception { + requestHandler = buildHandlerWithRouter(tenant -> { throw new IllegalStateException("setup failed"); }); + MessageSendParams params = MessageSendParams.builder().message(Message.builder() + .messageId("setup-failure").role(Message.Role.ROLE_USER).parts(new TextPart("hello")).build()).build(); + assertThrows(IllegalStateException.class, + () -> requestHandler.onMessageSendStream(params, contextWithEffectiveCard(true))); + assertInitialMessagesEventuallyEmpty(); + } + + private void assertInitialMessagesEventuallyEmpty() throws Exception { + var field = MainEventBusProcessor.class.getDeclaredField("initialMessages"); + field.setAccessible(true); + Map pending = (Map) field.get(mainEventBusProcessor); + await().atMost(5, TimeUnit.SECONDS) + .untilAsserted(() -> assertTrue(pending.isEmpty(), "opening messages should be cleared")); + } + /** * Streaming counterpart of {@link #testSendMessage_WithBlankTaskId_TreatedAsNewTask(String)}. */ @@ -1263,6 +1363,20 @@ void testGetTaskPushNotificationConfigDefaultsMissingIdToTaskId() throws Excepti assertEquals("http://example.com/get-default-config-id", result.url()); } + @Test + void testGetTaskPushNotificationConfigReturnsTaskNotFoundWhenNoConfigExists() throws Exception { + String taskId = "get-missing-config"; + taskStore.save(Task.builder() + .id(taskId) + .contextId("ctx-get-missing-config") + .status(new TaskStatus(TaskState.TASK_STATE_WORKING)) + .build(), false); + + assertThrows(TaskNotFoundError.class, + () -> requestHandler.onGetTaskPushNotificationConfig( + new GetTaskPushNotificationConfigParams(taskId, "missing-config"), NULL_CONTEXT)); + } + @ParameterizedTest @NullAndEmptySource void testGetTaskPushNotificationConfigDefaultsMissingIdToTaskIdWithEffectiveCard(String configId) diff --git a/server-common/src/test/java/org/a2aproject/sdk/server/tasks/AgentEmitterTest.java b/server-common/src/test/java/org/a2aproject/sdk/server/tasks/AgentEmitterTest.java index 6c8a8ae10..bb1a8dc94 100644 --- a/server-common/src/test/java/org/a2aproject/sdk/server/tasks/AgentEmitterTest.java +++ b/server-common/src/test/java/org/a2aproject/sdk/server/tasks/AgentEmitterTest.java @@ -22,8 +22,10 @@ import org.a2aproject.sdk.spec.Event; import org.a2aproject.sdk.spec.Message; import org.a2aproject.sdk.spec.Part; +import org.a2aproject.sdk.spec.Task; import org.a2aproject.sdk.spec.TaskArtifactUpdateEvent; import org.a2aproject.sdk.spec.TaskState; +import org.a2aproject.sdk.spec.TaskStatus; import org.a2aproject.sdk.spec.TaskStatusUpdateEvent; import org.a2aproject.sdk.spec.TextPart; import org.junit.jupiter.api.AfterEach; @@ -437,6 +439,62 @@ public void testConcurrentCompletionAttempts() throws Exception { assertNull(eventQueue.dequeueEventItem(0)); } + @Test + public void sendGeneratedMessageWithoutTaskOmitsTaskId() throws Exception { + agentEmitter.sendMessage("direct response"); + + EventQueueItem item = eventQueue.dequeueEventItem(WAIT_MILLI_SECONDS); + assertNotNull(item); + Message message = assertInstanceOf(Message.class, item.getEvent()); + assertNull(message.taskId()); + assertEquals(TEST_TASK_CONTEXT_ID, message.contextId()); + } + + @Test + public void sendExplicitGeneratedMessageWithoutTaskOmitsTaskId() throws Exception { + agentEmitter.sendMessage(agentEmitter.newAgentMessage(SAMPLE_PARTS, null)); + Message message = assertInstanceOf(Message.class, eventQueue.dequeueEventItem(WAIT_MILLI_SECONDS).getEvent()); + assertNull(message.taskId()); + assertEquals(TEST_TASK_CONTEXT_ID, message.contextId()); + } + + @Test + public void sendExplicitGeneratedMessageAfterTaskIncludesTaskId() throws Exception { + agentEmitter.startWork(); + assertNotNull(eventQueue.dequeueEventItem(WAIT_MILLI_SECONDS)); + agentEmitter.sendMessage(agentEmitter.newAgentMessage(SAMPLE_PARTS, null)); + Message message = assertInstanceOf(Message.class, eventQueue.dequeueEventItem(WAIT_MILLI_SECONDS).getEvent()); + assertEquals(TEST_TASK_ID, message.taskId()); + } + + @Test + public void sendGeneratedMessageAfterTaskEventIncludesTaskId() throws Exception { + agentEmitter.startWork(); + assertNotNull(eventQueue.dequeueEventItem(WAIT_MILLI_SECONDS)); + agentEmitter.sendMessage("task response"); + + EventQueueItem item = eventQueue.dequeueEventItem(WAIT_MILLI_SECONDS); + assertNotNull(item); + Message message = assertInstanceOf(Message.class, item.getEvent()); + assertEquals(TEST_TASK_ID, message.taskId()); + assertEquals(TEST_TASK_CONTEXT_ID, message.contextId()); + } + + @Test + public void sendGeneratedMessageForExistingTaskIncludesTaskId() throws Exception { + Task task = Task.builder().id(TEST_TASK_ID).contextId(TEST_TASK_CONTEXT_ID) + .status(new TaskStatus(TaskState.TASK_STATE_WORKING)).build(); + RequestContext context = new RequestContext.Builder().setTaskId(TEST_TASK_ID) + .setContextId(TEST_TASK_CONTEXT_ID).setTask(task).build(); + new AgentEmitter(context, eventQueue).sendMessage("task response"); + + EventQueueItem item = eventQueue.dequeueEventItem(WAIT_MILLI_SECONDS); + assertNotNull(item); + Message message = assertInstanceOf(Message.class, item.getEvent()); + assertEquals(TEST_TASK_ID, message.taskId()); + assertEquals(TEST_TASK_CONTEXT_ID, message.contextId()); + } + @Test public void sendMessageWithMatchingIdsSucceeds() throws Exception { agentEmitter.sendMessage(SAMPLE_MESSAGE); @@ -445,7 +503,7 @@ public void sendMessageWithMatchingIdsSucceeds() throws Exception { assertNotNull(item); assertInstanceOf(Message.class, item.getEvent()); Message message = (Message) item.getEvent(); - assertEquals(TEST_TASK_ID, message.taskId()); + assertNull(message.taskId()); assertEquals(TEST_TASK_CONTEXT_ID, message.contextId()); } diff --git a/server-common/src/test/java/org/a2aproject/sdk/server/tasks/TaskManagerTest.java b/server-common/src/test/java/org/a2aproject/sdk/server/tasks/TaskManagerTest.java index e36ad6cc9..5c1f2c771 100644 --- a/server-common/src/test/java/org/a2aproject/sdk/server/tasks/TaskManagerTest.java +++ b/server-common/src/test/java/org/a2aproject/sdk/server/tasks/TaskManagerTest.java @@ -8,6 +8,9 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.util.Collections; import java.util.HashMap; @@ -60,6 +63,38 @@ public void testGetTaskNonExistent() { assertNull(retrieved); } + @Test + public void savingTaskReadsStoreOnlyOnce() throws A2AServerException { + TaskStore store = spy(new InMemoryTaskStore()); + Message initial = Message.builder().role(Message.Role.ROLE_USER) + .messageId("opening").parts(List.of(new TextPart("hello"))).build(); + TaskManager manager = new TaskManager(minimalTask.id(), minimalTask.contextId(), store, initial); + + manager.saveTaskEvent(minimalTask, false); + + verify(store, times(1)).get(minimalTask.id()); + assertEquals("opening", store.get(minimalTask.id()).history().get(0).messageId()); + } + + @Test + void newTaskAddsOpeningMessageToExistingHistoryWithoutDuplicates() throws A2AServerException { + Message opening = Message.builder().role(Message.Role.ROLE_USER).messageId("opening") + .parts(List.of(new TextPart("hello"))).build(); + Message reply = Message.builder().role(Message.Role.ROLE_AGENT).messageId("reply") + .parts(List.of(new TextPart("response"))).build(); + TaskManager manager = new TaskManager(minimalTask.id(), minimalTask.contextId(), taskStore, opening); + manager.saveTaskEvent(Task.builder(minimalTask).history(List.of(reply)).build(), false); + assertEquals(List.of("opening", "reply"), manager.getTask().history().stream() + .map(Message::messageId).toList()); + + TaskStore anotherStore = new InMemoryTaskStore(); + TaskManager another = new TaskManager(minimalTask.id(), minimalTask.contextId(), anotherStore, opening); + Message sameId = Message.builder(opening).contextId("normalized-context").build(); + another.saveTaskEvent(Task.builder(minimalTask).history(List.of(sameId, reply)).build(), false); + assertEquals(List.of("opening", "reply"), another.getTask().history().stream() + .map(Message::messageId).toList()); + } + @Test public void testSaveTaskEventNewTask() throws A2AServerException { taskManager.saveTaskEvent(minimalTask, false); diff --git a/server-common/src/test/java/org/a2aproject/sdk/server/util/sse/SseFormatterTest.java b/server-common/src/test/java/org/a2aproject/sdk/server/util/sse/SseFormatterTest.java new file mode 100644 index 000000000..d69030eb2 --- /dev/null +++ b/server-common/src/test/java/org/a2aproject/sdk/server/util/sse/SseFormatterTest.java @@ -0,0 +1,37 @@ +package org.a2aproject.sdk.server.util.sse; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import java.util.List; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.a2aproject.sdk.jsonrpc.common.wrappers.SendStreamingMessageResponse; +import org.a2aproject.sdk.spec.Message; +import org.a2aproject.sdk.spec.TextPart; +import org.junit.jupiter.api.Test; + +class SseFormatterTest { + @Test + void directStreamingMessageOmitsTaskId() { + Message message = Message.builder().messageId("message").contextId("context") + .role(Message.Role.ROLE_AGENT).parts(List.of(new TextPart("hello"))).build(); + String event = SseFormatter.formatResponseAsSSE(new SendStreamingMessageResponse("request", message), 0); + String data = event.lines().filter(line -> line.startsWith("data: ")).findFirst().orElseThrow().substring(6); + JsonObject result = JsonParser.parseString(data).getAsJsonObject().getAsJsonObject("result") + .getAsJsonObject("message"); + assertFalse(result.has("taskId")); + assertEquals("context", result.get("contextId").getAsString()); + } + @Test + void taskAssociatedStreamingMessageKeepsTaskId() { + Message message = Message.builder().messageId("message").taskId("task").contextId("context") + .role(Message.Role.ROLE_AGENT).parts(List.of(new TextPart("hello"))).build(); + String event = SseFormatter.formatResponseAsSSE(new SendStreamingMessageResponse("request", message), 0); + String data = event.lines().filter(line -> line.startsWith("data: ")).findFirst().orElseThrow().substring(6); + JsonObject result = JsonParser.parseString(data).getAsJsonObject().getAsJsonObject("result") + .getAsJsonObject("message"); + assertEquals("task", result.get("taskId").getAsString()); + } +} diff --git a/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtils.java b/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtils.java index 5cc40a8c9..99c6d091f 100644 --- a/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtils.java +++ b/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtils.java @@ -263,7 +263,7 @@ private static A2ARequest parseMethodRequest(String version, Object id, Strin } case SEND_MESSAGE_METHOD -> { org.a2aproject.sdk.grpc.SendMessageRequest.Builder builder = org.a2aproject.sdk.grpc.SendMessageRequest.newBuilder(); - parseRequestBody(params, builder, id); + parseSendMessageParams(params, builder, id); setTenantIfAbsent(builder::getTenant, builder::setTenant, tenant); return new SendMessageRequest(version, id, ProtoUtils.FromProto.messageSendParams(builder)); } @@ -293,7 +293,7 @@ private static A2ARequest parseMethodRequest(String version, Object id, Strin } case SEND_STREAMING_MESSAGE_METHOD -> { org.a2aproject.sdk.grpc.SendMessageRequest.Builder builder = org.a2aproject.sdk.grpc.SendMessageRequest.newBuilder(); - parseRequestBody(params, builder, id); + parseSendMessageParams(params, builder, id); setTenantIfAbsent(builder::getTenant, builder::setTenant, tenant); return new SendStreamingMessageRequest(version, id, ProtoUtils.FromProto.messageSendParams(builder)); } @@ -462,6 +462,13 @@ protected static void parseRequestBody(JsonElement jsonRpc, com.google.protobuf. parseJsonString(jsonRpc.toString(), builder, id); } + // SendMessage permits extra top-level operation parameters; nested protocol objects remain strict. + private static void parseSendMessageParams(JsonElement jsonRpc, com.google.protobuf.Message.Builder builder, Object id) + throws JsonProcessingException { + JsonElement params = ProtoJsonUtils.retainKnownFields(jsonRpc, builder.getDescriptorForType()); + parseJsonString(params.toString(), builder, id); + } + public static void parseJsonString(String body, com.google.protobuf.Message.Builder builder, Object id) throws JsonProcessingException { parseJsonString(body, builder, id, false); } @@ -613,11 +620,42 @@ public static String toJsonRPCRequest(@Nullable String requestId, String method, } public static String toJsonRPCResultResponse(@Nullable Object requestId, com.google.protobuf.MessageOrBuilder builder) { + return toJsonRPCResultResponse(requestId, builder, RESPONSE_PRINTER); + } + + /** + * Serializes a ListTasks success response without empty task artifact arrays. + * + *

Other empty response fields, including {@code tasks}, remain present.

+ * + * @param requestId the request identifier + * @param builder the protobuf response + * @return a JSON-RPC success response + */ + public static String toJsonRPCListTasksResultResponse(@Nullable Object requestId, + com.google.protobuf.MessageOrBuilder builder) { + return toJsonRPCResultResponse(requestId, builder, RESPONSE_PRINTER, true); + } + + private static String toJsonRPCResultResponse(@Nullable Object requestId, + com.google.protobuf.MessageOrBuilder builder, JsonFormat.Printer printer) { + return toJsonRPCResultResponse(requestId, builder, printer, false); + } + + private static String toJsonRPCResultResponse(@Nullable Object requestId, + com.google.protobuf.MessageOrBuilder builder, JsonFormat.Printer printer, boolean omitEmptyTaskArtifacts) { try (StringWriter result = new StringWriter(); JsonWriter output = GSON.newJsonWriter(result)) { output.beginObject(); output.name("jsonrpc").value("2.0"); JsonUtil.writeJsonRpcId(output, requestId); - String resultValue = ProtoJsonUtils.toJson(RESPONSE_PRINTER, builder); + String resultValue = ProtoJsonUtils.toJson(printer, builder); + if (builder instanceof org.a2aproject.sdk.grpc.SendMessageResponseOrBuilder + || builder instanceof org.a2aproject.sdk.grpc.StreamResponseOrBuilder) { + resultValue = ProtoJsonUtils.omitEmptyMessageTaskId(resultValue); + } + if (omitEmptyTaskArtifacts) { + resultValue = ProtoJsonUtils.omitEmptyTaskArtifacts(resultValue); + } output.name("result").jsonValue(resultValue); output.endObject(); return result.toString(); diff --git a/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/ProtoJsonUtils.java b/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/ProtoJsonUtils.java index 2a40afd44..95f009893 100644 --- a/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/ProtoJsonUtils.java +++ b/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/ProtoJsonUtils.java @@ -1,5 +1,10 @@ package org.a2aproject.sdk.grpc.utils; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.MessageOrBuilder; import com.google.protobuf.util.JsonFormat; @@ -19,6 +24,17 @@ public final class ProtoJsonUtils { private ProtoJsonUtils() { } + /** Removes unknown top-level fields while preserving nested objects for strict parsing. */ + public static JsonElement retainKnownFields(JsonElement json, Descriptor descriptor) { + if (!json.isJsonObject()) { + return json; + } + JsonObject result = json.getAsJsonObject().deepCopy(); + result.keySet().removeIf(name -> descriptor.findFieldByName(name) == null + && descriptor.getFields().stream().noneMatch(field -> field.getJsonName().equals(name))); + return result; + } + /** * Serializes a protobuf message to JSON using the supplied printer, * then removes HTML escaping. @@ -36,4 +52,46 @@ public static String toJson(JsonFormat.Printer printer, @Nullable MessageOrBuild } return HtmlEscapeUtils.removeHtmlEscaping(printer.print(proto)); } + + /** + * Removes empty {@code artifacts} arrays from the tasks in a ListTasks response while + * preserving all other default-valued response fields. + * + * @param json a serialized ListTasks response + * @return the response with empty task artifact arrays omitted + */ + public static String omitEmptyTaskArtifacts(String json) { + JsonObject response = JsonParser.parseString(json).getAsJsonObject(); + JsonElement tasksElement = response.get("tasks"); + if (tasksElement == null || !tasksElement.isJsonArray()) { + return json; + } + JsonArray tasks = tasksElement.getAsJsonArray(); + for (JsonElement taskElement : tasks) { + if (!taskElement.isJsonObject()) { + continue; + } + JsonObject task = taskElement.getAsJsonObject(); + JsonElement artifacts = task.get("artifacts"); + if (artifacts != null && artifacts.isJsonArray() && artifacts.getAsJsonArray().isEmpty()) { + task.remove("artifacts"); + } + } + return HtmlEscapeUtils.removeHtmlEscaping(response.toString()); + } + + /** Removes the unset task ID from a direct SendMessage response. */ + public static String omitEmptyMessageTaskId(String json) { + JsonObject response = JsonParser.parseString(json).getAsJsonObject(); + JsonElement element = response.get("message"); + if (element != null && element.isJsonObject()) { + JsonObject message = element.getAsJsonObject(); + JsonElement taskId = message.get("taskId"); + if (taskId != null && taskId.isJsonPrimitive() && taskId.getAsString().isEmpty()) { + message.remove("taskId"); + return HtmlEscapeUtils.removeHtmlEscaping(response.toString()); + } + } + return json; + } } diff --git a/spec-grpc/src/test/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtilsTest.java b/spec-grpc/src/test/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtilsTest.java index f5ad6d651..530d4412c 100644 --- a/spec-grpc/src/test/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtilsTest.java +++ b/spec-grpc/src/test/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtilsTest.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.fail; import java.util.Collections; +import java.util.List; import java.util.Map; import com.google.gson.JsonArray; @@ -46,6 +47,7 @@ import org.a2aproject.sdk.jsonrpc.common.wrappers.ListTasksResponse; import org.a2aproject.sdk.jsonrpc.common.wrappers.ListTasksResult; import org.a2aproject.sdk.jsonrpc.common.wrappers.SendMessageRequest; +import org.a2aproject.sdk.jsonrpc.common.wrappers.SendStreamingMessageRequest; import org.a2aproject.sdk.spec.DataPart; import org.a2aproject.sdk.spec.InvalidParamsError; import org.a2aproject.sdk.spec.JSONParseError; @@ -54,6 +56,8 @@ import org.a2aproject.sdk.spec.Task; import org.a2aproject.sdk.spec.TaskNotFoundError; import org.a2aproject.sdk.spec.TaskPushNotificationConfig; +import org.a2aproject.sdk.spec.TaskState; +import org.a2aproject.sdk.spec.TaskStatus; import org.a2aproject.sdk.spec.TextPart; import org.a2aproject.sdk.spec.util.ErrorDetail; import org.junit.jupiter.api.Test; @@ -62,6 +66,23 @@ public class JSONRPCUtilsTest { + @Test + public void testListTasksResponseOmitsEmptyArtifacts() { + Task task = Task.builder() + .id("task-without-artifacts") + .contextId("context") + .status(new TaskStatus(TaskState.TASK_STATE_COMPLETED)) + .build(); + ListTasksResult result = new ListTasksResult(List.of(task)); + + String json = JSONRPCUtils.toJsonRPCListTasksResultResponse("request-1", + ProtoUtils.ToProto.listTasksResult(result)); + + JsonObject listedTask = JsonParser.parseString(json).getAsJsonObject() + .getAsJsonObject("result").getAsJsonArray("tasks").get(0).getAsJsonObject(); + assertFalse(listedTask.has("artifacts")); + } + @Test public void testSendMessage_WithExplicitNulls_RoundTrips() throws JsonProcessingException { String json = """ @@ -497,6 +518,65 @@ public void testParseUnknownField_ThrowsJsonMappingException() throws JsonMappin assertEquals(ERROR_MESSAGE.formatted("unknown in message lf.a2a.v1.Message"), exception.getMessage()); } + @Test + public void testSendMessageAcceptsExtraRequestParameter() throws Exception { + String json = """ + {"jsonrpc":"2.0","id":1,"method":"SendMessage","params":{ + "message":{"messageId":"dm-extra-001-msg","role":"ROLE_USER", + "parts":[{"text":"tck-complete-task extra field"}]}, + "x_custom_field":"test" + }} + """; + + SendMessageRequest request = assertInstanceOf(SendMessageRequest.class, JSONRPCUtils.parseRequestBody(json, null)); + assertEquals("dm-extra-001-msg", request.getParams().message().messageId()); + } + + @Test + public void testStreamingMessageAcceptsExtraRequestParameter() throws Exception { + String json = """ + {"jsonrpc":"2.0","id":1,"method":"SendStreamingMessage","params":{ + "message":{"messageId":"message-1","role":"ROLE_USER","parts":[{"text":"hello"}]}, + "extra":{"arbitrary":true} + }} + """; + assertInstanceOf(SendStreamingMessageRequest.class, JSONRPCUtils.parseRequestBody(json, null)); + } + + @Test + public void testSendMessageStillRequiresMessageAndRejectsNestedExtras() { + for (String method : List.of("SendMessage", "SendStreamingMessage")) { + String missing = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"" + method + + "\",\"params\":{\"extra\":true}}"; + assertThrows(JsonProcessingException.class, () -> JSONRPCUtils.parseRequestBody(missing, null)); + String nested = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"" + method + + "\",\"params\":{\"message\":{\"role\":\"ROLE_USER\",\"messageId\":\"m\"," + + "\"parts\":[{\"text\":\"hello\"}],\"extra\":true}}}"; + assertThrows(JsonProcessingException.class, () -> JSONRPCUtils.parseRequestBody(nested, null)); + } + } + + @Test + void rejectsExtraParametersForOtherMethods() { + String json = """ + {"jsonrpc":"2.0","id":1,"method":"GetTask", + "params":{"id":"task-1","histroyLength":2}} + """; + assertThrows(JsonMappingException.class, () -> JSONRPCUtils.parseRequestBody(json, null)); + } + + @Test + void streamingMessageWithoutTaskIdOmitsItFromJsonRpcResult() { + Message message = Message.builder().role(Message.Role.ROLE_AGENT) + .parts(Collections.singletonList(new TextPart("hello"))) + .messageId("stream-message").contextId("context").build(); + String json = JSONRPCUtils.toJsonRPCResultResponse("id", ProtoUtils.ToProto.taskOrMessageStream(message)); + JsonObject resultMessage = JsonParser.parseString(json).getAsJsonObject() + .getAsJsonObject("result").getAsJsonObject("message"); + assertFalse(resultMessage.has("taskId")); + assertEquals("context", resultMessage.get("contextId").getAsString()); + } + @Test public void testParseInvalidTypeWithNullId_UsesEmptyStringSentinel() throws Exception { // Test the low-level convertProtoBufExceptionToJsonProcessingException with null ID diff --git a/spec/src/test/java/org/a2aproject/sdk/spec/A2AErrorCodesTest.java b/spec/src/test/java/org/a2aproject/sdk/spec/A2AErrorCodesTest.java new file mode 100644 index 000000000..f0ae8002b --- /dev/null +++ b/spec/src/test/java/org/a2aproject/sdk/spec/A2AErrorCodesTest.java @@ -0,0 +1,17 @@ +package org.a2aproject.sdk.spec; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class A2AErrorCodesTest { + @Test + void mapsA2aErrorsAccordingToVersion100() { + assertEquals(409, A2AErrorCodes.TASK_NOT_CANCELABLE.httpCode()); + assertEquals("UNIMPLEMENTED", A2AErrorCodes.PUSH_NOTIFICATION_NOT_SUPPORTED.grpcStatus()); + assertEquals("UNIMPLEMENTED", A2AErrorCodes.UNSUPPORTED_OPERATION.grpcStatus()); + assertEquals(415, A2AErrorCodes.CONTENT_TYPE_NOT_SUPPORTED.httpCode()); + assertEquals(502, A2AErrorCodes.INVALID_AGENT_RESPONSE.httpCode()); + assertEquals("UNIMPLEMENTED", A2AErrorCodes.VERSION_NOT_SUPPORTED.grpcStatus()); + } +} diff --git a/tests/multiversion/jsonrpc/src/test/java/org/a2aproject/sdk/tests/multiversion/jsonrpc/MultiVersionJSONRPCTest.java b/tests/multiversion/jsonrpc/src/test/java/org/a2aproject/sdk/tests/multiversion/jsonrpc/MultiVersionJSONRPCTest.java index bd7996d2a..b92ccc63e 100644 --- a/tests/multiversion/jsonrpc/src/test/java/org/a2aproject/sdk/tests/multiversion/jsonrpc/MultiVersionJSONRPCTest.java +++ b/tests/multiversion/jsonrpc/src/test/java/org/a2aproject/sdk/tests/multiversion/jsonrpc/MultiVersionJSONRPCTest.java @@ -1,6 +1,8 @@ package org.a2aproject.sdk.tests.multiversion.jsonrpc; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.net.URI; import java.net.http.HttpClient; @@ -9,6 +11,7 @@ import jakarta.inject.Inject; +import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.quarkus.test.junit.QuarkusTest; import io.vertx.core.Vertx; @@ -46,6 +49,22 @@ protected void configureTransport(ClientBuilder builder) { new JSONRPCTransportConfigBuilder() .httpClient(new VertxA2AHttpClient(vertx))); } + + @Test + public void testDirectMessageWireFormat() throws Exception { + HttpResponse response = decodeResponse("1.0", "", """ + {"jsonrpc":"2.0","id":"wire-format-003","method":"SendMessage","params":{ + "message":{"messageId":"wire-format-003-msg","role":"ROLE_USER", + "parts":[{"text":"tck-message-response test defaults"}]}}} + """); + + JsonObject message = JsonParser.parseString(response.body()).getAsJsonObject() + .getAsJsonObject("result").getAsJsonObject("message"); + assertEquals("ROLE_AGENT", message.get("role").getAsString()); + assertTrue(message.has("contextId")); + assertFalse(message.get("contextId").getAsString().isEmpty()); + assertFalse(message.has("taskId"), "A direct message must omit taskId"); + } @Test public void testUnsupportedVersionBeforeBodyValidation() throws Exception { for (String body : new String[] {"{", "{\"id\":\"recoverable\",\"method\":false}"}) { diff --git a/tests/multiversion/rest/src/test/java/org/a2aproject/sdk/tests/multiversion/rest/MultiVersionRestTest.java b/tests/multiversion/rest/src/test/java/org/a2aproject/sdk/tests/multiversion/rest/MultiVersionRestTest.java index cb347b4e6..c815866d2 100644 --- a/tests/multiversion/rest/src/test/java/org/a2aproject/sdk/tests/multiversion/rest/MultiVersionRestTest.java +++ b/tests/multiversion/rest/src/test/java/org/a2aproject/sdk/tests/multiversion/rest/MultiVersionRestTest.java @@ -17,6 +17,9 @@ import org.a2aproject.sdk.client.transport.rest.RestTransport; import org.a2aproject.sdk.client.transport.rest.RestTransportConfigBuilder; import org.a2aproject.sdk.server.apps.common.AbstractA2AServerTest; +import org.a2aproject.sdk.spec.Task; +import org.a2aproject.sdk.spec.TaskState; +import org.a2aproject.sdk.spec.TaskStatus; import org.a2aproject.sdk.spec.TransportProtocol; import org.junit.jupiter.api.Test; @@ -46,6 +49,29 @@ protected void configureTransport(ClientBuilder builder) { new RestTransportConfigBuilder() .httpClient(new VertxA2AHttpClient(vertx))); } + @Test + public void testResponseContentTypeMatchesSelectedVersion() throws Exception { + String taskId = "versioned-content-type-test"; + saveTaskInTaskStore(Task.builder().id(taskId).contextId("versioned-content-type-context") + .status(new TaskStatus(TaskState.TASK_STATE_WORKING)).build()); + try { + HttpClient client = HttpClient.newHttpClient(); + for (String version : new String[] {"0.3", "1.0"}) { + for (String id : new String[] {taskId, "missing-versioned-content-type-test"}) { + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(getTransportUrl() + "/v1/tasks/" + id)) + .header("A2A-Version", version).GET().build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + assertEquals(id.equals(taskId) ? 200 : 404, response.statusCode()); + assertEquals("0.3".equals(version) ? "application/json" : "application/a2a+json", + response.headers().firstValue("Content-Type").orElseThrow()); + } + } + } finally { + deleteTaskInTaskStore(taskId); + } + } + @Test public void testUnsupportedVersionBeforeMalformedHistory() throws Exception { HttpResponse response = historyResponse("2.0", "historyLength=bad"); @@ -72,7 +98,8 @@ private HttpResponse historyResponse(String header, String query) throws request.header("A2A-Version", header); } HttpResponse response = HttpClient.newHttpClient().send(request.build(), HttpResponse.BodyHandlers.ofString()); - assertEquals("application/json", response.headers().firstValue("Content-Type").orElseThrow()); + assertEquals("1.0".equals(header) ? "application/a2a+json" : "application/json", + response.headers().firstValue("Content-Type").orElseThrow()); return response; } diff --git a/tests/multiversion/rest/src/test/java/org/a2aproject/sdk/tests/multiversion/rest/MultiVersion_v0_3_RestTest.java b/tests/multiversion/rest/src/test/java/org/a2aproject/sdk/tests/multiversion/rest/MultiVersion_v0_3_RestTest.java index 9462576e2..751b62966 100644 --- a/tests/multiversion/rest/src/test/java/org/a2aproject/sdk/tests/multiversion/rest/MultiVersion_v0_3_RestTest.java +++ b/tests/multiversion/rest/src/test/java/org/a2aproject/sdk/tests/multiversion/rest/MultiVersion_v0_3_RestTest.java @@ -68,7 +68,8 @@ private HttpResponse historyResponse(String header, String query) throws request.header("A2A-Version", header); } HttpResponse response = HttpClient.newHttpClient().send(request.build(), HttpResponse.BodyHandlers.ofString()); - assertEquals("application/json", response.headers().firstValue("Content-Type").orElseThrow()); + assertEquals("1.0".equals(header) ? "application/a2a+json" : "application/json", + response.headers().firstValue("Content-Type").orElseThrow()); return response; } diff --git a/tests/server-common/src/test/java/org/a2aproject/sdk/server/apps/common/AbstractA2AServerTest.java b/tests/server-common/src/test/java/org/a2aproject/sdk/server/apps/common/AbstractA2AServerTest.java index a700cbbf5..12c55df4a 100644 --- a/tests/server-common/src/test/java/org/a2aproject/sdk/server/apps/common/AbstractA2AServerTest.java +++ b/tests/server-common/src/test/java/org/a2aproject/sdk/server/apps/common/AbstractA2AServerTest.java @@ -18,6 +18,7 @@ import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -60,6 +61,8 @@ import org.a2aproject.sdk.spec.AgentInterface; import org.a2aproject.sdk.spec.Artifact; import org.a2aproject.sdk.spec.CancelTaskParams; +import org.a2aproject.sdk.spec.ContentTypeNotSupportedError; +import org.a2aproject.sdk.spec.DataPart; import org.a2aproject.sdk.spec.DeleteTaskPushNotificationConfigParams; import org.a2aproject.sdk.spec.Event; import org.a2aproject.sdk.spec.GetTaskPushNotificationConfigParams; @@ -180,6 +183,105 @@ public void testGetTaskSuccess() throws Exception { testGetTask(); } + @Test + public void testGetTaskHistoryIsChronological() throws Exception { + List history = List.of( + Message.builder(MESSAGE) + .messageId("history-first") + .role(Message.Role.ROLE_USER) + .parts(new TextPart("chronological first")) + .build(), + Message.builder(MESSAGE) + .messageId("history-second") + .role(Message.Role.ROLE_AGENT) + .parts(new TextPart("chronological second")) + .build(), + Message.builder(MESSAGE) + .messageId("history-third") + .role(Message.Role.ROLE_USER) + .parts(new TextPart("chronological third")) + .build()); + Task task = Task.builder() + .id("task-with-chronological-history") + .contextId("chronological-history-context") + .status(new TaskStatus(TaskState.TASK_STATE_COMPLETED)) + .history(history) + .build(); + saveTaskInTaskStore(task); + + try { + Task response = getClient().getTask(new TaskQueryParams(task.id())); + + assertNotNull(response.history()); + assertEquals(List.of("history-first", "history-second", "history-third"), + response.history().stream().map(Message::messageId).toList(), + "History messages must be returned in chronological order"); + assertEquals("chronological first", ((TextPart) response.history().get(0).parts().get(0)).text()); + assertEquals("chronological second", ((TextPart) response.history().get(1).parts().get(0)).text()); + assertEquals("chronological third", ((TextPart) response.history().get(2).parts().get(0)).text()); + } finally { + deleteTaskInTaskStore(task.id()); + } + } + + @Test + public void testMultiTurnHistoryIsChronological() throws Exception { + Task firstResponse = sendMessageAndAwaitTask(Message.builder(MESSAGE) + .messageId("chronological-first") + .role(Message.Role.ROLE_USER) + .parts(new TextPart("history-workflow:chronological first")) + .build()); + + try { + Task secondResponse = sendMessageAndAwaitTask(Message.builder(MESSAGE) + .messageId("chronological-second") + .role(Message.Role.ROLE_USER) + .taskId(firstResponse.id()) + .contextId(firstResponse.contextId()) + .parts(new TextPart("history-workflow:chronological second")) + .build()); + sendMessageAndAwaitTask(Message.builder(MESSAGE) + .messageId("chronological-third") + .role(Message.Role.ROLE_USER) + .taskId(secondResponse.id()) + .contextId(secondResponse.contextId()) + .parts(new TextPart("history-workflow:chronological third")) + .build()); + + Task task = getClient().getTask(new TaskQueryParams(firstResponse.id())); + List userMessages = task.history().stream() + .filter(message -> message.role() == Message.Role.ROLE_USER) + .map(message -> ((TextPart) message.parts().get(0)).text()) + .toList(); + assertEquals(List.of( + "history-workflow:chronological first", + "history-workflow:chronological second", + "history-workflow:chronological third"), userMessages, + "User messages must be retained in chronological order"); + } finally { + deleteTaskInTaskStore(firstResponse.id()); + } + } + + private Task sendMessageAndAwaitTask(Message message) throws Exception { + CountDownLatch latch = new CountDownLatch(1); + AtomicReference task = new AtomicReference<>(); + AtomicReference failure = new AtomicReference<>(); + getNonStreamingClient().sendMessage(message, List.of((event, agentCard) -> { + if (event instanceof TaskEvent taskEvent) { + task.set(taskEvent.getTask()); + latch.countDown(); + } + }), error -> { + failure.set(error); + latch.countDown(); + }); + + assertTrue(latch.await(10, TimeUnit.SECONDS), "Expected a task response"); + assertNull(failure.get(), "Unexpected error while sending message"); + return java.util.Objects.requireNonNull(task.get(), "Expected a task response"); + } + private void testGetTask() throws Exception { testGetTask(null); } @@ -290,6 +392,37 @@ public void testListTasksSuccess() throws Exception { } } + @Test + public void testListTasksWithoutArtifacts() throws Exception { + Task taskWithArtifact = Task.builder() + .id("list-task-with-artifact") + .contextId("context-with-artifact") + .status(new TaskStatus(TaskState.TASK_STATE_COMPLETED)) + .artifacts(List.of(Artifact.builder() + .artifactId("list-artifact-1") + .parts(new TextPart("artifact content")) + .build())) + .build(); + saveTaskInTaskStore(taskWithArtifact); + + try { + ListTasksParams params = ListTasksParams.builder() + .contextId(taskWithArtifact.contextId()) + .includeArtifacts(false) + .tenant("") + .build(); + + ListTasksResult result = getClient().listTasks(params); + + assertEquals(1, result.tasks().size()); + assertEquals(taskWithArtifact.id(), result.tasks().get(0).id()); + assertTrue(result.tasks().get(0).artifacts().isEmpty(), + "ListTasks with includeArtifacts=false must omit task artifacts"); + } finally { + deleteTaskInTaskStore(taskWithArtifact.id()); + } + } + @Test public void testListTasksFilterByContextId() throws Exception { Task task1 = Task.builder() @@ -504,6 +637,63 @@ public void testSendMessageNewMessageSuccess() throws Exception { assertEquals("test message", ((TextPart) part).text()); } + @Test + public void testSendMessageAcceptsPlainTextForTextInputMode() throws Exception { + Message message = Message.builder() + .messageId("plain-text-content-type-message") + .role(Message.Role.ROLE_USER) + .parts(new TextPart("hello", null, "text/plain; charset=utf-8")) + .build(); + getNonStreamingClient().sendMessage(message); + } + + /** + * A server that advertises only {@code text} input must reject a message part whose media type + * it does not support. This is the protocol-level regression test for ACTS CORE-SEND-004. + */ + @Test + public void testSendMessageRejectsUnsupportedPartContentType() { + Message message = Message.builder() + .messageId("unsupported-content-type-message") + .role(Message.Role.ROLE_USER) + .parts(new DataPart(Map.of("value", "unsupported"), null, "application/x-a2a-unsupported")) + .build(); + + try { + getNonStreamingClient().sendMessage(message); + fail("Expected ContentTypeNotSupportedError for an unsupported message-part content type"); + } catch (A2AClientException e) { + assertInstanceOf(ContentTypeNotSupportedError.class, e.getCause()); + } + } + + @Test + public void testStreamingSendRejectsUnsupportedPartContentType() throws Exception { + Message message = Message.builder() + .messageId("unsupported-stream-content-type-message") + .role(Message.Role.ROLE_USER) + .parts(new DataPart(Map.of("value", "unsupported"), null, "application/x-a2a-unsupported")) + .build(); + CountDownLatch errorLatch = new CountDownLatch(1); + AtomicReference error = new AtomicReference<>(); + try { + getClient().sendMessage(message, List.of(), failure -> { + if (failure != null) { + error.set(failure); + errorLatch.countDown(); + } + }); + assertTrue(errorLatch.await(10, TimeUnit.SECONDS), "Expected unsupported content type error"); + Throwable cause = error.get(); + while (cause != null && !(cause instanceof ContentTypeNotSupportedError)) { + cause = cause.getCause(); + } + assertInstanceOf(ContentTypeNotSupportedError.class, cause); + } catch (A2AClientException e) { + assertInstanceOf(ContentTypeNotSupportedError.class, e.getCause()); + } + } + @Test public void testRequestScopedBeanAvailableOnAgentExecutorThread() throws Exception { Message message = Message.builder() @@ -685,6 +875,20 @@ public void testGetPushNotificationSuccess() throws Exception { } } + @Test + public void testGetNonexistentPushNotificationConfigReturnsTaskNotFoundError() throws Exception { + saveTaskInTaskStore(MINIMAL_TASK); + try { + getClient().getTaskPushNotificationConfiguration( + new GetTaskPushNotificationConfigParams(MINIMAL_TASK.id(), "non-existent-config-id")); + fail("Expected TaskNotFoundError when the push notification config does not exist"); + } catch (A2AClientException e) { + assertInstanceOf(TaskNotFoundError.class, e.getCause()); + } finally { + deleteTaskInTaskStore(MINIMAL_TASK.id()); + } + } + @Test public void testError() throws Exception { saveTaskInTaskStore(SEND_MESSAGE_NOT_SUPPORTED); @@ -2899,14 +3103,14 @@ public void testMainQueueStaysOpenForNonFinalTasks() throws Exception { * 2. Task reaches COMPLETED state (final) * 3. ChildQueue closes after receiving final event * 4. MainQueue should close because task is finalized - * 5. Resubscription should fail with TaskNotFoundError + * 5. Resubscription should fail with UnsupportedOperationError */ @Test @Timeout(value = 2, unit = TimeUnit.MINUTES) public void testMainQueueClosesForFinalizedTasks() throws Exception { // Send a message without taskId - server generates one Message message = Message.builder(MESSAGE) - .parts(new TextPart("complete task")) + .parts(new TextPart("queue-finalization:complete task")) .build(); CountDownLatch completionLatch = new CountDownLatch(1); @@ -2920,10 +3124,6 @@ public void testMainQueueClosesForFinalizedTasks() throws Exception { if (te.getTask().status().state().isFinal()) { completionLatch.countDown(); } - } else if (event instanceof MessageEvent me) { - // Message is considered a final event - capture taskId from the message - generatedTaskId.compareAndSet(null, me.getMessage().taskId()); - completionLatch.countDown(); } else if (event instanceof TaskUpdateEvent tue && tue.getUpdateEvent() instanceof TaskStatusUpdateEvent status) { generatedTaskId.compareAndSet(null, status.taskId()); @@ -2951,8 +3151,9 @@ public void testMainQueueClosesForFinalizedTasks() throws Exception { String taskId = generatedTaskId.get(); assertNotNull(taskId, "Should have captured server-generated taskId"); - // Give cleanup time to run after final event - Thread.sleep(2000); + // -1 means the main queue is closed or no longer registered. + assertTrue(awaitChildQueueCountStable(taskId, -1, 15000), + "MainQueue should close after the task reaches a final state"); // Try to subscribe to finalized task - should fail CountDownLatch errorLatch = new CountDownLatch(1); @@ -2982,24 +3183,24 @@ public void testMainQueueClosesForFinalizedTasks() throws Exception { Throwable error = resubErrorRef.get(); assertNotNull(error, "Resubscription should fail for finalized task"); - // Verify it's a TaskNotFoundError + // Terminal tasks reject subscription with UnsupportedOperationError. Throwable cause = error; - boolean foundTaskNotFound = false; - while (cause != null && !foundTaskNotFound) { - if (cause instanceof TaskNotFoundError + boolean foundUnsupportedOperation = false; + while (cause != null && !foundUnsupportedOperation) { + if (cause instanceof UnsupportedOperationError || (cause instanceof A2AClientException - && ((A2AClientException) cause).getCause() instanceof TaskNotFoundError)) { - foundTaskNotFound = true; + && ((A2AClientException) cause).getCause() instanceof UnsupportedOperationError)) { + foundUnsupportedOperation = true; } cause = cause.getCause(); } - assertTrue(foundTaskNotFound, - "Should receive TaskNotFoundError - MainQueue closed for finalized task"); + assertTrue(foundUnsupportedOperation, + "Should receive UnsupportedOperationError for a finalized task"); } catch (A2AClientException e) { // Exception might be thrown immediately instead of via error handler - assertInstanceOf(TaskNotFoundError.class, e.getCause(), - "Should fail with TaskNotFoundError - MainQueue cleaned up for finalized task"); + assertInstanceOf(UnsupportedOperationError.class, e.getCause(), + "Should fail with UnsupportedOperationError for a finalized task"); } } finally { diff --git a/tests/server-common/src/test/java/org/a2aproject/sdk/server/apps/common/AgentExecutorProducer.java b/tests/server-common/src/test/java/org/a2aproject/sdk/server/apps/common/AgentExecutorProducer.java index b46519e30..e3059c2e3 100644 --- a/tests/server-common/src/test/java/org/a2aproject/sdk/server/apps/common/AgentExecutorProducer.java +++ b/tests/server-common/src/test/java/org/a2aproject/sdk/server/apps/common/AgentExecutorProducer.java @@ -53,6 +53,11 @@ public void execute(RequestContext context, AgentEmitter agentEmitter) throws A2 String taskId = context.getTaskId(); String input = context.getMessage() != null ? extractTextFromMessage(context.getMessage()) : ""; + if (input.startsWith("tck-message-response")) { + agentEmitter.sendMessage("tck message response"); + return; + } + // Agent-to-agent communication test (routed by message content prefix) if (input.startsWith("delegate:") || input.startsWith("a2a-local:")) { handleAgentToAgentTest(context, agentEmitter); @@ -68,6 +73,13 @@ public void execute(RequestContext context, AgentEmitter agentEmitter) throws A2 return; } + // Create and finish a task for the finalized queue lifecycle test. + if (input.startsWith("queue-finalization:")) { + agentEmitter.startWork(); + agentEmitter.complete(); + return; + } + // Special handling for multi-event test (routed by message content) if (input.startsWith("multi-event:first")) { agentEmitter.startWork(); @@ -97,6 +109,13 @@ public void execute(RequestContext context, AgentEmitter agentEmitter) throws A2 return; } + if (input.startsWith("history-workflow:")) { + agentEmitter.requiresInput(agentEmitter.newAgentMessage( + List.of(new TextPart("Please provide the next history message")), + context.getMessage().metadata())); + return; + } + // Special handling for auth-required test (routed by message content) if (input.startsWith("auth-required:")) { agentEmitter.requiresAuth(agentEmitter.newAgentMessage( diff --git a/transport/grpc/src/main/java/org/a2aproject/sdk/transport/grpc/handler/GrpcHandler.java b/transport/grpc/src/main/java/org/a2aproject/sdk/transport/grpc/handler/GrpcHandler.java index ea70660b9..d583327d9 100644 --- a/transport/grpc/src/main/java/org/a2aproject/sdk/transport/grpc/handler/GrpcHandler.java +++ b/transport/grpc/src/main/java/org/a2aproject/sdk/transport/grpc/handler/GrpcHandler.java @@ -35,6 +35,7 @@ import org.a2aproject.sdk.server.AgentCardTransportValidator; import org.a2aproject.sdk.server.AgentCardValidator; import org.a2aproject.sdk.server.CachingAgentCardTransportValidator; +import org.a2aproject.sdk.server.InputModeValidator; import org.a2aproject.sdk.server.ServerCallContext; import org.a2aproject.sdk.server.auth.UnauthenticatedUser; import org.a2aproject.sdk.server.auth.User; @@ -216,6 +217,7 @@ public void sendMessage(org.a2aproject.sdk.grpc.SendMessageRequest request, ServerCallContext context = createCallContext(responseObserver, tenant); MessageSendParams params = FromProto.messageSendParams( request.toBuilder().setTenant(canonicalTenant(context)).build()); + InputModeValidator.validate(params.message(), Objects.requireNonNull(context.getEffectiveAgentCard()).card()); EventKind taskOrMessage = getRequestHandler().onMessageSend(params, context); org.a2aproject.sdk.grpc.SendMessageResponse response = ToProto.taskOrMessage(taskOrMessage); responseObserver.onNext(response); @@ -418,6 +420,7 @@ public void sendStreamingMessage(org.a2aproject.sdk.grpc.SendMessageRequest requ installForkedContextWrapper(context); MessageSendParams params = FromProto.messageSendParams( request.toBuilder().setTenant(canonicalTenant(context)).build()); + InputModeValidator.validate(params.message(), Objects.requireNonNull(context.getEffectiveAgentCard()).card()); Flow.Publisher publisher = getRequestHandler().onMessageSendStream(params, context); convertToStreamResponse(publisher, responseObserver, context); } catch (TenantNotFoundException e) { diff --git a/transport/jsonrpc/src/main/java/org/a2aproject/sdk/transport/jsonrpc/handler/JSONRPCHandler.java b/transport/jsonrpc/src/main/java/org/a2aproject/sdk/transport/jsonrpc/handler/JSONRPCHandler.java index a15a181d5..2e2467440 100644 --- a/transport/jsonrpc/src/main/java/org/a2aproject/sdk/transport/jsonrpc/handler/JSONRPCHandler.java +++ b/transport/jsonrpc/src/main/java/org/a2aproject/sdk/transport/jsonrpc/handler/JSONRPCHandler.java @@ -48,6 +48,7 @@ import org.a2aproject.sdk.server.EffectiveAgentCard; import org.a2aproject.sdk.server.ExtendedAgentCard; import org.a2aproject.sdk.server.FixedInstance; +import org.a2aproject.sdk.server.InputModeValidator; import org.a2aproject.sdk.server.PublicAgentCard; import org.a2aproject.sdk.server.ServerCallContext; import org.a2aproject.sdk.server.auth.TaskOperation; @@ -263,6 +264,7 @@ public SendMessageResponse onMessageSend(SendMessageRequest request, ServerCallC String tenant = request.getParams() != null ? request.getParams().tenant() : null; EffectiveAgentCard effective = preflight(tenant, context, AgentCardOperation.none()); MessageSendParams params = request.getParams(); + InputModeValidator.validate(params.message(), effective.card()); EventKind taskOrMessage = requestHandler.onMessageSend(new MessageSendParams(params.message(), params.configuration(), params.metadata(), effective.tenant()), context); return new SendMessageResponse(request.getId(), taskOrMessage); @@ -315,6 +317,7 @@ public Flow.Publisher onMessageSendStream( try { EffectiveAgentCard effective = preflight(tenant, context, STREAMING); MessageSendParams params = request.getParams(); + InputModeValidator.validate(params.message(), effective.card()); Flow.Publisher publisher = requestHandler.onMessageSendStream(new MessageSendParams(params.message(), params.configuration(), params.metadata(), effective.tenant()), context); diff --git a/transport/rest/src/main/java/org/a2aproject/sdk/transport/rest/handler/RestHandler.java b/transport/rest/src/main/java/org/a2aproject/sdk/transport/rest/handler/RestHandler.java index ae48c890a..bad06cd56 100644 --- a/transport/rest/src/main/java/org/a2aproject/sdk/transport/rest/handler/RestHandler.java +++ b/transport/rest/src/main/java/org/a2aproject/sdk/transport/rest/handler/RestHandler.java @@ -4,6 +4,7 @@ import static org.a2aproject.sdk.server.AgentCardOperation.PUSH_NOTIFICATIONS; import static org.a2aproject.sdk.server.AgentCardOperation.STREAMING; +import static org.a2aproject.sdk.common.MediaType.APPLICATION_A2A_JSON; import static org.a2aproject.sdk.common.MediaType.APPLICATION_JSON; import static org.a2aproject.sdk.server.util.async.AsyncUtils.createTubeConfig; @@ -44,6 +45,7 @@ import org.a2aproject.sdk.server.EffectiveAgentCard; import org.a2aproject.sdk.server.ExtendedAgentCard; import org.a2aproject.sdk.server.FixedInstance; +import org.a2aproject.sdk.server.InputModeValidator; import org.a2aproject.sdk.server.PublicAgentCard; import org.a2aproject.sdk.server.ServerCallContext; import org.a2aproject.sdk.server.auth.TaskOperation; @@ -244,7 +246,9 @@ public HTTPRestResponse sendMessage(ServerCallContext context, String tenant, St org.a2aproject.sdk.grpc.SendMessageRequest.Builder request = org.a2aproject.sdk.grpc.SendMessageRequest.newBuilder(); parseRequestBody(body, request); request.setTenant(Utils.defaultIfNull(effectiveCard.tenant(), "")); - EventKind result = requestHandler.onMessageSend(ProtoUtils.FromProto.messageSendParams(request), context); + MessageSendParams params = ProtoUtils.FromProto.messageSendParams(request); + InputModeValidator.validate(params.message(), effectiveCard.card()); + EventKind result = requestHandler.onMessageSend(params, context); return createSuccessResponse(200, org.a2aproject.sdk.grpc.SendMessageResponse.newBuilder(ProtoUtils.ToProto.taskOrMessage(result))); } catch (A2AError e) { return createErrorResponse(e); @@ -314,6 +318,7 @@ public HTTPRestResponse sendStreamingMessage(ServerCallContext context, String t parseRequestBody(body, request); request.setTenant(Utils.defaultIfNull(effectiveCard.tenant(), "")); MessageSendParams params = ProtoUtils.FromProto.messageSendParams(request); + InputModeValidator.validate(params.message(), effectiveCard.card()); try { requestHandler.authorizeTaskAccess(params.message().taskId(), context, TaskOperation.MESSAGE_SEND_STREAM); } catch (A2AError e) { @@ -621,7 +626,8 @@ public HTTPRestResponse listTasks(ServerCallContext context, String tenant, ListTasksParams params = paramsBuilder.build(); ListTasksResult result = requestHandler.onListTasks(params, context); - return createSuccessResponse(200, org.a2aproject.sdk.grpc.ListTasksResponse.newBuilder(ProtoUtils.ToProto.listTasksResult(result))); + return createListTasksSuccessResponse(200, + org.a2aproject.sdk.grpc.ListTasksResponse.newBuilder(ProtoUtils.ToProto.listTasksResult(result))); } catch (A2AError e) { return createErrorResponse(e); } catch (Throwable throwable) { @@ -717,7 +723,7 @@ public HTTPRestResponse deleteTaskPushNotificationConfiguration(ServerCallContex EffectiveAgentCard effectiveCard = preflight(tenant, context, PUSH_NOTIFICATIONS); DeleteTaskPushNotificationConfigParams params = new DeleteTaskPushNotificationConfigParams(requiredTaskId, requiredConfigId, effectiveCard.tenant()); requestHandler.onDeleteTaskPushNotificationConfig(params, context); - return new HTTPRestResponse(204, APPLICATION_JSON, ""); + return new HTTPRestResponse(204, APPLICATION_A2A_JSON, ""); } catch (A2AError e) { return createErrorResponse(e); } catch (Throwable throwable) { @@ -758,6 +764,9 @@ private void parseRequestBody(String body, com.google.protobuf.Message.Builder b throw new InvalidRequestError("Request body is required"); } validate(body); + if (builder instanceof org.a2aproject.sdk.grpc.SendMessageRequest.Builder) { + body = ProtoJsonUtils.retainKnownFields(JsonParser.parseString(body), builder.getDescriptorForType()).toString(); + } JsonFormat.parser().merge(body, builder); } catch (InvalidProtocolBufferException e) { LOGGER.log(Level.SEVERE, "Error parsing JSON request body (length={0})", @@ -779,7 +788,21 @@ private HTTPRestResponse createSuccessResponse(int statusCode, com.google.protob try { // Include default value fields to ensure empty arrays, zeros, etc. are present in JSON String jsonBody = ProtoJsonUtils.toJson(JsonFormat.printer().alwaysPrintFieldsWithNoPresence(), builder); - return new HTTPRestResponse(statusCode, APPLICATION_JSON, jsonBody); + if (builder instanceof org.a2aproject.sdk.grpc.SendMessageResponseOrBuilder) { + jsonBody = ProtoJsonUtils.omitEmptyMessageTaskId(jsonBody); + } + return new HTTPRestResponse(statusCode, APPLICATION_A2A_JSON, jsonBody); + } catch (InvalidProtocolBufferException e) { + LOGGER.log(Level.SEVERE, "Failed to serialize response", e); + return createErrorResponse(new InternalError("Internal error")); + } + } + + private HTTPRestResponse createListTasksSuccessResponse(int statusCode, com.google.protobuf.Message.Builder builder) { + try { + String jsonBody = ProtoJsonUtils.toJson(JsonFormat.printer().alwaysPrintFieldsWithNoPresence(), builder); + jsonBody = ProtoJsonUtils.omitEmptyTaskArtifacts(jsonBody); + return new HTTPRestResponse(statusCode, APPLICATION_A2A_JSON, jsonBody); } catch (InvalidProtocolBufferException e) { LOGGER.log(Level.SEVERE, "Failed to serialize response", e); return createErrorResponse(new InternalError("Internal error")); @@ -799,7 +822,7 @@ public HTTPRestResponse createErrorResponse(A2AError error) { private HTTPRestResponse createErrorResponse(int statusCode, A2AError error) { String jsonBody = new HTTPRestErrorResponse(error).toJson(); - return new HTTPRestResponse(statusCode, APPLICATION_JSON, jsonBody); + return new HTTPRestResponse(statusCode, APPLICATION_A2A_JSON, jsonBody); } /** @@ -931,7 +954,7 @@ public HTTPRestResponse getExtendedAgentCard(ServerCallContext context, @Nullabl if (extCard == null) { throw new ExtendedAgentCardNotConfiguredError(null, "Extended Card not configured", null); } - return new HTTPRestResponse(200, APPLICATION_JSON, JsonUtil.toJson(extCard)); + return new HTTPRestResponse(200, APPLICATION_A2A_JSON, JsonUtil.toJson(extCard)); } catch (A2AError e) { return createErrorResponse(e); } catch (Throwable t) { diff --git a/transport/rest/src/test/java/org/a2aproject/sdk/transport/rest/handler/RestHandlerTest.java b/transport/rest/src/test/java/org/a2aproject/sdk/transport/rest/handler/RestHandlerTest.java index 5e162c4ac..0699a028f 100644 --- a/transport/rest/src/test/java/org/a2aproject/sdk/transport/rest/handler/RestHandlerTest.java +++ b/transport/rest/src/test/java/org/a2aproject/sdk/transport/rest/handler/RestHandlerTest.java @@ -1,6 +1,6 @@ package org.a2aproject.sdk.transport.rest.handler; -import static org.a2aproject.sdk.common.MediaType.APPLICATION_JSON; +import static org.a2aproject.sdk.common.MediaType.APPLICATION_A2A_JSON; import java.util.Collections; import java.util.HashSet; @@ -35,12 +35,15 @@ import org.a2aproject.sdk.spec.AgentCard; import org.a2aproject.sdk.spec.AgentExtension; import org.a2aproject.sdk.spec.AgentInterface; +import org.a2aproject.sdk.spec.Artifact; import org.a2aproject.sdk.spec.ListTaskPushNotificationConfigsParams; import org.a2aproject.sdk.spec.ListTaskPushNotificationConfigsResult; import org.a2aproject.sdk.spec.ListTasksParams; import org.a2aproject.sdk.spec.Task; import org.a2aproject.sdk.spec.TaskQueryParams; import org.a2aproject.sdk.spec.TaskState; +import org.a2aproject.sdk.spec.TaskStatus; +import org.a2aproject.sdk.spec.TextPart; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -64,6 +67,20 @@ private static AgentCardCacheMetadata createCacheMetadata(AgentCard card) { return new AgentCardCacheMetadata(card, new DefaultValuesConfigProvider()); } + @Test + public void testSendMessageRejectsUnsupportedPartMediaType() { + AgentCard card = AgentCard.builder(CARD).defaultInputModes(List.of("text/plain")).build(); + RestHandler handler = new RestHandler(card, createCacheMetadata(card), requestHandler, internalExecutor); + + String requestBody = """ + {"message":{"messageId":"message-1","role":"ROLE_USER", + "parts":[{"text":"hello","mediaType":"image/png"}]}} + """; + + assertProblemDetail(handler.sendMessage(callContext, "", requestBody), 415, + "CONTENT_TYPE_NOT_SUPPORTED", "Input media type is not supported: image/png"); + } + @Test public void testGetTaskSuccess() { RestHandler handler = new RestHandler(CARD, createCacheMetadata(), requestHandler, internalExecutor); @@ -72,13 +89,13 @@ public void testGetTaskSuccess() { RestHandler.HTTPRestResponse response = handler.getTask(callContext, "", MINIMAL_TASK.id(), "0"); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); response = handler.getTask(callContext, "", MINIMAL_TASK.id(), "2"); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); } @@ -116,10 +133,33 @@ public void testListTasksStatusWireString() { null, null, null); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); } + @Test + public void testListTasksWithoutArtifactsOmitsArtifactsFromJson() { + RestHandler handler = new RestHandler(CARD, createCacheMetadata(), requestHandler, internalExecutor); + Task task = Task.builder() + .id("list-task-with-artifact") + .contextId("list-context-with-artifact") + .status(new TaskStatus(TaskState.TASK_STATE_COMPLETED)) + .artifacts(List.of(Artifact.builder() + .artifactId("artifact-1") + .parts(new TextPart("artifact content")) + .build())) + .build(); + taskStore.save(task, false); + + RestHandler.HTTPRestResponse response = handler.listTasks(callContext, "", task.contextId(), null, null, null, + null, null, "false"); + + Assertions.assertEquals(200, response.getStatusCode()); + JsonObject listedTask = JsonParser.parseString(response.getBody()).getAsJsonObject() + .getAsJsonArray("tasks").get(0).getAsJsonObject(); + Assertions.assertFalse(listedTask.has("artifacts")); + } + @Test public void testListTasksInvalidStatus() { RestHandler handler = new RestHandler(CARD, createCacheMetadata(), requestHandler, internalExecutor); @@ -166,10 +206,27 @@ public void testSendMessage() throws InvalidProtocolBufferException { RestHandler.HTTPRestResponse response = handler.sendMessage(callContext, "", requestBody); Assertions.assertEquals(200, response.getStatusCode(), response.toString()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertNotNull(response.getBody()); } + @Test + public void testDirectMessageOmitsTaskId() { + RestHandler handler = new RestHandler(CARD, createCacheMetadata(), requestHandler, internalExecutor); + agentExecutorExecute = (context, emitter) -> emitter.sendMessage("direct response"); + String requestBody = """ + {"message":{"messageId":"direct-message","role":"ROLE_USER", + "parts":[{"text":"hello"}]}} + """; + + RestHandler.HTTPRestResponse response = handler.sendMessage(callContext, "", requestBody); + Assertions.assertEquals(200, response.getStatusCode()); + JsonObject message = JsonParser.parseString(response.getBody()).getAsJsonObject().getAsJsonObject("message"); + Assertions.assertEquals("ROLE_AGENT", message.get("role").getAsString()); + Assertions.assertFalse(message.get("contextId").getAsString().isEmpty()); + Assertions.assertFalse(message.has("taskId")); + } + @Test public void testSendMessageInvalidBody() { RestHandler handler = new RestHandler(CARD, createCacheMetadata(), requestHandler, internalExecutor); @@ -181,6 +238,39 @@ public void testSendMessageInvalidBody() { "JSON_PARSE", "Failed to parse json"); } + @Test + public void testSendMessageAllowsExtraTopLevelFieldsOnly() { + RestHandler handler = new RestHandler(CARD, createCacheMetadata(), requestHandler, internalExecutor); + agentExecutorExecute = (context, emitter) -> emitter.sendMessage("response"); + String message = "\"message\":{\"messageId\":\"message-1\",\"role\":\"ROLE_USER\",\"parts\":[{\"text\":\"hello\"}]}"; + String body = "{" + message + ",\"extra\":{\"any\":true}}"; + + Assertions.assertEquals(200, handler.sendMessage(callContext, "", body).getStatusCode()); + Assertions.assertInstanceOf(RestHandler.HTTPRestStreamingResponse.class, + handler.sendStreamingMessage(callContext, "", body)); + + String nested = "{\"message\":{\"messageId\":\"message-1\",\"role\":\"ROLE_USER\"," + + "\"parts\":[{\"text\":\"hello\"}],\"extra\":true}}"; + Assertions.assertEquals(422, handler.sendMessage(callContext, "", nested).getStatusCode()); + assertStreamingError(handler.sendStreamingMessage(callContext, "", nested)); + Assertions.assertNotEquals(200, handler.sendMessage(callContext, "", "{\"extra\":true}").getStatusCode()); + assertStreamingError(handler.sendStreamingMessage(callContext, "", "{\"extra\":true}")); + } + + private static void assertStreamingError(RestHandler.HTTPRestResponse response) { + RestHandler.HTTPRestStreamingResponse stream = Assertions.assertInstanceOf( + RestHandler.HTTPRestStreamingResponse.class, response); + CompletableFuture event = new CompletableFuture<>(); + stream.getPublisher().subscribe(new Flow.Subscriber<>() { + @Override public void onSubscribe(Flow.Subscription subscription) { subscription.request(1); } + @Override public void onNext(String item) { event.complete(item); } + @Override public void onError(Throwable failure) { event.completeExceptionally(failure); } + @Override public void onComplete() { } + }); + Assertions.assertTrue(JsonParser.parseString(event.orTimeout(5, TimeUnit.SECONDS).join()) + .getAsJsonObject().has("error")); + } + @Test public void testSendMessageWrongValueBody() { RestHandler handler = new RestHandler(CARD, createCacheMetadata(), requestHandler, internalExecutor); @@ -201,7 +291,7 @@ public void testSendMessageWrongValueBody() { RestHandler.HTTPRestResponse response = handler.sendMessage(callContext, "", requestBody); Assertions.assertEquals(422, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); JsonObject body = JsonParser.parseString(response.getBody()).getAsJsonObject(); JsonObject error = body.getAsJsonObject("error"); Assertions.assertEquals(422, error.get("code").getAsInt()); @@ -237,7 +327,7 @@ public void testCancelTaskSuccess() { RestHandler.HTTPRestResponse response = handler.cancelTask(callContext, "", requestBody, MINIMAL_TASK.id()); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); } @@ -279,7 +369,7 @@ public void testCancelTaskWithMetadata() { RestHandler.HTTPRestResponse response = handler.cancelTask(callContext, "", requestBody, MINIMAL_TASK.id()); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); } @@ -303,7 +393,7 @@ public void testCancelTaskWithEmptyMetadata() { RestHandler.HTTPRestResponse response = handler.cancelTask(callContext, "", requestBody, MINIMAL_TASK.id()); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); } @@ -323,7 +413,7 @@ public void testCancelTaskWithNoMetadata() { RestHandler.HTTPRestResponse response = handler.cancelTask(callContext, "", requestBody, MINIMAL_TASK.id()); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); } @@ -341,7 +431,7 @@ public void testCancelTaskWithNullBody() { RestHandler.HTTPRestResponse response = handler.cancelTask(callContext, "", null, MINIMAL_TASK.id()); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); } @@ -416,7 +506,7 @@ public void testPushNotificationConfigSuccess() { RestHandler.HTTPRestResponse response = handler.createTaskPushNotificationConfiguration(callContext, "", requestBody, MINIMAL_TASK.id()); Assertions.assertEquals(201, response.getStatusCode(), response.toString()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertNotNull(response.getBody()); } @@ -457,11 +547,11 @@ public void testGetPushNotificationConfig() { }""".formatted(MINIMAL_TASK.id()); RestHandler.HTTPRestResponse response = handler.createTaskPushNotificationConfiguration(callContext, "", createRequestBody, MINIMAL_TASK.id()); Assertions.assertEquals(201, response.getStatusCode(), response.toString()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); // Now get it response = handler.getTaskPushNotificationConfiguration(callContext, "", MINIMAL_TASK.id(), "default-config-id"); Assertions.assertEquals(200, response.getStatusCode(), response.toString()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); } @Test @@ -480,7 +570,7 @@ public void testListPushNotificationConfigs() { RestHandler.HTTPRestResponse response = handler.listTaskPushNotificationConfigurations(callContext, "", MINIMAL_TASK.id(), "0", ""); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertNotNull(response.getBody()); } @@ -809,7 +899,7 @@ public void testRequiredExtensionProvidedSuccess() { // Should succeed without error Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertNotNull(response.getBody()); } @@ -1010,7 +1100,7 @@ public void testCompatibleVersionSuccess() { // Should succeed without error Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertNotNull(response.getBody()); } @@ -1096,7 +1186,7 @@ public void testListTasksProtobufEnumStatus() { null, null, null); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); } @@ -1110,7 +1200,7 @@ public void testListTasksEnumConstantStatus() { null, null, null); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains(MINIMAL_TASK.id())); } @@ -1123,7 +1213,7 @@ public void testListTasksEmptyResultIncludesAllFields() { null, null, null); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); String body = response.getBody(); // Verify all required fields are present (not missing) @@ -1147,7 +1237,7 @@ void constructorDoesNotResolveAgentCardInstances() { private static void assertProblemDetail(RestHandler.HTTPRestResponse response, int expectedStatus, String expectedReason, String expectedMessage) { Assertions.assertEquals(expectedStatus, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); JsonObject body = JsonParser.parseString(response.getBody()).getAsJsonObject(); Assertions.assertTrue(body.has("error"), "error wrapper should be present"); JsonObject error = body.getAsJsonObject("error"); @@ -1290,7 +1380,7 @@ public void testExtendedAgentCardWithRouterKnownTenant() { RestHandler.HTTPRestResponse response = handler.getExtendedAgentCard(callContext, "acme"); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertTrue(response.getBody().contains("acme-card")); } @@ -1553,7 +1643,7 @@ private static void assertSingleStreamProblem(RestHandler.HTTPRestStreamingRespo @Override public void onError(Throwable failure) { event.completeExceptionally(failure); } @Override public void onComplete() { } }); - assertProblemDetail(new RestHandler.HTTPRestResponse(status, APPLICATION_JSON, event.join()), + assertProblemDetail(new RestHandler.HTTPRestResponse(status, APPLICATION_A2A_JSON, event.join()), status, reason, message); } @@ -1671,7 +1761,7 @@ private void assertRawVersionError(RestHandler.HTTPRestResponse response) { private void assertRawInputError(RestHandler.HTTPRestResponse response, int status, String reason, String message) { Assertions.assertEquals(status, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); Assertions.assertFalse(response instanceof RestHandler.HTTPRestStreamingResponse); Assertions.assertEquals(Map.of(), response.getHeaders()); JsonObject expected = JsonParser.parseString(""" @@ -1798,7 +1888,7 @@ public void testListTasksRawQueryValidationOrder() { RestHandler.HTTPRestResponse response = validationRestHandler.listTasks(validationContext, "", null, "task_state_submitted", number, null, number, null, raw); Assertions.assertEquals(200, response.getStatusCode()); - Assertions.assertEquals(APPLICATION_JSON, response.getContentType()); + Assertions.assertEquals(APPLICATION_A2A_JSON, response.getContentType()); ArgumentCaptor params = ArgumentCaptor.forClass(ListTasksParams.class); Mockito.verify(validationHandler).onListTasks(params.capture(), Mockito.any()); From 1f6d90e06bad88d8d913dfc1353c195638d23ae1 Mon Sep 17 00:00:00 2001 From: Emmanuel Hugonnet Date: Thu, 19 Nov 2026 08:57:30 +0100 Subject: [PATCH 2/2] Updating TCK to main Signed-off-by: Emmanuel Hugonnet --- .github/workflows/run-tck.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/run-tck.yml b/.github/workflows/run-tck.yml index 473d6ffca..d127b7bb8 100644 --- a/.github/workflows/run-tck.yml +++ b/.github/workflows/run-tck.yml @@ -15,7 +15,8 @@ on: env: # Tag/branch of the TCK - TCK_VERSION: 1.0.0.alpha3 + #TCK_VERSION: 1.0.0.alpha3 + TCK_VERSION: main TCK_VERSION_0_3: 0.3.0.beta6 # Tells uv to not need a venv, and instead use system UV_SYSTEM_PYTHON: 1 @@ -93,10 +94,10 @@ jobs: done - name: Run TCK id: run-tck - timeout-minutes: 5 + timeout-minutes: 10 run: | set -o pipefail - uv run ./run_tck.py --sut-host ${{ env.SUT_URL }} -v 2>&1 | tee tck-output.log + ./run_tck.py --sut-host ${{ env.SUT_URL }} -v 2>&1 | tee tck-output.log working-directory: a2a-tck - name: TCK Summary if: always() && steps.run-tck.outcome != 'skipped'