import { useCallback } from "react";
import { completeOpenStreamingMessagesInTranscript } from "./agentSessionState";
import { cancelAgentSessionRun, markStaleRunningLoadSuppressed, } from "./useAgentSessionSync";
export function useAgentStopCommand(input) {
    const { readOnly, agentId, armStopGuard, setIsWaitingForResponse, isWaitingRef, setIsConnecting, setIsSubmitting, setAgent, shouldCreateNewMessage, setIsAgentThinking, messagesRef, sessionActions, } = input;
    return useCallback(async () => {
        if (readOnly) {
            console.warn("[AgentTerminal] handleStop blocked: read-only access");
            return;
        }
        try {
            markStaleRunningLoadSuppressed(agentId);
            armStopGuard();
            sessionActions.armStopGuard();
            setIsWaitingForResponse(false);
            isWaitingRef.current = false;
            setIsConnecting(false);
            setIsSubmitting(false);
            setAgent((prev) => prev ? { ...prev, status: "idle", statusMessage: undefined } : prev);
            shouldCreateNewMessage.current = false;
            setIsAgentThinking(false);
            sessionActions.replaceQueuedPrompts([]);
            messagesRef.current = completeOpenStreamingMessagesInTranscript(messagesRef.current);
            sessionActions.completeOpenStreamingMessages();
            if (agentId) {
                try {
                    const cancelResult = await cancelAgentSessionRun(agentId);
                    if (cancelResult?.success !== false) {
                        markStaleRunningLoadSuppressed(agentId);
                    }
                }
                catch (err) {
                    console.error("Failed to cancel agent on backend:", err);
                }
            }
        }
        catch (e) {
            console.error("Failed to stop agent execution", e);
        }
    }, [
        agentId,
        armStopGuard,
        isWaitingRef,
        messagesRef,
        readOnly,
        sessionActions,
        setAgent,
        setIsAgentThinking,
        setIsConnecting,
        setIsSubmitting,
        setIsWaitingForResponse,
        shouldCreateNewMessage,
    ]);
}
//# sourceMappingURL=useAgentStopCommand.js.map