@ttt-productions/chat-react 0.13.16 → 0.13.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/context/ChatNameResolverContext.d.ts +0 -23
- package/dist/context/ChatNameResolverContext.d.ts.map +1 -1
- package/dist/context/ChatNameResolverContext.js +0 -16
- package/dist/context/ChatNameResolverContext.js.map +1 -1
- package/dist/hooks/useChatMessages.d.ts +0 -4
- package/dist/hooks/useChatMessages.d.ts.map +1 -1
- package/dist/hooks/useChatMessages.js +0 -10
- package/dist/hooks/useChatMessages.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -3
- package/dist/index.js.map +1 -1
- package/dist/realtime/channel-client.d.ts +0 -248
- package/dist/realtime/channel-client.d.ts.map +1 -1
- package/dist/realtime/channel-client.js +5 -432
- package/dist/realtime/channel-client.js.map +1 -1
- package/dist/realtime/diagnostics.d.ts +0 -62
- package/dist/realtime/diagnostics.d.ts.map +1 -1
- package/dist/realtime/diagnostics.js +4 -89
- package/dist/realtime/diagnostics.js.map +1 -1
- package/dist/realtime/inbox-client.d.ts +0 -71
- package/dist/realtime/inbox-client.d.ts.map +1 -1
- package/dist/realtime/inbox-client.js +0 -98
- package/dist/realtime/inbox-client.js.map +1 -1
- package/dist/realtime/initial-load-budget.d.ts +1 -16
- package/dist/realtime/initial-load-budget.d.ts.map +1 -1
- package/dist/realtime/initial-load-budget.js +1 -20
- package/dist/realtime/initial-load-budget.js.map +1 -1
- package/dist/realtime/map.d.ts +0 -26
- package/dist/realtime/map.d.ts.map +1 -1
- package/dist/realtime/map.js +0 -33
- package/dist/realtime/map.js.map +1 -1
- package/dist/realtime/shared.d.ts +0 -78
- package/dist/realtime/shared.d.ts.map +1 -1
- package/dist/realtime/shared.js +2 -76
- package/dist/realtime/shared.js.map +1 -1
- package/dist/realtime/socket.d.ts +0 -15
- package/dist/realtime/socket.d.ts.map +1 -1
- package/dist/realtime/socket.js +0 -4
- package/dist/realtime/socket.js.map +1 -1
- package/dist/realtime/transport.d.ts +0 -23
- package/dist/realtime/transport.d.ts.map +1 -1
- package/dist/realtime/transport.js +0 -13
- package/dist/realtime/transport.js.map +1 -1
- package/dist/realtime/useRealtimeChatMessages.d.ts +0 -17
- package/dist/realtime/useRealtimeChatMessages.d.ts.map +1 -1
- package/dist/realtime/useRealtimeChatMessages.js +0 -22
- package/dist/realtime/useRealtimeChatMessages.js.map +1 -1
- package/dist/realtime/wire.d.ts +0 -56
- package/dist/realtime/wire.d.ts.map +1 -1
- package/dist/realtime/wire.js +0 -16
- package/dist/realtime/wire.js.map +1 -1
- package/dist/types.d.ts +0 -39
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +0 -3
- package/dist/types.js.map +1 -1
- package/dist/ui/ChatShell.d.ts +0 -42
- package/dist/ui/ChatShell.d.ts.map +1 -1
- package/dist/ui/ChatShell.js +4 -41
- package/dist/ui/ChatShell.js.map +1 -1
- package/dist/ui/Composer.d.ts +0 -13
- package/dist/ui/Composer.d.ts.map +1 -1
- package/dist/ui/Composer.js +0 -13
- package/dist/ui/Composer.js.map +1 -1
- package/dist/ui/MessageItemDefault.d.ts +0 -5
- package/dist/ui/MessageItemDefault.d.ts.map +1 -1
- package/dist/ui/MessageItemDefault.js +2 -34
- package/dist/ui/MessageItemDefault.js.map +1 -1
- package/dist/ui/MessageList.d.ts +0 -24
- package/dist/ui/MessageList.d.ts.map +1 -1
- package/dist/ui/MessageList.js +4 -14
- package/dist/ui/MessageList.js.map +1 -1
- package/dist/ui/MessageText.d.ts +0 -13
- package/dist/ui/MessageText.d.ts.map +1 -1
- package/dist/ui/MessageText.js.map +1 -1
- package/dist/ui/SenderName.d.ts +0 -5
- package/dist/ui/SenderName.d.ts.map +1 -1
- package/dist/ui/SenderName.js +0 -5
- package/dist/ui/SenderName.js.map +1 -1
- package/dist/ui/menus.d.ts +0 -2
- package/dist/ui/menus.d.ts.map +1 -1
- package/dist/ui/menus.js +6 -10
- package/dist/ui/menus.js.map +1 -1
- package/package.json +10 -10
- package/src/styles/chat.css +2 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel-client.js","sourceRoot":"","sources":["../../src/realtime/channel-client.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,kFAAkF;AAClF,8EAA8E;AAC9E,EAAE;AACF,iCAAiC;AACjC,iFAAiF;AACjF,4DAA4D;AAC5D,mFAAmF;AACnF,kEAAkE;AAClE,gDAAgD;AAChD,+DAA+D;AAC/D,wFAAwF;AACxF,2EAA2E;AAC3E,oFAAoF;AACpF,EAAE;AACF,oFAAoF;AAEpF,OAAO,EACL,yBAAyB,GAE1B,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,6BAA6B,EAC7B,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,UAAU,EACV,UAAU,EACV,eAAe,GAIhB,MAAM,WAAW,CAAC;AAUnB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,cAAc,EACd,sBAAsB,EACtB,cAAc,GAEf,MAAM,UAAU,CAAC;AAElB,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,6BAA6B,IAAI,IAAI,GAGtC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACnB,yBAAyB,EACzB,uBAAuB,EACvB,2BAA2B,EAC3B,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AA0H7D,MAAM,OAAO,GAAuB;IAClC,MAAM,EAAE,MAAM;IACd,QAAQ,EAAE,EAAE;IACZ,MAAM,EAAE,EAAE;IACV,QAAQ,EAAE,EAAE;IACZ,eAAe,EAAE,KAAK;IACtB,QAAQ,EAAE,IAAI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AE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC,CAAC;IACxF,CAAC;CACF;AAED,SAAS,SAAS,CAAC,CAAgB,EAAE,CAAgB;IACnD,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,EAAE,GAAG,EAAE,CAAC;IAC9B,OAAO,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC;AACnC,CAAC","sourcesContent":["// The Channel realtime client: ONE WebSocket to a single channel DO, driving the\n// Contract C wire protocol. Framework-neutral (a plain observable store the React\n// hook subscribes to) so it is unit-testable with a mock socket and no React.\n//\n// Responsibilities (Contract C):\n// - connect via subprotocol auth (grant offered by the injected grantProvider)\n// - receive versioned `message` frames; server owns `seq`\n// - optimistic send keyed by clientMessageId, reconciled on the server `ack` seq\n// - explicit read acks (delivery != read; focus signals \"read\")\n// - typing (>= 2s coalesced per the V1 limit)\n// - presence-subscribe/-unsubscribe + a 20s client heartbeat\n// - reconnect (realtime-core controller) with a resume cursor -> snapshot then deltas\n// - history pagination over the socket (page <= 50, epoch-aware via seq)\n// - error codes incl. 4401 AUTH_EXPIRED -> re-mint a grant ONCE via grantProvider\n//\n// Timers are injected (setTimeout/clearTimeout/now) so tests run deterministically.\n\nimport {\n createReconnectController,\n type ReconnectController,\n} from '@ttt-productions/realtime-core';\nimport type { ChatMessageV1 } from '@ttt-productions/chat-core';\nimport {\n CLIENT_KINDS,\n CHAT_CLOSE_CODES,\n ChatSendRejectedPayloadSchema,\n HEARTBEAT_MS,\n TYPING_COALESCE_MS,\n HISTORY_PAGE_MAX,\n} from '@ttt-productions/chat-schemas';\nimport {\n buildFrame,\n parseFrame,\n isInboxSnapshot,\n type WireMessageRow,\n type WireChannelSnapshot,\n type RevisionKind,\n} from './wire.js';\nimport type {\n ChatHistoryPayload,\n ChatReadAckPayload,\n ChatResumePayload,\n ChatSendPayload,\n ClientFrameKind,\n ChatSendRejectionCode,\n} from '@ttt-productions/chat-schemas';\nimport type { RealtimeSocket, SocketFactory } from './socket.js';\nimport {\n wireRowToMessage,\n optimisticMessage,\n seqToMessageId,\n applyModerationOverlay,\n overlayFromRow,\n type ModerationOverlay,\n} from './map.js';\nimport type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';\nimport {\n createDiagnosticsEmitter,\n safeDiagnosticLabel,\n CHAT_CLIENT_DIAGNOSTIC_EVENTS as DIAG,\n type ChatClientDiagnosticsEmitter,\n type ChatClientDiagnosticsOption,\n} from './diagnostics.js';\nimport {\n defaultTimers,\n isChatAccessDeniedError,\n isTerminalErrorCode,\n TERMINAL_ERROR_CODE,\n MAX_PENDING_SEND_ATTEMPTS,\n PENDING_SEND_MAX_AGE_MS,\n SERVER_RETRYABLE_MAX_AGE_MS,\n SEND_RETRY_MIN_DELAY_MS,\n SEND_RETRY_MAX_DELAY_MS,\n} from './shared.js';\nimport { InitialLoadBudget } from './initial-load-budget.js';\n\n/**\n * The payload of each frame this client sends, typed by the chat-schemas payload the Worker parses\n * it with, so a sender that drifts from the contract fails to compile. A frame with no payload\n * schema (typing, presence, heartbeat) carries an empty object.\n */\ntype ChannelFramePayload<K extends ClientFrameKind> = K extends typeof CLIENT_KINDS.SEND\n ? ChatSendPayload\n : K extends typeof CLIENT_KINDS.READ_ACK\n ? ChatReadAckPayload\n : K extends typeof CLIENT_KINDS.HISTORY\n ? ChatHistoryPayload\n : K extends typeof CLIENT_KINDS.RESUME\n ? ChatResumePayload\n : Record<string, never>;\n\n/** An un-acked send tracked for reconnect resend (clientMessageId idempotency). */\ninterface PendingSend {\n clientMessageId: string;\n text: string;\n /** When the send was first attempted (for the age/budget caps). Reset by retrySend(). */\n sentAt: number;\n /** How many times it has been (re)sent over a socket. Reset by retrySend(). */\n attempts: number;\n /** True once the attempt/age/budget cap flipped this send to the visible failed\n * state. A failed entry is RETAINED (not deleted) so retrySend() can re-queue it\n * with the SAME clientMessageId; it is skipped by the automatic reconnect resend. */\n failed: boolean;\n /**\n * Set true once the Worker has declared THIS send retryable — either a correlated\n * `send-rejected` (retryable) frame or the legacy uncorrelated\n * `error{code:'membership-pending'}`. A server-retryable send is governed by the\n * {@link SERVER_RETRYABLE_MAX_AGE_MS} wall-clock budget and is NEVER failed by the\n * generic {@link MAX_PENDING_SEND_ATTEMPTS} cap (that cap stays for blind reconnect\n * resends of sends the server has said nothing about).\n */\n serverRetryable: boolean;\n /** The most recent server rejection code, recorded so a budget-exhausted failure\n * can surface the reason (and keep a retry affordance for the transient class). */\n lastRejectionCode?: ChatSendRejectionCode;\n /** The single per-send resend timer for a correlated retryable rejection (never\n * stacks — a newer rejection clears it first; cleared on ack/echo/manual\n * retry/terminal/close/dispose). */\n retryTimer: ReturnType<TransportTimers['setTimeout']> | null;\n}\n\nexport interface ChannelClientState {\n status: RealtimeStatus;\n /** Ordered ascending by seq; optimistic messages (no seq yet) sort to the tail. */\n messages: ChatMessageV1[];\n /** uids currently typing (cleared after ~TYPING_COALESCE_MS of silence). */\n typing: string[];\n /** uids the DO reports online (presence). Empty until presence-subscribe. */\n presence: string[];\n /** True while an older-history page request is in flight. */\n isFetchingOlder: boolean;\n /** False once a history page returns fewer than the requested limit (reached the head). */\n hasOlder: boolean;\n /** The last structured error code the DO sent (e.g. 'blocked-word', 'too-long', flood reason). */\n lastErrorCode: string | null;\n /**\n * True once the FIRST authoritative chat data has been applied — a non-resync\n * resume snapshot, OR the first history page (INCLUDING an empty one). Drives the\n * hook's `isInitialLoading` so the shell shows an honest \"Opening chat…\" state\n * while the first data is loading, and a real empty-chat surface only after an\n * authoritative empty result. NEVER inferred from `messages.length === 0` (an\n * empty first history page IS a successful load). Once true it stays true — a\n * later disconnect/reconnect keeps loaded messages mounted, not a re-loader.\n * A grant retry / socket open before any snapshot leaves it false.\n */\n hasLoadedInitialData: boolean;\n /**\n * True once the first open has failed for good enough to say so: attempts have kept\n * failing for {@link CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS} without any initial data, or\n * reconnecting stopped (gave up, or the socket was revoked) before any. The client keeps\n * retrying in the background; the first authoritative data, or a manual `retryNow()`,\n * clears it. Never true once initial data has loaded — a later outage keeps the loaded\n * messages under the reconnect banner instead.\n */\n initialLoadFailed: boolean;\n /**\n * True while the channel is CURRENT: the socket is open, initial data has loaded, and the\n * authoritative state has been re-applied since this socket opened — a non-resync resume\n * snapshot, or the history page answering a resync. Cleared the moment the socket closes,\n * reconnects, or is denied, and false again on every new socket until its resume lands, so a\n * consumer that must act on the conversation's current terms (an agreement, an offer) waits for\n * it. Unlike `hasLoadedInitialData` it is never sticky.\n */\n isSynced: boolean;\n}\n\nexport interface ChannelClientConfig {\n /** WebSocket endpoint base, e.g. `wss://chat.example.com`. The client appends `/channel`. */\n endpoint: string;\n /** The logical thread id the UI keys on (used as ChatMessageV1.threadId). */\n threadId: string;\n /** The authenticated uid (sender identity for optimistic echoes + auth-switch guard). */\n currentUserId: string;\n /** Mints/refreshes a channel grant. Called on connect and once on a 4401 re-grant. */\n grantProvider: GrantProvider;\n socketFactory: SocketFactory;\n timers?: TransportTimers;\n /** Reconnect backoff tuning (forwarded to realtime-core). */\n reconnect?: {\n baseDelayMs?: number;\n maxDelayMs?: number;\n maxAttempts?: number | null;\n random?: () => number;\n };\n /**\n * OPT-IN structured client diagnostics (default OFF — absent/`false` changes\n * nothing and costs one nullish check per decision point). `true` emits one\n * `console.debug` line per decision with a stable `chat_client_*` event name\n * and a compact, content-free JSON payload; a function routes those entries\n * into the app's own logger instead. Never logs message text, captions,\n * filenames, URLs, tokens, or previews — ids, seqs, states, counts, and codes\n * only. See `./diagnostics.ts`.\n */\n diagnostics?: ChatClientDiagnosticsOption;\n}\n\nconst INITIAL: ChannelClientState = {\n status: 'idle',\n messages: [],\n typing: [],\n presence: [],\n isFetchingOlder: false,\n hasOlder: true,\n lastErrorCode: null,\n hasLoadedInitialData: false,\n initialLoadFailed: false,\n isSynced: false,\n};\n\n/**\n * Retryable error-frame code the channel DO sends when a send arrives BEFORE the\n * member row has synced through the async backend→worker pipeline (a just-created\n * invite/channel). The socket stays open; the client re-sends after `retryAfterMs`\n * through the normal resendPendingSends machinery (same caps). The string is part\n * of the wire contract with the worker runtime's send handler.\n */\nconst MEMBERSHIP_PENDING_CODE = 'membership-pending';\n\n/** Why a history page was requested: to re-page after a resync, or for older messages. */\ntype HistoryRequestKind = 'resync' | 'older';\n/** Fallback retry delay when the frame omits/breaks `retryAfterMs`. */\nconst MEMBERSHIP_PENDING_DEFAULT_RETRY_MS = 2000;\n\n/**\n * Dead-socket watchdog: how long inbound silence may last before this client\n * treats the socket as dead and closes it locally.\n *\n * CHANNEL-ONLY, and this is why it is sound here: the channel DO answers every\n * 20 s client `heartbeat` through the hibernation AUTO-RESPONSE API, so a healthy\n * channel socket is NEVER silent for a full heartbeat window. Inbound silence past\n * this threshold is therefore provable death (a half-open TCP connection whose\n * `onclose` never fires), not idleness. The INBOX socket has no such auto-response\n * and a healthy idle inbox is legitimately silent for hours — applying this rule\n * there would endlessly reconnect healthy sockets, so it is deliberately absent\n * from `inbox-client.ts`.\n *\n * PRIVATE CLIENT POLICY, not a wire constant: nothing on the worker side agrees to\n * it, so it does not belong in `@ttt-productions/chat-schemas` or in this package's\n * exported surface. The check rides the existing 20 s heartbeat tick (no second\n * timer), so detection lands on the NEXT tick after the deadline rather than at\n * exactly 50 s — intended: 2.5 missed windows is unambiguous, and it costs no\n * extra timer.\n */\nconst INBOUND_SILENCE_LIMIT_MS = 50_000;\n\n/**\n * Close code used for the watchdog's LOCAL close. A browser `WebSocket.close()`\n * accepts only 1000 or 3000–4999, and the private 4xxx range is the chat wire's\n * (`CHAT_CLOSE_CODES`) — a client-invented code there could collide with a future\n * server code. 1000 keeps the close frame valid and, being neither 4401 nor 4403,\n * routes through `onClose`'s ordinary transient path, which owns reconnect,\n * backoff, and resume. The reason string + the liveness diagnostic are what\n * identify it.\n */\nconst WATCHDOG_CLOSE_CODE = 1000;\n\nexport class ChannelClient {\n private readonly timers: TransportTimers;\n private readonly controller: ReconnectController;\n private socket: RealtimeSocket | null = null;\n private state: ChannelClientState = INITIAL;\n private readonly listeners = new Set<(s: ChannelClientState) => void>();\n\n /** Resume cursor: highest seq we've durably applied. Sent on resume after reconnect. */\n private resumeSeq = 0;\n /** Last read-ack the UI requested; re-sent on reconnect so a drop during a closed\n * socket window is recovered (M2). */\n private lastReadAck: { readSeq: number; focused: boolean } | null = null;\n /** True after a `4401` re-grant has been attempted for the CURRENT connect cycle (once-only). */\n private reauthAttempted = false;\n private presenceSubscribed = false;\n private heartbeatTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n /**\n * When the CURRENT socket last proved it was alive: set on open, refreshed by\n * every successfully parsed inbound frame (`heartbeat-ack` included — that IS\n * the DO's liveness answer). Null whenever no socket is live, so the watchdog\n * can never judge a socket that does not exist. See {@link INBOUND_SILENCE_LIMIT_MS}.\n */\n private lastInboundAt: number | null = null;\n // History requests sent on the current socket and not yet answered, oldest first.\n private historyRequests: HistoryRequestKind[] = [];\n private typingTimers = new Map<string, ReturnType<TransportTimers['setTimeout']>>();\n private lastTypingSentAt = Number.NEGATIVE_INFINITY;\n private reconnectTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n /** Single scheduled re-send for the membership-pending window (never stacks). */\n private membershipRetryTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private closedByUs = false;\n /**\n * The current lifecycle's number, advanced by every `connect()` and `close()`. A grant\n * that resolves, or a timer that fires, for an older lifecycle is dropped — so a\n * close → connect while an earlier grant is still minting can never open a second\n * socket or touch the new lifecycle's state (FRONTEND-108).\n */\n private lifecycle = 0;\n /** Reports the first open as failed once its attempts have failed for the budget. */\n private readonly initialLoad: InitialLoadBudget;\n /**\n * Per-seq moderation overlay (the max-revision wins). A `revision` frame writes\n * here keyed by `messageSeq` so it applies whether it arrives BEFORE its base\n * row (re-applied when the row later renders) or AFTER (re-renders the present\n * row in place). Merged with the row's own inline `moderationKind` so a row that\n * arrives already-moderated from the DO AND one covered by a live frame both\n * render the moderated state. */\n private overlays = new Map<number, ModerationOverlay>();\n /**\n * The ORIGINAL (un-overlaid) mapped message per seq. A `restore` revision must\n * revert a previously-redacted message to its original text, so re-renders start\n * from this cache rather than the (possibly already-blanked) message in state. */\n private originalRows = new Map<number, ChatMessageV1>();\n /**\n * Un-acked sends keyed by clientMessageId. A send is added here when its frame is\n * written and removed when its `ack` (or the canonical `message` echo carrying the\n * same clientMessageId) arrives. On every reconnect resume they are RE-SENT with\n * the SAME clientMessageId — the DO dedups (re-acks without re-broadcast), so a\n * send that lost its socket before the ack is delivered exactly once. A pending\n * send that exceeds the attempt/age cap is flipped to a visible failed state\n * (retry affordance) instead of staying a ghost. */\n private pendingSends = new Map<string, PendingSend>();\n /**\n * The structured diagnostics emitter, or null when diagnostics are off (the\n * default). Every call site uses `this.diag?.(...)` so the off path constructs\n * no payload at all.\n */\n private readonly diag: ChatClientDiagnosticsEmitter;\n /** Monotonic socket-open attempt counter (diagnostics correlation only). */\n private connectAttempt = 0;\n /** Why the CURRENT connect attempt is happening (diagnostics only). */\n private reconnectCause:\n 'initial' | 'auth-expired' | 'transient-close' | 'grant-error' | 'manual-retry' = 'initial';\n /** The last close code observed, carried into the next attempt's cause line. */\n private lastCloseCode: number | null = null;\n\n constructor(private readonly config: ChannelClientConfig) {\n this.timers = config.timers ?? defaultTimers;\n this.controller = createReconnectController(config.reconnect ?? {});\n this.diag = createDiagnosticsEmitter(config.diagnostics);\n this.initialLoad = new InitialLoadBudget(this.timers, () => this.reportInitialLoadFailed());\n }\n\n // ---- observable store ----\n\n getState(): ChannelClientState {\n return this.state;\n }\n\n subscribe(fn: (s: ChannelClientState) => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n private setState(patch: Partial<ChannelClientState>): void {\n this.state = { ...this.state, ...patch };\n // Only an open socket can be current.\n if (this.state.status !== 'open') this.state.isSynced = false;\n for (const fn of this.listeners) fn(this.state);\n }\n\n // ---- connection lifecycle ----\n\n async connect(): Promise<void> {\n return this.startLifecycle(true);\n }\n\n /**\n * Retry now (the first-open failure's Retry). While a reconnect is waiting out its\n * backoff, the wait is cancelled and a socket opens at once; a lifecycle that stopped\n * (reconnect gave up, or the socket was revoked) starts again; an attempt already in\n * flight is left to finish. Either way the first-open failure clears, so the opening state\n * shows while the retry runs. The spent budget stays spent: a retry that fails is reported\n * again at once, and one that hangs a full budget later.\n */\n retryNow(): void {\n if (!this.state.hasLoadedInitialData) this.initialLoad.manualRetry();\n if (this.state.status === 'closed') {\n void this.startLifecycle(false);\n return;\n }\n if (this.reconnectTimer == null) {\n if (this.state.initialLoadFailed) this.setState({ initialLoadFailed: false });\n return;\n }\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n this.controller.reset();\n this.controller.start();\n this.reconnectCause = 'manual-retry';\n this.setState({ status: 'reconnecting', initialLoadFailed: false });\n void this.openSocket();\n }\n\n private async startLifecycle(freshBudget: boolean): Promise<void> {\n // Idempotency guard (C-B7): connect() only starts a lifecycle from a fresh\n // (idle) or fully torn-down (closed) state. A second connect() while one is\n // already connecting / open / reconnecting is a no-op, so a stray double-owner\n // can't open a second WebSocket. The reconnect path uses openSocket() /\n // scheduleReconnect() directly (never connect()), so this never blocks a\n // legitimate reconnect.\n if (this.state.status !== 'idle' && this.state.status !== 'closed') return;\n // REVIVE the controller. `controller.close()` is PERMANENT: while it is in\n // state `closed`, `start()` and `onOpen()` no-op and every later `onClose()`\n // returns null. So without this reset a close() → connect() client opens a\n // socket and works normally until its FIRST transient close, at which point\n // `scheduleReconnect()` gets null and parks it terminally in `closed` with\n // reconnect disabled and no surfaced error code. The idempotency guard above\n // is what keeps this from disturbing a live lifecycle: only an `idle` or\n // fully torn-down (`closed`) client ever reaches here.\n this.controller.reset();\n // A terminal verdict (4403 REVOKED / ChatAccessDeniedError) is terminal WITHIN\n // its lifecycle; an explicit connect() is a fresh attempt the authority may\n // legitimately re-deny, so the previous lifecycle's code must not persist into\n // this one (the hook maps `access-denied` to `allowed: false`). Loaded\n // messages and the initial-load flag are deliberately KEPT — a lifecycle\n // restart must not churn the UI back to an empty opening state.\n if (isTerminalErrorCode(this.state.lastErrorCode)) this.setState({ lastErrorCode: null });\n this.closedByUs = false;\n this.lifecycle += 1;\n this.reconnectCause = 'initial';\n if (!this.state.hasLoadedInitialData) this.initialLoad.begin(freshBudget);\n this.controller.start();\n this.setState({ status: 'connecting', initialLoadFailed: false });\n await this.openSocket();\n }\n\n /** The first open has failed for long enough to say so (see `initialLoadFailed`). */\n private reportInitialLoadFailed(): void {\n if (this.state.hasLoadedInitialData || this.state.initialLoadFailed) return;\n this.setState({ initialLoadFailed: true });\n }\n\n /** The first authoritative data is applied; it ends any first-open failure. */\n private initialDataLoaded(): Partial<ChannelClientState> {\n this.initialLoad.loaded();\n return { hasLoadedInitialData: true, initialLoadFailed: false };\n }\n\n private async openSocket(): Promise<void> {\n const lifecycle = this.lifecycle;\n this.connectAttempt += 1;\n this.diag?.(DIAG.CONNECT_ATTEMPT, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n closeCode: this.lastCloseCode,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n });\n let grantToken: string;\n try {\n grantToken = await this.config.grantProvider();\n } catch (err) {\n // A grant for a lifecycle that has since been closed or restarted answers nobody.\n if (lifecycle !== this.lifecycle) return;\n // A TERMINAL access denial (the app's grant provider translated an\n // authoritative policy \"no\" into the package-owned ChatAccessDeniedError)\n // must NOT reconnect — the next mint would just re-deny, stranding the shell\n // on the opening loader forever. Every other mint failure (network, transient\n // 'unavailable'/'internal', post-login 'unauthenticated') stays retryable and\n // backs off exactly as before.\n const terminal = isChatAccessDeniedError(err);\n this.diag?.(DIAG.GRANT_FAILED, { attempt: this.connectAttempt, terminal });\n if (terminal) return this.denyAccessTerminally();\n this.reconnectCause = 'grant-error';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n return this.scheduleReconnect();\n }\n // A grant minted for an earlier lifecycle must never open a socket in this one.\n if (lifecycle !== this.lifecycle || this.closedByUs) return;\n // Socket REPLACEMENT: the previous socket's liveness record dies with it, so\n // the watchdog never judges a new socket against an old deadline.\n this.lastInboundAt = null;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/channel`;\n // Every callback is fenced to THIS socket: once it has been replaced or torn down,\n // its late open, frames, and close are ignored.\n let socket: RealtimeSocket | null = null;\n const isCurrent = () => socket !== null && this.socket === socket;\n socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => {\n if (isCurrent()) this.onOpen();\n },\n onMessage: (data) => {\n if (isCurrent()) this.onMessage(data);\n },\n onClose: (code, reason) => {\n if (isCurrent()) this.onClose(code, reason);\n },\n onError: () => {\n if (isCurrent()) this.onError();\n },\n },\n });\n this.socket = socket;\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n // Start the liveness clock at open — the first heartbeat window is measured\n // from here, not from a stale previous socket.\n this.lastInboundAt = this.timers.now();\n // A new socket is current only once its resume lands.\n this.historyRequests = [];\n this.setState({ status: 'open', isSynced: false });\n this.diag?.(DIAG.SOCKET_OPEN, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n presenceSubscribed: this.presenceSubscribed,\n });\n // Resume: ask the DO for the authoritative snapshot, then live deltas flow. The\n // field name MUST be `afterSeq` — the Channel DO reads `payload.afterSeq`; any other\n // name reads as cursorless and forces a full resync every reconnect.\n this.sendFrame(CLIENT_KINDS.RESUME, { afterSeq: this.resumeSeq });\n this.diag?.(DIAG.RESUME_REQUEST, { afterSeq: this.resumeSeq, attempt: this.connectAttempt });\n // If the UI had presence open, re-subscribe after a reconnect.\n if (this.presenceSubscribed) this.sendFrame(CLIENT_KINDS.PRESENCE_SUBSCRIBE, {});\n // Re-send the last read cursor so a read-ack dropped during the disconnect window\n // (sendFrame returns false on a closed socket) is not lost until the next message.\n if (this.lastReadAck) this.sendFrame(CLIENT_KINDS.READ_ACK, { ...this.lastReadAck });\n // Re-send every un-acked pending send with its ORIGINAL clientMessageId so a send\n // that lost its socket before the ack is not silently dropped. The DO dedups\n // (re-acks, no re-broadcast, no flood-token) — this is the client half of the\n // Contract C send-idempotency the server side was built for.\n this.resendPendingSends('reconnect');\n this.startHeartbeat();\n }\n\n /**\n * On reconnect, re-send each un-acked pending send with the SAME clientMessageId\n * (the DO dedups). A send that has exceeded the attempt or age cap is flipped to a\n * visible failed state instead of being resent forever — the ghost becomes a\n * retryable failure the UI can surface.\n */\n private resendPendingSends(reason: 'reconnect' | 'membership-pending'): void {\n if (this.pendingSends.size === 0) return;\n const now = this.timers.now();\n for (const pending of [...this.pendingSends.values()]) {\n // Already flipped to the visible failed state — only an explicit retrySend()\n // re-queues it; the automatic reconnect resend leaves it alone.\n if (pending.failed) continue;\n if (pending.serverRetryable) {\n // The Worker declared this send retryable — give-up is the wall-clock budget\n // ONLY (the 5-attempt cap must not fail a server-declared transient after\n // ~10 s while the backend projection window is up to 60+ s).\n if (now - pending.sentAt >= SERVER_RETRYABLE_MAX_AGE_MS) {\n this.failPendingSend(pending.clientMessageId, pending.lastRejectionCode, true);\n continue;\n }\n // This reconnect resend supersedes any per-send timer scheduled before the\n // socket dropped — clear it so the send doesn't go out twice (the DO would\n // dedup, but the duplicate frame is pure waste). A fresh rejection frame\n // re-schedules as usual.\n this.clearSendRetryTimer(pending);\n } else {\n // A blind reconnect resend of a send the server has said nothing about: the\n // generic attempt/age caps still protect against a permanent ghost.\n const tooOld = now - pending.sentAt >= PENDING_SEND_MAX_AGE_MS;\n const tooManyAttempts = pending.attempts >= MAX_PENDING_SEND_ATTEMPTS;\n if (tooOld || tooManyAttempts) {\n this.failPendingSend(pending.clientMessageId);\n continue;\n }\n }\n const sent = this.sendFrame(CLIENT_KINDS.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n });\n if (sent) pending.attempts += 1;\n this.diag?.(DIAG.SEND_RETRY, {\n clientMessageId: pending.clientMessageId,\n reason,\n attempts: pending.attempts,\n serverRetryable: pending.serverRetryable,\n ageMs: now - pending.sentAt,\n sent,\n });\n }\n }\n\n /**\n * Flip an un-acked optimistic row to a visible failed state. The pending entry is\n * RETAINED (marked `failed`) so retrySend() can re-queue it with the SAME\n * clientMessageId; the row is marked `meta.sendFailed` (plus the correlated\n * `sendFailureCode`/`sendRetryable` when a `send-rejected` frame supplied them) so\n * the default renderer shows the right reason + retry affordance rather than an\n * indistinguishable \"sent\" bubble. A late ack/echo still reconciles + clears it.\n *\n * `code`/`retryable` are present for a correlated rejection (terminal) or a\n * budget-exhausted server-retryable send; absent for a blind reconnect give-up\n * (which keeps the neutral `send-failed` code).\n */\n private failPendingSend(\n clientMessageId: string,\n code?: ChatSendRejectionCode,\n retryable?: boolean,\n ): void {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending || pending.failed) return;\n pending.failed = true;\n // A terminal/exhausted send never retries on a timer — cancel any scheduled one.\n this.clearSendRetryTimer(pending);\n this.diag?.(DIAG.SEND_FAILED, {\n clientMessageId,\n code: code ?? 'send-failed',\n retryable: retryable ?? null,\n attempts: pending.attempts,\n serverRetryable: pending.serverRetryable,\n ageMs: this.timers.now() - pending.sentAt,\n });\n const next = this.state.messages.map((m) =>\n m.meta?.optimistic && m.meta?.clientMessageId === clientMessageId\n ? {\n ...m,\n meta: {\n ...m.meta,\n sendFailed: true,\n ...(code ? { sendFailureCode: code } : {}),\n ...(retryable != null ? { sendRetryable: retryable } : {}),\n },\n }\n : m,\n );\n this.setState({ messages: next, lastErrorCode: code ?? 'send-failed' });\n }\n\n /** Clear a pending send's per-send retry timer (idempotent). */\n private clearSendRetryTimer(pending: PendingSend): void {\n if (pending.retryTimer != null) {\n this.timers.clearTimeout(pending.retryTimer);\n pending.retryTimer = null;\n }\n }\n\n /**\n * Stop tracking a send (acked / reconciled by an echo / history row): cancel its\n * per-send retry timer first so a late reconcile never leaves a stray timer that\n * would resend after the send already landed, then drop it from the map.\n */\n private clearPendingSend(clientMessageId: string): void {\n const pending = this.pendingSends.get(clientMessageId);\n if (pending) this.clearSendRetryTimer(pending);\n this.pendingSends.delete(clientMessageId);\n }\n\n /** One timer for the membership-pending re-send window; a newer frame resets it. */\n private scheduleMembershipPendingRetry(delayMs: number): void {\n if (this.membershipRetryTimer != null) this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = this.timers.setTimeout(() => {\n this.membershipRetryTimer = null;\n if (this.closedByUs) return;\n this.resendPendingSends('membership-pending');\n }, delayMs);\n }\n\n /**\n * Handle a CORRELATED `send-rejected` frame (the target protocol): parse the\n * untrusted payload with the shared schema, correlate to EXACTLY ONE pending send\n * by clientMessageId, and either fail just that bubble (terminal) or schedule a\n * single per-send resend (retryable).\n *\n * A frame that fails validation is NOT simply dropped when it still names one of\n * OUR pending sends: unlike an unknown frame type, an id-correlated rejection is\n * the server explicitly telling us this send did not land — swallowing it would\n * strand the bubble on \"Sending…\" forever (no further frame, no reconnect, no\n * budget check ever runs). A future/unknown rejection code (version skew during a\n * rollout) therefore fails that send CLOSED with the neutral copy + Retry. A\n * malformed frame with no recognizable pending id is dropped (forward-compat\n * noise), never surfaced as an error.\n */\n private applySendRejected(payload: Record<string, unknown>): void {\n const parsed = ChatSendRejectedPayloadSchema.safeParse(payload);\n if (!parsed.success) {\n // Defensive fail-closed: if the unparseable rejection still carries a string\n // id matching one of our un-failed pending sends, that send was rejected by a\n // server speaking a newer/buggy dialect — fail it visibly (neutral code-less\n // \"Couldn't send\" + Retry) instead of stranding it.\n const rawId = (payload as { clientMessageId?: unknown }).clientMessageId;\n if (typeof rawId === 'string' && rawId.length > 0 && rawId.length <= 200) {\n const orphaned = this.pendingSends.get(rawId);\n if (orphaned && !orphaned.failed) {\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId: rawId,\n outcome: 'unparseable-fail-closed',\n });\n this.failPendingSend(rawId);\n return;\n }\n }\n this.diag?.(DIAG.SEND_REJECTED, { clientMessageId: null, outcome: 'unparseable-dropped' });\n return;\n }\n const { clientMessageId, code, retryable, retryAfterMs } = parsed.data;\n const pending = this.pendingSends.get(clientMessageId);\n // No matching pending send — already acked/reconciled, or never ours. A late\n // ack/echo (which may have already landed) always wins; nothing to correlate.\n if (!pending || pending.failed) {\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId,\n code,\n retryable,\n outcome: 'no-pending-send',\n });\n return;\n }\n\n if (!retryable) {\n // Terminal: an unchanged resend cannot succeed (blocked-word / archived /\n // deleted). Fail ONLY this bubble, recording the reason + terminal class.\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId,\n code,\n retryable: false,\n outcome: 'terminal',\n });\n this.failPendingSend(clientMessageId, code, false);\n return;\n }\n\n // Retryable: server-declared, so switch this send onto the wall-clock budget\n // (the 5-attempt cap no longer applies) and record the reason for a possible\n // budget-exhausted failure.\n pending.serverRetryable = true;\n pending.lastRejectionCode = code;\n // If the budget already elapsed (a long stream of retryable rejections), fail\n // now rather than scheduling yet another doomed resend.\n if (this.timers.now() - pending.sentAt >= SERVER_RETRYABLE_MAX_AGE_MS) {\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId,\n code,\n retryable: true,\n outcome: 'budget-exhausted',\n });\n this.failPendingSend(clientMessageId, code, true);\n return;\n }\n const delayMs = this.clampRetryDelay(retryAfterMs);\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId,\n code,\n retryable: true,\n outcome: 'retry-scheduled',\n delayMs,\n });\n this.scheduleSendRetry(clientMessageId, delayMs);\n }\n\n /**\n * Schedule EXACTLY ONE per-send resend of a correlated retryable rejection (never\n * stacks — a newer rejection clears the prior timer first). When it fires it\n * re-sends the SAME clientMessageId (the DO dedups) unless the wall-clock budget\n * has elapsed, in which case the send fails with its recorded reason.\n */\n private scheduleSendRetry(clientMessageId: string, delayMs: number): void {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending) return;\n this.clearSendRetryTimer(pending);\n pending.retryTimer = this.timers.setTimeout(() => {\n pending.retryTimer = null;\n if (this.closedByUs) return;\n const current = this.pendingSends.get(clientMessageId);\n if (!current || current.failed) return;\n if (this.timers.now() - current.sentAt >= SERVER_RETRYABLE_MAX_AGE_MS) {\n this.failPendingSend(clientMessageId, current.lastRejectionCode, true);\n return;\n }\n // A server-retryable resend does NOT count toward the attempt cap (that cap is\n // for blind reconnect resends only) — leave `attempts` untouched.\n const sent = this.sendFrame(CLIENT_KINDS.SEND, {\n clientMessageId: current.clientMessageId,\n text: current.text,\n });\n this.diag?.(DIAG.SEND_RETRY, {\n clientMessageId: current.clientMessageId,\n reason: 'scheduled',\n attempts: current.attempts,\n serverRetryable: current.serverRetryable,\n ageMs: this.timers.now() - current.sentAt,\n sent,\n });\n // Budget backstop: the contract says every send gets an ack or a rejection,\n // and either one replaces/clears this timer. If the server goes silent (a\n // contract violation), NOTHING else would ever re-check the budget on a\n // stable socket — so arm a deadline check that fails the send at budget end.\n // This makes SERVER_RETRYABLE_MAX_AGE_MS a hard ceiling, not a best effort.\n const remainingMs =\n SERVER_RETRYABLE_MAX_AGE_MS -\n (this.timers.now() - current.sentAt) +\n SEND_RETRY_MIN_DELAY_MS;\n current.retryTimer = this.timers.setTimeout(() => {\n current.retryTimer = null;\n if (this.closedByUs) return;\n const atDeadline = this.pendingSends.get(clientMessageId);\n if (!atDeadline || atDeadline.failed) return;\n if (this.timers.now() - atDeadline.sentAt >= SERVER_RETRYABLE_MAX_AGE_MS) {\n this.failPendingSend(clientMessageId, atDeadline.lastRejectionCode, true);\n }\n }, remainingMs);\n }, delayMs);\n }\n\n /** Clamp a server `retryAfterMs` hint into a sane resend delay (defaulting when absent). */\n private clampRetryDelay(retryAfterMs: number | undefined): number {\n const raw =\n typeof retryAfterMs === 'number' && retryAfterMs > 0\n ? retryAfterMs\n : MEMBERSHIP_PENDING_DEFAULT_RETRY_MS;\n return Math.min(Math.max(raw, SEND_RETRY_MIN_DELAY_MS), SEND_RETRY_MAX_DELAY_MS);\n }\n\n /**\n * Flip EVERY un-acked pending send to the visible failed state. Called on the\n * terminal close paths (4403 REVOKED, reconnect give-up) — without this, a send\n * in flight when the socket dies for good shows \"Sending…\" until unmount.\n */\n private failAllPendingSends(): void {\n for (const clientMessageId of [...this.pendingSends.keys()]) {\n this.failPendingSend(clientMessageId);\n }\n }\n\n /**\n * Retry a FAILED (or still-pending) send, RE-USING its original clientMessageId\n * so the DO's send-idempotency dedups against any copy that actually landed.\n * Resets the attempt/age budget, clears the row's `sendFailed` marker (back to\n * the normal pending/optimistic look), and re-sends immediately when the socket\n * is open — otherwise the entry rides the next reconnect's automatic resend.\n * Returns false when the clientMessageId is not a tracked pending send (already\n * acked/reconciled, or never sent from this client).\n */\n retrySend(clientMessageId: string): boolean {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending) return false;\n // A manual retry supersedes any scheduled server-retryable resend and starts a\n // fresh budget from now; the server re-declares retryability if it rejects again.\n this.clearSendRetryTimer(pending);\n pending.failed = false;\n pending.serverRetryable = false;\n pending.lastRejectionCode = undefined;\n pending.sentAt = this.timers.now();\n const sent = this.sendFrame(CLIENT_KINDS.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n });\n pending.attempts = sent ? 1 : 0;\n this.diag?.(DIAG.SEND_RETRY, {\n clientMessageId,\n reason: 'manual',\n attempts: pending.attempts,\n serverRetryable: false,\n ageMs: 0,\n sent,\n });\n const next = this.state.messages.map((m) => {\n if (!(\n m.meta?.optimistic &&\n m.meta?.clientMessageId === clientMessageId &&\n m.meta?.sendFailed\n )) {\n return m;\n }\n // Back to the normal pending look — drop every failure marker.\n const {\n sendFailed: _sendFailed,\n sendFailureCode: _sendFailureCode,\n sendRetryable: _sendRetryable,\n ...restMeta\n } = m.meta;\n return { ...m, meta: { ...restMeta } };\n });\n this.setState({ messages: next, lastErrorCode: null });\n return true;\n }\n\n private onError(): void {\n // The close handler does the backoff; onerror is advisory in browsers.\n }\n\n private onClose(code: number, _reason: string): void {\n this.stopHeartbeat();\n this.socket = null;\n this.lastInboundAt = null;\n this.lastCloseCode = code;\n // An older-history request in flight died with the socket; nothing will answer it.\n if (this.state.isFetchingOlder) this.setState({ isFetchingOlder: false });\n if (this.closedByUs) {\n this.diag?.(DIAG.SOCKET_CLOSE, {\n code,\n closedByUs: true,\n outcome: 'closed',\n resumeSeq: this.resumeSeq,\n });\n this.setState({ status: 'closed' });\n return;\n }\n // 4401 AUTH_EXPIRED: re-mint a grant ONCE and reconnect immediately, no backoff.\n if (code === CHAT_CLOSE_CODES.AUTH_EXPIRED && !this.reauthAttempted) {\n this.reauthAttempted = true;\n this.reconnectCause = 'auth-expired';\n this.diag?.(DIAG.SOCKET_CLOSE, {\n code,\n closedByUs: false,\n outcome: 're-grant',\n resumeSeq: this.resumeSeq,\n });\n this.setState({ status: 'reconnecting' });\n void this.openSocket();\n return;\n }\n // 4403 REVOKED: access pulled. Stop — a reconnect would just re-deny at mint.\n // Terminal: flip every un-acked pending send to the visible failed state first\n // (failPendingSend sets lastErrorCode 'send-failed'; the 'revoked' set below\n // wins as the final surfaced code).\n if (code === CHAT_CLOSE_CODES.REVOKED) {\n this.closedByUs = true;\n this.controller.close();\n this.diag?.(DIAG.SOCKET_CLOSE, {\n code,\n closedByUs: false,\n outcome: 'revoked',\n resumeSeq: this.resumeSeq,\n });\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.REVOKED });\n // Revoked before anything loaded: the first open has failed, and nothing retries it.\n this.reportInitialLoadFailed();\n return;\n }\n this.reconnectCause = 'transient-close';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n this.diag?.(DIAG.SOCKET_CLOSE, {\n code,\n closedByUs: false,\n outcome: 'reconnect',\n resumeSeq: this.resumeSeq,\n });\n this.scheduleReconnect();\n }\n\n private scheduleReconnect(): void {\n const delay = this.controller.onClose();\n this.diag?.(DIAG.RECONNECT_SCHEDULED, {\n delayMs: delay,\n cause: this.reconnectCause,\n attempt: this.connectAttempt,\n resumeSeq: this.resumeSeq,\n });\n if (delay == null) {\n // Reconnect give-up: terminal, same as REVOKED — pending sends must not stay\n // an eternal \"Sending…\"; flip them to the visible failed/retry state.\n this.failAllPendingSends();\n this.setState({ status: 'closed' });\n // Gave up before anything loaded: nothing retries the first open any more.\n this.reportInitialLoadFailed();\n return;\n }\n this.setState({ status: 'reconnecting' });\n const lifecycle = this.lifecycle;\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs || lifecycle !== this.lifecycle) return;\n void this.openSocket();\n }, delay);\n }\n\n /**\n * Terminal access denial surfaced by the grant provider (ChatAccessDeniedError).\n * A reconnect would just re-deny at the next mint, so stop for good — the same\n * terminal posture as a 4403 REVOKED close: mark closed-by-us, close the reconnect\n * controller, and flip every un-acked pending send to the visible failed state.\n * `access-denied` is set AFTER failAllPendingSends so its 'send-failed' code does\n * not win as the surfaced error; the React hook maps 'access-denied' to\n * `allowed: false` so the shell renders its existing no-access surface.\n */\n private denyAccessTerminally(): void {\n this.closedByUs = true;\n this.controller.close();\n this.initialLoad.dispose();\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.ACCESS_DENIED });\n }\n\n // ---- inbound frames ----\n\n private onMessage(data: string): void {\n const frame = parseFrame(data);\n if (!frame || !frame.type) {\n // Unparseable: bytes arrived, but nothing proves they came from a DO\n // speaking this protocol, so this must NOT refresh the liveness deadline.\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'unparseable', reason: 'bad-envelope' });\n return;\n }\n // A well-formed envelope IS the liveness proof — including the `heartbeat-ack`\n // the DO auto-responds with, and a forward-compat type this build does not\n // handle yet (a newer DO's frames must never be read as a dead socket).\n this.lastInboundAt = this.timers.now();\n const payload = frame.payload ?? {};\n switch (frame.type) {\n case 'message':\n return this.applyMessage((payload as { message: WireMessageRow }).message, 'live');\n case 'ack':\n return this.applyAck(\n payload as { clientMessageId?: string; seq?: number; readSeq?: number },\n );\n case 'history-page':\n return this.applyHistoryPage((payload as { messages: WireMessageRow[] }).messages ?? []);\n case 'presence':\n return this.setState({ presence: (payload as { online: string[] }).online ?? [] });\n case 'typing':\n return this.applyTyping((payload as { uid: string }).uid);\n case 'snapshot':\n return this.applyChannelSnapshot(payload as unknown as WireChannelSnapshot);\n case 'send-rejected':\n return this.applySendRejected(payload);\n case 'error': {\n const code = String((payload as { code?: unknown }).code ?? 'error');\n // ROLLOUT COMPATIBILITY ONLY (not the target protocol): a Worker that predates\n // the correlated `send-rejected` frame emits an UNCORRELATED\n // error{code:'membership-pending'} with no clientMessageId, so we cannot target\n // one send. Keep the send(s) pending (no visible error — the bubble stays\n // \"Sending…\"), mark every in-flight send server-retryable so the wall-clock\n // budget (NOT the 5-attempt cap) governs give-up, and re-send all after the\n // server-suggested delay. The correlated path below is the target protocol.\n if (code === MEMBERSHIP_PENDING_CODE) {\n const raw = (payload as { retryAfterMs?: unknown }).retryAfterMs;\n const delay = this.clampRetryDelay(typeof raw === 'number' ? raw : undefined);\n this.diag?.(DIAG.ERROR_FRAME, {\n code: MEMBERSHIP_PENDING_CODE,\n correlated: false,\n delayMs: delay,\n pendingSends: this.pendingSends.size,\n });\n for (const pending of this.pendingSends.values()) {\n if (!pending.failed) {\n pending.serverRetryable = true;\n pending.lastRejectionCode = MEMBERSHIP_PENDING_CODE;\n }\n }\n return this.scheduleMembershipPendingRetry(delay);\n }\n this.diag?.(DIAG.ERROR_FRAME, { code: safeDiagnosticLabel(code), correlated: false });\n return this.setState({ lastErrorCode: code });\n }\n case 'revision':\n return this.applyRevisionFrame(\n payload as { messageSeq?: number; kind?: RevisionKind; messageRevision?: number },\n );\n case 'heartbeat-ack':\n // The DO runtime's hibernation AUTO-RESPONSE to our 20s `heartbeat`. Per\n // Contract C liveness is tracked SERVER-side (the auto-response timestamp\n // the dueWork sweep reads), so the client heartbeat is fire-and-forget: the\n // ack needs no state change and the next tick is already scheduled. Explicit\n // no-op — and deliberately NO diagnostic, not even frame_applied: at ~20s\n // this is the one frame that recurs forever, so logging it would violate the\n // bounded \"one line per DECISION, never per heartbeat\" contract and drown the\n // frame_dropped signal that distinguishes \"never arrived\" from \"dropped\".\n return;\n default:\n // unknown/optional types tolerated (forward compat)\n this.diag?.(DIAG.FRAME_DROPPED, {\n kind: safeDiagnosticLabel(frame.type),\n reason: 'unknown-type',\n });\n return;\n }\n }\n\n /**\n * Apply a live moderation `revision` frame: record the overlay keyed by seq\n * (max-`messageRevision` wins — a stale/older frame is ignored) and re-render the\n * matching message in place if it is already loaded. If the base row hasn't\n * arrived yet the overlay is retained and re-applied when the row renders, so a\n * frame that races ahead of its message never lets the original content show.\n */\n private applyRevisionFrame(payload: {\n messageSeq?: number;\n kind?: RevisionKind;\n messageRevision?: number;\n }): void {\n const seq = payload.messageSeq;\n const kind = payload.kind;\n const messageRevision = payload.messageRevision;\n if (typeof seq !== 'number' || kind == null || typeof messageRevision !== 'number') {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'revision', reason: 'malformed-payload' });\n return;\n }\n const prev = this.overlays.get(seq);\n // Max-revision merge: a higher messageRevision supersedes; an older one is dropped.\n if (prev && prev.messageRevision >= messageRevision) {\n this.diag?.(DIAG.FRAME_DROPPED, {\n kind: 'revision',\n reason: 'stale-revision',\n seq,\n messageRevision,\n heldRevision: prev.messageRevision,\n });\n return;\n }\n this.overlays.set(seq, { kind, messageRevision });\n // Re-render the matching message in place if it is already present. Re-derive\n // from the ORIGINAL row so a `restore` reverts a previously-blanked text.\n const messageId = seqToMessageId(seq);\n const original = this.originalRows.get(seq);\n const rendered =\n Boolean(original) && this.state.messages.some((m) => m.messageId === messageId);\n this.diag?.(DIAG.REVISION_APPLIED, {\n seq,\n kind,\n messageRevision,\n // false = overlay retained for a row not loaded yet (re-applied when it renders).\n rendered,\n });\n if (rendered && original) {\n const overlaid = applyModerationOverlay(original, this.effectiveOverlay(seq, null));\n const next = this.state.messages.map((m) => (m.messageId === messageId ? overlaid : m));\n this.setState({ messages: next });\n }\n }\n\n /**\n * The effective overlay for a seq = the max-`messageRevision` between the row's\n * own inline overlay (from the DO history/delta merge) and any received `revision`\n * frame stored in `this.overlays`. Either source may be ahead of the other.\n */\n private effectiveOverlay(\n seq: number,\n rowOverlay: ModerationOverlay | null,\n ): ModerationOverlay | null {\n const fromFrame = this.overlays.get(seq) ?? null;\n if (!rowOverlay) return fromFrame;\n if (!fromFrame) return rowOverlay;\n return fromFrame.messageRevision >= rowOverlay.messageRevision ? fromFrame : rowOverlay;\n }\n\n /** Map a DO row to a UI message with its effective moderation overlay applied. */\n private renderRow(row: WireMessageRow): ChatMessageV1 {\n const mapped = wireRowToMessage(row, this.config.threadId);\n // Cache the ORIGINAL so a later `restore` frame can revert a blanked message.\n this.originalRows.set(row.seq, mapped);\n return applyModerationOverlay(mapped, this.effectiveOverlay(row.seq, overlayFromRow(row)));\n }\n\n /**\n * Apply the Contract C resume snapshot. The DO always returns the authoritative\n * tail + read cursor and, per the pinned contract, EITHER a contiguous delta\n * (`resync:false`) OR a resync directive (`resync:true`).\n *\n * - `resync === false`: apply the contiguous `delta` (the ≤500-message backlog\n * after our cursor, oldest-first) through the same render/merge path as a live\n * `message`, then advance `resumeSeq` to `lastMessageSeq`. This heals ANY gap\n * within the backlog — including moderation `revision`s the DO baked into the\n * delta rows — with no history fetch, so a >50-message reconnect gap is no\n * longer a permanent hole.\n * - `resync === true`: the gap is beyond the backlog (or we sent no cursor). Drop\n * the local tail (messages + overlays + original-row cache) and re-page history\n * from the top via a cursorless `requestHistory(null)`.\n *\n * A pre-contract DO (no `resync`/`delta`) is treated as `resync:true` ⇒ the safe\n * re-page path, so a stale worker never strands the client. An empty delta with\n * `resync:false` (already caught up) is a no-op beyond advancing the cursor.\n */\n private applyChannelSnapshot(snap: WireChannelSnapshot): void {\n // Guard: an inbox snapshot must never reach a channel client.\n if (isInboxSnapshot(snap as never)) {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'snapshot', reason: 'inbox-snapshot-on-channel' });\n return;\n }\n if (typeof snap.lastMessageSeq !== 'number') {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'snapshot', reason: 'missing-last-message-seq' });\n return;\n }\n\n // Absent `resync` (legacy/pre-contract DO) is treated as a resync directive.\n const resync = snap.resync !== false;\n const cursorBefore = this.resumeSeq;\n const delta = Array.isArray(snap.delta) ? snap.delta : [];\n\n if (!resync) {\n // Apply the contiguous delta oldest-first, exactly like live messages, then\n // advance the cursor to the authoritative tail so the NEXT resume tells the DO\n // we're caught up only after we actually applied the backlog.\n for (const row of delta) this.applyMessage(row, 'delta');\n if (snap.lastMessageSeq > this.resumeSeq) this.resumeSeq = snap.lastMessageSeq;\n this.diag?.(DIAG.RESUME_RESULT, {\n lastMessageSeq: snap.lastMessageSeq,\n resync: false,\n deltaCount: delta.length,\n cursorBefore,\n cursorAfter: this.resumeSeq,\n readSeq: typeof snap.readSeq === 'number' ? snap.readSeq : null,\n });\n // A non-resync snapshot IS the first authoritative data (even an empty delta =\n // caught up) — end initial loading. A resync snapshot instead defers to the\n // re-paged first history page below, so it must NOT end it here.\n this.setState({\n ...(this.state.hasLoadedInitialData ? {} : this.initialDataLoaded()),\n isSynced: true,\n });\n return;\n }\n\n // Resync: drop the local tail and re-page from the top per the pinned contract.\n // Clear the derived caches too so a stale overlay/original-row can't resurrect a\n // message the re-page will reload fresh (with its baked-in moderation state).\n // KEEP un-acked optimistic rows — they aren't server history yet; their pending\n // sends were already re-sent in onOpen and reconcile when the DO echoes them.\n this.overlays.clear();\n this.originalRows.clear();\n this.resumeSeq = 0;\n const priorCount = this.state.messages.length;\n const keptOptimistic = this.state.messages.filter((m) => m.meta?.optimistic);\n this.diag?.(DIAG.RESUME_RESULT, {\n lastMessageSeq: snap.lastMessageSeq,\n resync: true,\n deltaCount: delta.length,\n cursorBefore,\n cursorAfter: 0,\n readSeq: typeof snap.readSeq === 'number' ? snap.readSeq : null,\n });\n this.diag?.(DIAG.RESYNC_DROPPED_TAIL, {\n // The client REMOVED rows from the UI here — the counterpart of an upsert.\n removedCount: priorCount - keptOptimistic.length,\n keptOptimistic: keptOptimistic.length,\n });\n this.setState({ messages: keptOptimistic, hasOlder: true, isFetchingOlder: false });\n this.requestHistory(null, 'resync');\n }\n\n /**\n * Apply one server row (a live `message` frame or a resume-delta row) and record\n * the decision the client made about it.\n *\n * Diagnostics bounding: a LIVE frame always emits one `chat_client_frame_applied`\n * line; a DELTA row emits one only when it is materially interesting (carries a\n * moderation kind, or reconciles one of our optimistic sends) — a 500-row backlog\n * is otherwise summarized by `chat_client_resume_result` rather than spamming 500\n * lines.\n */\n private applyMessage(row: WireMessageRow, source: 'live' | 'delta'): void {\n if (!row || typeof row.seq !== 'number') {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'message', source, reason: 'missing-seq' });\n return;\n }\n // Read the pre-merge view ONLY when diagnostics are on (these are O(n) scans).\n const prior = this.diag ? this.priorRowFacts(row) : null;\n const cursorBefore = this.resumeSeq;\n const mapped = this.renderRow(row);\n this.mergeMessage(mapped, row);\n if (row.seq > this.resumeSeq) this.resumeSeq = row.seq;\n if (!this.diag || !prior) return;\n\n const notable = row.moderationKind != null || prior.reconciledOptimistic;\n if (source === 'delta' && !notable) return;\n this.diag(DIAG.FRAME_APPLIED, {\n kind: 'message',\n source,\n seq: row.seq,\n hasClientMessageId: Boolean(row.clientMessageId),\n moderationKind: row.moderationKind ?? null,\n op: prior.reconciledOptimistic\n ? 'optimistic-reconcile'\n : prior.hadRow\n ? 'replace-by-seq'\n : 'insert',\n cursorBefore,\n cursorAfter: this.resumeSeq,\n });\n }\n\n /**\n * The pre-merge view of a row's seq: whether we already hold that seq, and whether\n * this row reconciles a live optimistic send.\n * Diagnostics-only — never called when diagnostics are off.\n */\n private priorRowFacts(row: WireMessageRow): {\n hadRow: boolean;\n reconciledOptimistic: boolean;\n } {\n const messageId = seqToMessageId(row.seq);\n const existing = this.state.messages.find((m) => m.messageId === messageId);\n return {\n hadRow: existing != null,\n reconciledOptimistic: Boolean(\n row.clientMessageId &&\n this.state.messages.some(\n (m) => m.meta?.optimistic && m.meta?.clientMessageId === row.clientMessageId,\n ),\n ),\n };\n }\n\n /**\n * Merge a server message: reconcile an optimistic echo by clientMessageId (swap\n * the `optimistic:` row for the canonical seq row), or insert/replace by seq.\n * Keeps the list sorted ascending by seq with optimistic rows at the tail.\n */\n private mergeMessage(mapped: ChatMessageV1, row: WireMessageRow): void {\n // If this canonical row carries a clientMessageId we still have pending (the\n // sender's own broadcast, or a resume delta that included our send), the send\n // landed — stop tracking it for reconnect resend (and cancel any retry timer).\n if (row.clientMessageId) this.clearPendingSend(row.clientMessageId);\n const next = this.state.messages.filter(\n (m) =>\n m.messageId !== mapped.messageId &&\n // drop the optimistic placeholder this server row reconciles\n (m.meta?.clientMessageId !== row.clientMessageId || !m.meta?.optimistic),\n );\n next.push(mapped);\n next.sort(sortBySeq);\n this.setState({ messages: next });\n }\n\n private applyAck(payload: { clientMessageId?: string; seq?: number; readSeq?: number }): void {\n // A read-ack echo carries readSeq only — nothing to reconcile locally.\n if (payload.clientMessageId == null || typeof payload.seq !== 'number') return;\n // Reconcile the optimistic echo: stamp the server seq onto it. The canonical\n // `message` broadcast (which the sender also receives) replaces it fully; this\n // ack guarantees the seq even if the broadcast is dropped/reordered.\n const seq = payload.seq;\n const cmid = payload.clientMessageId;\n this.diag?.(DIAG.SEND_ACK, {\n clientMessageId: cmid,\n seq,\n cursorBefore: this.resumeSeq,\n cursorAfter: seq > this.resumeSeq ? seq : this.resumeSeq,\n wasPending: this.pendingSends.has(cmid),\n });\n // The send is acked — stop tracking it for reconnect resend (and cancel any\n // per-send retry timer so a scheduled resend never fires after it landed).\n this.clearPendingSend(cmid);\n const next = this.state.messages.map((m) => {\n if (!m.meta?.optimistic || m.meta?.clientMessageId !== cmid) return m;\n // Strip any failed markers — a late ack (e.g. a retry raced the cap, or a\n // correlated rejection was superseded) means the send actually landed, so the\n // row must render as delivered, not failed.\n const {\n sendFailed: _sendFailed,\n sendFailureCode: _sendFailureCode,\n sendRetryable: _sendRetryable,\n ...restMeta\n } = m.meta;\n return {\n ...m,\n messageId: seqToMessageId(seq),\n meta: { ...restMeta, optimistic: false, seq },\n };\n });\n next.sort(sortBySeq);\n if (seq > this.resumeSeq) this.resumeSeq = seq;\n this.setState({ messages: next });\n }\n\n private applyHistoryPage(rows: WireMessageRow[]): void {\n const cursorBefore = this.resumeSeq;\n // The socket answers history requests in the order they were sent; the page answering a\n // resync is the one that makes the channel current again.\n const answersResync = this.historyRequests.shift() === 'resync';\n const mapped = rows.map((r) => this.renderRow(r));\n // Mirror mergeMessage's optimistic reconciliation: a history row carrying a\n // clientMessageId we still hold as an optimistic placeholder IS that send (the\n // DO stored it; the ack was lost). Drop the placeholder — keyed `optimistic:{cmid}`,\n // it would otherwise survive alongside its seq-keyed server row as a duplicate\n // bubble after a resync + re-page — and stop tracking it for resend.\n const incomingCmids = new Set<string>();\n for (const r of rows) {\n if (r.clientMessageId) {\n incomingCmids.add(r.clientMessageId);\n this.clearPendingSend(r.clientMessageId);\n }\n }\n const bySeq = new Map<string, ChatMessageV1>();\n for (const m of this.state.messages) {\n if (\n m.meta?.optimistic &&\n typeof m.meta?.clientMessageId === 'string' &&\n incomingCmids.has(m.meta.clientMessageId)\n ) {\n continue; // reconciled by the incoming server row\n }\n bySeq.set(m.messageId, m);\n }\n for (const m of mapped) bySeq.set(m.messageId, m);\n const merged = [...bySeq.values()].sort(sortBySeq);\n for (const r of rows) if (r.seq > this.resumeSeq) this.resumeSeq = r.seq;\n this.setState({\n messages: merged,\n isFetchingOlder: false,\n hasOlder: rows.length >= HISTORY_PAGE_MAX,\n // The first history page — INCLUDING an empty one — is a successful authoritative\n // load, so it ends initial loading. An older page arrives only after it, so this\n // never runs a second time.\n ...(this.state.hasLoadedInitialData ? {} : this.initialDataLoaded()),\n ...(answersResync ? { isSynced: true } : {}),\n });\n if (!this.diag) return;\n const seqs = rows.map((r) => r.seq).filter((s): s is number => typeof s === 'number');\n this.diag(DIAG.HISTORY_PAGE, {\n count: rows.length,\n minSeq: seqs.length > 0 ? Math.min(...seqs) : null,\n maxSeq: seqs.length > 0 ? Math.max(...seqs) : null,\n cursorBefore,\n cursorAfter: this.resumeSeq,\n reconciledOptimistic: incomingCmids.size,\n hasOlder: rows.length >= HISTORY_PAGE_MAX,\n total: merged.length,\n });\n }\n\n private applyTyping(uid: string): void {\n if (!uid || uid === this.config.currentUserId) return;\n if (!this.state.typing.includes(uid)) this.setState({ typing: [...this.state.typing, uid] });\n const prev = this.typingTimers.get(uid);\n if (prev) this.timers.clearTimeout(prev);\n this.typingTimers.set(\n uid,\n this.timers.setTimeout(() => {\n this.typingTimers.delete(uid);\n this.setState({ typing: this.state.typing.filter((u) => u !== uid) });\n }, TYPING_COALESCE_MS * 2),\n );\n }\n\n // ---- outbound actions ----\n\n private sendFrame<K extends ClientFrameKind>(type: K, payload: ChannelFramePayload<K>): boolean {\n if (!this.socket || !this.socket.isOpen) return false;\n this.socket.send(buildFrame(type, payload));\n return true;\n }\n\n /**\n * Optimistic send: render the echo immediately keyed by clientMessageId, then\n * emit the `send` frame. The server `ack`/`message` reconciles on the seq.\n */\n send(args: { clientMessageId: string; text: string }): boolean {\n // C-B8: write the frame FIRST and render the optimistic echo ONLY if it was\n // actually sent over an open socket. A closed socket returns false — no phantom\n // \"sent\" bubble, and the caller keeps the composer text — so a disconnect between\n // render and click can't silently swallow the message.\n const sent = this.sendFrame(CLIENT_KINDS.SEND, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n });\n if (!sent) {\n this.diag?.(DIAG.SEND_FAILED, {\n clientMessageId: args.clientMessageId,\n code: 'send-failed',\n retryable: null,\n attempts: 0,\n reason: 'socket-not-open',\n });\n this.setState({ lastErrorCode: 'send-failed' });\n return false;\n }\n const now = this.timers.now();\n // Track the un-acked send so a reconnect re-sends it with the same\n // clientMessageId (the DO dedups) — until the ack/echo clears it.\n this.pendingSends.set(args.clientMessageId, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n sentAt: now,\n attempts: 1,\n failed: false,\n serverRetryable: false,\n retryTimer: null,\n });\n const echo = optimisticMessage({\n clientMessageId: args.clientMessageId,\n threadId: this.config.threadId,\n senderId: this.config.currentUserId,\n text: args.text,\n createdAt: now,\n });\n const next = [...this.state.messages, echo].sort(sortBySeq);\n this.setState({ messages: next, lastErrorCode: null });\n this.diag?.(DIAG.SEND_OPTIMISTIC, {\n clientMessageId: args.clientMessageId,\n pendingSends: this.pendingSends.size,\n });\n return true;\n }\n\n /**\n * Explicit read ack (delivery != read). `focused` => the channel is open + at latest.\n * Remembers the cursor (re-sent on reconnect) and returns whether the frame was\n * actually sent over an open socket, so the caller only advances its local\n * already-acked marker on a real send (M2).\n */\n readAck(readSeq: number, focused: boolean): boolean {\n this.lastReadAck = { readSeq, focused };\n return this.sendFrame(CLIENT_KINDS.READ_ACK, { readSeq, focused });\n }\n\n /** Coalesced typing signal: at most one frame per TYPING_COALESCE_MS. */\n typing(): void {\n const now = this.timers.now();\n if (now - this.lastTypingSentAt < TYPING_COALESCE_MS) return;\n this.lastTypingSentAt = now;\n this.sendFrame(CLIENT_KINDS.TYPING, {});\n }\n\n presenceSubscribe(): void {\n this.presenceSubscribed = true;\n this.sendFrame(CLIENT_KINDS.PRESENCE_SUBSCRIBE, {});\n }\n\n presenceUnsubscribe(): void {\n this.presenceSubscribed = false;\n this.sendFrame(CLIENT_KINDS.PRESENCE_UNSUBSCRIBE, {});\n this.setState({ presence: [] });\n }\n\n /** Fetch the page of history older than the oldest loaded message (epoch-aware by seq). */\n fetchOlder(): void {\n if (this.state.isFetchingOlder || !this.state.hasOlder) return;\n const oldest = this.state.messages.find((m) => typeof m.meta?.seq === 'number');\n const beforeSeq =\n oldest && typeof oldest.meta?.seq === 'number' ? (oldest.meta.seq as number) : null;\n this.setState({ isFetchingOlder: true });\n // Unsent (the socket is down): nothing will answer, so it is not in flight.\n if (!this.requestHistory(beforeSeq, 'older')) this.setState({ isFetchingOlder: false });\n }\n\n private requestHistory(beforeSeq: number | null, kind: HistoryRequestKind): boolean {\n const sent = this.sendFrame(CLIENT_KINDS.HISTORY, { beforeSeq, limit: HISTORY_PAGE_MAX });\n if (sent) this.historyRequests.push(kind);\n this.diag?.(DIAG.HISTORY_REQUEST, { beforeSeq, limit: HISTORY_PAGE_MAX, sent });\n return sent;\n }\n\n // ---- heartbeat (20s) + dead-socket watchdog ----\n\n private startHeartbeat(): void {\n this.stopHeartbeat();\n const tick = () => {\n if (!this.socket || !this.socket.isOpen) return;\n // Liveness is checked BEFORE the write: a socket already proven dead must\n // not be handed another frame. Closing here does not reschedule — onClose\n // stops the heartbeat and owns what happens next.\n if (this.isInboundSilent()) return this.closeDeadSocket();\n this.sendFrame(CLIENT_KINDS.HEARTBEAT, {});\n this.heartbeatTimer = this.timers.setTimeout(tick, HEARTBEAT_MS);\n };\n this.heartbeatTimer = this.timers.setTimeout(tick, HEARTBEAT_MS);\n }\n\n private stopHeartbeat(): void {\n if (this.heartbeatTimer != null) {\n this.timers.clearTimeout(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n /** True when the live socket has produced no parseable frame for too long. */\n private isInboundSilent(): boolean {\n if (this.lastInboundAt == null) return false;\n return this.timers.now() - this.lastInboundAt >= INBOUND_SILENCE_LIMIT_MS;\n }\n\n /**\n * The channel DO auto-acks every heartbeat, so silence past\n * {@link INBOUND_SILENCE_LIMIT_MS} means this socket is dead even though no\n * `onclose` ever fired (the half-open-connection case that otherwise strands\n * the UI on a socket that will never deliver another message).\n *\n * Close it LOCALLY and deliberately WITHOUT setting `closedByUs`, so the close\n * lands on `onClose`'s ordinary transient path — which already owns the\n * reconnect scheduling, the backoff, and the resume-cursor recovery. Nothing\n * about reconnect policy is duplicated here.\n */\n private closeDeadSocket(): void {\n const socket = this.socket;\n this.diag?.(DIAG.SOCKET_LIVENESS_TIMEOUT, {\n silentMs: this.lastInboundAt == null ? null : this.timers.now() - this.lastInboundAt,\n thresholdMs: INBOUND_SILENCE_LIMIT_MS,\n attempt: this.connectAttempt,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n });\n this.lastInboundAt = null;\n socket?.close(WATCHDOG_CLOSE_CODE, 'client liveness timeout');\n }\n\n // ---- teardown ----\n\n /** Permanently close this client (auth-user switch / unmount). Idempotent. */\n close(): void {\n this.closedByUs = true;\n this.lifecycle += 1;\n this.controller.close();\n this.initialLoad.dispose();\n this.stopHeartbeat();\n // The heartbeat timer IS the watchdog's timer — stopping it above ends both.\n // Clearing the record too means a later connect() starts from a clean deadline.\n this.lastInboundAt = null;\n for (const t of this.typingTimers.values()) this.timers.clearTimeout(t);\n this.typingTimers.clear();\n this.overlays.clear();\n this.originalRows.clear();\n // Cancel every per-send retry timer before dropping the tracking map.\n for (const pending of this.pendingSends.values()) this.clearSendRetryTimer(pending);\n this.pendingSends.clear();\n if (this.reconnectTimer != null) {\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.membershipRetryTimer != null) {\n this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = null;\n }\n if (this.socket) {\n // Detach first: the socket's own late close is not this lifecycle's event.\n const socket = this.socket;\n this.socket = null;\n socket.close(1000, 'client teardown');\n }\n this.setState({ status: 'closed', typing: [], presence: [], isFetchingOlder: false });\n }\n}\n\nfunction sortBySeq(a: ChatMessageV1, b: ChatMessageV1): number {\n const sa = typeof a.meta?.seq === 'number' ? (a.meta.seq as number) : Number.POSITIVE_INFINITY;\n const sb = typeof b.meta?.seq === 'number' ? (b.meta.seq as number) : Number.POSITIVE_INFINITY;\n if (sa !== sb) return sa - sb;\n return a.createdAt - b.createdAt;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"channel-client.js","sourceRoot":"","sources":["../../src/realtime/channel-client.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,GAE1B,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,6BAA6B,EAC7B,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,UAAU,EACV,UAAU,EACV,eAAe,GAIhB,MAAM,WAAW,CAAC;AAUnB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,cAAc,EACd,sBAAsB,EACtB,cAAc,GAEf,MAAM,UAAU,CAAC;AAElB,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,6BAA6B,IAAI,IAAI,GAGtC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACnB,yBAAyB,EACzB,uBAAuB,EACvB,2BAA2B,EAC3B,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAoD7D,MAAM,OAAO,GAAuB;IAClC,MAAM,EAAE,MAAM;IACd,QAAQ,EAAE,EAAE;IACZ,MAAM,EAAE,EAAE;IACV,QAAQ,EAAE,EAAE;IACZ,eAAe,EAAE,KAAK;IACtB,QAAQ,EAAE,IAAI;IACd,aAAa,EAAE,IAAI;IACnB,oBAAoB,EAAE,KAAK;IAC3B,iBAAiB,EAAE,KAAK;IACxB,QAAQ,EAAE,KAAK;CAChB,CAAC;AAEF,MAAM,uBAAuB,GAAG,oBAAoB,CAAC;AAGrD,MAAM,mCAAmC,GAAG,IAAI,CA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;QACxC,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC,CAAC;IACxF,CAAC;CACF;AAED,SAAS,SAAS,CAAC,CAAgB,EAAE,CAAgB;IACnD,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,EAAE,GAAG,EAAE,CAAC;IAC9B,OAAO,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC;AACnC,CAAC","sourcesContent":["import {\n createReconnectController,\n type ReconnectController,\n} from '@ttt-productions/realtime-core';\nimport type { ChatMessageV1 } from '@ttt-productions/chat-core';\nimport {\n CLIENT_KINDS,\n CHAT_CLOSE_CODES,\n ChatSendRejectedPayloadSchema,\n HEARTBEAT_MS,\n TYPING_COALESCE_MS,\n HISTORY_PAGE_MAX,\n} from '@ttt-productions/chat-schemas';\nimport {\n buildFrame,\n parseFrame,\n isInboxSnapshot,\n type WireMessageRow,\n type WireChannelSnapshot,\n type RevisionKind,\n} from './wire.js';\nimport type {\n ChatHistoryPayload,\n ChatReadAckPayload,\n ChatResumePayload,\n ChatSendPayload,\n ClientFrameKind,\n ChatSendRejectionCode,\n} from '@ttt-productions/chat-schemas';\nimport type { RealtimeSocket, SocketFactory } from './socket.js';\nimport {\n wireRowToMessage,\n optimisticMessage,\n seqToMessageId,\n applyModerationOverlay,\n overlayFromRow,\n type ModerationOverlay,\n} from './map.js';\nimport type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';\nimport {\n createDiagnosticsEmitter,\n safeDiagnosticLabel,\n CHAT_CLIENT_DIAGNOSTIC_EVENTS as DIAG,\n type ChatClientDiagnosticsEmitter,\n type ChatClientDiagnosticsOption,\n} from './diagnostics.js';\nimport {\n defaultTimers,\n isChatAccessDeniedError,\n isTerminalErrorCode,\n TERMINAL_ERROR_CODE,\n MAX_PENDING_SEND_ATTEMPTS,\n PENDING_SEND_MAX_AGE_MS,\n SERVER_RETRYABLE_MAX_AGE_MS,\n SEND_RETRY_MIN_DELAY_MS,\n SEND_RETRY_MAX_DELAY_MS,\n} from './shared.js';\nimport { InitialLoadBudget } from './initial-load-budget.js';\n\ntype ChannelFramePayload<K extends ClientFrameKind> = K extends typeof CLIENT_KINDS.SEND\n ? ChatSendPayload\n : K extends typeof CLIENT_KINDS.READ_ACK\n ? ChatReadAckPayload\n : K extends typeof CLIENT_KINDS.HISTORY\n ? ChatHistoryPayload\n : K extends typeof CLIENT_KINDS.RESUME\n ? ChatResumePayload\n : Record<string, never>;\n\ninterface PendingSend {\n clientMessageId: string;\n text: string;\n sentAt: number;\n attempts: number;\n failed: boolean;\n serverRetryable: boolean;\n lastRejectionCode?: ChatSendRejectionCode;\n retryTimer: ReturnType<TransportTimers['setTimeout']> | null;\n}\n\nexport interface ChannelClientState {\n status: RealtimeStatus;\n messages: ChatMessageV1[];\n typing: string[];\n presence: string[];\n isFetchingOlder: boolean;\n hasOlder: boolean;\n lastErrorCode: string | null;\n hasLoadedInitialData: boolean;\n initialLoadFailed: boolean;\n isSynced: boolean;\n}\n\nexport interface ChannelClientConfig {\n endpoint: string;\n threadId: string;\n currentUserId: string;\n grantProvider: GrantProvider;\n socketFactory: SocketFactory;\n timers?: TransportTimers;\n reconnect?: {\n baseDelayMs?: number;\n maxDelayMs?: number;\n maxAttempts?: number | null;\n random?: () => number;\n };\n diagnostics?: ChatClientDiagnosticsOption;\n}\n\nconst INITIAL: ChannelClientState = {\n status: 'idle',\n messages: [],\n typing: [],\n presence: [],\n isFetchingOlder: false,\n hasOlder: true,\n lastErrorCode: null,\n hasLoadedInitialData: false,\n initialLoadFailed: false,\n isSynced: false,\n};\n\nconst MEMBERSHIP_PENDING_CODE = 'membership-pending';\n\ntype HistoryRequestKind = 'resync' | 'older';\nconst MEMBERSHIP_PENDING_DEFAULT_RETRY_MS = 2000;\n\n// Sound only on the channel socket: its DO auto-answers every heartbeat, so silence this long\n// means a half-open socket. A healthy idle inbox socket is silent for hours.\nconst INBOUND_SILENCE_LIMIT_MS = 50_000;\n\n// Browser `WebSocket.close()` accepts only 1000 or 3000–4999, and 4xxx belongs to the chat wire.\nconst WATCHDOG_CLOSE_CODE = 1000;\n\nexport class ChannelClient {\n private readonly timers: TransportTimers;\n private readonly controller: ReconnectController;\n private socket: RealtimeSocket | null = null;\n private state: ChannelClientState = INITIAL;\n private readonly listeners = new Set<(s: ChannelClientState) => void>();\n\n private resumeSeq = 0;\n private lastReadAck: { readSeq: number; focused: boolean } | null = null;\n private reauthAttempted = false;\n private presenceSubscribed = false;\n private heartbeatTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private lastInboundAt: number | null = null;\n private historyRequests: HistoryRequestKind[] = [];\n private typingTimers = new Map<string, ReturnType<TransportTimers['setTimeout']>>();\n private lastTypingSentAt = Number.NEGATIVE_INFINITY;\n private reconnectTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private membershipRetryTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private closedByUs = false;\n private lifecycle = 0;\n private readonly initialLoad: InitialLoadBudget;\n private overlays = new Map<number, ModerationOverlay>();\n private originalRows = new Map<number, ChatMessageV1>();\n private pendingSends = new Map<string, PendingSend>();\n private readonly diag: ChatClientDiagnosticsEmitter;\n private connectAttempt = 0;\n private reconnectCause:\n 'initial' | 'auth-expired' | 'transient-close' | 'grant-error' | 'manual-retry' = 'initial';\n private lastCloseCode: number | null = null;\n\n constructor(private readonly config: ChannelClientConfig) {\n this.timers = config.timers ?? defaultTimers;\n this.controller = createReconnectController(config.reconnect ?? {});\n this.diag = createDiagnosticsEmitter(config.diagnostics);\n this.initialLoad = new InitialLoadBudget(this.timers, () => this.reportInitialLoadFailed());\n }\n\n getState(): ChannelClientState {\n return this.state;\n }\n\n subscribe(fn: (s: ChannelClientState) => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n private setState(patch: Partial<ChannelClientState>): void {\n this.state = { ...this.state, ...patch };\n if (this.state.status !== 'open') this.state.isSynced = false;\n for (const fn of this.listeners) fn(this.state);\n }\n\n async connect(): Promise<void> {\n return this.startLifecycle(true);\n }\n\n retryNow(): void {\n if (!this.state.hasLoadedInitialData) this.initialLoad.manualRetry();\n if (this.state.status === 'closed') {\n void this.startLifecycle(false);\n return;\n }\n if (this.reconnectTimer == null) {\n if (this.state.initialLoadFailed) this.setState({ initialLoadFailed: false });\n return;\n }\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n this.controller.reset();\n this.controller.start();\n this.reconnectCause = 'manual-retry';\n this.setState({ status: 'reconnecting', initialLoadFailed: false });\n void this.openSocket();\n }\n\n private async startLifecycle(freshBudget: boolean): Promise<void> {\n if (this.state.status !== 'idle' && this.state.status !== 'closed') return;\n this.controller.reset();\n if (isTerminalErrorCode(this.state.lastErrorCode)) this.setState({ lastErrorCode: null });\n this.closedByUs = false;\n this.lifecycle += 1;\n this.reconnectCause = 'initial';\n if (!this.state.hasLoadedInitialData) this.initialLoad.begin(freshBudget);\n this.controller.start();\n this.setState({ status: 'connecting', initialLoadFailed: false });\n await this.openSocket();\n }\n\n private reportInitialLoadFailed(): void {\n if (this.state.hasLoadedInitialData || this.state.initialLoadFailed) return;\n this.setState({ initialLoadFailed: true });\n }\n\n private initialDataLoaded(): Partial<ChannelClientState> {\n this.initialLoad.loaded();\n return { hasLoadedInitialData: true, initialLoadFailed: false };\n }\n\n private async openSocket(): Promise<void> {\n const lifecycle = this.lifecycle;\n this.connectAttempt += 1;\n this.diag?.(DIAG.CONNECT_ATTEMPT, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n closeCode: this.lastCloseCode,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n });\n let grantToken: string;\n try {\n grantToken = await this.config.grantProvider();\n } catch (err) {\n if (lifecycle !== this.lifecycle) return;\n const terminal = isChatAccessDeniedError(err);\n this.diag?.(DIAG.GRANT_FAILED, { attempt: this.connectAttempt, terminal });\n if (terminal) return this.denyAccessTerminally();\n this.reconnectCause = 'grant-error';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n return this.scheduleReconnect();\n }\n if (lifecycle !== this.lifecycle || this.closedByUs) return;\n this.lastInboundAt = null;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/channel`;\n let socket: RealtimeSocket | null = null;\n const isCurrent = () => socket !== null && this.socket === socket;\n socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => {\n if (isCurrent()) this.onOpen();\n },\n onMessage: (data) => {\n if (isCurrent()) this.onMessage(data);\n },\n onClose: (code, reason) => {\n if (isCurrent()) this.onClose(code, reason);\n },\n onError: () => {\n if (isCurrent()) this.onError();\n },\n },\n });\n this.socket = socket;\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n this.lastInboundAt = this.timers.now();\n this.historyRequests = [];\n this.setState({ status: 'open', isSynced: false });\n this.diag?.(DIAG.SOCKET_OPEN, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n presenceSubscribed: this.presenceSubscribed,\n });\n this.sendFrame(CLIENT_KINDS.RESUME, { afterSeq: this.resumeSeq });\n this.diag?.(DIAG.RESUME_REQUEST, { afterSeq: this.resumeSeq, attempt: this.connectAttempt });\n if (this.presenceSubscribed) this.sendFrame(CLIENT_KINDS.PRESENCE_SUBSCRIBE, {});\n if (this.lastReadAck) this.sendFrame(CLIENT_KINDS.READ_ACK, { ...this.lastReadAck });\n this.resendPendingSends('reconnect');\n this.startHeartbeat();\n }\n\n private resendPendingSends(reason: 'reconnect' | 'membership-pending'): void {\n if (this.pendingSends.size === 0) return;\n const now = this.timers.now();\n for (const pending of [...this.pendingSends.values()]) {\n if (pending.failed) continue;\n if (pending.serverRetryable) {\n if (now - pending.sentAt >= SERVER_RETRYABLE_MAX_AGE_MS) {\n this.failPendingSend(pending.clientMessageId, pending.lastRejectionCode, true);\n continue;\n }\n this.clearSendRetryTimer(pending);\n } else {\n const tooOld = now - pending.sentAt >= PENDING_SEND_MAX_AGE_MS;\n const tooManyAttempts = pending.attempts >= MAX_PENDING_SEND_ATTEMPTS;\n if (tooOld || tooManyAttempts) {\n this.failPendingSend(pending.clientMessageId);\n continue;\n }\n }\n const sent = this.sendFrame(CLIENT_KINDS.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n });\n if (sent) pending.attempts += 1;\n this.diag?.(DIAG.SEND_RETRY, {\n clientMessageId: pending.clientMessageId,\n reason,\n attempts: pending.attempts,\n serverRetryable: pending.serverRetryable,\n ageMs: now - pending.sentAt,\n sent,\n });\n }\n }\n\n private failPendingSend(\n clientMessageId: string,\n code?: ChatSendRejectionCode,\n retryable?: boolean,\n ): void {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending || pending.failed) return;\n pending.failed = true;\n this.clearSendRetryTimer(pending);\n this.diag?.(DIAG.SEND_FAILED, {\n clientMessageId,\n code: code ?? 'send-failed',\n retryable: retryable ?? null,\n attempts: pending.attempts,\n serverRetryable: pending.serverRetryable,\n ageMs: this.timers.now() - pending.sentAt,\n });\n const next = this.state.messages.map((m) =>\n m.meta?.optimistic && m.meta?.clientMessageId === clientMessageId\n ? {\n ...m,\n meta: {\n ...m.meta,\n sendFailed: true,\n ...(code ? { sendFailureCode: code } : {}),\n ...(retryable != null ? { sendRetryable: retryable } : {}),\n },\n }\n : m,\n );\n this.setState({ messages: next, lastErrorCode: code ?? 'send-failed' });\n }\n\n private clearSendRetryTimer(pending: PendingSend): void {\n if (pending.retryTimer != null) {\n this.timers.clearTimeout(pending.retryTimer);\n pending.retryTimer = null;\n }\n }\n\n private clearPendingSend(clientMessageId: string): void {\n const pending = this.pendingSends.get(clientMessageId);\n if (pending) this.clearSendRetryTimer(pending);\n this.pendingSends.delete(clientMessageId);\n }\n\n private scheduleMembershipPendingRetry(delayMs: number): void {\n if (this.membershipRetryTimer != null) this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = this.timers.setTimeout(() => {\n this.membershipRetryTimer = null;\n if (this.closedByUs) return;\n this.resendPendingSends('membership-pending');\n }, delayMs);\n }\n\n private applySendRejected(payload: Record<string, unknown>): void {\n const parsed = ChatSendRejectedPayloadSchema.safeParse(payload);\n if (!parsed.success) {\n const rawId = (payload as { clientMessageId?: unknown }).clientMessageId;\n if (typeof rawId === 'string' && rawId.length > 0 && rawId.length <= 200) {\n const orphaned = this.pendingSends.get(rawId);\n if (orphaned && !orphaned.failed) {\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId: rawId,\n outcome: 'unparseable-fail-closed',\n });\n this.failPendingSend(rawId);\n return;\n }\n }\n this.diag?.(DIAG.SEND_REJECTED, { clientMessageId: null, outcome: 'unparseable-dropped' });\n return;\n }\n const { clientMessageId, code, retryable, retryAfterMs } = parsed.data;\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending || pending.failed) {\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId,\n code,\n retryable,\n outcome: 'no-pending-send',\n });\n return;\n }\n\n if (!retryable) {\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId,\n code,\n retryable: false,\n outcome: 'terminal',\n });\n this.failPendingSend(clientMessageId, code, false);\n return;\n }\n\n pending.serverRetryable = true;\n pending.lastRejectionCode = code;\n if (this.timers.now() - pending.sentAt >= SERVER_RETRYABLE_MAX_AGE_MS) {\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId,\n code,\n retryable: true,\n outcome: 'budget-exhausted',\n });\n this.failPendingSend(clientMessageId, code, true);\n return;\n }\n const delayMs = this.clampRetryDelay(retryAfterMs);\n this.diag?.(DIAG.SEND_REJECTED, {\n clientMessageId,\n code,\n retryable: true,\n outcome: 'retry-scheduled',\n delayMs,\n });\n this.scheduleSendRetry(clientMessageId, delayMs);\n }\n\n private scheduleSendRetry(clientMessageId: string, delayMs: number): void {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending) return;\n this.clearSendRetryTimer(pending);\n pending.retryTimer = this.timers.setTimeout(() => {\n pending.retryTimer = null;\n if (this.closedByUs) return;\n const current = this.pendingSends.get(clientMessageId);\n if (!current || current.failed) return;\n if (this.timers.now() - current.sentAt >= SERVER_RETRYABLE_MAX_AGE_MS) {\n this.failPendingSend(clientMessageId, current.lastRejectionCode, true);\n return;\n }\n const sent = this.sendFrame(CLIENT_KINDS.SEND, {\n clientMessageId: current.clientMessageId,\n text: current.text,\n });\n this.diag?.(DIAG.SEND_RETRY, {\n clientMessageId: current.clientMessageId,\n reason: 'scheduled',\n attempts: current.attempts,\n serverRetryable: current.serverRetryable,\n ageMs: this.timers.now() - current.sentAt,\n sent,\n });\n const remainingMs =\n SERVER_RETRYABLE_MAX_AGE_MS -\n (this.timers.now() - current.sentAt) +\n SEND_RETRY_MIN_DELAY_MS;\n current.retryTimer = this.timers.setTimeout(() => {\n current.retryTimer = null;\n if (this.closedByUs) return;\n const atDeadline = this.pendingSends.get(clientMessageId);\n if (!atDeadline || atDeadline.failed) return;\n if (this.timers.now() - atDeadline.sentAt >= SERVER_RETRYABLE_MAX_AGE_MS) {\n this.failPendingSend(clientMessageId, atDeadline.lastRejectionCode, true);\n }\n }, remainingMs);\n }, delayMs);\n }\n\n private clampRetryDelay(retryAfterMs: number | undefined): number {\n const raw =\n typeof retryAfterMs === 'number' && retryAfterMs > 0\n ? retryAfterMs\n : MEMBERSHIP_PENDING_DEFAULT_RETRY_MS;\n return Math.min(Math.max(raw, SEND_RETRY_MIN_DELAY_MS), SEND_RETRY_MAX_DELAY_MS);\n }\n\n private failAllPendingSends(): void {\n for (const clientMessageId of [...this.pendingSends.keys()]) {\n this.failPendingSend(clientMessageId);\n }\n }\n\n retrySend(clientMessageId: string): boolean {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending) return false;\n this.clearSendRetryTimer(pending);\n pending.failed = false;\n pending.serverRetryable = false;\n pending.lastRejectionCode = undefined;\n pending.sentAt = this.timers.now();\n const sent = this.sendFrame(CLIENT_KINDS.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n });\n pending.attempts = sent ? 1 : 0;\n this.diag?.(DIAG.SEND_RETRY, {\n clientMessageId,\n reason: 'manual',\n attempts: pending.attempts,\n serverRetryable: false,\n ageMs: 0,\n sent,\n });\n const next = this.state.messages.map((m) => {\n if (!(\n m.meta?.optimistic &&\n m.meta?.clientMessageId === clientMessageId &&\n m.meta?.sendFailed\n )) {\n return m;\n }\n const {\n sendFailed: _sendFailed,\n sendFailureCode: _sendFailureCode,\n sendRetryable: _sendRetryable,\n ...restMeta\n } = m.meta;\n return { ...m, meta: { ...restMeta } };\n });\n this.setState({ messages: next, lastErrorCode: null });\n return true;\n }\n\n private onError(): void {\n // The close handler does the backoff; onerror is advisory in browsers.\n }\n\n private onClose(code: number, _reason: string): void {\n this.stopHeartbeat();\n this.socket = null;\n this.lastInboundAt = null;\n this.lastCloseCode = code;\n if (this.state.isFetchingOlder) this.setState({ isFetchingOlder: false });\n if (this.closedByUs) {\n this.diag?.(DIAG.SOCKET_CLOSE, {\n code,\n closedByUs: true,\n outcome: 'closed',\n resumeSeq: this.resumeSeq,\n });\n this.setState({ status: 'closed' });\n return;\n }\n if (code === CHAT_CLOSE_CODES.AUTH_EXPIRED && !this.reauthAttempted) {\n this.reauthAttempted = true;\n this.reconnectCause = 'auth-expired';\n this.diag?.(DIAG.SOCKET_CLOSE, {\n code,\n closedByUs: false,\n outcome: 're-grant',\n resumeSeq: this.resumeSeq,\n });\n this.setState({ status: 'reconnecting' });\n void this.openSocket();\n return;\n }\n if (code === CHAT_CLOSE_CODES.REVOKED) {\n this.closedByUs = true;\n this.controller.close();\n this.diag?.(DIAG.SOCKET_CLOSE, {\n code,\n closedByUs: false,\n outcome: 'revoked',\n resumeSeq: this.resumeSeq,\n });\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.REVOKED });\n this.reportInitialLoadFailed();\n return;\n }\n this.reconnectCause = 'transient-close';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n this.diag?.(DIAG.SOCKET_CLOSE, {\n code,\n closedByUs: false,\n outcome: 'reconnect',\n resumeSeq: this.resumeSeq,\n });\n this.scheduleReconnect();\n }\n\n private scheduleReconnect(): void {\n const delay = this.controller.onClose();\n this.diag?.(DIAG.RECONNECT_SCHEDULED, {\n delayMs: delay,\n cause: this.reconnectCause,\n attempt: this.connectAttempt,\n resumeSeq: this.resumeSeq,\n });\n if (delay == null) {\n this.failAllPendingSends();\n this.setState({ status: 'closed' });\n this.reportInitialLoadFailed();\n return;\n }\n this.setState({ status: 'reconnecting' });\n const lifecycle = this.lifecycle;\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs || lifecycle !== this.lifecycle) return;\n void this.openSocket();\n }, delay);\n }\n\n private denyAccessTerminally(): void {\n this.closedByUs = true;\n this.controller.close();\n this.initialLoad.dispose();\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.ACCESS_DENIED });\n }\n\n private onMessage(data: string): void {\n const frame = parseFrame(data);\n if (!frame || !frame.type) {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'unparseable', reason: 'bad-envelope' });\n return;\n }\n this.lastInboundAt = this.timers.now();\n const payload = frame.payload ?? {};\n switch (frame.type) {\n case 'message':\n return this.applyMessage((payload as { message: WireMessageRow }).message, 'live');\n case 'ack':\n return this.applyAck(\n payload as { clientMessageId?: string; seq?: number; readSeq?: number },\n );\n case 'history-page':\n return this.applyHistoryPage((payload as { messages: WireMessageRow[] }).messages ?? []);\n case 'presence':\n return this.setState({ presence: (payload as { online: string[] }).online ?? [] });\n case 'typing':\n return this.applyTyping((payload as { uid: string }).uid);\n case 'snapshot':\n return this.applyChannelSnapshot(payload as unknown as WireChannelSnapshot);\n case 'send-rejected':\n return this.applySendRejected(payload);\n case 'error': {\n const code = String((payload as { code?: unknown }).code ?? 'error');\n // An older Worker sends this uncorrelated form, with no clientMessageId to target one send.\n if (code === MEMBERSHIP_PENDING_CODE) {\n const raw = (payload as { retryAfterMs?: unknown }).retryAfterMs;\n const delay = this.clampRetryDelay(typeof raw === 'number' ? raw : undefined);\n this.diag?.(DIAG.ERROR_FRAME, {\n code: MEMBERSHIP_PENDING_CODE,\n correlated: false,\n delayMs: delay,\n pendingSends: this.pendingSends.size,\n });\n for (const pending of this.pendingSends.values()) {\n if (!pending.failed) {\n pending.serverRetryable = true;\n pending.lastRejectionCode = MEMBERSHIP_PENDING_CODE;\n }\n }\n return this.scheduleMembershipPendingRetry(delay);\n }\n this.diag?.(DIAG.ERROR_FRAME, { code: safeDiagnosticLabel(code), correlated: false });\n return this.setState({ lastErrorCode: code });\n }\n case 'revision':\n return this.applyRevisionFrame(\n payload as { messageSeq?: number; kind?: RevisionKind; messageRevision?: number },\n );\n case 'heartbeat-ack':\n return;\n default:\n this.diag?.(DIAG.FRAME_DROPPED, {\n kind: safeDiagnosticLabel(frame.type),\n reason: 'unknown-type',\n });\n return;\n }\n }\n\n private applyRevisionFrame(payload: {\n messageSeq?: number;\n kind?: RevisionKind;\n messageRevision?: number;\n }): void {\n const seq = payload.messageSeq;\n const kind = payload.kind;\n const messageRevision = payload.messageRevision;\n if (typeof seq !== 'number' || kind == null || typeof messageRevision !== 'number') {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'revision', reason: 'malformed-payload' });\n return;\n }\n const prev = this.overlays.get(seq);\n if (prev && prev.messageRevision >= messageRevision) {\n this.diag?.(DIAG.FRAME_DROPPED, {\n kind: 'revision',\n reason: 'stale-revision',\n seq,\n messageRevision,\n heldRevision: prev.messageRevision,\n });\n return;\n }\n this.overlays.set(seq, { kind, messageRevision });\n const messageId = seqToMessageId(seq);\n const original = this.originalRows.get(seq);\n const rendered =\n Boolean(original) && this.state.messages.some((m) => m.messageId === messageId);\n this.diag?.(DIAG.REVISION_APPLIED, {\n seq,\n kind,\n messageRevision,\n rendered,\n });\n if (rendered && original) {\n const overlaid = applyModerationOverlay(original, this.effectiveOverlay(seq, null));\n const next = this.state.messages.map((m) => (m.messageId === messageId ? overlaid : m));\n this.setState({ messages: next });\n }\n }\n\n private effectiveOverlay(\n seq: number,\n rowOverlay: ModerationOverlay | null,\n ): ModerationOverlay | null {\n const fromFrame = this.overlays.get(seq) ?? null;\n if (!rowOverlay) return fromFrame;\n if (!fromFrame) return rowOverlay;\n return fromFrame.messageRevision >= rowOverlay.messageRevision ? fromFrame : rowOverlay;\n }\n\n private renderRow(row: WireMessageRow): ChatMessageV1 {\n const mapped = wireRowToMessage(row, this.config.threadId);\n this.originalRows.set(row.seq, mapped);\n return applyModerationOverlay(mapped, this.effectiveOverlay(row.seq, overlayFromRow(row)));\n }\n\n private applyChannelSnapshot(snap: WireChannelSnapshot): void {\n if (isInboxSnapshot(snap as never)) {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'snapshot', reason: 'inbox-snapshot-on-channel' });\n return;\n }\n if (typeof snap.lastMessageSeq !== 'number') {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'snapshot', reason: 'missing-last-message-seq' });\n return;\n }\n\n const resync = snap.resync !== false;\n const cursorBefore = this.resumeSeq;\n const delta = Array.isArray(snap.delta) ? snap.delta : [];\n\n if (!resync) {\n for (const row of delta) this.applyMessage(row, 'delta');\n if (snap.lastMessageSeq > this.resumeSeq) this.resumeSeq = snap.lastMessageSeq;\n this.diag?.(DIAG.RESUME_RESULT, {\n lastMessageSeq: snap.lastMessageSeq,\n resync: false,\n deltaCount: delta.length,\n cursorBefore,\n cursorAfter: this.resumeSeq,\n readSeq: typeof snap.readSeq === 'number' ? snap.readSeq : null,\n });\n this.setState({\n ...(this.state.hasLoadedInitialData ? {} : this.initialDataLoaded()),\n isSynced: true,\n });\n return;\n }\n\n this.overlays.clear();\n this.originalRows.clear();\n this.resumeSeq = 0;\n const priorCount = this.state.messages.length;\n const keptOptimistic = this.state.messages.filter((m) => m.meta?.optimistic);\n this.diag?.(DIAG.RESUME_RESULT, {\n lastMessageSeq: snap.lastMessageSeq,\n resync: true,\n deltaCount: delta.length,\n cursorBefore,\n cursorAfter: 0,\n readSeq: typeof snap.readSeq === 'number' ? snap.readSeq : null,\n });\n this.diag?.(DIAG.RESYNC_DROPPED_TAIL, {\n removedCount: priorCount - keptOptimistic.length,\n keptOptimistic: keptOptimistic.length,\n });\n this.setState({ messages: keptOptimistic, hasOlder: true, isFetchingOlder: false });\n this.requestHistory(null, 'resync');\n }\n\n private applyMessage(row: WireMessageRow, source: 'live' | 'delta'): void {\n if (!row || typeof row.seq !== 'number') {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'message', source, reason: 'missing-seq' });\n return;\n }\n const prior = this.diag ? this.priorRowFacts(row) : null;\n const cursorBefore = this.resumeSeq;\n const mapped = this.renderRow(row);\n this.mergeMessage(mapped, row);\n if (row.seq > this.resumeSeq) this.resumeSeq = row.seq;\n if (!this.diag || !prior) return;\n\n const notable = row.moderationKind != null || prior.reconciledOptimistic;\n if (source === 'delta' && !notable) return;\n this.diag(DIAG.FRAME_APPLIED, {\n kind: 'message',\n source,\n seq: row.seq,\n hasClientMessageId: Boolean(row.clientMessageId),\n moderationKind: row.moderationKind ?? null,\n op: prior.reconciledOptimistic\n ? 'optimistic-reconcile'\n : prior.hadRow\n ? 'replace-by-seq'\n : 'insert',\n cursorBefore,\n cursorAfter: this.resumeSeq,\n });\n }\n\n private priorRowFacts(row: WireMessageRow): {\n hadRow: boolean;\n reconciledOptimistic: boolean;\n } {\n const messageId = seqToMessageId(row.seq);\n const existing = this.state.messages.find((m) => m.messageId === messageId);\n return {\n hadRow: existing != null,\n reconciledOptimistic: Boolean(\n row.clientMessageId &&\n this.state.messages.some(\n (m) => m.meta?.optimistic && m.meta?.clientMessageId === row.clientMessageId,\n ),\n ),\n };\n }\n\n private mergeMessage(mapped: ChatMessageV1, row: WireMessageRow): void {\n if (row.clientMessageId) this.clearPendingSend(row.clientMessageId);\n const next = this.state.messages.filter(\n (m) =>\n m.messageId !== mapped.messageId &&\n (m.meta?.clientMessageId !== row.clientMessageId || !m.meta?.optimistic),\n );\n next.push(mapped);\n next.sort(sortBySeq);\n this.setState({ messages: next });\n }\n\n private applyAck(payload: { clientMessageId?: string; seq?: number; readSeq?: number }): void {\n if (payload.clientMessageId == null || typeof payload.seq !== 'number') return;\n const seq = payload.seq;\n const cmid = payload.clientMessageId;\n this.diag?.(DIAG.SEND_ACK, {\n clientMessageId: cmid,\n seq,\n cursorBefore: this.resumeSeq,\n cursorAfter: seq > this.resumeSeq ? seq : this.resumeSeq,\n wasPending: this.pendingSends.has(cmid),\n });\n this.clearPendingSend(cmid);\n const next = this.state.messages.map((m) => {\n if (!m.meta?.optimistic || m.meta?.clientMessageId !== cmid) return m;\n const {\n sendFailed: _sendFailed,\n sendFailureCode: _sendFailureCode,\n sendRetryable: _sendRetryable,\n ...restMeta\n } = m.meta;\n return {\n ...m,\n messageId: seqToMessageId(seq),\n meta: { ...restMeta, optimistic: false, seq },\n };\n });\n next.sort(sortBySeq);\n if (seq > this.resumeSeq) this.resumeSeq = seq;\n this.setState({ messages: next });\n }\n\n private applyHistoryPage(rows: WireMessageRow[]): void {\n const cursorBefore = this.resumeSeq;\n const answersResync = this.historyRequests.shift() === 'resync';\n const mapped = rows.map((r) => this.renderRow(r));\n const incomingCmids = new Set<string>();\n for (const r of rows) {\n if (r.clientMessageId) {\n incomingCmids.add(r.clientMessageId);\n this.clearPendingSend(r.clientMessageId);\n }\n }\n const bySeq = new Map<string, ChatMessageV1>();\n for (const m of this.state.messages) {\n if (\n m.meta?.optimistic &&\n typeof m.meta?.clientMessageId === 'string' &&\n incomingCmids.has(m.meta.clientMessageId)\n ) {\n continue;\n }\n bySeq.set(m.messageId, m);\n }\n for (const m of mapped) bySeq.set(m.messageId, m);\n const merged = [...bySeq.values()].sort(sortBySeq);\n for (const r of rows) if (r.seq > this.resumeSeq) this.resumeSeq = r.seq;\n this.setState({\n messages: merged,\n isFetchingOlder: false,\n hasOlder: rows.length >= HISTORY_PAGE_MAX,\n ...(this.state.hasLoadedInitialData ? {} : this.initialDataLoaded()),\n ...(answersResync ? { isSynced: true } : {}),\n });\n if (!this.diag) return;\n const seqs = rows.map((r) => r.seq).filter((s): s is number => typeof s === 'number');\n this.diag(DIAG.HISTORY_PAGE, {\n count: rows.length,\n minSeq: seqs.length > 0 ? Math.min(...seqs) : null,\n maxSeq: seqs.length > 0 ? Math.max(...seqs) : null,\n cursorBefore,\n cursorAfter: this.resumeSeq,\n reconciledOptimistic: incomingCmids.size,\n hasOlder: rows.length >= HISTORY_PAGE_MAX,\n total: merged.length,\n });\n }\n\n private applyTyping(uid: string): void {\n if (!uid || uid === this.config.currentUserId) return;\n if (!this.state.typing.includes(uid)) this.setState({ typing: [...this.state.typing, uid] });\n const prev = this.typingTimers.get(uid);\n if (prev) this.timers.clearTimeout(prev);\n this.typingTimers.set(\n uid,\n this.timers.setTimeout(() => {\n this.typingTimers.delete(uid);\n this.setState({ typing: this.state.typing.filter((u) => u !== uid) });\n }, TYPING_COALESCE_MS * 2),\n );\n }\n\n private sendFrame<K extends ClientFrameKind>(type: K, payload: ChannelFramePayload<K>): boolean {\n if (!this.socket || !this.socket.isOpen) return false;\n this.socket.send(buildFrame(type, payload));\n return true;\n }\n\n send(args: { clientMessageId: string; text: string }): boolean {\n const sent = this.sendFrame(CLIENT_KINDS.SEND, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n });\n if (!sent) {\n this.diag?.(DIAG.SEND_FAILED, {\n clientMessageId: args.clientMessageId,\n code: 'send-failed',\n retryable: null,\n attempts: 0,\n reason: 'socket-not-open',\n });\n this.setState({ lastErrorCode: 'send-failed' });\n return false;\n }\n const now = this.timers.now();\n this.pendingSends.set(args.clientMessageId, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n sentAt: now,\n attempts: 1,\n failed: false,\n serverRetryable: false,\n retryTimer: null,\n });\n const echo = optimisticMessage({\n clientMessageId: args.clientMessageId,\n threadId: this.config.threadId,\n senderId: this.config.currentUserId,\n text: args.text,\n createdAt: now,\n });\n const next = [...this.state.messages, echo].sort(sortBySeq);\n this.setState({ messages: next, lastErrorCode: null });\n this.diag?.(DIAG.SEND_OPTIMISTIC, {\n clientMessageId: args.clientMessageId,\n pendingSends: this.pendingSends.size,\n });\n return true;\n }\n\n readAck(readSeq: number, focused: boolean): boolean {\n this.lastReadAck = { readSeq, focused };\n return this.sendFrame(CLIENT_KINDS.READ_ACK, { readSeq, focused });\n }\n\n typing(): void {\n const now = this.timers.now();\n if (now - this.lastTypingSentAt < TYPING_COALESCE_MS) return;\n this.lastTypingSentAt = now;\n this.sendFrame(CLIENT_KINDS.TYPING, {});\n }\n\n presenceSubscribe(): void {\n this.presenceSubscribed = true;\n this.sendFrame(CLIENT_KINDS.PRESENCE_SUBSCRIBE, {});\n }\n\n presenceUnsubscribe(): void {\n this.presenceSubscribed = false;\n this.sendFrame(CLIENT_KINDS.PRESENCE_UNSUBSCRIBE, {});\n this.setState({ presence: [] });\n }\n\n fetchOlder(): void {\n if (this.state.isFetchingOlder || !this.state.hasOlder) return;\n const oldest = this.state.messages.find((m) => typeof m.meta?.seq === 'number');\n const beforeSeq =\n oldest && typeof oldest.meta?.seq === 'number' ? (oldest.meta.seq as number) : null;\n this.setState({ isFetchingOlder: true });\n if (!this.requestHistory(beforeSeq, 'older')) this.setState({ isFetchingOlder: false });\n }\n\n private requestHistory(beforeSeq: number | null, kind: HistoryRequestKind): boolean {\n const sent = this.sendFrame(CLIENT_KINDS.HISTORY, { beforeSeq, limit: HISTORY_PAGE_MAX });\n if (sent) this.historyRequests.push(kind);\n this.diag?.(DIAG.HISTORY_REQUEST, { beforeSeq, limit: HISTORY_PAGE_MAX, sent });\n return sent;\n }\n\n private startHeartbeat(): void {\n this.stopHeartbeat();\n const tick = () => {\n if (!this.socket || !this.socket.isOpen) return;\n if (this.isInboundSilent()) return this.closeDeadSocket();\n this.sendFrame(CLIENT_KINDS.HEARTBEAT, {});\n this.heartbeatTimer = this.timers.setTimeout(tick, HEARTBEAT_MS);\n };\n this.heartbeatTimer = this.timers.setTimeout(tick, HEARTBEAT_MS);\n }\n\n private stopHeartbeat(): void {\n if (this.heartbeatTimer != null) {\n this.timers.clearTimeout(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n private isInboundSilent(): boolean {\n if (this.lastInboundAt == null) return false;\n return this.timers.now() - this.lastInboundAt >= INBOUND_SILENCE_LIMIT_MS;\n }\n\n private closeDeadSocket(): void {\n const socket = this.socket;\n this.diag?.(DIAG.SOCKET_LIVENESS_TIMEOUT, {\n silentMs: this.lastInboundAt == null ? null : this.timers.now() - this.lastInboundAt,\n thresholdMs: INBOUND_SILENCE_LIMIT_MS,\n attempt: this.connectAttempt,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n });\n this.lastInboundAt = null;\n socket?.close(WATCHDOG_CLOSE_CODE, 'client liveness timeout');\n }\n\n close(): void {\n this.closedByUs = true;\n this.lifecycle += 1;\n this.controller.close();\n this.initialLoad.dispose();\n this.stopHeartbeat();\n this.lastInboundAt = null;\n for (const t of this.typingTimers.values()) this.timers.clearTimeout(t);\n this.typingTimers.clear();\n this.overlays.clear();\n this.originalRows.clear();\n for (const pending of this.pendingSends.values()) this.clearSendRetryTimer(pending);\n this.pendingSends.clear();\n if (this.reconnectTimer != null) {\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.membershipRetryTimer != null) {\n this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = null;\n }\n if (this.socket) {\n const socket = this.socket;\n this.socket = null;\n socket.close(1000, 'client teardown');\n }\n this.setState({ status: 'closed', typing: [], presence: [], isFetchingOlder: false });\n }\n}\n\nfunction sortBySeq(a: ChatMessageV1, b: ChatMessageV1): number {\n const sa = typeof a.meta?.seq === 'number' ? (a.meta.seq as number) : Number.POSITIVE_INFINITY;\n const sb = typeof b.meta?.seq === 'number' ? (b.meta.seq as number) : Number.POSITIVE_INFINITY;\n if (sa !== sb) return sa - sb;\n return a.createdAt - b.createdAt;\n}\n"]}
|
|
@@ -1,101 +1,39 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A structured diagnostic sink. `event` is one of the stable
|
|
3
|
-
* {@link CHAT_CLIENT_DIAGNOSTIC_EVENTS} names; `data` is a compact, content-free
|
|
4
|
-
* payload (ids/seqs/states/counts/codes only). Supplying a sink lets the app
|
|
5
|
-
* route entries into its own logger; `true` uses the console.debug default.
|
|
6
|
-
*/
|
|
7
1
|
export type ChatClientDiagnosticsSink = (event: string, data: Record<string, unknown>) => void;
|
|
8
|
-
/**
|
|
9
|
-
* The additive `diagnostics` config value: `false`/absent = off (the default and
|
|
10
|
-
* the only production posture), `true` = the single-line `console.debug` sink,
|
|
11
|
-
* or a custom {@link ChatClientDiagnosticsSink}.
|
|
12
|
-
*/
|
|
13
2
|
export type ChatClientDiagnosticsOption = boolean | ChatClientDiagnosticsSink;
|
|
14
|
-
/** The bound emitter, or `null` when diagnostics are off (the zero-overhead path). */
|
|
15
3
|
export type ChatClientDiagnosticsEmitter = ChatClientDiagnosticsSink | null;
|
|
16
|
-
/**
|
|
17
|
-
* Stable event names. These are a QUERY CONTRACT — Cloud Logging filters, E2E
|
|
18
|
-
* console greps, and any later alert metric key on them, so a name is added or
|
|
19
|
-
* retired deliberately, never renamed in place.
|
|
20
|
-
*/
|
|
21
4
|
export declare const CHAT_CLIENT_DIAGNOSTIC_EVENTS: {
|
|
22
|
-
/** A socket open is being attempted (per attempt, with the reconnect cause). */
|
|
23
5
|
readonly CONNECT_ATTEMPT: "chat_client_connect_attempt";
|
|
24
|
-
/** The grant mint failed before a socket existed (terminal vs. retryable). */
|
|
25
6
|
readonly GRANT_FAILED: "chat_client_grant_failed";
|
|
26
|
-
/** The socket reached OPEN (the point the resume cursor is sent from). */
|
|
27
7
|
readonly SOCKET_OPEN: "chat_client_socket_open";
|
|
28
|
-
/** The socket closed, with the code and what the client decided to do next. */
|
|
29
8
|
readonly SOCKET_CLOSE: "chat_client_socket_close";
|
|
30
|
-
/**
|
|
31
|
-
* CHANNEL ONLY. The dead-socket watchdog closed a socket that had gone silent
|
|
32
|
-
* past the client's inbound-silence threshold (the channel DO auto-acks every
|
|
33
|
-
* heartbeat, so silence there is provable death). One line per detection —
|
|
34
|
-
* never per heartbeat — followed by the ordinary socket_close/reconnect lines.
|
|
35
|
-
*/
|
|
36
9
|
readonly SOCKET_LIVENESS_TIMEOUT: "chat_client_socket_liveness_timeout";
|
|
37
|
-
/** A reconnect was scheduled (`delayMs`) or given up on (`delayMs: null`). */
|
|
38
10
|
readonly RECONNECT_SCHEDULED: "chat_client_reconnect_scheduled";
|
|
39
|
-
/** The resume cursor sent to the DO. */
|
|
40
11
|
readonly RESUME_REQUEST: "chat_client_resume_request";
|
|
41
|
-
/** The DO's snapshot answer + how the cursor moved because of it. */
|
|
42
12
|
readonly RESUME_RESULT: "chat_client_resume_result";
|
|
43
|
-
/** A `resync: true` snapshot dropped the local tail (removal, not upsert). */
|
|
44
13
|
readonly RESYNC_DROPPED_TAIL: "chat_client_resync_dropped_tail";
|
|
45
|
-
/** A frame was applied to UI state (insert / replace-by-seq / optimistic reconcile). */
|
|
46
14
|
readonly FRAME_APPLIED: "chat_client_frame_applied";
|
|
47
|
-
/** A frame was NOT applied, with the reason. */
|
|
48
15
|
readonly FRAME_DROPPED: "chat_client_frame_dropped";
|
|
49
|
-
/** A moderation revision overlay was recorded (and whether a loaded row re-rendered). */
|
|
50
16
|
readonly REVISION_APPLIED: "chat_client_revision_applied";
|
|
51
|
-
/** A history page was requested (cursor + limit). */
|
|
52
17
|
readonly HISTORY_REQUEST: "chat_client_history_request";
|
|
53
|
-
/** A history page was applied: size, seq range, cursor advance. */
|
|
54
18
|
readonly HISTORY_PAGE: "chat_client_history_page";
|
|
55
|
-
/** An optimistic send was rendered and its frame written. */
|
|
56
19
|
readonly SEND_OPTIMISTIC: "chat_client_send_optimistic";
|
|
57
|
-
/** A send was acked by the server (seq assigned). */
|
|
58
20
|
readonly SEND_ACK: "chat_client_send_ack";
|
|
59
|
-
/** A correlated `send-rejected` (or its legacy uncorrelated form) was handled. */
|
|
60
21
|
readonly SEND_REJECTED: "chat_client_send_rejected";
|
|
61
|
-
/** A send was re-emitted (reconnect resume / scheduled hint / manual retry). */
|
|
62
22
|
readonly SEND_RETRY: "chat_client_send_retry";
|
|
63
|
-
/** A send reached its visible failed state, with the reason. */
|
|
64
23
|
readonly SEND_FAILED: "chat_client_send_failed";
|
|
65
|
-
/** An uncorrelated server `error` frame code. */
|
|
66
24
|
readonly ERROR_FRAME: "chat_client_error_frame";
|
|
67
|
-
/** An inbox socket open is being attempted (per attempt, with the reconnect cause). */
|
|
68
25
|
readonly INBOX_CONNECT_ATTEMPT: "chat_client_inbox_connect_attempt";
|
|
69
|
-
/** The inbox grant mint failed before a socket existed (terminal vs. retryable). */
|
|
70
26
|
readonly INBOX_GRANT_FAILED: "chat_client_inbox_grant_failed";
|
|
71
|
-
/** The inbox socket reached OPEN (the point `resume` is sent from). */
|
|
72
27
|
readonly INBOX_SOCKET_OPEN: "chat_client_inbox_socket_open";
|
|
73
|
-
/** The inbox socket closed, with the code and what the client decided to do next. */
|
|
74
28
|
readonly INBOX_SOCKET_CLOSE: "chat_client_inbox_socket_close";
|
|
75
|
-
/** An inbox reconnect was scheduled (`delayMs`) or given up on (`delayMs: null`). */
|
|
76
29
|
readonly INBOX_RECONNECT_SCHEDULED: "chat_client_inbox_reconnect_scheduled";
|
|
77
|
-
/** The cursorless inbox `resume` was sent (the DO answers with a full snapshot). */
|
|
78
30
|
readonly INBOX_RESUME_REQUEST: "chat_client_inbox_resume_request";
|
|
79
|
-
/** An authoritative inbox snapshot was applied — registry SIZES only, never refs. */
|
|
80
31
|
readonly INBOX_SNAPSHOT_APPLIED: "chat_client_inbox_snapshot_applied";
|
|
81
|
-
/** The unread projection actually CHANGED (dock dot and/or per-row dot count). */
|
|
82
32
|
readonly INBOX_UNREAD_UPDATED: "chat_client_inbox_unread_updated";
|
|
83
|
-
/** An inbox frame was NOT applied, with the reason. */
|
|
84
33
|
readonly INBOX_FRAME_DROPPED: "chat_client_inbox_frame_dropped";
|
|
85
|
-
/** A mark-read was written to the socket (no optimistic local clear). */
|
|
86
34
|
readonly INBOX_MARK_READ: "chat_client_inbox_mark_read";
|
|
87
35
|
};
|
|
88
36
|
export type ChatClientDiagnosticEventName = (typeof CHAT_CLIENT_DIAGNOSTIC_EVENTS)[keyof typeof CHAT_CLIENT_DIAGNOSTIC_EVENTS];
|
|
89
|
-
/**
|
|
90
|
-
* Clamp a server-supplied label before it enters a log line. Frame types and
|
|
91
|
-
* error codes are protocol tokens, not user content, but they arrive from the
|
|
92
|
-
* wire — bound them so a hostile/buggy peer cannot emit an unbounded line.
|
|
93
|
-
*/
|
|
94
37
|
export declare function safeDiagnosticLabel(raw: unknown): string;
|
|
95
|
-
/**
|
|
96
|
-
* Build the emitter for a `diagnostics` config value. Returns `null` when
|
|
97
|
-
* diagnostics are off so call sites can use `this.diag?.(...)` — with optional
|
|
98
|
-
* call syntax the argument object is not constructed at all on the off path.
|
|
99
|
-
*/
|
|
100
38
|
export declare function createDiagnosticsEmitter(option: ChatClientDiagnosticsOption | undefined): ChatClientDiagnosticsEmitter;
|
|
101
39
|
//# sourceMappingURL=diagnostics.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.d.ts","sourceRoot":"","sources":["../../src/realtime/diagnostics.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"diagnostics.d.ts","sourceRoot":"","sources":["../../src/realtime/diagnostics.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,yBAAyB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;AAE/F,MAAM,MAAM,2BAA2B,GAAG,OAAO,GAAG,yBAAyB,CAAC;AAE9E,MAAM,MAAM,4BAA4B,GAAG,yBAAyB,GAAG,IAAI,CAAC;AAG5E,eAAO,MAAM,6BAA6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgChC,CAAC;AAEX,MAAM,MAAM,6BAA6B,GACvC,CAAC,OAAO,6BAA6B,CAAC,CAAC,MAAM,OAAO,6BAA6B,CAAC,CAAC;AAIrF,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAIxD;AAOD,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,2BAA2B,GAAG,SAAS,GAC9C,4BAA4B,CAU9B"}
|