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
Stream Assistant cold sessions directly
rcourtman479ac6db2cc6
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 9ad6b52b78..626699edfa 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -1191,6 +1191,15 @@ internal workflow-state cards as assistant output. The user-facing stream ismodel text, model thinking where supported, model-selected tool calls, governedapproval requests, and model questions; internal runtime telemetry stays out ofthe chat transcript.+Cold-start Assistant chat session creation is also stream-owned. Ordinary first+messages may call `/api/ai/chat` without a `session_id`; `chat.Service.ExecuteStream`+must create or resolve the durable session before provider execution and emit a+first-class `session` SSE event carrying `SessionData{ID: ...}`. The browser+chat runtime binds its active session from that stream event, with `done` and+`question` session identifiers retained only as compatible terminal/interactive+payloads, rather than issuing a separate `/api/ai/sessions` preflight before+the first user message. Explicit session-management actions may still create a+session through the session endpoint.The AI transport files are shared with `api-contracts`, not delegated away toit. `frontend-modern/src/api/ai.ts`,diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 79538c7f06..fad314c9ad 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -431,6 +431,13 @@ payload shape change when the portal presents compact client rows.workflow telemetry may remain a transport event, but browser Assistantoutput is owned by the AI runtime presentation contract rather than byAPI-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+ 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,+ not the primary cold-session creation contract.34. `internal/api/ai_handlers.go` shared with `ai-runtime`: AI settings and remediation handlers are both an AI runtime control surface and a canonical API payload contract boundary.Provider test responses from `/api/ai/test` and provider-specific`/api/ai/test/{provider}` preflight responses must return one safediff --git a/frontend-modern/src/api/__tests__/aiChatEvents.test.ts b/frontend-modern/src/api/__tests__/aiChatEvents.test.tsindex b5a6afda53..7d3b99f7e9 100644--- a/frontend-modern/src/api/__tests__/aiChatEvents.test.ts+++ b/frontend-modern/src/api/__tests__/aiChatEvents.test.ts@@ -1,9 +1,19 @@import { describe, expect, it } from 'vitest';import aiChatEventsSource from '@/api/generated/aiChatEvents.ts?raw';+import type { AIChatStreamEvent, SessionData } from '@/api/generated/aiChatEvents';describe('AI chat stream event contract', () => {it('does not expose the retired explore pre-pass stream event', () => {expect(aiChatEventsSource).not.toContain('ExploreStatusData');expect(aiChatEventsSource).not.toContain("type: 'explore_status'");});++ it('exposes the backend-created session event as a typed stream contract', () => {+ const session: SessionData = { id: 'sess-stream' };+ const event: AIChatStreamEvent = { type: 'session', data: session };++ expect(event.data.id).toBe('sess-stream');+ expect(aiChatEventsSource).toContain('export interface SessionData');+ expect(aiChatEventsSource).toContain("type: 'session'");+ });});diff --git a/frontend-modern/src/api/generated/aiChatEvents.ts b/frontend-modern/src/api/generated/aiChatEvents.tsindex dcad190e5c..c788d9a76b 100644--- a/frontend-modern/src/api/generated/aiChatEvents.ts+++ b/frontend-modern/src/api/generated/aiChatEvents.ts@@ -83,6 +83,10 @@ export interface QuestionOption {description?: string;}+export interface SessionData {+ id: string;+}+export interface ThinkingData {text: string;}@@ -111,6 +115,7 @@ export interface WorkflowStateData {}export type AIChatStreamEvent =+ | { type: 'session'; data: SessionData }| { type: 'content'; data: ContentData }| { type: 'thinking'; data: ThinkingData }| { type: 'workflow_state'; data: WorkflowStateData }diff --git a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.tsindex d31356e97d..fa569c2f6a 100644--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts@@ -123,16 +123,27 @@ describe('useChat', () => {dispose();});- it('creates session when none exists and sends message', async () => {- mockCreateSession.mockResolvedValue({ id: 'new-sess' });- mockChat.mockResolvedValue(undefined);+ it('streams cold messages without precreating a session and binds the stream session', async () => {+ mockChat.mockImplementation(+ (+ _prompt: string,+ _session: string | undefined,+ _model: string | undefined,+ onEvent: (event: StreamEvent) => void,+ ) => {+ onEvent({ type: 'session', data: { id: 'new-sess' } } as StreamEvent);+ return Promise.resolve();+ },+ );const onConversationChanged = vi.fn();const { value: chat, dispose } = withRoot(() => useChat({ onConversationChanged }));const result = await chat.sendMessage('hello');expect(result).toBe(true);- expect(mockCreateSession).toHaveBeenCalledOnce();+ expect(mockCreateSession).not.toHaveBeenCalled();+ expect(mockChat).toHaveBeenCalledOnce();+ expect(mockChat.mock.calls[0][1]).toBeUndefined();expect(chat.sessionId()).toBe('new-sess');expect(onConversationChanged).toHaveBeenCalledTimes(2);@@ -145,14 +156,13 @@ describe('useChat', () => {dispose();});- it('shows a pending assistant turn before cold-session creation finishes', async () => {- let resolveSession!: (value: { id: string }) => void;- mockCreateSession.mockReturnValue(- new Promise((resolve) => {- resolveSession = resolve;+ it('starts the cold chat stream immediately with a pending assistant turn', async () => {+ let resolveChat!: () => void;+ mockChat.mockReturnValue(+ new Promise<void>((resolve) => {+ resolveChat = resolve;}),);- mockChat.mockResolvedValue(undefined);const { value: chat, dispose } = withRoot(() => useChat());const result = chat.sendMessage('test');@@ -166,12 +176,13 @@ describe('useChat', () => {isStreaming: true,pendingTools: [],});- expect(mockChat).not.toHaveBeenCalled();+ expect(mockCreateSession).not.toHaveBeenCalled();+ expect(mockChat).toHaveBeenCalledOnce();+ expect(mockChat.mock.calls[0][1]).toBeUndefined();- resolveSession({ id: 'new-sess' });+ resolveChat();await result;- expect(chat.sessionId()).toBe('new-sess');expect(chat.messages()).toHaveLength(2);expect(chat.messages()[1].role).toBe('assistant');dispose();@@ -189,21 +200,23 @@ describe('useChat', () => {dispose();});- it('returns false and notifies on session creation failure', async () => {- mockCreateSession.mockRejectedValue(new Error('network error'));+ it('handles cold chat API error without precreating a session', async () => {+ mockChat.mockRejectedValue(new Error('server error'));const { value: chat, dispose } = withRoot(() => useChat());const result = await chat.sendMessage('hello');expect(result).toBe(false);- expect(mockNotifyError).toHaveBeenCalledWith('Failed to create chat session');+ expect(mockCreateSession).not.toHaveBeenCalled();+ expect(mockNotifyError).toHaveBeenCalledWith('server error');expect(chat.messages()).toHaveLength(2);expect(chat.messages()[0]).toMatchObject({ role: 'user', content: 'hello' });expect(chat.messages()[1]).toMatchObject({role: 'assistant',- error: 'Could not start a chat session. Check your connection and try again.',+ error: 'server error',isStreaming: false,});+ expect(chat.sessionId()).toBe('');expect(chat.isLoading()).toBe(false);dispose();});@@ -478,12 +491,25 @@ describe('useChat', () => {dispose();});- it('stop during cold-session creation prevents the deferred chat call', async () => {- let resolveSession!: (value: { id: string }) => void;- mockCreateSession.mockReturnValue(- new Promise((resolve) => {- resolveSession = resolve;- }),+ it('stop during cold stream prevents deferred session binding', async () => {+ let capturedSignal: AbortSignal | undefined;+ let fireEvent!: TestStreamDispatch;+ const abortError = new Error('Aborted');+ abortError.name = 'AbortError';+ mockChat.mockImplementation(+ (+ _prompt: string,+ _session: string | undefined,+ _model: string | undefined,+ onEvent: (event: StreamEvent) => void,+ signal?: AbortSignal,+ ) => {+ capturedSignal = signal;+ fireEvent = (event) => dispatchTestStreamEvent(onEvent, event);+ return new Promise<void>((_resolve, reject) => {+ signal?.addEventListener('abort', () => reject(abortError));+ });+ },);const { value: chat, dispose } = withRoot(() => useChat());@@ -491,10 +517,11 @@ describe('useChat', () => {expect(chat.isLoading()).toBe(true);chat.stop();- resolveSession({ id: 'late-session' });+ fireEvent({ type: 'session', data: { id: 'late-session' } });await expect(send).resolves.toBe(false);- expect(mockChat).not.toHaveBeenCalled();+ expect(capturedSignal?.aborted).toBe(true);+ expect(mockAbortSession).not.toHaveBeenCalled();expect(chat.sessionId()).toBe('');expect(chat.isLoading()).toBe(false);dispose();diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.tsindex 7fb98298bb..b9b68b4e07 100644--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts@@ -182,9 +182,34 @@ export function useChat(options: UseChatOptions = {}) {return '';};+ const extractSessionId = (data: unknown): string => {+ if (!data || typeof data !== 'object') return '';+ const record = data as Record<string, unknown>;+ const id = record.id ?? record.session_id;+ return typeof id === 'string' ? id.trim() : '';+ };++ const applyStreamSessionId = (streamSessionId: string) => {+ if (!streamSessionId) return;+ const previousSessionId = sessionId();+ if (previousSessionId === streamSessionId) return;+ setSessionId(streamSessionId);+ if (!previousSessionId) {+ void notifyConversationChanged();+ }+ };+const processEvent = (assistantId: string, requestId: number, event: StreamEvent) => {if (requestId !== activeRequestId) return;+ if (event.type === 'session') {+ applyStreamSessionId(extractSessionId(event.data));+ return;+ }+ if (event.type === 'done' || event.type === 'question') {+ applyStreamSessionId(extractSessionId(event.data));+ }+setMessages((prev) =>prev.map((msg) => {if (msg.id !== assistantId) return msg;@@ -544,38 +569,10 @@ export function useChat(options: UseChatOptions = {}) {setIsLoading(true);const requestId = ++activeRequestId;- // Ensure we have a session for conversation continuity- // Without this, every message creates a new session and loses context+ // Existing sessions preserve conversation continuity. Cold chats let the+ // backend create the session inside the stream and bind via the session SSE+ // event, avoiding a separate preflight request before first token.let currentSessionId = sessionId();- if (!currentSessionId) {- try {- const session = await AIChatAPI.createSession();- if (requestId !== activeRequestId) {- return false;- }- currentSessionId = session.id;- setSessionId(currentSessionId);- void notifyConversationChanged();- logger.debug('[useChat] Created new session', { sessionId: currentSessionId });- } catch (error) {- logger.error('[useChat] Failed to create session:', error);- notificationStore.error('Failed to create chat session');- setMessages((prev) =>- prev.map((msg) =>- msg.id === assistantId- ? {- ...msg,- error: 'Could not start a chat session. Check your connection and try again.',- isStreaming: false,- pendingTools: [],- }- : msg,- ),- );- setIsLoading(false);- return false;- }- }if (backendAbortBeforeNextSend &&@@ -594,7 +591,7 @@ export function useChat(options: UseChatOptions = {}) {try {await AIChatAPI.chat(prompt,- currentSessionId,+ currentSessionId || undefined,model() || undefined,(event: StreamEvent) => {processEvent(assistantId, requestId, event);diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 67b7ad635d..5515ab6775 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -846,9 +846,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac}streamCallback(event)}- sessionData, _ := json.Marshal(struct {- ID string `json:"id"`- }{ID: session.ID})+ sessionData, _ := json.Marshal(SessionData{ID: session.ID})streamCallback(StreamEvent{Type: "session", Data: sessionData})resultMessages, err := loop.ExecuteWithTools(ctx, session.ID, messages, filteredTools, wrappedCallback)diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.goindex c95a89ba8f..aac9806894 100644--- a/internal/ai/chat/service_execute_additional_test.go+++ b/internal/ai/chat/service_execute_additional_test.go@@ -351,9 +351,7 @@ func TestService_ExecuteStream_Success(t *testing.T) {doneCount++}if event.Type == "session" {- var data struct {- ID string `json:"id"`- }+ var data SessionDataif err := json.Unmarshal(event.Data, &data); err != nil {t.Fatalf("unmarshal session event: %v", err)}diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.goindex 958a475429..ad9371fc8d 100644--- a/internal/ai/chat/types.go+++ b/internal/ai/chat/types.go@@ -207,6 +207,12 @@ type WorkflowStateData struct {Tool string `json:"tool,omitempty"` // Tool associated with this transition}+// SessionData is the data for "session" events emitted once the backend has+// created or resolved the durable chat session for a stream.+type SessionData struct {+ ID string `json:"id"`+}+// ToolStartData is the data for "tool_start" eventstype ToolStartData struct {ID string `json:"id"`diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 12dda2fa99..c5280ab77a 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -10532,6 +10532,13 @@ func TestContract_ChatStreamEventJSONSnapshots(t *testing.T) {event chat.StreamEventwant string}{+ {+ name: "session",+ event: mustStreamEvent(t, "session", chat.SessionData{+ ID: "session-1",+ }),+ want: `{"type":"session","data":{"id":"session-1"}}`,+ },{name: "content",event: mustStreamEvent(t, "content", chat.ContentData{diff --git a/scripts/generate-types.go b/scripts/generate-types.goindex 7f7b375391..5fad337d92 100644--- a/scripts/generate-types.go+++ b/scripts/generate-types.go@@ -38,6 +38,7 @@ func main() {reflect.TypeOf(chat.ContentData{}),reflect.TypeOf(chat.ThinkingData{}),reflect.TypeOf(chat.WorkflowStateData{}),+ reflect.TypeOf(chat.SessionData{}),reflect.TypeOf(chat.ToolStartData{}),reflect.TypeOf(chat.ToolEndData{}),reflect.TypeOf(chat.ApprovalPlanData{}),@@ -71,6 +72,7 @@ func main() {// Stream event union matches internal/api/contract_test.go snapshots.buf.WriteString("export type AIChatStreamEvent =\n")+ buf.WriteString(" | { type: 'session'; data: SessionData }\n")buf.WriteString(" | { type: 'content'; data: ContentData }\n")buf.WriteString(" | { type: 'thinking'; data: ThinkingData }\n")buf.WriteString(" | { type: 'workflow_state'; data: WorkflowStateData }\n")