Implementation:0xranx OpenContext useAgentStreaming
| Knowledge Sources | |
|---|---|
| Domains | UI, AI_Agents |
| Last Updated | 2026-10-24 12:00 GMT |
Overview
Concrete tool for handling agent streaming responses in the React frontend, subscribing to Tauri events and managing streaming UI state including content tokens, reasoning, tool calls, and permission dialogs.
Description
The useAgentStreaming hook is a React custom hook that manages the complete streaming response lifecycle for agent chat. It receives a large set of callback props from the parent component (session management, message manipulation, dialog control) and provides `isGenerating` state and a `generate` function.
Key responsibilities:
- Event subscription: Listens to `agent-stream-{requestId}` Tauri events for streaming tokens.
- Content handling: Appends content tokens to the active assistant message, handling text sanitization and incremental updates.
- Reasoning handling: Accumulates reasoning/thinking tokens in a separate `reasoningText` state, rendered as a collapsible thought block.
- Tool call rendering: Creates and updates tool messages with headers, content, and summaries using `ensureToolMessage` and `appendToolLikeMessage`.
- Permission handling: When a permission event arrives, shows a dialog via `setDialog`; tracks handled permissions to avoid duplicates.
- Elapsed timer: Tracks elapsed seconds during generation for UI display.
- Stop handling: Supports stop requests via `stopRequestedRef`, though native agent processes cannot always be cleanly interrupted.
The hook maintains several refs for state that doesn't trigger re-renders: `activeRequestIdRef`, `stopRequestedRef`, `toolMessageMapRef`, `activeToolAnchorRef`, `activeAssistantMessageRef`, `handledPermissionRef`.
Usage
- Desktop Agent Chat: Used by the AgentSidebar component to handle streaming responses.
- Multi-agent: Works with Codex, Claude, and OpenCode agents via the unified event format.
Code Reference
Source Location
- Repository: OpenContext
- File: src/ui/src/components/agent/hooks/useAgentStreaming.js
Signature
export const useAgentStreaming = ({
t, inputValue, setInputValue, activeSession, isInputReady,
contextBlock, buildModelMessages, updateSession, appendMessages,
updateMessageContent, updateMessageSummary, insertMessageAfter,
setExpandedThoughtMessages, resolveIntentFromText, deriveSessionTitle,
extractOcAction, sanitizeText, intentPrompts, statusLabelKeys,
createMessage, setDialog, isComposing,
}) => {
const [isGenerating, setIsGenerating] = useState(false);
const [generatingSessionId, setGeneratingSessionId] = useState(null);
const [reasoningText, setReasoningText] = useState('');
const [elapsedSeconds, setElapsedSeconds] = useState(0);
// ... refs for non-rendering state ...
return {
isGenerating,
isThoughtRunning,
reasoningText,
elapsedSeconds,
generate,
stop,
// ... other utilities
};
};
Import
import { useAgentStreaming } from './hooks/useAgentStreaming';
I/O Contract
Inputs (props)
| Name | Type | Description |
|---|---|---|
| activeSession | null | Currently active agent session |
| updateSession | Function | Update session state |
| appendMessages | Function | Append messages to a session |
| updateMessageContent | Function | Update a message's content |
| createMessage | Function | Create a new message object |
| setDialog | Function | Show a dialog (e.g., permission) |
| (and 15+ other props) | various | See signature for full list |
Outputs (return)
| Name | Type | Description |
|---|---|---|
| isGenerating | boolean | Whether a response is streaming |
| isThoughtRunning | boolean | Whether the active session is generating |
| reasoningText | string | Accumulated reasoning tokens |
| elapsedSeconds | number | Seconds since generation started |
| generate | Function | Trigger agent generation |
| stop | Function | Request generation stop |
Usage Examples
Basic Usage in AgentSidebar
import { useAgentStreaming } from './hooks/useAgentStreaming';
function AgentSidebar({ activeSession, updateSession, /* ...other props */ }) {
const {
isGenerating,
reasoningText,
elapsedSeconds,
generate,
stop,
} = useAgentStreaming({
activeSession,
updateSession,
appendMessages,
updateMessageContent,
createMessage,
setDialog,
// ... other props
});
const handleSubmit = () => {
generate({
agentId: activeSession.agentId,
model: activeSession.model,
messages: activeSession.messages,
});
};
return (
<div>
{isGenerating && <Timer seconds={elapsedSeconds} />}
{reasoningText && <ThoughtBlock text={reasoningText} />}
<button onClick={handleSubmit} disabled={isGenerating}>Send</button>
{isGenerating && <button onClick={stop}>Stop</button>}
</div>
);
}
Event Handling Flow
// Internal flow (simplified):
// 1. generate() invokes codex_exec/claude_exec/opencode_run
// 2. Listens to `agent-stream-${requestId}` events
// 3. For each event:
// - content -> updateMessageContent(append)
// - reasoning -> setReasoningText(append)
// - tool -> ensureToolMessage + appendToolLikeMessage
// - permission -> setDialog(permission)
// - done -> finalize, setIsGenerating(false)