Skip to content
Merged
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
4 changes: 4 additions & 0 deletions packages/genkit-a2ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ emit ` ```a2ui ` fences; the middleware rewrites them into
`application/a2ui+json` data parts. On the next turn, those parts become text
again so the model can see prior surfaces and button clicks.

A part's data is the A2UI extension spec's message list wrapper,
`{"messages": [...]}`, as in the Dart, JS and Go plugins. Parts written with the
older `envelopes` key are still read.

```python
from genkit import Genkit
from genkit_a2ui import Surfaces, envelopes_from_parts
Expand Down
39 changes: 26 additions & 13 deletions packages/genkit-a2ui/src/genkit_a2ui/_part.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,20 @@
from __future__ import annotations

from collections.abc import Sequence
from typing import Any

from genkit import Part

from ._types import A2UI_MIME_TYPE, Envelope


def a2ui_part(envelopes: list[Envelope]) -> Part:
return Part.from_data({'envelopes': envelopes}, metadata={'mimeType': A2UI_MIME_TYPE})
"""Wraps envelopes in an A2UI data part.

The list sits under the A2UI extension spec's own ``messages`` wrapper
(``{"messages": [...]}``), the same key the Dart, JS and Go plugins use.
"""
return Part.from_data({'messages': envelopes}, metadata={'mimeType': A2UI_MIME_TYPE})


def has_a2ui_mime(*, part: Part) -> bool:
Expand All @@ -36,27 +42,34 @@ def has_a2ui_mime(*, part: Part) -> bool:
return metadata.get('mimeType') == A2UI_MIME_TYPE


def is_a2ui_part(part: Part) -> bool:
if not has_a2ui_mime(part=part):
return False
def _messages_of(part: Part) -> list[Any] | None:
"""The message list in an A2UI part's data.

``messages``, or ``envelopes`` for a part written before the rename (still
read, so persisted sessions and older clients keep working). A
``messages`` key that is present but ``None`` falls back too.
"""
data = part.data
return isinstance(data, dict) and 'envelopes' in data
if not isinstance(data, dict):
return None
raw = data.get('messages')
if raw is None:
raw = data.get('envelopes')
return raw if isinstance(raw, list) else None


def is_a2ui_part(part: Part) -> bool:
return has_a2ui_mime(part=part) and _messages_of(part) is not None


def envelopes_from_parts(parts: Sequence[Part] | None) -> list[Envelope]:
if not parts:
return []
out: list[Envelope] = []
for part in parts:
if not is_a2ui_part(part):
continue
data = part.data
if not isinstance(data, dict):
continue
raw_envelopes = data.get('envelopes')
if not isinstance(raw_envelopes, list):
if not has_a2ui_mime(part=part):
continue
for item in raw_envelopes:
for item in _messages_of(part) or []:
if isinstance(item, dict):
out.append(item)
return out
31 changes: 19 additions & 12 deletions packages/genkit-a2ui/tests/generate_a2ui_inbound_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,12 @@


@pytest.mark.asyncio
async def test_generate_a2ui_sends_click_to_model_as_text() -> None:
"""A button click reaches the model as text, not as an A2UI data part."""
@pytest.mark.parametrize('key', ['messages', 'envelopes'])
async def test_generate_a2ui_sends_click_to_model_as_text(key: str) -> None:
"""A button click reaches the model as text, not as an A2UI data part.

Clients send ``messages``; ``envelopes`` is the pre-rename key, still read.
"""
ai, pm = setup()
pm.responses = [model_ok()]

Expand All @@ -53,17 +57,20 @@ async def test_generate_a2ui_sends_click_to_model_as_text() -> None:
role=Role.USER,
content=[
text_part('User interacted with the UI…'),
a2ui_data_part([
{
'action': {
'name': 'refresh',
'surfaceId': 's1',
'sourceComponentId': 'btn',
'timestamp': 't',
'context': {'city': 'Tokyo'},
a2ui_data_part(
[
{
'action': {
'name': 'refresh',
'surfaceId': 's1',
'sourceComponentId': 'btn',
'timestamp': 't',
'context': {'city': 'Tokyo'},
}
}
}
]),
],
key=key,
),
],
)
],
Expand Down
6 changes: 3 additions & 3 deletions packages/genkit-a2ui/tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ def no_root_fence(*, catalog_id: str = BASIC_CATALOG_ID) -> str:
])


def a2ui_data_part(envelopes: list[dict[str, Any]]) -> Part:
return Part.from_data({'envelopes': envelopes}, metadata={'mimeType': A2UI_MIME_TYPE})
def a2ui_data_part(envelopes: list[dict[str, Any]], *, key: str = 'messages') -> Part:
return Part.from_data({key: envelopes}, metadata={'mimeType': A2UI_MIME_TYPE})


def text_part(text: str) -> Part:
Expand Down Expand Up @@ -119,7 +119,7 @@ def envelopes(content: list[Part]) -> list[dict[str, Any]]:
data = part.data
if not isinstance(data, dict):
continue
raw = data.get('envelopes')
raw = data.get('messages')
if isinstance(raw, list):
out.extend(env for env in raw if isinstance(env, dict))
return out
Expand Down
75 changes: 75 additions & 0 deletions packages/genkit-a2ui/tests/part_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Copyright 2026 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
#
# http://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.
#
# SPDX-License-Identifier: Apache-2.0

"""The A2UI part's wire shape: written as ``messages``, read as either key."""

from __future__ import annotations

from genkit_a2ui import A2UI_MIME_TYPE, a2ui_part, envelopes_from_parts, is_a2ui_part

from genkit import Part

CREATE = {'version': 'v0.9', 'createSurface': {'surfaceId': 's', 'catalogId': 'c'}}
DELETE = {'version': 'v0.9', 'deleteSurface': {'surfaceId': 's'}}


def _part(data: dict[str, object]) -> Part:
return Part.from_data(data, metadata={'mimeType': A2UI_MIME_TYPE})


def test_a2ui_part_writes_the_spec_messages_key() -> None:
assert a2ui_part([CREATE]).data == {'messages': [CREATE]}


def test_reads_the_legacy_envelopes_key() -> None:
legacy = _part({'envelopes': [CREATE]})
assert is_a2ui_part(legacy)
assert envelopes_from_parts([legacy]) == [CREATE]


def test_messages_wins_when_both_keys_are_present() -> None:
assert envelopes_from_parts([_part({'messages': [CREATE], 'envelopes': [DELETE]})]) == [CREATE]


def test_empty_messages_list_wins_over_legacy_envelopes() -> None:
empty = _part({'messages': [], 'envelopes': [DELETE]})
assert is_a2ui_part(empty)
assert envelopes_from_parts([empty]) == []


def test_falls_back_to_envelopes_when_messages_is_none() -> None:
part = _part({'messages': None, 'envelopes': [CREATE]})
assert is_a2ui_part(part)
assert envelopes_from_parts([part]) == [CREATE]


def test_rejects_non_list_message_lists() -> None:
for bad in [
_part({'messages': 'oops'}),
_part({'messages': 'oops', 'envelopes': [CREATE]}),
_part({'envelopes': 'oops'}),
]:
assert not is_a2ui_part(bad)
assert envelopes_from_parts([bad]) == []


def test_rejects_non_a2ui_parts() -> None:
wrong_mime = Part.from_data({'messages': [CREATE]}, metadata={'mimeType': 'application/json'})
missing_mime = Part.from_data({'messages': [CREATE]})
plain_text = Part.from_text('hello')
for part in [wrong_mime, missing_mime, plain_text]:
assert not is_a2ui_part(part)
assert envelopes_from_parts([part]) == []
Loading