Skip to content

The platform for continuously improving AI agents.

2.8 KB
Raw Blame
import { useEffect, useState } from "react";

import api from "@/client";
import { whilePageVisible } from "@/lib/visible-stream";
import { type WorkshopMessage, WorkshopMessageFromJSON } from "@/openapi";

type ExperimentConversation = {
  connected: boolean;
  messages: WorkshopMessage[] | null;
  // Changes when a run or a stage of the experiment changes state.
  record: string | null;
};

const EMPTY: ExperimentConversation = { connected: false, messages: null, record: null };

export function useExperimentConversation(experiment: string): ExperimentConversation {
  const [state, setState] = useState<ExperimentConversation>(EMPTY);
  useEffect(() => {
    setState(EMPTY);
    return whilePageVisible(() => {
      const controller = new AbortController();
      let timer: ReturnType<typeof setTimeout>;
      const connect = async () => {
        try {
          const response = await api.researchExperiments.researchExperimentsEventsRetrieveRaw(
            { id: experiment },
            { signal: controller.signal }
          );
          if (controller.signal.aborted) return;
          const reader = response.raw.body?.getReader();
          if (!reader) throw new Error("The conversation stream is unavailable.");
          setState((current) => ({ ...current, connected: true }));
          const decoder = new TextDecoder();
          let buffer = "";
          while (!controller.signal.aborted) {
            const { done, value } = await reader.read();
            if (done || controller.signal.aborted) break;
            buffer += decoder.decode(value, { stream: true });
            const frames = buffer.split("\n\n");
            buffer = frames.pop() ?? "";
            for (const frame of frames) {
              const data = frame
                .split("\n")
                .filter((line) => line.startsWith("data: "))
                .map((line) => line.slice(6))
                .join("\n");
              if (!data) continue;
              const batch = JSON.parse(data) as { messages: unknown[]; record: string };
              setState({
                connected: true,
                messages: batch.messages.map(WorkshopMessageFromJSON),
                record: batch.record,
              });
            }
          }
        } catch {
          // Polling supplies the conversation while the stream reconnects.
        } finally {
          if (!controller.signal.aborted) {
            setState((current) => ({ ...current, connected: false, messages: null }));
            timer = setTimeout(connect, 1000);
          }
        }
      };
      void connect();
      return () => {
        controller.abort();
        clearTimeout(timer);
        setState((current) => ({ ...current, connected: false, messages: null }));
      };
    });
  }, [experiment]);
  return state;
}