@hyperflow/react
Headless stores, hooks, and application components.
Reading this reference
Use AppCore to set up the client, routing, navigation, and synchronization together. Use HyperflowProvider to initialize only the client and configure the other parts yourself. Then explore the area you want to customize.
Each area lists its primary components and hooks, followed by their supporting types. Components show props and defaults; hooks show parameters and returned fields. Type links open the corresponding definition.
Find a contract
Choose an area below. Each section groups its main contracts with their supporting types; links in the tables lead directly to the relevant definition.
| Area | What you will find |
|---|---|
| Application and configuration | Start with AppCore for the complete headless application boundary, or HyperflowProvider when composing your own routing and synchronization. |
| Authentication | Read authentication state, sign users in or out, and render authenticated account information. |
| Layout and navigation | Build a custom sidebar and navigation from headless contracts. Synchronization bridges connect application events to shared state. |
| Sessions and background tasks | Read session lists and details, create or update sessions, send messages, stop active work, and inspect background tasks. |
| Composer and controls | useComposer owns the draft, attachments, control slots, submission, and stop behavior. Use its contracts to build a visual skin without duplicating that state. |
| Timeline and messages | useTimeline provides semantic entries, aggregate status, history controls, and session-scoped background tasks. Render this contract rather than rebuilding the timeline from service state. |
| Human-in-the-loop | useHitl selects the pending request kind; HitlGate and the request-specific hooks expose the controls needed for custom panels. |
| Knowledge base | Browse and manage documents through the library contract. The sync bridge connects knowledge-base events to shared state. |
| Runtime and resources | Read configuration, models, runtime agents and tools, provider usage, connection state, and available workspaces. |
Application and configuration
Start with AppCore for the complete headless application boundary, or HyperflowProvider when composing your own routing and synchronization.
| Entry point | Kind |
|---|---|
AppCore | Component |
HyperflowProvider | Component |
useHyperflowRouter | Hook |
RequireAuth | Component |
RuntimeReloadTracker | Component |
AppCore
Composes the client provider, application router, navigation context, and synchronization bridges for a custom visual skin.
| Prop | Default | Type |
|---|---|---|
config | — | ClientConfigRequired. Hyperflow client configuration passed to the singleton client. |
routes | [] | HyperflowRoute[]Public routes rendered by the app router, in the supplied order. |
navItems | [] | NavItem[]Navigation items exposed to layout components through context. |
layoutComponent | — | ComponentType<{ children: ReactNode }>Required. Layout component used for protected routes. |
loginComponent | — | ComponentTypeRequired. Component rendered on the login route. |
runtimeReloadComponent | — | ComponentTypeOptional runtime-reload screen component. |
fallback | — | ReactNodeSuspense fallback used while the client initializes. |
AppCoreProps
/**
* Configuration for the core Hyperflow app shell.
*
* This component wires the client provider, router, and navigation context
* together so consumers can focus on route and layout composition.
*/
export interface AppCoreProps {
/** Hyperflow client configuration passed to the singleton client. */
config: ClientConfig;
/** Public routes rendered by the app router, in the supplied order. */
routes?: HyperflowRoute[];
/** Navigation items exposed to layout components through context. */
navItems?: NavItem[];
/** Layout component used for protected routes. */
layoutComponent: ComponentType<{
children: ReactNode;
}>;
/** Component rendered on the login route. */
loginComponent: ComponentType;
/** Optional runtime-reload screen component. */
runtimeReloadComponent?: ComponentType;
/** Suspense fallback used while the client initializes. */
fallback?: ReactNode;
}Related types: ClientConfig, HyperflowRoute, NavItem.
HyperflowProvider
Initializes the Hyperflow client and suspends the subtree until ready.
| Prop | Default | Type |
|---|---|---|
config | — | ClientConfigRequired. Hyperflow client configuration used to initialize the singleton client. |
children | — | ReactNodeRequired. Tree rendered once the client is ready. |
fallback | null | ReactNodeOptional fallback rendered while initialization is suspended. |
HyperflowProviderProps
interface HyperflowProviderProps {
/** Hyperflow client configuration used to initialize the singleton client. */
config: ClientConfig;
/** Tree rendered once the client is ready. */
children: ReactNode;
/** Optional fallback rendered while initialization is suspended. */
fallback?: ReactNode;
}Related types: ClientConfig.
useHyperflowRouter
Creates one Hyperflow data router for the supplied routes and replacement screens. The router is retained for this hook instance.
Parameters
| Parameter | Default | Type |
|---|---|---|
routes | [] | HyperflowRoute[]Routes rendered by the application router, in the supplied order. |
layoutComponent | — | ComponentType<{ children: ReactNode }>Required. Layout for protected routes; receives the routed page as children. |
loginComponent | — | ComponentTypeRequired. Component rendered by the login route. |
runtimeReloadComponent | — | ComponentTypeOptional component rendered during a runtime reload. |
Returns
DataRouter
The React Router DataRouter instance retained by this hook.
RequireAuth
Route guard that blocks unauthenticated access to protected screens.
| Prop | Default | Type |
|---|---|---|
| — | — | No props. |
RuntimeReloadTracker
Emits a recovery-success notification after leaving the runtime-reload screen. Mount inside a React Router context; this component renders nothing.
| Prop | Default | Type |
|---|---|---|
| — | — | No props. |
Supporting types
HyperflowRoute
interface HyperflowRoute {
/** Route path relative to the router root. */
path: string;
/** Component rendered when the route matches. */
component: ComponentType;
/** When true, the route requires authentication before rendering. */
requireAuth?: boolean;
/** When true, the route is rendered outside the main application layout. */
noLayout?: boolean;
/** Nested child routes rendered under this route. */
children?: HyperflowRoute[];
}NavItem
interface NavItem {
/** The route path associated with the navigation item. */
path: string;
/** The text label shown for the navigation item. */
label: string;
/** Optional icon component rendered next to the label. */
icon?: ComponentType;
}Authentication
Read authentication state, sign users in or out, and render authenticated account information.
| Entry point | Kind |
|---|---|
useAuth | Hook |
useLogin | Hook |
useLogout | Hook |
useAuthUser | Hook |
useMyAccount | Hook |
Auth | Component |
useAuth
Loads the current user and exposes authentication initialization, request state, login, and logout.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
initialized | booleanWhether the initial current-user request has finished, including a failed request. |
authUser | User | undefinedAuthenticated user, or undefined when no user is available. |
authMode | AuthModeAuthentication mode configured by the server. |
fetching | booleanWhether the current-user request is in progress. |
authorizing | booleanWhether a login request is in progress. |
login | (credentials: AuthorizeInput) => Promise<AuthorizeResult>Signs in with the supplied credentials and resolves to the authorization result. |
logout | () => voidClears the authenticated session and starts the logout flow. |
UseAuth
type UseAuth = {
/**
* Whether the initial current-user request has finished, including a failed
* request.
*/
initialized: boolean;
/** Authenticated user, or undefined when no user is available. */
authUser: User | undefined;
/** Authentication mode configured by the server. */
authMode: AuthMode;
/** Whether the current-user request is in progress. */
fetching: boolean;
/** Whether a login request is in progress. */
authorizing: boolean;
/**
* Signs in with the supplied credentials and resolves to the authorization result.
*/
login: (credentials: AuthorizeInput) => Promise<AuthorizeResult>;
/** Clears the authenticated session and starts the logout flow. */
logout: () => void;
};Related types: AuthMode, AuthorizeInput, AuthorizeResult, User.
useLogin
Exposes the login action with its request state and error.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
login | (credentials: AuthorizeInput) => Promise<AuthorizeResult>Signs in with the supplied credentials and resolves to the authorization result. |
error | Error | undefinedError from the login request, or undefined when no login error is recorded. |
authorizing | booleanWhether a login request is in progress. |
UseLogin
type UseLogin = {
/**
* Signs in with the supplied credentials and resolves to the authorization result.
*/
login: (credentials: AuthorizeInput) => Promise<AuthorizeResult>;
/** Error from the login request, or undefined when no login error is recorded. */
error?: Error | undefined;
/** Whether a login request is in progress. */
authorizing: boolean;
};Related types: AuthorizeInput, AuthorizeResult.
useLogout
Exposes the logout action for the authenticated session.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
logout | () => voidClears the authenticated session and starts the logout flow. |
UseLogout
type UseLogout = {
/** Clears the authenticated session and starts the logout flow. */
logout: () => void;
};useAuthUser
Loads the current user and exposes a manual reload action.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
authUser | User | undefinedAuthenticated user, or undefined when no user is available. |
fetching | booleanWhether the current-user request is in progress. |
authorizing | booleanWhether a login request is in progress. |
fetchAuthUser | () => Promise<User | undefined>Reloads the current user and resolves to the user, or undefined when unavailable. |
UseAuthUser
type UseAuthUser = {
/** Authenticated user, or undefined when no user is available. */
authUser: User | undefined;
/** Whether the current-user request is in progress. */
fetching: boolean;
/** Whether a login request is in progress. */
authorizing: boolean;
/**
* Reloads the current user and resolves to the user, or undefined when unavailable.
*/
fetchAuthUser: () => Promise<User | undefined>;
};Related types: User.
useMyAccount
Reads current account state and exposes account-details and password updates.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
authUser | User | undefinedCurrent account details, or undefined when no user is available. |
fetching | booleanWhether the current-user request is in progress. |
saving | booleanWhether an account-details update is in progress. |
changingPassword | booleanWhether a password change is in progress. |
error | Error | undefinedError from an account operation, or undefined when none is recorded. |
updateMyAccount | (input: UpdateMyAccountInput) => Promise<User>Saves the supplied account details and resolves to the updated user. |
changePassword | (input: ChangePasswordInput) => Promise<void>Changes the account password using the supplied current and new credentials. |
UseMyAccount
type UseMyAccount = {
/** Current account details, or undefined when no user is available. */
authUser: User | undefined;
/** Whether the current-user request is in progress. */
fetching: boolean;
/** Whether an account-details update is in progress. */
saving: boolean;
/** Whether a password change is in progress. */
changingPassword: boolean;
/** Error from an account operation, or undefined when none is recorded. */
error?: Error | undefined;
/** Saves the supplied account details and resolves to the updated user. */
updateMyAccount: (input: UpdateMyAccountInput) => Promise<User>;
/** Changes the account password using the supplied current and new credentials. */
changePassword: (input: ChangePasswordInput) => Promise<void>;
};Related types: ChangePasswordInput, UpdateMyAccountInput, User.
Auth
Helper component to access the authenticated user and auth state in the component tree.
| Prop | Default | Type |
|---|---|---|
children | — | (props: UseAuth) => React.ReactNodeRender prop receiving the current auth state. |
AuthUserProps
interface AuthUserProps {
/** Render prop receiving the current auth state. */
children?: (props: UseAuth) => React.ReactNode;
}Related types: UseAuth.
Layout and navigation
Build a custom sidebar and navigation from headless contracts. Synchronization bridges connect application events to shared state.
| Entry point | Kind |
|---|---|
useSidebar | Hook |
useNavItems | Hook |
useRowIndicators | Hook |
SessionSyncBridge | Component |
SessionUnreadSyncBridge | Component |
useSidebar
Combines session lists, grouping and ordering preferences, unread markers, and custom-group actions for a custom sidebar.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
groupBy | ListSessionsGroupByCurrent session grouping preference. |
setGroupBy | (groupBy: ListSessionsGroupBy) => voidChanges the grouping preference used to fetch and display the session list. |
sortBy | SessionListSortByCurrent session ordering preference. |
setSortBy | (sortBy: SessionListSortBy) => voidChanges the ordering preference used to fetch the session list. |
markSessionRead | (sessionId: string) => voidClears the unread marker for the supplied session id. |
groups | SessionListGroup[] | nullDisplay groups for the selected grouping mode, or null when the list is ungrouped. |
sessions | ReturnType<typeof useSessionStore.getState>["sessions"]Sessions currently loaded in the sidebar list. |
loading | booleanWhether the first page of sessions is being fetched. |
loadingMore | booleanWhether an additional page of sessions is being fetched. |
hasMore | booleanWhether another page of sessions is available. |
error | Error | undefinedSession-list request error, or undefined when no list error is recorded. |
refetch | () => Promise<void>Reloads the first page using the current grouping and ordering preferences. |
loadMore | () => Promise<void>Loads the next page when more sessions are available. |
createSession | ReturnType<typeof useSessionActions>["createSession"]Creates a session from the supplied input and resolves to the new session. |
updateSession | ReturnType<typeof useSessionActions>["updateSession"]Updates the session identified by id and resolves to the updated session. |
moveSessionToGroup | ReturnType<typeof useSessionActions>["moveSessionToGroup"]Moves a session to the supplied custom group; null removes its custom-group assignment. |
deleteSession | ReturnType<typeof useSessionActions>["deleteSession"]Deletes the session identified by id. |
renameSession | ReturnType<typeof useSessionActions>["renameSession"]Sets the title of the session identified by id and resolves to the updated session. |
createCustomGroup | (name: string) => Promise<SessionCustomGroup>Creates a named custom group and resolves to the created group. |
updateCustomGroup | (id: string, name: string) => Promise<SessionCustomGroup>Renames the custom group identified by id and resolves to the updated group. |
deleteCustomGroup | (id: string) => Promise<void>Deletes the custom group identified by id. |
customGroups | SessionCustomGroup[]Available custom session groups. |
customGroupsLoading | booleanWhether custom session groups are being fetched. |
customGroupsError | Error | undefinedCustom-group request error, or undefined when none is recorded. |
UseSidebar
type UseSidebar = {
/** Current session grouping preference. */
groupBy: ListSessionsGroupBy;
/** Changes the grouping preference used to fetch and display the session list. */
setGroupBy: (groupBy: ListSessionsGroupBy) => void;
/** Current session ordering preference. */
sortBy: SessionListSortBy;
/** Changes the ordering preference used to fetch the session list. */
setSortBy: (sortBy: SessionListSortBy) => void;
/** Clears the unread marker for the supplied session id. */
markSessionRead: (sessionId: string) => void;
/**
* Display groups for the selected grouping mode, or null when the list is
* ungrouped.
*/
groups: SessionListGroup[] | null;
/** Sessions currently loaded in the sidebar list. */
sessions: ReturnType<typeof useSessionStore.getState>["sessions"];
/** Whether the first page of sessions is being fetched. */
loading: boolean;
/** Whether an additional page of sessions is being fetched. */
loadingMore: boolean;
/** Whether another page of sessions is available. */
hasMore: boolean;
/** Session-list request error, or undefined when no list error is recorded. */
error?: Error | undefined;
/** Reloads the first page using the current grouping and ordering preferences. */
refetch: () => Promise<void>;
/** Loads the next page when more sessions are available. */
loadMore: () => Promise<void>;
/** Creates a session from the supplied input and resolves to the new session. */
createSession: ReturnType<typeof useSessionActions>["createSession"];
/** Updates the session identified by id and resolves to the updated session. */
updateSession: ReturnType<typeof useSessionActions>["updateSession"];
/**
* Moves a session to the supplied custom group; null removes its custom-group
* assignment.
*/
moveSessionToGroup: ReturnType<typeof useSessionActions>["moveSessionToGroup"];
/** Deletes the session identified by id. */
deleteSession: ReturnType<typeof useSessionActions>["deleteSession"];
/**
* Sets the title of the session identified by id and resolves to the updated
* session.
*/
renameSession: ReturnType<typeof useSessionActions>["renameSession"];
/** Creates a named custom group and resolves to the created group. */
createCustomGroup: (name: string) => Promise<SessionCustomGroup>;
/** Renames the custom group identified by id and resolves to the updated group. */
updateCustomGroup: (id: string, name: string) => Promise<SessionCustomGroup>;
/** Deletes the custom group identified by id. */
deleteCustomGroup: (id: string) => Promise<void>;
/** Available custom session groups. */
customGroups: SessionCustomGroup[];
/** Whether custom session groups are being fetched. */
customGroupsLoading: boolean;
/** Custom-group request error, or undefined when none is recorded. */
customGroupsError?: Error | undefined;
};Related types: ListSessionsGroupBy, SessionCustomGroup, SessionListGroup, SessionListSortBy.
useNavItems
Reads the navigation items supplied by AppCore. Returns an empty array when no navigation context is provided.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
NavItem[]
Navigation items from context as NavItem[].
useRowIndicators
Derives response activity, unread feedback, and an optional status indicator for a session row.
Parameters
| Parameter | Default | Type |
|---|---|---|
session | — | SessionRequired. Session represented by this sidebar row. |
isActive | — | booleanRequired. Whether this row is the currently open session. |
showStatusIndicator | true | booleanWhether to compute a status indicator for the row. |
Returns
| Field | Type |
|---|---|
isGenerating | booleanWhether the session is currently generating a response. |
hasUnread | booleanWhether the session has unread activity; false for the active session. |
statusIndicator | SessionStatusIndicator | nullStatus feedback for the row, or null when disabled or no indicator applies. |
UseRowIndicators
type UseRowIndicators = {
/** Whether the session is currently generating a response. */
isGenerating: boolean;
/** Whether the session has unread activity; false for the active session. */
hasUnread: boolean;
/** Status feedback for the row, or null when disabled or no indicator applies. */
statusIndicator: SessionStatusIndicator | null;
};Related types: SessionStatusIndicator.
SessionSyncBridge
App-shell listener for session events that affect global state outside one page.
| Prop | Default | Type |
|---|---|---|
| — | — | No props. |
SessionUnreadSyncBridge
Keeps SessionStore.unreadSessionIds aligned across tabs and refreshes.
| Prop | Default | Type |
|---|---|---|
| — | — | No props. |
Sessions and background tasks
Read session lists and details, create or update sessions, send messages, stop active work, and inspect background tasks.
| Entry point | Kind |
|---|---|
useSessions | Hook |
useSession | Hook |
useSessionActions | Hook |
useSendSessionMessage | Hook |
useAbortSessionAct | Hook |
useBackgroundTasks | Hook |
useSessionAlert | Hook |
useSessions
Loads a paginated session list using optional filtering, grouping, and ordering parameters.
Parameters
| Parameter | Default | Type |
|---|---|---|
params | — | ListSessionsParamsOptional session-list filters, grouping, ordering, and pagination settings. |
Returns
| Field | Type |
|---|---|
sessions | ReturnType<typeof useSessionStore.getState>["sessions"]Sessions loaded for the current list query. |
sessionGroups | ReturnType<typeof useSessionStore.getState>["sessionGroups"]Server-provided session groups, or null for an ungrouped list. |
loading | booleanWhether the first page is being fetched. |
loadingMore | booleanWhether the next page is being fetched. |
hasMore | booleanWhether another page is available. |
error | Error | undefinedList request error, or undefined when none is recorded. |
refetch | () => Promise<void>Reloads the first page for the current query. |
loadMore | () => Promise<void>Loads the next page when more sessions are available. |
UseSessions
type UseSessions = {
/** Sessions loaded for the current list query. */
sessions: ReturnType<typeof useSessionStore.getState>["sessions"];
/** Server-provided session groups, or null for an ungrouped list. */
sessionGroups: ReturnType<typeof useSessionStore.getState>["sessionGroups"];
/** Whether the first page is being fetched. */
loading: boolean;
/** Whether the next page is being fetched. */
loadingMore: boolean;
/** Whether another page is available. */
hasMore: boolean;
/** List request error, or undefined when none is recorded. */
error?: Error | undefined;
/** Reloads the first page for the current query. */
refetch: () => Promise<void>;
/** Loads the next page when more sessions are available. */
loadMore: () => Promise<void>;
};useSession
Loads details for one session and exposes its cached data and request state.
Parameters
| Parameter | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session to observe or control; undefined selects no session. |
Returns
| Field | Type |
|---|---|
session | Session | undefinedCached session details, falling back to the list entry; undefined when the session is unavailable. |
loading | booleanWhether the session details are being fetched; false without a session id. |
error | Error | undefinedSession-details request error, or undefined when none is recorded. |
refetch | () => Promise<void>Reloads the session details; does nothing without a session id. |
UseSession
type UseSession = {
/**
* Cached session details, falling back to the list entry; undefined when the
* session is unavailable.
*/
session: Session | undefined;
/** Whether the session details are being fetched; false without a session id. */
loading: boolean;
/** Session-details request error, or undefined when none is recorded. */
error?: Error | undefined;
/** Reloads the session details; does nothing without a session id. */
refetch: () => Promise<void>;
};Related types: Session.
useSessionActions
Exposes session creation, updates, grouping, deletion, and renaming actions over WebSocket.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
createSession | (input: CreateSessionInput) => Promise<Session>Creates a session from the supplied input and resolves to the new session. |
updateSession | (id: string, input: UpdateSessionInput) => Promise<Session>Updates the session identified by id and resolves to the updated session. |
moveSessionToGroup | ( id: string, customGroupId: string | null, ) => Promise<Session>Moves a session to the supplied custom group; null removes its custom-group assignment. |
deleteSession | (id: string) => Promise<void>Deletes the session identified by id. |
renameSession | (id: string, title: string) => Promise<Session>Sets the title of the session identified by id and resolves to the updated session. |
UseSessionActions
type UseSessionActions = {
/** Creates a session from the supplied input and resolves to the new session. */
createSession: (input: CreateSessionInput) => Promise<Session>;
/** Updates the session identified by id and resolves to the updated session. */
updateSession: (id: string, input: UpdateSessionInput) => Promise<Session>;
/**
* Moves a session to the supplied custom group; null removes its custom-group
* assignment.
*/
moveSessionToGroup: (id: string, customGroupId: string | null) => Promise<Session>;
/** Deletes the session identified by id. */
deleteSession: (id: string) => Promise<void>;
/**
* Sets the title of the session identified by id and resolves to the updated
* session.
*/
renameSession: (id: string, title: string) => Promise<Session>;
};Related types: CreateSessionInput, Session, UpdateSessionInput.
useSendSessionMessage
Submits a user message to an existing session and starts the agent response.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
send | ( sessionId: string, input: SendSessionMessageInput | string, options?: SendSessionMessageOptions, ) => Promise<void>Creates a user message in the supplied session and starts the agent response; accepts plain text or a structured message input. |
sending | booleanWhether this hook instance is submitting a message; does not represent the full response stream. |
error | Error | undefinedMessage-submission error, or undefined before submission or after the next attempt begins. |
UseSendSessionMessage
type UseSendSessionMessage = {
/**
* Creates a user message in the supplied session and starts the agent response;
* accepts plain text or a structured message input.
*/
send: (
sessionId: string,
input: SendSessionMessageInput | string,
options?: SendSessionMessageOptions,
) => Promise<void>;
/**
* Whether this hook instance is submitting a message; does not represent the full
* response stream.
*/
sending: boolean;
/**
* Message-submission error, or undefined before submission or after the next
* attempt begins.
*/
error: Error | undefined;
};Related types: SendSessionMessageInput, SendSessionMessageOptions.
useAbortSessionAct
Requests cancellation of the active response for one session.
Parameters
| Parameter | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session to observe or control; undefined selects no session. |
Returns
| Field | Type |
|---|---|
abortAct | () => Promise<void>Requests cancellation of the active response; does nothing without a session id. |
aborting | booleanWhether this hook is issuing the abort request; does not wait for the response stream to stop. |
error | Error | undefinedError while issuing the abort request, or undefined when none is recorded. |
UseAbortSessionAct
type UseAbortSessionAct = {
/**
* Requests cancellation of the active response; does nothing without a session id.
*/
abortAct: () => Promise<void>;
/**
* Whether this hook is issuing the abort request; does not wait for the response
* stream to stop.
*/
aborting: boolean;
/** Error while issuing the abort request, or undefined when none is recorded. */
error: Error | undefined;
};useBackgroundTasks
Loads and manages the background tasks belonging to one session.
Parameters
| Parameter | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session to observe or control; undefined selects no session. |
Returns
| Field | Type |
|---|---|
tasks | BackgroundTask[]Background tasks for the selected session; empty without a session id. |
loading | booleanWhether the session task list is being fetched; false without a session id. |
error | Error | undefinedTask-list request error, or undefined when none is recorded. |
refresh | () => Promise<void>Reloads the task list; does nothing without a session id. |
cancel | (taskId: string) => Promise<void>Requests cancellation of the task identified by taskId; does nothing without a session id. |
remove | (taskId: string) => Promise<void>Deletes the task identified by taskId; does nothing without a session id. |
clearFinished | () => Promise<void>Deletes all tasks whose status is not running. |
UseBackgroundTasks
type UseBackgroundTasks = {
/** Background tasks for the selected session; empty without a session id. */
tasks: BackgroundTask[];
/** Whether the session task list is being fetched; false without a session id. */
loading: boolean;
/** Task-list request error, or undefined when none is recorded. */
error?: Error | undefined;
/** Reloads the task list; does nothing without a session id. */
refresh: () => Promise<void>;
/**
* Requests cancellation of the task identified by taskId; does nothing without a
* session id.
*/
cancel: (taskId: string) => Promise<void>;
/** Deletes the task identified by taskId; does nothing without a session id. */
remove: (taskId: string) => Promise<void>;
/** Deletes all tasks whose status is not running. */
clearFinished: () => Promise<void>;
};Related types: BackgroundTask.
useSessionAlert
Resolves the visible alert state for one session detail view.
Parameters
| Parameter | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session to observe or control; undefined selects no session. |
Returns
| Field | Type |
|---|---|
alert | SessionAlertStateAlert for unresolved user intervention or provider-login recovery failure; kind is none when no alert is needed. |
UseSessionAlert
/** Session alert hook return shape. */
export type UseSessionAlert = {
/**
* Alert for unresolved user intervention or provider-login recovery failure; kind
* is none when no alert is needed.
*/
alert: SessionAlertState;
};Related types: SessionAlertState.
Supporting types
SessionAlertState · SessionListSortBy · SessionStatusIndicator.
SessionAlertState
/** Visible session alert state for shell and skin consumers. */
export type SessionAlertState =
| {
kind: "none";
}
| {
kind: "intervention_unavailable";
}
| {
kind: "provider_login_error";
message: string;
};SessionListSortBy
type SessionListSortBy = "createdAt" | "lastActivityAt";SessionStatusIndicator
type SessionStatusIndicator = "need_user_input" | "error";Composer and controls
useComposer owns the draft, attachments, control slots, submission, and stop behavior. Use its contracts to build a visual skin without duplicating that state.
| Entry point | Kind |
|---|---|
useComposer | Hook |
useContextWindowMeter | Hook |
useComposer
Unified composer flow for new and existing sessions. Requires a React Router context to resolve the active session and custom group.
Parameters
| Parameter | Default | Type |
|---|---|---|
options | {} | { submitOptions?: ComposerSubmitOptions | undefined; }Optional submission defaults. Requires a React Router context; sessionId and customGroupId are resolved from the current route. |
Returns
| Field | Type |
|---|---|
disclaimer | { … }Visibility and text of the configured composer disclaimer. |
draft | { … }Draft text and attachments, their editing actions, and submission eligibility. |
input | { … }Controlled textarea value, disabled state, placeholder, and keyboard, paste, and file-drop handlers. |
send | { … }Submission eligibility, busy state, form submit handler, and asynchronous submit action. |
slotControls | ComposerSlotControlsAgent, model, toolhost, context-window, approval, and status controls for custom renderers. |
sessionOptions | { … }Configured session-option components and their editable controls. |
submit | (options?: ComposerSubmitOptions) => Promise<ComposerSubmitResult>Submits the draft using optional overrides; creates a session when needed and resolves to the submission result. |
stop | () => Promise<void>Requests cancellation while a session is generating; does nothing without a session, during another abort, or when no response is generating. |
onStop | MouseEventHandler<HTMLButtonElement>Button click handler that requests cancellation and prevents the default click action. |
aborting | booleanWhether an abort request is being issued. |
isGenerating | booleanWhether the active session is generating a response. |
isBusy | booleanWhether draft submission or message sending is in progress; response generation and aborting have separate flags. |
error | Error | undefinedFirst available error from submission, abort, control state, configuration, or runtime resource loading; undefined when none exists. |
disclaimer
Visibility and text of the configured composer disclaimer.
{ enabled: boolean; text: string }draft
Draft text and attachments, their editing actions, and submission eligibility.
{
text: string;
setText: (value: string) => void;
attachments: File[];
attachmentItems: {
id: string;
file: File;
name: string;
remove: () => void;
preparation: DocumentAttachmentState | undefined;
retry: () => void;
}[];
addAttachments: (files: File[]) => void;
onAttachmentsChange: ChangeEventHandler<HTMLInputElement>;
attachmentsInputProps: {
type: "file";
multiple: boolean;
accept: string;
disabled: boolean;
onChange: ChangeEventHandler<HTMLInputElement>;
};
removeAttachment: (index: number) => void;
resetAttachments: () => void;
reset: () => void;
snapshot: () => { text: string; attachments: File[] };
replace: (snapshot: { text: string; attachments: File[] }) => void;
trimmed: string;
canSubmit: boolean;
}Related types: DocumentAttachmentState.
input
Controlled textarea value, disabled state, placeholder, and keyboard, paste, and file-drop handlers.
{
draftKey: string;
value: string;
revision: number;
setValue: (value: string) => void;
onLiveValueChange: (value: string) => void;
disabled: boolean;
placeholder: string;
onChange: ChangeEventHandler<HTMLTextAreaElement>;
onKeyDown: KeyboardEventHandler<HTMLTextAreaElement>;
onDragOver: DragEventHandler<HTMLElement>;
onDrop: DragEventHandler<HTMLElement>;
onPaste: ClipboardEventHandler<HTMLTextAreaElement>;
props: {
value: string;
disabled: boolean;
placeholder: string;
onChange: ChangeEventHandler<HTMLTextAreaElement>;
onKeyDown: KeyboardEventHandler<HTMLTextAreaElement>;
onDragOver: DragEventHandler<HTMLElement>;
onDrop: DragEventHandler<HTMLElement>;
onPaste: ClipboardEventHandler<HTMLTextAreaElement>;
};
}send
Submission eligibility, busy state, form submit handler, and asynchronous submit action.
{
canSubmit: boolean;
isBusy: boolean;
onSubmit: SubmitEventHandler<HTMLFormElement>;
submit: (options?: ComposerSubmitOptions) => Promise<ComposerSubmitResult>;
}Related types: ComposerSubmitOptions, ComposerSubmitResult.
sessionOptions
Configured session-option components and their editable controls.
{
components: SessionOptionsComponent[];
controls: ComposerSessionOptionControl[];
}Related types: ComposerSessionOptionControl, SessionOptionsComponent.
UseComposer
type UseComposer = ReturnType<typeof useComposer>;useContextWindowMeter
Builds reusable context-window and provider-usage semantic state from a composer slot. Does not own session synchronization.
Parameters
| Parameter | Default | Type |
|---|---|---|
options | — | UseContextWindowMeterOptionsRequired. Context-window slot from useComposer and optional automatic provider-usage refresh. |
UseContextWindowMeterOptions
type UseContextWindowMeterOptions = {
/** Context-window control supplied by useComposer.slotControls. */
slot: ComposerSlotControls["contextWindow"];
/**
* Whether to refresh usage automatically when the provider changes. Defaults to
* false.
*/
refreshProviderUsage?: boolean | undefined;
};Related types: ComposerSlotControls.
Returns
| Field | Type |
|---|---|
view | ContextWindowMeterViewContext-window usage, capacity, and breakdown derived from the supplied slot. |
indicatorModel | ContextWindowIndicatorModel | nullIndicator geometry and labels, or null when usage data or capacity is unavailable. |
planUsageItems | PlanUsageItem[]Provider plan-usage entries available for display. |
shouldShowPlanUsage | booleanWhether a provider is known and usage is loading, has entries, or has an error. |
UseContextWindowMeterResult
type UseContextWindowMeterResult = {
/** Context-window usage, capacity, and breakdown derived from the supplied slot. */
view: ContextWindowMeterView;
/**
* Indicator geometry and labels, or null when usage data or capacity is
* unavailable.
*/
indicatorModel: ContextWindowIndicatorModel | null;
/** Provider plan-usage entries available for display. */
planUsageItems: PlanUsageItem[];
/** Whether a provider is known and usage is loading, has entries, or has an error. */
shouldShowPlanUsage: boolean;
};Related types: ContextWindowIndicatorModel, ContextWindowMeterView, PlanUsageItem.
Supporting types
AgentOption · buildAgentMenu · buildModelMenu · ComposerAgentModeOption · ComposerResourceLink · ComposerSessionOptionControl · ComposerSlotControls · ComposerSlotDisplay · ComposerSubmitOptions · ComposerSubmitResult · ComposerToolhostCategory · ComposerToolhostOption · ComposerToolhostTool · ContextWindowBreakdownItem · ContextWindowBreakdownKey · ContextWindowIndicatorModel · ContextWindowMeterView · ModelGroupOption · ModelOption · ModelSelection · PlanUsageItem · PlanUsageSegment · readModelSelection · SlotRenderer · ThinkOption.
AgentOption
type AgentOption =
| {
type: "agent";
id: string;
name: string;
description?: string | null;
}
| {
type: "separator";
};buildAgentMenu
Build the agent selector dropdown from backend agent_selector.children. Returns an empty menu when the slot or children are missing.
declare function buildAgentMenu(
agentSelectorSlot: ComposerComponent | undefined,
agents: Record<string, ComposerResourceLink>,
): AgentOption[];Related types: AgentOption, ComposerComponent, ComposerResourceLink.
buildModelMenu
Build the nested provider → model menu shown in the model selector.
declare function buildModelMenu(groups: ComposerModelGroup[]): ModelGroupOption[];Related types: ModelGroupOption, ComposerModelGroup.
ComposerAgentModeOption
/** Runtime agent mode projected for composer mode selectors. */
export type ComposerAgentModeOption = AgentMode & {
label: string;
description?: string | undefined;
};Related types: AgentMode.
ComposerResourceLink
type ComposerResourceLink = {
name: string;
description?: string | null;
};ComposerSessionOptionControl
type ComposerSessionOptionControl =
| {
c: "agent_selector";
component: Extract<
SessionOptionsComponent,
{
c: "agent_selector";
}
>;
slot: ComposerSlotControls["agent"];
}
| {
c: "model_selector";
component: Extract<
SessionOptionsComponent,
{
c: "model_selector";
}
>;
slot: ComposerSlotControls["model"];
}
| {
c: "toolhost_selector";
component: Extract<
SessionOptionsComponent,
{
c: "toolhost_selector";
}
>;
slot: ComposerSlotControls["toolhost"];
}
| {
c: "tool_policy_selector";
component: Extract<
SessionOptionsComponent,
{
c: "tool_policy_selector";
}
>;
slot: ComposerSlotControls["approvalPolicy"];
};Related types: ComposerSlotControls, SessionOptionsComponent.
ComposerSlotControls
/** UI controls projected for the independent composer selector components. */
export type ComposerSlotControls = {
agent: {
/** Backend display region for this control. */
display: ComposerSlotDisplay;
value: string;
label: string;
options: ReturnType<typeof buildAgentMenu>;
selectOptions: Array<{
value: string;
label: string;
description?: string;
}>;
setValue: (agentId: string) => Promise<void>;
selectProps: {
value: string;
disabled: boolean;
onChange: ChangeEventHandler<HTMLSelectElement>;
};
};
model: {
/** Backend display region for this control. */
display: ComposerSlotDisplay;
value: ReturnType<typeof readModelSelection>;
label: string;
options: ReturnType<typeof buildModelMenu>;
selectedProvider: ReturnType<typeof buildModelMenu>[number] | undefined;
selectedModel:
| ReturnType<typeof buildModelMenu>[number]["models"][number]
| undefined;
modelOptions: ReturnType<typeof buildModelMenu>[number]["models"];
thinkingOptions: ReturnType<
typeof buildModelMenu
>[number]["models"][number]["thinkingOptions"];
thinkingVisible: boolean;
reasoningSupported: boolean;
attachmentsSupported: boolean;
setValue: (selection: ReturnType<typeof readModelSelection>) => Promise<void>;
setProvider: (provider: string) => Promise<void>;
setModel: (modelId: string, provider?: string | undefined) => Promise<void>;
setThink: (think: string) => Promise<void>;
providerSelectProps: {
value: string;
disabled: boolean;
onChange: ChangeEventHandler<HTMLSelectElement>;
};
modelSelectProps: {
value: string;
disabled: boolean;
onChange: ChangeEventHandler<HTMLSelectElement>;
};
thinkingSelectProps: {
value: string;
disabled: boolean;
onChange: ChangeEventHandler<HTMLSelectElement>;
};
};
toolhost: {
/** Backend display region for this control. */
display: ComposerSlotDisplay;
value: string | null;
selectValue: string;
label: string;
options: ComposerToolhostOption[];
selectOptions: Array<{
value: string;
label: string;
description?: string;
}>;
toolResources: Record<string, ResourceLink>;
toolResourcesLoading: boolean;
loading: boolean;
setValue: (toolhost: string | null) => Promise<void>;
dismissToolhost: (name: string) => void;
selectProps: {
value: string;
disabled: boolean;
onChange: ChangeEventHandler<HTMLSelectElement>;
};
};
contextWindow: {
/** Backend display region for this control. */
display: ComposerSlotDisplay;
/**
* Latest synchronized session context accounting, when session sync is mounted.
*/
contextWindow?: ContextWindowState | null | undefined;
/**
* Selected model context-window capacity used when runtime accounting is
* unavailable.
*/
catalogContextWindow?: number | null | undefined;
provider?: string | undefined;
usageProvider?: string | undefined;
providerUsageResponse?: ProviderUsageResponse | undefined;
providerUsageLoading: boolean;
providerUsageError?: Error | undefined;
refreshProviderUsage: () => Promise<void>;
};
approvalPolicy: {
/** Backend display region for this control. */
display: ComposerSlotDisplay;
value: ApprovalPolicy;
label: string;
modeName: string | null;
modes: ComposerAgentModeOption[];
options: Array<{
value: ApprovalPolicy;
label: string;
description?: string;
}>;
setValue: (policy: string) => Promise<void>;
setMode: (mode: ComposerAgentModeOption) => Promise<void>;
selectProps: {
value: ApprovalPolicy;
disabled: boolean;
onChange: ChangeEventHandler<HTMLSelectElement>;
};
};
status: {
updating: boolean;
error?: Error | undefined;
};
};Related types: ApprovalPolicy, buildAgentMenu, buildModelMenu, ComposerAgentModeOption, ComposerSlotDisplay, ComposerToolhostOption, ContextWindowState, ProviderUsageResponse, readModelSelection, ResourceLink.
ComposerSlotDisplay
type ComposerSlotDisplay =
| "left"
| "right"
| "top-left"
| "top-right"
| "bottom-left"
| "bottom-right"
| "none";ComposerSubmitOptions
/** Per-submit controls for composer routing behavior. */
export type ComposerSubmitOptions = {
/** Skips automatic navigation after a new session is created. */
disableNavigate?: boolean | undefined;
/** Overrides the route used after a new session is created. */
navigateTo?: string | undefined;
};ComposerSubmitResult
/** Result returned by a composer submission attempt. */
export type ComposerSubmitResult = {
submitted: boolean;
session?: Session | undefined;
};Related types: Session.
ComposerToolhostCategory
type ComposerToolhostCategory = "computer" | "server" | "cloud" | "shared";ComposerToolhostOption
/** Toolhost option projected from runtime metadata for composer renderers. */
export type ComposerToolhostOption = ToolhostInfo & {
/** Selectable value passed back to the session update. */
value: string;
/** Default headless label; skins may derive richer labels from metadata. */
label: string;
/** Semantic runtime category for skins that group toolhosts. */
category: ComposerToolhostCategory;
/** False when the runtime reports that the toolhost is no longer connected. */
available: boolean;
/** Tool names enriched with runtime descriptions when available. */
toolItems: ComposerToolhostTool[];
/** Runtime tools known by the agent but not exposed by this toolhost. */
missingTools: ComposerToolhostTool[];
/** Optional secondary text for headless renderers. */
description?: string | null;
};Related types: ComposerToolhostCategory, ComposerToolhostTool, ToolhostInfo.
ComposerToolhostTool
type ComposerToolhostTool = ComposerResourceLink;Related types: ComposerResourceLink.
ContextWindowBreakdownItem
type ContextWindowBreakdownItem = {
key: ContextWindowBreakdownKey;
tokens: number;
};Related types: ContextWindowBreakdownKey.
ContextWindowBreakdownKey
type ContextWindowBreakdownKey =
| "systemPrompt"
| "toolDefinitions"
| "messages"
| "promptOverhead";ContextWindowIndicatorModel
type ContextWindowIndicatorModel = {
progress: number;
percent: number;
resolvedUsedTokens: number;
breakdownItems: ContextWindowBreakdownItem[];
};Related types: ContextWindowBreakdownItem.
ContextWindowMeterView
type ContextWindowMeterView = {
hasData: boolean;
value: number;
usedTokens: number | null;
maxTokens: number | null;
breakdown: ContextWindowBreakdownItem[];
provider?: string | undefined;
};Related types: ContextWindowBreakdownItem.
ModelGroupOption
type ModelGroupOption = {
value: string;
label: string;
models: ModelOption[];
};Related types: ModelOption.
ModelOption
type ModelOption = {
value: string;
label: string;
thinkingOptions: ThinkOption[];
};Related types: ThinkOption.
ModelSelection
type ModelSelection = {
provider: string;
modelId: string;
think: string;
};PlanUsageItem
type PlanUsageItem = {
entityLabel: string;
windowLabel?: string | undefined;
percent: number;
used?: number | null | undefined;
limit?: number | null | undefined;
remainingPercent?: number | null | undefined;
resetAt?: string | null | undefined;
unit?: string | null | undefined;
plan?: string | null | undefined;
status: ProviderUsageStatus;
error?: string | null | undefined;
providerKey: string;
segments: readonly PlanUsageSegment[];
};Related types: PlanUsageSegment, ProviderUsageStatus.
PlanUsageSegment
type PlanUsageSegment = {
label: string;
percent: number;
providerKey: string;
};readModelSelection
Map session agent fields to the UI ModelSelection shape. Normalizes think to composer option values (on/off or effort levels).
declare function readModelSelection(
groups: ComposerModelGroup[],
models: ComposerModel[],
modelId: string,
think: ThinkMode | null | undefined,
chatClientRef: string | null,
): ModelSelection;Related types: ModelSelection, ComposerModel, ComposerModelGroup, ThinkMode.
SlotRenderer
type SlotRenderer<TSlot> = ComponentType<{
slot: TSlot;
disabled?: boolean;
}>;ThinkOption
type ThinkOption = {
value: string;
label: string;
};Timeline and messages
useTimeline provides semantic entries, aggregate status, history controls, and session-scoped background tasks. Render this contract rather than rebuilding the timeline from service state.
| Entry point | Kind |
|---|---|
useTimeline | Hook |
useTimeline
Loads and synchronizes a session's conversation, exposing ordered renderable entries, activity state, history pagination, and background-task controls.
Parameters
| Parameter | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session to observe or control; undefined selects no session. |
Returns
| Field | Type |
|---|---|
entries | readonly TimelineEntry[]Ordered semantic history and live entries ready to render, including messages, tools, and execution feedback. |
status | TimelineStatusInitial-history loading, failure, and empty-state flags, with the history request error when present. |
history | TimelineHistoryAvailability, loading state, and a load action for older responses. |
backgroundTasks | TimelineBackgroundTasksSession-scoped background tasks and their refresh, cancel, remove, and clear-finished actions. |
UseTimeline
type UseTimeline = {
/**
* Ordered semantic history and live entries ready to render, including messages,
* tools, and execution feedback.
*/
entries: readonly TimelineEntry[];
/**
* Initial-history loading, failure, and empty-state flags, with the history request
* error when present.
*/
status: TimelineStatus;
/** Availability, loading state, and a load action for older responses. */
history: TimelineHistory;
/**
* Session-scoped background tasks and their refresh, cancel, remove, and
* clear-finished actions.
*/
backgroundTasks: TimelineBackgroundTasks;
};Related types: TimelineBackgroundTasks, TimelineEntry, TimelineHistory, TimelineStatus.
Supporting types
SendSessionMessageInput · SendSessionMessageOptions · StreamingDraft · StreamingPhase · TimelineBackgroundTasks · TimelineEntry · TimelineHistory · TimelineStatus · ToolCallPair · ToolLabelContext.
SendSessionMessageInput
type SendSessionMessageInput = {
text: string;
attachments?: File[];
draftKey?: string;
};SendSessionMessageOptions
type SendSessionMessageOptions = {
/**
* Overrides automatic naming of untitled sessions with title generation enabled on
* their first message.
*/
generateTitle?: boolean;
};StreamingDraft
/**
* In-progress assistant response accumulated from `session.response.delta` events.
*
* Keyed by act id in `SessionStore.streamingDrafts`.
*/
export type StreamingDraft = {
actId: string;
itemId?: string | null;
content: string;
reasoningActivities?: ReasoningActivity[];
thinking: string;
toolCallArgs: Record<string, string>;
toolCallNames: Record<string, string>;
toolOutputs: Record<string, ToolOutputContent[]>;
phases?: StreamingPhase[];
lastSeq?: number;
};Related types: ReasoningActivity, StreamingPhase, ToolOutputContent.
StreamingPhase
type StreamingPhase =
| {
kind: "thinking";
offset: number;
itemId?: string | null;
seq?: number;
}
| {
kind: "content";
itemId?: string | null;
seq?: number;
}
| {
kind: "tool";
callId: string;
itemId?: string | null;
seq?: number;
};TimelineBackgroundTasks
type TimelineBackgroundTasks = {
/** Background tasks belonging to the session. */
tasks: BackgroundTask[];
/** Whether the session's background-task list is being fetched. */
loading: boolean;
/** Task-list request error, or undefined when none is recorded. */
error?: Error | undefined;
/** Reloads the session's background tasks. */
refresh: () => Promise<void>;
/** Requests cancellation of a task by id. */
cancel: (taskId: string) => Promise<void>;
/** Deletes a task by id. */
remove: (taskId: string) => Promise<void>;
/** Deletes every task whose status is not running. */
clearFinished: () => Promise<void>;
};Related types: BackgroundTask.
TimelineEntry
type TimelineEntry =
| {
id: string;
kind: "user_message";
item: SessionItem;
text: string;
/** Whether this user message is a valid rewind/fork pivot. */
historyActionsAvailable: boolean;
}
| {
id: string;
kind: "assistant_message";
item: SessionItem;
text: string;
/** Whether this is the final assistant message in a completed user turn. */
isLastInTurn: boolean;
}
| {
id: string;
kind: "session_change";
item: SessionItem;
}
| {
id: string;
kind: "compaction";
item: SessionItem;
}
| {
id: string;
kind: "tool_group";
pairs: ToolCallPair[];
toolResources: Record<string, ResourceLink>;
streaming: boolean;
}
| {
id: string;
kind: "draft";
draft: StreamingDraft;
}
| {
id: string;
kind: "thinking";
text: string;
streaming: boolean;
}
| {
id: string;
kind: "streaming_message";
content: string;
}
| {
id: string;
kind: "work_duration";
startedAt?: string | undefined;
hidden?: boolean | undefined;
}
| {
id: string;
kind: "background_task_group";
/** Whether this task was received through a live update in this page lifetime. */
live?: boolean | undefined;
tasks: Array<{
item: SessionItem;
taskId: string;
task?: BackgroundTask | undefined;
}>;
}
| {
id: string;
kind: "background_task_completed";
item: SessionItem;
taskId?: string | undefined;
task?: BackgroundTask | undefined;
}
| {
id: string;
kind: "session_error";
message: string;
}
| {
id: string;
kind: "act_error";
actId: string;
message: string;
}
| {
id: string;
kind: "act_note";
actId: string;
message: string;
};Related types: BackgroundTask, ResourceLink, SessionItem, StreamingDraft, ToolCallPair.
TimelineHistory
type TimelineHistory = {
/** Whether the server has older responses available to fetch. */
hasOlder: boolean;
/** Whether an older-history page is being fetched. */
isLoading: boolean;
/** Requests the next page of older responses. */
loadOlder: () => void;
};TimelineStatus
type TimelineStatus = {
/** Whether initial history is loading and no entries are available yet. */
isLoading: boolean;
/** Whether history loading has failed, after initial loading finishes. */
isError: boolean;
/** Whether there are no entries and neither loading nor error feedback applies. */
isEmpty: boolean;
/** Initial-history request error, or undefined when none is recorded. */
error?: Error | undefined;
};ToolCallPair
type ToolCallPair = {
call: SessionItem;
output?: SessionItem | undefined;
};Related types: SessionItem.
ToolLabelContext
type ToolLabelContext = {
locale?: string;
answeredToolCallIds?: ReadonlySet<string>;
};Human-in-the-loop
useHitl selects the pending request kind; HitlGate and the request-specific hooks expose the controls needed for custom panels.
| Entry point | Kind |
|---|---|
useHitl | Hook |
HitlGate | Component |
useToolInput | Hook |
useToolApproval | Hook |
useAgentAuth | Hook |
useHitl
Selects the pending human-in-the-loop request to display and exposes all pending requests for the session.
Parameters
| Parameter | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session to observe or control; undefined selects no session. |
Returns
| Field | Type |
|---|---|
kind | HitlKind | nullRequest kind to display, prioritizing tool input, tool approval, then agent authentication; null when none is pending. |
requests | HitlRequestsPending requests for all three interaction kinds; each missing request is undefined. |
UseHitl
type UseHitl = {
/**
* Request kind to display, prioritizing tool input, tool approval, then agent
* authentication; null when none is pending.
*/
kind: HitlKind | null;
/**
* Pending requests for all three interaction kinds; each missing request is
* undefined.
*/
requests: HitlRequests;
};Related types: HitlKind, HitlRequests.
HitlGate
Headless HITL gate — exposes the active overlay kind and pending requests.
| Prop | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session whose pending interaction should be rendered; undefined selects no session. |
children | — | (state: HitlGateState) => React.ReactNodeRequired. Render callback receiving the selected interaction kind and pending requests. |
HitlGateProps
type HitlGateProps = {
/**
* Session whose pending interaction should be rendered; undefined selects no
* session.
*/
sessionId: string | undefined;
/** Render callback receiving the selected interaction kind and pending requests. */
children: (state: HitlGateState) => React.ReactNode;
};Related types: HitlGateState.
useToolInput
Exposes the pending tool-input request, freeform or question-based form bindings, and submit and skip actions.
Parameters
| Parameter | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session to observe or control; undefined selects no session. |
Returns
| Field | Type |
|---|---|
request | ToolInputRequiredRequest | undefinedPending tool-input request for the session, or undefined when none is pending. |
agentModeName | string | nullActive agent mode name, or null when the session does not declare one. |
formState | { … }Normalized questions, answers, wizard position, and answer-completeness flags. |
input | { … }Freeform textarea bindings, including controlled props and uncontrolled draftProps. |
form | { … }Submission eligibility and a form handler that prevents default browser submission. |
formActions | { … }Question-answer editing, wizard navigation, and submit actions for the current form. |
submit | (nextAnswer: string, displayAnswer?: string) => Promise<void>Submits the supplied answer for the current request; does nothing without a session id or pending request. |
skip | () => Promise<void>Skips the current input request; does nothing without a session id or pending request. |
submitting | booleanWhether the current request is being submitted or skipped; stale requests do not keep this flag active. |
error | Error | undefinedSubmission or skip error for the current request, or undefined when none exists. |
formState
Normalized questions, answers, wizard position, and answer-completeness flags.
{
questions: InputRequestQuestion[];
contentType: ToolInputContentType;
answers: string[];
getAnswer: (index: number) => string;
step: number;
allAnswered: boolean;
isLastStep: boolean;
continueDisabled: boolean;
}Related types: InputRequestQuestion, ToolInputContentType.
input
Freeform textarea bindings, including controlled props and uncontrolled draftProps.
{
value: string;
setValue: (value: string) => void;
setDraftValue: (value: string) => void;
disabled: boolean;
onChange: ChangeEventHandler<HTMLTextAreaElement>;
props: {
value: string;
disabled: boolean;
onChange: ChangeEventHandler<HTMLTextAreaElement>;
};
draftProps: {
defaultValue: string;
disabled: boolean;
onChange: ChangeEventHandler<HTMLTextAreaElement>;
};
}form
Submission eligibility and a form handler that prevents default browser submission.
{
canSubmit: boolean;
onSubmit: (event: Pick<Event, "preventDefault">) => Promise<void>;
props: { onSubmit: (event: Pick<Event, "preventDefault">) => Promise<void> };
}formActions
Question-answer editing, wizard navigation, and submit actions for the current form.
{
setAnswer: (index: number, value: string) => void;
setAnswerDraft: (index: number, value: string) => void;
setStep: Dispatch<SetStateAction<number>>;
submit: () => Promise<void>;
continue: () => void;
}useToolApproval
Exposes the pending tool-execution approval request and an action to authorize it.
Parameters
| Parameter | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session with the pending approval; undefined makes approve a no-op. |
agentId | — | string | undefinedRequired. Agent whose tool execution is being approved; undefined makes approve a no-op. |
Returns
| Field | Type |
|---|---|
request | ToolExecutionApprovalRequest | undefinedPending tool-execution approval request, or undefined when none is pending. |
approve | (scope?: ToolAuthorizationType) => Promise<void>Approves the current request with the supplied scope, defaulting to "TOOL"; does nothing without sessionId, agentId, or a pending request. |
submitting | booleanWhether approval of the current request is in progress. |
error | Error | undefinedApproval error for the current request, or undefined when none exists. |
useAgentAuth
Reads the pending agent-auth request and exposes the resume handler.
Parameters
| Parameter | Default | Type |
|---|---|---|
sessionId | — | string | undefinedRequired. Session to observe or control; undefined selects no session. |
Returns
| Field | Type |
|---|---|
request | AgentAuthRequiredRequest | undefinedPending agent-authentication request, or undefined when none is pending. |
resume | () => Promise<void>Resumes the response after authentication; does nothing without a session id or pending request. |
submitting | booleanWhether the current authentication request is being resumed. |
error | Error | undefinedResume error for the current request, or undefined when none exists; background authentication polling errors are not reported here. |
Supporting types
HitlGateState · HitlKind · HitlRequests · ToolInputContentType.
HitlGateState
type HitlGateState = {
/** Active HITL overlay kind, or `null` when none is pending. */
kind: HitlKind | null;
hitl: UseHitl;
};Related types: UseHitl, HitlKind.
HitlKind
type HitlKind = "tool_input" | "tool_approval" | "agent_auth";HitlRequests
type HitlRequests = {
/** Pending tool-input request, or undefined when no input is requested. */
toolInput: ToolInputRequiredRequest | undefined;
/** Pending tool-execution approval, or undefined when no approval is requested. */
toolApproval: ToolExecutionApprovalRequest | undefined;
/** Pending agent authentication, or undefined when no authentication is requested. */
agentAuth: AgentAuthRequiredRequest | undefined;
};Related types: AgentAuthRequiredRequest, ToolExecutionApprovalRequest, ToolInputRequiredRequest.
ToolInputContentType
type ToolInputContentType =
| "freeform"
| "singlequestion"
| "structuredquestion"
| "wizard";Knowledge base
Browse and manage documents through the library contract. The sync bridge connects knowledge-base events to shared state.
| Entry point | Kind |
|---|---|
useKnowledgeBaseLibrary | Hook |
KnowledgeBaseSyncBridge | Component |
useKnowledgeBaseLibrary
Loads knowledge-base collections and their documents, and exposes selection, search, upload, retry, and deletion actions.
Parameters
| Parameter | Default | Type |
|---|---|---|
options | {} | { knowledgeBase?: string; query?: string }Optional controlled collection and search-query values. |
Returns
| Field | Type |
|---|---|
knowledgeBases | KnowledgeBaseSummary[]Available knowledge-base collections. |
activeKnowledgeBase | string | undefinedSelected knowledge-base name, or undefined when none is available. |
setActiveKnowledgeBase | (name: string) => voidSelects a collection and persists the selection for subsequent visits. |
documents | KnowledgeBaseDocument[]Documents in the selected collection, including upload and indexing progress and per-document errors. |
loading | booleanWhether collections or the selected collection's documents are being fetched. |
error | Error | undefinedKnowledge-base operation error, or undefined when none is recorded. |
query | stringCurrent document search text. |
setQuery | (query: string) => voidUpdates the search text; queries shorter than two trimmed characters clear the results. |
searchResults | KnowledgeBaseSearchResult[]Results for the active collection and current search query. |
searching | booleanWhether a document search is in progress. |
uploadFiles | (files: File[]) => Promise<void>Uploads files to the active collection and starts indexing synchronization; does nothing without a collection or files. |
retryUpload | (filename: string) => Promise<void>Retries a failed upload using its retained File, or refreshes indexing state if no original file is retained. |
deleteFile | (filename: string) => Promise<void>Deletes the named document from the active collection. |
refresh | () => Promise<void>Reloads documents in the active collection; does nothing without a selected collection. |
UseKnowledgeBaseLibrary
type UseKnowledgeBaseLibrary = {
/** Available knowledge-base collections. */
knowledgeBases: KnowledgeBaseSummary[];
/** Selected knowledge-base name, or undefined when none is available. */
activeKnowledgeBase?: string | undefined;
/** Selects a collection and persists the selection for subsequent visits. */
setActiveKnowledgeBase: (name: string) => void;
/**
* Documents in the selected collection, including upload and indexing progress and
* per-document errors.
*/
documents: KnowledgeBaseDocument[];
/** Whether collections or the selected collection's documents are being fetched. */
loading: boolean;
/** Knowledge-base operation error, or undefined when none is recorded. */
error?: Error | undefined;
/** Current document search text. */
query: string;
/**
* Updates the search text; queries shorter than two trimmed characters clear the
* results.
*/
setQuery: (query: string) => void;
/** Results for the active collection and current search query. */
searchResults: KnowledgeBaseSearchResult[];
/** Whether a document search is in progress. */
searching: boolean;
/**
* Uploads files to the active collection and starts indexing synchronization; does
* nothing without a collection or files.
*/
uploadFiles: (files: File[]) => Promise<void>;
/**
* Retries a failed upload using its retained File, or refreshes indexing state if
* no original file is retained.
*/
retryUpload: (filename: string) => Promise<void>;
/** Deletes the named document from the active collection. */
deleteFile: (filename: string) => Promise<void>;
/**
* Reloads documents in the active collection; does nothing without a selected
* collection.
*/
refresh: () => Promise<void>;
};Related types: KnowledgeBaseDocument, KnowledgeBaseSearchResult, KnowledgeBaseSummary.
KnowledgeBaseSyncBridge
Synchronizes Knowledge Base indexing progress received through the app WebSocket subscription.
| Prop | Default | Type |
|---|---|---|
| — | — | No props. |
Supporting types
DocumentAttachmentState · KnowledgeBaseDocument · KnowledgeBaseDocumentStatus · KnowledgeLibraryQuery · LibraryView.
DocumentAttachmentState
type DocumentAttachmentState = {
status: "uploading" | "ready" | "failed";
progress: number;
file?: FileInfo | undefined;
error?: Error | undefined;
};Related types: FileInfo.
KnowledgeBaseDocument
type KnowledgeBaseDocument = KnowledgeBaseFile & {
/** Current upload or indexing lifecycle state. */
status: KnowledgeBaseDocumentStatus;
/** Upload progress when available; undefined when no upload progress is tracked. */
uploadProgress?: number | undefined;
/** Indexing progress when available; undefined when no indexing progress is tracked. */
indexingProgress?: number | undefined;
/** Upload or indexing failure message, or undefined when none is recorded. */
error?: string | undefined;
/**
* Original browser File retained for retrying an upload, or undefined for
* server-loaded documents.
*/
uploadSource?: File | undefined;
};Related types: KnowledgeBaseDocumentStatus, KnowledgeBaseFile.
KnowledgeBaseDocumentStatus
type KnowledgeBaseDocumentStatus =
| "ready"
| "unindexed"
| "uploading"
| "queued"
| "indexing"
| "failed";KnowledgeLibraryQuery
type KnowledgeLibraryQuery = {
q: string;
indexed: "all" | "indexed" | "unindexed";
sort: "name" | "date" | "size";
page: number;
perPage: number;
};LibraryView
type LibraryView = "list" | "grid";Runtime and resources
Read configuration, models, runtime agents and tools, provider usage, connection state, and available workspaces.
| Entry point | Kind |
|---|---|
useConfig | Hook |
useModelCatalog | Hook |
useRuntimeAgents | Hook |
useRuntimeTools | Hook |
useRuntimeToolhosts | Hook |
useProviderUsage | Hook |
useAllProviderUsage | Hook |
useWebSocketConnection | Hook |
useCloudWorkspaces | Hook |
useConfig
Loads the server configuration and exposes its request state and a forced refresh.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
config | ConfigResponse | nullServer configuration, or null before it has been loaded. |
loading | booleanWhether server configuration is being fetched. |
error | Error | undefinedConfiguration request error, or undefined when none is recorded. |
refresh | () => Promise<ConfigResponse>Forces a configuration reload and resolves to the updated configuration. |
useModelCatalog
Loads the available model catalog as grouped and flattened composer options.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
groups | ComposerModelGroup[]Models organized into the groups exposed by the composer. |
models | ComposerModel[]Flattened model catalog available to composer controls. |
loading | booleanWhether the model catalog is being fetched. |
error | Error | undefinedCatalog request error, or undefined when none is recorded. |
refetch | () => Promise<void>Forces a model-catalog reload. |
UseModelCatalog
type UseModelCatalog = {
/** Models organized into the groups exposed by the composer. */
groups: ComposerModelGroup[];
/** Flattened model catalog available to composer controls. */
models: ComposerModel[];
/** Whether the model catalog is being fetched. */
loading: boolean;
/** Catalog request error, or undefined when none is recorded. */
error?: Error | undefined;
/** Forces a model-catalog reload. */
refetch: () => Promise<void>;
};Related types: ComposerModel, ComposerModelGroup.
useRuntimeAgents
Loads agent resource links and exposes on-demand loading of individual agent details.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
agents | Record<string, ResourceLink>Agent resource links keyed by agent id. |
agentResources | Record<string, AgentResource>Loaded agent details keyed by agent id; an entry is absent until its details have been loaded. |
loading | booleanWhether the agent list is being fetched. |
error | Error | undefinedRuntime-agent request error, or undefined when none is recorded. |
refetch | () => Promise<void>Forces the runtime-agent list to reload. |
getAgent | (agentId: string) => Promise<void>Loads and caches details for the supplied agent id; read the result from agentResources. |
UseRuntimeAgents
type UseRuntimeAgents = {
/** Agent resource links keyed by agent id. */
agents: Record<string, ResourceLink>;
/**
* Loaded agent details keyed by agent id; an entry is absent until its details have
* been loaded.
*/
agentResources: Record<string, AgentResource>;
/** Whether the agent list is being fetched. */
loading: boolean;
/** Runtime-agent request error, or undefined when none is recorded. */
error?: Error | undefined;
/** Forces the runtime-agent list to reload. */
refetch: () => Promise<void>;
/**
* Loads and caches details for the supplied agent id; read the result from
* agentResources.
*/
getAgent: (agentId: string) => Promise<void>;
};Related types: AgentResource, ResourceLink.
useRuntimeTools
Loads runtime tool links for the browser language and exposes a forced reload.
Parameters
| Parameter | Default | Type |
|---|---|---|
enabled | true | booleanWhether to load and observe tools automatically. Manual refetch remains available when false. |
Returns
| Field | Type |
|---|---|
tools | Record<string, ResourceLink>Tool resource links for the browser language, keyed by tool id; empty when disabled or that language has not been loaded. |
loading | booleanWhether tools for the current language are being fetched; false when disabled. |
error | Error | undefinedCurrent-language tool request error, or undefined when disabled or no matching error exists. |
refetch | () => Promise<void>Forces a tool-list reload, even when automatic loading is disabled. |
UseRuntimeTools
type UseRuntimeTools = {
/**
* Tool resource links for the browser language, keyed by tool id; empty when
* disabled or that language has not been loaded.
*/
tools: Record<string, ResourceLink>;
/** Whether tools for the current language are being fetched; false when disabled. */
loading: boolean;
/**
* Current-language tool request error, or undefined when disabled or no matching
* error exists.
*/
error?: Error | undefined;
/** Forces a tool-list reload, even when automatic loading is disabled. */
refetch: () => Promise<void>;
};Related types: ResourceLink.
useRuntimeToolhosts
Loads runtime toolhosts, observes availability changes, and lets the interface dismiss unavailable hosts.
Parameters
| Parameter | Default | Type |
|---|---|---|
enabled | true | booleanWhether to load and observe toolhosts automatically. Manual refetch remains available when false. |
Returns
| Field | Type |
|---|---|
toolhosts | RuntimeToolhostInfo[]Visible runtime toolhosts, excluding unavailable hosts dismissed by this hook instance. |
loading | booleanWhether toolhosts are being fetched; false when disabled. |
error | Error | undefinedToolhost request error, or undefined when disabled or none is recorded. |
refetch | () => Promise<void>Forces a toolhost reload, even when automatic loading is disabled. |
dismissToolhost | (name: string) => voidHides an unavailable toolhost by name; does nothing for unknown or available hosts. |
UseRuntimeToolhosts
type UseRuntimeToolhosts = {
/**
* Visible runtime toolhosts, excluding unavailable hosts dismissed by this hook
* instance.
*/
toolhosts: RuntimeToolhostInfo[];
/** Whether toolhosts are being fetched; false when disabled. */
loading: boolean;
/** Toolhost request error, or undefined when disabled or none is recorded. */
error?: Error | undefined;
/** Forces a toolhost reload, even when automatic loading is disabled. */
refetch: () => Promise<void>;
/**
* Hides an unavailable toolhost by name; does nothing for unknown or available
* hosts.
*/
dismissToolhost: (name: string) => void;
};Related types: RuntimeToolhostInfo.
useProviderUsage
Reads usage for one provider and exposes an explicit refresh action; it does not fetch automatically.
Parameters
| Parameter | Default | Type |
|---|---|---|
provider | — | stringProvider identifier to read; omitted means no provider and refresh does nothing. |
Returns
| Field | Type |
|---|---|
data | ProviderUsageResponse | undefinedLast usage snapshot for the provider, or undefined before usage has been loaded. |
loading | booleanWhether the provider usage request is in progress; false without a provider. |
error | Error | undefinedProvider-usage request error, or undefined when none is recorded. |
refresh | () => Promise<void>Loads usage for the selected provider; does nothing without a provider. This hook does not load automatically. |
UseProviderUsage
type UseProviderUsage = {
/**
* Last usage snapshot for the provider, or undefined before usage has been loaded.
*/
data: ProviderUsageResponse | undefined;
/** Whether the provider usage request is in progress; false without a provider. */
loading: boolean;
/** Provider-usage request error, or undefined when none is recorded. */
error?: Error | undefined;
/**
* Loads usage for the selected provider; does nothing without a provider. This hook
* does not load automatically.
*/
refresh: () => Promise<void>;
};Related types: ProviderUsageResponse.
useAllProviderUsage
Loads aggregate usage across providers and exposes a refresh action.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
data | ProviderUsageResponse | undefinedLast aggregate usage snapshot across providers, or undefined before it has been loaded. |
loading | booleanWhether aggregate provider usage is being fetched. |
error | Error | undefinedAggregate usage request error, or undefined when none is recorded. |
lastUpdatedAt | string | undefinedTimestamp of the last successful usage refresh, or undefined before one succeeds. |
refresh | () => Promise<void>Reloads aggregate provider usage. |
UseAllProviderUsage
type UseAllProviderUsage = {
/**
* Last aggregate usage snapshot across providers, or undefined before it has been
* loaded.
*/
data: ProviderUsageResponse | undefined;
/** Whether aggregate provider usage is being fetched. */
loading: boolean;
/** Aggregate usage request error, or undefined when none is recorded. */
error?: Error | undefined;
/**
* Timestamp of the last successful usage refresh, or undefined before one succeeds.
*/
lastUpdatedAt?: string | undefined;
/** Reloads aggregate provider usage. */
refresh: () => Promise<void>;
};Related types: ProviderUsageResponse.
useWebSocketConnection
Observes the shared WebSocket connection lifecycle and readiness.
Parameters
| Parameter | Default | Type |
|---|---|---|
| — | — | No parameters. |
Returns
| Field | Type |
|---|---|
state | WebSocketConnectionStateCurrent connection lifecycle state, initially idle. |
isReady | booleanWhether the connection state is "ready" and session operations can use it. |
UseWebSocketConnection
type UseWebSocketConnection = {
/** Current connection lifecycle state, initially idle. */
state: WebSocketConnectionState;
/** Whether the connection state is "ready" and session operations can use it. */
isReady: boolean;
};Related types: WebSocketConnectionState.
useCloudWorkspaces
Loads Cloud workspaces when enabled and exposes the selected workspace and selection action.
Parameters
| Parameter | Default | Type |
|---|---|---|
enabled | — | booleanRequired. Whether Cloud workspace loading is enabled; false clears the workspace list. |
Returns
| Field | Type |
|---|---|
workspaces | CloudWorkspace[]Available Cloud workspaces; empty when loading is disabled or fails. |
selectedWorkspaceId | string | undefinedSelected workspace id, or undefined when no selection exists. |
selectedWorkspace | CloudWorkspace | undefinedSelected workspace from the loaded list, or undefined when its id is absent or no longer listed. |
setSelectedWorkspaceId | (workspaceId?: string | undefined) => voidSelects a workspace by id; undefined clears the selection. |
loading | booleanWhether Cloud workspaces are being fetched. |
error | Error | undefinedWorkspace request error, or undefined when none is recorded. |
refresh | () => Promise<CloudWorkspace[]>Reloads workspaces; clears the list and resolves to an empty array when disabled. |
Supporting types
ComposerModel · ComposerModelCapabilities · ComposerModelGroup · RuntimeToolhostInfo.
ComposerModel
/**
* UI projection of {@link CatalogModel} — identity, protocol, and selector
* capabilities.
*/
export type ComposerModel = Pick<
CatalogModel,
"modelId" | "displayName" | "provider" | "protocol" | "contextWindow"
> & {
capabilities?: ComposerModelCapabilities | null;
};Related types: CatalogModel, ComposerModelCapabilities.
ComposerModelCapabilities
/** UI-facing capability subset of {@link ModelCapabilityFlags}. */
export type ComposerModelCapabilities = Pick<
ModelCapabilityFlags,
"reasoning" | "image" | "reasoningLevels"
>;Related types: ModelCapabilityFlags.
ComposerModelGroup
/** UI projection of {@link ChatClientModelGroup}. */
export type ComposerModelGroup = Pick<
ChatClientModelGroup,
"chatClientRef" | "catalogProvider" | "usageProvider"
> & {
models: ComposerModel[];
};Related types: ChatClientModelGroup, ComposerModel.
RuntimeToolhostInfo
type RuntimeToolhostInfo = ToolhostInfo & {
/** False when a previously known toolhost has detached from the runtime. */
available: boolean;
};Related types: ToolhostInfo.