diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b9a54a2..17d21cef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ Nightly builds of `master` are on [GitHub Packages](docs/guide/getting-started.md#nightly-builds-github-packages) as nightlies of the next version, `{version}-nightly.{yyyyMMdd}.g{shortSha}`. +### ✨ Added + +- `Sessions.GetTotalCostAsync` returns a session's total cost as opencode's own clients show it: a + session's cost plus the cost of every descendant subagent session, and a subagent session's own cost. + An unknown session fails with the server's not-found error, where opencode's client shows 0. + ### 🐛 Fixes - An `OpenCodeApiException` whose server message already ends in `.`, `!` or `?` no longer gets a diff --git a/docs/architecture/client-runtime.md b/docs/architecture/client-runtime.md index 4243f6be..a375eaf0 100644 --- a/docs/architecture/client-runtime.md +++ b/docs/architecture/client-runtime.md @@ -1,6 +1,6 @@ # Client Runtime Architecture -Date: 2026-11-17 +Date: 2026-11-23 Canonical current rules for client construction, transport ownership, API errors, streams, and the local server launcher. Protocol and generated-model rules live in @@ -532,7 +532,7 @@ resolves the message's network window from those carried traits. ([Typed plugin RPC](#typed-plugin-rpc)). - A one-shot call may select per-call `NoThrow`, returning the same typed error data on its response spine. There is no client-level error-behavior switch (ADR-0007). Streams, cursor traversals, - both waits and the typed RPC call refuse it at the call. + both waits, the session cost total and the typed RPC call refuse it at the call. - `Plugins.WaitForPluginsAsync` follows the CLI's one-shot wait (`plugin-startup.ts:6-13`): it lists the location's plugins until non-empty, waiting 25 ms after each empty answer for about five seconds. The schedule limit is checked after each answer, not a deadline that interrupts @@ -878,6 +878,18 @@ resolves the message's network window from those carried traits. - Automatic pagination is a finite pull sequence over ordinary buffered HTTP calls, not SSE. A different pagination dialect does not inherit these rules from naming or prose; it requires a mechanically proven binding of its own (ADR-0013, ADR-0017). +- `Sessions.GetTotalCostAsync` follows upstream's client data store + (`packages/client/src/solid/data.ts:1582-1590` at the pin): a session with a parent returns its + own `Cost`; any other session returns its own `Cost` plus the `Cost` of every descendant session, + the subtree upstream's store converges on as it loads them. It reads the descendants depth-first, + each level through the children traversal with `ParentId`, descending order and pages of 200, as + upstream's family sync reads a level, and counts each session once. It refuses `NoThrow` at the + call, and every failure propagates. + - Recorded divergence: upstream's store returns 0 for a session it has not loaded, and the SDK + fails with the server's not-found error for an unknown session. Upstream reads a local cache, + where an absent session is one not loaded yet; the SDK asks the server, where an absent session + is a wrong identifier, and returning 0 would hide it. If upstream's client starts treating an + unknown session as an error, this follows. ## Launcher diff --git a/docs/guide/errors-and-responses.md b/docs/guide/errors-and-responses.md index eaa22a56..4e57d917 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-22 +Date: 2026-11-23 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 @@ -94,7 +94,7 @@ instance, and `new OpenCodeRequestOptions { ErrorBehavior = ErrorBehavior.NoThro thing spelled out. There is deliberately no client-level switch: whether a failure is exceptional depends on the call, not on the client. -Four limits worth internalising: +Five limits worth internalising: - **`NoThrow` covers declared API errors only.** It never suppresses a transport failure. - **Streams and automatic cursor traversals refuse `NoThrow` at the call, before enumeration.** @@ -103,6 +103,7 @@ Four limits worth internalising: on connection state while retrying. See [streaming](streaming.md#-stream-error-channels) and [pagination](pagination.md). - **`Plugins.WaitForPluginsAsync` and `LanguageModels.WaitForDefaultAsync` refuse `NoThrow` at the call,** because they decide on each plugin-list answer whether to keep waiting. +- **`Sessions.GetTotalCostAsync` refuses `NoThrow` at the call,** because it returns a number, not an envelope. - **The typed plugin RPC call refuses `NoThrow` at the call,** because it returns the output, not an envelope. See [Calling a plugin's RPC](requests.md#-calling-a-plugins-rpc). diff --git a/spec/SNAPSHOT.md b/spec/SNAPSHOT.md index 71db488b..f9a8b647 100644 --- a/spec/SNAPSHOT.md +++ b/spec/SNAPSHOT.md @@ -1,6 +1,6 @@ # OpenAPI Snapshot -Date: 2026-11-22 +Date: 2026-11-23 `openapi.json` is the accepted snapshot of the upstream opencode OpenAPI 3.1 document (ADR-0005). The SDK is built against this snapshot, never against a live branch; the pin is diff --git a/spec/receipt.json b/spec/receipt.json index becad588..713f0175 100644 --- a/spec/receipt.json +++ b/spec/receipt.json @@ -34,25 +34,8 @@ "normalizedDocumentPath": null, "operationSetDigest": "7cb3e37b2498257d72ed0d5e46fdb6ba6e8738cbe7070f3919fd685a3d00fa7f", "operationCount": 173, - "addedOperations": [ - "experimental.automation.create", - "experimental.automation.delete", - "experimental.automation.get", - "experimental.automation.list", - "experimental.automation.pause", - "experimental.automation.resume", - "experimental.blob.get", - "experimental.generate.video.create", - "experimental.generate.video.get" - ], - "removedOperations": [ - "experimental.schedule.create", - "experimental.schedule.delete", - "experimental.schedule.get", - "experimental.schedule.list", - "experimental.schedule.pause", - "experimental.schedule.resume" - ], + "addedOperations": [], + "removedOperations": [], "componentCount": 521, "contentSchemaCount": 2, "watchedSources": [ @@ -1120,6 +1103,24 @@ } ] }, + { + "path": "packages/client/src/solid/data.ts", + "sha256": "6083ed87dd52b7000da6613158461986cda5ee5573ed841473f4303acaf1eda9", + "anchors": [ + { + "text": "if (session.parentID) return session.cost", + "matched": true + }, + { + "text": "const CHILD_PAGE = 200", + "matched": true + }, + { + "text": "const rootID = resolveRoot(sessionID)", + "matched": true + } + ] + }, { "path": "packages/client/src/promise/media.ts", "sha256": "ebfde36489ae44cb51505cbeba7d854fa6cf0c5ab92c1ff8fc67b7a71b4b640d", diff --git a/spec/source-watch.json b/spec/source-watch.json index bd55c344..64bcce7f 100644 --- a/spec/source-watch.json +++ b/spec/source-watch.json @@ -1517,6 +1517,36 @@ } ] }, + { + "path": "packages/client/src/solid/data.ts", + "sha256": "6083ed87dd52b7000da6613158461986cda5ee5573ed841473f4303acaf1eda9", + "behaviors": [ + { + "owner": "opencode-sdk-dotnet", + "behavior": "cost(sessionID) returns 0 for a session the store has not loaded, a session's own cost when it has a parent, and otherwise the sum of cost over the family index of its root. Sessions.GetTotalCostAsync follows it, except that an unknown session fails.", + "anchor": { + "type": "contains", + "text": "if (session.parentID) return session.cost" + } + }, + { + "owner": "opencode-sdk-dotnet", + "behavior": "listChildren reads a parent's direct children with session.list {parentID, order desc, limit 200}, following cursor.next while a page is full; sync with children fills the family index with them. Sessions.GetTotalCostAsync reads each level of descendants the same way.", + "anchor": { + "type": "contains", + "text": "const CHILD_PAGE = 200" + } + }, + { + "owner": "opencode-sdk-dotnet", + "behavior": "registerSession files every loaded session, at any depth, under the family of its resolved root, so cost() converges on the whole loaded subtree. Sessions.GetTotalCostAsync walks the whole subtree for the same total.", + "anchor": { + "type": "contains", + "text": "const rootID = resolveRoot(sessionID)" + } + } + ] + }, { "path": "packages/client/src/promise/media.ts", "sha256": "ebfde36489ae44cb51505cbeba7d854fa6cf0c5ab92c1ff8fc67b7a71b4b640d", diff --git a/src/OpenCode.Sdk/Sessions/Internal/SessionCostTotal.cs b/src/OpenCode.Sdk/Sessions/Internal/SessionCostTotal.cs new file mode 100644 index 00000000..0a91ace6 --- /dev/null +++ b/src/OpenCode.Sdk/Sessions/Internal/SessionCostTotal.cs @@ -0,0 +1,51 @@ +using OpenCode.Sdk.Models; + +namespace OpenCode.Sdk.Internal; + +/// Totals every descendant's cost for a root, or a child's own cost, matching packages/client/src/solid/data.ts:1582-1590. +/// The sessions family. +internal sealed class SessionCostTotal(SessionsClient client) +{ + /// Reads the session's own cost, adding every descendant only for a root session. + /// The session client. + /// The session identifier. + /// Options for each request. + /// Cancels the read or traversal. + /// The session's cost total. + public async Task ReadAsync(SessionClient session, string sessionId, + OpenCodeRequestOptions? requestOptions, CancellationToken cancellationToken) + { + var response = await session.GetAsync(requestOptions, cancellationToken).ConfigureAwait(false); + var info = response.Session; + if (info.ParentId is not null) + { + return info.Cost; + } + + var visited = new HashSet(StringComparer.Ordinal) { sessionId, info.Id }; + return await ReadDescendantsAsync(sessionId, info.Cost, visited, requestOptions, cancellationToken).ConfigureAwait(false); + } + + private async Task ReadDescendantsAsync(string sessionId, double total, HashSet visited, + OpenCodeRequestOptions? requestOptions, CancellationToken cancellationToken) + { + var children = new List(); + await foreach (var child in client.EnumerateSessionsAsync(new SessionListRequest + { + ParentId = SessionParentFilter.Of(sessionId), + Order = ListOrder.Descending, + Limit = 200, + }, requestOptions, cancellationToken).ConfigureAwait(false)) + { + children.Add(child); + } + + foreach (var child in children.Where(child => visited.Add(child.Id))) + { + total += child.Cost; + total = await ReadDescendantsAsync(child.Id, total, visited, requestOptions, cancellationToken).ConfigureAwait(false); + } + + return total; + } +} diff --git a/src/OpenCode.Sdk/Sessions/SessionsClientExtensions.cs b/src/OpenCode.Sdk/Sessions/SessionsClientExtensions.cs new file mode 100644 index 00000000..fbae6502 --- /dev/null +++ b/src/OpenCode.Sdk/Sessions/SessionsClientExtensions.cs @@ -0,0 +1,32 @@ +using OpenCode.Sdk.Internal; + +namespace OpenCode.Sdk; + +/// Reads session costs including every descendant subagent session. +public static class SessionsClientExtensions +{ + /// Returns a session's own cost plus the cost of every descendant session, or only its own cost for a child session. + /// The sessions family. + /// The session identifier. + /// Options for each request. + /// Cancels the session read or children traversal. + /// The session's cost total. + /// + /// Reads the session, then every descendant session depth-first, each level across every page, + /// and counts each session once. NoThrow is refused at the call. Every failure propagates, + /// including the server's not-found error for an unknown session. + /// + /// is null. + /// The session identifier is invalid, or selects NoThrow. + /// The session read or children traversal returned an API error. + /// The session read or children traversal failed in transport. + /// The caller canceled the session read or children traversal. + public static Task GetTotalCostAsync(this SessionsClient client, string sessionId, + OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(client); + ErrorBehaviorPolicy.RefuseNoThrow(requestOptions, "Session cost totals"); + var session = client.GetSessionClient(sessionId); + return new SessionCostTotal(client).ReadAsync(session, sessionId, requestOptions, cancellationToken); + } +} diff --git a/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs b/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs index ab57662b..cf42c7f6 100644 --- a/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs +++ b/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs @@ -35,6 +35,8 @@ private static IEnumerable Cases() yield return new("http", "raw-upload", caller => AtBodyAsync(upload: true, caller)); yield return new("default-wait", "headers", caller => AtHeadersAsync( static (client, token) => client.LanguageModels.WaitForDefaultAsync(cancellationToken: token), caller)); + yield return new("session-cost-total", "headers", caller => AtHeadersAsync( + static (client, token) => client.Sessions.GetTotalCostAsync(SessionId, cancellationToken: token), caller)); yield return new("plugin-wait", "headers", caller => AtHeadersAsync( static (client, token) => client.Plugins.WaitForPluginsAsync(cancellationToken: token), caller)); yield return new("client-mcp-token", "headers", caller => AtHeadersAsync( @@ -590,6 +592,7 @@ public bool Is(Type owner, string name, Type result, params Type[] parameters) = DeclaringType == owner && Name == name && ReturnType == result && IsStatic == (owner == typeof(OpenCodeServer) || owner == typeof(OpenCodeServiceConfiguration) || owner == typeof(LanguageModelsClientExtensions) || owner == typeof(PluginsClientExtensions) || + owner == typeof(SessionsClientExtensions) || owner == typeof(ExperimentalClientMcpExtensions)) && Parameters.SequenceEqual(parameters); @@ -684,6 +687,8 @@ _ when member.Is(typeof(EventsClient), nameof(EventsClient.WatchConnectionAsync) _ when ClientFamilies.Contains(member.DeclaringType) && IsGeneric(member.ReturnType, typeof(IAsyncEnumerable<>)) => "other-sse", _ when member.Is(typeof(LanguageModelsClientExtensions), nameof(LanguageModelsClientExtensions.WaitForDefaultAsync), typeof(Task), typeof(LanguageModelsClient), typeof(ModelDefaultRequest), typeof(OpenCodeRequestOptions), typeof(CancellationToken)) => "default-wait", + _ when member.Is(typeof(SessionsClientExtensions), nameof(SessionsClientExtensions.GetTotalCostAsync), typeof(Task), + typeof(SessionsClient), typeof(string), typeof(OpenCodeRequestOptions), typeof(CancellationToken)) => "session-cost-total", _ when member.Is(typeof(PluginsClientExtensions), nameof(PluginsClientExtensions.WaitForPluginsAsync), typeof(Task), typeof(PluginsClient), typeof(PluginListRequest), typeof(OpenCodeRequestOptions), typeof(CancellationToken)) => "plugin-wait", _ when member.IsStatic && member.DeclaringType == typeof(RpcClientExtensions) && member.Name == nameof(RpcClientExtensions.CallAsync) diff --git a/tests/OpenCode.Sdk.Tests/Sessions/SessionsClientExtensionsLiveTests.cs b/tests/OpenCode.Sdk.Tests/Sessions/SessionsClientExtensionsLiveTests.cs new file mode 100644 index 00000000..cb39ea84 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Sessions/SessionsClientExtensionsLiveTests.cs @@ -0,0 +1,88 @@ +using System.Text.Json.Nodes; +using OpenCode.Sdk.Models; +using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Sessions.Support; +using OpenCode.Sdk.Tests.Support; +using TUnit.Assertions.Enums; + +namespace OpenCode.Sdk.Tests.Sessions; + +[ClassDataSource(Shared = SharedType.PerTestSession)] +[NotInParallel(ParallelConstraintKeys.ServerProcess)] +public sealed class SessionsClientExtensionsLiveTests(SimulatedDriveServerFixture server) +{ + private const string CallId = "call_subagent"; + + [Test] + [Timeout(240_000)] + public async Task GetTotalCostAsync_Should_Walk_A_Real_Subagent_Family(CancellationToken cancellationToken) + { + var scenario = await OwnedToolScenario.CreateAsync(server, "session-cost-live", cancellationToken); + await scenario.RunAsync(async () => + { + var initial = await scenario.Session.GetAsync(cancellationToken: cancellationToken); + using var client = server.CreateClient(new LocationSelector { Directory = initial.Session.Location.Directory }); + var prompt = "Report this child marker: " + Guid.NewGuid().ToString("N"); + _ = await scenario.Session.PromptAsync(new SessionPromptRequest { Text = "Delegate the marker report." }, + cancellationToken: cancellationToken); + var first = await scenario.WaitForModelRequestAsync(); + await scenario.ScriptToolCallAsync(first, CallId, "subagent", + new JsonObject { ["agent"] = "general", ["description"] = "Report child marker", ["prompt"] = prompt }); + + using var barrier = SessionEventProbe.Barrier(cancellationToken); + var success = await scenario.Probe.WaitForAsync( + item => item.Data.SessionId == scenario.SessionId && item.Data.Id == CallId, + "subagent tool success", barrier.Token); + await Assert.That(success.Data.Metadata).IsNotNull(); + var childId = success.Data.Metadata!["sessionID"].GetString(); + await Assert.That(childId).IsNotNull(); + await Assert.That(success.Data.Content.OfType().Single().Text).Contains("sessionID: " + childId); + + var pending = new[] { await scenario.WaitForModelRequestAsync(), await scenario.WaitForModelRequestAsync() }; + var root = pending.Single(IsRootContinuation); + var child = pending.Single(invocation => !IsRootContinuation(invocation)); + await Assert.That(child.Body.GetRawText()).Contains(prompt); + Console.WriteLine("session-cost-live: first-request-after-tool-is-root=" + IsRootContinuation(pending[0])); + await scenario.ScriptFinalTextAsync(root, "Root waiting for the child notice."); + var rootEnded = await scenario.Probe.WaitForAsync( + item => item.Data.SessionId == scenario.SessionId, "first root completion", barrier.Token); + await scenario.ScriptFinalTextAsync(child, "Child marker reported."); + _ = await scenario.Probe.WaitForAsync( + item => item.Data.SessionId == childId, "child completion", barrier.Token); + var notice = await scenario.WaitForModelRequestAsync(); + await Assert.That(notice.Body.GetRawText()).Contains(childId!); + await Assert.That(notice.Body.GetRawText()).Contains("Child marker reported."); + await scenario.ScriptFinalTextAsync(notice, "Root received the child notice."); + _ = await scenario.Probe.WaitForAsync( + item => item.Data.SessionId == scenario.SessionId, "root notice completion", rootEnded, barrier.Token); + _ = await client.Experimental.WaitForSessionAsync(childId!, cancellationToken: cancellationToken); + _ = await scenario.WaitAsync(cancellationToken); + scenario.MarkTerminal(); + + var children = new List(); + await foreach (var session in client.Sessions.EnumerateSessionsAsync(new SessionListRequest + { + ParentId = SessionParentFilter.Of(scenario.SessionId), + Order = ListOrder.Descending, + Limit = 200, + }, cancellationToken: cancellationToken)) + { + children.Add(session); + } + + await Assert.That(children.Select(static session => session.Id)).IsEquivalentTo([childId!], CollectionOrdering.Matching); + await Assert.That(children.Single().ParentId).IsEqualTo(scenario.SessionId); + var rootRead = await scenario.Session.GetAsync(cancellationToken: cancellationToken); + await Assert.That(rootRead.Session.ParentId).IsNull(); + var childRead = await client.Sessions.GetSessionClient(childId!).GetAsync(cancellationToken: cancellationToken); + await Assert.That(await client.Sessions.GetTotalCostAsync(scenario.SessionId, cancellationToken: cancellationToken)) + .IsEqualTo(rootRead.Session.Cost + childRead.Session.Cost); + await Assert.That(await client.Sessions.GetTotalCostAsync(childId!, cancellationToken: cancellationToken)) + .IsEqualTo(childRead.Session.Cost); + }); + } + + private static bool IsRootContinuation(DriveInvocation invocation) => + invocation.Body.GetProperty("messages").EnumerateArray().Any(static message => + message.GetProperty("role").GetString() == "tool" && message.GetProperty("tool_call_id").GetString() == CallId); +} diff --git a/tests/OpenCode.Sdk.Tests/Sessions/SessionsClientExtensionsTests.cs b/tests/OpenCode.Sdk.Tests/Sessions/SessionsClientExtensionsTests.cs new file mode 100644 index 00000000..edde4f8a --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Sessions/SessionsClientExtensionsTests.cs @@ -0,0 +1,309 @@ +using System.Net; +using OpenCode.Sdk.Models; +using OpenCode.Sdk.Tests.Sessions.Support; +using OpenCode.Sdk.Tests.Support; +using TUnit.Assertions.Enums; + +namespace OpenCode.Sdk.Tests.Sessions; + +public sealed class SessionsClientExtensionsTests +{ + private readonly SessionCostFixtures _fixtures = new(); + + [Test] + [Arguments("ses_root")] + [Arguments("ses_returned")] + public async Task GetTotalCostAsync_Should_Count_Each_Session_Once_In_A_Cycle(string returnedId) + { + var root = _fixtures.Session(returnedId, 1); + var child = _fixtures.Session("ses_child", 2, root.Id); + var lists = 0; + using var scenario = PipelineScenario.Responding(request => + { + if (request.RequestUri!.AbsolutePath != "/api/session") + { + return Answer(SessionCostFixtures.Get(root)); + } + + if (++lists > 20) + { + return Answer(SessionCostFixtures.Page([])); + } + + return Answer(request.RequestUri.Query.Contains("parentID=ses_root", StringComparison.Ordinal) + ? SessionCostFixtures.Page([child]) : SessionCostFixtures.Page([root, _fixtures.Session("ses_root", 1), child])); + }); + + var total = await new SessionsClient(scenario.Pipeline).GetTotalCostAsync("ses_root"); + + await Assert.That(total).IsEqualTo(3); + await Assert.That(scenario.Requests.Select(static request => request.RequestUri!.PathAndQuery)) + .IsEquivalentTo(["/api/session/ses_root", "/api/session?limit=200&order=desc&parentID=ses_root", + "/api/session?limit=200&order=desc&parentID=ses_child"], CollectionOrdering.Matching); + } + + [Test] + public async Task GetTotalCostAsync_Should_Sum_A_Grandchild() + { + using var scenario = RootAndLists(1, listQuery => listQuery switch + { + var query when query.Contains("parentID=ses_root", StringComparison.Ordinal) => + SessionCostFixtures.Page([_fixtures.Session("ses_child", 2, "ses_root")]), + var query when query.Contains("parentID=ses_child", StringComparison.Ordinal) => + SessionCostFixtures.Page([_fixtures.Session("ses_grandchild", 3, "ses_child")]), + _ => SessionCostFixtures.Page([]), + }); + + var total = await new SessionsClient(scenario.Pipeline).GetTotalCostAsync("ses_root"); + + await Assert.That(total).IsEqualTo(6); + await Assert.That(scenario.Requests.Select(static request => request.RequestUri!.PathAndQuery)) + .IsEquivalentTo(["/api/session/ses_root", "/api/session?limit=200&order=desc&parentID=ses_root", + "/api/session?limit=200&order=desc&parentID=ses_child", + "/api/session?limit=200&order=desc&parentID=ses_grandchild"], CollectionOrdering.Matching); + } + + [Test] + public async Task GetTotalCostAsync_Should_Sum_The_Root_And_Every_Child_Page() + { + using var scenario = PipelineScenario.Responding(request => + { + if (request.RequestUri!.AbsolutePath != "/api/session") + { + return Answer(SessionCostFixtures.Get(_fixtures.Session("ses_root", 0.5))); + } + + if (!request.RequestUri.Query.Contains("parentID=ses_root", StringComparison.Ordinal)) + { + return Answer(SessionCostFixtures.Page([])); + } + + return Answer(request.RequestUri.Query.Contains("cursor=", StringComparison.Ordinal) + ? _fixtures.Page(200, 50) : _fixtures.Page(0, 200, "page_2")); + }); + + var total = await new SessionsClient(scenario.Pipeline).GetTotalCostAsync("ses_root"); + var expected = new List + { + "GET /api/session/ses_root", + "GET /api/session?limit=200&order=desc&parentID=ses_root", + "GET /api/session?limit=200&parentID=ses_root&cursor=page_2", + }; + expected.AddRange(_fixtures.Children(0, 250).Select(static child => "GET /api/session?limit=200&order=desc&parentID=" + child.Id)); + + await Assert.That(total).IsEqualTo(250.5); + await Assert.That(scenario.Requests.Select(static request => request.Method + " " + request.RequestUri!.PathAndQuery)) + .IsEquivalentTo(expected, CollectionOrdering.Matching); + } + + [Test] + public async Task GetTotalCostAsync_Should_Return_Only_A_Child_Sessions_Own_Cost() + { + using var scenario = PipelineScenario.Responding(request => Answer(request.RequestUri!.AbsolutePath == "/api/session" + ? SessionCostFixtures.Page([]) : SessionCostFixtures.Get(_fixtures.Session("ses_child", 1.25, "ses_root")))); + + var total = await new SessionsClient(scenario.Pipeline).GetTotalCostAsync("ses_child"); + + await Assert.That(total).IsEqualTo(1.25); + await Assert.That(scenario.Requests.Select(static request => request.RequestUri!.PathAndQuery)) + .IsEquivalentTo(["/api/session/ses_child"], CollectionOrdering.Matching); + } + + [Test] + public async Task GetTotalCostAsync_Should_Propagate_The_Declared_NotFound_Error() + { + using var scenario = PipelineScenario.Responding(_ => + new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(WireBodyData.SessionNotFoundError) }); + + var failure = await Assert.That(new SessionsClient(scenario.Pipeline).GetTotalCostAsync("ses_9")) + .Throws(); + + await Assert.That(failure!.Status).IsEqualTo(404); + var error = await Assert.That(failure.Error).IsTypeOf(); + await Assert.That(error!.SessionId).IsEqualTo("ses_9"); + await Assert.That(error.Message).IsEqualTo("gone"); + await Assert.That(failure.RawBody).IsEqualTo(WireBodyData.SessionNotFoundError); + await Assert.That(scenario.Requests.Select(static request => request.RequestUri!.PathAndQuery)) + .IsEquivalentTo(["/api/session/ses_9"], CollectionOrdering.Matching); + } + + [Test] + public async Task GetTotalCostAsync_Should_Refuse_NoThrow_At_The_Call() + { + using var scenario = PipelineScenario.Responding(); + + var failure = Assert.Throws(() => + _ = new SessionsClient(scenario.Pipeline).GetTotalCostAsync("ses_root", OpenCodeRequestOptions.NoThrow)); + + await Assert.That(failure.ParamName).IsEqualTo("requestOptions"); + // ArgumentException renders its parameter suffix differently on .NET Framework. +#if NETFRAMEWORK + const string suffix = "\r\nParameter name: requestOptions"; +#else + const string suffix = " (Parameter 'requestOptions')"; +#endif + await Assert.That(failure.Message).IsEqualTo( + "Session cost totals always throw API errors; NoThrow is not supported." + suffix); + await Assert.That(scenario.Requests).IsEmpty(); + } + + [Test] + [Arguments(" ", "The value cannot be an empty string or composed entirely of whitespace.")] + [Arguments("..", "Route values must not be dot segments.")] + public async Task GetTotalCostAsync_Should_Reject_An_Invalid_Id_At_The_Call(string sessionId, string message) + { + using var scenario = PipelineScenario.Responding(); + + var failure = Assert.Throws(() => + _ = new SessionsClient(scenario.Pipeline).GetTotalCostAsync(sessionId)); + + await Assert.That(failure.ParamName).IsEqualTo("sessionId"); + // ArgumentException renders its parameter suffix differently on .NET Framework. +#if NETFRAMEWORK + const string suffix = "\r\nParameter name: sessionId"; +#else + const string suffix = " (Parameter 'sessionId')"; +#endif + await Assert.That(failure.Message).IsEqualTo(message + suffix); + await Assert.That(scenario.Requests).IsEmpty(); + } + + [Test] + public async Task GetTotalCostAsync_Should_Reject_A_Null_Client() + { + var failure = Assert.Throws(() => + _ = SessionsClientExtensions.GetTotalCostAsync(null!, "ses_root")); + + await Assert.That(failure.ParamName).IsEqualTo("client"); + } + + [Test] + public async Task GetTotalCostAsync_Should_Return_The_Root_Cost_When_There_Are_No_Children() + { + using var scenario = PipelineScenario.Responding(request => Answer(request.RequestUri!.AbsolutePath == "/api/session" + ? SessionCostFixtures.Page([]) : SessionCostFixtures.Get(_fixtures.Session("ses_root", 0.5)))); + + var total = await new SessionsClient(scenario.Pipeline).GetTotalCostAsync("ses_root"); + + await Assert.That(total).IsEqualTo(0.5); + await Assert.That(scenario.Requests.Select(static request => request.RequestUri!.PathAndQuery)) + .IsEquivalentTo(["/api/session/ses_root", "/api/session?limit=200&order=desc&parentID=ses_root"], CollectionOrdering.Matching); + } + + [Test] + public async Task GetTotalCostAsync_Should_Add_The_Root_Before_Children_In_Arrival_Order() + { + using var scenario = RootAndLists(1, query => query.Contains("parentID=ses_root", StringComparison.Ordinal) + ? SessionCostFixtures.Page([_fixtures.Session("ses_small", 1, "ses_root"), + _fixtures.Session("ses_large", 10_000_000_000_000_000d, "ses_root")]) + : SessionCostFixtures.Page([])); + + var total = await new SessionsClient(scenario.Pipeline).GetTotalCostAsync("ses_root"); + + await Assert.That(total).IsEqualTo(10_000_000_000_000_002d); + } + + [Test] + public async Task GetTotalCostAsync_Should_Use_The_Generated_Virtual_Methods_On_A_Mocking_Instance() + { + var client = MockClient(); + using var caller = new CancellationTokenSource(); + var options = new OpenCodeRequestOptions(); + + var total = await client.GetTotalCostAsync("ses_root", options, caller.Token); + + await Assert.That(total).IsEqualTo(2.5); + await Assert.That(client.SessionId).IsEqualTo("ses_root"); + await Assert.That(client.Request!.ParentId).IsEqualTo(SessionParentFilter.Of("ses_root")); + await Assert.That(client.Request.Order).IsEqualTo(ListOrder.Descending); + await Assert.That(client.Request.Limit).IsEqualTo(200); + SessionParentFilter?[] parents = [SessionParentFilter.Of("ses_root"), SessionParentFilter.Of("ses_child")]; + await Assert.That(client.Calls.Select(static call => call.ParentId)).IsEquivalentTo(parents, CollectionOrdering.Matching); + foreach (var call in client.Calls) + { + await Assert.That(call.Options).IsSameReferenceAs(options); + await Assert.That(call.Token).IsEqualTo(caller.Token); + } + + await Assert.That(client.Read.Options).IsSameReferenceAs(options); + await Assert.That(client.Read.Token).IsEqualTo(caller.Token); + } + + [Test] + [Arguments(null)] + [Arguments("ses_root")] + [Arguments("ses_child")] + public async Task GetTotalCostAsync_Should_Propagate_The_Same_Failure(string? listParentId) + { + var failure = new InvalidOperationException("Cost read failed."); + var client = MockClient(failure, listParentId); + + var thrown = await Assert.That(client.GetTotalCostAsync("ses_root")).Throws(); + + await Assert.That(thrown).IsSameReferenceAs(failure); + } + + private PipelineScenario RootAndLists(double rootCost, Func page) => + PipelineScenario.Responding(request => + { + if (request.RequestUri!.AbsolutePath != "/api/session") + { + return Answer(SessionCostFixtures.Get(_fixtures.Session("ses_root", rootCost))); + } + + return Answer(page(request.RequestUri.Query)); + }); + + private CostSessionsClient MockClient(Exception? failure = null, string? listParentId = null) => + new(new CostSessionClient(_fixtures.Session("ses_root", 0.5), listParentId is null ? failure : null), + new SessionListResponse { Status = 200, Sessions = [_fixtures.Session("ses_child", 2, "ses_root")], Cursor = new ListCursor() }, + listParentId is null ? null : failure, listParentId); + + private static HttpResponseMessage Answer(string body) => new(HttpStatusCode.OK) { Content = new StringContent(body) }; + + private sealed class CostSessionClient(SessionInfo session, Exception? failure) : SessionClient + { + public OpenCodeRequestOptions? Options { get; private set; } + public CancellationToken Token { get; private set; } + + public override Task GetAsync(OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) + { + Options = requestOptions; + Token = cancellationToken; + return failure is null ? Task.FromResult(new SessionResponse { Status = 200, Session = session }) + : Task.FromException(failure); + } + } + + private sealed class CostSessionsClient(CostSessionClient read, SessionListResponse page, Exception? failure, string? listParentId) : SessionsClient + { + public CostSessionClient Read => read; + public string? SessionId { get; private set; } + public SessionListRequest? Request { get; private set; } + public List<(SessionParentFilter? ParentId, OpenCodeRequestOptions? Options, CancellationToken Token)> Calls { get; } = []; + + public override SessionClient GetSessionClient(string sessionId) + { + SessionId = sessionId; + return read; + } + + public override Task ListSessionsAsync(SessionListRequest? request = null, + OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) + { + Calls.Add((request?.ParentId, requestOptions, cancellationToken)); + if (failure is not null && listParentId is not null && request?.ParentId == SessionParentFilter.Of(listParentId)) + { + return Task.FromException(failure); + } + + if (request?.ParentId != SessionParentFilter.Of("ses_root")) + { + return Task.FromResult(page with { Sessions = [] }); + } + + Request = request; + return Task.FromResult(page); + } + } +} diff --git a/tests/OpenCode.Sdk.Tests/Sessions/Support/SessionCostFixtures.cs b/tests/OpenCode.Sdk.Tests/Sessions/Support/SessionCostFixtures.cs new file mode 100644 index 00000000..d9c6cab3 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Sessions/Support/SessionCostFixtures.cs @@ -0,0 +1,43 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Nodes; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Models; +using OpenCode.Sdk.Tests.Harness; + +namespace OpenCode.Sdk.Tests.Sessions.Support; + +internal sealed class SessionCostFixtures +{ + private readonly SessionInfo _template = JsonSerializer.Deserialize( + new FixtureLoader().LoadJson("Serialization.known-session.json"), OpenCodeJsonContext.Default.SessionInfo) + ?? throw new InvalidOperationException("The session template is null."); + + internal SessionInfo Session(string id, double cost, string? parentId = null) => + _template with { Id = id, Cost = cost, ParentId = parentId }; + + internal static string Get(SessionInfo session) => + new JsonObject { ["data"] = JsonSerializer.SerializeToNode(session, OpenCodeJsonContext.Default.SessionInfo) }.ToJsonString(); + + internal string Page(int start, int count, string? next = null) => + Page(Children(start, count), next); + + internal IEnumerable Children(int start, int count) => + Enumerable.Range(start, count).Select(index => + Session("ses_child_" + index.ToString(CultureInfo.InvariantCulture), 1, "ses_root")); + + internal static string Page(IEnumerable sessions, string? next = null) + { + var items = new JsonArray(); + foreach (var session in sessions) + { + items.Add(JsonSerializer.SerializeToNode(session, OpenCodeJsonContext.Default.SessionInfo)); + } + + return new JsonObject + { + ["data"] = items, + ["cursor"] = new JsonObject { ["next"] = next }, + }.ToJsonString(); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt b/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt index 04c027ae..bffba9f8 100644 --- a/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt +++ b/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt @@ -2231,6 +2231,10 @@ namespace OpenCode.Sdk public virtual OpenCode.Sdk.SessionClient GetSessionClient(string sessionId) { } public virtual System.Threading.Tasks.Task ListSessionsAsync(OpenCode.Sdk.SessionListRequest? request = null, OpenCode.Sdk.OpenCodeRequestOptions? requestOptions = null, System.Threading.CancellationToken cancellationToken = default) { } } + public static class SessionsClientExtensions + { + public static System.Threading.Tasks.Task GetTotalCostAsync(this OpenCode.Sdk.SessionsClient client, string sessionId, OpenCode.Sdk.OpenCodeRequestOptions? requestOptions = null, System.Threading.CancellationToken cancellationToken = default) { } + } public class ShellClient { protected ShellClient() { } diff --git a/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs b/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs index beb960df..328ea513 100644 --- a/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs +++ b/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs @@ -52,6 +52,7 @@ internal static class GeneratedSourceCompiler /// 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. + /// The session cost total sits above the generated SessionsClient, SessionClient and SessionListRequest, so it rides their emissions. /// internal static readonly (string Consumer, string RequiredEmission)[] GeneratedSurfaceConsumers = [ @@ -112,6 +113,11 @@ internal static readonly (string Consumer, string RequiredEmission)[] GeneratedS ("Rpc/Internal/RpcMethodCaller.cs", "Rpc/RpcClient.cs"), ("Rpc/RpcClientExtensions.cs", "Rpc/RpcClient.cs"), ("Rpc/RpcEventPayload.cs", "Events/Models/EventRpc.cs"), + ("Sessions/Internal/SessionCostTotal.cs", "Sessions/SessionsClient.cs"), + ("Sessions/Internal/SessionCostTotal.cs", "Sessions/SessionClient.cs"), + ("Sessions/Internal/SessionCostTotal.cs", "Sessions/SessionListRequest.cs"), + ("Sessions/SessionsClientExtensions.cs", "Sessions/SessionsClient.cs"), + ("Sessions/SessionsClientExtensions.cs", "Sessions/SessionClient.cs"), ]; /// diff --git a/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs b/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs index f2d90cdc..5a3ee072 100644 --- a/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs +++ b/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs @@ -164,6 +164,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "RpcEventPayload", "RpcMethod", "SessionParentFilter", + "SessionsClientExtensions", ], StringComparer.Ordinal); @@ -405,6 +406,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "ServiceTerminator", "ServiceTiming", "ServiceVersionPolicy", + "SessionCostTotal", "SignalDelivery", "SharedEventFeed", "SlopwatchSuppressAttribute",