Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(messages): star and unstar messages on both engines
Yudhi Armyndharis4e9058f0b09c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c79b43189..6f73bbae0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Messages can be starred and unstarred:** `POST /api/sessions/:sessionId/messages/star` with+ `{ chatId, messageId, star }`. Starring is private to the account, has no group-admin+ restriction, and never expires. Available in all five SDKs as `messages.star`.++ Best-effort on whatsapp-web.js: its `star()`/`unstar()` resolve with no value and silently do+ nothing when WhatsApp declines the message, so a `200` means the instruction was delivered rather+ than that the star is definitely set — there is no signal at the engine boundary to tell the two+ apart. Baileys applies it through an app-state modification and is exact.+- **Messages can be pinned and unpinned, on both engines:** `POST /api/sessions/:sessionId/messages/pin`and `.../messages/unpin`. `durationSeconds` is `86400` (24h, the default), `604800` (7d) or`2592000` (30d) — WhatsApp recognises no others, so anything else is a `400` here rather than adiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 0c799d451..7274da0dd 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -947,6 +947,30 @@ Pin a message in its chat for a bounded window.> On whatsapp-web.js the message must be within the 100-message fetch window for the chat, the same> limit that applies to react/delete/edit. On Baileys it must be in the adapter's message store.+#### POST /api/sessions/:sessionId/messages/star++Star (bookmark) a message, or remove its star. Starring is private to the account — the other party+never sees it — and unlike pinning it has no group-admin restriction and never expires.++**Auth:** API key (OPERATOR)++**Body**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| chatId | string | yes | Chat containing the message |+| messageId | string | yes | Message to star or unstar |+| star | boolean | yes | `true` to star, `false` to remove the star |++**Response** `200` — `{ "success": true }`++> **Best-effort on whatsapp-web.js.** Its `star()`/`unstar()` resolve with no value and silently do+> nothing when WhatsApp declines the message, so a `200` means the instruction was delivered, not+> that the star is definitely set. There is no signal at the engine boundary to distinguish the two.+> Baileys applies the change through an app-state modification and is exact.++**Errors:** `400` session not active · `401` missing/invalid API key · `404` message not found in the chat+#### POST /api/sessions/:sessionId/messages/unpinRemove a message's pin. Takes no duration.diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 0dd1db8bc..468e4cab3 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -265,6 +265,16 @@ curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/pin" \-d '{"chatId":"[email protected]","messageId":"[email protected]_3EB0ABCD","durationSeconds":604800}'```+#### POST /api/sessions/:sessionId/messages/star++Star or unstar a message.++```bash+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/star" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \+ -d '{"chatId":"[email protected]","messageId":"[email protected]_3EB0ABCD","star":true}'+```+#### POST /api/sessions/:sessionId/messages/unpin```bashdiff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex 493772eb7..0f581d411 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -29,7 +29,7 @@ All five SDKs expose the same fluent surface:| Resource | Methods || --- | --- || `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, sendBulk, batchStatus, cancelBatch |+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, sendBulk, batchStatus, cancelBatch || `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock || `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, inviteCode, revokeInviteCode || `webhooks` | list, get, create, update, delete, test |diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 6cfd16efb..79c1929ca 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -168,8 +168,8 @@ These are hand-maintained and had drifted from the source before this pass; theyfrom `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way whenadding a method, instead of incrementing the previous figure.-- **82** interface methods, **164** adapter-cells (82 × 2 engines).-- **147** supported cells; **17** not-available cells across **16** methods.+- **83** interface methods, **166** adapter-cells (83 × 2 engines).+- **149** supported cells; **17** not-available cells across **16** methods.- Of the 17 not-available cells: **2 adapter-gaps** (fixable) + **15 library-limitations** + **0 uncertain**.- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.diff --git a/openapi.json b/openapi.jsonindex 9f501e6ac..6e8c6e54f 100644--- a/openapi.json+++ b/openapi.json@@ -2233,6 +2233,47 @@]}},+ "/api/sessions/{sessionId}/messages/star": {+ "post": {+ "operationId": "MessageController_starMessage",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StarMessageDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Instruction delivered. On whatsapp-web.js the engine silently ignores a message it will not star, so this does not guarantee the star is set."+ },+ "400": {+ "description": "Session not active"+ },+ "404": {+ "description": "Message not found in the chat"+ }+ },+ "summary": "Star or unstar a message",+ "tags": [+ "messages"+ ]+ }+ },"/api/sessions/{sessionId}/messages/edit": {"post": {"operationId": "MessageController_edit",@@ -7242,6 +7283,26 @@"messageId"]},+ "StarMessageDto": {+ "type": "object",+ "properties": {+ "chatId": {+ "type": "string"+ },+ "messageId": {+ "type": "string"+ },+ "star": {+ "type": "boolean",+ "description": "true to star, false to remove the star."+ }+ },+ "required": [+ "chatId",+ "messageId",+ "star"+ ]+ },"EditMessageDto": {"type": "object","properties": {diff --git a/sdk/README.md b/sdk/README.mdindex f7f520fc8..1cb4a8ab9 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -25,7 +25,7 @@ All five SDKs expose the same fluent resource surface:| Resource | Methods || ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, sendBulk, batchStatus, cancelBatch |+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, sendBulk, batchStatus, cancelBatch || `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock || `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, get/updateGroupSettings, leave, inviteCode, revokeInviteCode || `webhooks` | list, get, create, update, delete, test |diff --git a/sdk/go/messages.go b/sdk/go/messages.goindex e831c064c..3b70e5fa9 100644--- a/sdk/go/messages.go+++ b/sdk/go/messages.go@@ -146,6 +146,15 @@ func (s *MessagesService) Pin(ctx context.Context, sessionID string, body PinMesreturn &out, nil}+// Star stars or unstars a message.+func (s *MessagesService) Star(ctx context.Context, sessionID string, body StarMessageRequest) (*SuccessResult, error) {+ var out SuccessResult+ if err := s.client.do(ctx, "POST", s.base(sessionID)+"/star", nil, body, &out); err != nil {+ return nil, err+ }+ return &out, nil+}+// Unpin removes a message's pin.func (s *MessagesService) Unpin(ctx context.Context, sessionID string, body UnpinMessageRequest) (*SuccessResult, error) {var out SuccessResultdiff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.goindex 644602542..3f0b589eb 100644--- a/sdk/go/routing_test.go+++ b/sdk/go/routing_test.go@@ -92,6 +92,7 @@ func TestRouting(t *testing.T) {{"Status.List", func(c *Client) { c.Status.List(ctx, "s1") }, "GET", "/api/sessions/s1/status"},{"Status.FromContact", func(c *Client) { c.Status.FromContact(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/status/u1"},{"Messages.Pin", func(c *Client) { c.Messages.Pin(ctx, "s1", PinMessageRequest{}) }, "POST", "/api/sessions/s1/messages/pin"},+ {"Messages.Star", func(c *Client) { c.Messages.Star(ctx, "s1", StarMessageRequest{}) }, "POST", "/api/sessions/s1/messages/star"},{"Messages.Unpin", func(c *Client) { c.Messages.Unpin(ctx, "s1", UnpinMessageRequest{}) }, "POST", "/api/sessions/s1/messages/unpin"},{"Messages.Media", func(c *Client) { c.Messages.Media(ctx, "s1", "c1", "m1") }, "GET", "/api/sessions/s1/messages/c1/m1/media"},{"Status.Media", func(c *Client) { c.Status.Media(ctx, "s1", "st1") }, "GET", "/api/sessions/s1/status/st1/media"},diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 277e6e925..76c1c128e 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -340,3 +340,11 @@ type UnpinMessageRequest struct {ChatID string `json:"chatId"`MessageID string `json:"messageId"`}++// StarMessageRequest stars or unstars a message. Best-effort on whatsapp-web.js,+// which silently ignores a message it will not star.+type StarMessageRequest struct {+ ChatID string `json:"chatId"`+ MessageID string `json:"messageId"`+ Star bool `json:"star"`+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/StarMessageRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/StarMessageRequest.javanew file mode 100644index 000000000..421cdf160--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/StarMessageRequest.java@@ -0,0 +1,34 @@+package com.rmyndharis.openwa.model;++/** Request body for starring or unstarring a message. */+public record StarMessageRequest(String chatId, String messageId, Boolean star) {+ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private String chatId;+ private String messageId;+ private Boolean star;++ public Builder chatId(String v) {+ this.chatId = v;+ return this;+ }++ public Builder messageId(String v) {+ this.messageId = v;+ return this;+ }++ /** true to star, false to remove the star. */+ public Builder star(Boolean v) {+ this.star = v;+ return this;+ }++ public StarMessageRequest build() {+ return new StarMessageRequest(chatId, messageId, star);+ }+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.javaindex 1059063b6..933425f29 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java@@ -27,6 +27,7 @@ import com.rmyndharis.openwa.model.SendAudioRequest;import com.rmyndharis.openwa.model.SendPollRequest;import com.rmyndharis.openwa.model.SendTemplateRequest;import com.rmyndharis.openwa.model.SendTextRequest;+import com.rmyndharis.openwa.model.StarMessageRequest;import com.rmyndharis.openwa.model.SuccessResult;import com.rmyndharis.openwa.model.UnpinMessageRequest;import java.util.List;@@ -171,6 +172,19 @@ public final class MessagesResource {SuccessResult.class);}+ /**+ * Star or unstar a message. Best-effort on whatsapp-web.js, which silently ignores a message it+ * will not star.+ */+ public SuccessResult star(String sessionId, StarMessageRequest body) {+ return client.request(+ HttpMethod.POST,+ "/api/sessions/" + encodeSegment(sessionId) + "/messages/star",+ null,+ body,+ SuccessResult.class);+ }+/** Remove a message's pin. */public SuccessResult unpin(String sessionId, UnpinMessageRequest body) {return client.request(diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.javaindex 813e51a43..34a304084 100644--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java@@ -27,6 +27,7 @@ import com.rmyndharis.openwa.model.SendAudioRequest;import com.rmyndharis.openwa.model.SendPollRequest;import com.rmyndharis.openwa.model.SendTemplateRequest;import com.rmyndharis.openwa.model.SendTextRequest;+import com.rmyndharis.openwa.model.StarMessageRequest;import com.rmyndharis.openwa.model.UnpinMessageRequest;import com.rmyndharis.openwa.support.MockTransport;import java.nio.charset.StandardCharsets;@@ -293,4 +294,12 @@ class MessagesResourceTest {assertEquals("http://h/api/sessions/s/messages/unpin", tx.lastRequest().url());assertEquals(HttpMethod.POST, tx.lastRequest().method());}++ @Test+ void starPostsToItsRoute() {+ tx.respond(200, "{\"success\":true}");+ client.messages.star("s", StarMessageRequest.builder().chatId("c1").messageId("m1").star(false).build());+ assertEquals("http://h/api/sessions/s/messages/star", tx.lastRequest().url());+ assertEquals(HttpMethod.POST, tx.lastRequest().method());+ }}diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.tsindex 5423210ae..73e36140e 100644--- a/sdk/javascript/src/resources/messages.ts+++ b/sdk/javascript/src/resources/messages.ts@@ -29,6 +29,7 @@ import type {SendLocationRequest,SendAudioRequest,SendMediaRequest,+ StarMessageRequest,UnpinMessageRequest,SendPollRequest,SendTemplateRequest,@@ -192,6 +193,18 @@ export class MessagesResource {});}+ /**+ * Star or unstar a message. Best-effort on whatsapp-web.js: it silently ignores a message it+ * will not star, so a resolved call is not proof the star is set.+ */+ star(sessionId: string, body: StarMessageRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/star`,+ body,+ });+ }+/** Remove a message's pin. */unpin(sessionId: string, body: UnpinMessageRequest): Promise<SuccessResult> {return this.client.request<SuccessResult>({diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 8246f1c23..d4d8b49e8 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -188,6 +188,13 @@ export interface PinMessageRequest {durationSeconds?: PinDurationSeconds;}+export interface StarMessageRequest {+ chatId: Jid;+ messageId: string;+ /** true to star, false to remove the star. */+ star: boolean;+}+export interface UnpinMessageRequest {chatId: Jid;messageId: string;diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.tsindex 84485b277..888f4a502 100644--- a/sdk/javascript/test/resources.test.ts+++ b/sdk/javascript/test/resources.test.ts@@ -215,6 +215,13 @@ describe('StatusResource — nested media bodies', () => {expect(t.lastCall!.body).toEqual({ video: { url: 'http://vid' }, recipients: ['[email protected]'] });});+ it('star posts the boolean through', async () => {+ const t = new MockTransport().on('POST', /\/messages\/star$/, { body: { success: true } });+ await client(t).messages.star('s', { chatId: 'c1', messageId: 'm1', star: false });+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/messages/star');+ expect(t.lastCall!.body).toEqual({ chatId: 'c1', messageId: 'm1', star: false });+ });+it('pin and unpin post to their own routes', async () => {const t = new MockTransport().on('POST', /\/messages\/(un)?pin$/, { body: { success: true } });const c = client(t);diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.phpindex 7dcf58f34..8a50ff023 100644--- a/sdk/php/src/Resources/MessagesResource.php+++ b/sdk/php/src/Resources/MessagesResource.php@@ -175,6 +175,18 @@ class MessagesResourcereturn $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/pin", [], $body) ?? [];}+ /**+ * Star or unstar a message. Best-effort on whatsapp-web.js, which silently ignores a message+ * it will not star.+ *+ * @param array<string,mixed> $body chatId, messageId and star (bool).+ * @return array<string,mixed>+ */+ public function star(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/star", [], $body) ?? [];+ }+/*** @param array<string,mixed> $body* @return array<string,mixed>diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.phpindex 42a6e337c..0954206ca 100644--- a/sdk/php/tests/ResourcesTest.php+++ b/sdk/php/tests/ResourcesTest.php@@ -256,6 +256,16 @@ class ResourcesTest extends TestCase$this->assertSame(['video' => ['url' => 'http://vid'], 'recipients' => ['[email protected]']], $backend->lastCall()['body']);}+ public function testStarPostsTheBooleanThrough(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $client->messages->star('s', ['chatId' => 'c1', 'messageId' => 'm1', 'star' => false]);+ $this->assertSame('/api/sessions/s/messages/star', $backend->lastCall()['path']);+ $this->assertSame('POST', $backend->lastCall()['method']);+ }+public function testPinAndUnpinPostToTheirRoutes(): void{$backend = new MockBackend();diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.pyindex 3e521d5a3..ca1ef2b18 100644--- a/sdk/python/openwa/resources/messages.py+++ b/sdk/python/openwa/resources/messages.py@@ -12,6 +12,7 @@ from .._http import quote_segmentfrom ..types import (MessageMedia,PinMessageRequest,+ StarMessageRequest,UnpinMessageRequest,BatchStatusResponse,BulkMessageResponse,@@ -114,6 +115,10 @@ class MessagesResource:"""Pin a message. ``durationSeconds`` must be 86400, 604800 or 2592000; defaults to 24h."""return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/pin", body=body)+ def star(self, session_id: str, body: StarMessageRequest) -> SuccessResult:+ """Star or unstar a message. Best-effort on whatsapp-web.js."""+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/star", body=body)+def unpin(self, session_id: str, body: UnpinMessageRequest) -> SuccessResult:return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/unpin", body=body)diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex e496ddd71..1f3681999 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -638,6 +638,14 @@ class PinMessageRequest(TypedDict, total=False):durationSeconds: int+class StarMessageRequest(TypedDict):+ """Star or unstar a message. Best-effort on whatsapp-web.js."""++ chatId: str+ messageId: str+ star: bool++class UnpinMessageRequest(TypedDict):chatId: strmessageId: strdiff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex cf91c14c1..689b418b1 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -497,6 +497,12 @@ class TestStatus:client.status.send_video("s", {"video": {"url": "http://vid"}, "recipients": ["[email protected]"]})assert backend.calls[-1].body == {"video": {"url": "http://vid"}, "recipients": ["[email protected]"]}+ def test_star_posts_the_boolean_through(self):+ backend = MockBackend().on("POST", "/messages/star", body={"success": True})+ make_client(backend).messages.star("s", {"chatId": "c1", "messageId": "m1", "star": False})+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/messages/star"+ assert backend.last_call.body == {"chatId": "c1", "messageId": "m1", "star": False}+def test_pin_and_unpin_post_to_their_routes(self):backend = MockBackend().on("POST", "/messages/pin", body={"success": True})backend.on("POST", "/messages/unpin", body={"success": True})diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex 0db1dfd4c..8dd3e3638 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -409,6 +409,17 @@ export class BaileysMessaging {return found;}+ async starMessage(chatId: string, messageId: string, star: boolean): Promise<void> {+ this.host.ensureReady();+ const target = await this.requireStored(messageId);+ // fromMe is load-bearing: the same message id addresses a different message depending on+ // direction, so omitting it would star the wrong side of the conversation.+ await this.sock().chatModify(+ { star: { messages: [{ id: target.key.id!, fromMe: target.key.fromMe ?? false }], star } },+ chatId,+ );+ }+/*** Pin/unpin a message IN THE CHAT. Deliberately not `chatModify({pin})` — that pins the chat* itself in the chat list, a different feature that happens to share the word.diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 6215d5b7b..6f671714e 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2505,6 +2505,28 @@ describe('BaileysAdapter store-backed ops', () => {});});+ it("starMessage carries the stored key's fromMe, not just the id", async () => {+ fakeStore.getMessage.mockResolvedValue(stored);+ const adapter = await ready();+ await adapter.starMessage('[email protected]', 'TARGET', true);+ // The same id addresses a different message depending on direction, so dropping fromMe would+ // star the wrong side of the conversation.+ expect(fakeSock.chatModify).toHaveBeenCalledWith(+ { star: { messages: [{ id: stored.key.id, fromMe: stored.key.fromMe ?? false }], star: true } },+ '[email protected]',+ );+ });++ it('starMessage passes star:false through for an unstar', async () => {+ fakeStore.getMessage.mockResolvedValue(stored);+ const adapter = await ready();+ await adapter.starMessage('[email protected]', 'TARGET', false);+ expect(fakeSock.chatModify).toHaveBeenCalledWith(+ { star: { messages: [{ id: stored.key.id, fromMe: stored.key.fromMe ?? false }], star: false } },+ '[email protected]',+ );+ });+it('pinMessage pins IN CHAT via the stored key, with the requested window', async () => {fakeStore.getMessage.mockResolvedValue(stored);const adapter = await ready();diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 130b01011..3742c755b 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -338,6 +338,10 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.messaging.deleteMessage(chatId, messageId, forEveryone);}+ async starMessage(chatId: string, messageId: string, star: boolean): Promise<void> {+ return this.messaging.starMessage(chatId, messageId, star);+ }+async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {return this.messaging.pinMessage(chatId, messageId, durationSeconds);}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 4e710a0f6..a191e418b 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -3591,6 +3591,41 @@ describe('pinMessage / unpinMessage', () => {});});+describe('starMessage', () => {+ const ready = (client: unknown): WhatsAppWebJsAdapter => {+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;+ (adapter as unknown as { client: unknown }).client = client;+ return adapter;+ };+ const chatWith = (messages: unknown[]) => ({+ getChatById: jest.fn().mockResolvedValue({ fetchMessages: jest.fn().mockResolvedValue(messages) }),+ });++ it('stars via star() and never calls unstar()', async () => {+ const star = jest.fn().mockResolvedValue(undefined);+ const unstar = jest.fn().mockResolvedValue(undefined);+ const adapter = ready(chatWith([{ id: { _serialized: 'M1' }, star, unstar }]));+ await adapter.starMessage('[email protected]', 'M1', true);+ expect(star).toHaveBeenCalled();+ expect(unstar).not.toHaveBeenCalled();+ });++ it('unstars via unstar() and never calls star()', async () => {+ const star = jest.fn().mockResolvedValue(undefined);+ const unstar = jest.fn().mockResolvedValue(undefined);+ const adapter = ready(chatWith([{ id: { _serialized: 'M1' }, star, unstar }]));+ await adapter.starMessage('[email protected]', 'M1', false);+ expect(unstar).toHaveBeenCalled();+ expect(star).not.toHaveBeenCalled();+ });++ it('throws MessageNotFoundError when the message is outside the fetch window', async () => {+ const adapter = ready(chatWith([]));+ await expect(adapter.starMessage('[email protected]', 'GONE', true)).rejects.toBeInstanceOf(MessageNotFoundError);+ });+});+describe('LID mapping persistence to LidMappingStore (#583 R3)', () => {const readyWithStore = (client: unknown, lidMappingStore: unknown): WhatsAppWebJsAdapter => {const adapter = new WhatsAppWebJsAdapter({diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 13bf6eea5..9fb6ec6cf 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1433,6 +1433,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}// Delete Message+ starMessage(chatId: string, messageId: string, star: boolean): Promise<void> {+ return this.messaging.starMessage(chatId, messageId, star);+ }+pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {return this.messaging.pinMessage(chatId, messageId, durationSeconds);}diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex 3208cc369..61c4850d6 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -689,6 +689,16 @@ export class WwebjsMessaging {this.host.logger.log(`Pinned message ${messageId} in chat ${chatId} for ${durationSeconds}s`);}+ async starMessage(chatId: string, messageId: string, star: boolean): Promise<void> {+ this.host.ensureReady();+ const message = await this.findInFetchWindow(chatId, messageId);+ // Both resolve void, and the page-side helper silently does nothing when canStarMsg() refuses+ // the message (Message.js:672-712). There is no signal to map, so a star that WhatsApp declined+ // is indistinguishable from one it accepted — documented rather than faked into a refusal.+ await (star ? message.star() : message.unstar());+ this.host.logger.log(`${star ? 'Starred' : 'Unstarred'} message ${messageId} in chat ${chatId}`);+ }+async unpinMessage(chatId: string, messageId: string): Promise<void> {this.host.ensureReady();const message = await this.findInFetchWindow(chatId, messageId);diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex b1fa10f89..5935afa67 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -234,6 +234,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {sendStickerMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },sendTextMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },sendVideoMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ starMessage: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs Message.star()/unstar() → Promise<void> (index.d.ts:1336-1338) — void, so there is no refusal signal to map, unlike pin; baileys chatModify({star:{messages:[{id,fromMe}],star}}, jid) (Types/Chat.d.ts:83-89) — needs the stored key's fromMe, since the same id means different messages depending on direction",+ },setGroupDescription: {wwjs: { status: 'supported' },baileys: { status: 'supported' },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 4f7b5bacc..b183e339d 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -694,6 +694,11 @@ export interface IWhatsAppEngine {* non-text or foreign messages at their own layer — the engine's error is surfaced as-is.*/editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult>;+ /**+ * Star (bookmark) a message, or remove its star. Starring is a private, account-local marker —+ * it is not visible to the other party and has no group-admin restriction.+ */+ starMessage(chatId: string, messageId: string, star: boolean): Promise<void>;/*** Pin a message in its chat for a bounded window. WhatsApp only recognises three durations —* 86400 (24h), 604800 (7d), 2592000 (30d) — so `durationSeconds` must be one of those; it isdiff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex 20d53a2f1..8c38e4770 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -224,6 +224,25 @@ export class PinMessageDto {durationSeconds?: number;}+export class StarMessageDto {+ @ApiProperty()+ @IsString()+ @IsNotEmpty()+ chatId: string;++ @ApiProperty()+ @IsString()+ @IsNotEmpty()+ messageId: string;++ @ApiProperty({ description: 'true to star, false to remove the star.' })+ // Read strictly for the same reason as DeleteMessageDto.forEveryone: implicit conversion would+ // turn the string "false" into boolean true, silently inverting the caller's intent.+ @ToStrictBoolean()+ @IsBoolean()+ star: boolean;+}+export class UnpinMessageDto {@ApiProperty()@IsString()diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex c1444765b..9616011ba 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -16,6 +16,7 @@ import {DeleteMessageDto,EditMessageDto,PinMessageDto,+ StarMessageDto,UnpinMessageDto,} from './dto/message-actions.dto';import { RequireRole } from '../auth/decorators/auth.decorators';@@ -440,6 +441,23 @@ export class MessageController {return this.messageService.unpinMessage(sessionId, dto);}+ @Post('star')+ @HttpCode(HttpStatus.OK)+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Star or unstar a message' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({+ status: 200,+ description:+ 'Instruction delivered. On whatsapp-web.js the engine silently ignores a message it will not ' ++ 'star, so this does not guarantee the star is set.',+ })+ @ApiResponse({ status: 400, description: 'Session not active' })+ @ApiResponse({ status: 404, description: 'Message not found in the chat' })+ async starMessage(@Param('sessionId') sessionId: string, @Body() dto: StarMessageDto): Promise<{ success: boolean }> {+ return this.messageService.starMessage(sessionId, dto);+ }+// ========== Edit Message ==========@Post('edit')diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 17792262e..bfd39fe02 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -33,6 +33,7 @@ function createMockEngine() {getMessageReactions: jest.fn().mockResolvedValue([]),deleteMessage: jest.fn().mockResolvedValue(undefined),pinMessage: jest.fn().mockResolvedValue(undefined),+ starMessage: jest.fn().mockResolvedValue(undefined),unpinMessage: jest.fn().mockResolvedValue(undefined),editMessage: jest.fn().mockResolvedValue(mockEngineResult),getChatHistory: jest.fn().mockResolvedValue([]),@@ -1454,6 +1455,13 @@ describe('MessageService', () => {});});+ describe('starMessage', () => {+ it.each([true, false])('passes star=%s straight through to the engine', async star => {+ await service.starMessage('sess-1', { chatId: '[email protected]', messageId: 'M1', star });+ expect(mockEngine.starMessage).toHaveBeenCalledWith('[email protected]', 'M1', star);+ });+ });+// ── archived chat media (read path) ───────────────────────────────describe('getChatMedia', () => {diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex cc20d99c7..83e75ea84 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -804,6 +804,20 @@ export class MessageService {return { success: true };}+ /**+ * Star or unstar a message. Like a pin, this is WhatsApp-owned state and is not mirrored locally+ * — but unlike a pin it is private to the account and never expires.+ *+ * Best-effort on whatsapp-web.js: its star/unstar resolve void and silently do nothing when+ * WhatsApp declines the message, so a 200 here means the instruction was delivered, not that the+ * star is definitely set.+ */+ async starMessage(sessionId: string, dto: { chatId: string; messageId: string; star: boolean }) {+ const engine = this.getEngine(sessionId);+ await engine.starMessage(dto.chatId, dto.messageId, dto.star);+ return { success: true };+ }+async deleteMessage(sessionId: string,dto: { chatId: string; messageId: string; forEveryone?: boolean },