Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(api): page messages with an `after` keyset cursor
Yudhi Armyndharisf8495548f5ce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a49160e89..dd2ea6cf5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- `GET /sessions/{sessionId}/messages` accepts `after`, a keyset cursor holding the `id` of the last+ message of the previous page. It anchors the window to a row instead of a count, so a message+ arriving mid-walk can no longer shift it and make a page repeat or skip rows. `offset` keeps+ working unchanged; an `after` that names no row in the session gives `400`+ ([#1479](https://github.com/rmyndharis/OpenWA/issues/1479)).- Each engine now names the install-time patches its library is missing as it starts, rather thanonly the message-id backport. A source install applies them with `--best-effort`, so a patch thatcould not apply left one line in the `npm install` transcript and nothing afterwards; thediff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 7d9b0154e..12f99ecaf 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1207,12 +1207,13 @@ Get persisted message history for a session from the local DB (paginated, filter**Query parameters**-| Name | Type | Required | Default | Description |-| ------ | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------- |-| chatId | string | No | — | Filter by chat ID. Matched across `@c.us` / `@s.whatsapp.net` dialects via the lid-mapping table. |-| from | string | No | — | Filter by sender. A phone also matches any lid that resolves to it. |-| limit | integer | No | 50 | Clamped to `[1,100]`; a non-finite value falls back to 50. |-| offset | integer | No | 0 | Clamped to `>=0`; a non-finite value falls back to 0. |+| Name | Type | Required | Default | Description |+| ------ | ------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| chatId | string | No | — | Filter by chat ID. Matched across `@c.us` / `@s.whatsapp.net` dialects via the lid-mapping table. |+| from | string | No | — | Filter by sender. A phone also matches any lid that resolves to it. |+| limit | integer | No | 50 | Clamped to `[1,100]`; a non-finite value falls back to 50. |+| offset | integer | No | 0 | Clamped to `>=0`; a non-finite value falls back to 0. |+| after | string | No | — | Keyset cursor: the `id` of the last message of the previous page. Anchors the window to a row rather than a count, so a message arriving mid-walk cannot shift it. Takes precedence over `offset`. Unknown in this session gives `400`. |**Response** `200`@@ -1239,7 +1240,7 @@ Get persisted message history for a session from the local DB (paginated, filter}```-Each `Message`: `{ id (uuid), sessionId, waMessageId (string|null), chatId, from, to, body (string|null), type, direction ('incoming'|'outgoing'), timestamp (number|null), metadata (object|null), status ('pending'|'sent'|'delivered'|'read'|'failed'), createdAt (ISO date) }`. Ordered by `createdAt` DESC, then `id` DESC. The tiebreaker matters: `createdAt` is not unique (SQLite stores whole seconds, a PostgreSQL bulk write ties every row it inserts, and a history backfill carries WhatsApp's own second-resolution timestamp), and without a total order two pages of one walk can repeat a row and omit another. Note that `offset` still addresses a position by count, so a list taking concurrent writes can shift under a walk; page promptly and treat a repeated `id` as a duplicate. The response is the raw service object (no envelope). Unlike the live `IncomingMessage` shape below, this persisted `Message` does **not** carry `kind` — re-derive the chat kind from `chatId` (see `ChatKind` / `chatKind()`) if needed.+Each `Message`: `{ id (uuid), sessionId, waMessageId (string|null), chatId, from, to, body (string|null), type, direction ('incoming'|'outgoing'), timestamp (number|null), metadata (object|null), status ('pending'|'sent'|'delivered'|'read'|'failed'), createdAt (ISO date) }`. Ordered by `createdAt` DESC, then `id` DESC. The tiebreaker matters: `createdAt` is not unique (SQLite stores whole seconds, a PostgreSQL bulk write ties every row it inserts, and a history backfill carries WhatsApp's own second-resolution timestamp), and without a total order two pages of one walk can repeat a row and omit another. Note that `offset` still addresses a position by count, so a list taking concurrent writes can shift under a walk: a message arriving mid-walk pushes every older row down one, and the next page re-serves a row the previous one already returned. Pass `after` instead to walk a live chat safely; it anchors on the last row you received, which an arriving message cannot move. The response is the raw service object (no envelope). Unlike the live `IncomingMessage` shape below, this persisted `Message` does **not** carry `kind` — re-derive the chat kind from `chatId` (see `ChatKind` / `chatKind()`) if needed.> **Inline media is carried up to a budget, then omitted.** `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default) bounds how much inline media one response may hold across its rows. A row is not a bounded object — `limit` is clamped to `[1,100]` but each row can carry its base64 in `metadata.media.data`, so a page of media rows could otherwise reach hundreds of megabytes and fail the read outright. The budget is spent newest-first, matching the `createdAt` DESC order above, so a page that cannot carry everything keeps the most recent media. Past it a payload is replaced with `{ mimetype, filename?, omitted: true, sizeBytes }` — the same marker the engine emits for inbound media over `MEDIA_DOWNLOAD_MAX_BYTES` — and the bytes remain available from [`GET /messages/:chatId/:messageId/media`](#get-apisessionssessionidmessageschatidmessageidmedia). Two rules bound the edges: the newest payload is always inlined even when it alone exceeds the budget (otherwise a single large photo would be permanently unreadable through this route), and a budget of `0` means "never inline" and grants no such allowance. The knob is validated at boot — `8MiB` would parse to 8 bytes — and is forwarded by both compose files. The MCP `MessageList` tool shares this path and the same budget.diff --git a/openapi.json b/openapi.jsonindex ab24c614b..3b57ac85b 100644--- a/openapi.json+++ b/openapi.json@@ -2297,6 +2297,15 @@"schema": {"type": "number"}+ },+ {+ "name": "after",+ "required": false,+ "in": "query",+ "description": "Keyset cursor: the id of the last message of the previous page. Anchors the window to a row rather than a count, so a message arriving mid-walk cannot shift it. Takes precedence over offset.",+ "schema": {+ "type": "string"+ }}],"responses": {diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 012a1aa35..5a568fab4 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -169,6 +169,9 @@ type ListMessagesQuery struct {From *stringLimit *intOffset *int+ // After is a keyset cursor: the id of the last message of the previous page. Takes+ // precedence over Offset.+ After *string}func (q *ListMessagesQuery) values() url.Values {@@ -177,6 +180,7 @@ func (q *ListMessagesQuery) values() url.Values {setStr(v, "from", q.From)setInt(v, "limit", q.Limit)setInt(v, "offset", q.Offset)+ setStr(v, "after", q.After)return v}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListMessagesQuery.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListMessagesQuery.javaindex 426b1d71e..bb7b59e1b 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListMessagesQuery.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListMessagesQuery.java@@ -1,7 +1,7 @@package com.rmyndharis.openwa.model;/** Query parameters for {@code GET /sessions/:id/messages}. Null fields are omitted. */-public record ListMessagesQuery(String chatId, String from, Integer limit, Integer offset) {+public record ListMessagesQuery(String chatId, String from, Integer limit, Integer offset, String after) {public static Builder builder() {return new Builder();}@@ -11,6 +11,7 @@ public record ListMessagesQuery(String chatId, String from, Integer limit, Integprivate String from;private Integer limit;private Integer offset;+ private String after;public Builder chatId(String v) {this.chatId = v;@@ -32,8 +33,14 @@ public record ListMessagesQuery(String chatId, String from, Integer limit, Integreturn this;}+ /** Keyset cursor: the id of the last message of the previous page. Takes precedence over offset. */+ public Builder after(String v) {+ this.after = v;+ return this;+ }+public ListMessagesQuery build() {- return new ListMessagesQuery(chatId, from, limit, offset);+ return new ListMessagesQuery(chatId, from, limit, offset, after);}}}diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 5c2561363..0c83df282 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -468,6 +468,8 @@ export interface ListMessagesQuery {from?: Jid;limit?: number;offset?: number;+ /** Keyset cursor: the `id` of the last message of the previous page. Takes precedence over `offset`. */+ after?: string;}export interface MessageHistoryQuery {diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex 912065c44..225466fc2 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -454,7 +454,8 @@ class SendPollRequest(TypedDict):# ``from`` is a Python keyword, so use the functional TypedDict form.ListMessagesQuery = TypedDict("ListMessagesQuery",- {"chatId": Jid, "from": Jid, "limit": int, "offset": int},+ # ``after`` is a keyset cursor: the id of the last message of the previous page.+ {"chatId": Jid, "from": Jid, "limit": int, "offset": int, "after": str},total=False,)diff --git a/src/modules/message/message-list-ordering.pg.spec.ts b/src/modules/message/message-list-ordering.pg.spec.tsindex 3409835e0..239d141c4 100644--- a/src/modules/message/message-list-ordering.pg.spec.ts+++ b/src/modules/message/message-list-ordering.pg.spec.ts@@ -116,4 +116,81 @@ const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';expect(served).toHaveLength(ROWS);expect(distinct.size).toBe(ROWS); // no row repeated, and therefore none missed});++ /**+ * The tiebreaker gives the list a total order; it does not stop the WINDOW drifting, because+ * `offset` addresses a position by count. A message arriving mid-walk pushes every older row down+ * one, so the next offset re-reads a row the previous page already served. `after` anchors on the+ * last row instead, which a concurrent insert cannot move.+ */+ describe('a message arriving between pages', () => {+ const LIVE_SESSION = 'sess-live-walk';+ const LIVE_ROWS = 500;+ const LIVE_PAGE = 100;++ const arrive = (n: number): Promise<unknown> =>+ repository.insert({+ id: randomUUID(),+ sessionId: LIVE_SESSION,+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ body: `live-${n}`,+ direction: MessageDirection.INCOMING,+ createdAt: new Date('2026-06-01T00:00:00.000Z'), // newer than the fixture: lands on page 0+ });++ beforeEach(async () => {+ await repository.delete({ sessionId: LIVE_SESSION });+ await repository.insert(+ Array.from({ length: LIVE_ROWS }, (_, i) => ({+ id: randomUUID(),+ sessionId: LIVE_SESSION,+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ body: `m${i}`,+ direction: MessageDirection.INCOMING,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ })),+ );+ });++ afterAll(async () => {+ await repository.delete({ sessionId: LIVE_SESSION });+ });++ it('shifts an offset walk, so it serves a row twice', async () => {+ const served: string[] = [];+ for (let page = 0; page * LIVE_PAGE < LIVE_ROWS; page++) {+ const { messages } = await service.getMessages(LIVE_SESSION, { limit: LIVE_PAGE, offset: page * LIVE_PAGE });+ served.push(...messages.map(m => m.id));+ await arrive(page);+ }++ expect(served.length - new Set(served).size).toBeGreaterThan(0);+ });++ it('does not shift an `after` walk', async () => {+ const served: string[] = [];+ let after: string | undefined;+ for (let page = 0; page * LIVE_PAGE < LIVE_ROWS; page++) {+ const { messages } = await service.getMessages(LIVE_SESSION, { limit: LIVE_PAGE, after });+ served.push(...messages.map(m => m.id));+ after = messages[messages.length - 1]?.id;+ await arrive(page);+ }++ expect(served).toHaveLength(LIVE_ROWS);+ expect(new Set(served).size).toBe(LIVE_ROWS);+ });++ it('rejects a cursor naming a row in another session', async () => {+ const foreign = await repository.findOne({ where: { sessionId: SESSION_ID } });++ await expect(service.getMessages(LIVE_SESSION, { limit: LIVE_PAGE, after: foreign!.id })).rejects.toThrow(+ /Unknown cursor/,+ );+ });+ });});diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex a15ef14c6..e9ecee4b7 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -76,6 +76,13 @@ export class MessageController {})@ApiQuery({ name: 'limit', required: false, type: Number, description: 'Max messages to return (default 50)' })@ApiQuery({ name: 'offset', required: false, type: Number, description: 'Offset for pagination' })+ @ApiQuery({+ name: 'after',+ required: false,+ description:+ 'Keyset cursor: the id of the last message of the previous page. Anchors the window to a row ' ++ 'rather than a count, so a message arriving mid-walk cannot shift it. Takes precedence over offset.',+ })@ApiResponse({status: 200,description: 'Message history',@@ -87,12 +94,14 @@ export class MessageController {@Query('from') from?: string,@Query('limit') limit?: string,@Query('offset') offset?: string,+ @Query('after') after?: string,) {return this.messageService.getMessages(sessionId, {chatId,from,limit: limit ? parseInt(limit, 10) : undefined,offset: offset ? parseInt(offset, 10) : undefined,+ after,});}diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 91d682f0b..c10ec0d2b 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -186,6 +186,62 @@ describe('MessageService', () => {});});+ // ── getMessages keyset cursor ─────────────────────────────────────++ describe('getMessages anchors on `after` instead of a count', () => {+ /** The cursor path clones for the count and reads rows separately, so getManyAndCount is unused. */+ const makeCursorQb = (rows: Message[]) => {+ const qb = {+ where: jest.fn().mockReturnThis(),+ orderBy: jest.fn().mockReturnThis(),+ addOrderBy: jest.fn().mockReturnThis(),+ skip: jest.fn().mockReturnThis(),+ take: jest.fn().mockReturnThis(),+ andWhere: jest.fn().mockReturnThis(),+ clone: jest.fn(),+ getCount: jest.fn().mockResolvedValue(7),+ getMany: jest.fn().mockResolvedValue(rows),+ getManyAndCount: jest.fn(),+ };+ qb.clone.mockReturnValue(qb);+ return qb;+ };++ it('narrows on the anchor row and leaves skip() unused, so a concurrent write cannot shift the window', async () => {+ const qb = makeCursorQb([{ id: 'm-2' } as Message]);+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);++ const result = await service.getMessages('sess-1', { after: 'm-1', offset: 500 });++ expect(qb.skip).not.toHaveBeenCalled();+ expect(qb.getManyAndCount).not.toHaveBeenCalled();+ const [clause, params] = qb.andWhere.mock.calls[0] as [string, Record<string, unknown>];+ expect(clause).toContain('(message.createdAt, message.id) <');+ // The anchor's sort key is resolved in SQL; only the id crosses the JS boundary.+ expect(clause).toContain('FROM messages anchor');+ expect(params).toEqual({ after: 'm-1', sessionId: 'sess-1' });+ // `total` counts the filter match, not the post-cursor remainder, so it stays stable per page.+ expect(result.total).toBe(7);+ });++ it('rejects a cursor that names no row in this session rather than reading as end-of-history', async () => {+ const qb = makeCursorQb([]);+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);+ repository.exists = jest.fn().mockResolvedValue(false);++ await expect(service.getMessages('sess-1', { after: 'nope' })).rejects.toThrow(BadRequestException);+ expect(repository.exists).toHaveBeenCalledWith({ where: { id: 'nope', sessionId: 'sess-1' } });+ });++ it('returns an empty page, not an error, when a valid cursor reaches the end of the history', async () => {+ const qb = makeCursorQb([]);+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);+ repository.exists = jest.fn().mockResolvedValue(true);++ await expect(service.getMessages('sess-1', { after: 'm-last' })).resolves.toEqual({ messages: [], total: 7 });+ });+ });+// ── getMessages from-filter (lid resolution becomes a hit) ─────────describe('getMessages from-filter resolves a lid to a phone', () => {// A group message whose stored author is an unresolved lid, plus a plain DM from the same person.diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 16efb3661..190e16bb3 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -28,6 +28,12 @@ export interface GetMessagesOptions {from?: string;limit?: number;offset?: number;+ /**+ * Keyset cursor: the `id` of the last row of the previous page. Anchors the window to a ROW+ * instead of to a count, so a write between two pages cannot shift it. Takes precedence over+ * `offset`, which is left working unchanged for callers that already use it.+ */+ after?: string;}/**@@ -223,7 +229,7 @@ export class MessageService implements PluginMessagePort {sessionId: string,options: GetMessagesOptions = {},): Promise<{ messages: Message[]; total: number }> {- const { chatId, from } = options;+ const { chatId, from, after } = options;// Sanitize pagination: a non-finite limit/offset — e.g. `?limit=abc` -> NaN —// must never reach TypeORM's take()/skip(). Clamp to sane bounds; fall back to defaults.const rawLimit = options.limit;@@ -243,9 +249,15 @@ export class MessageService implements PluginMessagePort {// never returns others. `id` is random, not chronological, but it is unique and stable, which// is all a total order needs..addOrderBy('message.id', 'DESC')- .skip(offset).take(limit);+ // `after` replaces the offset rather than adding to it: mixing a row anchor with a count is+ // meaningless, and silently ignoring one of the two is friendlier to an SDK that always sends+ // `offset=0` than a 400 would be.+ if (after === undefined) {+ query.skip(offset);+ }+if (chatId) {// Match across dialects: a stored chatId may be `@s.whatsapp.net` (e.g. an outbound send addressed// by a raw engine id) while the caller filters by the neutral `@c.us` from the chat list - same@@ -270,6 +282,31 @@ export class MessageService implements PluginMessagePort {});}+ if (after !== undefined) {+ // `total` keeps its documented meaning, rows matching the filters, so count before narrowing.+ const total = await query.clone().getCount();+ // The anchor's sort key is resolved INSIDE the statement. Carrying it in the cursor instead+ // would mean round-tripping a timestamp through JSON, and neither dialect survives that:+ // SQLite holds two text shapes for one instant (`datetime('now')` writes 19 chars, a stamped+ // JS Date writes 23) and compares them as text, while node-postgres truncates the column's+ // microseconds to a millisecond Date. Both mis-seek silently, which is the very failure this+ // cursor exists to remove.+ query.andWhere(+ '(message.createdAt, message.id) < ' ++ '(SELECT anchor."createdAt", anchor."id" FROM messages anchor ' ++ 'WHERE anchor."id" = :after AND anchor."sessionId" = :sessionId)',+ { after, sessionId },+ );+ const messages = await query.getMany();+ // An anchor that does not exist (or belongs to another session) makes the row comparison NULL,+ // which returns zero rows and reads exactly like the end of the history. Only pay for the+ // lookup on an empty page, and turn that silent truncation into a loud 400.+ if (messages.length === 0 && !(await this.messageRepository.exists({ where: { id: after, sessionId } }))) {+ throw new BadRequestException(`Unknown cursor '${after}' for this session`);+ }+ return { messages: spendInlineMediaBudget(messages, resolveMessageListInlineMediaBudgetBytes()), total };+ }+const [messages, total] = await query.getManyAndCount();// The 1..100 clamp above bounds the ROW COUNT, not the response: each row carries its inline// base64 in metadata.media.data. Spent newest-first (the query orders createdAt DESC), so the