Skip to main content

useAgentContext

The useAgentContext hook provides a comprehensive interface for establishing and managing real-time chat interactions with AI agents. It abstracts the complexities of Server-Sent Events (SSE) streaming, handles connection resilience automatically, and processes file and image attachments.

Hook Interface

messages
ConversationMessage[]
An array of conversational messages detailing the interaction history between the user and the agent.
quickQuestions
string[]
A list of suggested follow-up queries generated by the agent based on the context of the current conversation.
pendingMessage
string | null
The content of a message currently being streamed by the agent, facilitating real-time rendering.
pendingFiles
File[] | null
Files staged by the client for processing that have not yet fully resolved.
connectionState
ConnectionState
The underlying transport status of the SSE stream (e.g., connecting, open, closed).
isConnected
boolean
A state indicator confirming whether the real-time SSE stream is actively connected and returning health checks.
isExecuting
boolean
A state indicator confirming whether the agent is currently processing a query, invoking backend tools, or generating a response text.
executionStatus
FrontendStatus
Detailed diagnostic information regarding the agent’s current background execution phase.
isWaitingForInput
boolean
Indicates whether the agent has temporarily paused its execution thread to request explicit input parameters from the user.
hasMoreMessages
boolean
Indicates whether historical messages are available to be loaded via pagination from the backend store.
isLoadingMore
boolean
A state indicator confirming whether pagination requests for historical messages are currently resolving.

Methods

sendMessage
(message: string, attachments?: MessageAttachment[], files?: File[]) => Promise<void>
submitUserInput
(input: string) => Promise<void>
clearMessages
() => void
loadMoreMessages
() => Promise<void>
cancelExecution
() => Promise<void>
connect
() => void
disconnect
() => void

Configuration Parameters

You must configure the hook by supplying the relevant context and agent identifiers:
contextId
string
required
The unique identifier for the specific conversation thread.
agentName
string
required
The designated name of the target agent context to mount onto the stream.
platformAdapter
object
An optional network adapter for intercepting and handling custom platform events triggered during the SSE stream.
onUserInputRequest

Data Structures

Implementation Guidelines

Establishing a Conversational Interface

To implement a standard messaging infrastructure, monitor the isConnected state alongside mapping through the resolved messages array:
import { useAgentContext } from "@wacht/tanstack-router";

export function ChatInterface() {
  const { messages, pendingMessage, sendMessage, isConnected } = useAgentContext({
    contextId: "ctx_123",
    agentName: "support_bot",
  });

  return (
    <div className="flex flex-col h-full bg-white shadow rounded-lg overflow-hidden">
      {!isConnected && (
        <div className="bg-yellow-50 text-yellow-800 px-4 py-2 text-sm text-center">
          Connection lost. Attempting to reconnect session...
        </div>
      )}
      
      <div className="flex-1 overflow-y-auto p-6 space-y-4">
        {messages.map((msg) => (
          <div key={msg.id} className={msg.role === "user" ? "text-right" : "text-left"}>
            <span className={`inline-block px-4 py-2 rounded-lg max-w-[80%] ${
              msg.role === "user" ? "bg-blue-600 text-white" : "bg-gray-100 text-gray-900"
            }`}>
              {msg.content.text}
            </span>
          </div>
        ))}
        {pendingMessage && (
          <div className="text-left">
            <span className="inline-block px-4 py-2 rounded-lg bg-gray-50 text-gray-500 animate-pulse">
              {pendingMessage}
            </span>
          </div>
        )}
      </div>

      <div className="p-4 border-t border-gray-100">
        <input
          type="text"
          placeholder="Enter message..."
          onKeyDown={(e) => {
            if (e.key === "Enter" && e.currentTarget.value.trim()) {
              sendMessage(e.currentTarget.value);
              e.currentTarget.value = "";
            }
          }}
          className="w-full px-4 py-3 border border-gray-300 rounded focus:border-blue-500 focus:outline-none"
        />
      </div>
    </div>
  );
}

Processing File Uploads

When your implementation requires processing documents or images alongside chat messages, supply an array of files utilizing the files argument within sendMessage:
import { useAgentContext } from "@wacht/tanstack-router";

export function FileUploadInteraction() {
  const { sendMessage, pendingFiles, isExecuting } = useAgentContext({
    contextId: "ctx_123",
    agentName: "analyst_bot",
  });

  const handleSend = async (message: string, fileList: FileList | null) => {
    const filesArray = fileList ? Array.from(fileList) : [];
    await sendMessage(message, [], filesArray);
  };

  return (
    <div className="space-y-4 border p-4 rounded bg-gray-50">
      <input 
        type="file" 
        multiple 
        onChange={(e) => handleSend("Please review these attachments.", e.target.files)} 
        disabled={isExecuting}
        className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:border-0 file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
      />
      {pendingFiles && pendingFiles.length > 0 && (
        <p className="text-sm font-medium text-blue-600">
          Transmitting {pendingFiles.length} file(s) to the backend storage layer...
        </p>
      )}
    </div>
  );
}

Exposing Execution Cancellation

During long-running queries or complex agent executions, exposing a cancellation trigger is recommended for optimal resource management:
import { useAgentContext } from "@wacht/tanstack-router";

export function ExecutionControl() {
  const { isExecuting, cancelExecution, executionStatus } = useAgentContext({
    contextId: "ctx_123",
    agentName: "query_bot",
  });

  if (!isExecuting) return null;

  return (
    <div className="flex items-center gap-4 bg-gray-100 p-3 rounded-lg">
      <span className="text-sm text-gray-600 animate-pulse">
        {executionStatus?.status_text || 'System processing request...'}
      </span>
      <button 
        onClick={() => cancelExecution()}
        className="px-3 py-1.5 text-xs font-semibold bg-white border border-gray-300 text-gray-700 rounded hover:bg-gray-50"
      >
        Halt Execution
      </button>
    </div>
  );
}

Protocol Mechanics

The useAgentContext hook maintains a persistent Server-Sent Events stream with the Wacht backend via the following underlying mechanism: https://{api_host}/realtime/agent/stream?context_id={contextId} This implementation handles connection reliability automatically, incorporating exponential backoff for reconnection sequences, implementing keep-alive mechanisms, and securely mounting the active authentication payload.
  • useAgentIntegrations - Manage third-party integrations accessed by the agent.
  • useAgentSession - Establish the core semantic session preceding individual conversation contexts.