File size: 4,731 Bytes
c7fe97e
8800c81
 
 
 
42690cf
 
 
8800c81
 
 
 
 
42690cf
 
 
 
 
 
 
 
 
c7fe97e
 
42690cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7fe97e
42690cf
c7fe97e
42690cf
c7fe97e
8800c81
 
c7fe97e
 
 
8800c81
 
 
 
 
 
 
 
 
c7fe97e
 
 
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7fe97e
8800c81
 
c7fe97e
 
 
 
 
 
8800c81
c7fe97e
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
c7fe97e
 
8800c81
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import { useEffect, useRef } from 'react';
import type { PrincessDialogueEvent } from '../components/PrincessDialoguePopup';
import type { AuthUser } from '../firebaseClient';
import { getCompanionSettings, getRandomScriptedDialogue } from '../utils/companionService';
import { playBreakReminderTone } from '../utils/rpgAudio';
import { companionStore, useCompanionStore } from '../features/companion/store/useCompanionStore';
import { useOSStore } from '../stores/useOSStore';
import { shouldTriggerDialoguePopup } from '../features/companion/dialogueRouting';

export function useCompanionEvents(
  user: AuthUser | null,
  onOpenWindow: (windowId: string) => void
) {
  const isCompanionOpen = useOSStore(
    (s) => !!s.windows.companion?.isOpen && !s.windows.companion?.isMinimized
  );
  const companionState = useCompanionStore();
  const { transcript, companionSettings } = companionState;
  const lastTurnIdRef = useRef<string>(
    companionStore.getState().transcript.slice(-1)[0]?.id || ''
  );

  // Watch companion transcript for reactive events (review reactions, fatigue watchdog, landmarks)
  // When triggered, open/activate the unified companion dialogue box directly instead of showing a separate toast popup.
  useEffect(() => {
    const lastTurn = transcript[transcript.length - 1];
    const decision = shouldTriggerDialoguePopup({
      lastTurn,
      lastTurnId: lastTurnIdRef.current,
      isCompanionOpen,
      enabled: companionSettings.enabled,
      autoPopupEnabled: companionSettings.autoPopupEnabled,
    });

    if (decision.newLastTurnId !== lastTurnIdRef.current) {
      lastTurnIdRef.current = decision.newLastTurnId;
    }

    if (decision.shouldShow && decision.event) {
      onOpenWindow('companion');
    }
  }, [transcript, companionSettings.enabled, companionSettings.autoPopupEnabled, isCompanionOpen, onOpenWindow]);

  // Initial greeting on session start - prime proactive dialogue in transcript without separate toast
  useEffect(() => {
    if (user) {
      const settings = getCompanionSettings();
      if (settings.enabled) {
        companionStore.triggerProactiveGreeting();
      }
    }
  }, [user]);

  // Global companion event listener & pomodoro break reminder timer
  useEffect(() => {
    const handleCompanionEvent = (e: Event) => {
      const customEvent = e as CustomEvent<PrincessDialogueEvent>;
      if (customEvent.detail) {
        const newTurn = companionStore.addNotificationTurn({
          text: customEvent.detail.text,
          emotion: customEvent.detail.emotion,
          idPrefix: 'rev-custom',
        });
        lastTurnIdRef.current = newTurn.id;
        const settings = getCompanionSettings();
        if (settings.enabled && settings.autoPopupEnabled) {
          onOpenWindow('companion');
        }
      }
    };

    const handleAgentOpenWindow = (e: Event) => {
      const customEvent = e as CustomEvent<{ windowId: string }>;
      if (customEvent.detail?.windowId) {
        onOpenWindow(customEvent.detail.windowId);
      }
    };

    window.addEventListener('companion:dialogue', handleCompanionEvent);
    window.addEventListener('companion:open_window', handleAgentOpenWindow);

    let lastBreakTime = Date.now();
    const breakCheckInterval = setInterval(() => {
      const settings = getCompanionSettings();
      if (
        !settings.enabled ||
        !settings.autoPopupEnabled ||
        !settings.breakIntervalMinutes ||
        settings.breakIntervalMinutes <= 0
      ) {
        return;
      }

      const elapsedMinutes = (Date.now() - lastBreakTime) / (1000 * 60);
      if (elapsedMinutes >= settings.breakIntervalMinutes) {
        lastBreakTime = Date.now();
        playBreakReminderTone();
        const breakMsg = getRandomScriptedDialogue('break_reminder');
        const newTurn = companionStore.addNotificationTurn({
          text: breakMsg.text,
          emotion: breakMsg.emotion,
          idPrefix: 'fatigue-break',
          choiceSuggestions: [
            'Let us pause and rest by the fire.',
            'A short rest sounds wonderful.',
            'How is your strength holding up?',
          ],
        });
        lastTurnIdRef.current = newTurn.id;
        if (settings.autoPopupEnabled) {
          onOpenWindow('companion');
        }
      }
    }, 30000);

    return () => {
      window.removeEventListener('companion:dialogue', handleCompanionEvent);
      window.removeEventListener('companion:open_window', handleAgentOpenWindow);
      clearInterval(breakCheckInterval);
    };
  }, [onOpenWindow]);

  return {
    companionDialogueEvent: null as PrincessDialogueEvent | null,
    setCompanionDialogueEvent: (_event?: PrincessDialogueEvent | null) => {},
  };
}