# Add Private Messaging to a Socket.IO Chat

Yes. An agent adds usernames, a live user list and one-to-one messages to your Socket.IO chat, persisted and replayed on reconnect across workers, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-private-messaging/socket-io/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the server and the page before it adds an event. In an app laid out like socketio/chat-example, `index.js` is an ES module that forks one worker per CPU with `node:cluster` (each on `PORT` 3000 plus its index) and calls `setupPrimary()` from `@socket.io/cluster-adapter`; each worker opens `chat.db` with `sqlite` over `sqlite3`, creates a `messages` table with `id`, a unique `client_offset` and `content`, builds a `Server` with `connectionStateRecovery: {}` and the cluster adapter, and serves `index.html` from `/`. The one event, `chat message`, inserts the message with its client offset, treats a SQLite constraint error (`errno` 19) as an already-delivered duplicate and acknowledges it, and otherwise broadcasts with `io.emit` and the new row id. A socket that was not recovered replays rows with `id` above `socket.handshake.auth.serverOffset`. `index.html` connects with `auth.serverOffset`, `ackTimeout` 10000 and `retries` 3, sends each message with a `${socket.id}-${counter++}` offset, and appends every `chat message` to a list while advancing `serverOffset`. `package.json` depends on `socket.io` `^4.7.2`, `express` `^4.18.2`, the cluster adapter and the two SQLite packages, and has no test script.

Private messaging needs identity, and the example has none. The agent adds an `io.use` middleware that rejects a handshake without `auth.username` and stores it on `socket.data.username`, and has each socket `socket.join` a room named after its username, so `socket.to(username).emit(...)` reaches every tab that user has open on any worker, because rooms go through the cluster adapter. The page gains a username prompt before `io()` is called and passes it in `auth` beside `serverOffset`. A `users` event sends the list of connected usernames, built from `io.fetchSockets()` so it covers all workers, on connect and whenever someone joins or leaves, and the page renders it as a list the reader can click to pick a recipient.

Messages to one person follow the pattern the public channel already uses, so delivery guarantees stay the same. A `private message` event carries the recipient, the content and a client offset; the server inserts into a new `private_messages` table with `id`, a unique `client_offset`, `from_user`, `to_user` and `content`, treats constraint errors as duplicates exactly as `chat message` does, emits to the recipient's room and back to the sender's room with the row id, and acknowledges. Replay on reconnect selects rows where `to_user` or `from_user` is the socket's username and `id` is above a second offset the client keeps for private messages, since the two tables have separate id sequences. The public `chat message` handler is untouched.

The example has no tests, so the agent adds `socket.io-client` as a dev dependency and a `node --test` script with a test that starts the server in-process on a free port with the cluster disabled, connects two clients as different usernames, sends a private message from one, asserts the other receives it and a third client does not, then disconnects the recipient, sends again, reconnects with the stored offset and asserts the replay. It runs the test and the full clustered server (`npm start`) in the sandbox, opens the page in its browser with two tabs to see the user list and a private exchange, and only then opens the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add private messaging to this Socket.IO chat. Read package.json, index.js and index.html first. Add an io.use middleware that requires auth.username and stores it on socket.data, join each socket to a room named after its username, and emit a users list built with io.fetchSockets on connect, join and leave. Add a private message event with recipient, content and client offset that inserts into a new private_messages table (id, unique client_offset, from_user, to_user, content), treats a SQLite constraint error as a duplicate like chat message does, emits to the recipient's room and the sender's room with the row id, and acknowledges; replay private rows above a separate client offset on reconnect. Update index.html with a username prompt passed in auth, a clickable user list and a recipient field. Leave the public chat message path unchanged. Add socket.io-client as a dev dependency and a node --test script with a test that covers delivery to the recipient only and replay after reconnect, run it and the clustered server, check two tabs in the browser, and open a pull request that quotes the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request changes `index.js`, `index.html` and `package.json` (one dev dependency and a `test` script) and adds a test file. Its description explains the room-per-username design and why it works across the cluster adapter, shows the `private_messages` schema beside the existing `messages` one, and quotes the `node --test` output from the sandbox along with a screenshot of the two tabs.

A reviewer checks that the `io.use` middleware runs before any room join, that the recipient check uses the username from `socket.data` and never one supplied in the event, that the replay query cannot return another user's conversation, and that the public path still deduplicates by `client_offset` exactly as before.

From then on a user who closes the laptop and reopens it gets the public and private messages they missed, in order, and a second browser tab for the same user sees the same conversation.

## Run it on every chat service repository

A team with several real-time services sends this body once per repository from its own server, each `POST /o/{org}/sessions` with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own server: one on the Redis adapter instead of the cluster adapter gets the same rooms through it, and one with authentication already in place reuses its user identity instead of a prompt.

An automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request adds a socket event, check that it persists with a unique client offset, replays on reconnect and is covered by the test script, and post a review" runs once per pull request. The trigger adds the pull request after the prompt and fills in nothing else. Only work by an owner, member or collaborator fires it.

## Why run it on Rush?

The hard part of private messaging in this app is not the emit; it is keeping the delivery guarantees the example already has (deduplication, recovery, replay) while running on several workers, where a naive map of username to socket id breaks the moment two tabs land on different processes. The agent reuses the adapter-backed rooms, writes a test that actually disconnects and reconnects a client, runs the clustered server and a browser in its own sandbox, and keeps every command and its output with the pull request.

A reviewer reads one handler, one query and one test instead of reproducing a reconnect by hand. A team with several chat services starts the same request across all of them at once.

## Frequently asked questions

### Why rooms instead of a map of users to sockets?

Because the server runs one worker per CPU with the cluster adapter, and a user's two tabs can land on two workers. A room named after the username is shared through the adapter, so `socket.to(username)` reaches every tab on every worker; an in-memory map would reach only the local one.

### Can someone send as another user?

The sender's name comes from `socket.data.username`, set once in the handshake middleware, never from the event payload. The pull request points at that line, and the test includes a third client that must not receive the message.

### What happens to messages sent while the recipient is offline?

They are stored in `private_messages` and replayed when the recipient reconnects with their last private offset, the same mechanism the public chat uses with `serverOffset`. The test covers exactly that path.

### Does the public chat change?

No. The `chat message` handler, the `messages` table and the public replay are untouched; the new event and table sit beside them, and the only change to the client's public path is the username prompt before connecting.

## More Socket.IO jobs

- [Add Prometheus Metrics to a Socket.IO Server](https://getrush.ai/run/add-prometheus-metrics/socket-io/)
- [Add Rate Limiting to a Socket.IO Chat Server](https://getrush.ai/run/add-rate-limiting/socket-io/)
- [Add the Redis Adapter to a Socket.IO Server](https://getrush.ai/run/add-redis-adapter/socket-io/)

## More jobs like this: Hand off a long task

- [Add a Production Override to a Docker Compose Project](https://getrush.ai/run/add-production-compose-override/docker-compose/)
- [Add a Progress Bar to a Go Command-Line Tool](https://getrush.ai/run/add-progress-bar/go-cli/)
- [Add Prometheus Metrics to an Actix Web App](https://getrush.ai/run/add-prometheus-metrics/actix/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
