diff --git a/CHANGELOG.md b/CHANGELOG.md
index 674bf241d..98b093cae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,21 +9,32 @@ Nightly builds of `master` are on
[GitHub Packages](README.md#nightly-builds-github-packages) as nightlies of the next version,
`{version}-nightly.{yyyyMMdd}.g{shortSha}`.
+The next SDK version is **2.0.0**, on the same opencode **2.3.0** pin already released in SDK 1.1.0.
+
### π₯ Breaking changes
- `OpenCodeServerOptions.ReadinessTimeout` now defaults to `Timeout.InfiniteTimeSpan`: a standalone start waits for readiness until its cancellation token fires, as opencode's CLI does. Before: `StartAsync()` failed after 60 seconds without a readiness line. After: set `ReadinessTimeout = TimeSpan.FromSeconds(60)` to keep that failure, an `OpenCodeServerException` naming the bound; a cancellation token bounds the wait too, but ends the start with `OperationCanceledException`.
- **A background service registered without a password is used, as opencode's CLI uses it.** `OpenCodeServer.Password` is `string?`: such a service is now discovered and reused, and its handle's `Password` is null. Before: `string password = server.Password;`. After: `string? password = server.Password;`.
+- `EventsClient.SubscribeAsync` now uses one shared background source per root client. Each enumeration is an independent subscription with 4,096 queued selected events allowed; the next refused selected offer discards that subscriber's backlog and throws `OpenCodeEventSubscriberOverflowException`. A sole subscriber's overflow stops the source.
+- The first `server.connected` is an admission marker, possibly cached and sharing its Id with neighbours, not a new physical connection or liveness proof. Earlier business events are not replayed. A later marker still announces a possible gap.
+- Ordinary event-attempt failures retry forever instead of giving up after a minute. API, transport and failure-frame exceptions are exposed on connection state rather than ending the subscription. Consumers that require a deadline own a cancellation token.
+- An unexpected source/cleanup fault ends admitted subscriptions after their queued prefix with the same exception; state watchers receive Idle. Cancellation still wins over a preserved prefix on a later pull.
### β¨ Added
- `OpenCodeServerStopOptions.Pty` accepts `OpenCodeServerStopPtyMode.Handoff` so that `StopAsync` attempts a best-effort persistent-terminal handoff after it reads the registration and before it signals the process. Follow it with `EnsureAsync` using the same registration selection to restart as the managed connection does; preservation depends on preparing and adopting the ticket before it expires. Null and `Clear` keep the default: terminals end with the service, as with the CLI's `service restart`.
- `Plugins.WaitForPluginsAsync` waits for a location's plugins to load, as the CLI does before listing agents, models and integrations; `LanguageModels.WaitForDefaultAsync` now runs it.
- `OpenCodeServer.ShutdownPersistentPtyAsync` discovers the background service and, when one is running, shuts down its persistent terminals, as opencode's CLI does before an uninstall; with no service it does nothing. It is experimental (`OPENCODE002`).
+- Virtual `EventsClient.GetConnectionState()` and `WatchConnectionAsync(CancellationToken)` expose `EventConnectionState` and `EventConnectionStatus` (Idle, Connecting, Connected, Reconnecting). Watches coalesce to the latest unread state and do not start or retain a source.
+- `OpenCodeEventSubscriberOverflowException.Capacity` reports the SDK's fixed 4,096 bound, including for instances constructed through its standard public constructors.
### π§ 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)
- 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.
+- Event idle detection keeps running while a consumer holds an event. Disposing an enumerator with a pending move is supported: an unsettled move ends false unless cancelled, and an already settled move keeps its result. Disposal drains unread data and later pulls end false, even after an earlier overflow, fault or root disposal, unless an entry token is cancelled.
- Background-service discovery (`OpenCodeServer.DiscoverAsync` and the probe `EnsureAsync` runs) now takes the client's proxy decision for a loopback service. Behind an environment proxy (`HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`), set `NO_PROXY` to reach a loopback service directly, as with opencode's CLI; behind a system proxy, that proxy's own bypass list applies, as it does for the client. .NET Framework is unchanged.
### π Fixes
diff --git a/Directory.Build.props b/Directory.Build.props
index c2ed9b0d1..60cccac4a 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -15,7 +15,7 @@
- 1.1.1
+ 2.0.0
Deniz Δ°rgin
Deniz Δ°rgin
Deniz Δ°rgin
diff --git a/GLOSSARY.md b/GLOSSARY.md
index dbb87ce07..0ca924617 100644
--- a/GLOSSARY.md
+++ b/GLOSSARY.md
@@ -394,6 +394,26 @@ An explicit, registered runtime exception to the fail-closed default.
The hand-written transport core where all request behavior lives; generated methods only delegate to
it.
+**Event feed**:
+The SDK's client-wide background source, reconnect loop and ordered fan-out of the Live event
+stream. It decodes the bus once and shares Event references; ordinary attempt failures retry
+without end and are reported through Connection state.
+
+**Event subscription**:
+One enumeration of SubscribeAsync, with its own call-time, local, exact-ordinal Event selection and
+up to 4,096 queued selected Events. A null or empty selection takes every Event, and connection
+markers always pass. A source fault leaves its queued prefix readable before the same exception
+is thrown.
+
+**Subscriber overflow**:
+The ending when an Event subscription cannot queue its next selected Event. It discards that
+subscription's unread backlog and ends it alone, while other subscriptions continue.
+
+**Connection state**:
+The Event feed's Idle, Connecting, Connected or Reconnecting snapshot, with its retry count and
+last classified exception. Its watch coalesces to the latest unread state and never keeps a source
+alive; the state is neither an Event position nor a liveness or resynchronization barrier.
+
**Envelope**:
The generated, typed response object of one operation, carrying its status and error state and its
named payload properties.
diff --git a/README.md b/README.md
index 5a3ea18cb..db5229d13 100644
--- a/README.md
+++ b/README.md
@@ -385,9 +385,11 @@ has the two properties to set.
## Known Issues
- **The event bus has no replay.** `EventsClient.SubscribeAsync` is a live stream: events published
- while you are disconnected are lost, and a consumer slower than the producer can overflow and
- fail the stream. This is the server's contract, not an SDK limitation. See the
- [streaming guide](https://github.com/opencode-dotnet/opencode-sdk-dotnet/blob/master/docs/guide/streaming.md).
+ while you are disconnected are lost. The SDK shares one source per client and bounds each
+ subscription to 4,096 queued selected events; the next refused offer ends that subscriber with
+ `OpenCodeEventSubscriberOverflowException`. Recover by resubscribing, awaiting admission, then
+ refreshing and applying the buffered tail idempotently. See
+ [overflow recovery](https://github.com/opencode-dotnet/opencode-sdk-dotnet/blob/master/docs/guide/streaming.md#-recovering-after-subscriber-overflow).
- **A CLI-started server's durable session event stream holds only the sync marker.** It reads from
the server's event store, and the distributed `opencode` CLI starts its server without event
diff --git a/docs/adr/0007-error-model.md b/docs/adr/0007-error-model.md
index 400ea2872..0a1a494a7 100644
--- a/docs/adr/0007-error-model.md
+++ b/docs/adr/0007-error-model.md
@@ -1,6 +1,6 @@
# Error model: typed exception spine carrying tagged error data
-Date: 2026-10-16
+Date: 2026-11-15
API failures throw through a typed exception spine (`OpenCodeException` β
`OpenCodeApiException`) by default; per-call `NoThrow` returns them on the response spine.
@@ -9,10 +9,13 @@ no arbitrary header dictionary (sealed 2026-08-26; internal research, 2026-08-25
coverage-program grilling seal?").
Streams and automatic cursor traversals take the shared `OpenCodeRequestOptions`.
-`Location` applies to each stream connection attempt and every page request. A stream yields
+`Location` applies to other streams' connection attempts and every page request; the shared event
+bus accepts but ignores per-call Location and follows ADR-0041. A stream yields
an `IAsyncEnumerable` rather than a response envelope, so it has no envelope to carry an
API error; streams and automatic traversals refuse `NoThrow` at the call, before enumeration,
-and always throw API errors when encountered. Explicit page methods retain `NoThrow`.
+and other streams and automatic traversals throw API errors when encountered. The shared event
+bus reports ordinary attempt errors on connection state while retrying (ADR-0041).
+Explicit page methods retain `NoThrow`.
On `event.subscribe`, per-call `NetworkTimeout` is refused, including
`Timeout.InfiniteTimeSpan`: its 2-second connection and default 45-second idle windows follow
upstream's first-party behavior. Other streams apply `NetworkTimeout` only while opening;
@@ -23,7 +26,8 @@ surface is chosen over a dedicated stream options type so callers use the same p
location and behavior vocabulary. The trade-off is that the compiler cannot prevent a caller
from selecting a member a stream or traversal must refuse at run time.
-Transport and protocol failures always throw `OpenCodeTransportException`. The spec's tagged error
+Outside the shared event bus's retry loop, transport and protocol failures throw
+`OpenCodeTransportException`. The spec's tagged error
payloads are generated as typed models under an `OpenCodeError` base and ride **as data** on either
channel, pattern-matchable without string sniffing. There is no client-level switch. Throwing API
errors retain the raw body on `OpenCodeApiException`; `NoThrow` responses retain it on their shared
diff --git a/docs/adr/0021-normal-pty-public-surface-hand-written.md b/docs/adr/0021-normal-pty-public-surface-hand-written.md
index 2e33d0481..1f9f0a504 100644
--- a/docs/adr/0021-normal-pty-public-surface-hand-written.md
+++ b/docs/adr/0021-normal-pty-public-surface-hand-written.md
@@ -24,9 +24,11 @@ input, a cursor domain without a live-only mode, no pre-upgrade existence check)
families' public doors are hand-written over generated internal raw clients and share one
family-neutral socket core behind named decode, close, and upgrade seams.
-The Events family's public door is hand-written over its raw client, so behaviour above the
-generated stream belongs to hand-written code. Its raw endpoint, routes, adapters, wire models and
-serializer metadata stay generated; its signature and SSE behaviour are the generated stream method's.
+The Events family's public door owns the shared feed and local selection (ADR-0041), opening physical
+attempts through the generated route and adapter on the stream plane rather than delegating to its
+raw twin's subscribe method. The raw endpoint, routes, adapters, wire models and serializer metadata
+stay generated; the public subscription signature stays stable while its runtime contract belongs
+to hand-written code.
## Considered options
diff --git a/docs/adr/0041-one-shared-event-feed-per-client.md b/docs/adr/0041-one-shared-event-feed-per-client.md
new file mode 100644
index 000000000..0b43f614a
--- /dev/null
+++ b/docs/adr/0041-one-shared-event-feed-per-client.md
@@ -0,0 +1,71 @@
+# One shared event feed per client
+
+Date: 2026-11-15
+
+The default Events door follows the pinned first-party shared-feed model: one lazy physical source
+per root client, with an independent subscription per enumeration. A feed gate makes admission,
+marker replay, selected publication, endings and source state atomic. Reference identity fences
+retired generations; an observed runner ledger owns cleanup after synchronous logical detachment.
+This replaces pull-only per-enumeration connections so one consumer cannot postpone idle detection
+for the others, and several consumers do not duplicate wire traffic and decoding.
+
+## Contract and trade-offs
+
+- Each subscription allows 4,096 queued selected events. The next refused selected offer ends only
+ that subscription and releases its backlog. A pending move's direct handoff takes no queue slot.
+ A sole subscriber's overflow stops the source. The limit counts events, not bytes, and there is
+ no subscriber-count limit.
+- The latest cached `server.connected` marks admission in the feed's fan-out order, not liveness or a
+ new server connection. Its Id can be shared. Earlier business events are not replayed; a later
+ marker announces a possible gap. Recovery admits a replacement before refreshing, then applies
+ its buffered tail idempotently and restarts if that replacement overflows. Exactly-once and
+ cross-operation transactional snapshots are not promised.
+- Types are copied and validated at the call and matched locally, ordinally, with markers always
+ included. The source sends no Types query and only the ambient Location header. It decodes the
+ whole bus once, shares event/metadata references and couples malformed unselected traffic to the
+ shared attempt. Consumers treat payload graphs as read-only.
+- Ordinary failures retry forever with fixed connect, idle and retry windows. Virtual snapshot and
+ coalescing-watch members expose the last classified Exception, the retry counter and Idle when
+ no source exists. They are not a transition log, cursor or liveness barrier. Watchers neither
+ open nor retain a source.
+- An escaping source/cleanup fault detaches the generation, publishes Idle and preserves each
+ subscription's queued prefix before the same exception. Any still-current runner completion
+ takes this path, including cancellation and unexpected normal return. New admission starts fresh.
+- A settled move is immutable. A live caller token wins over unread data and every stored ending
+ on later selections; otherwise a prefix precedes its first stored fault. Explicit enumerator
+ disposal drains unread references and later pulls end false unless cancelled, without changing
+ a move already settled. Root disposal closes admission before lifetime/transport cleanup and
+ does not rewrite subscriptions already ended by source fault.
+- Physical stop uses the sanctioned worker-cancellation helper. Runner and cancel completion are
+ both observed before CTS disposal. Retired cancel failures are recorded and dropped; they cannot
+ poison a replacement. Pipeline remains Events-neutral through its owned-resource hook.
+
+## Considered options
+
+- Retain pull-only connections: rejected because a held event pauses detection and every consumer
+ duplicates I/O. A second opt-in feed door would leave the default first-party model inconsistent.
+- Await a full queue, drop items, or use an unbounded queue: rejected because one slow subscriber
+ would stall neighbours, silently lose data, or grow without its explicit overflow boundary.
+- Reconnect/resignal every subscriber for a late joiner: rejected because joining would disrupt
+ healthy neighbours merely to manufacture a fresh marker. Replay remains marker-only admission.
+- Discard a source-fault prefix: rejected; upstream preserves that valid prefix. Preserve an earlier
+ fault after explicit disposal: rejected; upstream later pulls end done after iterator return.
+- Keep a minute give-up or add backoff/configurable capacities: rejected. Observable connection
+ state supplies the missing failure channel, and fixed policy follows the pinned first-party model.
+- Deep-copy each payload: rejected because sharing is upstream's model and copying adds whole-graph
+ cost. Immutable treatment is documented rather than falsely implied by IReadOnlyDictionary.
+
+## Divergences and reversal triggers
+
+Retry composes inside the SDK source where upstream's shared layer and Solid split those layers.
+Cancellation throws OCE, including over a fault-preserved prefix or a stored overflow ending,
+because that is the SDK-wide cancellation contract; upstream abort returns done while subscribed
+and leaves a stored ending unchanged after source completion or overflow. Exception-valued Error, explicit Idle and the
+typed overflow exception are idiomatic .NET forms. Standard public exception constructors remain
+available and Capacity always reports the SDK's bound. Current runtime canon records these and the
+omitted application facilities (history, resync, lifecycle, re-resolution, batching and onActivity).
+Revisit with a corresponding upstream contract change, a change to the SDK cancellation contract,
+or a concrete consumer need. A one-off preference does not silently change the shared policy.
+
+The hand-written runtime/error-channel breaks require SDK 2.0.0 under ADR-0034. This does not move
+the protocol pin: opencode 2.3.0 already shipped with SDK 1.1.0.
diff --git a/docs/architecture/client-runtime.md b/docs/architecture/client-runtime.md
index ec4a54610..487e68987 100644
--- a/docs/architecture/client-runtime.md
+++ b/docs/architecture/client-runtime.md
@@ -82,10 +82,21 @@ upstream's behaviour. Each one is listed, with its reason, in the section it con
`OPENCODE_*` credential variable.
`Pipeline` owns construction, the policy roster, the one-shot plane and disposal orchestration.
+Its Events-neutral `RegisterOwned(IDisposable)` hook lets a hand-written family door register a
+root-owned resource. Registration and disposal share one atomic start boundary: later registration
+throws, and a later or concurrent disposal returns immediately, even while the first cleanup is held.
+The first disposal takes the owned list and disposes it once in reverse registration order, before
+beginning lifetime cancellation and the existing transport/lifetime cleanup chain. Nested finally
+blocks preserve cleanup when an owned dispose fails; a later failure masks an earlier one.
`ClientLifetime` owns root admission state and the saved lifetime token; `PipelineExchange` creates
messages and dispatches them through that roster. `StreamPlane` owns a single stream's opening,
-status and media walls, framing and response lifetime. `ReconnectingEventStream` owns the reconnect
-loop and its live caller/disposed ordering, using `StreamAttempt` for each attempt's windows.
+status and media walls, framing and response lifetime. The Events door composes one `SharedEventFeed`
+and registers it with the pipeline. The feed owns source generations, subscriptions, coalescing state
+watchers and the runner ledger. `EventSourceRunner` reads physical attempts independently of consumer
+pulls, using `StreamAttempt` for their windows. Every source callback is identity-fenced under the
+feed gate; cancellation and resource cleanup run after the gate. Retired runner and worker-cancel
+tasks remain observed, and a source's CTS is released only after both complete. A retired cancel
+failure is recorded and dropped. Synchronous root disposal fences mutation, not runner completion.
`OperationTraits` supplies per-operation rules once through `OperationRequest.Describe`; the exchange
resolves the message's network window from those carried traits.
@@ -96,12 +107,15 @@ resolves the message's network window from those carried traits.
- `OpenCodeRequestOptions.Location` overrides that directory per call. A set `Directory` wins;
a null selector or directory inherits the ambient value. Blank values are refused, so a caller
can inherit or replace the ambient directory but cannot clear it for one call.
+ `event.subscribe` is the exception: it accepts a per-call Location but does not send it; its
+ shared source sends only the client's ambient header snapshot.
- The directory is percent-encoded before it rides the header; the server percent-decodes it.
This applies to both the ambient snapshot and per-call overrides, including Unicode paths.
- An operation's declared `location[directory]` query is a separate channel, emitted by
`QueryStringBuilder.AddLocation`. It does not participate in the ambient/per-call header merge.
- The server ignores the directory header on operations that resolve location from a session
- or do not resolve location. The SDK sends it uniformly and adds no per-route validation.
+ or do not resolve location. Apart from the shared event source's ambient-only rule, the SDK sends
+ the merged header uniformly and adds no per-route validation.
- The pinned server has no workspace targeting channel, so none exists in the public selector or
in the header/query serializers. A generated wire model may still contain a workspace ID
when its own pinned component declares one; that is not a request-targeting channel.
@@ -114,9 +128,9 @@ resolves the message's network window from those carried traits.
`internalRaw` curation emission. Everything else the family needs β routes, query shapers,
response adapters, status verdicts, wire models, envelopes, and serializer metadata β stays
generated, so route, status, and schema drift still breaks compilation locally (ADR-0021).
-- The hand-written doors keep the generated family's shape: the protected mocking constructor,
- `virtual` members, and the `MockSeam` guard. Each door delegates once into its raw twin and
- adds nothing but the knowledge generation may not import.
+- The hand-written doors keep the protected mocking constructor, `virtual` members, and the
+ `MockSeam` guard. The PTY doors delegate once into their raw twins and add the knowledge generation
+ may not import. The Events door owns sharing and local selection over a generated route and adapter.
- `CreateConnectTokenAsync` is that knowledge. The server's connect-token handler requires a
fixed `x-opencode-ticket` value that exists only in upstream implementation source, which
ADR-0013 forbids importing into generation; the constant therefore lives in the hand-written
@@ -132,9 +146,12 @@ resolves the message's network window from those carried traits.
only generated internal-raw methods feed it, and only a parameter the pinned document declares
ever becomes an entry.
- The Events family is the third: `EventsClient` is hand-written over the generated internal
- `EventsRawClient`, under the same `internalRaw` emission (ADR-0021). Its signature and SSE
- behaviour are the generated stream method's; the raw endpoint, routes, adapters, wire models
- and serializer metadata remain generated.
+ `EventsRawClient`, under the same `internalRaw` emission (ADR-0021). Its subscription signature is
+ unchanged; the shared feed opens the generated route and adapter directly through `StreamPlane`.
+ `Pipeline.ExecuteStreamAsync` refuses reconnecting operations, after disposed/argument/options
+ checks and before any request, so the raw method cannot become a one-shot alternative. The
+ `event.subscribe` traits row remains. The raw endpoint, routes, adapters, wire models and serializer
+ metadata remain generated (ADR-0041).
### PTY WebSocket session
@@ -362,10 +379,14 @@ resolves the message's network window from those carried traits.
token-identity guarantee.
- Disposing the root client interrupts its in-flight HTTP operations and SSE streams and reports
`ObjectDisposedException`; caller cancellation already observed for the same failure takes
- precedence. A terminal session owns its connection separately: its session-disposal rules apply.
+ precedence. Event subscriptions already ended by a source fault are detached and retain their
+ queued prefix and fault; root disposal does not replace those endings. A terminal session owns
+ its connection separately: its session-disposal rules apply.
- Streaming operations take `OpenCodeRequestOptions` and return a stream rather than a response
- envelope. Per-call `Location` applies to every connection attempt; `NoThrow` and an undefined
- `ErrorBehavior` are refused at the call, before enumeration. Their failures always throw (ADR-0007).
+ envelope. Per-call `Location` applies to other streaming operations; `event.subscribe` accepts but
+ ignores that override. `NoThrow` and an undefined `ErrorBehavior` are refused at the call, before
+ enumeration. Declared errors on ordinary streams throw; ordinary event-attempt failures appear on
+ connection state while the shared source retries (ADR-0007, ADR-0041).
- Network progress is bounded by a per-read window: the send and every buffered body read must
progress inside it, and each read that progresses re-arms it, so a slow-but-flowing body
survives while a stalled one fails. Its length is the call's `OpenCodeRequestOptions.NetworkTimeout`
@@ -415,13 +436,37 @@ resolves the message's network window from those carried traits.
## Server-sent events
-- Streams are exposed as `IAsyncEnumerable` and open lazily on first enumeration.
-- Cancellation closes the stream through the enumeration token. On every target, caller cancellation
- or root-client disposal releases the live response even while the consumer holds a yielded event.
- Response disposal also interrupts downlevel reads that do not observe an async read token;
- disposal-induced failures use the cancellation and disposal rules in Error channels.
-- `event.subscribe` reconnects as upstream's first-party client does (`client/src/solid/connection.ts`
- at the pin), and no other stream reconnects:
+- Streams are exposed as `IAsyncEnumerable` and open lazily on the first move. Other streaming
+ operations remain one-shot, pull-driven streams; only `event.subscribe` has a shared background source.
+- Other streams close their owned response on caller cancellation or root disposal, including while
+ a consumer holds an item. Response disposal also interrupts downlevel reads that ignore a read token;
+ failures follow the cancellation and disposal ordering in Error channels.
+- Each enumeration is an independent subscription to one shared background source per client.
+ Calling `SubscribeAsync` captures and validates Types, but neither the call nor `GetAsyncEnumerator`
+ admits a subscription or opens I/O. The first live move admits it under the same gate as publication.
+- The first `server.connected` marks admission, not liveness; earlier business events are not replayed.
+ From admission on, every selected event fanned out by the feed is offered in source read order until
+ the subscription ends. An event read before admission but published through the gate afterwards is
+ included. A cached marker is handed over before later publications and may share its Id with other
+ subscriptions; it is the latest marker published by the source. A join during a drop waits for
+ the next validated marker. No business history is replayed.
+- A later marker announces a possible gap: refresh authoritative state. Event objects are shared references; treat them as read-only.
+ Payload graphs and metadata dictionaries are not deep-frozen. Sharing also shifts wire and decode
+ cost to the whole bus, once per client. Invalid JSON in unselected traffic fails the shared attempt
+ for every subscriber; tolerated payload skew still arrives through the existing unknown arm.
+- EventSubscribeRequest.Types is local selection captured and validated at the call. Null or an
+ empty list selects everything; comparisons are exact ordinal spellings, RPC names have no wildcard,
+ and typed or drifted server.connected markers are always selected. No physical attempt sends types.
+ A per-call Location is accepted but not sent: every attempt sends the ambient client snapshot.
+- A subscription retains at most 4,096 queued selected events. Overflow ends only that subscription and discards its backlog.
+ Direct handoff to a pending move, including admission-marker replay, consumes no queue slot.
+ After 4,096 queued events the next refused selected offer stores one
+ `OpenCodeEventSubscriberOverflowException` with message
+ `Event subscriber exceeded its 4096-event capacity`. Capacity always reports the SDK's 4,096 bound,
+ including on consumer-constructed exceptions. Unselected events consume no capacity. Subscriber count
+ and payload size are unbounded; the count bound is not a byte or client-wide memory bound.
+- The source retries ordinary attempt failures forever, 1 s apart without backoff; connection state reports the last classified failure.
+ The transport windows follow upstream's first-party client at the pin:
- Each attempt has 2 s to answer and deliver `server.connected` as its first event, or it fails.
The first open runs the same check. If the connect bound passes before response headers arrive,
the failure says "The opencode server did not answer the event stream request within 2 seconds."
@@ -431,43 +476,68 @@ resolves the message's network window from those carried traits.
`OpenCodeClientOptions.EventStreamIdleTimeout`, as upstream's `idleTimeout` option sets it. The
option accepts any window above zero and at most `int.MaxValue` milliseconds, but no window
that never ends, since upstream has none; it is read once, when the client is built.
- Any byte re-arms the window, including the server's keepalive comment every 15 s. The window
- stops while the consumer holds an event, because a pull-based consumer's own time is not the
- server's silence.
+ Any byte re-arms the window, including the server's keepalive comment every 15 s. The source
+ keeps reading, so idle detection continues while a consumer holds an event. Pre-marker bytes
+ do not extend the connect bound.
- Every failure is followed by a new attempt 1 s later, with no backoff. That covers a refused
connection, any HTTP error status (a 401 or a 404 included), an undeclared success, a body that
is not an event stream, malformed framing or JSON, a payload neither its primary nor its
unknown-arm metadata can materialize, a failure frame, the server ending the stream, and either
window passing. Tolerated payload skew is not a failed attempt.
- - No replay is requested. Each connection yields its own `server.connected`, so a second one
- tells the consumer that events published in between are gone and authoritative state should be
- refreshed.
- - A stream that has failed every attempt for 1 minute gives up and throws the last failure. The
- minute runs from the drop, or from the first attempt for a first open, and it stops once an
- attempt delivers `server.connected`. When it passes, it cuts whatever is in flight. A window
- passing surfaces as `OpenCodeTransportException`, never as a cancellation.
- - Caller cancellation or root-client disposal releases the live connection at once, including while
- the consumer holds an event. An opening, reading, or reconnecting wait ends with the cancellation
- or disposal exception specified in Error channels; a suspended enumeration reports it on its next
- pull. Nothing else ends it except the give-up window.
- - Recorded divergences, both intended:
- - Upstream retries forever and shows a connection status; the SDK has no status to show, so an
- endless silent retry would hang `await foreach`. The consequence for consumers is that a wrong
- address or a refused credential surfaces after one minute, not at once, as the error the server
- last answered. It reverses if the SDK gains a connection-status surface a consumer can watch,
- which would let it retry forever as upstream does.
- - Upstream's clients read the bus on a background loop into a 4,096-event queue per subscriber
- and fail a subscriber that falls behind (`client/src/shared-events.ts` at the pin). The SDK
- reads only when the consumer pulls, as .NET's `IAsyncEnumerable` model does, so back-pressure
- and pacing stay with the consumer, and it runs no background reader, no per-subscriber queue
- and no drop policy of its own. The consequences: a long-held event delays noticing a lost
- server, and a backlog sits in TCP and in the server's own 4,096-event limit. The streaming
- guide's live-bus section shows the short loop that hands events off. It reverses if upstream's
- first-party bus stops reading ahead of its consumer, or if a consumer need appears that pulling
- can't meet, such as noticing a lost server while an event is held.
- - `OpenCodeClientOptions.NetworkTimeout` does not reach `event.subscribe`, and a non-null per-call
- `NetworkTimeout` is refused, including `Timeout.InfiniteTimeSpan`. The 2 s connect bound and the
- 1 s delay are fixed, as in upstream; per-call `Location` is sent on every reconnect attempt.
+- GetConnectionState returns a gate-selected EventConnectionState without opening I/O.
+ WatchConnectionAsync selects the initial snapshot atomically with registration and then coalesces
+ to the latest unread state; it is not a transition log. Watchers never start or keep a source alive.
+ SDK snapshots are Idle(0, null) before admission, after last leave and after an escaping source fault;
+ Connecting(0, null) on first admission; Connected(0, null) after a validated first marker; and
+ Reconnecting(attempt, error) after failure. The loop counter resets when a connection lived at
+ least one monotonic second, then increments to 1 on its drop; a shorter connection retains the
+ counter even though Connected publishes 0. Error is retained through the next opening and cleared
+ on Connected or Idle. State is source-level, not a subscriber position or a liveness guarantee.
+- An escaping source fault preserves each subscription's queued prefix, then throws the same exception.
+ The current generation detaches first and watchers receive Idle with no error. Any still-current
+ runner completion, including cancellation or normal return, takes this path with a synthesized
+ exception when necessary. A new admission starts a fresh generation and counter. Retired completions
+ are observed without changing the replacement's state, marker or registry.
+- Live cancellation wins over unread data and stored endings, but never changes an already settled move.
+ Selection under the gate is: an already settled move; live entry-token cancellation; unread data;
+ the first stored ending; otherwise install a pending move or hand over an offered item. A settled
+ move clears its pending slot, and only SourceFault preserves a backlog. Cancellation, overflow,
+ enumerator disposal and root disposal discard it. A later cancellation also discards a preserved
+ fault prefix and wins on all later pulls, with the public token-identity rule in Error channels.
+- Enumerator disposal discards unread data and later pulls end false unless an entry token is cancelled.
+ A move settled before DisposeAsync keeps its item or error. An ordinary unsettled move ends false;
+ a live cancelled token gives OCE. Explicit disposal never revives a stored overflow/fault/root
+ ending on a later pull. Concurrent moves are refused without ending the first one. Root disposal
+ closes admission and ends registered subscriptions/watchers with ODE; an already fault-ended
+ subscription retains its prefix and fault unless explicitly disposed or cancelled.
+- Caller cancellation and enumerator disposal end only that subscription. Last leave detaches and
+ clears the cache/state under the gate, then requests worker-based cancellation. Its failure is
+ recorded and dropped after retirement; CTS disposal waits for both runner and cancellation tasks.
+ Response disposal interrupts downlevel reads that do not observe an async read token. Root disposal
+ fences the feed before beginning pipeline lifetime cancellation and transport cleanup.
+- OpenCodeClientOptions.NetworkTimeout does not reach event.subscribe. Any non-null per-call
+ NetworkTimeout is refused, including Timeout.InfiniteTimeSpan. NoThrow and undefined ErrorBehavior
+ values are refused at the call. Ordinary API, transport and failure-frame errors are connection-state
+ errors, not enumeration endings; a consumer that needs a deadline owns its token and reads state.
+- Overflow recovery is resubscribe, await admission, then refresh authoritative state while the new
+ tail buffers, then apply that tail idempotently. Restart at admission if the replacement overflows;
+ refresh again on a later marker. This assumes ordinary reads reflect a change no later than its event
+ is published. There is no verified cross-operation snapshot or exactly-once merge guarantee.
+- Recorded divergences and omissions (ADR-0041):
+ - Upstream's shared layer ends subscribers on a source failure and Solid retries above it; the SDK
+ composes retry inside its one shared source. Revisit if upstream changes those layer boundaries.
+ - Upstream abort ends with done and, after source completion or subscriber overflow, no longer
+ overrides the stored ending. The SDK's public cancellation contract requires OCE and live
+ cancellation over a fault-preserved prefix or a stored overflow ending.
+ Revisit only with a change to that SDK-wide contract. Prefix preservation on source fault itself
+ follows upstream and is not a divergence.
+ - Error is an Exception rather than a message, Idle explicitly represents no source, and overflow
+ has a typed SDK exception with the upstream message and capacity. These are idiomatic .NET forms
+ of the same facts; revisit if the corresponding upstream contract changes.
+ - There is no onActivity callback: the source already runs the byte watchdog independently of
+ consumers. Solid's error history, resync, page lifecycle, server re-resolution and flush batching
+ are application responsibilities, not a second SDK control plane. Revisit with a concrete
+ consumer need or a change in upstream's first-party shared-feed contract.
- Durable continuation is requested explicitly through `experimental.session.log`'s `after` parameter, an
exclusive aggregate sequence read from a durable envelope or from the sync marker. One
`log.synced` marker reports the watermark the replay was captured at; it is a boundary rather
diff --git a/docs/architecture/platform-and-packaging.md b/docs/architecture/platform-and-packaging.md
index 7b26c8134..e45634a68 100644
--- a/docs/architecture/platform-and-packaging.md
+++ b/docs/architecture/platform-and-packaging.md
@@ -90,10 +90,11 @@ Two separate API vintages shape the downlevel legs, and conflating them would mi
## Dependencies
-- Terminal sessions use `System.Threading.Channels` for their internal receive queue. The
+- Terminal sessions and event subscriptions use `System.Threading.Channels` for their internal queues. The
SDK declares that bridge package directly for `net472` and `netstandard2.0`; modern targets
use the inbox implementation. Channel types are not part of the public SDK API.
-- The pipeline's progress window and the launcher's early-end drain run on `TimeProvider`, so a
+- The pipeline's progress window, event attempt/retry timing and monotonic connection duration,
+ and the launcher's early-end drain run on `TimeProvider`, so a
test can run either bound on a clock it moves itself. The SDK declares
`Microsoft.Bcl.TimeProvider` for `net472` and `netstandard2.0`; modern targets use the inbox
type. `TimeProvider` is not part of the public SDK API.
diff --git a/docs/architecture/protocol-and-generation.md b/docs/architecture/protocol-and-generation.md
index ceafde31a..a1431bf4b 100644
--- a/docs/architecture/protocol-and-generation.md
+++ b/docs/architecture/protocol-and-generation.md
@@ -481,6 +481,11 @@ materializable.
payload, frame, declared failure event, typed cause, and statuses from the pin. Cause models,
converters, array metadata, and adapter metadata pass through the same emitted registry and
System.Text.Json source-generation compile proof as payload models (ADR-0008, ADR-0015).
+ The Events door captures local selection instead of forwarding its request/options to a raw
+ subscribe call. Its attempt source uses the generated route without Types and the generated
+ adapter directly on StreamPlane, retaining every status, framing and materialization wall.
+ Reconnecting operations are refused by the generic stream entry; no alternate one-shot Events
+ stream is exposed. Other generated streaming operations keep their existing one-shot semantics.
- Exclusion is reserved for transports the HTTP pipeline cannot carry, such as a WebSocket upgrade.
Every excluded operation is fingerprint-pinned so protocol drift forces review (ADR-0008).
- Unknown response media types fail generation. Supported non-JSON response bodies follow the
diff --git a/docs/guide/errors-and-responses.md b/docs/guide/errors-and-responses.md
index 2d22f663c..9dc44b3a1 100644
--- a/docs/guide/errors-and-responses.md
+++ b/docs/guide/errors-and-responses.md
@@ -90,14 +90,16 @@ Three limits worth internalising:
- **`NoThrow` covers declared API errors only.** It never suppresses a transport failure.
- **Streams and automatic cursor traversals refuse `NoThrow` at the call, before enumeration.**
- They take `requestOptions`, but their API errors always throw. A stream has no response envelope
- to carry an error. See [streaming](streaming.md#-streams-always-throw) and [pagination](pagination.md).
+ They take `requestOptions`, but have no response envelope to carry an error. Other streams and
+ automatic traversals throw API errors; the shared event bus reports ordinary attempt failures
+ on connection state while retrying. See [streaming](streaming.md#-stream-error-channels) and [pagination](pagination.md).
- **`Plugins.WaitForPluginsAsync` and `LanguageModels.WaitForDefaultAsync` refuse `NoThrow` at the call,**
because they decide on each plugin-list answer whether to keep waiting.
`OpenCodeRequestOptions` also carries `Location`, the per-call directory override, which merges over
the client's ambient location member by member β a set member wins, an unset one inherits.
-Streams apply it on every connection attempt and traversals on every page request; the server may
+Other streams apply it on every connection attempt and traversals on every page request. The shared
+event bus accepts but ignores per-call Location and sends only the ambient client snapshot. The server may
ignore it on a route that resolves location from a session or needs no location.
## π·οΈ The typed error family
diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md
index d960a7b75..7bb4716b3 100644
--- a/docs/guide/getting-started.md
+++ b/docs/guide/getting-started.md
@@ -138,7 +138,7 @@ event published before you listen is gone.
using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(5));
await using var events = client.Events.SubscribeAsync(cancellationToken: deadline.Token).GetAsyncEnumerator();
-// The first event is server.connected: from here on, nothing the session publishes is missed.
+// server.connected marks admission to the bounded shared feed, not liveness or replay of earlier business events.
await events.MoveNextAsync();
await session.PromptAsync(new SessionPromptRequest { Text = "Summarize this repository." }, cancellationToken: deadline.Token);
diff --git a/docs/guide/streaming.md b/docs/guide/streaming.md
index a643ca6a4..9eeeca35f 100644
--- a/docs/guide/streaming.md
+++ b/docs/guide/streaming.md
@@ -10,7 +10,7 @@ process, and the **durable session event stream** for one conversation.
- [π A single session's log](#-a-single-sessions-log)
- [π§© Unknown events do not break your consumer](#-unknown-events-do-not-break-your-consumer)
- [βΉοΈ Cancellation and lifetime](#οΈ-cancellation-and-lifetime)
-- [π₯ Streams always throw](#-streams-always-throw)
+- [π₯ Stream error channels](#-stream-error-channels)
## π The live event stream
@@ -197,7 +197,7 @@ the server is stopping, and the server resumes the turn after it restarts, with
`SessionExecutionStarted`. One exception at opencode v2.3.0: a Reject without a `Message` also ends
the turn with `Shutdown` while the server keeps running, and that turn resumes after a later
restart (open upstream as [anomalyco/opencode#54180](https://github.com/anomalyco/opencode/issues/54180)). The bus [reconnects](#-a-live-bus-that-reconnects) by itself once the
-server is back within a minute, so to follow the resumed turn keep reading and wait the same way.
+server is back, so to follow the resumed turn keep reading under your own deadline.
Match the three on their wire `Type`, not on their .NET type. A turn-end event whose payload has
drifted from its declared shape arrives as `UnknownEvent`, so a typed match would never see it and
@@ -222,15 +222,15 @@ static string? SessionOf(IEvent @event) => @event switch
};
```
Open the bus **before**
-you prompt, because an event published before you listen is gone; the first event,
-the `server.connected` frame, says the stream is live:
+you prompt, because earlier business events are not replayed; the first `server.connected`
+marks this subscription's admission to the client's shared feed, not liveness:
```csharp
var session = client.Sessions.GetSessionClient(sessionId);
using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(5));
await using var events = client.Events.SubscribeAsync(cancellationToken: deadline.Token).GetAsyncEnumerator();
-// The first event is server.connected: from here on, nothing the session publishes is missed.
+// Admission comes first: selected fan-out offers now reach this bounded, volatile subscription.
await events.MoveNextAsync();
await session.PromptAsync(new SessionPromptRequest { Text = "Summarize this repository." }, cancellationToken: deadline.Token);
@@ -268,7 +268,7 @@ var session = client.Sessions.GetSessionClient(sessionId);
using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(5));
await using var events = client.Events.SubscribeAsync(cancellationToken: deadline.Token).GetAsyncEnumerator();
-// 1. The stream is ready once its first event, server.connected, has arrived.
+// 1. This subscription is admitted after server.connected, which may be a cached marker.
if (!await events.MoveNextAsync() || events.Current.Type is not "server.connected")
{
throw new InvalidOperationException("The event stream did not start with a server.connected frame.");
@@ -310,10 +310,11 @@ while (!turnEnded && await events.MoveNextAsync())
}
```
-- **Open the bus first, and wait for a `server.connected` frame.** The server sends it to every new
- subscriber before anything else, so once it has arrived, nothing the session publishes is missed.
- Upstream's client and the SDK both fail a connection that starts with anything else, and
- upstream's CLI waits for this event before it sends a prompt.
+- **Subscribe first and wait for `server.connected`.** It marks admission in the shared feed's
+ fan-out order. Every later selected offer is ordered after it, until the subscription ends;
+ prior business history is not replayed. An already-read event published through the feed after
+ admission is included. The marker may be cached and share its Id with neighbours, so it is not
+ a liveness probe. A physical connection must still start with a validated marker.
- **Filter by session once.** Every typed event that belongs to a session implements
`ISessionScopedEvent`, and `SessionOf` also reads the session of an `UnknownEvent` from its
payload, so one check keeps this session's events, drifted ones included, and the `switch` below it
@@ -336,8 +337,9 @@ while (!turnEnded && await events.MoveNextAsync())
Messages already settled are on the session too: `EnumerateMessagesAsync` returns them, with each
text content in its final form.
-`EventSubscribeRequest.Types` filters by event type; the initial `server.connected` still arrives.
-Omit `Types` to receive every event:
+`EventSubscribeRequest.Types` is copied and validated at the call and filters locally by exact,
+ordinal type spelling. RPC names have no wildcard; typed and drifted `server.connected` markers
+always pass. Null or an empty list receives every event. Physical attempts send no Types query:
```csharp
await foreach (var @event in client.Events.SubscribeAsync(
@@ -347,38 +349,40 @@ await foreach (var @event in client.Events.SubscribeAsync(
}
```
-**This stream is live and volatile, by the server's design, not the SDK's.** It has no cursor,
-no replay, and no resume channel:
+**This stream is live and volatile.** It has no cursor, business replay or resume channel:
- Events published while you were disconnected are **gone**. There is no backfill to ask for.
-- A consumer slower than the producer can overflow and fail the stream.
+- The SDK admits 4,096 queued selected events per subscription; the next refused selected offer
+ ends only that subscriber with `OpenCodeEventSubscriberOverflowException` and discards its backlog.
+ Direct delivery to a pending move takes no queue slot. The bound counts events, not bytes;
+ subscriber count and payload sizes are unbounded.
+- The whole bus is decoded once per client and event/metadata objects are shared references.
+ Treat those graphs as read-only. Malformed unselected traffic can reconnect every subscriber;
+ the existing payload-skew tolerance remains.
### π A live bus that reconnects
-The SDK **reconnects** the bus the way upstream's own client does, and it tells you when it did:
+The SDK owns one lazy background source per client while an event subscription remains admitted:
- A connection that drops, fails, or goes 45 seconds without a byte is replaced one second later.
- The server's keepalive every 15 seconds keeps a quiet bus open, and the time your code spends on
- an event never counts as silence. `OpenCodeClientOptions.EventStreamIdleTimeout` sets another
+ The server's keepalive every 15 seconds keeps a quiet bus open. Reading and idle detection continue
+ while your code holds an event. `OpenCodeClientOptions.EventStreamIdleTimeout` sets another
window than 45 seconds; keep it above the 15-second keepalive, or a quiet, healthy bus is cut
and reconnected each time.
- Each connection has 2 seconds to answer and deliver a `server.connected` frame, or it counts as
- failed. A reachable server that is consistently slower than that fails every attempt, and the
- minute below applies.
-- **Every connection starts with a `server.connected` frame**, usually typed as `EventServerConnected`.
+ failed. A reachable server that is consistently slower than that keeps failing and retrying.
+- **Every physical connection starts with `server.connected`**, usually typed as `EventServerConnected`.
Match on `Type`: a drifted marker can arrive as `UnknownEvent`. A second one means you were
disconnected and the events in between are gone: refresh the state you care about with ordinary
calls and carry on reading.
-- The stream never ends on its own. Your cancellation token or disposing the client releases its
- live connection at once; a consumer holding an event sees the exception on its next pull.
- One minute in which every attempt failed also ends it.
- Before disposing a subscription's enumerator while a `MoveNextAsync` may still be pending, cancel
- its token and let that call settle, because disposing it then throws `NotSupportedException`.
-- That minute applies to the first subscribe too. **A wrong address or a refused password surfaces
- after one minute, not at once**, as the error the server last answered
- (`OpenCodeApiException`, `OpenCodeTransportException` or `OpenCodeStreamFailureException`).
- Upstream's client keeps retrying forever and shows a status; the SDK has no status to show, so it
- gives up instead of hanging your `await foreach`.
+- **Retries never give up.** A wrong address, refused password, failure frame or exhausted window is
+ reported as a classified exception on connection state while the source keeps retrying, one second
+ apart without backoff. Cancellation, enumerator/client disposal, subscriber overflow or an escaping
+ source fault ends a subscription. An escaping fault preserves its queued prefix before throwing
+ the same exception; ordinary reconnects keep the subscription alive.
+- Enumerator disposal with a pending move is supported. An already settled move keeps its result;
+ an unsettled move ends false unless its token is cancelled. Disposal releases unread references,
+ and later pulls return false even after a stored overflow/fault/root ending, unless cancelled.
```csharp
var connectedBefore = false;
@@ -395,44 +399,96 @@ await foreach (var @event in client.Events.SubscribeAsync(cancellationToken: can
}
```
-The SDK reads the bus only when your loop asks for the next event. While your code holds an event,
-nothing reads the connection and the idle window is stopped. A server lost then is noticed only when
-a later pull reads the connection again, after the events already received have been yielded: a clean
-loss fails that read at once and the SDK reconnects 1 second later; a half-open connection takes a full
-idle window (45 seconds by default) from that read to detect. If your handler
-is slow, hand each event off so the loop keeps reading, and process `pending.Reader` on a separate
-task. A repeated `server.connected` frame still means events were missed; an event dropped or refused
-by a full channel is a gap too: refresh the state you care about. With `System.Threading.Channels` imported:
+The source reads ahead independently of your loop. Keep event handling short enough to stay within
+your subscription's bound. An extra application queue is another buffer and another possible gap,
+not something needed to keep the SDK's connection reader alive; own and observe any worker you add.
+
+`GetConnectionState()` is an immediate source snapshot, and `WatchConnectionAsync` starts with that
+snapshot then coalesces to the latest unread state. Neither opens a source or keeps it alive. A watch
+alongside an existing event consumer can display connection health:
```csharp
-var pending = Channel.CreateBounded(new BoundedChannelOptions(256)
+await foreach (var state in client.Events.WatchConnectionAsync(cancellationToken))
{
- FullMode = BoundedChannelFullMode.Wait,
-});
-var gapDetected = 0;
+ Console.WriteLine($"{state.Status}, attempt={state.Attempt}, error={state.Error?.Message}");
+}
+```
+
+Idle means no source; Connecting is its first opening; Connected follows a validated first marker;
+Reconnecting carries the classified failure and retry counter. Connected publishes attempt 0, but
+the loop counter resets only after a connection lived at least one second, then its next drop
+publishes 1. Error stays through the next opening and clears on Connected or Idle.
+
+Own a deadline token for a workflow that must not wait forever. Watch or sample state **while still
+subscribed** to explain a wait or choose an application-specific fail-fast policy. Keep a failure
+you need before cancellation: last leave returns state to Idle and clears it. Watches are not
+transition logs, so never require observing one particular transient error. Connected is also not
+a subscription-position or liveness barrier; the event markers still delimit resynchronization.
+
+### π Recovering after subscriber overflow
+
+1. Catch `OpenCodeEventSubscriberOverflowException`; that subscription and its backlog are gone.
+2. Resubscribe and await its admission marker **before** refreshing.
+3. Refresh authoritative state while the new subscription buffers its tail.
+4. Apply the tail idempotently: use entity versions/times, full-value replacement or keyed updates,
+ not duplicate counters or append-only replay of delta text.
+5. If that replacement overflows, start again at admission. A later marker also requires refresh.
-_ = Task.Run(async () =>
+For example, active-session membership is refreshed once at admission. Turn-state events then
+update the set by key without an HTTP request for each event or text delta:
+
+```csharp
+var running = new HashSet(StringComparer.Ordinal);
+using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+budget.CancelAfter(TimeSpan.FromMinutes(5));
+
+async Task RefreshStateAsync(CancellationToken token)
{
- await foreach (var queued in pending.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
- {
- if (Interlocked.Exchange(ref gapDetected, 0) == 1)
- {
- // An event never reached this loop: refresh the state you care about.
- }
+ var snapshot = await client.Sessions.GetActiveAsync(cancellationToken: token);
+ running.Clear();
+ running.UnionWith(snapshot.Active.Keys);
+}
- // Slow work for `queued` goes here.
+void ApplyTail(IEvent item)
+{
+ switch (item)
+ {
+ case SessionExecutionStarted started:
+ running.Add(started.Data.SessionId);
+ break;
+ case SessionExecutionSucceeded or SessionExecutionFailed or SessionExecutionInterrupted:
+ running.Remove(((ISessionScopedEvent)item).SessionId);
+ break;
}
-}, cancellationToken);
+}
-await foreach (var @event in client.Events.SubscribeAsync(cancellationToken: cancellationToken).ConfigureAwait(false))
+while (!budget.IsCancellationRequested)
{
- if (!pending.Writer.TryWrite(@event))
+ try
{
- Interlocked.Exchange(ref gapDetected, 1);
+ await using var subscription = client.Events.SubscribeAsync(cancellationToken: budget.Token).GetAsyncEnumerator();
+ if (!await subscription.MoveNextAsync() || subscription.Current.Type is not "server.connected")
+ throw new InvalidOperationException("The subscription was not admitted.");
+ await RefreshStateAsync(budget.Token);
+ while (await subscription.MoveNextAsync())
+ {
+ if (subscription.Current.Type is "server.connected") await RefreshStateAsync(budget.Token);
+ else ApplyTail(subscription.Current);
+ }
+ break;
+ }
+ catch (OpenCodeEventSubscriberOverflowException overflow)
+ {
+ Console.WriteLine($"Resubscribing after {overflow.Capacity}-event subscriber overflow.");
}
}
```
+The recipe assumes ordinary reads reflect a change no later than its event is published. It does
+not create an atomic cross-operation snapshot or promise exactly-once merging. Final text values
+can replace text; live deltas are not a durable, idempotent history. A delta buffered across a
+refresh can repeat displayed text until SessionTextEnded replaces it, because the snapshot carries no delta cursor.
+
The durable session event stream below has a cursor, but it delivers events only from a server
started with event persistence β and the CLI you install does not start one that way; the note on
guarantees below has the whole story.
@@ -593,22 +649,27 @@ before. See the
## βΉοΈ Cancellation and lifetime
-- **Streams open lazily.** Calling `SubscribeAsync` or `ReadSessionLogAsync` does not touch the
- network; the request goes out on the first `MoveNextAsync`, which is to say on the first
- `await foreach`.
-- **The enumeration token is the off switch.** Cancelling it closes the stream and surfaces as
+- **Streams open lazily.** Calling SubscribeAsync or ReadSessionLogAsync does not touch the
+ network. The first event-subscription move admits it and starts or reuses the shared source;
+ other streams open their request on the first MoveNextAsync.
+- **Entry tokens are the off switch.** Cancelling either ends that enumeration and surfaces as
`OperationCanceledException` carrying your token. Pass one token at either entry point, or the
same token at both, for this identity guarantee; two distinct cancellable entry tokens are both
observed without an identity guarantee. A `CancellationTokenSource` with a timeout, as in the
first snippet, is a perfectly good session budget.
-- **Cancellation or root-client disposal releases the live response immediately on every target,**
- even while your code holds a yielded event. An opening or reading wait reports cancellation or
- `ObjectDisposedException`; a suspended enumeration reports it on the next `MoveNextAsync`.
+- **Cancellation affects only that event subscription**, releases its unread references and outranks
+ a stored fault/overflow on the next pull, without changing an already settled move. Neighbours
+ retain their source. Last leave logically detaches before worker-based physical cancellation;
+ runner and cancel completion are both observed before CTS release. Root-client disposal fences
+ the feed and releases transport; registered subscriptions/watchers report ObjectDisposedException.
+ A subscription already ended by source fault keeps its prefix and fault unless cancelled or explicitly disposed.
+ Other SSE streams retain their response-release-on-cancellation/disposal behavior, even while held.
See the canonical [lifetime rules](../architecture/client-runtime.md#server-sent-events).
- **`WithCancellation` works** where you did not pass a token at the call β `await foreach (var x
in stream.WithCancellation(token))`.
-- **Disposing the enumerator ends the connection**, which `await foreach` does for you on `break`,
- on `return`, and on an exception.
+- **Disposing an event enumerator ends its subscription**, which `await foreach` does on `break`,
+ `return` or an exception. Last leave stops the shared source. Other stream enumerators still own
+ their individual connection.
- On the event bus, a connection that receives nothing for its idle window (45 seconds unless you
set `EventStreamIdleTimeout`) is replaced, as above. It refuses a per-call `NetworkTimeout`,
including `Timeout.InfiniteTimeSpan`; its connection and idle windows apply instead. On the
@@ -616,19 +677,21 @@ before. See the
once open, a silent log stays open until you cancel,
the server ends it, or it fails.
-## π₯ Streams always throw
+## π₯ Stream error channels
Streaming operations take `requestOptions`, but return a stream, not a response envelope.
[`NoThrow`](errors-and-responses.md#-ask-for-the-failure-as-data-instead) is refused with
`ArgumentException` naming `requestOptions` at the call, before enumeration; an undefined
-`ErrorBehavior` is also refused. Per-call `Location` is sent on every connection attempt, including
-reconnects; it does not filter the live event stream or change a session's directory. There is no
-envelope to put an error on, so every failure is an exception:
+`ErrorBehavior` is also refused. The live event source accepts but ignores per-call Location and
+sends only the ambient client snapshot; other streams keep the per-call override. Neither filters
+the instance-wide bus or changes a session's directory. Ordinary live-attempt errors are classified
+exceptions on connection state while retry continues; overflow and escaping source faults end
+subscriptions. Other streams have no response envelope, so their failures throw directly:
```csharp
try
{
- await foreach (var @event in client.Events.SubscribeAsync(cancellationToken: cancellationToken))
+ await foreach (var @event in client.Experimental.ReadSessionLogAsync(sessionId, cancellationToken: cancellationToken))
{
Console.WriteLine(@event.Type);
}
@@ -646,7 +709,8 @@ catch (OpenCodeTransportException transport)
- `OpenCodeStreamFailureException` means the **server** ended the stream with a declared failure
frame; its `Causes` collection carries the typed causes and is never null.
- `OpenCodeTransportException` β its base class β covers everything else: a broken connection, a
- body cut mid-event, an undecodable frame, a stalled read. Catching the base handles both.
+ body cut mid-event, an undecodable frame, a stalled read. Catching the base handles both on this
+ one-shot durable stream; the live source instead retries ordinary attempt failures and reports them on state.
- `OperationCanceledException` stays itself. Your cancellation is never repackaged as a failure.
Ordering matters in that `catch` chain: `OpenCodeStreamFailureException` derives from
diff --git a/playground/aotcli/OpenCode.Playground.AotCli/Program.cs b/playground/aotcli/OpenCode.Playground.AotCli/Program.cs
index 186890dda..2faf999d7 100644
--- a/playground/aotcli/OpenCode.Playground.AotCli/Program.cs
+++ b/playground/aotcli/OpenCode.Playground.AotCli/Program.cs
@@ -31,7 +31,7 @@
await using var events = client.Events.SubscribeAsync(cancellationToken: listening.Token).GetAsyncEnumerator();
try
{
- // The first event is always server.connected: the subscription is live, so nothing published after it is missed.
+ // server.connected admits this bounded subscription; it is not liveness or replay of earlier business events.
await events.MoveNextAsync();
var vcs = await client.Vcs.GetVcsAsync(cancellationToken: deadline.Token);
var branch = vcs.Vcs.Branch.Current ?? await AnnouncedBranchAsync(events, client.Vcs, vcs.Location.Directory, listening, deadline.Token);
diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionConversation.cs b/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionConversation.cs
index b49d17cde..1e20a31fb 100644
--- a/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionConversation.cs
+++ b/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionConversation.cs
@@ -25,22 +25,35 @@ internal sealed class SessionConversation(OpenCodeClient client, ILoggerShows the prompt at once, then sends it with an id of HQ's own; false when the prompt was not sent.
diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionBoard.cs b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionBoard.cs
index 54acd18ef..08e61341e 100644
--- a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionBoard.cs
+++ b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionBoard.cs
@@ -13,11 +13,20 @@ internal sealed class SessionBoard(OpenCodeClient client, ILogger
private readonly ConcurrentDictionary _sessions = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary _running = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary _needsYou = new(StringComparer.Ordinal);
+ private bool _ready;
+ private bool _sourceConnected;
+ private string? _connectionError;
+ private string? _subscriptionError;
+ private string? _lastError;
public event EventHandler? Changed;
- public bool Connected { get; private set; }
- public string? LastError { get; private set; }
+ public bool Connected => _ready && _sourceConnected;
+ public string? LastError
+ {
+ get => _lastError ?? _subscriptionError ?? _connectionError;
+ private set => _lastError = value;
+ }
public IReadOnlyList Sessions =>
[
.. _sessions.Values.OrderByDescending(static session => session.Time.Updated)
@@ -74,37 +83,74 @@ public async Task AnswerFormAsync(FormInfo form, SessionFormReplyRequest reply,
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
- while (!stoppingToken.IsCancellationRequested)
+ using var watchLifetime = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
+ var watching = WatchConnectionAsync(watchLifetime.Token);
+ try
{
- try
+ while (!stoppingToken.IsCancellationRequested)
{
- #region panel: subscribe
- await using var events = client.Events.SubscribeAsync(cancellationToken: stoppingToken).GetAsyncEnumerator(stoppingToken);
- #endregion
- // Subscribe before seeding so events cannot fall in the gap between them.
- if (await events.MoveNextAsync())
+ try
{
- await SeedAsync(stoppingToken);
- Connected = true;
- Changed?.Invoke(this, EventArgs.Empty);
+ #region panel: subscribe
+ await using var events = client.Events.SubscribeAsync(cancellationToken: stoppingToken).GetAsyncEnumerator(stoppingToken);
+ #endregion
while (await events.MoveNextAsync())
{
+ // The admission marker refreshes first; the shared subscription buffers the idempotent dictionary updates.
await ApplyAsync(events.Current, stoppingToken);
}
}
+ catch (OpenCodeEventSubscriberOverflowException exception)
+ {
+ logger.LogWarning(exception, "The board fell behind; admitting a new subscription before refreshing.");
+ _ready = false;
+ Changed?.Invoke(this, EventArgs.Empty);
+ continue;
+ }
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ {
+ return;
+ }
+ catch (Exception exception)
+ {
+ logger.LogWarning(exception, "The board event subscription or refresh failed.");
+ _subscriptionError = exception.Message;
+ }
+
+ _ready = false;
+ Changed?.Invoke(this, EventArgs.Empty);
+ await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
}
- catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ }
+ finally
+ {
+ await watchLifetime.CancelAsync();
+ await watching;
+ }
+ }
+
+ private async Task WatchConnectionAsync(CancellationToken cancellationToken)
+ {
+ try
+ {
+ await foreach (var state in client.Events.WatchConnectionAsync(cancellationToken))
{
- return;
+ _sourceConnected = state.Status == EventConnectionStatus.Connected;
+ _connectionError = state.Error?.Message;
+ Changed?.Invoke(this, EventArgs.Empty);
}
- catch (Exception exception)
+
+ if (!cancellationToken.IsCancellationRequested)
{
- logger.LogWarning(exception, "The board lost its server; reading the lists again.");
+ throw new InvalidOperationException("The event connection watch ended before shutdown.");
}
-
- Connected = false;
+ }
+ catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
+ {
+ logger.LogWarning(exception, "The board connection watch failed.");
+ _sourceConnected = false;
+ _connectionError = exception.Message;
Changed?.Invoke(this, EventArgs.Empty);
- await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
}
}
@@ -167,14 +213,19 @@ private async Task SeedAsync(CancellationToken cancellationToken)
private async Task ApplyAsync(IEvent item, CancellationToken cancellationToken)
{
+ if (item.Type == "server.connected")
+ {
+ _ready = false;
+ Changed?.Invoke(this, EventArgs.Empty);
+ await SeedAsync(cancellationToken);
+ _subscriptionError = null;
+ _ready = true;
+ Changed?.Invoke(this, EventArgs.Empty);
+ return;
+ }
+
switch (item)
{
- case EventServerConnected:
- Connected = false;
- Changed?.Invoke(this, EventArgs.Empty);
- await SeedAsync(cancellationToken);
- Connected = true;
- break;
case SessionCreated created:
var read = await client.Sessions.GetSessionClient(created.Data.SessionId).GetAsync(cancellationToken: cancellationToken);
_sessions[read.Session.Id] = read.Session;
diff --git a/playground/hq/README.md b/playground/hq/README.md
index f7939defa..69a8e3aaa 100644
--- a/playground/hq/README.md
+++ b/playground/hq/README.md
@@ -64,12 +64,15 @@ The board opens the bus, awaits its first event, seeds the newest **500 sessions
running, reads asks for those sessions' directories, then follows events. An unavailable directory
is logged and skipped.
A session renamed, deleted or archived elsewhere keeps its old row until the board reconnects or HQ restarts.
-A repeated `server.connected` refreshes the lists because disconnected events are lost. After a
-failure surfaces, the screen says it is disconnected and the board retries. The SDK's own retries
-can take about a minute before an exception surfaces; `Connected` may stay true during that time.
+A repeated `server.connected` refreshes the lists because disconnected events are lost. The SDK
+retries ordinary attempt failures forever and reports them through connection state; the board's
+owned state watch updates `Connected` and the connection error independently of event consumption.
+Subscriber overflow admits a replacement before refreshing. A subscription or refresh failure
+is logged and shown separately from permission/form-answer errors; a failed watch also clears `Connected`.
A stopped server stays stopped until you press Start on its resource in the dashboard.
`/health` separately probes the server under a short timeout instead of reporting a stale 200.
-Each open session page holds its own event stream, cancelled when the page closes.
+Each open session page holds its own subscription on the same root client's shared source,
+cancelled when the page closes.
Pages don't prerender: a prerendered button shows before its handler is attached, so an early click is dropped (#775). The page appears once its connection is up.
The dashboard shows HttpClient and ASP.NET Core traces and host logs, not SDK spans: the SDK's own
diff --git a/src/OpenCode.Sdk/Events/EventConnectionState.cs b/src/OpenCode.Sdk/Events/EventConnectionState.cs
new file mode 100644
index 000000000..7872832d8
--- /dev/null
+++ b/src/OpenCode.Sdk/Events/EventConnectionState.cs
@@ -0,0 +1,25 @@
+namespace OpenCode.Sdk;
+
+/// A snapshot of the shared source; its error is a shared exception reference, not a frozen graph.
+public sealed class EventConnectionState
+{
+ /// Initializes a connection snapshot, including snapshots supplied by consumer overrides.
+ /// The connection phase.
+ /// The retry counter; SDK connected and idle snapshots carry zero.
+ /// The last classified attempt failure, or null.
+ public EventConnectionState(EventConnectionStatus status, int attempt, Exception? error)
+ {
+ Status = status;
+ Attempt = attempt;
+ Error = error;
+ }
+
+ /// Gets the source's current phase.
+ public EventConnectionStatus Status { get; }
+
+ /// Gets the retry counter, reset after a connection lived at least one second.
+ public int Attempt { get; }
+
+ /// Gets the last classified failure, retained through the next attempt and cleared on connection or idle.
+ public Exception? Error { get; }
+}
diff --git a/src/OpenCode.Sdk/Events/EventConnectionStatus.cs b/src/OpenCode.Sdk/Events/EventConnectionStatus.cs
new file mode 100644
index 000000000..4561d63e0
--- /dev/null
+++ b/src/OpenCode.Sdk/Events/EventConnectionStatus.cs
@@ -0,0 +1,14 @@
+namespace OpenCode.Sdk;
+
+/// The shared event source's current connection phase, not a subscription position or liveness proof.
+public enum EventConnectionStatus
+{
+ /// No admitted event subscription owns a source.
+ Idle,
+ /// The first source attempt has not delivered its connection marker.
+ Connecting,
+ /// The source received a validated connection marker.
+ Connected,
+ /// An attempt failed and the source is retrying.
+ Reconnecting,
+}
diff --git a/src/OpenCode.Sdk/Events/EventSubscribeRequest.cs b/src/OpenCode.Sdk/Events/EventSubscribeRequest.cs
index 674166798..389d40560 100644
--- a/src/OpenCode.Sdk/Events/EventSubscribeRequest.cs
+++ b/src/OpenCode.Sdk/Events/EventSubscribeRequest.cs
@@ -9,7 +9,10 @@ namespace OpenCode.Sdk;
public sealed record EventSubscribeRequest
{
///
- /// Only send events of these types, plus the initial server.connected event. When omitted, all events are sent.
+ /// Locally select exact event types, captured at the call; null or empty selects all events and server.connected always passes.
///
+ ///
+ /// The shared source sends no types query and decodes the whole bus once.
+ ///
public IReadOnlyList? Types { get; init; }
}
diff --git a/src/OpenCode.Sdk/Events/EventsClient.cs b/src/OpenCode.Sdk/Events/EventsClient.cs
index b0813e068..95b468dc4 100644
--- a/src/OpenCode.Sdk/Events/EventsClient.cs
+++ b/src/OpenCode.Sdk/Events/EventsClient.cs
@@ -8,12 +8,14 @@ namespace OpenCode.Sdk;
///
public class EventsClient
{
- private readonly EventsRawClient? _raw;
+ private readonly SharedEventFeed? _feed;
internal EventsClient(Pipeline pipeline)
{
ArgumentNullException.ThrowIfNull(pipeline);
- _raw = new EventsRawClient(pipeline);
+ var feed = new SharedEventFeed(pipeline);
+ pipeline.RegisterOwned(feed);
+ _feed = feed;
}
///
@@ -26,19 +28,54 @@ protected EventsClient()
///
/// Subscribe to events. Subscribe to native events and plugin RPC events across all server locations. Volatile by contract: a slow consumer overflows and fails the stream, and events during disconnection are missed.
///
- /// The request shaping the query.
- /// The per-call options; NoThrow is refused. NetworkTimeout bounds only the opening and is refused for reconnecting streams, including Timeout.InfiniteTimeSpan.
+ /// The local type selection, captured at the call; the connection reads the whole bus.
+ /// NoThrow and NetworkTimeout are refused. Location is accepted but the shared connection sends only the client's ambient location.
/// The cancellation token.
/// The 'IEvent' stream.
- /// The API returned a declared error status (declared: 400, 401); streaming API errors always throw.
- /// The opened stream reported a schema-valid failure with a typed cause.
- /// The server could not be reached, the stream could not be read, or a frame or failure cause was malformed.
+ /// The next selected offer exceeded the subscription's 4,096 queued events; its backlog was discarded.
+ /// An entry token was cancelled.
+ /// The root client was disposed.
///
- /// Operation event.subscribe: GET /api/event. The stream reconnects after a failure, with a new attempt 1 s later and no backoff. It does not complete on its own; caller cancellation or root-client disposal ends it. After 1 minute in which every attempt fails, it throws the last failure. A repeated server.connected event means events published in between were missed; refresh authoritative state.
+ /// Operation event.subscribe: GET /api/event.
+ /// Each enumeration is an independent subscription to one shared background source per client.
+ /// The first server.connected marks admission, not liveness; earlier business events are not replayed.
+ /// A later marker announces a possible gap: refresh authoritative state. Event objects are shared references; treat them as read-only.
+ /// A subscription retains at most 4,096 queued selected events. Overflow ends only that subscription and discards its backlog.
+ /// The source retries ordinary attempt failures forever, 1 s apart without backoff; connection state reports the last classified failure.
+ /// An escaping source fault preserves each subscription's queued prefix, then throws the same exception.
+ /// Live cancellation wins over unread data and stored endings, but never changes an already settled move.
+ /// Enumerator disposal discards unread data and later pulls end false unless an entry token is cancelled.
///
public virtual IAsyncEnumerable SubscribeAsync(EventSubscribeRequest? request = null,
- OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) =>
- Raw.SubscribeAsync(request, requestOptions, cancellationToken);
+ OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default)
+ {
+ var feed = Feed;
+ feed.ThrowIfDisposed();
+ ErrorBehaviorPolicy.RefuseNoThrow(requestOptions, "Streams", ErrorBehaviorPolicy.EventSubscriptionNoThrowMessage);
+ if (requestOptions?.NetworkTimeout is not null)
+ {
+ throw new ArgumentException(FailureClassification.EventStreamNetworkTimeoutMessage, nameof(requestOptions));
+ }
+
+ return feed.Subscribe(EventSelection.Capture(request?.Types, nameof(request)), cancellationToken);
+ }
+
+ /// Gets the shared source's current snapshot without opening a connection.
+ /// The current source-level state; it is not a subscription position or liveness proof.
+ /// The root client was disposed.
+ public virtual EventConnectionState GetConnectionState() => Feed.GetConnectionState();
+
+ /// Watches the initial source snapshot and then the latest unread snapshots, coalescing intermediate changes.
+ /// The cancellation token; the enumerator token is also observed.
+ /// A lazy state watch that never opens or keeps alive an event source.
+ /// An entry token was cancelled.
+ /// The root client was disposed.
+ public virtual IAsyncEnumerable WatchConnectionAsync(CancellationToken cancellationToken = default)
+ {
+ var feed = Feed;
+ feed.ThrowIfDisposed();
+ return feed.Watch(cancellationToken);
+ }
- private EventsRawClient Raw => _raw ?? throw MockSeam.CreateError("EventsClient", "Pipeline");
+ private SharedEventFeed Feed => _feed ?? throw MockSeam.CreateError("EventsClient", "Pipeline");
}
diff --git a/src/OpenCode.Sdk/Events/Internal/Abstractions/IEventAttemptSource.cs b/src/OpenCode.Sdk/Events/Internal/Abstractions/IEventAttemptSource.cs
new file mode 100644
index 000000000..fae2b3e8b
--- /dev/null
+++ b/src/OpenCode.Sdk/Events/Internal/Abstractions/IEventAttemptSource.cs
@@ -0,0 +1,9 @@
+using OpenCode.Sdk.Models;
+
+namespace OpenCode.Sdk.Internal;
+
+/// Opens one physical event attempt; the source runner owns its windows and retry.
+internal interface IEventAttemptSource
+{
+ public IAsyncEnumerable OpenAsync(StreamAttempt attempt, CancellationToken cancellationToken);
+}
diff --git a/src/OpenCode.Sdk/Events/Internal/Abstractions/IEventFeedGateProbe.cs b/src/OpenCode.Sdk/Events/Internal/Abstractions/IEventFeedGateProbe.cs
new file mode 100644
index 000000000..aaca90a72
--- /dev/null
+++ b/src/OpenCode.Sdk/Events/Internal/Abstractions/IEventFeedGateProbe.cs
@@ -0,0 +1,7 @@
+namespace OpenCode.Sdk.Internal;
+
+/// Test seam: lets a test order cancellation before publication selection; a no-op in production.
+internal interface IEventFeedGateProbe
+{
+ public void OnPublication();
+}
diff --git a/src/OpenCode.Sdk/Events/Internal/AfterGate.cs b/src/OpenCode.Sdk/Events/Internal/AfterGate.cs
new file mode 100644
index 000000000..387614043
--- /dev/null
+++ b/src/OpenCode.Sdk/Events/Internal/AfterGate.cs
@@ -0,0 +1,48 @@
+namespace OpenCode.Sdk.Internal;
+
+/// Runs every deferred callback outside the gate, even when selection or another callback fails.
+internal sealed class AfterGate
+{
+ private readonly List _items = [];
+ private readonly List _failures = [];
+
+ public void Add(Action item) => _items.Add(item);
+
+ public void RecordFailure(Exception exception) => _failures.Add(exception);
+
+ public void Run(Action gateSection)
+ {
+ try
+ {
+ gateSection();
+ }
+ catch (Exception exception)
+ {
+ RecordFailure(exception);
+ }
+ finally
+ {
+ Run();
+ }
+ }
+
+ public void Run()
+ {
+ foreach (var item in _items)
+ {
+ try
+ {
+ item();
+ }
+ catch (Exception exception)
+ {
+ RecordFailure(exception);
+ }
+ }
+
+ if (_failures.Count != 0)
+ {
+ throw new AggregateException(_failures);
+ }
+ }
+}
diff --git a/src/OpenCode.Sdk/Events/Internal/Delivery.cs b/src/OpenCode.Sdk/Events/Internal/Delivery.cs
new file mode 100644
index 000000000..9394c5624
--- /dev/null
+++ b/src/OpenCode.Sdk/Events/Internal/Delivery.cs
@@ -0,0 +1,6 @@
+using System.Runtime.ExceptionServices;
+
+namespace OpenCode.Sdk.Internal;
+
+/// A selected item, end of enumeration, or failure, independent of channel completion.
+internal sealed record Delivery(T? Item, Exception? Error, ExceptionDispatchInfo? Dispatch = null) where T : class;
diff --git a/src/OpenCode.Sdk/Events/Internal/EventAttemptSource.cs b/src/OpenCode.Sdk/Events/Internal/EventAttemptSource.cs
new file mode 100644
index 000000000..da532d2a5
--- /dev/null
+++ b/src/OpenCode.Sdk/Events/Internal/EventAttemptSource.cs
@@ -0,0 +1,16 @@
+using OpenCode.Sdk.Models;
+
+namespace OpenCode.Sdk.Internal;
+
+/// Opens the generated route and adapter directly on the stream plane for one runner-owned attempt.
+internal sealed class EventAttemptSource(Pipeline pipeline) : IEventAttemptSource
+{
+ public IAsyncEnumerable OpenAsync(StreamAttempt attempt, CancellationToken cancellationToken)
+ {
+ pipeline.Lifetime.ThrowIfDisposed();
+ // The operation id and method are hand-copied from the generated Events operation; route and adapter remain generated.
+ var request = OperationRequest.Describe
public IAsyncEnumerable ExecuteStreamAsync(string operationId, HttpMethod method, string route,
IStreamAdapter adapter, OpenCodeRequestOptions? requestOptions, CancellationToken cancellationToken)
@@ -192,34 +196,89 @@ public IAsyncEnumerable ExecuteStreamAsync(string op
var reconnecting = request.Traits.Reconnects;
if (reconnecting && requestOptions?.NetworkTimeout is not null)
{
- throw new ArgumentException("Reconnecting streams use their own connection and idle windows; NetworkTimeout is not supported.", nameof(requestOptions));
+ throw new ArgumentException(FailureClassification.EventStreamNetworkTimeoutMessage, nameof(requestOptions));
+ }
+
+ if (reconnecting)
+ {
+ throw new InvalidOperationException($"Operation '{operationId}' must be opened through its shared event feed.");
}
- return reconnecting
- ? _reconnectingEventStream.ExecuteReconnectingStreamAsync(request, adapter, cancellationToken)
- : _streamPlane.ExecuteStreamCoreAsync(request, adapter, attempt: null, cancellationToken);
+ return _streamPlane.ExecuteStreamCoreAsync(request, adapter, attempt: null, cancellationToken);
}
- public void Dispose()
+ ///
+ /// Lets a hand-written family door own a resource whose life ends with the root client, before the transport.
+ /// Registration and disposal share one admission boundary, even while an earlier resource's cleanup is still running.
+ ///
+ internal void RegisterOwned(IDisposable resource)
{
- if (!_lifetime.TryBeginDispose())
+ lock (_disposalGate)
{
- return;
+ if (_disposalStarted)
+ {
+ throw FailureClassification.DisposedClient();
+ }
+
+ _ownedResources.Add(resource);
}
+ }
- try
+ public void Dispose()
+ {
+ IDisposable[] resources;
+ lock (_disposalGate)
{
- _lifetimeSource.Cancel();
+ if (_disposalStarted)
+ {
+ return;
+ }
+
+ _disposalStarted = true;
+ resources = [.. _ownedResources];
+ _ownedResources.Clear();
}
- finally
+
+ void DisposeOwned(int index)
{
+ if (index < 0)
+ {
+ return;
+ }
+
try
{
- _transport.Dispose();
+ resources[index].Dispose();
}
finally
{
- _lifetimeSource.Dispose();
+ DisposeOwned(index - 1);
+ }
+ }
+
+ try
+ {
+ DisposeOwned(resources.Length - 1);
+ }
+ finally
+ {
+ if (_lifetime.TryBeginDispose())
+ {
+ try
+ {
+ _lifetimeSource.Cancel();
+ }
+ finally
+ {
+ try
+ {
+ _transport.Dispose();
+ }
+ finally
+ {
+ _lifetimeSource.Dispose();
+ }
+ }
}
}
}
diff --git a/src/OpenCode.Sdk/Internal/Transport/StreamReconnect.cs b/src/OpenCode.Sdk/Internal/Transport/StreamReconnect.cs
index 65f54a926..ed47e349b 100644
--- a/src/OpenCode.Sdk/Internal/Transport/StreamReconnect.cs
+++ b/src/OpenCode.Sdk/Internal/Transport/StreamReconnect.cs
@@ -4,8 +4,8 @@ namespace OpenCode.Sdk.Internal;
///
/// The reconnect rule of the event bus, as the pinned client runs it: how long each attempt may
-/// take, how long a connected stream may stay silent, the wait between attempts, and when a failing
-/// stream gives up. Knowledge source: upstream-observed.
+/// take, how long a connected stream may stay silent, and the wait between attempts.
+/// Knowledge source: upstream-observed.
///
///
/// Each attempt has to answer and deliver server.connected as its
@@ -13,9 +13,7 @@ namespace OpenCode.Sdk.Internal;
/// unless the client options set another, as upstream's
/// idleTimeout option does β and the server's keepalive keeps a quiet stream alive. Every
/// failure, of any kind, is followed by a new attempt after , with no backoff.
-/// Upstream retries forever and shows a status; the SDK has no status to show, so a stream that has
-/// failed every attempt for β from the drop, or from the first attempt of a
-/// first open β gives up and throws the last failure.
+/// The shared source retries forever and exposes its classified attempt failures through connection state.
///
internal static class StreamReconnect
{
@@ -34,9 +32,6 @@ internal static class StreamReconnect
///
public static TimeSpan DefaultIdleWindow { get; } = TimeSpan.FromSeconds(45);
- /// Gets how long every attempt may keep failing before the stream gives up.
- public static TimeSpan GiveUp { get; } = TimeSpan.FromMinutes(1);
-
///
/// Gets whether a frame establishes the connection that delivered it: an unnamed frame whose
/// payload is an object with type server.connected. The frame is read as the wire
diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionConversationTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionConversationTests.cs
index 6e4bbed7b..cbcea91a6 100644
--- a/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionConversationTests.cs
+++ b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionConversationTests.cs
@@ -1,4 +1,6 @@
using OpenCode.Playground.Hq.Tests.Features.Conversation.Support;
+using OpenCode.Sdk;
+using OpenCode.Sdk.Models;
using TUnit.Assertions.Enums;
using static OpenCode.Playground.Hq.Tests.Features.Conversation.Support.ConversationScenario;
@@ -6,6 +8,57 @@ namespace OpenCode.Playground.Hq.Tests.Features.Conversation;
public sealed class SessionConversationTests
{
+ [Test]
+ public async Task FollowAsync_Should_Replace_Refreshed_Text_With_The_Parts_Authoritative_End()
+ {
+ using var scenario = new ConversationScenario().WithHistory(Assistant(Text("snapshot text")));
+ scenario.SessionCalls.Running = true;
+ await scenario.FollowAsync(Ended(0, "authoritative text"), Succeeded());
+
+ await Assert.That(scenario.Conversation.Lines.Select(static line => line.Text))
+ .IsEquivalentTo(["authoritative text"], CollectionOrdering.Matching);
+ await Assert.That(scenario.Conversation.Running).IsFalse();
+ await Assert.That(scenario.Conversation.EndedTurns).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task FollowAsync_Should_Refresh_On_A_Drifted_Connection_Marker()
+ {
+ using var scenario = new ConversationScenario().WithHistory(User());
+ scenario.EventCalls.Items = [Connected, () =>
+ {
+ scenario.WithHistory(Assistant(Text("refreshed")));
+ var payload = System.Text.Json.JsonSerializer.SerializeToElement(new { type = "server.connected", data = false });
+ return new UnknownEvent("server.connected", payload);
+ }];
+ await scenario.Conversation.FollowAsync(SessionId, CancellationToken.None);
+
+ await Assert.That(scenario.Conversation.Lines.Select(static line => line.Text)).IsEquivalentTo(["refreshed"], CollectionOrdering.Matching);
+ }
+
+ [Test]
+ public async Task FollowAsync_Should_Recover_From_Overflow_By_Admission_Then_Refresh_Then_An_Idempotent_Tail()
+ {
+ using var scenario = new ConversationScenario();
+ scenario.EventCalls.Subscriptions.Enqueue([Connected, () =>
+ {
+ scenario.EventCalls.Trace.Add("overflow");
+ throw new OpenCodeEventSubscriberOverflowException();
+ }]);
+ scenario.EventCalls.Subscriptions.Enqueue([() =>
+ {
+ scenario.WithHistory(Assistant(Text("snapshot")));
+ return Connected();
+ }, () => Ended(0, "tail"), () => Succeeded()]);
+ _ = await Assert.That(scenario.Conversation.FollowAsync(SessionId, CancellationToken.None)).ThrowsNothing();
+
+ await Assert.That(scenario.EventCalls.Trace)
+ .IsEquivalentTo(["subscription", "history", "overflow", "subscription", "history", "subscription", "subscription"],
+ CollectionOrdering.Matching);
+ await Assert.That(scenario.Conversation.Lines.Select(static line => line.Text)).IsEquivalentTo(["tail"], CollectionOrdering.Matching);
+ await Assert.That(scenario.Conversation.EndedTurns).IsEqualTo(1);
+ }
+
[Test]
public async Task FollowAsync_Should_Read_History_After_The_Subscription_Opens()
{
diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/Support/ConversationScenario.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/Support/ConversationScenario.cs
index 77e847358..4db062296 100644
--- a/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/Support/ConversationScenario.cs
+++ b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/Support/ConversationScenario.cs
@@ -119,11 +119,15 @@ public Task FollowAsync(params IEvent[] events)
internal sealed class ConversationEvents : EventsClient
{
+ public Queue>> Subscriptions { get; } = new();
+ public override EventConnectionState GetConnectionState() => new(EventConnectionStatus.Connected, 0, null);
+ public override IAsyncEnumerable WatchConnectionAsync(CancellationToken cancellationToken = default) =>
+ new[] { GetConnectionState() }.ToAsyncEnumerable();
public IReadOnlyList> Items { get; set; } = [];
public List Trace { get; } = [];
public override IAsyncEnumerable SubscribeAsync(EventSubscribeRequest? request = null,
OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) =>
- Items.Select(next =>
+ (Subscriptions.TryDequeue(out var scripted) ? scripted : Items).Select(next =>
{
var item = next();
Trace.Add("subscription");
diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionBoardTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionBoardTests.cs
index ff2713af3..279b42668 100644
--- a/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionBoardTests.cs
+++ b/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionBoardTests.cs
@@ -1,7 +1,7 @@
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading.Channels;
-using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Logging;
using OpenCode.Playground.Hq.Features.Sessions;
using OpenCode.Sdk;
using OpenCode.Sdk.Models;
@@ -11,6 +11,109 @@ namespace OpenCode.Playground.Hq.Tests.Features.Sessions;
public sealed class SessionBoardTests
{
+ [Test]
+ public async Task SessionBoard_Should_Report_A_Watch_Fault_Before_Shutdown()
+ {
+ await using var scenario = new BoardScenario();
+ var failure = new InvalidOperationException("watch lost");
+ scenario.EventCalls.WatchFailure = failure;
+ await scenario.StartAsync();
+
+ await Assert.That(scenario.Board.Connected).IsFalse();
+ await Assert.That(scenario.Board.LastError).IsEqualTo("watch lost");
+ await Assert.That(scenario.Logger.LastFailure).IsSameReferenceAs(failure);
+ await Assert.That(scenario.EventCalls.SubscribeCalls).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task SessionBoard_Should_Keep_A_Permission_Answer_Error_After_Refresh()
+ {
+ await using var scenario = new BoardScenario();
+ await scenario.StartAsync();
+ scenario.SessionCalls.ReplyFailure = Unauthorized();
+ var ask = scenario.Board.NeedsYou.Single(static item => item.Id == "ask_first");
+ await scenario.Board.AnswerAsync(ask, PermissionReply.Once, CancellationToken.None);
+ scenario.SessionCalls.Items = [Session(7, "refreshed")];
+ await scenario.SendAsync(Connected());
+
+ await Assert.That(scenario.Board.LastError).IsEqualTo("Could not answer permission. Try again.");
+ await Assert.That(scenario.Board.Sessions.Single().Session.Id).IsEqualTo("ses_7");
+ }
+
+ [Test]
+ public async Task SessionBoard_Should_Own_And_Observe_The_State_Watch_With_Its_Hosting_Lifetime()
+ {
+ await using var scenario = new BoardScenario();
+ await scenario.StartAsync();
+ await Assert.That(scenario.EventCalls.WatchCalls).IsEqualTo(1);
+ await Assert.That(scenario.Board.Connected).IsTrue();
+ var failure = Unauthorized();
+ await scenario.SendStateAsync(new EventConnectionState(EventConnectionStatus.Reconnecting, 1, failure));
+ await Assert.That(scenario.Board.Connected).IsFalse();
+ await Assert.That(scenario.Board.LastError).IsEqualTo(failure.Message);
+ await Assert.That(scenario.EventCalls.SubscribeCalls).IsEqualTo(1);
+ await scenario.Board.StopAsync(CancellationToken.None);
+ await Assert.That(scenario.EventCalls.WatchToken.IsCancellationRequested).IsTrue();
+ await Assert.That(scenario.EventCalls.WatchEnded.Task.Status).IsEqualTo(TaskStatus.RanToCompletion);
+ }
+
+ [Test]
+ public async Task SessionBoard_Should_Recover_From_Overflow_By_Admission_Then_Refresh_Then_An_Idempotent_Tail()
+ {
+ await using var scenario = new BoardScenario();
+ await scenario.StartAsync();
+ var refreshes = scenario.SessionCalls.Refreshes;
+ scenario.EventCalls.Trace.Clear();
+ scenario.SessionCalls.Items = [Session(9, "last")];
+ scenario.SessionCalls.Active = new HashSet(["ses_9"], StringComparer.Ordinal);
+ scenario.SessionCalls.ListingRelease = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ scenario.EventCalls.Input.Writer.TryWrite(() =>
+ {
+ scenario.EventCalls.Trace.Add("overflow");
+ throw new OpenCodeEventSubscriberOverflowException();
+ });
+ await scenario.SettleAsync();
+ await Assert.That(scenario.EventCalls.SubscribeCalls).IsEqualTo(2);
+ await Assert.That(scenario.SessionCalls.Refreshes).IsEqualTo(refreshes);
+ await Assert.That(scenario.EventCalls.Trace).IsEquivalentTo(["overflow", "subscribe"], CollectionOrdering.Matching);
+ var refreshing = scenario.SendAsync(Connected());
+ try
+ {
+ await scenario.SessionCalls.ListingStarted.Task.WaitAsync(TimeSpan.FromSeconds(10));
+ await Assert.That(scenario.EventCalls.Trace)
+ .IsEquivalentTo(["overflow", "subscribe", "admission", "refresh"], CollectionOrdering.Matching);
+ var started = new SessionExecutionStarted
+ {
+ Id = "started",
+ Created = 1,
+ Durable = new() { AggregateId = "ses_9", Seq = 1, Version = 1 },
+ Data = new() { SessionId = "ses_9" },
+ };
+ scenario.EventCalls.Input.Writer.TryWrite(() => started);
+ }
+ finally
+ {
+ scenario.SessionCalls.ListingRelease.TrySetResult();
+ await refreshing;
+ }
+
+ await scenario.SettleAsync();
+ await Assert.That(scenario.Board.Sessions.Select(static row => row.Session.Id)).IsEquivalentTo(["ses_9"], CollectionOrdering.Matching);
+ await Assert.That(scenario.Board.Sessions.Single().Status).IsEqualTo("running");
+ }
+
+ [Test]
+ public async Task SessionBoard_Should_Refresh_On_A_Drifted_Connection_Marker()
+ {
+ await using var scenario = new BoardScenario();
+ await scenario.StartAsync();
+ scenario.SessionCalls.Items = [Session(9, "last")];
+ var payload = System.Text.Json.JsonSerializer.SerializeToElement(new { type = "server.connected", data = false });
+ await scenario.SendAsync(new UnknownEvent("server.connected", payload));
+
+ await Assert.That(scenario.Board.Sessions.Select(static row => row.Session.Id)).IsEquivalentTo(["ses_9"], CollectionOrdering.Matching);
+ }
+
[Test]
public async Task SessionBoard_Should_Not_List_Asks_For_Directories_Without_An_Active_Session()
{
@@ -96,11 +199,11 @@ public async Task SessionBoard_Should_Disconnect_And_Recover_After_Stream_Api_Fa
{
await using var scenario = new BoardScenario();
await scenario.StartAsync();
- scenario.EventCalls.Input.Writer.TryWrite(static () => throw Unauthorized());
- await scenario.SettleAsync();
+ await scenario.SendStateAsync(new EventConnectionState(EventConnectionStatus.Reconnecting, 1, Unauthorized()));
await Assert.That(scenario.Board.Connected).IsFalse();
scenario.SessionCalls.Items = [Session(8, "first")];
scenario.SessionCalls.Active = new HashSet(["ses_8"], StringComparer.Ordinal);
+ await scenario.SendStateAsync(new EventConnectionState(EventConnectionStatus.Connected, 0, null));
await scenario.SendAsync(Connected());
await Assert.That(scenario.Board.Connected).IsTrue();
await Assert.That(scenario.Board.Sessions.Select(static row => row.Session.Id)).IsEquivalentTo(["ses_8"], CollectionOrdering.Matching);
@@ -180,8 +283,13 @@ await Assert.That(scenario.Board.NeedsYou.Select(static item => item.Id))
private sealed class BoardScenario : OpenCodeClient, IAsyncDisposable
{
- public BoardScenario() => Board = new SessionBoard(this, NullLogger.Instance);
+ public BoardScenario()
+ {
+ Board = new SessionBoard(this, Logger);
+ SessionCalls.Trace = EventCalls.Trace;
+ }
public SessionBoard Board { get; }
+ public BoardLogger Logger { get; } = new();
public BoardSessions SessionCalls { get; } = new();
public BoardPermissions PermissionCalls { get; } = new();
public BoardForms FormCalls { get; } = new();
@@ -222,10 +330,22 @@ public async Task SendAsync(IEvent item)
await SettleAsync();
}
+ public async Task SendStateAsync(EventConnectionState state)
+ {
+ while (EventCalls.StatePulls.Reader.TryRead(out _))
+ {
+ // Drain acknowledgements for the state that preceded this explicit change.
+ }
+
+ EventCalls.States.Writer.TryWrite(state);
+ await EventCalls.StatePulls.Reader.ReadAsync(CancellationToken.None).AsTask().WaitAsync(TimeSpan.FromSeconds(10), CancellationToken.None);
+ }
+
public async Task SettleAsync()
{
// A pull after handling an event, or the service ending, bounds the observation; no sleep decides a verdict.
- await Task.WhenAny(EventCalls.Pulls.Reader.ReadAsync().AsTask(), Board.ExecuteTask ?? Task.CompletedTask).WaitAsync(TimeSpan.FromSeconds(10));
+ await Task.WhenAny(EventCalls.Pulls.Reader.ReadAsync(CancellationToken.None).AsTask(), Board.ExecuteTask ?? Task.CompletedTask)
+ .WaitAsync(TimeSpan.FromSeconds(10), CancellationToken.None);
}
public async ValueTask DisposeAsync()
@@ -238,21 +358,75 @@ public async ValueTask DisposeAsync()
private sealed class BoardEvents : EventsClient
{
+ private EventConnectionState _state = new(EventConnectionStatus.Connected, 0, null);
+ public Exception? WatchFailure { get; set; }
+ public List Trace { get; } = [];
+ public int SubscribeCalls { get; private set; }
+ public int WatchCalls { get; private set; }
+ public CancellationToken WatchToken { get; private set; }
+ public TaskCompletionSource WatchEnded { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public Channel States { get; } = Channel.CreateUnbounded();
+ public Channel StatePulls { get; } = Channel.CreateUnbounded();
+ public override EventConnectionState GetConnectionState() => _state;
+ public override async IAsyncEnumerable WatchConnectionAsync([EnumeratorCancellation] CancellationToken cancellationToken = default)
+ {
+ WatchCalls++;
+ WatchToken = cancellationToken;
+ try
+ {
+ yield return _state;
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ if (WatchFailure is { } failure)
+ {
+ throw failure;
+ }
+
+ StatePulls.Writer.TryWrite(0);
+ _state = await States.Reader.ReadAsync(cancellationToken);
+ yield return _state;
+ }
+ }
+ finally
+ {
+ WatchEnded.TrySetResult();
+ }
+ }
+
public Channel> Input { get; } = Channel.CreateUnbounded>();
public Channel Pulls { get; } = Channel.CreateUnbounded();
public override async IAsyncEnumerable SubscribeAsync(EventSubscribeRequest? request = null,
OpenCodeRequestOptions? requestOptions = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
+ SubscribeCalls++;
+ Trace.Add("subscribe");
while (!cancellationToken.IsCancellationRequested)
{
Pulls.Writer.TryWrite(0);
- yield return (await Input.Reader.ReadAsync(cancellationToken))();
+ var item = (await Input.Reader.ReadAsync(cancellationToken))();
+ if (item.Type == "server.connected")
+ {
+ Trace.Add("admission");
+ }
+
+ yield return item;
}
}
}
+ private sealed class BoardLogger : ILogger
+ {
+ public Exception? LastFailure { get; private set; }
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+ public bool IsEnabled(LogLevel logLevel) => true;
+ public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
+ Func formatter) => LastFailure = exception;
+ }
+
private sealed class BoardSessions : SessionsClient
{
+ public List Trace { get; set; } = [];
+ public int Refreshes { get; private set; }
private bool _descending;
public IReadOnlyList Items { get; set; } = [Session(0, "first"), Session(1, "gone"), Session(2, "last")];
public IReadOnlySet Active { get; set; } = new HashSet(["ses_0", "ses_1", "ses_2"], StringComparer.Ordinal);
@@ -266,15 +440,17 @@ public override Task GetActiveAsync(OpenCodeRequestOption
public override async Task ListSessionsAsync(SessionListRequest? request = null,
OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default)
{
- if (ListingRelease is { } release)
+ if (request?.Cursor is null)
{
- ListingStarted.TrySetResult();
- await release.Task.WaitAsync(cancellationToken);
+ _descending = request?.Order == ListOrder.Descending;
+ Refreshes++;
+ Trace.Add("refresh");
}
- if (request?.Cursor is null)
+ if (ListingRelease is { } release)
{
- _descending = request?.Order == ListOrder.Descending;
+ ListingStarted.TrySetResult();
+ await release.Task.WaitAsync(cancellationToken);
}
var ordered = _descending ? Items.OrderByDescending(static item => item.Time.Updated) : Items.OrderBy(static item => item.Time.Updated);
diff --git a/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs b/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs
index 6b3704ada..2283837f6 100644
--- a/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs
+++ b/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs
@@ -58,6 +58,7 @@ private static IEnumerable Cases()
yield return new("events", "first-open/" + entry, caller => AtEventWaitAsync("open", entry, caller));
yield return new("events", "live-read/" + entry, caller => AtStreamReadAsync(events: true, entry, caller));
yield return new("events", "reconnect-delay/" + entry, caller => AtEventWaitAsync("delay", entry, caller));
+ yield return new("event-state", "pending/" + entry, caller => AtEventStateAsync(entry, caller));
yield return new("other-sse", "headers/" + entry, caller => AtHeadersAsync(
(client, token) => PullAsync(client.Experimental.ReadSessionLogAsync(
SessionId, cancellationToken: MethodToken(entry, token)), EnumerationToken(entry, token)), caller));
@@ -177,6 +178,18 @@ private static async Task AtBodyAsync(bool upload, C
return await observed;
}
+ private static async Task AtEventStateAsync(string entry, CancellationTokenSource caller)
+ {
+ using var client = new OpenCodeClient(new OpenCodeClientOptions { Endpoint = PipelineFactory.Endpoint });
+ await using var watcher = client.Events.WatchConnectionAsync(MethodToken(entry, caller.Token))
+ .GetAsyncEnumerator(EnumerationToken(entry, caller.Token));
+ await Assert.That(await watcher.MoveNextAsync()).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Idle);
+ var observed = CancellationAsync(async () => _ = await watcher.MoveNextAsync());
+ await caller.CancelOnWorkerAsync();
+ return await observed;
+ }
+
private static async Task AtEventWaitAsync(string phase, string entry, CancellationTokenSource caller)
{
using var server = new ScriptedEventServer(_ => phase == "open"
@@ -748,6 +761,8 @@ _ when IsCursorEnumerator(member) => "cursor-items",
_ when ClientFamilies.Contains(member.DeclaringType) && IsGeneric(member.ReturnType, typeof(CursorSequence<,>)) => "cursor-items",
_ when member.Is(typeof(EventsClient), nameof(EventsClient.SubscribeAsync), typeof(IAsyncEnumerable),
typeof(EventSubscribeRequest), typeof(OpenCodeRequestOptions), typeof(CancellationToken)) => "events",
+ _ when member.Is(typeof(EventsClient), nameof(EventsClient.WatchConnectionAsync), typeof(IAsyncEnumerable),
+ typeof(CancellationToken)) => "event-state",
_ when ClientFamilies.Contains(member.DeclaringType) && IsGeneric(member.ReturnType, typeof(IAsyncEnumerable<>)) => "other-sse",
_ when member.Is(typeof(LanguageModelsClientExtensions), nameof(LanguageModelsClientExtensions.WaitForDefaultAsync), typeof(Task),
typeof(LanguageModelsClient), typeof(ModelDefaultRequest), typeof(OpenCodeRequestOptions), typeof(CancellationToken)) => "default-wait",
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventSelectionTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventSelectionTests.cs
new file mode 100644
index 000000000..6e00e78a7
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/EventSelectionTests.cs
@@ -0,0 +1,53 @@
+using OpenCode.Sdk.Internal;
+using OpenCode.Sdk.Models;
+using TUnit.Assertions.Enums;
+
+namespace OpenCode.Sdk.Tests.Events;
+
+public sealed class EventSelectionTests
+{
+ [Test]
+ public async Task Capture_Should_Copy_The_Callers_Types()
+ {
+ var types = new List { new("session.created"), new("rpc.sdk-test") };
+ var selection = EventSelection.Capture(types);
+ types.Clear();
+ types.Add(new EventType("rpc.other"));
+
+ string[] candidates = ["session.updated", "session.created", "rpc.other", "rpc.sdk-test", "future.event", "server.connected"];
+ await Assert.That(candidates.Where(selection.Includes))
+ .IsEquivalentTo(["session.created", "rpc.sdk-test", "server.connected"], CollectionOrdering.Matching);
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task Includes_Should_Select_All_Types_When_The_Selection_Is_Null_Or_Empty(bool empty)
+ {
+ var selection = EventSelection.Capture(empty ? [] : null);
+ string[] candidates = ["session.created", "rpc.other", "future.event", "server.connected"];
+
+ await Assert.That(candidates.Where(selection.Includes))
+ .IsEquivalentTo(["session.created", "rpc.other", "future.event", "server.connected"], CollectionOrdering.Matching);
+ }
+
+ [Test]
+ public async Task Includes_Should_Select_Exact_Ordinal_Types_And_The_Marker()
+ {
+ var selection = EventSelection.Capture([new("session.created"), new("rpc.sdk-test"), new("future.event"), new("")]);
+ string[] candidates =
+ ["Session.Created", "session.updated", "session.created", "rpc.other", "rpc.sdk-test", "future.event", "server.connected", ""];
+
+ await Assert.That(candidates.Where(selection.Includes))
+ .IsEquivalentTo(["session.created", "rpc.sdk-test", "future.event", "server.connected", ""], CollectionOrdering.Matching);
+ }
+
+ [Test]
+ public async Task Capture_Should_Refuse_A_Default_EventType()
+ {
+ var exception = await Assert.That(() => EventSelection.Capture([default])).Throws();
+
+ await Assert.That(exception!.Message).StartsWith("A default EventType has no wire value.");
+ await Assert.That(exception.ParamName).IsEqualTo("request");
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventSourceRunnerTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventSourceRunnerTests.cs
new file mode 100644
index 000000000..4c0c5ef34
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/EventSourceRunnerTests.cs
@@ -0,0 +1,414 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using OpenCode.Sdk.Internal;
+using OpenCode.Sdk.Models;
+using OpenCode.Sdk.Tests.Events.Support;
+using OpenCode.Sdk.Tests.Harness;
+using OpenCode.Sdk.Tests.Support;
+using TUnit.Assertions.Enums;
+
+namespace OpenCode.Sdk.Tests.Events;
+
+public sealed class EventSourceRunnerTests
+{
+ [Test]
+ public async Task RecordDrop_Should_Keep_The_Queued_Prefix_Across_A_Retried_Attempt()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("before-drop");
+ await scenario.PublishPrefixAsync("queued-one", "queued-two");
+ var failure = new OpenCodeTransportException("retryable read");
+ var state = await scenario.FailAttemptAsync(scenario.CurrentAttempt!, failure);
+ await Assert.That(state.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(events.RetainedCount).IsEqualTo(2);
+ scenario.Time.Advance(EventStreamSteps.Delay);
+ var retry = await scenario.Attempts.NextOpenAsync();
+ await retry.PublishAsync(SharedEventFeedScenario.Marker("after-drop"));
+
+ string?[] delivered = [(await EventStreamSteps.NextAsync(events)).Id, (await EventStreamSteps.NextAsync(events)).Id,
+ (await EventStreamSteps.NextAsync(events)).Id];
+ await Assert.That(delivered).IsEquivalentTo((string?[])["queued-one", "queued-two", "after-drop"], CollectionOrdering.Matching);
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(2);
+ }
+
+ [Test]
+ public async Task OpenAsync_Should_Fault_Synchronously_Without_Retry_And_Allow_A_Fresh_Subscription()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ var failure = new InvalidOperationException("synchronous source creation");
+ var opened = new List();
+ scenario.Attempts.OnOpen = () =>
+ {
+ opened.Add(scenario.Feed.GetCurrentSource()!);
+ throw failure;
+ };
+ for (var attempt = 1; attempt <= 2; attempt++)
+ {
+ await using var events = scenario.CreateSubscription();
+ await using var watcher = scenario.CreateWatcher();
+ Task? moving = null;
+ Task? connecting = null;
+ scenario.Feed.WithGate(_ =>
+ {
+ moving = EventStreamSteps.PendingNext(events);
+ connecting = EventStreamSteps.PendingNext(watcher);
+ });
+ await Assert.That(await connecting!.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Connecting);
+ var idle = await EventStreamSteps.NextAsync(watcher);
+ await Assert.That(idle.Status).IsEqualTo(EventConnectionStatus.Idle);
+ var observed = await Assert.That(moving!).Throws();
+ await Assert.That(observed).IsSameReferenceAs(failure);
+ await scenario.Feed.JoinAsync().WaitAsync(HangGuard.Bound);
+ await Assert.That(opened.Count).IsEqualTo(attempt);
+ await Assert.That(opened[^1].Token.IsCancellationRequested).IsTrue();
+ await Assert.That(scenario.Time.ArmedIn(EventStreamSteps.Delay)).IsEqualTo(0);
+ }
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task SubscribeAsync_Should_Not_Reconnect_The_Durable_Session_Log(bool failureFrame)
+ {
+ var fixtures = new FixtureLoader();
+ var tail = failureFrame
+ ? WireBodyData.NamedFrame("effect/http-api/stream/failure", WireBodyData.StreamFailureCause)
+ : WireBodyData.Frames(WireBodyData.LogSyncedEvent);
+ using var scenario = ContractScenario.RespondingWithFrames(WireBodyData.Frames(
+ fixtures.LoadJson("Events.session-created.json"), fixtures.LoadJson("Events.session-deleted.json")) + tail);
+ var received = new List();
+ async Task ReadAsync()
+ {
+ await foreach (var item in scenario.Client.Experimental.ReadSessionLogAsync("ses_9"))
+ {
+ received.Add(item);
+ }
+ }
+
+ var reading = ReadAsync();
+ if (failureFrame)
+ {
+ var failure = await Assert.That(reading.WaitAsync(HangGuard.Bound)).Throws();
+ await Assert.That(((StreamFailureCauseDie)failure!.Causes.Single()).Defect.GetString()).IsEqualTo("boom");
+ }
+ else
+ {
+ _ = await Assert.That(reading.WaitAsync(HangGuard.Bound)).ThrowsNothing();
+ }
+
+ string[] expected = failureFrame ? ["session.created", "session.deleted"] : ["session.created", "session.deleted", "log.synced"];
+ await Assert.That(received.Select(static item => item.Type)).IsEquivalentTo(expected, CollectionOrdering.Matching);
+ await Assert.That(((SessionCreated)received[0]).Id).IsEqualTo("evt_1");
+ await Assert.That(((SessionDeleted)received[1]).Id).IsEqualTo("evt_2");
+ await Assert.That(scenario.Requests.Single().RequestUri!.AbsolutePath).IsEqualTo("/api/experimental/session/ses_9/log");
+ var state = scenario.Client.Events.GetConnectionState();
+ await Assert.That(state.Status).IsEqualTo(EventConnectionStatus.Idle);
+ await Assert.That(state.Attempt).IsEqualTo(0);
+ await Assert.That(state.Error).IsNull();
+ }
+
+ [Test]
+ public async Task GetConnectionState_Should_Start_A_Fresh_Retry_Counter_After_A_Source_Fault()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = scenario.Feed.Subscribe(EventSelection.Capture(null), default).GetAsyncEnumerator();
+ var moving = EventStreamSteps.PendingNext(events);
+ var failed = await scenario.Attempts.NextOpenAsync();
+ _ = failed.Items.Writer.TryComplete(new OpenCodeTransportException("first failure"));
+ failed.ReleaseCleanup();
+ await scenario.Time.WaitForArmedAsync(EventStreamSteps.Delay, HangGuard.Bound);
+ scenario.Time.Advance(EventStreamSteps.Delay);
+ var connected = await scenario.Attempts.NextOpenAsync();
+ await connected.PublishAsync(SharedEventFeedScenario.Marker("M"));
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ connected.CleanupFailure = new InvalidOperationException("escaping cleanup");
+ _ = connected.Items.Writer.TryComplete();
+ connected.ReleaseCleanup();
+ await scenario.Feed.JoinAsync().WaitAsync(HangGuard.Bound);
+ await using var fresh = await scenario.AdmitAsync("M2");
+ var failure = new OpenCodeTransportException("fresh failure");
+ var state = await scenario.FailAttemptAsync(scenario.CurrentAttempt!, failure);
+ await Assert.That(state.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(state.Attempt).IsEqualTo(1);
+ await Assert.That(state.Error).IsSameReferenceAs(failure);
+ await Assert.That(fresh.Current.Id).IsEqualTo("M2");
+ }
+
+ [Test]
+ [Arguments(400, WireBodyData.InvalidRequestError, typeof(InvalidRequestError))]
+ [Arguments(401, WireBodyData.UnauthorizedError, typeof(UnauthorizedError))]
+ public async Task SubscribeAsync_Should_Keep_Retrying_Past_One_Minute_And_Expose_The_Last_Attempt_Error(
+ int status, string body, Type errorType)
+ {
+ const int failures = 61;
+ using var server = new ScriptedEventServer(index => index <= failures
+ ? ScriptedEventServer.Status((HttpStatusCode)status, body)
+ : ScriptedEventServer.StreamOf(EventStreamSteps.ConnectedFrame));
+ await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
+ var moving = EventStreamSteps.PendingNext(events);
+ using var waiter = new CancellationTokenSource();
+ Task? armed = null;
+ try
+ {
+ for (var attempt = 1; attempt <= failures; attempt++)
+ {
+ armed = server.Time.WaitForArmedOrCanceledAsync(EventStreamSteps.Delay, HangGuard.Bound, waiter.Token);
+ var completed = await Task.WhenAny(armed, moving).WaitAsync(HangGuard.Bound);
+ await Assert.That(completed).IsSameReferenceAs(armed);
+ await armed;
+ var state = server.Events.GetConnectionState();
+ await Assert.That(state.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(state.Attempt).IsEqualTo(attempt);
+ await Assert.That(state.Error).IsTypeOf();
+ var failure = (OpenCodeApiException)state.Error!;
+ await Assert.That(failure.Status).IsEqualTo(status);
+ await Assert.That(failure.Error!.GetType()).IsEqualTo(errorType);
+ await Assert.That(failure.RawBody).IsEqualTo(body);
+ server.Time.Advance(EventStreamSteps.Delay);
+ }
+ }
+ finally
+ {
+ await waiter.CancelOnWorkerAsync();
+ if (armed is { IsCanceled: true })
+ {
+ _ = await Assert.That(armed).Throws();
+ }
+ }
+
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(events.Current.Type).IsEqualTo("server.connected");
+ await Assert.That(server.RequestCount).IsEqualTo(62);
+ var connected = server.Events.GetConnectionState();
+ await Assert.That(connected.Status).IsEqualTo(EventConnectionStatus.Connected);
+ await Assert.That(connected.Attempt).IsEqualTo(0);
+ await Assert.That(connected.Error).IsNull();
+ }
+
+ [Test]
+ public async Task GetConnectionState_Should_Report_The_Latest_Classified_Failure()
+ {
+ using var server = new ScriptedEventServer(index => index switch
+ {
+ 1 => ScriptedEventServer.Status(HttpStatusCode.Unauthorized, WireBodyData.UnauthorizedError),
+ 2 => ScriptedEventServer.Status(HttpStatusCode.InternalServerError, WireBodyData.UnauthorizedError),
+ _ => ScriptedEventServer.StreamOf(EventStreamSteps.ConnectedFrame),
+ });
+ await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
+ var moving = EventStreamSteps.PendingNext(events);
+ await server.Time.WaitForArmedAsync(EventStreamSteps.Delay, HangGuard.Bound);
+ var first = server.Events.GetConnectionState().Error;
+ await Assert.That(((OpenCodeApiException)first!).Status).IsEqualTo(401);
+ server.Time.Advance(EventStreamSteps.Delay);
+ await server.Time.WaitForArmedAsync(EventStreamSteps.Delay, HangGuard.Bound);
+ var latest = server.Events.GetConnectionState();
+ await Assert.That(latest.Attempt).IsEqualTo(2);
+ await Assert.That(latest.Error).IsNotSameReferenceAs(first);
+ await Assert.That(((OpenCodeApiException)latest.Error!).Status).IsEqualTo(500);
+ server.Time.Advance(EventStreamSteps.Delay);
+ await EventStreamSteps.AssertConnectedAsync(events, await moving.WaitAsync(HangGuard.Bound));
+ }
+
+ [Test]
+ public async Task GetConnectionState_Should_Report_The_Ended_Text_Without_Ending_The_Subscription()
+ {
+ using var server = new ScriptedEventServer(index => ScriptedEventServer.StreamOf(EventStreamSteps.ConnectedFrame, ends: index == 1));
+ await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
+ await Assert.That((await EventStreamSteps.NextAsync(events)).Type).IsEqualTo("server.connected");
+ var moving = EventStreamSteps.PendingNext(events);
+ await server.Time.WaitForArmedAsync(EventStreamSteps.Delay, HangGuard.Bound);
+ var state = server.Events.GetConnectionState();
+ await Assert.That(state.Error).IsTypeOf();
+ await Assert.That(state.Error!.Message).IsEqualTo("The opencode event stream ended.");
+ server.Time.Advance(EventStreamSteps.Delay);
+ await EventStreamSteps.AssertConnectedAsync(events, await moving.WaitAsync(HangGuard.Bound));
+ }
+
+ [Test]
+ public async Task GetConnectionState_Should_Report_A_Typed_Stream_Failure_Cause_Then_Recover()
+ {
+ using var server = new ScriptedEventServer(index => index == 1
+ ? ScriptedEventServer.StreamOf(WireBodyData.NamedFrame("effect/http-api/stream/failure", WireBodyData.StreamFailureCause))
+ : ScriptedEventServer.StreamOf(EventStreamSteps.ConnectedFrame));
+ await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
+ var moving = EventStreamSteps.PendingNext(events);
+ await server.Time.WaitForArmedAsync(EventStreamSteps.Delay, HangGuard.Bound);
+ var state = server.Events.GetConnectionState();
+ await Assert.That(state.Error).IsTypeOf();
+ var cause = (StreamFailureCauseDie)((OpenCodeStreamFailureException)state.Error!).Causes.Single();
+ await Assert.That(cause.Defect.ValueKind).IsEqualTo(JsonValueKind.String);
+ await Assert.That(cause.Defect.GetString()).IsEqualTo("boom");
+ server.Time.Advance(EventStreamSteps.Delay);
+ await EventStreamSteps.AssertConnectedAsync(events, await moving.WaitAsync(HangGuard.Bound));
+ }
+
+ [Test]
+ [Arguments(0)]
+ [Arguments(1)]
+ [Arguments(2)]
+ [Arguments(3)]
+ public async Task GetConnectionState_Should_Classify_Opening_And_Stalled_Error_Body_Windows_Then_Recover(int kind)
+ {
+ using var body = new BlockingContent();
+ if (kind == 1)
+ {
+ body.Headers.ContentType = new MediaTypeHeaderValue("text/event-stream");
+ }
+
+ var status = kind switch
+ {
+ 1 => HttpStatusCode.OK,
+ 2 => HttpStatusCode.Unauthorized,
+ _ => HttpStatusCode.InternalServerError,
+ };
+ using var server = new ScriptedEventServer(index =>
+ {
+ if (index != 1)
+ {
+ return ScriptedEventServer.StreamOf(EventStreamSteps.ConnectedFrame);
+ }
+
+ return kind == 0 ? ScriptedEventServer.Silence : new HttpResponseMessage(status) { Content = body };
+ });
+ await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
+ var moving = EventStreamSteps.PendingNext(events);
+ await server.WaitForRequestAsync(1, HangGuard.Bound);
+ if (kind != 0)
+ {
+ var reading = body.ReadStarted.ContinueWith(static task => task.Status,
+ CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
+ await Assert.That(await reading.WaitAsync(HangGuard.Bound)).IsEqualTo(TaskStatus.RanToCompletion);
+ }
+
+ await server.Time.WaitForArmedAsync(EventStreamSteps.ConnectBound, HangGuard.Bound);
+ server.Time.Advance(EventStreamSteps.ConnectBound);
+ await server.Time.WaitForArmedAsync(EventStreamSteps.Delay, HangGuard.Bound);
+ var state = server.Events.GetConnectionState();
+ await Assert.That(state.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(state.Error).IsTypeOf();
+ await Assert.That(state.Error!.Message).IsEqualTo(kind == 0
+ ? "The opencode server did not answer the event stream request within 2 seconds."
+ : "The opencode server answered the event stream request but sent no event within 2 seconds.");
+ if (kind != 0)
+ {
+ await Assert.That(body.IsDisposed).IsTrue();
+ }
+
+ server.Time.Advance(EventStreamSteps.Delay);
+ await EventStreamSteps.AssertConnectedAsync(events, await moving.WaitAsync(HangGuard.Bound));
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task GetConnectionState_Should_Publish_Attempt_1_After_A_Connection_That_Lived_One_Second(bool longConnection)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = scenario.Feed.Subscribe(EventSelection.Capture(null), default).GetAsyncEnumerator();
+ var moving = EventStreamSteps.PendingNext(events);
+ var first = await scenario.Attempts.NextOpenAsync();
+ _ = first.Items.Writer.TryComplete(new OpenCodeTransportException("first open"));
+ first.ReleaseCleanup();
+ await scenario.Time.WaitForArmedAsync(EventStreamSteps.Delay, HangGuard.Bound);
+ scenario.Time.Advance(EventStreamSteps.Delay);
+ var second = await scenario.Attempts.NextOpenAsync();
+ await second.PublishAsync(SharedEventFeedScenario.Marker("M"));
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(scenario.Feed.GetConnectionState().Attempt).IsEqualTo(0);
+ scenario.Time.Advance(longConnection ? TimeSpan.FromSeconds(1) : TimeSpan.FromSeconds(1) - EventStreamSteps.OneTick);
+ var failure = new OpenCodeTransportException("connected drop");
+ var state = await scenario.FailAttemptAsync(second, failure);
+ await Assert.That(state.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(state.Attempt).IsEqualTo(longConnection ? 1 : 2);
+ await Assert.That(state.Error).IsSameReferenceAs(failure);
+ }
+
+ [Test]
+ public async Task GetConnectionState_Should_Keep_Error_Through_The_Next_Attempt_And_Clear_It_On_Connected_Or_Idle()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ var failure = new OpenCodeTransportException("drop");
+ _ = await scenario.FailAttemptAsync(scenario.CurrentAttempt!, failure);
+ scenario.Time.Advance(EventStreamSteps.Delay);
+ var replacement = await scenario.Attempts.NextOpenAsync();
+ var opening = scenario.Feed.GetConnectionState();
+ await Assert.That(opening.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(opening.Attempt).IsEqualTo(1);
+ await Assert.That(opening.Error).IsSameReferenceAs(failure);
+ await replacement.PublishAsync(SharedEventFeedScenario.Marker("M2"));
+ var connected = scenario.Feed.GetConnectionState();
+ await Assert.That(connected.Status).IsEqualTo(EventConnectionStatus.Connected);
+ await Assert.That(connected.Attempt).IsEqualTo(0);
+ await Assert.That(connected.Error).IsNull();
+ await events.DisposeAsync();
+ var idle = scenario.Feed.GetConnectionState();
+ await Assert.That(idle.Status).IsEqualTo(EventConnectionStatus.Idle);
+ await Assert.That(idle.Attempt).IsEqualTo(0);
+ await Assert.That(idle.Error).IsNull();
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task RunAsync_Should_Not_Carry_The_First_Subscribers_ExecutionContext(bool alreadySuppressed)
+ {
+ var ambient = new AsyncLocal { Value = "caller scope" };
+ string? observed = null;
+ var observations = 0;
+ await using var scenario = new SharedEventFeedScenario();
+ scenario.Attempts.OnOpen = () =>
+ {
+ observations++;
+ observed = ambient.Value;
+ };
+ await using var events = scenario.Feed.Subscribe(EventSelection.Capture(null), default).GetAsyncEnumerator();
+ Task moving;
+ if (alreadySuppressed)
+ {
+ using (ExecutionContext.SuppressFlow())
+ {
+ moving = EventStreamSteps.PendingNext(events);
+ }
+ }
+ else
+ {
+ moving = EventStreamSteps.PendingNext(events);
+ }
+
+ var attempt = await scenario.Attempts.NextOpenAsync();
+ await Assert.That(observations).IsEqualTo(1);
+ await Assert.That(observed).IsNull();
+ await Assert.That(ambient.Value).IsEqualTo("caller scope");
+ await attempt.PublishAsync(SharedEventFeedScenario.Marker("M"));
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(events.Current.Id).IsEqualTo("M");
+ }
+
+ [Test]
+ public async Task GetConnectionState_Should_Publish_Connecting_Then_Connected_Then_Reconnecting()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = scenario.Feed.Subscribe(EventSelection.Capture(null), default).GetAsyncEnumerator();
+ var moving = EventStreamSteps.PendingNext(events);
+ var opening = scenario.Feed.GetConnectionState();
+ await Assert.That(opening.Status).IsEqualTo(EventConnectionStatus.Connecting);
+ await Assert.That(opening.Attempt).IsEqualTo(0);
+ await Assert.That(opening.Error).IsNull();
+ var attempt = await scenario.Attempts.NextOpenAsync();
+ await attempt.PublishAsync(SharedEventFeedScenario.Marker("M"));
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(events.Current.Id).IsEqualTo("M");
+ var connected = scenario.Feed.GetConnectionState();
+ await Assert.That(connected.Status).IsEqualTo(EventConnectionStatus.Connected);
+ await Assert.That(connected.Attempt).IsEqualTo(0);
+ await Assert.That(connected.Error).IsNull();
+ var failure = new OpenCodeTransportException("lost connection");
+ var reconnecting = await scenario.FailAttemptAsync(attempt, failure);
+ await Assert.That(reconnecting.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(reconnecting.Attempt).IsEqualTo(1);
+ await Assert.That(reconnecting.Error).IsSameReferenceAs(failure);
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventSourceTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventSourceTests.cs
new file mode 100644
index 000000000..6762909f4
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/EventSourceTests.cs
@@ -0,0 +1,119 @@
+using OpenCode.Sdk.Tests.Events.Support;
+using OpenCode.Sdk.Tests.Support;
+using TUnit.Assertions.Enums;
+
+namespace OpenCode.Sdk.Tests.Events;
+
+public sealed class EventSourceTests
+{
+ [Test]
+ public async Task RecordFault_Should_Observe_A_Retired_Cancel_Failure_Without_Changing_The_Replacement()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var first = await scenario.AdmitAsync("M1");
+ var source = scenario.Feed.GetCurrentSource()!;
+ var oldAttempt = scenario.CurrentAttempt!;
+ var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ using var release = new ManualResetEventSlim();
+ var failure = new InvalidOperationException("retired cancellation callback");
+ using var registration = source.Token.UnsafeRegister(_ =>
+ {
+ entered.SetResult();
+ if (!release.Wait(HangGuard.Bound))
+ {
+ throw new TimeoutException("The test did not release retired cancellation.");
+ }
+
+ throw failure;
+ }, state: null);
+ try
+ {
+ await first.DisposeAsync();
+ await entered.Task.WaitAsync(HangGuard.Bound);
+ await using var replacement = await scenario.AdmitAsync("M2");
+ var current = scenario.Feed.GetCurrentSource();
+ _ = oldAttempt.Items.Writer.TryComplete();
+ oldAttempt.ReleaseCleanup();
+ await EventStreamSteps.ObserveSourceCompletionAsync(source);
+ await Assert.That(source.IsReleased).IsFalse();
+ release.Set();
+ await EventStreamSteps.ObserveSourceCompletionAsync(source, cancellation: true);
+
+ Exception[] expected = [failure];
+ await Assert.That(source.CancellationFailure!.InnerExceptions).IsEquivalentTo(expected, CollectionOrdering.Matching);
+ await Assert.That(source.IsReleased).IsTrue();
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsSameReferenceAs(current);
+ await scenario.PublishAsync("E2");
+ await Assert.That((await EventStreamSteps.NextAsync(replacement)).Id).IsEqualTo("E2");
+ }
+ finally
+ {
+ release.Set();
+ oldAttempt.ReleaseCleanup();
+ if (source.CancellationObservation is { } observing)
+ {
+ await observing.WaitAsync(HangGuard.Bound);
+ }
+ }
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task RequestStop_Should_Observe_Runner_And_Worker_Cancellation_Before_Releasing_The_Cts(bool failCancellation)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ var attempt = scenario.CurrentAttempt!;
+ var source = scenario.Feed.GetCurrentSource()!;
+ var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ using var release = new ManualResetEventSlim();
+ var failure = new InvalidOperationException("cancel callback");
+ using var registration = source.Token.UnsafeRegister(_ =>
+ {
+ entered.SetResult();
+ if (!release.Wait(HangGuard.Bound))
+ {
+ throw new TimeoutException("The test did not release the cancellation callback.");
+ }
+
+ if (failCancellation)
+ {
+ throw failure;
+ }
+ }, state: null);
+
+ try
+ {
+ await events.DisposeAsync();
+ await entered.Task.WaitAsync(HangGuard.Bound);
+ _ = attempt.Items.Writer.TryComplete();
+ attempt.ReleaseCleanup();
+ await EventStreamSteps.ObserveSourceCompletionAsync(source);
+
+ await Assert.That(source.IsReleased).IsFalse();
+ await Assert.That(source.Token.IsCancellationRequested).IsTrue();
+ }
+ finally
+ {
+ release.Set();
+ if (source.CancellationObservation is { } observing)
+ {
+ await observing.WaitAsync(HangGuard.Bound);
+ }
+ }
+
+ await Assert.That(source.CancellationObservation).IsNotNull();
+ await scenario.Feed.JoinAsync().WaitAsync(HangGuard.Bound);
+ await Assert.That(source.IsReleased).IsTrue();
+ if (failCancellation)
+ {
+ Exception[] expected = [failure];
+ await Assert.That(source.CancellationFailure!.InnerExceptions).IsEquivalentTo(expected, CollectionOrdering.Matching);
+ }
+ else
+ {
+ await Assert.That(source.CancellationFailure).IsNull();
+ }
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventStateWatcherTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventStateWatcherTests.cs
new file mode 100644
index 000000000..9dfc3e27e
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/EventStateWatcherTests.cs
@@ -0,0 +1,177 @@
+using OpenCode.Sdk.Internal;
+using OpenCode.Sdk.Tests.Events.Support;
+using OpenCode.Sdk.Tests.Support;
+
+namespace OpenCode.Sdk.Tests.Events;
+
+public sealed class EventStateWatcherTests
+{
+ [Test]
+ public async Task WatchConnectionAsync_Should_Refuse_A_Pull_On_The_Unenumerated_Recipe()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var recipe = (IAsyncEnumerator)scenario.Feed.Watch(default);
+ await EventStreamSteps.AssertRecipePullRefusedAsync(recipe);
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task WatchConnectionAsync_Should_Remain_Alive_And_Report_Idle_After_A_Source_Fault()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ await using var watcher = scenario.CreateWatcher();
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Connected);
+ var failure = new InvalidOperationException("source cleanup");
+ await scenario.FaultAsync(failure);
+
+ var idle = await EventStreamSteps.NextAsync(watcher);
+ await EventStreamSteps.AssertStateAsync(idle, EventConnectionStatus.Idle, 0, null);
+ var observed = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(observed).IsSameReferenceAs(failure);
+ await using var replacement = await scenario.AdmitAsync("M2");
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Connected);
+ await Assert.That(replacement.Current.Id).IsEqualTo("M2");
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task WatchConnectionAsync_Should_Select_The_Initial_Snapshot_Atomically_With_Registration(bool watchFirst)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ var source = scenario.Feed.GetCurrentSource()!;
+ await using var watcher = scenario.CreateWatcher();
+ if (watchFirst)
+ {
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Connected);
+ }
+
+ var failure = new OpenCodeTransportException("drop");
+ scenario.Feed.RecordDrop(source, failure, 1);
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(watcher.Current.Attempt).IsEqualTo(1);
+ await Assert.That(watcher.Current.Error).IsSameReferenceAs(failure);
+ }
+
+ [Test]
+ public async Task WatchConnectionAsync_Should_Coalesce_To_The_Latest_Unread_Snapshot()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ var source = scenario.Feed.GetCurrentSource()!;
+ await using var watcher = scenario.CreateWatcher();
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ var earlier = new OpenCodeTransportException("earlier");
+ var latest = new OpenCodeTransportException("latest");
+ scenario.Feed.RecordDrop(source, earlier, 1);
+ scenario.Feed.RecordDrop(source, latest, 2);
+ var moving = EventStreamSteps.PendingNext(watcher);
+ var after = new OpenCodeTransportException("after selection");
+ scenario.Feed.RecordDrop(source, after, 3);
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(watcher.Current.Attempt).IsEqualTo(2);
+ await Assert.That(watcher.Current.Error).IsSameReferenceAs(latest);
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Attempt).IsEqualTo(3);
+ await Assert.That(watcher.Current.Error).IsSameReferenceAs(after);
+ moving = EventStreamSteps.PendingNext(watcher);
+ scenario.Feed.RecordConnected(source, SharedEventFeedScenario.Marker("M2"));
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Connected);
+ moving = EventStreamSteps.PendingNext(watcher);
+ await Assert.That(moving.IsCompleted).IsFalse();
+ scenario.Feed.RecordDrop(source, earlier, 4);
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Attempt).IsEqualTo(4);
+ await Assert.That(watcher.Current.Error).IsSameReferenceAs(earlier);
+ }
+
+ [Test]
+ public async Task GetConnectionState_Should_Throw_ObjectDisposedException_After_Disposal()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var watcher = scenario.CreateWatcher();
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ var pending = EventStreamSteps.PendingNext(watcher);
+ scenario.Feed.Dispose();
+
+ _ = await Assert.That(scenario.Feed.GetConnectionState).Throws();
+ _ = await Assert.That(pending).Throws();
+ await Assert.That(scenario.Feed.WatcherCount).IsEqualTo(0);
+ await watcher.DisposeAsync();
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsFalse();
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ }
+
+ [Test]
+ [Arguments(false, false)]
+ [Arguments(false, true)]
+ [Arguments(true, false)]
+ [Arguments(true, true)]
+ public async Task WatchConnectionAsync_Should_Observe_The_Enumerator_Token_Without_Another_Pull(bool sameToken, bool cancelEnumerator)
+ {
+ using var caller = new CancellationTokenSource();
+ using var enumeration = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var watcher = scenario.CreateWatcher(caller.Token, sameToken ? caller.Token : enumeration.Token);
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Idle);
+ await Assert.That(watcher.RegistrationCount).IsEqualTo(sameToken ? 1 : 2);
+ await Assert.That(scenario.Feed.WatcherCount).IsEqualTo(1);
+ await (cancelEnumerator && !sameToken ? enumeration : caller).CancelOnWorkerAsync();
+
+ await Assert.That(watcher.RegistrationCount).IsEqualTo(0);
+ await Assert.That(scenario.Feed.WatcherCount).IsEqualTo(0);
+ var canceled = await EventStreamSteps.PendingCancellationAsync(watcher).WaitAsync(HangGuard.Bound);
+ await Assert.That(canceled).IsNotNull();
+ if (sameToken)
+ {
+ await Assert.That(canceled!.CancellationToken).IsEqualTo(caller.Token);
+ }
+
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task WatchConnectionAsync_Should_Dispose_Its_Own_Registration_From_The_Cancellation_Callback()
+ {
+ using var caller = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var watcher = scenario.CreateWatcher(caller.Token);
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ await DedicatedThread.Run(caller.Cancel).WaitAsync(HangGuard.Bound);
+
+ await Assert.That(watcher.RegistrationCount).IsEqualTo(0);
+ await Assert.That(scenario.Feed.WatcherCount).IsEqualTo(0);
+ var canceled = await Assert.That(async () => await watcher.MoveNextAsync()).Throws();
+ await Assert.That(canceled!.CancellationToken).IsEqualTo(caller.Token);
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task GetConnectionState_Should_Start_Idle_And_Not_Open_A_Source()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ var initial = scenario.Feed.GetConnectionState();
+ await Assert.That(initial.Status).IsEqualTo(EventConnectionStatus.Idle);
+ await Assert.That(initial.Attempt).IsEqualTo(0);
+ await Assert.That(initial.Error).IsNull();
+ await using var watcher = scenario.CreateWatcher();
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current).IsSameReferenceAs(initial);
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ await using var events = await scenario.AdmitAsync("M");
+ await events.DisposeAsync();
+ var idle = await EventStreamSteps.NextAsync(watcher);
+ await EventStreamSteps.AssertStateAsync(idle, EventConnectionStatus.Idle, 0, null);
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(1);
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventSubscriptionTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventSubscriptionTests.cs
new file mode 100644
index 000000000..18de738a7
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/EventSubscriptionTests.cs
@@ -0,0 +1,561 @@
+using NSubstitute;
+using OpenCode.Sdk.Internal;
+using OpenCode.Sdk.Models;
+using OpenCode.Sdk.Tests.Events.Support;
+using OpenCode.Sdk.Tests.Support;
+using TUnit.Assertions.Enums;
+
+namespace OpenCode.Sdk.Tests.Events;
+
+public sealed class EventSubscriptionTests
+{
+ [Test]
+ public async Task MoveNextAsync_Should_Keep_The_Stored_Faults_Stack_Stable_On_Repeated_Pulls()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("stack-marker");
+ var failure = new InvalidOperationException("stable dispatch");
+ await scenario.FaultAsync(failure);
+ var traces = new List();
+ for (var pull = 0; pull < 3; pull++)
+ {
+ var observed = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(observed).IsSameReferenceAs(failure);
+ traces.Add(observed!.StackTrace);
+ }
+
+ await Assert.That(traces[1]).IsNotNull();
+ await Assert.That(traces[2]).IsEqualTo(traces[1]);
+ }
+
+ [Test]
+ [Arguments("fault")]
+ [Arguments("root")]
+ [Arguments("false")]
+ [Arguments("overflow")]
+ public async Task MoveNextAsync_Should_Report_Cancellation_After_Overflow_Or_A_Stored_Ending(string ending)
+ {
+ using var caller = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M", caller.Token);
+ var failure = new InvalidOperationException("source cleanup");
+ switch (ending)
+ {
+ case "fault":
+ await scenario.FaultAsync(failure);
+ var observed = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(observed).IsSameReferenceAs(failure);
+ break;
+ case "root":
+ scenario.Feed.Dispose();
+ _ = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ break;
+ case "false":
+ await events.DisposeAsync();
+ await Assert.That(await events.MoveNextAsync()).IsFalse();
+ break;
+ default:
+ for (var index = 0; index < 4097; index++)
+ {
+ await scenario.PublishAsync("overflow");
+ }
+
+ _ = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ break;
+ }
+
+ await EventStreamSteps.CancelAndCaptureAsync(caller, events);
+ await Assert.That(events.RetainedCount).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Release_The_First_Lease_When_The_Second_Token_Registers_Cancelled()
+ {
+ using var caller = new CancellationTokenSource();
+ using var enumeration = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = new EventSubscription(scenario.Feed, EventSelection.Capture(null), caller.Token, enumeration.Token);
+ events.Precheck();
+ scenario.Feed.Adopt(events, events.RegisterToken(caller.Token));
+ await Assert.That(events.RegistrationCount).IsEqualTo(1);
+ await enumeration.CancelOnWorkerAsync();
+ scenario.Feed.Adopt(events, events.RegisterToken(enumeration.Token));
+
+ await Assert.That(events.RegistrationCount).IsEqualTo(0);
+ var completion = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously);
+ scenario.Feed.WithGate(work => events.MoveLocked(new EventPendingMove(completion), work));
+ var result = await completion.Task;
+ await Assert.That(result.Error).IsTypeOf();
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task MoveNextAsync_Should_Release_Registrations_When_Cancellation_Runs_Inline(bool disposeBeforeAdoption)
+ {
+ using var caller = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = scenario.CreateSubscription(caller.Token);
+ events.Precheck();
+ if (!disposeBeforeAdoption)
+ {
+ await caller.CancelOnWorkerAsync();
+ }
+
+ var lease = events.RegisterToken(caller.Token);
+ if (disposeBeforeAdoption)
+ {
+ await events.DisposeAsync();
+ }
+
+ scenario.Feed.Adopt(events, lease);
+ await EventStreamSteps.CancelAndCaptureAsync(caller, events);
+ await AssertNoAdmissionAsync(scenario, events);
+ }
+
+ [Test]
+ [Arguments(false, false)]
+ [Arguments(false, true)]
+ [Arguments(true, false)]
+ [Arguments(true, true)]
+ public async Task MoveNextAsync_Should_Observe_Both_Entry_Tokens_And_Preserve_One_Tokens_Identity(bool sameToken, bool cancelEnumerator)
+ {
+ using var caller = new CancellationTokenSource();
+ using var enumeration = new CancellationTokenSource();
+ var enumeratorToken = sameToken ? caller.Token : enumeration.Token;
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = scenario.CreateSubscription(caller.Token, enumeratorToken);
+ var moving = EventStreamSteps.PendingNext(events);
+ var attempt = await scenario.Attempts.NextOpenAsync();
+ await attempt.PublishAsync(SharedEventFeedScenario.Marker("M"));
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(events.Current.Id).IsEqualTo("M");
+ await Assert.That(events.RegistrationCount).IsEqualTo(sameToken ? 1 : 2);
+ await (cancelEnumerator && !sameToken ? enumeration : caller).CancelOnWorkerAsync();
+
+ await Assert.That(events.RegistrationCount).IsEqualTo(0);
+ var canceled = await EventStreamSteps.PendingCancellationAsync(events).WaitAsync(HangGuard.Bound);
+ await Assert.That(canceled).IsNotNull();
+ if (sameToken)
+ {
+ await Assert.That(canceled!.CancellationToken).IsEqualTo(caller.Token);
+ }
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Keep_A_Publication_That_Precedes_Cancellation()
+ {
+ using var caller = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M", caller.Token);
+ var moving = EventStreamSteps.PendingNext(events);
+ await scenario.PublishAsync("E1");
+ await caller.CancelOnWorkerAsync();
+
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(events.Current.Id).IsEqualTo("E1");
+ var canceled = await EventStreamSteps.PendingCancellationAsync(events).WaitAsync(HangGuard.Bound);
+ await Assert.That(canceled!.CancellationToken).IsEqualTo(caller.Token);
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Keep_4096_Queued_Selected_Events_In_Order()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ string?[] expected = [.. Enumerable.Range(1, 4096).Select(static index =>
+ "E" + index.ToString(System.Globalization.CultureInfo.InvariantCulture))];
+ foreach (var id in expected)
+ {
+ await scenario.PublishAsync(id!);
+ }
+
+ var received = new List();
+ for (var index = 0; index < 4096; index++)
+ {
+ received.Add((await EventStreamSteps.NextAsync(events)).Id);
+ }
+
+ await Assert.That(received).IsEquivalentTo(expected, CollectionOrdering.Matching);
+ await Assert.That(events.RetainedCount).IsEqualTo(0);
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task MoveNextAsync_Should_Not_Count_A_Pending_Handoff_As_A_Queue_Slot(bool replay)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var owner = await scenario.AdmitAsync("M");
+ await Assert.That(owner.RetainedCount).IsEqualTo(0);
+ await using var events = replay
+ ? (EventSubscription)scenario.Feed.Subscribe(EventSelection.Capture(null), default).GetAsyncEnumerator()
+ : owner;
+ var pending = events.MoveNextAsync().AsTask();
+ if (!replay)
+ {
+ await scenario.PublishAsync("E0");
+ }
+
+ await Assert.That(events.RetainedCount).IsEqualTo(0);
+ for (var index = 1; index <= 4097; index++)
+ {
+ await scenario.PublishAsync("E" + index.ToString(System.Globalization.CultureInfo.InvariantCulture));
+ }
+
+ await Assert.That(await pending.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(events.Current.Id).IsEqualTo(replay ? "M" : "E0");
+ _ = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(events.RetainedCount).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Check_Live_Cancellation_Before_A_Publication_Handoff()
+ {
+ using var caller = new CancellationTokenSource();
+ using var release = new ManualResetEventSlim();
+ var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var probe = Substitute.For();
+ probe.When(static item => item.OnPublication()).Do(_ =>
+ {
+ entered.SetResult();
+ if (!release.Wait(HangGuard.Bound))
+ {
+ throw new TimeoutException("The test did not release publication.");
+ }
+ });
+ await using var scenario = new SharedEventFeedScenario(probe);
+ await using var events = await scenario.AdmitAsync("M", caller.Token);
+ var pending = EventStreamSteps.PendingCancellationAsync(events);
+ Task? canceling = null;
+ var publishing = scenario.PublishAsync("E1");
+ try
+ {
+ await entered.Task.WaitAsync(HangGuard.Bound);
+ canceling = DedicatedThread.Run(caller.Cancel);
+ var visible = DedicatedThread.Run(() => caller.Token.WaitHandle.WaitOne(HangGuard.Bound));
+ await Assert.That(await visible.WaitAsync(HangGuard.Bound)).IsTrue();
+ }
+ finally
+ {
+ release.Set();
+ await publishing.WaitAsync(HangGuard.Bound);
+ if (canceling is not null)
+ {
+ await canceling.WaitAsync(HangGuard.Bound);
+ }
+ }
+
+ var canceled = await pending.WaitAsync(HangGuard.Bound);
+ await Assert.That(canceled).IsNotNull();
+ await Assert.That(canceled!.CancellationToken).IsEqualTo(caller.Token);
+ await Assert.That(events.RegistrationCount).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Report_Cancellation_Before_Disposal_At_Admission()
+ {
+ using var caller = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = scenario.CreateSubscription(caller.Token);
+ events.Precheck();
+ await caller.CancelOnWorkerAsync();
+ var lease = events.RegisterToken(caller.Token);
+ scenario.Feed.Dispose();
+ scenario.Feed.Adopt(events, lease);
+ var completion = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously);
+ var move = new EventPendingMove(completion);
+ scenario.Feed.WithGate(work => events.MoveLocked(move, work));
+ var result = await completion.Task;
+
+ await Assert.That(result.Error).IsTypeOf();
+ await Assert.That(((OperationCanceledException)result.Error!).CancellationToken).IsEqualTo(caller.Token);
+ await AssertNoAdmissionAsync(scenario, events);
+ }
+
+ [Test]
+ [Arguments("publication")]
+ [Arguments("root")]
+ [Arguments("pending")]
+ public async Task DisposeAsync_Should_Keep_A_Move_Settled_By_Root_Disposal_Or_Publication(string outcome)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ var pending = EventStreamSteps.PendingNext(events);
+ Task concurrent;
+ try
+ {
+ concurrent = EventStreamSteps.PendingNext(events);
+ }
+ catch (InvalidOperationException exception)
+ {
+ concurrent = Task.FromException(exception);
+ }
+ if (string.Equals(outcome, "publication", StringComparison.Ordinal))
+ {
+ await scenario.PublishAsync("E1");
+ }
+ else if (string.Equals(outcome, "root", StringComparison.Ordinal))
+ {
+ scenario.Feed.Dispose();
+ }
+
+ await events.DisposeAsync();
+ _ = await Assert.That(concurrent).Throws();
+ if (string.Equals(outcome, "root", StringComparison.Ordinal))
+ {
+ _ = await Assert.That(pending).Throws();
+ }
+ else
+ {
+ await Assert.That(await pending.WaitAsync(HangGuard.Bound))
+ .IsEqualTo(string.Equals(outcome, "publication", StringComparison.Ordinal));
+ if (string.Equals(outcome, "publication", StringComparison.Ordinal))
+ {
+ await Assert.That(events.Current.Id).IsEqualTo("E1");
+ }
+ }
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Deliver_Queued_Events_Before_The_Same_Source_Fault()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var first = await scenario.AdmitAsync("M");
+ await using var second = await scenario.AdmitAsync("M");
+ await scenario.PublishPrefixAsync("E1", "E2");
+ var failure = new InvalidOperationException("source cleanup");
+ await scenario.FaultAsync(failure);
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+ foreach (var events in new[] { first, second })
+ {
+ string?[] actual = [(await EventStreamSteps.NextAsync(events)).Id, (await EventStreamSteps.NextAsync(events)).Id];
+ await Assert.That(actual).IsEquivalentTo((string?[])["E1", "E2"], CollectionOrdering.Matching);
+ var observed = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(observed).IsSameReferenceAs(failure);
+ var repeated = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(repeated).IsSameReferenceAs(failure);
+ }
+
+ await using var fresh = await scenario.AdmitAsync("M2");
+ await Assert.That(fresh.Current.Id).IsEqualTo("M2");
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(2);
+ }
+
+ [Test]
+ public async Task Cancellation_Should_Discard_The_Queued_Backlog_Before_The_Next_Pull()
+ {
+ using var caller = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("live-cancel-marker", caller.Token);
+ await scenario.PublishPrefixAsync("cancel-one", "cancel-two");
+ await Assert.That(events.RetainedCount).IsEqualTo(2);
+ await Assert.That(scenario.Feed.GetConnectionState().Status).IsEqualTo(EventConnectionStatus.Connected);
+
+ await caller.CancelOnWorkerAsync();
+ await Assert.That(events.RetainedCount).IsEqualTo(0);
+ var canceled = await EventStreamSteps.PendingCancellationAsync(events).WaitAsync(HangGuard.Bound);
+ await Assert.That(canceled).IsNotNull();
+ await Assert.That(canceled!.CancellationToken).IsEqualTo(caller.Token);
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Discard_A_Preserved_Backlog_When_The_Token_Is_Cancelled()
+ {
+ using var caller = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M", caller.Token);
+ await scenario.PublishPrefixAsync("E1", "E2");
+ await scenario.FaultAsync(new InvalidOperationException("source cleanup"));
+ await EventStreamSteps.CancelAndCaptureAsync(caller, events);
+ await Assert.That(events.RetainedCount).IsEqualTo(0);
+ }
+
+ [Test]
+ [Arguments("overflow")]
+ [Arguments("fault")]
+ [Arguments("root")]
+ [Arguments("false")]
+ public async Task DisposeAsync_Should_Drain_The_Backlog_And_End_Later_Pulls(string ending)
+ {
+ using var caller = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M", caller.Token);
+ await scenario.PublishPrefixAsync("E1", "E2");
+ switch (ending)
+ {
+ case "fault":
+ await scenario.FaultAsync(new InvalidOperationException("source cleanup"));
+ break;
+ case "root":
+ scenario.Feed.Dispose();
+ break;
+ case "overflow":
+ for (var index = 0; index < 4095; index++)
+ {
+ await scenario.PublishAsync("overflow");
+ }
+
+ break;
+ default:
+ await events.DisposeAsync();
+ break;
+ }
+
+ await events.DisposeAsync();
+ await Assert.That(events.RetainedCount).IsEqualTo(0);
+ await Assert.That(await events.MoveNextAsync()).IsFalse();
+ await caller.CancelOnWorkerAsync();
+ var canceled = await EventStreamSteps.PendingCancellationAsync(events).WaitAsync(HangGuard.Bound);
+ await Assert.That(canceled!.CancellationToken).IsEqualTo(caller.Token);
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Preserve_A_Stored_Fault_Prefix_After_Root_Disposal()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var ended = await scenario.AdmitAsync("M");
+ await scenario.PublishPrefixAsync("E1", "E2");
+ var failure = new InvalidOperationException("source cleanup");
+ await scenario.FaultAsync(failure);
+ await using var live = await scenario.AdmitAsync("M2");
+ await scenario.PublishAsync("discarded");
+ scenario.Feed.Dispose();
+
+ string?[] prefix = [(await EventStreamSteps.NextAsync(ended)).Id, (await EventStreamSteps.NextAsync(ended)).Id];
+ await Assert.That(prefix).IsEquivalentTo((string?[])["E1", "E2"], CollectionOrdering.Matching);
+ var observed = await Assert.That(async () => await ended.MoveNextAsync()).Throws();
+ await Assert.That(observed).IsSameReferenceAs(failure);
+ _ = await Assert.That(async () => await live.MoveNextAsync()).Throws();
+ await Assert.That(live.RetainedCount).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task Capacity_Should_Report_The_Sdk_Bound_For_Consumer_Constructed_Exceptions()
+ {
+ var cause = new InvalidOperationException("underlying failure");
+ OpenCodeEventSubscriberOverflowException[] exceptions = [new(), new("message"), new("message", cause)];
+
+ await Assert.That(exceptions.Select(static exception => exception.Capacity))
+ .IsEquivalentTo([4096, 4096, 4096], CollectionOrdering.Matching);
+ await Assert.That(exceptions[1].Message).IsEqualTo("message");
+ await Assert.That(exceptions[2].Message).IsEqualTo("message");
+ await Assert.That(exceptions[2].InnerException).IsSameReferenceAs(cause);
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Overflow_On_The_4097th_Queued_Selected_Event_But_Not_The_4096th()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = scenario.Feed.Subscribe(EventSelection.Capture(null), CancellationToken.None).GetAsyncEnumerator();
+ var first = events.MoveNextAsync().AsTask();
+ var attempt = await scenario.Attempts.NextOpenAsync();
+ await attempt.PublishAsync(SharedEventFeedScenario.Marker("M"));
+ await Assert.That(await first.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(events.Current.Id).IsEqualTo("M");
+ var source = scenario.Feed.GetCurrentSource()!;
+ for (var index = 1; index <= 4096; index++)
+ {
+ await attempt.PublishAsync(SharedEventFeedScenario.Event("E" + index.ToString(System.Globalization.CultureInfo.InvariantCulture)));
+ }
+
+ await attempt.PublishAsync(SharedEventFeedScenario.Event("E4097"));
+ var overflow = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(overflow!.Capacity).IsEqualTo(4096);
+ await Assert.That(overflow.Message).IsEqualTo("Event subscriber exceeded its 4096-event capacity");
+ var repeated = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(repeated).IsSameReferenceAs(overflow);
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+ await Assert.That(scenario.Feed.GetConnectionState().Status).IsEqualTo(EventConnectionStatus.Idle);
+ attempt.ReleaseCleanup();
+ await scenario.Feed.JoinAsync().WaitAsync(HangGuard.Bound);
+ await Assert.That(attempt.Token.IsCancellationRequested).IsTrue();
+ await Assert.That(source.IsReleased).IsTrue();
+ }
+
+ private static async Task AssertNoAdmissionAsync(SharedEventFeedScenario scenario, EventSubscription events)
+ {
+ await Assert.That(events.RegistrationCount).IsEqualTo(0);
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task EndLocked_Should_Keep_The_First_Stored_Ending()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("first-ending-marker");
+ await scenario.PublishPrefixAsync("prefix-one", "prefix-two");
+ var first = new InvalidOperationException("first ending");
+ var second = new InvalidOperationException("second ending");
+ scenario.Feed.WithGate(work =>
+ {
+ events.EndLocked(new SubscriptionEnd(first, true, false), work);
+ events.EndLocked(new SubscriptionEnd(second, true, false), work);
+ });
+
+ string?[] prefix = [(await EventStreamSteps.NextAsync(events)).Id, (await EventStreamSteps.NextAsync(events)).Id];
+ await Assert.That(prefix).IsEquivalentTo((string?[])["prefix-one", "prefix-two"], CollectionOrdering.Matching);
+ var observed = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(observed).IsSameReferenceAs(first);
+ }
+
+ [Test]
+ public async Task OfferLocked_Should_Drain_Overflow_Before_Releasing_The_Gate()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("atomic-overflow-marker");
+ var offered = SharedEventFeedScenario.Event("atomic-overflow-offer");
+ var retainedAtDecision = -1;
+ scenario.Feed.WithGate(work =>
+ {
+ for (var index = 0; index < 4097; index++)
+ {
+ events.OfferLocked(offered, work);
+ }
+
+ retainedAtDecision = events.RetainedCount;
+ });
+
+ await Assert.That(retainedAtDecision).IsEqualTo(0);
+ _ = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ }
+
+ [Test]
+ public async Task Settle_Should_Keep_The_First_Result_And_Refuse_A_Second_Settlement()
+ {
+ var completion = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously);
+ var move = new EventPendingMove(completion);
+
+ bool[] settlements = [move.Settle(new Delivery("first", null)), move.Settle(new Delivery("second", null))];
+
+ await Assert.That(settlements).IsEquivalentTo([true, false], CollectionOrdering.Matching);
+ var delivery = await completion.Task;
+ await Assert.That(delivery.Item).IsEqualTo("first");
+ await Assert.That(delivery.Error).IsNull();
+ }
+
+ [Test]
+ public async Task AfterGate_Should_Run_Every_Item_And_Aggregate_The_Gate_Failure_First()
+ {
+ var gateFailure = new InvalidOperationException("gate");
+ var cleanupFailure = new InvalidOperationException("cleanup");
+ var ledger = new List();
+ var work = new AfterGate();
+
+ var exception = await Assert.That(() => work.Run(() =>
+ {
+ work.Add(() =>
+ {
+ ledger.Add("cleanup");
+ throw cleanupFailure;
+ });
+ work.Add(() => ledger.Add("stop"));
+ throw gateFailure;
+ })).Throws();
+
+ Exception[] expectedFailures = [gateFailure, cleanupFailure];
+ await Assert.That(exception!.InnerExceptions).IsEquivalentTo(expectedFailures, CollectionOrdering.Matching);
+ await Assert.That(ledger).IsEquivalentTo(["cleanup", "stop"], CollectionOrdering.Matching);
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventsClientContractTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventsClientContractTests.cs
index 04c9add96..c23745aa4 100644
--- a/tests/OpenCode.Sdk.Tests/Events/EventsClientContractTests.cs
+++ b/tests/OpenCode.Sdk.Tests/Events/EventsClientContractTests.cs
@@ -20,10 +20,11 @@ public sealed class EventsClientContractTests
private readonly FixtureLoader _fixtures = new();
[Test]
- public async Task SubscribeAsync_Should_Send_Types_On_Every_Reconnect_Attempt()
+ public async Task SubscribeAsync_Should_Send_No_Types_And_Select_Locally_On_Every_Reconnect_Attempt()
{
var time = new ManualTimeProvider();
- using var handler = EventStreamSteps.CreateReconnectHandler();
+ var frames = WireBodyData.Frames(ScriptedEventServer.Connected, _fixtures.LoadJson("Events.session-created.json"));
+ using var handler = new RecordingHttpHandler(_ => ScriptedEventServer.StreamOf(frames, ends: true));
using var httpClient = new HttpClient(handler);
using var pipeline = PipelineFactory.Create(httpClient, time: time);
var request = new EventSubscribeRequest
@@ -32,15 +33,18 @@ public async Task SubscribeAsync_Should_Send_Types_On_Every_Reconnect_Attempt()
};
await using var events = new EventsClient(pipeline).SubscribeAsync(request).GetAsyncEnumerator();
- var reconnect = await EventStreamSteps.PullAfterConnectionAsync(events);
+ await Assert.That((await EventStreamSteps.NextAsync(events)).Type).IsEqualTo("server.connected");
+ await Assert.That((await EventStreamSteps.NextAsync(events)).Id).IsEqualTo("evt_1");
+ var reconnect = EventStreamSteps.PendingNext(events);
await time.WaitForArmedAsync(EventStreamSteps.Delay, HangGuard.Bound);
time.Advance(EventStreamSteps.Delay);
await Assert.That(await reconnect.WaitAsync(HangGuard.Bound)).IsTrue();
await Assert.That(events.Current).IsTypeOf();
+ await Assert.That((await EventStreamSteps.NextAsync(events)).Id).IsEqualTo("evt_1");
await Assert.That(handler.Requests.Count).IsEqualTo(2);
await Assert.That(handler.Requests.Select(static attempt => attempt.RequestUri!.Query))
- .IsEquivalentTo(["?types=session.created&types=rpc.sdk-test", "?types=session.created&types=rpc.sdk-test"], CollectionOrdering.Matching);
+ .IsEquivalentTo([string.Empty, string.Empty], CollectionOrdering.Matching);
}
[Test]
@@ -49,7 +53,8 @@ await Assert.That(handler.Requests.Select(static attempt => attempt.RequestUri!.
[Arguments(2)]
public async Task SubscribeAsync_Should_Omit_The_Query_Without_Types(int kind)
{
- using var scenario = ContractScenario.RespondingWithFrames(EventStreamSteps.ConnectedFrame);
+ using var scenario = ContractScenario.RespondingWithFrames(WireBodyData.Frames(ScriptedEventServer.Connected,
+ _fixtures.LoadJson("Events.session-created.json"), _fixtures.LoadJson("Events.unknown-log-event.json")));
var request = kind switch
{
0 => null,
@@ -59,6 +64,8 @@ public async Task SubscribeAsync_Should_Omit_The_Query_Without_Types(int kind)
await using var events = scenario.Client.Events.SubscribeAsync(request).GetAsyncEnumerator();
await Assert.That(await EventStreamSteps.NextAsync(events)).IsTypeOf();
+ string[] selected = [(await EventStreamSteps.NextAsync(events)).Type, (await EventStreamSteps.NextAsync(events)).Type];
+ await Assert.That(selected).IsEquivalentTo(["session.created", "session.invented.tomorrow"], CollectionOrdering.Matching);
await Assert.That(scenario.Requests.Single().RequestUri!.Query).IsEqualTo(string.Empty);
}
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventsClientIdleWindowTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventsClientIdleWindowTests.cs
index 1a726bb25..1b8502fd8 100644
--- a/tests/OpenCode.Sdk.Tests/Events/EventsClientIdleWindowTests.cs
+++ b/tests/OpenCode.Sdk.Tests/Events/EventsClientIdleWindowTests.cs
@@ -7,7 +7,7 @@ namespace OpenCode.Sdk.Tests.Events;
///
/// A connected event stream is cut when its idle window passes without a byte. Every byte,
-/// including a heartbeat, restarts the window; time with the consumer does not count as silence.
+/// including a heartbeat, restarts the window; the source reads independently of its consumers.
/// Every bound runs on the test's clock, and each step waits until the bound it passes is armed.
///
public sealed class EventsClientIdleWindowTests
@@ -91,14 +91,16 @@ public async Task A_Heartbeat_Should_Arm_A_Full_Idle_Window_Before_The_Next_Empt
{
var window = TimeSpan.FromSeconds(10);
using var body = new LiveEventBody(ConnectedFrame);
+ var firstEmptyRead = body.NextEmptyRead;
using var server = new ScriptedEventServer(_ => ScriptedEventServer.Stream(body), eventStreamIdleTimeout: window);
using var caller = new CancellationTokenSource();
var events = server.Events.SubscribeAsync(cancellationToken: caller.Token).GetAsyncEnumerator();
await WithPendingCancellationAsync(caller, events, async startPull =>
{
- var firstEmptyRead = body.NextEmptyRead;
startPull();
- await firstEmptyRead.WaitAsync(HangGuard.Bound);
+ var observedRead = firstEmptyRead.ContinueWith(static task => task.Status,
+ CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
+ await Assert.That(await observedRead.WaitAsync(HangGuard.Bound)).IsEqualTo(TaskStatus.RanToCompletion);
await server.Time.WaitForArmedAsync(window, HangGuard.Bound);
server.Time.Advance(TimeSpan.FromSeconds(9));
@@ -188,19 +190,32 @@ private static async Task AssertSessionCreatedAsync(bool moved, IAsyncEnumerator
await Assert.That(server.RequestCount).IsEqualTo(1);
}
- /// The consumer's time with an event is not the server's silence, so a slow consumer is never cut.
+ /// The source keeps reading and observing idle silence even when its consumer holds the admission marker.
[Test]
- public async Task A_Consumer_Holding_An_Event_Should_Not_Count_As_Silence()
+ public async Task SubscribeAsync_Should_Keep_The_Idle_Window_Running_While_An_Event_Is_Held()
{
using var body = new LiveEventBody(ConnectedFrame);
- using var server = new ScriptedEventServer(_ => ScriptedEventServer.Stream(body));
+ using var replacement = new LiveEventBody(ConnectedFrame);
+ var reading = body.NextEmptyRead;
+ var replacementReading = replacement.NextEmptyRead;
+ using var server = new ScriptedEventServer(index => ScriptedEventServer.Stream(index == 1 ? body : replacement));
await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
- await Assert.That(await NextAsync(events)).IsTypeOf();
-
- server.Time.Advance(TimeSpan.FromMinutes(10));
- body.Append(SessionCreatedFrame);
-
- await Assert.That(await NextAsync(events)).IsTypeOf();
- await Assert.That(server.RequestCount).IsEqualTo(1);
+ var first = await NextAsync(events);
+ await Assert.That(first).IsTypeOf();
+ await reading.WaitAsync(HangGuard.Bound);
+ await Assert.That(server.Time.ArmedIn(IdleWindow)).IsEqualTo(1);
+ server.Time.Advance(IdleWindow);
+ await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
+ var reconnecting = server.Events.GetConnectionState();
+ await Assert.That(reconnecting.Status).IsEqualTo(EventConnectionStatus.Reconnecting);
+ await Assert.That(reconnecting.Error).IsTypeOf();
+ server.Time.Advance(Delay);
+ await replacementReading.WaitAsync(HangGuard.Bound);
+ await Assert.That(server.Events.GetConnectionState().Status).IsEqualTo(EventConnectionStatus.Connected);
+ await Assert.That(body.IsDisposed).IsTrue();
+ await Assert.That(server.RequestCount).IsEqualTo(2);
+ var next = await NextAsync(events);
+ await Assert.That(next).IsTypeOf();
+ await Assert.That(next).IsNotSameReferenceAs(first);
}
}
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventsClientLiveTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventsClientLiveTests.cs
index 89cc5708a..72c74eca9 100644
--- a/tests/OpenCode.Sdk.Tests/Events/EventsClientLiveTests.cs
+++ b/tests/OpenCode.Sdk.Tests/Events/EventsClientLiveTests.cs
@@ -42,14 +42,16 @@ public async Task SubscribeAsync_Should_Deliver_The_Owned_Rpc_Event_With_Its_Non
var nonce = "rpc-event-live-" + Guid.NewGuid().ToString("N");
var reader = new OwnedEventReader(EventWait, CleanupTimeout, cancellationToken);
var probe = new SessionEventProbe(reader);
+ var otherReader = new OwnedEventReader(EventWait, CleanupTimeout, cancellationToken);
+ var otherProbe = new SessionEventProbe(otherReader);
Exception? primaryFailure = null;
try
{
- // The subscription is attached before the emit call, so the proof rests on a causal
- // barrier rather than on replay.
+ // Both subscriptions are admitted before the emit call; neither depends on business replay.
probe.Start(client.Events.SubscribeAsync(cancellationToken: reader.Token));
- await probe.WaitForConnectedAsync(cancellationToken);
+ otherProbe.Start(client.Events.SubscribeAsync(cancellationToken: otherReader.Token));
+ await Task.WhenAll(probe.WaitForConnectedAsync(cancellationToken), otherProbe.WaitForConnectedAsync(cancellationToken));
var emitted = await client.Rpc.CallAsync(
TestRpcPlugin.Id,
@@ -62,14 +64,11 @@ public async Task SubscribeAsync_Should_Deliver_The_Owned_Rpc_Event_With_Its_Non
await Assert.That(output.GetProperty("nonce").GetString()).IsEqualTo(nonce);
using var barrier = SessionEventProbe.Barrier(cancellationToken);
- var observed = await probe.WaitForAsync(
- rpc => string.Equals(rpc.Type, ObservedEventType, StringComparison.Ordinal)
- && rpc.Data.TryGetValue("nonce", out var carried)
- && carried.ValueKind == JsonValueKind.String
- && string.Equals(carried.GetString(), nonce, StringComparison.Ordinal),
- "the rpc event '" + ObservedEventType + "' carrying the nonce", barrier.Token);
+ var observed = await WaitForNonceAsync(probe, nonce, barrier.Token);
+ var other = await WaitForNonceAsync(otherProbe, nonce, barrier.Token);
await Assert.That(observed.Data.Count).IsEqualTo(1);
await Assert.That(observed.Location.Directory).IsEqualTo(resolved.Directory);
+ await Assert.That(other).IsSameReferenceAs(observed);
Console.WriteLine(
"rpc-event-live: mode=owned arm=emit status=" + Number(emitted.Status) +
@@ -87,10 +86,17 @@ public async Task SubscribeAsync_Should_Deliver_The_Owned_Rpc_Event_With_Its_Non
}
finally
{
- await reader.CompleteAsync(primaryFailure);
+ await Task.WhenAll(reader.CompleteAsync(primaryFailure), otherReader.CompleteAsync(primaryFailure));
}
}
+ private static Task WaitForNonceAsync(SessionEventProbe probe, string nonce, CancellationToken cancellationToken) =>
+ probe.WaitForAsync(rpc => string.Equals(rpc.Type, ObservedEventType, StringComparison.Ordinal)
+ && rpc.Data.TryGetValue("nonce", out var carried)
+ && carried.ValueKind == JsonValueKind.String
+ && string.Equals(carried.GetString(), nonce, StringComparison.Ordinal),
+ "the rpc event '" + ObservedEventType + "' carrying the nonce", cancellationToken);
+
///
/// Activation is awaited in the client's location before the event proof depends on the plugin,
/// and the exact owned entry must be the active local directory the fixture seeded.
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventsClientReconnectTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventsClientReconnectTests.cs
index b9ba1d54f..b10da1883 100644
--- a/tests/OpenCode.Sdk.Tests/Events/EventsClientReconnectTests.cs
+++ b/tests/OpenCode.Sdk.Tests/Events/EventsClientReconnectTests.cs
@@ -1,6 +1,5 @@
using System.Net;
-using System.Net.Http.Headers;
-using System.Text.Json;
+using System.Reflection;
using OpenCode.Sdk.Internal;
using OpenCode.Sdk.Models;
using OpenCode.Sdk.Tests.Harness;
@@ -13,24 +12,64 @@ namespace OpenCode.Sdk.Tests.Events;
///
/// The event bus reconnects as the pinned client does. Each attempt has 2 seconds to answer and
/// deliver server.connected first. Every failure of any kind is followed by a new attempt
-/// one second later. A stream that has failed every attempt for one minute, from the drop or from
-/// the first attempt, throws the last failure. Every bound runs on the test's clock, and each step
+/// one second later. Attempt failures are classified on connection state while the source keeps
+/// retrying. Every bound runs on the test's clock, and each step
/// waits until the bound it passes is armed.
///
public sealed class EventsClientReconnectTests
{
+ [Test]
+ public async Task SubscribeAsync_Should_Decode_Unselected_Frames_And_Reconnect_All_Subscribers_On_Invalid_Json()
+ {
+ using var initial = new LiveEventBody(ConnectedFrame);
+ using var replacement = new LiveEventBody(ConnectedFrame);
+ using var server = new ScriptedEventServer(index => ScriptedEventServer.Stream(index == 1 ? initial : replacement));
+ var request = new EventSubscribeRequest { Types = [new("rpc.sdk-test")] };
+ await using var first = server.Events.SubscribeAsync(request).GetAsyncEnumerator();
+ await using var second = server.Events.SubscribeAsync(request).GetAsyncEnumerator();
+ var oldMarker = await NextAsync(first);
+ await Assert.That(await NextAsync(second)).IsSameReferenceAs(oldMarker);
+ await Assert.That(server.RequestCount).IsEqualTo(1);
+ Drop(initial, "malformed-frame");
+ await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
+ server.Time.Advance(Delay);
+ var newMarker = await NextAsync(first);
+ await Assert.That(newMarker).IsNotSameReferenceAs(oldMarker);
+ await Assert.That(await NextAsync(second)).IsSameReferenceAs(newMarker);
+ var drifted = System.Text.Json.Nodes.JsonNode.Parse(ScriptedEventServer.Connected)!.AsObject();
+ drifted["data"] = false;
+ replacement.Append(WireBodyData.Frames(drifted.ToJsonString()));
+ var left = await NextAsync(first);
+ var right = await NextAsync(second);
+
+ await Assert.That(left).IsTypeOf();
+ await Assert.That(left.Type).IsEqualTo("server.connected");
+ await Assert.That(right).IsSameReferenceAs(left);
+ await Assert.That(server.RequestCount).IsEqualTo(2);
+ await Assert.That(server.EarlierResponsesReleased).IsEquivalentTo([true, true], CollectionOrdering.Matching);
+ }
+
private readonly FixtureLoader _fixtures = new();
[Test]
[Arguments("door")]
[Arguments("spine")]
- public async Task Per_Call_Location_Should_Be_Sent_On_Every_Reconnect_Attempt(string entry)
+ public async Task SubscribeAsync_Should_Send_Only_The_Ambient_Location_Or_Refuse_The_Raw_Spine(string entry)
{
var time = new ManualTimeProvider();
using var handler = CreateReconnectHandler();
using var httpClient = new HttpClient(handler);
using var pipeline = PipelineFactory.Create(httpClient, location: new LocationSelector { Directory = "/ambient" }, time: time);
- var stream = Subscribe(entry, pipeline, new OpenCodeRequestOptions { Location = new LocationSelector { Directory = "/override/Γ§" } });
+ var options = new OpenCodeRequestOptions { Location = new LocationSelector { Directory = "/override/Γ§" } };
+ if (string.Equals(entry, "spine", StringComparison.Ordinal))
+ {
+ var refusal = await Assert.That(() => Subscribe(entry, pipeline, options)).Throws();
+ await Assert.That(refusal!.Message).IsEqualTo("Operation 'event.subscribe' must be opened through its shared event feed.");
+ await Assert.That(handler.Requests).IsEmpty();
+ return;
+ }
+
+ var stream = Subscribe(entry, pipeline, options);
await Assert.That(handler.Requests).IsEmpty().Because(entry);
await using var events = stream.GetAsyncEnumerator();
await Assert.That(await NextAsync(events)).IsTypeOf();
@@ -46,7 +85,8 @@ public async Task Per_Call_Location_Should_Be_Sent_On_Every_Reconnect_Attempt(st
}
await Assert.That(handler.Requests.Select(static request => request.Headers["x-opencode-directory"]))
- .IsEquivalentTo(["%2Foverride%2F%C3%A7", "%2Foverride%2F%C3%A7", "%2Foverride%2F%C3%A7"], CollectionOrdering.Matching);
+ .IsEquivalentTo(["%2Fambient", "%2Fambient", "%2Fambient"], CollectionOrdering.Matching);
+ await Assert.That(options.Location.Directory).IsEqualTo("/override/Γ§");
}
[Test]
@@ -68,6 +108,12 @@ public async Task SubscribeAsync_Should_Refuse_Per_Call_Options_Before_Enumerati
await Assert.That(exception!.GetType()).IsEqualTo(kind == 1 ? typeof(ArgumentOutOfRangeException) : typeof(ArgumentException));
await Assert.That(exception.ParamName).IsEqualTo("requestOptions");
+ if (kind == 0)
+ {
+ await Assert.That(exception.Message).StartsWith(
+ "Event subscriptions report ordinary attempt failures through connection state; NoThrow is not supported.");
+ }
+
if (exception is ArgumentOutOfRangeException range)
{
await Assert.That(range.ActualValue).IsEqualTo(options.ErrorBehavior);
@@ -110,6 +156,7 @@ public async Task Leaving_The_Loop_Should_Release_The_Connection_And_Open_No_Oth
await Assert.That(await NextAsync(events)).IsTypeOf();
}
+ await ObserveFeedStopAsync(server.Events);
await Assert.That(server.AllResponsesReleased).IsTrue();
server.Time.Advance(TimeSpan.FromMinutes(2));
await Assert.That(server.RequestCount).IsEqualTo(1);
@@ -162,7 +209,7 @@ public async Task An_Attempt_Should_Be_Cut_When_It_Does_Not_Connect_Within_2_Sec
///
/// Every way an open can fail is followed by a new attempt, the deterministic ones too, as the
- /// pinned client retries any failure: the minute decides when it stops, not the kind of failure.
+ /// pinned client retries any failure rather than selecting a permanent-failure category.
///
[Test]
[Arguments("unauthorized")]
@@ -240,273 +287,19 @@ public async Task Every_Drop_Of_A_Connected_Stream_Should_Be_Followed_By_A_New_A
await Assert.That(server.RequestCount).IsEqualTo(2);
}
- /// A wrong address or a refused credential surfaces after one minute of attempts, as the error the server answered.
- [Test]
- [Arguments(400, WireBodyData.InvalidRequestError, typeof(InvalidRequestError))]
- [Arguments(401, WireBodyData.UnauthorizedError, typeof(UnauthorizedError))]
- public async Task A_Stream_Refused_For_A_Minute_Should_Throw_The_Declared_Error_Exactly_At_The_Minute(int status, string body,
- Type expectedErrorType)
- {
- using var server = new ScriptedEventServer(_ => ScriptedEventServer.Status((HttpStatusCode)status, body));
- await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
- var first = PendingNext(events);
-
- await FailEveryAttemptUntilTheMinuteAsync(server, first, cyclesBefore: 59);
-
- var exception = await Assert.That(first.WaitAsync(HangGuard.Bound)).Throws();
- await Assert.That(exception!.Status).IsEqualTo(status);
- await Assert.That(exception.Error!.GetType()).IsEqualTo(expectedErrorType);
- await Assert.That(server.RequestCount).IsEqualTo(60);
- }
-
- /// Each failure replaces the one before, so the give-up throws the one that came last.
+ /// An opening status refusal retains its classified error even when the connect window passed during the send.
[Test]
- public async Task The_Give_Up_Should_Throw_The_Latest_Failure()
- {
- using var server = new ScriptedEventServer(number => number % 2 is 1
- ? ScriptedEventServer.Status(HttpStatusCode.Unauthorized, WireBodyData.UnauthorizedError)
- : ScriptedEventServer.Status(HttpStatusCode.InternalServerError, "{}"));
- await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
- var first = PendingNext(events);
-
- await FailEveryAttemptUntilTheMinuteAsync(server, first, cyclesBefore: 59);
-
- var exception = await Assert.That(first.WaitAsync(HangGuard.Bound)).Throws();
- await Assert.That(exception!.Status).IsEqualTo(500);
- await Assert.That(server.RequestCount).IsEqualTo(60);
- }
-
- /// A clean server end remains the last failure when the drop's give-up minute passes.
- [Test]
- public async Task An_Ended_Stream_Should_Report_The_Ended_Text_At_Give_Up()
- {
- using var server = new ScriptedEventServer(number =>
- ScriptedEventServer.StreamOf(number is 1 ? ConnectedFrame : string.Empty, ends: true));
- await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
- var next = await PullAfterConnectionAsync(events);
- await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
- server.Time.Advance(TimeSpan.FromMinutes(1));
-
- var failure = await Assert.That(next.WaitAsync(HangGuard.Bound)).Throws();
-
- await Assert.That(failure!.Message).IsEqualTo("The opencode event stream ended.");
- }
-
- /// A response rejected as the give-up passes retains its own protocol failure.
- [Test]
- public async Task The_Give_Up_Should_Throw_An_Attempts_Own_Failure_When_Its_Response_Arrives_At_The_Minute()
+ public async Task An_Opening_Status_Refusal_Should_Keep_Its_Classified_Error_When_The_Connect_Window_Passes()
{
var time = new ManualTimeProvider();
await AssertOpeningTransportFailureMessageAsync(time, _ =>
{
- // The send has started, so both the give-up and connect windows are armed.
+ // The synchronous responder returns after the already-armed connect window passed.
time.Advance(TimeSpan.FromMinutes(1));
return new HttpResponseMessage(HttpStatusCode.Redirect);
}, "The opencode API returned undeclared redirect status 302.");
}
- /// A first attempt cut by give-up, before any failure was recorded, names the give-up minute.
- [Test]
- public async Task The_Give_Up_Should_Name_Its_Minute_When_It_Cuts_The_First_Attempt()
- {
- var time = new ManualTimeProvider();
- await AssertOpeningTransportFailureMessageAsync(time, _ =>
- {
- // Keep the send on this stack until both windows have passed, before reporting its cancellation.
- time.Advance(TimeSpan.FromMinutes(1));
- throw new OperationCanceledException();
- }, "The opencode event stream did not connect within 60 seconds.");
- }
-
- /// An attempt still waiting at the minute is cut by the give-up, which throws the failure before it.
- [Test]
- public async Task The_Give_Up_Should_Cut_An_Attempt_In_Flight_And_Throw_The_Failure_Before_It()
- {
- using var server = new ScriptedEventServer(number => number switch
- {
- 60 => ScriptedEventServer.Silence,
- 59 => ScriptedEventServer.Status(HttpStatusCode.InternalServerError, "{}"),
- _ => ScriptedEventServer.Status(HttpStatusCode.Unauthorized, WireBodyData.UnauthorizedError),
- });
- await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
- var first = PendingNext(events);
- for (var second = 0; second < 59; second++)
- {
- await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
- server.Time.Advance(Delay);
- }
-
- await server.WaitForRequestAsync(60, HangGuard.Bound);
- await server.Time.WaitForArmedAsync(ConnectBound, HangGuard.Bound);
- server.Time.Advance(Delay - OneTick);
- await Assert.That(first.IsCompleted).IsFalse();
- server.Time.Advance(OneTick);
-
- var exception = await Assert.That(first.WaitAsync(HangGuard.Bound)).Throws();
- await Assert.That(exception!.Status).IsEqualTo(500);
- await Assert.That(server.AllResponsesReleased).IsTrue();
- }
-
- [Test]
- public async Task A_Stream_Failed_By_The_Server_For_A_Minute_Should_Throw_The_Typed_Failure_Cause()
- {
- using var server = new ScriptedEventServer(_ => ScriptedEventServer.StreamOf(
- WireBodyData.NamedFrame("effect/http-api/stream/failure", WireBodyData.StreamFailureCause)));
- await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
- var first = PendingNext(events);
-
- await FailEveryAttemptUntilTheMinuteAsync(server, first, cyclesBefore: 59);
-
- var exception = await Assert.That(first.WaitAsync(HangGuard.Bound)).Throws();
- var cause = (StreamFailureCauseDie)exception!.Causes.Single();
- await Assert.That(cause.Defect.ValueKind).IsEqualTo(JsonValueKind.String);
- await Assert.That(cause.Defect.GetString()).IsEqualTo("boom");
- }
-
- /// Attempts that never connect run 2 seconds each plus the delay; the last one cut names the bound that cut it.
- [Test]
- public async Task A_Server_That_Never_Answers_Should_Throw_The_Connect_Bound_Exactly_At_The_Minute()
- {
- using var server = new ScriptedEventServer(_ => ScriptedEventServer.Silence);
- await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
- var first = PendingNext(events);
-
- for (var attempt = 1; attempt <= 20; attempt++)
- {
- await server.WaitForRequestAsync(attempt, HangGuard.Bound);
- await server.Time.WaitForArmedAsync(ConnectBound, HangGuard.Bound);
- server.Time.Advance(ConnectBound);
- await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound, count: attempt < 20 ? 1 : 2);
- if (attempt < 20)
- {
- server.Time.Advance(Delay);
- }
- }
-
- server.Time.Advance(Delay - OneTick);
- await Assert.That(first.IsCompleted).IsFalse();
- server.Time.Advance(OneTick);
-
- var exception = await Assert.That(first.WaitAsync(HangGuard.Bound)).Throws();
- await Assert.That(exception!.Message).IsEqualTo("The opencode server did not answer the event stream request within 2 seconds.");
- await Assert.That(server.RequestCount).IsEqualTo(20);
- }
-
- /// An answered attempt that sends no event names that silence when its last reconnect delay reaches the give-up.
- [Test]
- public async Task A_Server_That_Answers_Without_An_Event_Should_Throw_The_Connect_Bound_At_Give_Up()
- {
- using var body = new BlockingContent();
- body.Headers.ContentType = new MediaTypeHeaderValue("text/event-stream");
- using var server = new ScriptedEventServer(number => number < 58
- ? ScriptedEventServer.Status(HttpStatusCode.Unauthorized, WireBodyData.UnauthorizedError)
- : new HttpResponseMessage(HttpStatusCode.OK) { Content = body });
- await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
- var first = PendingNext(events);
-
- // The final attempt starts at 57 s: its connect bound ends at 59 s, then the delay
- // and give-up fall due together. Wait for its body read so the headers are known to be in.
- for (var second = 0; second < 57; second++)
- {
- await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
- server.Time.Advance(Delay);
- }
-
- await body.ReadStarted.WaitAsync(HangGuard.Bound);
- await server.Time.WaitForArmedAsync(ConnectBound, HangGuard.Bound);
- server.Time.Advance(ConnectBound);
- await FailEveryAttemptUntilTheMinuteAsync(server, first, cyclesBefore: 0);
-
- var exception = await Assert.That(first.WaitAsync(HangGuard.Bound)).Throws();
- await Assert.That(exception!.Message).IsEqualTo("The opencode server answered the event stream request but sent no event within 2 seconds.");
- await Assert.That(server.RequestCount).IsEqualTo(58);
- await Assert.That(body.IsDisposed).IsTrue();
- }
-
- /// Error headers count as an answer even when buffering their body never completes.
- [Test]
- [Arguments(HttpStatusCode.Unauthorized)]
- [Arguments(HttpStatusCode.InternalServerError)]
- public async Task A_Server_Whose_Error_Body_Stalls_Should_Report_An_Answer_At_Give_Up(HttpStatusCode status)
- {
- using var stalled = new BlockingContent();
- using var server = new ScriptedEventServer(number => number == 58
- ? new HttpResponseMessage(status) { Content = stalled }
- : ScriptedEventServer.Status(HttpStatusCode.Unauthorized, WireBodyData.UnauthorizedError));
- await using var subscription = server.Events.SubscribeAsync().GetAsyncEnumerator();
- var pending = PendingNext(subscription);
- for (var number = 1; number < 58; number++)
- {
- await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
- server.Time.Advance(Delay);
- }
-
- await stalled.ReadStarted.WaitAsync(HangGuard.Bound);
- await server.Time.WaitForArmedAsync(ConnectBound, HangGuard.Bound);
- server.Time.Advance(ConnectBound);
- await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound, count: 2);
- server.Time.Advance(Delay);
-
- var failure = await Assert.That(pending.WaitAsync(HangGuard.Bound)).Throws();
- await Assert.That(failure!.Message).IsEqualTo("The opencode server answered the event stream request but sent no event within 2 seconds.");
- await Assert.That(stalled.IsDisposed).IsTrue();
- }
-
- /// A connection resets the minute; the next minute runs from the moment that connection drops.
- [Test]
- public async Task A_Connection_Should_Restart_The_Minute_From_Its_Drop()
- {
- using var connection = new LiveEventBody(WireBodyData.Frames(ScriptedEventServer.Connected));
- using var server = new ScriptedEventServer(number => number is 60
- ? ScriptedEventServer.Stream(connection)
- : ScriptedEventServer.Status(HttpStatusCode.Unauthorized, WireBodyData.UnauthorizedError));
- await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
- var first = PendingNext(events);
- for (var second = 0; second < 59; second++)
- {
- await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
- server.Time.Advance(Delay);
- }
-
- await Assert.That(await first.WaitAsync(HangGuard.Bound)).IsTrue();
- await Assert.That(events.Current).IsTypeOf();
- server.Time.Advance(TimeSpan.FromSeconds(5));
- connection.Append(WireBodyData.Frames(_fixtures.LoadJson("Events.session-created.json")));
- await Assert.That(await NextAsync(events)).IsTypeOf();
-
- var next = PendingNext(events);
- connection.End();
- await FailEveryAttemptUntilTheMinuteAsync(server, next, cyclesBefore: 59);
-
- _ = await Assert.That(next.WaitAsync(HangGuard.Bound)).Throws();
- await Assert.That(server.RequestCount).IsEqualTo(119);
- }
-
- /// A dropped connection arms a fresh give-up minute and waits exactly one second to reconnect.
- [Test]
- public async Task A_Drop_Should_Arm_A_Fresh_Give_Up_Minute_Before_The_Reconnect_Delay()
- {
- using var connection = new LiveEventBody(ConnectedFrame);
- using var server = new ScriptedEventServer(_ => ScriptedEventServer.Stream(connection));
- using var caller = new CancellationTokenSource();
- var events = server.Events.SubscribeAsync(cancellationToken: caller.Token).GetAsyncEnumerator();
- await WithPendingCancellationAsync(caller, events, async startPull =>
- {
- // Drain creation notifications for the give-up, attempt and response-progress windows.
- for (var timer = 0; timer < 3; timer++)
- {
- await server.Time.WaitForTimerAsync(HangGuard.Bound);
- }
-
- connection.End();
- startPull();
- await server.Time.WaitForTimerAsync(HangGuard.Bound);
-
- await Assert.That(server.Time.ArmedIn(TimeSpan.FromMinutes(1))).IsEqualTo(1);
- await Assert.That(server.Time.ArmedIn(Delay)).IsEqualTo(1);
- });
- }
-
[Test]
public async Task The_Callers_Token_Should_End_The_Stream_During_The_Delay_Without_Another_Attempt()
{
@@ -608,11 +401,20 @@ public async Task A_Disposed_Client_Should_End_The_Stream_At_Once(string phase)
public async Task SubscribeAsync_Should_Release_The_Response_While_The_Consumer_Holds_An_Event(bool disposeClient)
{
using var body = new LiveEventBody(ConnectedFrame);
+ var initiallyReading = body.NextEmptyRead;
using var server = new ScriptedEventServer(_ => ScriptedEventServer.Stream(body));
using var caller = new CancellationTokenSource();
- await using var events = server.Events.SubscribeAsync(cancellationToken: caller.Token).GetAsyncEnumerator();
- await Assert.That(await NextAsync(events)).IsTypeOf();
- server.Time.Advance(TimeSpan.FromMinutes(10));
+ await using var events = await SubscribeConnectedAsync(server, caller.Token);
+ await initiallyReading.WaitAsync(HangGuard.Bound);
+ var interval = TimeSpan.FromTicks(IdleWindow.Ticks / 2);
+ for (var elapsed = TimeSpan.Zero; elapsed < TimeSpan.FromMinutes(10); elapsed += interval)
+ {
+ server.Time.Advance(interval);
+ var reading = body.NextEmptyRead;
+ body.Append(ScriptedEventServer.Heartbeat);
+ await reading.WaitAsync(HangGuard.Bound);
+ }
+
await Assert.That(body.IsDisposed).IsFalse();
if (disposeClient)
@@ -625,6 +427,7 @@ public async Task SubscribeAsync_Should_Release_The_Response_While_The_Consumer_
}
// Assert release while still suspended at the yield, before requesting another event.
+ await ObserveFeedStopAsync(server.Events);
await Assert.That(server.AllResponsesReleased).IsTrue();
await Assert.That(body.IsDisposed).IsTrue();
if (disposeClient)
@@ -643,6 +446,12 @@ public async Task SubscribeAsync_Should_Release_The_Response_While_The_Consumer_
await Assert.That(server.RequestCount).IsEqualTo(1);
}
+ private static async Task ObserveFeedStopAsync(EventsClient events)
+ {
+ var feed = (SharedEventFeed)typeof(EventsClient).GetField("_feed", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(events)!;
+ await feed.JoinAsync().WaitAsync(HangGuard.Bound);
+ }
+
/// Asserts the pull ends in the caller's own cancellation with the stream's canceled text.
private static async Task AssertReadCanceledByCallerAsync(Task pending, CancellationToken caller)
{
@@ -653,38 +462,34 @@ private static async Task AssertReadCanceledByCallerAsync(Task
- /// Fails one-second cycles, then shows the last delay ends in the
- /// give-up exactly at the minute and not one tick before. Every attempt here fails at once. The
- /// clock runs timers due at the same instant in the order they were created, so the give-up,
- /// created with the stream, runs before the last delay.
- ///
- private static async Task FailEveryAttemptUntilTheMinuteAsync(ScriptedEventServer server, Task pending, int cyclesBefore)
- {
- for (var second = 0; second < cyclesBefore; second++)
- {
- await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
- server.Time.Advance(Delay);
- }
-
- // The give-up and the last delay fall due at the same instant; both are armed before time moves.
- await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound, count: 2);
- server.Time.Advance(Delay - OneTick);
- await Assert.That(pending.IsCompleted).IsFalse();
- server.Time.Advance(OneTick);
- }
-
/// Checks the opening failure's message while the subscription and its transport are still owned.
private static async Task AssertOpeningTransportFailureMessageAsync(ManualTimeProvider time,
Func answer, string expectedMessage)
{
- using var handler = new RecordingHttpHandler(answer);
+ var answered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ using var handler = new RecordingHttpHandler(request =>
+ {
+ try
+ {
+ return answer(request);
+ }
+ finally
+ {
+ answered.SetResult();
+ }
+ });
using var httpClient = new HttpClient(handler);
using var pipeline = PipelineFactory.Create(httpClient, time: time);
- await using var events = new EventsClient(pipeline).SubscribeAsync().GetAsyncEnumerator();
- var failure = await Assert.That(PendingNext(events).WaitAsync(HangGuard.Bound)).Throws();
-
- await Assert.That(failure!.Message).IsEqualTo(expectedMessage);
+ var door = new EventsClient(pipeline);
+ await using var events = door.SubscribeAsync().GetAsyncEnumerator();
+ var moving = PendingNext(events);
+ await answered.Task.WaitAsync(HangGuard.Bound);
+ await time.WaitForArmedAsync(Delay, HangGuard.Bound);
+ var state = door.GetConnectionState();
+ await Assert.That(state.Error).IsTypeOf();
+ await Assert.That(state.Error!.Message).IsEqualTo(expectedMessage);
+ await events.DisposeAsync();
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsFalse();
}
private static async Task> SubscribeConnectedAsync(ScriptedEventServer server, CancellationToken caller)
@@ -742,7 +547,7 @@ private static void Drop(LiveEventBody body, string drop)
}
}
- /// Opens the event bus through the generated door or straight through the stream spine it forwards to.
+ /// Exercises the public door or the raw stream spine's explicit refusal.
private static IAsyncEnumerable Subscribe(string entry, Pipeline pipeline, OpenCodeRequestOptions options) => entry == "door"
? new EventsClient(pipeline).SubscribeAsync(requestOptions: options)
: pipeline.ExecuteStreamAsync("event.subscribe", HttpMethod.Get, "/api/event", EventSubscribeResponseStreamAdapter.Instance, options, CancellationToken.None);
@@ -754,12 +559,10 @@ public async Task The_Callers_Cancellation_Should_Win_Over_Disposal_During_The_D
using var caller = new CancellationTokenSource();
await using var events = server.Events.SubscribeAsync(cancellationToken: caller.Token).GetAsyncEnumerator();
- // The failing send keeps link registration and this registration on the same thread.
- // Do not insert an incomplete await between starting the pull and registering disposal.
var pending = PendingCancellationAsync(events);
- using var disposal = caller.Token.Register(server.DisposeClient);
await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
await caller.CancelOnWorkerAsync();
+ server.DisposeClient();
await AssertReadCanceledByCallerAsync(pending, caller.Token);
}
@@ -767,14 +570,18 @@ public async Task The_Callers_Cancellation_Should_Win_Over_Disposal_During_The_D
[Test]
public async Task A_First_Event_Refusal_Should_Report_The_Exact_First_Frame_Text()
{
- using var server = new ScriptedEventServer(_ =>
- ScriptedEventServer.StreamOf(WireBodyData.Frames(_fixtures.LoadJson("Events.session-created.json"))));
+ using var server = new ScriptedEventServer(index => ScriptedEventServer.StreamOf(index == 1
+ ? WireBodyData.Frames(_fixtures.LoadJson("Events.session-created.json"))
+ : ConnectedFrame));
await using var events = server.Events.SubscribeAsync().GetAsyncEnumerator();
var first = PendingNext(events);
- await FailEveryAttemptUntilTheMinuteAsync(server, first, cyclesBefore: 59);
-
- var failure = await Assert.That(first.WaitAsync(HangGuard.Bound)).Throws();
- await Assert.That(failure!.Message).IsEqualTo("The opencode event stream did not start with server.connected.");
+ await server.Time.WaitForArmedAsync(Delay, HangGuard.Bound);
+ var state = server.Events.GetConnectionState();
+ await Assert.That(state.Error).IsTypeOf();
+ await Assert.That(state.Error!.Message).IsEqualTo("The opencode event stream did not start with server.connected.");
+ server.Time.Advance(Delay);
+ await Assert.That(await first.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(events.Current.Type).IsEqualTo("server.connected");
}
}
diff --git a/tests/OpenCode.Sdk.Tests/Events/EventsClientTests.cs b/tests/OpenCode.Sdk.Tests/Events/EventsClientTests.cs
index f8af9eb6f..817a6641b 100644
--- a/tests/OpenCode.Sdk.Tests/Events/EventsClientTests.cs
+++ b/tests/OpenCode.Sdk.Tests/Events/EventsClientTests.cs
@@ -1,3 +1,5 @@
+using System.Text.Json;
+using System.Threading.Channels;
using OpenCode.Sdk.Internal;
using OpenCode.Sdk.Models;
using OpenCode.Sdk.Tests.Events.Support;
@@ -9,8 +11,147 @@ namespace OpenCode.Sdk.Tests.Events;
public sealed class EventsClientTests
{
+ [Test]
+ public async Task SubscribeAsync_Should_Refuse_A_Pull_On_The_Unenumerated_Recipe()
+ {
+ using var server = new ScriptedEventServer(_ => ScriptedEventServer.StreamOf(EventStreamSteps.ConnectedFrame));
+ await using var recipe = (IAsyncEnumerator)server.Events.SubscribeAsync();
+ await EventStreamSteps.AssertRecipePullRefusedAsync(recipe);
+ await Assert.That(server.RequestCount).IsEqualTo(0);
+ }
+
private readonly FixtureLoader _fixtures = new();
+ [Test]
+ public async Task GetConnectionState_Should_Refuse_Disposed_Roots_And_End_Their_Pending_Watches()
+ {
+ using var handler = new RecordingHttpHandler();
+ using var httpClient = new HttpClient(handler);
+ using var pipeline = PipelineFactory.Create(httpClient, time: new ManualTimeProvider());
+ var door = new EventsClient(pipeline);
+ await using var watcher = door.WatchConnectionAsync().GetAsyncEnumerator();
+ await Assert.That(await EventStreamSteps.PendingNext(watcher).WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(watcher.Current.Status).IsEqualTo(EventConnectionStatus.Idle);
+ var pending = EventStreamSteps.PendingNext(watcher);
+ pipeline.Dispose();
+
+ _ = await Assert.That(door.GetConnectionState).Throws();
+ _ = await Assert.That(() => door.WatchConnectionAsync()).Throws();
+ _ = await Assert.That(pending).Throws();
+ await Assert.That(handler.Requests).IsEmpty();
+ }
+
+ [Test]
+ public async Task GetConnectionState_Should_Remain_Virtual_And_Use_The_Mocking_Seam()
+ {
+ EventsClient door = new MockEventsClient();
+ await Assert.That(door.GetConnectionState()).IsSameReferenceAs(MockEventsClient.KnownState);
+ await using var states = door.WatchConnectionAsync().GetAsyncEnumerator();
+ await Assert.That(await EventStreamSteps.PendingNext(states).WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(states.Current).IsSameReferenceAs(MockEventsClient.KnownState);
+ await Assert.That(await EventStreamSteps.PendingNext(states).WaitAsync(HangGuard.Bound)).IsFalse();
+ var expected = "'EventsClient.Pipeline' was invoked on an instance created through the protected mocking constructor; override the member under test.";
+ var snapshotFailure = await Assert.That(() => new UnoverriddenEventsClient().GetConnectionState()).Throws();
+ var watchFailure = await Assert.That(() => new UnoverriddenEventsClient().WatchConnectionAsync()).Throws();
+ await Assert.That(snapshotFailure!.Message).IsEqualTo(expected);
+ await Assert.That(watchFailure!.Message).IsEqualTo(expected);
+ }
+
+ [Test]
+ public async Task SubscribeAsync_Should_Receive_An_Event_Published_During_The_Refresh_After_Admission()
+ {
+ using var body = new LiveEventBody(EventStreamSteps.ConnectedFrame);
+ var initiallyReading = body.NextEmptyRead;
+ using var server = new ScriptedEventServer(_ => ScriptedEventServer.Stream(body));
+ await using var observer = server.Events.SubscribeAsync(new EventSubscribeRequest { Types = [new("rpc.other")] }).GetAsyncEnumerator();
+ await Assert.That((await EventStreamSteps.NextAsync(observer)).Type).IsEqualTo("server.connected");
+ await using var original = server.Events.SubscribeAsync().GetAsyncEnumerator();
+ await Assert.That((await EventStreamSteps.NextAsync(original)).Type).IsEqualTo("server.connected");
+ await initiallyReading.WaitAsync(HangGuard.Bound);
+ var overflowFrame = WireBodyData.Frames(JsonSerializer.Serialize(SharedEventFeedScenario.Event("overflow"), OpenCodeJsonContext.Default.IEvent));
+ var drained = body.NextEmptyRead;
+ body.Append(string.Concat(Enumerable.Repeat(overflowFrame, 4097)));
+ await drained.WaitAsync(HangGuard.Bound);
+ _ = await Assert.That(async () => await original.MoveNextAsync()).Throws();
+
+ await using var replacement = server.Events.SubscribeAsync().GetAsyncEnumerator();
+ await Assert.That((await EventStreamSteps.NextAsync(replacement)).Type).IsEqualTo("server.connected");
+ var refreshEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var release = Channel.CreateBounded(1);
+ async Task RefreshAsync()
+ {
+ refreshEntered.SetResult();
+ _ = await release.Reader.ReadAsync(CancellationToken.None);
+ }
+
+ var refreshing = RefreshAsync();
+ try
+ {
+ await refreshEntered.Task.WaitAsync(HangGuard.Bound);
+ drained = body.NextEmptyRead;
+ body.Append(WireBodyData.Frames(JsonSerializer.Serialize(SharedEventFeedScenario.Event("E2"), OpenCodeJsonContext.Default.IEvent)));
+ await drained.WaitAsync(HangGuard.Bound);
+ }
+ finally
+ {
+ _ = release.Writer.TryWrite(true);
+ }
+
+ await refreshing.WaitAsync(HangGuard.Bound);
+ var tail = await EventStreamSteps.NextAsync(replacement);
+ await Assert.That(tail.Id).IsEqualTo("E2");
+ await Assert.That(server.RequestCount).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task SubscribeAsync_Should_Snapshot_Types_And_Validate_Default_Values_At_The_Call()
+ {
+ var frames = WireBodyData.Frames(ScriptedEventServer.Connected,
+ _fixtures.LoadJson("Events.session-created.json"), _fixtures.LoadJson("Events.unknown-log-event.json"));
+ using var handler = new RecordingHttpHandler(_ => ScriptedEventServer.StreamOf(frames));
+ using var httpClient = new HttpClient(handler);
+ using var pipeline = PipelineFactory.Create(httpClient, time: new ManualTimeProvider());
+ var door = new EventsClient(pipeline);
+ var invalid = await Assert.That(() => door.SubscribeAsync(new EventSubscribeRequest { Types = [default] })).Throws();
+ await Assert.That(invalid!.ParamName).IsEqualTo("request");
+ await Assert.That(handler.Requests).IsEmpty();
+ var types = new List { EventType.SessionCreated };
+ var recipe = door.SubscribeAsync(new EventSubscribeRequest { Types = types });
+ types.Clear();
+ types.Add(new EventType("session.invented.tomorrow"));
+ await using var events = recipe.GetAsyncEnumerator();
+
+ await Assert.That((await EventStreamSteps.NextAsync(events)).Type).IsEqualTo("server.connected");
+ await Assert.That((await EventStreamSteps.NextAsync(events)).Id).IsEqualTo("evt_1");
+ await Assert.That(handler.Requests.Single().RequestUri!.Query).IsEqualTo(string.Empty);
+ }
+
+ [Test]
+ public async Task SubscribeAsync_Should_Share_One_Source_Between_Two_Subscriptions()
+ {
+ var bodies = new List();
+ using var server = new ScriptedEventServer(_ =>
+ {
+ var body = new LiveEventBody(EventStreamSteps.ConnectedFrame);
+ bodies.Add(body);
+ return ScriptedEventServer.Stream(body);
+ });
+ await using var first = server.Events.SubscribeAsync().GetAsyncEnumerator();
+ await using var second = server.Events.SubscribeAsync().GetAsyncEnumerator();
+ var firstMarker = await EventStreamSteps.NextAsync(first);
+ var secondMarker = await EventStreamSteps.NextAsync(second);
+
+ await Assert.That(server.RequestCount).IsEqualTo(1);
+ await Assert.That(secondMarker).IsSameReferenceAs(firstMarker);
+ bodies.Single().Append(WireBodyData.Frames(_fixtures.LoadJson("Events.session-created.json")));
+ _ = await EventStreamSteps.SharedEventAsync(first, second, "evt_1");
+ await first.DisposeAsync();
+ await Assert.That(bodies.Single().IsDisposed).IsFalse();
+ bodies.Single().Append(WireBodyData.Frames(_fixtures.LoadJson("Events.unknown-log-event.json")));
+ var tail = (UnknownEvent)await EventStreamSteps.NextAsync(second);
+ await Assert.That(tail.Payload.GetProperty("id").GetString()).IsEqualTo("evt_3");
+ }
+
[Test]
public async Task SubscribeAsync_Should_Delegate_The_Request_Options_And_Token()
{
@@ -21,7 +162,10 @@ public async Task SubscribeAsync_Should_Delegate_The_Request_Options_And_Token()
using var httpClient = new HttpClient(handler);
using var pipeline = PipelineFactory.Create(httpClient, location: new LocationSelector { Directory = "/ambient" }, time: time);
var door = new EventsClient(pipeline);
- var request = new EventSubscribeRequest { Types = [new EventType("session.created"), new EventType("rpc.sdk test/Γ§")] };
+ var request = new EventSubscribeRequest
+ {
+ Types = [new EventType("session.created"), new EventType("rpc.sdk test/Γ§"), new EventType("session.invented.tomorrow")],
+ };
var options = new OpenCodeRequestOptions { Location = new LocationSelector { Directory = "/override/Γ§" } };
using var caller = new CancellationTokenSource();
await using var events = door.SubscribeAsync(request, options, caller.Token).GetAsyncEnumerator();
@@ -39,9 +183,9 @@ await Assert.That(received.Select(static item => item.Type))
await Assert.That(received.Select(static item => item.Id)).IsEquivalentTo(expectedIds, CollectionOrdering.Matching);
await Assert.That(((UnknownEvent)received[2]).Payload.GetProperty("id").GetString()).IsEqualTo("evt_3");
await Assert.That(handler.Requests.Select(static attempt => attempt.RequestUri!.Query))
- .IsEquivalentTo(["?types=session.created&types=rpc.sdk%20test%2F%C3%A7"], CollectionOrdering.Matching);
+ .IsEquivalentTo([string.Empty], CollectionOrdering.Matching);
await Assert.That(handler.Requests.Select(static attempt => attempt.Headers["x-opencode-directory"]))
- .IsEquivalentTo(["%2Foverride%2F%C3%A7"], CollectionOrdering.Matching);
+ .IsEquivalentTo(["%2Fambient"], CollectionOrdering.Matching);
using var readyHandler = EventStreamSteps.CreateReconnectHandler();
using var readyHttpClient = new HttpClient(readyHandler);
@@ -72,11 +216,22 @@ await Assert.That(exception!.Message).IsEqualTo(
private sealed class MockEventsClient : EventsClient
{
- internal static readonly IEvent KnownEvent = new EventServerConnected { Id = "mocked", Data = new Dictionary(StringComparer.Ordinal) };
+ internal static readonly EventConnectionState KnownState = new(EventConnectionStatus.Reconnecting, 7, new OpenCodeTransportException("mock"));
+ internal static readonly IEvent KnownEvent = new EventServerConnected { Id = "mocked", Data = new Dictionary(StringComparer.Ordinal) };
public override IAsyncEnumerable SubscribeAsync(EventSubscribeRequest? request = null,
OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) => Sequence();
+ public override EventConnectionState GetConnectionState() => KnownState;
+
+ public override IAsyncEnumerable WatchConnectionAsync(CancellationToken cancellationToken = default) => States();
+
+ private static async IAsyncEnumerable States()
+ {
+ await Task.CompletedTask;
+ yield return KnownState;
+ }
+
private static async IAsyncEnumerable Sequence()
{
await Task.CompletedTask;
diff --git a/tests/OpenCode.Sdk.Tests/Events/SharedEventFeedTests.cs b/tests/OpenCode.Sdk.Tests/Events/SharedEventFeedTests.cs
new file mode 100644
index 000000000..5de6d746d
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/SharedEventFeedTests.cs
@@ -0,0 +1,459 @@
+using System.Reflection;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Threading.Channels;
+using OpenCode.Sdk.Internal;
+using OpenCode.Sdk.Models;
+using OpenCode.Sdk.Tests.Events.Support;
+using OpenCode.Sdk.Tests.Harness;
+using OpenCode.Sdk.Tests.Support;
+using TUnit.Assertions.Enums;
+
+namespace OpenCode.Sdk.Tests.Events;
+
+public sealed class SharedEventFeedTests
+{
+ [Test]
+ public async Task SubscribeAsync_Should_Create_Queue_And_Watch_State_Only_For_Enumerators()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var recipe = (EventSubscription)scenario.Feed.Subscribe(EventSelection.Capture(null), default);
+ await using var watchRecipe = (EventStateWatcher)scenario.Feed.Watch(default);
+ var queue = typeof(EventSubscription).GetField("_queue", BindingFlags.NonPublic | BindingFlags.Instance)!;
+ var watch = typeof(EventStateWatcher).GetField("_subscription", BindingFlags.NonPublic | BindingFlags.Instance)!;
+ await Assert.That(queue.GetValue(recipe)).IsNull();
+ await Assert.That(watch.GetValue(watchRecipe)).IsNull();
+ await using var events = recipe.GetAsyncEnumerator();
+ await using var watcher = watchRecipe.GetAsyncEnumerator();
+
+ await Assert.That(queue.GetValue(events)).IsNotNull();
+ await Assert.That(watch.GetValue(watcher)).IsNotNull();
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task SubscribeAsync_Should_Replay_The_Latest_Marker_Without_Business_History()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var first = await scenario.AdmitAsync("marker-one");
+ var lateRecipe = scenario.Feed.Subscribe(EventSelection.Capture(null), default);
+ var latest = SharedEventFeedScenario.Marker("marker-two");
+ await scenario.CurrentAttempt!.PublishAsync(latest);
+ await scenario.PublishAsync("earlier-business");
+ await using var late = lateRecipe.GetAsyncEnumerator();
+
+ await Assert.That(await EventStreamSteps.NextAsync(late)).IsSameReferenceAs(latest);
+ await scenario.PublishAsync("later-business");
+ await Assert.That((await EventStreamSteps.NextAsync(late)).Id).IsEqualTo("later-business");
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task Complete_Should_Propagate_The_Current_Runners_Faulted_Task()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("faulted-task-marker");
+ var source = scenario.Feed.GetCurrentSource()!;
+ var failure = new InvalidOperationException("faulted task");
+ scenario.Feed.Complete(source, Task.FromException(failure));
+
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+ var observed = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(observed).IsSameReferenceAs(failure);
+ }
+
+ private readonly FixtureLoader _fixtures = new();
+
+ [Test]
+ public async Task SubscribeAsync_Should_Not_Count_Excluded_Events_Toward_Capacity()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var owner = await scenario.AdmitAsync("M");
+ await using var selected = (EventSubscription)scenario.Feed.Subscribe(
+ EventSelection.Capture([new("rpc.sdk-test")]), default).GetAsyncEnumerator();
+ await Assert.That((await EventStreamSteps.NextAsync(selected)).Type).IsEqualTo("server.connected");
+ var excluded = new LocationShutdown { Id = "excluded", Created = 0, Data = new Dictionary(StringComparer.Ordinal) };
+ for (var index = 0; index < 4097; index++)
+ {
+ await scenario.CurrentAttempt!.PublishAsync(excluded);
+ }
+
+ await Assert.That(selected.RetainedCount).IsEqualTo(0);
+ await scenario.PublishAsync("selected");
+ await Assert.That((await EventStreamSteps.NextAsync(selected)).Id).IsEqualTo("selected");
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task SubscribeAsync_Should_Give_Two_Enumerations_Of_One_Result_Two_Subscriptions()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ using var caller = new CancellationTokenSource();
+ var recipe = scenario.Feed.Subscribe(EventSelection.Capture(null), default);
+ await using var first = recipe.GetAsyncEnumerator(caller.Token);
+ await using var second = recipe.GetAsyncEnumerator();
+ var firstMove = EventStreamSteps.PendingNext(first);
+ var secondMove = EventStreamSteps.PendingNext(second);
+ var attempt = await scenario.Attempts.NextOpenAsync();
+ await attempt.PublishAsync(SharedEventFeedScenario.Marker("M"));
+ await Assert.That(await firstMove.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(await secondMove.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(second.Current).IsSameReferenceAs(first.Current);
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(1);
+ await caller.CancelOnWorkerAsync();
+ await attempt.PublishAsync(SharedEventFeedScenario.Event("E1"));
+ await Assert.That((await EventStreamSteps.NextAsync(second)).Id).IsEqualTo("E1");
+ var canceled = await EventStreamSteps.PendingCancellationAsync(first).WaitAsync(HangGuard.Bound);
+ await Assert.That(canceled!.CancellationToken).IsEqualTo(caller.Token);
+ await using var otherRoot = new SharedEventFeedScenario();
+ await using var other = await otherRoot.AdmitAsync("other-root");
+ await Assert.That(other.Current.Id).IsEqualTo("other-root");
+ await Assert.That(otherRoot.Attempts.OpenCount).IsEqualTo(1);
+ await Assert.That(otherRoot.Feed.GetCurrentSource()).IsNotSameReferenceAs(scenario.Feed.GetCurrentSource());
+ }
+
+ [Test]
+ public async Task MoveNextAsync_Should_Admit_Lazily_And_Open_Nothing_After_Pre_Cancellation_Or_Pre_Disposal()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ var recipe = scenario.Feed.Subscribe(EventSelection.Capture(null), default);
+ await using var disposed = recipe.GetAsyncEnumerator();
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ await disposed.DisposeAsync();
+ await Assert.That(await disposed.MoveNextAsync()).IsFalse();
+ using var caller = new CancellationTokenSource();
+ await caller.CancelOnWorkerAsync();
+ await using var canceled = recipe.GetAsyncEnumerator(caller.Token);
+ var failure = await EventStreamSteps.PendingCancellationAsync(canceled).WaitAsync(HangGuard.Bound);
+ await Assert.That(failure!.CancellationToken).IsEqualTo(caller.Token);
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(0);
+ await using var live = await scenario.AdmitAsync("M");
+ await Assert.That(live.Current.Id).IsEqualTo("M");
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task SubscribeAsync_Should_Not_Replay_Business_Events_When_Publication_Wins(bool holdReadBeforeAdmission)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var owner = await scenario.AdmitAsync("M");
+ var marker = owner.Current;
+ await scenario.PublishAsync("E1");
+ var release = Channel.CreateBounded(1);
+ var read = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ Task? publishing = null;
+ if (holdReadBeforeAdmission)
+ {
+ scenario.CurrentAttempt!.BeforeReturn = async item =>
+ {
+ if (string.Equals(item.Id, "E2", StringComparison.Ordinal))
+ {
+ read.SetResult();
+ _ = await release.Reader.ReadAsync(CancellationToken.None);
+ }
+ };
+ publishing = scenario.PublishAsync("E2");
+ await read.Task.WaitAsync(HangGuard.Bound);
+ }
+
+ try
+ {
+ await using var late = await scenario.AdmitAsync("M");
+ await Assert.That(late.Current).IsSameReferenceAs(marker);
+ if (publishing is null)
+ {
+ publishing = scenario.PublishAsync("E2");
+ }
+
+ _ = release.Writer.TryWrite(true);
+ await publishing.WaitAsync(HangGuard.Bound);
+ string?[] received = [marker.Id, (await EventStreamSteps.NextAsync(late)).Id];
+ await Assert.That(received).IsEquivalentTo((string?[])["M", "E2"], CollectionOrdering.Matching);
+ }
+ finally
+ {
+ _ = release.Writer.TryWrite(true);
+ if (publishing is not null)
+ {
+ await publishing.WaitAsync(HangGuard.Bound);
+ }
+ }
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task SubscribeAsync_Should_Wait_For_A_New_Marker_When_A_Drop_Precedes_Admission(bool admissionFirst)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var owner = await scenario.AdmitAsync("M1");
+ var source = scenario.Feed.GetCurrentSource()!;
+ await using var late = scenario.Feed.Subscribe(EventSelection.Capture(null), default).GetAsyncEnumerator();
+ Task moving;
+ if (admissionFirst)
+ {
+ moving = EventStreamSteps.PendingNext(late);
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(late.Current.Id).IsEqualTo("M1");
+ scenario.Feed.RecordDrop(source, new OpenCodeTransportException("drop"), 1);
+ moving = EventStreamSteps.PendingNext(late);
+ }
+ else
+ {
+ scenario.Feed.RecordDrop(source, new OpenCodeTransportException("drop"), 1);
+ moving = EventStreamSteps.PendingNext(late);
+ }
+
+ scenario.Feed.RecordConnected(source, SharedEventFeedScenario.Marker("M2"));
+ scenario.Feed.Publish(source, SharedEventFeedScenario.Event("E2"));
+ await Assert.That(await moving.WaitAsync(HangGuard.Bound)).IsTrue();
+ string?[] received = [late.Current.Id, (await EventStreamSteps.NextAsync(late)).Id];
+ await Assert.That(received).IsEquivalentTo((string?[])["M2", "E2"], CollectionOrdering.Matching);
+ }
+
+ [Test]
+ [Arguments(0)]
+ [Arguments(1)]
+ [Arguments(2)]
+ public async Task SubscribeAsync_Should_Select_Exact_Types_And_Always_Include_The_Marker(int kind)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var owner = await scenario.AdmitAsync("M");
+ IReadOnlyList? types = kind switch
+ {
+ 0 => [EventType.SessionCreated, new("rpc.sdk-test")],
+ 1 => null,
+ _ => [],
+ };
+ await using var selected = scenario.Feed.Subscribe(EventSelection.Capture(types), default).GetAsyncEnumerator();
+ var marker = await EventStreamSteps.NextAsync(selected);
+ var excluded = new LocationShutdown { Id = "excluded", Created = 0, Data = new Dictionary(StringComparer.Ordinal) };
+ var native = JsonSerializer.Deserialize(_fixtures.LoadJson("Events.session-created.json"), OpenCodeJsonContext.Default.IEvent)!;
+ var unknown = JsonSerializer.Deserialize(_fixtures.LoadJson("Events.unknown-log-event.json"), OpenCodeJsonContext.Default.IEvent)!;
+ var drifted = JsonNode.Parse(ScriptedEventServer.Connected)!.AsObject();
+ drifted["data"] = false;
+ using var document = JsonDocument.Parse(drifted.ToJsonString());
+ IEvent driftedMarker = new UnknownEvent("server.connected", document.RootElement);
+ var candidates = new IEvent[]
+ {
+ excluded, native, SharedEventFeedScenario.Event("other") with { Type = "rpc.other" },
+ SharedEventFeedScenario.Event("requested"), unknown, driftedMarker,
+ };
+ foreach (var item in candidates)
+ {
+ await scenario.CurrentAttempt!.PublishAsync(item);
+ }
+
+ string[] expected = kind == 0
+ ? ["server.connected", "session.created", "rpc.sdk-test", "server.connected"]
+ : ["server.connected", "location.shutdown", "session.created", "rpc.other", "rpc.sdk-test", "session.invented.tomorrow", "server.connected"];
+ var actual = new List { marker.Type };
+ for (var index = 1; index < expected.Length; index++)
+ {
+ actual.Add((await EventStreamSteps.NextAsync(selected)).Type);
+ }
+
+ await Assert.That(actual).IsEquivalentTo(expected, CollectionOrdering.Matching);
+ await Assert.That(selected.Current).IsSameReferenceAs(driftedMarker);
+ await Assert.That(driftedMarker).IsTypeOf();
+ }
+
+ [Test]
+ public async Task SubscribeAsync_Should_Share_Event_And_Metadata_Instances_Between_Subscriptions()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var first = await scenario.AdmitAsync("M");
+ await using var second = await scenario.AdmitAsync("M");
+ var metadata = new Dictionary(StringComparer.Ordinal);
+ var native = (SessionCreated)JsonSerializer.Deserialize(_fixtures.LoadJson("Events.session-created.json"), OpenCodeJsonContext.Default.IEvent)!;
+ await scenario.CurrentAttempt!.PublishAsync(native with { Metadata = metadata });
+ var right = await EventStreamSteps.SharedEventAsync(first, second, "evt_1");
+ var left = first.Current;
+ await Assert.That(right.Metadata).IsSameReferenceAs(metadata);
+ metadata.Add("controlled-mutation", default);
+ await Assert.That(left.Metadata).ContainsKey("controlled-mutation");
+ await Assert.That(right.Metadata!["controlled-mutation"].ValueKind).IsEqualTo(JsonValueKind.Undefined);
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task RecordConnected_Should_Ignore_A_Retired_Source_After_Its_Replacement_Connects(bool cleanupFirst)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var retired = await scenario.AdmitAsync("M1");
+ var oldSource = scenario.Feed.GetCurrentSource()!;
+ var oldAttempt = scenario.CurrentAttempt!;
+ oldAttempt.CleanupFailure = new InvalidOperationException("retired cleanup");
+ await retired.DisposeAsync();
+ if (cleanupFirst)
+ {
+ oldAttempt.ReleaseCleanup();
+ await scenario.Feed.JoinAsync().WaitAsync(HangGuard.Bound);
+ }
+
+ await using var current = await scenario.AdmitAsync("M2");
+ var marker = current.Current;
+ var source = scenario.Feed.GetCurrentSource();
+ var state = scenario.Feed.GetConnectionState();
+ scenario.Feed.RecordConnected(oldSource, SharedEventFeedScenario.Marker("stale"));
+ scenario.Feed.Publish(oldSource, SharedEventFeedScenario.Event("stale-event"));
+ scenario.Feed.RecordDrop(oldSource, new OpenCodeTransportException("stale drop"), 1);
+ await Assert.That(scenario.Feed.RecordAttemptStarted(oldSource)).IsFalse();
+ scenario.Feed.RecordFault(oldSource, new InvalidOperationException("stale fault"));
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsSameReferenceAs(source);
+ await Assert.That(scenario.Feed.GetConnectionState()).IsSameReferenceAs(state);
+ await Assert.That(current.RetainedCount).IsEqualTo(0);
+ oldAttempt.ReleaseCleanup();
+ var observed = oldSource.RunnerObservation!.ContinueWith(static task => task.Status,
+ CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
+ await Assert.That(await observed.WaitAsync(HangGuard.Bound)).IsEqualTo(TaskStatus.RanToCompletion);
+ await using var late = await scenario.AdmitAsync("M2");
+
+ await Assert.That(late.Current).IsSameReferenceAs(marker);
+ await scenario.PublishAsync("E2");
+ string?[] received = [(await EventStreamSteps.NextAsync(current)).Id, (await EventStreamSteps.NextAsync(late)).Id];
+ await Assert.That(received).IsEquivalentTo((string?[])["E2", "E2"], CollectionOrdering.Matching);
+ await Assert.That(scenario.Attempts.OpenCount).IsEqualTo(2);
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task Dispose_Should_Fence_Publication_And_Close_Admission_Before_Cancelling_The_Runner(bool publicationFirst)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ var source = scenario.Feed.GetCurrentSource()!;
+ var pending = EventStreamSteps.PendingNext(events);
+ if (publicationFirst)
+ {
+ scenario.Feed.Publish(source, SharedEventFeedScenario.Event("E1"));
+ }
+
+ scenario.Feed.Dispose();
+ scenario.Feed.Publish(source, SharedEventFeedScenario.Event("rejected"));
+ scenario.Feed.RecordConnected(source, SharedEventFeedScenario.Marker("rejected-marker"));
+ if (publicationFirst)
+ {
+ await Assert.That(await pending.WaitAsync(HangGuard.Bound)).IsTrue();
+ await Assert.That(events.Current.Id).IsEqualTo("E1");
+ }
+ else
+ {
+ _ = await Assert.That(pending).Throws();
+ }
+
+ _ = await Assert.That(async () => await events.MoveNextAsync()).Throws();
+ await Assert.That(events.RetainedCount).IsEqualTo(0);
+ await using var late = scenario.Feed.Subscribe(EventSelection.Capture(null), default).GetAsyncEnumerator();
+ _ = await Assert.That(async () => await late.MoveNextAsync()).Throws();
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+ }
+
+ [Test]
+ [Arguments("cancel")]
+ [Arguments("dispose")]
+ [Arguments("overflow")]
+ public async Task EndLocked_Should_Stop_The_Source_Only_When_The_Last_Subscription_Leaves(string ending)
+ {
+ using var caller = new CancellationTokenSource();
+ await using var scenario = new SharedEventFeedScenario();
+ await using var first = await scenario.AdmitAsync("M", caller.Token);
+ await using var second = await scenario.AdmitAsync("M");
+ var source = scenario.Feed.GetCurrentSource()!;
+ if (string.Equals(ending, "cancel", StringComparison.Ordinal))
+ {
+ await caller.CancelOnWorkerAsync();
+ }
+ else if (string.Equals(ending, "dispose", StringComparison.Ordinal))
+ {
+ await first.DisposeAsync();
+ }
+ else
+ {
+ for (var index = 0; index < 4097; index++)
+ {
+ await scenario.PublishAsync("overflow");
+ await Assert.That((await EventStreamSteps.NextAsync(second)).Id).IsEqualTo("overflow");
+ }
+
+ _ = await Assert.That(async () => await first.MoveNextAsync()).Throws();
+ }
+
+ await scenario.PublishAsync("E2");
+ await Assert.That((await EventStreamSteps.NextAsync(second)).Id).IsEqualTo("E2");
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsSameReferenceAs(source);
+ await Assert.That(source.Token.IsCancellationRequested).IsFalse();
+ await second.DisposeAsync();
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+ scenario.CurrentAttempt!.ReleaseCleanup();
+ await scenario.Feed.JoinAsync().WaitAsync(HangGuard.Bound);
+ await Assert.That(source.Token.IsCancellationRequested).IsTrue();
+ await Assert.That(source.IsReleased).IsTrue();
+ }
+
+ [Test]
+ public async Task Publish_Should_Not_Run_A_Consumer_Continuation_Inside_The_Gate()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ var source = scenario.Feed.GetCurrentSource()!;
+ using var publishingScope = new ThreadLocal(static () => false);
+ var moving = EventStreamSteps.PendingNext(events);
+ var consumer = moving.ContinueWith(completed =>
+ {
+ _ = scenario.Feed.GetCurrentSource();
+ return publishingScope.Value;
+ }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
+ var publishing = DedicatedThread.Run(() =>
+ {
+ publishingScope.Value = true;
+ try
+ {
+ scenario.Feed.Publish(source, SharedEventFeedScenario.Event("E1"));
+ }
+ finally
+ {
+ publishingScope.Value = false;
+ }
+ });
+
+ await publishing.WaitAsync(HangGuard.Bound);
+ await Assert.That(await consumer.WaitAsync(HangGuard.Bound)).IsFalse();
+ await Assert.That(events.Current.Id).IsEqualTo("E1");
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task Complete_Should_Fault_Every_Subscription_When_The_Current_Runner_Returns_Or_Is_Cancelled(bool canceled)
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var first = await scenario.AdmitAsync("M");
+ await using var second = await scenario.AdmitAsync("M");
+ var source = scenario.Feed.GetCurrentSource()!;
+ using var cancellation = new CancellationTokenSource();
+ await cancellation.CancelOnWorkerAsync();
+ scenario.Feed.Complete(source, canceled ? Task.FromCanceled(cancellation.Token) : Task.CompletedTask);
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+
+ var left = await Assert.That(async () => await first.MoveNextAsync()).Throws();
+ var right = await Assert.That(async () => await second.MoveNextAsync()).Throws();
+ await Assert.That(left).IsSameReferenceAs(right);
+ if (canceled)
+ {
+ await Assert.That(left).IsTypeOf();
+ }
+ else
+ {
+ await Assert.That(left).IsTypeOf();
+ await Assert.That(left!.Message).IsEqualTo("The current event source returned without an ending.");
+ }
+
+ await Assert.That(scenario.Feed.GetCurrentSource()).IsNull();
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Events/Support/EventStreamSteps.cs b/tests/OpenCode.Sdk.Tests/Events/Support/EventStreamSteps.cs
index 377eac2a0..0394c9079 100644
--- a/tests/OpenCode.Sdk.Tests/Events/Support/EventStreamSteps.cs
+++ b/tests/OpenCode.Sdk.Tests/Events/Support/EventStreamSteps.cs
@@ -60,7 +60,7 @@ internal static async Task WithPendingCancellationAsync(CancellationTokenSource
/// Asks for the next event without waiting for it, and keeps the cancellation it ends with whole:
/// a downlevel WaitAsync rethrows a cancellation without its token.
///
- internal static async Task PendingCancellationAsync(IAsyncEnumerator events)
+ internal static async Task PendingCancellationAsync(IAsyncEnumerator events)
{
try
{
@@ -74,9 +74,53 @@ internal static async Task WithPendingCancellationAsync(CancellationTokenSource
}
/// Asks for the next event without waiting for it, so the test can move time while the read is pending.
- internal static Task PendingNext(IAsyncEnumerator events) => events.MoveNextAsync().AsTask();
+ internal static Task PendingNext(IAsyncEnumerator events) => events.MoveNextAsync().AsTask();
- internal static async Task NextAsync(IAsyncEnumerator events)
+ internal static async Task ObserveSourceCompletionAsync(EventSource source, bool cancellation = false)
+ {
+ var task = cancellation ? source.CancellationObservation! : source.RunnerObservation!;
+ var observation = task.ContinueWith(static completed => completed.Status,
+ CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
+ await Assert.That(await observation.WaitAsync(HangGuard.Bound, CancellationToken.None)).IsEqualTo(TaskStatus.RanToCompletion);
+ }
+
+ internal static async Task SharedEventAsync(IAsyncEnumerator first, IAsyncEnumerator second, string id)
+ {
+ var left = await NextAsync(first);
+ var right = await NextAsync(second);
+ await Assert.That(left.Id).IsEqualTo(id);
+ await Assert.That(right).IsSameReferenceAs(left);
+ return right;
+ }
+
+ internal static async Task AssertConnectedAsync(IAsyncEnumerator events, bool moved)
+ {
+ await Assert.That(moved).IsTrue();
+ await Assert.That(events.Current.Type).IsEqualTo("server.connected");
+ }
+
+ internal static async Task AssertStateAsync(EventConnectionState state, EventConnectionStatus status, int attempt, Exception? error)
+ {
+ await Assert.That(state.Status).IsEqualTo(status);
+ await Assert.That(state.Attempt).IsEqualTo(attempt);
+ await Assert.That(state.Error).IsSameReferenceAs(error);
+ }
+
+ internal static async Task CancelAndCaptureAsync(CancellationTokenSource caller, IAsyncEnumerator events)
+ {
+ await caller.CancelOnWorkerAsync();
+ var canceled = await PendingCancellationAsync(events).WaitAsync(HangGuard.Bound, CancellationToken.None);
+ await Assert.That(canceled!.CancellationToken).IsEqualTo(caller.Token);
+ }
+
+ internal static async Task AssertRecipePullRefusedAsync(IAsyncEnumerator recipe)
+ {
+ var failure = await Assert.That(async () => await recipe.MoveNextAsync()).Throws();
+ await Assert.That(failure!.Message)
+ .IsEqualTo("Enumerate the returned sequence with GetAsyncEnumerator before calling MoveNextAsync.");
+ }
+
+ internal static async Task NextAsync(IAsyncEnumerator events)
{
if (!await events.MoveNextAsync().AsTask().WaitAsync(HangGuard.Bound))
{
diff --git a/tests/OpenCode.Sdk.Tests/Events/Support/ScriptedEventAttemptSource.cs b/tests/OpenCode.Sdk.Tests/Events/Support/ScriptedEventAttemptSource.cs
new file mode 100644
index 000000000..414d8a6ea
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/Support/ScriptedEventAttemptSource.cs
@@ -0,0 +1,118 @@
+using System.Text;
+using System.Threading.Channels;
+using OpenCode.Sdk.Internal;
+using OpenCode.Sdk.Models;
+using OpenCode.Sdk.Tests.Support;
+
+namespace OpenCode.Sdk.Tests.Events.Support;
+
+/// One controllable queue per physical attempt, acknowledging publication after the runner advances.
+internal sealed class ScriptedEventAttemptSource : IEventAttemptSource
+{
+ private readonly Channel _opened = Channel.CreateUnbounded();
+ private readonly List _attempts = [];
+ private readonly Lock _gate = new();
+ public Action? OnOpen { get; set; }
+
+ public IAsyncEnumerable OpenAsync(StreamAttempt attempt, CancellationToken cancellationToken)
+ {
+ OnOpen?.Invoke();
+ var opened = new Attempt(attempt, cancellationToken);
+ lock (_gate)
+ {
+ _attempts.Add(opened);
+ }
+
+ _ = _opened.Writer.TryWrite(opened);
+ return opened;
+ }
+
+ public Task NextOpenAsync() => _opened.Reader.ReadAsync().AsTask().WaitAsync(HangGuard.Bound);
+
+ public int OpenCount
+ {
+ get
+ {
+ lock (_gate)
+ {
+ return _attempts.Count;
+ }
+ }
+ }
+
+ public void ReleaseCleanup()
+ {
+ lock (_gate)
+ {
+ foreach (var attempt in _attempts)
+ {
+ attempt.ReleaseCleanup();
+ }
+ }
+ }
+
+ internal sealed class Attempt(StreamAttempt attempt, CancellationToken token) : IAsyncEnumerable, IAsyncEnumerator
+ {
+ private readonly Channel _cleanupRelease = Channel.CreateUnbounded();
+ private Publication? _previous;
+ internal Channel Items { get; } = Channel.CreateUnbounded();
+ internal TaskCompletionSource CleanupEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ internal TaskCompletionSource CleanupReleased { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public CancellationToken Token { get; } = token;
+ public Exception? CleanupFailure { get; set; }
+ public Func? BeforeReturn { get; set; }
+ public IEvent Current { get; private set; } = null!;
+
+ public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) => this;
+
+ public async ValueTask MoveNextAsync()
+ {
+ _previous?.Published.SetResult();
+ _previous = null;
+ while (await Items.Reader.WaitToReadAsync(Token))
+ {
+ if (Items.Reader.TryRead(out var publication))
+ {
+ attempt.OnFrame(new ServerSentEvent(ServerSentEvent.DefaultName, Encoding.UTF8.GetBytes(ScriptedEventServer.Connected)));
+ Current = publication.Event;
+ _previous = publication;
+ if (BeforeReturn is { } beforeReturn)
+ {
+ await beforeReturn(Current);
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public void ReleaseCleanup() => _ = _cleanupRelease.Writer.TryWrite(true);
+
+ public async ValueTask DisposeAsync()
+ {
+ CleanupEntered.SetResult();
+ _ = await _cleanupRelease.Reader.ReadAsync(CancellationToken.None);
+ CleanupReleased.SetResult();
+ if (CleanupFailure is { } failure)
+ {
+ throw failure;
+ }
+ }
+
+ public async Task PublishAsync(IEvent item)
+ {
+ var published = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var publication = new Publication(item, published);
+ await Items.Writer.WriteAsync(publication, CancellationToken.None);
+ await published.Task.WaitAsync(HangGuard.Bound, CancellationToken.None);
+ }
+ }
+
+ internal sealed class Publication(IEvent item, TaskCompletionSource published)
+ {
+ public IEvent Event { get; } = item;
+ public TaskCompletionSource Published { get; } = published;
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Events/Support/ScriptedEventAttemptSourceTests.cs b/tests/OpenCode.Sdk.Tests/Events/Support/ScriptedEventAttemptSourceTests.cs
new file mode 100644
index 000000000..acaa046c2
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/Support/ScriptedEventAttemptSourceTests.cs
@@ -0,0 +1,95 @@
+using OpenCode.Sdk.Internal;
+using OpenCode.Sdk.Models;
+using OpenCode.Sdk.Tests.Support;
+using TUnit.Assertions.Enums;
+
+namespace OpenCode.Sdk.Tests.Events.Support;
+
+public sealed class ScriptedEventAttemptSourceTests
+{
+ [Test]
+ public async Task DisposeAsync_Should_Surface_A_Cleanup_Fault_After_A_Normal_End()
+ {
+ var source = new ScriptedEventAttemptSource();
+ using var attempt = new StreamAttempt(new ManualTimeProvider(), EventStreamSteps.IdleWindow, default);
+ var events = source.OpenAsync(attempt, default).GetAsyncEnumerator();
+ var moving = events.MoveNextAsync().AsTask();
+ var opened = await source.NextOpenAsync();
+ var failure = new InvalidOperationException("cleanup failure");
+ opened.CleanupFailure = failure;
+ _ = opened.Items.Writer.TryComplete();
+ opened.ReleaseCleanup();
+ bool? moved = null;
+ Exception? readFailure = null;
+ Exception? cleanupFailure = null;
+ try
+ {
+ try
+ {
+ moved = await moving.WaitAsync(HangGuard.Bound);
+ }
+ catch (Exception exception)
+ {
+ readFailure = exception;
+ }
+ }
+ finally
+ {
+ try
+ {
+ await events.DisposeAsync();
+ }
+ catch (Exception exception)
+ {
+ cleanupFailure = exception;
+ }
+ }
+
+ await Assert.That(readFailure).IsNull();
+ await Assert.That(moved).IsFalse();
+ await Assert.That(cleanupFailure).IsSameReferenceAs(failure);
+ }
+
+ [Test]
+ public async Task OpenAsync_Should_Acknowledge_Publication_And_Hold_Cleanup_Until_Released()
+ {
+ var source = new ScriptedEventAttemptSource();
+ using var attempt = new StreamAttempt(new ManualTimeProvider(), EventStreamSteps.IdleWindow, default);
+ var ledger = new List();
+ var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ async Task ReadAsync()
+ {
+ await foreach (var item in source.OpenAsync(attempt, default))
+ {
+ received.SetResult(item);
+ }
+ }
+
+ var reading = ReadAsync();
+ var opened = await source.NextOpenAsync();
+ try
+ {
+ ledger.Add("open");
+ var publishing = opened.PublishAsync(SharedEventFeedScenario.Marker("M"));
+ await Assert.That((await received.Task.WaitAsync(HangGuard.Bound)).Id).IsEqualTo("M");
+ await publishing.WaitAsync(HangGuard.Bound);
+ ledger.Add("publication");
+ _ = opened.Items.Writer.TryComplete();
+ var entered = opened.CleanupEntered.Task.ContinueWith(_ => ledger.Add("cleanup-entered"),
+ CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
+ await entered.WaitAsync(HangGuard.Bound);
+ await Assert.That(opened.CleanupReleased.Task.IsCompleted).IsFalse();
+ }
+ finally
+ {
+ _ = opened.Items.Writer.TryComplete();
+ source.ReleaseCleanup();
+ await reading.WaitAsync(HangGuard.Bound);
+ }
+
+ ledger.Add("cleanup-released");
+ await Assert.That(opened.CleanupReleased.Task.Status).IsEqualTo(TaskStatus.RanToCompletion);
+ await Assert.That(ledger)
+ .IsEquivalentTo(["open", "publication", "cleanup-entered", "cleanup-released"], CollectionOrdering.Matching);
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Events/Support/SharedEventFeedScenario.cs b/tests/OpenCode.Sdk.Tests/Events/Support/SharedEventFeedScenario.cs
new file mode 100644
index 000000000..fcd7e39b1
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/Support/SharedEventFeedScenario.cs
@@ -0,0 +1,104 @@
+using System.Text.Json;
+using OpenCode.Sdk.Internal;
+using OpenCode.Sdk.Models;
+using OpenCode.Sdk.Tests.Support;
+
+namespace OpenCode.Sdk.Tests.Events.Support;
+
+/// Owns the feed and all attempts until their cleanup and observations have completed.
+internal sealed class SharedEventFeedScenario : IAsyncDisposable
+{
+ public SharedEventFeedScenario(IEventFeedGateProbe? probe = null)
+ {
+ Feed = new SharedEventFeed(Attempts, Time, EventStreamSteps.IdleWindow, probe ?? new NoOpEventFeedGateProbe());
+ }
+
+ public ManualTimeProvider Time { get; } = new();
+ public ScriptedEventAttemptSource Attempts { get; } = new();
+ public SharedEventFeed Feed { get; }
+ public ScriptedEventAttemptSource.Attempt? CurrentAttempt { get; private set; }
+
+ public EventSubscription CreateSubscription(CancellationToken caller = default, CancellationToken enumeration = default) =>
+ (EventSubscription)Feed.Subscribe(EventSelection.Capture(null), caller).GetAsyncEnumerator(enumeration);
+
+ public EventStateWatcher CreateWatcher(CancellationToken caller = default, CancellationToken enumeration = default) =>
+ (EventStateWatcher)Feed.Watch(caller).GetAsyncEnumerator(enumeration);
+
+ public async Task> AdmitAsync(string id, CancellationToken cancellationToken = default)
+ {
+ var opensSource = Feed.GetCurrentSource() is null;
+ var events = CreateSubscription(cancellationToken);
+ var moving = events.MoveNextAsync().AsTask();
+ if (opensSource)
+ {
+ CurrentAttempt = await Attempts.NextOpenAsync();
+ await CurrentAttempt.PublishAsync(Marker(id));
+ }
+
+ if (!await moving.WaitAsync(HangGuard.Bound, CancellationToken.None))
+ {
+ throw new InvalidOperationException("The subscription ended instead of being admitted.");
+ }
+
+ return events;
+ }
+
+ public async Task PublishAsync(string id) => await CurrentAttempt!.PublishAsync(Event(id));
+
+ public async Task PublishPrefixAsync(params string[] ids)
+ {
+ foreach (var id in ids)
+ {
+ await PublishAsync(id);
+ }
+ }
+
+ public async Task FailAttemptAsync(ScriptedEventAttemptSource.Attempt attempt, Exception failure)
+ {
+ _ = attempt.Items.Writer.TryComplete(failure);
+ attempt.ReleaseCleanup();
+ await Time.WaitForArmedAsync(EventStreamSteps.Delay, HangGuard.Bound);
+ return Feed.GetConnectionState();
+ }
+
+ public async Task FaultAsync(Exception failure)
+ {
+ await using var watcher = CreateWatcher(CancellationToken.None, CancellationToken.None);
+ _ = await EventStreamSteps.NextAsync(watcher);
+ var changed = EventStreamSteps.PendingNext(watcher);
+ CurrentAttempt!.CleanupFailure = failure;
+ _ = CurrentAttempt.Items.Writer.TryComplete();
+ CurrentAttempt.ReleaseCleanup();
+ await Assert.That(await changed.WaitAsync(HangGuard.Bound, CancellationToken.None)).IsTrue();
+ await EventStreamSteps.AssertStateAsync(watcher.Current, EventConnectionStatus.Idle, 0, null);
+ await Feed.JoinAsync().WaitAsync(HangGuard.Bound, CancellationToken.None);
+ }
+
+ public static EventServerConnected Marker(string id) => new()
+ {
+ Id = id,
+ Data = new Dictionary(StringComparer.Ordinal),
+ };
+
+ public static EventRpc Event(string id) => new()
+ {
+ Id = id,
+ Created = 0,
+ Type = "rpc.sdk-test",
+ Location = new LocationPublicRef { Directory = "/test" },
+ Data = new Dictionary(StringComparer.Ordinal),
+ };
+
+ public async ValueTask DisposeAsync()
+ {
+ try
+ {
+ Feed.Dispose();
+ }
+ finally
+ {
+ Attempts.ReleaseCleanup();
+ await Feed.JoinAsync().WaitAsync(HangGuard.Bound, CancellationToken.None);
+ }
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Events/Support/SharedEventFeedScenarioTests.cs b/tests/OpenCode.Sdk.Tests/Events/Support/SharedEventFeedScenarioTests.cs
new file mode 100644
index 000000000..911f343e3
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Events/Support/SharedEventFeedScenarioTests.cs
@@ -0,0 +1,31 @@
+using TUnit.Assertions.Exceptions;
+
+namespace OpenCode.Sdk.Tests.Events.Support;
+
+public sealed class SharedEventFeedScenarioTests
+{
+ [Test]
+ public async Task DisposeAsync_Should_Release_And_Join_All_Owned_Work()
+ {
+ await using var scenario = new SharedEventFeedScenario();
+ await using var events = await scenario.AdmitAsync("M");
+ var attempt = scenario.CurrentAttempt!;
+ var source = scenario.Feed.GetCurrentSource()!;
+
+ _ = await Assert.That(async () =>
+ {
+ try
+ {
+ await Assert.That(events.Current.Id).IsEqualTo("forced assertion failure");
+ }
+ finally
+ {
+ await scenario.DisposeAsync();
+ }
+ }).Throws();
+
+ await Assert.That(attempt.CleanupReleased.Task.Status).IsEqualTo(TaskStatus.RanToCompletion);
+ await Assert.That(source.IsReleased).IsTrue();
+ await Assert.That(source.RunnerObservation!.Status).IsEqualTo(TaskStatus.RanToCompletion);
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Hosting/OpenCodeServerContractTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/OpenCodeServerContractTests.cs
index 14fd365ad..f2af770bc 100644
--- a/tests/OpenCode.Sdk.Tests/Hosting/OpenCodeServerContractTests.cs
+++ b/tests/OpenCode.Sdk.Tests/Hosting/OpenCodeServerContractTests.cs
@@ -183,11 +183,13 @@ public async Task CreateClient_Should_Carry_Every_Behavior_Member_Into_The_Built
.GetField("_exchange", BindingFlags.NonPublic | BindingFlags.Instance)!
.GetValue(pipeline));
await Assert.That(carriedWindow).IsEqualTo(sentinelWindow);
- var carriedIdleWindow = (TimeSpan)typeof(ReconnectingEventStream)
+ var carriedIdleWindow = (TimeSpan)typeof(EventSourceRunner)
.GetField("_idleWindow", BindingFlags.NonPublic | BindingFlags.Instance)!
- .GetValue(typeof(Pipeline)
- .GetField("_reconnectingEventStream", BindingFlags.NonPublic | BindingFlags.Instance)!
- .GetValue(pipeline))!;
+ .GetValue(typeof(SharedEventFeed)
+ .GetField("_runner", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .GetValue(typeof(EventsClient)
+ .GetField("_feed", BindingFlags.NonPublic | BindingFlags.Instance)!
+ .GetValue(client.Events)))!;
await Assert.That(carriedIdleWindow).IsEqualTo(sentinelIdleWindow);
}
diff --git a/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt b/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt
index 002bdb462..744858acb 100644
--- a/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt
+++ b/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt
@@ -147,6 +147,20 @@ namespace OpenCode.Sdk
Default = 0,
NoThrow = 1,
}
+ public sealed class EventConnectionState
+ {
+ public EventConnectionState(OpenCode.Sdk.EventConnectionStatus status, int attempt, System.Exception? error) { }
+ public int Attempt { get; }
+ public System.Exception? Error { get; }
+ public OpenCode.Sdk.EventConnectionStatus Status { get; }
+ }
+ public enum EventConnectionStatus
+ {
+ Idle = 0,
+ Connecting = 1,
+ Connected = 2,
+ Reconnecting = 3,
+ }
public sealed class EventSubscribeRequest : System.IEquatable
{
public EventSubscribeRequest() { }
@@ -155,7 +169,9 @@ namespace OpenCode.Sdk
public class EventsClient
{
protected EventsClient() { }
+ public virtual OpenCode.Sdk.EventConnectionState GetConnectionState() { }
public virtual System.Collections.Generic.IAsyncEnumerable SubscribeAsync(OpenCode.Sdk.EventSubscribeRequest? request = null, OpenCode.Sdk.OpenCodeRequestOptions? requestOptions = null, System.Threading.CancellationToken cancellationToken = default) { }
+ public virtual System.Collections.Generic.IAsyncEnumerable WatchConnectionAsync(System.Threading.CancellationToken cancellationToken = default) { }
}
[System.Diagnostics.CodeAnalysis.Experimental("OPENCODE001", UrlFormat="https://github.com/opencode-dotnet/opencode-sdk-dotnet/blob/master/docs/guide/exp" +
"erimental.md#opencode001")]
@@ -955,6 +971,13 @@ namespace OpenCode.Sdk
public string? Password { get; set; }
public string Username { get; set; }
}
+ public sealed class OpenCodeEventSubscriberOverflowException : OpenCode.Sdk.OpenCodeException
+ {
+ public OpenCodeEventSubscriberOverflowException() { }
+ public OpenCodeEventSubscriberOverflowException(string message) { }
+ public OpenCodeEventSubscriberOverflowException(string message, System.Exception innerException) { }
+ public int Capacity { get; }
+ }
public class OpenCodeException : System.Exception
{
public OpenCodeException() { }
diff --git a/tests/OpenCode.Sdk.Tests/Transport/PipelineOwnedResourceTests.cs b/tests/OpenCode.Sdk.Tests/Transport/PipelineOwnedResourceTests.cs
new file mode 100644
index 000000000..facd6159f
--- /dev/null
+++ b/tests/OpenCode.Sdk.Tests/Transport/PipelineOwnedResourceTests.cs
@@ -0,0 +1,121 @@
+using OpenCode.Sdk.Tests.Support;
+using TUnit.Assertions.Enums;
+
+namespace OpenCode.Sdk.Tests.Transport;
+
+public sealed class PipelineOwnedResourceTests
+{
+ [Test]
+ [Arguments(0)]
+ [Arguments(1)]
+ [Arguments(2)]
+ public async Task Dispose_Should_Dispose_Owned_Resources_In_Reverse_Order_Once_Before_The_Transport(int failures)
+ {
+ using var handler = new RecordingHttpHandler();
+ using var httpClient = new HttpClient(handler);
+ using var pipeline = PipelineFactory.Create(httpClient, ownsHttpClient: true);
+ var ledger = new List();
+ var transportStates = new List();
+ var firstDisposals = 0;
+ var secondDisposals = 0;
+ var firstFailure = new InvalidOperationException("first resource");
+ var secondFailure = new InvalidOperationException("second resource");
+ using var first = new OwnedResource(() =>
+ {
+ ledger.Add("first");
+ transportStates.Add(handler.IsDisposed);
+ firstDisposals++;
+ if (firstDisposals == 1 && failures == 2)
+ {
+ throw firstFailure;
+ }
+ });
+ using var second = new OwnedResource(() =>
+ {
+ ledger.Add("second");
+ transportStates.Add(handler.IsDisposed);
+ secondDisposals++;
+ if (secondDisposals == 1 && failures != 0)
+ {
+ throw secondFailure;
+ }
+ });
+ pipeline.RegisterOwned(first);
+ pipeline.RegisterOwned(second);
+ Exception? failure = null;
+ try
+ {
+ pipeline.Dispose();
+ }
+ catch (Exception exception)
+ {
+ failure = exception;
+ }
+
+ pipeline.Dispose();
+ await Assert.That(ledger).IsEquivalentTo(["second", "first"], CollectionOrdering.Matching);
+ await Assert.That(transportStates).IsEquivalentTo([false, false], CollectionOrdering.Matching);
+ await Assert.That(handler.IsDisposed).IsTrue();
+ await Assert.That(firstDisposals).IsEqualTo(1);
+ await Assert.That(secondDisposals).IsEqualTo(1);
+ if (failures == 0)
+ {
+ await Assert.That(failure).IsNull();
+ }
+ else if (failures == 1)
+ {
+ await Assert.That(failure).IsSameReferenceAs(secondFailure);
+ }
+ else
+ {
+ await Assert.That(failure).IsSameReferenceAs(firstFailure);
+ }
+
+ using var late = new OwnedResource(static () => { });
+ _ = await Assert.That(() => pipeline.RegisterOwned(late)).Throws();
+ }
+
+ [Test]
+ public async Task Dispose_Should_Close_Registration_And_Return_Concurrent_Disposals_While_Cleanup_Is_Held()
+ {
+ using var handler = new RecordingHttpHandler();
+ using var httpClient = new HttpClient(handler);
+ using var pipeline = PipelineFactory.Create(httpClient, ownsHttpClient: true);
+ var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ using var release = new ManualResetEventSlim();
+ var count = 0;
+ using var held = new OwnedResource(() =>
+ {
+ count++;
+ _ = entered.TrySetResult();
+ if (!release.Wait(HangGuard.Bound))
+ {
+ throw new TimeoutException("The test did not release owned cleanup.");
+ }
+ });
+ pipeline.RegisterOwned(held);
+ var disposing = DedicatedThread.Run(pipeline.Dispose);
+ try
+ {
+ await entered.Task.WaitAsync(HangGuard.Bound);
+ pipeline.Dispose();
+ await Assert.That(handler.IsDisposed).IsFalse();
+ using var refused = new OwnedResource(static () => { });
+ _ = await Assert.That(() => pipeline.RegisterOwned(refused)).Throws();
+ await Assert.That(count).IsEqualTo(1);
+ }
+ finally
+ {
+ release.Set();
+ await disposing.WaitAsync(HangGuard.Bound);
+ }
+
+ await Assert.That(handler.IsDisposed).IsTrue();
+ await Assert.That(count).IsEqualTo(1);
+ }
+
+ private sealed class OwnedResource(Action dispose) : IDisposable
+ {
+ public void Dispose() => dispose();
+ }
+}
diff --git a/tests/OpenCode.Sdk.Tests/Transport/PipelineStreamTests.cs b/tests/OpenCode.Sdk.Tests/Transport/PipelineStreamTests.cs
index 594254d73..013d4f303 100644
--- a/tests/OpenCode.Sdk.Tests/Transport/PipelineStreamTests.cs
+++ b/tests/OpenCode.Sdk.Tests/Transport/PipelineStreamTests.cs
@@ -13,6 +13,14 @@ namespace OpenCode.Sdk.Tests.Transport;
public sealed class PipelineStreamTests
{
+ [Test]
+ public async Task ExecuteStreamAsync_Should_Refuse_Event_Subscribe_Without_Request_Options()
+ {
+ await Assert.That((await RefuseStreamOptionsAsync(
+ "event.subscribe", new TestStreamAdapter(), options: null)).Message)
+ .IsEqualTo("Operation 'event.subscribe' must be opened through its shared event feed.");
+ }
+
private const string OperationId = "test.operation";
private const string EventStreamMediaType = "text/event-stream";
@@ -729,8 +737,8 @@ public async Task ExecuteStreamAsync_Should_Refuse_A_Route_Without_A_Leading_Sla
}
private static async Task RefuseStreamOptionsAsync(string operationId,
- IStreamAdapter adapter, OpenCodeRequestOptions options)
- where TException : ArgumentException
+ IStreamAdapter adapter, OpenCodeRequestOptions? options)
+ where TException : Exception
where TCause : IReadOnlyList
{
using var scenario = PipelineScenario.Responding();
diff --git a/tests/OpenCode.Sdk.Tools.Tests/Generator/Binding/description-overlap.txt b/tests/OpenCode.Sdk.Tools.Tests/Generator/Binding/description-overlap.txt
index 584c8ffd1..e56f20259 100644
--- a/tests/OpenCode.Sdk.Tools.Tests/Generator/Binding/description-overlap.txt
+++ b/tests/OpenCode.Sdk.Tools.Tests/Generator/Binding/description-overlap.txt
@@ -1,2 +1,3 @@
# Type[.Member] - reason for retaining a row whose target has an upstream projected description.
SessionCreateRequest.ParentId - the curated location rule replaces upstream's linked-child reporting description
+EventSubscribeRequest.Types - the shared Events door owns local call-time selection rather than a physical Types query
diff --git a/tests/OpenCode.Sdk.Tools.Tests/Generator/Emission/HandWrittenDoorRemarksTests.cs b/tests/OpenCode.Sdk.Tools.Tests/Generator/Emission/HandWrittenDoorRemarksTests.cs
index 8665f48a1..b048bfa43 100644
--- a/tests/OpenCode.Sdk.Tools.Tests/Generator/Emission/HandWrittenDoorRemarksTests.cs
+++ b/tests/OpenCode.Sdk.Tools.Tests/Generator/Emission/HandWrittenDoorRemarksTests.cs
@@ -25,6 +25,41 @@ public sealed partial class HandWrittenDoorRemarksTests(PinnedBinding pinned)
/// The hand-written public door types (ADR-0021): every public operation method on them names its operation.
private static readonly string[] DoorTypes = ["PtyClient", "PtysClient", "PersistentPtyClient", "PersistentPtysClient", "EventsClient"];
+ [Test]
+ public async Task SubscribeAsync_Remarks_Should_Quote_The_Current_Server_Sent_Events_Canon()
+ {
+ var method = (await LoadHandWrittenMethodsAsync()).Single(static method => method.TypeName == "EventsClient" && method.Name == "SubscribeAsync");
+ var fileSystem = new RealFileSystem();
+ var path = fileSystem.Path.Combine(new RepositoryRoot(fileSystem).Locate(), "docs/architecture/client-runtime.md");
+ var canon = await fileSystem.File.ReadAllTextAsync(path, CancellationToken.None);
+ const string heading = "## Server-sent events";
+ var start = canon.IndexOf(heading, StringComparison.Ordinal);
+ await Assert.That(start).IsGreaterThanOrEqualTo(0);
+ var end = canon.IndexOf("\n## ", start + heading.Length, StringComparison.Ordinal);
+ var section = Normalize((end < 0 ? canon[start..] : canon[start..end]).Replace("`", "", StringComparison.Ordinal));
+ var excerpts = Normalize(method.PlainRemarks).Split(". ", StringSplitOptions.RemoveEmptyEntries)
+ .Where(static excerpt => !excerpt.StartsWith("Operation ", StringComparison.Ordinal)).ToArray();
+ await Assert.That(excerpts).IsNotEmpty();
+ foreach (var excerpt in excerpts)
+ {
+ await Assert.That(section).Contains(excerpt.TrimEnd('.'));
+ }
+ }
+
+ private static string Normalize(string text) => string.Join(' ', text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
+
+ [Test]
+ [Arguments("SubscribeAsync", true, 1)]
+ [Arguments("WatchConnectionAsync", false, 0)]
+ [Arguments("GetConnectionState", false, 0)]
+ public async Task Classify_Should_Treat_Only_The_Events_Subscription_As_An_Http_Operation(string name, bool operation, int remarks)
+ {
+ var method = (await LoadHandWrittenMethodsAsync()).Single(method => method.TypeName == "EventsClient" && method.Name == name);
+
+ await Assert.That(method.IsPublicOperation).IsEqualTo(operation);
+ await Assert.That(method.Remarks.Count).IsEqualTo(remarks);
+ }
+
[Test]
public async Task HandWritten_Remarks_Should_Name_A_Pinned_Operation_By_Its_Method_And_Route()
{
@@ -97,19 +132,22 @@ private static async Task> LoadHandWrittenMethodsAsync()
private sealed record OperationRemark(string Member, string OperationId, string Method, string Route);
- private sealed record HandWrittenMethod(string TypeName, string Name, bool IsPublicOperation, IReadOnlyList Remarks)
+ private sealed record HandWrittenMethod(string TypeName, string Name, bool IsPublicOperation,
+ IReadOnlyList Remarks, string PlainRemarks)
{
public static HandWrittenMethod Of(MethodDeclarationSyntax method)
{
var typeName = ((TypeDeclarationSyntax)method.Parent!).Identifier.ValueText;
var name = method.Identifier.ValueText;
- var remarkText = string.Concat(method
+ var remarkElements = method
.GetLeadingTrivia()
.Select(static trivia => trivia.GetStructure())
.OfType()
.SelectMany(static comment => comment.Content.OfType())
- .Where(static element => element.StartTag.Name.LocalName.ValueText == "remarks")
- .Select(static element => element.Content.ToString()));
+ .Where(static element => element.StartTag.Name.LocalName.ValueText == "remarks").ToArray();
+ var remarkText = string.Concat(remarkElements.Select(static element => element.Content.ToString()));
+ var plainRemarks = string.Concat(remarkElements.SelectMany(static element => element.DescendantNodes().OfType())
+ .SelectMany(static text => text.TextTokens).Select(static token => token.ValueText));
var remarks = RemarkPattern()
.Matches(remarkText)
.Select(match => new OperationRemark(
@@ -118,9 +156,15 @@ public static HandWrittenMethod Of(MethodDeclarationSyntax method)
match.Groups["method"].Value,
match.Groups["route"].Value))
.ToArray();
- var isPublicOperation = method.Modifiers.Any(SyntaxKind.PublicKeyword)
- && method.ReturnType is GenericNameSyntax { Identifier.ValueText: "Task" or "IAsyncEnumerable" };
- return new HandWrittenMethod(typeName, name, isPublicOperation, remarks);
+ var isPublicOperation = method.Modifiers.Any(SyntaxKind.PublicKeyword) && (typeName == "EventsClient"
+ ? name switch
+ {
+ "SubscribeAsync" => true,
+ "WatchConnectionAsync" or "GetConnectionState" => false,
+ _ => throw new InvalidOperationException($"Unclassified Events door member: {name}"),
+ }
+ : method.ReturnType is GenericNameSyntax { Identifier.ValueText: "Task" or "IAsyncEnumerable" });
+ return new HandWrittenMethod(typeName, name, isPublicOperation, remarks, plainRemarks);
}
}
}
diff --git a/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs b/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs
index 9b790be97..89b020de9 100644
--- a/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs
+++ b/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs
@@ -51,6 +51,15 @@ internal static class GeneratedSourceCompiler
internal static readonly (string Consumer, string RequiredEmission)[] GeneratedSurfaceConsumers =
[
("Events/EventsClient.cs", "Events/Internal/EventsRawClient.cs"),
+ ("Events/Internal/Abstractions/IEventAttemptSource.cs", "Events/Internal/EventsRawClient.cs"),
+ ("Events/Internal/EventAttemptSource.cs", "Events/Internal/EventsRawClient.cs"),
+ ("Events/Internal/EventSelection.cs", "Events/Models/EventType.cs"),
+ ("Events/Internal/EventSource.cs", "Events/Internal/EventsRawClient.cs"),
+ ("Events/Internal/EventSourceRunner.cs", "Events/Internal/EventsRawClient.cs"),
+ ("Events/Internal/EventStateWatcher.cs", "Events/Internal/EventsRawClient.cs"),
+ ("Events/Internal/EventSubscription.cs", "Events/Internal/EventsRawClient.cs"),
+ ("Events/Internal/SharedEventFeed.cs", "Events/Internal/EventsRawClient.cs"),
+ ("Events/Internal/StopWork.cs", "Events/Internal/EventsRawClient.cs"),
("Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"),
("Hosting/BackgroundService/Internal/Handoff/ServicePtyShutdown.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"),
("Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"),
diff --git a/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs b/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs
index 3dbcc435a..dba91e5b3 100644
--- a/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs
+++ b/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs
@@ -78,6 +78,8 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client)
[
"CursorSequence",
"ErrorBehavior",
+ "EventConnectionState",
+ "EventConnectionStatus",
"EventsClient",
EffectStreamTypeNamePolicy.CauseMarkerInterface,
SessionScopedEventContract.InterfaceName,
@@ -89,6 +91,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client)
"OpenCodeApiException",
"OpenCodeClientOptions",
"OpenCodeException",
+ "OpenCodeEventSubscriberOverflowException",
"OpenCodeRequestOptions",
"OpenCodeResponse",
"OpenCodeServer",
@@ -157,6 +160,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client)
public static readonly FrozenSet InternalTypeNames = FrozenSet.ToFrozenSet(
[
"ActivityStream",
+ "AfterGate",
"BatchCommandLine",
"BoundedLineBuffer",
"BoundedWait",
@@ -175,11 +179,20 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client)
"CursorPaginator",
"DeclaredHeader",
"DefaultModelWait",
+ "Delivery",
"EmptyOpenMembers",
"EncodedResponseBody",
"EndpointPolicy",
"EnsureRequest",
"ErrorBehaviorPolicy",
+ "EventAttemptSource",
+ "EventFeedBounds",
+ "EventPendingMove",
+ "EventSelection",
+ "EventSource",
+ "EventSourceRunner",
+ "EventStateWatcher",
+ "EventSubscription",
"ExecutableResolver",
"ExecutableSearchEnvironment",
"ExitWaitKernel",
@@ -191,6 +204,8 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client)
"IChildExitStatus",
"ICursorPageAdapter",
"IEventStreamFramer",
+ "IEventAttemptSource",
+ "IEventFeedGateProbe",
"IExitWaitKernel",
"IFileRenameKernel",
"IJobObjects",
@@ -232,6 +247,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client)
"LoopbackTransport",
"MockSeam",
"NetworkTimeouts",
+ "NoOpEventFeedGateProbe",
"NulText",
"OpenCodeErrorReader",
"OpenCodeHttpMethod",
@@ -278,7 +294,6 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client)
"PtyUpgradeFailurePolicy",
"QueryStringBuilder",
"ReadinessOutcome",
- "ReconnectingEventStream",
"RecordPrinter",
"RequestDecorationPolicy",
"ResolvedExecutable",
@@ -329,15 +344,18 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client)
"ServiceTiming",
"ServiceVersionPolicy",
"SignalDelivery",
+ "SharedEventFeed",
"SlopwatchSuppressAttribute",
"StatusVerdict",
"StatusVerdictFailures",
+ "StopWork",
"StreamAttempt",
"StreamPlane",
"StreamReconnect",
"StrictJson",
"StructuralUnionClaim",
"StructuralUnionPrinter",
+ "SubscriptionEnd",
"TaskkillTreeKill",
"TerminalConnectionOutcome",
"TerminalReceivePump",
diff --git a/tools/curation.json b/tools/curation.json
index 9dc877aaa..4571d8bdd 100644
--- a/tools/curation.json
+++ b/tools/curation.json
@@ -1373,6 +1373,19 @@
}
]
},
+ {
+ "type": "EventSubscribeRequest",
+ "member": "Types",
+ "summary": "Locally select exact event types, captured at the call; null or empty selects all events and server.connected always passes.",
+ "remarks": "The shared source sends no types query and decodes the whole bus once.",
+ "reason": "Describe the hand-written Events door's local selection instead of implying a per-subscription wire query.",
+ "sources": [
+ {
+ "canon": "docs/architecture/client-runtime.md#server-sent-events",
+ "excerpt": "EventSubscribeRequest.Types is local selection captured and validated at the call."
+ }
+ ]
+ },
{
"type": "OpenCodeClient",
"member": "Forms",
diff --git a/tools/jscpd/tests.baseline.json b/tools/jscpd/tests.baseline.json
index a766be765..b09d12f29 100644
--- a/tools/jscpd/tests.baseline.json
+++ b/tools/jscpd/tests.baseline.json
@@ -86,14 +86,12 @@
"2ebc929ec99531d7": 1,
"2ef093de84b22985": 1,
"2fa52323893c6990": 1,
- "2fce9f9be54d9810": 1,
"30024875e03c93af": 1,
"303aee7f7b8af88f": 1,
"3081885a80a22be3": 1,
"3095017bef402cf6": 1,
"30a25f5818399fa9": 1,
"30c6457c90ba767e": 1,
- "31079b601cabad85": 1,
"31d2f6a6376bb9aa": 1,
"32e3d4ff25171289": 1,
"34812987b8a4a722": 1,
@@ -106,7 +104,6 @@
"3aa741762878529d": 1,
"3b4ee00b9fd149f5": 1,
"3c605c52befef8a8": 1,
- "3c708e3adddb4f26": 1,
"3dec5ec598cf3e79": 1,
"3e0f7db3f45db7c6": 1,
"3ea15c33ef67187a": 1,
@@ -160,7 +157,6 @@
"5ae402699aab9b4f": 1,
"5b5f89cf29e631cb": 1,
"5bb29ca2159fbdc5": 1,
- "5bcc598790149aed": 1,
"5be5c05917ff8d7e": 1,
"5c10d3e20ff8a618": 1,
"5d5ef92942ea8a4b": 1,
@@ -258,7 +254,6 @@
"8990b0dcf557805f": 1,
"89b40759e47ca8db": 1,
"8a46989d4cc28dc2": 1,
- "8a7e47959ada7043": 1,
"8d130dcf8156d446": 1,
"8dbef398f2f6ca1a": 1,
"8dc9324256cda03a": 1,
@@ -426,7 +421,6 @@
"f05e80092b0c0382": 1,
"f102cbf1fab8a3d9": 1,
"f1452c6004270377": 1,
- "f1812b941eb02542": 1,
"f1e800e542db712a": 1,
"f1f7493a31b45480": 1,
"f23a5dc8edef52e2": 1,