diff --git a/internal/ai/chat/agentic_final.go b/internal/ai/chat/agentic_final.go index aadc6d7ce0..57f69e42d4 100644 --- a/internal/ai/chat/agentic_final.go +++ b/internal/ai/chat/agentic_final.go @@ -74,18 +74,21 @@ func (a *AgenticLoop) ensureFinalTextResponseWithSystemPrompt( if override := strings.TrimSpace(systemPromptOverride); override != "" { summarySystemPrompt = override } + a.mu.Lock() + providerName := a.providerName + requestSanitizer := a.requestSanitizer + streamIdleTimeout := a.streamIdleTimeout + a.mu.Unlock() summaryReq := providers.ChatRequest{ - Messages: cleanMessages, - System: summarySystemPrompt, - ExecutionID: a.executionID, + Messages: cleanMessages, + System: summarySystemPrompt, + ExecutionID: a.executionID, + StreamIdleTimeout: investigationStreamIdleTimeout(a.currentExecutionProfile(), providerName, streamIdleTimeout), // No Tools field: this is a final narrative turn, and Pulse avoids // provider-specific tool_choice transport fields. } applyExecutionInferenceAllowance(&summaryReq, a.currentExecutionProfile(), true, a.totalOutputTokens) applyExecutionRuntimeEnvelope(&summaryReq, a.currentExecutionProfile()) - a.mu.Lock() - requestSanitizer := a.requestSanitizer - a.mu.Unlock() if requestSanitizer != nil { summaryReq = requestSanitizer(summaryReq) } diff --git a/internal/ai/chat/agentic_investigation_conclusion_test.go b/internal/ai/chat/agentic_investigation_conclusion_test.go index 3200c60621..80a4bd054f 100644 --- a/internal/ai/chat/agentic_investigation_conclusion_test.go +++ b/internal/ai/chat/agentic_investigation_conclusion_test.go @@ -209,3 +209,60 @@ func TestInvestigationSummaryTimeoutUsesTheRemainingDeadline(t *testing.T) { t.Fatalf("near-deadline summary timeout = %s, want %s (the deadline still bounds it)", got, base) } } + +func TestInvestigationSummaryRetainsStreamIdleTimeout(t *testing.T) { + cases := []struct { + name string + profile tools.ExecutionProfile + providerName string + wantIdle time.Duration + }{ + { + name: "streaming investigation preserves patrol idle budget on summary", + profile: tools.ProfilePatrolInvestigation, + providerName: "openai", + wantIdle: PatrolProviderStreamIdleTimeout, + }, + { + name: "subscription investigation widens idle budget on summary", + profile: tools.ProfilePatrolInvestigation, + providerName: string(providers.SubscriptionAgentCodex), + wantIdle: patrolSubscriptionInvestigationTurnTimeout, + }, + { + name: "interactive summary keeps provider default", + profile: tools.ProfileInteractiveAssistant, + providerName: "openai", + wantIdle: 0, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var gotIdle time.Duration + provider := &stubStreamingProvider{chatStream: func(ctx context.Context, req providers.ChatRequest, cb providers.StreamCallback) error { + gotIdle = req.StreamIdleTimeout + cb(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "Final summary."}}) + cb(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}}) + return nil + }} + loop := NewAgenticLoop(provider, tools.NewPulseToolExecutor(tools.ExecutorConfig{}), "Investigate") + loop.SetExecutionProfile(tc.profile) + loop.SetProviderInfo(tc.providerName, "test-model") + + _, err := loop.ensureFinalTextResponse( + context.Background(), + "summary-idle", + nil, + []providers.Message{{Role: "user", Content: "Check service"}}, + func(StreamEvent) {}, + ) + if err != nil { + t.Fatalf("ensureFinalTextResponse returned error: %v", err) + } + if gotIdle != tc.wantIdle { + t.Fatalf("summary StreamIdleTimeout = %s, want %s", gotIdle, tc.wantIdle) + } + }) + } +} diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.go index 4fba117c9b..28ab84fb6b 100644 --- a/internal/ai/patrol_findings.go +++ b/internal/ai/patrol_findings.go @@ -1895,11 +1895,14 @@ func stuckInvestigationResult(f *Finding, orchestrator InvestigationOrchestrator const abandonedRunError = "Patrol stopped waiting for this investigation after it ran past its time limit." // abandonedInvestigationSession is a run's session as the stuck-run sweep gives -// the run up at now: failed, because it ran past its limit without closing. -// The orchestrator's own session is left as it is. +// the run up at now: failed and timed out, because it ran past its limit without +// closing. The orchestrator's own session is left as it is. func abandonedInvestigationSession(session *InvestigationSession, now time.Time) *InvestigationSession { abandoned := *session abandoned.Status = aicontracts.InvestigationStatusFailed + if abandoned.Outcome == "" { + abandoned.Outcome = aicontracts.OutcomeTimedOut + } abandoned.CompletedAt = &now if strings.TrimSpace(abandoned.Error) == "" { abandoned.Error = abandonedRunError diff --git a/internal/ai/patrol_investigation_limits_test.go b/internal/ai/patrol_investigation_limits_test.go index 82f326b55c..cf17cd21fb 100644 --- a/internal/ai/patrol_investigation_limits_test.go +++ b/internal/ai/patrol_investigation_limits_test.go @@ -301,3 +301,38 @@ func TestInvestigationRunCeilingFollowsTheConfiguredTimeout(t *testing.T) { t.Fatalf("subscription ceiling = %s, want %s", got, want) } } + +func TestRecoverStuckInvestigationsRecordsTimedOutOnAbandonedSession(t *testing.T) { + now := time.Now() + findings := NewFindingsStore() + findings.Add(runningInvestigationFinding("stuck", "chat-stuck", nil)) + + orchestrator := &sessionReportingOrchestrator{sessions: map[string]*InvestigationSession{ + "stuck": {ID: "inv-stuck", FindingID: "stuck", SessionID: "chat-stuck", Status: aicontracts.InvestigationStatusRunning, StartedAt: now.Add(-time.Hour)}, + }} + var closedSession *InvestigationSession + patrol := &PatrolService{ + findings: findings, + investigationOrchestrator: orchestrator, + investigationRunCloser: func(findingID string, session *InvestigationSession) { + if findingID == "stuck" { + closedSession = session + } + }, + } + patrol.recoverStuckInvestigations() + + assertInvestigationState(t, findings, "stuck", InvestigationStatusFailed, InvestigationOutcomeTimedOut) + if closedSession == nil { + t.Fatal("expected abandoned session close callback to be invoked") + } + if closedSession.Status != aicontracts.InvestigationStatusFailed { + t.Fatalf("closed session status = %q, want %q", closedSession.Status, aicontracts.InvestigationStatusFailed) + } + if closedSession.Outcome != aicontracts.OutcomeTimedOut { + t.Fatalf("closed session outcome = %q, want %q", closedSession.Outcome, aicontracts.OutcomeTimedOut) + } + if closedSession.CompletedAt == nil || closedSession.CompletedAt.IsZero() { + t.Fatal("closed session CompletedAt was not set") + } +} diff --git a/internal/api/alerting/notifications.go b/internal/api/alerting/notifications.go index 27151be74f..895265a529 100644 --- a/internal/api/alerting/notifications.go +++ b/internal/api/alerting/notifications.go @@ -939,21 +939,21 @@ func classifyNotificationError(err error) (summary, detail string) { switch { case strings.Contains(lower, "connection refused"): - summary = "Could not connect to the server — check host, port, and firewall settings" + summary = "Could not connect to the server: check host, port, and firewall settings" case strings.Contains(lower, "no such host"): - summary = "Server hostname not found — check the server address" + summary = "Server hostname not found: check the server address" case strings.Contains(lower, "i/o timeout") || strings.Contains(lower, "deadline exceeded"): - summary = "Connection timed out — the server may be unreachable or the port may be blocked" - case strings.Contains(lower, "x509:") || strings.Contains(lower, "certificate"): - summary = "TLS certificate error — check certificate settings or try enabling 'Skip TLS Verify'" + summary = "Connection timed out: the server may be unreachable or the port may be blocked" + case strings.Contains(lower, "x509:") || strings.Contains(lower, "certificate") || strings.Contains(lower, "server gave http response to https client"): + summary = "TLS certificate error: check the server certificate and TLS settings" case strings.Contains(lower, "535") || strings.Contains(lower, "authentication"): - summary = "Authentication failed — check username and password" + summary = "Authentication failed: check username and password" case strings.Contains(lower, "executable file not found"): - summary = "Required program not found — ensure it is installed on the server" + summary = "Required program not found: ensure it is installed on the server" case strings.Contains(lower, "permission denied"): - summary = "Permission denied — the server process lacks access to the required resource" + summary = "Permission denied: the server process lacks access to the required resource" case strings.Contains(lower, "eof"): - summary = "The server closed the connection unexpectedly — check if TLS/StartTLS settings are correct" + summary = "The server closed the connection unexpectedly: check if TLS/StartTLS settings are correct" default: summary = raw detail = "" diff --git a/internal/api/alerting/notifications_test.go b/internal/api/alerting/notifications_test.go index 349fbb240d..cd3754f488 100644 --- a/internal/api/alerting/notifications_test.go +++ b/internal/api/alerting/notifications_test.go @@ -1286,63 +1286,70 @@ func TestClassifyNotificationError(t *testing.T) { { name: "connection refused", err: "dial tcp smtp.gmail.com:587: connect: connection refused", - wantSummary: "Could not connect to the server — check host, port, and firewall settings", + wantSummary: "Could not connect to the server: check host, port, and firewall settings", wantHasDetail: true, summaryMustNot: []string{"dial tcp"}, }, { name: "no such host", err: "dial tcp: lookup smtp.example.com: no such host", - wantSummary: "Server hostname not found — check the server address", + wantSummary: "Server hostname not found: check the server address", wantHasDetail: true, summaryMustNot: []string{"dial tcp"}, }, { name: "i/o timeout", err: "dial tcp 10.0.0.1:587: i/o timeout", - wantSummary: "Connection timed out — the server may be unreachable or the port may be blocked", + wantSummary: "Connection timed out: the server may be unreachable or the port may be blocked", wantHasDetail: true, summaryMustNot: []string{"dial tcp"}, }, { name: "context deadline exceeded", err: "context deadline exceeded", - wantSummary: "Connection timed out — the server may be unreachable or the port may be blocked", + wantSummary: "Connection timed out: the server may be unreachable or the port may be blocked", wantHasDetail: true, summaryMustNot: []string{"context"}, }, { name: "x509 certificate error", err: "x509: certificate signed by unknown authority", - wantSummary: "TLS certificate error — check certificate settings or try enabling 'Skip TLS Verify'", + wantSummary: "TLS certificate error: check the server certificate and TLS settings", wantHasDetail: true, - summaryMustNot: []string{"x509:"}, + summaryMustNot: []string{"x509:", "Skip TLS Verify"}, + }, + { + name: "https client to http endpoint", + err: `Post "https://192.168.1.50:8080/hook": http: server gave HTTP response to HTTPS client`, + wantSummary: "TLS certificate error: check the server certificate and TLS settings", + wantHasDetail: true, + summaryMustNot: []string{"Skip TLS Verify"}, }, { name: "smtp auth failure", err: "535 5.7.8 Username and Password not accepted", - wantSummary: "Authentication failed — check username and password", + wantSummary: "Authentication failed: check username and password", wantHasDetail: true, summaryMustNot: []string{"535"}, }, { name: "executable not found", err: `exec: "apprise": executable file not found in $PATH`, - wantSummary: "Required program not found — ensure it is installed on the server", + wantSummary: "Required program not found: ensure it is installed on the server", wantHasDetail: true, summaryMustNot: []string{"exec:"}, }, { name: "permission denied", err: "open /etc/ssl/certs: permission denied", - wantSummary: "Permission denied — the server process lacks access to the required resource", + wantSummary: "Permission denied: the server process lacks access to the required resource", wantHasDetail: true, summaryMustNot: []string{"open /etc"}, }, { name: "eof", err: "read tcp 192.168.1.1:587: EOF", - wantSummary: "The server closed the connection unexpectedly — check if TLS/StartTLS settings are correct", + wantSummary: "The server closed the connection unexpectedly: check if TLS/StartTLS settings are correct", wantHasDetail: true, summaryMustNot: []string{"read tcp"}, }, @@ -1381,7 +1388,7 @@ func TestWriteTestNotificationError(t *testing.T) { var resp map[string]string assert.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) - assert.Equal(t, "Could not connect to the server — check host, port, and firewall settings", resp["error"]) + assert.Equal(t, "Could not connect to the server: check host, port, and firewall settings", resp["error"]) assert.Equal(t, "dial tcp smtp.gmail.com:587: connect: connection refused", resp["detail"]) }) diff --git a/internal/notifications/failure_class.go b/internal/notifications/failure_class.go index 25da09a051..2c7aaafdd5 100644 --- a/internal/notifications/failure_class.go +++ b/internal/notifications/failure_class.go @@ -270,25 +270,27 @@ func ClassifyNotificationFailureError(err error) NotificationFailureClass { // Retryable reports whether another delivery attempt could plausibly succeed. // -// Authentication, configuration and rejection are verdicts about the request -// itself: the same payload, sent again to the same destination with the same -// credentials, gets the same answer. Retrying them spends attempts, delays the -// dead letter the operator needs to see, and learns nothing. Connectivity, -// rate limiting and server errors describe conditions that clear on their own, -// and an unclassified failure is retried because nothing proves it will not -// succeed. +// Authentication, configuration, rejection, and TLS certificate or handshake +// mismatches are verdicts about the destination setup or request itself: the +// same payload, sent again to the same destination with the same credentials +// and TLS settings, gets the same answer. Retrying them spends attempts, delays +// the dead letter the operator needs to see, and learns nothing. Connectivity +// (including transient EOF/reset/timeout drops), rate limiting, and server +// errors describe conditions that clear on their own, and an unclassified +// failure is retried because nothing proves it will not succeed. // // This generalises to every destination type the decision webhook delivery // already made for HTTP 4xx in isRetryableWebhookError. // // A dead letter is not the end of the road: once the operator fixes the -// credentials or the configuration, RetryTerminalFailures returns retained -// terminal failures to the queue with a fresh budget. +// credentials, certificate, or configuration, RetryTerminalFailures returns +// retained terminal failures to the queue with a fresh budget. func (class NotificationFailureClass) Retryable() bool { switch class { case NotificationFailureAuthentication, NotificationFailureConfiguration, - NotificationFailureRejected: + NotificationFailureRejected, + NotificationFailureTLS: return false default: return true diff --git a/internal/notifications/failure_class_test.go b/internal/notifications/failure_class_test.go index d61e03a818..6718e91541 100644 --- a/internal/notifications/failure_class_test.go +++ b/internal/notifications/failure_class_test.go @@ -254,10 +254,10 @@ func TestFailureClassRetryable(t *testing.T) { NotificationFailureAuthentication: false, NotificationFailureConfiguration: false, NotificationFailureRejected: false, + NotificationFailureTLS: false, NotificationFailureConnectivity: true, NotificationFailureRateLimited: true, NotificationFailureServerError: true, - NotificationFailureTLS: true, NotificationFailureUnknown: true, NotificationFailureClass(""): true, } @@ -295,6 +295,12 @@ func TestProcessNotificationDeadLettersDeterministicFailureImmediately(t *testin wantStatus: QueueStatusDLQ, wantCallCount: 1, }, + { + name: "tls does not retry", + sendErr: FailWithClass(NotificationFailureTLS, x509.UnknownAuthorityError{}), + wantStatus: QueueStatusDLQ, + wantCallCount: 1, + }, { name: "connectivity still retries", sendErr: FailWithClass(NotificationFailureConnectivity, errors.New("dial tcp: connection refused")),