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
Sanitize provider stream errors shown in the Assistant chat
rcourtman71b1762d535b
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.goindex 4571bfcce1..c2ea4808c1 100644--- a/internal/ai/chat/agentic.go+++ b/internal/ai/chat/agentic.go@@ -85,32 +85,80 @@ func sessionFSMState(fsm *SessionFSM) string {return string(fsm.State)}+const defaultProviderStreamErrorMessage = "AI response stream interrupted before completion. Please retry."+func fallbackProviderStreamErrorMessage(err error) string {- const defaultMessage = "AI response stream interrupted before completion. Please retry."if err == nil {- return defaultMessage+ return defaultProviderStreamErrorMessage}+ return sanitizeProviderStreamErrorForUser(err.Error())+}- msg := strings.TrimSpace(err.Error())+// sanitizeProviderStreamErrorForUser turns a raw provider/transport error into a+// clean, human message safe to render in the chat. Upstream errors (especially+// from OpenAI-compatible gateways like OpenRouter) embed raw JSON bodies and+// dashboard URLs — e.g. a 402 carries the provider's billing JSON and a+// workspace-key link. Those must never reach the user: they are unreadable and+// can leak provider routing and key fragments. Known classes map to actionable+// messages; anything else has its JSON/URL payload stripped before display.+func sanitizeProviderStreamErrorForUser(msg string) string {+ msg = strings.TrimSpace(msg)if msg == "" {- return defaultMessage+ return defaultProviderStreamErrorMessage}- msgLower := strings.ToLower(msg)+ lower := strings.ToLower(msg)switch {- case strings.Contains(msgLower, "context canceled"):+ case strings.Contains(lower, "context canceled"):return "AI response was canceled before completion."- case strings.Contains(msgLower, "timeout"),- strings.Contains(msgLower, "timed out"),- strings.Contains(msgLower, "deadline exceeded"):+ case strings.Contains(lower, "timeout"),+ strings.Contains(lower, "timed out"),+ strings.Contains(lower, "deadline exceeded"):return "AI response timed out before completion. Please retry."+ case strings.Contains(lower, "402"),+ strings.Contains(lower, "more credits"),+ strings.Contains(lower, "insufficient"),+ strings.Contains(lower, "quota"),+ strings.Contains(lower, "billing"),+ strings.Contains(lower, "payment required"):+ return "The AI provider rejected the request for billing or quota reasons. Check your provider credits or token limit, then retry."+ case strings.Contains(lower, "401"),+ strings.Contains(lower, "403"),+ strings.Contains(lower, "unauthorized"),+ strings.Contains(lower, "invalid api key"),+ strings.Contains(lower, "authentication"):+ return "The AI provider rejected the credentials. Check your AI provider API key in Settings."+ case strings.Contains(lower, "429"),+ strings.Contains(lower, "rate limit"),+ strings.Contains(lower, "too many requests"):+ return "The AI provider is rate limiting requests. Wait a moment, then retry."+ }++ cleaned := stripProviderErrorPayload(msg)+ if cleaned == "" {+ return "The AI provider returned an error. Please retry."+ }+ return "AI response stream interrupted: " + cleaned+}++// stripProviderErrorPayload removes any embedded JSON body or URL so raw+// provider payloads and links never surface in the chat, keeping just the+// leading human-readable summary (e.g. "API error (500)").+func stripProviderErrorPayload(msg string) string {+ cut := len(msg)+ if i := strings.Index(msg, "{"); i >= 0 && i < cut {+ cut = i+ }+ if i := strings.Index(strings.ToLower(msg), "http"); i >= 0 && i < cut {+ cut = i}+ cleaned := strings.TrimRight(strings.TrimSpace(msg[:cut]), " :-")- const maxLen = 220- if len(msg) > maxLen {- msg = msg[:maxLen] + "..."+ const maxLen = 160+ if len(cleaned) > maxLen {+ cleaned = cleaned[:maxLen] + "..."}- return "AI response stream interrupted: " + msg+ return cleaned}func (a *AgenticLoop) executeToolSafely(ctx context.Context, name string, input map[string]interface{}) (result tools.CallToolResult, err error) {@@ -577,8 +625,9 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, meif len(attemptErrorMessages) > 0 {// Defer emitting error events until retries are exhausted so transient- // provider blips don't leak to the client stream.- jsonData, _ := json.Marshal(ErrorData{Message: attemptErrorMessages[0]})+ // provider blips don't leak to the client stream. Sanitize so raw+ // provider JSON/URLs never reach the user.+ jsonData, _ := json.Marshal(ErrorData{Message: sanitizeProviderStreamErrorForUser(attemptErrorMessages[0])})callback(StreamEvent{Type: "error", Data: jsonData})} else {// Transport-level failures may not include an explicit provider error event.diff --git a/internal/ai/chat/agentic_error_message_test.go b/internal/ai/chat/agentic_error_message_test.gonew file mode 100644index 0000000000..e9977f8f6c--- /dev/null+++ b/internal/ai/chat/agentic_error_message_test.go@@ -0,0 +1,93 @@+package chat++import (+ "errors"+ "strings"+ "testing"+)++func TestSanitizeProviderStreamErrorForUser(t *testing.T) {+ // The exact shape the user hit: an OpenRouter 402 with a JSON body and a+ // workspace-key dashboard URL. None of that may reach the chat.+ openRouter402 := `stream error: API error (402): {"error":{"message":"This request requires more credits, or fewer max_tokens. You requested up to 65536 tokens, but can only afford 40. To increase, visit https://openrouter.ai/workspaces/default/keys/69abc"}}`++ cases := []struct {+ name string+ in string+ wantContain string+ wantAbsent []string+ }{+ {+ name: "billing 402 maps to a clean actionable message",+ in: openRouter402,+ wantContain: "billing or quota",+ wantAbsent: []string{"{", "http", "max_tokens", "402", "openrouter.ai"},+ },+ {+ name: "auth error",+ in: `API error (401): {"error":"invalid api key"}`,+ wantContain: "credentials",+ wantAbsent: []string{"{", "401", "invalid api key"},+ },+ {+ name: "rate limit",+ in: "API error (429): too many requests",+ wantContain: "rate limiting",+ wantAbsent: []string{"429"},+ },+ {+ name: "timeout",+ in: "context deadline exceeded",+ wantContain: "timed out",+ },+ {+ name: "canceled",+ in: "context canceled",+ wantContain: "canceled",+ },+ {+ name: "generic error strips JSON body but keeps the summary",+ in: `API error (500): {"error":"internal"}`,+ wantContain: "API error (500)",+ wantAbsent: []string{"{", "internal"},+ },+ {+ name: "generic error strips trailing URL",+ in: "upstream failed see https://example.com/secret",+ wantContain: "upstream failed",+ wantAbsent: []string{"http", "secret"},+ },+ {+ name: "empty falls back to default",+ in: " ",+ wantContain: "interrupted before completion",+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := sanitizeProviderStreamErrorForUser(tc.in)+ if !strings.Contains(got, tc.wantContain) {+ t.Fatalf("expected %q to contain %q", got, tc.wantContain)+ }+ lowerGot := strings.ToLower(got)+ for _, absent := range tc.wantAbsent {+ if strings.Contains(lowerGot, strings.ToLower(absent)) {+ t.Fatalf("sanitized message %q must not contain %q", got, absent)+ }+ }+ })+ }+}++func TestFallbackProviderStreamErrorMessage_NilAndError(t *testing.T) {+ if got := fallbackProviderStreamErrorMessage(nil); !strings.Contains(got, "interrupted before completion") {+ t.Fatalf("nil error should use the default message, got %q", got)+ }+ got := fallbackProviderStreamErrorMessage(errors.New(`API error (402): {"x":"https://o.ai/keys/1"}`))+ for _, absent := range []string{"{", "http", "402"} {+ if strings.Contains(strings.ToLower(got), absent) {+ t.Fatalf("message %q must not leak %q", got, absent)+ }+ }+}