Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

1.3 KB
Raw Blame
import { useLayoutEffect, useRef } from "react";
import { awaitingTurn } from "@/lib/turn-tail";
import type { Message } from "@/state/store";

/**
 * Whether the person's send is waiting for the turn it starts: from Enter until the bot is first seen busy, so the
 * status line shows with the bubble and stays through the gap between the send's reply (which carries the server's copy
 * and lands first) and the live frame that says the bot is busy. A send the server takes back, or any row after it,
 * ends the wait; so does seeing the bot busy, after which `busy` alone says whether the turn runs.
 */
export function useAwaitingTurn(threadId: string, lastMessage: Message | undefined, busy: boolean): boolean {
  const sent = useRef<{ threadId: string; sendId: string } | null>(null);
  const optimistic = awaitingTurn(lastMessage);
  const sendId = lastMessage?.role === "user" ? lastMessage.sendId : undefined;
  const waiting = optimistic || (!busy && sendId !== undefined && sent.current?.threadId === threadId && sent.current.sendId === sendId);
  useLayoutEffect(() => {
    if (optimistic && sendId) sent.current = { threadId, sendId };
    else if (busy || !sendId || sent.current?.threadId !== threadId || sent.current.sendId !== sendId) sent.current = null;
  }, [optimistic, sendId, busy, threadId]);
  return waiting && !busy;
}