diff --git a/.github/workflows/android-ci.yml b/.github/workflows/android-ci.yml new file mode 100644 index 0000000..f4b9d68 --- /dev/null +++ b/.github/workflows/android-ci.yml @@ -0,0 +1,114 @@ +# 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. + +name: Android CI + +on: + pull_request: + branches: [ main ] + workflow_dispatch: + +# Cancel superseded pull_request runs when a newer commit is pushed to the same +# PR. Other events get a per-commit group, so they are never cancelled. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +jobs: + build: + name: Android CI / build + # zizmor: ignore[unpinned-images] + runs-on: ubuntu-24.04 + timeout-minutes: 15 + + steps: + - name: Checkout samples repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + path: a2ui-samples + persist-credentials: false + + - name: Resolve core SDK branch + id: core_ref + env: + HEAD_REF: ${{ github.head_ref }} + run: | + RESOLVED_REF="main" + case "$HEAD_REF" in + test_*) + # Poll up to 80s for the parallel Copybara-Review-a2ui-core export to push test_. + for ATTEMPT in $(seq 1 9); do + if git ls-remote --exit-code --heads https://github.com/googlemaps/a2ui.git "refs/heads/$HEAD_REF" >/dev/null 2>&1; then + RESOLVED_REF="$HEAD_REF" + break + fi + if [ "$ATTEMPT" -lt 9 ]; then + echo "Waiting 10s for Copybara to push $HEAD_REF to googlemaps/a2ui (attempt $ATTEMPT/9)..." + sleep 10 + fi + done + if [ "$RESOLVED_REF" = "main" ]; then + echo "::warning::Branch $HEAD_REF not found on googlemaps/a2ui after 80s; falling back to main." + fi + ;; + esac + echo "Using googlemaps/a2ui ref: $RESOLVED_REF" + echo "ref=$RESOLVED_REF" >> "$GITHUB_OUTPUT" + + - name: Checkout core SDK repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + repository: googlemaps/a2ui + ref: ${{ steps.core_ref.outputs.ref }} + path: a2ui + persist-credentials: false + + - name: Set up JDK 17 + uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 + with: + distribution: 'temurin' + java-version: '17' + cache: 'gradle' + cache-dependency-path: | + a2ui/client/android/GoogleMapsA2UI/**/*.gradle* + a2ui-samples/client/android/**/*.gradle* + + - name: Publish core SDK to Maven Local + run: | + chmod +x ./gradlew + ./gradlew publishToMavenLocal --no-daemon + working-directory: a2ui/client/android/GoogleMapsA2UI + + - name: Build and test sample app + run: | + # app/build.gradle explicitly configures ~/.android/debug.keystore in signingConfigs.debug. + mkdir -p "$HOME/.android" + if [ ! -f "$HOME/.android/debug.keystore" ]; then + keytool -genkey -v \ + -keystore "$HOME/.android/debug.keystore" \ + -storepass android -alias androiddebugkey -keypass android \ + -keyalg RSA -keysize 2048 -validity 10000 \ + -dname "CN=Android Debug,O=Android,C=US" + fi + cat << 'EOF' > local.properties + MAPS_API_KEY=AIzaSyDummyKeyForCITestingOnly00000000 + GATEWAY_API_KEY=AIzaSyDummyKeyForCITestingOnly00000000 + GATEWAY_URL=http://10.0.2.2:10002 + EOF + chmod +x ./gradlew + ./gradlew testDebugUnitTest assembleDebug assembleDebugAndroidTest --no-daemon + working-directory: a2ui-samples/client/android diff --git a/.github/workflows/ios-ci.yml b/.github/workflows/ios-ci.yml new file mode 100644 index 0000000..1ef5aa9 --- /dev/null +++ b/.github/workflows/ios-ci.yml @@ -0,0 +1,96 @@ +# 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. + +name: iOS CI + +on: + pull_request: + branches: [ main ] + workflow_dispatch: + +# Cancel superseded pull_request runs when a newer commit is pushed to the same +# PR. Other events get a per-commit group, so they are never cancelled. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +jobs: + build: + name: iOS CI / build + # Pinned to macos-15 so the bundled Xcode and iOS Simulator lineup stay stable. + # zizmor: ignore[unpinned-images] + runs-on: macos-15 + timeout-minutes: 30 + + steps: + - name: Checkout samples repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + path: a2ui-samples + persist-credentials: false + + - name: Resolve core SDK branch + id: core_ref + env: + HEAD_REF: ${{ github.head_ref }} + run: | + RESOLVED_REF="main" + case "$HEAD_REF" in + test_*) + # Poll up to 80s for the parallel Copybara-Review-a2ui-core export to push test_. + for ATTEMPT in $(seq 1 9); do + if git ls-remote --exit-code --heads https://github.com/googlemaps/a2ui.git "refs/heads/$HEAD_REF" >/dev/null 2>&1; then + RESOLVED_REF="$HEAD_REF" + break + fi + if [ "$ATTEMPT" -lt 9 ]; then + echo "Waiting 10s for Copybara to push $HEAD_REF to googlemaps/a2ui (attempt $ATTEMPT/9)..." + sleep 10 + fi + done + if [ "$RESOLVED_REF" = "main" ]; then + echo "::warning::Branch $HEAD_REF not found on googlemaps/a2ui after 80s; falling back to main." + fi + ;; + esac + echo "Using googlemaps/a2ui ref: $RESOLVED_REF" + echo "ref=$RESOLVED_REF" >> "$GITHUB_OUTPUT" + + - name: Checkout core SDK repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + repository: googlemaps/a2ui + ref: ${{ steps.core_ref.outputs.ref }} + path: a2ui + persist-credentials: false + + - name: Build and test sample app + run: | + xcodebuild build-for-testing \ + -project A2UI-Example.xcodeproj \ + -scheme A2UI-Example \ + -destination 'platform=iOS Simulator,name=iPhone 16' \ + -skipPackagePluginValidation \ + CODE_SIGNING_ALLOWED=NO + xcodebuild test-without-building \ + -project A2UI-Example.xcodeproj \ + -scheme A2UI-Example \ + -destination 'platform=iOS Simulator,name=iPhone 16' \ + -only-testing:A2UI-ExampleTests \ + -skipPackagePluginValidation \ + CODE_SIGNING_ALLOWED=NO + working-directory: a2ui-samples/client/ios diff --git a/.github/workflows/python-ci.yml b/.github/workflows/python-ci.yml index 6704f4d..43c6dfe 100644 --- a/.github/workflows/python-ci.yml +++ b/.github/workflows/python-ci.yml @@ -20,6 +20,12 @@ on: pull_request: branches: [ main ] +# Cancel superseded pull_request runs when a newer commit is pushed to the same +# PR. Other events get a per-commit group, so they are never cancelled. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: build: name: Python CI / build @@ -27,29 +33,76 @@ jobs: permissions: contents: read steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - name: Checkout samples repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + path: a2ui-samples + persist-credentials: false + + - name: Resolve core SDK branch + id: core_ref + env: + HEAD_REF: ${{ github.head_ref }} + run: | + RESOLVED_REF="main" + case "$HEAD_REF" in + test_*) + # Poll up to 80s for the parallel Copybara-Review-a2ui-core export to push test_. + for ATTEMPT in $(seq 1 9); do + if git ls-remote --exit-code --heads https://github.com/googlemaps/a2ui.git "refs/heads/$HEAD_REF" >/dev/null 2>&1; then + RESOLVED_REF="$HEAD_REF" + break + fi + if [ "$ATTEMPT" -lt 9 ]; then + echo "Waiting 10s for Copybara to push $HEAD_REF to googlemaps/a2ui (attempt $ATTEMPT/9)..." + sleep 10 + fi + done + if [ "$RESOLVED_REF" = "main" ]; then + echo "::warning::Branch $HEAD_REF not found on googlemaps/a2ui after 80s; falling back to main." + fi + ;; + esac + echo "Using googlemaps/a2ui ref: $RESOLVED_REF" + echo "ref=$RESOLVED_REF" >> "$GITHUB_OUTPUT" + + - name: Checkout core SDK repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: + repository: googlemaps/a2ui + ref: ${{ steps.core_ref.outputs.ref }} + path: a2ui persist-credentials: false - + - name: Install uv uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 with: enable-cache: auto - name: Set up Python - run: uv python install + run: uv python install 3.13 - - name: Install dependencies - run: uv sync --all-groups - working-directory: agent/python - continue-on-error: true + - name: Configure local MAUI SDK path and install dependencies + run: | + chmod +x setup.sh + ./setup.sh ../../../a2ui/agent/python_agent + uv sync --all-groups + working-directory: a2ui-samples/agent/python + + - name: Verify sample agent imports and CLI entrypoint + run: uv run python __main__.py --help + working-directory: a2ui-samples/agent/python + + - name: Run unit tests + run: uv run python -m unittest discover -s . -p "test_*.py" + working-directory: a2ui-samples/agent/python - name: Type check with pyright run: uv run pyright - working-directory: agent/python + working-directory: a2ui-samples/agent/python continue-on-error: true - name: Lint with ruff run: uv run ruff check . - working-directory: agent/python + working-directory: a2ui-samples/agent/python continue-on-error: true diff --git a/.github/workflows/web-ci.yml b/.github/workflows/web-ci.yml index 88567df..33c52fc 100644 --- a/.github/workflows/web-ci.yml +++ b/.github/workflows/web-ci.yml @@ -20,16 +20,58 @@ on: pull_request: branches: [ main ] +# Cancel superseded pull_request runs when a newer commit is pushed to the same +# PR. Other events get a per-commit group, so they are never cancelled. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: build: name: Web CI / build runs-on: ubuntu-latest permissions: contents: read - packages: read steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Checkout samples repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: + path: a2ui-samples + persist-credentials: false + + - name: Resolve core SDK branch + id: core_ref + env: + HEAD_REF: ${{ github.head_ref }} + run: | + RESOLVED_REF="main" + case "$HEAD_REF" in + test_*) + # Poll up to 80s for the parallel Copybara-Review-a2ui-core export to push test_. + for ATTEMPT in $(seq 1 9); do + if git ls-remote --exit-code --heads https://github.com/googlemaps/a2ui.git "refs/heads/$HEAD_REF" >/dev/null 2>&1; then + RESOLVED_REF="$HEAD_REF" + break + fi + if [ "$ATTEMPT" -lt 9 ]; then + echo "Waiting 10s for Copybara to push $HEAD_REF to googlemaps/a2ui (attempt $ATTEMPT/9)..." + sleep 10 + fi + done + if [ "$RESOLVED_REF" = "main" ]; then + echo "::warning::Branch $HEAD_REF not found on googlemaps/a2ui after 80s; falling back to main." + fi + ;; + esac + echo "Using googlemaps/a2ui ref: $RESOLVED_REF" + echo "ref=$RESOLVED_REF" >> "$GITHUB_OUTPUT" + + - name: Checkout core SDK repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + repository: googlemaps/a2ui + ref: ${{ steps.core_ref.outputs.ref }} + path: a2ui persist-credentials: false - name: Use Node.js @@ -37,16 +79,16 @@ jobs: with: node-version: '22' - - name: Install dependencies - run: npm install - working-directory: client/web/react + - name: Build and link core Web SDK + run: npm run build-and-link + working-directory: a2ui/client/web - - name: Type check - run: npx tsc --noEmit - working-directory: client/web/react - continue-on-error: true + - name: Install dependencies + run: | + npm install + npm link @googlemaps/a2ui + working-directory: a2ui-samples/client/web/react - - name: Build + - name: Type check and build run: npm run build - working-directory: client/web/react - continue-on-error: true + working-directory: a2ui-samples/client/web/react diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml index 43ab814..fb2e5d4 100644 --- a/.github/workflows/zizmor.yml +++ b/.github/workflows/zizmor.yml @@ -20,6 +20,12 @@ on: pull_request: branches: [ main ] +# Cancel superseded pull_request runs when a newer commit is pushed to the same +# PR. Other events get a per-commit group, so they are never cancelled. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: security-events: write contents: read diff --git a/README.md b/README.md index 8e6f81c..63c6bf2 100644 --- a/README.md +++ b/README.md @@ -153,17 +153,9 @@ The iOS sample is a native app utilizing SwiftUI and the [GoogleMapsA2UI(iOS)](h For more server configration and other detailed setup, refer to the [iOS Sample README](client/ios/README.md). -#### Streaming vs. Non-Streaming Responses (`useStreaming`) +#### Grounding Method Selection -All three sample clients (Web, Android, and iOS) default to **SSE streaming** (`useStreaming = true`) so conversational text and A2UI map components render progressively as they arrive from the agent (`message/stream`). - -You can switch between **Streaming** (`message/stream` / `client.sendStream()`) and **Non-Streaming** (`message/send` / `client.send()`) at any time: - -* **In the UI**: Toggle the **Streaming** switch/checkbox in the sample app header or control bar. -* **In Code (Default Configuration)**: - * **Web (React)**: Set `DEFAULT_USE_STREAMING = true` (or `false`) in [`client/web/react/src/App.tsx`](client/web/react/src/App.tsx). - * **Android**: Set `DEFAULT_USE_STREAMING = true` (or `false`) in [`ChatRepository.kt`](client/android/app/src/main/java/com/example/maui/data/ChatRepository.kt). - * **iOS**: Set `defaultUseStreaming: Bool = true` (or `false`) in [`ChatService.swift`](client/ios/ChatService.swift). +All three sample clients (Web, Android, and iOS) let you switch between **Grounding Lite (MCP)** and **Grounding with Google Maps (Vertex)** in the client header or control bar. ## Google API Keys diff --git a/agent/python/README.md b/agent/python/README.md index a31a344..f3853e8 100644 --- a/agent/python/README.md +++ b/agent/python/README.md @@ -52,10 +52,10 @@ The sample server supports 4 agent backends configured via `--agent` or the Agent Mode | CLI Flag / Env Option | Description :--------------------------------------- | :---------------------------------------------------------------------- | :---------- -**Template Agent (Recommended)** | `--agent TEMPLATE`
`A2UI_DEFAULT_AGENT=TEMPLATE` | Low-latency template agent with fast intent classification (`LOCAL_SEARCH`, `DIRECTIONS`) and structured parameter merging. -**Grounding Template Agent** | `--agent GROUNDING_TEMPLATE`
`A2UI_DEFAULT_AGENT=GROUNDING_TEMPLATE` | Template agent using Vertex AI Maps Grounding. +**Template Agent (Recommended)** | `--agent TEMPLATE`
`A2UI_DEFAULT_AGENT=TEMPLATE` | Low-latency template agent with fast intent classification (`LOCAL_SEARCH`, `DIRECTIONS`, `PLACE_ANSWER_FACTUAL`, `NEARBY_PLACES_DEPTH`) and structured parameter merging. +**Grounding Template Agent** | `--agent GROUNDING_TEMPLATE`
`A2UI_DEFAULT_AGENT=GROUNDING_TEMPLATE` | Template agent combining Grounding with Google Maps and Google Search via Vertex AI. **Base Agent** | `--agent BASE`
`A2UI_DEFAULT_AGENT=BASE` | Standard dynamic UI agent generating unconstrained A2UI component trees. -**Grounding Agent** | `--agent GROUNDING`
`A2UI_DEFAULT_AGENT=GROUNDING` | Vertex AI Maps Grounding agent. +**Grounding Agent** | `--agent GROUNDING`
`A2UI_DEFAULT_AGENT=GROUNDING` | Dynamic agent combining Grounding with Google Maps and Google Search via Vertex AI. ### Running with Template Agent @@ -93,7 +93,7 @@ a static template: ### Streaming Support (`message/stream` & `message/send`) -The sample server uses `StreamingRequestHandler` by default, enabling both real-time Server-Sent Events (`message/stream`) and single-response JSON-RPC requests (`message/send`). Client applications across Web, Android, and iOS can toggle between streaming and non-streaming modes at runtime using their `useStreaming` toggle without restarting the server. +The sample server uses `StreamingRequestHandler` by default, enabling both real-time Server-Sent Events (`message/stream`) and single-response JSON-RPC requests (`message/send`). To run the frontend, follow the instructions in [../../client/web/react/README.md](../../client/web/react/README.md) diff --git a/client/android/README.md b/client/android/README.md index a1e326a..fb38dba 100644 --- a/client/android/README.md +++ b/client/android/README.md @@ -45,9 +45,8 @@ In `app/src/main/java/com/example/maui/MainActivity.kt`, verify the flags match * `DeviceType.PHYSICAL`: Use when testing on real Android devices. *(Note: If using a local Demo Server on a physical device, run `adb reverse tcp:10002 tcp:10002`)* * `DeviceType.EMULATOR`: Use when testing on emulators. -#### Streaming vs. Non-Streaming (`useStreaming`) -* By default, the app uses SSE streaming (`ChatRepository.DEFAULT_USE_STREAMING = true` in `ChatRepository.kt`, sending JSON-RPC `message/stream`). -* You can toggle between streaming (`message/stream`) and non-streaming (`message/send`) at runtime using the **Streaming** switch in the control bar (`MainActivity.kt`), or change `DEFAULT_USE_STREAMING` in `ChatRepository.kt`. +#### Grounding Method (`AgentType`) +* Use the radio buttons in the control bar (`MainActivity.kt`) to switch between **Grounding Lite (MCP)** and **Grounding with Google Maps (Vertex)**. ### 4. Build and Run the App diff --git a/client/android/app/build.gradle b/client/android/app/build.gradle index 48efb48..0109ff2 100644 --- a/client/android/app/build.gradle +++ b/client/android/app/build.gradle @@ -98,7 +98,9 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:5.3.2' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2' testImplementation 'junit:junit:4.13.2' - androidTestImplementation 'androidx.test.ext:junit:1.1.5' + androidTestImplementation 'androidx.test:core:1.6.1' + androidTestImplementation 'androidx.test.ext:junit:1.2.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.7.0' androidTestImplementation 'androidx.compose.ui:ui-test-junit4' androidTestImplementation 'com.google.truth:truth:1.4.2' androidTestImplementation 'com.google.testparameterinjector:test-parameter-injector:1.18' diff --git a/client/android/app/src/androidTest/java/com/example/maui/MainActivityTest.kt b/client/android/app/src/androidTest/java/com/example/maui/MainActivityTest.kt index 397d47c..16865ef 100644 --- a/client/android/app/src/androidTest/java/com/example/maui/MainActivityTest.kt +++ b/client/android/app/src/androidTest/java/com/example/maui/MainActivityTest.kt @@ -16,13 +16,24 @@ package com.example.maui +import android.content.Intent +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsOn +import androidx.compose.ui.test.assertIsSelected import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextReplacement +import androidx.test.core.app.ActivityScenario +import androidx.test.platform.app.InstrumentationRegistry import com.example.maui.A2UIWebViewAssertions.Components +import com.example.maui.data.ChatRepository +import com.google.common.truth.Truth.assertThat import com.google.testing.junit.testparameterinjector.TestParameter import com.google.testing.junit.testparameterinjector.TestParameterInjector +import org.json.JSONArray +import org.junit.After import org.junit.Assume.assumeFalse import org.junit.Rule import org.junit.Test @@ -34,6 +45,119 @@ class MainActivityTest { @get:Rule val composeTestRule = createAndroidComposeRule() + @After + fun tearDown() { + ChatRepository.baseUrlOverride = null + ChatRepository.bearerTokenOverride = null + } + + @Test + fun serverPrefix_returnsExpectedRoutingTag() { + assertThat(AgentType.LITE.serverPrefix).isEqualTo("[TEMPLATE] ") + assertThat(AgentType.VERTEX.serverPrefix).isEqualTo("[GROUNDING_TEMPLATE] ") + } + + @Test + fun chatRepository_usesBaseUrlAndBearerTokenOverrides() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val repository = ChatRepository(context) + ChatRepository.baseUrlOverride = "https://maui-backend.google.com" + ChatRepository.bearerTokenOverride = "test-bearer-token" + + val requestWithToken = repository.buildRequest(JSONArray()) + val sessionRequestWithToken = repository.buildSessionRequest() + assertThat(repository.baseUrl).isEqualTo("https://maui-backend.google.com") + assertThat(requestWithToken.url.toString()).startsWith("https://maui-backend.google.com/?key=") + assertThat(requestWithToken.header("Authorization")).isEqualTo("Bearer test-bearer-token") + assertThat(sessionRequestWithToken.header("Authorization")) + .isEqualTo("Bearer test-bearer-token") + + ChatRepository.bearerTokenOverride = "" + val requestWithoutToken = repository.buildRequest(JSONArray()) + val sessionRequestWithoutToken = repository.buildSessionRequest() + assertThat(requestWithoutToken.header("Authorization")).isNull() + assertThat(sessionRequestWithoutToken.header("Authorization")).isNull() + } + + @Test + fun launch_withBackendAndScreenExtras_appliesOverridesToRepositoryAndScreen() { + composeTestRule.activityRule.scenario.close() + val prompt = CannedResponse.SEATTLE_COFFEE_SHOPS.prompt + val intent = + Intent(InstrumentationRegistry.getInstrumentation().targetContext, MainActivity::class.java) + .putExtra(LaunchOverrides.EXTRA_BACKEND_URL_OVERRIDE, "https://maui-backend.google.com") + .putExtra(LaunchOverrides.EXTRA_BACKEND_BEARER_TOKEN, "test-bearer-token") + .putExtra(LaunchOverrides.EXTRA_USE_CANNED_RESPONSES, "false") + .putExtra(LaunchOverrides.EXTRA_AGENT_TYPE, "vertex") + .putExtra(LaunchOverrides.EXTRA_AUTO_SEND_PROMPT, prompt) + + ActivityScenario.launch(intent).use { + assertThat(ChatRepository.baseUrlOverride).isEqualTo("https://maui-backend.google.com") + assertThat(ChatRepository.bearerTokenOverride).isEqualTo("test-bearer-token") + composeTestRule.onNodeWithTag("switchCannedServer").assertIsOn() + composeTestRule.onNodeWithTag("radioAgentVertex").assertIsSelected() + composeTestRule.onNodeWithText(prompt).assertIsDisplayed() + } + } + + @Test + fun launch_withoutBackendExtras_keepsOverridesSetBeforeLaunch() { + ChatRepository.baseUrlOverride = "https://sut-backend.example.com" + ChatRepository.bearerTokenOverride = "preset-bearer-token" + + ActivityScenario.launch(MainActivity::class.java).use { + assertThat(ChatRepository.baseUrlOverride).isEqualTo("https://sut-backend.example.com") + assertThat(ChatRepository.bearerTokenOverride).isEqualTo("preset-bearer-token") + } + } + + @Test + fun launchOverrides_fromExtras_parsesSettingsAndPrompt() { + val extras = + mapOf( + LaunchOverrides.EXTRA_USE_CANNED_RESPONSES to "False", + LaunchOverrides.EXTRA_AGENT_TYPE to "vertex", + LaunchOverrides.EXTRA_AUTO_SEND_PROMPT to "Show 3 Indian Restaurants in Seattle", + ) + + val overrides = LaunchOverrides.fromExtras { extras[it] } + + assertThat(overrides) + .isEqualTo( + LaunchOverrides( + useCannedResponses = false, + agentType = AgentType.VERTEX, + autoSendPrompt = "Show 3 Indian Restaurants in Seattle", + ) + ) + } + + @Test + fun launchOverrides_fromExtras_parsesLiteAgentCaseInsensitivelyAndTrimsPrompt() { + val extras = + mapOf( + LaunchOverrides.EXTRA_AGENT_TYPE to "LITE", + LaunchOverrides.EXTRA_AUTO_SEND_PROMPT to " Edgewater Hotel ", + ) + + val overrides = LaunchOverrides.fromExtras { extras[it] } + + assertThat(overrides.agentType).isEqualTo(AgentType.LITE) + assertThat(overrides.autoSendPrompt).isEqualTo("Edgewater Hotel") + } + + @Test + fun launchOverrides_fromExtras_ignoresMissingAndInvalidValues() { + val extras = + mapOf( + LaunchOverrides.EXTRA_USE_CANNED_RESPONSES to "maybe", + LaunchOverrides.EXTRA_AGENT_TYPE to "unknown", + LaunchOverrides.EXTRA_AUTO_SEND_PROMPT to " ", + ) + + assertThat(LaunchOverrides.fromExtras { extras[it] }).isEqualTo(LaunchOverrides()) + } + @Test fun dynamicHeight_expandsToFitContent() { sendPromptAndAwaitSurface(CannedResponse.SEATTLE_COFFEE_SHOPS.prompt) diff --git a/client/android/app/src/main/java/com/example/maui/AgentType.kt b/client/android/app/src/main/java/com/example/maui/AgentType.kt index fff6fcc..d1b36b0 100644 --- a/client/android/app/src/main/java/com/example/maui/AgentType.kt +++ b/client/android/app/src/main/java/com/example/maui/AgentType.kt @@ -16,8 +16,7 @@ package com.example.maui -enum class AgentType { - LITE, - VERTEX, - TEMPLATE, +enum class AgentType(val serverPrefix: String) { + LITE("[TEMPLATE] "), + VERTEX("[GROUNDING_TEMPLATE] "), } diff --git a/client/android/app/src/main/java/com/example/maui/LaunchOverrides.kt b/client/android/app/src/main/java/com/example/maui/LaunchOverrides.kt new file mode 100644 index 0000000..44c0f8d --- /dev/null +++ b/client/android/app/src/main/java/com/example/maui/LaunchOverrides.kt @@ -0,0 +1,76 @@ +// 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. + +package com.example.maui + +import android.app.Activity +import android.content.pm.ApplicationInfo +import com.example.maui.data.ChatRepository + +/** + * Debug-only launch settings for automated UI tests. They let a test open the app in a given mode + * and send a prompt without tapping the controls. They are not needed to use the SDK, and release + * builds ignore them. A null field keeps the app's normal default. + */ +internal data class LaunchOverrides( + val useCannedResponses: Boolean? = null, + val agentType: AgentType? = null, + val autoSendPrompt: String? = null, +) { + companion object { + const val EXTRA_BACKEND_URL_OVERRIDE = "A2UI_BACKEND_URL_OVERRIDE" + const val EXTRA_BACKEND_BEARER_TOKEN = "A2UI_BACKEND_BEARER_TOKEN" + const val EXTRA_USE_CANNED_RESPONSES = "A2UI_USE_CANNED_RESPONSES" + const val EXTRA_AGENT_TYPE = "A2UI_AGENT_TYPE" + const val EXTRA_AUTO_SEND_PROMPT = "A2UI_AUTO_SEND_PROMPT" + + /** + * Reads launch settings from the intent of [activity] in debuggable builds, and returns no + * overrides otherwise. + * + * Also applies the backend URL and Bearer token to [ChatRepository], but only when their extras + * are passed, so an override that a test set before launching the activity is kept. + */ + fun applyDebugIntent(activity: Activity): LaunchOverrides { + val isDebuggable = (activity.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0 + val intent = activity.intent + if (!isDebuggable || intent == null) { + return LaunchOverrides() + } + intent + .getStringExtra(EXTRA_BACKEND_URL_OVERRIDE) + ?.takeIf { it.isNotEmpty() } + ?.let { ChatRepository.baseUrlOverride = it } + intent + .getStringExtra(EXTRA_BACKEND_BEARER_TOKEN) + ?.takeIf { it.isNotEmpty() } + ?.let { ChatRepository.bearerTokenOverride = it } + return fromExtras { key -> intent.getStringExtra(key) } + } + + /** Parses launch settings; `getExtra` returns the string extra for a key, or null. */ + fun fromExtras(getExtra: (String) -> String?): LaunchOverrides = + LaunchOverrides( + useCannedResponses = + getExtra(EXTRA_USE_CANNED_RESPONSES)?.lowercase()?.toBooleanStrictOrNull(), + agentType = + when (getExtra(EXTRA_AGENT_TYPE)?.lowercase()) { + "lite" -> AgentType.LITE + "vertex" -> AgentType.VERTEX + else -> null + }, + autoSendPrompt = getExtra(EXTRA_AUTO_SEND_PROMPT)?.trim()?.takeIf { it.isNotEmpty() }, + ) + } +} diff --git a/client/android/app/src/main/java/com/example/maui/MainActivity.kt b/client/android/app/src/main/java/com/example/maui/MainActivity.kt index a220a5d..a35798e 100644 --- a/client/android/app/src/main/java/com/example/maui/MainActivity.kt +++ b/client/android/app/src/main/java/com/example/maui/MainActivity.kt @@ -94,6 +94,9 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + // Debug-only test settings (see LaunchOverrides.kt); only read on the first launch. + val launchOverrides = + if (savedInstanceState == null) LaunchOverrides.applyDebugIntent(this) else LaunchOverrides() latencyLogger = LatencyLogger(this) val resourceLogger = ResourceLogger(this) val chatRepository = ChatRepository(this) @@ -110,7 +113,7 @@ class MainActivity : ComponentActivity() { MaterialTheme( colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme() ) { - ChatScreen(viewModel, latencyLogger) + ChatScreen(viewModel, latencyLogger, launchOverrides) } } } @@ -122,12 +125,27 @@ class MainActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3Api::class) @Composable -fun ChatScreen(viewModel: ChatViewModel, latencyLogger: LatencyLogger) { +internal fun ChatScreen( + viewModel: ChatViewModel, + latencyLogger: LatencyLogger, + launchOverrides: LaunchOverrides, +) { val messages by viewModel.uiState.collectAsStateWithLifecycle() var inputText by rememberSaveable { mutableStateOf("") } - var selectedAgentType by rememberSaveable { mutableStateOf(AgentType.TEMPLATE) } - var bypassCanned by rememberSaveable { mutableStateOf(false) } - var useStreaming by rememberSaveable { mutableStateOf(ChatRepository.DEFAULT_USE_STREAMING) } + var selectedAgentType by rememberSaveable { + mutableStateOf(launchOverrides.agentType ?: AgentType.LITE) + } + // The 'Server' switch is ON when canned responses are bypassed. + var bypassCanned by rememberSaveable { + mutableStateOf(launchOverrides.useCannedResponses == false) + } + + // Overrides are only passed on the first launch, so a recreated activity does not resend. + LaunchedEffect(Unit) { + launchOverrides.autoSendPrompt?.let { prompt -> + viewModel.sendMessage(prompt, selectedAgentType, bypassCanned) + } + } Column(modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surface)) { MessageList( @@ -141,8 +159,6 @@ fun ChatScreen(viewModel: ChatViewModel, latencyLogger: LatencyLogger) { onPromptSelected = { inputText = it }, bypassCanned = bypassCanned, onBypassCannedChange = { bypassCanned = it }, - useStreaming = useStreaming, - onUseStreamingChange = { useStreaming = it }, ) AgentSelectionColumn( @@ -155,7 +171,7 @@ fun ChatScreen(viewModel: ChatViewModel, latencyLogger: LatencyLogger) { onTextChange = { inputText = it }, onSend = { if (inputText.isNotBlank()) { - viewModel.sendMessage(inputText, selectedAgentType, bypassCanned, useStreaming) + viewModel.sendMessage(inputText, selectedAgentType, bypassCanned) inputText = "" } }, @@ -169,8 +185,6 @@ fun ControlPanel( onPromptSelected: (String) -> Unit, bypassCanned: Boolean, onBypassCannedChange: (Boolean) -> Unit, - useStreaming: Boolean = ChatRepository.DEFAULT_USE_STREAMING, - onUseStreamingChange: (Boolean) -> Unit = {}, ) { var expanded by remember { mutableStateOf(false) } val defaultPrompt = stringResource(R.string.most_asked_questions) @@ -234,22 +248,6 @@ fun ControlPanel( modifier = Modifier.scale(0.8f).testTag("switchCannedServer"), ) } - - Spacer(modifier = Modifier.width(8.dp)) - - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - "Streaming", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - Spacer(modifier = Modifier.width(4.dp)) - Switch( - checked = useStreaming, - onCheckedChange = onUseStreamingChange, - modifier = Modifier.scale(0.8f).testTag("switchStreaming"), - ) - } } } @@ -293,23 +291,6 @@ fun AgentSelectionColumn(selectedAgentType: AgentType, onAgentTypeChange: (Agent color = MaterialTheme.colorScheme.onSurface, ) } - Row(verticalAlignment = Alignment.CenterVertically) { - RadioButton( - selected = selectedAgentType == AgentType.TEMPLATE, - onClick = { onAgentTypeChange(AgentType.TEMPLATE) }, - colors = - RadioButtonDefaults.colors( - selectedColor = MaterialTheme.colorScheme.primary, - unselectedColor = MaterialTheme.colorScheme.onSurfaceVariant, - ), - modifier = Modifier.scale(0.8f).testTag("radioAgentTemplate"), - ) - Text( - stringResource(R.string.agent_template), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - } } } diff --git a/client/android/app/src/main/java/com/example/maui/data/ChatRepository.kt b/client/android/app/src/main/java/com/example/maui/data/ChatRepository.kt index a404d26..ca75755 100644 --- a/client/android/app/src/main/java/com/example/maui/data/ChatRepository.kt +++ b/client/android/app/src/main/java/com/example/maui/data/ChatRepository.kt @@ -95,6 +95,19 @@ class ChatRepository(private val context: Context) { private val apiKey = BuildConfig.GATEWAY_API_KEY private val contextId = UUID.randomUUID().toString() + internal fun buildSessionRequest(): Request = + Request.Builder() + .url("$baseUrl/apps/$appName/users/user/sessions?key=$apiKey") + .post("{}".toRequestBody("application/json".toMediaType())) + .applyBearerToken() + .build() + + private fun Request.Builder.applyBearerToken(): Request.Builder = apply { + bearerTokenOverride + ?.takeIf { it.isNotEmpty() } + ?.let { addHeader("Authorization", "Bearer $it") } + } + suspend fun discoverProtocol(): Boolean = withContext(Dispatchers.IO) { discoveryMutex.withLock { @@ -103,11 +116,7 @@ class ChatRepository(private val context: Context) { } hasDiscoveredProtocol = true - val request = - Request.Builder() - .url("$baseUrl/apps/$appName/users/user/sessions?key=$apiKey") - .post("{}".toRequestBody("application/json".toMediaType())) - .build() + val request = buildSessionRequest() try { client.newCall(request).execute().use { response -> @@ -149,8 +158,8 @@ class ChatRepository(private val context: Context) { it.readText() } val mapObj = JSONObject(mappingJson) - val strippedText = - text.removePrefix("[GROUNDING] ").removePrefix("[TEMPLATE] ").removePrefix("[MCP] ") + val strippedText = text.removePrefix("[GROUNDING_TEMPLATE] ").removePrefix("[TEMPLATE] ") + if (mapObj.has(strippedText)) { val filename = mapObj.getString(strippedText) return applicationContext.assets.open("canned_responses/$filename").bufferedReader().use { @@ -163,7 +172,7 @@ class ChatRepository(private val context: Context) { return null } - private fun buildRequest( + internal fun buildRequest( partsArray: JSONArray, useStreaming: Boolean = DEFAULT_USE_STREAMING, ): Request { @@ -204,6 +213,7 @@ class ChatRepository(private val context: Context) { if (activeServer == ServerType.VANILLA) { requestBuilder.addHeader("x-api-key", apiKey) } + requestBuilder.applyBearerToken() return requestBuilder.build() } @@ -320,7 +330,7 @@ class ChatRepository(private val context: Context) { .flowOn(Dispatchers.IO) companion object { - const val DEFAULT_USE_STREAMING = true + const val DEFAULT_USE_STREAMING = false fun rpcMethod(useStreaming: Boolean): String = if (useStreaming) "message/stream" else "message/send" @@ -337,5 +347,12 @@ class ChatRepository(private val context: Context) { * build time. `null`, the default, keeps [BuildConfig.GATEWAY_URL]. */ @Volatile @JvmStatic var baseUrlOverride: String? = null + + /** + * Overrides the Authorization Bearer token attached to backend requests. + * + * Set by integration tests that drive the app against an IAM-protected Cloud Run instance. + */ + @Volatile @JvmStatic var bearerTokenOverride: String? = null } } diff --git a/client/android/app/src/main/java/com/example/maui/ui/ChatViewModel.kt b/client/android/app/src/main/java/com/example/maui/ui/ChatViewModel.kt index 43716bc..cf42b7b 100644 --- a/client/android/app/src/main/java/com/example/maui/ui/ChatViewModel.kt +++ b/client/android/app/src/main/java/com/example/maui/ui/ChatViewModel.kt @@ -65,18 +65,13 @@ class ChatViewModel( fun sendMessage( text: String, - agentType: AgentType = AgentType.TEMPLATE, + agentType: AgentType = AgentType.LITE, bypassCanned: Boolean = false, useStreaming: Boolean = ChatRepository.DEFAULT_USE_STREAMING, ) { resetStreamingStateAndCancelJob() lastUseStreaming = useStreaming - val serverMessageText = - when (agentType) { - AgentType.VERTEX -> "[GROUNDING] $text" - AgentType.TEMPLATE -> "[TEMPLATE] $text" - AgentType.LITE -> "[MCP] $text" - } + val serverMessageText = "${agentType.serverPrefix}$text" addMessage(ChatMessage.Text(text = text, isUser = true)) val jsonObject = diff --git a/client/android/app/src/main/res/values/strings.xml b/client/android/app/src/main/res/values/strings.xml index 9350835..d06ef35 100644 --- a/client/android/app/src/main/res/values/strings.xml +++ b/client/android/app/src/main/res/values/strings.xml @@ -20,7 +20,6 @@ Server Grounding Lite (MCP) Grounding with Google Maps (Vertex) - Template Agent Type a message... Send diff --git a/client/ios/A2UI-Example.xcodeproj/project.pbxproj b/client/ios/A2UI-Example.xcodeproj/project.pbxproj index da1d774..cba6325 100644 --- a/client/ios/A2UI-Example.xcodeproj/project.pbxproj +++ b/client/ios/A2UI-Example.xcodeproj/project.pbxproj @@ -394,7 +394,7 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 26.0; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = "com.google.A2UI-ExampleTests"; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -414,7 +414,7 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 26.0; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = "com.google.A2UI-ExampleTests"; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -515,7 +515,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 26.0; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; @@ -572,7 +572,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 26.0; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; diff --git a/client/ios/ChatService.swift b/client/ios/ChatService.swift index da16249..8fb885f 100644 --- a/client/ios/ChatService.swift +++ b/client/ios/ChatService.swift @@ -50,7 +50,7 @@ actor ChatService: ChatServiceProtocol { } // --- CONFIGURATION --- - nonisolated static let defaultUseStreaming: Bool = true + nonisolated static let defaultUseStreaming: Bool = false private let remoteEndpoint = "REQUIRED_REMOTE_ENDPOINT" private let apiKey = "REQUIRED_REMOTE_API_KEY" // --------------------- @@ -62,8 +62,13 @@ actor ChatService: ChatServiceProtocol { /// UI test hooks in this file, so release builds always talk to `defaultServer`. nonisolated static let backendURLOverrideKey = "A2UI_BACKEND_URL_OVERRIDE" + /// Launch environment key that attaches an `Authorization: Bearer ` header to backend + /// requests in DEBUG builds (used when testing against IAM-protected Cloud Run instances). + nonisolated static let backendBearerTokenKey = "A2UI_BACKEND_BEARER_TOKEN" + let activeServer: ServerType let baseUrl: String + let bearerToken: String? init( defaultServer: ServerType = .remote, @@ -71,9 +76,13 @@ actor ChatService: ChatServiceProtocol { ) { #if DEBUG let overrideURL = environment[Self.backendURLOverrideKey].flatMap { $0.isEmpty ? nil : $0 } + let overrideToken = + environment[Self.backendBearerTokenKey].flatMap { $0.isEmpty ? nil : $0 } #else let overrideURL: String? = nil + let overrideToken: String? = nil #endif + self.bearerToken = overrideToken if let overrideURL { self.activeServer = .demo self.baseUrl = overrideURL @@ -104,15 +113,7 @@ actor ChatService: ChatServiceProtocol { ParsedA2AEvent, Swift.Error > { - var serverText = text - switch agentType { - case .vertex: - serverText = "[GROUNDING] \(text)" - case .template: - serverText = "[TEMPLATE] \(text)" - case .lite: - serverText = "[MCP] \(text)" - } + let serverText = "\(agentType.serverPrefix)\(text)" let payload: [String: Any] = ["text": serverText] return try await callPythonServer(userMessage: payload, useStreaming: useStreaming) } @@ -138,6 +139,15 @@ actor ChatService: ChatServiceProtocol { return try await callPythonServer(userMessage: payload, useStreaming: useStreaming) } + func applyAuthHeaders(to request: inout URLRequest) { + if activeServer == .remote { + request.setValue(apiKey, forHTTPHeaderField: "x-api-key") + } + if let bearerToken { + request.setValue("Bearer \(bearerToken)", forHTTPHeaderField: "Authorization") + } + } + private func initializeSession() async throws { #if DEBUG if ProcessInfo.processInfo.environment["UI_TEST_MOCK_SCENARIO"] != nil { return } @@ -159,9 +169,7 @@ actor ChatService: ChatServiceProtocol { var request = URLRequest(url: url) request.timeoutInterval = 120 request.httpMethod = "POST" - if activeServer == .remote { - request.setValue(apiKey, forHTTPHeaderField: "x-api-key") - } + applyAuthHeaders(to: &request) // Attempt handshake let (data, response) = try await URLSession.shared.data(for: request) @@ -217,14 +225,11 @@ actor ChatService: ChatServiceProtocol { request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") - if self.activeServer == .remote { - request.setValue(self.apiKey, forHTTPHeaderField: "x-api-key") - } - if self.activeServer == .demo { request.setValue( "https://a2ui.org/a2a-extension/a2ui/v0.9", forHTTPHeaderField: "X-A2A-Extensions") } + applyAuthHeaders(to: &request) return AsyncThrowingStream { continuation in #if DEBUG @@ -389,9 +394,8 @@ actor ChatService: ChatServiceProtocol { } let strippedText = text - .replacingOccurrences(of: "[GROUNDING] ", with: "") + .replacingOccurrences(of: "[GROUNDING_TEMPLATE] ", with: "") .replacingOccurrences(of: "[TEMPLATE] ", with: "") - .replacingOccurrences(of: "[MCP] ", with: "") return MockScenarioRegistry.scenarios.first(where: { $0.query == strippedText })?.fileName } } diff --git a/client/ios/ChatServiceTests.swift b/client/ios/ChatServiceTests.swift index 7e4f85b..7249966 100644 --- a/client/ios/ChatServiceTests.swift +++ b/client/ios/ChatServiceTests.swift @@ -76,8 +76,8 @@ final class ChatServiceTests: XCTestCase { XCTAssertNil(try ChatService.parseSSELine("event: message")) } - func testDefaultUseStreamingIsTrue() { - XCTAssertTrue(ChatService.defaultUseStreaming) + func testDefaultUseStreamingIsFalse() { + XCTAssertFalse(ChatService.defaultUseStreaming) } func testRpcMethod_switchesBetweenStreamAndSend() { @@ -123,6 +123,33 @@ final class ChatServiceTests: XCTestCase { XCTAssertEqual(baseUrl, "REQUIRED_REMOTE_ENDPOINT") } + func testInit_setsBearerTokenFromEnvironmentAndAppliesAuthorizationHeader() async throws { + let service = ChatService( + defaultServer: .demo, + environment: [ChatService.backendBearerTokenKey: "test-identity-token"] + ) + let bearerToken = await service.bearerToken + XCTAssertEqual(bearerToken, "test-identity-token") + + var request = URLRequest(url: try XCTUnwrap(URL(string: "https://maui-backend.google.com"))) + await service.applyAuthHeaders(to: &request) + XCTAssertEqual( + request.value(forHTTPHeaderField: "Authorization"), "Bearer test-identity-token") + } + + func testInit_ignoresEmptyBearerTokenInEnvironmentAndOmitsAuthorizationHeader() async throws { + let service = ChatService( + defaultServer: .demo, + environment: [ChatService.backendBearerTokenKey: ""] + ) + let bearerToken = await service.bearerToken + XCTAssertNil(bearerToken) + + var request = URLRequest(url: try XCTUnwrap(URL(string: "https://maui-backend.google.com"))) + await service.applyAuthHeaders(to: &request) + XCTAssertNil(request.value(forHTTPHeaderField: "Authorization")) + } + @MainActor func testChatViewModel_streamingChunks_stripsCreateSurfaceAndUpdatesSingleCardInPlace() async { let viewModel = ChatViewModel() @@ -180,4 +207,41 @@ final class ChatServiceTests: XCTestCase { XCTAssertNil(viewModel.currentUpdateComponentsMsg?["createSurface"]) XCTAssertEqual(viewModel.currentUpdateDataModelMsgs.count, 2) } + + func testAgentType_serverPrefix_returnsExpectedRoutingTag() { + XCTAssertEqual(AgentType.lite.serverPrefix, "[TEMPLATE] ") + XCTAssertEqual(AgentType.vertex.serverPrefix, "[GROUNDING_TEMPLATE] ") + } + + #if DEBUG + func testLaunchOverrides_parsesSettingsAndPrompt() { + let overrides = LaunchOverrides(environment: [ + LaunchOverrides.useCannedResponsesKey: "True", + LaunchOverrides.agentTypeKey: "vertex", + LaunchOverrides.autoSendPromptKey: "Show 3 Indian Restaurants in Seattle", + ]) + + XCTAssertEqual( + overrides, + LaunchOverrides( + useCannedResponses: true, agentType: .vertex, + autoSendPrompt: "Show 3 Indian Restaurants in Seattle")) + } + + func testLaunchOverrides_parsesLiteAgentCaseInsensitively() { + let overrides = LaunchOverrides(environment: [LaunchOverrides.agentTypeKey: "LITE"]) + + XCTAssertEqual(overrides.agentType, .lite) + } + + func testLaunchOverrides_ignoresMissingAndInvalidValues() { + let overrides = LaunchOverrides(environment: [ + LaunchOverrides.useCannedResponsesKey: "maybe", + LaunchOverrides.agentTypeKey: "unknown", + LaunchOverrides.autoSendPromptKey: " \n ", + ]) + + XCTAssertEqual(overrides, LaunchOverrides()) + } + #endif } diff --git a/client/ios/ChatView.swift b/client/ios/ChatView.swift index 530428f..f5ca73b 100644 --- a/client/ios/ChatView.swift +++ b/client/ios/ChatView.swift @@ -17,6 +17,52 @@ import GoogleMapsA2UI import SwiftUI +#if DEBUG + /// Debug-only launch settings that let UI tests open the app in a given mode and send a prompt + /// without tapping the controls. A nil field keeps the app's normal default. + struct LaunchOverrides: Equatable { + static let useCannedResponsesKey = "A2UI_USE_CANNED_RESPONSES" + static let agentTypeKey = "A2UI_AGENT_TYPE" + static let autoSendPromptKey = "A2UI_AUTO_SEND_PROMPT" + + var useCannedResponses: Bool? + var agentType: AgentType? + var autoSendPrompt: String? + + init( + useCannedResponses: Bool? = nil, + agentType: AgentType? = nil, + autoSendPrompt: String? = nil + ) { + self.useCannedResponses = useCannedResponses + self.agentType = agentType + self.autoSendPrompt = autoSendPrompt + } + + init(environment: [String: String]) { + switch environment[Self.useCannedResponsesKey]?.lowercased() { + case "true": + useCannedResponses = true + case "false": + useCannedResponses = false + default: + useCannedResponses = nil + } + switch environment[Self.agentTypeKey]?.lowercased() { + case "lite": + agentType = .lite + case "vertex": + agentType = .vertex + default: + agentType = nil + } + let prompt = environment[Self.autoSendPromptKey]?.trimmingCharacters( + in: .whitespacesAndNewlines) + autoSendPrompt = (prompt?.isEmpty ?? true) ? nil : prompt + } + } +#endif + struct ChatView: View { private enum Constants { static let scrollDelay: TimeInterval = 0.1 @@ -85,10 +131,6 @@ struct ChatView: View { } } - Toggle("Streaming", isOn: $viewModel.useStreaming) - .padding(.horizontal, 16) - .padding(.vertical, 4) - AgentSelector(selection: $viewModel.selectedAgentType) Divider() @@ -129,8 +171,33 @@ struct ChatView: View { .padding(.horizontal) .padding(.bottom, 8) } + #if DEBUG + .onAppear(perform: applyLaunchOverridesOnce) + #endif } + #if DEBUG + // Applies launch settings once, so returning to this view does not resend the prompt. + @State private var didApplyLaunchOverrides = false + + private func applyLaunchOverridesOnce() { + guard !didApplyLaunchOverrides else { return } + didApplyLaunchOverrides = true + let overrides = LaunchOverrides(environment: ProcessInfo.processInfo.environment) + if let useCannedResponses = overrides.useCannedResponses { + UserDefaults.standard.set( + useCannedResponses, forKey: MockScenarioRegistry.useCannedResponsesKey) + } + if let agentType = overrides.agentType { + viewModel.selectedAgentType = agentType + } + if let prompt = overrides.autoSendPrompt { + viewModel.sendMessage(text: prompt) + lastQuery = prompt + } + } + #endif + /// Submits the current input text to the view model. private func submitMessage() { let text = inputText.trimmingCharacters(in: .whitespaces) diff --git a/client/ios/ChatViewModel.swift b/client/ios/ChatViewModel.swift index d672494..f9767e2 100644 --- a/client/ios/ChatViewModel.swift +++ b/client/ios/ChatViewModel.swift @@ -24,7 +24,7 @@ class ChatViewModel: ObservableObject { @Published private(set) var messages: [ChatMessage] = [] @Published private(set) var isLoading: Bool = false @Published var webViewToScrollID: UUID? - @Published var selectedAgentType: AgentType = .template + @Published var selectedAgentType: AgentType = .lite @Published var useStreaming: Bool = ChatService.defaultUseStreaming private let chatService: ChatServiceProtocol diff --git a/client/ios/Models.swift b/client/ios/Models.swift index 41ca1a7..4345309 100644 --- a/client/ios/Models.swift +++ b/client/ios/Models.swift @@ -20,9 +20,17 @@ import SwiftUI enum AgentType: String, CaseIterable, Identifiable { case lite = "Grounding Lite (MCP)" case vertex = "Grounding with Google Maps (Vertex)" - case template = "Template Agent" var id: Self { self } + + var serverPrefix: String { + switch self { + case .lite: + return "[TEMPLATE] " + case .vertex: + return "[GROUNDING_TEMPLATE] " + } + } } struct ChatMessage: Identifiable { diff --git a/client/ios/README.md b/client/ios/README.md index c207250..472304c 100644 --- a/client/ios/README.md +++ b/client/ios/README.md @@ -13,7 +13,7 @@ This application relies on the core `GoogleMapsA2UI` module. To set up this depe ## Project Structure * `ChatApp.swift`: The main application entry point. -* `ChatView.swift`: The main chat UI, displaying message history, the input bar, and toggles to switch between different agent modes (e.g., Vertex AI Maps Grounding vs. MCP Lite vs. Template). +* `ChatView.swift`: The main chat UI, displaying message history, the input bar, and radio buttons to switch between Grounding Lite (MCP) and Grounding with Google Maps (Vertex). * `ChatViewModel.swift`: Handles all networking with the backend protocols, maintains state, and routes A2A responses to the `GoogleMapsA2UI` library parser. * `Models.swift`: Basic data structures for chat messages and agent mode configurations. * `GoogleMapsA2UI`: A Swift package dependency pulled in from the `a2ui` module. It provides the `A2UIView` SwiftUI component to render the dynamic maps components and parses the A2A payload into a list of `ParsedA2AEvent` objects. *(See the [Library Dependency](#library-dependency) section above for integration details).* @@ -60,8 +60,7 @@ If your `activeServer` is set to `.demo` (This means the server is running on yo Once the app is running: -* **Toggle Streaming vs. Non-Streaming (`useStreaming`):** Streaming (`message/stream`) is enabled by default (`ChatService.defaultUseStreaming = true` in `ChatService.swift`). You can switch between incremental SSE streaming (`message/stream`) and single-response non-streaming (`message/send`) at runtime using the **Streaming** toggle above the agent selector in `ChatView.swift`, or change the default `defaultUseStreaming` boolean in `ChatService.swift`. -* **Select agent Mode:** Use the radio buttons above the chat bar to toggle between **Grounding Lite (MCP)**, **Grounding with Google Maps (Vertex)** and **Template**. +* **Select Grounding Method:** Use the radio buttons above the chat bar to switch between **Grounding Lite (MCP)** and **Grounding with Google Maps (Vertex)**. * **Use Canned Prompts:** Tap the **Flask** or **List** icons next to the text input for a menu of pre-written test scenarios. * **Send Custom Prompts:** Type a query into the text box (e.g., *"Show me 3 Chinese restaurants in Seattle"*) and hit send. * **Interact with Maps:** Wait for the A2UI components to load. You can interact with the rendered maps and place cards (like tapping `Get Directions`) to trigger native Swift callbacks. diff --git a/client/ios/TestCasesMenuView.swift b/client/ios/TestCasesMenuView.swift index dd5acc7..f4d4547 100644 --- a/client/ios/TestCasesMenuView.swift +++ b/client/ios/TestCasesMenuView.swift @@ -40,6 +40,7 @@ struct TestCasesMenuView: View { .font(.title2) .foregroundColor(.orange) } + .accessibilityIdentifier("flask.fill") Menu { Section("Restaurant Finder") { diff --git a/client/web/react/README.md b/client/web/react/README.md index f9b3783..1768d11 100644 --- a/client/web/react/README.md +++ b/client/web/react/README.md @@ -13,8 +13,8 @@ npm run dev 2. Open [http://localhost:5173](http://localhost:5173) in your browser. You should see a chat interface. -## Streaming vs. Non-Streaming (`useStreaming`) +## Grounding Method Selection -By default, the React sample streams incremental text and A2UI component updates via `client.sendStream()` (`DEFAULT_USE_STREAMING = true` in `src/App.tsx`). You can switch between streaming (`client.sendStream()`) and non-streaming (`client.send()`) at any time using the **Streaming** checkbox in the chat header or by modifying `DEFAULT_USE_STREAMING` in `src/App.tsx`. +Use the **Grounding Method** radio buttons in the chat header to switch between **Grounding Lite (MCP)** and **Grounding with Google Maps (Vertex)**. To run the backend, follow the instructions in [../../../agent/python/README.md](../../../agent/python/README.md) diff --git a/client/web/react/src/App.css b/client/web/react/src/App.css index cc165d8..18ad2bb 100644 --- a/client/web/react/src/App.css +++ b/client/web/react/src/App.css @@ -67,15 +67,6 @@ color: var(--text-h); } -.streaming-toggle { - display: flex; - align-items: center; - gap: 6px; - font-size: 14px; - cursor: pointer; - margin-left: auto; - margin-right: 12px; -} .chat-messages { flex: 1; diff --git a/client/web/react/src/App.tsx b/client/web/react/src/App.tsx index 22c58c7..73b257f 100644 --- a/client/web/react/src/App.tsx +++ b/client/web/react/src/App.tsx @@ -22,7 +22,7 @@ import {useEffect, useRef, useState} from 'react'; import './App.css'; // --- Configuration --- -const DEFAULT_USE_STREAMING = true; +const DEFAULT_USE_STREAMING = false; type GroundingType = 'mcp' | 'vertex'; @@ -36,14 +36,8 @@ const GROUNDING_OPTIONS: readonly GroundingOption[] = [ {id: 'vertex', label: 'Grounding with Google Maps (Vertex)'}, ]; -function getAgentPrefix( - grounding: GroundingType, - useTemplates: boolean, -): string { - if (grounding === 'vertex') { - return useTemplates ? '[GROUNDING_TEMPLATE] ' : '[GROUNDING] '; - } - return useTemplates ? '[TEMPLATE] ' : '[MCP] '; +function getAgentPrefix(grounding: GroundingType): string { + return grounding === 'vertex' ? '[GROUNDING_TEMPLATE] ' : '[TEMPLATE] '; } /** @@ -53,10 +47,8 @@ function getAgentPrefix( function App() { // --- UI State --- const [isChatOpen, setIsChatOpen] = useState(true); - const [useStreaming, setUseStreaming] = useState(DEFAULT_USE_STREAMING); const [selectedGrounding, setSelectedGrounding] = useState('mcp'); - const [useTemplates, setUseTemplates] = useState(true); const [timeline, setTimeline] = useState([]); const [input, setInput] = useState(''); @@ -112,7 +104,7 @@ function App() { if (!input.trim() || isRequesting) return; const messageText = input.trim(); - const prefix = getAgentPrefix(selectedGrounding, useTemplates); + const prefix = getAgentPrefix(selectedGrounding); const serverText = `${prefix}${messageText}`; setInput(''); @@ -123,7 +115,7 @@ function App() { setTimeline([...rendererRef.current.timeline]); try { - if (useStreaming) { + if (DEFAULT_USE_STREAMING) { const streamedMessages: any[] = []; for await (const chunk of clientRef.current.sendStream(serverText)) { rendererRef.current.processResponse([chunk as any]); @@ -134,22 +126,22 @@ function App() { setTimeline([...rendererRef.current.timeline]); } } else { - // 2. Send the message to the A2A agent via A2UIClient - const response = await clientRef.current.send(serverText); - - // 3. Process the response (which may contain text and/or A2UI data) - rendererRef.current.processResponse(response); - - // Update last response JSON - const uiMessages = response - .filter((p: any) => p.type === 'a2ui') - .map((p: any) => p.message); - if (uiMessages.length > 0) { - setLastResponseJson(JSON.stringify(uiMessages, null, 2)); - } + // 2. Send the message to the A2A agent via A2UIClient + const response = await clientRef.current.send(serverText); + + // 3. Process the response (which may contain text and/or A2UI data) + rendererRef.current.processResponse(response); + + // Update last response JSON + const uiMessages = response + .filter((p: any) => p.type === 'a2ui') + .map((p: any) => p.message); + if (uiMessages.length > 0) { + setLastResponseJson(JSON.stringify(uiMessages, null, 2)); + } - // 4. Synchronize the React state with the renderer's updated timeline - setTimeline([...rendererRef.current.timeline]); + // 4. Synchronize the React state with the renderer's updated timeline + setTimeline([...rendererRef.current.timeline]); } } catch (error) { console.error('Failed to send message:', error); @@ -186,15 +178,6 @@ function App() {

Chat

- -
-