Skip to main content

useAgentSession

Within applications deploying embedded AI components or requiring stringent access validation prior to execution, the useAgentSession hook operates as the primary initialization interface. It handles secure one-time ticket exchanges, retrieves the current session state, and dictates the active conversational agent for the application instance. By interfacing with the /agent/session API endpoint, the hook ensures that subsequent operations executed via useAgentContext are fully authenticated and explicitly routed.

Configuration Parameters

ticket
string | null
An optional, single-use authentication ticket mapped to a backend grant. When supplied, the hook exchanges this token sequentially before fetching session parameters. Omit or pass null if navigating a standard, persistent session.

Hook Interface

hasSession
boolean
Indicates the verified existence of an active and valid agent session.
sessionLoading
boolean
Indicates whether the hook is actively resolving the required session state via network requests.
sessionError
Error | null
Captures errors resulting from malformed tickets, expired sessions, or network failures.
sessionId
string | null
The unique identifier mapped to the active agent session.
contextGroup
string | null
An organizational assignment key applied specifically to this session structure.
agents
AgentWithIntegrations[]
A serialized array of AI Agents explicitly available within the verified user’s authorization scope.
activeAgent
AgentWithIntegrations | null
The specific agent currently designated for active interaction processing.

Methods

setActiveAgent
(agent: AgentWithIntegrations) => void
ticketExchanged
boolean
A state indicator confirming that a strictly provided authorization ticket has successfully exchanged for a session footprint.
ticketLoading
boolean
Indicates whether the specific ticket exchange operation is actively processing.
refetch
() => Promise<void>

Implementation Guidelines

Dynamic Agent Selection

In multi-agent environments, explicit selection interfaces are required to ensure the user communicates against the proper context model:
import { useAgentSession } from "@wacht/nextjs";

function TargetAgentSelector() {
  const { sessionLoading, agents, activeAgent, setActiveAgent } = useAgentSession();

  if (sessionLoading) return <div className="text-gray-500 font-medium">Validating agent configurations...</div>;
  if (agents.length === 0) return <div className="text-red-700">No agents authorized for current session parameters.</div>;

  return (
    <div className="flex flex-col gap-3">
      <label htmlFor="agent-selector" className="text-sm font-semibold uppercase tracking-wide text-gray-700">
        Designate Operating Agent
      </label>
      <select
        id="agent-selector"
        className="form-select block w-full pl-3 pr-10 py-2.5 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md shadow-sm"
        value={activeAgent?.id ?? ""}
        onChange={(e) => {
          const selectedTarget = agents.find((agent) => agent.id === e.target.value);
          if (selectedTarget) setActiveAgent(selectedTarget);
        }}
      >
        <option value="" disabled>Awaiting agent selection...</option>
        {agents.map((agent) => (
          <option key={agent.id} value={agent.id}>
            {agent.name}
          </option>
        ))}
      </select>
    </div>
  );
}

Initializing Embedded Security Contexts

When configuring Wacht embedded contexts utilizing backend-generated session tickets, the hook must process the one-time artifact before rendering the interface:
import { useAgentSession } from "@wacht/nextjs";

function SecureEmbeddedContext({ authorizationTicket }: { authorizationTicket: string }) {
  const { ticketLoading, hasSession, sessionError } = useAgentSession(authorizationTicket);

  if (ticketLoading) {
    return (
      <div className="flex animate-pulse items-center justify-center p-12 text-indigo-700 font-semibold tracking-wide">
        Exchanging authorization token...
      </div>
    );
  }

  if (sessionError) {
    return (
      <div className="p-6 bg-red-50 border border-red-200 rounded-lg">
        <h3 className="text-red-800 font-bold mb-2">Authentication Subsystem Error</h3>
        <p className="text-red-600 font-mono text-sm">{sessionError.message}</p>
      </div>
    );
  }

  if (!hasSession) {
    return <div className="p-6 text-gray-500 italic text-center">Security context expired or rejected. Request new authorization parameters.</div>;
  }

  return (
    <div className="p-8 border border-gray-200 rounded-xl bg-white shadow-md">
      <h2 className="text-xl font-bold text-gray-900 border-b pb-4 mb-4">Secure Context Initialized</h2>
      <p className="text-gray-600 leading-relaxed">
        The application is now permitted to initiate execution streams against local operations.
      </p>
      {/* TargetAgentSelector and Chat components mount below */}
    </div>
  );
}
  • useAgentContext - Implemented upon agent selection to deploy the associated execution stream.
  • useAgentIntegrations - Review available integrations corresponding to the designated active agent.