|
| 1 | +import { PropsWithChildren, useCallback, useEffect, useRef } from 'react'; |
| 2 | + |
| 3 | +import { DeploymentStatus } from '@/client'; |
| 4 | +import { useElectronApi } from '@/hooks/useElectronApi'; |
| 5 | +import { useReward } from '@/hooks/useReward'; |
| 6 | +import { useServices } from '@/hooks/useServices'; |
| 7 | + |
| 8 | +const Notifications = { |
| 9 | + AgentEarned: |
| 10 | + "Your agent earned its rewards! It's now idle and will resume working next epoch.", |
| 11 | +}; |
| 12 | + |
| 13 | +export const SystemNotificationTriggers = ({ children }: PropsWithChildren) => { |
| 14 | + const electronApi = useElectronApi(); |
| 15 | + const { serviceStatus } = useServices(); |
| 16 | + const { isEligibleForRewards } = useReward(); |
| 17 | + |
| 18 | + const prevIsEligibleForRewards = useRef<boolean>(); |
| 19 | + |
| 20 | + // Notify the user when the agent earns rewards |
| 21 | + const handleAgentEarned = useCallback(() => { |
| 22 | + if (!electronApi.showNotification) return; |
| 23 | + |
| 24 | + // ignore if agent is not running |
| 25 | + if (serviceStatus !== DeploymentStatus.DEPLOYED) return; |
| 26 | + // ignore if eligibility is not yet defined |
| 27 | + if (isEligibleForRewards === undefined) return; |
| 28 | + // ignore if agent was previously eligible and is still eligible |
| 29 | + if (prevIsEligibleForRewards.current && isEligibleForRewards) return; |
| 30 | + // ignore if eligibility has not changed |
| 31 | + if (prevIsEligibleForRewards.current === isEligibleForRewards) return; |
| 32 | + |
| 33 | + // show notification when agent becomes eligible for rewards |
| 34 | + // (and was not previously eligible) |
| 35 | + if (isEligibleForRewards && prevIsEligibleForRewards.current === false) { |
| 36 | + electronApi.showNotification(Notifications.AgentEarned); |
| 37 | + } |
| 38 | + |
| 39 | + prevIsEligibleForRewards.current = isEligibleForRewards; |
| 40 | + }, [electronApi, isEligibleForRewards, serviceStatus]); |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + if (!electronApi.showNotification) return; |
| 44 | + // Show notification when agent earns rewards |
| 45 | + handleAgentEarned(); |
| 46 | + }, [electronApi, handleAgentEarned, isEligibleForRewards, serviceStatus]); |
| 47 | + |
| 48 | + return children; |
| 49 | +}; |
0 commit comments