@ttt-productions/chat-react 0.12.15 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +8 -8
  2. package/dist/hooks/useChatMessages.d.ts.map +1 -1
  3. package/dist/hooks/useChatMessages.js +0 -1
  4. package/dist/hooks/useChatMessages.js.map +1 -1
  5. package/dist/index.d.ts +2 -6
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +0 -2
  8. package/dist/index.js.map +1 -1
  9. package/dist/realtime/channel-client.d.ts +6 -13
  10. package/dist/realtime/channel-client.d.ts.map +1 -1
  11. package/dist/realtime/channel-client.js +7 -56
  12. package/dist/realtime/channel-client.js.map +1 -1
  13. package/dist/realtime/diagnostics.d.ts +0 -2
  14. package/dist/realtime/diagnostics.d.ts.map +1 -1
  15. package/dist/realtime/diagnostics.js +7 -5
  16. package/dist/realtime/diagnostics.js.map +1 -1
  17. package/dist/realtime/map.d.ts +4 -7
  18. package/dist/realtime/map.d.ts.map +1 -1
  19. package/dist/realtime/map.js +4 -41
  20. package/dist/realtime/map.js.map +1 -1
  21. package/dist/realtime/wire.d.ts +5 -5
  22. package/dist/realtime/wire.d.ts.map +1 -1
  23. package/dist/realtime/wire.js.map +1 -1
  24. package/dist/types.d.ts +0 -41
  25. package/dist/types.d.ts.map +1 -1
  26. package/dist/types.js.map +1 -1
  27. package/dist/ui/ChatShell.d.ts +2 -4
  28. package/dist/ui/ChatShell.d.ts.map +1 -1
  29. package/dist/ui/ChatShell.js +9 -14
  30. package/dist/ui/ChatShell.js.map +1 -1
  31. package/dist/ui/Composer.d.ts +5 -28
  32. package/dist/ui/Composer.d.ts.map +1 -1
  33. package/dist/ui/Composer.js +8 -104
  34. package/dist/ui/Composer.js.map +1 -1
  35. package/dist/ui/MessageItemDefault.d.ts +0 -5
  36. package/dist/ui/MessageItemDefault.d.ts.map +1 -1
  37. package/dist/ui/MessageItemDefault.js +6 -75
  38. package/dist/ui/MessageItemDefault.js.map +1 -1
  39. package/dist/ui/MessageList.d.ts +0 -3
  40. package/dist/ui/MessageList.d.ts.map +1 -1
  41. package/dist/ui/MessageList.js +2 -2
  42. package/dist/ui/MessageList.js.map +1 -1
  43. package/package.json +3 -6
  44. package/src/styles/chat.css +0 -139
  45. package/dist/context/ChatAttachmentMediaContext.d.ts +0 -37
  46. package/dist/context/ChatAttachmentMediaContext.d.ts.map +0 -1
  47. package/dist/context/ChatAttachmentMediaContext.js +0 -17
  48. package/dist/context/ChatAttachmentMediaContext.js.map +0 -1
  49. package/dist/context/ChatAttachmentUrlContext.d.ts +0 -25
  50. package/dist/context/ChatAttachmentUrlContext.d.ts.map +0 -1
  51. package/dist/context/ChatAttachmentUrlContext.js +0 -21
  52. package/dist/context/ChatAttachmentUrlContext.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"map.d.ts","sourceRoot":"","sources":["../../src/realtime/map.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAkB,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChF,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACzE,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAI9D,OAAO,EAAE,wBAAwB,EAAE,CAAC;AAEpC,sFAAsF;AACtF,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,YAAY,CAAC;IACnB,eAAe,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,GAAG,IAAI,GAAG,aAAa,CAc/G;AAED,4FAA4F;AAC5F,wBAAgB,cAAc,CAAC,GAAG,EAAE,cAAc,GAAG,iBAAiB,GAAG,IAAI,CAG5E;AAED,qFAAqF;AACrF,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAElD;AA0BD;;;;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M,GAAG,aAAa,CAkBrF;AAED,8FAA8F;AAC9F,wBAAgB,iBAAiB,CAAC,IAAI,EAAE;IACtC,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,cAAc,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CACjE,GAAG,aAAa,CAYhB"}
