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.

Tighten Assistant chat cancellation flow

rcourtman7103a27ee1d3
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 a84e2c9bb1..d492ef407d 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -691,13 +691,13 @@ describe('AIChat', () => {
expect(mockChat.sendMessage).not.toHaveBeenCalled();
});
- it('does not send when chat is loading', () => {
+ it('sends a replacement message when chat is loading', () => {
mockChat.isLoading.mockReturnValue(true);
renderChat();
const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
fireEvent.input(textarea, { target: { value: 'hello' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
- expect(mockChat.sendMessage).not.toHaveBeenCalled();
+ expect(mockChat.sendMessage).toHaveBeenCalledWith('hello', undefined, undefined);
});
it('clears input after successful submit', () => {
@@ -736,6 +736,7 @@ describe('AIChat', () => {
mockChat.isLoading.mockReturnValue(true);
renderChat();
expect(screen.getByTitle('Stop')).toBeInTheDocument();
+ expect(screen.getByTitle('Send')).toBeInTheDocument();
});
it('calls chat.stop when stop button is clicked', () => {
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 ac55095212..d31356e97d 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
@@ -7,6 +7,7 @@ vi.mock('@/api/aiChat', () => ({
createSession: vi.fn(),
chat: vi.fn(),
getMessages: vi.fn(),
+ abortSession: vi.fn(),
answerQuestion: vi.fn(),
},
}));
@@ -35,6 +36,7 @@ import { notificationStore } from '@/stores/notifications';
const mockCreateSession = AIChatAPI.createSession as ReturnType<typeof vi.fn>;
const mockChat = AIChatAPI.chat as ReturnType<typeof vi.fn>;
const mockGetMessages = AIChatAPI.getMessages as ReturnType<typeof vi.fn>;
+const mockAbortSession = AIChatAPI.abortSession as ReturnType<typeof vi.fn>;
const mockAnswerQuestion = AIChatAPI.answerQuestion as ReturnType<typeof vi.fn>;
const mockNotifyError = notificationStore.error as ReturnType<typeof vi.fn>;
@@ -64,6 +66,7 @@ function withRoot<T>(fn: () => T): { value: T; dispose: () => void } {
describe('useChat', () => {
beforeEach(() => {
vi.resetAllMocks();
+ mockAbortSession.mockResolvedValue(undefined);
});
// ──────────────────────────────────────────────
@@ -341,6 +344,7 @@ describe('useChat', () => {
let capturedSignal: AbortSignal | undefined;
const abortError = new Error('Aborted');
abortError.name = 'AbortError';
+ mockAbortSession.mockResolvedValue(undefined);
mockChat
.mockImplementationOnce(
@@ -373,6 +377,7 @@ describe('useChat', () => {
// First call should have been aborted
expect(capturedSignal?.aborted).toBe(true);
+ expect(mockAbortSession).toHaveBeenCalledWith('sess');
const result1 = await p1;
expect(result1).toBe(false); // Aborted → returns false
@@ -385,6 +390,115 @@ describe('useChat', () => {
expect(firstAssistant?.isStreaming).toBe(false);
dispose();
});
+
+ it('keeps replacement send loading state isolated from the aborted request', async () => {
+ let firstSignal: AbortSignal | undefined;
+ let resolveSecond!: () => void;
+ const abortError = new Error('Aborted');
+ abortError.name = 'AbortError';
+ mockAbortSession.mockResolvedValue(undefined);
+
+ mockChat
+ .mockImplementationOnce(
+ (
+ _p: string,
+ _s: string,
+ _m: string | undefined,
+ _onEvent: (e: StreamEvent) => void,
+ signal?: AbortSignal,
+ ) => {
+ firstSignal = signal;
+ return new Promise<void>((_resolve, reject) => {
+ signal?.addEventListener('abort', () => {
+ queueMicrotask(() => reject(abortError));
+ });
+ });
+ },
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveSecond = resolve;
+ }),
+ );
+
+ const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 'sess' }));
+ const first = chat.sendMessage('first');
+ await new Promise((r) => setTimeout(r, 0));
+
+ const second = chat.sendMessage('second');
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(firstSignal?.aborted).toBe(true);
+ await expect(first).resolves.toBe(false);
+ expect(chat.isLoading()).toBe(true);
+ expect(chat.messages().filter((message) => message.role === 'assistant')).toHaveLength(2);
+
+ resolveSecond();
+ await second;
+ expect(chat.isLoading()).toBe(false);
+ dispose();
+ });
+
+ it('stop aborts the browser stream and backend session', async () => {
+ let capturedSignal: AbortSignal | undefined;
+ const abortError = new Error('Aborted');
+ abortError.name = 'AbortError';
+ mockAbortSession.mockResolvedValue(undefined);
+ mockChat.mockImplementation(
+ (
+ _p: string,
+ _s: string,
+ _m: string | undefined,
+ _onEvent: (e: StreamEvent) => void,
+ signal?: AbortSignal,
+ ) => {
+ capturedSignal = signal;
+ return new Promise<void>((_resolve, reject) => {
+ signal?.addEventListener('abort', () => reject(abortError));
+ });
+ },
+ );
+
+ const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 'sess' }));
+ const send = chat.sendMessage('hello');
+ await new Promise((r) => setTimeout(r, 0));
+
+ chat.stop();
+ await expect(send).resolves.toBe(false);
+
+ expect(capturedSignal?.aborted).toBe(true);
+ expect(mockAbortSession).toHaveBeenCalledWith('sess');
+ expect(chat.isLoading()).toBe(false);
+ const assistant = chat.messages().find((message) => message.role === 'assistant');
+ expect(assistant).toMatchObject({
+ content: '(Stopped)',
+ isStreaming: false,
+ });
+ 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;
+ }),
+ );
+
+ const { value: chat, dispose } = withRoot(() => useChat());
+ const send = chat.sendMessage('cold start');
+
+ expect(chat.isLoading()).toBe(true);
+ chat.stop();
+ resolveSession({ id: 'late-session' });
+
+ await expect(send).resolves.toBe(false);
+ expect(mockChat).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.ts
index adf2cbce76..7fb98298bb 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -53,24 +53,63 @@ export function useChat(options: UseChatOptions = {}) {
// Abort controller for canceling requests
let abortControllerRef: AbortController | null = null;
+ let activeRequestId = 0;
+ let pendingBackendAbort: Promise<void> | null = null;
+
+ const abortBackendSession = (targetSessionId: string): Promise<void> | null => {
+ const normalizedSessionId = targetSessionId.trim();
+ if (!normalizedSessionId) return null;
+
+ const promise = AIChatAPI.abortSession(normalizedSessionId)
+ .catch((error) => {
+ logger.warn('[useChat] Failed to abort chat session:', error);
+ })
+ .finally(() => {
+ if (pendingBackendAbort === promise) {
+ pendingBackendAbort = null;
+ }
+ });
- // Cleanup on unmount
- onCleanup(() => {
- if (abortControllerRef) abortControllerRef.abort();
- });
+ pendingBackendAbort = promise;
+ return promise;
+ };
- // Stop/cancel current request
- const stop = () => {
+ const cancelActiveRequest = (markStopped: boolean): Promise<void> | null => {
+ const hasActiveRequest = isLoading() || abortControllerRef !== null;
+ if (!hasActiveRequest) return null;
+
+ const targetSessionId = sessionId();
if (abortControllerRef) {
abortControllerRef.abort();
abortControllerRef = null;
}
+ activeRequestId += 1;
+
setMessages((prev) =>
prev.map((msg) =>
- msg.isStreaming ? { ...msg, isStreaming: false, content: msg.content || '(Stopped)' } : msg,
+ msg.isStreaming
+ ? {
+ ...msg,
+ isStreaming: false,
+ content: markStopped ? msg.content || '(Stopped)' : msg.content,
+ pendingTools: [],
+ }
+ : msg,
),
);
setIsLoading(false);
+
+ return abortBackendSession(targetSessionId);
+ };
+
+ // Cleanup on unmount
+ onCleanup(() => {
+ void cancelActiveRequest(false);
+ });
+
+ // Stop/cancel current request
+ const stop = () => {
+ void cancelActiveRequest(true);
};
// Helper to add stream event for chronological display
@@ -143,7 +182,9 @@ export function useChat(options: UseChatOptions = {}) {
return '';
};
- const processEvent = (assistantId: string, event: StreamEvent) => {
+ const processEvent = (assistantId: string, requestId: number, event: StreamEvent) => {
+ if (requestId !== activeRequestId) return;
+
setMessages((prev) =>
prev.map((msg) => {
if (msg.id !== assistantId) return msg;
@@ -465,17 +506,16 @@ export function useChat(options: UseChatOptions = {}) {
): Promise<boolean> => {
if (!prompt.trim()) return false;
- // If already streaming, abort the current request first
- if (isLoading() && abortControllerRef) {
+ let backendAbortBeforeNextSend: Promise<void> | null = null;
+ const abortedSessionId = sessionId();
+
+ // If already streaming, abort the current request first.
+ // The UI is updated immediately; the next backend stream waits only when it
+ // would reuse the same session, so the abort endpoint cannot cancel the new
+ // run after it registers.
+ if (isLoading()) {
logger.debug('[useChat] Aborting current stream to send new message');
- abortControllerRef.abort();
- abortControllerRef = null;
- // Mark any streaming messages as stopped
- setMessages((prev) =>
- prev.map((msg) =>
- msg.isStreaming ? { ...msg, isStreaming: false, pendingTools: [] } : msg,
- ),
- );
+ backendAbortBeforeNextSend = cancelActiveRequest(false);
}
// Echo the user's message before any network work. Cold sessions can spend
@@ -502,6 +542,7 @@ export function useChat(options: UseChatOptions = {}) {
setMessages((prev) => [...prev, userMessage, streamingMessage]);
setIsLoading(true);
+ const requestId = ++activeRequestId;
// Ensure we have a session for conversation continuity
// Without this, every message creates a new session and loses context
@@ -509,6 +550,9 @@ export function useChat(options: UseChatOptions = {}) {
if (!currentSessionId) {
try {
const session = await AIChatAPI.createSession();
+ if (requestId !== activeRequestId) {
+ return false;
+ }
currentSessionId = session.id;
setSessionId(currentSessionId);
void notifyConversationChanged();
@@ -533,7 +577,19 @@ export function useChat(options: UseChatOptions = {}) {
}
}
- abortControllerRef = new AbortController();
+ if (
+ backendAbortBeforeNextSend &&
+ abortedSessionId &&
+ currentSessionId === abortedSessionId
+ ) {
+ await backendAbortBeforeNextSend;
+ if (requestId !== activeRequestId) {
+ return false;
+ }
+ }
+
+ const abortController = new AbortController();
+ abortControllerRef = abortController;
try {
await AIChatAPI.chat(
@@ -541,9 +597,9 @@ export function useChat(options: UseChatOptions = {}) {
currentSessionId,
model() || undefined,
(event: StreamEvent) => {
- processEvent(assistantId, event);
+ processEvent(assistantId, requestId, event);
},
- abortControllerRef?.signal,
+ abortController.signal,
mentions,
findingId,
sendOptions?.autonomousMode,
@@ -552,9 +608,15 @@ export function useChat(options: UseChatOptions = {}) {
sendOptions?.handoffActions,
sendOptions?.handoffMetadata,
);
+ if (requestId !== activeRequestId) {
+ return false;
+ }
await notifyConversationChanged();
return true;
} catch (error) {
+ if (requestId !== activeRequestId) {
+ return false;
+ }
if (error instanceof Error && error.name === 'AbortError') {
logger.debug('[useChat] Request aborted');
return false;
@@ -574,19 +636,23 @@ export function useChat(options: UseChatOptions = {}) {
await notifyConversationChanged();
return false;
} finally {
- abortControllerRef = null;
- setIsLoading(false);
+ if (requestId === activeRequestId) {
+ abortControllerRef = null;
+ setIsLoading(false);
+ }
}
};
// Clear messages and reset session (for starting fresh)
const clearMessages = () => {
+ void cancelActiveRequest(false);
setMessages([]);
setSessionId(''); // Clear session so next message creates a new one
};
// Load session messages
const loadSession = async (id: string): Promise<boolean> => {
+ void cancelActiveRequest(false);
try {
const msgs = await AIChatAPI.getMessages(id);
setMessages(
@@ -609,6 +675,7 @@ export function useChat(options: UseChatOptions = {}) {
// Create new session
const newSession = async () => {
+ void cancelActiveRequest(false);
try {
const session = await AIChatAPI.createSession();
setSessionId(session.id);
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index c84af26e81..26c0f1f87a 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -919,7 +919,6 @@ export const AIChat: Component<AIChatProps> = (props) => {
// Handle submit
const handleSubmit = () => {
- if (chat.isLoading()) return;
const prompt = input().trim();
if (!prompt) return;
const mentions = accumulatedMentions();
@@ -1686,7 +1685,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
onKeyDown={handleKeyDown}
placeholder={AI_CHAT_INPUT_PLACEHOLDER}
rows={1}
- class="max-h-40 min-h-[54px] flex-1 resize-none bg-transparent px-3.5 py-3.5 pr-14 text-sm leading-5 text-base-content placeholder-slate-400 focus:outline-none"
+ class="max-h-40 min-h-[54px] flex-1 resize-none bg-transparent px-3.5 py-3.5 pr-24 text-sm leading-5 text-base-content placeholder-slate-400 focus:outline-none"
/>
<div data-mention-autocomplete>
<MentionAutocomplete
@@ -1698,31 +1697,27 @@ export const AIChat: Component<AIChatProps> = (props) => {
visible={mentionActive()}
/>
</div>
- <div class="absolute bottom-2 right-2">
- <Show
- when={!chat.isLoading()}
- fallback={
- <button
- type="button"
- onClick={chat.stop}
- class="flex h-9 w-9 items-center justify-center rounded-md border border-border bg-surface text-base-content shadow-sm transition-colors hover:bg-surface-hover"
- title="Stop"
- aria-label="Stop response"
- >
- <SquareIcon class="h-4 w-4" />
- </button>
- }
- >
+ <div class="absolute bottom-2 right-2 flex items-center gap-1.5">
+ <Show when={chat.isLoading()}>
<button
- type="submit"
- disabled={!input().trim()}
- class="flex h-9 w-9 items-center justify-center rounded-md bg-blue-600 text-white shadow-sm transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-45"
- title="Send"
- aria-label="Send message"
+ type="button"
+ onClick={chat.stop}
+ class="flex h-9 w-9 items-center justify-center rounded-md border border-border bg-surface text-base-content shadow-sm transition-colors hover:bg-surface-hover"
+ title="Stop"
+ aria-label="Stop response"
>
- <SendIcon class="h-4 w-4" />
+ <SquareIcon class="h-4 w-4" />
</button>
</Show>
+ <button
+ type="submit"
+ disabled={!input().trim()}
+ class="flex h-9 w-9 items-center justify-center rounded-md bg-blue-600 text-white shadow-sm transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-45"
+ title="Send"
+ aria-label="Send message"
+ >
+ <SendIcon class="h-4 w-4" />
+ </button>
</div>
</div>
</form>