Skip to main content
Tuturuuu Chat keeps Postgres (private.chat_*) as the only durable record and uses a Cloudflare Worker, tuturuuu-chat-realtime, for live delivery. The Worker never reads or writes chat data. When it is unavailable or switched off, web and mobile clients fall back to polling the existing Chat API, so it can be rolled out and rolled back without losing messages.

Product decisions

Realtime architecture

  • WorkspaceInbox (one per workspace) holds one socket per open client and carries list-level events: conversation created, updated or deleted, new message summaries and unread changes. Events are filtered by audience (workspace for channels, explicit users for direct and group chats), matching the REST visibility rules.
  • ConversationRoom (one per conversation) holds sockets for clients that have the conversation open. It carries full message events, reactions, edits, deletes, read receipts, typing and presence.
  • Both use the WebSocket Hibernation API, so idle sockets do not bill duration. Per-socket state (user, ticket expiry, rate window) lives in the socket attachment, which survives hibernation.

Tickets and authorization

GET /api/v1/workspaces/:wsId/chat/realtime/ticket (optionally with conversationId) runs the normal chat route context: authenticate, normalize the workspace, require view_chat, and for a conversation ticket confirm participation through the private RPC. It returns the Worker URL and an HMAC ticket signed with CHAT_REALTIME_TOKEN_SECRET. The ticket binds audience chat-realtime, wsId, userId, scope subscribe, and the room. Inbox tickets last up to five minutes. Conversation tickets also bind conversationId and last up to 15 minutes. The client offers the ticket in Sec-WebSocket-Protocol and keeps it out of the URL. The Worker requires a dedicated CHAT_REALTIME_TOKEN_SECRET; the Supabase service key fallback is local-only and is never given to Cloudflare. Rooms enforce expiry on the next socket or room event and close expired sockets with code 4001. An idle socket can stay open after expiry until activity resumes. A new ticket requires a fresh authorization check. When a conversation member is removed, apps/web publishes member.removed and the room closes that user’s sockets. A short-lived SQLite record also blocks reconnections with tickets issued before the removal, including the allowed clock skew. Publishing is server-to-server only. apps/web signs a 60-second ticket with scope publish that is bound to the SHA-256 of the request body, after the RPC commits. Publishing requires a publish ticket. The rooms deduplicate event IDs within their replay window. Conversation events require a canonical lowercase room ID and an explicit user audience. Workspace-wide updates can signal channel list changes. Inbox frames carry only IDs and event metadata for conversation, message and reaction updates. Read receipts stay in their conversation room. Events sent outside the replay window are rejected.

Ordering, reconnect and backfill

Each room gives every fan-out frame a monotonic seq and keeps the last 200 frames, up to 15 minutes old, in its SQLite storage, pruned on each write. A reconnecting client sends since=<seq>; the room replays the gap or answers resync when the gap is gone. On resync, first connect or app resume, the client refetches from the REST API (messages after its newest persisted cursor). Message ids make every apply idempotent, so replay and refetch can overlap safely. Clients reconnect with jittered exponential backoff (1 s to 30 s). After five consecutive failures they switch to polling (15 s while the conversation is open, 60 s for the list) and retry the socket on the next foreground or network change.

Push notifications

Mobile push stays on the existing path: notifyChatMessageRecipients in apps/web creates notifications and sends them through the current FCM/APNs delivery. The ConversationRoom’s publish response lists users who have the conversation open in the foreground, and apps/web skips their push. Muted conversations push only for direct mentions.

Cost bounds and stop fence

The Worker does work only when a request arrives. It has no alarms, cron triggers, queues or outbound fetches, so nothing can reschedule itself. Two independent fences stop realtime delivery. Setting the Worker secret CHAT_REALTIME_STOPPED=true rejects upgrades and publishes with 503. A room closes existing sockets on their next inbound frame. Removing CHAT_REALTIME_URL from apps/web stops both minting and publishing. Either fence alone returns clients to polling with no data loss. Regression tests cover both.

Rollback

The Worker is additive. Rollback means unsetting CHAT_REALTIME_URL, after which clients poll within one backoff cycle, or rolling the Worker back to its previous version. No migration or data repair is needed.

Web and mobile experience

Web (apps/chat and the shared @tuturuuu/ui/chat workspace) and mobile (apps/mobile/lib/features/chat) share one behavior contract:
  • Conversation list: pinned first, then by recency; unread counts and a mention badge; filters for direct, groups, channels and Mira; live typing and presence dots.
  • Thread: day separators, grouped bursts, reply quotes with jump-to, reactions, mentions with autocomplete, link and integration cards, attachment previews, and an inline edited marker. Deleted messages show as a tombstone.
  • Read state: the room broadcasts read receipts; groups show “seen by” avatars up to five members.
  • Pinned messages and shared content: a details screen shows members, pinned messages, shared files, links and integration cards, plus mute and archive.
  • Search: workspace message search through chat_search_messages, scoped to conversations the actor participates in.
  • Attachments: Drive-backed workspace storage under :wsId/chats/:conversationId/*, as described on the Chat page.
  • Edit and delete: authors can edit and delete their own messages, and moderators with moderate_chat can delete any message. Each change writes a private.chat_audit_events row.
Mobile keeps the shell rules: no second top bar inside a shell body, Back through the floating navbar, and content that clears the floating dock. Mira chat failure UX is reused unchanged.

Integrations

Integrations attach typed cards to a message’s metadata.cards. Each card holds a reference ({ kind, wsId, id }), never a copy of the record. Cards load through the owning product’s internal API with the viewer’s permissions. A viewer who cannot see the record gets a “no access” card instead of its data. Slash commands (/task, /event, /meet, /mail, /file, /mira) open the same create flows. Mira joins a conversation through the existing AI chat settings and can use the same tools with the invoking user’s permissions. The card registry and command parser live in a framework-independent domain module, so web and mobile share one schema. Product calls go through @tuturuuu/internal-api on web and the matching repositories on mobile.

Rollout

  1. Worker, tickets and fallback polling. Clients use realtime only when CHAT_REALTIME_URL is set.
  2. Rebuilt web and mobile Chat surfaces.
  3. Integrations in this order: Tasks, Calendar and Meet, Mail, Drive, slash commands.
Regression coverage: Worker unit and workerd runtime tests in apps/chat-realtime, ticket route tests in apps/web, and the client fallback tests in packages/ui and apps/mobile/test/features/chat.