@ttt-productions/chat-react 0.13.11 → 0.13.13
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/dist/hooks/useChatMessages.d.ts.map +1 -1
- package/dist/hooks/useChatMessages.js +1 -2
- package/dist/hooks/useChatMessages.js.map +1 -1
- package/dist/realtime/channel-client.d.ts +10 -0
- package/dist/realtime/channel-client.d.ts.map +1 -1
- package/dist/realtime/channel-client.js +19 -6
- package/dist/realtime/channel-client.js.map +1 -1
- package/dist/realtime/useRealtimeChatMessages.d.ts +2 -0
- package/dist/realtime/useRealtimeChatMessages.d.ts.map +1 -1
- package/dist/realtime/useRealtimeChatMessages.js +2 -0
- package/dist/realtime/useRealtimeChatMessages.js.map +1 -1
- package/dist/ui/ChatShell.d.ts +8 -0
- package/dist/ui/ChatShell.d.ts.map +1 -1
- package/dist/ui/ChatShell.js +14 -4
- package/dist/ui/ChatShell.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useChatMessages.d.ts","sourceRoot":"","sources":["../../src/hooks/useChatMessages.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAOlD,MAAM,MAAM,qBAAqB,GAAG;IAClC,OAAO,EAAE,OAAO,CAAC;IACjB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,QAAQ,EAAE,OAAO,CAAC;IAClB,eAAe,EAAE,OAAO,CAAC;IACzB,+FAA+F;IAC/F,WAAW,EAAE,oBAAoB,CAAC;IAClC,kFAAkF;IAClF,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IACpB,4FAA4F;IAC5F,UAAU,EAAE,KAAK,GAAG,IAAI,CAAC;IACzB,sFAAsF;IACtF,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB,CAAC;AAiCF,wBAAgB,eAAe,CAAC,MAAM,EAAE,cAAc,GAAG,qBAAqB,
|
|
1
|
+
{"version":3,"file":"useChatMessages.d.ts","sourceRoot":"","sources":["../../src/hooks/useChatMessages.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAOlD,MAAM,MAAM,qBAAqB,GAAG;IAClC,OAAO,EAAE,OAAO,CAAC;IACjB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,QAAQ,EAAE,OAAO,CAAC;IAClB,eAAe,EAAE,OAAO,CAAC;IACzB,+FAA+F;IAC/F,WAAW,EAAE,oBAAoB,CAAC;IAClC,kFAAkF;IAClF,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IACpB,4FAA4F;IAC5F,UAAU,EAAE,KAAK,GAAG,IAAI,CAAC;IACzB,sFAAsF;IACtF,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB,CAAC;AAiCF,wBAAgB,eAAe,CAAC,MAAM,EAAE,cAAc,GAAG,qBAAqB,CA6E7E"}
|
|
@@ -14,7 +14,7 @@ function mapMsg(data, threadId) {
|
|
|
14
14
|
}
|
|
15
15
|
// A stored `replyTo` (if any legacy doc still carries one) is deliberately NOT
|
|
16
16
|
// mapped: chat has no reply-authoring affordance, so the UI has no reply
|
|
17
|
-
// renderer to feed
|
|
17
|
+
// renderer to feed.
|
|
18
18
|
return {
|
|
19
19
|
messageId: data.id,
|
|
20
20
|
threadId,
|
|
@@ -48,7 +48,6 @@ export function useChatMessages(config) {
|
|
|
48
48
|
enabled: allowed,
|
|
49
49
|
sort: "asc",
|
|
50
50
|
select: (data) => mapMsg(data, threadId),
|
|
51
|
-
getSortValue: (data) => toMillis(data.createdAt) ?? 0,
|
|
52
51
|
});
|
|
53
52
|
const messages = React.useMemo(() => (allowed ? items : []), [allowed, items]);
|
|
54
53
|
// Pre-warm name cache for all visible senders.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useChatMessages.js","sourceRoot":"","sources":["../../src/hooks/useChatMessages.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAI7E,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,2BAA2B,EAAE,MAAM,uCAAuC,CAAC;AAEpF,4CAA4C;AAC5C,MAAM,aAAa,GAAG,GAAG,CAAC;AAmB1B,SAAS,MAAM,CACb,IAAmC,EACnC,QAAgB;IAEhB,MAAM,CAAC,GAAG,IAAW,CAAC;IAEtB,MAAM,SAAS,GAAG,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IAExC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,oDAAoD,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC;IAC5F,CAAC;IAED,+EAA+E;IAC/E,yEAAyE;IACzE,
|
|
1
|
+
{"version":3,"file":"useChatMessages.js","sourceRoot":"","sources":["../../src/hooks/useChatMessages.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,Q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,EAAE,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI;QACvC,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type { DocumentData } from \"firebase/firestore\";\nimport { toMillis } from \"@ttt-productions/firebase-helpers\";\nimport { useFirestoreLiveInfinite } from \"@ttt-productions/query-core/react\";\nimport type { FirestoreSourceState } from \"@ttt-productions/query-core\";\nimport type { ChatMessageV1 } from \"@ttt-productions/chat-core\";\nimport type { ChatCoreConfig } from \"../types.js\";\nimport { messagesColPath } from \"../firestore/queries.js\";\nimport { useOptionalChatNameResolver } from \"../context/ChatNameResolverContext.js\";\n\n// Safety limit to prevent memory exhaustion\nconst MAX_PAGE_SIZE = 100;\n\nexport type UseChatMessagesResult = {\n allowed: boolean;\n isInitialLoading: boolean;\n messages: ChatMessageV1[];\n fetchOlder: () => Promise<void>;\n hasOlder: boolean;\n isFetchingOlder: boolean;\n /** The live listener's state: `connecting` while it (re)subscribes, `error` once it failed. */\n sourceState: FirestoreSourceState;\n /** The live listener's failure; the messages already shown stay in `messages`. */\n error: Error | null;\n /** The last older-page read failed; the list stops asking for older pages until `retry`. */\n olderError: Error | null;\n /** Re-run what failed: resubscribe a failed listener, re-read a failed older page. */\n retry: () => void;\n};\n\nfunction mapMsg(\n data: DocumentData & { id: string },\n threadId: string\n): ChatMessageV1 {\n const d = data as any;\n\n const createdAt = toMillis(d.createdAt);\n\n if (!createdAt) {\n console.error('[useChatMessages] Message missing valid createdAt:', data.id, d.createdAt);\n }\n\n // A stored `replyTo` (if any legacy doc still carries one) is deliberately NOT\n // mapped: chat has no reply-authoring affordance, so the UI has no reply\n // renderer to feed.\n return {\n messageId: data.id,\n threadId,\n createdAt: createdAt || 0,\n senderId: d.senderId,\n text: d.text ?? \"\",\n type: d.type,\n isSystemMessage: d.isSystemMessage ?? undefined,\n referencedUids: Array.isArray(d.referencedUids) ? d.referencedUids : undefined,\n // Moderation tombstone flag (backend-written) — carried through so renderers\n // can tombstone the content.\n hidden: d.hidden ?? undefined,\n meta: d.meta,\n };\n}\n\nexport function useChatMessages(config: ChatCoreConfig): UseChatMessagesResult {\n const {\n chatCollectionPath,\n messagesSubcollection = \"messages\",\n threadId,\n pageSize: requestedPageSize = 20,\n currentUserId,\n allowed,\n createdAtField = \"createdAt\",\n } = config;\n\n const pageSize = Math.min(requestedPageSize, MAX_PAGE_SIZE);\n\n if (requestedPageSize > MAX_PAGE_SIZE) {\n console.warn(\n `[useChatMessages] Requested pageSize ${requestedPageSize} exceeds maximum ${MAX_PAGE_SIZE}. Using ${MAX_PAGE_SIZE}.`\n );\n }\n\n // Stable key segment for the message collection path (string | string[]).\n const pathKey = React.useMemo(\n () =>\n JSON.stringify(\n Array.isArray(chatCollectionPath) ? chatCollectionPath : [chatCollectionPath]\n ),\n [chatCollectionPath]\n );\n\n // Slash-joined collection path for the generic hook (handles nested paths).\n const collectionPath = React.useMemo(\n () => messagesColPath(chatCollectionPath, threadId, messagesSubcollection).join(\"/\"),\n [chatCollectionPath, threadId, messagesSubcollection]\n );\n\n const { items, isInitialLoading, fetchOlder, hasOlder, isFetchingOlder, sourceState, error, olderError, retry } =\n useFirestoreLiveInfinite<ChatMessageV1>({\n collectionPath,\n queryKey: [\"chat-core\", \"messages\", pathKey, threadId, messagesSubcollection, pageSize, currentUserId],\n orderByField: createdAtField,\n pageSize,\n enabled: allowed,\n sort: \"asc\",\n select: (data) => mapMsg(data, threadId),\n });\n\n const messages = React.useMemo(() => (allowed ? items : []), [allowed, items]);\n\n // Pre-warm name cache for all visible senders.\n // Optional resolver: silent no-op if no provider is wrapped.\n const resolverCtx = useOptionalChatNameResolver();\n const senderIds = React.useMemo(() => {\n const set = new Set<string>();\n for (const m of messages) {\n set.add(m.senderId);\n for (const uid of m.referencedUids ?? []) set.add(uid);\n }\n return Array.from(set);\n }, [messages]);\n\n React.useEffect(() => {\n if (resolverCtx?.prewarm && senderIds.length > 0) {\n resolverCtx.prewarm(senderIds);\n }\n }, [resolverCtx, senderIds]);\n\n return {\n allowed,\n isInitialLoading: allowed ? isInitialLoading : false,\n messages,\n fetchOlder,\n hasOlder,\n isFetchingOlder,\n sourceState,\n error: allowed ? error : null,\n olderError: allowed ? olderError : null,\n retry,\n };\n}"]}
|
|
@@ -36,6 +36,15 @@ export interface ChannelClientState {
|
|
|
36
36
|
* messages under the reconnect banner instead.
|
|
37
37
|
*/
|
|
38
38
|
initialLoadFailed: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* True while the channel is CURRENT: the socket is open, initial data has loaded, and the
|
|
41
|
+
* authoritative state has been re-applied since this socket opened — a non-resync resume
|
|
42
|
+
* snapshot, or the history page answering a resync. Cleared the moment the socket closes,
|
|
43
|
+
* reconnects, or is denied, and false again on every new socket until its resume lands, so a
|
|
44
|
+
* consumer that must act on the conversation's current terms (an agreement, an offer) waits for
|
|
45
|
+
* it. Unlike `hasLoadedInitialData` it is never sticky.
|
|
46
|
+
*/
|
|
47
|
+
isSynced: boolean;
|
|
39
48
|
}
|
|
40
49
|
export interface ChannelClientConfig {
|
|
41
50
|
/** WebSocket endpoint base, e.g. `wss://chat.example.com`. The client appends `/channel`. */
|
|
@@ -89,6 +98,7 @@ export declare class ChannelClient {
|
|
|
89
98
|
* can never judge a socket that does not exist. See {@link INBOUND_SILENCE_LIMIT_MS}.
|
|
90
99
|
*/
|
|
91
100
|
private lastInboundAt;
|
|
101
|
+
private historyRequests;
|
|
92
102
|
private typingTimers;
|
|
93
103
|
private lastTypingSentAt;
|
|
94
104
|
private reconnectTimer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel-client.d.ts","sourceRoot":"","sources":["../../src/realtime/channel-client.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAoBhE,OAAO,KAAK,EAAkB,aAAa,EAAE,MAAM,aAAa,CAAC;AASjE,OAAO,KAAK,EAAE,aAAa,EAAE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C3F,UAAU,IAAI,IAAI;IASlB,OAAO,CAAC,cAAc;IAStB,OAAO,CAAC,cAAc;IActB,OAAO,CAAC,aAAa;IAOrB,8EAA8E;IAC9E,OAAO,CAAC,eAAe;IAKvB;;;;;;;;;;OAUG;IACH,OAAO,CAAC,eAAe;IAevB,8EAA8E;IAC9E,KAAK,IAAI,IAAI;CAgCd"}
|
|
@@ -30,6 +30,7 @@ const INITIAL = {
|
|
|
30
30
|
lastErrorCode: null,
|
|
31
31
|
hasLoadedInitialData: false,
|
|
32
32
|
initialLoadFailed: false,
|
|
33
|
+
isSynced: false,
|
|
33
34
|
};
|
|
34
35
|
/**
|
|
35
36
|
* Retryable error-frame code the channel DO sends when a send arrives BEFORE the
|
|
@@ -95,6 +96,8 @@ export class ChannelClient {
|
|
|
95
96
|
* can never judge a socket that does not exist. See {@link INBOUND_SILENCE_LIMIT_MS}.
|
|
96
97
|
*/
|
|
97
98
|
lastInboundAt = null;
|
|
99
|
+
// History requests sent on the current socket and not yet answered, oldest first.
|
|
100
|
+
historyRequests = [];
|
|
98
101
|
typingTimers = new Map();
|
|
99
102
|
lastTypingSentAt = Number.NEGATIVE_INFINITY;
|
|
100
103
|
reconnectTimer = null;
|
|
@@ -161,6 +164,9 @@ export class ChannelClient {
|
|
|
161
164
|
}
|
|
162
165
|
setState(patch) {
|
|
163
166
|
this.state = { ...this.state, ...patch };
|
|
167
|
+
// Only an open socket can be current.
|
|
168
|
+
if (this.state.status !== 'open')
|
|
169
|
+
this.state.isSynced = false;
|
|
164
170
|
for (const fn of this.listeners)
|
|
165
171
|
fn(this.state);
|
|
166
172
|
}
|
|
@@ -316,7 +322,9 @@ export class ChannelClient {
|
|
|
316
322
|
// Start the liveness clock at open — the first heartbeat window is measured
|
|
317
323
|
// from here, not from a stale previous socket.
|
|
318
324
|
this.lastInboundAt = this.timers.now();
|
|
319
|
-
|
|
325
|
+
// A new socket is current only once its resume lands.
|
|
326
|
+
this.historyRequests = [];
|
|
327
|
+
this.setState({ status: 'open', isSynced: false });
|
|
320
328
|
this.diag?.(DIAG.SOCKET_OPEN, {
|
|
321
329
|
attempt: this.connectAttempt,
|
|
322
330
|
cause: this.reconnectCause,
|
|
@@ -929,8 +937,7 @@ export class ChannelClient {
|
|
|
929
937
|
// A non-resync snapshot IS the first authoritative data (even an empty delta =
|
|
930
938
|
// caught up) — end initial loading. A resync snapshot instead defers to the
|
|
931
939
|
// re-paged first history page below, so it must NOT end it here.
|
|
932
|
-
|
|
933
|
-
this.setState(this.initialDataLoaded());
|
|
940
|
+
this.setState({ ...(this.state.hasLoadedInitialData ? {} : this.initialDataLoaded()), isSynced: true });
|
|
934
941
|
return;
|
|
935
942
|
}
|
|
936
943
|
// Resync: drop the local tail and re-page from the top per the pinned contract.
|
|
@@ -957,7 +964,7 @@ export class ChannelClient {
|
|
|
957
964
|
keptOptimistic: keptOptimistic.length,
|
|
958
965
|
});
|
|
959
966
|
this.setState({ messages: keptOptimistic, hasOlder: true, isFetchingOlder: false });
|
|
960
|
-
this.requestHistory(null);
|
|
967
|
+
this.requestHistory(null, 'resync');
|
|
961
968
|
}
|
|
962
969
|
/**
|
|
963
970
|
* Apply one server row (a live `message` frame or a resume-delta row) and record
|
|
@@ -1064,6 +1071,9 @@ export class ChannelClient {
|
|
|
1064
1071
|
}
|
|
1065
1072
|
applyHistoryPage(rows) {
|
|
1066
1073
|
const cursorBefore = this.resumeSeq;
|
|
1074
|
+
// The socket answers history requests in the order they were sent; the page answering a
|
|
1075
|
+
// resync is the one that makes the channel current again.
|
|
1076
|
+
const answersResync = this.historyRequests.shift() === 'resync';
|
|
1067
1077
|
const mapped = rows.map((r) => this.renderRow(r));
|
|
1068
1078
|
// Mirror mergeMessage's optimistic reconciliation: a history row carrying a
|
|
1069
1079
|
// clientMessageId we still hold as an optimistic placeholder IS that send (the
|
|
@@ -1098,6 +1108,7 @@ export class ChannelClient {
|
|
|
1098
1108
|
// load, so it ends initial loading. An older page arrives only after it, so this
|
|
1099
1109
|
// never runs a second time.
|
|
1100
1110
|
...(this.state.hasLoadedInitialData ? {} : this.initialDataLoaded()),
|
|
1111
|
+
...(answersResync ? { isSynced: true } : {}),
|
|
1101
1112
|
});
|
|
1102
1113
|
if (!this.diag)
|
|
1103
1114
|
return;
|
|
@@ -1219,11 +1230,13 @@ export class ChannelClient {
|
|
|
1219
1230
|
const beforeSeq = oldest && typeof oldest.meta?.seq === 'number' ? oldest.meta.seq : null;
|
|
1220
1231
|
this.setState({ isFetchingOlder: true });
|
|
1221
1232
|
// Unsent (the socket is down): nothing will answer, so it is not in flight.
|
|
1222
|
-
if (!this.requestHistory(beforeSeq))
|
|
1233
|
+
if (!this.requestHistory(beforeSeq, 'older'))
|
|
1223
1234
|
this.setState({ isFetchingOlder: false });
|
|
1224
1235
|
}
|
|
1225
|
-
requestHistory(beforeSeq) {
|
|
1236
|
+
requestHistory(beforeSeq, kind) {
|
|
1226
1237
|
const sent = this.sendFrame(CLIENT_FRAME.HISTORY, { beforeSeq, limit: HISTORY_PAGE_MAX });
|
|
1238
|
+
if (sent)
|
|
1239
|
+
this.historyRequests.push(kind);
|
|
1227
1240
|
this.diag?.(DIAG.HISTORY_REQUEST, { beforeSeq, limit: HISTORY_PAGE_MAX, sent });
|
|
1228
1241
|
return sent;
|
|
1229
1242
|
}
|
|
@@ -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,U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AAE,KAAK,EAAE,CAAC,CAAC;IACxF,CAAC;CACF;AAED,SAAS,SAAS,CAAC,CAAgB,EAAE,CAAgB;IACnD,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,EAAE,GAAG,EAAE,CAAC;IAC9B,OAAO,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC;AACnC,CAAC","sourcesContent":["// The Channel realtime client: ONE WebSocket to a single channel DO, driving the\n// Contract C wire protocol. Framework-neutral (a plain observable store the React\n// hook subscribes to) so it is unit-testable with a mock socket and no React.\n//\n// Responsibilities (Contract C):\n// - connect via subprotocol auth (grant offered by the injected grantProvider)\n// - receive versioned `message` frames; server owns `seq`\n// - optimistic send keyed by clientMessageId, reconciled on the server `ack` seq\n// - explicit read acks (delivery != read; focus signals \"read\")\n// - typing (>= 2s coalesced per the V1 limit)\n// - presence-subscribe/-unsubscribe + a 20s client heartbeat\n// - reconnect (realtime-core controller) with a resume cursor -> snapshot then deltas\n// - history pagination over the socket (page <= 50, epoch-aware via seq)\n// - error codes incl. 4401 AUTH_EXPIRED -> re-mint a grant ONCE via grantProvider\n//\n// Timers are injected (setTimeout/clearTimeout/now) so tests run deterministically.\n\nimport { 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 {\n ChatHistoryPayload,\n ChatReadAckPayload,\n ChatResumePayload,\n ChatSendPayload,\n ClientFrameKind,\n} from '@ttt-productions/chat-schemas';\nimport type { RealtimeSocket, SocketFactory } from './socket.js';\nimport {\n wireRowToMessage,\n optimisticMessage,\n seqToMessageId,\n applyModerationOverlay,\n overlayFromRow,\n type ModerationOverlay,\n} from './map.js';\nimport type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';\nimport {\n createDiagnosticsEmitter,\n safeDiagnosticLabel,\n CHAT_CLIENT_DIAGNOSTIC_EVENTS as DIAG,\n type ChatClientDiagnosticsEmitter,\n type ChatClientDiagnosticsOption,\n} from './diagnostics.js';\nimport {\n defaultTimers,\n isChatAccessDeniedError,\n isTerminalErrorCode,\n TERMINAL_ERROR_CODE,\n 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';\nimport { InitialLoadBudget } from './initial-load-budget.js';\n\n/**\n * The payload of each frame this client sends, typed by the chat-schemas payload the Worker parses\n * it with, so a sender that drifts from the contract fails to compile. A frame with no payload\n * schema (typing, presence, heartbeat) carries an empty object.\n */\ntype ChannelFramePayload<K extends ClientFrameKind> = K extends typeof CLIENT_FRAME.SEND\n ? ChatSendPayload\n : K extends typeof CLIENT_FRAME.READ_ACK\n ? ChatReadAckPayload\n : K extends typeof CLIENT_FRAME.HISTORY\n ? ChatHistoryPayload\n : K extends typeof CLIENT_FRAME.RESUME\n ? ChatResumePayload\n : Record<string, never>;\n\n/** An un-acked send tracked for reconnect resend (clientMessageId idempotency). */\ninterface PendingSend {\n clientMessageId: string;\n text: string;\n /** When the send was first attempted (for the age/budget caps). Reset by retrySend(). */\n sentAt: number;\n /** How many times it has been (re)sent over a socket. Reset by retrySend(). */\n attempts: number;\n /** True once the attempt/age/budget cap flipped this send to the visible failed\n * state. A failed entry is RETAINED (not deleted) so retrySend() can re-queue it\n * with the SAME clientMessageId; it is skipped by the automatic reconnect resend. */\n failed: boolean;\n /**\n * Set true once the Worker has declared THIS send retryable — either a correlated\n * `send-rejected` (retryable) frame or the legacy uncorrelated\n * `error{code:'membership-pending'}`. A server-retryable send is governed by the\n * {@link SERVER_RETRYABLE_MAX_AGE_MS} wall-clock budget and is NEVER failed by the\n * generic {@link MAX_PENDING_SEND_ATTEMPTS} cap (that cap stays for blind reconnect\n * resends of sends the server has said nothing about).\n */\n serverRetryable: boolean;\n /** The most recent server rejection code, recorded so a budget-exhausted failure\n * can surface the reason (and keep a retry affordance for the transient class). */\n lastRejectionCode?: ChatSendRejectionCode;\n /** The single per-send resend timer for a correlated retryable rejection (never\n * stacks — a newer rejection clears it first; cleared on ack/echo/manual\n * retry/terminal/close/dispose). */\n retryTimer: ReturnType<TransportTimers['setTimeout']> | null;\n}\n\nexport interface ChannelClientState {\n status: RealtimeStatus;\n /** Ordered ascending by seq; optimistic messages (no seq yet) sort to the tail. */\n messages: ChatMessageV1[];\n /** uids currently typing (cleared after ~TYPING_COALESCE_MS of silence). */\n typing: string[];\n /** uids the DO reports online (presence). Empty until presence-subscribe. */\n presence: string[];\n /** True while an older-history page request is in flight. */\n isFetchingOlder: boolean;\n /** False once a history page returns fewer than the requested limit (reached the head). */\n hasOlder: boolean;\n /** The last structured error code the DO sent (e.g. 'blocked-word', 'too-long', flood reason). */\n lastErrorCode: string | null;\n /**\n * True once the FIRST authoritative chat data has been applied — a non-resync\n * resume snapshot, OR the first history page (INCLUDING an empty one). Drives the\n * hook's `isInitialLoading` so the shell shows an honest \"Opening chat…\" state\n * while the first data is loading, and a real empty-chat surface only after an\n * authoritative empty result. NEVER inferred from `messages.length === 0` (an\n * empty first history page IS a successful load). Once true it stays true — a\n * later disconnect/reconnect keeps loaded messages mounted, not a re-loader.\n * A grant retry / socket open before any snapshot leaves it false.\n */\n hasLoadedInitialData: boolean;\n /**\n * True once the first open has failed for good enough to say so: attempts have kept\n * failing for {@link CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS} without any initial data, or\n * reconnecting stopped (gave up, or the socket was revoked) before any. The client keeps\n * retrying in the background; the first authoritative data, or a manual `retryNow()`,\n * clears it. Never true once initial data has loaded — a later outage keeps the loaded\n * messages under the reconnect banner instead.\n */\n initialLoadFailed: boolean;\n}\n\nexport interface ChannelClientConfig {\n /** WebSocket endpoint base, e.g. `wss://chat.example.com`. The client appends `/channel`. */\n endpoint: string;\n /** The logical thread id the UI keys on (used as ChatMessageV1.threadId). */\n threadId: string;\n /** The authenticated uid (sender identity for optimistic echoes + auth-switch guard). */\n currentUserId: string;\n /** Mints/refreshes a channel grant. Called on connect and once on a 4401 re-grant. */\n grantProvider: GrantProvider;\n socketFactory: SocketFactory;\n timers?: TransportTimers;\n /** Reconnect backoff tuning (forwarded to realtime-core). */\n reconnect?: { 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 initialLoadFailed: 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\n/**\n * Dead-socket watchdog: how long inbound silence may last before this client\n * treats the socket as dead and closes it locally.\n *\n * CHANNEL-ONLY, and this is why it is sound here: the channel DO answers every\n * 20 s client `heartbeat` through the hibernation AUTO-RESPONSE API, so a healthy\n * channel socket is NEVER silent for a full heartbeat window. Inbound silence past\n * this threshold is therefore provable death (a half-open TCP connection whose\n * `onclose` never fires), not idleness. The INBOX socket has no such auto-response\n * and a healthy idle inbox is legitimately silent for hours — applying this rule\n * there would endlessly reconnect healthy sockets, so it is deliberately absent\n * from `inbox-client.ts`.\n *\n * PRIVATE CLIENT POLICY, not a wire constant: nothing on the worker side agrees to\n * it, so it does not belong in `@ttt-productions/chat-schemas` or in this package's\n * exported surface. The check rides the existing 20 s heartbeat tick (no second\n * timer), so detection lands on the NEXT tick after the deadline rather than at\n * exactly 50 s — intended: 2.5 missed windows is unambiguous, and it costs no\n * extra timer.\n */\nconst INBOUND_SILENCE_LIMIT_MS = 50_000;\n\n/**\n * Close code used for the watchdog's LOCAL close. A browser `WebSocket.close()`\n * accepts only 1000 or 3000–4999, and the private 4xxx range is the chat wire's\n * (`CHAT_CLOSE_CODES`) — a client-invented code there could collide with a future\n * server code. 1000 keeps the close frame valid and, being neither 4401 nor 4403,\n * routes through `onClose`'s ordinary transient path, which owns reconnect,\n * backoff, and resume. The reason string + the liveness diagnostic are what\n * identify it.\n */\nconst WATCHDOG_CLOSE_CODE = 1000;\n\nexport class ChannelClient {\n private readonly timers: TransportTimers;\n private readonly controller: ReconnectController;\n private socket: RealtimeSocket | null = null;\n private state: ChannelClientState = INITIAL;\n private readonly listeners = new Set<(s: ChannelClientState) => void>();\n\n /** Resume cursor: highest seq we've durably applied. Sent on resume after reconnect. */\n private resumeSeq = 0;\n /** Last read-ack the UI requested; re-sent on reconnect so a drop during a closed\n * socket window is recovered (M2). */\n private lastReadAck: { readSeq: number; focused: boolean } | null = null;\n /** True after a `4401` re-grant has been attempted for the CURRENT connect cycle (once-only). */\n private reauthAttempted = false;\n private presenceSubscribed = false;\n private heartbeatTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n /**\n * When the CURRENT socket last proved it was alive: set on open, refreshed by\n * every successfully parsed inbound frame (`heartbeat-ack` included — that IS\n * the DO's liveness answer). Null whenever no socket is live, so the watchdog\n * can never judge a socket that does not exist. See {@link INBOUND_SILENCE_LIMIT_MS}.\n */\n private lastInboundAt: number | null = null;\n private typingTimers = new Map<string, ReturnType<TransportTimers['setTimeout']>>();\n private lastTypingSentAt = Number.NEGATIVE_INFINITY;\n private reconnectTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n /** Single scheduled re-send for the membership-pending window (never stacks). */\n private membershipRetryTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private closedByUs = false;\n /**\n * The current lifecycle's number, advanced by every `connect()` and `close()`. A grant\n * that resolves, or a timer that fires, for an older lifecycle is dropped — so a\n * close → connect while an earlier grant is still minting can never open a second\n * socket or touch the new lifecycle's state (FRONTEND-108).\n */\n private lifecycle = 0;\n /** Reports the first open as failed once its attempts have failed for the budget. */\n private readonly initialLoad: InitialLoadBudget;\n /**\n * Per-seq moderation overlay (the max-revision wins). A `revision` frame writes\n * here keyed by `messageSeq` so it applies whether it arrives BEFORE its base\n * row (re-applied when the row later renders) or AFTER (re-renders the present\n * row in place). Merged with the row's own inline `moderationKind` so a row that\n * arrives already-moderated from the DO AND one covered by a live frame both\n * render the moderated state. */\n private overlays = new Map<number, ModerationOverlay>();\n /**\n * The ORIGINAL (un-overlaid) mapped message per seq. A `restore` revision must\n * revert a previously-redacted message to its original text, so re-renders start\n * from this cache rather than the (possibly already-blanked) message in state. */\n private originalRows = new Map<number, ChatMessageV1>();\n /**\n * Un-acked sends keyed by clientMessageId. A send is added here when its frame is\n * written and removed when its `ack` (or the canonical `message` echo carrying the\n * same clientMessageId) arrives. On every reconnect resume they are RE-SENT with\n * the SAME clientMessageId — the DO dedups (re-acks without re-broadcast), so a\n * send that lost its socket before the ack is delivered exactly once. A pending\n * send that exceeds the attempt/age cap is flipped to a visible failed state\n * (retry affordance) instead of staying a ghost. */\n private pendingSends = new Map<string, PendingSend>();\n /**\n * The structured diagnostics emitter, or null when diagnostics are off (the\n * default). Every call site uses `this.diag?.(...)` so the off path constructs\n * no payload at all.\n */\n private readonly diag: ChatClientDiagnosticsEmitter;\n /** Monotonic socket-open attempt counter (diagnostics correlation only). */\n private connectAttempt = 0;\n /** Why the CURRENT connect attempt is happening (diagnostics only). */\n private reconnectCause: 'initial' | 'auth-expired' | 'transient-close' | 'grant-error' | 'manual-retry' = 'initial';\n /** The last close code observed, carried into the next attempt's cause line. */\n private lastCloseCode: number | null = null;\n\n constructor(private readonly config: ChannelClientConfig) {\n this.timers = config.timers ?? defaultTimers;\n this.controller = createReconnectController(config.reconnect ?? {});\n this.diag = createDiagnosticsEmitter(config.diagnostics);\n this.initialLoad = new InitialLoadBudget(this.timers, () => this.reportInitialLoadFailed());\n }\n\n // ---- observable store ----\n\n getState(): ChannelClientState {\n return this.state;\n }\n\n subscribe(fn: (s: ChannelClientState) => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n private setState(patch: Partial<ChannelClientState>): void {\n this.state = { ...this.state, ...patch };\n for (const fn of this.listeners) fn(this.state);\n }\n\n // ---- connection lifecycle ----\n\n async connect(): Promise<void> {\n return this.startLifecycle(true);\n }\n\n /**\n * Retry now (the first-open failure's Retry). While a reconnect is waiting out its\n * backoff, the wait is cancelled and a socket opens at once; a lifecycle that stopped\n * (reconnect gave up, or the socket was revoked) starts again; an attempt already in\n * flight is left to finish. Either way the first-open failure clears, so the opening state\n * shows while the retry runs. The spent budget stays spent: a retry that fails is reported\n * again at once, and one that hangs a full budget later.\n */\n retryNow(): void {\n if (!this.state.hasLoadedInitialData) this.initialLoad.manualRetry();\n if (this.state.status === 'closed') {\n void this.startLifecycle(false);\n return;\n }\n if (this.reconnectTimer == null) {\n if (this.state.initialLoadFailed) this.setState({ initialLoadFailed: false });\n return;\n }\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n this.controller.reset();\n this.controller.start();\n this.reconnectCause = 'manual-retry';\n this.setState({ status: 'reconnecting', initialLoadFailed: false });\n void this.openSocket();\n }\n\n private async startLifecycle(freshBudget: boolean): Promise<void> {\n // Idempotency guard (C-B7): connect() only starts a lifecycle from a fresh\n // (idle) or fully torn-down (closed) state. A second connect() while one is\n // already connecting / open / reconnecting is a no-op, so a stray double-owner\n // can't open a second WebSocket. The reconnect path uses openSocket() /\n // scheduleReconnect() directly (never connect()), so this never blocks a\n // legitimate reconnect.\n if (this.state.status !== 'idle' && this.state.status !== 'closed') return;\n // REVIVE the controller. `controller.close()` is PERMANENT: while it is in\n // state `closed`, `start()` and `onOpen()` no-op and every later `onClose()`\n // returns null. So without this reset a close() → connect() client opens a\n // socket and works normally until its FIRST transient close, at which point\n // `scheduleReconnect()` gets null and parks it terminally in `closed` with\n // reconnect disabled and no surfaced error code. The idempotency guard above\n // is what keeps this from disturbing a live lifecycle: only an `idle` or\n // fully torn-down (`closed`) client ever reaches here.\n this.controller.reset();\n // A terminal verdict (4403 REVOKED / ChatAccessDeniedError) is terminal WITHIN\n // its lifecycle; an explicit connect() is a fresh attempt the authority may\n // legitimately re-deny, so the previous lifecycle's code must not persist into\n // this one (the hook maps `access-denied` to `allowed: false`). Loaded\n // messages and the initial-load flag are deliberately KEPT — a lifecycle\n // restart must not churn the UI back to an empty opening state.\n if (isTerminalErrorCode(this.state.lastErrorCode)) this.setState({ lastErrorCode: null });\n this.closedByUs = false;\n this.lifecycle += 1;\n this.reconnectCause = 'initial';\n if (!this.state.hasLoadedInitialData) this.initialLoad.begin(freshBudget);\n this.controller.start();\n this.setState({ status: 'connecting', initialLoadFailed: false });\n await this.openSocket();\n }\n\n /** The first open has failed for long enough to say so (see `initialLoadFailed`). */\n private reportInitialLoadFailed(): void {\n if (this.state.hasLoadedInitialData || this.state.initialLoadFailed) return;\n this.setState({ initialLoadFailed: true });\n }\n\n /** The first authoritative data is applied; it ends any first-open failure. */\n private initialDataLoaded(): Partial<ChannelClientState> {\n this.initialLoad.loaded();\n return { hasLoadedInitialData: true, initialLoadFailed: false };\n }\n\n private async openSocket(): Promise<void> {\n const lifecycle = this.lifecycle;\n this.connectAttempt += 1;\n this.diag?.(DIAG.CONNECT_ATTEMPT, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n closeCode: this.lastCloseCode,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n });\n let grantToken: string;\n try {\n grantToken = await this.config.grantProvider();\n } catch (err) {\n // A grant for a lifecycle that has since been closed or restarted answers nobody.\n if (lifecycle !== this.lifecycle) return;\n // A TERMINAL access denial (the app's grant provider translated an\n // authoritative policy \"no\" into the package-owned ChatAccessDeniedError)\n // must NOT reconnect — the next mint would just re-deny, stranding the shell\n // on the opening loader forever. Every other mint failure (network, transient\n // 'unavailable'/'internal', post-login 'unauthenticated') stays retryable and\n // backs off exactly as before.\n const terminal = isChatAccessDeniedError(err);\n this.diag?.(DIAG.GRANT_FAILED, { attempt: this.connectAttempt, terminal });\n if (terminal) return this.denyAccessTerminally();\n this.reconnectCause = 'grant-error';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n return this.scheduleReconnect();\n }\n // A grant minted for an earlier lifecycle must never open a socket in this one.\n if (lifecycle !== this.lifecycle || this.closedByUs) return;\n // Socket REPLACEMENT: the previous socket's liveness record dies with it, so\n // the watchdog never judges a new socket against an old deadline.\n this.lastInboundAt = null;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/channel`;\n // Every callback is fenced to THIS socket: once it has been replaced or torn down,\n // its late open, frames, and close are ignored.\n let socket: RealtimeSocket | null = null;\n const isCurrent = () => socket !== null && this.socket === socket;\n socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => {\n if (isCurrent()) this.onOpen();\n },\n onMessage: (data) => {\n if (isCurrent()) this.onMessage(data);\n },\n onClose: (code, reason) => {\n if (isCurrent()) this.onClose(code, reason);\n },\n onError: () => {\n if (isCurrent()) this.onError();\n },\n },\n });\n this.socket = socket;\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n // Start the liveness clock at open — the first heartbeat window is measured\n // from here, not from a stale previous socket.\n this.lastInboundAt = this.timers.now();\n 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 });\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 });\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 });\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.lastInboundAt = null;\n this.lastCloseCode = code;\n // An older-history request in flight died with the socket; nothing will answer it.\n if (this.state.isFetchingOlder) this.setState({ isFetchingOlder: false });\n if (this.closedByUs) {\n this.diag?.(DIAG.SOCKET_CLOSE, { 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: TERMINAL_ERROR_CODE.REVOKED });\n // Revoked before anything loaded: the first open has failed, and nothing retries it.\n this.reportInitialLoadFailed();\n return;\n }\n this.reconnectCause = 'transient-close';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n this.diag?.(DIAG.SOCKET_CLOSE, { 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 // Gave up before anything loaded: nothing retries the first open any more.\n this.reportInitialLoadFailed();\n return;\n }\n this.setState({ status: 'reconnecting' });\n const lifecycle = this.lifecycle;\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs || lifecycle !== this.lifecycle) return;\n void this.openSocket();\n }, delay);\n }\n\n /**\n * Terminal access denial surfaced by the grant provider (ChatAccessDeniedError).\n * A reconnect would just re-deny at the next mint, so stop for good — the same\n * terminal posture as a 4403 REVOKED close: mark closed-by-us, close the reconnect\n * controller, and flip every un-acked pending send to the visible failed state.\n * `access-denied` is set AFTER failAllPendingSends so its 'send-failed' code does\n * not win as the surfaced error; the React hook maps 'access-denied' to\n * `allowed: false` so the shell renders its existing no-access surface.\n */\n private denyAccessTerminally(): void {\n this.closedByUs = true;\n this.controller.close();\n this.initialLoad.dispose();\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.ACCESS_DENIED });\n }\n\n // ---- inbound frames ----\n\n private onMessage(data: string): void {\n const frame = parseFrame(data);\n if (!frame || !frame.type) {\n // Unparseable: bytes arrived, but nothing proves they came from a DO\n // speaking this protocol, so this must NOT refresh the liveness deadline.\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'unparseable', reason: 'bad-envelope' });\n return;\n }\n // A well-formed envelope IS the liveness proof — including the `heartbeat-ack`\n // the DO auto-responds with, and a forward-compat type this build does not\n // handle yet (a newer DO's frames must never be read as a dead socket).\n this.lastInboundAt = this.timers.now();\n const payload = frame.payload ?? {};\n switch (frame.type) {\n case 'message':\n return this.applyMessage((payload as { message: WireMessageRow }).message, 'live');\n case 'ack':\n return this.applyAck(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(this.initialDataLoaded());\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. An older page arrives only after it, so this\n // never runs a second time.\n ...(this.state.hasLoadedInitialData ? {} : this.initialDataLoaded()),\n });\n if (!this.diag) return;\n const seqs = rows.map((r) => r.seq).filter((s): s is number => typeof s === 'number');\n this.diag(DIAG.HISTORY_PAGE, {\n count: rows.length,\n minSeq: seqs.length > 0 ? Math.min(...seqs) : null,\n maxSeq: seqs.length > 0 ? Math.max(...seqs) : null,\n cursorBefore,\n cursorAfter: this.resumeSeq,\n reconciledOptimistic: incomingCmids.size,\n hasOlder: rows.length >= HISTORY_PAGE_MAX,\n total: merged.length,\n });\n }\n\n private applyTyping(uid: string): void {\n if (!uid || uid === this.config.currentUserId) return;\n if (!this.state.typing.includes(uid)) this.setState({ typing: [...this.state.typing, uid] });\n const prev = this.typingTimers.get(uid);\n if (prev) this.timers.clearTimeout(prev);\n this.typingTimers.set(\n uid,\n this.timers.setTimeout(() => {\n this.typingTimers.delete(uid);\n this.setState({ typing: this.state.typing.filter((u) => u !== uid) });\n }, TYPING_COALESCE_MS * 2),\n );\n }\n\n // ---- outbound actions ----\n\n private sendFrame<K extends ClientFrameKind>(type: K, payload: ChannelFramePayload<K>): boolean {\n if (!this.socket || !this.socket.isOpen) return false;\n this.socket.send(buildFrame(type, payload));\n return true;\n }\n\n /**\n * Optimistic send: render the echo immediately keyed by clientMessageId, then\n * emit the `send` frame. The server `ack`/`message` reconciles on the seq.\n */\n send(args: { clientMessageId: string; text: string }): boolean {\n // C-B8: write the frame FIRST and render the optimistic echo ONLY if it was\n // actually sent over an open socket. A closed socket returns false — no phantom\n // \"sent\" bubble, and the caller keeps the composer text — so a disconnect between\n // render and click can't silently swallow the message.\n const sent = this.sendFrame(CLIENT_FRAME.SEND, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n });\n if (!sent) {\n this.diag?.(DIAG.SEND_FAILED, {\n clientMessageId: args.clientMessageId,\n code: 'send-failed',\n retryable: null,\n attempts: 0,\n reason: 'socket-not-open',\n });\n this.setState({ lastErrorCode: 'send-failed' });\n return false;\n }\n const now = this.timers.now();\n // Track the un-acked send so a reconnect re-sends it with the same\n // clientMessageId (the DO dedups) — until the ack/echo clears it.\n this.pendingSends.set(args.clientMessageId, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n sentAt: now,\n attempts: 1,\n failed: false,\n serverRetryable: false,\n retryTimer: null,\n });\n const echo = optimisticMessage({\n clientMessageId: args.clientMessageId,\n threadId: this.config.threadId,\n senderId: this.config.currentUserId,\n text: args.text,\n createdAt: now,\n });\n const next = [...this.state.messages, echo].sort(sortBySeq);\n this.setState({ messages: next, lastErrorCode: null });\n this.diag?.(DIAG.SEND_OPTIMISTIC, {\n clientMessageId: args.clientMessageId,\n pendingSends: this.pendingSends.size,\n });\n return true;\n }\n\n /**\n * Explicit read ack (delivery != read). `focused` => the channel is open + at latest.\n * Remembers the cursor (re-sent on reconnect) and returns whether the frame was\n * actually sent over an open socket, so the caller only advances its local\n * already-acked marker on a real send (M2).\n */\n readAck(readSeq: number, focused: boolean): boolean {\n this.lastReadAck = { readSeq, focused };\n return this.sendFrame(CLIENT_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 // Unsent (the socket is down): nothing will answer, so it is not in flight.\n if (!this.requestHistory(beforeSeq)) this.setState({ isFetchingOlder: false });\n }\n\n private requestHistory(beforeSeq: number | null): boolean {\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 return sent;\n }\n\n // ---- heartbeat (20s) + dead-socket watchdog ----\n\n private startHeartbeat(): void {\n this.stopHeartbeat();\n const tick = () => {\n if (!this.socket || !this.socket.isOpen) return;\n // Liveness is checked BEFORE the write: a socket already proven dead must\n // not be handed another frame. Closing here does not reschedule — onClose\n // stops the heartbeat and owns what happens next.\n if (this.isInboundSilent()) return this.closeDeadSocket();\n this.sendFrame(CLIENT_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 /** True when the live socket has produced no parseable frame for too long. */\n private isInboundSilent(): boolean {\n if (this.lastInboundAt == null) return false;\n return this.timers.now() - this.lastInboundAt >= INBOUND_SILENCE_LIMIT_MS;\n }\n\n /**\n * The channel DO auto-acks every heartbeat, so silence past\n * {@link INBOUND_SILENCE_LIMIT_MS} means this socket is dead even though no\n * `onclose` ever fired (the half-open-connection case that otherwise strands\n * the UI on a socket that will never deliver another message).\n *\n * Close it LOCALLY and deliberately WITHOUT setting `closedByUs`, so the close\n * lands on `onClose`'s ordinary transient path — which already owns the\n * reconnect scheduling, the backoff, and the resume-cursor recovery. Nothing\n * about reconnect policy is duplicated here.\n */\n private closeDeadSocket(): void {\n const socket = this.socket;\n this.diag?.(DIAG.SOCKET_LIVENESS_TIMEOUT, {\n silentMs: this.lastInboundAt == null ? null : this.timers.now() - this.lastInboundAt,\n thresholdMs: INBOUND_SILENCE_LIMIT_MS,\n attempt: this.connectAttempt,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n });\n this.lastInboundAt = null;\n socket?.close(WATCHDOG_CLOSE_CODE, 'client liveness timeout');\n }\n\n // ---- teardown ----\n\n /** Permanently close this client (auth-user switch / unmount). Idempotent. */\n close(): void {\n this.closedByUs = true;\n this.lifecycle += 1;\n this.controller.close();\n this.initialLoad.dispose();\n this.stopHeartbeat();\n // The heartbeat timer IS the watchdog's timer — stopping it above ends both.\n // Clearing the record too means a later connect() starts from a clean deadline.\n this.lastInboundAt = null;\n for (const t of this.typingTimers.values()) this.timers.clearTimeout(t);\n this.typingTimers.clear();\n this.overlays.clear();\n this.originalRows.clear();\n // Cancel every per-send retry timer before dropping the tracking map.\n for (const pending of this.pendingSends.values()) this.clearSendRetryTimer(pending);\n this.pendingSends.clear();\n if (this.reconnectTimer != null) {\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.membershipRetryTimer != null) {\n this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = null;\n }\n if (this.socket) {\n // Detach first: the socket's own late close is not this lifecycle's event.\n const socket = this.socket;\n this.socket = null;\n socket.close(1000, 'client teardown');\n }\n this.setState({ status: 'closed', typing: [], presence: [], isFetchingOlder: false });\n }\n}\n\nfunction sortBySeq(a: ChatMessageV1, b: ChatMessageV1): number {\n const sa = typeof a.meta?.seq === 'number' ? (a.meta.seq as number) : Number.POSITIVE_INFINITY;\n const sb = typeof b.meta?.seq === 'number' ? (b.meta.seq as number) : Number.POSITIVE_INFINITY;\n if (sa !== sb) return sa - sb;\n return a.createdAt - b.createdAt;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"channel-client.js","sourceRoot":"","sources":["../../src/realtime/channel-client.ts"],"names":[],"mappings":"AAAA,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;AASnB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,cAAc,EACd,sBAAsB,EACtB,cAAc,GAEf,MAAM,UAAU,CAAC;AAElB,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,6BAA6B,IAAI,IAAI,GAGtC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EAChB,yBAAyB,EACzB,uBAAuB,EACvB,2BAA2B,EAC3B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AM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;YAC3B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;YACnB,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;QACxC,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC,CAAC;IACxF,CAAC;CACF;AAED,SAAS,SAAS,CAAC,CAAgB,EAAE,CAAgB;IACnD,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,EAAE,GAAG,EAAE,CAAC;IAC9B,OAAO,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC;AACnC,CAAC","sourcesContent":["// 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 {\n ChatHistoryPayload,\n ChatReadAckPayload,\n ChatResumePayload,\n ChatSendPayload,\n ClientFrameKind,\n} from '@ttt-productions/chat-schemas';\nimport type { RealtimeSocket, SocketFactory } from './socket.js';\nimport {\n wireRowToMessage,\n optimisticMessage,\n seqToMessageId,\n applyModerationOverlay,\n overlayFromRow,\n type ModerationOverlay,\n} from './map.js';\nimport type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';\nimport {\n createDiagnosticsEmitter,\n safeDiagnosticLabel,\n CHAT_CLIENT_DIAGNOSTIC_EVENTS as DIAG,\n type ChatClientDiagnosticsEmitter,\n type ChatClientDiagnosticsOption,\n} from './diagnostics.js';\nimport {\n defaultTimers,\n isChatAccessDeniedError,\n isTerminalErrorCode,\n TERMINAL_ERROR_CODE,\n 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';\nimport { InitialLoadBudget } from './initial-load-budget.js';\n\n/**\n * The payload of each frame this client sends, typed by the chat-schemas payload the Worker parses\n * it with, so a sender that drifts from the contract fails to compile. A frame with no payload\n * schema (typing, presence, heartbeat) carries an empty object.\n */\ntype ChannelFramePayload<K extends ClientFrameKind> = K extends typeof CLIENT_FRAME.SEND\n ? ChatSendPayload\n : K extends typeof CLIENT_FRAME.READ_ACK\n ? ChatReadAckPayload\n : K extends typeof CLIENT_FRAME.HISTORY\n ? ChatHistoryPayload\n : K extends typeof CLIENT_FRAME.RESUME\n ? ChatResumePayload\n : Record<string, never>;\n\n/** An un-acked send tracked for reconnect resend (clientMessageId idempotency). */\ninterface PendingSend {\n clientMessageId: string;\n text: string;\n /** When the send was first attempted (for the age/budget caps). Reset by retrySend(). */\n sentAt: number;\n /** How many times it has been (re)sent over a socket. Reset by retrySend(). */\n attempts: number;\n /** True once the attempt/age/budget cap flipped this send to the visible failed\n * state. A failed entry is RETAINED (not deleted) so retrySend() can re-queue it\n * with the SAME clientMessageId; it is skipped by the automatic reconnect resend. */\n failed: boolean;\n /**\n * Set true once the Worker has declared THIS send retryable — either a correlated\n * `send-rejected` (retryable) frame or the legacy uncorrelated\n * `error{code:'membership-pending'}`. A server-retryable send is governed by the\n * {@link SERVER_RETRYABLE_MAX_AGE_MS} wall-clock budget and is NEVER failed by the\n * generic {@link MAX_PENDING_SEND_ATTEMPTS} cap (that cap stays for blind reconnect\n * resends of sends the server has said nothing about).\n */\n serverRetryable: boolean;\n /** The most recent server rejection code, recorded so a budget-exhausted failure\n * can surface the reason (and keep a retry affordance for the transient class). */\n lastRejectionCode?: ChatSendRejectionCode;\n /** The single per-send resend timer for a correlated retryable rejection (never\n * stacks — a newer rejection clears it first; cleared on ack/echo/manual\n * retry/terminal/close/dispose). */\n retryTimer: ReturnType<TransportTimers['setTimeout']> | null;\n}\n\nexport interface ChannelClientState {\n status: RealtimeStatus;\n /** Ordered ascending by seq; optimistic messages (no seq yet) sort to the tail. */\n messages: ChatMessageV1[];\n /** uids currently typing (cleared after ~TYPING_COALESCE_MS of silence). */\n typing: string[];\n /** uids the DO reports online (presence). Empty until presence-subscribe. */\n presence: string[];\n /** True while an older-history page request is in flight. */\n isFetchingOlder: boolean;\n /** False once a history page returns fewer than the requested limit (reached the head). */\n hasOlder: boolean;\n /** The last structured error code the DO sent (e.g. 'blocked-word', 'too-long', flood reason). */\n lastErrorCode: string | null;\n /**\n * True once the FIRST authoritative chat data has been applied — a non-resync\n * resume snapshot, OR the first history page (INCLUDING an empty one). Drives the\n * hook's `isInitialLoading` so the shell shows an honest \"Opening chat…\" state\n * while the first data is loading, and a real empty-chat surface only after an\n * authoritative empty result. NEVER inferred from `messages.length === 0` (an\n * empty first history page IS a successful load). Once true it stays true — a\n * later disconnect/reconnect keeps loaded messages mounted, not a re-loader.\n * A grant retry / socket open before any snapshot leaves it false.\n */\n hasLoadedInitialData: boolean;\n /**\n * True once the first open has failed for good enough to say so: attempts have kept\n * failing for {@link CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS} without any initial data, or\n * reconnecting stopped (gave up, or the socket was revoked) before any. The client keeps\n * retrying in the background; the first authoritative data, or a manual `retryNow()`,\n * clears it. Never true once initial data has loaded — a later outage keeps the loaded\n * messages under the reconnect banner instead.\n */\n initialLoadFailed: boolean;\n /**\n * True while the channel is CURRENT: the socket is open, initial data has loaded, and the\n * authoritative state has been re-applied since this socket opened — a non-resync resume\n * snapshot, or the history page answering a resync. Cleared the moment the socket closes,\n * reconnects, or is denied, and false again on every new socket until its resume lands, so a\n * consumer that must act on the conversation's current terms (an agreement, an offer) waits for\n * it. Unlike `hasLoadedInitialData` it is never sticky.\n */\n isSynced: boolean;\n}\n\nexport interface ChannelClientConfig {\n /** WebSocket endpoint base, e.g. `wss://chat.example.com`. The client appends `/channel`. */\n endpoint: string;\n /** The logical thread id the UI keys on (used as ChatMessageV1.threadId). */\n threadId: string;\n /** The authenticated uid (sender identity for optimistic echoes + auth-switch guard). */\n currentUserId: string;\n /** Mints/refreshes a channel grant. Called on connect and once on a 4401 re-grant. */\n grantProvider: GrantProvider;\n socketFactory: SocketFactory;\n timers?: TransportTimers;\n /** Reconnect backoff tuning (forwarded to realtime-core). */\n reconnect?: { 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 initialLoadFailed: false,\n isSynced: false,\n};\n\n/**\n * Retryable error-frame code the channel DO sends when a send arrives BEFORE the\n * member row has synced through the async backend→worker pipeline (a just-created\n * invite/channel). The socket stays open; the client re-sends after `retryAfterMs`\n * through the normal resendPendingSends machinery (same caps). The string is part\n * of the wire contract with the worker runtime's send handler.\n */\nconst MEMBERSHIP_PENDING_CODE = 'membership-pending';\n\n/** Why a history page was requested: to re-page after a resync, or for older messages. */\ntype HistoryRequestKind = 'resync' | 'older';\n/** Fallback retry delay when the frame omits/breaks `retryAfterMs`. */\nconst MEMBERSHIP_PENDING_DEFAULT_RETRY_MS = 2000;\n\n/**\n * Dead-socket watchdog: how long inbound silence may last before this client\n * treats the socket as dead and closes it locally.\n *\n * CHANNEL-ONLY, and this is why it is sound here: the channel DO answers every\n * 20 s client `heartbeat` through the hibernation AUTO-RESPONSE API, so a healthy\n * channel socket is NEVER silent for a full heartbeat window. Inbound silence past\n * this threshold is therefore provable death (a half-open TCP connection whose\n * `onclose` never fires), not idleness. The INBOX socket has no such auto-response\n * and a healthy idle inbox is legitimately silent for hours — applying this rule\n * there would endlessly reconnect healthy sockets, so it is deliberately absent\n * from `inbox-client.ts`.\n *\n * PRIVATE CLIENT POLICY, not a wire constant: nothing on the worker side agrees to\n * it, so it does not belong in `@ttt-productions/chat-schemas` or in this package's\n * exported surface. The check rides the existing 20 s heartbeat tick (no second\n * timer), so detection lands on the NEXT tick after the deadline rather than at\n * exactly 50 s — intended: 2.5 missed windows is unambiguous, and it costs no\n * extra timer.\n */\nconst INBOUND_SILENCE_LIMIT_MS = 50_000;\n\n/**\n * Close code used for the watchdog's LOCAL close. A browser `WebSocket.close()`\n * accepts only 1000 or 3000–4999, and the private 4xxx range is the chat wire's\n * (`CHAT_CLOSE_CODES`) — a client-invented code there could collide with a future\n * server code. 1000 keeps the close frame valid and, being neither 4401 nor 4403,\n * routes through `onClose`'s ordinary transient path, which owns reconnect,\n * backoff, and resume. The reason string + the liveness diagnostic are what\n * identify it.\n */\nconst WATCHDOG_CLOSE_CODE = 1000;\n\nexport class ChannelClient {\n private readonly timers: TransportTimers;\n private readonly controller: ReconnectController;\n private socket: RealtimeSocket | null = null;\n private state: ChannelClientState = INITIAL;\n private readonly listeners = new Set<(s: ChannelClientState) => void>();\n\n /** Resume cursor: highest seq we've durably applied. Sent on resume after reconnect. */\n private resumeSeq = 0;\n /** Last read-ack the UI requested; re-sent on reconnect so a drop during a closed\n * socket window is recovered (M2). */\n private lastReadAck: { readSeq: number; focused: boolean } | null = null;\n /** True after a `4401` re-grant has been attempted for the CURRENT connect cycle (once-only). */\n private reauthAttempted = false;\n private presenceSubscribed = false;\n private heartbeatTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n /**\n * When the CURRENT socket last proved it was alive: set on open, refreshed by\n * every successfully parsed inbound frame (`heartbeat-ack` included — that IS\n * the DO's liveness answer). Null whenever no socket is live, so the watchdog\n * can never judge a socket that does not exist. See {@link INBOUND_SILENCE_LIMIT_MS}.\n */\n private lastInboundAt: number | null = null;\n // History requests sent on the current socket and not yet answered, oldest first.\n private historyRequests: HistoryRequestKind[] = [];\n private typingTimers = new Map<string, ReturnType<TransportTimers['setTimeout']>>();\n private lastTypingSentAt = Number.NEGATIVE_INFINITY;\n private reconnectTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n /** Single scheduled re-send for the membership-pending window (never stacks). */\n private membershipRetryTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private closedByUs = false;\n /**\n * The current lifecycle's number, advanced by every `connect()` and `close()`. A grant\n * that resolves, or a timer that fires, for an older lifecycle is dropped — so a\n * close → connect while an earlier grant is still minting can never open a second\n * socket or touch the new lifecycle's state (FRONTEND-108).\n */\n private lifecycle = 0;\n /** Reports the first open as failed once its attempts have failed for the budget. */\n private readonly initialLoad: InitialLoadBudget;\n /**\n * Per-seq moderation overlay (the max-revision wins). A `revision` frame writes\n * here keyed by `messageSeq` so it applies whether it arrives BEFORE its base\n * row (re-applied when the row later renders) or AFTER (re-renders the present\n * row in place). Merged with the row's own inline `moderationKind` so a row that\n * arrives already-moderated from the DO AND one covered by a live frame both\n * render the moderated state. */\n private overlays = new Map<number, ModerationOverlay>();\n /**\n * The ORIGINAL (un-overlaid) mapped message per seq. A `restore` revision must\n * revert a previously-redacted message to its original text, so re-renders start\n * from this cache rather than the (possibly already-blanked) message in state. */\n private originalRows = new Map<number, ChatMessageV1>();\n /**\n * Un-acked sends keyed by clientMessageId. A send is added here when its frame is\n * written and removed when its `ack` (or the canonical `message` echo carrying the\n * same clientMessageId) arrives. On every reconnect resume they are RE-SENT with\n * the SAME clientMessageId — the DO dedups (re-acks without re-broadcast), so a\n * send that lost its socket before the ack is delivered exactly once. A pending\n * send that exceeds the attempt/age cap is flipped to a visible failed state\n * (retry affordance) instead of staying a ghost. */\n private pendingSends = new Map<string, PendingSend>();\n /**\n * The structured diagnostics emitter, or null when diagnostics are off (the\n * default). Every call site uses `this.diag?.(...)` so the off path constructs\n * no payload at all.\n */\n private readonly diag: ChatClientDiagnosticsEmitter;\n /** Monotonic socket-open attempt counter (diagnostics correlation only). */\n private connectAttempt = 0;\n /** Why the CURRENT connect attempt is happening (diagnostics only). */\n private reconnectCause: 'initial' | 'auth-expired' | 'transient-close' | 'grant-error' | 'manual-retry' = 'initial';\n /** The last close code observed, carried into the next attempt's cause line. */\n private lastCloseCode: number | null = null;\n\n constructor(private readonly config: ChannelClientConfig) {\n this.timers = config.timers ?? defaultTimers;\n this.controller = createReconnectController(config.reconnect ?? {});\n this.diag = createDiagnosticsEmitter(config.diagnostics);\n this.initialLoad = new InitialLoadBudget(this.timers, () => this.reportInitialLoadFailed());\n }\n\n // ---- observable store ----\n\n getState(): ChannelClientState {\n return this.state;\n }\n\n subscribe(fn: (s: ChannelClientState) => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n private setState(patch: Partial<ChannelClientState>): void {\n this.state = { ...this.state, ...patch };\n // Only an open socket can be current.\n if (this.state.status !== 'open') this.state.isSynced = false;\n for (const fn of this.listeners) fn(this.state);\n }\n\n // ---- connection lifecycle ----\n\n async connect(): Promise<void> {\n return this.startLifecycle(true);\n }\n\n /**\n * Retry now (the first-open failure's Retry). While a reconnect is waiting out its\n * backoff, the wait is cancelled and a socket opens at once; a lifecycle that stopped\n * (reconnect gave up, or the socket was revoked) starts again; an attempt already in\n * flight is left to finish. Either way the first-open failure clears, so the opening state\n * shows while the retry runs. The spent budget stays spent: a retry that fails is reported\n * again at once, and one that hangs a full budget later.\n */\n retryNow(): void {\n if (!this.state.hasLoadedInitialData) this.initialLoad.manualRetry();\n if (this.state.status === 'closed') {\n void this.startLifecycle(false);\n return;\n }\n if (this.reconnectTimer == null) {\n if (this.state.initialLoadFailed) this.setState({ initialLoadFailed: false });\n return;\n }\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n this.controller.reset();\n this.controller.start();\n this.reconnectCause = 'manual-retry';\n this.setState({ status: 'reconnecting', initialLoadFailed: false });\n void this.openSocket();\n }\n\n private async startLifecycle(freshBudget: boolean): Promise<void> {\n // Idempotency guard (C-B7): connect() only starts a lifecycle from a fresh\n // (idle) or fully torn-down (closed) state. A second connect() while one is\n // already connecting / open / reconnecting is a no-op, so a stray double-owner\n // can't open a second WebSocket. The reconnect path uses openSocket() /\n // scheduleReconnect() directly (never connect()), so this never blocks a\n // legitimate reconnect.\n if (this.state.status !== 'idle' && this.state.status !== 'closed') return;\n // REVIVE the controller. `controller.close()` is PERMANENT: while it is in\n // state `closed`, `start()` and `onOpen()` no-op and every later `onClose()`\n // returns null. So without this reset a close() → connect() client opens a\n // socket and works normally until its FIRST transient close, at which point\n // `scheduleReconnect()` gets null and parks it terminally in `closed` with\n // reconnect disabled and no surfaced error code. The idempotency guard above\n // is what keeps this from disturbing a live lifecycle: only an `idle` or\n // fully torn-down (`closed`) client ever reaches here.\n this.controller.reset();\n // A terminal verdict (4403 REVOKED / ChatAccessDeniedError) is terminal WITHIN\n // its lifecycle; an explicit connect() is a fresh attempt the authority may\n // legitimately re-deny, so the previous lifecycle's code must not persist into\n // this one (the hook maps `access-denied` to `allowed: false`). Loaded\n // messages and the initial-load flag are deliberately KEPT — a lifecycle\n // restart must not churn the UI back to an empty opening state.\n if (isTerminalErrorCode(this.state.lastErrorCode)) this.setState({ lastErrorCode: null });\n this.closedByUs = false;\n this.lifecycle += 1;\n this.reconnectCause = 'initial';\n if (!this.state.hasLoadedInitialData) this.initialLoad.begin(freshBudget);\n this.controller.start();\n this.setState({ status: 'connecting', initialLoadFailed: false });\n await this.openSocket();\n }\n\n /** The first open has failed for long enough to say so (see `initialLoadFailed`). */\n private reportInitialLoadFailed(): void {\n if (this.state.hasLoadedInitialData || this.state.initialLoadFailed) return;\n this.setState({ initialLoadFailed: true });\n }\n\n /** The first authoritative data is applied; it ends any first-open failure. */\n private initialDataLoaded(): Partial<ChannelClientState> {\n this.initialLoad.loaded();\n return { hasLoadedInitialData: true, initialLoadFailed: false };\n }\n\n private async openSocket(): Promise<void> {\n const lifecycle = this.lifecycle;\n this.connectAttempt += 1;\n this.diag?.(DIAG.CONNECT_ATTEMPT, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n closeCode: this.lastCloseCode,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n });\n let grantToken: string;\n try {\n grantToken = await this.config.grantProvider();\n } catch (err) {\n // A grant for a lifecycle that has since been closed or restarted answers nobody.\n if (lifecycle !== this.lifecycle) return;\n // A TERMINAL access denial (the app's grant provider translated an\n // authoritative policy \"no\" into the package-owned ChatAccessDeniedError)\n // must NOT reconnect — the next mint would just re-deny, stranding the shell\n // on the opening loader forever. Every other mint failure (network, transient\n // 'unavailable'/'internal', post-login 'unauthenticated') stays retryable and\n // backs off exactly as before.\n const terminal = isChatAccessDeniedError(err);\n this.diag?.(DIAG.GRANT_FAILED, { attempt: this.connectAttempt, terminal });\n if (terminal) return this.denyAccessTerminally();\n this.reconnectCause = 'grant-error';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n return this.scheduleReconnect();\n }\n // A grant minted for an earlier lifecycle must never open a socket in this one.\n if (lifecycle !== this.lifecycle || this.closedByUs) return;\n // Socket REPLACEMENT: the previous socket's liveness record dies with it, so\n // the watchdog never judges a new socket against an old deadline.\n this.lastInboundAt = null;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/channel`;\n // Every callback is fenced to THIS socket: once it has been replaced or torn down,\n // its late open, frames, and close are ignored.\n let socket: RealtimeSocket | null = null;\n const isCurrent = () => socket !== null && this.socket === socket;\n socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => {\n if (isCurrent()) this.onOpen();\n },\n onMessage: (data) => {\n if (isCurrent()) this.onMessage(data);\n },\n onClose: (code, reason) => {\n if (isCurrent()) this.onClose(code, reason);\n },\n onError: () => {\n if (isCurrent()) this.onError();\n },\n },\n });\n this.socket = socket;\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n // Start the liveness clock at open — the first heartbeat window is measured\n // from here, not from a stale previous socket.\n this.lastInboundAt = this.timers.now();\n // A new socket is current only once its resume lands.\n this.historyRequests = [];\n this.setState({ status: 'open', isSynced: false });\n this.diag?.(DIAG.SOCKET_OPEN, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n presenceSubscribed: this.presenceSubscribed,\n });\n // Resume: ask the DO for the authoritative snapshot, then live deltas flow. The\n // field name MUST be `afterSeq` — the Channel DO reads `payload.afterSeq`; any other\n // name reads as cursorless and forces a full resync every reconnect.\n this.sendFrame(CLIENT_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 });\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 });\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 });\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.lastInboundAt = null;\n this.lastCloseCode = code;\n // An older-history request in flight died with the socket; nothing will answer it.\n if (this.state.isFetchingOlder) this.setState({ isFetchingOlder: false });\n if (this.closedByUs) {\n this.diag?.(DIAG.SOCKET_CLOSE, { 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: TERMINAL_ERROR_CODE.REVOKED });\n // Revoked before anything loaded: the first open has failed, and nothing retries it.\n this.reportInitialLoadFailed();\n return;\n }\n this.reconnectCause = 'transient-close';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n this.diag?.(DIAG.SOCKET_CLOSE, { 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 // Gave up before anything loaded: nothing retries the first open any more.\n this.reportInitialLoadFailed();\n return;\n }\n this.setState({ status: 'reconnecting' });\n const lifecycle = this.lifecycle;\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs || lifecycle !== this.lifecycle) return;\n void this.openSocket();\n }, delay);\n }\n\n /**\n * Terminal access denial surfaced by the grant provider (ChatAccessDeniedError).\n * A reconnect would just re-deny at the next mint, so stop for good — the same\n * terminal posture as a 4403 REVOKED close: mark closed-by-us, close the reconnect\n * controller, and flip every un-acked pending send to the visible failed state.\n * `access-denied` is set AFTER failAllPendingSends so its 'send-failed' code does\n * not win as the surfaced error; the React hook maps 'access-denied' to\n * `allowed: false` so the shell renders its existing no-access surface.\n */\n private denyAccessTerminally(): void {\n this.closedByUs = true;\n this.controller.close();\n this.initialLoad.dispose();\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.ACCESS_DENIED });\n }\n\n // ---- inbound frames ----\n\n private onMessage(data: string): void {\n const frame = parseFrame(data);\n if (!frame || !frame.type) {\n // Unparseable: bytes arrived, but nothing proves they came from a DO\n // speaking this protocol, so this must NOT refresh the liveness deadline.\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'unparseable', reason: 'bad-envelope' });\n return;\n }\n // A well-formed envelope IS the liveness proof — including the `heartbeat-ack`\n // the DO auto-responds with, and a forward-compat type this build does not\n // handle yet (a newer DO's frames must never be read as a dead socket).\n this.lastInboundAt = this.timers.now();\n const payload = frame.payload ?? {};\n switch (frame.type) {\n case 'message':\n return this.applyMessage((payload as { message: WireMessageRow }).message, 'live');\n case 'ack':\n return this.applyAck(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 this.setState({ ...(this.state.hasLoadedInitialData ? {} : this.initialDataLoaded()), isSynced: 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, 'resync');\n }\n\n /**\n * Apply one server row (a live `message` frame or a resume-delta row) and record\n * the decision the client made about it.\n *\n * Diagnostics bounding: a LIVE frame always emits one `chat_client_frame_applied`\n * line; a DELTA row emits one only when it is materially interesting (carries a\n * moderation kind, or reconciles one of our optimistic sends) — a 500-row backlog\n * is otherwise summarized by `chat_client_resume_result` rather than spamming 500\n * lines.\n */\n private applyMessage(row: WireMessageRow, source: 'live' | 'delta'): void {\n if (!row || typeof row.seq !== 'number') {\n this.diag?.(DIAG.FRAME_DROPPED, { kind: 'message', source, reason: 'missing-seq' });\n return;\n }\n // Read the pre-merge view ONLY when diagnostics are on (these are O(n) scans).\n const prior = this.diag ? this.priorRowFacts(row) : null;\n const cursorBefore = this.resumeSeq;\n const mapped = this.renderRow(row);\n this.mergeMessage(mapped, row);\n if (row.seq > this.resumeSeq) this.resumeSeq = row.seq;\n if (!this.diag || !prior) return;\n\n const notable = row.moderationKind != null || prior.reconciledOptimistic;\n if (source === 'delta' && !notable) return;\n this.diag(DIAG.FRAME_APPLIED, {\n kind: 'message',\n source,\n seq: row.seq,\n hasClientMessageId: Boolean(row.clientMessageId),\n moderationKind: row.moderationKind ?? null,\n op: prior.reconciledOptimistic ? '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 // The socket answers history requests in the order they were sent; the page answering a\n // resync is the one that makes the channel current again.\n const answersResync = this.historyRequests.shift() === 'resync';\n const mapped = rows.map((r) => this.renderRow(r));\n // Mirror mergeMessage's optimistic reconciliation: a history row carrying a\n // clientMessageId we still hold as an optimistic placeholder IS that send (the\n // DO stored it; the ack was lost). Drop the placeholder — keyed `optimistic:{cmid}`,\n // it would otherwise survive alongside its seq-keyed server row as a duplicate\n // bubble after a resync + re-page — and stop tracking it for resend.\n const incomingCmids = new Set<string>();\n for (const r of rows) {\n if (r.clientMessageId) {\n incomingCmids.add(r.clientMessageId);\n this.clearPendingSend(r.clientMessageId);\n }\n }\n const bySeq = new Map<string, ChatMessageV1>();\n for (const m of this.state.messages) {\n if (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. An older page arrives only after it, so this\n // never runs a second time.\n ...(this.state.hasLoadedInitialData ? {} : this.initialDataLoaded()),\n ...(answersResync ? { isSynced: true } : {}),\n });\n if (!this.diag) return;\n const seqs = rows.map((r) => r.seq).filter((s): s is number => typeof s === 'number');\n this.diag(DIAG.HISTORY_PAGE, {\n count: rows.length,\n minSeq: seqs.length > 0 ? Math.min(...seqs) : null,\n maxSeq: seqs.length > 0 ? Math.max(...seqs) : null,\n cursorBefore,\n cursorAfter: this.resumeSeq,\n reconciledOptimistic: incomingCmids.size,\n hasOlder: rows.length >= HISTORY_PAGE_MAX,\n total: merged.length,\n });\n }\n\n private applyTyping(uid: string): void {\n if (!uid || uid === this.config.currentUserId) return;\n if (!this.state.typing.includes(uid)) this.setState({ typing: [...this.state.typing, uid] });\n const prev = this.typingTimers.get(uid);\n if (prev) this.timers.clearTimeout(prev);\n this.typingTimers.set(\n uid,\n this.timers.setTimeout(() => {\n this.typingTimers.delete(uid);\n this.setState({ typing: this.state.typing.filter((u) => u !== uid) });\n }, TYPING_COALESCE_MS * 2),\n );\n }\n\n // ---- outbound actions ----\n\n private sendFrame<K extends ClientFrameKind>(type: K, payload: ChannelFramePayload<K>): boolean {\n if (!this.socket || !this.socket.isOpen) return false;\n this.socket.send(buildFrame(type, payload));\n return true;\n }\n\n /**\n * Optimistic send: render the echo immediately keyed by clientMessageId, then\n * emit the `send` frame. The server `ack`/`message` reconciles on the seq.\n */\n send(args: { clientMessageId: string; text: string }): boolean {\n // C-B8: write the frame FIRST and render the optimistic echo ONLY if it was\n // actually sent over an open socket. A closed socket returns false — no phantom\n // \"sent\" bubble, and the caller keeps the composer text — so a disconnect between\n // render and click can't silently swallow the message.\n const sent = this.sendFrame(CLIENT_FRAME.SEND, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n });\n if (!sent) {\n this.diag?.(DIAG.SEND_FAILED, {\n clientMessageId: args.clientMessageId,\n code: 'send-failed',\n retryable: null,\n attempts: 0,\n reason: 'socket-not-open',\n });\n this.setState({ lastErrorCode: 'send-failed' });\n return false;\n }\n const now = this.timers.now();\n // Track the un-acked send so a reconnect re-sends it with the same\n // clientMessageId (the DO dedups) — until the ack/echo clears it.\n this.pendingSends.set(args.clientMessageId, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n sentAt: now,\n attempts: 1,\n failed: false,\n serverRetryable: false,\n retryTimer: null,\n });\n const echo = optimisticMessage({\n clientMessageId: args.clientMessageId,\n threadId: this.config.threadId,\n senderId: this.config.currentUserId,\n text: args.text,\n createdAt: now,\n });\n const next = [...this.state.messages, echo].sort(sortBySeq);\n this.setState({ messages: next, lastErrorCode: null });\n this.diag?.(DIAG.SEND_OPTIMISTIC, {\n clientMessageId: args.clientMessageId,\n pendingSends: this.pendingSends.size,\n });\n return true;\n }\n\n /**\n * Explicit read ack (delivery != read). `focused` => the channel is open + at latest.\n * Remembers the cursor (re-sent on reconnect) and returns whether the frame was\n * actually sent over an open socket, so the caller only advances its local\n * already-acked marker on a real send (M2).\n */\n readAck(readSeq: number, focused: boolean): boolean {\n this.lastReadAck = { readSeq, focused };\n return this.sendFrame(CLIENT_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 // Unsent (the socket is down): nothing will answer, so it is not in flight.\n if (!this.requestHistory(beforeSeq, 'older')) this.setState({ isFetchingOlder: false });\n }\n\n private requestHistory(beforeSeq: number | null, kind: HistoryRequestKind): boolean {\n const sent = this.sendFrame(CLIENT_FRAME.HISTORY, { beforeSeq, limit: HISTORY_PAGE_MAX });\n if (sent) this.historyRequests.push(kind);\n this.diag?.(DIAG.HISTORY_REQUEST, { beforeSeq, limit: HISTORY_PAGE_MAX, sent });\n return sent;\n }\n\n // ---- heartbeat (20s) + dead-socket watchdog ----\n\n private startHeartbeat(): void {\n this.stopHeartbeat();\n const tick = () => {\n if (!this.socket || !this.socket.isOpen) return;\n // Liveness is checked BEFORE the write: a socket already proven dead must\n // not be handed another frame. Closing here does not reschedule — onClose\n // stops the heartbeat and owns what happens next.\n if (this.isInboundSilent()) return this.closeDeadSocket();\n this.sendFrame(CLIENT_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 /** True when the live socket has produced no parseable frame for too long. */\n private isInboundSilent(): boolean {\n if (this.lastInboundAt == null) return false;\n return this.timers.now() - this.lastInboundAt >= INBOUND_SILENCE_LIMIT_MS;\n }\n\n /**\n * The channel DO auto-acks every heartbeat, so silence past\n * {@link INBOUND_SILENCE_LIMIT_MS} means this socket is dead even though no\n * `onclose` ever fired (the half-open-connection case that otherwise strands\n * the UI on a socket that will never deliver another message).\n *\n * Close it LOCALLY and deliberately WITHOUT setting `closedByUs`, so the close\n * lands on `onClose`'s ordinary transient path — which already owns the\n * reconnect scheduling, the backoff, and the resume-cursor recovery. Nothing\n * about reconnect policy is duplicated here.\n */\n private closeDeadSocket(): void {\n const socket = this.socket;\n this.diag?.(DIAG.SOCKET_LIVENESS_TIMEOUT, {\n silentMs: this.lastInboundAt == null ? null : this.timers.now() - this.lastInboundAt,\n thresholdMs: INBOUND_SILENCE_LIMIT_MS,\n attempt: this.connectAttempt,\n resumeSeq: this.resumeSeq,\n pendingSends: this.pendingSends.size,\n });\n this.lastInboundAt = null;\n socket?.close(WATCHDOG_CLOSE_CODE, 'client liveness timeout');\n }\n\n // ---- teardown ----\n\n /** Permanently close this client (auth-user switch / unmount). Idempotent. */\n close(): void {\n this.closedByUs = true;\n this.lifecycle += 1;\n this.controller.close();\n this.initialLoad.dispose();\n this.stopHeartbeat();\n // The heartbeat timer IS the watchdog's timer — stopping it above ends both.\n // Clearing the record too means a later connect() starts from a clean deadline.\n this.lastInboundAt = null;\n for (const t of this.typingTimers.values()) this.timers.clearTimeout(t);\n this.typingTimers.clear();\n this.overlays.clear();\n this.originalRows.clear();\n // Cancel every per-send retry timer before dropping the tracking map.\n for (const pending of this.pendingSends.values()) this.clearSendRetryTimer(pending);\n this.pendingSends.clear();\n if (this.reconnectTimer != null) {\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.membershipRetryTimer != null) {\n this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = null;\n }\n if (this.socket) {\n // Detach first: the socket's own late close is not this lifecycle's event.\n const socket = this.socket;\n this.socket = null;\n socket.close(1000, 'client teardown');\n }\n this.setState({ status: 'closed', typing: [], presence: [], isFetchingOlder: false });\n }\n}\n\nfunction sortBySeq(a: ChatMessageV1, b: ChatMessageV1): number {\n const sa = typeof a.meta?.seq === 'number' ? (a.meta.seq as number) : Number.POSITIVE_INFINITY;\n const sb = typeof b.meta?.seq === 'number' ? (b.meta.seq as number) : Number.POSITIVE_INFINITY;\n if (sa !== sb) return sa - sb;\n return a.createdAt - b.createdAt;\n}\n"]}
|
|
@@ -10,6 +10,8 @@ export type UseRealtimeChatMessagesResult = {
|
|
|
10
10
|
isFetchingOlder: boolean;
|
|
11
11
|
/** True once the first open has failed (see `ChannelClientState.initialLoadFailed`). */
|
|
12
12
|
initialLoadFailed: boolean;
|
|
13
|
+
/** The channel is current (see `ChannelClientState.isSynced`): act on its terms only while true. */
|
|
14
|
+
isSynced: boolean;
|
|
13
15
|
/** Retry the connection now — the first-open failure's Retry. */
|
|
14
16
|
retry: () => void;
|
|
15
17
|
/** Realtime extras (not present on the firestore result) — optional for the UI. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRealtimeChatMessages.d.ts","sourceRoot":"","sources":["../../src/realtime/useRealtimeChatMessages.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAI9D,MAAM,MAAM,6BAA6B,GAAG;IAC1C,OAAO,EAAE,OAAO,CAAC;IACjB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,QAAQ,EAAE,OAAO,CAAC;IAClB,eAAe,EAAE,OAAO,CAAC;IACzB,wFAAwF;IACxF,iBAAiB,EAAE,OAAO,CAAC;IAC3B,iEAAiE;IACjE,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,mFAAmF;IACnF,MAAM,EAAE,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IACrC;4CACwC;IACxC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,MAAM,EAAE,MAAM,EAAE,C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AC,CAAC;IACrC;4CACwC;IACxC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,iHAAiH;IACjH,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IAChC;;;;;uCAKmC;IACnC,SAAS,EAAE,CAAC,eAAe,EAAE,MAAM,KAAK,OAAO,CAAC;IAChD,sIAAsI;IACtI,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC;IACxD,YAAY,EAAE,MAAM,IAAI,CAAC;IACzB;;yEAEqE;IACrE,iBAAiB,EAAE,MAAM,IAAI,CAAC;IAC9B,mBAAmB,EAAE,MAAM,IAAI,CAAC;CACjC,CAAC;AAEF,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,kBAAkB,GAAG,6BAA6B,CAkFjG"}
|
|
@@ -58,6 +58,8 @@ export function useRealtimeChatMessages(client) {
|
|
|
58
58
|
// fall back into the opening state. `hasLoadedInitialData` encodes the full table.
|
|
59
59
|
isInitialLoading: !state.hasLoadedInitialData,
|
|
60
60
|
initialLoadFailed: state.initialLoadFailed,
|
|
61
|
+
// Current: open, loaded, and resynced since this socket opened (never sticky).
|
|
62
|
+
isSynced: state.isSynced,
|
|
61
63
|
retry,
|
|
62
64
|
messages: state.messages,
|
|
63
65
|
fetchOlder,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRealtimeChatMessages.js","sourceRoot":"","sources":["../../src/realtime/useRealtimeChatMessages.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,qEAAqE;AACrE,+EAA+E;AAC/E,kFAAkF;AAClF,2EAA2E;AAC3E,oFAAoF;AACpF,iFAAiF;AACjF,mFAAmF;AACnF,oFAAoF;AACpF,gBAAgB;AAEhB,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AA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\n\n// React hook for the REALTIME transport, returning the SAME shape as\n// `useChatMessages` (the firestore path) so `ChatShell` is transport-agnostic.\n// It SUBSCRIBES to a `RealtimeChatClient`'s observable state. It does NOT own the\n// socket lifecycle: the caller (the app hook that CREATES the client, e.g.\n// `useRealtimeChannelClient`) is the single connect/close owner (C-B7) — connecting\n// here too opened a second WebSocket. The client instance is owned by the caller\n// (passed via config) so its identity is the subscription key — a new client for a\n// new uid replaces the old one (Contract A auth-user-switch teardown happens in the\n// owning hook).\n\nimport * as React from \"react\";\nimport type { ChatMessageV1 } from \"@ttt-productions/chat-core\";\nimport type { RealtimeChatClient } from \"./transport.js\";\nimport type { ChannelClientState } from \"./channel-client.js\";\nimport { useOptionalChatNameResolver } from \"../context/ChatNameResolverContext.js\";\nimport { newCorrelationId } from \"./shared.js\";\n\nexport type UseRealtimeChatMessagesResult = {\n allowed: boolean;\n isInitialLoading: boolean;\n messages: ChatMessageV1[];\n fetchOlder: () => Promise<void>;\n hasOlder: boolean;\n isFetchingOlder: boolean;\n /** True once the first open has failed (see `ChannelClientState.initialLoadFailed`). */\n initialLoadFailed: boolean;\n /** The channel is current (see `ChannelClientState.isSynced`): act on its terms only while true. */\n isSynced: boolean;\n /** Retry the connection now — the first-open failure's Retry. */\n retry: () => void;\n /** Realtime extras (not present on the firestore result) — optional for the UI. */\n status: ChannelClientState[\"status\"];\n /** The last structured error code the DO sent (e.g. a close reason). Drives the\n * disconnected-banner detail (R13). */\n lastErrorCode: string | null;\n typing: string[];\n presence: string[];\n /** Returns false when the socket was closed and nothing was sent (C-B8) — the caller keeps the composer text. */\n send: (text: string) => boolean;\n /** Retry a failed/un-acked send by its ORIGINAL clientMessageId (read from the\n * failed row's `meta.clientMessageId`) — the transport re-queues the tracked\n * pending send with the SAME id so the DO's send-idempotency dedups any copy\n * that already landed. Returns false for an unknown id (already acked/\n * reconciled). ChatShell wires this to MessageItemDefault's failed-bubble\n * retry affordance by default. */\n retrySend: (clientMessageId: string) => boolean;\n /** Returns whether the ack frame was sent (false on a closed socket) so the caller advances its local cursor only on success (M2). */\n readAck: (readSeq: number, focused: boolean) => boolean;\n signalTyping: () => void;\n /** Watched-only presence (R14): the UI subscribes ONLY while a member-list / online\n * indicator is open, and unsubscribes when it closes, so an unwatched channel runs\n * zero presence alarms. `presence` stays empty until subscribed. */\n presenceSubscribe: () => void;\n presenceUnsubscribe: () => void;\n};\n\nexport function useRealtimeChatMessages(client: RealtimeChatClient): UseRealtimeChatMessagesResult {\n const [state, setState] = React.useState<ChannelClientState>(() => client.getState());\n\n // Subscribe only; the owning hook drives connect/close (single lifecycle owner, C-B7).\n // Re-subscribes on client identity change (auth-user switch).\n React.useEffect(() => {\n const unsub = client.subscribe(setState);\n setState(client.getState());\n return unsub;\n }, [client]);\n\n // Pre-warm the name cache for visible senders (parity with the firestore hook).\n const resolverCtx = useOptionalChatNameResolver();\n const senderIds = React.useMemo(() => {\n const set = new Set<string>();\n for (const m of state.messages) {\n set.add(m.senderId);\n for (const uid of m.referencedUids ?? []) set.add(uid);\n }\n return Array.from(set);\n }, [state.messages]);\n\n React.useEffect(() => {\n if (resolverCtx?.prewarm && senderIds.length > 0) resolverCtx.prewarm(senderIds);\n }, [resolverCtx, senderIds]);\n\n const fetchOlder = React.useCallback(async () => {\n client.channel.fetchOlder();\n }, [client]);\n\n const send = React.useCallback(\n (text: string): boolean =>\n client.channel.send({ clientMessageId: newCorrelationId(), text }),\n [client],\n );\n\n const retrySend = React.useCallback(\n (clientMessageId: string): boolean => client.channel.retrySend(clientMessageId),\n [client],\n );\n\n const readAck = React.useCallback(\n (readSeq: number, focused: boolean) => client.channel.readAck(readSeq, focused),\n [client],\n );\n\n const signalTyping = React.useCallback(() => client.channel.typing(), [client]);\n const retry = React.useCallback(() => client.retry(), [client]);\n const presenceSubscribe = React.useCallback(() => client.channel.presenceSubscribe(), [client]);\n const presenceUnsubscribe = React.useCallback(() => client.channel.presenceUnsubscribe(), [client]);\n\n return {\n // On the realtime transport DATA ACCESS is enforced by the DO grant, so the hook\n // is \"allowed\" client-side UNLESS the grant provider surfaced a TERMINAL access\n // denial (ChatAccessDeniedError → stable 'access-denied' code). That single case\n // maps to allowed:false so ChatShell renders its no-access surface instead of an\n // eternal loader; a transient close / 4403-revoke keeps allowed:true and rides the\n // reconnect/disconnected banner. Otherwise accessMode is presentation-only here.\n allowed: state.lastErrorCode !== \"access-denied\",\n // Derive initial loading from authoritative-data completion, NOT connection status:\n // a socket can be 'open' with no snapshot yet, and a post-load reconnect must not\n // fall back into the opening state. `hasLoadedInitialData` encodes the full table.\n isInitialLoading: !state.hasLoadedInitialData,\n initialLoadFailed: state.initialLoadFailed,\n // Current: open, loaded, and resynced since this socket opened (never sticky).\n isSynced: state.isSynced,\n retry,\n messages: state.messages,\n fetchOlder,\n hasOlder: state.hasOlder,\n isFetchingOlder: state.isFetchingOlder,\n status: state.status,\n lastErrorCode: state.lastErrorCode,\n typing: state.typing,\n presence: state.presence,\n send,\n retrySend,\n readAck,\n signalTyping,\n presenceSubscribe,\n presenceUnsubscribe,\n };\n}\n\n"]}
|
package/dist/ui/ChatShell.d.ts
CHANGED
|
@@ -48,6 +48,14 @@ export type ChatShellProps = {
|
|
|
48
48
|
* full-height page panel doesn't grow unbounded or waste space on a fixed 400px box.
|
|
49
49
|
* The consumer must give ChatShell a bounded-height parent (e.g. an `h-full` panel). */
|
|
50
50
|
fillHeight?: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Called with whether the conversation is READY — its access allowed, its initial data loaded
|
|
53
|
+
* with no failure, and (realtime) the channel current since its socket last opened — each time
|
|
54
|
+
* that changes, and with `false` when the shell unmounts. A consumer that lets someone act on
|
|
55
|
+
* what the conversation says (an agreement, an offer) offers and accepts that action only while
|
|
56
|
+
* it is true; reading the conversation needs no readiness.
|
|
57
|
+
*/
|
|
58
|
+
onReadinessChange?: (ready: boolean) => void;
|
|
51
59
|
/** Advanced override for the scrollable region's class (forwarded to MessageList).
|
|
52
60
|
* Usually unnecessary — prefer `fill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C,aAAa,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,KAAK,CAAC,SAAS,CAAC;IAC5C,gBAAgB,CAAC,EAAE,uBAAuB,CAAC;IAC3C,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAE9B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,SAAS,CAAC,EAAE,OAAO,CAAC;IAGpB,mBAAmB,CAAC,EAAE,MAAM,KAAK,CAAC,SAAS,CAAC;IAC5C,mBAAmB,CAAC,EAAE,MAAM,KAAK,CAAC,SAAS,CAAC;IAC5C,kDAAkD;IAClD,YAAY,CAAC,EAAE,MAAM,KAAK,CAAC,SAAS,CAAC;IAGrC,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IAG3C,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;6FAGyF;IACzF,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;;OAMG;IACH,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IAC7C;qDACiD;IACjD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;iEAC6D;IAC7D,eAAe,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC,wBAAwB,CAAC,CAAC;CACjE,CAAC;AAgCF;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,cAAc,qBAK9C"}
|
package/dist/ui/ChatShell.js
CHANGED
|
@@ -33,6 +33,7 @@ function FirestoreChatShell(props) {
|
|
|
33
33
|
return (_jsx(ChatShellView, { ...props, resolved: {
|
|
34
34
|
allowed: r.allowed,
|
|
35
35
|
isInitialLoading: r.isInitialLoading,
|
|
36
|
+
transportCurrent: true,
|
|
36
37
|
messages: r.messages,
|
|
37
38
|
fetchOlder: r.fetchOlder,
|
|
38
39
|
hasOlder: r.hasOlder,
|
|
@@ -64,6 +65,7 @@ function RealtimeChatShell(props) {
|
|
|
64
65
|
// The app's access fact AND the grant's: a terminal denial closes it either way.
|
|
65
66
|
allowed: config.allowed && r.allowed,
|
|
66
67
|
isInitialLoading: r.isInitialLoading,
|
|
68
|
+
transportCurrent: r.isSynced,
|
|
67
69
|
messages: r.messages,
|
|
68
70
|
fetchOlder: r.fetchOlder,
|
|
69
71
|
hasOlder: r.hasOlder,
|
|
@@ -79,10 +81,19 @@ function RealtimeChatShell(props) {
|
|
|
79
81
|
} }));
|
|
80
82
|
}
|
|
81
83
|
function ChatShellView(props) {
|
|
82
|
-
const { config, header, renderMessage, messageRenderers, handlers, composerPlaceholder, autoFocus = false, renderAboveMessages, renderBelowMessages, renderFooter, onSenderClick, composerDisabled, fillHeight = false, scrollClassName, scrollContainer, renderLoadError, resolved, } = props;
|
|
84
|
+
const { config, header, renderMessage, messageRenderers, handlers, composerPlaceholder, autoFocus = false, renderAboveMessages, renderBelowMessages, renderFooter, onSenderClick, composerDisabled, fillHeight = false, scrollClassName, scrollContainer, renderLoadError, onReadinessChange, resolved, } = props;
|
|
83
85
|
const { allowed, isInitialLoading, messages, fetchOlder, hasOlder, isFetchingOlder, loadFailure, olderFailure, send, retrySend, readAck, status, typing, signalTyping } = resolved;
|
|
84
86
|
// Nothing loaded and the read failed: the failure takes the list's place.
|
|
85
87
|
const initialFailure = loadFailure?.scope === "initial" ? loadFailure : null;
|
|
88
|
+
const ready = allowed && !isInitialLoading && loadFailure === null && resolved.transportCurrent;
|
|
89
|
+
const readinessListener = React.useRef(onReadinessChange);
|
|
90
|
+
React.useEffect(() => {
|
|
91
|
+
readinessListener.current = onReadinessChange;
|
|
92
|
+
});
|
|
93
|
+
React.useEffect(() => {
|
|
94
|
+
readinessListener.current?.(ready);
|
|
95
|
+
}, [ready]);
|
|
96
|
+
React.useEffect(() => () => readinessListener.current?.(false), []);
|
|
86
97
|
const [showScrollToBottom, setShowScrollToBottom] = React.useState(false);
|
|
87
98
|
const [atBottom, setAtBottom] = React.useState(true);
|
|
88
99
|
const [focused, setFocused] = React.useState(true);
|
|
@@ -147,9 +158,8 @@ function ChatShellView(props) {
|
|
|
147
158
|
// parchment/skeleton box (which read as an empty chat) and NOT the reconnect banner
|
|
148
159
|
// (which must not compete with the initial-opening message). Only the MessageList
|
|
149
160
|
// region is replaced: the consumer's header + actions + the three render-slots +
|
|
150
|
-
// footer
|
|
151
|
-
//
|
|
152
|
-
// must work whether or not realtime chat has connected yet (F4.1).
|
|
161
|
+
// footer still render, and `onReadinessChange` tells a consumer whose slots carry
|
|
162
|
+
// actions that the conversation is not ready to act on.
|
|
153
163
|
return (_jsxs(Card, { className: cardClassName, children: [(header || handlers) && (_jsxs(CardHeader, { className: "flex flex-row items-start justify-between gap-4 space-y-0", children: [_jsx("div", { children: header }), _jsx("div", { className: "flex flex-col items-end gap-2", children: _jsx(ThreadActions, { threadId: config.threadId, isAdmin: config.isAdmin, handlers: handlers }) })] })), (() => {
|
|
154
164
|
// The wrapper (and its border) renders only when the slot actually
|
|
155
165
|
// produced content — a slot returning null (e.g. a collapsed
|
package/dist/ui/ChatShell.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatShell.js","sourceRoot":"","sources":["../../src/ui/ChatShell.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAM/B,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAC9G,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AAEjF,OAAO,EAAE,WAAW,EAAiC,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,YA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mB,GAChC,GACmB,IACZ,CACd,IACI,CACR,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,EAAE,MAAM,EAAuB;IAC3D,IAAI,MAAM,KAAK,cAAc,IAAI,MAAM,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IAClE,OAAO,CACL,cACE,SAAS,EAAC,yEAAyE,EACnF,IAAI,EAAC,QAAQ,eACH,QAAQ,YAEjB,MAAM,KAAK,cAAc;YACxB,CAAC,CAAC,wCAAwC;YAC1C,CAAC,CAAC,6CAA6C,GAC7C,CACP,CAAC;AACJ,CAAC;AAED;0EAC0E;AAC1E,SAAS,eAAe,CAAC,EAAE,MAAM,EAAyB;IACxD,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAChD,OAAO,CACL,cAAK,SAAS,EAAC,sCAAsC,eAAW,QAAQ,YACrE,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,4BAA4B,GACtE,CACP,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type { ChatMessageV1, ModerationHandlers } from \"@ttt-productions/chat-core\";\nimport type {\n ChatCoreConfig,\n MessageRendererRegistry,\n} from \"../types.js\";\nimport { Card, CardHeader, CardContent, CardFooter, Skeleton, Spinner } from \"@ttt-productions/ui-core/react\";\nimport { KeyboardAvoidingView } from \"@ttt-productions/mobile-core/react\";\nimport { useChatMessages } from \"../hooks/useChatMessages.js\";\nimport { useRealtimeChatMessages } from \"../realtime/useRealtimeChatMessages.js\";\nimport type { RealtimeChatClient } from \"../realtime/transport.js\";\nimport { MessageList, type ChatScrollContainerProps } from \"./MessageList.js\";\nimport { Composer } from \"./Composer.js\";\nimport { ThreadActions } from \"./menus.js\";\n\n/**\n * A read the chat could not complete, handed to the app's `renderLoadError`:\n * - `initial` — nothing loaded: the first open failed (the realtime client's attempts\n * failed for its budget, or the Firestore listener failed before any message). It\n * takes the place of the message list.\n * - `live` — the Firestore listener failed after messages loaded. The messages stay,\n * with this band above them.\n * - `older` — an older page failed to load. It renders at the top of the list, which\n * stops asking for older pages until `retry`.\n * `error` is the read's own error (null on the realtime transport); `retry` re-runs what\n * failed — the realtime transport also keeps retrying in the background. `retrying` is true\n * while a retry of this failure is running and the failure is still shown (an older page being\n * read again), so the app's Retry shows its pending state. A retried initial or live failure\n * gives way to the opening state instead.\n */\nexport type ChatLoadFailure = {\n scope: \"initial\" | \"live\" | \"older\";\n error: Error | null;\n retry: () => void;\n retrying: boolean;\n};\n\nexport type ChatShellProps = {\n config: ChatCoreConfig;\n\n /**\n * Renders every failed read (see {@link ChatLoadFailure}) — the app's own error state and\n * copy. Required: a chat that cannot load must say so, and the words are the app's.\n */\n renderLoadError: (failure: ChatLoadFailure) => React.ReactNode;\n\n // Header\n header?: React.ReactNode;\n\n // Send handler — text-only. On the realtime transport this is OPTIONAL: the\n // shell sends through the DO socket. If provided, it is still called (so a\n // consumer can mirror to analytics), but the socket send is authoritative.\n onSend?: (text: string) => Promise<void>;\n\n // Message rendering\n renderMessage?: (m: any) => React.ReactNode;\n messageRenderers?: MessageRendererRegistry;\n handlers?: ModerationHandlers;\n\n composerPlaceholder?: string;\n autoFocus?: boolean;\n\n // Three render slots\n renderAboveMessages?: () => React.ReactNode;\n renderBelowMessages?: () => React.ReactNode;\n /** If provided, replaces the Composer entirely */\n renderFooter?: () => React.ReactNode;\n\n // Sender interaction\n onSenderClick?: (senderId: string) => void;\n\n // Disable\n composerDisabled?: boolean;\n\n /** Fill the parent's height instead of the default fixed-height card. Lays the Card out\n * as `flex flex-col h-full` with the message list flexing to fill (scrolls inside), so a\n * full-height page panel doesn't grow unbounded or waste space on a fixed 400px box.\n * The consumer must give ChatShell a bounded-height parent (e.g. an `h-full` panel). */\n fillHeight?: boolean;\n /** Advanced override for the scrollable region's class (forwarded to MessageList).\n * Usually unnecessary — prefer `fillHeight`. */\n scrollClassName?: string;\n /** Renders the scrollable message region (forwarded to MessageList) in place of the default div,\n * so the consumer can give it its own surface component. */\n scrollContainer?: React.ComponentType<ChatScrollContainerProps>;\n};\n\n/** The resolved data a transport hook hands the presentational view. */\ntype ResolvedChat = {\n allowed: boolean;\n isInitialLoading: boolean;\n messages: ChatMessageV1[];\n fetchOlder: () => Promise<void>;\n hasOlder: boolean;\n isFetchingOlder: boolean;\n /** The failed read that replaces or annotates the list (initial / live), or null. */\n loadFailure: ChatLoadFailure | null;\n /** The failed older page, or null. */\n olderFailure: ChatLoadFailure | null;\n /** The send handler the Composer calls (socket send on realtime, prop on firestore). */\n send: (text: string) => Promise<void>;\n /** Retry a failed realtime send by its original clientMessageId (realtime only;\n * absent on firestore). Wired to MessageItemDefault's failed-bubble retry. */\n retrySend?: (clientMessageId: string) => void;\n /** Advance the authoritative read cursor (realtime only; absent on the firestore path).\n * Returns whether the ack was actually sent so the caller advances its local cursor only on success (M2). */\n readAck?: (latestSeq: number, focused: boolean) => boolean;\n /** Realtime connection status — drives the disconnected banner (R13). Absent on firestore. */\n status?: string;\n /** uids currently typing (realtime only) — drives the typing indicator (R14). */\n typing?: string[];\n /** Signal the local user is typing (coalesced by the transport). Wired to the Composer (R14). */\n signalTyping?: () => void;\n};\n\n/**\n * ChatShell dispatches on `config.transport`. Hooks must be unconditional, so the\n * two transports live in separate inner components (each calls exactly ONE data\n * hook) and both render the shared presentational `ChatShellView`. The default\n * (undefined / 'firestore') transport is byte-for-byte the previous behavior.\n */\nexport function ChatShell(props: ChatShellProps) {\n if (props.config.transport === \"realtime\") {\n return <RealtimeChatShell {...props} />;\n }\n return <FirestoreChatShell {...props} />;\n}\n\nfunction FirestoreChatShell(props: ChatShellProps) {\n const { config, onSend } = props;\n const r = useChatMessages(config);\n const send = React.useCallback(\n async (text: string) => {\n if (onSend) await onSend(text);\n },\n [onSend],\n );\n const { error, olderError, retry, messages, isFetchingOlder } = r;\n const loadFailure = React.useMemo<ChatLoadFailure | null>(\n () => (error ? { scope: messages.length > 0 ? \"live\" : \"initial\", error, retry, retrying: false } : null),\n [error, messages.length, retry],\n );\n const olderFailure = React.useMemo<ChatLoadFailure | null>(\n () => (olderError ? { scope: \"older\", error: olderError, retry, retrying: isFetchingOlder } : null),\n [olderError, retry, isFetchingOlder],\n );\n return (\n <ChatShellView\n {...props}\n resolved={{\n allowed: r.allowed,\n isInitialLoading: r.isInitialLoading,\n messages: r.messages,\n fetchOlder: r.fetchOlder,\n hasOlder: r.hasOlder,\n isFetchingOlder: r.isFetchingOlder,\n loadFailure,\n olderFailure,\n send,\n }}\n />\n );\n}\n\nfunction RealtimeChatShell(props: ChatShellProps) {\n const { config, onSend } = props;\n const client = config.realtime?.client as RealtimeChatClient | undefined;\n if (!client) {\n throw new Error(\n \"[ChatShell] transport 'realtime' requires config.realtime.client (createRealtimeChatClient(...))\",\n );\n }\n const r = useRealtimeChatMessages(client);\n const { initialLoadFailed, retry } = r;\n const loadFailure = React.useMemo<ChatLoadFailure | null>(\n () => (initialLoadFailed ? { scope: \"initial\", error: null, retry, retrying: false } : null),\n [initialLoadFailed, retry],\n );\n const send = React.useCallback(\n async (text: string) => {\n const ok = r.send(text);\n // C-B8: surface a closed-socket failure so the Composer keeps the user's text\n // instead of clearing it on a no-op send.\n if (!ok) throw new Error(\"chat-send-failed\");\n if (onSend) await onSend(text); // optional mirror\n },\n [r, onSend],\n );\n return (\n <ChatShellView\n {...props}\n resolved={{\n // The app's access fact AND the grant's: a terminal denial closes it either way.\n allowed: config.allowed && r.allowed,\n isInitialLoading: r.isInitialLoading,\n messages: r.messages,\n fetchOlder: r.fetchOlder,\n hasOlder: r.hasOlder,\n isFetchingOlder: r.isFetchingOlder,\n loadFailure,\n olderFailure: null,\n send,\n retrySend: r.retrySend,\n readAck: r.readAck,\n status: r.status,\n typing: r.typing,\n signalTyping: r.signalTyping,\n }}\n />\n );\n}\n\nfunction ChatShellView(props: ChatShellProps & { resolved: ResolvedChat }) {\n const {\n config,\n header,\n renderMessage,\n messageRenderers,\n handlers,\n composerPlaceholder,\n autoFocus = false,\n renderAboveMessages,\n renderBelowMessages,\n renderFooter,\n onSenderClick,\n composerDisabled,\n fillHeight = false,\n scrollClassName,\n scrollContainer,\n renderLoadError,\n resolved,\n } = props;\n\n const { allowed, isInitialLoading, messages, fetchOlder, hasOlder, isFetchingOlder, loadFailure, olderFailure, send, retrySend, readAck, status, typing, signalTyping } = resolved;\n // Nothing loaded and the read failed: the failure takes the list's place.\n const initialFailure = loadFailure?.scope === \"initial\" ? loadFailure : null;\n\n const [showScrollToBottom, setShowScrollToBottom] = React.useState(false);\n const [atBottom, setAtBottom] = React.useState(true);\n const [focused, setFocused] = React.useState(true);\n const lastAckedRef = React.useRef(0);\n const leaseHeldRef = React.useRef(false);\n\n // The latest authoritative seq currently rendered (optimistic rows have no seq).\n const latestSeq = React.useMemo(() => {\n let max = 0;\n for (const m of messages) {\n const seq = typeof m.meta?.seq === \"number\" ? (m.meta?.seq as number) : 0;\n if (seq > max) max = seq;\n }\n return max;\n }, [messages]);\n\n // Track tab focus/visibility so the read-ack \"focused\" lease releases on blur/hide.\n React.useEffect(() => {\n const compute = () =>\n typeof document === \"undefined\" ||\n (document.visibilityState !== \"hidden\" && (typeof document.hasFocus !== \"function\" || document.hasFocus()));\n setFocused(compute());\n const onChange = () => setFocused(compute());\n window.addEventListener(\"focus\", onChange);\n window.addEventListener(\"blur\", onChange);\n document.addEventListener(\"visibilitychange\", onChange);\n return () => {\n window.removeEventListener(\"focus\", onChange);\n window.removeEventListener(\"blur\", onChange);\n document.removeEventListener(\"visibilitychange\", onChange);\n };\n }, []);\n\n // C-B6: advance the authoritative read cursor when the reader is actually at the\n // latest message (channel mounted + tab focused + scrolled to bottom); release the\n // focus lease exactly once when they stop. No-op on the firestore path (no readAck).\n React.useEffect(() => {\n if (!readAck || latestSeq <= 0) return;\n if (focused && atBottom) {\n leaseHeldRef.current = true;\n if (latestSeq > lastAckedRef.current) {\n // Advance the local marker ONLY if the frame was actually sent — a drop during a\n // disconnect window must stay un-acked so it retries (the client also re-sends the\n // cursor on reconnect). (M2)\n if (readAck(latestSeq, true)) lastAckedRef.current = latestSeq;\n }\n } else if (leaseHeldRef.current) {\n leaseHeldRef.current = false;\n readAck(latestSeq, false);\n }\n }, [readAck, latestSeq, atBottom, focused]);\n\n // In fill mode the Card flexes to its parent's height and the message list fills the\n // space between header and composer; otherwise it's the default natural-height card.\n const cardClassName = fillHeight ? \"w-full flex flex-col h-full min-h-0\" : \"w-full\";\n const contentClassName = fillHeight ? \"p-0 flex-1 min-h-0 flex flex-col\" : \"p-0\";\n\n if (!allowed) {\n return <div className=\"p-4 text-sm opacity-70\">You don't have access to this thread.</div>;\n }\n\n if (isInitialLoading || initialFailure) {\n // Before the first authoritative snapshot/history result, show an HONEST working\n // state — a visible \"Opening chat…\" spinner in a polite live region — NOT a blank\n // parchment/skeleton box (which read as an empty chat) and NOT the reconnect banner\n // (which must not compete with the initial-opening message). Only the MessageList\n // region is replaced: the consumer's header + actions + the three render-slots +\n // footer all still render, because a consumer that hangs critical controls off those\n // slots (e.g. the guild-invite binding-agreement Agree/Decline/stake-share controls)\n // must work whether or not realtime chat has connected yet (F4.1).\n return (\n <Card className={cardClassName}>\n {(header || handlers) && (\n <CardHeader className=\"flex flex-row items-start justify-between gap-4 space-y-0\">\n <div>{header}</div>\n <div className=\"flex flex-col items-end gap-2\">\n <ThreadActions threadId={config.threadId} isAdmin={config.isAdmin} handlers={handlers} />\n </div>\n </CardHeader>\n )}\n {(() => {\n // The wrapper (and its border) renders only when the slot actually\n // produced content — a slot returning null (e.g. a collapsed\n // conversation-files section) must not paint an empty bordered strip.\n const aboveMessages = renderAboveMessages?.() ?? null;\n return aboveMessages != null && aboveMessages !== false ? (\n <div className=\"border-b\">{aboveMessages}</div>\n ) : null;\n })()}\n <CardContent className={contentClassName}>\n {initialFailure ? (\n renderLoadError(initialFailure)\n ) : (\n <div\n className=\"flex flex-col items-center justify-center gap-2 py-12 text-sm text-muted-foreground\"\n role=\"status\"\n aria-live=\"polite\"\n >\n <Spinner size=\"sm\" />\n <span>Opening chat…</span>\n </div>\n )}\n </CardContent>\n {renderBelowMessages && (\n <div className=\"border-t\">{renderBelowMessages()}</div>\n )}\n {renderFooter ? (\n <CardFooter className=\"border-t\">{renderFooter()}</CardFooter>\n ) : (\n <CardFooter className=\"border-t\">\n <Skeleton className=\"h-10 w-full\" />\n </CardFooter>\n )}\n </Card>\n );\n }\n\n return (\n <Card className={cardClassName}>\n {(header || handlers) && (\n <CardHeader className=\"flex flex-row items-start justify-between gap-4 space-y-0\">\n <div>{header}</div>\n <div className=\"flex flex-col items-end gap-2\">\n <ThreadActions threadId={config.threadId} isAdmin={config.isAdmin} handlers={handlers} />\n </div>\n </CardHeader>\n )}\n\n {/* R13: a disconnected/reconnecting banner so a configured-but-unreachable Worker\n never presents a healthy-looking empty thread. Only the realtime path sets `status`. */}\n <ChatConnectionBanner status={status} />\n\n {renderAboveMessages && (\n <div className=\"border-b\">{renderAboveMessages()}</div>\n )}\n\n {/* The listener failed after messages loaded: they stay, with the failure above them. */}\n {loadFailure?.scope === \"live\" && <div className=\"border-b\">{renderLoadError(loadFailure)}</div>}\n\n <CardContent className={contentClassName}>\n <MessageList\n messages={messages}\n currentUserId={config.currentUserId}\n isAdmin={config.isAdmin}\n isFetchingOlder={isFetchingOlder}\n hasOlder={hasOlder}\n onLoadOlder={() => fetchOlder()}\n renderMessage={renderMessage}\n messageRenderers={messageRenderers}\n showScrollToBottom={showScrollToBottom}\n onScrollToBottom={() => setShowScrollToBottom(false)}\n onAtBottomChange={setAtBottom}\n fillHeight={fillHeight}\n scrollClassName={scrollClassName}\n scrollContainer={scrollContainer}\n handlers={handlers}\n onSenderClick={onSenderClick}\n onRetrySend={retrySend}\n olderLoadErrorRow={olderFailure ? renderLoadError(olderFailure) : null}\n />\n </CardContent>\n\n {renderBelowMessages && (\n <div className=\"border-t\">{renderBelowMessages()}</div>\n )}\n\n {renderFooter ? (\n <CardFooter className=\"border-t\">\n {renderFooter()}\n </CardFooter>\n ) : (\n <CardFooter className=\"border-t flex-col items-stretch gap-1\">\n {/* R14: typing dots above the composer (realtime only — `typing` is undefined on firestore). */}\n <TypingIndicator typing={typing} />\n <KeyboardAvoidingView padding offset={8} className=\"w-full\">\n <Composer\n onSend={send}\n onTyping={signalTyping}\n disabled={composerDisabled}\n autoFocus={autoFocus}\n placeholder={composerPlaceholder}\n />\n </KeyboardAvoidingView>\n </CardFooter>\n )}\n </Card>\n );\n}\n\n/**\n * R13 — connection-state banner. The realtime path sets `status`; once the first\n * snapshot has loaded (ChatShellView is past `isInitialLoading`), a dropped/unreachable\n * socket surfaces here instead of a silently-empty thread. Renders nothing on the\n * firestore path (`status` undefined) or while live (`open`).\n */\nfunction ChatConnectionBanner({ status }: { status?: string }) {\n if (status !== \"reconnecting\" && status !== \"closed\") return null;\n return (\n <div\n className=\"px-3 py-1.5 text-xs text-center bg-muted text-muted-foreground border-b\"\n role=\"status\"\n aria-live=\"polite\"\n >\n {status === \"reconnecting\"\n ? \"Reconnecting… messages may be delayed.\"\n : \"Disconnected — messages may be out of date.\"}\n </div>\n );\n}\n\n/** R14 — typing indicator. `typing` is the set of OTHER users typing (the transport\n * excludes the local user). Generic copy (no name resolution) for v1. */\nfunction TypingIndicator({ typing }: { typing?: string[] }) {\n if (!typing || typing.length === 0) return null;\n return (\n <div className=\"text-xs italic text-muted-foreground\" aria-live=\"polite\">\n {typing.length === 1 ? \"Someone is typing…\" : \"Several people are typing…\"}\n </div>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ChatShell.js","sourceRoot":"","sources":["../../src/ui/ChatShell.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAM/B,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,gCAAgC,C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AAM,KAAK,cAAc;YACxB,CAAC,CAAC,wCAAwC;YAC1C,CAAC,CAAC,6CAA6C,GAC7C,CACP,CAAC;AACJ,CAAC;AAED;0EAC0E;AAC1E,SAAS,eAAe,CAAC,EAAE,MAAM,EAAyB;IACxD,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAChD,OAAO,CACL,cAAK,SAAS,EAAC,sCAAsC,eAAW,QAAQ,YACrE,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,4BAA4B,GACtE,CACP,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type { ChatMessageV1, ModerationHandlers } from \"@ttt-productions/chat-core\";\nimport type {\n ChatCoreConfig,\n MessageRendererRegistry,\n} from \"../types.js\";\nimport { Card, CardHeader, CardContent, CardFooter, Skeleton, Spinner } from \"@ttt-productions/ui-core/react\";\nimport { KeyboardAvoidingView } from \"@ttt-productions/mobile-core/react\";\nimport { useChatMessages } from \"../hooks/useChatMessages.js\";\nimport { useRealtimeChatMessages } from \"../realtime/useRealtimeChatMessages.js\";\nimport type { RealtimeChatClient } from \"../realtime/transport.js\";\nimport { MessageList, type ChatScrollContainerProps } from \"./MessageList.js\";\nimport { Composer } from \"./Composer.js\";\nimport { ThreadActions } from \"./menus.js\";\n\n/**\n * A read the chat could not complete, handed to the app's `renderLoadError`:\n * - `initial` — nothing loaded: the first open failed (the realtime client's attempts\n * failed for its budget, or the Firestore listener failed before any message). It\n * takes the place of the message list.\n * - `live` — the Firestore listener failed after messages loaded. The messages stay,\n * with this band above them.\n * - `older` — an older page failed to load. It renders at the top of the list, which\n * stops asking for older pages until `retry`.\n * `error` is the read's own error (null on the realtime transport); `retry` re-runs what\n * failed — the realtime transport also keeps retrying in the background. `retrying` is true\n * while a retry of this failure is running and the failure is still shown (an older page being\n * read again), so the app's Retry shows its pending state. A retried initial or live failure\n * gives way to the opening state instead.\n */\nexport type ChatLoadFailure = {\n scope: \"initial\" | \"live\" | \"older\";\n error: Error | null;\n retry: () => void;\n retrying: boolean;\n};\n\nexport type ChatShellProps = {\n config: ChatCoreConfig;\n\n /**\n * Renders every failed read (see {@link ChatLoadFailure}) — the app's own error state and\n * copy. Required: a chat that cannot load must say so, and the words are the app's.\n */\n renderLoadError: (failure: ChatLoadFailure) => React.ReactNode;\n\n // Header\n header?: React.ReactNode;\n\n // Send handler — text-only. On the realtime transport this is OPTIONAL: the\n // shell sends through the DO socket. If provided, it is still called (so a\n // consumer can mirror to analytics), but the socket send is authoritative.\n onSend?: (text: string) => Promise<void>;\n\n // Message rendering\n renderMessage?: (m: any) => React.ReactNode;\n messageRenderers?: MessageRendererRegistry;\n handlers?: ModerationHandlers;\n\n composerPlaceholder?: string;\n autoFocus?: boolean;\n\n // Three render slots\n renderAboveMessages?: () => React.ReactNode;\n renderBelowMessages?: () => React.ReactNode;\n /** If provided, replaces the Composer entirely */\n renderFooter?: () => React.ReactNode;\n\n // Sender interaction\n onSenderClick?: (senderId: string) => void;\n\n // Disable\n composerDisabled?: boolean;\n\n /** Fill the parent's height instead of the default fixed-height card. Lays the Card out\n * as `flex flex-col h-full` with the message list flexing to fill (scrolls inside), so a\n * full-height page panel doesn't grow unbounded or waste space on a fixed 400px box.\n * The consumer must give ChatShell a bounded-height parent (e.g. an `h-full` panel). */\n fillHeight?: boolean;\n /**\n * Called with whether the conversation is READY — its access allowed, its initial data loaded\n * with no failure, and (realtime) the channel current since its socket last opened — each time\n * that changes, and with `false` when the shell unmounts. A consumer that lets someone act on\n * what the conversation says (an agreement, an offer) offers and accepts that action only while\n * it is true; reading the conversation needs no readiness.\n */\n onReadinessChange?: (ready: boolean) => void;\n /** Advanced override for the scrollable region's class (forwarded to MessageList).\n * Usually unnecessary — prefer `fillHeight`. */\n scrollClassName?: string;\n /** Renders the scrollable message region (forwarded to MessageList) in place of the default div,\n * so the consumer can give it its own surface component. */\n scrollContainer?: React.ComponentType<ChatScrollContainerProps>;\n};\n\n/** The resolved data a transport hook hands the presentational view. */\ntype ResolvedChat = {\n allowed: boolean;\n isInitialLoading: boolean;\n /** The transport's own readiness beyond loaded-and-allowed (realtime: the channel is current). */\n transportCurrent: boolean;\n messages: ChatMessageV1[];\n fetchOlder: () => Promise<void>;\n hasOlder: boolean;\n isFetchingOlder: boolean;\n /** The failed read that replaces or annotates the list (initial / live), or null. */\n loadFailure: ChatLoadFailure | null;\n /** The failed older page, or null. */\n olderFailure: ChatLoadFailure | null;\n /** The send handler the Composer calls (socket send on realtime, prop on firestore). */\n send: (text: string) => Promise<void>;\n /** Retry a failed realtime send by its original clientMessageId (realtime only;\n * absent on firestore). Wired to MessageItemDefault's failed-bubble retry. */\n retrySend?: (clientMessageId: string) => void;\n /** Advance the authoritative read cursor (realtime only; absent on the firestore path).\n * Returns whether the ack was actually sent so the caller advances its local cursor only on success (M2). */\n readAck?: (latestSeq: number, focused: boolean) => boolean;\n /** Realtime connection status — drives the disconnected banner (R13). Absent on firestore. */\n status?: string;\n /** uids currently typing (realtime only) — drives the typing indicator (R14). */\n typing?: string[];\n /** Signal the local user is typing (coalesced by the transport). Wired to the Composer (R14). */\n signalTyping?: () => void;\n};\n\n/**\n * ChatShell dispatches on `config.transport`. Hooks must be unconditional, so the\n * two transports live in separate inner components (each calls exactly ONE data\n * hook) and both render the shared presentational `ChatShellView`. The default\n * (undefined / 'firestore') transport is byte-for-byte the previous behavior.\n */\nexport function ChatShell(props: ChatShellProps) {\n if (props.config.transport === \"realtime\") {\n return <RealtimeChatShell {...props} />;\n }\n return <FirestoreChatShell {...props} />;\n}\n\nfunction FirestoreChatShell(props: ChatShellProps) {\n const { config, onSend } = props;\n const r = useChatMessages(config);\n const send = React.useCallback(\n async (text: string) => {\n if (onSend) await onSend(text);\n },\n [onSend],\n );\n const { error, olderError, retry, messages, isFetchingOlder } = r;\n const loadFailure = React.useMemo<ChatLoadFailure | null>(\n () => (error ? { scope: messages.length > 0 ? \"live\" : \"initial\", error, retry, retrying: false } : null),\n [error, messages.length, retry],\n );\n const olderFailure = React.useMemo<ChatLoadFailure | null>(\n () => (olderError ? { scope: \"older\", error: olderError, retry, retrying: isFetchingOlder } : null),\n [olderError, retry, isFetchingOlder],\n );\n return (\n <ChatShellView\n {...props}\n resolved={{\n allowed: r.allowed,\n isInitialLoading: r.isInitialLoading,\n transportCurrent: true,\n messages: r.messages,\n fetchOlder: r.fetchOlder,\n hasOlder: r.hasOlder,\n isFetchingOlder: r.isFetchingOlder,\n loadFailure,\n olderFailure,\n send,\n }}\n />\n );\n}\n\nfunction RealtimeChatShell(props: ChatShellProps) {\n const { config, onSend } = props;\n const client = config.realtime?.client as RealtimeChatClient | undefined;\n if (!client) {\n throw new Error(\n \"[ChatShell] transport 'realtime' requires config.realtime.client (createRealtimeChatClient(...))\",\n );\n }\n const r = useRealtimeChatMessages(client);\n const { initialLoadFailed, retry } = r;\n const loadFailure = React.useMemo<ChatLoadFailure | null>(\n () => (initialLoadFailed ? { scope: \"initial\", error: null, retry, retrying: false } : null),\n [initialLoadFailed, retry],\n );\n const send = React.useCallback(\n async (text: string) => {\n const ok = r.send(text);\n // C-B8: surface a closed-socket failure so the Composer keeps the user's text\n // instead of clearing it on a no-op send.\n if (!ok) throw new Error(\"chat-send-failed\");\n if (onSend) await onSend(text); // optional mirror\n },\n [r, onSend],\n );\n return (\n <ChatShellView\n {...props}\n resolved={{\n // The app's access fact AND the grant's: a terminal denial closes it either way.\n allowed: config.allowed && r.allowed,\n isInitialLoading: r.isInitialLoading,\n transportCurrent: r.isSynced,\n messages: r.messages,\n fetchOlder: r.fetchOlder,\n hasOlder: r.hasOlder,\n isFetchingOlder: r.isFetchingOlder,\n loadFailure,\n olderFailure: null,\n send,\n retrySend: r.retrySend,\n readAck: r.readAck,\n status: r.status,\n typing: r.typing,\n signalTyping: r.signalTyping,\n }}\n />\n );\n}\n\nfunction ChatShellView(props: ChatShellProps & { resolved: ResolvedChat }) {\n const {\n config,\n header,\n renderMessage,\n messageRenderers,\n handlers,\n composerPlaceholder,\n autoFocus = false,\n renderAboveMessages,\n renderBelowMessages,\n renderFooter,\n onSenderClick,\n composerDisabled,\n fillHeight = false,\n scrollClassName,\n scrollContainer,\n renderLoadError,\n onReadinessChange,\n resolved,\n } = props;\n\n const { allowed, isInitialLoading, messages, fetchOlder, hasOlder, isFetchingOlder, loadFailure, olderFailure, send, retrySend, readAck, status, typing, signalTyping } = resolved;\n // Nothing loaded and the read failed: the failure takes the list's place.\n const initialFailure = loadFailure?.scope === \"initial\" ? loadFailure : null;\n\n const ready = allowed && !isInitialLoading && loadFailure === null && resolved.transportCurrent;\n const readinessListener = React.useRef(onReadinessChange);\n React.useEffect(() => {\n readinessListener.current = onReadinessChange;\n });\n React.useEffect(() => {\n readinessListener.current?.(ready);\n }, [ready]);\n React.useEffect(() => () => readinessListener.current?.(false), []);\n\n const [showScrollToBottom, setShowScrollToBottom] = React.useState(false);\n const [atBottom, setAtBottom] = React.useState(true);\n const [focused, setFocused] = React.useState(true);\n const lastAckedRef = React.useRef(0);\n const leaseHeldRef = React.useRef(false);\n\n // The latest authoritative seq currently rendered (optimistic rows have no seq).\n const latestSeq = React.useMemo(() => {\n let max = 0;\n for (const m of messages) {\n const seq = typeof m.meta?.seq === \"number\" ? (m.meta?.seq as number) : 0;\n if (seq > max) max = seq;\n }\n return max;\n }, [messages]);\n\n // Track tab focus/visibility so the read-ack \"focused\" lease releases on blur/hide.\n React.useEffect(() => {\n const compute = () =>\n typeof document === \"undefined\" ||\n (document.visibilityState !== \"hidden\" && (typeof document.hasFocus !== \"function\" || document.hasFocus()));\n setFocused(compute());\n const onChange = () => setFocused(compute());\n window.addEventListener(\"focus\", onChange);\n window.addEventListener(\"blur\", onChange);\n document.addEventListener(\"visibilitychange\", onChange);\n return () => {\n window.removeEventListener(\"focus\", onChange);\n window.removeEventListener(\"blur\", onChange);\n document.removeEventListener(\"visibilitychange\", onChange);\n };\n }, []);\n\n // C-B6: advance the authoritative read cursor when the reader is actually at the\n // latest message (channel mounted + tab focused + scrolled to bottom); release the\n // focus lease exactly once when they stop. No-op on the firestore path (no readAck).\n React.useEffect(() => {\n if (!readAck || latestSeq <= 0) return;\n if (focused && atBottom) {\n leaseHeldRef.current = true;\n if (latestSeq > lastAckedRef.current) {\n // Advance the local marker ONLY if the frame was actually sent — a drop during a\n // disconnect window must stay un-acked so it retries (the client also re-sends the\n // cursor on reconnect). (M2)\n if (readAck(latestSeq, true)) lastAckedRef.current = latestSeq;\n }\n } else if (leaseHeldRef.current) {\n leaseHeldRef.current = false;\n readAck(latestSeq, false);\n }\n }, [readAck, latestSeq, atBottom, focused]);\n\n // In fill mode the Card flexes to its parent's height and the message list fills the\n // space between header and composer; otherwise it's the default natural-height card.\n const cardClassName = fillHeight ? \"w-full flex flex-col h-full min-h-0\" : \"w-full\";\n const contentClassName = fillHeight ? \"p-0 flex-1 min-h-0 flex flex-col\" : \"p-0\";\n\n if (!allowed) {\n return <div className=\"p-4 text-sm opacity-70\">You don't have access to this thread.</div>;\n }\n\n if (isInitialLoading || initialFailure) {\n // Before the first authoritative snapshot/history result, show an HONEST working\n // state — a visible \"Opening chat…\" spinner in a polite live region — NOT a blank\n // parchment/skeleton box (which read as an empty chat) and NOT the reconnect banner\n // (which must not compete with the initial-opening message). Only the MessageList\n // region is replaced: the consumer's header + actions + the three render-slots +\n // footer still render, and `onReadinessChange` tells a consumer whose slots carry\n // actions that the conversation is not ready to act on.\n return (\n <Card className={cardClassName}>\n {(header || handlers) && (\n <CardHeader className=\"flex flex-row items-start justify-between gap-4 space-y-0\">\n <div>{header}</div>\n <div className=\"flex flex-col items-end gap-2\">\n <ThreadActions threadId={config.threadId} isAdmin={config.isAdmin} handlers={handlers} />\n </div>\n </CardHeader>\n )}\n {(() => {\n // The wrapper (and its border) renders only when the slot actually\n // produced content — a slot returning null (e.g. a collapsed\n // conversation-files section) must not paint an empty bordered strip.\n const aboveMessages = renderAboveMessages?.() ?? null;\n return aboveMessages != null && aboveMessages !== false ? (\n <div className=\"border-b\">{aboveMessages}</div>\n ) : null;\n })()}\n <CardContent className={contentClassName}>\n {initialFailure ? (\n renderLoadError(initialFailure)\n ) : (\n <div\n className=\"flex flex-col items-center justify-center gap-2 py-12 text-sm text-muted-foreground\"\n role=\"status\"\n aria-live=\"polite\"\n >\n <Spinner size=\"sm\" />\n <span>Opening chat…</span>\n </div>\n )}\n </CardContent>\n {renderBelowMessages && (\n <div className=\"border-t\">{renderBelowMessages()}</div>\n )}\n {renderFooter ? (\n <CardFooter className=\"border-t\">{renderFooter()}</CardFooter>\n ) : (\n <CardFooter className=\"border-t\">\n <Skeleton className=\"h-10 w-full\" />\n </CardFooter>\n )}\n </Card>\n );\n }\n\n return (\n <Card className={cardClassName}>\n {(header || handlers) && (\n <CardHeader className=\"flex flex-row items-start justify-between gap-4 space-y-0\">\n <div>{header}</div>\n <div className=\"flex flex-col items-end gap-2\">\n <ThreadActions threadId={config.threadId} isAdmin={config.isAdmin} handlers={handlers} />\n </div>\n </CardHeader>\n )}\n\n {/* R13: a disconnected/reconnecting banner so a configured-but-unreachable Worker\n never presents a healthy-looking empty thread. Only the realtime path sets `status`. */}\n <ChatConnectionBanner status={status} />\n\n {renderAboveMessages && (\n <div className=\"border-b\">{renderAboveMessages()}</div>\n )}\n\n {/* The listener failed after messages loaded: they stay, with the failure above them. */}\n {loadFailure?.scope === \"live\" && <div className=\"border-b\">{renderLoadError(loadFailure)}</div>}\n\n <CardContent className={contentClassName}>\n <MessageList\n messages={messages}\n currentUserId={config.currentUserId}\n isAdmin={config.isAdmin}\n isFetchingOlder={isFetchingOlder}\n hasOlder={hasOlder}\n onLoadOlder={() => fetchOlder()}\n renderMessage={renderMessage}\n messageRenderers={messageRenderers}\n showScrollToBottom={showScrollToBottom}\n onScrollToBottom={() => setShowScrollToBottom(false)}\n onAtBottomChange={setAtBottom}\n fillHeight={fillHeight}\n scrollClassName={scrollClassName}\n scrollContainer={scrollContainer}\n handlers={handlers}\n onSenderClick={onSenderClick}\n onRetrySend={retrySend}\n olderLoadErrorRow={olderFailure ? renderLoadError(olderFailure) : null}\n />\n </CardContent>\n\n {renderBelowMessages && (\n <div className=\"border-t\">{renderBelowMessages()}</div>\n )}\n\n {renderFooter ? (\n <CardFooter className=\"border-t\">\n {renderFooter()}\n </CardFooter>\n ) : (\n <CardFooter className=\"border-t flex-col items-stretch gap-1\">\n {/* R14: typing dots above the composer (realtime only — `typing` is undefined on firestore). */}\n <TypingIndicator typing={typing} />\n <KeyboardAvoidingView padding offset={8} className=\"w-full\">\n <Composer\n onSend={send}\n onTyping={signalTyping}\n disabled={composerDisabled}\n autoFocus={autoFocus}\n placeholder={composerPlaceholder}\n />\n </KeyboardAvoidingView>\n </CardFooter>\n )}\n </Card>\n );\n}\n\n/**\n * R13 — connection-state banner. The realtime path sets `status`; once the first\n * snapshot has loaded (ChatShellView is past `isInitialLoading`), a dropped/unreachable\n * socket surfaces here instead of a silently-empty thread. Renders nothing on the\n * firestore path (`status` undefined) or while live (`open`).\n */\nfunction ChatConnectionBanner({ status }: { status?: string }) {\n if (status !== \"reconnecting\" && status !== \"closed\") return null;\n return (\n <div\n className=\"px-3 py-1.5 text-xs text-center bg-muted text-muted-foreground border-b\"\n role=\"status\"\n aria-live=\"polite\"\n >\n {status === \"reconnecting\"\n ? \"Reconnecting… messages may be delayed.\"\n : \"Disconnected — messages may be out of date.\"}\n </div>\n );\n}\n\n/** R14 — typing indicator. `typing` is the set of OTHER users typing (the transport\n * excludes the local user). Generic copy (no name resolution) for v1. */\nfunction TypingIndicator({ typing }: { typing?: string[] }) {\n if (!typing || typing.length === 0) return null;\n return (\n <div className=\"text-xs italic text-muted-foreground\" aria-live=\"polite\">\n {typing.length === 1 ? \"Someone is typing…\" : \"Several people are typing…\"}\n </div>\n );\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ttt-productions/chat-react",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.13",
|
|
4
4
|
"description": "Chat React UI, hooks, and Firebase-client adapter for TTT Productions apps (realtime newest window + infinite older pagination)",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
},
|
|
34
34
|
"peerDependencies": {
|
|
35
35
|
"@tanstack/react-query": ">=5.0.0",
|
|
36
|
-
"@ttt-productions/query-core": "^0.14.
|
|
36
|
+
"@ttt-productions/query-core": "^0.14.13",
|
|
37
37
|
"firebase": ">=12.0.0",
|
|
38
38
|
"lucide-react": "^1.30.0",
|
|
39
39
|
"react": ">=19.0.0",
|
|
@@ -63,13 +63,13 @@
|
|
|
63
63
|
"@ttt-productions/chat-core": "^0.11.2",
|
|
64
64
|
"@ttt-productions/chat-schemas": "^0.10.5",
|
|
65
65
|
"@ttt-productions/realtime-core": "^0.1.3",
|
|
66
|
-
"@ttt-productions/ui-core": "^0.11.
|
|
66
|
+
"@ttt-productions/ui-core": "^0.11.30",
|
|
67
67
|
"@ttt-productions/upload-ui": "^0.7.13",
|
|
68
68
|
"@ttt-productions/mobile-core": "^0.9.3",
|
|
69
|
-
"@ttt-productions/firebase-helpers": "^0.12.
|
|
69
|
+
"@ttt-productions/firebase-helpers": "^0.12.11"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
|
-
"@ttt-productions/query-core": "^0.14.
|
|
72
|
+
"@ttt-productions/query-core": "^0.14.13",
|
|
73
73
|
"@types/react": "^19.0.0",
|
|
74
74
|
"@types/react-dom": "^19.0.0",
|
|
75
75
|
"lucide-react": "^1.30.0",
|