diff --git a/src/ClaudeCodeSdk.MAF/ClaudeCodeAIAgent.cs b/src/ClaudeCodeSdk.MAF/ClaudeCodeAIAgent.cs index c1336d1..4c0a9d7 100644 --- a/src/ClaudeCodeSdk.MAF/ClaudeCodeAIAgent.cs +++ b/src/ClaudeCodeSdk.MAF/ClaudeCodeAIAgent.cs @@ -100,11 +100,6 @@ protected override async Task RunCoreAsync( await foreach (var claudeMessage in asyncEnumMsgs) { - if (client != null && cancellationToken.IsCancellationRequested) - { - await InterruptAsync(client); - } - if (claudeMessage is ResultMessage resultMessage) { usageDetails = resultMessage.ToUsageDetails(); @@ -150,7 +145,7 @@ protected override async IAsyncEnumerable RunCoreStreamingA if (!string.IsNullOrWhiteSpace(content)) { var (asyncEnumMsgs, client) = await SendUserInput(claudeThread, content, cancellationToken); - + if (client != null && cancellationToken.IsCancellationRequested) { await InterruptAsync(client); @@ -160,11 +155,6 @@ protected override async IAsyncEnumerable RunCoreStreamingA // Receive and yield responses await foreach (var claudeMessage in asyncEnumMsgs) { - if (client != null && cancellationToken.IsCancellationRequested) - { - await InterruptAsync(client); - } - var update = claudeMessage.ToAgentRunResponseUpdate(); if (update != null) { @@ -203,15 +193,37 @@ private async Task InterruptAsync(ClaudeSdkClient client) } else { - client = await _clientManager.GetClientAsync(claudeThread, cancellationToken); + client = await _clientManager.GetClientAsync(claudeThread, CancellationToken.None); await client.QueryAsync(content, sessionId: claudeThread.SessionId.ToString(), - cancellationToken: cancellationToken); + cancellationToken: CancellationToken.None); - asyncEnumMsgs = client.ReceiveResponseAsync(cancellationToken); + asyncEnumMsgs = client.ReceiveResponseAsync(CancellationToken.None); } + // + var interruptRequested = 0; + using var cancellationRegistration = cancellationToken.Register(() => + { + if (client == null) return; + if (Interlocked.Exchange(ref interruptRequested, 1) != 0) + return; + + _ = Task.Run(async () => + { + try + { + await InterruptAsync(client); + } + catch (Exception ex) + { + _logger?.LogDebug(ex, "Failed to interrupt Claude SDK client during streaming cancellation"); + } + }); + }); + + return (asyncEnumMsgs, client); } diff --git a/src/ClaudeCodeSdk/ClaudeSDKClient.cs b/src/ClaudeCodeSdk/ClaudeSDKClient.cs index 286b8d0..7445844 100644 --- a/src/ClaudeCodeSdk/ClaudeSDKClient.cs +++ b/src/ClaudeCodeSdk/ClaudeSDKClient.cs @@ -120,7 +120,7 @@ public async Task InterruptAsync(CancellationToken cancellationToken = default) ConnectStatus = ConnectStatus.DisConnecting; await _process.InterruptAsync(); - await this.DisposeAsync(); + ConnectStatus = ConnectStatus.DisConnected; } /// @@ -171,4 +171,4 @@ public async ValueTask DisposeAsync() } GC.SuppressFinalize(this); } -} \ No newline at end of file +}