# Add Message History Pagination to a Socket.IO Chat

Yes. An agent replaces the replay of every stored message on connect with one bounded page and a load-earlier request, keeping connection recovery intact.

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

## What the agent does

In a chat laid out like socketio/chat-example, `index.js` is one ES module on `express`, `socket.io` `^4.7.2`, `sqlite` with `sqlite3`, and `@socket.io/cluster-adapter`. The primary process forks one worker per CPU from `availableParallelism()`, each on `3000 + i`; each worker opens `chat.db`, creates `messages (id INTEGER PRIMARY KEY AUTOINCREMENT, client_offset TEXT UNIQUE, content TEXT)` if needed, and builds `new Server(server, { connectionStateRecovery: {}, adapter: createAdapter() })`. On `chat message` it inserts the row, treats a `SQLITE_CONSTRAINT` on `client_offset` as a duplicate to acknowledge, and broadcasts `io.emit('chat message', msg, result.lastID)`. On a connection that is not `socket.recovered`, it runs `db.each('SELECT id, content FROM messages WHERE id > ?', [socket.handshake.auth.serverOffset || 0])` and emits every row. `index.html` connects with `auth: { serverOffset: 0 }`, `ackTimeout: 10000` and `retries: 3`, appends each message as an `li`, and sets `socket.auth.serverOffset` to the id it just received. A new browser therefore receives the whole table, one event per row.

The agent keeps the offset mechanism, since it is what makes a reconnect cheap, and bounds the first load. A `PAGE_SIZE` constant at the top of `index.js` sets the page. On a connection with `serverOffset` of `0`, the server sends the newest page: `SELECT id, content FROM messages ORDER BY id DESC LIMIT ?`, reversed so it arrives oldest first, as one `history` event carrying the rows, the oldest id in the page and a `hasMore` flag, instead of one `chat message` event per row. On a connection with a non-zero offset, it sends rows after the offset as before, but with the same limit and the same flag, so a client that was away for a long time gets a page and a flag rather than everything it missed. A new `history before` event takes an id and an acknowledgement callback and answers with the page before that id and its own `hasMore`, from `SELECT id, content FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?`. The recovered-connection branch is untouched: when `socket.recovered` is true, Socket.IO has already replayed the missed events.

In `index.html`, the client handles `history` by inserting the rows at the top of `#messages`, remembering the oldest id, and setting `serverOffset` to the newest, so the existing `chat message` handler keeps working for live messages. A `Load earlier` button above the list, shown while `hasMore` is true, emits `history before` with the oldest id and prepends the answer while keeping the scroll position where it was. The duplicate-send protection with `client_offset`, the `ackTimeout` and `retries` settings, and the styles are unchanged.

The repository has no tests, so the agent adds `test/history.test.js` under Node's built-in test runner and a `test` script. It starts the server with one worker, uses `socket.io-client` to send more messages than one page from a first client, connects a second client fresh, and asserts it receives exactly `PAGE_SIZE` rows with `hasMore` true and nothing else; requests `history before` twice and asserts the ids strictly decrease with no overlap and the final `hasMore` is false; then disconnects a client, sends two more messages, reconnects it with its last offset, and asserts it receives just those two. In its sandbox it runs `npm install`, `npm test`, and opens the page in the browser to take a screenshot with the button and a loaded earlier page, which it attaches to the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add message history pagination to this Socket.IO chat. Read index.js, index.html and package.json first. Keep connection state recovery and the serverOffset mechanism. On a connection that is not recovered, send one history event with the newest PAGE_SIZE rows (oldest first), the oldest id and a hasMore flag, instead of emitting every row; apply the same limit when the client sends a non-zero offset. Add a history before event that takes an id and an acknowledgement and answers with the previous page and its hasMore. In index.html, render the history event, add a Load earlier button that requests the previous page and prepends it, and keep the chat message handler and client_offset logic as they are. Add test/history.test.js under node --test and a test script: a fresh client gets exactly one page, two earlier pages have strictly decreasing ids with no overlap, and a reconnect with an offset gets only the gap. Run npm install and npm test, open the page in the browser and attach a screenshot. 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 changes `index.js` and `index.html`, adds `test/history.test.js`, a `test` script and `socket.io-client` as a dev dependency in `package.json` and `package-lock.json`, and nothing else. The description shows the two new events with their payloads, explains why the recovered branch is untouched, quotes the `npm test` output, and carries the screenshot of the page with the button and an earlier page loaded.

The run's record keeps the test run and the browser session, so a reviewer can see the exact rows a fresh client received and the page loading in a real browser rather than read a description of them.

Before merging, a reviewer picks `PAGE_SIZE` for their traffic and decides whether `hasMore` on a reconnect with a large gap should also tell the user that messages were skipped, which the pull request leaves as a flag in the event and a sentence in the description.

## Run it on every Linear issue labelled pagination

A team that tracks this kind of change in Linear runs it from an automation with a `linear` trigger on a label: when an issue in the chat app's Linear team gets the label, the automation's prompt asks the agent to read the issue, find the unbounded query it describes in `index.js`, and open a pull request with the page, the event and the test, linking the issue. The trigger adds the issue's title and description after the prompt as event text, so the prompt itself holds no placeholder.

Each labelled issue starts one run, with its own sandbox and record, and the pull request it opens is linked back from the session. An issue that names a query the agent cannot find ends with an answer saying so and no pull request.

## Why run it on Rush?

The hard part of this change is not the SQL but the three paths a client can arrive on: fresh, with an old offset, or recovered by Socket.IO itself, and a change that breaks one of them is invisible until a user reconnects. In a Rush sandbox the agent runs real clients against a real server for all three and shows the page in a browser, so the pull request proves each path rather than describing it.

The test run and the browser session stay in the run's record and the pull request carries the screenshot, so review is reading two events and a test rather than standing up a server to try it. A team with several Socket.IO services runs the job on each at once, one sandbox and one pull request each.

## Frequently asked questions

### Does this break connection state recovery?

No. The `socket.recovered` branch is untouched: when Socket.IO recovers a connection it replays the missed events itself and the server sends no history. The new behavior applies only to a connection Socket.IO could not recover, which is where the full-table replay happened before.

### What happens on a reconnect with an old offset?

The server sends the rows after the offset, as it did before, but at most one page, with `hasMore` set when there were more. The test covers the short gap, where the client gets exactly the messages it missed; a long gap gets a page and the flag, and the client can request earlier pages from there.

### Why one history event instead of one chat message per row?

Because a page of rows is one unit: the client needs the oldest id and the `hasMore` flag with it to render a button, and prepending a batch keeps the scroll position in one move. Live messages still arrive one `chat message` event each, through the handler that already exists.

### Does the cluster adapter change anything here?

No. Each worker answers `history` and `history before` from the shared `chat.db` for its own sockets, and the adapter only carries the live `io.emit` broadcast between workers, as it did before. The test runs the server with one worker to keep a single port; the code path is the same with many.

## More Socket.IO jobs

- [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/)
- [Add Rate Limiting to a Socket.IO Chat Server](https://getrush.ai/run/add-rate-limiting/socket-io/)

## The same job on other stacks

- [Add Pagination to a Wagtail Blog Index](https://getrush.ai/run/add-pagination/wagtail/)
- [Add Pagination to an aiohttp App](https://getrush.ai/run/add-pagination/aiohttp/)
- [Add Pagination to an Eleventy Blog Archive](https://getrush.ai/run/add-pagination/eleventy/)

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