Skip to main content

useAgentContexts

For applications requiring conversation history management, the useAgentContexts hook delivers essential CRUD interfaces for interacting with agent contexts. Built-in pagination mapping and status filtering ensure optimal performance when rendering extensive session histories. By interacting directly with the /agent/contexts API endpoints, this hook facilitates the development of session logs and sidebar interfaces with minimal manual network fetching overhead.

Configuration Options

Configure the hook’s underlying requests to fit the application’s data retrieval requirements:
limit
number
The maximum number of conversation contexts retrieved per paginated request. Defaults to 20.
offset
number
The numeric count of records bypassed prior to fetching the current paginated batch. Defaults to 0.
status
string
An optional query parameter to isolate returned contexts by status (e.g., active or archived).
An optional query parameter to search conversation titles by matching text criteria.
enabled
boolean
A control flag determining whether automatic data fetching is enabled upon component mount. Defaults to true.

Hook Interface

contexts
AgentContext[]
The current operational array of conversation contexts based on the provided configuration.
loading
boolean
Indicates whether the primary fetch request for the component is actively resolving.
error
Error | null
Captures network failures or authorization discrepancies encountered during data retrieval.
hasMore
boolean
Indicates whether the API response sequence contains additional paginated records beyond the currently loaded batch.

Methods

createContext
(request: CreateContextRequest) => Promise<AgentContext>
deleteContext
(id: string) => Promise<void>
updateContext
(id: string, updates: { title?: string }) => Promise<void>
refetch
() => Promise<void>

Implementation Guidelines

Developing a Directory Interface

To implement a historical log of communication contexts, map the contexts response directly into an interface component:
import { useAgentContexts } from "@wacht/react-router";

export function ContextDirectory() {
  const { contexts, loading, error } = useAgentContexts({ limit: 10 });

  if (loading) return <div className="p-4 text-gray-500 font-medium tracking-wide">Retrieving records...</div>;
  if (error) return <div className="p-4 text-red-600 font-medium">Failed to retrieve records: {error.message}</div>;

  return (
    <div className="border border-gray-200 rounded-lg overflow-hidden bg-white">
      <ul className="divide-y divide-gray-100">
        {contexts.map((ctx) => (
          <li 
            key={ctx.id} 
            className="px-6 py-4 hover:bg-gray-50 cursor-pointer transition-colors flex justify-between items-center"
          >
            <span className="font-semibold text-gray-800">
              {ctx.title || "Uncategorized Session"}
            </span>
            <span className="text-xs text-gray-400 font-mono">
              ID: {ctx.id.slice(0, 8)}
            </span>
          </li>
        ))}
        {contexts.length === 0 && (
          <div className="px-6 py-8 text-center text-gray-400 italic">No historical records available.</div>
        )}
      </ul>
    </div>
  );
}

Context Lifecycle Management

Enabling direct management of conversation threads streamlines data organization. The following implementation demonstrates instantiation and synchronous modification of a context:
import { useState } from "react";
import { useAgentContexts } from "@wacht/react-router";

export function ContextManager() {
  const { createContext, updateContext } = useAgentContexts();
  const [isProcessing, setIsProcessing] = useState(false);

  const initializeSequence = async () => {
    setIsProcessing(true);
    try {
      const activeSession = await createContext({ title: "Temporary Analysis" });
      await updateContext(activeSession.id, { title: "Draft Data Evaluation" });
    } catch (err) {
      console.error("Failed to initialize system sequence", err);
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <button 
      onClick={initializeSequence}
      disabled={isProcessing}
      className={`px-5 py-2.5 rounded-md font-medium text-white transition-opacity ${
        isProcessing ? "bg-indigo-400 opacity-70 cursor-wait" : "bg-indigo-600 hover:bg-indigo-700 shadow-sm"
      }`}
    >
      {isProcessing ? "Allocating Resources..." : "Initialize Context Sequence"}
    </button>
  );
}
  • useAgentContext - Utilized for mounting the SSE communication stream within an initiated context.
  • useAgentSession - Utilized for verifying active session parameters prior to accessing context operations.