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.

Anchor Assistant stream and OpenRouter default

rcourtman0d2f2a3cc852
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 4e87b4f493..4bc47698ec 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -98,6 +98,13 @@ runtime cost control, and shared AI transport surfaces.
is handled as a normal failed turn with draft restoration. Same-model
configured-provider alternatives remain one-click route changes as well as
send-time recovery choices, not required preconditions for typing or sending.
+ Assistant model-selection defaults are settings-owned: the drawer may persist
+ explicit model selections only for concrete session IDs, while blank-session
+ chat defaults must flow from `/api/settings/ai` `chat_model` or `model`.
+ Browser storage must not keep a hidden `__default__` model route that
+ overrides the configured chat model after the operator changes provider
+ settings; stale blank-session defaults must be ignored and cleaned on mount
+ so routes such as OpenRouter become visible and effective immediately.
Follow-up sends during an active Assistant response are chat-runtime queue
state by default. The drawer must accept and echo the user's follow-up as a
queued user turn without aborting or replacing the active model stream, must
@@ -146,6 +153,14 @@ runtime cost control, and shared AI transport surfaces.
the drawer must update the in-flight transcript row when `provider_fallback`
names the next route so message labels, cost context, retry decisions, and
model-route recovery do not continue to point at the failed provider.
+ Interactive Assistant streams must establish the session ID and emit the
+ `session` event once as soon as the HTTP SSE writer is ready, before finding
+ handoff recovery, model resolution, provider fallback planning,
+ handoff/context prefetch, recent-session injection, inventory summary reads,
+ tool scoping, or provider startup. The chat service then persists/ensures
+ that same session ID while suppressing duplicate session events. This keeps
+ the drawer's visible turn anchored while backend preparation continues and
+ prevents simple prompts from appearing stuck in an opaque thinking state.
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
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index d3ba7b7071..1ffe0cf0cf 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -443,8 +443,10 @@ payload shape change when the portal presents compact client rows.
boundary. Browser Assistant output is owned by the AI runtime presentation
contract rather than by API-client event typing.
Cold Assistant streams must include a typed `session` event backed by
- `internal/ai/chat.SessionData` before user-visible provider output so the
- frontend can bind the backend-created session without a separate
+ `internal/ai/chat.SessionData` as soon as the HTTP SSE writer is ready and
+ before backend handoff recovery, model resolution, provider fallback
+ planning, context prefetch, inventory reads, or user-visible provider output
+ so the frontend can bind the backend-created session without a separate
create-session request. The generated frontend union, stream parser tests,
and backend JSON snapshot proof must stay in lockstep with that payload;
`done.session_id` and `question.session_id` remain compatibility payloads,
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
index d82fe90fcd..5553587d69 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -2612,16 +2612,30 @@ describe('AIChat', () => {
expect(localStorage.getItem('pulse:ai_chat_models_by_session')).toBe('{broken json');
});
- it('initializes useChat with stored default model', () => {
+ it('drops stale stored default model overrides on mount', () => {
localStorage.setItem(
'pulse:ai_chat_models_by_session',
JSON.stringify({ __default__: 'claude-3' }),
);
renderChat();
- // The component should have passed this model into useChat — we can verify
- // the stored value persists (the component reads it at construction)
- const stored = JSON.parse(localStorage.getItem('pulse:ai_chat_models_by_session')!);
- expect(stored.__default__).toBe('claude-3');
+ expect(mockChat.setModel).not.toHaveBeenCalledWith('claude-3');
+ expect(localStorage.getItem('pulse:ai_chat_models_by_session')).toBeNull();
+ });
+
+ it('restores stored model choices for real sessions', async () => {
+ localStorage.setItem(
+ 'pulse:ai_chat_models_by_session',
+ JSON.stringify({ 'session-1': 'openrouter:deepseek/deepseek-v4-pro' }),
+ );
+ mockChat.sessionId.mockReturnValue('session-1');
+
+ renderChat();
+
+ await waitFor(() => {
+ expect(mockChat.setModel).toHaveBeenCalledWith(
+ 'openrouter:deepseek/deepseek-v4-pro',
+ );
+ });
});
});
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index 4d4a23cc8f..bd2d798405 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -634,7 +634,25 @@ export const AIChat: Component<AIChatProps> = (props) => {
try {
const raw = localStorage.getItem(MODEL_SESSION_STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : {};
- return typeof parsed === 'object' && parsed ? (parsed as Record<string, string>) : {};
+ if (!parsed || typeof parsed !== 'object') return {};
+
+ const selections: Record<string, string> = {};
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
+ const sessionId = key.trim();
+ const modelId = typeof value === 'string' ? value.trim() : '';
+ if (!sessionId || sessionId === DEFAULT_SESSION_KEY || !modelId) continue;
+ selections[sessionId] = modelId;
+ }
+
+ if (raw && JSON.stringify(parsed) !== JSON.stringify(selections)) {
+ if (Object.keys(selections).length > 0) {
+ localStorage.setItem(MODEL_SESSION_STORAGE_KEY, JSON.stringify(selections));
+ } else {
+ localStorage.removeItem(MODEL_SESSION_STORAGE_KEY);
+ }
+ }
+
+ return selections;
} catch (error) {
logger.warn('[AIChat] Failed to read stored models:', error);
return {};
@@ -654,16 +672,19 @@ export const AIChat: Component<AIChatProps> = (props) => {
createSignal<Record<string, string>>(initialModelSelections);
const getStoredModel = (sessionId: string) => {
- const key = sessionId || DEFAULT_SESSION_KEY;
+ const key = sessionId.trim();
+ if (!key) return '';
return modelSelections()[key] || '';
};
const updateStoredModel = (sessionId: string, modelId: string) => {
- const key = sessionId || DEFAULT_SESSION_KEY;
+ const key = sessionId.trim();
+ if (!key) return;
setModelSelections((prev) => {
const next = { ...prev };
- if (modelId) {
- next[key] = modelId;
+ const normalizedModel = modelId.trim();
+ if (normalizedModel) {
+ next[key] = normalizedModel;
} else {
delete next[key];
}
@@ -679,7 +700,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
// Chat hook
const chat = useChat({
- model: initialModelSelections[DEFAULT_SESSION_KEY] || '',
+ model: '',
defaultModel: () => defaultModel().trim(),
onConversationChanged: refreshSessions,
});
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index d33ea01ca7..2e8a312826 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -527,6 +527,15 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
log.Debug().Str("session_id", session.ID).Msg("[ChatService] Session ensured")
+ streamCallback := callback
+ if streamCallback == nil {
+ streamCallback = func(StreamEvent) {}
+ }
+ if !req.SuppressSessionEvent {
+ sessionData, _ := json.Marshal(SessionData{ID: session.ID})
+ streamCallback(StreamEvent{Type: "session", Data: sessionData})
+ }
+
handoffContext := strings.TrimSpace(req.HandoffContext)
handoffResources := normalizeHandoffResources(req.HandoffResources)
handoffActions := normalizeHandoffActions(req.HandoffActions)
@@ -787,10 +796,6 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
Int("tools_count", len(filteredTools)).
Msg("[ChatService] Prepared governed tool manifest, starting agentic loop")
- streamCallback := callback
- if streamCallback == nil {
- streamCallback = func(StreamEvent) {}
- }
wrappedCallback := func(event StreamEvent) {
event = sanitizeStreamEventForHandoffResourcePolicy(event, handoffResources, handoffResourceProvider)
var ok bool
@@ -800,8 +805,6 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
}
streamCallback(event)
}
- sessionData, _ := json.Marshal(SessionData{ID: session.ID})
- streamCallback(StreamEvent{Type: "session", Data: sessionData})
if initialFallbackModel != "" {
emitChatProviderFallback(streamCallback, selectedModel, initialFallbackModel)
}
diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go
index e84d6d7e78..1146cda2c1 100644
--- a/internal/ai/chat/service_execute_additional_test.go
+++ b/internal/ai/chat/service_execute_additional_test.go
@@ -24,6 +24,22 @@ type stubServiceProvider struct {
streamFn func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error
}
+type sessionAwareStateProvider struct {
+ readSeen *atomic.Bool
+ sessionSeen *atomic.Bool
+ readBeforeSession *atomic.Bool
+}
+
+func (p sessionAwareStateProvider) ReadSnapshot() models.StateSnapshot {
+ if p.readSeen != nil {
+ p.readSeen.Store(true)
+ }
+ if p.sessionSeen != nil && !p.sessionSeen.Load() && p.readBeforeSession != nil {
+ p.readBeforeSession.Store(true)
+ }
+ return models.StateSnapshot{}
+}
+
type recordingAgentServer struct {
calls atomic.Int32
}
@@ -383,6 +399,91 @@ func TestService_ExecuteStream_Success(t *testing.T) {
}
}
+func TestService_ExecuteStream_EmitsSessionBeforeInventoryPrefetch(t *testing.T) {
+ tmpDir := t.TempDir()
+ store, err := NewSessionStore(tmpDir)
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ var sessionSeen atomic.Bool
+ var stateReadSeen atomic.Bool
+ var stateReadBeforeSession atomic.Bool
+ provider := &stubServiceProvider{}
+ service := NewService(Config{
+ AIConfig: &config.AIConfig{ChatModel: "openai:test"},
+ StateProvider: sessionAwareStateProvider{
+ readSeen: &stateReadSeen,
+ sessionSeen: &sessionSeen,
+ readBeforeSession: &stateReadBeforeSession,
+ },
+ })
+ service.sessions = store
+ service.provider = provider
+ service.started = true
+
+ err = service.ExecuteStream(context.Background(), ExecuteRequest{
+ SessionID: "sess-early-session",
+ Prompt: "how many devices are in this",
+ }, func(event StreamEvent) {
+ if event.Type == "session" {
+ sessionSeen.Store(true)
+ }
+ })
+ if err != nil {
+ t.Fatalf("ExecuteStream failed: %v", err)
+ }
+ if !sessionSeen.Load() {
+ t.Fatal("session event was not emitted")
+ }
+ if !stateReadSeen.Load() {
+ t.Fatal("inventory prefetch did not read state")
+ }
+ if stateReadBeforeSession.Load() {
+ t.Fatal("inventory prefetch read state before the browser-visible session event")
+ }
+}
+
+func TestService_ExecuteStream_SuppressesSessionEventWhenCallerAlreadySentIt(t *testing.T) {
+ tmpDir := t.TempDir()
+ store, err := NewSessionStore(tmpDir)
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ provider := &stubServiceProvider{}
+ service := NewService(Config{
+ AIConfig: &config.AIConfig{ChatModel: "openai:test"},
+ })
+ service.sessions = store
+ service.provider = provider
+ service.started = true
+
+ var sessionEvents int
+ var doneEvents int
+ err = service.ExecuteStream(context.Background(), ExecuteRequest{
+ SessionID: "sess-session-suppressed",
+ Prompt: "hello",
+ SuppressSessionEvent: true,
+ }, func(event StreamEvent) {
+ switch event.Type {
+ case "session":
+ sessionEvents++
+ case "done":
+ doneEvents++
+ }
+ })
+ if err != nil {
+ t.Fatalf("ExecuteStream failed: %v", err)
+ }
+ if sessionEvents != 0 {
+ t.Fatalf("session events = %d, want 0", sessionEvents)
+ }
+ if doneEvents != 1 {
+ t.Fatalf("done events = %d, want 1", doneEvents)
+ }
+}
+
func TestService_ExecuteStream_FallsBackWhenPrimaryProviderFailsBeforeVisibleOutput(t *testing.T) {
tmpDir := t.TempDir()
store, err := NewSessionStore(tmpDir)
diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.go
index d17fc380ea..50a6ecc3a4 100644
--- a/internal/ai/chat/types.go
+++ b/internal/ai/chat/types.go
@@ -223,6 +223,11 @@ type ExecuteRequest struct {
HandoffMetadata HandoffMetadata `json:"handoff_metadata,omitempty"` // Browser-safe identity for restoring saved product handoffs.
MaxTurns int `json:"max_turns,omitempty"` // Override max agentic turns (0 = use default)
AutonomousMode *bool `json:"autonomous_mode,omitempty"` // Per-request autonomous override (nil = use service default)
+
+ // SuppressSessionEvent is set by HTTP streaming callers that have already
+ // emitted the browser-visible session event before expensive handoff or
+ // provider setup work.
+ SuppressSessionEvent bool `json:"-"`
}
// QuestionAnswer represents a user's answer to a question
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index b744d9c4d8..f787662193 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -13,6 +13,7 @@ import (
"fmt"
+ "github.com/google/uuid"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
airuntime "github.com/rcourtman/pulse-go-rewrite/internal/ai"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
@@ -2458,6 +2459,14 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
flusher.Flush()
}
+ streamSessionID := strings.TrimSpace(req.SessionID)
+ if streamSessionID == "" {
+ streamSessionID = uuid.NewString()
+ }
+ req.SessionID = streamSessionID
+ sessionData, _ := json.Marshal(chat.SessionData{ID: streamSessionID})
+ writeEvent(chat.StreamEvent{Type: "session", Data: sessionData})
+
// Convert API mentions to chat mentions
var chatMentions []chat.StructuredMention
for _, m := range req.Mentions {
@@ -2547,16 +2556,17 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
serviceSentDone := false
serviceSentError := false
err := svc.ExecuteStream(ctx, chat.ExecuteRequest{
- Prompt: req.Prompt,
- SessionID: req.SessionID,
- Model: req.Model,
- Mentions: chatMentions,
- FindingID: findingID,
- HandoffContext: handoffContext,
- HandoffResources: handoffResources,
- HandoffActions: handoffActions,
- HandoffMetadata: handoffMetadata,
- AutonomousMode: chatAutonomousModeForFindingHandoff(req.AutonomousMode, findingID, handoffContext, handoffResources, handoffActions, handoffMetadata),
+ Prompt: req.Prompt,
+ SessionID: req.SessionID,
+ Model: req.Model,
+ Mentions: chatMentions,
+ FindingID: findingID,
+ HandoffContext: handoffContext,
+ HandoffResources: handoffResources,
+ HandoffActions: handoffActions,
+ HandoffMetadata: handoffMetadata,
+ AutonomousMode: chatAutonomousModeForFindingHandoff(req.AutonomousMode, findingID, handoffContext, handoffResources, handoffActions, handoffMetadata),
+ SuppressSessionEvent: true,
}, func(event chat.StreamEvent) {
if event.Type == "done" {
serviceSentDone = true
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index ab7540f270..f40bece618 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -582,6 +582,50 @@ func TestHandleChat_Success(t *testing.T) {
assert.Contains(t, w.Header().Get("Content-Type"), "text/event-stream")
}
+func TestHandleChat_EmitsSessionBeforeExecuteStream(t *testing.T) {
+ cfg := &config.Config{}
+ h := newTestAIHandler(cfg, nil, nil)
+ mockSvc := new(MockAIService)
+ h.defaultService = mockSvc
+ w := httptest.NewRecorder()
+
+ mockSvc.On("IsRunning").Return(true)
+ mockSvc.On(
+ "ExecuteStream",
+ mock.Anything,
+ mock.MatchedBy(func(req chat.ExecuteRequest) bool {
+ return req.SessionID == "early-http-session" && req.SuppressSessionEvent
+ }),
+ mock.Anything,
+ ).Return(nil).Run(func(args mock.Arguments) {
+ if !strings.Contains(w.Body.String(), `"type":"session"`) {
+ t.Fatal("session event was not written before ExecuteStream")
+ }
+ callback := args.Get(2).(chat.StreamCallback)
+ contentData, _ := json.Marshal(chat.ContentData{Text: "hello"})
+ callback(chat.StreamEvent{Type: "content", Data: contentData})
+ })
+
+ body := `{"prompt": "hi", "session_id": "early-http-session"}`
+ req := httptest.NewRequest("POST", "/api/ai/chat", strings.NewReader(body))
+
+ h.HandleChat(w, req)
+
+ response := w.Body.String()
+ sessionIndex := strings.Index(response, `"type":"session"`)
+ contentIndex := strings.Index(response, `"type":"content"`)
+ if sessionIndex < 0 {
+ t.Fatal("response missing session event")
+ }
+ if contentIndex < 0 {
+ t.Fatal("response missing content event")
+ }
+ if sessionIndex > contentIndex {
+ t.Fatalf("session event appeared after content event: %s", response)
+ }
+ assert.Equal(t, 1, strings.Count(response, `"type":"session"`))
+}
+
func TestHandleChat_UsesClientSafeStreamProjection(t *testing.T) {
cfg := &config.Config{}
h := newTestAIHandler(cfg, nil, nil)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 2111aa77a5..21cc65398c 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -376,7 +376,7 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
"func chatAutonomousModeForFindingHandoff(requested *bool, findingID, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction, handoffMetadata chat.HandoffMetadata) *bool",
`if strings.TrimSpace(findingID) != ""`,
"chatApprovalRequiredAutonomousMode()",
- "AutonomousMode: chatAutonomousModeForFindingHandoff(req.AutonomousMode, findingID, handoffContext, handoffResources, handoffActions, handoffMetadata)",
+ "AutonomousMode: chatAutonomousModeForFindingHandoff(req.AutonomousMode, findingID, handoffContext, handoffResources, handoffActions, handoffMetadata)",
`appendChatContextLine(&b, "Finding Status", unifiedFindingChatStatus(f, time.Now()))`,
`appendChatContextLine(&b, "Finding Detected At", f.DetectedAt.Format(time.RFC3339))`,
`appendChatContextLine(&b, "Finding Last Seen At", f.LastSeenAt.Format(time.RFC3339))`,
@@ -418,10 +418,11 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
"Model Boundary",
`return "suppressed"`,
"Prompt:",
- "HandoffContext:",
- "HandoffResources: handoffResources",
- "HandoffActions: handoffActions",
- "HandoffMetadata: handoffMetadata",
+ "HandoffContext: handoffContext",
+ "HandoffResources: handoffResources",
+ "HandoffActions: handoffActions",
+ "HandoffMetadata: handoffMetadata",
+ "SuppressSessionEvent: true",
} {
if !strings.Contains(handlerText, required) {
t.Fatalf("ai_handler.go must preserve model-only finding handoff contract: missing %q", required)