# Show Online Users in a Socket.IO Chat

Yes. An agent adds usernames and a live online list to your Socket.IO chat, counting sockets across cluster workers with fetchSockets, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-online-users/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 whole app, which in a chat laid out like socketio/chat-example is two files. `index.js` runs under `node:cluster`: the primary forks one worker per `availableParallelism()` with `PORT` set to 3000 plus the index and calls `setupPrimary()` from `@socket.io/cluster-adapter` 0.2.2; each worker opens `chat.db` with `sqlite` 5.0.1 over `sqlite3` 5.1.6, creates a `messages` table with a unique `client_offset`, serves `index.html` from Express 4.18.2, and builds a Socket.IO 4.7.2 `Server` with `connectionStateRecovery: {}` and `adapter: createAdapter()`. A `chat message` handler inserts the row, treats a `SQLITE_CONSTRAINT` error as a duplicate and acknowledges it, and emits the message to everyone with `result.lastID`. On a connection that is not `socket.recovered`, it replays rows after `socket.handshake.auth.serverOffset`. `index.html` connects with `io({ auth: { serverOffset: 0 }, ackTimeout: 10000, retries: 3 })` and sends `${socket.id}-${counter++}` as the client offset. There is no username, no `test` script, and `.gitignore` lists only `node_modules/` and `chat.db`.

The client gets a name. `index.html` asks for one on load, keeps it in `localStorage`, and sends it in the same `auth` object as `serverOffset`, so the name travels with every reconnect and with connection state recovery. A `<ul id="users">` beside the message list renders a `users` event, an array of names, each time it arrives. The server reads `socket.handshake.auth.username` in an `io.use` middleware, refuses the connection with `next(new Error("username required"))` when it is missing, and stores the name in `socket.data.username` so it survives on the socket rather than in a closure.

Presence has to be computed across workers, because each worker holds only its own sockets. The agent writes one `publishUsers()` that calls `await io.fetchSockets()`, which the cluster adapter answers with the sockets of every worker including their `data`, maps them to `username`, drops duplicates with a `Set` so a person with two tabs counts once, and emits `users` to everyone. It runs after each connection and in each socket's `disconnect` handler, after the adapter has removed the socket. The handler stays inside the worker branch of `index.js`; the primary only forks.

To test it, the agent moves the worker's app into `app.js`, a function that takes a port and a database path and returns the `Server`, so `index.js` keeps the cluster code and a test can start one worker in-process without forking. `test/users.test.js` uses `node:test`, which the Node 20 base image in `.codesandbox/Dockerfile` ships, and `socket.io-client` as a dev dependency: two clients named `ann` and `bob` connect and both receive `users` containing both names; a second `ann` tab does not add a second entry; a client with no username gets `connect_error`; after `bob` disconnects, `ann` receives a list without him. A `test` script runs `node --test`, and the suite points the app at a temporary database file so `chat.db` is untouched.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add an online users list to this Socket.IO chat. Read package.json, package-lock.json, index.js, index.html, .gitignore and .codesandbox/Dockerfile first. The server runs one worker per CPU with @socket.io/cluster-adapter, so presence must be computed with io.fetchSockets() rather than a per-process map. Ask for a username on the client, store it in localStorage, send it in the socket auth object next to serverOffset, refuse connections without one in an io.use middleware, keep it in socket.data.username, and emit a deduplicated users array to everyone after each connect and disconnect; render it in a list beside the messages. Move the worker's app into app.js as a function of port and database path so a test can start one worker in-process, and write node --test tests with socket.io-client covering two users, a duplicate tab, a missing username and a disconnect. Add a test script, run it, and open a pull request that quotes the 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 adds `app.js` and `test/users.test.js`, changes `index.js` (the cluster branch now calls `app.js`), `index.html` (the prompt, the `auth` field, the list and its `users` handler), `package.json` and `package-lock.json` (the `test` script and `socket.io-client` as a dev dependency), and the README (how a name is chosen and what the list shows). Its description quotes the `node --test` output and the JSON of a `users` event.

A reviewer opens two tabs with different names and a third with a repeated one, then watches the list as tabs close. In the code they look for the two things that go wrong with presence: a `publishUsers()` called before the adapter has dropped the leaving socket, and a name read from a closure instead of `socket.data`, which would be lost on recovery.

Whether the middleware should reject or assign a guest name is left as a question in the description, with the stricter behaviour implemented.

## Run it on every Linear issue labelled chat

An automation on the Project with a `linear` trigger on `linear.issue.labeled` and the label `chat` starts one read-only run per issue, which reads `app.js` and comments on the issue with how the feature fits the existing `users` and `chat message` events. The trigger adds the issue after the prompt and fills in no placeholder.

The run that pushes the branch is started from the team's own server with this body, the repository in `resources`, the issue URL as a second resource, and a `request_id` that is a UUID v5 of the issue id, so a retried webhook delivery returns the run already started rather than opening two pull requests.

## Why run it on Rush?

Presence bugs appear only with several real connections and several processes, which is exactly what a laptop test skips. The agent starts the server in its own sandbox, drives it with real Socket.IO clients, runs the suite and keeps the output with the pull request, so the first evidence a reviewer sees is a passing test rather than a screenshot of two browser tabs.

The change is shaped by the repository's own choices: the cluster adapter, `socket.data`, the `auth` object that already carries `serverOffset`. A team with several Socket.IO services starts the same request on each at once and gets a pull request per service that reads its own `index.js`.

## Frequently asked questions

### Why fetchSockets and not a Map of names?

Each worker only sees its own connections. A `Map` in one process would list the users of that process alone. `io.fetchSockets()` asks every worker through the cluster adapter and returns their sockets with `data`, so the list is the same whichever worker a client landed on.

### Does connection state recovery keep the name?

Yes. The name is sent in `auth`, which the client resends on every connect, and stored in `socket.data`, which recovery restores. A recovered socket does not replay messages, and the server still republishes the list for it.

### Why does a user with two tabs appear once?

The list is built from a `Set` of usernames rather than of sockets. Two tabs are two sockets with one name, and the name stays in the list until the last of them disconnects.

### Why move the app into app.js?

`index.js` forks workers at import time, so a test cannot require it. `app.js` exports a function that builds one worker's server on a given port and database path; `index.js` calls it in the worker branch and the tests call it directly.

### What about a sign-in instead of a typed name?

The `auth` object is where a session token would go too. The middleware would verify it and set `socket.data.username` from the account instead of trusting the client, and the rest of the change stays the same.

## More Socket.IO jobs

- [Add Message History Pagination to a Socket.IO Chat](https://getrush.ai/run/add-pagination/socket-io/)
- [Add Private Messaging to a Socket.IO Chat](https://getrush.ai/run/add-private-messaging/socket-io/)
- [Add Prometheus Metrics to a Socket.IO Server](https://getrush.ai/run/add-prometheus-metrics/socket-io/)

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

- [Add Open Graph Tags to a Leptos App](https://getrush.ai/run/add-open-graph-tags/leptos/)
- [Add Open Graph Tags to an mdBook Site](https://getrush.ai/run/add-open-graph-tags/mdbook/)
- [Add Open Graph Tags to Sphinx Docs](https://getrush.ai/run/add-open-graph-tags/sphinx/)

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