# Add Rooms to a Socket.IO Chat

Yes. An agent adds rooms to your Socket.IO chat with a join event, per-room broadcasts and replay, a room column in SQLite, tests across workers, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-rooms/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 how messages flow today before it scopes them. In a chat server like socketio/chat-example, `index.js` is one file: the cluster primary forks one worker per core with `cluster.fork({ PORT: 3000 + i })` and calls `setupPrimary()` from `@socket.io/cluster-adapter`; each worker opens `chat.db` through `sqlite` and `sqlite3`, runs `CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, client_offset TEXT UNIQUE, content TEXT)`, and builds `new Server(server, { connectionStateRecovery: {}, adapter: createAdapter() })`. The `chat message` handler inserts a row, treats SQLite error 19 as a duplicate and acknowledges it, then calls `io.emit('chat message', msg, result.lastID)` to every socket on every worker; when `socket.recovered` is false it replays rows above `socket.handshake.auth.serverOffset`. `index.html` connects with `auth: { serverOffset: 0 }`, `ackTimeout` and `retries`, sends each message with a `clientOffset` of `${socket.id}-${counter++}`, and stores the returned id as `socket.auth.serverOffset`. `package.json` is `type: module` with `socket.io` `^4.7.2`, `express` `^4.18.2`, `@socket.io/cluster-adapter` `^0.2.2`, a `start` script and no test script.

The schema is the first change and the one that can bite an existing deployment. `CREATE TABLE IF NOT EXISTS` does nothing to a `chat.db` that already exists, so the agent adds a `room TEXT NOT NULL DEFAULT 'general'` column with an `ALTER TABLE` guarded by a `PRAGMA table_info(messages)` check, and an index on `(room, id)` for the replay query. Existing rows land in `general`, which is also the room the client joins when the page has no `?room=` in its URL. On the server, a `join` event takes a room name, validates it against a short pattern, leaves the socket's previous room, calls `socket.join(room)`, stores the name on `socket.data.room`, and replays that room's rows with `SELECT id, content FROM messages WHERE room = ? AND id > ?` from the offset the client sends in the join; the `chat message` handler writes the room with the row and broadcasts with `io.to(socket.data.room).emit` instead of `io.emit`. The global autoincrement `id` keeps working as the offset within a room because the query filters by room first.

Two properties of the existing setup decide how reconnects work. The cluster adapter forwards `io.to(room).emit()` to the other workers, so a room spans every process without more code. Its feature table, though, lists connection state recovery as unsupported, so the agent does not rely on a recovered socket still being in its room: `index.html` sends `join` on every `connect` event with the room and the last offset it saw, and the server treats a repeated join as idempotent. The client reads the room from `location.search`, shows it in the title, and keeps the `clientOffset` scheme unchanged so the `UNIQUE` constraint still deduplicates retries.

Tests need a server that is not the cluster entry point, so the worker body moves to `server.js` as an exported `createServer({ dbFile })` that `index.js` calls inside each fork; `test/rooms.test.js` uses `node:test`, which is available because `index.js` already imports `availableParallelism` from `node:os` and so already requires a Node version that ships the test runner, and `socket.io-client` as a new dev dependency. The cases: two clients in different rooms, a message in one never reaches the other; a client joining a room after messages exist receives only that room's rows; a client that disconnects and reconnects with its offset receives only what it missed in its room; and an invalid room name is refused with an error in the acknowledgement. The database is a temporary file per test run. The agent adds a `test` script, runs `npm install` and `npm test` in its sandbox and keeps the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add rooms to this Socket.IO chat. Read package.json, index.js, index.html, README.md and the .codesandbox files first. Add a room TEXT NOT NULL DEFAULT 'general' column to the messages table with an ALTER TABLE guarded by PRAGMA table_info so an existing chat.db keeps working, and an index on room and id. Add a join event that validates the room name, leaves the previous room, calls socket.join, stores the room on socket.data, and replays that room's messages after the offset the client sends; write the room with each message and broadcast with io.to(room) instead of io.emit. In index.html read the room from the ?room= query, default to general, and send join with the last offset on every connect event because the cluster adapter does not support connection state recovery. Move the worker body into server.js as an exported createServer so tests can start it without the cluster. Add socket.io-client as a dev dependency and node:test tests for isolation between rooms, replay on join, replay after reconnect, and a refused room name, using a temporary database file. Add a test script, run npm test, include the output, update the README, and open a pull request.",
  "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

