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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Let flowing AI streams outlive the configured request timeout
rcourtman7a1e41bcf98b
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.goindex 48a5df8602..a3af463bf3 100644--- a/internal/ai/providers/openai.go+++ b/internal/ai/providers/openai.go@@ -17,15 +17,14 @@ import ()const (- openaiAPIURL = "https://api.openai.com/v1/chat/completions"- openaiMaxRetries = 3- openaiInitialBackoff = 2 * time.Second- openaiStreamMaxRetries = 1- openaiStreamInitialBackoff = 1 * time.Second- openaiStreamResponseHeaderTimeout = 12 * time.Second- openaiStreamChunkTimeout = 12 * 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+ openaiStreamChunkTimeout = 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. Keep this high@@ -37,16 +36,21 @@ const (// OpenAIClient implements the Provider interface for OpenAI's API// Also works with OpenAI-compatible APIs like DeepSeektype OpenAIClient struct {- providerName string- apiKey string- model string- baseURL string- requestTimeout time.Duration- client *http.Client- streamClient *http.Client- // OpenAI-compatible gateways can accept SSE headers and then stall between- // body chunks. Bound that gap separately from the full turn timeout so chat- // fallback can move before the drawer looks dead.+ providerName string+ apiKey string+ model string+ baseURL string+ client *http.Client+ streamClient *http.Client+ // The configured request timeout bounds how long Pulse waits for the+ // stream to START (response headers and first chunk). Once deltas flow+ // there is deliberately no overall wall-clock deadline: reasoning models+ // (qwen3 via Ollama, DeepSeek) stream thinking deltas for minutes before+ // real content, and a live stream must never be killed mid-thought+ // (#1576). Only the stall bounds below end a flowing stream.+ //+ // streamChunkTimeout bounds the gap BETWEEN chunks once the stream is+ // flowing, so chat fallback can move before the drawer looks dead.streamChunkTimeout time.Duration// Local OpenAI-compatible backends (LM Studio, llama.cpp, vLLM on CPU) can// legitimately spend minutes on prompt processing before the first SSE@@ -81,7 +85,6 @@ func NewOpenAICompatibleClient(providerName, apiKey, model, baseURL string, timeapiKey: apiKey,model: model,baseURL: baseURL,- requestTimeout: timeout,client: &http.Client{Timeout: timeout},streamClient: newOpenAIStreamHTTPClient(timeout),streamChunkTimeout: boundedOpenAIStreamChunkTimeout(timeout),@@ -147,19 +150,16 @@ 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)+ // Local backends can hold the response headers while the model loads+ // (Ollama does exactly this on a cold model), so the header wait+ // honors the configured request timeout like the first-chunk wait+ // does, rather than a short fixed bound.+ transport.ResponseHeaderTimeout = timeoutclient.Transport = transport}return client}-func boundedOpenAIStreamResponseHeaderTimeout(timeout time.Duration) time.Duration {- if timeout > 0 && timeout < openaiStreamResponseHeaderTimeout {- return timeout- }- return openaiStreamResponseHeaderTimeout-}-func boundedOpenAIStreamChunkTimeout(timeout time.Duration) time.Duration {if timeout > 0 && timeout < openaiStreamChunkTimeout {return timeout@@ -907,13 +907,11 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callbackreturn fmt.Errorf("failed to marshal request: %w", err)}- streamCtx := ctx- var cancelStream context.CancelFunc- if c.requestTimeout > 0 {- streamCtx, cancelStream = context.WithTimeout(ctx, c.requestTimeout)- defer cancelStream()- }-+ // No overall wall-clock deadline on the stream: header and first-chunk+ // waits honor the configured request timeout, and once deltas flow the+ // inter-chunk stall bound plus caller cancellation are the only limits.+ // Reasoning models legitimately stream thinking deltas for longer than+ // any fixed turn budget (#1576).var resp *http.Responsevar lastErr errorstreamClient := c.streamClient@@ -933,19 +931,19 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callbackbackoffTimer := time.NewTimer(backoff)select {- case <-streamCtx.Done():+ case <-ctx.Done():if !backoffTimer.Stop() {select {case <-backoffTimer.C:default:}}- return streamCtx.Err()+ return ctx.Err()case <-backoffTimer.C:}}- httpReq, err := http.NewRequestWithContext(streamCtx, "POST", c.baseURL, bytes.NewReader(body))+ httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL, bytes.NewReader(body))if err != nil {return fmt.Errorf("failed to create request: %w", err)}@@ -1138,7 +1136,7 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callbackif !receivedFirstChunk {chunkTimeout = c.streamFirstChunkTimeout}- n, err := readOpenAIStreamChunk(streamCtx, reader, buf, chunkTimeout)+ n, err := readOpenAIStreamChunk(ctx, reader, buf, chunkTimeout)if n > 0 {receivedFirstChunk = truependingData += string(buf[:n])diff --git a/internal/ai/providers/openai_test.go b/internal/ai/providers/openai_test.goindex 7d02659435..7f7dc5973e 100644--- a/internal/ai/providers/openai_test.go+++ b/internal/ai/providers/openai_test.go@@ -181,11 +181,15 @@ func TestOpenAIClient_ChatStream_RetriesTransientStartupError(t *testing.T) {assert.Equal(t, "ok", content)}-func TestNewOpenAIClient_BoundsStreamResponseHeaderTimeout(t *testing.T) {+func TestNewOpenAIClient_StreamTimeouts(t *testing.T) {+ // The waits for the stream to start (response headers, first chunk) honor+ // the configured request timeout: local backends hold headers during model+ // load and can spend minutes on prompt processing. Only the inter-chunk+ // gap keeps the short stall bound.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)+ assert.Equal(t, 300*time.Second, transport.ResponseHeaderTimeout)assert.Equal(t, openaiStreamChunkTimeout, client.streamChunkTimeout)assert.Equal(t, 300*time.Second, client.streamFirstChunkTimeout)@@ -197,6 +201,52 @@ func TestNewOpenAIClient_BoundsStreamResponseHeaderTimeout(t *testing.T) {assert.Equal(t, 2*time.Second, shortTimeoutClient.streamFirstChunkTimeout)}+// TestOpenAIClient_ChatStream_ReasoningPhaseOutlivesRequestTimeout guards the+// thinking-model path (#1576). qwen3 served via Ollama's OpenAI-compatible+// endpoint streams per-token "reasoning" deltas with empty content for most of+// the turn; that live activity must not be killed by a wall-clock cap at the+// configured request timeout. Here the stream stays busy well past the 150ms+// request timeout and must still complete.+func TestOpenAIClient_ChatStream_ReasoningPhaseOutlivesRequestTimeout(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "text/event-stream")+ w.WriteHeader(http.StatusOK)+ flusher := w.(http.Flusher)+ for i := 0; i < 20; i++ {+ fmt.Fprintf(w, "data: {\"choices\":[{\"delta\":{\"content\":\"\",\"reasoning\":\"think%d \"}}]}\n\n", i)+ flusher.Flush()+ time.Sleep(20 * time.Millisecond)+ }+ fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"answer\"},\"finish_reason\":\"stop\"}]}\n\n")+ fmt.Fprint(w, "data: [DONE]\n\n")+ flusher.Flush()+ }))+ defer server.Close()++ client := NewOpenAIClient("sk-test", "gpt-4", server.URL, 150*time.Millisecond)++ var thinkingChunks int+ var content string+ var doneCalled bool+ err := client.ChatStream(context.Background(), ChatRequest{+ Messages: []Message{{Role: "user", Content: "Hi"}},+ }, func(event StreamEvent) {+ switch event.Type {+ case "thinking":+ thinkingChunks+++ case "content":+ content += event.Data.(ContentEvent).Text+ case "done":+ doneCalled = true+ }+ })++ require.NoError(t, err)+ assert.Equal(t, 20, thinkingChunks)+ assert.Equal(t, "answer", content)+ assert.True(t, doneCalled)+}+func TestNewOpenAICompatibleClient_NormalizesProviderBasePaths(t *testing.T) {tests := []struct {name string