Real-time¶
Tomoda's frontend opens two WebSocket streams, each with a single client living in a service singleton:
| Hub | Backend endpoint | Client owner | Scope |
|---|---|---|---|
| Chat session | /ws/chats/:id |
services/chatService.ts (ChatService) |
One open chat room at a time |
| Client hub | /ws/client |
contexts/WebSocketContext.tsx (useWsSubscription) |
One per signed-in user, across every device the user has open |
The chat hub is per-room and connects on demand; the client hub is app-level and connects once on cold launch. Server-side this matches the two backend hubs documented in Real-time architecture.
The chat hub client is covered first; see Client hub (/ws/client) below for the app-level stream.
Chat session hub¶
Real-time chat in Tomoda runs over a per-room WebSocket connection. The client lives entirely in frontend/services/chatService.ts as a singleton ChatService instance.
Connection URL¶
The base WebSocket URL comes from EXPO_PUBLIC_WS_URL (see API Client):
| Environment | URL |
|---|---|
| Production | wss://api.tomoda.life/ws |
| Local (web / iOS sim) | ws://127.0.0.1:8080/ws |
| Local (Android emulator) | ws://10.0.2.2:8080/ws |
Per-room URL pattern:
${WS_URL}/chats/${chatId}?token=${jwt}
The JWT is passed as a query parameter because the WebSocket constructor (both browser and React Native) does not accept custom headers. The backend authenticates the upgrade request from the query string.
Lifecycle¶
A single ChatService instance is exported and lives for the app's lifetime. It connects when a chat room is opened and disconnects when the user leaves.
import { chatService } from '@/services/chatService';
useEffect(() => {
const owner = {};
chatService.connect(chatId, owner);
const off = chatService.onMessage((msg, from) => { if (from === chatId) handleMessage(msg); });
return () => { off(); chatService.disconnect(owner); };
}, [chatId]);
components/chat/useChatRealtime.ts is the one consumer that drives this lifecycle.
- Open: when the user enters a chat room screen (
/connect/chat/:id). The screen that connects last owns the socket. - Stacked chat screens: every callback receives the chat the socket is open for, and a screen drops events for any other chat.
disconnect(owner)from a screen that no longer owns the socket is a no-op, and a chat screen that regains focus reconnects if a screen above it took the socket. - Close: when the owning screen unmounts;
disconnect()sends close code1000("Client disconnect"). - Catch-up: every socket open (first connect, reconnect, focus regained) refetches the newest page and merges it by id, so messages sent while the socket was down appear. A failed first load shows an error state with a retry button and retries on the next open.
- Heartbeat: while open, the client sends
{"type":"ping"}every 30 seconds. If no frame of any kind arrives within 45 seconds of a ping, the socket is treated as dead, closed and reconnected. - Reconnect: any close the client didn't initiate (a server
1000included) reconnects without a cap: back-off from 1s doubling to 30s with ±20% jitter, reset when a socket opens. A handshake still connecting after 10 seconds is abandoned and retried the same way. Returning to the foreground reconnects at once (a socket stuck connecting is replaced), or pings an open socket to probe it. A handshake that closes without ever opening (an expired access token) first refreshes the token once through the shared single-flight refresh and reconnects; a rejected refresh stops reconnecting and signs the user out, and a transient one (no answer) allows another refresh on the next failed handshake. The/clientsocket follows the same rule and also refreshes before connecting when the token is already expired.
Inbound event types¶
ChatService.handleMessage() dispatches the following server-sent types:
| Type | Payload | Triggers |
|---|---|---|
new_message |
ChatMessage |
Render incoming message; append to local cache |
message_updated |
{ message_id, chat_id, content, edited_at } |
Replace in list, show "edited" hint |
message_deleted |
{ message_id, chat_id, new_last_message? } |
Remove message; update room's last-message preview |
messages_expired |
{ chat_id, message_ids[] } |
Remove disappearing messages whose TTL elapsed |
reaction_update |
{ message_id, chat_id, reactions: Record<emoji, userId[]> } |
Re-render reaction bar |
mark_read |
{ user_id, chat_id, last_read_at, ... } |
Update read receipts |
user_joined |
{ user_id, user_name, online_count } |
Presence indicator |
user_left |
{ user_id, online_count } |
Presence indicator |
pong |
— | Heartbeat ack (no UI effect) |
error |
{ message } |
Surface via errorCallbacks |
Sending messages¶
Messages are sent over REST (chatService.postMessage, POST /chats/:id/messages), never the socket, so a send works before the socket opens (the first message of a new DM) and every send gets a response. Each send carries a client-generated client_msg_id UUID:
- The composer adds an optimistic bubble whose id is the
client_msg_id, and hands the send to the device outbox. It shows as pending (dimmed, with a clock) only if it is still unconfirmed afterPENDING_GRACE_MS(1 s), so a fast send never flashes; a failure shows at once. - The REST response or the
new_messageecho (which carriesmetadata.client_msg_id), whichever lands first, confirms it; the other is deduplicated by id. Unconfirmed bubbles always stay below confirmed messages, so a confirmed message lands where its server time sorts and nothing moves afterwards. - Only a definite error (a 4xx other than 408, 409 or 429) marks a send failed with "Not sent. Tap to retry." A network error, a timeout or a 5xx keeps it pending and retries.
Outbox and offline history¶
services/chatOffline.ts keeps chat state on the device (AsyncStorage), cleared on sign-out and before another account signs in.
- Outbox: every pending or failed send (text, GIF, reply, images with their uploaded keys) is stored per chat by
client_msg_id. Each chat delivers one send at a time in send order; a head that can't get through holds the ones behind it and retries with backoff (1s doubling to 30s). Delivery doesn't depend on the chat being open: the chat's socket opening, the client hub connecting and the app returning to the foreground all retry at once. Reopening a chat shows its queued sends in place. A confirmed send (response, echo or a history page carrying itsclient_msg_id) leaves the outbox. A send queued more than 24 hours ago (the server dedup window) shows failed and only retries when tapped. Images upload once; later attempts resend only the keys. - Unsend and delete: the sender's menu offers Unsend on a sent message, which deletes it for everyone (
delete_message, no time limit). An unsent message renders as a muted divider-style line, "You unsent a message" or "{name} unsent a message", with no bubble, avatar, reactions, media or menu, and it breaks the sender group. Replies quoting it show "Unsent message" with no preview. The chat list shows the server's previous visible message, or the unsent line when none is left. An unconfirmed message offers Delete, which drops it from the list and the outbox and aborts its upload or request. - Edits, unsends and reactions go through
chatActions: each is stored on the device as an end state (react with or clear an emoji, set content, delete), sent when the socket is open, resent in order on every socket open (also after an app restart), and removed only when the server's broadcast confirms it (reaction_updateshowing the wanted state,message_updated,message_deleted). A newer action on the same message replaces an older one; one resent more than 5 times unconfirmed is dropped. A reaction shows at once and the broadcast replaces it. - Read receipts that fail retry with backoff.
- History: the newest 50 confirmed messages of each chat are cached after the server answers, for the 30 most recently viewed chats. A chat opened offline shows the cache at once; the server page merges in by id when it lands. When older history can't load, the top of the list shows a quiet "Can't load older messages" row that retries on tap or on reconnect.
- Header status: while the socket has been down for more than 1.5 seconds, the header shows "Connecting…", or "Waiting for network" when the last fetch failed at the network level. It clears when the socket opens.
Outbound commands¶
The client sends framed JSON messages of the form { "type": "...", "data": {...} }:
| Type | Sent via | Body |
|---|---|---|
edit_message |
editMessage(id, content) |
{ message_id, content } |
delete_message |
deleteMessage(id) |
{ message_id } |
add_reaction |
sendReaction(id, emoji, active, selfId) |
{ message_id, emoji, active }: active sets or clears that emoji (without it the server toggles) |
ping |
heartbeat | — |
markRead(chatId) is a REST call (POST /chats/:id/read), not a WS message — it's idempotent and survives socket drops.
Close codes¶
Decoded in WS_CLOSE_CODES for diagnostics:
| Code | Meaning |
|---|---|
1000 |
Normal close (client disconnect) |
1001 |
Server going away |
1006 |
Connection lost (no close frame; network or crash) |
1008 |
Policy violation (likely bad token) |
1011 |
Server error |
4001 |
Unauthorized |
4003 |
Forbidden |
4004 |
Room not found |
The browser onerror callback is intentionally empty — the WebSocket spec hides error details from JS. The close code + reason is the canonical signal.
Platform notes¶
Both targets use the same code path — new WebSocket(url):
- On native (iOS / Android), Tomoda uses React Native's built-in WebSocket implementation.
- On web,
react-native-webre-exports the DOMWebSocket.
There is no platform branch in ChatService for transport.
Where it sits in the stack¶
connect on mount, disconnect on unmount (close code 1000). Between those, chatService fans server events to subscribers and forwards edits, deletes and reactions as framed JSON; sends go over REST. A 30-second ping keeps the socket warm and detects a dead one.Client hub (/ws/client)¶
The app-level WebSocket the user holds open for as long as they're signed in. Where the chat hub is per-room and short-lived, the client hub is per-user and persistent: notifications, friend-graph nudges, chat-room previews, and event-detail invalidations all ride it so the surface stays live without polling.
Connection lifecycle¶
AppWebSocketProvider (mounted in app/_layout.tsx for any authed shell) opens the socket on first render after auth resolves and keeps it warm for the session. URL pattern:
${WS_URL}/client?token=${jwt}
Same JWT-in-query convention as the chat hub, and the same liveness frames: the client sends {"type":"ping"} every 30 seconds, the server's ClientConn.ReadPump answers {"type":"pong"}, and a socket that delivers no frame within 45 seconds of a ping is closed and reconnected. A handshake still connecting after 10 seconds is abandoned. On foreground an open socket must answer a ping within 5 seconds or it is replaced; a closed one reconnects at once. After a drop the first retry waits a random 0 to 3 seconds (so a server restart doesn't bring every client back at once), later ones use the chat socket's jittered backoff (utils/backoff.ts, 1s doubling to 30s), and the backoff resets only after a socket has stayed open 30 seconds. The same refresh rule as the chat hub applies.
The token only gates the handshake, so a token refresh keeps the open socket; sign-out or an account switch tears it down. Each connect carries an epoch, and every handler of a socket from an earlier epoch returns early, so a torn-down socket that reports its close late can't clear the live socket or schedule a duplicate.
Subscribing¶
Components consume the stream via useWsSubscription, a small hook in the same context module. Multiple subscribers can listen to the same event type; the provider dispatches each inbound envelope to every matching subscription synchronously.
useWsSubscription<{ notification: NotificationRow }>('notification:new', (data) => {
// update local cache with the freshly emitted inbox row
});
Inbound event types¶
The same set the backend emits on /ws/client. The notifications context is the central consumer for the notification:* events; the others land directly in their owning context.
| Event type | Consumer | What it updates |
|---|---|---|
notification:new |
NotificationsContext |
Prepend / merge into the inbox cache; bump unreadCount |
notification:unread |
NotificationsContext |
Authoritative unread count from server (drives the tab bell badge) |
notification:resolved |
NotificationsContext |
Morph the row (Accept → Message CTA, Approve → Manage CTA) or remove it (decline / reject); see Backend → Notifications |
notification:transient |
NotificationsContext |
Render a transient toast / banner for non-inbox kinds (chat) |
chat:new_message |
ChatUnreadContext |
Update the unread total + chat-list preview; the open chat (if any) still gets the message over the per-room ChatService |
chat:mark_read |
ChatUnreadContext |
Multi-device read-receipt sync |
friend:graph_changed |
FriendsContext |
Invalidate the friend cache (re-fetches on next read) |
event:updated |
Event detail screens | Patch the in-flight event detail when the host edits allowlisted fields |
item.parsed |
Item board (components/planner/ItemSheet.tsx) |
Replace a captured item's placeholder with its parsed result once the backend finishes unfurling |
Why two streams instead of one¶
The two hubs share a Redis pub/sub primitive on the backend but are deliberately split by scope on the wire so the client lifecycle stays tractable. The chat session client owns ephemeral, high-frequency, room-scoped traffic; the client hub owns long-lived, low-frequency, user-scoped traffic. Splitting also means the client hub keeps delivering notifications when no chat is open, and the per-room socket can drop / reconnect without affecting the inbox.
Cross-links¶
- API Client — REST counterpart and
WS_URLresolution - Backend WebSocket Hub — server-side implementation
- Real-time architecture — system-level real-time design
- Notifications service — inbox model + WS event semantics