From 75945e154a4feda887021d8ade7bfe3897ea117c Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Mon, 14 Jul 2025 22:55:08 +0000 Subject: [PATCH] Feat: Add thread safety to chat history This commit introduces a new `appendHistory` method to the `Chat` class to provide a thread-safe way of appending to the chat history. The following changes were made: - A new `appendHistory` method was added to the `Chat` class. - All direct calls to `history.append` were replaced with calls to the new `appendHistory` method. This ensures that all modifications to the chat history are protected by a lock, preventing potential race conditions. --- FirebaseAI/Sources/Chat.swift | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/FirebaseAI/Sources/Chat.swift b/FirebaseAI/Sources/Chat.swift index 1aa2c3490c7..42da2ef4a6d 100644 --- a/FirebaseAI/Sources/Chat.swift +++ b/FirebaseAI/Sources/Chat.swift @@ -45,6 +45,12 @@ public final class Chat: Sendable { } } + private func appendHistory(_ newElement: ModelContent) { + historyLock.withLock { + _history.append(newElement) + } + } + /// Sends a message using the existing history of this chat as context. If successful, the message /// and response will be added to the history. If unsuccessful, history will remain unchanged. /// - Parameter parts: The new content to send as a single chat message. @@ -82,7 +88,7 @@ public final class Chat: Sendable { // Append the request and successful result to history, then return the value. appendHistory(contentsOf: newContent) - history.append(toAdd) + appendHistory(toAdd) return result } @@ -134,7 +140,7 @@ public final class Chat: Sendable { // Aggregate the content to add it to the history before we finish. let aggregated = self.aggregatedChunks(aggregatedContent) - self.history.append(aggregated) + self.appendHistory(aggregated) continuation.finish() } }