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.

Surface dead chat streams as interruptions; never restore phantom active turns

rcourtman3f37da8b1778
diff --git a/frontend-modern/src/api/__tests__/aiChat.test.ts b/frontend-modern/src/api/__tests__/aiChat.test.ts
index acb098e435..c24ac734c8 100644
--- a/frontend-modern/src/api/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts
@@ -1147,7 +1147,9 @@ describe('AIChatAPI', () => {
.fn()
.mockResolvedValueOnce({
done: false,
- value: encoder.encode('data: {"type":"content","data":{"text":"First"}}\n\n'),
+ value: encoder.encode(
+ 'data: {"type":"content","data":{"text":"First"}}\n\ndata: {"type":"done"}\n\n',
+ ),
})
.mockResolvedValueOnce({ done: true, value: undefined });
const releaseLock = vi.fn();
@@ -1187,6 +1189,36 @@ describe('AIChatAPI', () => {
expect(releaseLock).toHaveBeenCalledTimes(1);
});
+ it('surfaces a stream that closes without a terminal event as an interruption error', async () => {
+ const encoder = new TextEncoder();
+ const read = vi
+ .fn()
+ .mockResolvedValueOnce({
+ done: false,
+ value: encoder.encode('data: {"type":"content","data":{"text":"partial answer"}}\n\n'),
+ })
+ .mockResolvedValueOnce({ done: true, value: undefined });
+ const releaseLock = vi.fn();
+ const onEvent = vi.fn();
+
+ apiFetchMock.mockResolvedValueOnce({
+ ok: true,
+ body: {
+ getReader: () => ({ read, releaseLock }),
+ },
+ } as unknown as Response);
+
+ await AIChatAPI.chat('hello', undefined, undefined, onEvent);
+
+ const types = onEvent.mock.calls.map(([event]) => event.type);
+ expect(types).toEqual(['content', 'error']);
+ expect(onEvent.mock.calls[1][0]).toMatchObject({
+ type: 'error',
+ data: { message: expect.stringContaining('closed before the response finished') },
+ });
+ expect(releaseLock).toHaveBeenCalledTimes(1);
+ });
+
it('preserves safe handoff summaries on listed chat sessions', async () => {
const session = {
id: 'session-operator-briefing',
@@ -1371,7 +1403,11 @@ describe('AIChatAPI', () => {
expect(read).toHaveBeenCalledTimes(1);
expect(releaseLock).toHaveBeenCalledTimes(1);
- expect(onEvent).toHaveBeenCalledWith({ type: 'done' });
+ // A close without a terminal event is an interruption, not completion.
+ expect(onEvent).toHaveBeenCalledWith({
+ type: 'error',
+ data: { message: expect.stringContaining('closed before the response finished') },
+ });
expect(clearTimeoutSpy).toHaveBeenCalled();
clearTimeoutSpy.mockRestore();
});
@@ -1429,7 +1465,12 @@ describe('AIChatAPI', () => {
expect(logger.error).toHaveBeenCalledWith('[AI Chat] Failed to parse event', {
line: 'data: not valid json',
});
- expect(onEvent).toHaveBeenCalledWith({ type: 'done' });
+ // The malformed stream never delivered a terminal event, so the close
+ // surfaces as an interruption.
+ expect(onEvent).toHaveBeenCalledWith({
+ type: 'error',
+ data: { message: expect.stringContaining('closed before the response finished') },
+ });
expect(releaseLock).toHaveBeenCalledTimes(1);
});
diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.ts
index 10bbde738e..2ffb6a6af6 100644
--- a/frontend-modern/src/api/aiChat.ts
+++ b/frontend-modern/src/api/aiChat.ts
@@ -158,6 +158,13 @@ export interface AIChatStreamLifecycle {
const AI_CHAT_STREAM_TEXT_PAINT_CHECKPOINT_INTERVAL = 4;
const AI_CHAT_STREAM_TEXT_EVENT_TYPES = new Set(['content', 'thinking']);
+// The backend writes an SSE ": heartbeat" comment every 5 seconds while a
+// turn is in flight, so a healthy connection never goes quiet for long. If no
+// bytes arrive for this window the connection is dead (backend restart,
+// half-open socket) and the turn must fail fast instead of leaving the user
+// staring at "Generating response" for the old 300s ceiling.
+export const AI_CHAT_STREAM_INACTIVITY_TIMEOUT_MS = 30000;
+
const isAIChatStreamTextEvent = (event: Pick<StreamEvent, 'type'>): boolean =>
AI_CHAT_STREAM_TEXT_EVENT_TYPES.has(event.type);
@@ -417,8 +424,17 @@ export class AIChatAPI {
throw new Error('Pulse Assistant stream timed out waiting for provider data.');
},
onComplete: () => {
- onEvent({ type: 'done' });
+ // The backend always terminates a chat stream with an explicit done or
+ // error event. A clean close without one means the connection was
+ // severed mid-turn (backend restart, proxy drop) — surface an
+ // interruption the user can retry instead of pretending the turn
+ // finished.
+ onEvent({
+ type: 'error',
+ data: { message: 'Connection to Pulse closed before the response finished.' },
+ } as StreamEvent);
},
+ timeoutMs: AI_CHAT_STREAM_INACTIVITY_TIMEOUT_MS,
yieldBetweenEvents: createAIChatStreamPaintCheckpointPredicate(),
});
}
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
index dd609b835f..190849deb1 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
@@ -3313,6 +3313,30 @@ describe('useChat', () => {
dispose();
});
+ it('marks every restored message as not streaming so no phantom active turn survives a load', async () => {
+ mockGetMessages.mockResolvedValue([
+ { id: 'msg-1', role: 'user', content: 'check minipc', timestamp: '2024-01-01T00:00:00Z' },
+ {
+ id: 'msg-2',
+ role: 'assistant',
+ // A persisted turn that ended without a final answer (e.g. the
+ // stream died mid-turn) must still restore as settled history.
+ content: '',
+ timestamp: '2024-01-01T00:00:01Z',
+ tool_calls: [{ name: 'pulse_query', input: '{}', output: '', success: false }],
+ },
+ ]);
+
+ const { value: chat, dispose } = withRoot(() => useChat());
+ const loaded = await chat.loadSession('sess-interrupted');
+
+ expect(loaded).toBe(true);
+ for (const msg of chat.messages()) {
+ expect(msg.isStreaming).toBe(false);
+ }
+ dispose();
+ });
+
it('restores the latest explicit model route before publishing the loaded session id', async () => {
mockGetMessages.mockResolvedValue([
{
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index bb620fb941..046918ebaf 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -2159,6 +2159,11 @@ export function useChat(options: UseChatOptions = {}) {
model: m.model,
toolCalls,
streamEvents,
+ // Restored messages are never live. Leaving this undefined reads as
+ // "still streaming" to the activity dock (isStreaming !== false),
+ // which pinned a phantom "Generating response" after loading any
+ // session whose last turn ended without a terminal event.
+ isStreaming: false as const,
};
});
const restoredModel = latestExplicitModelRouteFromTranscript(loadedMessages);