Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Bound provider stream startup waits

rcourtmane1a9b6986280
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 66e655a06a..a0cb863b0a 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -6767,11 +6767,11 @@
{
"id": "codex-lane-followup-architecture-post-rc-canonicalization",
"agent_id": "codex",
- "summary": "Add same-model OpenRouter fallback for Assistant provider route failures",
+ "summary": "Bound Assistant OpenAI-compatible first-token waits",
"target_id": "v6-product-lane-expansion",
"claimed_at": "2026-06-05T21:57:48Z",
- "heartbeat_at": "2026-06-05T23:22:05Z",
- "expires_at": "2026-06-06T01:22:05Z",
+ "heartbeat_at": "2026-06-05T23:28:35Z",
+ "expires_at": "2026-06-06T01:28:35Z",
"work_item": {
"kind": "lane-followup",
"id": "architecture-post-rc-canonicalization"
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 7f9d5a1701..4637cb4e01 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -166,9 +166,8 @@ runtime cost control, and shared AI transport surfaces.
provider defaults. That same-model gateway planning must remain catalog-free
and may continue to the next configured provider if the gateway attempt also
fails before visible output. Once visible output has streamed, Pulse must
- not silently switch
- providers for that turn; the error belongs to the visible attempt and is
- surfaced through normal failed-turn recovery. Assistant
+ not silently switch providers for that turn; the error belongs to the visible
+ attempt and is surfaced through normal failed-turn recovery. Assistant
completion events must carry the effective model route that actually
completed the turn, and the drawer must update the in-flight transcript row
when `provider_fallback` names the next route so message labels, cost
@@ -207,7 +206,8 @@ runtime cost control, and shared AI transport surfaces.
rendering before changing Pulse behavior; parity means adapting the proven
interaction model, not guessing from screenshots or observed behavior alone.
Streamed provider startup must be bounded by the configured Assistant request
- timeout and the OpenAI-compatible SSE response-header guard; transient
+ timeout, the OpenAI-compatible SSE response-header guard, and the first SSE
+ body-read guard adapted from OpenCode's provider `wrapSSE` source; transient
startup failures may retry once before surfacing failed-turn recovery, but a
stalled route must not leave the user in an opaque first-token wait for the
full provider timeout.
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.go
index 3750b91515..318c5494cd 100644
--- a/internal/ai/providers/openai.go
+++ b/internal/ai/providers/openai.go
@@ -22,6 +22,7 @@ const (
openaiStreamMaxRetries = 1
openaiStreamInitialBackoff = 1 * time.Second
openaiStreamResponseHeaderTimeout = 12 * time.Second
+ openaiStreamFirstEventTimeout = 12 * time.Second
openrouterRefererURL = "https://pulse.app"
openrouterAppTitle = "Pulse"
// OpenRouter preflights affordability against the requested maximum
@@ -41,6 +42,10 @@ type OpenAIClient struct {
requestTimeout time.Duration
client *http.Client
streamClient *http.Client
+ // OpenAI-compatible gateways can accept SSE headers and then stall before
+ // the first body chunk. Bound that gap separately from the full turn timeout
+ // so chat fallback can move before the drawer looks dead.
+ streamFirstEventTimeout time.Duration
}
// NewOpenAIClient creates a new OpenAI API client
@@ -78,12 +83,13 @@ func NewOpenAIClient(apiKey, model, baseURL string, timeout time.Duration) *Open
timeout = 300 * time.Second // Default 5 minutes
}
return &OpenAIClient{
- apiKey: apiKey,
- model: model,
- baseURL: baseURL,
- requestTimeout: timeout,
- client: &http.Client{Timeout: timeout},
- streamClient: newOpenAIStreamHTTPClient(timeout),
+ apiKey: apiKey,
+ model: model,
+ baseURL: baseURL,
+ requestTimeout: timeout,
+ client: &http.Client{Timeout: timeout},
+ streamClient: newOpenAIStreamHTTPClient(timeout),
+ streamFirstEventTimeout: boundedOpenAIStreamFirstEventTimeout(timeout),
}
}
@@ -104,6 +110,44 @@ func boundedOpenAIStreamResponseHeaderTimeout(timeout time.Duration) time.Durati
return openaiStreamResponseHeaderTimeout
}
+func boundedOpenAIStreamFirstEventTimeout(timeout time.Duration) time.Duration {
+ if timeout > 0 && timeout < openaiStreamFirstEventTimeout {
+ return timeout
+ }
+ return openaiStreamFirstEventTimeout
+}
+
+type openAIStreamReadResult struct {
+ n int
+ err error
+}
+
+func readOpenAIStreamChunk(ctx context.Context, body io.ReadCloser, buf []byte, timeout time.Duration, enforceTimeout bool) (int, error) {
+ if !enforceTimeout || timeout <= 0 {
+ return body.Read(buf)
+ }
+
+ resultCh := make(chan openAIStreamReadResult, 1)
+ go func() {
+ n, err := body.Read(buf)
+ resultCh <- openAIStreamReadResult{n: n, err: err}
+ }()
+
+ timer := time.NewTimer(timeout)
+ defer timer.Stop()
+
+ select {
+ case result := <-resultCh:
+ return result.n, result.err
+ case <-ctx.Done():
+ _ = body.Close()
+ return 0, ctx.Err()
+ case <-timer.C:
+ _ = body.Close()
+ return 0, fmt.Errorf("stream first event timed out after %s", timeout)
+ }
+}
+
func isRetryableOpenAIStreamStartupError(err error) bool {
if err == nil {
return false
@@ -942,6 +986,7 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
reader := resp.Body
buf := make([]byte, 4096)
var pendingData string
+ firstStreamBytesSeen := false
toolCallBuilders := make(map[int]*openaiStreamToolCallBuilder)
var inputTokens, outputTokens int
var finishReason string
@@ -1049,8 +1094,9 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
}
for {
- n, err := reader.Read(buf)
+ n, err := readOpenAIStreamChunk(streamCtx, reader, buf, c.streamFirstEventTimeout, !firstStreamBytesSeen)
if n > 0 {
+ firstStreamBytesSeen = true
pendingData += string(buf[:n])
lines := strings.Split(pendingData, "\n")
diff --git a/internal/ai/providers/openai_test.go b/internal/ai/providers/openai_test.go
index efe3ad67ab..addc134339 100644
--- a/internal/ai/providers/openai_test.go
+++ b/internal/ai/providers/openai_test.go
@@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync"
"testing"
"time"
@@ -39,6 +40,27 @@ func (b *readOnceEOFBody) Close() error {
return nil
}
+type blockingReadCloser struct {
+ closed chan struct{}
+ once sync.Once
+}
+
+func newBlockingReadCloser() *blockingReadCloser {
+ return &blockingReadCloser{closed: make(chan struct{})}
+}
+
+func (b *blockingReadCloser) Read([]byte) (int, error) {
+ <-b.closed
+ return 0, io.ErrClosedPipe
+}
+
+func (b *blockingReadCloser) Close() error {
+ b.once.Do(func() {
+ close(b.closed)
+ })
+ return nil
+}
+
func TestOpenAIClient_ChatStream_Success(t *testing.T) {
// Mock OpenAI SSE stream
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -134,11 +156,41 @@ func TestNewOpenAIClient_BoundsStreamResponseHeaderTimeout(t *testing.T) {
transport, ok := client.streamClient.Transport.(*http.Transport)
require.True(t, ok)
assert.Equal(t, openaiStreamResponseHeaderTimeout, transport.ResponseHeaderTimeout)
+ assert.Equal(t, openaiStreamFirstEventTimeout, client.streamFirstEventTimeout)
shortTimeoutClient := NewOpenAIClient("sk-test", "gpt-4", "https://api.openai.com/v1", 2*time.Second)
shortTransport, ok := shortTimeoutClient.streamClient.Transport.(*http.Transport)
require.True(t, ok)
assert.Equal(t, 2*time.Second, shortTransport.ResponseHeaderTimeout)
+ assert.Equal(t, 2*time.Second, shortTimeoutClient.streamFirstEventTimeout)
+}
+
+func TestOpenAIClient_ChatStream_TimesOutWaitingForFirstStreamEvent(t *testing.T) {
+ body := newBlockingReadCloser()
+ client := NewOpenAIClient("sk-test", "gpt-4", "https://example.invalid/v1", time.Second)
+ client.streamFirstEventTimeout = 10 * time.Millisecond
+ client.streamClient = &http.Client{
+ Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: body,
+ }, nil
+ }),
+ }
+
+ started := time.Now()
+ var eventCount int
+ err := client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "Hi"}},
+ }, func(StreamEvent) {
+ eventCount++
+ })
+
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "stream first event timed out")
+ assert.Less(t, time.Since(started), 200*time.Millisecond)
+ assert.Equal(t, 0, eventCount)
}
// TestOpenAIClient_ChatStream_OpenRouterReasoning guards the OpenRouter reasoning