@ttt-productions/chat-react 0.12.15 → 0.13.1
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 +8 -8
- package/dist/hooks/useChatMessages.d.ts.map +1 -1
- package/dist/hooks/useChatMessages.js +0 -1
- package/dist/hooks/useChatMessages.js.map +1 -1
- package/dist/index.d.ts +2 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -2
- package/dist/index.js.map +1 -1
- package/dist/realtime/channel-client.d.ts +6 -13
- package/dist/realtime/channel-client.d.ts.map +1 -1
- package/dist/realtime/channel-client.js +7 -56
- package/dist/realtime/channel-client.js.map +1 -1
- package/dist/realtime/diagnostics.d.ts +0 -2
- package/dist/realtime/diagnostics.d.ts.map +1 -1
- package/dist/realtime/diagnostics.js +7 -5
- package/dist/realtime/diagnostics.js.map +1 -1
- package/dist/realtime/map.d.ts +4 -7
- package/dist/realtime/map.d.ts.map +1 -1
- package/dist/realtime/map.js +4 -41
- package/dist/realtime/map.js.map +1 -1
- package/dist/realtime/wire.d.ts +5 -5
- package/dist/realtime/wire.d.ts.map +1 -1
- package/dist/realtime/wire.js.map +1 -1
- package/dist/types.d.ts +0 -41
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/ui/ChatShell.d.ts +2 -4
- package/dist/ui/ChatShell.d.ts.map +1 -1
- package/dist/ui/ChatShell.js +9 -14
- package/dist/ui/ChatShell.js.map +1 -1
- package/dist/ui/Composer.d.ts +5 -28
- package/dist/ui/Composer.d.ts.map +1 -1
- package/dist/ui/Composer.js +8 -104
- 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 +6 -75
- package/dist/ui/MessageItemDefault.js.map +1 -1
- package/dist/ui/MessageList.d.ts +0 -3
- package/dist/ui/MessageList.d.ts.map +1 -1
- package/dist/ui/MessageList.js +2 -2
- package/dist/ui/MessageList.js.map +1 -1
- package/package.json +3 -6
- package/src/styles/chat.css +0 -139
- package/dist/context/ChatAttachmentMediaContext.d.ts +0 -37
- package/dist/context/ChatAttachmentMediaContext.d.ts.map +0 -1
- package/dist/context/ChatAttachmentMediaContext.js +0 -17
- package/dist/context/ChatAttachmentMediaContext.js.map +0 -1
- package/dist/context/ChatAttachmentUrlContext.d.ts +0 -25
- package/dist/context/ChatAttachmentUrlContext.d.ts.map +0 -1
- package/dist/context/ChatAttachmentUrlContext.js +0 -21
- package/dist/context/ChatAttachmentUrlContext.js.map +0 -1
|
@@ -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,EAAE,yBAAyB,EAA4B,MAAM,gCAAgC,CAAC;AAErG,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,UAAU,EACV,eAAe,EACf,6BAA6B,GAK9B,MAAM,WAAW,CAAC;AAEnB,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,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EAChB,yBAAyB,EACzB,uBAAuB,EACvB,2BAA2B,EAC3B,uBAAuB,EACvB,uBAAuB,GACxB,M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CAAC,cAAc,GAAG,IAAI,CAAC;QAC7B,CAAC;QACD,IAAI,IAAI,CAAC,oBAAoB,IAAI,IAAI,EAAE,CAAC;YACtC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;YACpD,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC;QACnC,CAAC;QACD,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;YAC3C,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACrB,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;IAChE,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 { createReconnectController, type ReconnectController } from '@ttt-productions/realtime-core';\nimport type { ChatMessageV1 } from '@ttt-productions/chat-core';\nimport {\n CLIENT_FRAME,\n CHAT_CLOSE_CODES,\n buildFrame,\n parseFrame,\n isInboxSnapshot,\n ChatSendRejectedPayloadSchema,\n type WireMessageRow,\n type WireChannelSnapshot,\n type RevisionKind,\n type ChatSendRejectionCode,\n} from './wire.js';\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 HEARTBEAT_MS,\n TYPING_COALESCE_MS,\n HISTORY_PAGE_MAX,\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';\n\n/** An un-acked send tracked for reconnect resend (clientMessageId idempotency). */\ninterface PendingSend {\n clientMessageId: string;\n text: string;\n replyTo: { messageSeq: number; preview: string } | null;\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\nexport interface ChannelClientConfig {\n /** WebSocket endpoint base, e.g. `wss://chat.ttt.productions`. 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?: { baseDelayMs?: number; maxDelayMs?: number; maxAttempts?: number | null; random?: () => number };\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};\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/** Fallback retry delay when the frame omits/breaks `retryAfterMs`. */\nconst MEMBERSHIP_PENDING_DEFAULT_RETRY_MS = 2000;\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 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 * 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: 'initial' | 'auth-expired' | 'transient-close' | 'grant-error' = '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 }\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 for (const fn of this.listeners) fn(this.state);\n }\n\n // ---- connection lifecycle ----\n\n async connect(): 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 this.closedByUs = false;\n this.reconnectCause = 'initial';\n this.controller.start();\n this.setState({ status: 'connecting' });\n await this.openSocket();\n }\n\n private async openSocket(): Promise<void> {\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 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 return this.scheduleReconnect();\n }\n if (this.closedByUs) return;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/channel`;\n this.socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => this.onOpen(),\n onMessage: (data) => this.onMessage(data),\n onClose: (code, reason) => this.onClose(code, reason),\n onError: () => this.onError(),\n },\n });\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n this.setState({ status: 'open' });\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_FRAME.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_FRAME.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_FRAME.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_FRAME.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n replyTo: pending.replyTo,\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, { clientMessageId: rawId, outcome: 'unparseable-fail-closed' });\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, { clientMessageId, code, retryable, outcome: 'no-pending-send' });\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, { clientMessageId, code, retryable: false, outcome: 'terminal' });\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, { clientMessageId, code, retryable: true, outcome: 'budget-exhausted' });\n this.failPendingSend(clientMessageId, code, true);\n return;\n }\n const delayMs = this.clampRetryDelay(retryAfterMs);\n this.diag?.(DIAG.SEND_REJECTED, { clientMessageId, code, retryable: true, outcome: 'retry-scheduled', delayMs });\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_FRAME.SEND, {\n clientMessageId: current.clientMessageId,\n text: current.text,\n replyTo: current.replyTo,\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 - (this.timers.now() - current.sentAt) + 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_FRAME.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n replyTo: pending.replyTo,\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 (!(m.meta?.optimistic && m.meta?.clientMessageId === clientMessageId && m.meta?.sendFailed)) {\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.lastCloseCode = code;\n if (this.closedByUs) {\n this.diag?.(DIAG.SOCKET_CLOSE, { code, closedByUs: true, outcome: 'closed', resumeSeq: this.resumeSeq });\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, { code, closedByUs: false, outcome: 're-grant', resumeSeq: this.resumeSeq });\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, { code, closedByUs: false, outcome: 'revoked', resumeSeq: this.resumeSeq });\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: 'revoked' });\n return;\n }\n this.reconnectCause = 'transient-close';\n this.diag?.(DIAG.SOCKET_CLOSE, { code, closedByUs: false, outcome: 'reconnect', resumeSeq: this.resumeSeq });\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 return;\n }\n this.setState({ status: 'reconnecting' });\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs) 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.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: '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 this.diag?.(DIAG.FRAME_DROPPED, { kind: 'unparseable', reason: 'bad-envelope' });\n return;\n }\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(payload as { clientMessageId?: string; seq?: number; readSeq?: number });\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(payload as { messageSeq?: number; kind?: RevisionKind; messageRevision?: number });\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, { kind: safeDiagnosticLabel(frame.type), reason: 'unknown-type' });\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: { messageSeq?: number; kind?: RevisionKind; messageRevision?: number }): 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 = 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(seq: number, rowOverlay: ModerationOverlay | null): 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 if (!this.state.hasLoadedInitialData) this.setState({ hasLoadedInitialData: true });\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);\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 an\n * attachment state, carries a moderation kind, or reconciles one of our optimistic\n * sends) — a 500-row backlog is otherwise summarized by `chat_client_resume_result`\n * rather than spamming 500 lines. Attachment transitions ALWAYS emit, from either\n * source, because an in-place attachment mutation is the exact event this\n * instrumentation exists to prove.\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 attachmentState = typeof row.attachmentState === 'string' ? row.attachmentState : null;\n // Emit a transition for a real change only: first arrival of an attachment row\n // (null -> pending) and every later in-place mutation (pending -> ready/failed).\n if (attachmentState !== prior.attachmentState && (attachmentState != null || prior.hadRow)) {\n this.diag(DIAG.ATTACHMENT_TRANSITION, {\n seq: row.seq,\n from: prior.attachmentState,\n to: attachmentState,\n source,\n });\n }\n const notable = attachmentState != null || 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 attachmentState,\n moderationKind: row.moderationKind ?? null,\n op: prior.reconciledOptimistic ? 'optimistic-reconcile' : prior.hadRow ? 'replace-by-seq' : '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, its current\n * attachment state, and whether 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 attachmentState: string | null;\n reconciledOptimistic: boolean;\n } {\n const messageId = seqToMessageId(row.seq);\n const existing = this.state.messages.find((m) => m.messageId === messageId);\n const raw = existing?.meta?.attachmentState;\n return {\n hadRow: existing != null,\n attachmentState: typeof raw === 'string' ? raw : null,\n reconciledOptimistic: Boolean(\n row.clientMessageId &&\n this.state.messages.some((m) => m.meta?.optimistic && m.meta?.clientMessageId === row.clientMessageId),\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 { ...m, messageId: seqToMessageId(seq), meta: { ...restMeta, optimistic: false, seq } };\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 // Pre-page attachment states for the seqs we already hold — a history page that\n // carries a DIFFERENT state for a row we already rendered is an in-place mutation\n // the client learned about by re-fetching, which is exactly the reveal path under\n // investigation. Diagnostics-only, so only built when they are on.\n const priorAttachment = this.diag ? this.snapshotAttachmentStates() : null;\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 (m.meta?.optimistic && typeof m.meta?.clientMessageId === 'string' && incomingCmids.has(m.meta.clientMessageId)) {\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. (Older-page fetches redundantly re-set true,\n // which is a harmless no-op since the flag never flips back to false.)\n hasLoadedInitialData: true,\n });\n if (!this.diag) return;\n if (priorAttachment) {\n for (const r of rows) {\n if (typeof r.seq !== 'number') continue;\n const before = priorAttachment.get(r.seq);\n if (before === undefined) continue; // a row we did not hold — not a transition\n const after = typeof r.attachmentState === 'string' ? r.attachmentState : null;\n if (before !== after) {\n this.diag(DIAG.ATTACHMENT_TRANSITION, { seq: r.seq, from: before, to: after, source: 'history' });\n }\n }\n }\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 /**\n * A seq -> attachmentState map of the rows currently held (diagnostics-only, so a\n * later in-place mutation can be reported as an explicit `old -> new` transition).\n */\n private snapshotAttachmentStates(): Map<number, string | null> {\n const out = new Map<number, string | null>();\n for (const m of this.state.messages) {\n const seq = m.meta?.seq;\n if (typeof seq !== 'number') continue;\n const raw = m.meta?.attachmentState;\n out.set(seq, typeof raw === 'string' ? raw : null);\n }\n return out;\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(type: string, payload: Record<string, unknown>): 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; replyTo?: { messageSeq: number; preview: string } | null }): 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_FRAME.SEND, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n replyTo: args.replyTo ?? null,\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 replyTo: args.replyTo ?? null,\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 replyTo: args.replyTo ? { messageId: seqToMessageId(args.replyTo.messageSeq), messagePreview: args.replyTo.preview } : null,\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 hasReplyTo: Boolean(args.replyTo),\n replyToSeq: args.replyTo?.messageSeq ?? null,\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_FRAME.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_FRAME.TYPING, {});\n }\n\n presenceSubscribe(): void {\n this.presenceSubscribed = true;\n this.sendFrame(CLIENT_FRAME.PRESENCE_SUBSCRIBE, {});\n }\n\n presenceUnsubscribe(): void {\n this.presenceSubscribed = false;\n this.sendFrame(CLIENT_FRAME.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 = oldest && typeof oldest.meta?.seq === 'number' ? (oldest.meta.seq as number) : null;\n this.setState({ isFetchingOlder: true });\n this.requestHistory(beforeSeq);\n }\n\n private requestHistory(beforeSeq: number | null): void {\n const sent = this.sendFrame(CLIENT_FRAME.HISTORY, { beforeSeq, limit: HISTORY_PAGE_MAX });\n this.diag?.(DIAG.HISTORY_REQUEST, { beforeSeq, limit: HISTORY_PAGE_MAX, sent });\n }\n\n // ---- heartbeat (20s) ----\n\n private startHeartbeat(): void {\n this.stopHeartbeat();\n const tick = () => {\n if (!this.socket || !this.socket.isOpen) return;\n this.sendFrame(CLIENT_FRAME.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 // ---- teardown ----\n\n /** Permanently close this client (auth-user switch / unmount). Idempotent. */\n close(): void {\n this.closedByUs = true;\n this.controller.close();\n this.stopHeartbeat();\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 this.socket.close(1000, 'client teardown');\n this.socket = null;\n }\n this.setState({ status: 'closed', typing: [], presence: [] });\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,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,EAAE,yBAAyB,EAA4B,MAAM,gCAAgC,CAAC;AAErG,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,UAAU,EACV,eAAe,EACf,6BAA6B,GAK9B,MAAM,WAAW,CAAC;AAEnB,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,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EAChB,yBAAyB,EACzB,uBAAuB,EACvB,2BAA2B,EAC3B,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AAqFrB,MAAM,OAAO,GAAuB;IAClC,MAAM,EAAE,MAAM;IACd,QAAQ,EAAE,EAAE;IACZ,MAAM,EAAE,EAAE;IACV,QAAQ,EAAE,EAAE;I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C/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 { createReconnectController, type ReconnectController } from '@ttt-productions/realtime-core';\nimport type { ChatMessageV1 } from '@ttt-productions/chat-core';\nimport {\n CLIENT_FRAME,\n CHAT_CLOSE_CODES,\n buildFrame,\n parseFrame,\n isInboxSnapshot,\n ChatSendRejectedPayloadSchema,\n type WireMessageRow,\n type WireChannelSnapshot,\n type RevisionKind,\n type ChatSendRejectionCode,\n} from './wire.js';\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 HEARTBEAT_MS,\n TYPING_COALESCE_MS,\n HISTORY_PAGE_MAX,\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';\n\n/** An un-acked send tracked for reconnect resend (clientMessageId idempotency). */\ninterface PendingSend {\n clientMessageId: string;\n text: string;\n replyTo: { messageSeq: number; preview: string } | null;\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\nexport interface ChannelClientConfig {\n /** WebSocket endpoint base, e.g. `wss://chat.ttt.productions`. 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?: { baseDelayMs?: number; maxDelayMs?: number; maxAttempts?: number | null; random?: () => number };\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};\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/** Fallback retry delay when the frame omits/breaks `retryAfterMs`. */\nconst MEMBERSHIP_PENDING_DEFAULT_RETRY_MS = 2000;\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 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 * 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: 'initial' | 'auth-expired' | 'transient-close' | 'grant-error' = '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 }\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 for (const fn of this.listeners) fn(this.state);\n }\n\n // ---- connection lifecycle ----\n\n async connect(): 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 this.closedByUs = false;\n this.reconnectCause = 'initial';\n this.controller.start();\n this.setState({ status: 'connecting' });\n await this.openSocket();\n }\n\n private async openSocket(): Promise<void> {\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 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 return this.scheduleReconnect();\n }\n if (this.closedByUs) return;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/channel`;\n this.socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => this.onOpen(),\n onMessage: (data) => this.onMessage(data),\n onClose: (code, reason) => this.onClose(code, reason),\n onError: () => this.onError(),\n },\n });\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n this.setState({ status: 'open' });\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_FRAME.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_FRAME.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_FRAME.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_FRAME.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n replyTo: pending.replyTo,\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, { clientMessageId: rawId, outcome: 'unparseable-fail-closed' });\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, { clientMessageId, code, retryable, outcome: 'no-pending-send' });\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, { clientMessageId, code, retryable: false, outcome: 'terminal' });\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, { clientMessageId, code, retryable: true, outcome: 'budget-exhausted' });\n this.failPendingSend(clientMessageId, code, true);\n return;\n }\n const delayMs = this.clampRetryDelay(retryAfterMs);\n this.diag?.(DIAG.SEND_REJECTED, { clientMessageId, code, retryable: true, outcome: 'retry-scheduled', delayMs });\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_FRAME.SEND, {\n clientMessageId: current.clientMessageId,\n text: current.text,\n replyTo: current.replyTo,\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 - (this.timers.now() - current.sentAt) + 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_FRAME.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n replyTo: pending.replyTo,\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 (!(m.meta?.optimistic && m.meta?.clientMessageId === clientMessageId && m.meta?.sendFailed)) {\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.lastCloseCode = code;\n if (this.closedByUs) {\n this.diag?.(DIAG.SOCKET_CLOSE, { code, closedByUs: true, outcome: 'closed', resumeSeq: this.resumeSeq });\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, { code, closedByUs: false, outcome: 're-grant', resumeSeq: this.resumeSeq });\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, { code, closedByUs: false, outcome: 'revoked', resumeSeq: this.resumeSeq });\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: 'revoked' });\n return;\n }\n this.reconnectCause = 'transient-close';\n this.diag?.(DIAG.SOCKET_CLOSE, { code, closedByUs: false, outcome: 'reconnect', resumeSeq: this.resumeSeq });\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 return;\n }\n this.setState({ status: 'reconnecting' });\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs) 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.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: '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 this.diag?.(DIAG.FRAME_DROPPED, { kind: 'unparseable', reason: 'bad-envelope' });\n return;\n }\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(payload as { clientMessageId?: string; seq?: number; readSeq?: number });\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(payload as { messageSeq?: number; kind?: RevisionKind; messageRevision?: number });\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, { kind: safeDiagnosticLabel(frame.type), reason: 'unknown-type' });\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: { messageSeq?: number; kind?: RevisionKind; messageRevision?: number }): 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 = 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(seq: number, rowOverlay: ModerationOverlay | null): 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 if (!this.state.hasLoadedInitialData) this.setState({ hasLoadedInitialData: true });\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);\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 ? 'optimistic-reconcile' : prior.hadRow ? 'replace-by-seq' : '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((m) => m.meta?.optimistic && m.meta?.clientMessageId === row.clientMessageId),\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 { ...m, messageId: seqToMessageId(seq), meta: { ...restMeta, optimistic: false, seq } };\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 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 (m.meta?.optimistic && typeof m.meta?.clientMessageId === 'string' && incomingCmids.has(m.meta.clientMessageId)) {\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. (Older-page fetches redundantly re-set true,\n // which is a harmless no-op since the flag never flips back to false.)\n hasLoadedInitialData: 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(type: string, payload: Record<string, unknown>): 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; replyTo?: { messageSeq: number; preview: string } | null }): 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_FRAME.SEND, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n replyTo: args.replyTo ?? null,\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 replyTo: args.replyTo ?? null,\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 replyTo: args.replyTo ? { messageId: seqToMessageId(args.replyTo.messageSeq), messagePreview: args.replyTo.preview } : null,\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 hasReplyTo: Boolean(args.replyTo),\n replyToSeq: args.replyTo?.messageSeq ?? null,\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_FRAME.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_FRAME.TYPING, {});\n }\n\n presenceSubscribe(): void {\n this.presenceSubscribed = true;\n this.sendFrame(CLIENT_FRAME.PRESENCE_SUBSCRIBE, {});\n }\n\n presenceUnsubscribe(): void {\n this.presenceSubscribed = false;\n this.sendFrame(CLIENT_FRAME.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 = oldest && typeof oldest.meta?.seq === 'number' ? (oldest.meta.seq as number) : null;\n this.setState({ isFetchingOlder: true });\n this.requestHistory(beforeSeq);\n }\n\n private requestHistory(beforeSeq: number | null): void {\n const sent = this.sendFrame(CLIENT_FRAME.HISTORY, { beforeSeq, limit: HISTORY_PAGE_MAX });\n this.diag?.(DIAG.HISTORY_REQUEST, { beforeSeq, limit: HISTORY_PAGE_MAX, sent });\n }\n\n // ---- heartbeat (20s) ----\n\n private startHeartbeat(): void {\n this.stopHeartbeat();\n const tick = () => {\n if (!this.socket || !this.socket.isOpen) return;\n this.sendFrame(CLIENT_FRAME.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 // ---- teardown ----\n\n /** Permanently close this client (auth-user switch / unmount). Idempotent. */\n close(): void {\n this.closedByUs = true;\n this.controller.close();\n this.stopHeartbeat();\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 this.socket.close(1000, 'client teardown');\n this.socket = null;\n }\n this.setState({ status: 'closed', typing: [], presence: [] });\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"]}
|
|
@@ -39,8 +39,6 @@ export declare const CHAT_CLIENT_DIAGNOSTIC_EVENTS: {
|
|
|
39
39
|
readonly FRAME_APPLIED: "chat_client_frame_applied";
|
|
40
40
|
/** A frame was NOT applied, with the reason. */
|
|
41
41
|
readonly FRAME_DROPPED: "chat_client_frame_dropped";
|
|
42
|
-
/** An attachment lifecycle change AS SEEN BY THE CLIENT: seq, old -> new state. */
|
|
43
|
-
readonly ATTACHMENT_TRANSITION: "chat_client_attachment_transition";
|
|
44
42
|
/** A moderation revision overlay was recorded (and whether a loaded row re-rendered). */
|
|
45
43
|
readonly REVISION_APPLIED: "chat_client_revision_applied";
|
|
46
44
|
/** A history page was requested (cursor + limit). */
|
|
@@ -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":"AA2BA;;;;;GAKG;AACH,MAAM,MAAM,yBAAyB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;AAE/F;;;;GAIG;AACH,MAAM,MAAM,2BAA2B,GAAG,OAAO,GAAG,yBAAyB,CAAC;AAE9E,sFAAsF;AACtF,MAAM,MAAM,4BAA4B,GAAG,yBAAyB,GAAG,IAAI,CAAC;AAE5E;;;;GAIG;AACH,eAAO,MAAM,6BAA6B;IACxC,gFAAgF;;IAEhF,8EAA8E;;IAE9E,0EAA0E;;IAE1E,+EAA+E;;IAE/E,8EAA8E;;IAE9E,wCAAwC;;IAExC,qEAAqE;;IAErE,8EAA8E;;IAE9E,wFAAwF;;IAExF,gDAAgD;;IAEhD,yFAAyF;;IAEzF,qDAAqD;;IAErD,mEAAmE;;IAEnE,6DAA6D;;IAE7D,qDAAqD;;IAErD,kFAAkF;;IAElF,gFAAgF;;IAEhF,gEAAgE;;IAEhE,iDAAiD;;IAKjD,uFAAuF;;IAEvF,oFAAoF;;IAEpF,uEAAuE;;IAEvE,qFAAqF;;IAErF,qFAAqF;;IAErF,oFAAoF;;IAEpF,qFAAqF;;IAErF,kFAAkF;;IAElF,uDAAuD;;IAEvD,yEAAyE;;CAEjE,CAAC;AAEX,MAAM,MAAM,6BAA6B,GACvC,CAAC,OAAO,6BAA6B,CAAC,CAAC,MAAM,OAAO,6BAA6B,CAAC,CAAC;AAKrF;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAIxD;AAaD;;;;GAIG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,2BAA2B,GAAG,SAAS,GAC9C,4BAA4B,CAY9B"}
|
|
@@ -2,9 +2,13 @@
|
|
|
2
2
|
//
|
|
3
3
|
// The E2E/browser harness can already capture the raw WebSocket frames; what it
|
|
4
4
|
// cannot see is what the CLIENT DECIDED about them — which frame it applied,
|
|
5
|
-
// which it dropped and why, what resume cursor it sent, whether
|
|
6
|
-
//
|
|
7
|
-
//
|
|
5
|
+
// which it dropped and why, what resume cursor it sent, and whether a send was
|
|
6
|
+
// reconciled or failed. This module is that missing half: a bounded, structured,
|
|
7
|
+
// opt-in decision log.
|
|
8
|
+
//
|
|
9
|
+
// The connection-time, resume, presence, and socket-timing instruments are the
|
|
10
|
+
// baseline-campaign metric families — they stay. Only the attachment-serving
|
|
11
|
+
// instruments were retired with the chat-attachment architecture.
|
|
8
12
|
//
|
|
9
13
|
// Rules this module exists to enforce:
|
|
10
14
|
// - OFF BY DEFAULT and zero behavior change. When the option is absent the
|
|
@@ -46,8 +50,6 @@ export const CHAT_CLIENT_DIAGNOSTIC_EVENTS = {
|
|
|
46
50
|
FRAME_APPLIED: 'chat_client_frame_applied',
|
|
47
51
|
/** A frame was NOT applied, with the reason. */
|
|
48
52
|
FRAME_DROPPED: 'chat_client_frame_dropped',
|
|
49
|
-
/** An attachment lifecycle change AS SEEN BY THE CLIENT: seq, old -> new state. */
|
|
50
|
-
ATTACHMENT_TRANSITION: 'chat_client_attachment_transition',
|
|
51
53
|
/** A moderation revision overlay was recorded (and whether a loaded row re-rendered). */
|
|
52
54
|
REVISION_APPLIED: 'chat_client_revision_applied',
|
|
53
55
|
/** A history page was requested (cursor + limit). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.js","sourceRoot":"","sources":["../../src/realtime/diagnostics.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,EAAE;AACF,gFAAgF;AAChF,6EAA6E;AAC7E,8EAA8E;AAC9E,iFAAiF;AACjF,oEAAoE;AACpE,EAAE;AACF,uCAAuC;AACvC,6EAA6E;AAC7E,4EAA4E;AAC5E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8E;QAC9E,qEAAqE;QACrE,IAAI,CAAC;YACH,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACpB,CAAC;QAAC,MAAM,CAAC;YACP,sDAAsD;QACxD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// OPT-IN structured client diagnostics for the realtime chat transport.\n//\n// The E2E/browser harness can already capture the raw WebSocket frames; what it\n// cannot see is what the CLIENT DECIDED about them — which frame it applied,\n// which it dropped and why, what resume cursor it sent, whether an attachment\n// row mutated in place, and whether a send was reconciled or failed. This module\n// is that missing half: a bounded, structured, opt-in decision log.\n//\n// Rules this module exists to enforce:\n// - OFF BY DEFAULT and zero behavior change. When the option is absent the\n// factory returns `null`, every call site is `this.diag?.(...)`, and JS\n// optional-call short-circuiting means the payload object is never even\n// constructed. The cost when off is one nullish check.\n// - NEVER user content. Ids, seqs, states, counts, codes, booleans only —\n// never message text, captions, filenames, URLs, tokens, or previews. The\n// INBOX events go one step further and log SIZES only: a `channelRef` names\n// one specific conversation, so registry/unread lines carry counts and\n// deltas, never the refs themselves.\n// - STABLE event names (`chat_client_*`) suitable for log queries and later\n// alert metrics; one line per DECISION, never per render or per heartbeat.\n// - A diagnostics sink can never break the client: every emit is wrapped, so a\n// throwing sink is swallowed rather than turned into a transport failure.\n\n/**\n * A structured diagnostic sink. `event` is one of the stable\n * {@link CHAT_CLIENT_DIAGNOSTIC_EVENTS} names; `data` is a compact, content-free\n * payload (ids/seqs/states/counts/codes only). Supplying a sink lets the app\n * route entries into its own logger; `true` uses the console.debug default.\n */\nexport type ChatClientDiagnosticsSink = (event: string, data: Record<string, unknown>) => void;\n\n/**\n * The additive `diagnostics` config value: `false`/absent = off (the default and\n * the only production posture), `true` = the single-line `console.debug` sink,\n * or a custom {@link ChatClientDiagnosticsSink}.\n */\nexport type ChatClientDiagnosticsOption = boolean | ChatClientDiagnosticsSink;\n\n/** The bound emitter, or `null` when diagnostics are off (the zero-overhead path). */\nexport type ChatClientDiagnosticsEmitter = ChatClientDiagnosticsSink | null;\n\n/**\n * Stable event names. These are a QUERY CONTRACT — Cloud Logging filters, E2E\n * console greps, and any later alert metric key on them, so a name is added or\n * retired deliberately, never renamed in place.\n */\nexport const CHAT_CLIENT_DIAGNOSTIC_EVENTS = {\n /** A socket open is being attempted (per attempt, with the reconnect cause). */\n CONNECT_ATTEMPT: 'chat_client_connect_attempt',\n /** The grant mint failed before a socket existed (terminal vs. retryable). */\n GRANT_FAILED: 'chat_client_grant_failed',\n /** The socket reached OPEN (the point the resume cursor is sent from). */\n SOCKET_OPEN: 'chat_client_socket_open',\n /** The socket closed, with the code and what the client decided to do next. */\n SOCKET_CLOSE: 'chat_client_socket_close',\n /** A reconnect was scheduled (`delayMs`) or given up on (`delayMs: null`). */\n RECONNECT_SCHEDULED: 'chat_client_reconnect_scheduled',\n /** The resume cursor sent to the DO. */\n RESUME_REQUEST: 'chat_client_resume_request',\n /** The DO's snapshot answer + how the cursor moved because of it. */\n RESUME_RESULT: 'chat_client_resume_result',\n /** A `resync: true` snapshot dropped the local tail (removal, not upsert). */\n RESYNC_DROPPED_TAIL: 'chat_client_resync_dropped_tail',\n /** A frame was applied to UI state (insert / replace-by-seq / optimistic reconcile). */\n FRAME_APPLIED: 'chat_client_frame_applied',\n /** A frame was NOT applied, with the reason. */\n FRAME_DROPPED: 'chat_client_frame_dropped',\n /** An attachment lifecycle change AS SEEN BY THE CLIENT: seq, old -> new state. */\n ATTACHMENT_TRANSITION: 'chat_client_attachment_transition',\n /** A moderation revision overlay was recorded (and whether a loaded row re-rendered). */\n REVISION_APPLIED: 'chat_client_revision_applied',\n /** A history page was requested (cursor + limit). */\n HISTORY_REQUEST: 'chat_client_history_request',\n /** A history page was applied: size, seq range, cursor advance. */\n HISTORY_PAGE: 'chat_client_history_page',\n /** An optimistic send was rendered and its frame written. */\n SEND_OPTIMISTIC: 'chat_client_send_optimistic',\n /** A send was acked by the server (seq assigned). */\n SEND_ACK: 'chat_client_send_ack',\n /** A correlated `send-rejected` (or its legacy uncorrelated form) was handled. */\n SEND_REJECTED: 'chat_client_send_rejected',\n /** A send was re-emitted (reconnect resume / scheduled hint / manual retry). */\n SEND_RETRY: 'chat_client_send_retry',\n /** A send reached its visible failed state, with the reason. */\n SEND_FAILED: 'chat_client_send_failed',\n /** An uncorrelated server `error` frame code. */\n ERROR_FRAME: 'chat_client_error_frame',\n\n // ---- inbox socket (one per USER, separate from the per-thread channel socket) ----\n\n /** An inbox socket open is being attempted (per attempt, with the reconnect cause). */\n INBOX_CONNECT_ATTEMPT: 'chat_client_inbox_connect_attempt',\n /** The inbox grant mint failed before a socket existed (terminal vs. retryable). */\n INBOX_GRANT_FAILED: 'chat_client_inbox_grant_failed',\n /** The inbox socket reached OPEN (the point `resume` is sent from). */\n INBOX_SOCKET_OPEN: 'chat_client_inbox_socket_open',\n /** The inbox socket closed, with the code and what the client decided to do next. */\n INBOX_SOCKET_CLOSE: 'chat_client_inbox_socket_close',\n /** An inbox reconnect was scheduled (`delayMs`) or given up on (`delayMs: null`). */\n INBOX_RECONNECT_SCHEDULED: 'chat_client_inbox_reconnect_scheduled',\n /** The cursorless inbox `resume` was sent (the DO answers with a full snapshot). */\n INBOX_RESUME_REQUEST: 'chat_client_inbox_resume_request',\n /** An authoritative inbox snapshot was applied — registry SIZES only, never refs. */\n INBOX_SNAPSHOT_APPLIED: 'chat_client_inbox_snapshot_applied',\n /** The unread projection actually CHANGED (dock dot and/or per-row dot count). */\n INBOX_UNREAD_UPDATED: 'chat_client_inbox_unread_updated',\n /** An inbox frame was NOT applied, with the reason. */\n INBOX_FRAME_DROPPED: 'chat_client_inbox_frame_dropped',\n /** A mark-read was written to the socket (no optimistic local clear). */\n INBOX_MARK_READ: 'chat_client_inbox_mark_read',\n} as const;\n\nexport type ChatClientDiagnosticEventName =\n (typeof CHAT_CLIENT_DIAGNOSTIC_EVENTS)[keyof typeof CHAT_CLIENT_DIAGNOSTIC_EVENTS];\n\n/** Max length of a server-supplied label (frame type, error code) we echo into a log line. */\nconst MAX_LABEL_LEN = 48;\n\n/**\n * Clamp a server-supplied label before it enters a log line. Frame types and\n * error codes are protocol tokens, not user content, but they arrive from the\n * wire — bound them so a hostile/buggy peer cannot emit an unbounded line.\n */\nexport function safeDiagnosticLabel(raw: unknown): string {\n if (typeof raw !== 'string') return 'unknown';\n const trimmed = raw.slice(0, MAX_LABEL_LEN);\n return trimmed.length > 0 ? trimmed : 'unknown';\n}\n\n/**\n * The default sink: ONE `console.debug` line per decision, shaped\n * `chat_client_<event> {\"compact\":\"json\"}` so a browser console capture or a log\n * query can filter on the stable prefix and parse the payload without a\n * multi-line join.\n */\nconst consoleDebugSink: ChatClientDiagnosticsSink = (event, data) => {\n if (typeof console === 'undefined' || typeof console.debug !== 'function') return;\n console.debug(`${event} ${JSON.stringify(data)}`);\n};\n\n/**\n * Build the emitter for a `diagnostics` config value. Returns `null` when\n * diagnostics are off so call sites can use `this.diag?.(...)` — with optional\n * call syntax the argument object is not constructed at all on the off path.\n */\nexport function createDiagnosticsEmitter(\n option: ChatClientDiagnosticsOption | undefined,\n): ChatClientDiagnosticsEmitter {\n if (option == null || option === false) return null;\n const sink = option === true ? consoleDebugSink : option;\n return (event, data) => {\n // Diagnostics observe; they must never alter transport behavior — a sink that\n // throws (or a payload that cannot be serialized) is swallowed here.\n try {\n sink(event, data);\n } catch {\n /* diagnostics are never allowed to fail the client */\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"diagnostics.js","sourceRoot":"","sources":["../../src/realtime/diagnostics.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,EAAE;AACF,gFAAgF;AAChF,6EAA6E;AAC7E,+EAA+E;AAC/E,iFAAiF;AACjF,uBAAuB;AACvB,EAAE;AACF,+EAA+E;AAC/E,6EAA6E;AAC7E,kEAAkE;AAClE,EAAE;AACF,uCAAuC;AACvC,6EAA6E;AAC7E,4EAA4E;AAC5E,4EAA4E;AAC5E,2DAA2D;AAC3D,4EAA4E;AAC5E,8EAA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AAC,MAAM,CAAC;YACP,sDAAsD;QACxD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// OPT-IN structured client diagnostics for the realtime chat transport.\n//\n// The E2E/browser harness can already capture the raw WebSocket frames; what it\n// cannot see is what the CLIENT DECIDED about them — which frame it applied,\n// which it dropped and why, what resume cursor it sent, and whether a send was\n// reconciled or failed. This module is that missing half: a bounded, structured,\n// opt-in decision log.\n//\n// The connection-time, resume, presence, and socket-timing instruments are the\n// baseline-campaign metric families — they stay. Only the attachment-serving\n// instruments were retired with the chat-attachment architecture.\n//\n// Rules this module exists to enforce:\n// - OFF BY DEFAULT and zero behavior change. When the option is absent the\n// factory returns `null`, every call site is `this.diag?.(...)`, and JS\n// optional-call short-circuiting means the payload object is never even\n// constructed. The cost when off is one nullish check.\n// - NEVER user content. Ids, seqs, states, counts, codes, booleans only —\n// never message text, captions, filenames, URLs, tokens, or previews. The\n// INBOX events go one step further and log SIZES only: a `channelRef` names\n// one specific conversation, so registry/unread lines carry counts and\n// deltas, never the refs themselves.\n// - STABLE event names (`chat_client_*`) suitable for log queries and later\n// alert metrics; one line per DECISION, never per render or per heartbeat.\n// - A diagnostics sink can never break the client: every emit is wrapped, so a\n// throwing sink is swallowed rather than turned into a transport failure.\n\n/**\n * A structured diagnostic sink. `event` is one of the stable\n * {@link CHAT_CLIENT_DIAGNOSTIC_EVENTS} names; `data` is a compact, content-free\n * payload (ids/seqs/states/counts/codes only). Supplying a sink lets the app\n * route entries into its own logger; `true` uses the console.debug default.\n */\nexport type ChatClientDiagnosticsSink = (event: string, data: Record<string, unknown>) => void;\n\n/**\n * The additive `diagnostics` config value: `false`/absent = off (the default and\n * the only production posture), `true` = the single-line `console.debug` sink,\n * or a custom {@link ChatClientDiagnosticsSink}.\n */\nexport type ChatClientDiagnosticsOption = boolean | ChatClientDiagnosticsSink;\n\n/** The bound emitter, or `null` when diagnostics are off (the zero-overhead path). */\nexport type ChatClientDiagnosticsEmitter = ChatClientDiagnosticsSink | null;\n\n/**\n * Stable event names. These are a QUERY CONTRACT — Cloud Logging filters, E2E\n * console greps, and any later alert metric key on them, so a name is added or\n * retired deliberately, never renamed in place.\n */\nexport const CHAT_CLIENT_DIAGNOSTIC_EVENTS = {\n /** A socket open is being attempted (per attempt, with the reconnect cause). */\n CONNECT_ATTEMPT: 'chat_client_connect_attempt',\n /** The grant mint failed before a socket existed (terminal vs. retryable). */\n GRANT_FAILED: 'chat_client_grant_failed',\n /** The socket reached OPEN (the point the resume cursor is sent from). */\n SOCKET_OPEN: 'chat_client_socket_open',\n /** The socket closed, with the code and what the client decided to do next. */\n SOCKET_CLOSE: 'chat_client_socket_close',\n /** A reconnect was scheduled (`delayMs`) or given up on (`delayMs: null`). */\n RECONNECT_SCHEDULED: 'chat_client_reconnect_scheduled',\n /** The resume cursor sent to the DO. */\n RESUME_REQUEST: 'chat_client_resume_request',\n /** The DO's snapshot answer + how the cursor moved because of it. */\n RESUME_RESULT: 'chat_client_resume_result',\n /** A `resync: true` snapshot dropped the local tail (removal, not upsert). */\n RESYNC_DROPPED_TAIL: 'chat_client_resync_dropped_tail',\n /** A frame was applied to UI state (insert / replace-by-seq / optimistic reconcile). */\n FRAME_APPLIED: 'chat_client_frame_applied',\n /** A frame was NOT applied, with the reason. */\n FRAME_DROPPED: 'chat_client_frame_dropped',\n /** A moderation revision overlay was recorded (and whether a loaded row re-rendered). */\n REVISION_APPLIED: 'chat_client_revision_applied',\n /** A history page was requested (cursor + limit). */\n HISTORY_REQUEST: 'chat_client_history_request',\n /** A history page was applied: size, seq range, cursor advance. */\n HISTORY_PAGE: 'chat_client_history_page',\n /** An optimistic send was rendered and its frame written. */\n SEND_OPTIMISTIC: 'chat_client_send_optimistic',\n /** A send was acked by the server (seq assigned). */\n SEND_ACK: 'chat_client_send_ack',\n /** A correlated `send-rejected` (or its legacy uncorrelated form) was handled. */\n SEND_REJECTED: 'chat_client_send_rejected',\n /** A send was re-emitted (reconnect resume / scheduled hint / manual retry). */\n SEND_RETRY: 'chat_client_send_retry',\n /** A send reached its visible failed state, with the reason. */\n SEND_FAILED: 'chat_client_send_failed',\n /** An uncorrelated server `error` frame code. */\n ERROR_FRAME: 'chat_client_error_frame',\n\n // ---- inbox socket (one per USER, separate from the per-thread channel socket) ----\n\n /** An inbox socket open is being attempted (per attempt, with the reconnect cause). */\n INBOX_CONNECT_ATTEMPT: 'chat_client_inbox_connect_attempt',\n /** The inbox grant mint failed before a socket existed (terminal vs. retryable). */\n INBOX_GRANT_FAILED: 'chat_client_inbox_grant_failed',\n /** The inbox socket reached OPEN (the point `resume` is sent from). */\n INBOX_SOCKET_OPEN: 'chat_client_inbox_socket_open',\n /** The inbox socket closed, with the code and what the client decided to do next. */\n INBOX_SOCKET_CLOSE: 'chat_client_inbox_socket_close',\n /** An inbox reconnect was scheduled (`delayMs`) or given up on (`delayMs: null`). */\n INBOX_RECONNECT_SCHEDULED: 'chat_client_inbox_reconnect_scheduled',\n /** The cursorless inbox `resume` was sent (the DO answers with a full snapshot). */\n INBOX_RESUME_REQUEST: 'chat_client_inbox_resume_request',\n /** An authoritative inbox snapshot was applied — registry SIZES only, never refs. */\n INBOX_SNAPSHOT_APPLIED: 'chat_client_inbox_snapshot_applied',\n /** The unread projection actually CHANGED (dock dot and/or per-row dot count). */\n INBOX_UNREAD_UPDATED: 'chat_client_inbox_unread_updated',\n /** An inbox frame was NOT applied, with the reason. */\n INBOX_FRAME_DROPPED: 'chat_client_inbox_frame_dropped',\n /** A mark-read was written to the socket (no optimistic local clear). */\n INBOX_MARK_READ: 'chat_client_inbox_mark_read',\n} as const;\n\nexport type ChatClientDiagnosticEventName =\n (typeof CHAT_CLIENT_DIAGNOSTIC_EVENTS)[keyof typeof CHAT_CLIENT_DIAGNOSTIC_EVENTS];\n\n/** Max length of a server-supplied label (frame type, error code) we echo into a log line. */\nconst MAX_LABEL_LEN = 48;\n\n/**\n * Clamp a server-supplied label before it enters a log line. Frame types and\n * error codes are protocol tokens, not user content, but they arrive from the\n * wire — bound them so a hostile/buggy peer cannot emit an unbounded line.\n */\nexport function safeDiagnosticLabel(raw: unknown): string {\n if (typeof raw !== 'string') return 'unknown';\n const trimmed = raw.slice(0, MAX_LABEL_LEN);\n return trimmed.length > 0 ? trimmed : 'unknown';\n}\n\n/**\n * The default sink: ONE `console.debug` line per decision, shaped\n * `chat_client_<event> {\"compact\":\"json\"}` so a browser console capture or a log\n * query can filter on the stable prefix and parse the payload without a\n * multi-line join.\n */\nconst consoleDebugSink: ChatClientDiagnosticsSink = (event, data) => {\n if (typeof console === 'undefined' || typeof console.debug !== 'function') return;\n console.debug(`${event} ${JSON.stringify(data)}`);\n};\n\n/**\n * Build the emitter for a `diagnostics` config value. Returns `null` when\n * diagnostics are off so call sites can use `this.diag?.(...)` — with optional\n * call syntax the argument object is not constructed at all on the off path.\n */\nexport function createDiagnosticsEmitter(\n option: ChatClientDiagnosticsOption | undefined,\n): ChatClientDiagnosticsEmitter {\n if (option == null || option === false) return null;\n const sink = option === true ? consoleDebugSink : option;\n return (event, data) => {\n // Diagnostics observe; they must never alter transport behavior — a sink that\n // throws (or a payload that cannot be serialized) is swallowed here.\n try {\n sink(event, data);\n } catch {\n /* diagnostics are never allowed to fail the client */\n }\n };\n}\n"]}
|
package/dist/realtime/map.d.ts
CHANGED
|
@@ -27,13 +27,10 @@ export declare function seqToMessageId(seq: number): string;
|
|
|
27
27
|
* thread id (the UI's thread key); the DO row carries no threadId of its own.
|
|
28
28
|
* - `messageId` = the server seq (string) — stable + dedup key.
|
|
29
29
|
* - `replyTo` JSON `{ messageSeq, preview }` → UI `{ messageId, senderId:'', messagePreview }`.
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
* `mediaAssetId` via the attachment-URL resolver context (identity/media
|
|
35
|
-
* invariant: no URLs are ever stored). The raw lifecycle also stays on
|
|
36
|
-
* `meta.attachment*` for consumers that key on it.
|
|
30
|
+
*
|
|
31
|
+
* A DO row carries TEXT only. Files are not part of the message timeline — they
|
|
32
|
+
* live in the conversation's Conversation Files list, published through the
|
|
33
|
+
* canonical media pipeline and read from Firestore, never mapped from a chat row.
|
|
37
34
|
*/
|
|
38
35
|
export declare function wireRowToMessage(row: WireMessageRow, threadId: string): ChatMessageV1;
|
|
39
36
|
/** The optimistic local echo a `send` produces before the server `ack` reconciles the seq. */
|