import { useEffect, useRef } from "react";
import { subscribeAgentSessionStream } from "./useAgentSessionSync";
export function useAgentStreamSubscription(input) {
    const { effectiveIsVisible, editContext, agentStubId, agent, onMessage, subscribedAgentIdRef, seenMessageIdsRef, lastSeqRef, setIsWaitingForResponse, isWaitingRef, shouldCreateNewMessage, setIsAgentThinking, } = input;
    const addSocketMessageListener = editContext?.addSocketMessageListener;
    const agentRef = useRef(agent);
    const onMessageRef = useRef(onMessage);
    useEffect(() => {
        agentRef.current = agent;
    }, [agent]);
    useEffect(() => {
        onMessageRef.current = onMessage;
    }, [onMessage]);
    useEffect(() => {
        if (!effectiveIsVisible || !addSocketMessageListener) {
            subscribedAgentIdRef.current = null;
            return;
        }
        const stableHandler = (message) => {
            onMessageRef.current(message);
        };
        const unsubscribe = subscribeAgentSessionStream({
            agentId: agentStubId,
            addSocketMessageListener,
            onMessage: stableHandler,
        });
        subscribedAgentIdRef.current = agentStubId;
        seenMessageIdsRef.current.clear();
        lastSeqRef.current = 0;
        const currentAgent = agentRef.current;
        if (currentAgent) {
            const isRunning = currentAgent.status === "running" || currentAgent.status === 1;
            const isWaitingForApproval = currentAgent.status === "waitingForApproval" ||
                currentAgent.status === 2;
            const isWaitingForInput = currentAgent.status === "waitingForInput";
            if (isRunning) {
                setIsWaitingForResponse(true);
                isWaitingRef.current = true;
                shouldCreateNewMessage.current = false;
                setIsAgentThinking(true);
            }
            else if (isWaitingForApproval || isWaitingForInput) {
                setIsWaitingForResponse(false);
                isWaitingRef.current = false;
                setIsAgentThinking(false);
            }
            else {
                setIsWaitingForResponse(false);
                isWaitingRef.current = false;
                setIsAgentThinking(false);
            }
        }
        return () => {
            unsubscribe();
            subscribedAgentIdRef.current = null;
        };
    }, [
        addSocketMessageListener,
        agentStubId,
        effectiveIsVisible,
        isWaitingRef,
        lastSeqRef,
        seenMessageIdsRef,
        setIsAgentThinking,
        setIsWaitingForResponse,
        shouldCreateNewMessage,
        subscribedAgentIdRef,
    ]);
}
//# sourceMappingURL=useAgentStreamSubscription.js.map