All files / packages/agent-client/src useAgentConversation.ts

100% Statements 80/80
100% Branches 35/35
100% Functions 15/15
100% Lines 71/71

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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171                                                                128x 128x 128x 128x 128x 128x 128x   128x 30x 28x 28x 28x     128x 36x   5x 6x       5x   3x 5x 4x     3x   3x 3x   11x 11x   4x     4x 2x   4x   3x 3x       7x       128x   32x 32x   30x 30x 30x 30x   30x 30x 30x   2x   30x           128x 5x 5x 5x   4x 4x 4x 2x                 2x       128x 4x 4x 4x   3x 3x 3x 1x         2x       128x 2x 2x 2x 2x 2x 2x 2x     128x                          
import { useCallback, useRef, useState } from "react";
 
import type { AgentEvent, AgentSharedState, PendingAction, Suggestion } from "./events";
import type { AgentTransport, ImageAttachment } from "./transport";
 
export type ChatMessage = {
  id: string;
  role: "user" | "assistant" | "system";
  text: string;
};
 
export type UseAgentConversation = {
  messages: ChatMessage[];
  suggestions: Suggestion[];
  pendingAction: PendingAction | null;
  /** Last STATE_SNAPSHOT from the agent — null until the first turn ends. */
  sharedState: AgentSharedState | null;
  isStreaming: boolean;
  error: string | null;
  send: (text: string, images?: ImageAttachment[]) => Promise<void>;
  confirm: () => Promise<void>;
  cancel: () => Promise<void>;
  reset: () => void;
};
 
/**
 * Folds the normalized `AgentEvent` stream into chat state. Transport-agnostic:
 * it is handed an `AgentTransport` and never imports a concrete transport or
 * any SDK. Swap SSE → CopilotKit by passing a different transport — this hook
 * and every screen using it are unchanged.
 */
export function useAgentConversation(transport: AgentTransport): UseAgentConversation {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
  const [pendingAction, setPendingAction] = useState<PendingAction | null>(null);
  const [sharedState, setSharedState] = useState<AgentSharedState | null>(null);
  const [isStreaming, setIsStreaming] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const threadIdRef = useRef<string | null>(null);
 
  const ensureThread = useCallback(async (): Promise<string> => {
    if (threadIdRef.current) return threadIdRef.current;
    const thread = await transport.createThread();
    threadIdRef.current = thread.id;
    return thread.id;
  }, [transport]);
 
  const applyEvent = useCallback((event: AgentEvent): void => {
    switch (event._tag) {
      case "TextStart":
        setMessages((prev) =>
          prev.some((m) => m.id === event.messageId)
            ? prev
            : [...prev, { id: event.messageId, role: "assistant", text: "" }],
        );
        break;
      case "TextDelta":
        setMessages((prev) =>
          prev.some((m) => m.id === event.messageId)
            ? prev.map((m) => (m.id === event.messageId ? { ...m, text: m.text + event.delta } : m))
            : [...prev, { id: event.messageId, role: "assistant", text: event.delta }],
        );
        break;
      case "Blocks":
        setSuggestions(event.suggestions);
        break;
      case "PendingAction":
        setPendingAction(event.pending);
        break;
      case "SharedState":
        setSharedState(event.state);
        // The snapshot is authoritative for pending state: an explicit null
        // clears a stale card that a missed decision would otherwise leave up.
        if (event.state.pendingAction === null) {
          setPendingAction(null);
        }
        break;
      case "RunError":
        setError(event.message);
        break;
      default:
        // RunStarted / ToolCall* / ToolResult / Metadata / TextEnd / RunFinished
        // carry no chat-visible state in this v1.
        break;
    }
  }, []);
 
  const send = useCallback(
    async (text: string, images?: ImageAttachment[]): Promise<void> => {
      const trimmed = text.trim();
      if (!trimmed || isStreaming) return;
 
      setError(null);
      setSuggestions([]);
      setMessages((prev) => [...prev, { id: `u-${Date.now()}`, role: "user", text: trimmed }]);
      setIsStreaming(true);
 
      try {
        const threadId = await ensureThread();
        await transport.streamTurn({ threadId, message: trimmed, images }, { onEvent: applyEvent });
      } catch (e) {
        setError(e instanceof Error ? e.message : "Something went wrong.");
      } finally {
        setIsStreaming(false);
      }
    },
    [transport, ensureThread, applyEvent, isStreaming],
  );
 
  const confirm = useCallback(async (): Promise<void> => {
    const pending = pendingAction;
    const threadId = threadIdRef.current;
    if (!pending || !threadId) return;
 
    setPendingAction(null);
    try {
      const result = await transport.confirm(threadId, pending.pendingActionId);
      setMessages((prev) => [
        ...prev,
        {
          id: `s-${Date.now()}`,
          role: "system",
          text: `✓ Action ${result.status}.`,
        },
      ]);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Confirm failed.");
    }
  }, [transport, pendingAction]);
 
  const cancel = useCallback(async (): Promise<void> => {
    const pending = pendingAction;
    const threadId = threadIdRef.current;
    if (!pending || !threadId) return;
 
    setPendingAction(null);
    try {
      await transport.cancel(threadId, pending.pendingActionId);
      setMessages((prev) => [
        ...prev,
        { id: `s-${Date.now()}`, role: "system", text: "Action cancelled." },
      ]);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Cancel failed.");
    }
  }, [transport, pendingAction]);
 
  const reset = useCallback((): void => {
    threadIdRef.current = null;
    setMessages([]);
    setSuggestions([]);
    setPendingAction(null);
    setSharedState(null);
    setError(null);
    setIsStreaming(false);
  }, []);
 
  return {
    messages,
    suggestions,
    pendingAction,
    sharedState,
    isStreaming,
    error,
    send,
    confirm,
    cancel,
    reset,
  };
}