> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tuturuuu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Chat realtime and integrations

> Cloudflare Durable Object delivery for Tuturuuu Chat, the web and mobile experience it serves, and how Chat links Tasks, Calendar, Meet, Mail and Drive.

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

| Decision | Scope | Default | Exceptions |
| - | - | - | - |
| Postgres is the source of truth; realtime frames only signal and carry already-persisted DTOs | Web, Chat satellite, mobile | Always | Typing and presence are ephemeral and never stored |
| Clients connect straight to the Worker over WebSocket with a short-lived ticket from `apps/web` | Web, Chat satellite, mobile | When `CHAT_REALTIME_URL` is set | Without it, clients poll; the SSE proxy route returns `realtime_unavailable` |
| One Durable Object per conversation and one per workspace inbox | All realtime traffic | Always | None |
| Realtime never widens access: tickets are minted after the same membership and `view_chat` checks as the REST routes | All realtime traffic | Always | None |
| Push skips recipients who have the conversation open in the foreground | Mobile push | When the conversation room reports them | Mentions always push unless the conversation is muted |
| Message edits and deletes keep an audit trail; deleted messages render as a tombstone | Web, mobile | Always | Workspace moderators can see who deleted a message, not its content |
| Integration actions run through the owning product's API with the actor's own permissions | Chat cards and slash commands | Always | None. Chat never bypasses Tasks, Calendar, Meet, Mail or Drive authorization |

## Realtime architecture

```text theme={null}
client ──ticket──▶ apps/web /chat/realtime/ticket   (auth, membership, view_chat)
client ══WS══════▶ chat-realtime Worker ─▶ WorkspaceInbox DO  (wsId)
client ══WS══════▶ chat-realtime Worker ─▶ ConversationRoom DO (wsId:conversationId)
apps/web ─publish─▶ chat-realtime Worker ─▶ ConversationRoom DO ─▶ WorkspaceInbox DO
```

* **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.

| Bound | Value |
| - | - |
| Client frame size | 2 KB; larger frames close the socket with `1009` |
| Client frames per socket | 20 per 10 s (typing, presence, read); excess closes with `1008` |
| Sockets per user per room | 5; the oldest is closed |
| Accepted connection attempts per user per room | 10 per minute |
| Presence and typing broadcasts per room | 20 per 10 s |
| Sockets per room | 500 per conversation, 5,000 per workspace inbox |
| Publish body | 64 KB, one event per request |
| Stored frames per room | 200, at most 15 minutes old |

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](https://docs.tuturuuu.com/platform/applications/chat.md)
  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.

| Integration | From chat | Card |
| - | - | - |
| Tasks | Create a task from a message (prefilled title, link back), or link an existing one | Status, assignee, due date; toggle complete |
| Calendar | Schedule an event with the conversation members | Time, attendees, RSVP |
| Meet | Start or schedule a meeting | Join card with live participant count |
| Mail | Share a thread into chat, or start a chat from a Mail thread | Subject, participants, open in Mail |
| Drive | Attach or share a Drive file | File preview with signed download |
| People | Mention members across apps | Profile hover with their work in Tasks and Calendar |

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`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.