cloudflare / cloudflare/agents

useAgent ready resolves on the identity frame, before the initial state frame

Open
#2,268 0 comments 0 reactions 1 assignee Claimed by @threepointone View on GitHub
bug
Dominant language
TypeScript
Stars
5.6k
Forks
711
Avg merge
1d 20h
Merged PRs (30d)
53

Description

## Problem

The connect sequence sends `cf_agent_identity` and then a separate `cf_agent_state` frame. `AgentClient` and `useAgent` resolve `ready` (and flip `identified`) when the identity frame arrives, so a caller that awaits `ready` on a host with stored state can observe `state === undefined` for one message event before the state frame is handled. In React this is one extra render with the default state.

This has always been Agent's behaviour. Since #2257 the `WebSockets` capability owns the connect sequence for every host, so a plain host has it too. Flagged by Devin on #2257 (`packages/agents/src/websockets/websockets.ts`, `sendIdentity`/`sendState`).

## Options

1. Carry the initial state inside the identity frame, so one frame resolves `ready` with state already set. Cleanest; changes the identity frame shape for every client.
2. Add a flag to the identity frame saying a state frame follows, and have the client hold `ready` until it lands. Needs care so a stateless host, or one whose state is `undefined`, never waits forever.

Either way this is a wire change that has to land in `client.ts`, `react.tsx`, and the capability together, with the React and workers suites updated to the new ordering guarantee.

## Where

- `packages/agents/src/websockets/websockets.ts`: `#connect`, `sendIdentity`, `sendState`
- `packages/agents/src/client.ts`, `packages/agents/src/react.tsx`: identity handling and `_resolveReady`

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.