Skip to content

Component WebSocket Transport

Reese Hodge edited this page Nov 19, 2026 · 4 revisions

Component WebSocket Transport

Branch qualification (2026-11-15): the Lambda handler cited below has been removed on the architecture-review branch; its source is pinned to the earlier plan revision. Source-Agent-Infra-Deployment-Review records the remaining migration, not a working deployed replacement.

The WebSocket transport is split between frontend serialization/hook code and an infra Lambda handler. The frontend hook is wired into Component-Frontend-App; the Cognito presigning, rate limiter, and error-recovery services exist but are not currently used by useWebSocket.ts. Message shapes should be compared with Contract-WebSocket-API and Contract-Message-Protocol.

The guest-credential helper describes existing, unwired code, not the constitution v1.5.0 access target. Spend-bearing actions require verified, allowlisted sign-in; spec 003 supersedes spec 001's guest access contract.

Files

  • packages/frontend/src/hooks/useWebSocket.ts opens the browser WebSocket, handles server messages, updates stores, and exposes send helpers.
  • packages/frontend/src/services/websocketManager.ts serializes/deserializes messages, enforces max outbound size, maps close codes, calculates backoff, and builds resume payloads.
  • packages/frontend/src/services/rateLimiter.ts checks and increments hourly/daily counters.
  • packages/frontend/src/services/errorRecovery.ts defines retry and token-timeout helpers.
  • packages/frontend/src/services/cognitoAuth.ts fetches Cognito guest credentials and builds a SigV4 presigned WebSocket URL.
  • packages/frontend/src/types/messages.ts defines client/server message TypeScript unions.
  • packages/infra/lib/handlers/websocket-handler.ts handles API Gateway WebSocket $connect, $disconnect, and $default routes.

Exported functions and types

Frontend:

  • useWebSocket({ url, sessionId, enabled = true }: UseWebSocketOptions)
  • serialize(message: ClientMessage): string
  • deserialize(raw: string): ServerMessage
  • calculateBackoffDelay(attempt: number): number
  • buildSessionResumePayload(sessionId: string, actorId: string, lastReceivedTurnIndex: number)
  • mapCloseCodeToState(code: number): SessionState | null
  • checkRateLimit(counters: RateLimitState): RateLimitResult
  • incrementCounters(counters: RateLimitState): RateLimitState
  • createErrorRecovery(options?: ErrorRecoveryOptions): ErrorRecovery
  • isCredentialExpired(expiration: Date): boolean
  • getGuestCredentials(identityPoolId: string, client?: CognitoIdentityClient): Promise<GuestCredentials>
  • generatePresignedWsUrl(credentials: GuestCredentials, endpoint: string, region: string, stage = 'production'): Promise<string>

Backend:

  • handler: APIGatewayProxyWebsocketHandlerV2

Message ownership

types/messages.ts defines client messages:

  • session_start
  • user_message
  • interrupt
  • session_resume
  • session_end

Server messages:

  • connection_ack with agentCoreSessionId
  • agent_token
  • agent_turn_complete
  • session_state_change with previousState, newState, reason, and optional in-character message
  • error

useWebSocket updates stores as follows:

  • connection_ack -> useConnectionStore.setConnected(sessionId, msg.payload.agentCoreSessionId)
  • agent_token -> useConversationStore.appendToken(token)
  • agent_turn_complete -> setFullText(fullText), update counters, advanceTurn()
  • session_state_change -> setSessionState(newState)
  • error -> no action today beyond a comment

Runtime details

serialize() rejects outbound messages over 32_768 bytes. deserialize() rejects invalid JSON, missing type, and unknown server message types.

calculateBackoffDelay() returns exponential delays of 1s, 2s, then capped at 4s.

mapCloseCodeToState() maps:

  • 1000 and 1001 to no state change.
  • 4000 to ENDED.
  • 4001 to BUDGET_CAPPED.
  • 4002 to RATE_LIMITED.
  • 4008 to SIGNAL_LOST.
  • 4500 to ERROR.
  • anything else to SIGNAL_LOST.

The Lambda handler accepts known client message types, validates non-empty user_message.payload.text, and enforces MAX_MESSAGE_LENGTH = 500 characters. It posts response frames through ApiGatewayManagementApiClient.

Gotchas

  • Frontend and backend response payloads do not currently line up. The frontend expects connection_ack.payload.agentCoreSessionId, but the Lambda sends connection_ack.payload.sessionId. The frontend expects session_state_change.payload.newState, but the Lambda sends payload.state. The Lambda's default agent_turn_complete payload contains only turnIndex, while the frontend expects fullText, token counts, and turn totals.
  • useWebSocket does not currently call createErrorRecovery(), checkRateLimit(), getGuestCredentials(), or generatePresignedWsUrl().
  • The cleanup path closes the socket with code 1000; the close handler treats no mapped state as eligible for reconnect while retries remain, so normal cleanup can schedule reconnect unless the component lifecycle prevents it.
  • Frontend TextInput allows up to 2,000 characters by default, while the Lambda rejects user_message text over 500 characters.

Clone this wiki locally