diff --git a/CHANGELOG.md b/CHANGELOG.md index 303bd94d..913af32a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ The next SDK version is **2.0.0**, on the same opencode **2.3.0** pin already re - `OpenCodeClientOptions.HttpHandler` accepts a caller-owned HTTP transport for requests, event streams, and terminal upgrades on modern targets. - `OpenCodeClientOptions.Headers` and `OpenCodeRequestOptions.Headers` set client-wide and per-call HTTP headers, with per-call values winning. +- `OpenCodeServer.ResolveAsync` selects an explicit endpoint, an owned standalone server or the shared service with the CLI's precedence, including the saved `disabled` flag. Connections expose resolve-time `ServerVersion`; explicit mismatches can invoke `OnServerVersionMismatch`. Managed `ServiceOperations` reconnect or restart with a best-effort persistent-terminal handoff using the resolve-time snapshot. - `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`). diff --git a/GLOSSARY.md b/GLOSSARY.md index 0ca92461..734ce436 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -249,6 +249,14 @@ was typed at. #### Connection modes +**Explicit server**: +A server addressed by the caller's Endpoint and optional Password, without ownership of its process. + +**Server connection**: +The result of `OpenCodeServer.ResolveAsync`: the selected connection mode, endpoint, credential and +resolve-time version, composing an owned Standalone server or a shared Background service handle +where applicable. Only a Background service connection exposes reconnect and restart operations. + **Launcher**: The in-core component that starts, monitors and stops a local `opencode serve` process for the Standalone server mode. diff --git a/README.md b/README.md index 6038bb66..a69f16a4 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,7 @@ Pick the connection mode that matches where your server lives: | You want… | Use | Who stops the server | |---|---|---| +| The CLI's explicit / standalone / managed precedence | `OpenCodeServer.ResolveAsync()` | Disposal ends only an owned standalone server | | A private server for this app only | `OpenCodeServer.StartAsync()` | The SDK, when you dispose it | | A server you already run | `new OpenCodeClient(options)` | You | | The background service the CLI shares with other clients | `OpenCodeServer.DiscoverAsync()` or `EnsureAsync()` | Nobody, unless you call `StopAsync()` | diff --git a/docs/architecture/client-runtime.md b/docs/architecture/client-runtime.md index 0c080a2b..76ab5625 100644 --- a/docs/architecture/client-runtime.md +++ b/docs/architecture/client-runtime.md @@ -91,8 +91,9 @@ upstream's behaviour. Each one is listed, with its reason, in the section it con [Error channels](#error-channels). - Client options are snapshotted at construction. Explicit-endpoint construction reads no process environment variable; consumers resolve their own configuration. `OpenCodeServer.DiscoverAsync`, - `OpenCodeServer.FindIncumbentAsync`, `OpenCodeServer.ShutdownPersistentPtyAsync` and - `OpenCodeServer.StopAsync` are the doors that read the environment, and they read exactly + `OpenCodeServer.FindIncumbentAsync`, `OpenCodeServer.ShutdownPersistentPtyAsync`, + `OpenCodeServer.StopAsync`, `OpenCodeServer.EnsureAsync` and the non-explicit paths of + `OpenCodeServer.ResolveAsync` are the doors that read the environment, and they read exactly `XDG_STATE_HOME`, `XDG_CONFIG_HOME`, `OPENCODE_CONFIG_DIR`, and the user profile (`USERPROFILE` on Windows, `HOME` elsewhere), because those roots locate the registration file. For discovery that file is the mode's complete endpoint-and-credential contract; `FindIncumbentAsync` takes its @@ -430,8 +431,9 @@ resolves the message's network window from those carried traits. - Caller cancellation of a public asynchronous operation or enumeration throws `OperationCanceledException` carrying the caller's token, not an SDK-owned linked token. The rule applies to HTTP operations, SSE, cursor traversal, both terminal families, and `StartAsync`, - `DiscoverAsync`, `FindIncumbentAsync`, `EnsureAsync`, `ShutdownPersistentPtyAsync`, and - `StopAsync`. This identity guarantee applies when one caller token is supplied, including the + `DiscoverAsync`, `FindIncumbentAsync`, `EnsureAsync`, `ShutdownPersistentPtyAsync`, `StopAsync`, + `ResolveAsync`, `ServiceOperations.ReconnectAsync` and `ServiceOperations.RestartAsync`. + This identity guarantee applies when one caller token is supplied, including the same token supplied at both enumeration entry points; two distinct cancellable entry tokens are both observed but have no token-identity guarantee. - Disposing the root client interrupts its in-flight HTTP operations and SSE streams and reports @@ -1108,16 +1110,31 @@ user data, state, cache, and config roots as any other opencode process on the m caller redirects `XDG_DATA_HOME`, `XDG_STATE_HOME`, `XDG_CACHE_HOME`, and `XDG_CONFIG_HOME` through `Environment` — observed on Windows as well as on Unix. -**Explicit endpoint** (CLI `--server` parity; upstream builds a plain client plus a 5-second-bounded -status check and a version warning, `server-connection.ts:24-39`) → plain `OpenCodeClient` -construction. There is no dedicated SDK verb or member for this door; the validation recipe -composes two existing pieces: construct the client against the known endpoint, call -`Server.GetInfoAsync` under a caller-owned `CancellationTokenSource(TimeSpan.FromSeconds(5))` — a -total deadline, as upstream's `AbortSignal.timeout(5_000)` is, where `NetworkTimeout` bounds only -the time between progress — and compare the returned `ServerInfo.Version` against the caller's own -expectation. The SDK carries no version comparand of its own — the accepted snapshot -(`spec/SNAPSHOT.md`) is a protocol identity, not a runtime version — so a dedicated helper would -need a comparand the SDK does not have. +**Explicit endpoint** (CLI `--server` parity, `server-connection.ts:34-50`) → +`OpenCodeServer.ResolveAsync` with `Endpoint`. It probes `Server.GetInfoAsync` under a five-second +total deadline on the probe pipeline's clock, not the inactivity-only `NetworkTimeout`. A tagged +unauthorized response says either “requires a password; set OpenCodeServerResolveOptions.Password” +or “rejected the password”; transport failures and the deadline say “Could not reach server”, while +a protocol-status refusal, API error or malformed success body says “did not provide a compatible V2 health response”. +Those failures are `OpenCodeServerException` with the original exception inside; caller cancellation +propagates unwrapped with the caller's token and wins over the deadline. The explicit server's +version is compared ordinally with the SDK's internal pinned-release comparand, equal to the +receipt's release tag without `v`. A mismatch invokes the synchronous `OnServerVersionMismatch` +callback once and resolution continues; a null callback is silent and a callback exception +propagates. `ServerVersion` carries the probe's version. Unused `Service`, `Launch` and `Autostart` +options are neither read nor validated. Plain `OpenCodeClient` construction remains the no-probe form. + +**Resolving a connection** (`ServerConnection.resolve`) → `OpenCodeServer.ResolveAsync`: explicit +Endpoint first; otherwise validate and copy Service, then use a standalone server when `Standalone` +is true or the channel config's `disabled` flag is true; otherwise locate the service and capture +its saved environment overlay once. `Endpoint` plus `Standalone`, and a non-null `Password` without +`Endpoint`, are refused before I/O. `Launch` is snapshotted only if Start is reached. With +`Autostart = false`, discover any version and start standalone on a miss; otherwise ensure with the +caller's policy, version and OnStart. The pin is never a managed version default. The returned +`OpenCodeServerConnection` composes the process-backed handle (ADR-0024), rather than replacing it: +disposal ends only its owned standalone server, and never stops an explicit server or a shared +service. `ServerVersion` is the registration's version in Service mode, and null in Standalone mode, +where the readiness line supplies no version. Only Service mode exposes `ServiceOperations`. **Background service** (`Service.discover/ensure/stop`, public export `@opencode/client/service`) → the registration-file mode. The first-party CLI's `opencode serve --service` publishes `url`, @@ -1138,12 +1155,12 @@ is and leave the rewrite to the daemon's next read, which reads the same `env`. donor or repairing a legacy `remote` in place, and write it (`GetOrCreatePasswordAsync` stores a password). Remote access is set only through the CLI (`opencode service set remote`); the SDK's config repair can generate a route, and the service's remote URL reaches callers in `ServerInfo.Urls` -while its tunnel is attached. The config's `disabled` key is read only by CLI commands: the connection-mode -selector (`resolve` starts a standalone server instead of reaching the service when it is true) and -the pairing command's guard (`opencode pair` needs the service); the pinned client's -`Service.discover`, `ensure`, and `stop` do not read it, and neither do `DiscoverAsync`, -`FindIncumbentAsync`, `EnsureAsync`, and `StopAsync` — a caller that honors a disabled service -chooses `StartAsync`, as `resolve` does. +while its tunnel is attached. The CLI's pairing command also reads the `disabled` key +(`opencode pair` needs the service). `ResolveAsync` reads the config's `disabled` key after the config migration and +before the registration migration, as `resolve` does. The pinned client's `Service.discover`, +`ensure` and `stop` do not read it; neither do `DiscoverAsync`, `FindIncumbentAsync`, `EnsureAsync`, `StopAsync` or +`ShutdownPersistentPtyAsync`. A direct registration path has no config file and is never disabled. +Resolution reads the service configuration through the config store, as the CLI does; a refused document reads as absent, as for Discovery, Ensure and Stop. The registration and service-config files are read the way libuv opens files, sharing read, write, and delete, so a poll never makes the daemon's remove-on-exit fail on Windows, and a UTF-8 byte-order mark is skipped as the CLI's decoder skips it. A daemon bound to every interface @@ -1318,11 +1335,15 @@ when the POSIX-semantics rename proves unsound on a volume the SDK supports. The daemon side of the lifecycle is the spawned CLI's, not the SDK's: the incumbent check, the exit-0 loser on a port another daemon holds, the `chdir` into the user home, and the registration write all run inside `opencode serve --service` (`server-process.ts`), and the election reads a -loser's exit 0 the way upstream's does. The CLI's `reconnect` is `EnsureAsync`. `StopAsync` then -`EnsureAsync` is the CLI's `service restart`, where persistent terminals end. With -`Pty = OpenCodeServerStopPtyMode.Handoff`, the same pair is the managed -connection's restart: `EnsureAsync` adopts the published ticket to keep the terminals, best-effort -and only when preparation and adoption precede its expiry. +loser's exit 0 the way upstream's does. `ServiceOperations.ReconnectAsync` and `RestartAsync` are +the managed connection's `reconnect` and `restart`: paths and the overlay (including captured +absence) were read once at resolve, so neither operation locates, migrates or reads config again. +Both ensure with Ignore and without OnStart; restart first stops with +`Pty = OpenCodeServerStopPtyMode.Handoff`, then ensures only if Stop succeeded. Ticket preparation +and adoption before expiry preserve terminals best-effort. Both return a new non-owning handle; +the connection's Endpoint, Server and ServerVersion still describe the resolve. Plain `StopAsync` +then `EnsureAsync` remains the CLI's `service restart`, where persistent terminals end. Unlike the +resolver snapshot, public Ensure reads the config anew at every spawn. Each background-service door chooses `TimeProvider.System` once at its composition root: Discover supplies its probe, from one factory that `ShutdownPersistentPtyAsync` and @@ -1335,12 +1356,33 @@ deadline comparisons and spawn stamps read UTC, and handoff expiry reads UTC epo neither is a monotonic elapsed-time policy. Each request deadline arms after probe headers, after ticket pipeline construction, or at entry to the separate shutdown fallback, respectively. +Resolve reuses the launcher's clock for config repair; the explicit bound uses the probe pipeline's clock; located discovery +shares Discover's factory, and located Stop and Ensure share their respective doors' roots. + `BannedSymbols.Clock.txt` bans the system clock in shipped src outside the five counted composition roots: launcher, client pipeline, Discover, Stop and Ensure. Where the SDK deliberately differs from the pinned chain, it differs here, each for a recorded reason (ADR-0031): +- **CLI flags become options.** A library has no command line; the options preserve the same + precedence. Reversal: upstream exposes resolution in a client package with different inputs. +- **Explicit Password is an option, not an environment read.** Its first unauthorized message + names `OpenCodeServerResolveOptions.Password`, not upstream's `OPENCODE_PASSWORD`, because a + remedy naming an unread variable would mislead. Reversal: the maintainer reverses the no-env-var + rule, or upstream's client package reads those variables for an explicit endpoint. +- **Version warnings use a silent-by-default callback, not stderr.** A library owns no console; + the callback follows OnStart's shape, and ServerVersion exposes the same fact. Reversal: the SDK + adopts a general diagnostics channel. +- **The explicit comparand is the pinned release, not a compiled CLI identity.** The SDK has no + such identity. Reversal: it ships or pins the CLI binary it starts, or upstream publishes a + version the SDK can carry. +- **Managed Replace/Error require the caller's ExpectedVersion.** The pin is never a default: + the SDK spawns PATH `opencode`, not itself. Reversal: the same binary/version condition as the + explicit-comparand divergence. +- **Probe failures use OpenCodeServerException with InnerException.** This is the idiomatic .NET + form of upstream's `Error(message, { cause })`. Reversal: upstream exports typed connect errors. + - **Stricter readers than upstream's `JSON.parse`.** The registration and service-config readers refuse a repeated member. The registration reader also refuses a pid that is not a positive 32-bit integer and a URL that is not absolute HTTP or HTTPS. A refused document reads as absent. diff --git a/docs/guide/connection-modes.md b/docs/guide/connection-modes.md index a260776b..1206ab88 100644 --- a/docs/guide/connection-modes.md +++ b/docs/guide/connection-modes.md @@ -7,6 +7,7 @@ There are three ways to get a client bound to a running opencode server: **let t for every client on the machine**. Dependency injection is not a fourth way in — it is how you register any of them with a container. +- [🧭 Resolving a connection as the CLI does](#-resolving-a-connection-as-the-cli-does) - [🚀 The SDK starts the server](#-the-sdk-starts-the-server) - [🔗 A server you already run](#-a-server-you-already-run) - [🛰️ Discovering the background service](#️-discovering-the-background-service) @@ -17,6 +18,138 @@ register any of them with a container. - [🔌 Supplying a handler](#-supplying-a-handler) - [🧩 Registering with dependency injection](#-registering-with-dependency-injection) +## 🧭 Resolving a connection as the CLI does + +Use one door when you want the CLI's connection selection rather than a specific lifecycle door: + +```csharp +await using var connection = await OpenCodeServer.ResolveAsync(); +using var client = connection.CreateClient(); +var info = await client.Server.GetInfoAsync(); +Console.WriteLine($"{connection.Mode}: opencode {info.ServerInfo.Version}"); +``` + +| In precedence order | Result | +|---|---| +| `Endpoint` is set | Probe the explicit server; ignore `Service`, `Launch` and `Autostart`, including their validation | +| `Standalone = true` | Start privately with `Launch`, without reading service config | +| The selected channel config has `disabled: true` | Start privately with `Launch` | +| `Autostart = false` | Discover any ready compatible version; start privately on a miss | +| Otherwise | Ensure the selected managed service with `Service` options | + +`Endpoint` with `Standalone`, and a non-null `Password` without `Endpoint`, are refused with +`ArgumentException`. Managed options are validated before managed I/O; `Replace` and `Error` still +need your `ExpectedVersion`. The SDK's pinned release is never a managed default. +Direct registration-file selection has no config file and cannot be disabled. + +The connection's `Mode` makes disposal explicit: **Standalone** owns its `Server` and ends it on +disposal; **Service** carries a shared handle whose disposal does not stop it; **Explicit** has +no `Server` handle and nothing to release. `CreateClient` returns a caller-owned client in every +mode. Its configuration delegate can set behavior, not Endpoint, Username or Password. + +`ServerVersion` describes the resolve: the probe's version in Explicit mode, the registration's +version in Service mode (possibly null), and null in Standalone mode, whose readiness line carries +no version. In explicit mode, `OnServerVersionMismatch` optionally receives Endpoint, ServerVersion +and ClientVersion (the pinned release). Comparison is ordinal; the synchronous callback fires once, +resolution continues after it, and a null callback is silent. A callback exception propagates. + +Only Service mode has `ServiceOperations`. `ReconnectAsync` ensures with Ignore and no OnStart; +`RestartAsync` first stops with best-effort persistent-terminal handoff, then reconnects. Both reuse +the paths, copied command/environment and saved overlay captured at resolve, including an absent +overlay. Neither re-locates, migrates or re-reads config. They return new non-owning handles without +changing the connection's Endpoint, Server or ServerVersion. + +Explicit probes have a five-second **total** deadline. A tagged authentication refusal reports a +missing Password option or a rejected password; transport and deadline failures say “Could not +reach”; protocol-status refusals, malformed bodies and other API errors say “did not provide a compatible V2 health response”. +These are `OpenCodeServerException` with the original `InnerException`. Your cancellation is an +unwrapped `OperationCanceledException`. Standalone and managed failures retain their doors' +[failure contracts](errors-and-responses.md#-when-a-local-server-door-fails). + +### Re-resolving beside an active event subscription + +The application owns re-resolution; it is one of the facilities deliberately omitted from the +shared-feed contract ([ADR-0041](../adr/0041-one-shared-event-feed-per-client.md)). A +`WatchConnectionAsync` watcher opens no source and keeps none alive: hold an active +`SubscribeAsync` enumeration beside it. States coalesce, so react to the latest **yielded** +`Reconnecting` state, not an assumed log of every transition. Reconnect, cancel and dispose the old +subscription and watcher, dispose the old client, then create a new client from the returned handle +and attach **both** enumerations again. This example takes the application's cancellation token: + +```csharp +static async Task RunManagedEventsAsync(CancellationToken cancellationToken) +{ + await using var connection = await OpenCodeServer.ResolveAsync(cancellationToken: cancellationToken); + var operations = connection.ServiceOperations + ?? throw new InvalidOperationException("This recipe requires a managed service connection."); + var client = connection.CreateClient(); + try + { + while (!cancellationToken.IsCancellationRequested) + { + OpenCodeServer? replacement = null; + using (var cycle = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + { + await using var events = client.Events.SubscribeAsync(cancellationToken: cycle.Token) + .GetAsyncEnumerator(); + await using var states = client.Events.WatchConnectionAsync(cycle.Token).GetAsyncEnumerator(); + var eventMove = events.MoveNextAsync().AsTask(); // Starts and keeps an active source. + var stateMove = states.MoveNextAsync().AsTask(); + try + { + while (true) + { + var completed = await Task.WhenAny(stateMove, eventMove); + if (completed == stateMove) + { + if (!await stateMove) + break; + if (states.Current.Status == EventConnectionStatus.Reconnecting) + { + replacement = await operations.ReconnectAsync(cancellationToken); + break; + } + stateMove = states.MoveNextAsync().AsTask(); + } + else + { + if (!await eventMove) + break; + Console.WriteLine(events.Current.Type); + eventMove = events.MoveNextAsync().AsTask(); + } + } + } + finally + { + cycle.Cancel(); + try + { + await Task.WhenAll(eventMove, stateMove); + } + catch (OperationCanceledException) when (cycle.IsCancellationRequested) + { + // Observe the cancelled pending moves before disposing their enumerators. + } + } + } + client.Dispose(); + if (replacement is null) + return; + await using (replacement) + client = replacement.CreateClient(); + } + } + finally + { + client.Dispose(); + } +} +``` + +Replacing the client also replaces its source and connection-state watch. It is not a history +replay or a transactional resync: reconcile any event gap in your application's projections. + ## 🚀 The SDK starts the server `OpenCodeServer.StartAsync()` launches a private `opencode serve` child, waits for it to report @@ -264,29 +397,28 @@ See it running: [Worker](../../playground/worker/README.md) and ## 🔗 A server you already run -If you already know an endpoint, construct the client directly. There is no separate verb for this -door: the endpoint and the credential *are* the connection. +If you already know an endpoint, use the resolver for its bounded info probe and optional version +notification: ```csharp var endpoint = new Uri("http://127.0.0.1:4096"); -using var client = new OpenCodeClient(new OpenCodeClientOptions +await using var connection = await OpenCodeServer.ResolveAsync(new OpenCodeServerResolveOptions { Endpoint = endpoint, Password = Environment.GetEnvironmentVariable("OPENCODE_PASSWORD"), }); -using var probe = new CancellationTokenSource(TimeSpan.FromSeconds(5)); -var info = await client.Server.GetInfoAsync(cancellationToken: probe.Token); +using var client = connection.CreateClient(); +var info = await client.Server.GetInfoAsync(); Console.WriteLine($"opencode {info.ServerInfo.Version} (pid {info.ServerInfo.Pid})"); ``` -That bounded info call is the whole validation recipe for *reaching* the server, and it is -deliberately yours to write: the SDK carries no version comparand of its own, and its `NetworkTimeout` -bounds a call that stops making progress (no response headers, or no new body bytes), not the whole -call, so a `CancellationTokenSource` is the honest deadline and your own expectation is the honest -version check. It is liveness only — a server answering status can still have an empty model catalog +The resolver compares the explicit version with the pinned release; its callback is silent by +default. Plain `new OpenCodeClient(new OpenCodeClientOptions { Endpoint = endpoint })` remains the +no-probe form when you do not want validation. `NetworkTimeout` is an inactivity window, not the +resolver's total probe deadline. The probe establishes liveness only — a server answering status can still have an empty model catalog for a second or two while its plugins activate, which [choosing a model](getting-started.md#choosing-a-model) covers. @@ -303,7 +435,8 @@ working. The client never reads either one, or any other environment variable, f in the snippet above is your application's choice; a configuration section or a secret store works exactly as well. The canonical [construction contract](../architecture/client-runtime.md#construction-and-transport-ownership) -names the background-service doors that read the environment and the path variables they use. +names the background-service doors, including Ensure and the resolver's non-explicit paths, that +read path variables, never a credential variable. ### An app-owned server on a fixed endpoint @@ -633,8 +766,9 @@ shared release registration. | `InstalledVersion` | The migration comparand, as for discovery. A stop never filters by version. | | `Pty` | Governs persistent terminals (`OpenCodeClient.PersistentPtys`) only; ordinary terminals (`OpenCodeClient.Ptys`) end with the service either way. Null or `OpenCodeServerStopPtyMode.Clear` removes any handoff ticket; persistent terminals end with the service. `Handoff` attempts a best-effort handoff for the next service. | -To restart as the managed connection does and attempt to keep persistent terminals, stop with -`Handoff`, then ensure with the same registration selection (the same channel or direct path). +For a resolved managed connection, call `connection.ServiceOperations.RestartAsync()` to attempt +to keep persistent terminals. The plain-door equivalent is to stop with `Handoff`, then ensure with +the same registration selection (the same channel or direct path). Preservation is best-effort: the ticket must be prepared and adopted by the next service before it expires. @@ -685,6 +819,8 @@ It needs the [opt-in](experimental.md#opencode002) (`OPENCODE002`), as the persi `OpenCodeServer.EnsureAsync` is what the CLI does before it connects: reuse the registered service when one is ready, and start one when nothing usable is registered. It is the same election every opencode client runs, so ten callers starting at once end up sharing one daemon. +For the CLI's complete mode selection, including the saved `disabled` flag and standalone fallback, +use [ResolveAsync](#-resolving-a-connection-as-the-cli-does). ```csharp await using var server = await OpenCodeServer.EnsureAsync(); diff --git a/docs/guide/errors-and-responses.md b/docs/guide/errors-and-responses.md index 6bfd9ddc..f09cc58a 100644 --- a/docs/guide/errors-and-responses.md +++ b/docs/guide/errors-and-responses.md @@ -1,6 +1,6 @@ # 🧱 Errors and responses -Date: 2026-11-15 +Date: 2026-11-16 Every one-shot call of a client family answers with a **response envelope** that carries the same four members no matter which operation produced it, and every failure is either a typed API error you can branch on @@ -63,7 +63,7 @@ OpenCodeException │ └── OpenCodeRpcException a typed plugin RPC call's failure (adds ErrorType and the error's data) ├── OpenCodeTransportException the call never produced a usable response │ └── OpenCodeStreamFailureException a stream ended with a declared failure frame -└── OpenCodeServerException a local-server door failed: a start, discovery with no home to search, or a stop that could not end the process +└── OpenCodeServerException a local-server door failed, or an explicit server the resolver could not reach, authenticate with, or read ``` ## 🤝 Ask for the failure as data instead @@ -315,7 +315,7 @@ Terminal sessions own their connections separately. See the canonical ## 🚀 When a local-server door fails The local-server doors — `OpenCodeServer.StartAsync`, `OpenCodeServer.DiscoverAsync`, -`OpenCodeServer.FindIncumbentAsync`, `OpenCodeServer.ShutdownPersistentPtyAsync`, +`OpenCodeServer.FindIncumbentAsync`, `OpenCodeServer.ResolveAsync`, `OpenCodeServer.ShutdownPersistentPtyAsync`, `OpenCodeServer.StopAsync`, and `OpenCodeServer.EnsureAsync` — use `OpenCodeServerException` for their local lifecycle failures. Discovery uses it for exactly one cause: an XDG variable was unset and no user home directory @@ -342,6 +342,14 @@ nothing and completes, and a failed shutdown request throws `OpenCodeApiExceptio [connection guide](connection-modes.md#️-discovering-the-background-service) covers discovery, the registered owner's state, stop, the persistent-terminal shutdown, and ensure. +`ResolveAsync` also reports an explicit server it could not reach, authenticate with or read as +`OpenCodeServerException`, retaining the original probe exception in `InnerException`. A tagged +unauthorized response names the missing Password option or reports a rejected password; the +five-second total probe bound is a “Could not reach” failure; a protocol-status refusal, malformed body or other API error +is an incompatible V2 health response. Caller cancellation remains `OperationCanceledException` +with the caller's token, never a wrapped server failure. Managed and standalone paths retain their +underlying doors' failure contracts. See [resolving a connection](connection-modes.md#-resolving-a-connection-as-the-cli-does). + The launcher has more to say, because a child process ran: ```csharp diff --git a/spec/source-watch.json b/spec/source-watch.json index 6af59b24..2976cffa 100644 --- a/spec/source-watch.json +++ b/spec/source-watch.json @@ -975,7 +975,7 @@ "behaviors": [ { "owner": "opencode-sdk-dotnet", - "behavior": "resolve routes the default CLI connection to Standalone.start when --standalone is given as the command\u0027s argument or the global flag (--server likewise) or the service config\u0027s disabled is true, before any managed-service path; otherwise it goes through ServiceConfig.options, which performs legacy registration migration before discovery or ensure and enables the version gate only when mismatch is not ignore; with autostart false it only discovers a running service, with no version filter, and falls back to Standalone.start when none answers. An explicit --server connection uses server.info with a five-second bound and warns on a version mismatch. shutdownPersistentPty discovers with no version filter and, when a service answers, calls persistentPty.shutdown with no request bound; the managed restart stops with a handoff and ensures again.", + "behavior": "resolve gives explicit --server precedence and probes server.info under a five-second total bound, warning and continuing on an ordinal version mismatch. Standalone or a strictly true migrated config disabled flag starts privately before managed processing. Otherwise ServiceConfig.options locates and migrates once and captures env once, excluding XDG_STATE_HOME; managed reconnect and handoff-then-ensure restart reuse those options without onStart, a version filter, migration or config reads. With autostart false, discover accepts any version and starts standalone on a miss. The SDK projects flags to ResolveAsync options, explicit warnings to a silent-by-default callback and ServerVersion, and keeps the pinned release comparand out of managed version defaults. shutdownPersistentPty discovers with no version filter and calls persistentPty.shutdown with no request bound.", "anchor": { "type": "contains", "text": "ServiceConfig.options({ checkVersion: mismatch !== \u0022ignore\u0022 })" @@ -989,7 +989,7 @@ "behaviors": [ { "owner": "opencode-sdk-dotnet", - "behavior": "The CLI reads the server password from OPENCODE_PASSWORD and falls back to the legacy OPENCODE_SERVER_PASSWORD; the session environment it hands on omits both.", + "behavior": "The CLI reads the server password from OPENCODE_PASSWORD and falls back to the legacy OPENCODE_SERVER_PASSWORD; the session environment it hands on omits both. The SDK explicit resolver instead takes Password as an option and reads neither variable, and its missing-password remedy names that option.", "anchor": { "type": "contains", "text": "Config.orElse(() =\u003E Config.Redacted(\u0022OPENCODE_SERVER_PASSWORD\u0022))" diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigReadResult.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigReadResult.cs new file mode 100644 index 00000000..6ba2c92e --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigReadResult.cs @@ -0,0 +1,10 @@ +namespace OpenCode.Sdk.Internal; + +/// A decoded document, a refused path, or absence when both are null. +/// The readable, possibly repaired configuration. +/// The current or donor path the strict reader cannot decode but the CLI may read. +internal sealed record ServiceConfigReadResult(ServiceConfigDocument? Document, string? RefusedPath) +{ + /// No configuration readable by the CLI is available. + internal static ServiceConfigReadResult Absent { get; } = new(null, null); +} diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigStore.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigStore.cs index 544ee21d..a07d8577 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigStore.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigStore.cs @@ -20,29 +20,42 @@ internal sealed class ServiceConfigStore( /// The caller's token, forwarded unchanged to every read. /// The decoded or repaired document, or empty when the CLI has no readable config. public async Task ReadForWriteAsync(ServiceSelection selection, CancellationToken cancellationToken) + { + var result = await ReadAsync(selection, cancellationToken).ConfigureAwait(false); + return result.RefusedPath is { } path ? throw Refusal(path) : result.Document ?? new ServiceConfigDocument(); + } + + /// Reads, migrates and repairs, distinguishing absence from a strict-reader refusal. + /// The entry-time validated selection. + /// The caller's token, forwarded unchanged to every read. + /// The document, a refused path, or absence when the CLI has no readable config. + internal async Task ReadAsync(ServiceSelection selection, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var paths = ResolvePaths(selection); - // Config operations never select direct-file mode, so they always have a config path. - var configFile = paths.ConfigFile!; + if (paths.ConfigFile is not { } configFile) + { + return ServiceConfigReadResult.Absent; + } + var bytes = await fileSystem.TryReadAllBytesAsync(configFile, cancellationToken).ConfigureAwait(false); if (bytes is null) { if (fileSystem.Exists(configFile) || paths.LegacyConfigFile is not { } donor) { - return new ServiceConfigDocument(); + return ServiceConfigReadResult.Absent; } var donorBytes = await fileSystem.TryReadAllBytesAsync(donor, cancellationToken).ConfigureAwait(false); if (donorBytes is null) { - return new ServiceConfigDocument(); + return ServiceConfigReadResult.Absent; } var decodedBytes = ServiceConfigReader.DecodeCliDonor(donorBytes); if (decodedBytes is null) { - return new ServiceConfigDocument(); + return ServiceConfigReadResult.Absent; } var donorDocument = ServiceConfigReader.TryReadDocument(decodedBytes); @@ -50,10 +63,10 @@ public async Task ReadForWriteAsync(ServiceSelection sele { if (!ServiceConfigReader.IsProvenUnreadableByCliAsCurrent(decodedBytes)) { - throw Refusal(donor); + return new ServiceConfigReadResult(Document: null, RefusedPath: donor); } - return new ServiceConfigDocument(); + return ServiceConfigReadResult.Absent; } await new ServiceMigration(fileSystem).ApplyConfigAsync(configFile, decodedBytes, cancellationToken).ConfigureAwait(false); @@ -62,13 +75,14 @@ public async Task ReadForWriteAsync(ServiceSelection sele if (bytes is null) { - return new ServiceConfigDocument(); + return ServiceConfigReadResult.Absent; } var document = ServiceConfigReader.TryReadDocument(bytes); if (document is null) { - return ServiceConfigReader.IsProvenUnreadableByCli(bytes) ? new ServiceConfigDocument() : throw Refusal(configFile); + return ServiceConfigReader.IsProvenUnreadableByCli(bytes) + ? ServiceConfigReadResult.Absent : new ServiceConfigReadResult(Document: null, RefusedPath: configFile); } if (document.LegacyRemote is { } enabled) @@ -77,7 +91,7 @@ public async Task ReadForWriteAsync(ServiceSelection sele await WriteAsync(paths, document, cancellationToken).ConfigureAwait(false); } - return document; + return new ServiceConfigReadResult(document, RefusedPath: null); } /// Publishes the CLI's written bytes through its overwriting PID temporary file and bounded rename retry. diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceConfigEnvironment.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceConfigEnvironment.cs new file mode 100644 index 00000000..0d20527f --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceConfigEnvironment.cs @@ -0,0 +1,5 @@ +namespace OpenCode.Sdk.Internal; + +/// The saved environment overlay; null entries mean the read captured no usable config. +/// The saved map without XDG_STATE_HOME, or null. +internal sealed record ServiceConfigEnvironment(IReadOnlyDictionary? Entries); diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceConfigEnvironmentReader.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceConfigEnvironmentReader.cs new file mode 100644 index 00000000..c120673d --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceConfigEnvironmentReader.cs @@ -0,0 +1,23 @@ +namespace OpenCode.Sdk.Internal; + +/// Reads the saved overlay without moving the service registration's state root. +internal sealed class ServiceConfigEnvironmentReader(IServiceFileSystem fileSystem) +{ + /// Captures the current config overlay, including its absence. + /// The already located service paths. + /// The caller's token. + /// A non-null capture whose entries may be absent. + public async Task ReadAsync(ServicePaths paths, CancellationToken cancellationToken) + { + IReadOnlyDictionary? configured = null; + if (paths.ConfigFile is { } configFile && + await fileSystem.TryReadAllBytesAsync(configFile, cancellationToken).ConfigureAwait(false) is { } bytes) + { + configured = ServiceConfigReader.TryReadEnvironment(bytes)? + .Where(static entry => !string.Equals(entry.Key, "XDG_STATE_HOME", StringComparison.Ordinal)) + .ToDictionary(static entry => entry.Key, static entry => entry.Value, StringComparer.Ordinal); + } + + return new ServiceConfigEnvironment(configured); + } +} diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceElection.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceElection.cs index 129ab0ee..c199397b 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceElection.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceElection.cs @@ -13,7 +13,11 @@ namespace OpenCode.Sdk.Internal; /// Its fields are upstream's loop locals and its contender pool's state; one instance serves one /// call. /// -internal sealed class ServiceElection(ServiceElectionSeams seams, EnsureRequest request, ServicePaths paths) +/// The election's process, filesystem, network and clock boundaries. +/// The validated service request. +/// The already located service paths. +/// The captured overlay, or null to read config dynamically at every spawn. +internal sealed class ServiceElection(ServiceElectionSeams seams, EnsureRequest request, ServicePaths paths, ServiceConfigEnvironment? snapshot) { private static readonly ServiceProbeResult NoService = new(State: null, Version: null, TimedOut: false, Compatible: true); @@ -264,8 +268,8 @@ [.. request.Command.Skip(1)], } /// - /// The channel's service-config env (the CLI's ServiceConfig.options()), with the - /// caller's entries winning at spawn for a key spelled the same. + /// Uses the captured overlay, or reads service config at every spawn when no snapshot was + /// supplied, with the caller's entries winning for a key spelled the same. /// /// /// The saved map never supplies XDG_STATE_HOME: clients find the service at its registration @@ -275,14 +279,9 @@ [.. request.Command.Skip(1)], /// private async Task?> OverlayAsync(CancellationToken cancellationToken) { - Dictionary? configured = null; - if (paths.ConfigFile is { } configFile && - await seams.FileSystem.TryReadAllBytesAsync(configFile, cancellationToken).ConfigureAwait(false) is { } bytes) - { - configured = ServiceConfigReader.TryReadEnvironment(bytes)? - .Where(static entry => !string.Equals(entry.Key, "XDG_STATE_HOME", StringComparison.Ordinal)) - .ToDictionary(static entry => entry.Key, static entry => entry.Value, StringComparer.Ordinal); - } + var captured = snapshot ?? await new ServiceConfigEnvironmentReader(seams.FileSystem) + .ReadAsync(paths, cancellationToken).ConfigureAwait(false); + var configured = captured.Entries; if (configured is null || request.Environment is null) { diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceEnsurer.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceEnsurer.cs index 5f8653e1..fe19781d 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceEnsurer.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Ensure/ServiceEnsurer.cs @@ -39,6 +39,20 @@ public async Task EnsureAsync(OpenCodeServerEnsureOptions? .LocateAsync(request.Selection, cancellationToken) .ConfigureAwait(false); + return await EnsureLocatedAsync(request, paths, snapshot: null, cancellationToken).ConfigureAwait(false); + } + + /// Runs the same election against already located paths and an optional captured overlay. + /// The validated and copied request. + /// The already located paths. + /// A captured overlay, or null for a dynamic read at every spawn. + /// The caller's token. + /// The ready service's registration. + public async Task EnsureLocatedAsync( + EnsureRequest request, ServicePaths paths, ServiceConfigEnvironment? snapshot, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (request.Policy == OpenCodeServerVersionPolicy.Error) { // resolveManaged: a service at the expected version is reused, a service at @@ -64,6 +78,6 @@ public async Task EnsureAsync(OpenCodeServerEnsureOptions? time, executableResolver, timing); - return await new ServiceElection(seams, request, paths).RunAsync(cancellationToken).ConfigureAwait(false); + return await new ServiceElection(seams, request, paths, snapshot).RunAsync(cancellationToken).ConfigureAwait(false); } } diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceDisabledCheck.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceDisabledCheck.cs new file mode 100644 index 00000000..eafe63b3 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceDisabledCheck.cs @@ -0,0 +1,19 @@ +using System.Security.Cryptography; + +namespace OpenCode.Sdk.Internal; + +/// Reads the connection-mode flag through the migrating and repairing configuration store. +internal sealed class ServiceDisabledCheck(IServiceEnvironment environment, IServiceFileSystem fileSystem, TimeProvider time) +{ + /// Checks whether the selected channel disables its managed service. + /// The validated service selection. + /// The caller's token. + /// True only for a valid config whose disabled flag is true. + public async Task IsDisabledAsync(ServiceSelection selection, CancellationToken cancellationToken) + { + using var random = RandomNumberGenerator.Create(); + var store = new ServiceConfigStore(environment, fileSystem, time, new RandomCredential(random)); + var result = await store.ReadAsync(selection, cancellationToken).ConfigureAwait(false); + return result.Document?.Disabled == true; + } +} diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceMigration.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceMigration.cs index 0d5bd685..452755e3 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceMigration.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceMigration.cs @@ -45,6 +45,15 @@ public async Task ApplyAsync(ServiceSelection selection, ServicePaths paths, Can await CopyAsync(paths.RegistrationFile, bytes, cancellationToken).ConfigureAwait(false); } + await ApplyConfigAsync(paths, cancellationToken).ConfigureAwait(false); + } + + /// Considers only the legacy config donor, independently of registration migration. + /// The resolved config paths. + /// The caller's token. + /// A task that completes after the config donor has been considered. + public async Task ApplyConfigAsync(ServicePaths paths, CancellationToken cancellationToken) + { if (paths.LegacyConfigFile is { } legacyConfig && paths.ConfigFile is { } configFile) { cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Stop/ServiceStopper.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Stop/ServiceStopper.cs index bd33e806..68e22366 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Stop/ServiceStopper.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Stop/ServiceStopper.cs @@ -36,6 +36,17 @@ public async Task StopAsync(OpenCodeServerStopOptions? options, CancellationToke var paths = await new ServiceRegistrationLocator(environment, fileSystem) .LocateAsync(selection, cancellationToken) .ConfigureAwait(false); + await StopLocatedAsync(paths, mode, cancellationToken).ConfigureAwait(false); + } + + /// Stops the registration at already located paths without migration. + /// The already located service paths. + /// Clear or hand off persistent terminals. + /// The caller's token. + /// A task completing when the registered process is gone or absent. + public async Task StopLocatedAsync(ServicePaths paths, OpenCodeServerStopPtyMode? mode, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); var registration = await ServiceRegistrationReader .TryReadAsync(fileSystem, paths.RegistrationFile, cancellationToken) .ConfigureAwait(false); diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs index 999ff6e5..95c83acf 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs @@ -116,11 +116,21 @@ private static ServiceInfoProbe PlatformProbe(ServiceTiming timing, TimeProvider new(timing, new LoopbackTransport(new LoopbackSocketConnector()), time); /// The non-owning handle over a registered service. - private static OpenCodeServer SharedService(ServiceRegistration registration) => + internal static OpenCodeServer SharedService(ServiceRegistration registration) => new( registration.Endpoint, registration.Password, - registration.ProcessId); + registration.ProcessId, + registration.Version); + + /// Discovers an already located service without migration. + internal static async Task DiscoverLocatedAsync( + ServicePaths paths, string? expectedVersion, CancellationToken cancellationToken) + { + var discovery = new ServiceDiscovery(new ServiceEnvironment(), new ServiceFileSystem(), SystemDiscoveryProbe()); + var registration = await discovery.DiscoverAtAsync(paths, expectedVersion, cancellationToken).ConfigureAwait(false); + return registration is null ? null : SharedService(registration); + } /// /// The CLI's shutdownPersistentPty: discovers the background service and shuts down its @@ -190,21 +200,27 @@ internal static async Task ShutdownPersistentPtyWithSeamsAsync( /// No user home directory resolves for an XDG fallback, or the registered process is still running after the hard kill. public static Task StopAsync( OpenCodeServerStopOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) => + SystemStopper().StopAsync(options, cancellationToken); + + /// Stops an already located service without migration. + internal static Task StopLocatedAsync(ServicePaths paths, OpenCodeServerStopPtyMode? mode, CancellationToken cancellationToken) => + SystemStopper().StopLocatedAsync(paths, mode, cancellationToken); + + private static ServiceStopper SystemStopper() { var timing = ServiceTiming.Default; #pragma warning disable RS0030 // The stop composition root chooses the system clock; its handoff and terminator share it. var time = TimeProvider.System; #pragma warning restore RS0030 var fileSystem = new ServiceFileSystem(); - var stopper = new ServiceStopper( + return new ServiceStopper( new ServiceEnvironment(), fileSystem, new ServicePtyHandoff(fileSystem, time, new ServicePtyShutdown()), new ServiceProcessControl(new ChildExitStatusReader()), timing, time); - return stopper.StopAsync(options, cancellationToken); } /// @@ -223,14 +239,28 @@ public static Task StopAsync( /// A non-owning handle over the ready service. /// An option is blank, the registration path is relative, the command is empty, a command or environment entry contains a NUL, Replace or Error is set without ExpectedVersion, or the options contradict one another. /// No user home directory resolves, the election timed out, a contender or the registered service failed to start, the registered service speaks an incompatible health protocol at a version the call accepts, a version mismatch was refused, or a spawned command could not be resolved. - public static Task EnsureAsync( + public static async Task EnsureAsync( OpenCodeServerEnsureOptions? options = null, CancellationToken cancellationToken = default) { + var registration = await SystemEnsurer().EnsureAsync(options, cancellationToken).ConfigureAwait(false); + return SharedService(registration); + } + + /// Ensures an already located service using its captured environment. + internal static async Task EnsureLocatedAsync( + EnsureRequest request, ServicePaths paths, ServiceConfigEnvironment snapshot, CancellationToken cancellationToken) + { + var registration = await SystemEnsurer().EnsureLocatedAsync(request, paths, snapshot, cancellationToken).ConfigureAwait(false); + return SharedService(registration); + } + + private static ServiceEnsurer SystemEnsurer() + { #pragma warning disable RS0030 // The ensure composition root chooses the system clock; election collaborators and spawned contenders receive it. var time = TimeProvider.System; #pragma warning restore RS0030 - return EnsureWithSeamsAsync(options, ServiceTiming.Default, new ServiceContenderSpawner(new PosixSpawn(), new WindowsSpawn(), time), time, cancellationToken); + return CreateEnsurer(ServiceTiming.Default, new ServiceContenderSpawner(new PosixSpawn(), new WindowsSpawn(), time), time); } /// @@ -258,8 +288,38 @@ internal static async Task EnsureWithSeamsAsync( ArgumentNullException.ThrowIfNull(spawner); ArgumentNullException.ThrowIfNull(time); + var registration = await CreateEnsurer(timing, spawner, time).EnsureAsync(options, cancellationToken).ConfigureAwait(false); + return SharedService(registration); + } + + /// The located Ensure over the same injected election boundaries as EnsureWithSeamsAsync. + /// The captured request, service paths and environment overlay. + /// The lifecycle timing. + /// The contender spawn. + /// The clock shared by the election collaborators. + /// The caller's token. + /// A non-owning handle over the ready service. + internal static async Task EnsureLocatedWithSeamsAsync( + ManagedServiceSnapshot snapshot, + ServiceTiming timing, + IServiceContenderSpawner spawner, + TimeProvider time, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(snapshot); + ArgumentNullException.ThrowIfNull(timing); + ArgumentNullException.ThrowIfNull(spawner); + ArgumentNullException.ThrowIfNull(time); + + var registration = await CreateEnsurer(timing, spawner, time) + .EnsureLocatedAsync(snapshot.Request, snapshot.Paths, snapshot.Overlay, cancellationToken).ConfigureAwait(false); + return SharedService(registration); + } + + private static ServiceEnsurer CreateEnsurer(ServiceTiming timing, IServiceContenderSpawner spawner, TimeProvider time) + { var fileSystem = new ServiceFileSystem(); - var ensurer = new ServiceEnsurer( + return new ServiceEnsurer( new ServiceEnvironment(), fileSystem, PlatformProbe(timing, time), @@ -269,7 +329,5 @@ internal static async Task EnsureWithSeamsAsync( time, new ExecutableResolver(ExecutableSearchEnvironment.ForCurrentProcess()), timing); - var registration = await ensurer.EnsureAsync(options, cancellationToken).ConfigureAwait(false); - return SharedService(registration); } } diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/Abstractions/IServerDoors.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/Abstractions/IServerDoors.cs new file mode 100644 index 00000000..304d8f7f --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/Abstractions/IServerDoors.cs @@ -0,0 +1,14 @@ +namespace OpenCode.Sdk.Internal; + +/// The process and network boundaries the connection composition calls. +internal interface IServerDoors +{ + public Task StartAsync(OpenCodeServerOptions? options, CancellationToken cancellationToken); + + public Task DiscoverLocatedAsync(ServicePaths paths, string? expectedVersion, CancellationToken cancellationToken); + + public Task EnsureLocatedAsync( + EnsureRequest request, ServicePaths paths, ServiceConfigEnvironment snapshot, CancellationToken cancellationToken); + + public Task StopLocatedAsync(ServicePaths paths, OpenCodeServerStopPtyMode? mode, CancellationToken cancellationToken); +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/ConnectionResolver.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/ConnectionResolver.cs new file mode 100644 index 00000000..ac0fee20 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/ConnectionResolver.cs @@ -0,0 +1,49 @@ +namespace OpenCode.Sdk.Internal; + +/// The CLI's explicit, standalone and managed connection precedence over substituted boundaries. +internal sealed class ConnectionResolver(ConnectionSeams seams) +{ + public async Task ResolveAsync(ResolveRequest request, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (request.Endpoint is { } endpoint) + { + var info = await new ExplicitServerProbe(seams.ProbeTransport, seams.ProbeTime) + .GetInfoAsync(endpoint, request.Password, cancellationToken).ConfigureAwait(false); + VersionMismatchNotifier.Notify(endpoint, info.Version, request.OnServerVersionMismatch); + return new OpenCodeServerConnection(endpoint, request.Password, info.Version); + } + + var service = EnsureRequest.Snapshot(request.Service); + if (request.Standalone || await new ServiceDisabledCheck( + seams.Environment, seams.FileSystem, seams.ProbeTime ?? LauncherSeams.ForCurrentProcess().Time) + .IsDisabledAsync(service.Selection, cancellationToken).ConfigureAwait(false)) + { + return await StartStandaloneAsync(request.Launch, cancellationToken).ConfigureAwait(false); + } + + var paths = await new ServiceRegistrationLocator(seams.Environment, seams.FileSystem) + .LocateAsync(service.Selection, cancellationToken).ConfigureAwait(false); + var overlay = await new ServiceConfigEnvironmentReader(seams.FileSystem).ReadAsync(paths, cancellationToken).ConfigureAwait(false); + var snapshot = new ManagedServiceSnapshot(service, paths, overlay); + if (!request.Autostart) + { + var discovered = await seams.Doors.DiscoverLocatedAsync(paths, expectedVersion: null, cancellationToken).ConfigureAwait(false); + return discovered is null + ? await StartStandaloneAsync(request.Launch, cancellationToken).ConfigureAwait(false) + : ServiceConnection(discovered, snapshot); + } + + var server = await seams.Doors.EnsureLocatedAsync(service, paths, overlay, cancellationToken).ConfigureAwait(false); + return ServiceConnection(server, snapshot); + } + + private async Task StartStandaloneAsync(OpenCodeServerOptions? launch, CancellationToken cancellationToken) + { + var server = await seams.Doors.StartAsync(launch, cancellationToken).ConfigureAwait(false); + return new OpenCodeServerConnection(server, serverVersion: null); + } + + private OpenCodeServerConnection ServiceConnection(OpenCodeServer server, ManagedServiceSnapshot snapshot) => + new(server, server.RegisteredVersion, new OpenCodeServerServiceOperations(snapshot, seams.Doors)); +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/ConnectionSeams.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/ConnectionSeams.cs new file mode 100644 index 00000000..e703f2b6 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/ConnectionSeams.cs @@ -0,0 +1,14 @@ +namespace OpenCode.Sdk.Internal; + +/// The boundaries shared by connection selection and the explicit probe. +/// Launcher and located service operations. +/// The service roots. +/// Config and registration access. +/// The test-only transport, null in production. +/// The test-only clock, null in production. +internal sealed record ConnectionSeams( + IServerDoors Doors, + IServiceEnvironment Environment, + IServiceFileSystem FileSystem, + HttpClient? ProbeTransport = null, + TimeProvider? ProbeTime = null); diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/ExplicitProbeFailureClassifier.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/ExplicitProbeFailureClassifier.cs new file mode 100644 index 00000000..44e870f7 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/ExplicitProbeFailureClassifier.cs @@ -0,0 +1,39 @@ +using System.Text.Json; +using OpenCode.Sdk.Models; + +namespace OpenCode.Sdk.Internal; + +/// The explicit connection's ordered error policy, independent of transport and clocks. +/// +/// Pipeline status refusals and +/// carry no inner transport cause. Decoder failures carry JsonException; network failures retain their transport cause. +/// +internal static class ExplicitProbeFailureClassifier +{ + public static Exception Map(Exception failure, Uri endpoint, bool hasPassword, CancellationToken caller, CancellationToken bound) + { + if (caller.IsCancellationRequested) + { + return FailureClassification.CallerCancellation(failure, failure.Message, caller); + } + + if (failure is OpenCodeApiException { Error: UnauthorizedError }) + { + return new OpenCodeServerException(hasPassword + ? $"Server at {endpoint} rejected the password" + : $"Server at {endpoint} requires a password; set OpenCodeServerResolveOptions.Password", failure); + } + + if (failure is OperationCanceledException && bound.IsCancellationRequested) + { + return new OpenCodeServerException($"Could not reach server at {endpoint}: {failure.Message}", failure); + } + + if (failure is OpenCodeTransportException { InnerException: { } cause } && cause is not JsonException) + { + return new OpenCodeServerException($"Could not reach server at {endpoint}: {cause.Message}", failure); + } + + return new OpenCodeServerException($"Server at {endpoint} did not provide a compatible V2 health response: {failure.Message}", failure); + } +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/ExplicitServerProbe.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/ExplicitServerProbe.cs new file mode 100644 index 00000000..9a1714b5 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/ExplicitServerProbe.cs @@ -0,0 +1,26 @@ +using OpenCode.Sdk.Models; + +namespace OpenCode.Sdk.Internal; + +/// Probes the explicit server under a total bound on the probe pipeline's own clock. +internal sealed class ExplicitServerProbe(HttpClient? transport = null, TimeProvider? time = null) +{ + public async Task GetInfoAsync(Uri endpoint, string? password, CancellationToken cancellationToken) + { + var options = new OpenCodeClientOptions { Endpoint = endpoint, Password = password }; + using var pipeline = transport is null + ? Pipeline.Create(options, time) + : new Pipeline(transport, ownsHttpClient: false, options, time: time); + using var bound = TimedCancellation.Create(TimeSpan.FromSeconds(5), pipeline.Connection.Time); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, bound.Token); + try + { + var response = await new ServerClient(pipeline).GetInfoAsync(cancellationToken: linked.Token).ConfigureAwait(false); + return response.ServerInfo; + } + catch (Exception failure) when (failure is OpenCodeApiException or OpenCodeTransportException or OperationCanceledException) + { + throw ExplicitProbeFailureClassifier.Map(failure, endpoint, password is not null, cancellationToken, bound.Token); + } + } +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/ManagedServiceSnapshot.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/ManagedServiceSnapshot.cs new file mode 100644 index 00000000..be987f17 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/ManagedServiceSnapshot.cs @@ -0,0 +1,11 @@ +namespace OpenCode.Sdk.Internal; + +/// The request, paths and overlay captured once when a managed connection resolves. +/// The validated resolve-time service request. +/// The located paths. +/// The captured overlay, including captured absence. +internal sealed record ManagedServiceSnapshot(EnsureRequest Request, ServicePaths Paths, ServiceConfigEnvironment Overlay) +{ + /// Gets the same inputs without version replacement or a start announcement. + public EnsureRequest ReconnectRequest => Request with { Policy = OpenCodeServerVersionPolicy.Ignore, OnStart = null }; +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/PinnedRelease.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/PinnedRelease.cs new file mode 100644 index 00000000..e63380d0 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/PinnedRelease.cs @@ -0,0 +1,7 @@ +namespace OpenCode.Sdk.Internal; + +/// The releaseTag in spec/receipt.json without its leading v, equality-checked by PinnedReleaseTests. +internal static class PinnedRelease +{ + internal const string Version = "2.3.0"; +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/ResolveRequest.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/ResolveRequest.cs new file mode 100644 index 00000000..e2c3a6f7 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/ResolveRequest.cs @@ -0,0 +1,32 @@ +namespace OpenCode.Sdk.Internal; + +/// The resolver's entry snapshot; managed validation happens only after the explicit branch. +internal sealed record ResolveRequest( + Uri? Endpoint, + string? Password, + bool Standalone, + bool Autostart, + OpenCodeServerOptions? Launch, + OpenCodeServerEnsureOptions? Service, + Action? OnServerVersionMismatch) +{ + public static ResolveRequest Snapshot(OpenCodeServerResolveOptions? options) + { + if (options?.Endpoint is not null && options.Standalone) + { + throw new ArgumentException("OpenCodeServerResolveOptions.Endpoint and Standalone cannot be combined.", nameof(options)); + } + if (options?.Password is not null && options.Endpoint is null) + { + throw new ArgumentException( + "Password applies only to an explicit Endpoint; a standalone or service connection carries its own credentials.", nameof(options)); + } + if (options?.Endpoint is { } endpoint) + { + _ = EndpointPolicy.Normalize(endpoint); + } + + return new ResolveRequest(options?.Endpoint, options?.Password, options?.Standalone ?? false, + options?.Autostart ?? true, options?.Launch, options?.Service, options?.OnServerVersionMismatch); + } +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/ServerDoors.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/ServerDoors.cs new file mode 100644 index 00000000..3066ae1f --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/ServerDoors.cs @@ -0,0 +1,18 @@ +namespace OpenCode.Sdk.Internal; + +/// Forwards connection operations to the existing launcher and located service cores. +internal sealed class ServerDoors : IServerDoors +{ + public Task StartAsync(OpenCodeServerOptions? options, CancellationToken cancellationToken) => + OpenCodeServer.StartAsync(options, cancellationToken); + + public Task DiscoverLocatedAsync(ServicePaths paths, string? expectedVersion, CancellationToken cancellationToken) => + OpenCodeServer.DiscoverLocatedAsync(paths, expectedVersion, cancellationToken); + + public Task EnsureLocatedAsync( + EnsureRequest request, ServicePaths paths, ServiceConfigEnvironment snapshot, CancellationToken cancellationToken) => + OpenCodeServer.EnsureLocatedAsync(request, paths, snapshot, cancellationToken); + + public Task StopLocatedAsync(ServicePaths paths, OpenCodeServerStopPtyMode? mode, CancellationToken cancellationToken) => + OpenCodeServer.StopLocatedAsync(paths, mode, cancellationToken); +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/Internal/VersionMismatchNotifier.cs b/src/OpenCode.Sdk/Hosting/Connection/Internal/VersionMismatchNotifier.cs new file mode 100644 index 00000000..e268fc7b --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/Internal/VersionMismatchNotifier.cs @@ -0,0 +1,17 @@ +namespace OpenCode.Sdk.Internal; + +/// Reports an explicit version mismatch without owning a diagnostics channel. +internal static class VersionMismatchNotifier +{ + /// Invokes the optional callback once on an ordinal mismatch. + /// The explicit endpoint. + /// The probe's version. + /// The optional synchronous callback. + public static void Notify(Uri endpoint, string serverVersion, Action? callback) + { + if (!string.Equals(serverVersion, PinnedRelease.Version, StringComparison.Ordinal)) + { + callback?.Invoke(new OpenCodeServerVersionMismatchContext(endpoint, serverVersion, PinnedRelease.Version)); + } + } +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServer.Connection.cs b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServer.Connection.cs new file mode 100644 index 00000000..be25c576 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServer.Connection.cs @@ -0,0 +1,22 @@ +using OpenCode.Sdk.Internal; + +namespace OpenCode.Sdk; + +public partial class OpenCodeServer +{ + /// Resolves an explicit endpoint, an owned standalone server, or the shared managed service, in that order. + /// Connection selection; null ensures the default managed service unless its config disables it. + /// The caller's token; its cancellation is never wrapped. + /// A connection whose mode describes ownership and available service operations. + /// Options contradict one another, the endpoint is refused, or managed options are invalid. + /// An explicit probe failed or a launcher or service door failed. + public static async Task ResolveAsync( + OpenCodeServerResolveOptions? options = null, CancellationToken cancellationToken = default) => + await ResolveWithSeamsAsync(options, new ConnectionSeams(new ServerDoors(), new ServiceEnvironment(), new ServiceFileSystem()), cancellationToken) + .ConfigureAwait(false); + + /// The same resolver over injected external boundaries. + internal static Task ResolveWithSeamsAsync( + OpenCodeServerResolveOptions? options, ConnectionSeams seams, CancellationToken cancellationToken) => + new ConnectionResolver(seams).ResolveAsync(ResolveRequest.Snapshot(options), cancellationToken); +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerConnection.cs b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerConnection.cs new file mode 100644 index 00000000..8e9c5953 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerConnection.cs @@ -0,0 +1,92 @@ +using System.Runtime.CompilerServices; +using OpenCode.Sdk.Internal; + +namespace OpenCode.Sdk; + +/// A resolved connection that composes a process-backed handle when its mode has one. +public class OpenCodeServerConnection : IAsyncDisposable +{ + private readonly OpenCodeServerConnectionMode _mode; + private readonly Uri? _endpoint; + private readonly string? _password; + private readonly string? _serverVersion; + private readonly OpenCodeServer? _server; + private readonly OpenCodeServerServiceOperations? _serviceOperations; + private int _disposed; + + /// Initializes a mocking instance whose unoverridden members throw an instructive failure. + protected OpenCodeServerConnection() + { + } + + internal OpenCodeServerConnection(Uri endpoint, string? password, string serverVersion) + { + _endpoint = endpoint; + _password = password; + _serverVersion = serverVersion; + _mode = OpenCodeServerConnectionMode.Explicit; + } + + internal OpenCodeServerConnection(OpenCodeServer server, string? serverVersion) + { + _endpoint = server.Endpoint; + _password = server.Password; + _server = server; + _serverVersion = serverVersion; + _mode = OpenCodeServerConnectionMode.Standalone; + } + + internal OpenCodeServerConnection(OpenCodeServer server, string? serverVersion, OpenCodeServerServiceOperations serviceOperations) + : this(server, serverVersion) + { + _mode = OpenCodeServerConnectionMode.Service; + _serviceOperations = serviceOperations; + } + + /// Gets how this connection reaches and owns its server. + public virtual OpenCodeServerConnectionMode Mode => Read(_mode); + + /// Gets the resolved endpoint, unchanged by reconnect or restart. + public virtual Uri Endpoint => _endpoint ?? throw MockSeam.CreateError(nameof(OpenCodeServerConnection), nameof(Endpoint)); + + /// Gets the pinned server's basic-authentication username, opencode. + public virtual string Username => Read("opencode"); + + /// Gets the selected mode's credential, or null for an unauthenticated server. + public virtual string? Password => Read(_password); + + /// Gets the version learned at resolve, or null when none was learned. + /// Reconnect and restart return new handles and never update this value. + public virtual string? ServerVersion => Read(_serverVersion); + + /// Gets the owned standalone or shared service handle, or null in explicit mode. + public virtual OpenCodeServer? Server => Read(_server); + + /// Gets reconnect and restart operations in service mode, or null otherwise. + public virtual OpenCodeServerServiceOperations? ServiceOperations => Read(_serviceOperations); + + /// Builds a caller-owned client; the delegate may configure behavior but not connection identity. + /// Optional behavior configuration, with identity members left unset. + /// A new client bound to this connection. + /// The delegate set an identity member. + public virtual OpenCodeClient CreateClient(Action? configure = null) => + ClientIdentityComposer.CreateClient(Endpoint, Password, configure); + + /// Ends an owned standalone server once; explicit and shared service connections release nothing. + /// A task completing after any owned server has ended. + public virtual async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) + { + return; + } + GC.SuppressFinalize(this); + if (_mode == OpenCodeServerConnectionMode.Standalone && _server is not null) + { + await _server.DisposeAsync().ConfigureAwait(false); + } + } + + private T Read(T value, [CallerMemberName] string member = "") => + _endpoint is null ? throw MockSeam.CreateError(nameof(OpenCodeServerConnection), member) : value; +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerConnectionMode.cs b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerConnectionMode.cs new file mode 100644 index 00000000..f6da52ea --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerConnectionMode.cs @@ -0,0 +1,14 @@ +namespace OpenCode.Sdk; + +/// The way a resolved connection reaches and owns its server. +public enum OpenCodeServerConnectionMode +{ + /// An explicitly addressed server, whose lifetime belongs elsewhere. + Explicit = 0, + + /// A private server whose lifetime belongs to the connection. + Standalone = 1, + + /// A registered background service shared with other clients. + Service = 2, +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerResolveOptions.cs b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerResolveOptions.cs new file mode 100644 index 00000000..ab20d8e6 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerResolveOptions.cs @@ -0,0 +1,30 @@ +namespace OpenCode.Sdk; + +/// Selects an explicit server, a private standalone server, or the shared managed service. +public sealed class OpenCodeServerResolveOptions +{ + /// Gets or sets the explicit endpoint; managed options are ignored when set. + public Uri? Endpoint { get; set; } + + /// Gets or sets the explicit endpoint's password; null sends no credential, while an empty string sends one. + /// A password without an Endpoint is refused; no credential environment variable is read. + public string? Password { get; set; } + + /// Gets or sets a value indicating whether to start a private standalone server without reading service config. + /// Cannot be combined with Endpoint. + public bool Standalone { get; set; } + + /// Gets or sets a value indicating whether to ensure the managed service; false discovers any version and starts standalone on a miss. + public bool Autostart { get; set; } = true; + + /// Gets or sets launch options for every standalone path, ignored for an explicit endpoint or a service hit. + public OpenCodeServerOptions? Launch { get; set; } + + /// Gets or sets managed selection, version policy, command, environment and initial start callback. + /// Ignored and not validated for an explicit Endpoint. Replace and Error require ExpectedVersion; the pinned release is never a default. + public OpenCodeServerEnsureOptions? Service { get; set; } + + /// Gets or sets the synchronous explicit-version mismatch callback, silent by default. + /// Invoked once on an ordinal mismatch against the pinned release; resolution continues unless the callback throws. + public Action? OnServerVersionMismatch { get; set; } +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerServiceOperations.cs b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerServiceOperations.cs new file mode 100644 index 00000000..4bae1694 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerServiceOperations.cs @@ -0,0 +1,45 @@ +using OpenCode.Sdk.Internal; + +namespace OpenCode.Sdk; + +/// Reconnects or restarts a shared service using the connection's resolve-time inputs. +/// Calls are not serialized. Returned handles do not own the daemon and belong to the caller. +public class OpenCodeServerServiceOperations +{ + private readonly ManagedServiceSnapshot? _snapshot; + private readonly IServerDoors? _doors; + + /// Initializes a mocking instance whose unoverridden operations throw an instructive failure. + protected OpenCodeServerServiceOperations() + { + } + + internal OpenCodeServerServiceOperations(ManagedServiceSnapshot snapshot, IServerDoors doors) + { + _snapshot = snapshot; + _doors = doors; + } + + /// Ensures the captured service without a version requirement or start announcement. + /// The caller's token. + /// A new non-owning handle, without changing the resolved connection. + public virtual async Task ReconnectAsync(CancellationToken cancellationToken = default) + { + var snapshot = _snapshot ?? throw MockSeam.CreateError(nameof(OpenCodeServerServiceOperations), nameof(ReconnectAsync)); + cancellationToken.ThrowIfCancellationRequested(); + // A real instance initializes both collaborators together. + return await _doors!.EnsureLocatedAsync(snapshot.ReconnectRequest, snapshot.Paths, snapshot.Overlay, cancellationToken).ConfigureAwait(false); + } + + /// Stops with best-effort persistent-terminal handoff, then reconnects to the captured service. + /// The caller's token; a cancelled call never starts stopping. + /// A new non-owning handle, without changing the resolved connection. + public virtual async Task RestartAsync(CancellationToken cancellationToken = default) + { + var snapshot = _snapshot ?? throw MockSeam.CreateError(nameof(OpenCodeServerServiceOperations), nameof(RestartAsync)); + cancellationToken.ThrowIfCancellationRequested(); + // A real instance initializes both collaborators together. + await _doors!.StopLocatedAsync(snapshot.Paths, OpenCodeServerStopPtyMode.Handoff, cancellationToken).ConfigureAwait(false); + return await _doors.EnsureLocatedAsync(snapshot.ReconnectRequest, snapshot.Paths, snapshot.Overlay, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerVersionMismatchContext.cs b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerVersionMismatchContext.cs new file mode 100644 index 00000000..6f166c0d --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Connection/OpenCodeServerVersionMismatchContext.cs @@ -0,0 +1,21 @@ +namespace OpenCode.Sdk; + +/// The explicit server's version and the pinned release it differs from. +public sealed class OpenCodeServerVersionMismatchContext +{ + internal OpenCodeServerVersionMismatchContext(Uri endpoint, string serverVersion, string clientVersion) + { + Endpoint = endpoint; + ServerVersion = serverVersion; + ClientVersion = clientVersion; + } + + /// Gets the explicitly selected server's endpoint. + public Uri Endpoint { get; } + + /// Gets the version the explicit probe reported. + public string ServerVersion { get; } + + /// Gets the SDK's pinned release comparand, not the version of a CLI found on PATH. + public string ClientVersion { get; } +} diff --git a/src/OpenCode.Sdk/Hosting/Internal/ClientIdentityComposer.cs b/src/OpenCode.Sdk/Hosting/Internal/ClientIdentityComposer.cs new file mode 100644 index 00000000..f8b61183 --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/Internal/ClientIdentityComposer.cs @@ -0,0 +1,38 @@ +namespace OpenCode.Sdk.Internal; + +/// Builds clients with door-owned identity and caller-configured behavior. +internal static class ClientIdentityComposer +{ + public static OpenCodeClient CreateClient(Uri endpoint, string? password, Action? configure) + { + var options = new OpenCodeClientOptions(); + configure?.Invoke(options); + if (options.Endpoint is not null || + options.Password is not null || + !string.Equals(options.Username, "opencode", StringComparison.Ordinal)) + { + throw new InvalidOperationException( + "CreateClient owns the connection identity: leave Endpoint, Username, and Password unset — the started server supplies them. Configure behavior members such as Location only."); + } + + // A distinct instance carries the door's identity into the client: the object the + // delegate received stays identity-unset for as long as the caller keeps a reference to + // it, rather than being mutated out from under them after the delegate returns. + var clientOptions = new OpenCodeClientOptions + { + Endpoint = endpoint, + Username = options.Username, + Password = password, + Location = options.Location, + HttpHandler = options.HttpHandler, + NetworkTimeout = options.NetworkTimeout, + EventStreamIdleTimeout = options.EventStreamIdleTimeout, + }; + foreach (var header in options.Headers) + { + clientOptions.Headers.Add(header); + } + + return new OpenCodeClient(clientOptions); + } +} diff --git a/src/OpenCode.Sdk/Hosting/OpenCodeServer.cs b/src/OpenCode.Sdk/Hosting/OpenCodeServer.cs index 9738501e..b3915864 100644 --- a/src/OpenCode.Sdk/Hosting/OpenCodeServer.cs +++ b/src/OpenCode.Sdk/Hosting/OpenCodeServer.cs @@ -58,13 +58,17 @@ internal OpenCodeServer(Uri endpoint, string password) /// Initializes a handle over a server another process runs: the identity a registration /// published, no child, no ownership. Disposal is a no-op. /// - internal OpenCodeServer(Uri endpoint, string? password, int processId) + internal OpenCodeServer(Uri endpoint, string? password, int processId, string? version) { _endpoint = endpoint; _password = password; _processId = processId; + RegisteredVersion = version; } + /// Gets the version carried by the registration, if any. + internal string? RegisteredVersion { get; } + /// /// Initializes a mocking instance; members invoked without an override throw an instructive failure. /// @@ -129,40 +133,8 @@ protected OpenCodeServer() /// Optional behavior configuration; identity members must stay unset. /// A new client bound to this server's endpoint and credential: a started server's lease, a registration's password, or none. /// The delegate set an identity member. - public virtual OpenCodeClient CreateClient(Action? configure = null) - { - var endpoint = Endpoint; - var password = Password; - var options = new OpenCodeClientOptions(); - configure?.Invoke(options); - if (options.Endpoint is not null || - options.Password is not null || - !string.Equals(options.Username, "opencode", StringComparison.Ordinal)) - { - throw new InvalidOperationException( - "CreateClient owns the connection identity: leave Endpoint, Username, and Password unset — the started server supplies them. Configure behavior members such as Location only."); - } - - // A distinct instance carries the door's identity into the client: the object the - // delegate received stays identity-unset for as long as the caller keeps a reference to - // it, rather than being mutated out from under them after the delegate returns. - var clientOptions = new OpenCodeClientOptions - { - Endpoint = endpoint, - Username = options.Username, - Password = password, - Location = options.Location, - HttpHandler = options.HttpHandler, - NetworkTimeout = options.NetworkTimeout, - EventStreamIdleTimeout = options.EventStreamIdleTimeout, - }; - foreach (var header in options.Headers) - { - clientOptions.Headers.Add(header); - } - - return new OpenCodeClient(clientOptions); - } + public virtual OpenCodeClient CreateClient(Action? configure = null) => + ClientIdentityComposer.CreateClient(Endpoint, Password, configure); /// /// Ends the owned child, bounded at every step, quiet for a child that is already gone, and diff --git a/src/OpenCode.Sdk/Hosting/OpenCodeServerException.cs b/src/OpenCode.Sdk/Hosting/OpenCodeServerException.cs index 4f5a2cdc..979f5d8d 100644 --- a/src/OpenCode.Sdk/Hosting/OpenCodeServerException.cs +++ b/src/OpenCode.Sdk/Hosting/OpenCodeServerException.cs @@ -2,6 +2,7 @@ namespace OpenCode.Sdk; /// /// A local server door failed: a standalone server could not start, report readiness, or stop, +/// an explicit server the resolver could not reach, authenticate with, or read, /// or background-service discovery or ensure could not resolve the user home its registration /// roots hang off, timed out, or refused a version mismatch. An absent or unusable registration /// is not a failure for discovery, which reports it as null; ensure starts a service instead. diff --git a/src/OpenCode.Sdk/Internal/Operations/ResponseAdapter.cs b/src/OpenCode.Sdk/Internal/Operations/ResponseAdapter.cs index 9c5835fc..82b8c434 100644 --- a/src/OpenCode.Sdk/Internal/Operations/ResponseAdapter.cs +++ b/src/OpenCode.Sdk/Internal/Operations/ResponseAdapter.cs @@ -9,6 +9,8 @@ namespace OpenCode.Sdk.Internal; internal abstract class ResponseAdapter where TResponse : OpenCodeResponse { + internal const string NullSuccessBodyMessage = "The opencode API returned a null success body."; + /// /// Classifies a status under the operation's pinned contract. Generated from the status /// table; the single authority the planes and the materializer switch on. @@ -51,7 +53,7 @@ protected static TPayload ReadBarePayload(string rawBody, JsonTypeInfo try { return JsonSerializer.Deserialize(rawBody, typeInfo) - ?? throw new OpenCodeTransportException("The opencode API returned a null success body."); + ?? throw new OpenCodeTransportException(NullSuccessBodyMessage); } catch (JsonException exception) { @@ -67,7 +69,7 @@ protected static TPayload ReadBarePayload(ReadOnlySpan utf8Body, try { return JsonSerializer.Deserialize(utf8Body, typeInfo) - ?? throw new OpenCodeTransportException("The opencode API returned a null success body."); + ?? throw new OpenCodeTransportException(NullSuccessBodyMessage); } catch (JsonException exception) { diff --git a/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs b/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs index 0c81a54d..313787f4 100644 --- a/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs +++ b/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs @@ -51,6 +51,10 @@ private static IEnumerable Cases() yield return new("ensure", "handoff-ticket", caller => ServiceDoors.AtServiceRequestAsync("ensure", "ticket", caller)); yield return new("ensure", "shutdown-fallback", caller => ServiceDoors.AtServiceRequestAsync("ensure", "fallback", caller)); yield return new("shutdown-persistent-pty", "shutdown-request", caller => ServiceDoors.AtServiceRequestAsync("shutdown-persistent-pty", "shutdown", caller)); + yield return new("resolve", "explicit-probe", caller => ServiceDoors.AtServiceRequestAsync("resolve", "probe", caller)); + yield return new("resolve", "service-config-store-read", ServiceDoors.AtResolveConfigStoreReadAsync); + yield return new("reconnect", "authenticated-probe", caller => ServiceDoors.AtServiceRequestAsync("reconnect", "probe", caller)); + yield return new("restart", "handoff-ticket", caller => ServiceDoors.AtServiceRequestAsync("restart", "ticket", caller)); // Since upstream v2.3.0 stop has no cancellable network wait: entry is its first cancellation point. // Mid-poll cancellation is proven by StopAsync_Should_Leave_The_Registration_When_Cancelled_After_The_Terminate_Signal. yield return new("stop", "pre-cancelled", ServiceDoors.AtStopPreCancelledAsync); @@ -627,6 +631,12 @@ _ when member.Is(typeof(OpenCodeServiceConfiguration), nameof(OpenCodeServiceCon typeof(OpenCodeServiceConfigOptions), typeof(CancellationToken)) => "service-config-read", _ when member.Is(typeof(OpenCodeServiceConfiguration), nameof(OpenCodeServiceConfiguration.GetOrCreatePasswordAsync), typeof(Task), typeof(OpenCodeServiceConfigOptions), typeof(CancellationToken)) => "service-config-write", + _ when member.Is(typeof(OpenCodeServer), nameof(OpenCodeServer.ResolveAsync), typeof(Task), + typeof(OpenCodeServerResolveOptions), typeof(CancellationToken)) => "resolve", + _ when member.Is(typeof(OpenCodeServerServiceOperations), nameof(OpenCodeServerServiceOperations.ReconnectAsync), typeof(Task), + typeof(CancellationToken)) => "reconnect", + _ when member.Is(typeof(OpenCodeServerServiceOperations), nameof(OpenCodeServerServiceOperations.RestartAsync), typeof(Task), + typeof(CancellationToken)) => "restart", _ when member.Is(typeof(PtyClient), nameof(PtyClient.ConnectAsync), typeof(Task), typeof(PtyConnectOptions), typeof(CancellationToken)) => "pty-connect", _ when member.Is(typeof(PersistentPtyClient), nameof(PersistentPtyClient.ConnectAsync), typeof(Task), diff --git a/tests/OpenCode.Sdk.Tests/Harness/EnsureServiceContext.cs b/tests/OpenCode.Sdk.Tests/Harness/EnsureServiceContext.cs index 9937e9c0..b0d080f3 100644 --- a/tests/OpenCode.Sdk.Tests/Harness/EnsureServiceContext.cs +++ b/tests/OpenCode.Sdk.Tests/Harness/EnsureServiceContext.cs @@ -26,6 +26,7 @@ internal sealed class EnsureServiceContext : IAsyncDisposable private const int LegacyWindowsReleasePort = 45278; private const int LogTailLines = 40; private static readonly TimeSpan ExitBound = TimeSpan.FromSeconds(15); + private static readonly TimeProvider Clock = TimeProvider.System; /// /// Bounds : three guarded ports and the caller's own port can be @@ -110,7 +111,7 @@ public Task EnsureAsync(OpenCodeServerEnsureOptions options, Can /// The non-owning handle Ensure returns. public async Task EnsureAsync(OpenCodeServerEnsureOptions options, ServiceTiming timing, CancellationToken cancellationToken) { - var server = await OpenCodeServer.EnsureWithSeamsAsync(options, timing, Ledger, TimeProvider.System, cancellationToken).ConfigureAwait(false); + var server = await OpenCodeServer.EnsureWithSeamsAsync(options, timing, Ledger, Clock, cancellationToken).ConfigureAwait(false); // The handle does not own the elected service; a service that fails the check is ended by // this context's teardown like every other one it recorded. @@ -118,6 +119,32 @@ public async Task EnsureAsync(OpenCodeServerEnsureOptions option return server; } + /// Runs the located election through the same owned contender ledger. + /// The captured service request. + /// The already located paths. + /// The captured environment overlay. + /// The caller's token. + /// The non-owning handle returned by the located core. + public async Task EnsureLocatedAsync( + EnsureRequest request, ServicePaths paths, ServiceConfigEnvironment snapshot, CancellationToken cancellationToken) + { + var server = await OpenCodeServer.EnsureLocatedWithSeamsAsync( + new ManagedServiceSnapshot(request, paths, snapshot), ServiceTiming.Default, Ledger, Clock, cancellationToken).ConfigureAwait(false); + Isolation.ConfirmHonored("The service the located election chose"); + return server; + } + + /// Reads the service's configuration directories at this context's isolated location. + /// The service to query. + /// The caller's token. + /// The normalized directory paths, in the server's order. + public async Task> ReadConfigDirectoriesAsync(OpenCodeServer server, CancellationToken cancellationToken) + { + using var client = server.CreateClient(options => options.Location = new LocationSelector { Directory = RunRoot }); + var response = await client.Config.GetConfigAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + return [.. response.Config.OfType().Select(directory => _fileSystem.Path.GetFullPath(directory.Path))]; + } + /// Reads every recorded contender still running, identified by this process. /// The caller's token. /// The live contenders. diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/OpenCodeServerEnsureLiveTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/OpenCodeServerEnsureLiveTests.cs index 7d2bf324..4621150e 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/OpenCodeServerEnsureLiveTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/OpenCodeServerEnsureLiveTests.cs @@ -1,7 +1,6 @@ using System.Text; using System.Text.Json.Nodes; using OpenCode.Sdk.Internal; -using OpenCode.Sdk.Models; using OpenCode.Sdk.Tests.Harness; using OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; using OpenCode.Sdk.Tests.Support; @@ -200,11 +199,7 @@ public async Task EnsureAsync_Should_Start_On_The_Callers_Config_Dir_And_Serve_T // The service config is selected before the saved environment is applied. await Assert.That(server.Endpoint.Port).IsEqualTo(context.Port); - using var client = server.CreateClient(options => - options.Location = new LocationSelector { Directory = context.RunRoot }); - var response = await client.Config.GetConfigAsync(cancellationToken: cancellationToken); - var directories = response.Config.OfType() - .Select(directory => _fileSystem.Path.GetFullPath(directory.Path)).ToList(); + var directories = await context.ReadConfigDirectoriesAsync(server, cancellationToken); // Application config discovery reads the saved environment after startup. await Assert.That(directories).Contains(_fileSystem.Path.GetFullPath(savedDirectory)); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/ServiceConfigEnvironmentReaderTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/ServiceConfigEnvironmentReaderTests.cs new file mode 100644 index 00000000..6d0d3dc4 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/ServiceConfigEnvironmentReaderTests.cs @@ -0,0 +1,55 @@ +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Hosting.BackgroundService.Registration; +using Testably.Abstractions.Testing; +using TUnit.Assertions.Enums; + +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Ensure; + +public sealed class ServiceConfigEnvironmentReaderTests +{ + [Test] + [Arguments("service-config-env-state-home.json", "A", "1")] + [Arguments("service-config-env-state-home-lowercase.json", "xdg_state_home", "/elsewhere/state")] + [Arguments("service-config-env-state-home-only.json", null, null)] + public async Task ReadAsync_Should_Drop_XDG_STATE_HOME(string fixture, string? key, string? value) + { + var fileSystem = new MockFileSystem(); + var path = fileSystem.Path.Combine(fileSystem.Path.GetTempPath(), "config.json"); + _ = fileSystem.Initialize().WithFile(path) + .Which(file => file.HasStringContent(new FixtureLoader().LoadJson("BackgroundService." + fixture))); + var paths = new ServicePaths("registration.json", path, [], null); + + var result = await new ServiceConfigEnvironmentReader(new TestablyServiceFileSystem(fileSystem)) + .ReadAsync(paths, CancellationToken.None); + + await Assert.That(result).IsNotNull(); + await Assert.That(result.Entries).IsNotNull(); + var expected = new Dictionary(StringComparer.Ordinal); + if (key is not null) + { + await Assert.That(value).IsNotNull(); + expected.Add(key, value); + } + await Assert.That(result.Entries).IsEquivalentTo(expected, CollectionOrdering.Matching); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task ReadAsync_Should_Return_An_Absent_Map_For_Invalid_Or_Missing_Config(bool invalid) + { + var fileSystem = new MockFileSystem(); + var path = fileSystem.Path.Combine(fileSystem.Path.GetTempPath(), "config.json"); + if (invalid) + { + _ = fileSystem.Initialize().WithFile(path).Which(file => file.HasStringContent(ServiceConfigData.Malformed)); + } + + var result = await new ServiceConfigEnvironmentReader(new TestablyServiceFileSystem(fileSystem)) + .ReadAsync(new ServicePaths("registration.json", path, [], null), CancellationToken.None); + + await Assert.That(result).IsNotNull(); + await Assert.That(result.Entries).IsNull(); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/ServiceEnsurerTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/ServiceEnsurerTests.cs index 4718cef1..ee94fa4d 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/ServiceEnsurerTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Ensure/ServiceEnsurerTests.cs @@ -14,7 +14,7 @@ namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Ensure; /// The Ensure door over substituted seams: no live process, no real registration, no socket. Each /// test states one upstream behavior (ensure in promise/service.ts, its contender rules /// in contenderPool in service-contender.ts, its decision in decide in -/// service-probe.ts, and server-connection.ts:74-84) and asserts what the seams observed +/// service-probe.ts, and server-connection.ts:89-99) and asserts what the seams observed /// — spawns, signals, handoff calls, OnStart, and the instants the test's own clock showed at /// each — never how many times the loop read the clock. /// @@ -1028,6 +1028,74 @@ public async Task EnsureAsync_Should_Rethrow_A_Token_Cancelled_Before_The_Call() .Throws(); } + [Test] + public async Task EnsureLocatedAsync_Should_Spawn_With_The_Snapshot_Overlay_Without_Reading_The_Config() + { + Seed(ConfigPath(), ServiceConfigData.DisabledWithEnvironment); + var fileSystem = RecordingFiles(); + var paths = new ServicePathResolver(_environment).Resolve(ServiceSelection.Snapshot((OpenCodeServerEnsureOptions?)null)); + var overlay = new ServiceConfigEnvironment(new Dictionary(StringComparer.Ordinal) { ["A"] = "snapshot" }); + ElectOnSpawn(Version); + + _ = await Ensurer(fileSystem: fileSystem).EnsureLocatedAsync(EnsureRequest.Snapshot(null), paths, overlay, CancellationToken.None); + + await Assert.That(_starts.Single().Environment["A"]).IsEqualTo("snapshot"); + _ = fileSystem.DidNotReceive().TryReadAllBytesAsync(ConfigPath(), Arg.Any()); + } + + [Test] + public async Task EnsureLocatedAsync_Should_Keep_An_Absent_Captured_Overlay() + { + Seed(ConfigPath(), ServiceConfigData.DisabledWithEnvironment); + var fileSystem = RecordingFiles(); + var paths = new ServicePathResolver(_environment).Resolve(ServiceSelection.Snapshot((OpenCodeServerEnsureOptions?)null)); + ElectOnSpawn(Version); + + _ = await Ensurer(fileSystem: fileSystem).EnsureLocatedAsync( + EnsureRequest.Snapshot(null), paths, new ServiceConfigEnvironment(Entries: null), CancellationToken.None); + + await Assert.That(_starts.Single().Environment).IsEmpty(); + _ = fileSystem.DidNotReceive().TryReadAllBytesAsync(ConfigPath(), Arg.Any()); + } + + private IServiceFileSystem RecordingFiles() + { + var adapter = new TestablyServiceFileSystem(_fileSystem); + var fileSystem = Substitute.For(); + fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()) + .Returns(call => adapter.TryReadAllBytesAsync(call.Arg(), call.Arg())); + return fileSystem; + } + + /// Characterizes the public path's per-spawn read, including a contender that exits without registering. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task EnsureAsync_Should_Read_The_Config_At_Every_Spawn(bool secondSpawn) + { + Seed(ConfigPath(), ServiceConfigData.DisabledWithEnvironment); + var changed = new System.Text.Json.Nodes.JsonObject + { + ["env"] = new System.Text.Json.Nodes.JsonObject { ["A"] = "2" }, + }; + var options = new OpenCodeServerEnsureOptions { OnStart = _ => Seed(ConfigPath(), changed.ToJsonString()) }; + _clock.GetUtcNow().Returns(_ => _time.GetUtcNow()); + ExitCleanlyUntilElected(secondSpawn ? 2 : 1, contender => + contender.TryGetFailure().Returns(_ => + { + changed["env"]!["A"] = "3"; + Seed(ConfigPath(), changed.ToJsonString()); + _time.Advance(TimeSpan.FromSeconds(2)); + return null; + })); + + _ = await Ensurer(Timing with { SpawnDelay = TimeSpan.FromSeconds(1) }).EnsureAsync(options, CancellationToken.None); + + string?[] expected = secondSpawn ? ["2", "3"] : ["2"]; + await Assert.That(_starts.Select(start => start.Environment["A"])) + .IsEquivalentTo(expected, CollectionOrdering.Matching); + } + private static OpenCodeServerEnsureOptions ReplacementOptions() => new() { ExpectedVersion = "2.0.4", VersionPolicy = OpenCodeServerVersionPolicy.Replace }; @@ -1055,10 +1123,10 @@ private async Task EnsureReplacementAsync() await Assert.That(_announced).IsEquivalentTo([(OpenCodeServerEnsureReason.VersionMismatch, (string?)Version)], CollectionOrdering.Any); } - private ServiceEnsurer Ensurer(ServiceTiming? timing = null) => + private ServiceEnsurer Ensurer(ServiceTiming? timing = null, IServiceFileSystem? fileSystem = null) => new( _environment, - new TestablyServiceFileSystem(_fileSystem), + fileSystem ?? new TestablyServiceFileSystem(_fileSystem), _probe, _spawner, _handoff, diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Registration/ServiceDisabledCheckTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Registration/ServiceDisabledCheckTests.cs new file mode 100644 index 00000000..230d2a79 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Registration/ServiceDisabledCheckTests.cs @@ -0,0 +1,105 @@ +using System.Text.Json.Nodes; +using NSubstitute; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Support; +using Testably.Abstractions.Testing; + +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Registration; + +public sealed class ServiceDisabledCheckTests +{ + private readonly MockFileSystem _fileSystem = new(); + private readonly IServiceEnvironment _environment = Substitute.For(); + + [Test] + public async Task IsDisabledAsync_Should_Migrate_The_Config_But_Not_The_Registration() + { + var selection = Select(); + var paths = Paths(selection); + await SeedAsync(paths.LegacyConfigFile!, ServiceConfigData.DisabledTrue); + await SeedAsync(paths.LegacyRegistrationFiles[0], ServiceRegistrationData.DevPrereleaseDotted); + + var disabled = await Check().IsDisabledAsync(selection, CancellationToken.None); + + await Assert.That(disabled).IsTrue(); + await Assert.That(await ReadAsync(paths.ConfigFile!)).IsEqualTo(ServiceConfigData.DisabledTrue); + await Assert.That(_fileSystem.Directory.GetFiles(_fileSystem.Path.GetDirectoryName(paths.RegistrationFile)!)) + .DoesNotContain(paths.RegistrationFile); + await Assert.That(await ReadAsync(paths.LegacyRegistrationFiles[0])) + .IsEqualTo(ServiceRegistrationData.DevPrereleaseDotted); + } + + [Test] + [Arguments(ServiceConfigData.DisabledFalse)] + [Arguments(ServiceConfigData.DisabledAsString)] + [Arguments(ServiceConfigData.DisabledNull)] + [Arguments(ServiceConfigData.Malformed)] + [Arguments(null)] + public async Task IsDisabledAsync_Should_Not_Disable_For_False_Absent_Or_Undecodable_Config(string? config) + { + var selection = Select(); + var paths = Paths(selection); + if (config is not null) + { + await SeedAsync(paths.ConfigFile!, config); + } + + await Assert.That(await Check().IsDisabledAsync(selection, CancellationToken.None)).IsFalse(); + } + + [Test] + public async Task IsDisabledAsync_Should_Read_A_Legacy_Remote_Shape() + { + var selection = Select(); + var paths = Paths(selection); + var legacy = new JsonObject { ["remote"] = true, ["disabled"] = true }; + await SeedAsync(paths.ConfigFile!, legacy.ToJsonString()); + + await Assert.That(await Check().IsDisabledAsync(selection, CancellationToken.None)).IsTrue(); + } + + [Test] + public async Task IsDisabledAsync_Should_Not_Read_A_Config_For_A_Direct_Registration_File() + { + var fileSystem = Substitute.For(); + var selection = ServiceSelection.Snapshot(new OpenCodeServerDiscoverOptions + { + RegistrationFilePath = _fileSystem.Path.Combine(_fileSystem.Path.GetTempPath(), "direct.json"), + }); + + await Assert.That(await new ServiceDisabledCheck(_environment, fileSystem, new ManualTimeProvider()) + .IsDisabledAsync(selection, CancellationToken.None)).IsFalse(); + await Assert.That(fileSystem.ReceivedCalls()).IsEmpty(); + await Assert.That(_environment.ReceivedCalls()).IsEmpty(); + } + + private ServiceDisabledCheck Check() => new(_environment, new TestablyServiceFileSystem(_fileSystem), new ManualTimeProvider()); + + private static ServiceSelection Select() => + ServiceSelection.Snapshot(new OpenCodeServerDiscoverOptions { Channel = "dev" }); + + private ServicePaths Paths(ServiceSelection selection) + { + _environment.GetEnvironmentVariable("XDG_STATE_HOME") + .Returns(_fileSystem.Path.Combine(_fileSystem.Path.GetTempPath(), "disabled-state")); + _environment.GetEnvironmentVariable("XDG_CONFIG_HOME") + .Returns(_fileSystem.Path.Combine(_fileSystem.Path.GetTempPath(), "disabled-config")); + return new ServicePathResolver(_environment).Resolve(selection); + } + + private async Task SeedAsync(string path, string content) + { + _ = _fileSystem.Directory.CreateDirectory(_fileSystem.Path.GetDirectoryName(path)!); + using var stream = _fileSystem.File.Create(path); + using var writer = new StreamWriter(stream); + await writer.WriteAsync(content); + } + + private async Task ReadAsync(string path) + { + using var stream = _fileSystem.File.OpenRead(path); + using var reader = new StreamReader(stream); + return await reader.ReadToEndAsync(); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Registration/ServiceMigrationTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Registration/ServiceMigrationTests.cs index 196d85d6..37b1c18d 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Registration/ServiceMigrationTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Registration/ServiceMigrationTests.cs @@ -322,6 +322,22 @@ public async Task ApplyAsync_Should_Rethrow_Caller_Cancellation() .Throws(); } + [Test] + public async Task ApplyConfigAsync_Should_Copy_Only_The_Config_Donor() + { + var paths = ChannelPaths(Channel); + Seed(paths.LegacyConfigFile!, ServiceConfigData.DisabledTrue); + Seed(paths.LegacyRegistrationFiles[0], ServiceRegistrationData.DevPrereleaseDotted); + + await Migration().ApplyConfigAsync(paths, CancellationToken.None); + + await Assert.That(_fileSystem.Directory.GetFiles(_fileSystem.Path.GetDirectoryName(paths.ConfigFile!)!)) + .IsEquivalentTo([paths.LegacyConfigFile!, paths.ConfigFile!], CollectionOrdering.Any); + await Assert.That(_fileSystem.Directory.GetFiles(_fileSystem.Path.GetDirectoryName(paths.RegistrationFile)!)) + .IsEquivalentTo([paths.LegacyRegistrationFiles[0]], CollectionOrdering.Matching); + await Assert.That(_fileSystem.File.ReadAllText(paths.ConfigFile!)).IsEqualTo(ServiceConfigData.DisabledTrue); + } + private ServiceMigration Migration() => new(new TestablyServiceFileSystem(_fileSystem)); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Stop/ServiceStopperTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Stop/ServiceStopperTests.cs index 5cae6926..70b45dd3 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Stop/ServiceStopperTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Stop/ServiceStopperTests.cs @@ -638,6 +638,21 @@ public async Task StopAsync_Should_Refuse_An_Undefined_Pty_Mode_Before_Reading() await Assert.That(_processControl.ReceivedCalls()).IsEmpty(); } + [Test] + public async Task StopLocatedAsync_Should_Not_Migrate_A_Legacy_Registration() + { + var selection = ServiceSelection.Snapshot(new OpenCodeServerStopOptions { Channel = "dev" }); + var paths = new ServicePathResolver(_environment).Resolve(selection); + Seed(paths.LegacyRegistrationFiles[0], ServiceRegistrationData.DevPrereleaseDotted); + + await Stopper().StopLocatedAsync(paths, mode: null, CancellationToken.None); + + await Assert.That(_fileSystem.Directory.GetFiles(_fileSystem.Path.GetDirectoryName(paths.RegistrationFile)!)) + .DoesNotContain(paths.RegistrationFile); + _ = _processControl.DidNotReceiveWithAnyArgs().TrySignal(default, default); + await Assert.That(ReadText(paths.LegacyRegistrationFiles[0])).IsEqualTo(ServiceRegistrationData.DevPrereleaseDotted); + } + private async Task AssertSharedRegistrationAbsentAsync() => await Assert.That(SharedRegistrationPath()).Satisfies(path => !_fileSystem.File.Exists(path)); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/ClientIdentityComposerTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/ClientIdentityComposerTests.cs new file mode 100644 index 00000000..797839f8 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/ClientIdentityComposerTests.cs @@ -0,0 +1,34 @@ +using System.Reflection; +using OpenCode.Sdk.Internal; + +namespace OpenCode.Sdk.Tests.Hosting; + +public sealed class ClientIdentityComposerTests +{ + [Test] + public async Task CreateClient_Should_Copy_Behavior_And_Leave_The_Delegate_Options_Identity_Unset() + { + var endpoint = new Uri("http://127.0.0.1:4096"); + var location = new LocationSelector { Directory = "/workspace" }; + OpenCodeClientOptions? observed = null; + using var client = ClientIdentityComposer.CreateClient(endpoint, "pw", options => + { + observed = options; + options.Location = location; + options.NetworkTimeout = TimeSpan.FromSeconds(7); + options.EventStreamIdleTimeout = TimeSpan.FromSeconds(9); + }); + var pipeline = (Pipeline)typeof(OpenCodeClient).GetField("_pipeline", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(client)!; + var exchange = typeof(Pipeline).GetField("_exchange", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(pipeline)!; + + await Assert.That(observed).IsNotNull(); + await Assert.That(observed.Endpoint).IsNull(); + await Assert.That(observed.Password).IsNull(); + await Assert.That(pipeline.Connection.EndpointBase).IsEqualTo(endpoint.AbsoluteUri.TrimEnd('/')); + await Assert.That(pipeline.Connection.Authorization?.ToString()).IsEqualTo("Basic b3BlbmNvZGU6cHc="); + await Assert.That(pipeline.Connection.Location).IsEqualTo(location); + await Assert.That(typeof(PipelineExchange).GetField("_clientNetworkTimeout", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(exchange)).IsEqualTo(TimeSpan.FromSeconds(7)); + await Assert.That(pipeline.IdleWindow).IsEqualTo(TimeSpan.FromSeconds(9)); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/ConnectionResolverTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ConnectionResolverTests.cs new file mode 100644 index 00000000..aedd933f --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ConnectionResolverTests.cs @@ -0,0 +1,470 @@ +using System.Net; +using System.Text.Json.Nodes; +using NSubstitute; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Hosting.BackgroundService.Registration; +using OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; +using OpenCode.Sdk.Tests.Support; +using Testably.Abstractions.Testing; +using TUnit.Assertions.Enums; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +public sealed class ConnectionResolverTests : IDisposable +{ + private static readonly Uri Endpoint = new("http://127.0.0.1:4096"); + private readonly MockFileSystem _mock = new(); + private readonly IServiceEnvironment _environment = Substitute.For(); + private readonly IServiceFileSystem _files = Substitute.For(); + private readonly IServerDoors _doors = Substitute.For(); + private readonly List _reads = []; + private readonly RecordingHttpHandler _handler; + private readonly HttpClient _transport; + private readonly ConnectionSeams _seams; + + public ConnectionResolverTests() + { + _environment.GetEnvironmentVariable("XDG_STATE_HOME").Returns(_mock.Path.Combine(_mock.Path.GetTempPath(), "resolve-state")); + _environment.GetEnvironmentVariable("XDG_CONFIG_HOME").Returns(_mock.Path.Combine(_mock.Path.GetTempPath(), "resolve-config")); + var adapter = new TestablyServiceFileSystem(_mock); + _files.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns(call => + { + var path = call.Arg(); + _reads.Add(path); + return adapter.TryReadAllBytesAsync(path, call.Arg()); + }); + _files.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(call => adapter.TryCreateExclusiveAsync(call.Arg(), call.Arg>(), call.Arg())); + _doors.StartAsync(Arg.Any(), Arg.Any()).Returns(_ => Shared(null)); + _doors.DiscoverLocatedAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns((OpenCodeServer?)null); + _doors.EnsureLocatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Shared("2.2.7")); + _handler = new RecordingHttpHandler(_ => InfoReply("2.3.0")); + _transport = new HttpClient(_handler, disposeHandler: false); + _seams = new ConnectionSeams(_doors, _environment, _files, _transport, new ManualTimeProvider()); + _environment.ClearReceivedCalls(); + } + + public void Dispose() + { + _transport.Dispose(); + _handler.Dispose(); + } + + [Test] + public async Task ResolveAsync_Should_Return_An_Explicit_Connection_When_The_Version_Matches() + { + var contexts = new List(); + await using var connection = await ResolveAsync(new() { Endpoint = Endpoint, Password = "pw", OnServerVersionMismatch = contexts.Add }); + + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Explicit); + await Assert.That(connection.Endpoint).IsEqualTo(Endpoint); + await Assert.That(connection.Username).IsEqualTo("opencode"); + await Assert.That(connection.Password).IsEqualTo("pw"); + await Assert.That(connection.ServerVersion).IsEqualTo("2.3.0"); + await Assert.That(connection.Server).IsNull(); + await Assert.That(connection.ServiceOperations).IsNull(); + await Assert.That(contexts).IsEmpty(); + await Assert.That(_doors.ReceivedCalls()).IsEmpty(); + await Assert.That(_environment.ReceivedCalls()).IsEmpty(); + await Assert.That(_files.ReceivedCalls()).IsEmpty(); + } + + [Test] + [Arguments("2.2.9")] + [Arguments("v2.3.0")] + [Arguments("2.3.0 ")] + [Arguments("2.3.00")] + public async Task ResolveAsync_Should_Report_A_Differing_Version_Once_And_Continue(string version) + { + using var handler = new RecordingHttpHandler(_ => InfoReply(version)); + using var transport = new HttpClient(handler); + var seams = _seams with { ProbeTransport = transport }; + var contexts = new List(); + var resolving = OpenCodeServer.ResolveWithSeamsAsync( + new() { Endpoint = Endpoint, OnServerVersionMismatch = contexts.Add }, seams, CancellationToken.None); + await Assert.That(resolving).ThrowsNothing(); + await using var connection = await resolving; + + await Assert.That(contexts.Count).IsEqualTo(1); + await Assert.That(contexts[0].Endpoint).IsEqualTo(Endpoint); + await Assert.That(contexts[0].ServerVersion).IsEqualTo(version); + await Assert.That(contexts[0].ClientVersion).IsEqualTo("2.3.0"); + await Assert.That(connection.ServerVersion).IsEqualTo(version); + await using var silent = await OpenCodeServer.ResolveWithSeamsAsync(new() { Endpoint = Endpoint }, seams, CancellationToken.None); + await Assert.That(silent.ServerVersion).IsEqualTo(version); + } + + [Test] + public async Task ResolveAsync_Should_Not_Validate_Unused_Service_Options_In_Explicit_Mode() + { + var resolving = ResolveAsync(new() + { + Endpoint = Endpoint, + Launch = new OpenCodeServerOptions(), + Service = new OpenCodeServerEnsureOptions { VersionPolicy = OpenCodeServerVersionPolicy.Replace }, + }); + await Assert.That(resolving).ThrowsNothing(); + await using var connection = await resolving; + + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Explicit); + await Assert.That(_doors.ReceivedCalls()).IsEmpty(); + await Assert.That(_environment.ReceivedCalls()).IsEmpty(); + } + + [Test] + [Arguments(true)] + [Arguments(false)] + public async Task ResolveAsync_Should_Start_A_Standalone_Server_Without_Reading_The_Config(bool autostart) + { + var launch = new OpenCodeServerOptions(); + await using var started = Shared(null); + _doors.StartAsync(launch, Arg.Any()).Returns(started); + await using var connection = await ResolveAsync(new() { Standalone = true, Launch = launch, Autostart = autostart }); + + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Standalone); + await Assert.That(connection.Server).IsSameReferenceAs(started); + await Assert.That(connection.ServerVersion).IsNull(); + await Assert.That(connection.ServiceOperations).IsNull(); + await AssertCallsAsync("StartAsync"); + _ = _doors.Received(1).StartAsync(launch, Arg.Any()); + await Assert.That(_reads).IsEmpty(); + await Assert.That(_environment.ReceivedCalls()).IsEmpty(); + } + + [Test] + [Arguments(true)] + [Arguments(false)] + public async Task ResolveAsync_Should_Start_A_Standalone_Server_When_The_Service_Is_Disabled(bool autostart) + { + var service = new OpenCodeServerEnsureOptions { Channel = "dev" }; + var paths = Paths(service); + Seed(paths.ConfigFile!, ServiceConfigData.DisabledAsTheCliWritesIt); + + await using var connection = await ResolveAsync(new() { Service = service, Autostart = autostart }); + + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Standalone); + await Assert.That(connection.ServerVersion).IsNull(); + await Assert.That(connection.ServiceOperations).IsNull(); + await AssertCallsAsync("StartAsync"); + await Assert.That(_reads).IsEquivalentTo([paths.ConfigFile!], CollectionOrdering.Matching); + } + + [Test] + public async Task ResolveAsync_Should_Repair_A_Legacy_Disabled_Config_Before_Starting_Standalone() + { + var scenario = new ServiceConfigScenario(); + var legacy = new JsonObject { ["disabled"] = true, ["remote"] = false }; + await scenario.SeedAsync(scenario.Paths.ConfigFile!, legacy.ToJsonString()); + var seams = _seams with { Environment = scenario.Environment, FileSystem = scenario.FileSystem, ProbeTime = scenario.Time }; + + await using var connection = await OpenCodeServer.ResolveWithSeamsAsync( + new() { Service = new OpenCodeServerEnsureOptions { Channel = "local" } }, seams, CancellationToken.None); + + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Standalone); + var repaired = JsonNode.Parse(await scenario.ReadTextAsync(scenario.Paths.ConfigFile!))!.AsObject(); + await Assert.That(repaired.Select(static member => member.Key)).IsEquivalentTo(["disabled"], CollectionOrdering.Matching); + await Assert.That(repaired["disabled"]!.GetValue()).IsTrue(); + await AssertCallsAsync("StartAsync"); + } + + [Test] + [Arguments("absent")] + [Arguments("unreadable")] + [Arguments("refused")] + public async Task ResolveAsync_Should_Treat_Absent_Unreadable_Or_Refused_Config_As_Empty_Without_Throwing(string shape) + { + var service = new OpenCodeServerEnsureOptions { Channel = "dev" }; + var config = shape switch + { + "unreadable" => ServiceConfigData.DisabledAsString, + "refused" => await RepeatedDisabledConfigAsync(), + _ => null, + }; + if (config is not null) + { + Seed(Paths(service).ConfigFile!, config); + } + + var resolving = ResolveAsync(new() { Service = service }); + await Assert.That(resolving).ThrowsNothing(); + await using var connection = await resolving; + + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Service); + await Assert.That(connection.ServerVersion).IsEqualTo("2.2.7"); + await Assert.That(connection.ServiceOperations).IsNotNull(); + await AssertCallsAsync("EnsureLocatedAsync"); + } + + [Test] + public async Task ResolveAsync_Should_Propagate_A_Failed_Standalone_Start_Unchanged() + { + var cause = new OpenCodeServerException("start failed"); + _doors.StartAsync(Arg.Any(), Arg.Any()).Returns(Task.FromException(cause)); + + var failure = await Assert.That(async () => _ = await ResolveAsync(new() { Standalone = true })).Throws(); + + await Assert.That(failure).IsSameReferenceAs(cause); + } + + [Test] + [Arguments(OpenCodeServerVersionPolicy.Ignore)] + [Arguments(OpenCodeServerVersionPolicy.Replace)] + [Arguments(OpenCodeServerVersionPolicy.Error)] + public async Task ResolveAsync_Should_Ensure_The_Snapshot_With_The_Callers_Request(OpenCodeServerVersionPolicy policy) + { + Action onStart = _ => throw new InvalidOperationException("door substitution never starts"); + var service = new OpenCodeServerEnsureOptions { ExpectedVersion = "2.2.0", VersionPolicy = policy, OnStart = onStart }; + + await using var connection = await ResolveAsync(new() { Service = service }); + + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Service); + await Assert.That(connection.ServiceOperations).IsNotNull(); + await AssertCallsAsync("EnsureLocatedAsync"); + var request = (EnsureRequest)_doors.ReceivedCalls().Single().GetArguments()[0]!; + await Assert.That(request.OnStart).IsSameReferenceAs(onStart); + await Assert.That(request.Policy).IsEqualTo(policy); + await Assert.That(request.Selection.ExpectedVersion).IsEqualTo("2.2.0"); + await Assert.That(request.LoopVersion).IsEqualTo(policy == OpenCodeServerVersionPolicy.Ignore ? null : "2.2.0"); + } + + [Test] + [Arguments(true)] + [Arguments(false)] + public async Task ResolveAsync_Should_Report_The_Registered_Version_In_Service_Mode(bool autostart) + { + _doors.DiscoverLocatedAsync(Arg.Any(), expectedVersion: null, Arg.Any()).Returns(_ => Shared("2.2.7")); + await using var connection = await ResolveAsync(new() { Autostart = autostart }); + + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Service); + await Assert.That(connection.ServerVersion).IsEqualTo("2.2.7"); + await Assert.That(connection.Server!.RegisteredVersion).IsEqualTo("2.2.7"); + } + + [Test] + public async Task ResolveAsync_Should_Not_Default_A_Service_Version_To_The_Pin() + { + _doors.EnsureLocatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Shared(null)); + await using var connection = await ResolveAsync(null); + + var request = (EnsureRequest)_doors.ReceivedCalls().Single().GetArguments()[0]!; + await Assert.That(request.LoopVersion).IsNull(); + await Assert.That(request.Selection.ExpectedVersion).IsNull(); + await Assert.That(connection.ServerVersion).IsNull(); + } + + [Test] + [Arguments(true)] + [Arguments(false)] + public async Task ResolveAsync_Should_Discover_Any_Version_When_Autostart_Is_False(bool hit) + { + _doors.DiscoverLocatedAsync(Arg.Any(), expectedVersion: null, Arg.Any()) + .Returns(_ => hit ? Shared("2.2.7") : null); + var resolving = ResolveAsync(new() + { + Autostart = false, + Service = new OpenCodeServerEnsureOptions { ExpectedVersion = "2.2.0", VersionPolicy = OpenCodeServerVersionPolicy.Error }, + }); + await Assert.That(resolving).ThrowsNothing(); + await using var connection = await resolving; + + await Assert.That(connection.Mode).IsEqualTo(hit ? OpenCodeServerConnectionMode.Service : OpenCodeServerConnectionMode.Standalone); + await Assert.That(connection.ServerVersion).IsEqualTo(hit ? "2.2.7" : null); + await Assert.That(connection.ServiceOperations is null).IsEqualTo(!hit); + if (hit) + { + await AssertCallsAsync("DiscoverLocatedAsync"); + } + else + { + await AssertCallsAsync("DiscoverLocatedAsync", "StartAsync"); + } + await Assert.That(_doors.ReceivedCalls().First().GetArguments()[1]).IsNull(); + } + + [Test] + public async Task ResolveAsync_Should_Copy_The_Service_Options_At_The_Call() + { + var command = new[] { "original", "serve" }; + var environment = new Dictionary(StringComparer.Ordinal) { ["A"] = "1" }; + Action onStart = _ => throw new InvalidOperationException("unused"); + var service = new OpenCodeServerEnsureOptions { Channel = "dev", Command = command, Environment = environment, OnStart = onStart }; + await using var connection = await ResolveAsync(new() { Service = service }); + var initial = _doors.ReceivedCalls().Single().GetArguments(); + service.Channel = "other"; + command[0] = "changed"; + environment["A"] = "2"; + service.OnStart = null; + + await using var reconnected = await connection.ServiceOperations!.ReconnectAsync(); + + var next = _doors.ReceivedCalls().Last().GetArguments(); + await Assert.That(((EnsureRequest)initial[0]!).OnStart).IsSameReferenceAs(onStart); + var request = (EnsureRequest)next[0]!; + await Assert.That(request.OnStart).IsNull(); + await Assert.That(request.Command).IsEquivalentTo(["original", "serve"], CollectionOrdering.Matching); + await Assert.That(request.Environment).IsEquivalentTo([new KeyValuePair("A", "1")], CollectionOrdering.Matching); + await Assert.That(next[1]).IsSameReferenceAs(initial[1]); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task ResolveAsync_Should_Read_The_Config_And_Donors_As_Upstream_Does(bool direct) + { + var service = direct + ? new OpenCodeServerEnsureOptions { RegistrationFilePath = _mock.Path.Combine(_mock.Path.GetTempPath(), "direct.json") } + : new OpenCodeServerEnsureOptions { Channel = "dev" }; + var paths = Paths(service); + await using var connection = await ResolveAsync(new() { Service = service }); + + string[] expected = direct ? [] : [paths.ConfigFile!, paths.LegacyConfigFile!, .. paths.LegacyRegistrationFiles, + paths.LegacyConfigFile!, paths.ConfigFile!]; + await Assert.That(_reads).IsEquivalentTo(expected, CollectionOrdering.Matching); + _reads.Clear(); + await using var reconnected = await connection.ServiceOperations!.ReconnectAsync(); + await using var restarted = await connection.ServiceOperations.RestartAsync(); + await Assert.That(_reads).IsEmpty(); + } + + [Test] + public async Task ReconnectAsync_Should_Use_The_Captured_Absent_Overlay() + { + var service = new OpenCodeServerEnsureOptions { Channel = "dev" }; + var paths = Paths(service); + await using var connection = await ResolveAsync(new() { Service = service }); + var captured = (ServiceConfigEnvironment)_doors.ReceivedCalls().Single().GetArguments()[2]!; + Seed(paths.ConfigFile!, new FixtureLoader().LoadJson("BackgroundService.service-config-env-state-home.json")); + _reads.Clear(); + + await using var reconnected = await connection.ServiceOperations!.ReconnectAsync(); + + await Assert.That(_doors.ReceivedCalls().Last().GetArguments()[2]).IsSameReferenceAs(captured); + await Assert.That(captured.Entries).IsNull(); + await Assert.That(_reads).IsEmpty(); + } + + [Test] + [Arguments("standalone")] + [Arguments("discovery-hit")] + [Arguments("discovery-miss")] + [Arguments("managed")] + public async Task ResolveAsync_Should_Forward_The_Callers_Token_To_Every_Door_And_Read(string arm) + { + using var caller = new CancellationTokenSource(); + var options = TokenOptions(arm); + // TokenOptions always supplies the selected channel. + var paths = Paths(options.Service!); + Seed(paths.ConfigFile!, new FixtureLoader().LoadJson("BackgroundService.service-config-env-state-home.json")); + _doors.DiscoverLocatedAsync(Arg.Any(), expectedVersion: null, Arg.Any()) + .Returns(_ => arm == "discovery-hit" ? Shared("2.2.7") : null); + + await using var connection = await OpenCodeServer.ResolveWithSeamsAsync(options, _seams, caller.Token); + + if (options.Standalone || arm == "discovery-miss") + { + _ = _doors.Received(1).StartAsync(options.Launch, caller.Token); + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Standalone); + } + if (!options.Standalone && !options.Autostart) + { + _ = _doors.Received(1).DiscoverLocatedAsync(Arg.Any(), expectedVersion: null, caller.Token); + } + if (!options.Standalone && options.Autostart) + { + _ = _doors.Received(1).EnsureLocatedAsync( + Arg.Any(), Arg.Any(), Arg.Any(), caller.Token); + } + if (options.Standalone) + { + await AssertCallsAsync("StartAsync"); + await Assert.That(_reads).IsEmpty(); + } + else + { + string[] expectedDoors = arm switch + { + "discovery-hit" => ["DiscoverLocatedAsync"], + "discovery-miss" => ["DiscoverLocatedAsync", "StartAsync"], + _ => ["EnsureLocatedAsync"], + }; + await AssertCallsAsync(expectedDoors); + await Assert.That(_reads).IsEquivalentTo( + [paths.ConfigFile!, .. paths.LegacyRegistrationFiles, paths.LegacyConfigFile!, paths.ConfigFile!], + CollectionOrdering.Matching); + } + foreach (var read in _files.ReceivedCalls().Where(call => + call.GetMethodInfo().Name == nameof(IServiceFileSystem.TryReadAllBytesAsync))) + { + await Assert.That(read.GetArguments()[1]).IsEqualTo(caller.Token); + } + } + + [Test] + [Arguments("standalone")] + [Arguments("discovery-hit")] + [Arguments("discovery-miss")] + [Arguments("managed")] + public async Task ResolveAsync_Should_Refuse_A_Cancelled_Call_Before_Any_Door_Or_Read(string arm) + { + using var caller = new CancellationTokenSource(); + await caller.CancelOnWorkerAsync(); + + var failure = await Assert.That(OpenCodeServer.ResolveWithSeamsAsync(TokenOptions(arm), _seams, caller.Token)) + .Throws(); + + await Assert.That(failure!.CancellationToken).IsEqualTo(caller.Token); + await Assert.That(_doors.ReceivedCalls()).IsEmpty(); + await Assert.That(_reads).IsEmpty(); + await Assert.That(_files.ReceivedCalls()).IsEmpty(); + await Assert.That(_environment.ReceivedCalls()).IsEmpty(); + } + + private static OpenCodeServerResolveOptions TokenOptions(string arm) => new() + { + Standalone = arm == "standalone", + Autostart = arm is "standalone" or "managed", + Launch = new OpenCodeServerOptions(), + Service = new OpenCodeServerEnsureOptions { Channel = "dev" }, + }; + + private Task ResolveAsync(OpenCodeServerResolveOptions? options) => + OpenCodeServer.ResolveWithSeamsAsync(options, _seams, CancellationToken.None); + + private static HttpResponseMessage InfoReply(string version) + { + // The canonical info fixture is a valid object; only its version varies here. + var document = JsonNode.Parse(WireBodyData.InfoOk)!; + document["version"] = version; + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(document.ToJsonString(), System.Text.Encoding.UTF8, "application/json"), + }; + } + + private static OpenCodeServer Shared(string? version) => new(Endpoint, "pw", 42, version); + + private static async Task RepeatedDisabledConfigAsync() + { + var bytes = new System.Buffers.ArrayBufferWriter(); + await using var writer = new System.Text.Json.Utf8JsonWriter(bytes); + writer.WriteStartObject(); + writer.WriteBoolean("disabled", false); + writer.WriteBoolean("disabled", true); + writer.WriteEndObject(); + await writer.FlushAsync(); + return System.Text.Encoding.UTF8.GetString(bytes.WrittenMemory.ToArray()); + } + + private ServicePaths Paths(OpenCodeServerEnsureOptions service) => + new ServicePathResolver(_environment).Resolve(EnsureRequest.Snapshot(service).Selection); + + private void Seed(string path, string content) => + _ = _mock.Initialize().WithFile(path).Which(file => file.HasStringContent(content)); + + private async Task AssertCallsAsync(params string[] expected) => + await Assert.That(_doors.ReceivedCalls().Select(call => call.GetMethodInfo().Name)).IsEquivalentTo(expected, CollectionOrdering.Matching); +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/ExplicitProbeFailureClassifierTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ExplicitProbeFailureClassifierTests.cs new file mode 100644 index 00000000..61e9c26c --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ExplicitProbeFailureClassifierTests.cs @@ -0,0 +1,77 @@ +using System.Text.Json; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Models; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +public sealed class ExplicitProbeFailureClassifierTests +{ + private static readonly Uri Endpoint = new("http://127.0.0.1:4096"); + + [Test] + [Arguments(false, "Server at http://127.0.0.1:4096/ requires a password; set OpenCodeServerResolveOptions.Password")] + [Arguments(true, "Server at http://127.0.0.1:4096/ rejected the password")] + public async Task Map_Should_Use_The_Password_Dependent_Message_For_A_Tagged_Refusal(bool hasPassword, string expected) + { + var cause = new OpenCodeApiException("refused", 400, new UnauthorizedError { Message = "password required" }, rawBody: null); + + var mapped = ExplicitProbeFailureClassifier.Map(cause, Endpoint, hasPassword, default, default); + + await Assert.That(mapped).IsTypeOf(); + await Assert.That(mapped.Message).IsEqualTo(expected); + await Assert.That(mapped.InnerException).IsSameReferenceAs(cause); + } + + [Test] + [Arguments(401)] + [Arguments(500)] + public async Task Map_Should_Report_An_Incompatible_Health_Response_For_An_Untagged_Status(int status) + { + var cause = new OpenCodeApiException("unexpected response", status, error: null, rawBody: null); + + var mapped = ExplicitProbeFailureClassifier.Map(cause, Endpoint, hasPassword: false, default, default); + + await Assert.That(mapped.Message).IsEqualTo( + "Server at http://127.0.0.1:4096/ did not provide a compatible V2 health response: unexpected response"); + await Assert.That(mapped.InnerException).IsSameReferenceAs(cause); + } + + [Test] + public async Task Map_Should_Report_An_Unreachable_Server_For_A_Transport_Fault() + { + var cause = new OpenCodeTransportException("send failed", new HttpRequestException("connection refused")); + + var mapped = ExplicitProbeFailureClassifier.Map(cause, Endpoint, hasPassword: false, default, default); + + await Assert.That(mapped.Message).IsEqualTo("Could not reach server at http://127.0.0.1:4096/: connection refused"); + await Assert.That(mapped.InnerException).IsSameReferenceAs(cause); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Map_Should_Report_An_Incompatible_Health_Response_For_A_Malformed_Body(bool nullBody) + { + var cause = nullBody + ? new OpenCodeTransportException(ResponseAdapter.NullSuccessBodyMessage) + : new OpenCodeTransportException("malformed body", new JsonException("bad JSON")); + + var mapped = ExplicitProbeFailureClassifier.Map(cause, Endpoint, hasPassword: false, default, default); + + await Assert.That(mapped.Message).IsEqualTo("Server at http://127.0.0.1:4096/ did not provide a compatible V2 health response: " + cause.Message); + await Assert.That(mapped.InnerException).IsSameReferenceAs(cause); + } + + [Test] + public async Task Map_Should_Prefer_The_Callers_Cancellation_When_The_Bound_Also_Cancelled() + { + var caller = new CancellationToken(canceled: true); + var bound = new CancellationToken(canceled: true); + var cause = new OperationCanceledException("deadline", bound); + + var mapped = ExplicitProbeFailureClassifier.Map(cause, Endpoint, hasPassword: false, caller, bound); + + await Assert.That(mapped).IsTypeOf(); + await Assert.That(((OperationCanceledException)mapped).CancellationToken).IsEqualTo(caller); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/ExplicitServerProbeTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ExplicitServerProbeTests.cs new file mode 100644 index 00000000..a98074ab --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ExplicitServerProbeTests.cs @@ -0,0 +1,138 @@ +using System.Net; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Support; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +public sealed class ExplicitServerProbeTests +{ + private static readonly Uri Endpoint = new("http://127.0.0.1:4096"); + + [Test] + [Arguments(null, null)] + [Arguments("pw", "Basic b3BlbmNvZGU6cHc=")] + [Arguments("", "Basic b3BlbmNvZGU6")] + public async Task GetInfoAsync_Should_Send_Basic_Auth_Only_When_A_Password_Is_Set(string? password, string? expected) + { + using var handler = new RecordingHttpHandler(_ => Reply()); + using var transport = new HttpClient(handler); + + var info = await new ExplicitServerProbe(transport, new ManualTimeProvider()) + .GetInfoAsync(Endpoint, password, CancellationToken.None); + + await Assert.That(info.Version).IsEqualTo("0.0.0-test"); + await Assert.That(handler.Requests.Count).IsEqualTo(1); + await Assert.That(handler.Requests[0].Authorization).IsEqualTo(expected); + await Assert.That(handler.Requests[0].RequestUri).IsEqualTo(new Uri("http://127.0.0.1:4096/api/info")); + await Assert.That(handler.IsDisposed).IsFalse(); + } + + [Test] + public async Task ResolveAsync_Should_Report_An_Unreachable_Server_When_The_Five_Second_Bound_Expires() => + await AssertHeldProbeAsync(cancelCaller: false, cancelBound: true); + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task ResolveAsync_Should_Propagate_The_Callers_Cancellation_Unwrapped(bool alsoCancelBound) => + await AssertHeldProbeAsync(cancelCaller: true, cancelBound: alsoCancelBound); + + [Test] + public async Task GetInfoAsync_Should_Report_An_Undeclared_Success_As_An_Incompatible_Response() + { + using var handler = new RecordingHttpHandler(_ => new HttpResponseMessage(HttpStatusCode.NoContent)); + using var transport = new HttpClient(handler); + + await AssertProbeFailureAsync(new ExplicitServerProbe(transport, new ManualTimeProvider()), + "Server at http://127.0.0.1:4096/ did not provide a compatible V2 health response: The opencode API returned undeclared success status 204."); + await Assert.That(handler.Requests.Count).IsEqualTo(1); + } + + [Test] + [Arguments("null", ResponseAdapter.NullSuccessBodyMessage)] + [Arguments("{", "The opencode API returned a malformed success body.")] + public async Task GetInfoAsync_Should_Classify_The_Actual_Decoder_Failure(string body, string expected) + { + using var handler = new RecordingHttpHandler(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(body, System.Text.Encoding.UTF8, "application/json"), + }); + using var transport = new HttpClient(handler); + + await AssertProbeFailureAsync(new ExplicitServerProbe(transport, new ManualTimeProvider()), + "Server at http://127.0.0.1:4096/ did not provide a compatible V2 health response: " + expected); + await Assert.That(handler.Requests.Count).IsEqualTo(1); + } + + private static async Task AssertProbeFailureAsync(ExplicitServerProbe probe, string expected) + { + var failure = await Assert.That(probe.GetInfoAsync(Endpoint, password: null, CancellationToken.None)) + .Throws(); + await Assert.That(failure!.Message).IsEqualTo(expected); + await Assert.That(failure.InnerException).IsTypeOf(); + } + + private static async Task AssertHeldProbeAsync(bool cancelCaller, bool cancelBound) + { + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var release = new ManualResetEventSlim(); + using var handler = new RecordingHttpHandler(_ => + { + entered.SetResult(); + release.Wait(); + return Reply(); + }); + using var transport = new HttpClient(handler); + using var caller = new CancellationTokenSource(); + var time = new ManualTimeProvider(); + var boundInstant = time.GetUtcNow() + TimeSpan.FromSeconds(5); + var probe = new ExplicitServerProbe(transport, time); + // RecordingHttpHandler's responder is synchronous: only this dedicated thread waits for release. + var pending = Task.Factory.StartNew(() => probe.GetInfoAsync(Endpoint, password: null, caller.Token), + CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap(); + try + { + // A zero-length mutant can finish before entering the handler; that is an early + // completion verdict, not a hang while waiting for a request that will never arrive. + _ = await Task.WhenAny(entered.Task, pending).WaitAsync(HangGuard.Bound); + await Assert.That(pending.IsCompleted).IsFalse(); + time.Advance(TimeSpan.FromMilliseconds(4_999)); + await Assert.That(handler.CancellationTokens[0].IsCancellationRequested).IsFalse(); + await Assert.That(pending.IsCompleted).IsFalse(); + if (cancelCaller) + { + await caller.CancelOnWorkerAsync(); + } + if (cancelBound) + { + time.Advance(TimeSpan.FromMilliseconds(1)); + await Assert.That(handler.CancellationTokens[0].IsCancellationRequested).IsTrue(); + } + release.Set(); + + if (cancelCaller) + { + var failure = await Assert.That(pending).Throws(); + await Assert.That(failure!.CancellationToken).IsEqualTo(caller.Token); + } + else + { + var failure = await Assert.That(pending).Throws(); + await Assert.That(failure!.InnerException).IsTypeOf(); + await Assert.That(failure.Message).IsEqualTo( + "Could not reach server at http://127.0.0.1:4096/: " + failure.InnerException!.Message); + } + } + finally + { + release.Set(); + await new OperationDeadlineScenario().DrainAsync(pending); + await Assert.That(time.ArmedIn(boundInstant - time.GetUtcNow())).IsEqualTo(0); + } + } + + private static HttpResponseMessage Reply() => new(HttpStatusCode.OK) + { + Content = new StringContent(WireBodyData.InfoOk, System.Text.Encoding.UTF8, "application/json"), + }; +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/ManagedServiceSnapshotTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ManagedServiceSnapshotTests.cs new file mode 100644 index 00000000..5a691e8b --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ManagedServiceSnapshotTests.cs @@ -0,0 +1,31 @@ +using OpenCode.Sdk.Internal; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +public sealed class ManagedServiceSnapshotTests +{ + [Test] + public async Task ReconnectRequest_Should_Keep_The_Captured_Inputs_Without_Policy_Or_OnStart() + { + var request = EnsureRequest.Snapshot(new OpenCodeServerEnsureOptions + { + ExpectedVersion = "2.2.7", + VersionPolicy = OpenCodeServerVersionPolicy.Replace, + OnStart = _ => throw new InvalidOperationException("must not forward"), + }); + var paths = new ServicePaths("registration.json", null, [], null); + var overlay = new ServiceConfigEnvironment(Entries: null); + var snapshot = new ManagedServiceSnapshot(request, paths, overlay); + + var reconnect = snapshot.ReconnectRequest; + + await Assert.That(snapshot.Paths).IsSameReferenceAs(paths); + await Assert.That(snapshot.Overlay).IsSameReferenceAs(overlay); + await Assert.That(reconnect.Selection).IsSameReferenceAs(request.Selection); + await Assert.That(reconnect.Command).IsSameReferenceAs(request.Command); + await Assert.That(reconnect.Environment).IsSameReferenceAs(request.Environment); + await Assert.That(reconnect.Policy).IsEqualTo(OpenCodeServerVersionPolicy.Ignore); + await Assert.That(reconnect.LoopVersion).IsNull(); + await Assert.That(reconnect.OnStart).IsNull(); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerConnectionTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerConnectionTests.cs new file mode 100644 index 00000000..adf96058 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerConnectionTests.cs @@ -0,0 +1,87 @@ +using NSubstitute; +using OpenCode.Sdk.Internal; +using TUnit.Assertions.Enums; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +public sealed class OpenCodeServerConnectionTests +{ + private static readonly Uri Endpoint = new("http://127.0.0.1:4096"); + + [Test] + public async Task DisposeAsync_Should_Quietly_Dispose_A_Mock_Connection() + { + var mock = Substitute.ForPartsOf(); + + await Assert.That(async () => await mock.DisposeAsync()).ThrowsNothing(); + await Assert.That(async () => await mock.DisposeAsync()).ThrowsNothing(); + } + + [Test] + [Arguments(OpenCodeServerConnectionMode.Explicit)] + [Arguments(OpenCodeServerConnectionMode.Standalone)] + [Arguments(OpenCodeServerConnectionMode.Service)] + [Arguments(OpenCodeServerConnectionMode.Explicit, "Username")] + [Arguments(OpenCodeServerConnectionMode.Standalone, "Password")] + [Arguments(OpenCodeServerConnectionMode.Service, "Endpoint")] + public async Task CreateClient_Should_Refuse_Identity_Members_In_Every_Mode( + OpenCodeServerConnectionMode mode, string member = "Endpoint") + { + await using var server = new OpenCodeServer(Endpoint, "pw"); + await using var connection = Connection(mode, server); + + var failure = await Assert.That(() => connection.CreateClient(options => + { + switch (member) + { + case "Endpoint": options.Endpoint = Endpoint; break; + case "Username": options.Username = "other"; break; + case "Password": options.Password = "other"; break; + } + })).Throws(); + + await Assert.That(failure!.Message).IsEqualTo( + "CreateClient owns the connection identity: leave Endpoint, Username, and Password unset — the started server supplies them. Configure behavior members such as Location only."); + } + + [Test] + [Arguments(OpenCodeServerConnectionMode.Explicit)] + [Arguments(OpenCodeServerConnectionMode.Standalone)] + [Arguments(OpenCodeServerConnectionMode.Service)] + public async Task DisposeAsync_Should_End_Only_An_Owned_Standalone_Server(OpenCodeServerConnectionMode mode) + { + var server = Substitute.For(); + server.Endpoint.Returns(Endpoint); + server.Password.Returns("pw"); + var connection = Connection(mode, server); + + await connection.DisposeAsync(); + await connection.DisposeAsync(); + + string[] expected = mode == OpenCodeServerConnectionMode.Standalone ? ["DisposeAsync"] : []; + await Assert.That(server.ReceivedCalls().Where(call => call.GetMethodInfo().Name == "DisposeAsync") + .Select(call => call.GetMethodInfo().Name)) + .IsEquivalentTo(expected, CollectionOrdering.Matching); + } + + [Test] + public async Task Members_Should_Throw_The_Instructive_Mock_Failure_When_Not_Overridden() + { + var mock = Substitute.ForPartsOf(); + string[] members = ["Mode", "Endpoint", "Username", "Password", "ServerVersion", "Server", "ServiceOperations"]; + foreach (var member in members) + { + var property = typeof(OpenCodeServerConnection).GetProperty(member)!; + var failure = await Assert.That(() => property.GetValue(mock)).Throws(); + await Assert.That(failure!.InnerException!.Message).IsEqualTo(MockSeam.CreateError(nameof(OpenCodeServerConnection), member).Message); + } + } + + private static OpenCodeServerConnection Connection(OpenCodeServerConnectionMode mode, OpenCodeServer server) => mode switch + { + OpenCodeServerConnectionMode.Explicit => new OpenCodeServerConnection(Endpoint, "pw", "2.3.0"), + OpenCodeServerConnectionMode.Standalone => new OpenCodeServerConnection(server, serverVersion: null), + OpenCodeServerConnectionMode.Service => new OpenCodeServerConnection(server, "2.2.7", Substitute.For()), + _ => throw new ArgumentOutOfRangeException(nameof(mode)), + }; +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerResolveLiveTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerResolveLiveTests.cs new file mode 100644 index 00000000..733daed7 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerResolveLiveTests.cs @@ -0,0 +1,91 @@ +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Support; +using Testably.Abstractions; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +[ClassDataSource(Shared = SharedType.PerTestSession)] +[NotInParallel(ParallelConstraintKeys.ServerProcess)] +public sealed class OpenCodeServerResolveLiveTests(PinnedOpenCodeServerFixture fixture) +{ + [Test] + [Timeout(120_000)] + public async Task ResolveAsync_Should_Reach_The_Pinned_Server_Explicitly(CancellationToken cancellationToken) + { + using var plain = fixture.CreateClient(); + var independent = await plain.Server.GetInfoAsync(cancellationToken: cancellationToken); + var external = ExternalServerEndpoint.FromEnvironment(); + var password = fixture.IsExternal ? external?.Password : fixture.Server.Password; + var sourceRun = !fixture.IsExternal && PinnedServerCommandOverride.FromEnvironment() is null; + var expected = sourceRun ? "local" : independent.ServerInfo.Version; + var arm = sourceRun ? "source-run" : "installed-command"; + if (fixture.IsExternal) + { + arm = "external"; + } + Console.WriteLine($"resolver-live: arm={arm}; version={expected}"); + var contexts = new List(); + await using var connection = await OpenCodeServer.ResolveAsync(new() + { + Endpoint = fixture.Endpoint, + Password = password, + OnServerVersionMismatch = contexts.Add, + }, cancellationToken); + + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Explicit); + await Assert.That(connection.ServerVersion).IsEqualTo(expected); + await Assert.That(contexts.Count).IsEqualTo(string.Equals(expected, "2.3.0", StringComparison.Ordinal) ? 0 : 1); + if (contexts.Count != 0) + { + await Assert.That(contexts[0].Endpoint).IsEqualTo(fixture.Endpoint); + await Assert.That(contexts[0].ServerVersion).IsEqualTo(expected); + await Assert.That(contexts[0].ClientVersion).IsEqualTo("2.3.0"); + } + using var client = connection.CreateClient(); + var reached = await client.Server.GetInfoAsync(cancellationToken: cancellationToken); + await Assert.That(reached.ServerInfo.Pid).IsEqualTo(independent.ServerInfo.Pid); + await Assert.That(reached.ServerInfo.Version).IsEqualTo(expected); + var failure = await Assert.That(async () => _ = await OpenCodeServer.ResolveAsync(new() + { + Endpoint = fixture.Endpoint, + Password = "incorrect-" + Guid.NewGuid().ToString("N"), + }, cancellationToken)).Throws(); + await Assert.That(failure!.Message).IsEqualTo($"Server at {fixture.Endpoint} rejected the password"); + } + + [Test] + [Timeout(120_000)] + public async Task ResolveAsync_Should_Start_And_End_A_Standalone_Server(CancellationToken cancellationToken) + { + var files = new RealFileSystem(); + using var root = new TestRunRoot(files); + var isolation = ServerIsolation.For(files, root.Path); + var command = new PinnedServerCommand(files); + await using var connection = await OpenCodeServer.ResolveAsync(new() + { + Standalone = true, + Launch = new OpenCodeServerOptions + { + Command = command.Resolve(), + WorkingDirectory = command.WorkingDirectory, + Environment = isolation.Environment, + }, + }, cancellationToken); + isolation.ConfirmHonored("The resolver's standalone server"); + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Standalone); + await Assert.That(connection.Server).IsNotNull(); + await Assert.That(connection.Server.OwnsProcess).IsTrue(); + await Assert.That(connection.ServerVersion).IsNull(); + using var client = connection.CreateClient(); + var info = await client.Server.GetInfoAsync(cancellationToken: cancellationToken); + await Assert.That(info.ServerInfo.Pid).IsEqualTo(connection.Server.ProcessId); + + await connection.DisposeAsync(); + + var exit = await ChildExitObservation.WithinAsync(connection.Server, TimeSpan.FromSeconds(30)); + await Assert.That(exit).IsNotEqualTo(ChildExitStatus.Unknown).Because(exit.Describe()); + await Assert.That(await ProcessObservation.ObserveExitWithinAsync( + connection.Server.ProcessId, TimeSpan.FromSeconds(30), cancellationToken)).IsTrue(); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerResolveServiceLiveTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerResolveServiceLiveTests.cs new file mode 100644 index 00000000..d5462cf8 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerResolveServiceLiveTests.cs @@ -0,0 +1,142 @@ +using System.Text; +using System.Text.Json.Nodes; +using NSubstitute; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Models; +using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.PersistentPtys; +using Testably.Abstractions; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +[NotInParallel] +[Category(TestCategories.ServiceElection)] +public sealed class OpenCodeServerResolveServiceLiveTests +{ + [Test] + [Timeout(180_000)] + public async Task ServiceOperations_Should_Reconnect_To_The_Same_Daemon_And_Restart_A_New_One(CancellationToken cancellationToken) + { + await using var context = await EnsureServiceContext.CreateAsync(cancellationToken); + var service = new OpenCodeServerEnsureOptions + { + RegistrationFilePath = context.RegistrationFile, + Command = [context.ShimPath, "serve", "--service"], + Environment = context.Environment, + }; + var doors = Substitute.For(); + var actual = new ServerDoors(); + // Only contender ownership is injected: the actual located core runs through the ledger, + // and production discovery and Stop retain their own clock roots and handoff behavior. + doors.EnsureLocatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(call => context.EnsureLocatedAsync(call.Arg(), call.Arg(), + call.Arg(), call.Arg())); + doors.DiscoverLocatedAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(call => actual.DiscoverLocatedAsync(call.Arg(), call.ArgAt(1), call.Arg())); + doors.StopLocatedAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(call => actual.StopLocatedAsync(call.Arg(), call.Arg(), call.Arg())); + await using var connection = await OpenCodeServer.ResolveWithSeamsAsync(new() { Service = service }, + new ConnectionSeams(doors, new ServiceEnvironment(), new ServiceFileSystem()), cancellationToken); + await Assert.That(connection.Mode).IsEqualTo(OpenCodeServerConnectionMode.Service); + await Assert.That(connection.Server).IsNotNull(); + await Assert.That(connection.ServerVersion).IsEqualTo("local"); + await Assert.That(connection.Server.RegisteredVersion).IsEqualTo("local"); + await Assert.That(connection.ServiceOperations).IsNotNull(); + // Keep an incorrect discovery miss safe and observable as a valid standalone result. + doors.StartAsync(Arg.Any(), Arg.Any()) + .Returns(_ => new OpenCodeServer(connection.Endpoint, connection.Password, connection.Server.ProcessId, version: null)); + await using var discovered = await OpenCodeServer.ResolveWithSeamsAsync(new() + { + Autostart = false, + Service = new OpenCodeServerEnsureOptions + { + RegistrationFilePath = context.RegistrationFile, + ExpectedVersion = "not-local", + VersionPolicy = OpenCodeServerVersionPolicy.Error, + }, + }, new ConnectionSeams(doors, new ServiceEnvironment(), new ServiceFileSystem()), cancellationToken); + await Assert.That(discovered.Mode).IsEqualTo(OpenCodeServerConnectionMode.Service); + await Assert.That(discovered.ServerVersion).IsEqualTo("local"); + await Assert.That(discovered.Server).IsNotNull(); + await Assert.That(discovered.Server.ProcessId).IsEqualTo(connection.Server.ProcessId); + _ = doors.DidNotReceiveWithAnyArgs().StartAsync(options: null, cancellationToken); + await using var reconnected = await connection.ServiceOperations.ReconnectAsync(cancellationToken); + await Assert.That(reconnected.ProcessId).IsEqualTo(connection.Server.ProcessId); + using var client = connection.CreateClient(options => options.Location = new LocationSelector { Directory = context.RunRoot }); + var session = await client.Sessions.CreateSessionAsync(new SessionCreateRequest { Title = "resolver restart" }, cancellationToken: cancellationToken); + var created = await client.PersistentPtys.CreatePersistentPtyAsync(session.Session.Id, + PersistentPtyLiveTests.CreateRequest(), OpenCodeRequestOptions.NoThrow, cancellationToken); + if (PersistentPtyDaemonGate.DaemonExpected) + { + await Assert.That(created.IsError).IsFalse(); + Console.WriteLine($"resolver-service-live: daemon-present; terminal={created.PersistentPty.Id}"); + } + else + { + await Assert.That(created.Status).IsEqualTo(503); + Console.WriteLine($"resolver-service-live: daemon-absent; status={created.Status.ToString(System.Globalization.CultureInfo.InvariantCulture)}"); + await Assert.That(created.Error).IsTypeOf(); + await Assert.That(((ServiceUnavailableError)created.Error!).Service).IsEqualTo("opencode-pty"); + } + + await using var restarted = await connection.ServiceOperations.RestartAsync(cancellationToken); + + await Assert.That(restarted.ProcessId).IsNotEqualTo(reconnected.ProcessId); + await Assert.That(restarted.RegisteredVersion).IsEqualTo("local"); + await Assert.That(connection.ServerVersion).IsEqualTo("local"); + using var after = restarted.CreateClient(options => options.Location = new LocationSelector { Directory = context.RunRoot }); + var info = await after.Server.GetInfoAsync(cancellationToken: cancellationToken); + await Assert.That(info.ServerInfo.Pid).IsEqualTo(restarted.ProcessId); + if (PersistentPtyDaemonGate.DaemonExpected) + { + var listed = await after.PersistentPtys.ListPersistentPtysAsync(session.Session.Id, cancellationToken: cancellationToken); + await Assert.That(listed.PersistentPtys.Select(terminal => terminal.Id)).Contains(created.PersistentPty.Id); + } + } + + [Test] + [Timeout(180_000)] + public async Task EnsureLocatedWithSeamsAsync_Should_Spawn_With_The_Captured_Config_Directory(CancellationToken cancellationToken) + { + await using var context = await EnsureServiceContext.CreateAsync(cancellationToken); + var files = new RealFileSystem(); + var captured = files.Path.Combine(context.RunRoot, "captured-config"); + var changed = files.Path.Combine(context.RunRoot, "changed-config"); + foreach (var directory in new[] { captured, changed }) + { + await SeedConfigAsync(files, files.Path.Combine(directory, "service-local.json"), + new JsonObject { ["port"] = context.Port }, cancellationToken); + } + var configFile = files.Path.Combine(context.Environment["OPENCODE_CONFIG_DIR"], "service-local.json"); + await SeedConfigAsync(files, configFile, new JsonObject + { + ["env"] = new JsonObject { ["OPENCODE_CONFIG_DIR"] = changed }, + }, cancellationToken); + var request = EnsureRequest.Snapshot(new OpenCodeServerEnsureOptions + { + RegistrationFilePath = context.RegistrationFile, + Command = [context.ShimPath, "serve", "--service"], + Environment = context.Environment.Where(entry => !string.Equals(entry.Key, "OPENCODE_CONFIG_DIR", StringComparison.Ordinal)) + .ToDictionary(entry => entry.Key, entry => entry.Value, StringComparer.Ordinal), + }); + var paths = new ServicePaths(context.RegistrationFile, configFile, [], null); + var overlay = new ServiceConfigEnvironment(new Dictionary(StringComparer.Ordinal) + { + ["OPENCODE_CONFIG_DIR"] = captured, + }); + + await using var server = await context.EnsureLocatedAsync(request, paths, overlay, cancellationToken); + var directories = await context.ReadConfigDirectoriesAsync(server, cancellationToken); + + await Assert.That(directories).Contains(files.Path.GetFullPath(captured)); + await Assert.That(directories).DoesNotContain(files.Path.GetFullPath(changed)); + await Assert.That(server.RegisteredVersion).IsEqualTo("local"); + } + + private static async Task SeedConfigAsync(RealFileSystem files, string path, JsonObject config, CancellationToken cancellationToken) + { + _ = files.Directory.CreateDirectory(files.Path.GetDirectoryName(path)!); + using var stream = files.FileStream.New(path, FileMode.Create, FileAccess.Write, FileShare.None); + await stream.WriteAsync(Encoding.UTF8.GetBytes(config.ToJsonString()), cancellationToken); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerServiceOperationsTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerServiceOperationsTests.cs new file mode 100644 index 00000000..e48b4e31 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/OpenCodeServerServiceOperationsTests.cs @@ -0,0 +1,131 @@ +using NSubstitute; +using OpenCode.Sdk.Internal; +using TUnit.Assertions.Enums; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +public sealed class OpenCodeServerServiceOperationsTests +{ + private static readonly Uri Endpoint = new("http://127.0.0.1:4096"); + private readonly IServerDoors _doors = Substitute.For(); + private readonly ManagedServiceSnapshot _snapshot = new( + EnsureRequest.Snapshot(new OpenCodeServerEnsureOptions + { + ExpectedVersion = "2.2.7", + VersionPolicy = OpenCodeServerVersionPolicy.Replace, + Command = ["opencode", "serve", "--service"], + Environment = new Dictionary(StringComparer.Ordinal) { ["A"] = "1" }, + OnStart = _ => throw new InvalidOperationException("must not forward"), + }), + new ServicePaths("registration.json", "config.json", [], null), + new ServiceConfigEnvironment(Entries: null)); + + [Test] + public async Task ReconnectAsync_Should_Return_Pre_Cancellation_Through_The_Task() + { + var token = new CancellationToken(canceled: true); + var operations = new OpenCodeServerServiceOperations(_snapshot, _doors); + List> reconnecting = []; + void Invoke() => reconnecting.Add(operations.ReconnectAsync(token)); + + await Assert.That(Invoke).ThrowsNothing(); + await Assert.That(reconnecting.Count).IsEqualTo(1); + var failure = await Assert.That(reconnecting[0]).Throws(); + await Assert.That(failure!.CancellationToken).IsEqualTo(token); + await Assert.That(_doors.ReceivedCalls()).IsEmpty(); + } + + [Test] + public async Task ReconnectAsync_Should_Ensure_The_Snapshot_With_Ignore_And_No_OnStart() + { + await using var replacement = Replacement(); + using var caller = new CancellationTokenSource(); + ReturnOnEnsure(replacement, caller.Token); + + var result = await new OpenCodeServerServiceOperations(_snapshot, _doors).ReconnectAsync(caller.Token); + + await Assert.That(result).IsSameReferenceAs(replacement); + var calls = _doors.ReceivedCalls().ToArray(); + await Assert.That(calls.Select(call => call.GetMethodInfo().Name)).IsEquivalentTo(["EnsureLocatedAsync"], CollectionOrdering.Matching); + var arguments = calls[0].GetArguments(); + var request = (EnsureRequest)arguments[0]!; + await Assert.That(request.Policy).IsEqualTo(OpenCodeServerVersionPolicy.Ignore); + await Assert.That(request.LoopVersion).IsNull(); + await Assert.That(request.OnStart).IsNull(); + await Assert.That(request.Command).IsEquivalentTo(["opencode", "serve", "--service"], CollectionOrdering.Matching); + await Assert.That(request.Environment).IsEquivalentTo([new KeyValuePair("A", "1")], CollectionOrdering.Matching); + await Assert.That(arguments[1]).IsSameReferenceAs(_snapshot.Paths); + await Assert.That(arguments[2]).IsSameReferenceAs(_snapshot.Overlay); + await Assert.That(arguments[3]).IsEqualTo(caller.Token); + } + + [Test] + public async Task RestartAsync_Should_Stop_With_Handoff_Then_Ensure() + { + await using var replacement = Replacement(); + using var caller = new CancellationTokenSource(); + ReturnOnEnsure(replacement, caller.Token); + + var result = await new OpenCodeServerServiceOperations(_snapshot, _doors).RestartAsync(caller.Token); + + await Assert.That(result).IsSameReferenceAs(replacement); + var calls = _doors.ReceivedCalls().ToArray(); + await Assert.That(calls.Select(call => call.GetMethodInfo().Name)) + .IsEquivalentTo(["StopLocatedAsync", "EnsureLocatedAsync"], CollectionOrdering.Matching); + await Assert.That(calls[0].GetArguments()).IsEquivalentTo( + new object?[] { _snapshot.Paths, OpenCodeServerStopPtyMode.Handoff, caller.Token }, CollectionOrdering.Matching); + _ = _doors.Received(1).EnsureLocatedAsync(_snapshot.ReconnectRequest, _snapshot.Paths, _snapshot.Overlay, caller.Token); + } + + [Test] + public async Task RestartAsync_Should_Not_Ensure_When_The_Stop_Fails() + { + var cause = new OpenCodeServerException("stop failed"); + _doors.StopLocatedAsync(_snapshot.Paths, OpenCodeServerStopPtyMode.Handoff, Arg.Any()) + .Returns(Task.FromException(cause)); + + var failure = await Assert.That(async () => _ = await new OpenCodeServerServiceOperations(_snapshot, _doors).RestartAsync()) + .Throws(); + + await Assert.That(failure).IsSameReferenceAs(cause); + await Assert.That(_doors.ReceivedCalls().Select(call => call.GetMethodInfo().Name)) + .IsEquivalentTo(["StopLocatedAsync"], CollectionOrdering.Matching); + } + + [Test] + public async Task RestartAsync_Should_Refuse_A_Cancelled_Call_Before_Stopping() + { + var token = new CancellationToken(canceled: true); + + var failure = await Assert.That(async () => _ = await new OpenCodeServerServiceOperations(_snapshot, _doors).RestartAsync(token)) + .Throws(); + + await Assert.That(failure!.CancellationToken).IsEqualTo(token); + await Assert.That(_doors.ReceivedCalls()).IsEmpty(); + } + + private static OpenCodeServer Replacement() => new(Endpoint, "pw", 42, "2.3.0"); + + private void ReturnOnEnsure(OpenCodeServer replacement, CancellationToken token) => + _doors.EnsureLocatedAsync(Arg.Any(), _snapshot.Paths, _snapshot.Overlay, token).Returns(replacement); + + [Test] + public async Task ServerVersion_Should_Keep_The_Resolved_Value_After_Reconnect_And_Restart() + { + var operations = new OpenCodeServerServiceOperations(_snapshot, _doors); + await using var resolved = new OpenCodeServer(Endpoint, "pw", 41, "2.2.7"); + await using var connection = new OpenCodeServerConnection(resolved, "2.2.7", operations); + await using var replacement = new OpenCodeServer(Endpoint, "pw", 42, "2.3.0"); + _doors.EnsureLocatedAsync(Arg.Any(), _snapshot.Paths, _snapshot.Overlay, Arg.Any()) + .Returns(replacement); + + var reconnected = await operations.ReconnectAsync(); + var restarted = await operations.RestartAsync(); + + await Assert.That(connection.ServerVersion).IsEqualTo("2.2.7"); + await Assert.That(reconnected.RegisteredVersion).IsEqualTo("2.3.0"); + await Assert.That(restarted.RegisteredVersion).IsEqualTo("2.3.0"); + await Assert.That(connection.Server).IsSameReferenceAs(resolved); + await Assert.That(connection.Endpoint).IsEqualTo(Endpoint); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/PinnedReleaseTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/PinnedReleaseTests.cs new file mode 100644 index 00000000..9dca5c25 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/PinnedReleaseTests.cs @@ -0,0 +1,19 @@ +using System.Text.Json; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +public sealed class PinnedReleaseTests +{ + [Test] + public async Task Version_Should_Equal_The_Receipt_Release_Tag_Without_Its_Prefix() + { + using var receipt = JsonDocument.Parse(new FixtureLoader().LoadJson("Pinned.receipt.json")); + var releaseTag = receipt.RootElement.GetProperty("releaseTag").GetString(); + + await Assert.That(releaseTag).IsNotNull(); + await Assert.That(releaseTag).StartsWith("v"); + await Assert.That(PinnedRelease.Version).IsEqualTo(releaseTag[1..]); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/ResolveRequestTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ResolveRequestTests.cs new file mode 100644 index 00000000..31bcfbad --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/ResolveRequestTests.cs @@ -0,0 +1,88 @@ +using NSubstitute; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Transport.Support; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +public sealed class ResolveRequestTests +{ + private readonly IServerDoors _doors = Substitute.For(); + private readonly IServiceFileSystem _files = Substitute.For(); + private readonly IServiceEnvironment _environment = Substitute.For(); + + [Test] + [Arguments("conflict")] + [Arguments("password")] + [Arguments("service")] + public async Task ResolveAsync_Should_Return_Argument_Failures_Through_The_Task(string invalid) + { + var options = invalid switch + { + "conflict" => new OpenCodeServerResolveOptions { Endpoint = new Uri("http://127.0.0.1:4096"), Standalone = true }, + "password" => new OpenCodeServerResolveOptions { Password = "pw" }, + _ => new OpenCodeServerResolveOptions { Service = new OpenCodeServerEnsureOptions { VersionPolicy = OpenCodeServerVersionPolicy.Replace } }, + }; + List> resolving = []; + void Invoke() => resolving.Add(OpenCodeServer.ResolveAsync(options)); + + await Assert.That(Invoke).ThrowsNothing(); + await Assert.That(resolving.Count).IsEqualTo(1); + var failure = await Assert.That(resolving[0]).Throws(); + await Assert.That(failure!.ParamName).IsEqualTo("options"); + } + + [Test] + public async Task Snapshot_Should_Refuse_An_Endpoint_With_Standalone() + { + var failure = await Assert.That(() => ResolveRequest.Snapshot(new OpenCodeServerResolveOptions + { + Endpoint = new Uri("http://127.0.0.1:4096"), + Standalone = true, + })).Throws(); + + await RouteRefusal.AssertAsync(failure, "OpenCodeServerResolveOptions.Endpoint and Standalone cannot be combined.", "options"); + } + + [Test] + [Arguments(true, true)] + [Arguments(false, false)] + [Arguments(false, true)] + public async Task Snapshot_Should_Refuse_A_Password_Without_An_Endpoint(bool standalone, bool autostart) + { + var failure = await Assert.That(async () => _ = await OpenCodeServer.ResolveWithSeamsAsync( + new OpenCodeServerResolveOptions { Password = "pw", Standalone = standalone, Autostart = autostart }, + new ConnectionSeams(_doors, _environment, _files), CancellationToken.None)).Throws(); + + await RouteRefusal.AssertAsync(failure, "Password applies only to an explicit Endpoint; a standalone or service connection carries its own credentials.", "options"); + await Assert.That(_doors.ReceivedCalls()).IsEmpty(); + await Assert.That(_files.ReceivedCalls()).IsEmpty(); + await Assert.That(_environment.ReceivedCalls()).IsEmpty(); + } + + [Test] + [Arguments("relative")] + [Arguments("ftp://host/path")] + [Arguments("http://host/?query=1")] + [Arguments("http://host/#fragment")] + [Arguments("http://user@host/")] + public async Task Snapshot_Should_Refuse_An_Endpoint_The_Client_Would_Refuse(string endpoint) + { + _ = await Assert.That(() => ResolveRequest.Snapshot(new OpenCodeServerResolveOptions + { + Endpoint = new Uri(endpoint, UriKind.RelativeOrAbsolute), + })).Throws(); + } + + [Test] + public async Task ResolveAsync_Should_Refuse_Invalid_Service_Options_Before_Any_Io_On_A_Managed_Path() + { + var failure = await Assert.That(async () => _ = await OpenCodeServer.ResolveWithSeamsAsync( + new OpenCodeServerResolveOptions { Service = new OpenCodeServerEnsureOptions { VersionPolicy = OpenCodeServerVersionPolicy.Replace } }, + new ConnectionSeams(_doors, _environment, _files), CancellationToken.None)).Throws(); + + await RouteRefusal.AssertAsync(failure, "OpenCodeServerEnsureOptions.VersionPolicy Replace needs ExpectedVersion; without it there is nothing to mismatch.", "options"); + await Assert.That(_files.ReceivedCalls()).IsEmpty(); + await Assert.That(_environment.ReceivedCalls()).IsEmpty(); + await Assert.That(_doors.ReceivedCalls()).IsEmpty(); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/Connection/VersionMismatchNotifierTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/Connection/VersionMismatchNotifierTests.cs new file mode 100644 index 00000000..88f7dd99 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/Connection/VersionMismatchNotifierTests.cs @@ -0,0 +1,43 @@ +using OpenCode.Sdk.Internal; + +namespace OpenCode.Sdk.Tests.Hosting.Connection; + +public sealed class VersionMismatchNotifierTests +{ + private static readonly Uri Endpoint = new("http://127.0.0.1:4096"); + + [Test] + public async Task Notify_Should_Fire_Once_With_The_Exact_Context() + { + var contexts = new List(); + + VersionMismatchNotifier.Notify(Endpoint, "2.2.9", contexts.Add); + + await Assert.That(contexts.Count).IsEqualTo(1); + await Assert.That(contexts[0].Endpoint).IsEqualTo(Endpoint); + await Assert.That(contexts[0].ServerVersion).IsEqualTo("2.2.9"); + await Assert.That(contexts[0].ClientVersion).IsEqualTo("2.3.0"); + } + + [Test] + public async Task Notify_Should_Stay_Silent_Without_A_Callback_Or_On_A_Match() + { + var contexts = new List(); + + VersionMismatchNotifier.Notify(Endpoint, "2.2.9", callback: null); + VersionMismatchNotifier.Notify(Endpoint, "2.3.0", contexts.Add); + + await Assert.That(contexts).IsEmpty(); + } + + [Test] + public async Task Notify_Should_Propagate_A_Callback_Exception() + { + var cause = new InvalidOperationException("consumer callback failed"); + + var failure = await Assert.That(() => VersionMismatchNotifier.Notify(Endpoint, "2.2.9", _ => throw cause)) + .Throws(); + + await Assert.That(failure).IsSameReferenceAs(cause); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/OpenCodeServerContractTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/OpenCodeServerContractTests.cs index 2e9a3d80..1ee946ed 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/OpenCodeServerContractTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/OpenCodeServerContractTests.cs @@ -13,7 +13,7 @@ public sealed class OpenCodeServerContractTests private static OpenCodeServer CreateStartedDoor() => new(DoorEndpoint, DoorPassword); - private static OpenCodeServer CreateDiscoveredDoor() => new(DoorEndpoint, DoorPassword, processId: 48213); + private static OpenCodeServer CreateDiscoveredDoor() => new(DoorEndpoint, DoorPassword, processId: 48213, version: null); [Test] public async Task CreateClient_Should_Copy_And_Snapshot_Configured_Headers_On_The_Wire() @@ -91,7 +91,7 @@ public async Task CreateClient_Should_Use_The_Discovered_Identity() [Test] public async Task CreateClient_Should_Send_No_Credential_For_A_Passwordless_Registered_Handle() { - var server = new OpenCodeServer(DoorEndpoint, password: null, processId: 48213); + var server = new OpenCodeServer(DoorEndpoint, password: null, processId: 48213, version: null); await Assert.That(server.Password).IsNull(); using var client = server.CreateClient(); @@ -331,7 +331,7 @@ public async Task Exited_Should_Throw_The_Mock_Seam_Failure_On_A_Bare_Mock() [Test] public async Task Exited_Should_Throw_When_The_Handle_Owns_No_Process() { - var shared = new OpenCodeServer(new Uri("http://127.0.0.1:4096"), "pw", processId: 4242); + var shared = new OpenCodeServer(new Uri("http://127.0.0.1:4096"), "pw", processId: 4242, version: null); var failure = await Assert.That(() => { _ = shared.Exited; }).Throws(); @@ -339,6 +339,19 @@ public async Task Exited_Should_Throw_When_The_Handle_Owns_No_Process() await Assert.That(failure!.Message).Contains("owns no process"); } + [Test] + [Arguments("2.2.7")] + [Arguments(null)] + public async Task SharedService_Should_Carry_The_Registration_Version(string? version) + { + var registration = new ServiceRegistration("srv_version", version, DoorEndpoint.AbsoluteUri, DoorEndpoint, 48213, DoorPassword); + var server = OpenCodeServer.SharedService(registration); + + await Assert.That(server.RegisteredVersion).IsEqualTo(version); + await Assert.That(server.Endpoint).IsEqualTo(DoorEndpoint); + await Assert.That(server.ProcessId).IsEqualTo(48213); + } + private sealed class MockableServer : OpenCodeServer { } diff --git a/tests/OpenCode.Sdk.Tests/OpenCode.Sdk.Tests.csproj b/tests/OpenCode.Sdk.Tests/OpenCode.Sdk.Tests.csproj index b9a71163..86a9dc61 100644 --- a/tests/OpenCode.Sdk.Tests/OpenCode.Sdk.Tests.csproj +++ b/tests/OpenCode.Sdk.Tests/OpenCode.Sdk.Tests.csproj @@ -82,6 +82,7 @@ + diff --git a/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt b/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt index 8b7bf2e4..6696f1f3 100644 --- a/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt +++ b/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt @@ -1031,12 +1031,32 @@ namespace OpenCode.Sdk public static System.Threading.Tasks.Task DiscoverAsync(OpenCode.Sdk.OpenCodeServerDiscoverOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } public static System.Threading.Tasks.Task EnsureAsync(OpenCode.Sdk.OpenCodeServerEnsureOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } public static System.Threading.Tasks.Task FindIncumbentAsync(System.Uri url, OpenCode.Sdk.OpenCodeServerDiscoverOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task ResolveAsync(OpenCode.Sdk.OpenCodeServerResolveOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } [System.Diagnostics.CodeAnalysis.Experimental("OPENCODE002", UrlFormat="https://github.com/opencode-dotnet/opencode-sdk-dotnet/blob/master/docs/guide/exp" + "erimental.md#opencode002")] public static System.Threading.Tasks.Task ShutdownPersistentPtyAsync(OpenCode.Sdk.OpenCodeServerDiscoverOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } public static System.Threading.Tasks.Task StartAsync(OpenCode.Sdk.OpenCodeServerOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } public static System.Threading.Tasks.Task StopAsync(OpenCode.Sdk.OpenCodeServerStopOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } } + public class OpenCodeServerConnection : System.IAsyncDisposable + { + protected OpenCodeServerConnection() { } + public virtual System.Uri Endpoint { get; } + public virtual OpenCode.Sdk.OpenCodeServerConnectionMode Mode { get; } + public virtual string? Password { get; } + public virtual OpenCode.Sdk.OpenCodeServer? Server { get; } + public virtual string? ServerVersion { get; } + public virtual OpenCode.Sdk.OpenCodeServerServiceOperations? ServiceOperations { get; } + public virtual string Username { get; } + public virtual OpenCode.Sdk.OpenCodeClient CreateClient(System.Action? configure = null) { } + public virtual System.Threading.Tasks.ValueTask DisposeAsync() { } + } + public enum OpenCodeServerConnectionMode + { + Explicit = 0, + Standalone = 1, + Service = 2, + } public sealed class OpenCodeServerDiscoverOptions { public OpenCodeServerDiscoverOptions() { } @@ -1118,6 +1138,23 @@ namespace OpenCode.Sdk public required System.Collections.Generic.IReadOnlyList StandardOutput { get; init; } public required bool StandardOutputTruncated { get; init; } } + public sealed class OpenCodeServerResolveOptions + { + public OpenCodeServerResolveOptions() { } + public bool Autostart { get; set; } + public System.Uri? Endpoint { get; set; } + public OpenCode.Sdk.OpenCodeServerOptions? Launch { get; set; } + public System.Action? OnServerVersionMismatch { get; set; } + public string? Password { get; set; } + public OpenCode.Sdk.OpenCodeServerEnsureOptions? Service { get; set; } + public bool Standalone { get; set; } + } + public class OpenCodeServerServiceOperations + { + protected OpenCodeServerServiceOperations() { } + public virtual System.Threading.Tasks.Task ReconnectAsync(System.Threading.CancellationToken cancellationToken = default) { } + public virtual System.Threading.Tasks.Task RestartAsync(System.Threading.CancellationToken cancellationToken = default) { } + } public enum OpenCodeServerState { Ready = 0, @@ -1137,6 +1174,12 @@ namespace OpenCode.Sdk Clear = 0, Handoff = 1, } + public sealed class OpenCodeServerVersionMismatchContext + { + public string ClientVersion { get; } + public System.Uri Endpoint { get; } + public string ServerVersion { get; } + } public enum OpenCodeServerVersionPolicy { Ignore = 0, diff --git a/tests/OpenCode.Sdk.Tests/Support/ServiceCancellationDoors.cs b/tests/OpenCode.Sdk.Tests/Support/ServiceCancellationDoors.cs index cc06c2dd..43e45ddd 100644 --- a/tests/OpenCode.Sdk.Tests/Support/ServiceCancellationDoors.cs +++ b/tests/OpenCode.Sdk.Tests/Support/ServiceCancellationDoors.cs @@ -1,8 +1,10 @@ using System.IO.Abstractions; using System.Net; using System.Text; +using NSubstitute; using OpenCode.Sdk.Internal; using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; using TUnit.Assertions.Enums; namespace OpenCode.Sdk.Tests.Support; @@ -15,6 +17,30 @@ internal sealed class ServiceCancellationDoors( private const string ShutdownPath = "/api/experimental/persistent-pty/shutdown"; private const string ServicePassword = "synthetic-identity-password"; + internal async Task AtResolveConfigStoreReadAsync(CancellationTokenSource caller) + { + var scenario = new ServiceConfigScenario(); + var forwarded = default(CancellationToken); + scenario.FileSystem.TryReadAllBytesAsync(scenario.Paths.ConfigFile!, Arg.Any()) + .Returns(async call => + { + forwarded = call.Arg(); + await caller.CancelOnWorkerAsync(); + forwarded.ThrowIfCancellationRequested(); + return null; + }); + var seams = new ConnectionSeams( + Substitute.For(), scenario.Environment, scenario.FileSystem, ProbeTime: scenario.Time); + var failure = await observeCancellation(async () => + { + await using var connection = await OpenCodeServer.ResolveWithSeamsAsync( + new() { Service = new OpenCodeServerEnsureOptions { Channel = "local" } }, seams, caller.Token); + }); + + await Assert.That(forwarded).IsEqualTo(caller.Token); + return failure; + } + internal async Task AtConfigPreCancelledAsync(string row, CancellationTokenSource caller) { var options = new OpenCodeServiceConfigOptions(); @@ -58,6 +84,7 @@ internal async Task AtServiceRequestAsync(string row var heldPath = (row, stage) switch { ("discover" or "incumbent", _) => "/api/info", + ("resolve" or "reconnect", _) => "/api/info", (_, "ticket") => HandoffPath, _ => ShutdownPath, }; @@ -103,6 +130,8 @@ await Assert.That(request.Headers["Authorization"]).IsEqualTo( string[] expectedPaths = (row, stage) switch { ("discover" or "incumbent", _) => ["/api/info"], + ("resolve" or "reconnect", _) => ["/api/info"], + ("restart", _) => [heldPath], (_, "fallback") => ["/api/info", HandoffPath, ShutdownPath], _ => ["/api/info", heldPath], }; @@ -159,6 +188,10 @@ private static async Task InvokeServiceAsync(string row, string registrationPath await OpenCodeServer.ShutdownPersistentPtyAsync( new OpenCodeServerDiscoverOptions { RegistrationFilePath = registrationPath }, caller); } + else if (row is "resolve" or "reconnect" or "restart") + { + await InvokeConnectionAsync(row, registrationPath, endpoint, caller); + } else { await using var server = await OpenCodeServer.EnsureAsync(new OpenCodeServerEnsureOptions @@ -170,4 +203,26 @@ await OpenCodeServer.ShutdownPersistentPtyAsync( }, caller); } } + + private static async Task InvokeConnectionAsync(string row, string registrationPath, Uri endpoint, CancellationToken caller) + { + if (row == "resolve") + { + await using var connection = await OpenCodeServer.ResolveAsync(new OpenCodeServerResolveOptions + { + Endpoint = endpoint, + Password = ServicePassword, + }, caller); + return; + } + + var snapshot = new ManagedServiceSnapshot( + EnsureRequest.Snapshot(new OpenCodeServerEnsureOptions { RegistrationFilePath = registrationPath }), + new ServicePaths(registrationPath, ConfigFile: null, LegacyRegistrationFiles: [], LegacyConfigFile: null), + new ServiceConfigEnvironment(Entries: null)); + var operations = new OpenCodeServerServiceOperations(snapshot, new ServerDoors()); + await using var server = row == "reconnect" + ? await operations.ReconnectAsync(caller) + : await operations.RestartAsync(caller); + } } diff --git a/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs b/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs index 66e38f93..c95c6aea 100644 --- a/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs +++ b/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs @@ -51,6 +51,7 @@ internal static class GeneratedSourceCompiler /// generated LanguageModelsClient, so it rides that client's emission. /// The typed RPC call sits above the generated RpcClient and reads its two RPC error models, so it rides their emissions. /// The typed RPC subscription sits above the Events door and the generated EventRpc, so it rides both. + /// Connection resolution adds an explicit probe over the generated server client and unauthorized error. /// internal static readonly (string Consumer, string RequiredEmission)[] GeneratedSurfaceConsumers = [ @@ -68,6 +69,21 @@ internal static readonly (string Consumer, string RequiredEmission)[] GeneratedS ("Hosting/BackgroundService/Internal/Handoff/ServicePtyShutdown.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), ("Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), ("Hosting/BackgroundService/OpenCodeServerIncumbent.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), + ("Hosting/Connection/OpenCodeServer.Connection.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), + ("Hosting/Connection/OpenCodeServer.Connection.cs", "Server/ServerClient.cs"), + ("Hosting/Connection/OpenCodeServer.Connection.cs", "Common/Errors/UnauthorizedError.cs"), + ("Hosting/Connection/OpenCodeServerConnection.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), + ("Hosting/Connection/OpenCodeServerServiceOperations.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), + ("Hosting/Connection/Internal/Abstractions/IServerDoors.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), + ("Hosting/Connection/Internal/ServerDoors.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), + ("Hosting/Connection/Internal/ConnectionSeams.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), + ("Hosting/Connection/Internal/ConnectionResolver.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), + ("Hosting/Connection/Internal/ConnectionResolver.cs", "Server/ServerClient.cs"), + ("Hosting/Connection/Internal/ConnectionResolver.cs", "Common/Errors/UnauthorizedError.cs"), + ("Hosting/Connection/Internal/ExplicitServerProbe.cs", "Server/ServerClient.cs"), + ("Hosting/Connection/Internal/ExplicitServerProbe.cs", "Common/Errors/UnauthorizedError.cs"), + ("Hosting/Connection/Internal/ExplicitProbeFailureClassifier.cs", "Common/Errors/UnauthorizedError.cs"), + ("Hosting/Internal/ClientIdentityComposer.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), ("Hosting/Launcher/OpenCodeServer.Launcher.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), ("Hosting/OpenCodeServer.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), ("LanguageModels/Internal/DefaultModelWait.cs", "LanguageModels/LanguageModelsClient.cs"), diff --git a/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs b/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs index 4abad4f4..21babe5c 100644 --- a/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs +++ b/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs @@ -97,6 +97,8 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "OpenCodeResponse", "OpenCodeRpcException", "OpenCodeServer", + "OpenCodeServerConnection", + "OpenCodeServerConnectionMode", "OpenCodeServerDiscoverOptions", "OpenCodeServerEnsureOptions", "OpenCodeServerEnsureReason", @@ -108,9 +110,12 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "OpenCodeServerOptions", "OpenCodeServerOutput", "OpenCodeServerOutputSnapshot", + "OpenCodeServerResolveOptions", + "OpenCodeServerServiceOperations", "OpenCodeServerState", "OpenCodeServerStopOptions", "OpenCodeServerStopPtyMode", + "OpenCodeServerVersionMismatchContext", "OpenCodeServerVersionPolicy", "OpenCodeServiceConfig", "OpenCodeServiceConfigOptions", @@ -185,8 +190,11 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "ChildStreamEnd", "ChildStreamRoute", "ChildStreamSet", + "ClientIdentityComposer", "ClientLifetime", "ClientTerminalWebSocket", + "ConnectionResolver", + "ConnectionSeams", "ConnectionSnapshot", "CursorPaginator", "DeclaredHeader", @@ -209,6 +217,8 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "ExecutableSearchEnvironment", "ExitWaitKernel", "ExperimentalDiagnostics", + "ExplicitProbeFailureClassifier", + "ExplicitServerProbe", "FailureClassification", "FailurePhase", "FileRenameKernel", @@ -225,6 +235,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "IPosixSpawn", "IProcessGroupSignal", "IProcessJob", + "IServerDoors", "IServerLadder", "IServiceContender", "IServiceContenderSpawner", @@ -257,6 +268,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "LoopbackConnectAttempt", "LoopbackSocketConnector", "LoopbackTransport", + "ManagedServiceSnapshot", "MockSeam", "NetworkTimeouts", "NoOpEventFeedGateProbe", @@ -272,6 +284,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "PersistentPtyFrameDecoder", "PersistentPtyInputFrame", "PersistentPtyUpgradeFailurePolicy", + "PinnedRelease", "PipeLineReader", "PipeOutputPump", "Pipeline", @@ -309,6 +322,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "ReadinessOutcome", "RecordPrinter", "RequestDecorationPolicy", + "ResolveRequest", "ResolvedExecutable", "ResponseAdapter", "ResponseBufferingPolicy", @@ -321,18 +335,23 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "SafeThreadHandle", "ServerChild", "ServerChildStart", + "ServerDoors", "ServerReadyLine", "ServerSentEvent", "ServerSentEventFramer", "ServerSentEventReader", "ServiceConfigDocument", "ServiceConfigEditor", + "ServiceConfigEnvironment", + "ServiceConfigEnvironmentReader", "ServiceConfigJsonWriter", "ServiceConfigReader", + "ServiceConfigReadResult", "ServiceConfigStore", "ServiceContender", "ServiceContenderEnvironmentComposer", "ServiceContenderSpawner", + "ServiceDisabledCheck", "ServiceDiscovery", "ServiceElection", "ServiceElectionSeams", @@ -397,6 +416,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "UnionTagTable", "UnionVariantRead", "UserAgentPolicy", + "VersionMismatchNotifier", "WebSocketSchemePolicy", "WindowsChildExit", "WindowsCommand",