diff --git a/CHANGELOG.md b/CHANGELOG.md
index 98b093ca..4279747d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ The next SDK version is **2.0.0**, on the same opencode **2.3.0** pin already re
### 🔧 Changes
- `StopAsync` and the `EnsureAsync` version-mismatch replacement treat a failed persistent-terminal handoff or clear as best-effort, whatever the exception type, as opencode's CLI does. Before: a failure other than an `OpenCodeServerException` ended `StopAsync` before it terminated the old service, and ended `EnsureAsync` at once. After: `StopAsync` terminates the old service; `EnsureAsync` keeps polling, and the last replacement failure becomes the inner exception of its timeout. The caller's cancellation still ends both. (#871)
+- `StopAsync` with `Pty = Handoff` and the `EnsureAsync` replacement treat every persistent-terminal ticket-request, shutdown fallback or sidecar-publish failure as best-effort, as opencode's CLI does. Before: a failure other than an `OpenCodeException` could end the handoff preparation before terminal shutdown or empty-ticket publication completed. After: a failed ticket request still takes the terminal-shutdown fallback and publishes the empty handoff ticket; a failed shutdown no longer skips publication, and a failed publish no longer ends the preparation. The caller's cancellation still ends it. (#895)
- The packages' .NET dependency floors move from `10.0.13` to the `10.0.15` servicing release: on `net472` and `netstandard2.0`, `System.Text.Json`, `System.Threading.Channels`, `System.Collections.Immutable`, `Microsoft.Bcl.AsyncInterfaces`, `Microsoft.Bcl.Memory` and `Microsoft.Bcl.TimeProvider`; in `OpenCodeDotNet.Sdk.Extensions`, on every target, `Microsoft.Extensions.DependencyInjection.Abstractions` and `Microsoft.Extensions.Options.ConfigurationExtensions`. No security advisory of the .NET 10.0.14 or 10.0.15 release lists these packages.
- Event Types are copied and validated at the call and selected locally; physical attempts send no Types query. The whole bus is decoded once, so malformed unselected traffic reconnects every subscriber. Event and metadata instances are shared references, not deep-frozen graphs; consumers treat them as read-only. Queue bounds count events, not bytes, and subscriber count remains unbounded.
- Event subscriptions accept but no longer forward per-call Location. Every shared attempt sends only the client's ambient header snapshot; other operations retain their existing override behavior.
diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs
index f68d27a9..f38850f1 100644
--- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs
+++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs
@@ -62,8 +62,9 @@ public async Task PrepareAsync(
{
throw FailureClassification.CallerCancellation(failure, "The persistent-terminal handoff request was canceled.", cancellationToken);
}
- catch (Exception failure) when (failure is OpenCodeException or OperationCanceledException or ArgumentException { ParamName: "endpoint" })
+ catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
+ // The SDK drops request failures where upstream warns (prepare in pty-handoff.ts); it has no warning channel here.
// Another caller may already have prepared and stopped this server; otherwise the
// daemon's terminals are shut down and the replacement starts without a handoff.
if (await IsFreshMatchAsync(sidecarPath, registration, cancellationToken).ConfigureAwait(false))
@@ -190,7 +191,7 @@ private PtyHandoffSidecar Parse(ServiceHandoffTicketResponse answer, ServiceRegi
///
[SlopwatchSuppress(
"SW003",
- "The pinned client's shutdown .catch(() => {}) is best-effort (prepare in pty-handoff.ts): endpoint refusal or a failed shutdown leads to a null sidecar and replacement without these terminals.")]
+ "The pinned client's prepare drops every shutdown fallback failure with .catch(() => {}) (prepare in pty-handoff.ts); the SDK drops it silently as upstream does. Only the caller's cancellation propagates, and a null sidecar is published next.")]
private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan timeout, CancellationToken cancellationToken)
{
using var deadline = TimedCancellation.Create(timeout, time);
@@ -203,7 +204,7 @@ private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan time
{
throw FailureClassification.CallerCancellation(failure, "The persistent-terminal shutdown fallback was canceled.", cancellationToken);
}
- catch (Exception failure) when (failure is OpenCodeException or OperationCanceledException or ArgumentException { ParamName: "endpoint" })
+ catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
// Best-effort: the replacement starts without these terminals.
}
@@ -211,18 +212,18 @@ private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan time
///
/// publish(...).catch(warn): a sidecar that cannot be written leaves the replacement
- /// without a handoff; it never fails the preparation.
+ /// without a handoff; only the caller's cancellation fails the preparation.
///
[SlopwatchSuppress(
"SW003",
- "The pinned client only warns when publishing the handoff fails (prepare in pty-handoff.ts): the replacement then starts without the terminals, which is the best-effort contract.")]
+ "The pinned client's prepare catches every sidecar publish failure and only warns (prepare in pty-handoff.ts); the SDK has no warning channel here, so the failure is dropped. Only the caller's cancellation propagates, so the replacement starts without the terminals.")]
private async Task TryPublishAsync(string sidecarPath, PtyHandoffSidecar sidecar, CancellationToken cancellationToken)
{
try
{
await PublishAsync(sidecarPath, sidecar, cancellationToken).ConfigureAwait(false);
}
- catch (OpenCodeServerException)
+ catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
// Best-effort: no sidecar means no handoff.
}
diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs
new file mode 100644
index 00000000..f1cf0fa5
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs
@@ -0,0 +1,289 @@
+using System.Net;
+using NSubstitute;
+using NSubstitute.ExceptionExtensions;
+using OpenCode.Sdk.Internal;
+using OpenCode.Sdk.Tests.Harness;
+using OpenCode.Sdk.Tests.Support;
+using TUnit.Assertions.Enums;
+using static OpenCode.Sdk.Tests.Hosting.BackgroundService.Handoff.ServicePtyHandoffScenario;
+
+namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Handoff;
+
+/// Failed inner preparation steps are best-effort; only the caller's cancellation propagates.
+public sealed class ServicePtyHandoffBestEffortTests
+{
+ private readonly ServicePtyHandoffScenario _scenario = new();
+
+ [Test]
+ public async Task PrepareAsync_Should_Expire_The_Ticket_On_The_Injected_Clock()
+ {
+ _scenario.EnsureSidecarDirectory();
+ var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ await using var server = LoopbackHttpServer.Start(_ => Pending(entered));
+ var shutdown = Substitute.For();
+ shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask);
+ using var caller = new CancellationTokenSource();
+ var registration = ServicePtyHandoffScenario.Registration(server.Endpoint);
+ var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown)
+ .PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, caller.Token);
+ try
+ {
+ await entered.Task.WaitAsync(PreparationHangGuard);
+ await AdvanceToJustBeforeRequestTimeoutAsync();
+ await Assert.That(pending.IsCompleted).IsFalse();
+ _ = shutdown.DidNotReceiveWithAnyArgs().ShutdownAsync(default!, default);
+ _scenario.Clock.Advance(TimeSpan.FromTicks(1));
+ await pending.WaitAsync(PreparationHangGuard);
+
+ _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any());
+ await AssertNullSidecarAfterExpiryAsync();
+ }
+ finally
+ {
+ await caller.CancelOnWorkerAsync();
+ server.ReleaseResponses();
+ }
+ }
+
+ [Test]
+ public async Task PrepareAsync_Should_Expire_The_Fallback_On_The_Injected_Clock()
+ {
+ _scenario.EnsureSidecarDirectory();
+ await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}"));
+ var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var shutdown = Substitute.For();
+ CancellationToken received = default;
+ shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(async call =>
+ {
+ received = call.Arg();
+ var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ using var cancellation = received.Register(() => held.TrySetCanceled(received));
+ entered.TrySetResult();
+ await held.Task;
+ });
+ using var caller = new CancellationTokenSource();
+ var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown)
+ .PrepareAsync(_scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token);
+ try
+ {
+ await entered.Task.WaitAsync(PreparationHangGuard);
+ await AdvanceToJustBeforeRequestTimeoutAsync();
+ await Assert.That(received.IsCancellationRequested).IsFalse();
+ await Assert.That(pending.IsCompleted).IsFalse();
+ _scenario.Clock.Advance(TimeSpan.FromTicks(1));
+ await pending.WaitAsync(PreparationHangGuard);
+
+ await Assert.That(received.IsCancellationRequested).IsTrue();
+ await AssertNullSidecarAfterExpiryAsync();
+ }
+ finally
+ {
+ await caller.CancelOnWorkerAsync();
+ }
+ }
+
+ [Test]
+ public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Sidecar_When_The_Daemon_Answers_An_Error()
+ {
+ _scenario.EnsureSidecarDirectory();
+ await using var server = LoopbackHttpServer.Start(static path => path == ShutdownPath
+ ? NoContent()
+ : Json(HttpStatusCode.InternalServerError, "{}"));
+
+ await _scenario.PrepareAsync(server.Endpoint);
+
+ await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull();
+ await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath, ShutdownPath], CollectionOrdering.Matching);
+ }
+
+ [Test]
+ [Arguments("options")]
+ [Arguments("io")]
+ public async Task PrepareAsync_Should_Swallow_A_Failed_Shutdown_Fallback(string? parameterName)
+ {
+ _scenario.EnsureSidecarDirectory();
+ await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}"));
+ Exception failure = parameterName == "io"
+ ? new IOException("The shutdown failed.")
+ : new ArgumentException("The shutdown implementation rejected another parameter.", parameterName);
+ var shutdown = Substitute.For();
+ shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.FromException(failure));
+ var handoff = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown);
+
+ await Assert.That(async () => await handoff.PrepareAsync(
+ _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing();
+
+ _ = shutdown.Received(1).ShutdownAsync(Arg.Any(), Arg.Any());
+ _ = await _scenario.AssertNullSidecarAsync();
+ }
+
+ [Test]
+ public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_When_The_Ticket_Request_Fails_With_An_IO_Error()
+ {
+ _scenario.EnsureSidecarDirectory();
+ await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}"));
+ var files = new TestablyServiceFileSystem(_scenario.FileSystem);
+ var fileSystem = Substitute.For();
+ fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any())
+ .Returns(call => files.TryReadAllBytesAsync(call.Arg(), call.Arg()));
+ fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any())
+ .Returns(call => files.TryCreateExclusiveAsync(call.Arg(), call.Arg>(), call.Arg()));
+ fileSystem.When(static system => system.Rename(Arg.Any(), Arg.Any()))
+ .Do(call => files.Rename(call.ArgAt(0), call.ArgAt(1)));
+ var time = Substitute.For();
+ time.GetUtcNow().Returns(_scenario.Clock.GetUtcNow());
+ // Fail the ticket request's bound once, before transport can wrap the IOException;
+ // the shutdown fallback gets a working bound from the same clock seam.
+ time.CreateTimer(Arg.Any(), Arg.Any