@@ -60,54 +60,19 @@ function parseJson(raw) {
60
60
  * thread id (the UI's thread key); the DO row carries no threadId of its own.
61
61
  * - `messageId` = the server seq (string) — stable + dedup key.
62
62
  * - `replyTo` JSON `{ messageSeq, preview }` → UI `{ messageId, senderId:'', messagePreview }`.
63
- * - The DO row carries only the attachment LIFECYCLE (`attachmentState` +
64
- * `attachmentMeta` with `mediaAssetId`/`attachmentKind`/`failureReason`), never a
65
- * full stored `ChatAttachment` — the projection below rebuilds the renderable
66
- * `attachment` from that lifecycle, and the render-time URL comes from
67
- * `mediaAssetId` via the attachment-URL resolver context (identity/media
68
- * invariant: no URLs are ever stored). The raw lifecycle also stays on
69
- * `meta.attachment*` for consumers that key on it.
63
+ *
64
+ * A DO row carries TEXT only. Files are not part of the message timeline — they
65
+ * live in the conversation's Conversation Files list, published through the
66
+ * canonical media pipeline and read from Firestore, never mapped from a chat row.
70
67
  */
71
68
  export function wireRowToMessage(row, threadId) {
72
69
  const reply = parseJson(row.replyTo);
73
- const meta = parseJson(row.attachmentMeta);
74
- // Project the DO's attachment LIFECYCLE into the renderable `attachment` object —
75
- // the renderer keys on `m.attachment` (AttachmentView: pending spinner / failed
76
- // bubble / ready media via the attachment-URL resolver + `mediaAssetId`). Before
77
- // this projection existed, a wire-delivered attachment message (live broadcast,
78
- // resume snapshot, history page) mapped to a message with NO `attachment` and
79
- // rendered as an empty bubble — the recipient never saw the media at all (found
80
- // live 2026-07-20, hosted path 11.3). `name`/`size`/`storagePath` are wire-absent
81
- // and render-irrelevant (labels are kind-scrubbed; storagePath is never a serving
82
- // contract) — placeholders keep the ChatAttachment shape without inventing data.
83
- const state = row.attachmentState === 'pending' || row.attachmentState === 'ready' || row.attachmentState === 'failed'
84
- ? row.attachmentState
85
- : null;
86
- const kind = meta?.attachmentKind === 'image' || meta?.attachmentKind === 'video' || meta?.attachmentKind === 'audio'
87
- ? meta.attachmentKind
88
- : // Rows written before the DO stored `attachmentKind` carry none — 'image' keeps
89
- // them rendering through the media path (the resolver serves whatever the asset
90
- // is); new rows always carry the real kind.
91
- 'image';
92
- const attachment = state
93
- ? {
94
- id: row.clientMessageId,
95
- name: '',
96
- type: kind,
97
- size: 0,
98
- storagePath: '',
99
- ...(meta?.mediaAssetId ? { mediaAssetId: meta.mediaAssetId } : {}),
100
- status: state,
101
- ...(meta?.failureReason ? { failureReason: meta.failureReason } : {}),
102
- }
103
- : null;
104
70
  return {
105
71
  messageId: seqToMessageId(row.seq),
106
72
  threadId,
107
73
  createdAt: row.createdAt,
108
74
  senderId: row.senderUid,
109
75
  text: row.text,
110
- ...(attachment ? { attachment } : {}),
111
76
  replyTo: reply
112
77
  ? { messageId: seqToMessageId(reply.messageSeq), senderId: '', messagePreview: reply.preview }
113
78
  : undefined,
@@ -115,8 +80,6 @@ export function wireRowToMessage(row, threadId) {
115
80
  meta: {
116
81
  seq: row.seq,
117
82
  epoch: row.epoch,
118
- ...(row.attachmentState ? { attachmentState: row.attachmentState } : {}),
119
- ...(meta ? { attachmentMeta: meta } : {}),
120
83
  },
121
84
  };
122
85
  }
@@ -1 +1 @@
1
- {"version":3,"file":"map.js","sourceRoot":"","sources":["../../src/realtime/map.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,+EAA+E;AAC/E,kDAAkD;AAClD,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,4CAA4C;AAG5C,OAAO,EAAE,wBA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SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,EAAE,EAAE,EAAE,cAAc,EAAE,IAAI,CAAC,OAAO,CAAC,cAAc,IAAI,EAAE,EAAE;YACxG,CAAC,CAAC,SAAS;QACb,IAAI,EAAE,EAAE,eAAe,EAAE,IAAI,CAAC,eAAe,EAAE,UAAU,EAAE,IAAI,EAAE;KAClE,CAAC;AACJ,CAAC","sourcesContent":["// Map the DO wire row (`WireMessageRow`) into the UI `ChatMessageV1` shape so the\n// UI stays transport-agnostic — the MessageList renders the same shape whether\n// the bytes came from Firestore or the DO socket.\n//\n// Identity invariant: the DO stores uid references only (`senderUid`), never a\n// display name — names resolve at render time through the ChatNameResolver\n// context, identical to the Firestore path.\n\nimport type { ChatAttachment, ChatMessageV1 } from '@ttt-productions/chat-core';\nimport { MODERATION_REDACTED_TEXT } from '@ttt-productions/chat-schemas';\nimport type { RevisionKind, WireMessageRow } from './wire.js';\n\n// The redacted-text constant lives in the wire contract; re-export to keep this\n// module's public surface stable.\nexport { MODERATION_REDACTED_TEXT };\n\n/** The effective moderation overlay for a message: the max-`messageRevision` kind. */\nexport interface ModerationOverlay {\n kind: RevisionKind;\n messageRevision: number;\n}\n\n/**\n * Apply a moderation overlay to a mapped message so the ORIGINAL content never\n * renders for a hidden/deleted message. Pure — returns a new message; the input\n * is not mutated. The overlay state rides on `meta` (`meta` is opaque to\n * chat-core), so the renderer can branch on `meta.moderated` / `meta.moderationKind`.\n * - `delete` / `moderate` → blank/replace the text + mark moderated.\n * - `edit` → the row already carries the overlaid text (the DO rewrites `text`),\n * so only the marker is stamped.\n * - `restore` → original content (the DO row is the original); no redaction.\n */\nexport function applyModerationOverlay(message: ChatMessageV1, overlay: ModerationOverlay | null): ChatMessageV1 {\n if (!overlay) return message;\n const redacted = overlay.kind === 'delete' || overlay.kind === 'moderate';\n return {\n ...message,\n ...(redacted ? { text: MODERATION_REDACTED_TEXT } : {}),\n meta: {\n ...message.meta,\n moderationKind: overlay.kind,\n messageRevision: overlay.messageRevision,\n // `restore` is the absence of active moderation — it reverts to the original.\n moderated: overlay.kind !== 'restore',\n },\n };\n}\n\n/** The overlay carried inline on a DO row (the getHistory/getDeltaSince merge), or null. */\nexport function overlayFromRow(row: WireMessageRow): ModerationOverlay | null {\n if (row.moderationKind == null) return null;\n return { kind: row.moderationKind, messageRevision: row.messageRevision ?? 0 };\n}\n\n/** The DO `seq` is the stable per-channel message id (monotonic, epoch-spanning). */\nexport function seqToMessageId(seq: number): string {\n return String(seq);\n}\n\ninterface WireReplyTo {\n messageSeq: number;\n preview: string;\n}\n\ninterface WireAttachmentMeta {\n senderOnly?: boolean;\n mediaAssetId?: string;\n failureReason?: string;\n /** 'image' | 'video' | 'audio' — stored by the Channel DO from the placeholder\n * command's validated contentType kind; inherited by the ready flip. */\n attachmentKind?: string;\n [k: string]: unknown;\n}\n\nfunction parseJson<T>(raw: string | null): T | null {\n if (raw == null) return null;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a DO message row to the UI message. `threadId` is the caller's logical\n * thread id (the UI's thread key); the DO row carries no threadId of its own.\n * - `messageId` = the server seq (string) — stable + dedup key.\n * - `replyTo` JSON `{ messageSeq, preview }` → UI `{ messageId, senderId:'', messagePreview }`.\n * - The DO row carries only the attachment LIFECYCLE (`attachmentState` +\n * `attachmentMeta` with `mediaAssetId`/`attachmentKind`/`failureReason`), never a\n * full stored `ChatAttachment` — the projection below rebuilds the renderable\n * `attachment` from that lifecycle, and the render-time URL comes from\n * `mediaAssetId` via the attachment-URL resolver context (identity/media\n * invariant: no URLs are ever stored). The raw lifecycle also stays on\n * `meta.attachment*` for consumers that key on it.\n */\nexport function wireRowToMessage(row: WireMessageRow, threadId: string): ChatMessageV1 {\n const reply = parseJson<WireReplyTo>(row.replyTo);\n const meta = parseJson<WireAttachmentMeta>(row.attachmentMeta);\n\n // Project the DO's attachment LIFECYCLE into the renderable `attachment` object —\n // the renderer keys on `m.attachment` (AttachmentView: pending spinner / failed\n // bubble / ready media via the attachment-URL resolver + `mediaAssetId`). Before\n // this projection existed, a wire-delivered attachment message (live broadcast,\n // resume snapshot, history page) mapped to a message with NO `attachment` and\n // rendered as an empty bubble — the recipient never saw the media at all (found\n // live 2026-07-20, hosted path 11.3). `name`/`size`/`storagePath` are wire-absent\n // and render-irrelevant (labels are kind-scrubbed; storagePath is never a serving\n // contract) — placeholders keep the ChatAttachment shape without inventing data.\n const state =\n row.attachmentState === 'pending' || row.attachmentState === 'ready' || row.attachmentState === 'failed'\n ? row.attachmentState\n : null;\n const kind =\n meta?.attachmentKind === 'image' || meta?.attachmentKind === 'video' || meta?.attachmentKind === 'audio'\n ? meta.attachmentKind\n : // Rows written before the DO stored `attachmentKind` carry none — 'image' keeps\n // them rendering through the media path (the resolver serves whatever the asset\n // is); new rows always carry the real kind.\n 'image';\n const attachment: ChatAttachment | null = state\n ? {\n id: row.clientMessageId,\n name: '',\n type: kind,\n size: 0,\n storagePath: '',\n ...(meta?.mediaAssetId ? { mediaAssetId: meta.mediaAssetId } : {}),\n status: state,\n ...(meta?.failureReason ? { failureReason: meta.failureReason } : {}),\n }\n : null;\n\n return {\n messageId: seqToMessageId(row.seq),\n threadId,\n createdAt: row.createdAt,\n senderId: row.senderUid,\n text: row.text,\n ...(attachment ? { attachment } : {}),\n replyTo: reply\n ? { messageId: seqToMessageId(reply.messageSeq), senderId: '', messagePreview: reply.preview }\n : undefined,\n isSystemMessage: row.senderUid === 'system' || undefined,\n meta: {\n seq: row.seq,\n epoch: row.epoch,\n ...(row.attachmentState ? { attachmentState: row.attachmentState } : {}),\n ...(meta ? { attachmentMeta: meta } : {}),\n },\n };\n}\n\n/** The optimistic local echo a `send` produces before the server `ack` reconciles the seq. */\nexport function optimisticMessage(args: {\n clientMessageId: string;\n threadId: string;\n senderId: string;\n text: string;\n createdAt: number;\n replyTo?: { messageId: string; messagePreview?: string } | null;\n}): ChatMessageV1 {\n return {\n messageId: `optimistic:${args.clientMessageId}`,\n threadId: args.threadId,\n createdAt: args.createdAt,\n senderId: args.senderId,\n text: args.text,\n replyTo: args.replyTo\n ? { messageId: args.replyTo.messageId, senderId: '', messagePreview: args.replyTo.messagePreview ?? '' }\n : undefined,\n meta: { clientMessageId: args.clientMessageId, optimistic: true },\n };\n}\n"]}
1
+ {"version":3,"file":"map.js","sourceRoot":"","sources":["../../src/realtime/map.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,+EAA+E;AAC/E,kDAAkD;AAClD,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,4CAA4C;AAG5C,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAGzE,gFAAgF;AAChF,kCAAkC;AAClC,OAAO,EAAE,wBAAwB,EAAE,CAAC;AAQpC;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CAAC,OAAsB,EAAE,OAAiC;IAC9F,IAAI,CAAC,OAAO;QAAE,OAAO,OAAO,CAAC;IAC7B,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU,CAAC;IAC1E,OAAO;QACL,GAAG,OAAO;QACV,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,wBAAwB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvD,IAAI,EAAE;YACJ,GAAG,OAAO,CAAC,IAAI;YACf,cAAc,EAAE,OAAO,CAAC,IAAI;YAC5B,eAAe,EAAE,OAAO,CAAC,eAAe;YACxC,8EAA8E;YAC9E,SAAS,EAAE,OAAO,CAAC,IAAI,KAAK,SAAS;SACtC;KACF,CAAC;AACJ,CAAC;AAED,4FAA4F;AAC5F,MAAM,UAAU,cAAc,CAAC,GAAmB;IAChD,IAAI,GAAG,CAAC,cAAc,IAAI,IAAI;QAAE,OAAO,IAAI,CAAC;IAC5C,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,cAAc,EAA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I,CAAC,QAAQ;QACvB,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,OAAO,EAAE,IAAI,CAAC,OAAO;YACnB,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,EAAE,EAAE,EAAE,cAAc,EAAE,IAAI,CAAC,OAAO,CAAC,cAAc,IAAI,EAAE,EAAE;YACxG,CAAC,CAAC,SAAS;QACb,IAAI,EAAE,EAAE,eAAe,EAAE,IAAI,CAAC,eAAe,EAAE,UAAU,EAAE,IAAI,EAAE;KAClE,CAAC;AACJ,CAAC","sourcesContent":["// Map the DO wire row (`WireMessageRow`) into the UI `ChatMessageV1` shape so the\n// UI stays transport-agnostic — the MessageList renders the same shape whether\n// the bytes came from Firestore or the DO socket.\n//\n// Identity invariant: the DO stores uid references only (`senderUid`), never a\n// display name — names resolve at render time through the ChatNameResolver\n// context, identical to the Firestore path.\n\nimport type { ChatMessageV1 } from '@ttt-productions/chat-core';\nimport { MODERATION_REDACTED_TEXT } from '@ttt-productions/chat-schemas';\nimport type { RevisionKind, WireMessageRow } from './wire.js';\n\n// The redacted-text constant lives in the wire contract; re-export to keep this\n// module's public surface stable.\nexport { MODERATION_REDACTED_TEXT };\n\n/** The effective moderation overlay for a message: the max-`messageRevision` kind. */\nexport interface ModerationOverlay {\n kind: RevisionKind;\n messageRevision: number;\n}\n\n/**\n * Apply a moderation overlay to a mapped message so the ORIGINAL content never\n * renders for a hidden/deleted message. Pure — returns a new message; the input\n * is not mutated. The overlay state rides on `meta` (`meta` is opaque to\n * chat-core), so the renderer can branch on `meta.moderated` / `meta.moderationKind`.\n * - `delete` / `moderate` → blank/replace the text + mark moderated.\n * - `edit` → the row already carries the overlaid text (the DO rewrites `text`),\n * so only the marker is stamped.\n * - `restore` → original content (the DO row is the original); no redaction.\n */\nexport function applyModerationOverlay(message: ChatMessageV1, overlay: ModerationOverlay | null): ChatMessageV1 {\n if (!overlay) return message;\n const redacted = overlay.kind === 'delete' || overlay.kind === 'moderate';\n return {\n ...message,\n ...(redacted ? { text: MODERATION_REDACTED_TEXT } : {}),\n meta: {\n ...message.meta,\n moderationKind: overlay.kind,\n messageRevision: overlay.messageRevision,\n // `restore` is the absence of active moderation — it reverts to the original.\n moderated: overlay.kind !== 'restore',\n },\n };\n}\n\n/** The overlay carried inline on a DO row (the getHistory/getDeltaSince merge), or null. */\nexport function overlayFromRow(row: WireMessageRow): ModerationOverlay | null {\n if (row.moderationKind == null) return null;\n return { kind: row.moderationKind, messageRevision: row.messageRevision ?? 0 };\n}\n\n/** The DO `seq` is the stable per-channel message id (monotonic, epoch-spanning). */\nexport function seqToMessageId(seq: number): string {\n return String(seq);\n}\n\ninterface WireReplyTo {\n messageSeq: number;\n preview: string;\n}\n\nfunction parseJson<T>(raw: string | null): T | null {\n if (raw == null) return null;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a DO message row to the UI message. `threadId` is the caller's logical\n * thread id (the UI's thread key); the DO row carries no threadId of its own.\n * - `messageId` = the server seq (string) — stable + dedup key.\n * - `replyTo` JSON `{ messageSeq, preview }` → UI `{ messageId, senderId:'', messagePreview }`.\n *\n * A DO row carries TEXT only. Files are not part of the message timeline — they\n * live in the conversation's Conversation Files list, published through the\n * canonical media pipeline and read from Firestore, never mapped from a chat row.\n */\nexport function wireRowToMessage(row: WireMessageRow, threadId: string): ChatMessageV1 {\n const reply = parseJson<WireReplyTo>(row.replyTo);\n\n return {\n messageId: seqToMessageId(row.seq),\n threadId,\n createdAt: row.createdAt,\n senderId: row.senderUid,\n text: row.text,\n replyTo: reply\n ? { messageId: seqToMessageId(reply.messageSeq), senderId: '', messagePreview: reply.preview }\n : undefined,\n isSystemMessage: row.senderUid === 'system' || undefined,\n meta: {\n seq: row.seq,\n epoch: row.epoch,\n },\n };\n}\n\n/** The optimistic local echo a `send` produces before the server `ack` reconciles the seq. */\nexport function optimisticMessage(args: {\n clientMessageId: string;\n threadId: string;\n senderId: string;\n text: string;\n createdAt: number;\n replyTo?: { messageId: string; messagePreview?: string } | null;\n}): ChatMessageV1 {\n return {\n messageId: `optimistic:${args.clientMessageId}`,\n threadId: args.threadId,\n createdAt: args.createdAt,\n senderId: args.senderId,\n text: args.text,\n replyTo: args.replyTo\n ? { messageId: args.replyTo.messageId, senderId: '', messagePreview: args.replyTo.messagePreview ?? '' }\n : undefined,\n meta: { clientMessageId: args.clientMessageId, optimistic: true },\n };\n}\n"]}
@@ -11,9 +11,11 @@ import type { ChannelRefTuple, ChatSendRejectedPayload } from '@ttt-productions/
11
11
  export type RevisionKind = 'delete' | 'moderate' | 'edit' | 'restore';
12
12
  /**
13
13
  * A message row as the Channel DO stores + broadcasts it (the worker runtime's
14
- * message row). `replyTo`/`attachmentMeta` arrive as JSON STRINGS (or null) —
15
- * the DO stores them stringified and does not re-parse before broadcast. The
16
- * adapter mapping in `map.ts` parses them into the UI `ChatMessageV1` shape.
14
+ * message row). `replyTo` arrives as a JSON STRING (or null) — the DO stores it
15
+ * stringified and does not re-parse before broadcast. The adapter mapping in
16
+ * `map.ts` parses it into the UI `ChatMessageV1` shape.
17
+ *
18
+ * The row is TEXT-only: there is no attachment lifecycle on a chat message.
17
19
  */
18
20
  export interface WireMessageRow {
19
21
  seq: number;
@@ -21,8 +23,6 @@ export interface WireMessageRow {
21
23
  clientMessageId: string;
22
24
  text: string;
23
25
  replyTo: string | null;
24
- attachmentState: string | null;
25
- attachmentMeta: string | null;
26
26
  createdAt: number;
27
27
  epoch: number;
28
28
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"wire.d.ts","sourceRoot":"","sources":["../../src/realtime/wire.ts"],"names":[],"mappings":"AAiBA,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,IAAI,YAAY,EAC5B,YAAY,IAAI,YAAY,EAE5B,6BAA6B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,CAAC;QACvD,OAAO,MAA0E,CAAC;IACpF,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,wGAAwG;AACxG,MAAM,UAAU,eAAe,CAAC,CAA0C;IACxE,OAAO,KAAK,CAAC,OAAO,CAAE,CAAuB,CAAC,QAAQ,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["// Chat realtime WIRE PROTOCOL (Contract C) — the client side of the Channel +\n// Inbox Durable Object protocol. The canonical protocol declarations (subprotocol,\n// frame-kind maps, close codes, channel-ref tuple, grant scope, client-agreed\n// limits) are owned by `@ttt-productions/chat-schemas`; this file consumes them\n// and adds the client-side raw row/frame shapes the transport maps into the UI\n// message shape. The client and the worker runtime agree on the wire by both\n// importing that one contract; neither imports the other.\n//\n// Frame shape on the socket is `{ v, type, payload }` (NOT realtime-core's\n// `{ v, kind, payload }`): the worker runtime `send`/`broadcast` emit\n// `JSON.stringify({ v: 1, type, payload })` and read `env.type` + `env.payload`.\n// We keep that field name here to match; realtime-core's envelope schema is the\n// generic transport primitive, the chat protocol chose `type` for its frames.\n\n// Re-export the canonical wire contract so this package's public surface is\n// unchanged. `CLIENT_FRAME`/`SERVER_FRAME` are this package's historical names\n// for the frame-kind maps (`CLIENT_KINDS`/`SERVER_KINDS` in the contract).\nexport {\n CHAT_SUBPROTOCOL,\n CHAT_WIRE_VERSION,\n CHAT_CLOSE_CODES,\n CLIENT_KINDS as CLIENT_FRAME,\n SERVER_KINDS as SERVER_FRAME,\n // Correlated send-rejection contract (SERVER_FRAME.SEND_REJECTED payload).\n ChatSendRejectedPayloadSchema,\n CHAT_SEND_REJECTION_CODES,\n CHAT_SEND_REJECTION_RETRYABLE,\n} from '@ttt-productions/chat-schemas';\nexport type {\n ChatCloseCode,\n ChannelRefTuple,\n ChatSendRejectedPayload,\n ChatSendRejectionCode,\n} from '@ttt-productions/chat-schemas';\n\nimport { CHAT_WIRE_VERSION } from '@ttt-productions/chat-schemas';\nimport type { ChannelRefTuple, ChatSendRejectedPayload } from '@ttt-productions/chat-schemas';\n\n// ---- raw wire row shapes (what the DO serializes; opaque-but-typed here) ----\n\n/**\n * The moderation revision `kind` (the worker runtime's revision input + the\n * `revisions.kind` column). The EFFECTIVE state of a message is its\n * MAX-`messageRevision` row's kind, so a `restore` (a later revision) supersedes\n * an earlier `moderate`/`delete`. `moderate`/`delete` blank the original text;\n * `edit` overlays new text; `restore` reverts to the original.\n */\nexport type RevisionKind = 'delete' | 'moderate' | 'edit' | 'restore';\n\n/**\n * A message row as the Channel DO stores + broadcasts it (the worker runtime's\n * message row). `replyTo`/`attachmentMeta` arrive as JSON STRINGS (or null) —\n * the DO stores them stringified and does not re-parse before broadcast. The\n * adapter mapping in `map.ts` parses them into the UI `ChatMessageV1` shape.\n */\nexport interface WireMessageRow {\n seq: number;\n senderUid: string;\n clientMessageId: string;\n text: string;\n replyTo: string | null;\n attachmentState: string | null;\n attachmentMeta: string | null;\n createdAt: number;\n epoch: number;\n /**\n * The effective (max-`messageRevision`) moderation kind for this row, or null\n * when never moderated. Populated by the DO's getHistory/getDeltaSince overlay\n * merge so a hidden/deleted/edited row arrives already-moderated and its\n * ORIGINAL text never reaches the renderer. Optional/absent on pre-overlay rows.\n */\n moderationKind?: RevisionKind | null;\n /**\n * The effective `messageRevision` that `moderationKind` reflects (the DO's\n * max-revision). Used to break ties against a live `revision` frame: a higher\n * `messageRevision` wins; a stale/older one is ignored. Optional/absent on\n * pre-overlay rows (treated as revision 0).\n */\n messageRevision?: number;\n}\n\n/**\n * The channel resume snapshot the DO returns for a `resume` frame (Contract C).\n * `resync` / `delta` are the durable gap-repair half of the contract:\n * - `resync: false` + `delta` = the contiguous ≤500-message backlog after the\n * client's cursor (oldest-first); the client APPLIES the delta and advances its\n * cursor to `lastMessageSeq` — a missed broadcast is never permanent.\n * - `resync: true` = the gap exceeds the backlog (or the client sent no cursor);\n * the client DROPS its local tail and re-pages history from the top.\n * Both are OPTIONAL/absent on a pre-contract DO (treated as `resync: true`, empty\n * delta — the safe re-page path) so a stale worker can't leave a client stuck.\n */\nexport interface WireChannelSnapshot {\n lastMessageSeq: number;\n readSeq: number;\n resync?: boolean;\n delta?: WireMessageRow[];\n}\n\n/** A registry entry in the inbox snapshot (the worker runtime's registry entry). */\nexport interface WireRegistryEntry {\n channelRef: string;\n kind: string;\n state: 'active' | 'tombstoned';\n registryVersion: number;\n /**\n * The typed channel-ref tuple — the OPENABLE identity for the inbox view (the\n * `channelRef` is an opaque DO-id dedup key). Null/absent on legacy or pre-tuple\n * rows; the consumer falls back to hiding the open action for those entries.\n */\n ref?: ChannelRefTuple | null;\n /**\n * Per-entry unread flag (drives the per-row dot). Optional/absent until the inbox\n * DO populates it; `deriveUnreadRefs` reads it as a typed field (no cast).\n */\n unread?: boolean;\n /**\n * Archived state — DISTINCT from `tombstoned`. An archived row is still an ACTIVE\n * membership (`state: 'active'`, history readable) but is grouped under the inbox\n * view's Archived toggle instead of the active list. The client must NOT count\n * archived rows in the unread roll-up (archive = done; the DO clears unread on\n * archive). Optional/absent on a pre-archive DO (treated as not-archived).\n */\n archived?: boolean;\n}\n\n/** The inbox snapshot payload pushed on connect / `resume` / live delta. */\nexport interface WireInboxSnapshot {\n registry: WireRegistryEntry[];\n hasUnread: boolean;\n}\n\n// ---- server → client frame payloads (discriminated on `type`) ----\n\nexport type ServerFrame =\n | { type: 'message'; payload: { message: WireMessageRow } }\n | { type: 'ack'; payload: { clientMessageId?: string; seq?: number; readSeq?: number } }\n | { type: 'history-page'; payload: { messages: WireMessageRow[] } }\n | { type: 'presence'; payload: { online: string[] } }\n | { type: 'typing'; payload: { uid: string; at: number } }\n | { type: 'snapshot'; payload: WireChannelSnapshot | WireInboxSnapshot }\n // A standalone unread push (inbox scope): either a full inbox snapshot or a\n // lightweight dock-dot patch. Represented in the union so the inbox client routes\n // it instead of silently dropping it (forward-compatible with a future DO push).\n | { type: 'unread'; payload: WireInboxSnapshot | { hasUnread: boolean } }\n | { type: 'error'; payload: { code: string; retryAfterMs?: number } }\n // A CORRELATED send rejection (SERVER_FRAME.SEND_REJECTED): names the SAME\n // clientMessageId as the rejected send + the canonical retry classification, so\n // exactly one optimistic bubble is failed/retried. See ChatSendRejectedPayload.\n | { type: 'send-rejected'; payload: ChatSendRejectedPayload }\n // A moderation revision was applied to one message. The Channel DO broadcasts\n // this on a NEWLY-applied revision (the worker runtime's moderation apply) so live\n // viewers hide/blank/edit/restore the message immediately with no extra fetch.\n // `messageSeq` is the target message id; `kind` is the applied revision kind;\n // `messageRevision` is its per-message revision number (max-revision wins).\n | { type: 'revision'; payload: { messageSeq: number; kind: RevisionKind; messageRevision: number } };\n\n/** Build an outbound `{ v, type, payload }` frame (the wire format the DO reads). */\nexport function buildFrame(type: string, payload: Record<string, unknown>): string {\n return JSON.stringify({ v: CHAT_WIRE_VERSION, type, payload });\n}\n\n/** Parse an inbound frame, tolerating malformed JSON. Returns null on garbage. */\nexport function parseFrame(raw: string): { v?: number; type?: string; payload?: Record<string, unknown> } | null {\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (!parsed || typeof parsed !== 'object') return null;\n return parsed as { v?: number; type?: string; payload?: Record<string, unknown> };\n } catch {\n return null;\n }\n}\n\n/** A snapshot with `registry` is an inbox snapshot; one with `lastMessageSeq` is a channel snapshot. */\nexport function isInboxSnapshot(p: WireChannelSnapshot | WireInboxSnapshot): p is WireInboxSnapshot {\n return Array.isArray((p as WireInboxSnapshot).registry);\n}\n"]}
1
+ {"version":3,"file":"wire.js","sourceRoot":"","sources":["../../src/realtime/wire.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,mFAAmF;AACnF,8EAA8E;AAC9E,gFAAgF;AAChF,+EAA+E;AAC/E,6EAA6E;AAC7E,0DAA0D;AAC1D,EAAE;AACF,2EAA2E;AAC3E,sEAAsE;AACtE,iFAAiF;AACjF,gFAAgF;AAChF,8EAA8E;AAE9E,4EAA4E;AAC5E,+EAA+E;AAC/E,2EAA2E;AAC3E,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,IAAI,YAAY,EAC5B,YAAY,IAAI,YAAY;AAC5B,2EAA2E;AAC3E,6BAA6B,EAC7B,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,+BAA+B,CAAC;AAQvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AA0HlE,qFAAqF;AACrF,MAAM,UAAU,UAAU,CAAC,IAAY,EAAE,OAAgC;IACvE,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,EAAE,iBAAiB,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;AACjE,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAY,CAAC;QAC1C,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QACvD,OAAO,MAA0E,CAAC;IACpF,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,wGAAwG;AACxG,MAAM,UAAU,eAAe,CAAC,CAA0C;IACxE,OAAO,KAAK,CAAC,OAAO,CAAE,CAAuB,CAAC,QAAQ,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["// Chat realtime WIRE PROTOCOL (Contract C) — the client side of the Channel +\n// Inbox Durable Object protocol. The canonical protocol declarations (subprotocol,\n// frame-kind maps, close codes, channel-ref tuple, grant scope, client-agreed\n// limits) are owned by `@ttt-productions/chat-schemas`; this file consumes them\n// and adds the client-side raw row/frame shapes the transport maps into the UI\n// message shape. The client and the worker runtime agree on the wire by both\n// importing that one contract; neither imports the other.\n//\n// Frame shape on the socket is `{ v, type, payload }` (NOT realtime-core's\n// `{ v, kind, payload }`): the worker runtime `send`/`broadcast` emit\n// `JSON.stringify({ v: 1, type, payload })` and read `env.type` + `env.payload`.\n// We keep that field name here to match; realtime-core's envelope schema is the\n// generic transport primitive, the chat protocol chose `type` for its frames.\n\n// Re-export the canonical wire contract so this package's public surface is\n// unchanged. `CLIENT_FRAME`/`SERVER_FRAME` are this package's historical names\n// for the frame-kind maps (`CLIENT_KINDS`/`SERVER_KINDS` in the contract).\nexport {\n CHAT_SUBPROTOCOL,\n CHAT_WIRE_VERSION,\n CHAT_CLOSE_CODES,\n CLIENT_KINDS as CLIENT_FRAME,\n SERVER_KINDS as SERVER_FRAME,\n // Correlated send-rejection contract (SERVER_FRAME.SEND_REJECTED payload).\n ChatSendRejectedPayloadSchema,\n CHAT_SEND_REJECTION_CODES,\n CHAT_SEND_REJECTION_RETRYABLE,\n} from '@ttt-productions/chat-schemas';\nexport type {\n ChatCloseCode,\n ChannelRefTuple,\n ChatSendRejectedPayload,\n ChatSendRejectionCode,\n} from '@ttt-productions/chat-schemas';\n\nimport { CHAT_WIRE_VERSION } from '@ttt-productions/chat-schemas';\nimport type { ChannelRefTuple, ChatSendRejectedPayload } from '@ttt-productions/chat-schemas';\n\n// ---- raw wire row shapes (what the DO serializes; opaque-but-typed here) ----\n\n/**\n * The moderation revision `kind` (the worker runtime's revision input + the\n * `revisions.kind` column). The EFFECTIVE state of a message is its\n * MAX-`messageRevision` row's kind, so a `restore` (a later revision) supersedes\n * an earlier `moderate`/`delete`. `moderate`/`delete` blank the original text;\n * `edit` overlays new text; `restore` reverts to the original.\n */\nexport type RevisionKind = 'delete' | 'moderate' | 'edit' | 'restore';\n\n/**\n * A message row as the Channel DO stores + broadcasts it (the worker runtime's\n * message row). `replyTo` arrives as a JSON STRING (or null) — the DO stores it\n * stringified and does not re-parse before broadcast. The adapter mapping in\n * `map.ts` parses it into the UI `ChatMessageV1` shape.\n *\n * The row is TEXT-only: there is no attachment lifecycle on a chat message.\n */\nexport interface WireMessageRow {\n seq: number;\n senderUid: string;\n clientMessageId: string;\n text: string;\n replyTo: string | null;\n createdAt: number;\n epoch: number;\n /**\n * The effective (max-`messageRevision`) moderation kind for this row, or null\n * when never moderated. Populated by the DO's getHistory/getDeltaSince overlay\n * merge so a hidden/deleted/edited row arrives already-moderated and its\n * ORIGINAL text never reaches the renderer. Optional/absent on pre-overlay rows.\n */\n moderationKind?: RevisionKind | null;\n /**\n * The effective `messageRevision` that `moderationKind` reflects (the DO's\n * max-revision). Used to break ties against a live `revision` frame: a higher\n * `messageRevision` wins; a stale/older one is ignored. Optional/absent on\n * pre-overlay rows (treated as revision 0).\n */\n messageRevision?: number;\n}\n\n/**\n * The channel resume snapshot the DO returns for a `resume` frame (Contract C).\n * `resync` / `delta` are the durable gap-repair half of the contract:\n * - `resync: false` + `delta` = the contiguous ≤500-message backlog after the\n * client's cursor (oldest-first); the client APPLIES the delta and advances its\n * cursor to `lastMessageSeq` — a missed broadcast is never permanent.\n * - `resync: true` = the gap exceeds the backlog (or the client sent no cursor);\n * the client DROPS its local tail and re-pages history from the top.\n * Both are OPTIONAL/absent on a pre-contract DO (treated as `resync: true`, empty\n * delta — the safe re-page path) so a stale worker can't leave a client stuck.\n */\nexport interface WireChannelSnapshot {\n lastMessageSeq: number;\n readSeq: number;\n resync?: boolean;\n delta?: WireMessageRow[];\n}\n\n/** A registry entry in the inbox snapshot (the worker runtime's registry entry). */\nexport interface WireRegistryEntry {\n channelRef: string;\n kind: string;\n state: 'active' | 'tombstoned';\n registryVersion: number;\n /**\n * The typed channel-ref tuple — the OPENABLE identity for the inbox view (the\n * `channelRef` is an opaque DO-id dedup key). Null/absent on legacy or pre-tuple\n * rows; the consumer falls back to hiding the open action for those entries.\n */\n ref?: ChannelRefTuple | null;\n /**\n * Per-entry unread flag (drives the per-row dot). Optional/absent until the inbox\n * DO populates it; `deriveUnreadRefs` reads it as a typed field (no cast).\n */\n unread?: boolean;\n /**\n * Archived state — DISTINCT from `tombstoned`. An archived row is still an ACTIVE\n * membership (`state: 'active'`, history readable) but is grouped under the inbox\n * view's Archived toggle instead of the active list. The client must NOT count\n * archived rows in the unread roll-up (archive = done; the DO clears unread on\n * archive). Optional/absent on a pre-archive DO (treated as not-archived).\n */\n archived?: boolean;\n}\n\n/** The inbox snapshot payload pushed on connect / `resume` / live delta. */\nexport interface WireInboxSnapshot {\n registry: WireRegistryEntry[];\n hasUnread: boolean;\n}\n\n// ---- server → client frame payloads (discriminated on `type`) ----\n\nexport type ServerFrame =\n | { type: 'message'; payload: { message: WireMessageRow } }\n | { type: 'ack'; payload: { clientMessageId?: string; seq?: number; readSeq?: number } }\n | { type: 'history-page'; payload: { messages: WireMessageRow[] } }\n | { type: 'presence'; payload: { online: string[] } }\n | { type: 'typing'; payload: { uid: string; at: number } }\n | { type: 'snapshot'; payload: WireChannelSnapshot | WireInboxSnapshot }\n // A standalone unread push (inbox scope): either a full inbox snapshot or a\n // lightweight dock-dot patch. Represented in the union so the inbox client routes\n // it instead of silently dropping it (forward-compatible with a future DO push).\n | { type: 'unread'; payload: WireInboxSnapshot | { hasUnread: boolean } }\n | { type: 'error'; payload: { code: string; retryAfterMs?: number } }\n // A CORRELATED send rejection (SERVER_FRAME.SEND_REJECTED): names the SAME\n // clientMessageId as the rejected send + the canonical retry classification, so\n // exactly one optimistic bubble is failed/retried. See ChatSendRejectedPayload.\n | { type: 'send-rejected'; payload: ChatSendRejectedPayload }\n // A moderation revision was applied to one message. The Channel DO broadcasts\n // this on a NEWLY-applied revision (the worker runtime's moderation apply) so live\n // viewers hide/blank/edit/restore the message immediately with no extra fetch.\n // `messageSeq` is the target message id; `kind` is the applied revision kind;\n // `messageRevision` is its per-message revision number (max-revision wins).\n | { type: 'revision'; payload: { messageSeq: number; kind: RevisionKind; messageRevision: number } };\n\n/** Build an outbound `{ v, type, payload }` frame (the wire format the DO reads). */\nexport function buildFrame(type: string, payload: Record<string, unknown>): string {\n return JSON.stringify({ v: CHAT_WIRE_VERSION, type, payload });\n}\n\n/** Parse an inbound frame, tolerating malformed JSON. Returns null on garbage. */\nexport function parseFrame(raw: string): { v?: number; type?: string; payload?: Record<string, unknown> } | null {\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (!parsed || typeof parsed !== 'object') return null;\n return parsed as { v?: number; type?: string; payload?: Record<string, unknown> };\n } catch {\n return null;\n }\n}\n\n/** A snapshot with `registry` is an inbox snapshot; one with `lastMessageSeq` is a channel snapshot. */\nexport function isInboxSnapshot(p: WireChannelSnapshot | WireInboxSnapshot): p is WireInboxSnapshot {\n return Array.isArray((p as WireInboxSnapshot).registry);\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -1,6 +1,4 @@
1
- import type { FirebaseStorage } from "firebase/storage";
2
1
  import type { ReactNode } from "react";
3
- import type { MediaOriginSpec } from "@ttt-productions/media-schemas";
4
2
  import type { ChatAccessMode, ChatMessageV1, MentionProvider, MentionRef, RecentMentionsAdapter } from "@ttt-productions/chat-core";
5
3
  /** Custom renderer for a single autocomplete row / mention result. */
6
4
  export type MentionResultRenderer<TKind extends string = string> = (ref: MentionRef<TKind>) => ReactNode;
@@ -16,45 +14,6 @@ export type RenderableMentionProvider<TKind extends string = string, TContext =
16
14
  */
17
15
  renderResult?: MentionResultRenderer<TKind>;
18
16
  };
19
- /**
20
- * Pluggable upload-path strategy for chat attachments.
21
- *
22
- * Consumers supply this to tell the composer (a) what opaque origin identifier
23
- * to record for the upload, (b) how to build the Firebase Storage path for the
24
- * temporary upload, and (c) optional extra metadata to attach to the Storage
25
- * object.
26
- *
27
- * `buildUploadPath` and `buildUploadMetadata` receive the userId and
28
- * attachmentId so consumers can interpolate them per their own conventions.
29
- * The composer does not interpret `originId` — it forwards it via callbacks
30
- * and uses it for adapter identity only.
31
- */
32
- export type ChatUploadAdapter = {
33
- /** Opaque origin identifier (e.g. "chat-attachment"). Not interpreted here. */
34
- originId: string;
35
- /** Build the Firebase Storage path for the upload. Called once per attachment. */
36
- buildUploadPath: (args: {
37
- userId: string;
38
- attachmentId: string;
39
- }) => string;
40
- /** Optional extra metadata merged onto the Storage object metadata (e.g. customMetadata). */
41
- buildUploadMetadata?: (args: {
42
- userId: string;
43
- attachmentId: string;
44
- }) => Record<string, unknown>;
45
- };
46
- export type ChatAttachmentConfig = {
47
- attachmentSpec: MediaOriginSpec;
48
- storage: FirebaseStorage;
49
- /** The current user's auth uid. Forwarded to `uploadAdapter` callbacks. */
50
- userId: string;
51
- /**
52
- * Pluggable upload-path strategy. Consumers wire this to their app's
53
- * conventions (for example: originId "chat-attachment", path
54
- * `uploads/chat-attachment/{userId}/{attachmentId}`).
55
- */
56
- uploadAdapter: ChatUploadAdapter;
57
- };
58
17
  /**
59
18
  * Pluggable mention system config. When attached to ChatCoreConfig, the
60
19
  * composer enables `@`-trigger autocomplete and the message renderer parses
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AACvC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,KAAK,EACV,cAAc,EACd,aAAa,EACb,eAAe,EACf,UAAU,EACV,qBAAqB,EACtB,MAAM,4BAA4B,CAAC;AAMpC,sEAAsE;AACtE,MAAM,MAAM,qBAAqB,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM,IAAI,CACjE,GAAG,EAAE,UAAU,CAAC,KAAK,CAAC,KACnB,SAAS,CAAC;AAEf;;;;GAIG;AACH,MAAM,MAAM,yBAAyB,CACnC,KAAK,SAAS,MAAM,GAAG,MAAM,EAC7B,QAAQ,GAAG,OAAO,IAChB,eAAe,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG;IACrC;;;OAGG;IACH,YAAY,CAAC,EAAE,qBAAqB,CAAC,KAAK,CAAC,CAAC;CAC7C,CAAC;AAMF;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,+EAA+E;IAC/E,QAA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C;;;;OAIG;IACH,UAAU,EAAE,cAAc,CAAC;IAC3B;;OAEG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAChC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,aAAa,CAAC,EAAE,iBAAiB,CAAC;CACnC,CAAC;AAMF,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,EAAE,aAAa,KAAK,SAAS,CAAC;AAE9D,MAAM,MAAM,uBAAuB,GAAG,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,6EAA6E;AAC7E,4DAA4D","sourcesContent":["// React- and Firebase-client-coupled chat types. These were previously on the\n// chat-core root; they live here so the pure chat-core package stays free of\n// react / firebase/firestore / firebase/storage references.\n\nimport type { FirebaseStorage } from \"firebase/storage\";\nimport type { ReactNode } from \"react\";\nimport type { MediaOriginSpec } from \"@ttt-productions/media-schemas\";\nimport type {\n ChatAccessMode,\n ChatMessageV1,\n MentionProvider,\n MentionRef,\n RecentMentionsAdapter,\n} from \"@ttt-productions/chat-core\";\n\n// ============================================\n// MENTION RENDER TYPES (React-coupled)\n// ============================================\n\n/** Custom renderer for a single autocomplete row / mention result. */\nexport type MentionResultRenderer<TKind extends string = string> = (\n ref: MentionRef<TKind>,\n) => ReactNode;\n\n/**\n * A pure {@link MentionProvider} augmented with optional React row rendering.\n * The autocomplete UI consumes this; the pure provider contract (search) lives\n * in @ttt-productions/chat-core.\n */\nexport type RenderableMentionProvider<\n TKind extends string = string,\n TContext = unknown,\n> = MentionProvider<TKind, TContext> & {\n /**\n * Optional custom row UI. When omitted, the autocomplete renders the\n * `displayText` plain.\n */\n renderResult?: MentionResultRenderer<TKind>;\n};\n\n// ============================================\n// CHAT UPLOAD ADAPTER (injected into ChatAttachmentConfig)\n// ============================================\n\n/**\n * Pluggable upload-path strategy for chat attachments.\n *\n * Consumers supply this to tell the composer (a) what opaque origin identifier\n * to record for the upload, (b) how to build the Firebase Storage path for the\n * temporary upload, and (c) optional extra metadata to attach to the Storage\n * object.\n *\n * `buildUploadPath` and `buildUploadMetadata` receive the userId and\n * attachmentId so consumers can interpolate them per their own conventions.\n * The composer does not interpret `originId` — it forwards it via callbacks\n * and uses it for adapter identity only.\n */\nexport type ChatUploadAdapter = {\n /** Opaque origin identifier (e.g. \"chat-attachment\"). Not interpreted here. */\n originId: string;\n /** Build the Firebase Storage path for the upload. Called once per attachment. */\n buildUploadPath: (args: { userId: string; attachmentId: string }) => string;\n /** Optional extra metadata merged onto the Storage object metadata (e.g. customMetadata). */\n buildUploadMetadata?: (args: { userId: string; attachmentId: string }) => Record<string, unknown>;\n};\n\n// ============================================\n// ATTACHMENT CONFIG (passed through ChatShell → Composer)\n// ============================================\n\nexport type ChatAttachmentConfig = {\n attachmentSpec: MediaOriginSpec;\n storage: FirebaseStorage;\n /** The current user's auth uid. Forwarded to `uploadAdapter` callbacks. */\n userId: string;\n /**\n * Pluggable upload-path strategy. Consumers wire this to their app's\n * conventions (for example: originId \"chat-attachment\", path\n * `uploads/chat-attachment/{userId}/{attachmentId}`).\n */\n uploadAdapter: ChatUploadAdapter;\n};\n\n// ============================================\n// MENTION SYSTEM CONFIG (passed through ChatShell → Composer)\n// ============================================\n\n/**\n * Pluggable mention system config. When attached to ChatCoreConfig, the\n * composer enables `@`-trigger autocomplete and the message renderer parses\n * mention tokens out of `text`.\n *\n * Generic over `TKind` and `TContext` is intentionally NOT exposed here at the\n * type level — `ChatCoreConfig` would have to become generic too, which\n * cascades. Instead this type accepts permissive `string`-keyed providers;\n * consumers binding stricter kind unions narrow at the call site via their\n * provider definitions.\n */\nexport type ChatMentionConfig = {\n /** Providers in display order. */\n providers: RenderableMentionProvider<string, unknown>[];\n /** Context object forwarded to every provider's `search`. */\n context: unknown;\n /** Optional recent-mentions adapter. */\n recent?: RecentMentionsAdapter<string>;\n /** Trigger character. Defaults to `'@'`. */\n trigger?: string;\n /** Minimum query length before search fires. Default: 0. */\n minQueryLength?: number;\n /** Search debounce window in ms. Default: 200. */\n searchDebounceMs?: number;\n /**\n * Optional custom renderer for mentions inside rendered message text.\n * When omitted, the default chip (`<span class=\"chat-mention-chip\">`) is\n * used. Receives the resolved MentionRef.\n */\n renderMention?: (ref: MentionRef) => ReactNode;\n};\n\n// ============================================\n// CONFIG\n// ============================================\n\n/**\n * Which transport backs a chat thread.\n * - `firestore` — the current Firestore newest-window + cursor path (default).\n * - `realtime` — the Cloudflare Durable Object socket (chat-edge-rebuild). On\n * this transport DATA ACCESS is enforced by the DO grant, so `accessMode`\n * becomes PRESENTATION-ONLY (UI affordances like read-only), never a\n * data-access gate.\n */\nexport type ChatTransportMode = 'firestore' | 'realtime';\n\n/**\n * Realtime (Durable Object) transport handle. The concrete socket client is built\n * in this package (`realtime/transport.ts`); chat-react consumes it through this\n * config so the UI stays transport-agnostic. The app builds the `client` via\n * `createRealtimeChatClient({ endpoint, channelRef, grantProvider, ... })` and\n * passes it here. `channelRef`/`client` stay structurally typed (`unknown` at the\n * config seam) so `ChatCoreConfig` does not pull the realtime module's types into\n * every firestore consumer — the realtime hook narrows them at the call site.\n */\nexport interface ChatRealtimeTransportConfig {\n /** Opaque channel reference the socket is scoped to (guild channel / invite thread). */\n channelRef: unknown;\n /**\n * The realtime client handle from `createRealtimeChatClient(...)`. Drives the\n * channel socket (subscribe / send / ack / typing / presence / history). The UI\n * never reaches into the socket directly — it goes through `useRealtimeChatMessages`.\n */\n client: unknown;\n}\n\nexport type ChatCoreConfig = {\n chatCollectionPath: string | string[];\n messagesSubcollection?: string; // default: \"messages\"\n threadId: string;\n currentUserId: string;\n currentUserDisplayName?: string;\n isAdmin: boolean;\n /**\n * Which transport backs this thread. Defaults to `'firestore'` (the current\n * path) so existing call sites are unchanged. See {@link ChatTransportMode}.\n */\n transport?: ChatTransportMode;\n /** Required iff `transport === 'realtime'`; ignored on the firestore transport. */\n realtime?: ChatRealtimeTransportConfig;\n /**\n * The Firestore data-access gate (see ChatAccessMode docs in\n * @ttt-productions/chat-core). REQUIRED. On the `realtime` transport this is\n * PRESENTATION-ONLY — the DO grant is the real data-access authority.\n */\n accessMode: ChatAccessMode;\n /**\n * Required iff accessMode === \"explicit-allowlist\". Ignored otherwise.\n */\n threadAllowedUserIds?: string[];\n createdAtField?: string; // default: \"createdAt\"\n pageSize?: number;\n /**\n * Optional mention system configuration. When present, the composer enables\n * `@`-trigger autocomplete using the supplied providers and renders mention\n * chips in messages. Each provider corresponds to one mention kind.\n */\n mentionConfig?: ChatMentionConfig;\n};\n\n// ============================================\n// RENDERING\n// ============================================\n\nexport type MessageRenderer = (m: ChatMessageV1) => ReactNode;\n\nexport type MessageRendererRegistry = Record<string, MessageRenderer>;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,6EAA6E;AAC7E,4DAA4D","sourcesContent":["// React- and Firebase-client-coupled chat types. These were previously on the\n// chat-core root; they live here so the pure chat-core package stays free of\n// react / firebase/firestore / firebase/storage references.\n\nimport type { ReactNode } from \"react\";\nimport type {\n ChatAccessMode,\n ChatMessageV1,\n MentionProvider,\n MentionRef,\n RecentMentionsAdapter,\n} from \"@ttt-productions/chat-core\";\n\n// ============================================\n// MENTION RENDER TYPES (React-coupled)\n// ============================================\n\n/** Custom renderer for a single autocomplete row / mention result. */\nexport type MentionResultRenderer<TKind extends string = string> = (\n ref: MentionRef<TKind>,\n) => ReactNode;\n\n/**\n * A pure {@link MentionProvider} augmented with optional React row rendering.\n * The autocomplete UI consumes this; the pure provider contract (search) lives\n * in @ttt-productions/chat-core.\n */\nexport type RenderableMentionProvider<\n TKind extends string = string,\n TContext = unknown,\n> = MentionProvider<TKind, TContext> & {\n /**\n * Optional custom row UI. When omitted, the autocomplete renders the\n * `displayText` plain.\n */\n renderResult?: MentionResultRenderer<TKind>;\n};\n\n// ============================================\n// MENTION SYSTEM CONFIG (passed through ChatShell → Composer)\n// ============================================\n//\n// Chat carries TEXT only. There is no upload adapter or attachment config here:\n// a conversation's files are owned by the consuming app's Conversation Files\n// surface, which runs the canonical upload pipeline outside the chat timeline.\n\n/**\n * Pluggable mention system config. When attached to ChatCoreConfig, the\n * composer enables `@`-trigger autocomplete and the message renderer parses\n * mention tokens out of `text`.\n *\n * Generic over `TKind` and `TContext` is intentionally NOT exposed here at the\n * type level — `ChatCoreConfig` would have to become generic too, which\n * cascades. Instead this type accepts permissive `string`-keyed providers;\n * consumers binding stricter kind unions narrow at the call site via their\n * provider definitions.\n */\nexport type ChatMentionConfig = {\n /** Providers in display order. */\n providers: RenderableMentionProvider<string, unknown>[];\n /** Context object forwarded to every provider's `search`. */\n context: unknown;\n /** Optional recent-mentions adapter. */\n recent?: RecentMentionsAdapter<string>;\n /** Trigger character. Defaults to `'@'`. */\n trigger?: string;\n /** Minimum query length before search fires. Default: 0. */\n minQueryLength?: number;\n /** Search debounce window in ms. Default: 200. */\n searchDebounceMs?: number;\n /**\n * Optional custom renderer for mentions inside rendered message text.\n * When omitted, the default chip (`<span class=\"chat-mention-chip\">`) is\n * used. Receives the resolved MentionRef.\n */\n renderMention?: (ref: MentionRef) => ReactNode;\n};\n\n// ============================================\n// CONFIG\n// ============================================\n\n/**\n * Which transport backs a chat thread.\n * - `firestore` — the current Firestore newest-window + cursor path (default).\n * - `realtime` — the Cloudflare Durable Object socket (chat-edge-rebuild). On\n * this transport DATA ACCESS is enforced by the DO grant, so `accessMode`\n * becomes PRESENTATION-ONLY (UI affordances like read-only), never a\n * data-access gate.\n */\nexport type ChatTransportMode = 'firestore' | 'realtime';\n\n/**\n * Realtime (Durable Object) transport handle. The concrete socket client is built\n * in this package (`realtime/transport.ts`); chat-react consumes it through this\n * config so the UI stays transport-agnostic. The app builds the `client` via\n * `createRealtimeChatClient({ endpoint, channelRef, grantProvider, ... })` and\n * passes it here. `channelRef`/`client` stay structurally typed (`unknown` at the\n * config seam) so `ChatCoreConfig` does not pull the realtime module's types into\n * every firestore consumer — the realtime hook narrows them at the call site.\n */\nexport interface ChatRealtimeTransportConfig {\n /** Opaque channel reference the socket is scoped to (guild channel / invite thread). */\n channelRef: unknown;\n /**\n * The realtime client handle from `createRealtimeChatClient(...)`. Drives the\n * channel socket (subscribe / send / ack / typing / presence / history). The UI\n * never reaches into the socket directly — it goes through `useRealtimeChatMessages`.\n */\n client: unknown;\n}\n\nexport type ChatCoreConfig = {\n chatCollectionPath: string | string[];\n messagesSubcollection?: string; // default: \"messages\"\n threadId: string;\n currentUserId: string;\n currentUserDisplayName?: string;\n isAdmin: boolean;\n /**\n * Which transport backs this thread. Defaults to `'firestore'` (the current\n * path) so existing call sites are unchanged. See {@link ChatTransportMode}.\n */\n transport?: ChatTransportMode;\n /** Required iff `transport === 'realtime'`; ignored on the firestore transport. */\n realtime?: ChatRealtimeTransportConfig;\n /**\n * The Firestore data-access gate (see ChatAccessMode docs in\n * @ttt-productions/chat-core). REQUIRED. On the `realtime` transport this is\n * PRESENTATION-ONLY — the DO grant is the real data-access authority.\n */\n accessMode: ChatAccessMode;\n /**\n * Required iff accessMode === \"explicit-allowlist\". Ignored otherwise.\n */\n threadAllowedUserIds?: string[];\n createdAtField?: string; // default: \"createdAt\"\n pageSize?: number;\n /**\n * Optional mention system configuration. When present, the composer enables\n * `@`-trigger autocomplete using the supplied providers and renders mention\n * chips in messages. Each provider corresponds to one mention kind.\n */\n mentionConfig?: ChatMentionConfig;\n};\n\n// ============================================\n// RENDERING\n// ============================================\n\nexport type MessageRenderer = (m: ChatMessageV1) => ReactNode;\n\nexport type MessageRendererRegistry = Record<string, MessageRenderer>;\n"]}
@@ -1,6 +1,6 @@
1
1
  import * as React from "react";
2
- import type { ChatMessageV1, SendAttachmentFn, ModerationHandlers } from "@ttt-productions/chat-core";
3
- import type { ChatCoreConfig, ChatAttachmentConfig, MessageRendererRegistry } from "../types.js";
2
+ import type { ChatMessageV1, ModerationHandlers } from "@ttt-productions/chat-core";
3
+ import type { ChatCoreConfig, MessageRendererRegistry } from "../types.js";
4
4
  export type ChatShellProps = {
5
5
  config: ChatCoreConfig;
6
6
  header?: React.ReactNode;
@@ -8,8 +8,6 @@ export type ChatShellProps = {
8
8
  renderMessage?: (m: any) => React.ReactNode;
9
9
  messageRenderers?: MessageRendererRegistry;
10
10
  handlers?: ModerationHandlers;
11
- attachmentConfig?: ChatAttachmentConfig;
12
- sendAttachment?: SendAttachmentFn;
13
11
  composerPlaceholder?: string;
14
12
  autoFocus?: boolean;
15
13
  renderAboveMessages?: () => React.ReactNode;
@@ -1 +1 @@
1
- {"version":3,"file":"ChatShell.d.ts","sourceRoot":"","sources":["../../src/ui/ChatShell.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACtG,OAAO,KAAK,EACV,cAAc,EACd,oBAAoB,EACpB,uBAAuB,EACxB,MAAM,aAAa,CAAC;AAYrB,MAAM,MAAM,cAAc,GAAG;IAC3B,MAAM,EAAE,cAAc,CAAC;IAGvB,MAAM,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;IAKzB,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAG7E,aAAa,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,KAAK,CAAC,SAAS,CAAC;IAC5C,gBAAgB,CAAC,EAAE,uBAAuB,CAAC;IAC3C,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAG9B,gBAAgB,CAAC,EAAE,oBAAoB,CAAC;IACxC,cAAc,CAAC,EAAE,gBAAgB,CAAC;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AAE,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,EAAE,WAAW,EAAE,MAAM,KAAK,IAAI,CAAC;IAGhE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;6FAGyF;IACzF,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;qDACiD;IACjD,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AA0BF;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,cAAc,qBAK9C"}
@@ -66,24 +66,13 @@ function RealtimeChatShell(props) {
66
66
  } }));
67
67
  }
68
68
  function ChatShellView(props) {
69
- const { config, header, renderMessage, messageRenderers, handlers, attachmentConfig, sendAttachment, composerPlaceholder, autoFocus = false, renderAboveMessages, renderBelowMessages, renderFooter, onSenderClick, composerDisabled, fillHeight = false, scrollClassName, resolved, } = props;
69
+ const { config, header, renderMessage, messageRenderers, handlers, composerPlaceholder, autoFocus = false, renderAboveMessages, renderBelowMessages, renderFooter, onSenderClick, composerDisabled, fillHeight = false, scrollClassName, resolved, } = props;
70
70
  const { allowed, isInitialLoading, messages, fetchOlder, hasOlder, isFetchingOlder, send, retrySend, readAck, status, typing, signalTyping } = resolved;
71
71
  const [showScrollToBottom, setShowScrollToBottom] = React.useState(false);
72
72
  const [atBottom, setAtBottom] = React.useState(true);
73
73
  const [focused, setFocused] = React.useState(true);
74
74
  const lastAckedRef = React.useRef(0);
75
75
  const leaseHeldRef = React.useRef(false);
76
- // A terminally-failed attachment bubble re-opens the canonical picker through the
77
- // Composer's imperative handle. The action is offered only when attachment support
78
- // is actually configured AND the default Composer is rendered (a custom renderFooter
79
- // replaces it, so the picker would not exist). The new file then rides the ordinary
80
- // Composer → guarded-upload flow with a fresh id — never reusing a storage path or
81
- // mutating the terminal row.
82
- const composerRef = React.useRef(null);
83
- const attachmentSupported = Boolean(attachmentConfig && sendAttachment && !renderFooter);
84
- const handleRetryAttachment = React.useCallback(() => {
85
- composerRef.current?.openAttachmentSelector();
86
- }, []);
87
76
  // The latest authoritative seq currently rendered (optimistic rows have no seq).
88
77
  const latestSeq = React.useMemo(() => {
89
78
  let max = 0;
@@ -146,9 +135,15 @@ function ChatShellView(props) {
146
135
  // footer all still render, because a consumer that hangs critical controls off those
147
136
  // slots (e.g. the guild-invite binding-agreement Agree/Decline/stake-share controls)
148
137
  // must work whether or not realtime chat has connected yet (F4.1).
149
- 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 }) })] })), renderAboveMessages && (_jsx("div", { className: "border-b", children: renderAboveMessages() })), _jsx(CardContent, { className: contentClassName, children: _jsxs("div", { className: "flex flex-col items-center justify-center gap-2 py-12 text-sm text-muted-foreground", role: "status", "aria-live": "polite", children: [_jsx(Loader2, { className: "h-5 w-5 animate-spin", "aria-hidden": "true" }), _jsx("span", { children: "Opening chat\u2026" })] }) }), renderBelowMessages && (_jsx("div", { className: "border-t", children: renderBelowMessages() })), renderFooter ? (_jsx(CardFooter, { className: "border-t", children: renderFooter() })) : (_jsx(CardFooter, { className: "border-t", children: _jsx(Skeleton, { className: "h-10 w-full" }) }))] }));
138
+ 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 }) })] })), (() => {
139
+ // The wrapper (and its border) renders only when the slot actually
140
+ // produced content — a slot returning null (e.g. a collapsed
141
+ // conversation-files section) must not paint an empty bordered strip.
142
+ const aboveMessages = renderAboveMessages?.() ?? null;
143
+ return aboveMessages != null && aboveMessages !== false ? (_jsx("div", { className: "border-b", children: aboveMessages })) : null;
144
+ })(), _jsx(CardContent, { className: contentClassName, children: _jsxs("div", { className: "flex flex-col items-center justify-center gap-2 py-12 text-sm text-muted-foreground", role: "status", "aria-live": "polite", children: [_jsx(Loader2, { className: "h-5 w-5 animate-spin", "aria-hidden": "true" }), _jsx("span", { children: "Opening chat\u2026" })] }) }), renderBelowMessages && (_jsx("div", { className: "border-t", children: renderBelowMessages() })), renderFooter ? (_jsx(CardFooter, { className: "border-t", children: renderFooter() })) : (_jsx(CardFooter, { className: "border-t", children: _jsx(Skeleton, { className: "h-10 w-full" }) }))] }));
150
145
  }
