Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion FirebaseAI/Sources/Chat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public final class Chat: Sendable {
let request = history + newContent
let stream = try model.generateContentStream(request, generationConfig: generationConfig)
return AsyncThrowingStream { continuation in
Task {
let task = Task {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The task should check for cancellation before modifying the chat history. If the stream is cancelled, appending newContent and the partial aggregatedContent to _history (lines 138-142) might lead to an inconsistent chat state. Consider adding a check like guard !Task.isCancelled else { return } before updating the history.

var aggregatedContent: [ModelContent] = []

do {
Expand All @@ -142,6 +142,9 @@ public final class Chat: Sendable {
self._history.append(aggregated)
continuation.finish()
}
continuation.onTermination = { _ in
task.cancel()
}
}
}

Expand Down
Loading