)` | Add plugins to the runner. |
+| `.instantSource(InstantSource)` | Custom timestamp source (useful for testing). |
+| `.uuidProvider(UuidProvider)` | Custom ID generator (useful for testing). |
+| `.scheduler(Scheduler)` | RxJava scheduler for async hand-offs. |
+| `.toRunnerBuilder()` | Returns a `Runner.Builder` for further customization before building. |
+| `.build()` | Builds and returns the configured `Runner`. |
+
+> **Note**: If neither `.withGcsArtifacts()` nor `.artifactService()` is set, and `gcs.adk.bucket.name` is not configured, `.build()` defaults to using `InMemoryArtifactService` for artifacts. This lets text-based agents run without any Google Cloud Storage setup, though any artifacts stored will be ephemeral and lost across restarts or distributed servers. For durable artifact persistence in production, configure `.withGcsArtifacts(...)` or `.artifactService(...)`.
+---
+
+## Legacy Constructor API (Deprecated)
+
+> **These constructors are deprecated.** Migrate to `FirestoreDatabaseRunner.newBuilder()`.
+
+The direct constructor style is retained for backward compatibility but has two important behavior differences from the old API:
+
+- **Previously**: startup threw `RuntimeException` when `gcs.adk.bucket.name` was not configured.
+- **Now**: falls back silently to `InMemoryArtifactService` and **logs a `WARN`** so operators are aware. Artifacts stored in-memory are ephemeral and will be lost on restart.
+
+```java
+// @Deprecated — migrate to newBuilder()
+FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(agent, firestore);
+FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(agent, appName, firestore);
+FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(agent, appName, plugins, firestore);
+```
+
+**Migration path** — replace any constructor call with the equivalent builder:
+
+```java
+// Before (deprecated)
+new FirestoreDatabaseRunner(agent, appName, firestore);
+
+// After (recommended)
+FirestoreDatabaseRunner.newBuilder()
+ .agent(agent)
+ .appName(appName)
+ .firestore(firestore)
+ .withGcsArtifacts("your-bucket-name") // explicit — no silent fallback
+ .build();
+```
diff --git a/contrib/firestore-session-service/src/main/java/com/google/adk/runner/FirestoreDatabaseRunner.java b/contrib/firestore-session-service/src/main/java/com/google/adk/runner/FirestoreDatabaseRunner.java
index 8e8255a808..64ba9e0f05 100644
--- a/contrib/firestore-session-service/src/main/java/com/google/adk/runner/FirestoreDatabaseRunner.java
+++ b/contrib/firestore-session-service/src/main/java/com/google/adk/runner/FirestoreDatabaseRunner.java
@@ -17,50 +17,354 @@
package com.google.adk.runner;
import com.google.adk.agents.BaseAgent;
+import com.google.adk.apps.App;
+import com.google.adk.artifacts.BaseArtifactService;
+import com.google.adk.artifacts.GcsArtifactService;
+import com.google.adk.artifacts.InMemoryArtifactService;
+import com.google.adk.memory.BaseMemoryService;
import com.google.adk.memory.FirestoreMemoryService;
+import com.google.adk.platform.UuidProvider;
import com.google.adk.plugins.BasePlugin;
+import com.google.adk.plugins.Plugin;
+import com.google.adk.sessions.BaseSessionService;
import com.google.adk.sessions.FirestoreSessionService;
import com.google.adk.utils.FirestoreProperties;
import com.google.cloud.firestore.Firestore;
+import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import io.reactivex.rxjava3.core.Scheduler;
+import java.time.InstantSource;
+import java.util.ArrayList;
+import java.util.List;
+import org.jspecify.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-/** FirestoreDatabaseRunner */
+/**
+ * Runner subclass pre-configured with Google Cloud Firestore for session and memory management.
+ *
+ * Supports two usage styles:
+ *
+ *
+ * - Constructor-based (legacy, deprecated): retained for backward compatibility.
+ * Logs a warning and falls back to {@link InMemoryArtifactService} when
+ * {@code gcs.adk.bucket.name} is not configured. Migrate to {@link #newBuilder()}.
+ *
- Builder-based (recommended): use {@link #newBuilder()} for explicit control over
+ * artifact storage, service injection, plugins, and runtime settings.
+ *
+ *
+ * When neither an explicit {@link BaseArtifactService} nor a GCS bucket (via {@link
+ * Builder#withGcsArtifacts(String)} or {@link Builder#withGcsArtifacts(String, Storage)}) is
+ * configured, the runner defaults to {@link InMemoryArtifactService}. Artifacts stored in-memory
+ * are ephemeral and will be lost on restart or across distributed servers.
+ */
public class FirestoreDatabaseRunner extends Runner {
- /** Constructor for FirestoreDatabaseRunner */
+ private static final Logger logger = LoggerFactory.getLogger(FirestoreDatabaseRunner.class);
+
+ // -------------------------------------------------------------------------
+ // Legacy constructor-based API (deprecated — use newBuilder())
+ // -------------------------------------------------------------------------
+
+ /**
+ * Creates a runner with Firestore services.
+ *
+ * @deprecated Use {@link #newBuilder()} for explicit artifact storage configuration.
+ */
+ @Deprecated
+ @SuppressWarnings("deprecation")
public FirestoreDatabaseRunner(BaseAgent baseAgent, Firestore firestore) {
- this(baseAgent, baseAgent.name(), new java.util.ArrayList<>(), firestore);
+ this(baseAgent, baseAgent.name(), new ArrayList<>(), firestore);
}
- /** Constructor for FirestoreDatabaseRunner with appName */
+ /**
+ * Creates a runner with Firestore services and a custom app name.
+ *
+ * @deprecated Use {@link #newBuilder()} for explicit artifact storage configuration.
+ */
+ @Deprecated
+ @SuppressWarnings("deprecation")
public FirestoreDatabaseRunner(BaseAgent baseAgent, String appName, Firestore firestore) {
- this(baseAgent, appName, new java.util.ArrayList<>(), firestore);
+ this(baseAgent, appName, new ArrayList<>(), firestore);
}
- /** Constructor for FirestoreDatabaseRunner with parent runners */
+ /**
+ * Creates a runner with Firestore services, a custom app name, and plugins.
+ *
+ * @deprecated Use {@link #newBuilder()} for explicit artifact storage configuration.
+ */
+ @Deprecated
+ @SuppressWarnings("deprecation") // calls deprecated Runner(BaseAgent, String, ..., List) super
public FirestoreDatabaseRunner(
BaseAgent baseAgent,
String appName,
- java.util.List plugins,
+ List plugins,
Firestore firestore) {
super(
baseAgent,
appName,
- new com.google.adk.artifacts.GcsArtifactService(
- getBucketNameFromEnv(), StorageOptions.getDefaultInstance().getService()),
+ resolveDefaultArtifactService(),
new FirestoreSessionService(firestore),
new FirestoreMemoryService(firestore),
plugins);
}
- /** Gets the GCS bucket name from the environment variable ADK_GCS_BUCKET_NAME. */
- private static String getBucketNameFromEnv() {
+ /**
+ * Resolves the artifact service for legacy constructors. Uses GCS if {@code gcs.adk.bucket.name}
+ * is set in properties; otherwise falls back to {@link InMemoryArtifactService} and logs a
+ * warning so operators are aware that artifacts will not be persisted.
+ */
+ private static BaseArtifactService resolveDefaultArtifactService() {
+ String bucketName = findBucketNameFromProperties();
+ if (bucketName != null && !bucketName.trim().isEmpty()) {
+ return new GcsArtifactService(
+ bucketName, StorageOptions.getDefaultInstance().getService());
+ }
+ logger.warn(
+ "No Google Cloud Storage (GCS) bucket configured for artifact storage; falling back to InMemoryArtifactService."
+ + " Artifacts will be ephemeral and lost on restart."
+ + " Set 'gcs.adk.bucket.name' in adk-firestore.properties or migrate to"
+ + " FirestoreDatabaseRunner.newBuilder().withGcsArtifacts(\"bucket-name\").");
+ return new InMemoryArtifactService();
+ }
+
+ /** Return the GCS bucket name from properties, or null if not set. */
+ private static @Nullable String findBucketNameFromProperties() {
String bucketName = FirestoreProperties.getInstance().getGcsAdkBucketName();
- if (bucketName == null || bucketName.trim().isEmpty()) {
- throw new RuntimeException(
- "Required property 'gcs.adk.bucket.name' is not set. This"
- + " is needed for the GcsArtifactService.");
+ return (bucketName == null || bucketName.trim().isEmpty()) ? null : bucketName.trim();
+ }
+
+ // -------------------------------------------------------------------------
+ // Builder-based API
+ // -------------------------------------------------------------------------
+
+ /** Returns a new {@link Builder} to configure and build a {@link Runner}. */
+ public static Builder newBuilder() {
+ return new Builder();
+ }
+
+ /**
+ * Convenience factory: creates a {@link Runner} for the given agent and Firestore instance. Uses
+ * GCS artifacts if {@code gcs.adk.bucket.name} is set in properties; otherwise defaults to
+ * {@link InMemoryArtifactService}.
+ */
+ public static Runner create(BaseAgent agent, Firestore firestore) {
+ return newBuilder().agent(agent).firestore(firestore).build();
+ }
+
+ /**
+ * Convenience factory: creates a {@link Runner} for the given agent, app name, and Firestore
+ * instance.
+ */
+ public static Runner create(BaseAgent agent, String appName, Firestore firestore) {
+ return newBuilder().agent(agent).appName(appName).firestore(firestore).build();
+ }
+
+ /** Builder for configuring and creating a {@link Runner} backed by Firestore. */
+ public static class Builder {
+ private @Nullable BaseAgent agent;
+ private @Nullable App app;
+ private @Nullable String appName;
+ private final List plugins = new ArrayList<>();
+
+ private @Nullable Firestore firestore;
+ private @Nullable BaseSessionService sessionService;
+ private @Nullable BaseMemoryService memoryService;
+ private @Nullable BaseArtifactService artifactService;
+
+ private @Nullable String gcsBucketName;
+ private @Nullable Storage storage;
+
+ private InstantSource instantSource = InstantSource.system();
+ private UuidProvider uuidProvider = UuidProvider.SYSTEM;
+ private @Nullable Scheduler scheduler;
+
+ private Builder() {}
+
+ /** Sets the agent to run. Mutually exclusive with {@link #app(App)}. */
+ @CanIgnoreReturnValue
+ public Builder agent(BaseAgent agent) {
+ Preconditions.checkState(this.app == null, "Cannot set agent when app is already set.");
+ this.agent = agent;
+ return this;
+ }
+
+ /** Sets the app to run. Mutually exclusive with {@link #agent(BaseAgent)}. */
+ @CanIgnoreReturnValue
+ public Builder app(App app) {
+ Preconditions.checkState(this.agent == null, "Cannot set app when agent is already set.");
+ this.app = app;
+ return this;
+ }
+
+ /** Sets the application name. Defaults to agent or app name if not provided. */
+ @CanIgnoreReturnValue
+ public Builder appName(String appName) {
+ this.appName = appName;
+ return this;
+ }
+
+ /** Sets the Firestore client instance used for session and memory services. */
+ @CanIgnoreReturnValue
+ public Builder firestore(Firestore firestore) {
+ this.firestore = firestore;
+ return this;
+ }
+
+ /** Explicitly provides a custom {@link BaseSessionService}. */
+ @CanIgnoreReturnValue
+ public Builder sessionService(BaseSessionService sessionService) {
+ this.sessionService = sessionService;
+ return this;
+ }
+
+ /** Explicitly provides a custom {@link BaseMemoryService}. */
+ @CanIgnoreReturnValue
+ public Builder memoryService(BaseMemoryService memoryService) {
+ this.memoryService = memoryService;
+ return this;
+ }
+
+ /** Explicitly provides an artifact service implementation. */
+ @CanIgnoreReturnValue
+ public Builder artifactService(BaseArtifactService artifactService) {
+ this.artifactService = artifactService;
+ return this;
+ }
+
+ /** Configures GCS artifact storage with a bucket name and default storage options. */
+ @CanIgnoreReturnValue
+ public Builder withGcsArtifacts(String bucketName) {
+ return withGcsArtifacts(bucketName, null);
+ }
+
+ /** Configures GCS artifact storage with a bucket name and explicit {@link Storage} client. */
+ @CanIgnoreReturnValue
+ public Builder withGcsArtifacts(String bucketName, @Nullable Storage storage) {
+ this.gcsBucketName = bucketName;
+ this.storage = storage;
+ return this;
+ }
+
+ /** Adds plugins to the runner. */
+ @CanIgnoreReturnValue
+ public Builder plugins(List extends Plugin> plugins) {
+ this.plugins.addAll(plugins);
+ return this;
+ }
+
+ /** Adds plugins to the runner. */
+ @CanIgnoreReturnValue
+ public Builder plugins(Plugin... plugins) {
+ this.plugins.addAll(ImmutableList.copyOf(plugins));
+ return this;
+ }
+
+ /** Sets the {@link InstantSource} for timestamp generation. */
+ @CanIgnoreReturnValue
+ public Builder instantSource(InstantSource instantSource) {
+ this.instantSource = Preconditions.checkNotNull(instantSource);
+ return this;
+ }
+
+ /** Sets the {@link UuidProvider} for ID generation. */
+ @CanIgnoreReturnValue
+ public Builder uuidProvider(UuidProvider uuidProvider) {
+ this.uuidProvider = Preconditions.checkNotNull(uuidProvider);
+ return this;
+ }
+
+ /** Sets the {@link Scheduler} for hand-offs to worker threads. */
+ @CanIgnoreReturnValue
+ public Builder scheduler(@Nullable Scheduler scheduler) {
+ this.scheduler = scheduler;
+ return this;
+ }
+
+ /**
+ * Converts this builder into a standard {@link Runner.Builder}, pre-configured with Firestore
+ * services and artifact service. Callers can use this to apply any additional runner settings.
+ */
+ public Runner.Builder toRunnerBuilder() {
+ if (this.app == null && this.agent == null) {
+ throw new IllegalStateException("Either agent or app must be set.");
+ }
+
+ String resolvedAppName = this.appName;
+ if (resolvedAppName == null) {
+ resolvedAppName = (this.app != null) ? this.app.name() : this.agent.name();
+ }
+
+ BaseSessionService resolvedSessionService = this.sessionService;
+ BaseMemoryService resolvedMemoryService = this.memoryService;
+
+ if (resolvedSessionService == null || resolvedMemoryService == null) {
+ if (this.firestore == null) {
+ throw new IllegalStateException(
+ "Firestore client must be provided when session or memory service is not explicitly"
+ + " configured.");
+ }
+ if (resolvedSessionService == null) {
+ resolvedSessionService =
+ new FirestoreSessionService(this.firestore, this.instantSource, this.uuidProvider);
+ }
+ if (resolvedMemoryService == null) {
+ resolvedMemoryService = new FirestoreMemoryService(this.firestore);
+ }
+ }
+
+ BaseArtifactService resolvedArtifactService = this.artifactService;
+ if (resolvedArtifactService == null) {
+ String bucket = this.gcsBucketName;
+ if (bucket == null || bucket.trim().isEmpty()) {
+ bucket = FirestoreProperties.getInstance().getGcsAdkBucketName();
+ }
+
+ if (bucket != null && !bucket.trim().isEmpty()) {
+ Storage storageClient =
+ this.storage != null ? this.storage : StorageOptions.getDefaultInstance().getService();
+ resolvedArtifactService = new GcsArtifactService(bucket.trim(), storageClient);
+ } else {
+ resolvedArtifactService = new InMemoryArtifactService();
+ }
+ }
+
+ Runner.Builder runnerBuilder = Runner.builder();
+ if (this.app != null) {
+ // Runner.Builder.appName() requires app to be unset, so set it before app().
+ // Runner.Builder.build() honours appName even when app is set (line: appName == null ?
+ // app.name() : appName), so an explicit override is correctly propagated.
+ if (this.appName != null) {
+ runnerBuilder.appName(this.appName);
+ }
+ runnerBuilder.app(this.app);
+ } else {
+ runnerBuilder.agent(this.agent).appName(resolvedAppName);
+ }
+
+ runnerBuilder
+ .sessionService(resolvedSessionService)
+ .memoryService(resolvedMemoryService)
+ .artifactService(resolvedArtifactService)
+ .instantSource(this.instantSource)
+ .uuidProvider(this.uuidProvider);
+
+ if (!this.plugins.isEmpty()) {
+ runnerBuilder.plugins(this.plugins);
+ }
+ if (this.scheduler != null) {
+ runnerBuilder.scheduler(this.scheduler);
+ }
+
+ return runnerBuilder;
+ }
+
+ /** Builds the configured {@link Runner}. */
+ public Runner build() {
+ return toRunnerBuilder().build();
}
- return bucketName;
}
}
diff --git a/contrib/firestore-session-service/src/main/java/com/google/adk/utils/Constants.java b/contrib/firestore-session-service/src/main/java/com/google/adk/utils/Constants.java
index 0cfd6f133c..175f1a0402 100644
--- a/contrib/firestore-session-service/src/main/java/com/google/adk/utils/Constants.java
+++ b/contrib/firestore-session-service/src/main/java/com/google/adk/utils/Constants.java
@@ -69,7 +69,7 @@ public class Constants {
/** root collection name fof firestore */
public static final String ROOT_COLLECTION_NAME =
- FirestoreProperties.getInstance().getFirebaseRootCollectionName();
+ FirestoreProperties.getInstance().getFirestoreRootCollectionName();
/** private constrctor */
private Constants() {
diff --git a/contrib/firestore-session-service/src/main/java/com/google/adk/utils/FirestoreProperties.java b/contrib/firestore-session-service/src/main/java/com/google/adk/utils/FirestoreProperties.java
index 7a798a7aca..ebb1c02cb3 100644
--- a/contrib/firestore-session-service/src/main/java/com/google/adk/utils/FirestoreProperties.java
+++ b/contrib/firestore-session-service/src/main/java/com/google/adk/utils/FirestoreProperties.java
@@ -43,8 +43,9 @@ public class FirestoreProperties {
private final Properties properties;
- private final String firebaseRootCollectionNameKey = "firebase.root.collection.name";
- private final String firebaseRootCollectionDefaultValue = "adk-session";
+ private final String firestoreRootCollectionNameKey = "firestore.root.collection.name";
+ private final String legacyFirebaseRootCollectionNameKey = "firebase.root.collection.name";
+ private final String firestoreRootCollectionDefaultValue = "adk-session";
private final String gcsAdkBucketNameKey = "gcs.adk.bucket.name";
@@ -120,13 +121,28 @@ public String getProperty(String key) {
/**
* Get the root collection name from the properties file, or return the default value if not
- * found.
+ * found. Checks 'firestore.root.collection.name' first, falling back to legacy
+ * 'firebase.root.collection.name'.
*
* @return the root collection name
*/
+ public String getFirestoreRootCollectionName() {
+ String name = this.properties.getProperty(firestoreRootCollectionNameKey);
+ if (name != null && !name.trim().isEmpty()) {
+ return name;
+ }
+ String legacyName = this.properties.getProperty(legacyFirebaseRootCollectionNameKey);
+ return (legacyName != null && !legacyName.trim().isEmpty()) ? legacyName.trim() : firestoreRootCollectionDefaultValue;
+ }
+
+ /**
+ * Legacy method for getting the root collection name.
+ *
+ * @deprecated Use {@link #getFirestoreRootCollectionName()} instead.
+ */
+ @Deprecated
public String getFirebaseRootCollectionName() {
- return this.properties.getProperty(
- firebaseRootCollectionNameKey, firebaseRootCollectionDefaultValue);
+ return getFirestoreRootCollectionName();
}
/**
diff --git a/contrib/firestore-session-service/src/test/java/com/google/adk/memory/FirestoreMemoryServiceTest.java b/contrib/firestore-session-service/src/test/java/com/google/adk/memory/FirestoreMemoryServiceTest.java
index 7526461af9..197515ff34 100644
--- a/contrib/firestore-session-service/src/test/java/com/google/adk/memory/FirestoreMemoryServiceTest.java
+++ b/contrib/firestore-session-service/src/test/java/com/google/adk/memory/FirestoreMemoryServiceTest.java
@@ -21,8 +21,10 @@
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import com.google.adk.sessions.Session;
import com.google.api.core.ApiFutures;
import com.google.cloud.firestore.CollectionGroup;
import com.google.cloud.firestore.Firestore;
@@ -191,6 +193,27 @@ void searchMemory_withDocWithNoParts_returnsMemoryWithEmptyContent() {
});
}
+ /** Tests that addSessionToMemory completes without error (it is a deliberate no-op). */
+ @Test
+ void addSessionToMemory_completesSuccessfully() {
+ Session session = mock(Session.class);
+
+ memoryService.addSessionToMemory(session).test().assertComplete();
+ }
+
+ /** Tests that searchMemory returns empty when every query word is a stop word. */
+ @Test
+ void searchMemory_withAllStopWordsQuery_returnsEmptyWithoutHittingFirestore() {
+ // "a the is" are all stop words — extractKeywords returns empty set,
+ // so searchMemory short-circuits without touching Firestore.
+ TestObserver testObserver =
+ memoryService.searchMemory("test-app", "test-user", "a the is").test();
+
+ testObserver.awaitCount(1);
+ testObserver.assertComplete();
+ testObserver.assertValue(response -> response.memories().isEmpty());
+ }
+
/** Tests that searchMemory handles documents with non-text content parts gracefully. */
@Test
void searchMemory_withDocWithNonTextPart_returnsMemoryWithEmptyContent() {
diff --git a/contrib/firestore-session-service/src/test/java/com/google/adk/runner/FirestoreDatabaseRunnerTest.java b/contrib/firestore-session-service/src/test/java/com/google/adk/runner/FirestoreDatabaseRunnerTest.java
index eae6de3b40..61393ae065 100644
--- a/contrib/firestore-session-service/src/test/java/com/google/adk/runner/FirestoreDatabaseRunnerTest.java
+++ b/contrib/firestore-session-service/src/test/java/com/google/adk/runner/FirestoreDatabaseRunnerTest.java
@@ -17,19 +17,33 @@
package com.google.adk.runner;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.adk.agents.BaseAgent;
import com.google.adk.agents.InvocationContext;
import com.google.adk.agents.RunConfig;
+import com.google.adk.apps.App;
+import com.google.adk.artifacts.BaseArtifactService;
+import com.google.adk.artifacts.GcsArtifactService;
+import com.google.adk.artifacts.InMemoryArtifactService;
import com.google.adk.events.Event;
+import com.google.adk.memory.BaseMemoryService;
+import com.google.adk.memory.FirestoreMemoryService;
+import com.google.adk.platform.UuidProvider;
import com.google.adk.plugins.BasePlugin;
+import com.google.adk.plugins.Plugin;
+import com.google.adk.sessions.BaseSessionService;
+import com.google.adk.sessions.FirestoreSessionService;
import com.google.adk.sessions.Session;
import com.google.adk.utils.FirestoreProperties;
import com.google.api.core.ApiFutures;
@@ -40,16 +54,22 @@
import com.google.cloud.firestore.Query;
import com.google.cloud.firestore.QuerySnapshot;
import com.google.cloud.firestore.WriteResult;
+import com.google.cloud.storage.Storage;
+import com.google.cloud.storage.StorageOptions;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
+import io.reactivex.rxjava3.schedulers.Schedulers;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.Instant;
+import java.time.InstantSource;
import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
@@ -58,194 +78,607 @@
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
-/** Test class for {@link FirestoreDatabaseRunner} tests. */
+/** Unit tests for {@link FirestoreDatabaseRunner}. */
@ExtendWith(MockitoExtension.class)
public class FirestoreDatabaseRunnerTest {
- private static final String ENV_PROPERTY_NAME = "env"; // Renamed for clarity
-
- @BeforeEach
- public void setup() throws Exception {
- // Reset properties before each test to ensure isolation
- FirestoreProperties.resetForTest();
- }
+ private static final String ENV_PROPERTY_NAME = "env";
@Mock private BaseAgent mockAgent;
@Mock private Firestore mockFirestore;
- // Mocks for the FirestoreSessionService that will be created internally
+ @Mock private Storage mockStorage;
+
+ // Firestore mock chain used by legacy constructor tests
@Mock private CollectionReference mockRootCollection;
@Mock private DocumentReference mockUserDocRef;
@Mock private CollectionReference mockSessionsCollection;
@Mock private DocumentReference mockSessionDocRef;
@Mock private DocumentSnapshot mockSessionSnapshot;
- // Mocks for state updates
- @Mock private CollectionReference mockAppStateCollection;
- @Mock private DocumentReference mockAppStateDocRef;
- @Mock private CollectionReference mockUserStateRootCollection;
- @Mock private DocumentReference mockUserStateAppDocRef;
- @Mock private CollectionReference mockUserStateUsersCollection;
- @Mock private DocumentReference mockUserStateUserDocRef;
@Mock private CollectionReference mockEventsCollection;
@Mock private DocumentReference mockEventDocRef;
@Mock private Query mockQuery;
@Mock private QuerySnapshot mockQuerySnapshot;
@Mock private WriteResult mockWriteResult;
- /**
- * Tests that the constructor succeeds when the required properties are set.
- *
- * @throws Exception
- */
- @Test
- void constructor_succeeds() throws Exception {
- // Ensure the required property is set for the success case
- System.setProperty(ENV_PROPERTY_NAME, "default"); // Loads adk-firestore.properties
- Mockito.when(mockAgent.name()).thenReturn("test-agent");
+ @BeforeEach
+ void setUp() {
+ FirestoreProperties.resetForTest();
+ }
- FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(mockAgent, mockFirestore);
- assertNotNull(runner);
+ @AfterEach
+ void tearDown() {
+ FirestoreProperties.resetForTest();
+ System.clearProperty(ENV_PROPERTY_NAME);
}
- /**
- * Tests that the constructor throws an exception when the GCS bucket name property is missing.
- *
- * @throws Exception
- */
- @Test
- void constructor_withAppName_throwsExceptionWhenBucketNameIsMissing() {
- assertThrows(
- RuntimeException.class,
- () -> {
- // Arrange: Use mockito-inline to mock the static method call.
- try (MockedStatic mockedProps =
- Mockito.mockStatic(FirestoreProperties.class)) {
- FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class);
- mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance);
- when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(" "); // Empty string
-
- // Act
+ // =========================================================================
+ // Legacy constructor tests
+ // =========================================================================
+
+ @Nested
+ @SuppressWarnings("deprecation")
+ class LegacyConstructors {
+
+ @Test
+ void constructor_succeeds() {
+ System.setProperty(ENV_PROPERTY_NAME, "default");
+ when(mockAgent.name()).thenReturn("test-agent");
+
+ FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(mockAgent, mockFirestore);
+ assertNotNull(runner);
+ }
+
+ @Test
+ void constructor_withAppName_usesInMemoryArtifactServiceWhenBucketNameIsBlank() {
+ try (MockedStatic mockedProps =
+ Mockito.mockStatic(FirestoreProperties.class)) {
+ FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class);
+ mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance);
+ when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(" ");
+
+ Runner runner =
new FirestoreDatabaseRunner(
mockAgent, "test-app", new ArrayList(), mockFirestore);
- }
- });
+
+ assertEquals("test-app", runner.appName());
+ assertInstanceOf(InMemoryArtifactService.class, runner.artifactService());
+ }
+ }
+
+ @Test
+ void constructor_usesInMemoryArtifactServiceWhenBucketNameIsNull() {
+ try (MockedStatic mockedProps =
+ Mockito.mockStatic(FirestoreProperties.class)) {
+ FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class);
+ mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance);
+ when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(null);
+
+ Runner runner = new FirestoreDatabaseRunner(mockAgent, mockFirestore);
+
+ assertInstanceOf(InMemoryArtifactService.class, runner.artifactService());
+ }
+ }
+
+ @Test
+ void run_withUserInput_createsSessionAndExecutesAgent() throws Exception {
+ System.setProperty(ENV_PROPERTY_NAME, "default");
+ when(mockAgent.name()).thenReturn("test-agent");
+
+ String userInput = "hello\nexit\n";
+ InputStream originalIn = System.in;
+ System.setIn(new ByteArrayInputStream(userInput.getBytes()));
+
+ when(mockFirestore.collection("default-adk-session")).thenReturn(mockRootCollection);
+ when(mockRootCollection.document(anyString())).thenReturn(mockUserDocRef);
+ when(mockUserDocRef.collection(anyString())).thenReturn(mockSessionsCollection);
+ when(mockSessionsCollection.document(anyString())).thenReturn(mockSessionDocRef);
+ when(mockSessionDocRef.create(anyMap()))
+ .thenReturn(ApiFutures.immediateFuture(mockWriteResult));
+ when(mockSessionDocRef.update(anyMap()))
+ .thenReturn(ApiFutures.immediateFuture(mockWriteResult));
+ when(mockSessionDocRef.collection(anyString())).thenReturn(mockEventsCollection);
+ when(mockEventsCollection.document()).thenReturn(mockEventDocRef);
+ when(mockEventDocRef.getId()).thenReturn("test-event-id");
+ when(mockEventsCollection.document(anyString())).thenReturn(mockEventDocRef);
+ when(mockEventDocRef.set(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult));
+ when(mockSessionDocRef.get()).thenReturn(ApiFutures.immediateFuture(mockSessionSnapshot));
+ when(mockSessionSnapshot.exists()).thenReturn(true);
+ when(mockSessionSnapshot.getData())
+ .thenReturn(
+ Map.of(
+ "id", "test-session-id",
+ "appName", "test-app",
+ "userId", "test-user-id",
+ "updateTime", Instant.now().toString(),
+ "state", Map.of()));
+ when(mockSessionSnapshot.getReference()).thenReturn(mockSessionDocRef);
+ when(mockEventsCollection.orderBy(anyString())).thenReturn(mockQuery);
+ when(mockQuery.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot));
+
+ Event mockAgentEvent =
+ Event.builder()
+ .content(Content.builder().parts(Part.fromText("Hi there!")).build())
+ .author(mockAgent.name())
+ .build();
+ when(mockAgent.runAsync(any(InvocationContext.class)))
+ .thenReturn(Flowable.just(mockAgentEvent));
+
+ FirestoreDatabaseRunner runner =
+ new FirestoreDatabaseRunner(mockAgent, "test-app", mockFirestore);
+
+ Session session =
+ runner.sessionService().createSession("test-app", "test-user-id").blockingGet();
+ Content userContent = Content.builder().parts(Part.fromText("hello")).build();
+ runner
+ .runAsync(session.userId(), session.id(), userContent, RunConfig.builder().build())
+ .blockingSubscribe();
+
+ ArgumentCaptor contextCaptor =
+ ArgumentCaptor.forClass(InvocationContext.class);
+ verify(mockAgent).runAsync(contextCaptor.capture());
+ assertNotNull(contextCaptor.getValue().userContent().get().parts().get().get(0).text());
+
+ System.setIn(originalIn);
+ }
+ }
+
+ // =========================================================================
+ // Builder tests
+ // =========================================================================
+
+ @Nested
+ class BuilderTests {
+
+ @Test
+ void create_withAgentAndFirestore_buildsRunnerWithDefaults() {
+ when(mockAgent.name()).thenReturn("test-agent");
+
+ Runner runner = FirestoreDatabaseRunner.create(mockAgent, mockFirestore);
+
+ assertNotNull(runner);
+ assertEquals("test-agent", runner.appName());
+ assertInstanceOf(FirestoreSessionService.class, runner.sessionService());
+ assertInstanceOf(FirestoreMemoryService.class, runner.memoryService());
+ // adk-firestore.properties in test resources configures test-bucket
+ assertInstanceOf(GcsArtifactService.class, runner.artifactService());
+ }
+
+ @Test
+ void create_withAgentAppNameAndFirestore_usesCustomAppName() {
+ Runner runner = FirestoreDatabaseRunner.create(mockAgent, "custom-app", mockFirestore);
+
+ assertNotNull(runner);
+ assertEquals("custom-app", runner.appName());
+ }
+
+ @Test
+ void builder_withApp_buildsRunnerFromApp() {
+ App app = App.builder().name("my_app").rootAgent(mockAgent).build();
+
+ Runner runner = FirestoreDatabaseRunner.newBuilder().app(app).firestore(mockFirestore).build();
+
+ assertNotNull(runner);
+ assertEquals("my_app", runner.appName());
+ assertEquals(mockAgent, runner.agent());
+ }
+
+ @Test
+ void builder_withAppAndExplicitAppName_usesExplicitAppName() {
+ App app = App.builder().name("my_app").rootAgent(mockAgent).build();
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .app(app)
+ .appName("custom_override")
+ .firestore(mockFirestore)
+ .build();
+
+ assertEquals("custom_override", runner.appName());
+ }
+
+ @Test
+ void builder_withAgentAndApp_throwsIllegalStateException() {
+ App app = App.builder().name("my_app").rootAgent(mockAgent).build();
+
+ assertThrows(
+ IllegalStateException.class,
+ () -> FirestoreDatabaseRunner.newBuilder().agent(mockAgent).app(app));
+
+ assertThrows(
+ IllegalStateException.class,
+ () -> FirestoreDatabaseRunner.newBuilder().app(app).agent(mockAgent));
+ }
+
+ @Test
+ void builder_withGcsArtifacts_configuresGcsArtifactService() {
+ when(mockAgent.name()).thenReturn("test-agent");
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .firestore(mockFirestore)
+ .withGcsArtifacts("test-bucket", mockStorage)
+ .build();
+
+ assertInstanceOf(GcsArtifactService.class, runner.artifactService());
+ }
+
+ @Test
+ void builder_whenNoGcsBucketConfigured_usesInMemoryArtifactService() {
+ when(mockAgent.name()).thenReturn("test-agent");
+ try (MockedStatic mockedProps =
+ Mockito.mockStatic(FirestoreProperties.class)) {
+ FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class);
+ mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance);
+ when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(null);
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .firestore(mockFirestore)
+ .build();
+ assertInstanceOf(InMemoryArtifactService.class, runner.artifactService());
+
+ }
+ }
+
+ @Test
+ void builder_withExplicitInMemoryArtifactService_succeedsWithoutGcsBucket() {
+ when(mockAgent.name()).thenReturn("test-agent");
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .firestore(mockFirestore)
+ .artifactService(new InMemoryArtifactService())
+ .build();
+
+ assertInstanceOf(InMemoryArtifactService.class, runner.artifactService());
+ }
+
+ @Test
+ void builder_withExplicitArtifactService_usesProvidedArtifactService() {
+ when(mockAgent.name()).thenReturn("test-agent");
+ BaseArtifactService mockArtifactService = mock(BaseArtifactService.class);
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .firestore(mockFirestore)
+ .artifactService(mockArtifactService)
+ .build();
+
+ assertEquals(mockArtifactService, runner.artifactService());
+ }
+
+ @Test
+ void builder_withCustomSessionAndMemoryServices_doesNotRequireFirestore() {
+ when(mockAgent.name()).thenReturn("test-agent");
+ BaseSessionService customSessionService = mock(BaseSessionService.class);
+ BaseMemoryService customMemoryService = mock(BaseMemoryService.class);
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .sessionService(customSessionService)
+ .memoryService(customMemoryService)
+ .build();
+
+ assertEquals(customSessionService, runner.sessionService());
+ assertEquals(customMemoryService, runner.memoryService());
+ }
+
+ @Test
+ void builder_missingAgentAndApp_throwsIllegalStateException() {
+ assertThrows(
+ IllegalStateException.class,
+ () -> FirestoreDatabaseRunner.newBuilder().firestore(mockFirestore).build());
+ }
+
+ @Test
+ void builder_missingFirestoreAndServices_throwsIllegalStateException() {
+ assertThrows(
+ IllegalStateException.class,
+ () -> FirestoreDatabaseRunner.newBuilder().agent(mockAgent).build());
+ }
+
+ @Test
+ void builder_withCustomProvidersAndScheduler_passesThroughToRunner() {
+ when(mockAgent.name()).thenReturn("test-agent");
+ InstantSource fixedSource = InstantSource.fixed(Instant.parse("2025-01-01T00:00:00Z"));
+ UuidProvider customUuid = () -> "fixed-uuid";
+ Plugin mockPlugin = mock(Plugin.class);
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .firestore(mockFirestore)
+ .instantSource(fixedSource)
+ .uuidProvider(customUuid)
+ .scheduler(Schedulers.trampoline())
+ .plugins(List.of(mockPlugin))
+ .build();
+
+ assertNotNull(runner);
+ }
+
+ @Test
+ void builder_withOnlySessionServiceProvided_usesFirestoreForMemoryService() {
+ when(mockAgent.name()).thenReturn("test-agent");
+ BaseSessionService customSessionService = mock(BaseSessionService.class);
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .firestore(mockFirestore)
+ .sessionService(customSessionService)
+ .build();
+
+ assertSame(customSessionService, runner.sessionService());
+ assertInstanceOf(FirestoreMemoryService.class, runner.memoryService());
+ }
+
+ @Test
+ void toRunnerBuilder_allowsFurtherCustomization() {
+ when(mockAgent.name()).thenReturn("test-agent");
+
+ Runner.Builder runnerBuilder =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .firestore(mockFirestore)
+ .toRunnerBuilder();
+
+ Runner runner = runnerBuilder.build();
+ assertNotNull(runner);
+ assertEquals("test-agent", runner.appName());
+ }
+ }
+
+ @Test
+ void builder_withCustomArtifactServiceAndGcsBucket_usesCustomArtifactService() {
+ when(mockAgent.name()).thenReturn("test-agent");
+ BaseArtifactService customArtifactService = mock(BaseArtifactService.class);
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .firestore(mockFirestore)
+ .withGcsArtifacts("test-bucket", mockStorage)
+ .artifactService(customArtifactService)
+ .build();
+
+ assertEquals(customArtifactService, runner.artifactService());
}
- /**
- * Tests that the constructor throws an exception when the GCS bucket name is null.
- *
- * @throws Exception
- */
@Test
- void constructor_throwsExceptionWhenBucketNameIsNull() {
- assertThrows(
- RuntimeException.class,
- () -> {
- // Arrange: Use mockito-inline to mock the static method call.
- try (MockedStatic mockedProps =
- Mockito.mockStatic(FirestoreProperties.class)) {
- FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class);
- mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance);
- when(mockPropsInstance.getGcsAdkBucketName())
- .thenReturn(null); // Explicitly return null for bucketName
- // Act
- new FirestoreDatabaseRunner(mockAgent, mockFirestore);
- }
- });
+ void builder_withCustomServices_wiresServicesCorrectly() {
+ System.setProperty(ENV_PROPERTY_NAME, "default");
+ try {
+ Firestore mockFirestore = mock(Firestore.class);
+ String appName = "test-app";
+ GcsArtifactService customArtifactService =
+ new GcsArtifactService("test-bucket", mockStorage);
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .appName(appName)
+ .firestore(mockFirestore)
+ .artifactService(customArtifactService)
+ .build();
+
+ assertEquals(appName, runner.appName());
+ assertInstanceOf(FirestoreSessionService.class, runner.sessionService());
+ assertSame(customArtifactService, runner.artifactService());
+ } finally {
+ System.clearProperty(ENV_PROPERTY_NAME);
+ }
}
- /**
- * Tests that run with user input creates a session and executes the agent.
- *
- * @throws Exception
- */
@Test
- void run_withUserInput_createsSessionAndExecutesAgent() throws Exception {
- // Arrange
- System.setProperty(ENV_PROPERTY_NAME, "default"); // Ensure properties are loaded
- when(mockAgent.name()).thenReturn("test-agent");
+ void builder_withCustomServices_wiresServicesCorrectlyNoArtifactService() {
+ System.setProperty(ENV_PROPERTY_NAME, "default");
+ try {
+ Firestore mockFirestore = mock(Firestore.class);
+ String appName = "test-app";
- // Mock user input
- String userInput = "hello\nexit\n";
- InputStream originalIn = System.in;
- System.setIn(new ByteArrayInputStream(userInput.getBytes()));
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .appName(appName)
+ .firestore(mockFirestore)
+ .build();
- // Mock the Firestore calls that SessionService will make
- when(mockFirestore.collection("default-adk-session")).thenReturn(mockRootCollection);
+ assertEquals(appName, runner.appName());
+ assertInstanceOf(FirestoreSessionService.class, runner.sessionService());
+ } finally {
+ System.clearProperty(ENV_PROPERTY_NAME);
+ }
+ }
+
+ @Test
+ void builder_withCustomArtifactService_runsAgentAndProducesEvents() {
+ System.setProperty(ENV_PROPERTY_NAME, "default");
+
+ String appName = "test-app";
+ GcsArtifactService customArtifactService = new GcsArtifactService("test-bucket", mockStorage);
+
+ when(mockFirestore.collection(anyString())).thenReturn(mockRootCollection);
when(mockRootCollection.document(anyString())).thenReturn(mockUserDocRef);
when(mockUserDocRef.collection(anyString())).thenReturn(mockSessionsCollection);
when(mockSessionsCollection.document(anyString())).thenReturn(mockSessionDocRef);
-
- when(mockSessionDocRef.create(anyMap()))
- .thenReturn(ApiFutures.immediateFuture(mockWriteResult));
- when(mockSessionDocRef.update(anyMap()))
- .thenReturn(ApiFutures.immediateFuture(mockWriteResult));
- // Mock the event sub-collection chain
+ when(mockSessionDocRef.create(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult));
+ when(mockSessionDocRef.update(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult));
when(mockSessionDocRef.collection(anyString())).thenReturn(mockEventsCollection);
- // THIS IS THE MISSING MOCK: Stub the no-arg document() call for ID generation.
when(mockEventsCollection.document()).thenReturn(mockEventDocRef);
when(mockEventDocRef.getId()).thenReturn("test-event-id");
when(mockEventsCollection.document(anyString())).thenReturn(mockEventDocRef);
when(mockEventDocRef.set(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult));
- // THIS IS THE MISSING MOCK: Stub the get() call on the session document.
when(mockSessionDocRef.get()).thenReturn(ApiFutures.immediateFuture(mockSessionSnapshot));
when(mockSessionSnapshot.exists()).thenReturn(true);
- // Provide a complete map for the session data
when(mockSessionSnapshot.getData())
.thenReturn(
Map.of(
"id", "test-session-id",
- "appName", "test-app",
- "userId", "test-user-id",
+ "appName", appName,
+ "userId", "user1234",
"updateTime", Instant.now().toString(),
"state", Map.of()));
when(mockSessionSnapshot.getReference()).thenReturn(mockSessionDocRef);
- // THIS IS THE MISSING MOCK: Stub the orderBy() call on the events collection.
when(mockEventsCollection.orderBy(anyString())).thenReturn(mockQuery);
when(mockQuery.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot));
- // Mock Agent behavior
- Event mockAgentEvent =
- Event.builder()
- .content(Content.builder().parts(Part.fromText("Hi there!")).build())
- .author(mockAgent.name())
+ BaseAgent testAgent =
+ new BaseAgent("test-agent", "Test agent", List.of(), List.of(), List.of()) {
+ @Override
+ protected Flowable runAsyncImpl(InvocationContext invocationContext) {
+ return Flowable.just(
+ Event.builder()
+ .id(Event.generateEventId())
+ .invocationId(invocationContext.invocationId())
+ .author(name())
+ .content(Content.fromParts(Part.fromText("Hello from test agent!")))
+ .build());
+ }
+
+ @Override
+ protected Flowable runLiveImpl(InvocationContext invocationContext) {
+ return Flowable.error(new UnsupportedOperationException("Live mode not supported"));
+ }
+ };
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(testAgent)
+ .appName(appName)
+ .firestore(mockFirestore)
+ .artifactService(customArtifactService)
.build();
- when(mockAgent.runAsync(any(InvocationContext.class)))
- .thenReturn(Flowable.just(mockAgentEvent));
-
- // Create runner, which will internally create a FirestoreSessionService
- // using our mocked Firestore object.
- FirestoreDatabaseRunner runner =
- new FirestoreDatabaseRunner(mockAgent, "test-app", mockFirestore);
-
- // Act
- // First, create a session to get a valid session ID
- Session session =
- runner.sessionService().createSession("test-app", "test-user-id").blockingGet();
- // Now, run the agent with the user input
- Content userContent = Content.builder().parts(Part.fromText("hello")).build();
- runner
- .runAsync(session.userId(), session.id(), userContent, RunConfig.builder().build())
- .blockingSubscribe(); // block until the flow completes
-
- // Assert
- ArgumentCaptor contextCaptor =
- ArgumentCaptor.forClass(InvocationContext.class);
- verify(mockAgent).runAsync(contextCaptor.capture());
- assertNotNull(contextCaptor.getValue().userContent().get().parts().get().get(0).text());
-
- // Restore original System.in
- System.setIn(originalIn);
+
+ assertSame(customArtifactService, runner.artifactService());
+
+ Session session = runner.sessionService().createSession(appName, "user1234").blockingGet();
+ assertNotNull(session);
+
+ List events =
+ runner
+ .runAsync(session.userId(), session.id(), Content.fromParts(Part.fromText("Hello!")),
+ RunConfig.builder().build())
+ .toList()
+ .blockingGet();
+
+ assertEquals(1, events.size());
+ assertEquals("test-agent", events.get(0).author());
+ assertEquals("Hello from test agent!", events.get(0).stringifyContent());
}
- /**
- * Cleans up after each test.
- *
- * @throws Exception
- */
- @AfterEach
- public void teardown() throws Exception {
- // Clean up the environment variable after each test
- FirestoreProperties.resetForTest(); // Reset the singleton instance
- System.clearProperty(ENV_PROPERTY_NAME); // Clear the system property
+ @Test
+ void builder_withMultiplePluginCalls_accumulatesPlugins() {
+ Firestore mockFirestore = mock(Firestore.class);
+ Plugin plugin1 = new BasePlugin("plugin-1") {};
+ Plugin plugin2 = new BasePlugin("plugin-2") {};
+ Plugin plugin3 = new BasePlugin("plugin-3") {};
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .appName("test-app")
+ .firestore(mockFirestore)
+ .plugins(plugin1)
+ .plugins(plugin2, plugin3)
+ .build();
+
+ assertSame(plugin1, runner.pluginManager().getPlugin("plugin-1").orElseThrow());
+ assertSame(plugin2, runner.pluginManager().getPlugin("plugin-2").orElseThrow());
+ assertSame(plugin3, runner.pluginManager().getPlugin("plugin-3").orElseThrow());
+ }
+
+ @Test
+ void builder_withGcsArtifactsBucketOnly_usesDefaultStorageOptions() {
+ Firestore mockFirestore = mock(Firestore.class);
+ StorageOptions mockStorageOptions = mock(StorageOptions.class);
+ Storage mockDefaultStorage = mock(Storage.class);
+ when(mockStorageOptions.getService()).thenReturn(mockDefaultStorage);
+
+ try (MockedStatic storageOptionsStatic = mockStatic(StorageOptions.class)) {
+ storageOptionsStatic.when(StorageOptions::getDefaultInstance).thenReturn(mockStorageOptions);
+
+ Runner runner =
+ FirestoreDatabaseRunner.newBuilder()
+ .agent(mockAgent)
+ .appName("test-app")
+ .firestore(mockFirestore)
+ .withGcsArtifacts("test-bucket")
+ .build();
+
+ assertInstanceOf(GcsArtifactService.class, runner.artifactService());
+ storageOptionsStatic.verify(StorageOptions::getDefaultInstance);
+ verify(mockStorageOptions).getService();
+ }
}
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void resolveDefaultArtifactService_whenBucketIsNull_returnsInMemoryArtifactService() {
+ assertInMemoryArtifactServiceForBucket(null);
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void resolveDefaultArtifactService_whenBucketIsEmpty_returnsInMemoryArtifactService() {
+ assertInMemoryArtifactServiceForBucket("");
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void resolveDefaultArtifactService_whenBucketIsBlank_returnsInMemoryArtifactService() {
+ assertInMemoryArtifactServiceForBucket(" ");
+ }
+
+ @SuppressWarnings("deprecation")
+ private void assertInMemoryArtifactServiceForBucket(String bucketName) {
+ try (MockedStatic mockedProps =
+ Mockito.mockStatic(FirestoreProperties.class);
+ MockedStatic mockedStorageOptions =
+ Mockito.mockStatic(StorageOptions.class)) {
+ FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class);
+ mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance);
+ when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(bucketName);
+
+ Runner runner =
+ new FirestoreDatabaseRunner(
+ mockAgent, "test-app", new ArrayList(), mockFirestore);
+
+ assertInstanceOf(InMemoryArtifactService.class, runner.artifactService());
+ mockedStorageOptions.verifyNoInteractions();
+ }
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void resolveDefaultArtifactService_whenBucketConfigured_returnsGcsArtifactService() {
+ StorageOptions mockStorageOptions = mock(StorageOptions.class);
+ Storage mockStorage = mock(Storage.class);
+ when(mockStorageOptions.getService()).thenReturn(mockStorage);
+
+ try (MockedStatic mockedProps =
+ Mockito.mockStatic(FirestoreProperties.class);
+ MockedStatic mockedStorageOptions =
+ Mockito.mockStatic(StorageOptions.class)) {
+ FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class);
+ mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance);
+ when(mockPropsInstance.getGcsAdkBucketName()).thenReturn("my-test-bucket");
+ mockedStorageOptions
+ .when(StorageOptions::getDefaultInstance)
+ .thenReturn(mockStorageOptions);
+
+ Runner runner =
+ new FirestoreDatabaseRunner(
+ mockAgent, "test-app", new ArrayList(), mockFirestore);
+
+ assertInstanceOf(GcsArtifactService.class, runner.artifactService());
+ mockedStorageOptions.verify(StorageOptions::getDefaultInstance);
+ verify(mockStorageOptions).getService();
+ }
+ }
}
diff --git a/contrib/firestore-session-service/src/test/java/com/google/adk/sessions/FirestoreSessionServiceTest.java b/contrib/firestore-session-service/src/test/java/com/google/adk/sessions/FirestoreSessionServiceTest.java
index d4b15b3a52..5dc59e74fc 100644
--- a/contrib/firestore-session-service/src/test/java/com/google/adk/sessions/FirestoreSessionServiceTest.java
+++ b/contrib/firestore-session-service/src/test/java/com/google/adk/sessions/FirestoreSessionServiceTest.java
@@ -1575,6 +1575,161 @@ void deleteSession_appNameMismatch_doesNotDelete() {
verify(mockWriteBatch, never()).commit();
}
+ /** Tests that appendEvent with a regular (non-prefixed) state key updates session state. */
+ @Test
+ void appendEvent_withRegularStateDeltaKey_updatesSessionState() {
+ Session session =
+ Session.builder(SESSION_ID)
+ .appName(APP_NAME)
+ .userId(USER_ID)
+ .state(new ConcurrentHashMap<>())
+ .build();
+
+ EventActions actions =
+ EventActions.builder()
+ .stateDelta(new ConcurrentHashMap<>(ImmutableMap.of("myKey", "myValue")))
+ .build();
+
+ Event event =
+ Event.builder()
+ .author("model")
+ .content(Content.builder().parts(List.of(Part.fromText("."))).build())
+ .actions(actions)
+ .build();
+
+ when(mockSessionsCollection.document(SESSION_ID)).thenReturn(mockSessionDocRef);
+ when(mockEventsCollection.document()).thenReturn(mockEventDocRef);
+ when(mockEventDocRef.getId()).thenReturn(EVENT_ID);
+ when(mockEventsCollection.document(EVENT_ID)).thenReturn(mockEventDocRef);
+ when(mockSessionDocRef.update(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult));
+
+ sessionService.appendEvent(session, event).test().assertComplete();
+
+ assertThat(session.state()).containsEntry("myKey", "myValue");
+ }
+
+ /** Tests that deleteSession silently succeeds when the session has no events. */
+ @Test
+ void deleteSession_whenSessionHasNoEvents_deletesSessionDocumentOnly() {
+ when(mockSessionsCollection.document(SESSION_ID)).thenReturn(mockSessionDocRef);
+ when(mockSessionDocRef.get()).thenReturn(ApiFutures.immediateFuture(mockSessionSnapshot));
+ when(mockSessionSnapshot.exists()).thenReturn(true);
+ when(mockSessionSnapshot.get(Constants.KEY_APP_NAME)).thenReturn(APP_NAME);
+ when(mockSessionDocRef.collection(Constants.EVENTS_SUBCOLLECTION_NAME))
+ .thenReturn(mockEventsCollection);
+ when(mockEventsCollection.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot));
+ when(mockQuerySnapshot.getDocuments()).thenReturn(Collections.emptyList());
+
+ sessionService.deleteSession(APP_NAME, USER_ID, SESSION_ID).test().assertComplete();
+
+ verify(mockWriteBatch, never()).commit();
+ verify(mockSessionDocRef).delete();
+ }
+
+ /** Tests that listSessions silently skips documents whose data() returns null. */
+ @Test
+ void listSessions_whenDocumentDataIsNull_skipsDocument() {
+ when(mockSessionsCollection.whereEqualTo(Constants.KEY_APP_NAME, APP_NAME))
+ .thenReturn(mockQuery);
+ when(mockQuery.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot));
+
+ QueryDocumentSnapshot nullDataDoc = mock(QueryDocumentSnapshot.class);
+ when(nullDataDoc.getData()).thenReturn(null);
+
+ QueryDocumentSnapshot validDoc = mock(QueryDocumentSnapshot.class);
+ when(validDoc.getData())
+ .thenReturn(
+ ImmutableMap.of(
+ "id", SESSION_ID,
+ "appName", APP_NAME,
+ "userId", USER_ID,
+ "updateTime", NOW.toString()));
+
+ when(mockQuerySnapshot.getDocuments()).thenReturn(ImmutableList.of(nullDataDoc, validDoc));
+
+ TestObserver testObserver =
+ sessionService.listSessions(APP_NAME, USER_ID).test();
+
+ testObserver.awaitCount(1);
+ testObserver.assertComplete();
+ testObserver.assertValue(response -> response.sessions().size() == 1);
+ }
+
+ /**
+ * Tests that getSession gracefully skips a part whose "functionCall" value is not a Map,
+ * exercising the safeCast type-mismatch path and functionCallPartFromMap(null).
+ */
+ @Test
+ void getSession_withNonMapFunctionCallValue_skipsInvalidPart() {
+ when(mockSessionsCollection.document(SESSION_ID)).thenReturn(mockSessionDocRef);
+ when(mockSessionDocRef.get()).thenReturn(ApiFutures.immediateFuture(mockSessionSnapshot));
+ when(mockSessionSnapshot.exists()).thenReturn(true);
+ when(mockSessionSnapshot.getReference()).thenReturn(mockSessionDocRef);
+ when(mockSessionSnapshot.getData())
+ .thenReturn(
+ ImmutableMap.of(
+ "id", SESSION_ID,
+ "appName", APP_NAME,
+ "userId", USER_ID,
+ "updateTime", NOW.toString(),
+ "state", Collections.emptyMap()));
+
+ // Event with a "functionCall" value that is a String, not a Map
+ when(mockEventSnapshot.getData())
+ .thenReturn(
+ ImmutableMap.of(
+ Constants.KEY_AUTHOR, "agent",
+ Constants.KEY_TIMESTAMP, NOW.toString(),
+ "content",
+ ImmutableMap.of(
+ "parts", ImmutableList.of(ImmutableMap.of("functionCall", "not-a-map")))));
+ when(mockQuery.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot));
+ when(mockQuerySnapshot.getDocuments()).thenReturn(ImmutableList.of(mockEventSnapshot));
+
+ TestObserver testObserver =
+ sessionService.getSession(APP_NAME, USER_ID, SESSION_ID, Optional.empty()).test();
+
+ testObserver.awaitCount(1);
+ testObserver.assertComplete();
+ testObserver.assertValue(
+ session -> {
+ // The malformed part is skipped; the event is still returned with empty parts
+ assertThat(session.events()).hasSize(1);
+ return true;
+ });
+ }
+
+ /** Tests that appendEvent with an empty-string text part does not add it to keywords. */
+ @Test
+ @SuppressWarnings("unchecked")
+ void appendEvent_withEmptyStringTextPart_producesNoKeywords() {
+ Session session =
+ Session.builder(SESSION_ID)
+ .appName(APP_NAME)
+ .userId(USER_ID)
+ .state(new ConcurrentHashMap<>())
+ .build();
+
+ Event event =
+ Event.builder()
+ .author("model")
+ .content(Content.builder().parts(List.of(Part.fromText(""))).build())
+ .build();
+
+ when(mockSessionsCollection.document(SESSION_ID)).thenReturn(mockSessionDocRef);
+ when(mockEventsCollection.document()).thenReturn(mockEventDocRef);
+ when(mockEventDocRef.getId()).thenReturn(EVENT_ID);
+ when(mockEventsCollection.document(EVENT_ID)).thenReturn(mockEventDocRef);
+ when(mockSessionDocRef.update(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult));
+
+ sessionService.appendEvent(session, event).test().assertComplete();
+
+ ArgumentCaptor