import { jsx as d, jsxs as F, Fragment as de } from "react/jsx-runtime";
import { useStreamContext as pe } from "../providers/Stream.es.js";
import { useCustomComponents as fe } from "../providers/CustomComponentProvider.es.js";
import { logger as ge } from "../utils/logger.es.js";
import { isAiWithToolCalls as W, isToolMessage as k } from "../utils/utils.es.js";
import J, { useState as he, useMemo as x, useRef as A, useCallback as g, useEffect as T, useLayoutEffect as me } from "react";
import ye from "./messages/AgentMessage.es.js";
import ve from "./messages/CustomComponentRender.es.js";
import Me from "./messages/HumanMessage.es.js";
import Q from "./Thinking.es.js";
function je({ setIsFirstMessage: R, enableToolCallIndicator: _ = !0, chatBodyProps: j }) {
  const a = pe(), { interruptComponents: X } = fe(), N = a.messages, u = a.isLoading, [B, Z] = he({});
  ge.debug("ChatBody render - messages count:", N, "isLoading:", u);
  const c = x(() => N ?? [], [N]), q = x(() => {
    const e = /* @__PURE__ */ new Set(), n = a.values?.ui;
    if (!Array.isArray(n)) return e;
    for (const o of n) {
      const r = o, i = r.metadata && typeof r.metadata == "object" ? r.metadata : void 0, h = [
        typeof r.id == "string" ? r.id : void 0,
        typeof i?.id == "string" ? i.id : void 0,
        typeof i?.message_id == "string" ? i.message_id : void 0
      ];
      for (const p of h)
        p && e.add(p);
    }
    return e;
  }, [a.values?.ui]), y = A(null), K = A(0), C = A(!0), z = A(/* @__PURE__ */ new Map()), L = g((e) => Array.isArray(e) ? e.map((n, o) => {
    if (!n || typeof n != "object") return null;
    const r = n, i = r.status;
    return typeof r.content != "string" || i !== "pending" && i !== "in_progress" && i !== "completed" ? null : {
      id: r.id && typeof r.id == "string" ? r.id : `todo-${o}`,
      content: r.content,
      status: i,
      updatedAt: r.updatedAt instanceof Date || typeof r.updatedAt == "string" || typeof r.updatedAt == "number" ? r.updatedAt : void 0,
      run_id: typeof r.run_id == "string" ? r.run_id : void 0,
      runId: typeof r.runId == "string" ? r.runId : void 0,
      messageId: typeof r.messageId == "string" ? r.messageId : void 0,
      checkpoint: typeof r.checkpoint == "string" ? r.checkpoint : void 0
    };
  }).filter((n) => n !== null) : [], []), O = g((e, n) => {
    Z((o) => ({
      ...o,
      [e]: n
    }));
  }, []), D = g(async (e) => {
    if (!e) {
      console.error("No parent checkpoint available for regeneration");
      return;
    }
    await a.submit(void 0, {
      checkpoint: e,
      streamMode: ["values"],
      streamSubgraphs: !0,
      streamResumable: !0
    });
  }, [a]), G = g((e) => {
    a.setBranch(e);
  }, [a]), b = g((e) => {
    a.submit(null, {
      command: { resume: e },
      streamMode: ["values", "messages-tuple", "updates", "custom"],
      streamSubgraphs: !0
    });
  }, [a]), $ = x(() => {
    const e = a.interrupt;
    if (!e) return null;
    const o = e.value?.actionRequests ?? [];
    return {
      approve: () => {
        b({
          decisions: o.map(() => ({ type: "approve" }))
        });
      },
      reject: (r) => {
        b({
          decisions: o.map(() => ({
            type: "reject",
            message: r || void 0
          }))
        });
      },
      edit: (r) => {
        const i = o[0];
        b({
          decisions: [
            {
              type: "edit",
              editedAction: {
                name: i?.name ?? "",
                args: { ...i?.args, ...r }
              }
            }
          ]
        });
      }
    };
  }, [a.interrupt, b]), f = g(() => {
    if (y.current) {
      let e = y.current.parentElement;
      for (; e; ) {
        const n = window.getComputedStyle(e);
        if (n.overflowY === "auto" || n.overflowY === "scroll")
          return e;
        e = e.parentElement;
      }
    }
    return null;
  }, []);
  T(() => {
    c.length > 0 && R && R(!1);
  }, [c.length, R]);
  const U = g((e, n, o) => {
    const r = u && n === o.length - 1 && e.type === "ai";
    if (!e.content.length && !W(e) && !r || e.additional_kwargs?.hidden)
      return null;
    const i = e.id ?? `msg-${n}`, h = (t) => typeof t.id == "string" && q.has(t.id);
    if (e.type === "human")
      return /* @__PURE__ */ d(Me, { message: e, fontSize: j?.fontSize }, i);
    if (k(e))
      return null;
    if (e.type === "ai" && n > 0) {
      let t = n - 1;
      for (; t >= 0 && k(o[t]); )
        t--;
      if (t >= 0 && o[t].type === "ai" && !h(e))
        return null;
    }
    const p = [e];
    let v = n + 1;
    for (; v < o.length; ) {
      const t = o[v];
      if (k(t))
        p.push(t), v++;
      else if (t.type === "ai") {
        if (h(t))
          break;
        p.push(t), v++;
      } else
        break;
    }
    const l = p.filter((t) => t.type === "ai"), H = l.some((t) => Array.isArray(t.content)), m = /* @__PURE__ */ new Set(), S = H ? l.flatMap((t) => Array.isArray(t.content) ? t.content.filter((s) => {
      if (s.type === "text" && typeof s.text == "string") {
        if (m.has(s.text)) return !1;
        m.add(s.text);
      }
      return !0;
    }) : typeof t.content == "string" && t.content.length > 0 ? m.has(t.content) ? [] : (m.add(t.content), [{ type: "text", text: t.content }]) : []) : (() => {
      const t = [];
      for (const s of l) {
        const M = typeof s.content == "string" ? s.content : "";
        M && !m.has(M) && (m.add(M), t.push(M));
      }
      return t.join(`

`);
    })(), ee = H ? S.map((t) => t.type === "text" ? t.text : "").filter(Boolean).join(" ") : S, te = {
      ...e,
      content: S
    }, Y = e ? a.getMessagesMetadata(e) : void 0, ne = H ? S.some(
      (t) => t.type === "thinking" && t.thinking?.length > 0 || t.type === "reasoning" && t.reasoning?.length > 0
    ) : !1, re = l.some((t) => {
      const s = t.additional_kwargs;
      return typeof s?.reasoning_content == "string" && s.reasoning_content.length > 0;
    }), oe = l.some((t) => {
      const s = t.additional_kwargs;
      return Array.isArray(s?.tool_status) && s.tool_status.length > 0;
    }), se = p.some((t) => k(t)), ae = _ && (l.some((t) => W(t)) || oe || se), V = !!ee || ne || re || ae, ie = v >= o.length, w = u && ie, I = l.map((t) => t.id).filter((t) => typeof t == "string" && t.length > 0).join("|") || i, ce = (() => {
      const t = z.current.get(I);
      if (!w && t && t.length > 0)
        return t;
      if (w) {
        const s = L(a.values?.todos);
        if (s.length > 0)
          return z.current.set(I, s), s;
      }
      for (let s = l.length - 1; s >= 0; s--) {
        const le = a.getMessagesMetadata(l[s])?.firstSeenState?.values, E = L(le?.todos);
        if (E.length > 0)
          return (!t || t.length === 0) && z.current.set(I, E), t ?? E;
      }
      return t && t.length > 0 ? t : [];
    })(), ue = w && !V;
    return /* @__PURE__ */ F(J.Fragment, { children: [
      ue && /* @__PURE__ */ d(Q, {}),
      V && /* @__PURE__ */ d(
        ye,
        {
          agentName: j?.agentName,
          fontSize: j?.fontSize,
          message: te,
          groupedMessages: p,
          showToolActivity: _,
          isStreaming: w,
          onRegenerate: D,
          feedback: e.id ? B[e.id] : void 0,
          onFeedback: O,
          branch: Y?.branch,
          branchOptions: Y?.branchOptions,
          onBranchSelect: G,
          todos: ce
        }
      ),
      l.map((t) => /* @__PURE__ */ d(ve, { message: t, thread: a }, t.id))
    ] }, i);
  }, [u, a, L, _, D, B, O, G, q]), P = x(() => c.map((e, n) => {
    const o = U(e, n, c);
    return o && !o.key ? J.cloneElement(o, { key: e.id ?? `msg-${n}` }) : o;
  }), [c, U]);
  return T(() => {
    const e = f();
    if (!e) return;
    const n = () => {
      const { scrollTop: o, scrollHeight: r, clientHeight: i } = e, h = r - o - i;
      C.current = h < 100;
    };
    return e.addEventListener("scroll", n), () => e.removeEventListener("scroll", n);
  }, [f]), T(() => {
    const e = f();
    if (!e) return;
    const n = c.length;
    n > K.current && (e.scrollTop = e.scrollHeight, C.current = !0), K.current = n;
  }, [c, f]), T(() => {
    const e = f();
    if (!e || !u) return;
    const n = new MutationObserver(() => {
      C.current && e && (e.scrollTop = e.scrollHeight);
    });
    return y.current && n.observe(y.current, {
      childList: !0,
      subtree: !0,
      characterData: !0
    }), () => n.disconnect();
  }, [u, f]), me(() => {
    const e = f();
    u && C.current && e && (e.scrollTop = e.scrollHeight);
  }), /* @__PURE__ */ d(
    "div",
    {
      ref: y,
      className: "flex flex-col gap-4 rounded-4xl p-2",
      children: c.length === 0 ? /* @__PURE__ */ d("div", { className: "flex items-center justify-center h-full text-zinc-500", children: u ? /* @__PURE__ */ F("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ d("div", { className: "animate-spin h-5 w-5 border-2 border-zinc-500 border-t-transparent rounded-full" }),
        /* @__PURE__ */ d("span", { children: "Loading conversation..." })
      ] }) : "Start a conversation..." }) : /* @__PURE__ */ F(de, { children: [
        P,
        u && c.length > 0 && c[c.length - 1].type === "human" && /* @__PURE__ */ d(Q, {}),
        !u && a.interrupt && $ && (() => {
          const e = a.interrupt.value, n = e?.actionRequests?.[0]?.name, o = n ? X[n] : void 0;
          return o ? /* @__PURE__ */ d(o, { interrupt: e, actions: $ }) : null;
        })()
      ] })
    }
  );
}
export {
  je as default
};
//# sourceMappingURL=ChatBody.es.js.map
