Repository navigation
fix: route SSE streaming through WP HTTP API + http_api_curl - #15
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughRefactors OpenTrust_Chat_Provider::stream_post() to use wp_safe_remote_post() with a request-scoped http_api_curl filter that installs cURL header/write callbacks for incremental SSE parsing, early-status capture, error-body accumulation, connection-abort handling, and consistent error reporting. Updates POT with new cURL requirement messages and timestamp. ChangesSSE Streaming Transport Refactor
i18n catalog updates
Sequence Diagram(s)sequenceDiagram
participant Method as stream_post()
participant WP as wp_safe_remote_post()
participant Filter as http_api_curl Filter
participant cURL as cURL Handle
participant SSE as SSE Parser
participant ErrorBuf as Error Buffer
Method->>Method: Initialize shared state
Method->>WP: Register filter and call (Accept: text/event-stream)
WP->>Filter: Provide cURL handle during setup
Filter->>cURL: Set CURLOPT_HEADERFUNCTION
Filter->>cURL: Set CURLOPT_WRITEFUNCTION
cURL->>Filter: Header callback (captures early HTTP status)
loop For each response chunk
cURL->>Filter: Write callback invoked with chunk
alt early status is 2xx
Filter->>SSE: Buffer until newline, emit complete SSE lines
SSE->>Method: Deliver SSE event lines
else non-2xx
Filter->>ErrorBuf: Accumulate response body (no SSE parsing)
end
alt connection_aborted()
Filter-->>cURL: Return 0 (abort transfer)
end
end
cURL-->>WP: Transfer complete
WP-->>Method: Return response
Method->>Method: Flush trailing SSE buffer (if 2xx) and derive final HTTP code
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@includes/providers/class-opentrust-chat-provider.php`:
- Around line 527-535: Initialize a curl_hook_ran flag on the $state object
(e.g., 'curl_hook_ran' => false) when you build $state; inside the http_api_curl
filter callback (the $filter closure that calls curl_init() and sets
CURLOPT_HEADERFUNCTION/WRITEFUNCTION) set $state->curl_hook_ran = true; after
you call remove_action(...) verify $state->curl_hook_ran is true and if not set
an appropriate error on $state (e.g., populate $state->error_body and return a
WP_Error or fail the request) so streaming doesn’t silently fall back when a
non-cURL transport was selected.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 929de1e4-d515-47c6-bcfd-c8cfd46f699c
📒 Files selected for processing (1)
includes/providers/class-opentrust-chat-provider.php
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@includes/providers/class-opentrust-chat-provider.php`:
- Around line 599-613: The http hook added with add_action('http_api_curl',
$filter, 10, 3) might not be removed if wp_safe_remote_post() throws, so wrap
the wp_safe_remote_post($url, [...]) invocation in a try/finally block: call
add_action(...) before the try, perform the wp_safe_remote_post(...) inside the
try, and always call remove_action('http_api_curl', $filter, 10) inside the
finally so the SSE-specific curl handler ($filter) is unregistered even on
exceptions; reference the existing symbols add_action, wp_safe_remote_post,
$filter, and remove_action when making the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: cef3a939-0847-49be-bb87-d8c952577533
📒 Files selected for processing (2)
includes/providers/class-opentrust-chat-provider.phplanguages/opentrust.pot
Claude Code reviewVerdict: APPROVE This is a clean, faithful implementation of the round-2 analysis. The single raw-cURL block at Checks performed
QA gate (per analysis.md §"Open verification")The author's PR body acknowledges the single critical manual gate: open Minor non-blocking observations
— Claude (automated review on behalf of @nolderoos) |
The previous code installed both CURLOPT_WRITEFUNCTION and CURLOPT_HEADERFUNCTION
via the http_api_curl filter. Replacing HEADERFUNCTION clobbered WP's Requests Curl
transport stream_headers() method, leaving its internal $this->headers buffer empty.
After curl_exec, Requests::parse_response() called strpos('', "\r\n\r\n"), got false,
and threw \WpOrg\Requests\Exception('Missing header/body separator', 'requests.no_crlf_separator')
out of wp-includes/Requests/src/Requests.php:737. WP wrapped it as WP_Error, the
upstream Anthropic call returned ['ok' => false, 'error' => 'Missing header/body
separator'], and the chat UI rendered that exact string as a red error banner
beneath an empty assistant bubble — even on successful upstream streams.
The round-2 analysis at wporg-review/04-curl-vs-http-api/analysis.md:16 predicted
$this->headers would stay empty but assumed WP would "bubble up a response array
with empty body, empty headers, falsy code." It does not; parse_response throws
before WP can wrap the response.
Fix:
- Remove the CURLOPT_HEADERFUNCTION setopt entirely so Requests' stream_headers
runs unmodified and accumulates the header block ending in \r\n\r\n. After
our WRITEFUNCTION consumes the body, Requests' parser finds the separator
(headers + empty body) and returns a normal response array.
- Capture early_status lazily inside WRITEFUNCTION via curl_getinfo($ch,
CURLINFO_HTTP_CODE). cURL guarantees the status line is parsed before any
body callback fires, so this is reliable. Keeps the same error-body routing
semantics for non-2xx upstream responses.
- After wp_safe_remote_post returns, copy headers from
wp_remote_retrieve_headers($response) into $state->response_headers so
describe_streaming_error() still surfaces retry-after / anthropic-ratelimit-*
/ x-ratelimit-* hints in the error path.
- Add a load-bearing comment above the filter explaining why HEADERFUNCTION
must not be re-added.
Net diff: +38 / -28. No change to streaming semantics, visitor-abort handling,
host allowlist, SSL verification, or error-body shape. The wp.org reviewer's
constraint (route outbound HTTP through wp_safe_remote_post / wp_safe_remote_get
and use http_api_curl only as the documented escape hatch for setopt) is
preserved — and tightened, since this drops one setopt call.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Line refs in includes/providers/class-opentrust-chat-provider.php shifted when the CURLOPT_HEADERFUNCTION block was deleted in d54bc42: - "AI streaming requires the WordPress cURL transport.": 622 → 620 - "Provider returned HTTP %d": 664 → 674, 719 → 729 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes #14
What
Refactors
OpenTrust_Chat_Provider::stream_post()to drive outbound SSE requests throughwp_safe_remote_post().CURLOPT_WRITEFUNCTION/CURLOPT_HEADERFUNCTION(and the connect-timeout split) are installed via a one-shot, URL-scopedhttp_api_curlaction and removed unconditionally after the request.Why
wp.org review round 1, issue 4. The only raw
curl_init/curl_execblock in the plugin is replaced with the documented WP HTTP API escape hatch. Real-time token streaming, visitor abort, host allowlist, SSL verify, no-redirect, and thedescribe_streaming_error()rate-limit log path are all preserved. Falls back to a clean error return whencurl_initis unavailable so non-cURL transports never silently buffer.QA gate
Open
/trust-center/ask/, ask a multi-token question, confirm tokens stream word-by-word. Click "Stop" mid-stream and confirm the request aborts within ~1 s.Summary by CodeRabbit
Bug Fixes
Documentation