| 20 | * - Followup question changing/disappearing |
| 21 | */ |
| 22 | export function useFollowupCountdown({ pendingAsk, onAutoSubmit }: UseFollowupCountdownOptions) { |
| 23 | const { showCustomInput, countdownSeconds, setCountdownSeconds } = useUIStateStore() |
| 24 | const countdownIntervalRef = useRef<NodeJS.Timeout | null>(null) |
| 25 | |
| 26 | // Use ref for onAutoSubmit to avoid stale closure issues without needing it in dependencies |
| 27 | const onAutoSubmitRef = useRef(onAutoSubmit) |
| 28 | useEffect(() => { |
| 29 | onAutoSubmitRef.current = onAutoSubmit |
| 30 | }, [onAutoSubmit]) |
| 31 | |
| 32 | // Cleanup interval on unmount |
| 33 | useEffect(() => { |
| 34 | return () => { |
| 35 | if (countdownIntervalRef.current) { |
| 36 | clearInterval(countdownIntervalRef.current) |
| 37 | } |
| 38 | } |
| 39 | }, []) |
| 40 | |
| 41 | // Start countdown when a followup question with suggestions appears |
| 42 | useEffect(() => { |
| 43 | // Clear any existing countdown |
| 44 | if (countdownIntervalRef.current) { |
| 45 | clearInterval(countdownIntervalRef.current) |
| 46 | countdownIntervalRef.current = null |
| 47 | } |
| 48 | |
| 49 | // Only start countdown for followup questions with suggestions (not custom input mode) |
| 50 | if ( |
| 51 | pendingAsk?.type === "followup" && |
| 52 | pendingAsk.suggestions && |
| 53 | pendingAsk.suggestions.length > 0 && |
| 54 | !showCustomInput |
| 55 | ) { |
| 56 | // Start countdown |
| 57 | setCountdownSeconds(FOLLOWUP_TIMEOUT_SECONDS) |
| 58 | |
| 59 | countdownIntervalRef.current = setInterval(() => { |
| 60 | const currentSeconds = useUIStateStore.getState().countdownSeconds |
| 61 | if (currentSeconds === null || currentSeconds <= 1) { |
| 62 | // Time's up! Auto-select first option |
| 63 | if (countdownIntervalRef.current) { |
| 64 | clearInterval(countdownIntervalRef.current) |
| 65 | countdownIntervalRef.current = null |
| 66 | } |
| 67 | setCountdownSeconds(null) |
| 68 | // Auto-submit the first suggestion |
| 69 | if (pendingAsk?.suggestions && pendingAsk.suggestions.length > 0) { |
| 70 | const firstSuggestion = pendingAsk.suggestions[0] |
| 71 | if (firstSuggestion) { |
| 72 | onAutoSubmitRef.current(firstSuggestion.answer) |
| 73 | } |
| 74 | } |
| 75 | } else { |
| 76 | setCountdownSeconds(currentSeconds - 1) |
| 77 | } |
| 78 | }, 1000) |
| 79 | } else { |