chats 0.5.0 → 0.5.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 709f9d9d48f89eaac706a8c974cdfdb05ac89ed02a15677874be21dcd069c951
4
- data.tar.gz: b5fcf75df095a3aaf34016e056fbc662def488efcfe502fa797745ac807d0183
3
+ metadata.gz: 233373c7319647cf267ec239c0227e7751deae6ea9a4afd8d94c578994c85a22
4
+ data.tar.gz: 02b7e37be81c69063969d202094430b1657640ea707a1f63e78c06876eb6877d
5
5
  SHA512:
6
- metadata.gz: '09ef3d73a35fb2276770e14cf032925c2d4ebc80c4890e4bc21f3df72cc0ef6ef2ea11cb482ae570bba694dd1aa3047cac22b63b64bd99095bfcc738fe04b377'
7
- data.tar.gz: 424502a1634c16786c512f62f246e71f7655fdb11dc13a6386bd5767474b4fdb483e409d4c988258bce54d494eb71eecb52314d469c79ddaa96e0b2cbc8d26b0
6
+ metadata.gz: 9bd561feaae573165ce631dac3e669b892d5d70271435a475bc36d92dc532fcd6f55b0b908415141845b47105600088dd739ae7adfeb520baf4cb4bcc0096127
7
+ data.tar.gz: ecd69642c82c827c53b5d038b8dd60f5853f5b012368c5d4db846b4549befbd4fd8b153b45d0468228cd77746b77b6c60dadd26ab5d36f73f2a31a4ec84a2edd
data/CHANGELOG.md CHANGED
@@ -4,6 +4,237 @@ All notable changes to this project are documented here.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
5
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.5.1] - 2026-10-18
8
+
9
+ A page that missed a broadcast is never left stale: every live surface
10
+ catches up on its own, without polling (fixes
11
+ [#1](https://github.com/rameerez/chats/issues/1)). Also: the dock's unread
12
+ count in every language's plural forms, one extension point for a
13
+ conversation that must open although the inbox hides it
14
+ (`conversation_lookup_scopes`), and real conversations told from
15
+ system-only threads. **No migration, nothing to configure.**
16
+
17
+ ### Added
18
+ - **Real conversations vs system-only threads.** `with_messages` asks whether
19
+ a conversation holds anything at all, system lines and tombstones
20
+ included; ops walls, moderation lists and analytics ask whether a messager
21
+ wrote something there that still stands. Four additive reads answer that:
22
+ `Chats::Message.human` (kind `text`, not deleted: written by a messager,
23
+ person or not, as opposed to posted by the app, so a bot's or a headless
24
+ desk's text message counts and a photo with no caption counts too), `Chats::Conversation.with_human_messages` and
25
+ `.without_human_messages` (one correlated `EXISTS` / `NOT EXISTS` built
26
+ from `Message.human`, so they compose with `alice.chats`, `inbox_for`,
27
+ `about`, `unread_by` and `with_messages` and never multiply rows),
28
+ `Conversation#last_human_message` (a query, not the `last_message`
29
+ pointer), and its batch twin `Chats::Message.last_human_in(conversations)`:
30
+ the newest human message of each conversation in ONE query, for a loaded
31
+ page, ids, a single record, or an unloaded relation, which is read as a
32
+ subquery and never loaded first. It returns a relation, so a `.select` can
33
+ narrow the columns. Viewer-facing lists start from `alice.chats`, which
34
+ applies blocks and `config.inbox_scope`; the bare `Chats::Conversation`
35
+ scopes see every conversation and belong behind staff authorization.
36
+ Nothing changes by default: system messages still bump `messages_count`
37
+ and `last_message`, and the inbox still lists system-only threads.
38
+ - **`Chats::ApplicationController#conversation_lookup_scopes`, the one
39
+ extension point for a conversation that must open although the inbox
40
+ hides it.** Every engine endpoint (the thread, a dock window, sending,
41
+ editing, reacting, reading) finds a conversation through
42
+ `find_conversation(id)`, which now asks each relation
43
+ `conversation_lookup_scopes` returns, in order (`find_by(id:)`), and
44
+ raises `ActiveRecord::RecordNotFound` when none has it. By default that is
45
+ `[chats_current_messager.chats]`, exactly the old lookup. A product gem
46
+ (support_desk: a requester's own ticket, which the host's `inbox_scope`
47
+ keeps out of the inbox) prepends a module whose
48
+ `conversation_lookup_scopes` returns `super + [its own scope]`, instead of
49
+ re-implementing the lookup and recognising a miss by the exception's
50
+ details. Later scopes are asked only on a miss; each scope must hold only
51
+ conversations the viewer may open, so nothing outside them becomes
52
+ reachable; and an error a scope raises is not rescued into a 404.
53
+
54
+ ### Fixed
55
+ - **The dock's window count used the right plural form only in two-form
56
+ languages.** `dock_controller.js` picked `one` for exactly 1 and `other`
57
+ for everything else, so Polish, Russian, Ukrainian, Croatian or Serbian
58
+ (one/few/many, with 21 read like 1 in the East Slavic ones) and
59
+ Arabic-style zero/two read wrong. The dock now renders every plural form
60
+ the locale provides for `chats.dock.window_unread` (`zero`, `one`, `two`,
61
+ `few`, `many`, `other`; new helper `chats_plural_forms`), and the
62
+ controller picks one with `Intl.PluralRules` in the page's language
63
+ (`<html lang>`, else the browser's), reading a missing form as `other`
64
+ and falling back to the old rule where `Intl` is unavailable. The gem's
65
+ `en` and `es` keep `one`/`other`; a host adds the forms its languages need
66
+ in its own locale files.
67
+ - **Every live surface catches up on the broadcasts it missed.** Action
68
+ Cable has no replay, so a broadcast sent while a page's socket was down
69
+ (a laptop asleep, a backgrounded tab or Hotwire Native WebView, a network
70
+ blip) never reached it, and the inbox, a thread, the unread badge or the
71
+ dock could sit on old content until the next navigation. One shared
72
+ module, `chats/recovery` (pinned for importmap hosts, like the
73
+ controllers), now watches each surface's own
74
+ `<turbo-cable-stream-source>` and the page, and asks for what was missed
75
+ when the stream reconnects, when the page comes back after 10 seconds or
76
+ more hidden, when the network comes back online (it asks Action Cable to
77
+ check its socket at once instead of after its backoff, and catches up
78
+ anyway: after a short outage the socket can look open while what was
79
+ sent during it is gone) and when the page
80
+ is restored from the back/forward cache or from Turbo's snapshot cache (a
81
+ back navigation, a Hotwire Native stack pop). Never otherwise: a healthy,
82
+ visible page fetches nothing. A hidden page never fetches; what it missed
83
+ waits until it is seen. Triggers that arrive together make one catch-up,
84
+ and catch-ups are at least five seconds apart.
85
+ - **A reconnect Action Cable never reported is seen.** When Action Cable
86
+ reopens a socket that went quiet (the half-open connection of a phone that
87
+ slept), it drops the old socket's handlers before its close event can
88
+ arrive: subscribers hear "connected" again and never "disconnected", and
89
+ the `reconnected: true` detail reaches only the first subscription
90
+ confirmed. Every confirmation after the first now counts.
91
+ - **A page restored from Turbo's snapshot cache catches up.** It came back
92
+ as old as when it was left, with no request: a thread restored by a back
93
+ navigation missed every message sent since. Its stream sources are marked
94
+ as they go into the cache, and a restored one catches up once it is live.
95
+ - **The inbox** reruns a refresh that arrived while another visit was
96
+ loading, which Turbo ignores (`Session#refresh` skips one while
97
+ `navigator.currentVisit` is set): a message landing mid-refresh was lost
98
+ with a healthy socket. A refresh no longer rewrites the field you're
99
+ typing in, no longer drops the search (see Changed), and a morph no longer
100
+ strips the stream source's `connected` attribute.
101
+ - **The inbox refresh is durable.** `refresh_inbox_of` enqueues
102
+ `Chats::InboxRefreshJob` straight from the after_commit instead of calling
103
+ `broadcast_refresh_later_to`, which parked the refresh for half a second
104
+ in an in-process timer (`Turbo::Debouncer`) before enqueueing it, so a
105
+ deploy or a crash inside that window dropped it. At most one is queued
106
+ per recipient: while one is queued and hasn't started, it stands for
107
+ every write that commits before it runs (a short-lived marker in
108
+ `Rails.cache`, removed by the job as it starts, before it broadcasts), so
109
+ a burst is one job per recipient. A lost marker costs an extra job, never
110
+ a missed refresh, and the marker expires after two seconds. Only a
111
+ marker that is really there counts as "queued": a store that can't hold
112
+ it (RedisCacheStore answers nil when a write fails; any store may raise)
113
+ means the write queues its own refresh. Since another
114
+ write may count on a refresh whose enqueue is still in flight, a failed
115
+ enqueue is retried once, then the refresh is broadcast on the spot. Every
116
+ refusal goes to `Rails.error` (raised, `false`, or a job the adapter
117
+ declined), never up through the write that committed. The refresh
118
+ tag carries `method="morph" scroll="preserve"`, so the inbox morphs
119
+ whatever the host layout's refresh meta says, and no request id, since
120
+ it may stand for several requests' writes.
121
+ - **The thread's catch-up asks on two cursors.** It sent only the newest
122
+ `updated_at` it had rendered and the server appended what was created
123
+ after it, so a message created at 10:15 and missed, while a bubble on
124
+ screen was edited at 10:20, never came. Now `after=` (the newest creation
125
+ on screen) decides what is appended and `changed=` (the newest change)
126
+ what is replaced, and both scopes split on the same creation cursor
127
+ (`created_after` / `created_through(…).updated_after(…)`). Each cursor is
128
+ a moment to the microsecond plus the ids on screen at it (`after_ids=`,
129
+ `changed_ids=`): a message missed in the very instant of one on screen,
130
+ or a change missed inside the same millisecond as one on screen (the old
131
+ cursor rounded up to the millisecond), is no longer lost. The cursors
132
+ are reconciled moments: a complete render sets them (the page, a window,
133
+ a history re-render), and so does a catch-up that arrived (its
134
+ `chats_caught_up` action); a live bubble never moves them, since it can
135
+ arrive after one that was missed (a message missed at 10:15, then one
136
+ live at 10:20). What arrived live is named instead, at most 200 ids
137
+ (`after_ids`, `changed_ids`, each id at most 64 characters); past that,
138
+ or with `full=1`, the history is re-rendered. Kept on the element
139
+ (`data-chats-reconciled`), so a dock window moved by a Turbo visit, or a
140
+ restored snapshot, keeps them. Each catch-up is bound to one render of
141
+ the thread (`render=`, echoed by the answer): an answer that arrives
142
+ after the page or a dock window rendered the conversation again is
143
+ dropped unrendered, and its cursors ignored — checked again by every
144
+ stream of it at the moment Turbo applies it, a repaint later, so a visit
145
+ or a window reload in between can't hand the old streams the new render.
146
+ A history re-render is followed by one more catch-up from its own
147
+ cursors once Turbo has actually applied it, however late that is, so a
148
+ message written while that page was being built isn't lost. Every
149
+ catch-up is bounded: a request with no answer after 15 seconds is
150
+ aborted (a fetch can hang across a network interruption, and would
151
+ otherwise stand in for every later one), a thread has at most one answer
152
+ waiting for Turbo (a newer one, or the thread going away, drops the
153
+ older one's leftover streams and stops watching for them — going away
154
+ for good: a dock window Turbo carries across a visit is off the page
155
+ until that render ends, which a host's asynchronous `turbo:before-render`
156
+ can make last many tasks, and keeps its answer, decided only once every
157
+ `turbo:before-render` has had its `turbo:render`, paired first in, first
158
+ out; a render that runs past 10 seconds stops holding things up but stays
159
+ paired until its own end, and one that never ends is forgotten after a
160
+ minute), and only the
161
+ answer's own streams are guarded (`data-chats-answer`), never a host's
162
+ stream rendered at the same moment. A thread whose catch-up didn't apply,
163
+ for any reason (its page rendered it away, the request failed, Turbo
164
+ never got to it), is marked behind (`data-chats-stale`, on the thread
165
+ element itself, so the mark travels with the dock and can't be
166
+ forgotten while the thread exists) and catches up again when it
167
+ connects, on its stream's confirmation and after every page render,
168
+ through the same coalescing and 5-second spacing as every other trigger;
169
+ only the answer of the newest catch-up clears it (they are numbered on
170
+ the element, `data-chats-catch-up`), so an older answer that applies
171
+ after a newer one failed leaves the thread marked; and nothing older
172
+ than the newest catch-up that has applied (`data-chats-applied`) may
173
+ apply after it, so an older answer arriving last can't put back older
174
+ bubbles, read state or cursors. A catch-up always gets an answer built
175
+ after it was asked: the same request asked in the same instant is made
176
+ once, but asked while it is already on its way, it is made once more as
177
+ soon as that one has its answer from the network (never waiting on
178
+ Turbo to apply it), for everyone who asked meanwhile, each keeping its
179
+ own `when` and its own outcome. An answer Turbo hasn't applied 10
180
+ seconds after it joined the page is cancelled (its callers settle, and a
181
+ thread stays marked behind), and neither a caller's hook that throws nor
182
+ a stream that fails to render can leave an answer half-applied or its
183
+ callers waiting. An empty
184
+ thread, which used to ask nothing, asks from the epoch: its first message
185
+ may be the one it missed.
186
+ - **The thread's catch-up is complete.** `GET /:id/refresh` now also
187
+ replaces the read state (a read the stream missed left "Sent" where it
188
+ should say "Seen"), catches reactions (a reaction now moves its message's
189
+ `updated_at`, with `update_columns`, so the bubble is not broadcast twice),
190
+ and, under `deletion: :hard`, lists the messages that still exist from the
191
+ oldest rendered bubble on (`from=`), so the thread removes the ones that
192
+ are gone (the `chats_prune` stream action). Catching up still reads
193
+ nothing.
194
+ - **The unread badge and the dock catch up.** The viewer's own
195
+ `chats_unread_badge` is wrapped in a `chats--unread-badge` controller (a
196
+ `span.chats-unread-badge-live`, `display: contents`, so it changes no
197
+ layout) that asks the new `GET /badge` for every unread badge on the page:
198
+ the nav badge and the dock's, with the count the badge streams send
199
+ (`unread_chats_count`). Someone else's badge stays live but doesn't catch
200
+ up. The dock fetches the same, and reloads its recent list; each open
201
+ window's thread catches up by itself. A message missed while offline
202
+ never pops a window open late.
203
+
204
+ - **Both search forms are search landmarks.** `form_with … role: "search"`
205
+ rendered no `role` at all (`form_with` drops HTML attributes it doesn't
206
+ know unless they go through `html:`), on the inbox and in the dock.
207
+
208
+ ### Changed
209
+ - A page now counts as having been away after 10 seconds hidden, not 60
210
+ (the inbox and the thread used 60).
211
+ - A thread more than a page behind no longer gets a page refresh, which
212
+ cleared the composer's draft and, in a dock window, refreshed the host's
213
+ whole page: its history (`chats/conversations/_history`, inside
214
+ `#history_conversation_<id>`) is re-rendered at the latest page, the
215
+ composer untouched. An ejected thread whose scroller has no
216
+ `id="<%= dom_id(conversation, :history) %>"` keeps getting the page
217
+ refresh.
218
+ - The inbox's search keeps its query in the URL (`data-turbo-action=
219
+ "replace"`, submitting to the inbox's own path), so a refresh re-renders
220
+ the same results instead of the unfiltered list. The dock's recent list
221
+ frame has `refresh="morph"`, so a reload keeps its scroll and its search.
222
+ - New: the `GET /badge` collection route, the `chats--unread-badge`
223
+ controller, `Chats::InboxRefreshJob`, and `data-message-id`,
224
+ `data-created-at-us` and `data-updated-at-us` on every bubble, which no
225
+ longer carries `data-updated-at-ms`.
226
+ - **If you wrapped the inbox in a reconciler of your own** (a
227
+ stream-reconciler controller around `turbo_stream_from … :chats_inbox`),
228
+ remove it: two on one page both fire, and the gem's covers what yours did.
229
+ **If you ejected the inbox**, keep the
230
+ `data-controller="chats--refresh-inbox"` element around its
231
+ `turbo_stream_from chats_current_messager, :chats_inbox` (an inbox without
232
+ it doesn't catch up), and add `turbo_action: "replace"` to the search
233
+ form's `data` and `url: request.original_fullpath.split("?").first`. An
234
+ ejected message partial (with only `data-updated-at-ms`) keeps the one
235
+ cursor it had (`since=`), and a hard delete missed while offline stays on
236
+ screen until the next load.
237
+
7
238
  ## [0.5.0] - 2026-10-18
8
239
 
9
240
  The messaging dock. LinkedIn and Steam keep your conversations in small
data/README.md CHANGED
@@ -98,6 +98,8 @@ Or give every page LinkedIn-style floating chat windows with one line in your la
98
98
 
99
99
  > [!NOTE]
100
100
  > **Want customer support?** Ticketing stays out of `chats` on purpose — queues, assignment and SLAs are not messaging. [`support_desk`](https://github.com/rameerez/support_desk) is the product gem that adds them ON TOP of this one: tickets that are real conversations, a support desk that sends while your staff sign, and a BYOUI agent console. It uses the seams below (headless messagers, subject locks, message authorship, grouped inbox rows), so you get the same threads, attachments and read state you already have.
101
+ >
102
+ > A product on chats may need a conversation to open although your `inbox_scope` keeps it out of the inbox (a requester's own ticket). `Chats::ApplicationController#conversation_lookup_scopes` is the one extension point for that: every engine endpoint looks a conversation up through it, in order (by default `[viewer.chats]`), and the product appends its own relation, `super + [own_cases_scope]`, from a prepended module. Each scope must hold only conversations the viewer may open: nothing outside them becomes reachable, a miss is still a plain 404, and an error inside a scope is not rescued.
101
103
 
102
104
  ## 🧱 The data model
103
105
 
@@ -114,6 +116,30 @@ Two deliberate design decisions worth knowing:
114
116
  1. **Read state is a horizon, not per-message receipts.** A participant has ONE `last_read_at`; a message is unread iff it's newer. That's unread counts, badges, and "Seen" indicators with zero extra writes per message (a receipts table writes N rows per message — the classic chat-schema scaling trap), and it's exactly how Basecamp's Campfire models it.
115
117
  2. **Direct conversations have a deterministic identity** (`direct_key`, unique-indexed): two people DMing each other in the same instant race into the SAME conversation, guaranteed by the database, not by hope.
116
118
 
119
+ ### Real conversations vs system-only threads
120
+
121
+ A system message is a message: `post_system_message!` bumps `messages_count`, moves `last_message` and re-sorts the inbox like a human one, and a deleted message stays behind as a tombstone. That is on purpose: "Your ride was cancelled" matters to the passenger, so the inbox lists a thread only your app has spoken in. Two questions, two scopes:
122
+
123
+ - **`with_messages`** asks *is there anything here?*: any message, system lines and tombstones included. Every list the gem renders reads through it, so a thread that was opened and never used is not listed.
124
+ - **`with_human_messages`** asks *did a messager write something here that still stands?*: at least one `text` message that isn't deleted. "Human" is the gem's word for a `text` message: written by a messager, person or not, as opposed to posted by the app. So a bot's or a headless desk's message counts, and so does a photo with no caption. It is for ops walls, moderation lists and "conversations started this week" charts, which must not count a thread holding only "Alice joined".
125
+
126
+ ```ruby
127
+ # What a viewer sees: start from alice.chats, so blocks and config.inbox_scope apply
128
+ alice.chats.with_human_messages # threads where somebody actually wrote
129
+ alice.chats.with_messages.without_human_messages # listed, but only the app has spoken
130
+ conversation.last_human_message # the newest human message, or nil (a query, not the pointer)
131
+ Chats::Message.last_human_in(alice.chats.limit(20)) # the same for a page of threads, in ONE query
132
+
133
+ # Admin-wide: no viewer, so no blocks and no inbox_scope. Only behind your staff authorization.
134
+ Chats::Conversation.with_human_messages.count
135
+ Chats::Conversation.about(ride).without_human_messages
136
+ Chats::Message.last_human_in(page) # page: records, ids, or a relation (read as a subquery, see below)
137
+ .select(:id, :conversation_id, :body) # narrow the columns if you like
138
+ .index_by(&:conversation_id) # { id => message }; no key means nobody wrote
139
+ ```
140
+
141
+ Both conversation scopes are a single correlated `EXISTS` built from `Chats::Message.human` (kind `text`, not deleted), so they compose with anything (`about`, `unread_by`, `with_messages`) and never multiply rows. `last_human_in` reads an unloaded relation as a subquery without its `includes` (they only load records), so a relation that filters on an associated table needs that table joined explicitly, with `joins` or `left_joins`; `includes(:participants).references(:participants).where(chats_participants: …)` loses the join and raises. Or pass the loaded page, or its ids. Counting what messagers wrote per conversation is the plain `Chats::Message.human.where(conversation_id: ids).group(:conversation_id).count`. None of this changes the inbox, unread counts, `messages_count` or `last_message`.
142
+
117
143
  ## 🧩 The macros
118
144
 
119
145
  ### `acts_as_messager(notifications: true, blockable: true, inbox: :default, group_path: nil, verified: false)`
@@ -155,12 +181,34 @@ All three are inert by default (the label falls back to the record's `to_s`, not
155
181
 
156
182
  - **The thread** subscribes to one conversation stream. New messages append surgically; edits/deletes replace bubbles in place; the sender's own bubble comes straight back in the form response (no cable round-trip), and Turbo's same-id dedup makes the echo broadcast a no-op.
157
183
  - **Bubbles are broadcast viewer-agnostic** — one render shared by every subscriber. A tiny Stimulus controller aligns own-vs-other client-side by comparing sender keys. This is what makes single-render broadcasts possible at all.
158
- - **The inbox** receives Turbo 8 page *refreshes* (morphing, scroll-preserving) instead of surgically patched rows: inbox rows are intensely per-viewer (unread badges, bold states, ordering), so each client re-requests and gets a correct, personalized render. Refreshes are debounced and tagged so the tab that caused the change skips its own.
184
+ - **The inbox** receives Turbo 8 page *refreshes* (morphing, scroll-preserving) instead of surgically patched rows: inbox rows are intensely per-viewer (unread badges, bold states, ordering), so each client re-requests and gets a correct, personalized render. Each refresh carries `method="morph" scroll="preserve"` itself, so it morphs whatever your layout's refresh meta says. A search keeps its query in the URL, so a refresh re-renders the same results, and the field you're typing in is never rewritten under you.
159
185
  - **Unread badges** get their own stream (`chats_unread_badge` helper) so any page can host a live badge without inheriting inbox refreshes.
160
186
  - **The messaging dock** has one more per-messager stream (`[messager, :chats_dock]`): its badges, and a signal naming the conversation that changed and whether its window may pop open. The signal only names a conversation the participant can see (blocks and `inbox_scope` applied). No polling, no channel of its own.
161
187
  - **Typing indicators** are a Turbo Stream *custom action* — ephemeral, nothing persisted, no Action Cable channel class, no connection identification requirements.
162
188
  - **Cable down?** Everything still works request/response. Real-time is an enhancement, not a requirement.
163
189
 
190
+ ### What happens when a broadcast is missed
191
+
192
+ Action Cable has no replay: a broadcast sent while a page's socket is down (a laptop asleep, a phone in a pocket, a backgrounded Hotwire Native WebView, an elevator) never reaches it. So every live surface catches up by itself, with no polling and nothing to configure. It fetches what it missed at the moments it may have missed something, and only then:
193
+
194
+ - **its stream reconnects.** Every confirmation of the subscription after the first counts, including a socket Action Cable reopened without ever reporting it closed (the half-open TCP of a phone that slept);
195
+ - **the page comes back after 10 seconds or more hidden** (an app foregrounded, a tab returned to). A hidden page never fetches; what it missed waits until it is seen;
196
+ - **the network comes back online.** Action Cable is asked to check its socket right away instead of waiting out its backoff (a dead one reconnects: the first trigger), and the surface catches up anyway, because after a short outage the socket can still look open while what was sent during it is gone;
197
+ - **the page is restored**, from the browser's back/forward cache or from Turbo's own snapshot cache (a back navigation, a Hotwire Native stack pop).
198
+
199
+ Triggers that arrive together make one catch-up, and catch-ups are at least five seconds apart, so a flapping connection can't turn into a fetch loop. While the socket is healthy and the page is on screen, nothing is fetched. What each surface fetches:
200
+
201
+ | surface | catches up with |
202
+ |---|---|
203
+ | the inbox | the same morphing page refresh a broadcast triggers. A refresh that arrives while another visit is still loading, which Turbo would otherwise ignore, runs when that visit completes |
204
+ | a thread (page or dock window) | `GET /:id/refresh?after=…&changed=…`, on two cursors: messages created after the newest one on screen are appended (an empty thread asks from the beginning), and edits, tombstones and reactions made to the ones on screen since the newest change it saw are replaced. Two, because a message created at 10:15 and missed is older than a 10:20 edit that did arrive. Each cursor is a moment to the microsecond up to which the thread knows it has everything: set by a complete render or by a catch-up that arrived, never by a live bubble, which can arrive after one that was missed. What arrived live since is named instead (at most 200 ids; past that the history is re-rendered), so it isn't sent twice, and two messages that share a timestamp are never mistaken for each other. Each catch-up belongs to one render of the thread: an answer that arrives after the page or the window rendered the conversation again is dropped unrendered. The read receipts are updated too, the read receipts updated, and, under `deletion: :hard`, bubbles whose messages are gone removed. The composer, its draft and your scroll position are never touched. A thread more than a page behind gets its history re-rendered at the latest page |
205
+ | `chats_unread_badge` and the dock's badges | `GET /badge`, every unread badge on the page in one Turbo Stream |
206
+ | the dock's recent list | a reload of its frame, morphed in place so it keeps its scroll position and your search |
207
+
208
+ None of these requests marks anything read, and none can be prefetched (they are not links). On the server, the inbox refresh is enqueued straight into your job queue when the write commits (`Chats::InboxRefreshJob`), and not parked first in Turbo's in-process half-second debounce, where a deploy or a crash inside that window would drop it. A burst is one job per recipient, not one per write: a refresh carries no data (the inbox re-requests itself), so while one is queued and hasn't started it stands for every write that commits before it runs. A short-lived marker in `Rails.cache` says one is queued, and the job removes it as it starts, before it broadcasts, so a write that still finds the marker is covered and a write after it queues the next job. Because another write may already be counting on it, an enqueue that fails is tried once more, and if the queue refuses again the refresh is broadcast on the spot. Every refusal goes to `Rails.error`, whether the adapter raised, returned `false` or declined the job. Whatever happens to the marker costs an extra job, never a missed refresh: a cache that can't hold it (a null store, a per-process memory store, a Redis that refuses the write) only means no coalescing, and it expires after two seconds, so a job lost from the queue holds nothing back for longer than that. The refresh names no request id, because it may stand for several requests' writes. Refreshes that still arrive close together merge in the browser: Turbo runs one page refresh for those within 150 ms of each other.
209
+
210
+ **Hotwire Native** needs nothing. The catch-up is the same code path a broadcast takes (the inbox's is a Turbo page refresh, which Turbo hands to the native adapter as it does any refresh), and a back navigation is a Turbo restore, which catches up like any other. A WebView that lives for the whole app session is the case all of this is for: when the app comes back to the foreground, the WebView reports the page visible again, and in any case the socket that died in the background reconnects, and that reconnect is a trigger of its own. **If you wrapped the inbox in a reconciler of your own** (a stream-reconciler controller around `turbo_stream_from … :chats_inbox`), remove it: two reconcilers on one page both fire, and the gem's now covers everything yours did.
211
+
164
212
  ## 🛡️ Trust & Safety: snaps onto the [`moderate`](https://github.com/rameerez/moderate) gem
165
213
 
166
214
  Messages are user-generated content — App Store Guideline 1.2, Google Play's UGC policy, and the EU DSA all expect **report**, **block**, and **filter** capabilities before you ship a chat. Instead of re-implementing any of that, `chats` exposes the exact seams the `moderate` gem expects, with **no hard dependency in either direction**: each gem runs standalone, and together they behave like one system. This section is the complete recipe.
@@ -552,7 +600,7 @@ LinkedIn and Steam don't send you to another page to answer a message: chats liv
552
600
  - **The bar** sits flush with the bottom-right corner: your avatar, "Messages" and the live unread badge (the same number as `chats_unread_badge`).
553
601
  - **The panel** opens from it: the inbox's search, your ten most recent conversations exactly as the inbox renders them (stacks, verified badges, a bell-slash on muted ones, previews, unread counts) and "See all messages". It is a `<details>`: it opens without JavaScript, and every row, the search and the link are real links and forms.
554
602
  - **A window** is the same thread the full page shows (live messages, read receipts, typing, the long-press menu, attachments, action buttons, your `composer_actions`, the locked composer) under a compact header: the name (click it to minimize, as on LinkedIn), the `conversation_header_actions` slot in a ⋯ menu, ⤢ for the full page, – and ×. As many windows open as fit beside the panel, up to three: two at 1280px, one at 768px. Opening one more closes the least recently used window that isn't **in use**. A window in use (it has the focus, or text you haven't sent) is never closed to make room: it folds to a narrow header (its avatar and ×) beside the new window instead. Two limits always hold: never more than `windows:` windows, folded ones included, and never wider than the screen beside the panel. When a conversation can't fit even with every window in use folded, the dock doesn't open it: the row's link opens the conversation's page instead (a pop-up simply doesn't happen). Unfolding a folded window makes room the same way; when it can't, the window stays folded. Narrowing the browser closes idle windows and folds the ones in use, the focused one last; if even a row of folded headers is too wide, the least recently used windows close too, their unsent text kept for when you reopen them. Text in a window that goes away (you close it, it makes room, its conversation becomes unreachable, its load fails) is kept for when you reopen it, and goes back into the composer the moment it appears, unless you've already started typing there.
555
- - **Live**: a new message updates the badge and the list, and opens its conversation's window without taking the focus. That never happens for your own messages, for a conversation you muted, on a phone, for one you closed in the last five minutes, or by closing a window you're using. The window waits with the accent header and its count, and "New message from …" is announced politely. Edits, deletes and your own sends from another tab keep the list in order.
603
+ - **Live**: a new message updates the badge and the list, and opens its conversation's window without taking the focus. That never happens for your own messages, for a conversation you muted, on a phone, for one you closed in the last five minutes, or by closing a window you're using. The window waits with the accent header and its count, and "New message from …" is announced politely. Edits, deletes and your own sends from another tab keep the list in order. A message that arrived while you were offline doesn't pop a window late: the badge and the list [catch up](#what-happens-when-a-broadcast-is-missed), and so does every open window's thread.
556
604
  - **Reading** waits for you. A minimized window never marks anything read (the thread checks the window's state, not just its size), and a window that popped open marks messages read once you focus it, press in it or scroll it. One you opened yourself reads right away.
557
605
  - **It stays put**: the dock is `data-turbo-permanent`, so Turbo Drive carries its windows, drafts and scroll positions from page to page. Its id names the viewer, so a visit that lands on another account's page never inherits it. Open windows, minimized ones, recently closed ones, the panel and unsent drafts are kept in `localStorage` under keys that name the viewer (`chats:dock:v1:<key>`, `chats:draft:<key>:<id>`), so a reload brings them back as they were, folded ones included (fitted to the width there is). A browser that refuses storage only means the dock forgets.
558
606
  - **Keyboard**: Escape unwinds from the inside out (the long-press popup, an edit, the ⋯ menu, then the window minimizes, then the panel closes). Focus rings are inset; the history scrolls with the arrow keys.
@@ -605,7 +653,7 @@ It needs `chats_dock` on the same page: without the dock, the button's response
605
653
  }
606
654
  ```
607
655
 
608
- The `dock_panel_footer` [slot](#-view-slots) puts your own link next to "See all messages". `rails generate chats:views` ejects the dock's partials (`chats/dock/`) along with everything else. All labels are localized under `chats.dock.*`.
656
+ The `dock_panel_footer` [slot](#-view-slots) puts your own link next to "See all messages". `rails generate chats:views` ejects the dock's partials (`chats/dock/`) along with everything else. All labels are localized under `chats.dock.*`. The window's unread count (`chats.dock.window_unread`) is pluralized in the browser with `Intl.PluralRules` in the page's `<html lang>`: the gem ships `one`/`other`, so add the forms your languages need (`zero`, `two`, `few`, `many`) in your own locale file, e.g. Polish `few: "%{count} nowe wiadomości"`, `many: "%{count} nowych wiadomości"`.
609
657
 
610
658
  ## 🔗 Profile links
611
659
 
@@ -639,7 +687,7 @@ Want full control? Eject the views Devise-style and restyle with your own stack
639
687
  rails generate chats:views
640
688
  ```
641
689
 
642
- Override any bundled Stimulus controller by pinning the same importmap key — host pins win. The current keys are `controllers/chats/thread_controller`, `controllers/chats/composer_controller`, `controllers/chats/debounced_submit_controller`, `controllers/chats/refresh_inbox_controller`, and `controllers/chats/dock_controller`.
690
+ Override any bundled Stimulus controller by pinning the same importmap key — host pins win. The current keys are `controllers/chats/thread_controller`, `controllers/chats/composer_controller`, `controllers/chats/debounced_submit_controller`, `controllers/chats/refresh_inbox_controller`, `controllers/chats/unread_badge_controller`, and `controllers/chats/dock_controller`. What the inbox, thread, badge and dock controllers share to catch up on missed broadcasts is `chats/recovery` (`recoverMissedBroadcasts`, `renderStreamFrom`); a controller of your own can import it too.
643
691
 
644
692
  ## Configuration reference
645
693
 
@@ -706,6 +754,7 @@ alice.message!(bob, "hi", about: ride) # send (resolves the thread)
706
754
  alice.message!(conversation, "hi", files: []) # send into a conversation
707
755
  alice.chats # every conversation she's in (what she may open), newest first
708
756
  alice.chats.with_messages # ...the ones with a message: what lists show
757
+ alice.chats.with_human_messages # ...the ones a messager wrote in (system lines and tombstones don't count)
709
758
  alice.unread_chats_count # conversations with unread messages
710
759
  alice.message!(bob, "hi", author: lucia) # written by lucia, sent from alice's seat
711
760
  alice.message!(bob, "Let's play!", # with one button under it
@@ -755,6 +804,8 @@ Chats::Conversation.group!(alice, [bob, carol], title: "Trip")
755
804
  Chats::Conversation.direct .groups .about(ride) .recent_first
756
805
  Chats::Conversation.inbox_for(alice) .excluding_blocked_for(alice) .unread_by(alice)
757
806
  Chats::Conversation.with_messages # has at least one message, system messages and tombstones included (`last_message_id` set); every list reads through this
807
+ Chats::Conversation.with_human_messages .without_human_messages # a messager wrote / only system lines, tombstones or nothing
808
+ conversation.last_human_message # newest text, non-deleted message, or nil (a query)
758
809
  Chats::Conversation.unread_counts_for(alice, conversations) # { id => count } in one query
759
810
  conversation.direct? / conversation.group?
760
811
  conversation.participant_for(alice) # the seat, or nil
@@ -767,6 +818,8 @@ message.attachments?
767
818
  message.sent_by?(alice) message.sender_key
768
819
  Chats::Message.visible .oldest_first .recent_first .before_message(message) # keyset pagination
769
820
  Chats::Message.created_since(time) .updated_since(time) # what the stale-thread catch-up reads
821
+ Chats::Message.human # kind text, not deleted: what messagers wrote
822
+ Chats::Message.last_human_in(conversations) # newest human message per conversation, one query
770
823
 
771
824
  # Participants — reading
772
825
  participant.active? / participant.left? / participant.muted? / participant.owner?
@@ -809,7 +862,7 @@ All available in the bundled views **and** in your own templates:
809
862
  | helper | renders |
810
863
  |---|---|
811
864
  | `chat_button_to(other, about:, label:, dock:, **html)` | a "Message" button, only when the viewer may message them; `dock: true` opens a dock window instead of navigating |
812
- | `chats_unread_badge(messager = viewer)` | the live unread badge with its own stream |
865
+ | `chats_unread_badge(messager = viewer)` | the live unread badge with its own stream; the viewer's own also [catches up](#what-happens-when-a-broadcast-is-missed) on updates it missed |
813
866
  | `chats_dock(windows: 3, recent: 10, launcher: true, everywhere: false)` | the [messaging dock](#-messaging-dock): bar, panel and floating windows |
814
867
  | `chats_dock_opener(conversation)` / `chats_dock_toggle` | data for your own links: open that conversation's dock window, or open the dock's panel |
815
868
  | `chats_muted?(conversation, viewer)` | whether the viewer muted it (read from the preloaded seats) |
@@ -849,7 +902,7 @@ rails generate chats:upgrade # 0.2.0: message authorship columns · 0.4.0: the
849
902
  rails db:migrate
850
903
  ```
851
904
 
852
- 0.5.0 needs no migration: the messaging dock is opt-in (`chats_dock`). A few things change on their own: a conversation with no messages is no longer listed (it used to show as a "No messages yet" row), a thread the host's policy no longer allows shows the notice in the composer's place, a Turbo hover prefetch no longer marks a thread read, and the thread body moved into `chats/conversations/_thread.html.erb`. Read the 0.5.0 [CHANGELOG](CHANGELOG.md) entry if you ejected `show.html.erb` or the unread badge. 0.4.0 needs that migration (one nullable JSON column, `chats_messages.action`) and nothing else: actions and the `composer_actions` slot are opt-in. The generator is guarded: it doesn't write the action migration where the column already exists (a fresh 0.4.0 install), and re-running it is harmless. Rolling that migration back keeps the column, because a migration must never drop a column it may not have added. If you ejected the composer, read the 0.4.0 [CHANGELOG](CHANGELOG.md) entry: its DOM changed shape. 0.3.x needs no migration and no new configuration: `verified: true` (0.3.0) and `Chats::SendRateLimited` (0.3.2) are opt-in. Nothing in 0.2.0 changes behaviour until you set an option.
905
+ 0.5.1 needs no migration and nothing to configure: every live surface now [catches up](#what-happens-when-a-broadcast-is-missed) on missed broadcasts by itself. If you wrapped the inbox in a reconciler of your own, remove it; if you ejected the inbox, the thread or the message partial, read the 0.5.1 [CHANGELOG](CHANGELOG.md) entry. 0.5.0 needs no migration: the messaging dock is opt-in (`chats_dock`). A few things change on their own: a conversation with no messages is no longer listed (it used to show as a "No messages yet" row), a thread the host's policy no longer allows shows the notice in the composer's place, a Turbo hover prefetch no longer marks a thread read, and the thread body moved into `chats/conversations/_thread.html.erb`. Read the 0.5.0 [CHANGELOG](CHANGELOG.md) entry if you ejected `show.html.erb` or the unread badge. 0.4.0 needs that migration (one nullable JSON column, `chats_messages.action`) and nothing else: actions and the `composer_actions` slot are opt-in. The generator is guarded: it doesn't write the action migration where the column already exists (a fresh 0.4.0 install), and re-running it is harmless. Rolling that migration back keeps the column, because a migration must never drop a column it may not have added. If you ejected the composer, read the 0.4.0 [CHANGELOG](CHANGELOG.md) entry: its DOM changed shape. 0.3.x needs no migration and no new configuration: `verified: true` (0.3.0) and `Chats::SendRateLimited` (0.3.2) are opt-in. Nothing in 0.2.0 changes behaviour until you set an option.
853
906
 
854
907
  ## Database support
855
908
 
@@ -133,6 +133,9 @@
133
133
  flex-shrink: 0;
134
134
  }
135
135
  .chats-badge--floating[hidden] { display: none; }
136
+ /* chats_unread_badge's wrapper (its catch-up controller): no box of its own,
137
+ so the badge sits in the host's layout exactly as if it weren't there. */
138
+ .chats-unread-badge-live { display: contents; }
136
139
 
137
140
  /* --- Empty states ------------------------------------------------------------ */
138
141
 
@@ -55,11 +55,52 @@ module Chats
55
55
  Chats.config.layout
56
56
  end
57
57
 
58
- # Conversations are ALWAYS resolved through the viewer's own inbox
59
- # relation: not-a-participant, left, or blocked-counterpart threads all
60
- # come back as a plain 404 — existence is never leaked to outsiders.
58
+ # Conversations are ALWAYS resolved through relations that only hold
59
+ # what this viewer may open (conversation_lookup_scopes): not a
60
+ # participant, left, or a blocked counterpart all come back as a plain
61
+ # 404, the same 404 as an id that doesn't exist — existence is never
62
+ # leaked to outsiders. Every engine endpoint (the thread, a dock window,
63
+ # sending, editing, reacting, reading) looks a conversation up here.
64
+ #
65
+ # The first scope that has it wins; later scopes are asked only on a
66
+ # miss. Errors a scope raises are not rescued: a broken product scope
67
+ # must fail loudly, never turn into a quiet 404.
61
68
  def find_conversation(id = params[:id])
62
- chats_current_messager.chats.find(id)
69
+ conversation_lookup_scopes.each do |scope|
70
+ conversation = scope.find_by(id: id)
71
+ return conversation if conversation
72
+ end
73
+
74
+ raise ActiveRecord::RecordNotFound.new(
75
+ "Couldn't find Chats::Conversation with 'id'=#{id}", Chats::Conversation.name, "id", id
76
+ )
77
+ end
78
+
79
+ protected
80
+
81
+ # Where find_conversation looks, in order: by default the viewer's own
82
+ # inbox relation (`Messager#chats`: their active seats, blocks and
83
+ # `config.inbox_scope` applied).
84
+ #
85
+ # THE extension point for a conversation that must open although the
86
+ # inbox hides it. A product gem built on chats (support_desk: a
87
+ # requester's own ticket, which the host's inbox_scope keeps out of the
88
+ # inbox) prepends a module that appends its own relation:
89
+ #
90
+ # module SupportDesk::ConversationLookup
91
+ # protected
92
+ #
93
+ # def conversation_lookup_scopes
94
+ # super + [SupportDesk::Ticket.conversations_of(chats_current_messager)]
95
+ # end
96
+ # end
97
+ # Chats::ApplicationController.prepend(SupportDesk::ConversationLookup)
98
+ #
99
+ # Each scope must hold only conversations this viewer may open: the
100
+ # union of the scopes IS the authorization. Nothing the scopes don't
101
+ # name becomes reachable.
102
+ def conversation_lookup_scopes
103
+ [chats_current_messager.chats]
63
104
  end
64
105
  end
65
106
  end