Repository navigation
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.
-
packages/frontend/src/hooks/useWebSocket.tsopens the browser WebSocket, handles server messages, updates stores, and exposes send helpers. -
packages/frontend/src/services/websocketManager.tsserializes/deserializes messages, enforces max outbound size, maps close codes, calculates backoff, and builds resume payloads. -
packages/frontend/src/services/rateLimiter.tschecks and increments hourly/daily counters. -
packages/frontend/src/services/errorRecovery.tsdefines retry and token-timeout helpers. -
packages/frontend/src/services/cognitoAuth.tsfetches Cognito guest credentials and builds a SigV4 presigned WebSocket URL. -
packages/frontend/src/types/messages.tsdefines client/server message TypeScript unions. -
packages/infra/lib/handlers/websocket-handler.tshandles API Gateway WebSocket$connect,$disconnect, and$defaultroutes.
Frontend:
useWebSocket({ url, sessionId, enabled = true }: UseWebSocketOptions)serialize(message: ClientMessage): stringdeserialize(raw: string): ServerMessagecalculateBackoffDelay(attempt: number): numberbuildSessionResumePayload(sessionId: string, actorId: string, lastReceivedTurnIndex: number)mapCloseCodeToState(code: number): SessionState | nullcheckRateLimit(counters: RateLimitState): RateLimitResultincrementCounters(counters: RateLimitState): RateLimitStatecreateErrorRecovery(options?: ErrorRecoveryOptions): ErrorRecoveryisCredentialExpired(expiration: Date): booleangetGuestCredentials(identityPoolId: string, client?: CognitoIdentityClient): Promise<GuestCredentials>generatePresignedWsUrl(credentials: GuestCredentials, endpoint: string, region: string, stage = 'production'): Promise<string>
Backend:
handler: APIGatewayProxyWebsocketHandlerV2
types/messages.ts defines client messages:
session_startuser_messageinterruptsession_resumesession_end
Server messages:
-
connection_ackwithagentCoreSessionId agent_tokenagent_turn_complete-
session_state_changewithpreviousState,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
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:
-
1000and1001to no state change. -
4000toENDED. -
4001toBUDGET_CAPPED. -
4002toRATE_LIMITED. -
4008toSIGNAL_LOST. -
4500toERROR. - 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.
- Frontend and backend response payloads do not currently line up. The frontend expects
connection_ack.payload.agentCoreSessionId, but the Lambda sendsconnection_ack.payload.sessionId. The frontend expectssession_state_change.payload.newState, but the Lambda sendspayload.state. The Lambda's defaultagent_turn_completepayload contains onlyturnIndex, while the frontend expectsfullText, token counts, and turn totals. -
useWebSocketdoes not currently callcreateErrorRecovery(),checkRateLimit(),getGuestCredentials(), orgeneratePresignedWsUrl(). - 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
TextInputallows up to 2,000 characters by default, while the Lambda rejectsuser_messagetext over 500 characters.
- Concept-Cloud-Only-Inference
- Concept-Budget-Ceiling
- Concept-Personality-Gate
- Concept-IP-And-Legal-Posture
- Concept-Supply-Chain-Discipline
- Concept-Graceful-Degradation
- Concept-Observability
- Concept-Testing-And-TDD
- Concept-Credential-Hygiene
Editing in the browser? Wiki edits are live and bypass wiki:lint. Read
Guide-Wiki-Contributing first.