151
- 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 }) })] })), _jsx(ChatConnectionBanner, { status: status }), renderAboveMessages && (_jsx("div", { className: "border-b", children: renderAboveMessages() })), _jsx(CardContent, { className: contentClassName, children: _jsx(MessageList, { messages: messages, currentUserId: config.currentUserId, isAdmin: config.isAdmin, isFetchingOlder: isFetchingOlder, hasOlder: hasOlder, onLoadOlder: () => fetchOlder(), renderMessage: renderMessage, messageRenderers: messageRenderers, showScrollToBottom: showScrollToBottom, onScrollToBottom: () => setShowScrollToBottom(false), onAtBottomChange: setAtBottom, fillHeight: fillHeight, scrollClassName: scrollClassName, handlers: handlers, onSenderClick: onSenderClick, onRetrySend: retrySend, onRetryAttachment: attachmentSupported ? handleRetryAttachment : undefined }) }), renderBelowMessages && (_jsx("div", { className: "border-t", children: renderBelowMessages() })), renderFooter ? (_jsx(CardFooter, { className: "border-t", children: renderFooter() })) : (_jsxs(CardFooter, { className: "border-t flex-col items-stretch gap-1", children: [_jsx(TypingIndicator, { typing: typing }), _jsx(KeyboardAvoidingView, { padding: true, offset: 8, className: "w-full", children: _jsx(Composer, { ref: composerRef, onSend: send, onTyping: signalTyping, attachmentConfig: attachmentConfig, sendAttachment: sendAttachment, disabled: composerDisabled, autoFocus: autoFocus, placeholder: composerPlaceholder, mentionConfig: config.mentionConfig }) })] }))] }));
146
+ 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 }) })] })), _jsx(ChatConnectionBanner, { status: status }), renderAboveMessages && (_jsx("div", { className: "border-b", children: renderAboveMessages() })), _jsx(CardContent, { className: contentClassName, children: _jsx(MessageList, { messages: messages, currentUserId: config.currentUserId, isAdmin: config.isAdmin, isFetchingOlder: isFetchingOlder, hasOlder: hasOlder, onLoadOlder: () => fetchOlder(), renderMessage: renderMessage, messageRenderers: messageRenderers, showScrollToBottom: showScrollToBottom, onScrollToBottom: () => setShowScrollToBottom(false), onAtBottomChange: setAtBottom, fillHeight: fillHeight, scrollClassName: scrollClassName, handlers: handlers, onSenderClick: onSenderClick, onRetrySend: retrySend }) }), renderBelowMessages && (_jsx("div", { className: "border-t", children: renderBelowMessages() })), renderFooter ? (_jsx(CardFooter, { className: "border-t", children: renderFooter() })) : (_jsxs(CardFooter, { className: "border-t flex-col items-stretch gap-1", children: [_jsx(TypingIndicator, { typing: typing }), _jsx(KeyboardAvoidingView, { padding: true, offset: 8, className: "w-full", children: _jsx(Composer, { onSend: send, onTyping: signalTyping, disabled: composerDisabled, autoFocus: autoFocus, placeholder: composerPlaceholder, mentionConfig: config.mentionConfig }) })] }))] }));
152
147
  }
