Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 94 additions & 7 deletions samples/client/lit/shell/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,99 @@ import { A2AClient } from "@a2a-js/sdk/client";
import { v0_8 } from "@a2ui/lit";

const A2UI_MIME_TYPE = "application/json+a2ui";
const TEXT_FALLBACK_SURFACE_ID = "@default";
const TEXT_FALLBACK_ROOT_ID = "__a2ui_text_fallback_root";

function textFallbackComponentId(index: number) {
return `__a2ui_text_fallback_${index}`;
}

export function convertA2APartsToMessages(
parts: Part[]
): v0_8.Types.ServerToClientMessage[] {
const dataMessages: v0_8.Types.ServerToClientMessage[] = [];
const textMessages: string[] = [];

for (const part of parts) {
if (part.kind === "data") {
dataMessages.push(part.data as v0_8.Types.ServerToClientMessage);
continue;
}

if (part.kind === "text" && part.text.trim().length > 0) {
textMessages.push(part.text);
}
}

if (dataMessages.length > 0 || textMessages.length === 0) {
return dataMessages;
}

if (textMessages.length === 1) {
const rootId = textFallbackComponentId(0);
return [
{
beginRendering: {
root: rootId,
surfaceId: TEXT_FALLBACK_SURFACE_ID,
},
},
{
surfaceUpdate: {
surfaceId: TEXT_FALLBACK_SURFACE_ID,
components: [
{
id: rootId,
component: {
Text: {
usageHint: "body" as const,
text: { literalString: textMessages[0] },
},
},
},
],
},
},
];
}

const childIds = textMessages.map((_, index) => textFallbackComponentId(index));

return [
{
beginRendering: {
root: TEXT_FALLBACK_ROOT_ID,
surfaceId: TEXT_FALLBACK_SURFACE_ID,
},
},
{
surfaceUpdate: {
surfaceId: TEXT_FALLBACK_SURFACE_ID,
components: [
{
id: TEXT_FALLBACK_ROOT_ID,
component: {
Column: {
children: {
explicitList: childIds,
},
},
},
},
...textMessages.map((text, index) => ({
id: childIds[index],
component: {
Text: {
usageHint: "body" as const,
text: { literalString: text },
},
},
})),
],
},
},
];
Comment on lines +50 to +113
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The logic for handling single and multiple text messages is a bit repetitive. Both branches of the if statement construct and return a similar array of beginRendering and surfaceUpdate messages. You can reduce this duplication by first determining the rootId and components array based on the number of text messages, and then constructing the final message array once.

  let rootId: string;
  let components: v0_8.Types.ComponentInstance[];

  if (textMessages.length === 1) {
    rootId = textFallbackComponentId(0);
    components = [
      {
        id: rootId,
        component: {
          Text: {
            usageHint: "body" as const,
            text: { literalString: textMessages[0] },
          },
        },
      },
    ];
  } else {
    rootId = TEXT_FALLBACK_ROOT_ID;
    const childIds = textMessages.map((_, index) =>
      textFallbackComponentId(index)
    );
    components = [
      {
        id: TEXT_FALLBACK_ROOT_ID,
        component: {
          Column: {
            children: {
              explicitList: childIds,
            },
          },
        },
      },
      ...textMessages.map((text, index) => ({
        id: childIds[index],
        component: {
          Text: {
            usageHint: "body" as const,
            text: { literalString: text },
          },
        },
      })),
    ];
  }

  return [
    {
      beginRendering: {
        root: rootId,
        surfaceId: TEXT_FALLBACK_SURFACE_ID,
      },
    },
    {
      surfaceUpdate: {
        surfaceId: TEXT_FALLBACK_SURFACE_ID,
        components,
      },
    },
  ];

}

export class A2UIClient {
#serverUrl: string;
Expand Down Expand Up @@ -98,13 +191,7 @@ export class A2UIClient {

const result = (response as SendMessageSuccessResponse).result as Task;
if (result.kind === "task" && result.status.message?.parts) {
const messages: v0_8.Types.ServerToClientMessage[] = [];
for (const part of result.status.message.parts) {
if (part.kind === 'data') {
messages.push(part.data as v0_8.Types.ServerToClientMessage);
}
}
return messages;
return convertA2APartsToMessages(result.status.message.parts);
}

return [];
Expand Down
85 changes: 85 additions & 0 deletions samples/client/lit/shell/tests/client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import test from "node:test";
import assert from "node:assert/strict";
import { v0_8 } from "@a2ui/lit";
import { convertA2APartsToMessages } from "../client.js";
import type { Part } from "@a2a-js/sdk";

test("convertA2APartsToMessages preserves A2UI data parts", () => {
const beginRendering: v0_8.Types.ServerToClientMessage = {
beginRendering: {
root: "root",
surfaceId: "@default",
},
};

const messages = convertA2APartsToMessages([
{
kind: "data",
data: beginRendering as unknown as Record<string, unknown>,
mimeType: "application/json+a2ui",
} as Part,
{
kind: "text",
text: "This should not replace a valid A2UI response.",
} as Part,
]);

assert.deepEqual(messages, [beginRendering]);
});

test("convertA2APartsToMessages converts a text-only fallback into renderable messages", () => {
const messages = convertA2APartsToMessages([
{
kind: "text",
text: "Oops, I couldn't find anything you requested.",
} as Part,
]);

assert.equal(messages.length, 2);
assert.deepEqual(messages[0], {
beginRendering: {
root: "__a2ui_text_fallback_0",
surfaceId: "@default",
},
});

const processor = new v0_8.Data.A2uiMessageProcessor();
processor.processMessages(messages);

const surface = processor.getSurfaces().get("@default");
assert.ok(surface);
assert.equal(surface.rootComponentId, "__a2ui_text_fallback_0");
assert.ok(surface.components.has("__a2ui_text_fallback_0"));
});

test("convertA2APartsToMessages stacks multiple text fallbacks into a column", () => {
const messages = convertA2APartsToMessages([
{ kind: "text", text: "First fallback" } as Part,
{ kind: "text", text: "Second fallback" } as Part,
]);

const processor = new v0_8.Data.A2uiMessageProcessor();
processor.processMessages(messages);

const surface = processor.getSurfaces().get("@default");
assert.ok(surface);
assert.equal(surface.rootComponentId, "__a2ui_text_fallback_root");
assert.ok(surface.components.has("__a2ui_text_fallback_0"));
assert.ok(surface.components.has("__a2ui_text_fallback_1"));
});