Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

10.2 KB
Raw Blame
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { useT } from '../../lib/i18n/I18nContext';
import { resolveIntegrationRoute } from '../../lib/notificationRouter';
import {
  dismissNotification,
  fetchNotifications,
  markNotificationActed,
  markNotificationRead,
} from '../../services/notificationService';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import {
  dismissIntegrationNotification,
  markIntegrationActed,
  markIntegrationRead,
  setIntegrationError,
  setIntegrationLoading,
  setIntegrationNotifications,
} from '../../store/notificationSlice';
import ChipTabs from '../layout/ChipTabs';
import { Alert, AlertDescription } from '../ui';
import Button from '../ui/Button';
import CoreNotificationCard from './CoreNotificationCard';
import FlowApprovalCard from './FlowApprovalCard';
import GateApprovalCard, { isGateApprovalNotification } from './GateApprovalCard';
import NotificationCard from './NotificationCard';

// ─────────────────────────────────────────────────────────────────────────────
// Component
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Chip id standing in for "no provider filter". `selectedProvider` is
 * `string | undefined` (undefined is what the fetch effect sends as "all"),
 * but `ChipTabs` is single-select over a non-optional value — so the sentinel
 * lives in the row and never reaches the state or the request.
 */
const ALL_PROVIDERS = '__all__';

/**
 * A paused `tinyflows` run's approval prompt (issue B3a) — id set by
 * `notify_pending_approval` in `crates/openhuman-core/src/flows/ops.rs`. Routed to
 * `FlowApprovalCard` instead of the generic `CoreNotificationCard`, which is
 * hardcoded to the meeting auto-join RPC.
 */
function isFlowApproval(item: { id: string }): boolean {
  return item.id.startsWith('flow-pending-approval:');
}

const NotificationCenter = () => {
  const { t } = useT();
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const {
    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);
  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.
  const [allProviders, setAllProviders] = useState<string[]>([]);
  const visibleItems = items.filter(
    n => n.status !== 'dismissed' && (!selectedProvider || n.provider === selectedProvider)
  );

  // Fetch on mount and when provider filter changes.
  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      dispatch(setIntegrationLoading(true));
      try {
        const result = await fetchNotifications({ provider: selectedProvider, limit: 100 });
        if (!cancelled) {
          dispatch(setIntegrationNotifications(result));
          // Accumulate providers only from unfiltered loads so the pill row
          // stays stable when a filter is active.
          if (!selectedProvider) {
            const seen = Array.from(new Set(result.items.map(n => n.provider))).sort();
            setAllProviders(seen);
          }
        }
      } catch (err) {
        if (!cancelled) {
          dispatch(
            setIntegrationError(err instanceof Error ? err.message : 'Failed to load notifications')
          );
        }
      }
    };
    void load();
    return () => {
      cancelled = true;
    };
  }, [dispatch, selectedProvider]);

  const handleMarkRead = async (id: string) => {
    dispatch(markIntegrationRead(id));
    try {
      await markNotificationRead(id);
    } catch {
      // Optimistic update already applied; log failure silently.
    }
  };

  /** Navigate to the resolved route for the notification and mark it as acted. */
  const handleNavigate = async (id: string) => {
    const n = items.find(i => i.id === id);
    if (!n) return;
    const route = resolveIntegrationRoute(n);
    dispatch(markIntegrationActed(id));
    navigate(route);
    try {
      await markNotificationActed(id);
    } catch {
      // Optimistic update already applied; failure is non-critical.
    }
  };

  const handleDismiss = async (id: string) => {
    dispatch(dismissIntegrationNotification(id));
    try {
      await dismissNotification(id);
    } catch {
      // Optimistic update applied; failure is silent.
    }
  };

  // Unread count scoped to the currently displayed (filtered) items.
  const filteredUnreadCount = visibleItems.filter(n => n.status === 'unread').length;

  const handleMarkAllRead = async () => {
    const unreadIds = visibleItems.filter(n => n.status === 'unread').map(n => n.id);
    for (const id of unreadIds) {
      dispatch(markIntegrationRead(id));
      try {
        await markNotificationRead(id);
      } catch {
        // Ignore individual failures.
      }
    }
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-line">
        <div className="flex items-center gap-2">
          <h2 className="text-base font-semibold text-content">
            {t('notifications.center.title')}
          </h2>
          {filteredUnreadCount > 0 && (
            <span className="px-1.5 py-0.5 rounded-full text-[11px] font-semibold bg-primary-500 text-content-inverted">
              {filteredUnreadCount}
            </span>
          )}
        </div>
        {filteredUnreadCount > 0 && (
          <Button
            variant="tertiary"
            size="xs"
            onClick={() => {
              void handleMarkAllRead();
            }}
            className="text-primary-600 hover:text-primary-700">
            {t('notifications.center.markAllRead')}
          </Button>
        )}
      </div>

      {/* Provider filter pills — the same `ChipTabs` grammar as the category
          row two levels up the page, which is visible on screen at the same
          time and used to be painted differently.

          `ALL_PROVIDERS` is a sentinel: `ChipTabs` is single-select over a
          non-optional value, while `selectedProvider` is `string | undefined`
          (undefined = unfiltered, and the value the fetch effect keys on).
          The one behaviour this drops is re-click-to-clear on the active
          provider chip; the explicit "All" chip still clears the filter. */}
      {allProviders.length > 1 && (
        <ChipTabs
          as="tab"
          ariaLabel={t('notifications.center.filterAll')}
          className="flex items-center gap-1.5 overflow-x-auto border-b border-line-subtle px-4 py-2"
          items={[
            { id: ALL_PROVIDERS, label: t('notifications.center.filterAll') },
            ...allProviders.map(p => ({ id: p, label: p })),
          ]}
          value={selectedProvider ?? ALL_PROVIDERS}
          onChange={id => setSelectedProvider(id === ALL_PROVIDERS ? undefined : id)}
        />
      )}

      {/* 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 => {
              if (isFlowApproval(item)) {
                return <FlowApprovalCard key={item.id} notification={item} />;
              }
              if (isGateApprovalNotification(item)) {
                return <GateApprovalCard key={item.id} notification={item} />;
              }
              return <CoreNotificationCard key={item.id} notification={item} />;
            })}
          </div>
        )}

        {loading && (
          <div className="flex items-center justify-center py-12 text-content-faint text-sm">
            {t('common.loading')}
          </div>
        )}

        {!loading && error && (
          <Alert variant="destructive" className="m-4">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        {!loading && !error && visibleItems.length === 0 && coreActionItems.length === 0 && (
          <div className="flex flex-col items-center justify-center py-16 text-content-faint">
            <svg
              className="w-10 h-10 mb-3 opacity-40"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={1.5}
                d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
              />
            </svg>
            <p className="text-sm font-medium">{t('notifications.center.empty')}</p>
            <p className="text-xs mt-1 opacity-70">{t('notifications.center.emptyHint')}</p>
          </div>
        )}

        {!loading && !error && visibleItems.length > 0 && (
          <div className="divide-y-0">
            {visibleItems.map(n => (
              <NotificationCard
                key={n.id}
                notification={n}
                onMarkRead={id => {
                  void handleMarkRead(id);
                }}
                onNavigate={id => {
                  void handleNavigate(id);
                }}
                onDismiss={id => {
                  void handleDismiss(id);
                }}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default NotificationCenter;