Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions app/src/components/notifications/CoreNotificationCard.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/**
* Action-button contract for core notification cards (issue #3507).
* Asserts that the calendar auto-join prompt renders its buttons, dispatches
* the `openhuman.agent_meetings_notification_action` RPC with the right
* params on click, and surfaces an error when the RPC rejects.
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { Provider } from 'react-redux';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { store } from '../../store';
import { type NotificationItem } from '../../store/notificationSlice';
import CoreNotificationCard from './CoreNotificationCard';

const callCoreRpc = vi.hoisted(() => vi.fn());
vi.mock('../../services/coreRpcClient', () => ({ callCoreRpc }));

function makeItem(overrides: Partial<NotificationItem> = {}): NotificationItem {
return {
id: 'meet-auto-join:m1',
category: 'meetings',
title: 'Meeting starting: Standup',
body: 'Add Tiny to this meeting?',
timestamp: Date.now(),
read: false,
actions: [
{ actionId: 'join_listen', label: 'Join (listen only)', payload: { meetingId: 'm1' } },
{ actionId: 'join_active', label: 'Join & reply', payload: { meetingId: 'm1' } },
{ actionId: 'skip', label: 'Not this one', payload: { meetingId: 'm1' } },
{ actionId: 'always_join', label: 'Always join', payload: { meetingId: 'm1' } },
],
...overrides,
};
}

function renderCard(item: NotificationItem) {
return render(
<Provider store={store}>
<CoreNotificationCard notification={item} />
</Provider>
);
}

describe('CoreNotificationCard', () => {
beforeEach(() => {
vi.clearAllMocks();
store.dispatch({ type: 'notifications/clearAll' });
});

it('renders a localized button per action', () => {
renderCard(makeItem());
expect(screen.getByRole('button', { name: 'Join (listen only)' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Join & reply' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Not this one' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Always join' })).toBeInTheDocument();
});

it('dispatches the notification-action RPC with action_id + payload on click', async () => {
callCoreRpc.mockResolvedValue({ ok: true });
renderCard(makeItem());

fireEvent.click(screen.getByRole('button', { name: 'Join (listen only)' }));

await waitFor(() => expect(callCoreRpc).toHaveBeenCalledTimes(1));
expect(callCoreRpc).toHaveBeenCalledWith({
method: 'openhuman.agent_meetings_notification_action',
params: { action_id: 'join_listen', payload: { meetingId: 'm1' } },
});
});

it('marks the notification read in the store after a successful action', async () => {
callCoreRpc.mockResolvedValue({ ok: true });
store.dispatch({ type: 'notifications/notificationReceived', payload: makeItem() });
renderCard(makeItem());

fireEvent.click(screen.getByRole('button', { name: 'Not this one' }));

await waitFor(() => {
const item = store.getState().notifications.items.find(i => i.id === 'meet-auto-join:m1');
expect(item?.read).toBe(true);
});
});

it('clears the action buttons after a successful action so it cannot be re-clicked', async () => {
callCoreRpc.mockResolvedValue({ ok: true });
store.dispatch({ type: 'notifications/notificationReceived', payload: makeItem() });
renderCard(makeItem());

fireEvent.click(screen.getByRole('button', { name: 'Not this one' }));

await waitFor(() => {
const item = store.getState().notifications.items.find(i => i.id === 'meet-auto-join:m1');
expect(item?.actions ?? []).toHaveLength(0);
});
});

it('keeps the action buttons when the RPC rejects', async () => {
callCoreRpc.mockRejectedValue(new Error('boom'));
store.dispatch({ type: 'notifications/notificationReceived', payload: makeItem() });
renderCard(makeItem());

fireEvent.click(screen.getByRole('button', { name: 'Not this one' }));

await waitFor(() =>
expect(
screen.getByText('Could not complete that action. Please try again.')
).toBeInTheDocument()
);
const item = store.getState().notifications.items.find(i => i.id === 'meet-auto-join:m1');
expect(item?.actions).toHaveLength(4);
});

it('surfaces an error message when the RPC rejects', async () => {
callCoreRpc.mockRejectedValue(new Error('boom'));
renderCard(makeItem());

fireEvent.click(screen.getByRole('button', { name: 'Always join' }));

await waitFor(() =>
expect(
screen.getByText('Could not complete that action. Please try again.')
).toBeInTheDocument()
);
});

it('renders nothing actionable when there are no actions', () => {
renderCard(makeItem({ actions: [] }));
expect(screen.queryByRole('button')).toBeNull();
});

it('disables all buttons while an action RPC is in flight', async () => {
let resolve!: (v: unknown) => void;
callCoreRpc.mockImplementation(
() =>
new Promise(r => {
resolve = r;
})
);
renderCard(makeItem());

fireEvent.click(screen.getByRole('button', { name: 'Join (listen only)' }));

// All buttons should be disabled while the call is pending.
const buttons = screen.getAllByRole('button');
buttons.forEach(btn => expect(btn).toBeDisabled());

resolve({ ok: true });
await waitFor(() => buttons.forEach(btn => expect(btn).not.toBeDisabled()));
});

it('shows no unread dot when notification is already read', () => {
renderCard(makeItem({ read: true }));
expect(document.querySelector('[aria-hidden="true"]')).toBeNull();
});

it('shows unread dot when notification is unread', () => {
renderCard(makeItem({ read: false }));
expect(document.querySelector('[aria-hidden="true"]')).toBeInTheDocument();
});
});
157 changes: 157 additions & 0 deletions app/src/components/notifications/CoreNotificationCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import debug from 'debug';
import { useState } from 'react';

import { useT } from '../../lib/i18n/I18nContext';
import { callCoreRpc } from '../../services/coreRpcClient';
Comment thread
coderabbitai[bot] marked this conversation as resolved.
import { useAppDispatch } from '../../store/hooks';
import {
clearNotificationActions,
markRead,
type NotificationItem,
} from '../../store/notificationSlice';
import NotificationBody from './NotificationBody';

// Namespaced debug per project logging rules (mirrors nativeNotifications).
const log = debug('notifications:core-card');

/** Relative human-readable time string from epoch ms, e.g. "2m ago". */
function relativeTime(timestampMs: number): string {
const diff = Math.max(0, Date.now() - timestampMs);
const s = Math.floor(diff / 1000);
if (s < 60) return `${s}s ago`;
const m = Math.floor(s / 60);
if (m < 60) return `${m}m ago`;
const h = Math.floor(m / 60);
if (h < 24) return `${h}h ago`;
return `${Math.floor(h / 24)}d ago`;
}
Comment thread
YellowSnnowmann marked this conversation as resolved.

