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 Assistant stream provider startup

rcourtman9c06cda3ea45
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 375a0b37dd..6d9c998529 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -128,6 +128,11 @@ runtime cost control, and shared AI transport surfaces.
notable model/provider before falling back to the general model selector.
Retry remains available, but it must not be the only visible action when a
failed Assistant turn is shown.
+ Streamed provider startup must be bounded by the configured Assistant request
+ timeout and the OpenAI-compatible SSE response-header guard; 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.
Restored Assistant sessions must hydrate saved assistant content and
persisted tool calls into the same transcript event shape used by live
streams so switching sessions does not hide prior tool evidence or collapse
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 41d1e56656..2673f61815 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -2263,7 +2263,7 @@ func (s *Service) createProviderForModel(modelStr string) (providers.StreamingPr
providerName := parts[0]
modelName := parts[1]
- timeout := 5 * time.Minute
+ timeout := s.cfg.GetRequestTimeout()
switch providerName {
case "anthropic":
diff --git a/internal/ai/chat/service_patrol_additional_test.go b/internal/ai/chat/service_patrol_additional_test.go
index df4893a98f..d5e8612de6 100644
--- a/internal/ai/chat/service_patrol_additional_test.go
+++ b/internal/ai/chat/service_patrol_additional_test.go
@@ -91,6 +91,41 @@ func TestService_CreateProviderForModel(t *testing.T) {
}
}
+func TestService_CreateProviderForModel_UsesConfiguredRequestTimeout(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ time.Sleep(1500 * time.Millisecond)
+ w.Header().Set("Content-Type", "text/event-stream")
+ _, _ = w.Write([]byte("data: [DONE]\n"))
+ }))
+ defer server.Close()
+
+ svc := &Service{
+ cfg: &config.AIConfig{
+ OpenAIAPIKey: "sk-test",
+ OpenAIBaseURL: server.URL,
+ RequestTimeoutSeconds: 1,
+ },
+ }
+
+ provider, err := svc.createProviderForModel("openai:gpt-4")
+ if err != nil {
+ t.Fatalf("expected openai provider: %v", err)
+ }
+
+ start := time.Now()
+ err = provider.ChatStream(context.Background(), providers.ChatRequest{
+ Messages: []providers.Message{{Role: "user", Content: "Hi"}},
+ }, func(providers.StreamEvent) {})
+ elapsed := time.Since(start)
+
+ if err == nil {
+ t.Fatal("expected configured request timeout to bound streamed provider startup")
+ }
+ if elapsed >= 1400*time.Millisecond {
+ t.Fatalf("expected configured timeout near 1s, took %s", elapsed)
+ }
+}
+
func TestService_CreateProviderForModel_OllamaUsesConfiguredBasicAuth(t *testing.T) {
versionHits := 0
tagsHits := 0
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.go
index 32f62207c0..f0c2ef5e88 100644
--- a/internal/ai/providers/openai.go
+++ b/internal/ai/providers/openai.go
@@ -16,11 +16,14 @@ import (
)
const (
- openaiAPIURL = "https://api.openai.com/v1/chat/completions"
- openaiMaxRetries = 3
- openaiInitialBackoff = 2 * time.Second
- openrouterRefererURL = "https://pulse.app"
- openrouterAppTitle = "Pulse"
+ openaiAPIURL = "https://api.openai.com/v1/chat/completions"
+ openaiMaxRetries = 3
+ openaiInitialBackoff = 2 * time.Second
+ openaiStreamMaxRetries = 1
+ openaiStreamInitialBackoff = 1 * time.Second
+ openaiStreamResponseHeaderTimeout = 12 * time.Second
+ openrouterRefererURL = "https://pulse.app"
+ openrouterAppTitle = "Pulse"
// OpenRouter preflights affordability against the requested maximum
// completion budget. Leaving it unset can make small chat turns reserve a
// model-scale default and fail against per-key total limits.
@@ -30,10 +33,12 @@ const (
// OpenAIClient implements the Provider interface for OpenAI's API
// Also works with OpenAI-compatible APIs like DeepSeek
type OpenAIClient struct {
- apiKey string
- model string
- baseURL string
- client *http.Client
+ apiKey string
+ model string
+ baseURL string
+ requestTimeout time.Duration
+ client *http.Client
+ streamClient *http.Client
}
// NewOpenAIClient creates a new OpenAI API client
@@ -71,13 +76,46 @@ 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,
- client: &http.Client{
- Timeout: timeout,
- },
+ apiKey: apiKey,
+ model: model,
+ baseURL: baseURL,
+ requestTimeout: timeout,
+ client: &http.Client{Timeout: timeout},
+ streamClient: newOpenAIStreamHTTPClient(timeout),
+ }
+}
+
+func newOpenAIStreamHTTPClient(timeout time.Duration) *http.Client {
+ client := &http.Client{}
+ if transport, ok := http.DefaultTransport.(*http.Transport); ok {
+ transport = transport.Clone()
+ transport.ResponseHeaderTimeout = boundedOpenAIStreamResponseHeaderTimeout(timeout)
+ client.Transport = transport
}
+ return client
+}
+
+func boundedOpenAIStreamResponseHeaderTimeout(timeout time.Duration) time.Duration {
+ if timeout > 0 && timeout < openaiStreamResponseHeaderTimeout {
+ return timeout
+ }
+ return openaiStreamResponseHeaderTimeout
+}
+
+func isRetryableOpenAIStreamStartupError(err error) bool {
+ if err == nil {
+ return false
+ }
+ errStr := strings.ToLower(err.Error())
+ return strings.Contains(errStr, "connection reset") ||
+ strings.Contains(errStr, "connection refused") ||
+ strings.Contains(errStr, "eof")
+}
+
+func isRetryableOpenAIStreamStatus(statusCode int) bool {
+ return statusCode == http.StatusBadGateway ||
+ statusCode == http.StatusServiceUnavailable ||
+ statusCode == http.StatusGatewayTimeout
}
// Name returns the provider name
@@ -766,33 +804,87 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
return fmt.Errorf("failed to marshal request: %w", err)
}
- httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL, bytes.NewReader(body))
- if err != nil {
- return fmt.Errorf("failed to create request: %w", err)
+ streamCtx := ctx
+ var cancelStream context.CancelFunc
+ if c.requestTimeout > 0 {
+ streamCtx, cancelStream = context.WithTimeout(ctx, c.requestTimeout)
+ defer cancelStream()
}
- httpReq.Header.Set("Content-Type", "application/json")
- httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
- httpReq.Header.Set("Accept", "text/event-stream")
- c.applyProviderHeaders(httpReq)
-
- resp, err := c.client.Do(httpReq)
- if err != nil {
- return fmt.Errorf("request failed: %w", err)
+ var resp *http.Response
+ var lastErr error
+ streamClient := c.streamClient
+ if streamClient == nil {
+ streamClient = c.client
}
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
+ for attempt := 0; attempt <= openaiStreamMaxRetries; attempt++ {
+ if attempt > 0 {
+ backoff := openaiStreamInitialBackoff * time.Duration(1<<(attempt-1))
+ log.Warn().
+ Int("attempt", attempt).
+ Dur("backoff", backoff).
+ Str("last_error", lastErr.Error()).
+ Msg("Retrying OpenAI/DeepSeek stream startup after transient error")
+
+ backoffTimer := time.NewTimer(backoff)
+ select {
+ case <-streamCtx.Done():
+ if !backoffTimer.Stop() {
+ select {
+ case <-backoffTimer.C:
+ default:
+ }
+ }
+ return streamCtx.Err()
+ case <-backoffTimer.C:
+ }
+ }
+
+ httpReq, err := http.NewRequestWithContext(streamCtx, "POST", c.baseURL, bytes.NewReader(body))
+ if err != nil {
+ return fmt.Errorf("failed to create request: %w", err)
+ }
+
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
+ httpReq.Header.Set("Accept", "text/event-stream")
+ c.applyProviderHeaders(httpReq)
+
+ resp, err = streamClient.Do(httpReq)
+ if err != nil {
+ if isRetryableOpenAIStreamStartupError(err) {
+ lastErr = fmt.Errorf("connection error: %w", err)
+ continue
+ }
+ return fmt.Errorf("request failed: %w", err)
+ }
+
+ if resp.StatusCode == http.StatusOK {
+ lastErr = nil
+ break
+ }
+
respBody, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
var errResp openaiError
+ errMsg := string(respBody)
if err := json.Unmarshal(respBody, &errResp); err == nil && errResp.Error.Message != "" {
- errMsg := appendRateLimitInfo(errResp.Error.Message, resp)
- return fmt.Errorf("API error (%d): %s", resp.StatusCode, errMsg)
+ errMsg = errResp.Error.Message
+ }
+ errMsg = appendRateLimitInfo(errMsg, resp)
+ lastErr = fmt.Errorf("API error (%d): %s", resp.StatusCode, errMsg)
+ if isRetryableOpenAIStreamStatus(resp.StatusCode) {
+ continue
}
- errMsg := appendRateLimitInfo(string(respBody), resp)
- return fmt.Errorf("API error (%d): %s", resp.StatusCode, errMsg)
+ return lastErr
}
+ if lastErr != nil {
+ return fmt.Errorf("request failed after %d stream retries: %w", openaiStreamMaxRetries, lastErr)
+ }
+ defer resp.Body.Close()
+
// Parse SSE stream
reader := resp.Body
buf := make([]byte, 4096)
diff --git a/internal/ai/providers/openai_test.go b/internal/ai/providers/openai_test.go
index 7cb7c9fed7..6c3336ce13 100644
--- a/internal/ai/providers/openai_test.go
+++ b/internal/ai/providers/openai_test.go
@@ -94,6 +94,53 @@ func TestOpenAIClient_ChatStream_Success(t *testing.T) {
assert.True(t, doneCalled)
}
+func TestOpenAIClient_ChatStream_RetriesTransientStartupError(t *testing.T) {
+ client := NewOpenAIClient("sk-test", "gpt-4", "https://example.invalid/v1", 0)
+ attempts := 0
+ client.streamClient = &http.Client{
+ Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ attempts++
+ if attempts == 1 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(
+ "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n" +
+ "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n" +
+ "data: [DONE]\n",
+ )),
+ }, nil
+ }),
+ }
+
+ var content string
+ err := client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "Hi"}},
+ }, func(event StreamEvent) {
+ if event.Type == "content" {
+ content += event.Data.(ContentEvent).Text
+ }
+ })
+
+ require.NoError(t, err)
+ assert.Equal(t, 2, attempts)
+ assert.Equal(t, "ok", content)
+}
+
+func TestNewOpenAIClient_BoundsStreamResponseHeaderTimeout(t *testing.T) {
+ client := NewOpenAIClient("sk-test", "gpt-4", "https://api.openai.com/v1", 0)
+ transport, ok := client.streamClient.Transport.(*http.Transport)
+ require.True(t, ok)
+ assert.Equal(t, openaiStreamResponseHeaderTimeout, transport.ResponseHeaderTimeout)
+
+ 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)
+}
+
// TestOpenAIClient_ChatStream_OpenRouterReasoning guards the OpenRouter reasoning
// path. OpenRouter (and other OpenAI-compatible gateways) stream chain-of-thought
// in the "reasoning" delta field rather than DeepSeek's "reasoning_content". A
@@ -148,7 +195,7 @@ func TestOpenAIClient_ChatStream_OpenRouterReasoning(t *testing.T) {
func TestOpenAIClient_ChatStream_OpenRouterDefaultsCompletionBudget(t *testing.T) {
var captured openaiStreamRequest
client := NewOpenAIClient("sk-test", "openrouter:deepseek/deepseek-v4-pro", "https://openrouter.ai/api/v1", 0)
- client.client = &http.Client{
+ client.streamClient = &http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
if err := json.NewDecoder(r.Body).Decode(&captured); err != nil {
return nil, err
@@ -177,7 +224,7 @@ func TestOpenAIClient_ChatStream_OpenRouterDefaultsCompletionBudget(t *testing.T
func TestOpenAIClient_ChatStream_OpenAIDoesNotDefaultCompletionBudget(t *testing.T) {
var captured openaiStreamRequest
client := NewOpenAIClient("sk-test", "gpt-4", "https://api.openai.com/v1", 0)
- client.client = &http.Client{
+ client.streamClient = &http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
if err := json.NewDecoder(r.Body).Decode(&captured); err != nil {
return nil, err
@@ -297,7 +344,7 @@ func TestOpenAIClient_ChatStream_ToolCallEOFWithBufferedDone(t *testing.T) {
}, "\n")
client := NewOpenAIClient("sk-test", "gpt-4", "https://example.invalid/v1", 0)
- client.client = &http.Client{
+ client.streamClient = &http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
@@ -339,7 +386,7 @@ func TestOpenAIClient_ChatStream_EOFWithoutDoneFinalizesToolCalls(t *testing.T)
}, "\n")
client := NewOpenAIClient("sk-test", "gpt-4", "https://example.invalid/v1", 0)
- client.client = &http.Client{
+ client.streamClient = &http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
@@ -376,7 +423,7 @@ func TestOpenAIClient_ChatStream_EOFWithoutDoneRejectsIncompleteToolCall(t *test
}, "\n")
client := NewOpenAIClient("sk-test", "gpt-4", "https://example.invalid/v1", 0)
- client.client = &http.Client{
+ client.streamClient = &http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
@@ -407,7 +454,7 @@ func TestOpenAIClient_ChatStream_EOFWithoutDoneFinalizesStopResponse(t *testing.
}, "\n")
client := NewOpenAIClient("sk-test", "gpt-4", "https://example.invalid/v1", 0)
- client.client = &http.Client{
+ client.streamClient = &http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,