-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Wait for OpenCode Go Zen balance in CLI usage reads #2583
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
steipete
merged 4 commits into
steipete:main
from
Yuxin-Qiao:codex/fix-opencodego-zen-balance-2581
Aug 5, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
102 changes: 102 additions & 0 deletions
102
Tests/CodexBarTests/OpenCodeGoOptionalZenBalanceTimeoutTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| import Foundation | ||
| import Testing | ||
| @testable import CodexBarCore | ||
|
|
||
| private final class OptionalZenBalanceTimeoutRecorder<Value: Sendable>: @unchecked Sendable { | ||
| private let lock = NSLock() | ||
| private var storage: [Value] = [] | ||
|
|
||
| func append(_ value: Value) { | ||
| self.lock.lock() | ||
| defer { self.lock.unlock() } | ||
| self.storage.append(value) | ||
| } | ||
|
|
||
| var values: [Value] { | ||
| self.lock.lock() | ||
| defer { self.lock.unlock() } | ||
| return self.storage | ||
| } | ||
| } | ||
|
|
||
| struct OpenCodeGoOptionalZenBalanceTimeoutTests { | ||
| @Test | ||
| func `optional zen balance caps workspace and balance request timeouts`() async throws { | ||
| defer { | ||
| OptionalZenBalanceTimeoutURLProtocol.handler = nil | ||
| } | ||
|
|
||
| let timeouts = OptionalZenBalanceTimeoutRecorder<TimeInterval>() | ||
| OptionalZenBalanceTimeoutURLProtocol.handler = { request in | ||
| guard let url = request.url else { throw URLError(.badURL) } | ||
| timeouts.append(request.timeoutInterval) | ||
| if url.path == "/_server" { | ||
| return Self.makeResponse( | ||
| url: url, | ||
| body: #"{"workspaces":[{"id":"wrk_TEST123"}]}"#, | ||
| contentType: "application/json") | ||
| } | ||
| #expect(url.path == "/workspace/wrk_TEST123") | ||
| return Self.makeResponse( | ||
| url: url, | ||
| body: #"<html><body><h2>Current balance $98.76</h2></body></html>"#, | ||
| contentType: "text/html") | ||
| } | ||
|
|
||
| let configuration = URLSessionConfiguration.ephemeral | ||
| configuration.protocolClasses = [OptionalZenBalanceTimeoutURLProtocol.self] | ||
| let balance = try await OpenCodeGoUsageFetcher.fetchOptionalZenBalance( | ||
| cookieHeader: "auth=test", | ||
| timeout: 60, | ||
| session: URLSession(configuration: configuration)) | ||
|
|
||
| #expect(balance == 98.76) | ||
| #expect(timeouts.values == [5, 5]) | ||
| } | ||
|
|
||
| private static func makeResponse( | ||
| url: URL, | ||
| body: String, | ||
| contentType: String) -> (HTTPURLResponse, Data) | ||
| { | ||
| let response = HTTPURLResponse( | ||
| url: url, | ||
| statusCode: 200, | ||
| httpVersion: "HTTP/1.1", | ||
| headerFields: ["Content-Type": contentType])! | ||
| return (response, Data(body.utf8)) | ||
| } | ||
| } | ||
|
|
||
| private final class OptionalZenBalanceTimeoutURLProtocol: URLProtocol { | ||
| private static let handlerBox = LockIsolated<((URLRequest) throws -> (HTTPURLResponse, Data))?>(nil) | ||
| static var handler: ((URLRequest) throws -> (HTTPURLResponse, Data))? { | ||
| get { Self.handlerBox.value } | ||
| set { Self.handlerBox.setValue(newValue) } | ||
| } | ||
|
|
||
| override static func canInit(with request: URLRequest) -> Bool { | ||
| request.url?.host == "opencode.ai" | ||
| } | ||
|
|
||
| override static func canonicalRequest(for request: URLRequest) -> URLRequest { | ||
| request | ||
| } | ||
|
|
||
| override func startLoading() { | ||
| guard let handler = Self.handler else { | ||
| self.client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse)) | ||
| return | ||
| } | ||
| do { | ||
| let (response, data) = try handler(self.request) | ||
| self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) | ||
| self.client?.urlProtocol(self, didLoad: data) | ||
| self.client?.urlProtocolDidFinishLoading(self) | ||
| } catch { | ||
| self.client?.urlProtocol(self, didFailWithError: error) | ||
| } | ||
| } | ||
|
|
||
| override func stopLoading() {} | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When the subscription request or parsing takes more than five seconds but the Zen task has already completed successfully, this returns a zero timeout and then races an observer of the completed source task against
Task.sleep(for: .zero). The timeout task can win and cancel/discard that already-available balance, so the new completeness path can still omitproviderCostnondeterministically on slow subscription responses. Start and retain the timeout race when the Zen task is created, so completion before the deadline is recorded independently of when subscription parsing finishes.Useful? React with 👍 / 👎.