Skip to content

Commit 353c686

Browse files
committed
Fix cancellation
1 parent 01bcaad commit 353c686

2 files changed

Lines changed: 10 additions & 6 deletions

File tree

Core/Sources/SuggestionWidget/FeatureReducers/PromptToCode.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ public struct PromptToCode: ReducerProtocol {
219219
case .stopRespondingButtonTapped:
220220
state.isResponding = false
221221
promptToCodeService.stopResponding()
222-
return .none
222+
return .cancel(id: CancellationKey.modifyCode(state.id))
223223

224224
case let .modifyCodeTrunkReceived(code, description):
225225
state.code = code

Tool/Sources/OpenAIService/ChatGPTService.swift

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public class ChatGPTService: ChatGPTServiceType {
6363
public var functionProvider: ChatGPTFunctionProvider
6464

6565
var uuidGenerator: () -> String = { UUID().uuidString }
66-
var cancelTask: Cancellable?
66+
var runningTask: Task<Void, Never>?
6767
var buildCompletionStreamAPI: CompletionStreamAPIBuilder = OpenAICompletionStreamAPI.init
6868
var buildCompletionAPI: CompletionAPIBuilder = OpenAICompletionAPI.init
6969

@@ -204,8 +204,8 @@ public class ChatGPTService: ChatGPTServiceType {
204204
}
205205

206206
public func stopReceivingMessage() {
207-
cancelTask?()
208-
cancelTask = nil
207+
runningTask?.cancel()
208+
runningTask = nil
209209
}
210210
}
211211

@@ -285,9 +285,11 @@ extension ChatGPTService {
285285
references: prompt.references
286286
)
287287
let (trunks, cancel) = try await api()
288-
cancelTask = cancel
289288
for try await trunk in trunks {
290-
try Task.checkCancellation()
289+
if Task.isCancelled {
290+
cancel()
291+
throw CancellationError()
292+
}
291293
guard let delta = trunk.choices?.first?.delta else { continue }
292294

293295
// The api will always return a function call with JSON object.
@@ -333,6 +335,8 @@ extension ChatGPTService {
333335
}
334336
}
335337

338+
runningTask = task
339+
336340
continuation.onTermination = { _ in
337341
task.cancel()
338342
}

0 commit comments

Comments
 (0)