/**
* Map a known meeting auto-join action id to its i18n key so button labels
* are localized rather than trusting the (English) label the core sends.
* Unknown action ids fall back to the server-provided label.
*/
const ACTION_LABEL_KEYS: Record<string, string> = {
join_listen: 'notifications.meeting.joinListen',
join_active: 'notifications.meeting.joinActive',
skip: 'notifications.meeting.skip',
always_join: 'notifications.meeting.alwaysJoin',
};

/** Primary (filled) vs secondary (outline) styling per action id. */
function isPrimaryAction(actionId: string): boolean {
return actionId === 'join_listen' || actionId === 'join_active';
}

interface Props {
notification: NotificationItem;
}

/**
* Renders a core-originated notification (from `state.notifications.items`)
* that carries action buttons — e.g. the calendar auto-join prompt
* (issue #3507). Clicking a button dispatches the
* `openhuman.agent_meetings_notification_action` RPC and marks the item read.
*/
const CoreNotificationCard = ({ notification: n }: Props) => {
const { t } = useT();
const dispatch = useAppDispatch();
const [pendingActionId, setPendingActionId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);

const handleAction = async (actionId: string, payload: unknown) => {
if (pendingActionId) return; // ignore double-clicks while a call is in flight
setPendingActionId(actionId);
setError(null);
log('action click id=%s notification=%s', actionId, n.id);
try {
await callCoreRpc<{ ok: boolean }>({
method: 'openhuman.agent_meetings_notification_action',
params: { action_id: actionId, payload },
});
log('action ok id=%s', actionId);
dispatch(markRead({ id: n.id }));
// Remove the buttons so the handled prompt can't be re-clicked (which would
// re-fire bot:join, or flip always_join after a skip). Without this the
// card stays pinned in NotificationCenter with live actions.
dispatch(clearNotificationActions({ id: n.id }));
} catch (err) {
log('action failed id=%s err=%o', actionId, err);
setError(t('notifications.meeting.actionError'));
} finally {
setPendingActionId(null);
}
};

return (
<div
className={`w-full p-3 border-b border-stone-100 dark:border-neutral-800 transition-colors duration-150 ${
n.read ? 'bg-white dark:bg-neutral-900' : 'bg-primary-50/30'
}`}
data-testid="core-notification-card">
<div className="flex items-start gap-3">
{/* Unread dot — reserve space so text stays aligned whether read or unread */}
<div className="mt-1.5 flex-shrink-0 w-2">
{!n.read && (
<span className="block w-2 h-2 rounded-full bg-primary-500" aria-hidden="true" />
)}
</div>

<div className="flex-1 min-w-0 text-left">
{/* Header row: category badge + timestamp */}
<div className="flex items-center gap-2 mb-1">
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium border bg-stone-100 dark:bg-neutral-800 text-stone-700 dark:text-neutral-200 border-stone-200 dark:border-neutral-800">
{t(`notifications.category.${n.category}`)}
</span>
<span className="ml-auto text-[11px] text-stone-400 dark:text-neutral-500 flex-shrink-0">
{relativeTime(n.timestamp)}
</span>
</div>

{/* Title */}
<p className="text-sm font-medium text-stone-900 dark:text-neutral-100">{n.title}</p>

{/* Body */}
{n.body && (
<p
data-testid="core-notification-body"
className="text-xs text-stone-500 dark:text-neutral-400 mt-0.5">
<NotificationBody body={n.body} />
</p>
)}

{/* Action buttons */}
{n.actions && n.actions.length > 0 && (
<div className="flex flex-wrap items-center gap-2 mt-2">
{n.actions.map(action => {
const labelKey = ACTION_LABEL_KEYS[action.actionId];
const label = labelKey ? t(labelKey) : action.label;
const primary = isPrimaryAction(action.actionId);
return (
<button
key={action.actionId}
type="button"
disabled={pendingActionId !== null}
onClick={() => {
void handleAction(action.actionId, action.payload);
}}
className={`px-2.5 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
primary
? 'bg-primary-500 text-white hover:bg-primary-600'
: 'bg-stone-100 dark:bg-neutral-800 text-stone-700 dark:text-neutral-200 hover:bg-stone-200 dark:hover:bg-neutral-800/60'
}`}>
{label}
</button>
);
})}
</div>
)}

{error && <p className="text-xs text-red-600 mt-1.5">{error}</p>}
</div>
</div>
</div>
);
};

