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.

Notify when the Assistant finishes or needs you while the tab is in the background

rcourtmandb7679a984be
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/assistantNotifications.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/assistantNotifications.test.ts
new file mode 100644
index 0000000000..57455712fe
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/assistantNotifications.test.ts
@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const installNotificationMock = (permission: NotificationPermission) => {
+ const instances: Array<{ title: string; options?: NotificationOptions }> = [];
+ class NotificationMock {
+ static permission: NotificationPermission = permission;
+ static requestPermission = vi.fn(async () => NotificationMock.permission);
+ onclick: (() => void) | null = null;
+ close = vi.fn();
+ constructor(title: string, options?: NotificationOptions) {
+ instances.push({ title, options });
+ }
+ }
+ vi.stubGlobal('Notification', NotificationMock);
+ return { NotificationMock, instances };
+};
+
+const setDocumentHidden = (hidden: boolean) => {
+ Object.defineProperty(document, 'hidden', { value: hidden, configurable: true });
+};
+
+const loadModule = async () => {
+ vi.resetModules();
+ return import('../assistantNotifications');
+};
+
+describe('assistantNotifications', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ setDocumentHidden(true);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ setDocumentHidden(false);
+ });
+
+ it('stays silent until the user opts in', async () => {
+ const { instances } = installNotificationMock('granted');
+ const mod = await loadModule();
+
+ mod.notifyAssistantAttention('done');
+ expect(instances).toHaveLength(0);
+ });
+
+ it('requests permission on enable and notifies while the tab is hidden', async () => {
+ const { NotificationMock, instances } = installNotificationMock('default');
+ NotificationMock.requestPermission = vi.fn(async () => {
+ NotificationMock.permission = 'granted';
+ return 'granted' as NotificationPermission;
+ });
+ const mod = await loadModule();
+
+ await expect(mod.setAssistantNotificationsEnabled(true)).resolves.toBe(true);
+ expect(NotificationMock.requestPermission).toHaveBeenCalledOnce();
+
+ mod.notifyAssistantAttention('question');
+ expect(instances).toHaveLength(1);
+ expect(instances[0].title).toBe('Pulse Assistant');
+ expect(instances[0].options?.body).toBe('The Assistant has a question for you.');
+ // Generic copy only: no answer text, commands, or resource names.
+ expect(instances[0].options?.tag).toBe('pulse-assistant-question');
+ });
+
+ it('reports a denied permission as not enabled', async () => {
+ const { NotificationMock } = installNotificationMock('default');
+ NotificationMock.requestPermission = vi.fn(async () => 'denied' as NotificationPermission);
+ const mod = await loadModule();
+
+ await expect(mod.setAssistantNotificationsEnabled(true)).resolves.toBe(false);
+ expect(mod.assistantNotificationsEnabled()).toBe(false);
+ });
+
+ it('does not notify while the tab is visible and focused', async () => {
+ const { instances } = installNotificationMock('granted');
+ const mod = await loadModule();
+ await mod.setAssistantNotificationsEnabled(true);
+
+ setDocumentHidden(false);
+ const hasFocus = vi.spyOn(document, 'hasFocus').mockReturnValue(true);
+ mod.notifyAssistantAttention('done');
+ expect(instances).toHaveLength(0);
+ hasFocus.mockRestore();
+ });
+
+ it('persists the preference across module reloads', async () => {
+ const { NotificationMock } = installNotificationMock('granted');
+ NotificationMock.requestPermission = vi.fn(async () => 'granted' as NotificationPermission);
+ let mod = await loadModule();
+ await mod.setAssistantNotificationsEnabled(true);
+
+ mod = await loadModule();
+ expect(mod.assistantNotificationsEnabled()).toBe(true);
+
+ await mod.setAssistantNotificationsEnabled(false);
+ mod = await loadModule();
+ expect(mod.assistantNotificationsEnabled()).toBe(false);
+ });
+});
diff --git a/frontend-modern/src/components/AI/Chat/assistantNotifications.ts b/frontend-modern/src/components/AI/Chat/assistantNotifications.ts
new file mode 100644
index 0000000000..5a7f9c689c
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/assistantNotifications.ts
@@ -0,0 +1,91 @@
+import { createSignal } from 'solid-js';
+import { logger } from '@/utils/logger';
+
+export type AssistantAttentionKind = 'done' | 'error' | 'question' | 'approval';
+
+const STORAGE_KEY = 'pulse:ai_chat_attention_notifications';
+
+// Generic, fixed copy only. OS notification centers persist and sync text, so
+// answers, commands, and resource names must never travel through them.
+const ATTENTION_BODY: Record<AssistantAttentionKind, string> = {
+ done: 'The Assistant finished its response.',
+ error: 'The Assistant ran into an error.',
+ question: 'The Assistant has a question for you.',
+ approval: 'An action is waiting for your approval.',
+};
+
+const readStoredPreference = (): boolean => {
+ try {
+ return localStorage.getItem(STORAGE_KEY) === 'true';
+ } catch {
+ return false;
+ }
+};
+
+const [enabled, setEnabled] = createSignal(readStoredPreference());
+
+export const assistantNotificationsSupported = (): boolean =>
+ typeof window !== 'undefined' && 'Notification' in window;
+
+export const assistantNotificationsEnabled = enabled;
+
+const persistPreference = (value: boolean) => {
+ try {
+ localStorage.setItem(STORAGE_KEY, value ? 'true' : 'false');
+ } catch {
+ // Preference simply won't survive a reload.
+ }
+};
+
+// Enabling asks the browser for permission (must run in a user gesture).
+// Returns the resulting enabled state so callers can reflect a denial.
+export const setAssistantNotificationsEnabled = async (value: boolean): Promise<boolean> => {
+ if (!value) {
+ setEnabled(false);
+ persistPreference(false);
+ return false;
+ }
+ if (!assistantNotificationsSupported()) return false;
+
+ let permission = Notification.permission;
+ if (permission === 'default') {
+ try {
+ permission = await Notification.requestPermission();
+ } catch (error) {
+ logger.debug('[AssistantNotifications] Permission request failed', { error });
+ permission = 'denied';
+ }
+ }
+ const granted = permission === 'granted';
+ setEnabled(granted);
+ persistPreference(granted);
+ return granted;
+};
+
+// Notify only when the user is away: tab hidden or window unfocused. A
+// notification for a visible chat is noise.
+const userIsAway = (): boolean => {
+ if (typeof document === 'undefined') return false;
+ if (document.hidden) return true;
+ return typeof document.hasFocus === 'function' ? !document.hasFocus() : false;
+};
+
+export const notifyAssistantAttention = (kind: AssistantAttentionKind): void => {
+ if (!enabled()) return;
+ if (!assistantNotificationsSupported() || Notification.permission !== 'granted') return;
+ if (!userIsAway()) return;
+
+ try {
+ const notification = new Notification('Pulse Assistant', {
+ body: ATTENTION_BODY[kind],
+ // One slot per kind: a burst of events replaces instead of stacking.
+ tag: `pulse-assistant-${kind}`,
+ });
+ notification.onclick = () => {
+ window.focus();
+ notification.close();
+ };
+ } catch (error) {
+ logger.debug('[AssistantNotifications] Failed to show notification', { error });
+ }
+};
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index 18ab26ca8c..562ffb8080 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -20,6 +20,7 @@ import {
type AssistantOutputArtifactStreamState,
} from '../assistantOutputHygiene';
import { isAssistantExplicitModelRoute } from '../assistantModelRoutes';
+import { notifyAssistantAttention } from '../assistantNotifications';
import { getAssistantFastToolCompletionSettleUntil } from '../streamActivityTiming';
import type {
ChatMessage,
@@ -1321,6 +1322,13 @@ export function useChat(options: UseChatOptions = {}) {
const processEvent = (assistantId: string, requestId: number, event: StreamEvent) => {
if (requestId !== activeRequestId) return;
+ // Attention notifications fire here (once per stream event), never inside
+ // the setMessages updaters below, which Solid may re-run.
+ if (event.type === 'done') notifyAssistantAttention('done');
+ else if (event.type === 'error') notifyAssistantAttention('error');
+ else if (event.type === 'question') notifyAssistantAttention('question');
+ else if (event.type === 'approval_needed') notifyAssistantAttention('approval');
+
if (event.type === 'session') {
applyStreamSessionId(extractSessionId(event.data));
return;
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index b453e02957..0ae25ce412 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -25,6 +25,8 @@ import RotateCwIcon from 'lucide-solid/icons/rotate-cw';
import SettingsIcon from 'lucide-solid/icons/settings';
import Undo2Icon from 'lucide-solid/icons/undo-2';
import XIcon from 'lucide-solid/icons/x';
+import BellIcon from 'lucide-solid/icons/bell';
+import BellOffIcon from 'lucide-solid/icons/bell-off';
import BookmarkIcon from 'lucide-solid/icons/bookmark';
import CheckIcon from 'lucide-solid/icons/check';
import CircleHelpIcon from 'lucide-solid/icons/circle-help';
@@ -172,6 +174,11 @@ import {
type AssistantSlashCommand,
type AssistantSlashCommandAction,
} from './assistantSlashCommands';
+import {
+ assistantNotificationsEnabled,
+ assistantNotificationsSupported,
+ setAssistantNotificationsEnabled,
+} from './assistantNotifications';
import {
buildAssistantTranscriptFilename,
downloadAssistantTranscriptFile,
@@ -3526,6 +3533,20 @@ export const AIChat: Component<AIChatProps> = (props) => {
focusComposer();
};
+ const handleToggleAttentionNotifications = async () => {
+ if (assistantNotificationsEnabled()) {
+ await setAssistantNotificationsEnabled(false);
+ return;
+ }
+ const granted = await setAssistantNotificationsEnabled(true);
+ if (!granted) {
+ notificationStore.info(
+ 'Notifications are blocked for this site. Allow them in your browser to be alerted when the Assistant needs you.',
+ 4000,
+ );
+ }
+ };
+
const handleForkSession = async () => {
if (forkingSession()) return;
const sourceSessionId = chat.sessionId().trim();
@@ -3939,6 +3960,34 @@ export const AIChat: Component<AIChatProps> = (props) => {
<span class="font-medium">{AI_CHAT_NEW_SESSION_SHORT_LABEL}</span>
</button>
+ <Show when={assistantNotificationsSupported()}>
+ <button
+ type="button"
+ onClick={() => {
+ void handleToggleAttentionNotifications();
+ }}
+ class={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border transition-colors hover:border-border hover:bg-surface-hover hover:text-base-content ${
+ assistantNotificationsEnabled()
+ ? 'bg-surface-alt text-base-content'
+ : 'bg-surface text-muted'
+ }`}
+ title={
+ assistantNotificationsEnabled()
+ ? 'Notifications on: you are alerted when the Assistant finishes or needs you while this tab is in the background'
+ : 'Notify me when the Assistant finishes or needs me while this tab is in the background'
+ }
+ aria-label="Toggle Assistant attention notifications"
+ aria-pressed={assistantNotificationsEnabled()}
+ >
+ <Show
+ when={assistantNotificationsEnabled()}
+ fallback={<BellOffIcon class="h-4 w-4" aria-hidden="true" />}
+ >
+ <BellIcon class="h-4 w-4" aria-hidden="true" />
+ </Show>
+ </button>
+ </Show>
+
<button
type="button"
onClick={() => {