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
An array of conversational messages detailing the interaction history between the user and the agent.
A list of suggested follow-up queries generated by the agent based on the context of the current conversation.
The content of a message currently being streamed by the agent, facilitating real-time rendering.
Files staged by the client for processing that have not yet fully resolved.
The underlying transport status of the SSE stream (e.g., connecting, open, closed).
A state indicator confirming whether the real-time SSE stream is actively connected and returning health checks.
A state indicator confirming whether the agent is currently processing a query, invoking backend tools, or generating a response text.
Detailed diagnostic information regarding the agent’s current background execution phase.
Indicates whether the agent has temporarily paused its execution thread to request explicit input parameters from the user.
Indicates whether historical messages are available to be loaded via pagination from the backend store.
A state indicator confirming whether pagination requests for historical messages are currently resolving.
Methods
sendMessage
(message: string, attachments?: MessageAttachment[], files?: File[]) => Promise<void>
Show Dispatch an event to the agent
The text content of the message payload.
Previously processed attachments to include in the conversation context.
Raw files requested for upload and subsequent analysis.
Resolves once the message payload has been successfully accepted by the server.
submitUserInput
(input: string) => Promise<void>
Show Provide requested input parameters
The user’s direct response to an agent’s execution prompt.
Resolves upon successful submission.
Clears the frontend array of messages without mutating the persisting context on the backend servers.
Show Fetch historical records
Appends the next paginated segment of historical messages to the messages array.
Show Halt current execution
Instructs the backend to terminally halt the agent’s current generation or tool execution sequence.
Show Establish connection
Manually initiates the SSE stream protocol immediately.
Show Terminate connection
Closes the SSE stream gracefully.
Configuration Parameters
You must configure the hook by supplying the relevant context and agent identifiers:
The unique identifier for the specific conversation thread.
The designated name of the target agent context to mount onto the stream.
An optional network adapter for intercepting and handling custom platform events triggered during the SSE stream.
Show Callback handler for user input requests
The parameters outlining the required input format (e.g., text boundaries, selection parameters).
The verified user output to return.
No return value expected.
Data Structures
interface ConversationMessage {
id : string ;
role : "user" | "assistant" | "system" ;
content : ConversationContent ;
timestamp : string ;
metadata ?: {
message_type : MessageType ;
};
}
Show UserInputRequestContent
interface UserInputRequestContent {
type : "user_input_request" ;
question : string ;
context : string ;
input_type : "text" | "number" | "select" | "multiselect" | "boolean" | "date" ;
options ?: string [];
default_value ?: string ;
placeholder ?: string ;
}
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.