export default CoreNotificationCard;
18 changes: 17 additions & 1 deletion app/src/components/notifications/NotificationCenter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
setIntegrationLoading,
setIntegrationNotifications,
} from '../../store/notificationSlice';
import CoreNotificationCard from './CoreNotificationCard';
import NotificationCard from './NotificationCard';

// ─────────────────────────────────────────────────────────────────────────────
Expand All @@ -32,7 +33,12 @@ const NotificationCenter = () => {
integrationItems: items,
integrationLoading: loading,
integrationError: error,
items: coreItems,
} = useAppSelector(s => s.notifications);
// Core-originated notifications that carry action buttons (e.g. the calendar
// auto-join prompt, issue #3507). These live in a separate Redux array from
// the server-fetched integration notifications and are surfaced at the top.
const coreActionItems = coreItems.filter(i => i.actions && i.actions.length > 0);
Comment thread
YellowSnnowmann marked this conversation as resolved.
const [selectedProvider, setSelectedProvider] = useState<string | undefined>(undefined);
// All providers seen across unfiltered loads — kept separate so the filter
// pill row doesn't collapse when a provider filter is active.
Expand Down Expand Up @@ -172,6 +178,16 @@ const NotificationCenter = () => {

{/* Content */}
<div className="flex-1 overflow-y-auto">
{/* Actionable core notifications (e.g. meeting auto-join prompt) —
always shown first, independent of integration load state. */}
{coreActionItems.length > 0 && (
<div className="divide-y-0">
{coreActionItems.map(item => (
<CoreNotificationCard key={item.id} notification={item} />
))}
</div>
)}

{loading && (
<div className="flex items-center justify-center py-12 text-stone-400 dark:text-neutral-500 text-sm">
{t('common.loading')}
Expand All @@ -184,7 +200,7 @@ const NotificationCenter = () => {
</div>
)}

{!loading && !error && visibleItems.length === 0 && (
{!loading && !error && visibleItems.length === 0 && coreActionItems.length === 0 && (
<div className="flex flex-col items-center justify-center py-16 text-stone-400 dark:text-neutral-500">
<svg
className="w-10 h-10 mb-3 opacity-40"
Expand Down
1 change: 1 addition & 0 deletions app/src/components/settings/hooks/useSettingsNavigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export type SettingsRoute =
| 'security'
| 'migration'
| 'companion'
| 'meetings'
| 'embeddings'
| 'search'
| 'skills-runner'
Expand Down
5 changes: 5 additions & 0 deletions app/src/components/settings/layout/settingsNavIcons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ export const SETTINGS_NAV_ICONS: Record<string, ReactNode> = {
'M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z'
)
),
meetings: icon(
stroke(
'M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z'
)
),
'developer-options': icon(stroke('M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4')),
about: icon(stroke('M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z')),
usage: icon(
Expand Down
Loading
Loading