iterate.com / ui

git clone https://git.iterate.com/repos/ui

ui / src / agent-kind-view / below.tsmain at d68d7e1

// below.ts — THE AGENTS BELOW AN AGENT THAT WORK NOW, for the view of that agent.
//
// Jonas, 28 Nov 2026, in the Dash on a phone, of a thread's line under a message: "Why does it
// say 'iterate is working on a reply' and not some kind" (of status of what the thread's agent
// does). A thread is an agent below the conversation (`<conversation>/t/<offset>`), and what it
// does now is on its own log, which the conversation's view does not hold. The page holds the
// row of every agent already (the list's). So the page hands the view the rows below its own
// path that are at work, by the rule that the list uses (`agentAtWork`), and no other row: a
// conversation can have some thousand agents below it, and a frame is told at each change.

import { useEffect, useMemo, useState } from "react";
import { agentAtWork } from "iterate/agents/at-work";

/** What the page says of one agent at work: its row's own words. */
export type AtWork = { status: string; activity?: string; lastActivityAt?: string };
export type AtWorkBelow = Readonly<Record<string, AtWork>>;

type Row = {
  path: string;
  status: "working" | "idle" | "waiting" | "ended" | null;
  activity: string | null;
  lastActivityAt: string | null;
};

const NONE: AtWorkBelow = Object.freeze({});
/** A row at work with no news falls out by the clock: the page looks again this often. */
const LOOK_AGAIN_MS = 30_000;

/** The rows below `path` that are at work at `now`, by path. */
export function atWorkBelowOf(
  rows: readonly Row[] | undefined,
  path: string,
  now: number,
): AtWorkBelow {
  const under = `${path.replace(/\/+$/, "")}/`;
  const found: Record<string, AtWork> = {};
  for (const row of rows || []) {
    if (!row.path.startsWith(under) || !row.status || !agentAtWork(row, now)) continue;
    found[row.path] = {
      status: row.status,
      ...(row.activity ? { activity: row.activity } : {}),
      ...(row.lastActivityAt ? { lastActivityAt: row.lastActivityAt } : {}),
    };
  }
  return Object.keys(found).length ? found : NONE;
}

/** The same object while nothing changed, so the frame is told once. */
export function useAtWorkBelow(rows: readonly Row[] | undefined, path: string): AtWorkBelow {
  const [now, setNow] = useState(() => Date.now());
  const found = useMemo(() => atWorkBelowOf(rows, path, now), [rows, path, now]);
  const any = found !== NONE;
  useEffect(() => {
    // a new list is a new look at the clock; while a row is at work, so is each half minute
    setNow(Date.now());
    if (!any) return;
    const timer = setInterval(() => setNow(Date.now()), LOOK_AGAIN_MS);
    return () => clearInterval(timer);
  }, [rows, any]);
  const signature = JSON.stringify(found);
  // oxlint-disable-next-line react-hooks/exhaustive-deps -- `found` changes only with its text
  return useMemo(() => found, [signature]);
}