What comes back is a pull request that adds `server.js` and `test/rooms.test.js`, and changes `index.js`, `index.html`, `package.json`, `package-lock.json` and `README.md`. The `clientOffset` scheme, the `UNIQUE` constraint and the cluster primary are unchanged.

The description explains the guarded `ALTER TABLE`, why the client joins again on every connect, and how the global offset still works per room, and quotes the `node --test` output. The commands and their full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer runs `npm start`, opens two tabs with different `?room=` values and a third in the same room as one of them, and watches which tab receives what; then restarts the server to see the old `general` messages replay. A follow-up message to the same session can add a room list endpoint, a cap on rows replayed per join, or a check that a user may enter a room.

## Run it on every chat server where every message reaches every socket

A team with several Socket.IO services sends one `POST /o/{org}/sessions` per repository with this prompt as `input` and the repository in `resources`. Each run reads its own server file, so a service on the Redis adapter gets the same room logic with the recovery note dropped where that adapter supports it, and one that already persists a room keeps its column name.

Send a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` reports when each run the key starts finishes, with `session_url` for the pull request link and the test output.

## Why run it on Rush?

Rooms are three calls in the Socket.IO API and a dozen decisions around them: what happens to the existing table, whether an offset still means anything per room, what a reconnecting socket remembers under this adapter, and how to test any of it under a cluster. The agent reads the schema, the adapter and the client's offset scheme, and proves isolation and replay with real sockets against a real server in a sandbox of its own, with the output kept.

The pull request carries the schema guard, the server and client changes and the tests, so a reviewer sees that a message in one room never crosses into another before they open two browser tabs. Several services can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Will the schema change break my existing chat.db?

No. `CREATE TABLE IF NOT EXISTS` would leave an old file without the column, so the agent checks `PRAGMA table_info(messages)` and runs `ALTER TABLE … ADD COLUMN` only when `room` is missing. Existing rows get the default `general` and keep replaying there.

### Do rooms work across the cluster workers?

Yes. The cluster adapter forwards `io.to(room).emit()` to every worker, so two clients in the same room on different processes both receive the message. The adapter does not support connection state recovery, which is why the client re-joins on every `connect`.

### Can a socket be in several rooms at once?

Socket.IO allows it, but this chat keeps one room per socket on `socket.data.room` so a message has one destination. Say in the prompt if you want a socket to subscribe to several rooms and the agent changes the join to add rather than replace.

### Why does the client join again on reconnect?

With this adapter a reconnecting socket cannot be assumed to have kept its rooms, so the page sends `join` with the last offset it saw on every `connect` event. The server treats a repeated join as idempotent and replays only rows above that offset in that room.

### Does this add authorization to rooms?

No. The join handler validates the name's shape and nothing else, since the example has no users. Rooms are a server-only concept, so a check on who may join belongs in that handler; name your auth model and the agent adds it there.

## More Socket.IO jobs

- [Add Structured Logging to a Socket.IO Server](https://getrush.ai/run/add-structured-logging/socket-io/)
- [Add a Typing Indicator to a Socket.IO Chat](https://getrush.ai/run/add-typing-indicator/socket-io/)
- [Convert a Socket.IO Chat Server to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/socket-io/)

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

- [Add a Typed RPC Client to a Hono API](https://getrush.ai/run/add-rpc-client/hono/)
- [Add an RSS Feed to a Contentlayer Blog](https://getrush.ai/run/add-rss-feed/contentlayer/)
- [Add an RSS Feed to a Starlight Docs Site](https://getrush.ai/run/add-rss-feed/starlight/)

## 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/)
