Hooks
import ApiTable from "../../../../components/docs/ApiTable.astro"; import Callout from "../../../../components/docs/Callout.astro"; All hooks must be called inside a `<ArlopassProvider>`. They are re-exported from `@arlopass/react`. --- ### useConnection Manages the WebSocket-like connection to the Arlopass browser extension. ```tsx import { useConnection } from "@arlopass/react"; ``` <ApiTable props={[ { name: "state", type: "ClientState", description: 'Current connection state: "disconnected" | "connecting" | "connected" | "degraded" | "reconnecting" | "failed".', }, { name: "sessionId", type: "string | null", description: "Active session ID, or null when disconnected.", }, { name: "isConnected", type: "boolean", description: 'True when state is "connected" or "degraded".', }, { name: "isConnecting", type: "boolean", description: 'True when state is "connecting" or "reconnecting".', }, { name: "error", type: "ArlopassSDKError | null", description: "Most recent connection error, or null.", }, { name: "connect", type: "() => Promise<void>", description: "Initiate a connection. Throws on failure.", }, { name: "disconnect", type: "() => Promise<void>", description: "Disconnect the client and reset state.", }, { name: "retry", type: "(() => Promise<void>) | null", description: "Retry function when the last error is retryable. Null otherwise.", }, ]} /> ```tsx import { useConnection } from "@arlopass/react"; const { state, isConnected, connect, retry } = useConnection(); ``` --- ### useProviders Lists available AI providers and selects a provider/model pair. Automatically fetches providers when the connection reaches `"connected"` or `"degraded"`. ```tsx import { useProviders } from "@arlopass/react"; ``` <ApiTable props={[ { name: "providers", type: "readonly ProviderDescriptor[]", description: "List of available providers and their models.", }, { name: "selectedProvider", type: "{ providerId: string; modelId: string } | null", description: "Currently selected provider/model pair, or null.", }, { name: "isLoading", type: "boolean", description: "True while listing or selecting a provider.", }, { name: "error", type: "ArlopassSDKError | null", description: "Error from the last provider operation.", }, { name: "listProviders", type: "() => Promise<void>", description: "Fetch providers from the extension. Called automatically on connect.", }, { name: "selectProvider", type: "(input: SelectProviderInput) => Promise<void>", description: "Select a provider and model.", }, { name: "retry", type: "(() => Promise<void>) | null", description: "Retry last operation when the error is retryable.", }, ]} /> ```tsx import { useProviders } from "@arlopass/react"; const { providers, selectedProvider, selectProvider } = useProviders(); ``` --- ### useChat Stateful chat with message tracking, streaming, and abort. Does not support tools or context-window management — use `useConversation` for that. ```tsx import { useChat } from "@arlopass/react"; ``` **Options** <ApiTable props={[ { name: "initialMessages", type: "TrackedChatMessage[]", description: "Seed the message list (e.g. restored from storage).", }, { name: "systemPrompt", type: "string", description: "Prepended as a system message to every request.", }, ]} /> **Return value** <ApiTable props={[ { name: "messages", type: "readonly TrackedChatMessage[]", description: "All tracked messages (user + assistant).", }, { name: "streamingContent", type: "string", description: "Accumulated text of the current streaming response.", }, { name: "streamingMessageId", type: "MessageId | null", description: "ID of the message currently being streamed.", }, { name: "isStreaming", type: "boolean", description: "True while a stream is in progress.", }, { name: "isSending", type: "boolean", description: "True while a non-streaming send is in progress.", }, { name: "error", type: "ArlopassSDKError | null", description: "Error from the last chat operation.", }, { name: "contextInfo", type: "ContextWindowInfo", description: "Context window usage info: maxTokens, usedTokens, reservedOutputTokens, remainingTokens, usageRatio. Recomputed when messages change.", }, { name: "send", type: "(content: string) => Promise<MessageId>", description: "Send a message and wait for the full response. Returns the user message ID.", }, { name: "stream", type: "(content: string) => Promise<MessageId>", description: "Send a message and stream the response token-by-token. Returns the user message ID.", }, { name: "stop", type: "() => void", description: "Abort the current stream. Partial content is kept.", }, { name: "clearMessages", type: "() => void", description: "Clear all messages and reset state.", }, { name: "retry", type: "(() => Promise<void>) | null", description: "Retry the last failed operation when the error is retryable.", }, { name: "subscribe", type: "ChatSubscribeNoTools", description: 'Subscribe to chat events: "response", "stream", "error".', }, ]} /> ```tsx import { useChat } from "@arlopass/react"; const { messages, stream, isStreaming, stop, contextInfo } = useChat({ systemPrompt: "You are a helpful assistant.", }); // contextInfo.usageRatio is 0–1, useful for progress bars console.log(`Context: ${contextInfo.usedTokens}/${contextInfo.maxTokens}`); ``` <Callout type="info" title="One operation at a time"> Calling `send` or `stream` while another is in flight throws. Call `stop()` first to abort the current operation. </Callout> --- ### useConversation Full-featured conversation hook built on `ConversationManager`. Adds tool calling, context-window management, token counting, message pinning, and summarization. ```tsx import { useConversation } from "@arlopass/react"; ``` **Options** <ApiTable props={[ { name: "initialMessages", type: "TrackedChatMessage[]", description: "Seed the message list.", }, { name: "systemPrompt", type: "string", description: "System prompt prepended to every request.", }, { name: "tools", type: "ToolDefinition[]", description: "Tool definitions the model can call.", }, { name: "maxTokens", type: "number", description: "Context window limit in tokens. Auto-detected from model if omitted.", }, { name: "maxToolRounds", type: "number", default: "5", description: "Maximum tool-call rounds before returning text.", }, { name: "primeTools", type: "boolean", default: "false", description: "Enable tool priming for all messages.", }, { name: "hideToolCalls", type: "boolean", default: "false", description: "Strip tool-call markup from streamed/returned text.", }, ]} /> **Return value** <ApiTable props={[ { name: "messages", type: "readonly TrackedChatMessage[]", description: "All tracked messages (user + assistant).", }, { name: "streamingContent", type: "string", description: "Accumulated text of the current streaming response.", }, { name: "streamingMessageId", type: "MessageId | null", description: "ID of the message currently being streamed.", }, { name: "isStreaming", type: "boolean", description: "True while a stream is in progress.", }, { name: "isSending", type: "boolean", description: "True while a non-streaming send is in progress.", }, { name: "error", type: "ArlopassSDKError | null", description: "Error from the last operation.", }, { name: "tokenCount", type: "number", description: "Estimated tokens currently used by the context window.", }, { name: "contextWindow", type: "readonly ChatMessage[]", description: "Messages that will be sent in the next request (post-summarization).", }, { name: "contextInfo", type: "ContextWindowInfo", description: "Context window usage: maxTokens, usedTokens, reservedOutputTokens, remainingTokens, usageRatio. Updates after each send/stream/clear.", }, { name: "send", type: "(content: string, options?: { pinned?: boolean }) => Promise<MessageId>", description: "Send a message. Optionally pin it to survive summarization.", }, { name: "stream", type: "(content: string, options?: { pinned?: boolean }) => Promise<MessageId>", description: "Stream a response. Optionally pin the user message.", }, { name: "stop", type: "() => void", description: "Abort the current stream.", }, { name: "clearMessages", type: "() => void", description: "Clear all messages, reset token count, and clear the ConversationManager.", }, { name: "pinMessage", type: "(messageId: MessageId, pinned: boolean) => void", description: "Toggle pin status for a message. Pinned messages survive context-window summarization.", }, { name: "submitToolResult", type: "(toolCallId: string, result: string) => void", description: "Submit a result for a manual tool call (tools without a handler).", }, { name: "retry", type: "(() => Promise<void>) | null", description: "Retry the last failed operation. Null when not retryable.", }, { name: "subscribe", type: "ChatSubscribe", description: 'Subscribe to events: "response", "stream", "error", "tool_call", "tool_result", "tool_priming_start", "tool_priming_match", "tool_priming_end".', }, ]} /> ```tsx import { useConversation } from "@arlopass/react"; const { messages, stream, tokenCount, contextInfo, pinMessage } = useConversation({ systemPrompt: "You are a helpful assistant.", tools: [ { name: "search", description: "Search the web", handler: async (args) => "results", }, ], }); // Build a usage meter from contextInfo const pct = Math.round(contextInfo.usageRatio * 100); console.log( `${pct}% of context used (${contextInfo.remainingTokens} tokens left)`, ); ``` --- ### useClient Escape hatch to the underlying `ArlopassClient` instance. Returns `null` when the transport is unavailable or the client is in a `"disconnected"` or `"failed"` state. ```tsx import { useClient } from "@arlopass/react"; ``` <ApiTable props={[ { name: "(return)", type: "ArlopassClient | null", description: "The underlying ArlopassClient instance, or null if the transport is unavailable or the client is disconnected/failed.", }, ]} /> ```tsx import { useClient } from "@arlopass/react"; const client = useClient(); // Use for advanced operations not covered by other hooks ```All hooks must be called inside a <ArlopassProvider>. They are re-exported from @arlopass/react.
useConnection
Manages the WebSocket-like connection to the Arlopass browser extension.
import { useConnection } from "@arlopass/react";
| Prop | Type | Default | Description |
|---|---|---|---|
state | ClientState | — | Current connection state: "disconnected" | "connecting" | "connected" | "degraded" | "reconnecting" | "failed". |
sessionId | string | null | — | Active session ID, or null when disconnected. |
isConnected | boolean | — | True when state is "connected" or "degraded". |
isConnecting | boolean | — | True when state is "connecting" or "reconnecting". |
error | ArlopassSDKError | null | — | Most recent connection error, or null. |
connect | () => Promise<void> | — | Initiate a connection. Throws on failure. |
disconnect | () => Promise<void> | — | Disconnect the client and reset state. |
retry | (() => Promise<void>) | null | — | Retry function when the last error is retryable. Null otherwise. |
import { useConnection } from "@arlopass/react";
const { state, isConnected, connect, retry } = useConnection();
useProviders
Lists available AI providers and selects a provider/model pair. Automatically fetches providers when the connection reaches "connected" or "degraded".
import { useProviders } from "@arlopass/react";
| Prop | Type | Default | Description |
|---|---|---|---|
providers | readonly ProviderDescriptor[] | — | List of available providers and their models. |
selectedProvider | { providerId: string; modelId: string } | null | — | Currently selected provider/model pair, or null. |
isLoading | boolean | — | True while listing or selecting a provider. |
error | ArlopassSDKError | null | — | Error from the last provider operation. |
listProviders | () => Promise<void> | — | Fetch providers from the extension. Called automatically on connect. |
selectProvider | (input: SelectProviderInput) => Promise<void> | — | Select a provider and model. |
retry | (() => Promise<void>) | null | — | Retry last operation when the error is retryable. |
import { useProviders } from "@arlopass/react";
const { providers, selectedProvider, selectProvider } = useProviders();
useChat
Stateful chat with message tracking, streaming, and abort. Does not support tools or context-window management — use useConversation for that.
import { useChat } from "@arlopass/react";
Options
| Prop | Type | Default | Description |
|---|---|---|---|
initialMessages | TrackedChatMessage[] | — | Seed the message list (e.g. restored from storage). |
systemPrompt | string | — | Prepended as a system message to every request. |
Return value
| Prop | Type | Default | Description |
|---|---|---|---|
messages | readonly TrackedChatMessage[] | — | All tracked messages (user + assistant). |
streamingContent | string | — | Accumulated text of the current streaming response. |
streamingMessageId | MessageId | null | — | ID of the message currently being streamed. |
isStreaming | boolean | — | True while a stream is in progress. |
isSending | boolean | — | True while a non-streaming send is in progress. |
error | ArlopassSDKError | null | — | Error from the last chat operation. |
contextInfo | ContextWindowInfo | — | Context window usage info: maxTokens, usedTokens, reservedOutputTokens, remainingTokens, usageRatio. Recomputed when messages change. |
send | (content: string) => Promise<MessageId> | — | Send a message and wait for the full response. Returns the user message ID. |
stream | (content: string) => Promise<MessageId> | — | Send a message and stream the response token-by-token. Returns the user message ID. |
stop | () => void | — | Abort the current stream. Partial content is kept. |
clearMessages | () => void | — | Clear all messages and reset state. |
retry | (() => Promise<void>) | null | — | Retry the last failed operation when the error is retryable. |
subscribe | ChatSubscribeNoTools | — | Subscribe to chat events: "response", "stream", "error". |
import { useChat } from "@arlopass/react";
const { messages, stream, isStreaming, stop, contextInfo } = useChat({
systemPrompt: "You are a helpful assistant.",
});
// contextInfo.usageRatio is 0–1, useful for progress bars
console.log(`Context: ${contextInfo.usedTokens}/${contextInfo.maxTokens}`);
useConversation
Full-featured conversation hook built on ConversationManager. Adds tool calling, context-window management, token counting, message pinning, and summarization.
import { useConversation } from "@arlopass/react";
Options
| Prop | Type | Default | Description |
|---|---|---|---|
initialMessages | TrackedChatMessage[] | — | Seed the message list. |
systemPrompt | string | — | System prompt prepended to every request. |
tools | ToolDefinition[] | — | Tool definitions the model can call. |
maxTokens | number | — | Context window limit in tokens. Auto-detected from model if omitted. |
maxToolRounds | number | 5 | Maximum tool-call rounds before returning text. |
primeTools | boolean | false | Enable tool priming for all messages. |
hideToolCalls | boolean | false | Strip tool-call markup from streamed/returned text. |
Return value
| Prop | Type | Default | Description |
|---|---|---|---|
messages | readonly TrackedChatMessage[] | — | All tracked messages (user + assistant). |
streamingContent | string | — | Accumulated text of the current streaming response. |
streamingMessageId | MessageId | null | — | ID of the message currently being streamed. |
isStreaming | boolean | — | True while a stream is in progress. |
isSending | boolean | — | True while a non-streaming send is in progress. |
error | ArlopassSDKError | null | — | Error from the last operation. |
tokenCount | number | — | Estimated tokens currently used by the context window. |
contextWindow | readonly ChatMessage[] | — | Messages that will be sent in the next request (post-summarization). |
contextInfo | ContextWindowInfo | — | Context window usage: maxTokens, usedTokens, reservedOutputTokens, remainingTokens, usageRatio. Updates after each send/stream/clear. |
send | (content: string, options?: { pinned?: boolean }) => Promise<MessageId> | — | Send a message. Optionally pin it to survive summarization. |
stream | (content: string, options?: { pinned?: boolean }) => Promise<MessageId> | — | Stream a response. Optionally pin the user message. |
stop | () => void | — | Abort the current stream. |
clearMessages | () => void | — | Clear all messages, reset token count, and clear the ConversationManager. |
pinMessage | (messageId: MessageId, pinned: boolean) => void | — | Toggle pin status for a message. Pinned messages survive context-window summarization. |
submitToolResult | (toolCallId: string, result: string) => void | — | Submit a result for a manual tool call (tools without a handler). |
retry | (() => Promise<void>) | null | — | Retry the last failed operation. Null when not retryable. |
subscribe | ChatSubscribe | — | Subscribe to events: "response", "stream", "error", "tool_call", "tool_result", "tool_priming_start", "tool_priming_match", "tool_priming_end". |
import { useConversation } from "@arlopass/react";
const { messages, stream, tokenCount, contextInfo, pinMessage } =
useConversation({
systemPrompt: "You are a helpful assistant.",
tools: [
{
name: "search",
description: "Search the web",
handler: async (args) => "results",
},
],
});
// Build a usage meter from contextInfo
const pct = Math.round(contextInfo.usageRatio * 100);
console.log(
`${pct}% of context used (${contextInfo.remainingTokens} tokens left)`,
);
useClient
Escape hatch to the underlying ArlopassClient instance. Returns null when the transport is unavailable or the client is in a "disconnected" or "failed" state.
import { useClient } from "@arlopass/react";
| Prop | Type | Default | Description |
|---|---|---|---|
(return) | ArlopassClient | null | — | The underlying ArlopassClient instance, or null if the transport is unavailable or the client is disconnected/failed. |
import { useClient } from "@arlopass/react";
const client = useClient();
// Use for advanced operations not covered by other hooks