Skip to content

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

2.4 KB
Raw Blame
import { optimisticMessageId } from "@/state/optimistic-send";
import type { Message } from "@/state/store";

/** Whether the mascot and its status line show under the transcript. They stay for the whole turn: a bot's text in the
 * middle of a turn ("Now I'll build the dashboard") is not its end, and the engine may then spend minutes writing a
 * file before its next step shows. A turn ends across three frames (reply, turn.completed, busy off), so a settled
 * reply at the tail hides them only once the turn has ended; no timer ever does. */
export function showWorkingDots(
  busy: boolean | undefined,
  lastMessage: Message | undefined,
  speakerBotId?: string,
  turnEnded = false,
): boolean {
  if (!busy) return false;
  if (!lastMessage) return true;
  const settledReply = lastMessage.role === "bot" && lastMessage.kind === "text";
  if (!settledReply) return true;
  if (speakerBotId !== undefined && lastMessage.from?.botId !== speakerBotId) return true;
  return !turnEnded;
}

/** Whether the newest row is the person's send the server has not yet taken: its optimistic stand-in. A send it refuses
 * is taken back. (hooks/use-awaiting-turn carries the wait on to the frame that says the bot is busy.) */
export function awaitingTurn(lastMessage: Message | undefined): boolean {
  return lastMessage?.role === "user" && lastMessage.sendId !== undefined && lastMessage.id === optimisticMessageId(lastMessage.sendId);
}

export function awaitedMemberId(
  working: boolean | undefined,
  speakerBotId: string | null | undefined,
  lastMessage: Message | undefined,
): string | undefined {
  if (!working || speakerBotId) return undefined;
  if (lastMessage?.kind !== "activity" || !lastMessage.tool || lastMessage.tool.ok !== undefined) return undefined;
  return lastMessage.from?.botId;
}

/** The reply Regenerate sits on: this bot's last text answer. A tagged teammate's answer in the chat is not this
 * bot's reply, so it is skipped, but never past the person's line it answered: that request then has no reply of its own. */
export function regenerateTarget(messages: readonly Message[], botId: string): string | undefined {
  let skippedTeammate = false;
  for (let i = messages.length - 1; i >= 0; i--) {
    const m = messages[i]!;
    if (skippedTeammate && m.role === "user") return undefined;
    if (m.role !== "bot" || m.kind !== "text") continue;
    if (!m.from || m.from.botId === botId) return m.id;
    skippedTeammate = true;
  }
  return undefined;
}