153
148
  /**
154
149
  * R13 — connection-state banner. The realtime path sets `status`; once the first
@@ -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;AAO/B,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AACrG,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AAEjF,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAsE3C;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,KAAqB;IAC7C,IAAI,KAAK,CAAC,MAAM,CAAC,SAAS,KAAK,UAAU,EAAE,CAAC;QAC1C,OAAO,KAAC,iBAAiB,OAAK,KAAK,GAAI,CAAC;IAC1C,CAAC;IACD,OAAO,KAAC,kBAAkB,OAAK,KAAK,GAAI,CAAC;AAC3C,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAqB;IAC/C,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IACjC,MAAM,CAAC,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;IAClC,MAAM,IAAI,GAAG,KAAK,CAAC,WAAW,CAC5B,KAAK,EAAE,IAAY,EAAE,OAAkC,EAAE,EA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A6C,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, SendAttachmentFn, ModerationHandlers } from \"@ttt-productions/chat-core\";\nimport type {\n ChatCoreConfig,\n ChatAttachmentConfig,\n MessageRendererRegistry,\n} from \"../types.js\";\nimport { Card, CardHeader, CardContent, CardFooter, Skeleton } from \"@ttt-productions/ui-core/react\";\nimport { KeyboardAvoidingView } from \"@ttt-productions/mobile-core/react\";\nimport { Loader2 } from \"lucide-react\";\nimport { useChatMessages } from \"../hooks/useChatMessages.js\";\nimport { useRealtimeChatMessages } from \"../realtime/useRealtimeChatMessages.js\";\nimport type { RealtimeChatClient } from \"../realtime/transport.js\";\nimport { MessageList } from \"./MessageList.js\";\nimport { Composer } from \"./Composer.js\";\nimport type { ComposerHandle } from \"./Composer.js\";\nimport { ThreadActions } from \"./menus.js\";\n\nexport type ChatShellProps = {\n config: ChatCoreConfig;\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, replyTo?: ChatMessageV1[\"replyTo\"]) => Promise<void>;\n\n // Message rendering\n renderMessage?: (m: any) => React.ReactNode;\n messageRenderers?: MessageRendererRegistry;\n handlers?: ModerationHandlers;\n\n // Composer attachment config\n attachmentConfig?: ChatAttachmentConfig;\n sendAttachment?: SendAttachmentFn;\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, displayName: 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};\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 send handler the Composer calls (socket send on realtime, prop on firestore). */\n send: (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => 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, replyTo?: ChatMessageV1[\"replyTo\"]) => {\n if (onSend) await onSend(text, replyTo);\n },\n [onSend],\n );\n return <ChatShellView {...props} resolved={{ ...r, send }} />;\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 send = React.useCallback(\n async (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => {\n // Map the UI replyTo (messageId-based) to the wire replyTo (seq + preview).\n const wireReply =\n replyTo && replyTo.messageId\n ? { messageSeq: Number(replyTo.messageId), preview: replyTo.messagePreview ?? \"\" }\n : null;\n const ok = r.send(text, Number.isFinite(wireReply?.messageSeq) ? wireReply : null);\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, replyTo); // optional mirror\n },\n [r, onSend],\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 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 attachmentConfig,\n sendAttachment,\n composerPlaceholder,\n autoFocus = false,\n renderAboveMessages,\n renderBelowMessages,\n renderFooter,\n onSenderClick,\n composerDisabled,\n fillHeight = false,\n scrollClassName,\n resolved,\n } = props;\n\n const { allowed, isInitialLoading, messages, fetchOlder, hasOlder, isFetchingOlder, send, retrySend, readAck, status, typing, signalTyping } = resolved;\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 // A terminally-failed attachment bubble re-opens the canonical picker through the\n // Composer's imperative handle. The action is offered only when attachment support\n // is actually configured AND the default Composer is rendered (a custom renderFooter\n // replaces it, so the picker would not exist). The new file then rides the ordinary\n // Composer → guarded-upload flow with a fresh id — never reusing a storage path or\n // mutating the terminal row.\n const composerRef = React.useRef<ComposerHandle>(null);\n const attachmentSupported = Boolean(attachmentConfig && sendAttachment && !renderFooter);\n const handleRetryAttachment = React.useCallback(() => {\n composerRef.current?.openAttachmentSelector();\n }, []);\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&apos;t have access to this thread.</div>;\n }\n\n if (isInitialLoading) {\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 {renderAboveMessages && (\n <div className=\"border-b\">{renderAboveMessages()}</div>\n )}\n <CardContent className={contentClassName}>\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 <Loader2 className=\"h-5 w-5 animate-spin\" aria-hidden=\"true\" />\n <span>Opening chat…</span>\n </div>\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 <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 handlers={handlers}\n onSenderClick={onSenderClick}\n onRetrySend={retrySend}\n onRetryAttachment={attachmentSupported ? handleRetryAttachment : undefined}\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 ref={composerRef}\n onSend={send}\n onTyping={signalTyping}\n attachmentConfig={attachmentConfig}\n sendAttachment={sendAttachment}\n disabled={composerDisabled}\n autoFocus={autoFocus}\n placeholder={composerPlaceholder}\n mentionConfig={config.mentionConfig}\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,MAAM,gCAAgC,CAAC;AACrG,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OA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AAgB,EAC1B,SAAS,EAAE,SAAS,EACpB,WAAW,EAAE,mBAAmB,EAChC,aAAa,EAAE,MAAM,CAAC,aAAa,GACnC,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 } from \"@ttt-productions/ui-core/react\";\nimport { KeyboardAvoidingView } from \"@ttt-productions/mobile-core/react\";\nimport { Loader2 } from \"lucide-react\";\nimport { useChatMessages } from \"../hooks/useChatMessages.js\";\nimport { useRealtimeChatMessages } from \"../realtime/useRealtimeChatMessages.js\";\nimport type { RealtimeChatClient } from \"../realtime/transport.js\";\nimport { MessageList } from \"./MessageList.js\";\nimport { Composer } from \"./Composer.js\";\nimport { ThreadActions } from \"./menus.js\";\n\nexport type ChatShellProps = {\n config: ChatCoreConfig;\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, replyTo?: ChatMessageV1[\"replyTo\"]) => 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, displayName: 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};\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 send handler the Composer calls (socket send on realtime, prop on firestore). */\n send: (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => 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, replyTo?: ChatMessageV1[\"replyTo\"]) => {\n if (onSend) await onSend(text, replyTo);\n },\n [onSend],\n );\n return <ChatShellView {...props} resolved={{ ...r, send }} />;\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 send = React.useCallback(\n async (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => {\n // Map the UI replyTo (messageId-based) to the wire replyTo (seq + preview).\n const wireReply =\n replyTo && replyTo.messageId\n ? { messageSeq: Number(replyTo.messageId), preview: replyTo.messagePreview ?? \"\" }\n : null;\n const ok = r.send(text, Number.isFinite(wireReply?.messageSeq) ? wireReply : null);\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, replyTo); // optional mirror\n },\n [r, onSend],\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 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 resolved,\n } = props;\n\n const { allowed, isInitialLoading, messages, fetchOlder, hasOlder, isFetchingOlder, send, retrySend, readAck, status, typing, signalTyping } = resolved;\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&apos;t have access to this thread.</div>;\n }\n\n if (isInitialLoading) {\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 <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 <Loader2 className=\"h-5 w-5 animate-spin\" aria-hidden=\"true\" />\n <span>Opening chat…</span>\n </div>\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 <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 handlers={handlers}\n onSenderClick={onSenderClick}\n onRetrySend={retrySend}\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 mentionConfig={config.mentionConfig}\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,10 +1,10 @@
1
1
  import * as React from "react";
2
- import type { ChatMessageV1, SendAttachmentFn } from "@ttt-productions/chat-core";
3
- import type { ChatAttachmentConfig } from "../types.js";
2
+ import type { ChatMessageV1 } from "@ttt-productions/chat-core";
4
3
  export type ComposerProps = {
5
4
  /**
6
- * Text-only send. Composer calls this when there is no pending attachment.
7
- * Consumer creates the message doc. Return value is ignored.
5
+ * Text send. The composer is TEXT-ONLY — files are shared through the
6
+ * conversation's Conversation Files surface, never through the message
7
+ * timeline, so there is no attachment path here.
8
8
  */
9
9
  onSend: (text: string, replyTo?: ChatMessageV1["replyTo"]) => Promise<void>;
10
10
  /**
@@ -13,33 +13,10 @@ export type ComposerProps = {
13
13
  * Optional — absent on the firestore transport (no typing broadcast).
14
14
  */
15
15
  onTyping?: () => void;
16
- attachmentConfig?: ChatAttachmentConfig;
17
- /**
18
- * Attachment send. Composer uploads the file to Storage first, then calls
19
- * this with the resulting metadata. Consumer wires it to a backend callable
20
- * (`startUpload`) that writes the pendingMedia doc. The processor creates
21
- * the message doc after moderation succeeds.
22
- * Required for attachment functionality.
23
- */
24
- sendAttachment?: SendAttachmentFn;
25
16
  disabled?: boolean;
26
17
  autoFocus?: boolean;
27
18
  placeholder?: string;
28
19
  mentionConfig?: import('../types.js').ChatMentionConfig;
29
20
  };
30
- /**
31
- * Imperative handle exposed by {@link Composer} via `ref`. Additive — ref-less
32
- * usage is unaffected. ChatShell holds this ref so a failed-attachment bubble's
33
- * "Attach again" action can re-open the canonical picker.
34
- */
35
- export type ComposerHandle = {
36
- /**
37
- * Open the attachment picker, delegating to the underlying MediaInput's
38
- * `openSelection()`. Must be called synchronously from a user gesture. No-op
39
- * when attachments are not configured (the MediaInput is not mounted) or the
40
- * composer is disabled/sending (MediaInput's own gate no-ops it).
41
- */
42
- openAttachmentSelector: () => void;
43
- };
44
- export declare const Composer: React.ForwardRefExoticComponent<ComposerProps & React.RefAttributes<ComposerHandle>>;
21
+ export declare function Composer(props: ComposerProps): React.JSX.Element;
45
22
  //# sourceMappingURL=Composer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Composer.d.ts","sourceRoot":"","sources":["../../src/ui/Composer.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAU/B,OAAO,KAAK,EAAkB,aAAa,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAClG,OAAO,KAAK,EAAE,oBAAoB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