All files / src/hooks useRunningTurns.ts

100% Statements 20/20
87.5% Branches 14/16
100% Functions 6/6
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            12x     12x       12x   223x                                               222x 222x     71x     489x     222x 222x 222x 222x 110x 5x   110x 2x   110x     222x    
import type { RunningTurn } from "@/objects/Turn";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useRef } from "react";
 
const NONE: RunningTurn[] = [];
 
/** How often a page with a turn still running asks whether it has ended. */
export const RUNNING_TURNS_POLL_MS = 3000;
 
/** Read on every poll, so a page test can keep a poll from landing in the
 *  middle of it (an update React reports as outside `act`). */
export const runningTurnsPolling = { intervalMs: RUNNING_TURNS_POLL_MS };
 
export const runningTurnsKey = (target: RunningTurnsTarget) => [
  QUERY_KEYS.GET.RUNNING_TURNS,
  target.agentId ?? null,
  target.modelId ?? null,
];
 
export interface RunningTurnsTarget {
  agentId?: string;
  modelId?: string;
}
 
/**
 * The person's turns still running with an agent or a model (svc-core
 * `GET /app/turns`). A turn runs to its end and is stored whether or not
 * anyone is on the page, so a chat page opened while one runs shows it.
 *
 * Polled while there are any. svc-core lists a turn until it is stored, so
 * `onFinished` is called for each one that disappears: the conversation now
 * holds its answer.
 */
export function useRunningTurns(
  target: RunningTurnsTarget,
  onFinished: (turn: RunningTurn) => void,
): RunningTurn[] {
  const { getApiHandler } = useApiHandler();
  const { data } = useQuery<RunningTurn[]>({
    queryKey: runningTurnsKey(target),
    queryFn: async () =>
      (await getApiHandler().turn_router.list(target)) ?? [],
    enabled: !!(target.agentId || target.modelId),
    refetchInterval: (query) =>
      query.state.data?.length ? runningTurnsPolling.intervalMs : false,
  });
 
  const finished = useRef(onFinished);
  finished.current = onFinished;
  const seen = useRef<Map<string, RunningTurn>>(new Map());
  useEffect(() => {
    const now = new Map<string, RunningTurn>(
      (data ?? NONE).map((turn: RunningTurn) => [turn.id, turn]),
    );
    for (const [id, turn] of seen.current) {
      Eif (!now.has(id)) finished.current(turn);
    }
    seen.current = now;
  }, [data]);
 
  return data ?? NONE;
}