diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd8069b..20ed90b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,9 +54,12 @@ jobs: # 2. repository variables (vars.RENDERER_REPO / vars.RENDERER_REF) # → per-fork config set under Settings → Variables, applies # to push and pull_request runs without editing this file. - # 3. upstream default - # → UPSTREAM_RENDERER_REPO, ref `main` when the client build - # context is `main`, otherwise `Dev`. + # 3. dynamic, owner-aware default (no hardcoded fork name) + # → /Nitro_Render_V3 when it carries + # the resolved ref, else UPSTREAM_RENDERER_REPO. Ref is + # `main` on a main build, otherwise `Dev`. So a fork's + # client pairs with the fork's renderer when the companion + # code lives there, and with upstream when it doesn't. # # The two repos must stay wire-aligned (composer/parser # signatures); pairing the client with a stale renderer is what @@ -72,42 +75,53 @@ jobs: VAR_REPO: ${{ vars.RENDERER_REPO }} VAR_REF: ${{ vars.RENDERER_REF }} run: | - # Branch-aware auto pairing — the default when neither a - # dispatch input nor a repo variable is supplied. + # Dynamic, owner-aware renderer pairing — nothing is hardcoded to a + # specific fork. The companion renderer is discovered from the + # client repo's OWNER first, then the upstream fallback: "if the + # companion code is on my fork, pair with my fork; otherwise pair + # with upstream". For PRs the context is the base ref. # - # Everything (including the custom features — rare values, - # fortune wheel, soundboard) now lives on duckietm's own - # `main` / `Dev` branches, so the renderer always pairs - # against UPSTREAM_RENDERER_REPO: `main` when the client build - # context is `main`, otherwise `Dev`. For PRs the context is - # the base ref. + # Precedence (most specific wins): + # 1. workflow_dispatch inputs (renderer_repo / renderer_ref) + # 2. repo variables (vars.RENDERER_REPO / vars.RENDERER_REF) + # 3. dynamic: /Nitro_Render_V3 when it carries the ref, + # else ${UPSTREAM_RENDERER_REPO}. case "${GITHUB_EVENT_NAME}" in - pull_request) - CTX="${GITHUB_BASE_REF}" - ;; - *) - CTX="${GITHUB_REF_NAME}" - ;; + pull_request) CTX="${GITHUB_BASE_REF}" ;; + *) CTX="${GITHUB_REF_NAME}" ;; esac - AUTO_REPO="${UPSTREAM_RENDERER_REPO}" + # Branch-aware desired ref: main on a main build, else Dev. case "$CTX" in main) AUTO_REF="main" ;; *) AUTO_REF="Dev" ;; esac - # Precedence (most specific wins): dispatch input → repo - # variable → branch-aware auto default. The auto default is - # the final fallback so a Dev/feat build never silently pairs - # against a renderer that's missing its companion exports. - REPO="$IN_REPO" - [ -z "$REPO" ] && REPO="$VAR_REPO" - [ -z "$REPO" ] && REPO="$AUTO_REPO" - REF="$IN_REF" [ -z "$REF" ] && REF="$VAR_REF" [ -z "$REF" ] && REF="$AUTO_REF" + # Probe whether has branch (remote-only, no checkout). + has_ref() { git ls-remote --exit-code --heads "https://github.com/$1.git" "$2" >/dev/null 2>&1; } + + REPO="$IN_REPO" + [ -z "$REPO" ] && REPO="$VAR_REPO" + if [ -z "$REPO" ]; then + OWN_REPO="${GITHUB_REPOSITORY_OWNER}/Nitro_Render_V3" + if has_ref "$OWN_REPO" "$REF"; then + REPO="$OWN_REPO" # companion lives on my own fork + else + REPO="$UPSTREAM_RENDERER_REPO" # fall back to upstream + fi + fi + + # Safety net: never pair against a repo/ref that doesn't exist. + if ! has_ref "$REPO" "$REF"; then + echo "::warning::renderer '$REPO' has no branch '$REF' — falling back to ${UPSTREAM_RENDERER_REPO}" + REPO="$UPSTREAM_RENDERER_REPO" + has_ref "$REPO" "$REF" || REF="Dev" + fi + echo "repo=$REPO" >> "$GITHUB_OUTPUT" echo "ref=$REF" >> "$GITHUB_OUTPUT" echo "Resolved renderer pairing: $REPO @ $REF (client ctx: $CTX, event: ${GITHUB_EVENT_NAME})" diff --git a/CLAUDE.md b/CLAUDE.md index b64a97f..4e9578a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -440,3 +440,13 @@ See `docs/ARCHITECTURE.md` "Recently fixed" for fix shapes. classes/enums kept around just so the `src/api/*` barrel cascade imports without throwing. **Grow this file when a new test needs a symbol; prefer real deterministic stubs over `vi.fn()`.** + +## Furni names (furnidata-driven) + +Furni name/description are furnidata-driven (`FurnitureData` by classname) — the +client does NOT get furni display names from the server. The 3 furni surfaces +refresh live on the window event `nitro-localization-updated`: catalog +(`useCatalog.ts`), inventory (`useInventoryFurni.ts`), infostand +(`useAvatarInfoWidget.ts`). The renderer's `FurnitureDataReload` packet (header +10047) dispatches that event on server-pushed furnidata changes — no client code +needed. diff --git a/docs/superpowers/plans/2026-06-02-messenger-phase1-friend-groups.md b/docs/superpowers/plans/2026-06-02-messenger-phase1-friend-groups.md new file mode 100644 index 0000000..98a7ca9 --- /dev/null +++ b/docs/superpowers/plans/2026-06-02-messenger-phase1-friend-groups.md @@ -0,0 +1,1213 @@ +# Messenger Phase 1 — Friend Groups Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add full custom friend groups (create / rename / delete / assign) to the existing React friends list, with an Online/Offline-primary view plus a per-group chip filter. + +**Architecture:** Four new client→server packets (renderer composers + Arcturus handlers) drive category CRUD + friend assignment. The server persists to the existing `messenger_categories` table and the `messenger_friendships.category` column, then re-pushes authoritative state through the **existing** `MessengerInitComposer` (category list) and `UpdateFriendComposer` (a friend's new `categoryId`). The client already receives `categories` via `MessengerInitEvent` and `categoryId` per friend — we add CRUD actions + UI and a pure group-filter helper. + +**Tech Stack:** Arcturus (Java 21/Maven/HikariCP), Nitro_Render_V3 (TypeScript, yarn workspaces, Vitest), Nitro-V3 (React 19, Vite, Vitest). + +--- + +## Cross-codebase header-ID contract + +Renderer **Outgoing** header N == Arcturus **Incoming** header N (verified across 8 existing friend packets, e.g. `SET_RELATIONSHIP_STATUS = 3768 == ChangeRelationEvent = 3768`). Phase 1 reuses existing server→client headers, so it needs **4 new client→server header IDs only**, used identically in `OutgoingHeader.ts` (renderer) and `Incoming.java` (Arcturus): + +| Logical packet | Renderer composer | Arcturus handler | Constant name (both sides) | +|---|---|---|---| +| Add category | `AddFriendCategoryComposer(name)` | `AddFriendCategoryEvent` | `ADD_FRIEND_CATEGORY` / `AddFriendCategoryEvent` | +| Rename category | `RenameFriendCategoryComposer(categoryId, name)` | `RenameFriendCategoryEvent` | `RENAME_FRIEND_CATEGORY` / `RenameFriendCategoryEvent` | +| Remove category | `RemoveFriendCategoryComposer(categoryId)` | `RemoveFriendCategoryEvent` | `REMOVE_FRIEND_CATEGORY` / `RemoveFriendCategoryEvent` | +| Assign friend → category | `MoveFriendToCategoryComposer(friendId, categoryId)` | `MoveFriendToCategoryEvent` | `MOVE_FRIEND_TO_CATEGORY` / `MoveFriendToCategoryEvent` | + +The concrete numbers are chosen and verified in **Task 1**. + +## File map + +**Arcturus (`Arcturus-Morningstar-Extended/Emulator/src/main/java/com/eu/habbo/`):** +- Modify `messages/incoming/Incoming.java` — 4 new constants +- Modify `messages/PacketManager.java` — 4 `registerHandler` lines +- Modify `habbohotel/messenger/MessengerBuddy.java` — `setCategoryId(int)` +- Modify `habbohotel/users/HabboInfo.java` — `renameMessengerCategory(int, String)` +- Create `messages/incoming/friends/AddFriendCategoryEvent.java` +- Create `messages/incoming/friends/RenameFriendCategoryEvent.java` +- Create `messages/incoming/friends/RemoveFriendCategoryEvent.java` +- Create `messages/incoming/friends/MoveFriendToCategoryEvent.java` + +**Renderer (`Nitro_Render_V3/packages/communication/src/`):** +- Modify `messages/outgoing/OutgoingHeader.ts` — 4 constants +- Modify `NitroMessages.ts` — imports + 4 `_composers.set` +- Modify `messages/outgoing/friendlist/index.ts` — 4 exports +- Create `messages/outgoing/friendlist/AddFriendCategoryComposer.ts` +- Create `messages/outgoing/friendlist/RenameFriendCategoryComposer.ts` +- Create `messages/outgoing/friendlist/RemoveFriendCategoryComposer.ts` +- Create `messages/outgoing/friendlist/MoveFriendToCategoryComposer.ts` +- Create `messages/outgoing/friendlist/__tests__/FriendCategoryComposers.test.ts` + +**Client (`Nitro-V3/src/`):** +- Create `api/friends/friendCategory.helpers.ts` + `.test.ts` +- Modify `api/friends/index.ts` — export helper +- Modify `hooks/friends/useFriends.ts` — 4 actions + composer imports +- Modify `components/friends/views/friends-list/FriendsListView.tsx` — chip row + filter +- Create `components/friends/views/friends-list/FriendsListGroupChipsView.tsx` — chip filter row +- Create `components/friends/views/friends-list/FriendsCategoryManagerView.tsx` — create/rename/delete modal +- Modify `components/friends/views/friends-list/friends-list-group/FriendsListGroupItemView.tsx` — assign control +- Modify `css/friends/FriendsView.css` — chip + manager + assign styles + +--- + +## Task 1: Allocate & verify the 4 category header IDs + +**Files:** none yet (decision + verification only). + +- [ ] **Step 1: Try official IDs, then pick verified-free fallbacks** + +The user prefers official Habbo revision IDs for category packets. First check whether the connecting revision shipped friend-category management packets: + +Run (renderer): `grep -rin "categor" Nitro_Render_V3/packages/communication/src/messages/outgoing/OutgoingHeader.ts` +Expected: only `MESSENGER_*` friend headers, **no** add/rename/remove/move-category constant. + +If no official category constants are found (expected — the bundled revision's `OutgoingHeader.ts` has none), use the custom fallback quartet **4081, 4082, 4083, 4084** and verify they are free on BOTH sides. + +- [ ] **Step 2: Verify the four numbers are unused on both sides** + +Run: +``` +grep -rnE "= ?408[1-4]\b" Nitro_Render_V3/packages/communication/src/messages/outgoing/OutgoingHeader.ts +grep -rnE "= ?408[1-4]\b" Arcturus-Morningstar-Extended/Emulator/src/main/java/com/eu/habbo/messages/incoming/Incoming.java +``` +Expected: **no output** from either command (the IDs are free). + +If either prints a match, increment the base (try 4085–4088, etc.) and re-run until both commands return nothing. Record the final quartet here before continuing: + +``` +ADD_FRIEND_CATEGORY = 4081 +RENAME_FRIEND_CATEGORY = 4082 +REMOVE_FRIEND_CATEGORY = 4083 +MOVE_FRIEND_TO_CATEGORY = 4084 +``` + +All later tasks reference the **constant names**, so only Tasks 2 and 4 (the constant definitions) carry the raw numbers. If you changed the numbers above, use your values in Tasks 2 and 4. + +- [ ] **Step 3: No commit** (decision task — nothing changed on disk yet). + +--- + +## Task 2: Renderer — 4 outgoing composers + registration + test + +**Files:** +- Create: `Nitro_Render_V3/packages/communication/src/messages/outgoing/friendlist/AddFriendCategoryComposer.ts` +- Create: `Nitro_Render_V3/packages/communication/src/messages/outgoing/friendlist/RenameFriendCategoryComposer.ts` +- Create: `Nitro_Render_V3/packages/communication/src/messages/outgoing/friendlist/RemoveFriendCategoryComposer.ts` +- Create: `Nitro_Render_V3/packages/communication/src/messages/outgoing/friendlist/MoveFriendToCategoryComposer.ts` +- Modify: `Nitro_Render_V3/packages/communication/src/messages/outgoing/OutgoingHeader.ts` +- Modify: `Nitro_Render_V3/packages/communication/src/messages/outgoing/friendlist/index.ts` +- Modify: `Nitro_Render_V3/packages/communication/src/NitroMessages.ts` +- Test: `Nitro_Render_V3/packages/communication/src/messages/outgoing/friendlist/__tests__/FriendCategoryComposers.test.ts` + +- [ ] **Step 1: Write the failing test** + +Create `__tests__/FriendCategoryComposers.test.ts`: +```typescript +import { describe, expect, it } from 'vitest'; +import { AddFriendCategoryComposer } from '../AddFriendCategoryComposer'; +import { RenameFriendCategoryComposer } from '../RenameFriendCategoryComposer'; +import { RemoveFriendCategoryComposer } from '../RemoveFriendCategoryComposer'; +import { MoveFriendToCategoryComposer } from '../MoveFriendToCategoryComposer'; + +describe('friend category composers', () => +{ + it('AddFriendCategoryComposer carries the name', () => + { + expect(new AddFriendCategoryComposer('Best friends').getMessageArray()).toEqual([ 'Best friends' ]); + }); + + it('RenameFriendCategoryComposer carries id + name', () => + { + expect(new RenameFriendCategoryComposer(5, 'Staff').getMessageArray()).toEqual([ 5, 'Staff' ]); + }); + + it('RemoveFriendCategoryComposer carries the id', () => + { + expect(new RemoveFriendCategoryComposer(7).getMessageArray()).toEqual([ 7 ]); + }); + + it('MoveFriendToCategoryComposer carries friendId + categoryId', () => + { + expect(new MoveFriendToCategoryComposer(42, 3).getMessageArray()).toEqual([ 42, 3 ]); + }); +}); +``` + +- [ ] **Step 2: Run it to confirm it fails** + +Run: `cd Nitro_Render_V3 && yarn test --run packages/communication/src/messages/outgoing/friendlist/__tests__/FriendCategoryComposers.test.ts` +Expected: FAIL — cannot find module `../AddFriendCategoryComposer` (files not created yet). + +- [ ] **Step 3: Create the four composers** + +`AddFriendCategoryComposer.ts`: +```typescript +import { IMessageComposer } from '@nitrots/api'; + +export class AddFriendCategoryComposer implements IMessageComposer> +{ + private _data: ConstructorParameters; + + constructor(name: string) + { + this._data = [ name ]; + } + + public getMessageArray() + { + return this._data; + } + + public dispose(): void + { + return; + } +} +``` + +`RenameFriendCategoryComposer.ts`: +```typescript +import { IMessageComposer } from '@nitrots/api'; + +export class RenameFriendCategoryComposer implements IMessageComposer> +{ + private _data: ConstructorParameters; + + constructor(categoryId: number, name: string) + { + this._data = [ categoryId, name ]; + } + + public getMessageArray() + { + return this._data; + } + + public dispose(): void + { + return; + } +} +``` + +`RemoveFriendCategoryComposer.ts`: +```typescript +import { IMessageComposer } from '@nitrots/api'; + +export class RemoveFriendCategoryComposer implements IMessageComposer> +{ + private _data: ConstructorParameters; + + constructor(categoryId: number) + { + this._data = [ categoryId ]; + } + + public getMessageArray() + { + return this._data; + } + + public dispose(): void + { + return; + } +} +``` + +`MoveFriendToCategoryComposer.ts`: +```typescript +import { IMessageComposer } from '@nitrots/api'; + +export class MoveFriendToCategoryComposer implements IMessageComposer> +{ + private _data: ConstructorParameters; + + constructor(friendId: number, categoryId: number) + { + this._data = [ friendId, categoryId ]; + } + + public getMessageArray() + { + return this._data; + } + + public dispose(): void + { + return; + } +} +``` + +- [ ] **Step 4: Run the test to confirm it passes** + +Run: `cd Nitro_Render_V3 && yarn test --run packages/communication/src/messages/outgoing/friendlist/__tests__/FriendCategoryComposers.test.ts` +Expected: PASS (4 tests). + +- [ ] **Step 5: Add the four header constants** + +In `OutgoingHeader.ts`, next to the other friend headers (after `public static FRIEND_LIST_UPDATE = 1419;`), add (use your Task 1 numbers): +```typescript +public static ADD_FRIEND_CATEGORY = 4081; +public static RENAME_FRIEND_CATEGORY = 4082; +public static REMOVE_FRIEND_CATEGORY = 4083; +public static MOVE_FRIEND_TO_CATEGORY = 4084; +``` + +- [ ] **Step 6: Export the composers from the friendlist barrel** + +In `messages/outgoing/friendlist/index.ts`, add: +```typescript +export * from './AddFriendCategoryComposer'; +export * from './MoveFriendToCategoryComposer'; +export * from './RemoveFriendCategoryComposer'; +export * from './RenameFriendCategoryComposer'; +``` + +- [ ] **Step 7: Register the composers in NitroMessages** + +First find how friendlist composers are imported in `NitroMessages.ts`: +Run: `grep -n "SendMessageComposer" Nitro_Render_V3/packages/communication/src/NitroMessages.ts` +This shows both the import line and the `_composers.set(...)` line. + +Add the four classes to that same import statement (the one that imports `SendMessageComposer`, `SetRelationshipStatusComposer`, etc.). Then, next to `this._composers.set(OutgoingHeader.SET_RELATIONSHIP_STATUS, SetRelationshipStatusComposer);`, add: +```typescript +this._composers.set(OutgoingHeader.ADD_FRIEND_CATEGORY, AddFriendCategoryComposer); +this._composers.set(OutgoingHeader.RENAME_FRIEND_CATEGORY, RenameFriendCategoryComposer); +this._composers.set(OutgoingHeader.REMOVE_FRIEND_CATEGORY, RemoveFriendCategoryComposer); +this._composers.set(OutgoingHeader.MOVE_FRIEND_TO_CATEGORY, MoveFriendToCategoryComposer); +``` + +- [ ] **Step 8: Type-check + full test run** + +Run: `cd Nitro_Render_V3 && yarn compile:fast && yarn test --run` +Expected: compile clean; all tests pass (138 prior + 4 new = 142). + +- [ ] **Step 9: Commit** + +```bash +cd Nitro_Render_V3 +git add packages/communication/src/messages/outgoing/friendlist/ packages/communication/src/messages/outgoing/OutgoingHeader.ts packages/communication/src/NitroMessages.ts +git commit -m "feat(messenger): add friend-category client composers (add/rename/remove/move)" +``` + +--- + +## Task 3: Emulator — category persistence helpers + +**Files:** +- Modify: `Arcturus-Morningstar-Extended/Emulator/src/main/java/com/eu/habbo/habbohotel/messenger/MessengerBuddy.java` +- Modify: `Arcturus-Morningstar-Extended/Emulator/src/main/java/com/eu/habbo/habbohotel/users/HabboInfo.java` + +> The emulator has **no unit-test infrastructure** (confirmed: no `src/test`, no JUnit in `pom.xml`). Verification for Tasks 3–4 is a successful `mvn package` + the manual integration checklist in Task 11. + +- [ ] **Step 1: Add `setCategoryId` to MessengerBuddy** + +`MessengerBuddy` already has `private int categoryId = 0;`, `private int userOne = 0;` (the owner's id), `this.id` (the friend's id), and `getCategoryId()`. Mirror the existing `setRelation`/`run()` DB idiom. Add after `getCategoryId()` (around line 141): +```java + public void setCategoryId(int categoryId) { + this.categoryId = categoryId; + + final int cat = categoryId; + final int owner = this.userOne; + final int friend = this.id; + + Emulator.getThreading().run(() -> { + try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE messenger_friendships SET category = ? WHERE user_one_id = ? AND user_two_id = ?")) { + statement.setInt(1, cat); + statement.setInt(2, owner); + statement.setInt(3, friend); + statement.execute(); + } catch (SQLException e) { + LOGGER.error("Caught SQL exception", e); + } + }); + } +``` +(`Connection`, `PreparedStatement`, `SQLException`, `Emulator`, and `LOGGER` are already imported in this file.) + +- [ ] **Step 2: Add `renameMessengerCategory` to HabboInfo** + +`HabboInfo` already has `loadMessengerCategories()`, `addMessengerCategory(MessengerCategory)` (INSERT + sets generated id), `deleteMessengerCategory(MessengerCategory)` (removes + DELETE via `SqlQueries.update`), and `getMessengerCategories()`. Add a rename helper after `deleteMessengerCategory` (around line 238), reusing the same `SqlQueries.update` idiom: +```java + public void renameMessengerCategory(int categoryId, String name) { + for (MessengerCategory category : this.messengerCategories) { + if (category.getId() == categoryId) { + category.setName(name); + break; + } + } + + try { + SqlQueries.update("UPDATE messenger_categories SET name = ? WHERE id = ? AND user_id = ?", name, categoryId, this.id); + } catch (SqlQueries.DataAccessException e) { + LOGGER.error("Caught SQL exception", e); + } + } +``` +(`SqlQueries`, `MessengerCategory`, and `LOGGER` are already imported/available in this file.) + +- [ ] **Step 3: Compile** + +Run: `cd Arcturus-Morningstar-Extended/Emulator && mvn -q compile` +Expected: BUILD SUCCESS (no compile errors). + +- [ ] **Step 4: Commit** + +```bash +cd Arcturus-Morningstar-Extended +git add Emulator/src/main/java/com/eu/habbo/habbohotel/messenger/MessengerBuddy.java Emulator/src/main/java/com/eu/habbo/habbohotel/users/HabboInfo.java +git commit -m "feat(messenger): persist friend category assignment + category rename" +``` + +--- + +## Task 4: Emulator — 4 incoming handlers + registration + +**Files:** +- Create: `Arcturus-Morningstar-Extended/Emulator/src/main/java/com/eu/habbo/messages/incoming/friends/AddFriendCategoryEvent.java` +- Create: `.../friends/RenameFriendCategoryEvent.java` +- Create: `.../friends/RemoveFriendCategoryEvent.java` +- Create: `.../friends/MoveFriendToCategoryEvent.java` +- Modify: `.../messages/incoming/Incoming.java` +- Modify: `.../messages/PacketManager.java` + +- [ ] **Step 1: Add the 4 header constants to Incoming.java** + +Next to the other friend constants (e.g. after `public static final int InviteFriendsEvent = 1276;`), add (use your Task 1 numbers — must match the renderer): +```java + public static final int AddFriendCategoryEvent = 4081; + public static final int RenameFriendCategoryEvent = 4082; + public static final int RemoveFriendCategoryEvent = 4083; + public static final int MoveFriendToCategoryEvent = 4084; +``` + +- [ ] **Step 2: Create AddFriendCategoryEvent** + +Caps: ≤ 20 categories/user, name 1–25 chars, case-insensitive de-dupe. Persists via the existing `HabboInfo.addMessengerCategory` (which sets the generated id), then re-pushes the category list with the existing `MessengerInitComposer`. +```java +package com.eu.habbo.messages.incoming.friends; + +import com.eu.habbo.habbohotel.messenger.MessengerCategory; +import com.eu.habbo.habbohotel.users.Habbo; +import com.eu.habbo.messages.incoming.MessageHandler; +import com.eu.habbo.messages.outgoing.friends.MessengerInitComposer; + +public class AddFriendCategoryEvent extends MessageHandler { + @Override + public void handle() throws Exception { + String name = this.packet.readString(); + Habbo habbo = this.client.getHabbo(); + + if (habbo == null || name == null) return; + + name = name.trim(); + if (name.isEmpty() || name.length() > 25) return; + if (habbo.getHabboInfo().getMessengerCategories().size() >= 20) return; + + for (MessengerCategory existing : habbo.getHabboInfo().getMessengerCategories()) { + if (existing.getName().equalsIgnoreCase(name)) return; + } + + MessengerCategory category = new MessengerCategory(name, habbo.getHabboInfo().getId(), 0); + habbo.getHabboInfo().addMessengerCategory(category); + + this.client.sendResponse(new MessengerInitComposer(habbo)); + } +} +``` + +- [ ] **Step 3: Create RenameFriendCategoryEvent** + +```java +package com.eu.habbo.messages.incoming.friends; + +import com.eu.habbo.habbohotel.messenger.MessengerCategory; +import com.eu.habbo.habbohotel.users.Habbo; +import com.eu.habbo.messages.incoming.MessageHandler; +import com.eu.habbo.messages.outgoing.friends.MessengerInitComposer; + +public class RenameFriendCategoryEvent extends MessageHandler { + @Override + public void handle() throws Exception { + int categoryId = this.packet.readInt(); + String name = this.packet.readString(); + Habbo habbo = this.client.getHabbo(); + + if (habbo == null || name == null) return; + + name = name.trim(); + if (name.isEmpty() || name.length() > 25) return; + + boolean found = false; + for (MessengerCategory category : habbo.getHabboInfo().getMessengerCategories()) { + if (category.getId() == categoryId) { + found = true; + break; + } + } + if (!found) return; + + habbo.getHabboInfo().renameMessengerCategory(categoryId, name); + + this.client.sendResponse(new MessengerInitComposer(habbo)); + } +} +``` + +- [ ] **Step 4: Create RemoveFriendCategoryEvent** + +Deleting a group resets its members to category `0`, pushing each via the existing `UpdateFriendComposer`, then re-pushes the (now shorter) category list. +```java +package com.eu.habbo.messages.incoming.friends; + +import com.eu.habbo.habbohotel.messenger.MessengerBuddy; +import com.eu.habbo.habbohotel.messenger.MessengerCategory; +import com.eu.habbo.habbohotel.users.Habbo; +import com.eu.habbo.messages.incoming.MessageHandler; +import com.eu.habbo.messages.outgoing.friends.MessengerInitComposer; +import com.eu.habbo.messages.outgoing.friends.UpdateFriendComposer; + +public class RemoveFriendCategoryEvent extends MessageHandler { + @Override + public void handle() throws Exception { + int categoryId = this.packet.readInt(); + Habbo habbo = this.client.getHabbo(); + + if (habbo == null) return; + + MessengerCategory target = null; + for (MessengerCategory category : habbo.getHabboInfo().getMessengerCategories()) { + if (category.getId() == categoryId) { + target = category; + break; + } + } + if (target == null) return; + + habbo.getHabboInfo().deleteMessengerCategory(target); + + for (MessengerBuddy buddy : habbo.getMessenger().getFriends().values()) { + if (buddy.getCategoryId() == categoryId) { + buddy.setCategoryId(0); + this.client.sendResponse(new UpdateFriendComposer(habbo, buddy, 0)); + } + } + + this.client.sendResponse(new MessengerInitComposer(habbo)); + } +} +``` + +- [ ] **Step 5: Create MoveFriendToCategoryEvent** + +`categoryId == 0` means "uncategorized"; any other id must be an existing category. Persists via `MessengerBuddy.setCategoryId` and pushes the updated friend via `UpdateFriendComposer`. +```java +package com.eu.habbo.messages.incoming.friends; + +import com.eu.habbo.habbohotel.messenger.MessengerBuddy; +import com.eu.habbo.habbohotel.messenger.MessengerCategory; +import com.eu.habbo.habbohotel.users.Habbo; +import com.eu.habbo.messages.incoming.MessageHandler; +import com.eu.habbo.messages.outgoing.friends.UpdateFriendComposer; + +public class MoveFriendToCategoryEvent extends MessageHandler { + @Override + public void handle() throws Exception { + int friendId = this.packet.readInt(); + int categoryId = this.packet.readInt(); + Habbo habbo = this.client.getHabbo(); + + if (habbo == null) return; + + MessengerBuddy buddy = habbo.getMessenger().getFriends().get(friendId); + if (buddy == null) return; + + if (categoryId != 0) { + boolean exists = false; + for (MessengerCategory category : habbo.getHabboInfo().getMessengerCategories()) { + if (category.getId() == categoryId) { + exists = true; + break; + } + } + if (!exists) return; + } + + buddy.setCategoryId(categoryId); + this.client.sendResponse(new UpdateFriendComposer(habbo, buddy, 0)); + } +} +``` + +- [ ] **Step 6: Register the 4 handlers** + +In `PacketManager.java`, inside `registerFriends()`, add: +```java + this.registerHandler(Incoming.AddFriendCategoryEvent, AddFriendCategoryEvent.class); + this.registerHandler(Incoming.RenameFriendCategoryEvent, RenameFriendCategoryEvent.class); + this.registerHandler(Incoming.RemoveFriendCategoryEvent, RemoveFriendCategoryEvent.class); + this.registerHandler(Incoming.MoveFriendToCategoryEvent, MoveFriendToCategoryEvent.class); +``` +Then add the four imports near the other `com.eu.habbo.messages.incoming.friends.*` imports at the top of the file: +```java +import com.eu.habbo.messages.incoming.friends.AddFriendCategoryEvent; +import com.eu.habbo.messages.incoming.friends.RenameFriendCategoryEvent; +import com.eu.habbo.messages.incoming.friends.RemoveFriendCategoryEvent; +import com.eu.habbo.messages.incoming.friends.MoveFriendToCategoryEvent; +``` +(If `PacketManager.java` already uses a wildcard `import com.eu.habbo.messages.incoming.friends.*;`, skip the explicit imports — check with `grep -n "incoming.friends" PacketManager.java` first.) + +- [ ] **Step 7: Build the fat jar** + +Run: `cd Arcturus-Morningstar-Extended/Emulator && mvn -q clean package -DskipTests` +Expected: BUILD SUCCESS; jar produced under `target/`. A failure here most likely means a duplicate header (the `registerHandler` guard throws `Header already registered`) — return to Task 1 and pick different free IDs. + +- [ ] **Step 8: Commit** + +```bash +cd Arcturus-Morningstar-Extended +git add Emulator/src/main/java/com/eu/habbo/messages/incoming/friends/ Emulator/src/main/java/com/eu/habbo/messages/incoming/Incoming.java Emulator/src/main/java/com/eu/habbo/messages/PacketManager.java +git commit -m "feat(messenger): friend-category CRUD + assign packet handlers" +``` + +--- + +## Task 5: Client — pure group-filter helper (TDD) + +**Files:** +- Create: `Nitro-V3/src/api/friends/friendCategory.helpers.ts` +- Test: `Nitro-V3/src/api/friends/friendCategory.helpers.test.ts` +- Modify: `Nitro-V3/src/api/friends/index.ts` + +- [ ] **Step 1: Write the failing test** + +`friendCategory.helpers.test.ts`: +```typescript +import { describe, expect, it } from 'vitest'; +import { MessengerFriend } from './MessengerFriend'; +import { countFriendsByCategory, filterFriendsByCategory } from './friendCategory.helpers'; + +const makeFriend = (id: number, categoryId: number): MessengerFriend => +{ + const friend = new MessengerFriend(); + friend.id = id; + friend.categoryId = categoryId; + return friend; +}; + +describe('filterFriendsByCategory', () => +{ + const friends = [ makeFriend(1, 0), makeFriend(2, 5), makeFriend(3, 5), makeFriend(4, 8) ]; + + it('returns all friends when categoryId is 0 (All)', () => + { + expect(filterFriendsByCategory(friends, 0)).toHaveLength(4); + }); + + it('returns only the friends in the given category', () => + { + expect(filterFriendsByCategory(friends, 5).map(f => f.id)).toEqual([ 2, 3 ]); + }); + + it('returns an empty array for a category with no members', () => + { + expect(filterFriendsByCategory(friends, 99)).toEqual([]); + }); + + it('is null-safe', () => + { + expect(filterFriendsByCategory(null, 5)).toEqual([]); + }); +}); + +describe('countFriendsByCategory', () => +{ + const friends = [ makeFriend(1, 0), makeFriend(2, 5), makeFriend(3, 5) ]; + + it('counts members per category id', () => + { + const counts = countFriendsByCategory(friends); + expect(counts.get(0)).toBe(1); + expect(counts.get(5)).toBe(2); + }); + + it('is null-safe', () => + { + expect(countFriendsByCategory(null).size).toBe(0); + }); +}); +``` + +- [ ] **Step 2: Run it to confirm it fails** + +Run: `cd Nitro-V3 && yarn test --run src/api/friends/friendCategory.helpers.test.ts` +Expected: FAIL — cannot resolve `./friendCategory.helpers`. + +- [ ] **Step 3: Implement the helper** + +`friendCategory.helpers.ts`: +```typescript +import { MessengerFriend } from './MessengerFriend'; + +/** + * Filter a friend list to a single category. categoryId 0 means + * "All" (no filtering) and returns the list unchanged. + */ +export const filterFriendsByCategory = (friends: MessengerFriend[], categoryId: number): MessengerFriend[] => +{ + if(!friends) return []; + + if(!categoryId) return friends; + + return friends.filter(friend => (friend.categoryId === categoryId)); +}; + +/** + * Count how many friends belong to each category id. Used to render + * member counts on the group chips. + */ +export const countFriendsByCategory = (friends: MessengerFriend[]): Map => +{ + const counts = new Map(); + + if(!friends) return counts; + + for(const friend of friends) + { + counts.set(friend.categoryId, (counts.get(friend.categoryId) ?? 0) + 1); + } + + return counts; +}; +``` + +- [ ] **Step 4: Run the test to confirm it passes** + +Run: `cd Nitro-V3 && yarn test --run src/api/friends/friendCategory.helpers.test.ts` +Expected: PASS (6 cases). + +- [ ] **Step 5: Export from the friends api barrel** + +In `src/api/friends/index.ts`, add: +```typescript +export * from './friendCategory.helpers'; +``` + +- [ ] **Step 6: Commit** + +```bash +cd Nitro-V3 +git add src/api/friends/friendCategory.helpers.ts src/api/friends/friendCategory.helpers.test.ts src/api/friends/index.ts +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(friends): pure category filter + count helpers" +``` + +--- + +## Task 6: Client — category CRUD + assign actions in the friends store + +**Files:** +- Modify: `Nitro-V3/src/hooks/friends/useFriends.ts` + +The store re-pushes authoritative state through the server (the existing `MessengerInitEvent` handler updates `settings.categories`; `FriendListUpdateEvent` updates each friend's `categoryId`), so these actions are thin send-wrappers — no optimistic local mutation. + +- [ ] **Step 1: Import the new composers** + +In the top import from `@nitrots/nitro-renderer` in `useFriends.ts`, add `AddFriendCategoryComposer`, `MoveFriendToCategoryComposer`, `RemoveFriendCategoryComposer`, `RenameFriendCategoryComposer` to the named-import list. + +- [ ] **Step 2: Add the four actions inside `useFriendsStore`** + +Add alongside `followFriend` / `updateRelationship` (around line 42), before the `return`: +```typescript + const addCategory = (name: string) => + { + const trimmed = (name ?? '').trim(); + + if(!trimmed.length || (trimmed.length > 25)) return; + + SendMessageComposer(new AddFriendCategoryComposer(trimmed)); + }; + + const renameCategory = (categoryId: number, name: string) => + { + const trimmed = (name ?? '').trim(); + + if(!categoryId || !trimmed.length || (trimmed.length > 25)) return; + + SendMessageComposer(new RenameFriendCategoryComposer(categoryId, trimmed)); + }; + + const removeCategory = (categoryId: number) => + { + if(!categoryId) return; + + SendMessageComposer(new RemoveFriendCategoryComposer(categoryId)); + }; + + const moveFriendToCategory = (friendId: number, categoryId: number) => + { + if(!friendId) return; + + SendMessageComposer(new MoveFriendToCategoryComposer(friendId, categoryId)); + }; +``` + +- [ ] **Step 3: Expose them from the store return** + +In `useFriendsStore`'s `return { ... }` add: `addCategory, renameCategory, removeCategory, moveFriendToCategory`. + +- [ ] **Step 4: Expose them via `useFriendsActions`** + +In the `useFriendsActions` destructure-from-`useBetween` AND its `return`, add the four names so consumers can pull them: +```typescript +export const useFriendsActions = () => +{ + const { + requestFriend, + requestResponse, + followFriend, + updateRelationship, + addCategory, + renameCategory, + removeCategory, + moveFriendToCategory + } = useBetween(useFriendsStore); + + return { + requestFriend, + requestResponse, + followFriend, + updateRelationship, + addCategory, + renameCategory, + removeCategory, + moveFriendToCategory + }; +}; +``` +(The deprecated `useFriends` shim returns the whole store, so it picks these up automatically.) + +- [ ] **Step 5: Type-check + full test run** + +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run` +Expected: typecheck clean; all tests pass (no regressions). + +- [ ] **Step 6: Commit** + +```bash +cd Nitro-V3 +git add src/hooks/friends/useFriends.ts +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(friends): category CRUD + assign actions in friends store" +``` + +--- + +## Task 7: Client — group chip-filter row + +**Files:** +- Create: `Nitro-V3/src/components/friends/views/friends-list/FriendsListGroupChipsView.tsx` +- Modify: `Nitro-V3/src/components/friends/views/friends-list/FriendsListView.tsx` + +- [ ] **Step 1: Create the chip row component** + +It renders an "All" chip plus one chip per category (with member count), and a gear button to open the manager (wired in Task 8). It is a controlled component: parent owns `selectedCategoryId`. +```tsx +import { FC } from 'react'; +import { FriendCategoryData } from '@nitrots/nitro-renderer'; +import { countFriendsByCategory, LocalizeText, MessengerFriend } from '../../../../api'; +import { Flex } from '../../../../common'; + +interface FriendsListGroupChipsViewProps +{ + categories: FriendCategoryData[]; + friends: MessengerFriend[]; + selectedCategoryId: number; + setSelectedCategoryId: (id: number) => void; + onManageClick: () => void; +} + +export const FriendsListGroupChipsView: FC = props => +{ + const { categories = [], friends = [], selectedCategoryId = 0, setSelectedCategoryId = null, onManageClick = null } = props; + + const counts = countFriendsByCategory(friends); + + return ( + + +
setSelectedCategoryId(0) }> + { LocalizeText('friendlist.friends') } ({ friends.length }) +
+ { categories.map(category => ( +
setSelectedCategoryId(category.id) }> + { category.name } ({ counts.get(category.id) ?? 0 }) +
+ )) } +
+
+ ⚙ +
+
+ ); +}; +``` +(If `Flex` is not exported from `../../../../common`, check the import other friends views use — `FriendsListView.tsx` already imports `Flex`, `Button` from `../../../../common`; match that path.) + +- [ ] **Step 2: Wire the chip row + filtering into FriendsListView** + +In `FriendsListView.tsx`: +1. Add imports: +```tsx +import { useState } from 'react'; +import { filterFriendsByCategory } from '../../../../api'; +import { FriendsListGroupChipsView } from './FriendsListGroupChipsView'; +import { FriendsCategoryManagerView } from './FriendsCategoryManagerView'; +``` +(`useState` may already be imported — merge into the existing react import. `FriendsCategoryManagerView` is created in Task 8; this import is fine to add now and will resolve after Task 8.) + +2. Pull `settings` from the friends state hook used in this component (it already destructures from `useFriendsState`/`useFriends`). Ensure `settings` (and `friends` for the unfiltered counts) are in scope: +```tsx +const { onlineFriends, offlineFriends, requests, settings, friends } = useFriendsState(); +``` +(Adjust to match the existing hook call in this file — keep whatever names it already destructures and add `settings` + `friends`.) + +3. Add local UI state near the other `useState` calls: +```tsx +const [ selectedCategoryId, setSelectedCategoryId ] = useState(0); +const [ showCategoryManager, setShowCategoryManager ] = useState(false); + +const categories = settings?.categories ?? []; +const filteredOnlineFriends = filterFriendsByCategory(onlineFriends, selectedCategoryId); +const filteredOfflineFriends = filterFriendsByCategory(offlineFriends, selectedCategoryId); +``` + +4. Insert the chip row directly under `` (before the ``): +```tsx + setShowCategoryManager(true) } /> +``` + +5. Replace every reference to `onlineFriends` / `offlineFriends` that feeds the **rendered list and counts** with the filtered versions (six edits): + - online section header count: `(${ filteredOnlineFriends.length })` + - online `select_all` toolbar: map/every over `filteredOnlineFriends` + - online `` + - offline section header count: `(${ filteredOfflineFriends.length })` + - offline `select_all` toolbar: map/every over `filteredOfflineFriends` + - offline `` + + (Leave the unfiltered `friends` for the chip counts and `onlineFriends`/`offlineFriends` references that are NOT about the rendered sections, if any.) + +6. Render the manager modal at the end of the returned fragment (next to the existing `showRoomInvite` / `showRemoveFriendsConfirmation` blocks): +```tsx +{ showCategoryManager && + setShowCategoryManager(false) } /> } +``` + +- [ ] **Step 3: Type-check** + +Run: `cd Nitro-V3 && yarn typecheck` +Expected: clean (a TS2307 for `FriendsCategoryManagerView` is acceptable here only until Task 8 lands; if you implement Task 8 next there should be no errors). If you want a green checkpoint now, temporarily comment the manager import + render block, then restore in Task 8. + +- [ ] **Step 4: Commit** + +```bash +cd Nitro-V3 +git add src/components/friends/views/friends-list/FriendsListGroupChipsView.tsx src/components/friends/views/friends-list/FriendsListView.tsx +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(friends): group chip-filter row over online/offline list" +``` + +--- + +## Task 8: Client — category manager (create / rename / delete) + +**Files:** +- Create: `Nitro-V3/src/components/friends/views/friends-list/FriendsCategoryManagerView.tsx` + +- [ ] **Step 1: Create the manager modal** + +A small `NitroCardView` with an add-input and a list of categories, each with inline rename + delete. Uses `useFriendsActions`. +```tsx +import { FC, useState } from 'react'; +import { FriendCategoryData } from '@nitrots/nitro-renderer'; +import { LocalizeText } from '../../../../api'; +import { Button, Column, Flex, NitroCardContentView, NitroCardHeaderView, NitroCardView } from '../../../../common'; +import { useFriendsActions } from '../../../../hooks'; + +interface FriendsCategoryManagerViewProps +{ + categories: FriendCategoryData[]; + onCloseClick: () => void; +} + +export const FriendsCategoryManagerView: FC = props => +{ + const { categories = [], onCloseClick = null } = props; + const { addCategory, renameCategory, removeCategory } = useFriendsActions(); + const [ newName, setNewName ] = useState(''); + const [ editingId, setEditingId ] = useState(0); + const [ editingName, setEditingName ] = useState(''); + + const submitAdd = () => + { + const trimmed = newName.trim(); + + if(!trimmed.length) return; + + addCategory(trimmed); + setNewName(''); + }; + + const submitRename = () => + { + const trimmed = editingName.trim(); + + if(editingId && trimmed.length) renameCategory(editingId, trimmed); + + setEditingId(0); + setEditingName(''); + }; + + return ( + + + + + setNewName(event.target.value) } onKeyDown={ event => (event.key === 'Enter') && submitAdd() } /> + + + + { categories.map(category => ( + + { (editingId === category.id) ? + <> + setEditingName(event.target.value) } onKeyDown={ event => (event.key === 'Enter') && submitRename() } /> + + + : + <> + { category.name } +
{ setEditingId(category.id); setEditingName(category.name); } } /> +
removeCategory(category.id) } /> + } + + )) } + { !categories.length && + { LocalizeText('friendlist.friends.offlinecaption') } } + + + + ); +}; +``` + +> **Verify imports against the codebase.** `Column`, `Flex`, `Button`, and the `NitroCard*` components come from `../../../../common`; confirm the exact set with `grep -n "from '../../../../common'" src/components/friends/views/friends-list/FriendsListView.tsx`. The localization keys above (`generic.create` / `generic.save` / `generic.edit` / `generic.delete`) are placeholders for whatever your locale files already define — if a key renders raw, swap it for an existing one or add it to the locale JSON. The `icon-edit` / `icon-deselect` spritesheet classes: reuse whatever exists in `FriendsView.css`; if absent, use a plain text label ("✎" / "✕") instead. + +- [ ] **Step 2: Type-check + test** + +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run` +Expected: clean; tests green. (If you commented the manager wiring in Task 7 Step 3, restore it now.) + +- [ ] **Step 3: Commit** + +```bash +cd Nitro-V3 +git add src/components/friends/views/friends-list/FriendsCategoryManagerView.tsx src/components/friends/views/friends-list/FriendsListView.tsx +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(friends): create/rename/delete group manager" +``` + +--- + +## Task 9: Client — per-friend "assign to group" control + +**Files:** +- Modify: `Nitro-V3/src/components/friends/views/friends-list/friends-list-group/FriendsListGroupItemView.tsx` + +- [ ] **Step 1: Add categories + action to the component** + +At the top of the component body, pull categories from state and the move action from actions: +```tsx +import { useFriendsActions, useFriendsState } from '../../../../../hooks'; +``` +(Match the existing relative depth — this file is one level deeper than `FriendsListView.tsx`, so it's `../../../../../hooks`; confirm with the file's existing imports.) + +Inside the component: +```tsx +const { settings } = useFriendsState(); +const { moveFriendToCategory } = useFriendsActions(); +const [ isGroupMenuOpen, setIsGroupMenuOpen ] = useState(false); +const categories = settings?.categories ?? []; +``` +(`useState` is likely already imported; if not, add it.) + +- [ ] **Step 2: Add the assign control to the actions row** + +In the `friends-list-actions` div (currently the follow / chat / relationship icons), add — only when the friend is a real user (`friend.id > 0`) and at least one category exists — a group icon that toggles a small menu: +```tsx +{ (friend.id > 0) && (categories.length > 0) && +
+
setIsGroupMenuOpen(prev => !prev) } /> + { isGroupMenuOpen && +
+
{ moveFriendToCategory(friend.id, 0); setIsGroupMenuOpen(false); } }> + { LocalizeText('friendlist.friends') } +
+ { categories.map(category => ( +
{ moveFriendToCategory(friend.id, category.id); setIsGroupMenuOpen(false); } }> + { category.name } +
+ )) } +
} +
} +``` +(Reuse an existing spritesheet class for `icon-group` if one fits, or fall back to a text glyph. The "uncategorized" entry uses `friend.categoryId === 0`.) + +- [ ] **Step 3: Type-check + test** + +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run` +Expected: clean; tests green. + +- [ ] **Step 4: Commit** + +```bash +cd Nitro-V3 +git add src/components/friends/views/friends-list/friends-list-group/FriendsListGroupItemView.tsx +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(friends): per-friend assign-to-group control" +``` + +--- + +## Task 10: Client — styles for chips, manager, assign menu + +**Files:** +- Modify: `Nitro-V3/src/css/friends/FriendsView.css` + +- [ ] **Step 1: Append styles** + +Match the existing palette in this file (grays `#f3f3ef`/`#e6e6e6`, accent blue `#bfe7f6`, `#111` text). Append: +```css +.friends-group-chips { border-bottom: 1px solid #e6e6e6; } +.friends-group-chips-scroll { overflow-x: auto; flex-wrap: nowrap; } +.friends-group-chips-scroll::-webkit-scrollbar { height: 4px; } +.friends-group-chip { + flex: 0 0 auto; + padding: 1px 8px; + border: 1px solid #d0d0c8; + border-radius: 10px; + background: #f3f3ef; + font-size: 11px; + line-height: 16px; + white-space: nowrap; + cursor: pointer; + user-select: none; +} +.friends-group-chip.active { background: #bfe7f6; border-color: #7fb9d6; } +.friends-group-chip-manage { padding: 1px 6px; } + +.nitro-friends-category-manager { width: 280px; } + +.friends-list-group-assign { display: inline-flex; } +.friends-list-group-menu { + position: absolute; + right: 0; + top: 100%; + z-index: 20; + min-width: 120px; + max-height: 180px; + overflow-y: auto; + background: #fff; + border: 1px solid #c0c0b8; + border-radius: 4px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); +} +.friends-list-group-menu-item { + padding: 3px 8px; + font-size: 11px; + cursor: pointer; + white-space: nowrap; +} +.friends-list-group-menu-item:hover { background: #efefef; } +.friends-list-group-menu-item.active { background: #bfe7f6; } +``` + +- [ ] **Step 2: Visual sanity (build only)** + +Run: `cd Nitro-V3 && yarn typecheck` +Expected: clean (CSS isn't type-checked, but confirm nothing else broke). + +- [ ] **Step 3: Commit** + +```bash +cd Nitro-V3 +git add src/css/friends/FriendsView.css +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "style(friends): group chips, category manager, assign menu" +``` + +--- + +## Task 11: Integration verification (two live sessions) + +**Files:** none (manual verification + final checks). Fix-up commits only if something fails. + +- [ ] **Step 1: Apply the DB-side prerequisite check** + +The `messenger_categories` and `messenger_friendships.category` schema already exist (verified). Confirm against the running DB: +``` +SELECT COUNT(*) FROM messenger_categories; +SHOW COLUMNS FROM messenger_friendships LIKE 'category'; +``` +(Per house rules, if a destructive statement is ever needed, hand the user a one-liner to run under `E:\laragon\bin\mysql\...` — but nothing destructive is required here.) + +- [ ] **Step 2: Run the new emulator jar + client dev server** + +- Emulator: run the jar built in Task 4 (`java -jar Arcturus-Morningstar-Extended/Emulator/target/Habbo-*-jar-with-dependencies.jar`). +- Client: `cd Nitro-V3 && yarn start` (Vite picks up the renderer source live — no renderer build needed). + +- [ ] **Step 3: Manual test matrix (log in, open Friends)** + +Verify each: +1. **Create group:** open the manager (⚙), type a name, Create → a new chip appears (server re-pushed `MessengerInit`). +2. **Rename group:** edit a category name → chip label updates after round-trip. +3. **Delete group:** delete a category → chip disappears; any friend that was in it shows as uncategorized (its assign menu no longer marks that group active). +4. **Assign friend:** open a friend's group menu, pick a group → switch the chip filter to that group and confirm the friend appears there; switch to "All" and confirm they still appear once. +5. **Filter:** click each chip → only that group's friends show in both Online and Offline sections; counts in headers match; "All" shows everyone. +6. **Caps:** creating a 21st group is rejected (Create disabled at 20); a >25-char name is truncated by `maxLength`/server. +7. **Persistence:** relog → groups and assignments survive (DB-backed). +8. **No regressions:** follow, chat, relationship icons, requests, search, room-invite, remove-friend still work. + +- [ ] **Step 4: Final automated checks** + +Run: +``` +cd Nitro_Render_V3 && yarn compile:fast && yarn test --run +cd Nitro-V3 && yarn typecheck && yarn test --run && yarn eslint +cd Arcturus-Morningstar-Extended/Emulator && mvn -q clean package -DskipTests +``` +Expected: renderer tests green (142), client tests green (existing + 6 new helper cases), client typecheck + eslint clean, emulator BUILD SUCCESS. + +- [ ] **Step 5: Commit any fix-ups** + +```bash +# only if Step 3/4 required changes +cd Nitro-V3 +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -am "fix(friends): integration fixes for friend groups" +``` + +--- + +## Notes for the next phase + +- Phase 2 (offline messages) reuses the same `FriendChatMessageComposer` replay path — no new packets — and the `messenger_offline` table that already exists. +- Phases 3–4 (read receipts, typing) will add custom packets following the same renderer-composer/Arcturus-handler pattern proven here, plus a new server→client event+parser (mirror `NewConsoleMessageEvent`/`NewConsoleMessageParser`) which this phase did not need. +- Do NOT push automatically (the auto-push rule is scoped to the react19 branches only). Open PRs against the correct base per the duckietm `--base dev`/`Dev` convention when the user asks. diff --git a/docs/superpowers/plans/2026-06-02-messenger-phase2-offline-messages.md b/docs/superpowers/plans/2026-06-02-messenger-phase2-offline-messages.md new file mode 100644 index 0000000..d6b6d37 --- /dev/null +++ b/docs/superpowers/plans/2026-06-02-messenger-phase2-offline-messages.md @@ -0,0 +1,447 @@ +# Messenger Phase 2 — Offline Messages Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Messages sent to an offline friend are stored and delivered on the recipient's next login, tagged "sent while offline". + +**Architecture:** No new packets. The emulator stores send-to-offline in the existing `messenger_offline` table; on login it replays them through the existing `FriendChatMessageComposer` (extended with an optional `extraData` marker) so the client's existing `NewConsoleMessageEvent` path renders them. The client adds an `offlineDelivered` flag (derived from `extraData === "offline"`) and a subtle marker in the thread. + +**Tech Stack:** Arcturus (Java 21/Maven/HikariCP), Nitro-V3 (React 19, Vite, Vitest). No renderer change. + +--- + +## Branches +All repos are already on `feat/messenger-groups-receipts` (continuing the messenger initiative). Continue committing there. Client commits use the house-rule author override `git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com`. No Co-Authored-By / AI attribution anywhere. + +## Pre-flight: how messages flow today (read once) +- `FriendPrivateMessageEvent` (incoming) → `buddy.onMessageReceived(sender, message)` which delivers via `FriendChatMessageComposer` ONLY if the recipient is online (else the message is silently dropped — that's the gap we close). +- On login the client sends `MessengerInitComposer` → emulator `RequestInitFriendsEvent` sends `MessengerInitComposer` + the friend list. +- `FriendChatMessageComposer.composeInternal()` appends: `toId` (the sender id shown to the recipient), message text, `secondsSinceSent` (= now − message.timestamp). For group chat (`toId < 0`) it appends an extra `name/look/id` string. For 1:1 it appends nothing after `secondsSinceSent`. +- Client: `useMessenger` subscribes to `NewConsoleMessageEvent` and calls `sendMessage(thread, parser.senderId, parser.messageText, parser.secondsSinceSent, parser.extraData)`, which stores `extraData` on the created `MessengerThreadChat`. +- `messenger_offline` columns (verified): `id` (PK auto), `user_id` (recipient), `user_from_id` (sender), `message` varchar(500), `sended_on` int (unix). + +## File map +**Emulator (`Arcturus-Morningstar-Extended/Emulator/src/main/java/com/eu/habbo/`):** +- Modify `habbohotel/messenger/Message.java` — add a `(fromId, toId, message, timestamp)` constructor. +- Modify `messages/outgoing/friends/FriendChatMessageComposer.java` — optional `extraData` appended for 1:1. +- Modify `habbohotel/messenger/Messenger.java` — `addOfflineMessage(...)` + `deliverOfflineMessages(...)` + cap constant. +- Modify `messages/incoming/friends/FriendPrivateMessageEvent.java` — branch online vs offline. +- Modify `messages/incoming/friends/RequestInitFriendsEvent.java` — deliver offline on login. + +**Client (`Nitro-V3/src/`):** +- Modify `api/friends/MessengerThreadChat.ts` — `offlineDelivered` getter. +- Create `api/friends/MessengerThreadChat.test.ts` — getter test. +- Modify `components/friends/views/messenger/messenger-thread/FriendsMessengerThreadGroup.tsx` — render marker. +- Modify `public/configuration/UITexts.example` — add `messenger.offline.delivered` text key. +- Modify a messenger CSS file — `.messenger-offline-tag` style. + +--- + +## Task 1: Emulator — `Message` timestamp constructor + composer `extraData` + +**Files:** +- Modify: `Emulator/src/main/java/com/eu/habbo/habbohotel/messenger/Message.java` +- Modify: `Emulator/src/main/java/com/eu/habbo/messages/outgoing/friends/FriendChatMessageComposer.java` + +> Emulator has no unit tests; verification is `mvn compile`. + +- [ ] **Step 1: Add a timestamp constructor to `Message`** + +`Message` has `private final int timestamp;` set to `Emulator.getIntUnixTimestamp()` in the existing constructor. Add a second constructor that accepts an explicit timestamp (needed so a replayed offline message reports its original age). Add it right after the existing constructor (after the block ending at the line `this.timestamp = Emulator.getIntUnixTimestamp(); }`): +```java + public Message(int fromId, int toId, String message, int timestamp) { + this.fromId = fromId; + this.toId = toId; + this.message = message; + this.timestamp = timestamp; + } +``` + +- [ ] **Step 2: Add optional `extraData` to `FriendChatMessageComposer`** + +Add an `extraData` field + a 4-arg constructor, and append it for the 1:1 path. Replace the field/constructor region and the `composeInternal` tail. + +Add the field next to the existing fields: +```java + private String extraData = null; +``` +Add this constructor after the existing `FriendChatMessageComposer(Message message, int toId, int fromId)`: +```java + public FriendChatMessageComposer(Message message, int toId, int fromId, String extraData) { + this.message = message; + this.toId = toId; + this.fromId = fromId; + this.extraData = extraData; + } +``` +In `composeInternal()`, the existing `if (this.toId < 0) { ...group chat... }` block stays. Immediately AFTER that `if` block (before `return this.response;`), add an `else if` so 1:1 messages with a marker append it (online 1:1 messages pass `extraData == null` and append nothing — wire unchanged): +```java + else if (this.extraData != null) { + this.response.appendString(this.extraData); + } +``` +The result is: +```java + if (this.toId < 0) // group chat + { + // ... existing group block unchanged ... + this.response.appendString(name + "/" + look + "/" + this.fromId); + } + else if (this.extraData != null) { + this.response.appendString(this.extraData); + } + + return this.response; +``` + +- [ ] **Step 3: Compile** + +Run: `cd Arcturus-Morningstar-Extended/Emulator && mvn -q compile` +Expected: BUILD SUCCESS. + +- [ ] **Step 4: Commit (only these 2 files)** +```bash +cd Arcturus-Morningstar-Extended +git add Emulator/src/main/java/com/eu/habbo/habbohotel/messenger/Message.java Emulator/src/main/java/com/eu/habbo/messages/outgoing/friends/FriendChatMessageComposer.java +git commit -m "feat(messenger): Message timestamp ctor + optional extraData on chat composer" +``` +Verify with `git show --stat HEAD` that ONLY these 2 files are committed (the working tree also has an unrelated `soundboard/SoundboardPlayEvent.java` modification and untracked jars — never stage those). + +--- + +## Task 2: Emulator — offline message store + deliver helpers in `Messenger` + +**Files:** +- Modify: `Emulator/src/main/java/com/eu/habbo/habbohotel/messenger/Messenger.java` + +`Messenger` already has static DB methods (e.g. `unfriend`) using `Emulator.getDatabase().getDataSource().getConnection()` with try-with-resources, and a `LOGGER`. `Message` and `MessengerCategory` are in the same package (no import needed). You WILL need imports for `java.sql.ResultSet`, `java.util.ArrayList`, `java.util.List`, `com.eu.habbo.habbohotel.gameclients.GameClient`, and `com.eu.habbo.messages.outgoing.friends.FriendChatMessageComposer` — check the existing import block and add whichever are missing. + +- [ ] **Step 1: Add the cap constant** + +Near the other `Messenger` constants (e.g. by `MAXIMUM_FRIENDS`), add: +```java + public static final int MAXIMUM_OFFLINE_MESSAGES = 200; +``` + +- [ ] **Step 2: Add `addOfflineMessage`** + +Stores one offline message for `toId`, evicting the oldest if the per-user inbox is at the cap. Add as a static method: +```java + public static void addOfflineMessage(int fromId, int toId, String message) { + try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) { + try (PreparedStatement count = connection.prepareStatement("SELECT COUNT(*) FROM messenger_offline WHERE user_id = ?")) { + count.setInt(1, toId); + try (ResultSet set = count.executeQuery()) { + if (set.next() && set.getInt(1) >= MAXIMUM_OFFLINE_MESSAGES) { + try (PreparedStatement delete = connection.prepareStatement("DELETE FROM messenger_offline WHERE user_id = ? ORDER BY id ASC LIMIT 1")) { + delete.setInt(1, toId); + delete.execute(); + } + } + } + } + + try (PreparedStatement insert = connection.prepareStatement("INSERT INTO messenger_offline (user_id, user_from_id, message, sended_on) VALUES (?, ?, ?, ?)")) { + insert.setInt(1, toId); + insert.setInt(2, fromId); + insert.setString(3, message); + insert.setInt(4, Emulator.getIntUnixTimestamp()); + insert.execute(); + } + } catch (SQLException e) { + LOGGER.error("Caught SQL exception", e); + } + } +``` + +- [ ] **Step 3: Add `deliverOfflineMessages`** + +Loads any stored messages for the logging-in user (oldest first), replays each through `FriendChatMessageComposer` with the `"offline"` marker and the original timestamp, then deletes the delivered rows. +```java + public static void deliverOfflineMessages(GameClient client) { + if (client == null || client.getHabbo() == null) return; + + int userId = client.getHabbo().getHabboInfo().getId(); + List messages = new ArrayList<>(); + + try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); + PreparedStatement statement = connection.prepareStatement("SELECT user_from_id, message, sended_on FROM messenger_offline WHERE user_id = ? ORDER BY sended_on ASC, id ASC")) { + statement.setInt(1, userId); + try (ResultSet set = statement.executeQuery()) { + while (set.next()) { + messages.add(new Message(set.getInt("user_from_id"), userId, set.getString("message"), set.getInt("sended_on"))); + } + } + } catch (SQLException e) { + LOGGER.error("Caught SQL exception", e); + } + + if (messages.isEmpty()) return; + + for (Message message : messages) { + client.sendResponse(new FriendChatMessageComposer(message, message.getFromId(), message.getFromId(), "offline")); + } + + try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); + PreparedStatement statement = connection.prepareStatement("DELETE FROM messenger_offline WHERE user_id = ?")) { + statement.setInt(1, userId); + statement.execute(); + } catch (SQLException e) { + LOGGER.error("Caught SQL exception", e); + } + } +``` + +- [ ] **Step 4: Compile** + +Run: `cd Arcturus-Morningstar-Extended/Emulator && mvn -q compile` +Expected: BUILD SUCCESS. If it fails on a missing symbol, add the missing import (see the list at the top of this task). + +- [ ] **Step 5: Commit (only Messenger.java)** +```bash +cd Arcturus-Morningstar-Extended +git add Emulator/src/main/java/com/eu/habbo/habbohotel/messenger/Messenger.java +git commit -m "feat(messenger): store + deliver offline messages (capped inbox)" +``` + +--- + +## Task 3: Emulator — wire send-to-offline + deliver-on-login + +**Files:** +- Modify: `Emulator/src/main/java/com/eu/habbo/messages/incoming/friends/FriendPrivateMessageEvent.java` +- Modify: `Emulator/src/main/java/com/eu/habbo/messages/incoming/friends/RequestInitFriendsEvent.java` + +- [ ] **Step 1: Branch online vs offline in `FriendPrivateMessageEvent`** + +Currently the handler ends with `buddy.onMessageReceived(this.client.getHabbo(), message);`. Replace that single line with a branch: deliver if the recipient is online, otherwise store (word-filtered, matching the filtering the online path applies before sending). Add imports `com.eu.habbo.habbohotel.messenger.Messenger` and `com.eu.habbo.habbohotel.modtool.WordFilter`. + +Replace: +```java + buddy.onMessageReceived(this.client.getHabbo(), message); +``` +with: +```java + if (Emulator.getGameServer().getGameClientManager().getHabbo(userId) != null) { + buddy.onMessageReceived(this.client.getHabbo(), message); + } else { + String stored = message; + if (WordFilter.ENABLED_FRIENDCHAT) { + stored = Emulator.getGameEnvironment().getWordFilter().filter(message, this.client.getHabbo()); + } + Messenger.addOfflineMessage(this.client.getHabbo().getHabboInfo().getId(), userId, stored); + } +``` +(`Emulator` is already imported in this file. `userId` is the recipient read at the top of `handle()`.) + +- [ ] **Step 2: Deliver offline messages on login in `RequestInitFriendsEvent`** + +After the existing `this.client.sendResponses(messages);`, add a call to deliver any stored offline messages (sent AFTER the friend list so the client's thread lookup can resolve the sender as a known friend). Add import `com.eu.habbo.habbohotel.messenger.Messenger`. + +The method becomes: +```java + public void handle() throws Exception { + ArrayList messages = new ArrayList<>(); + messages.add(new MessengerInitComposer(this.client.getHabbo()).compose()); + messages.addAll(FriendsComposer.getMessagesForBuddyList(this.client.getHabbo().getMessenger().getFriends().values())); + this.client.sendResponses(messages); + + Messenger.deliverOfflineMessages(this.client); + } +``` + +- [ ] **Step 3: Build the fat jar** + +Run: `cd Arcturus-Morningstar-Extended/Emulator && mvn -q clean package -DskipTests` +Expected: BUILD SUCCESS. + +- [ ] **Step 4: Commit (only these 2 files)** +```bash +cd Arcturus-Morningstar-Extended +git add Emulator/src/main/java/com/eu/habbo/messages/incoming/friends/FriendPrivateMessageEvent.java Emulator/src/main/java/com/eu/habbo/messages/incoming/friends/RequestInitFriendsEvent.java +git commit -m "feat(messenger): persist messages to offline friends, replay on login" +``` +Verify `git show --stat HEAD` shows exactly 2 files. + +--- + +## Task 4: Client — `offlineDelivered` getter on `MessengerThreadChat` (TDD) + +**Files:** +- Modify: `Nitro-V3/src/api/friends/MessengerThreadChat.ts` +- Test: `Nitro-V3/src/api/friends/MessengerThreadChat.test.ts` + +`MessengerThreadChat` already stores `_extraData` and `_type`, with `CHAT = 0`. The emulator sends `extraData === "offline"` only for replayed 1:1 messages. + +- [ ] **Step 1: Write the failing test** + +Create `src/api/friends/MessengerThreadChat.test.ts`: +```typescript +import { describe, expect, it } from 'vitest'; +import { MessengerThreadChat } from './MessengerThreadChat'; + +describe('MessengerThreadChat.offlineDelivered', () => +{ + it('is true for a CHAT message with extraData "offline"', () => + { + const chat = new MessengerThreadChat(5, 'hello', 60, 'offline', MessengerThreadChat.CHAT); + expect(chat.offlineDelivered).toBe(true); + }); + + it('is false for a normal CHAT message with no extraData', () => + { + const chat = new MessengerThreadChat(5, 'hello', 0, null, MessengerThreadChat.CHAT); + expect(chat.offlineDelivered).toBe(false); + }); + + it('is false when extraData is some other value (e.g. group chat data)', () => + { + const chat = new MessengerThreadChat(5, 'hi', 0, 'Bob/figurestr/5', MessengerThreadChat.CHAT); + expect(chat.offlineDelivered).toBe(false); + }); + + it('is false for a non-CHAT type even if extraData is "offline"', () => + { + const chat = new MessengerThreadChat(5, 'hi', 0, 'offline', MessengerThreadChat.ROOM_INVITE); + expect(chat.offlineDelivered).toBe(false); + }); +}); +``` + +- [ ] **Step 2: Run it, confirm FAIL** + +Run: `cd Nitro-V3 && yarn test --run src/api/friends/MessengerThreadChat.test.ts` +Expected: FAIL — `offlineDelivered` is not a function/getter. + +- [ ] **Step 3: Add the getter** + +In `MessengerThreadChat.ts`, add after the `extraData` getter: +```typescript + public get offlineDelivered(): boolean + { + return (this._type === MessengerThreadChat.CHAT) && (this._extraData === 'offline'); + } +``` + +- [ ] **Step 4: Run the test, confirm PASS (4 cases).** + +- [ ] **Step 5: Type-check + full suite** + +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run` +Expected: typecheck shows only the known pre-existing `FloorplanCanvasSVG.tsx(143,20): TS2503`; tests green except the 3 known pre-existing floorplan failures. + +- [ ] **Step 6: Commit** +```bash +cd Nitro-V3 +git add src/api/friends/MessengerThreadChat.ts src/api/friends/MessengerThreadChat.test.ts +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(messenger): offlineDelivered flag on thread chat" +``` + +--- + +## Task 5: Client — render the "sent while offline" marker + +**Files:** +- Modify: `Nitro-V3/src/components/friends/views/messenger/messenger-thread/FriendsMessengerThreadGroup.tsx` +- Modify: `Nitro-V3/public/configuration/UITexts.example` +- Modify: a messenger CSS file (see Step 3) + +- [ ] **Step 1: Add the localization key** + +In `public/configuration/UITexts.example`, add a key near other `messenger.*` entries (match the file's JSON format — confirm by reading an existing `messenger.` line): +```json +"messenger.offline.delivered": "Sent while you were offline", +``` +(The user can localize the value in their live `UITexts` later. `LocalizeText` falls back to the key string if absent, so this never crashes.) + +- [ ] **Step 2: Render the marker in the message bubble** + +In `FriendsMessengerThreadGroup.tsx`, the bubble maps `group.chats`. `LocalizeText` is already imported. In the NON-translation branch (the `if(!chat.showTranslation)` return), append the marker when `chat.offlineDelivered`. Replace: +```tsx + if(!chat.showTranslation) + { + return { chat.message }; + } +``` +with: +```tsx + if(!chat.showTranslation) + { + return ( + + { chat.message } + { chat.offlineDelivered && + { LocalizeText('messenger.offline.delivered') } } + + ); + } +``` +(Leave the translation branch as-is — an offline message that is also auto-translated is a rare combination and the marker on the plain branch covers the normal case.) + +- [ ] **Step 3: Add the marker style** + +Find the CSS file that styles the messenger thread (search for an existing class used here, e.g. `messenger-message-bubble` or `messenger-message-time`): +Run: `grep -rl "messenger-message-bubble" Nitro-V3/src/css` +Append to that file a subtle style: +```css +.messenger-offline-tag { + display: block; + margin-top: 2px; + font-size: 10px; + font-style: italic; + opacity: 0.6; +} +``` +If the grep finds no file (the classes are global/elsewhere), append the same rule to `src/css/friends/FriendsView.css` instead, and note that in your report. + +- [ ] **Step 4: Type-check + full suite** + +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run` +Expected: only the known pre-existing typecheck error; no new test failures. + +- [ ] **Step 5: Commit** +```bash +cd Nitro-V3 +git add src/components/friends/views/messenger/messenger-thread/FriendsMessengerThreadGroup.tsx public/configuration/UITexts.example +# plus the CSS file you edited: +git add +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(messenger): show 'sent while offline' marker in thread" +``` + +--- + +## Task 6: Integration verification + +**Files:** none (manual + automated checks; fix-up commits only). + +- [ ] **Step 1: Automated checks** +``` +cd Nitro-V3 && yarn typecheck && yarn test --run +cd Arcturus-Morningstar-Extended/Emulator && mvn -q clean package -DskipTests +``` +Expected: client typecheck shows only the pre-existing `FloorplanCanvasSVG.tsx(143,20): TS2503`; client tests green except the 3 known floorplan failures (+4 new MessengerThreadChat cases passing); emulator BUILD SUCCESS. (No renderer change this phase.) + +- [ ] **Step 2: Live two-session manual test** + +Run the new jar + `yarn start`. With two accounts A and B who are friends: +1. **Store while offline:** B logs out. A opens the messenger thread with B and sends a message. (A's client shows the sent message as normal.) +2. **Deliver on login:** B logs in → the message appears in B's thread with A, carrying the "Sent while you were offline" marker. +3. **Order + multiple:** A sends 3 messages while B is offline → on B's login all 3 appear in order, each marked, and the `messenger_offline` rows for B are gone (delivered + deleted): + `SELECT * FROM messenger_offline WHERE user_id = ;` → 0 rows after login. +4. **Online still instant:** with both online, messages deliver immediately and show NO offline marker (wire unchanged for online 1:1). +5. **Cap:** (optional) inserting >200 stored messages for one user evicts the oldest. +6. **No regressions:** room invites, group/staff chat, and normal messaging still work. + +- [ ] **Step 3: Commit any fix-ups** (only if needed) +```bash +cd Nitro-V3 +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -am "fix(messenger): offline message integration fixes" +``` + +--- + +## Notes / scope boundaries +- **Word filter:** offline messages are word-filtered at store time (sender online) so the recipient sees filtered text, matching the online path. They are NOT written to `chatlogs_private` (offline messages were never chat-logged before; adding that is out of scope). +- **Displayed time:** the thread shows the client receive-time (existing behavior); `secondsSinceSent` is sent but the bubble timestamp is local. The "sent while offline" marker is what signals the message is delayed; back-dating the bubble timestamp is out of scope. +- **Read receipts (Phase 3)** will mark these delivered-on-login messages as read once the recipient opens the thread — not part of Phase 2. +- Do NOT push/merge automatically; the branch already carries Phase 1 + the user's own `feat(chat)` commit. diff --git a/docs/superpowers/plans/2026-06-02-messenger-phase3-read-receipts.md b/docs/superpowers/plans/2026-06-02-messenger-phase3-read-receipts.md new file mode 100644 index 0000000..fb41845 --- /dev/null +++ b/docs/superpowers/plans/2026-06-02-messenger-phase3-read-receipts.md @@ -0,0 +1,586 @@ +# Messenger Phase 3 — Read Receipts (✓ / ✓✓) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** WhatsApp-style 2-state read receipts on your own sent messages — `✓` sent, `✓✓` read — driven by a live relay (no persistence). + +**Architecture:** Two new CUSTOM packets. Client→server `MarkConsoleRead(peerId)` is sent when you focus/read a conversation. The emulator relays it to the peer (if online and a friend) as server→client `ConsoleReadReceipt(readerId)`. The recipient's client marks its own messages in that conversation as READ and renders `✓✓`. + +**Design note — no DB, live-relay only (refinement of the spec):** the spec proposed a `messenger_read_state` table + a login-time receipt batch. The Nitro client does NOT persist per-message history across sessions, so a persisted receipt would have no message to update on next login. Persistence is therefore omitted; receipts are a live in-session relay. This keeps Phase 3 simpler with no loss of user-visible behavior. (If cross-session receipts are ever wanted, they'd require persisting client-side message history first — out of scope.) + +**Tech Stack:** Arcturus (Java 21/Maven), Nitro_Render_V3 (TypeScript, Vitest), Nitro-V3 (React 19, Vitest). + +--- + +## Branches & rules +All repos on `feat/messenger-groups-receipts`. Client commits use `git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com`. No Co-Authored-By / AI attribution. Emulator working tree has an UNRELATED modified `soundboard/SoundboardPlayEvent.java` + untracked jars — never stage those; `git add` only the listed files. + +## Header IDs (custom, verified free in all 4 files) +| Packet | Direction | Renderer header | Emulator header | Value | +|---|---|---|---|---| +| MarkConsoleRead | client→server | `OutgoingHeader.MARK_CONSOLE_READ` | `Incoming.MarkConsoleReadEvent` | **4085** | +| ConsoleReadReceipt | server→client | `IncomingHeader.CONSOLE_READ_RECEIPT` | `Outgoing.ConsoleReadReceiptComposer` | **4086** | + +(Renderer Outgoing N == Emulator Incoming N; Renderer Incoming N == Emulator Outgoing N — the verified convention.) + +## File map +**Renderer (`Nitro_Render_V3/packages/communication/src/`):** +- Modify `messages/outgoing/OutgoingHeader.ts`, `messages/incoming/IncomingHeader.ts`, `NitroMessages.ts`, the 3 friendlist `index.ts` barrels. +- Create `messages/outgoing/friendlist/MarkConsoleReadComposer.ts` +- Create `messages/incoming/friendlist/ConsoleReadReceiptEvent.ts` +- Create `messages/parser/friendlist/ConsoleReadReceiptParser.ts` +- Create `messages/parser/friendlist/__tests__/ConsoleReadReceiptParser.test.ts` + +**Emulator (`Arcturus-Morningstar-Extended/Emulator/src/main/java/com/eu/habbo/`):** +- Modify `messages/incoming/Incoming.java`, `messages/outgoing/Outgoing.java`, `messages/PacketManager.java` +- Create `messages/incoming/friends/MarkConsoleReadEvent.java` +- Create `messages/outgoing/friends/ConsoleReadReceiptComposer.java` + +**Client (`Nitro-V3/src/`):** +- Modify `api/friends/MessengerThreadChat.ts` (+ test) and `api/friends/MessengerThread.ts` (+ test) +- Modify `hooks/friends/useMessenger.ts` +- Modify `components/friends/views/messenger/messenger-thread/FriendsMessengerThreadGroup.tsx` +- Modify `src/css/friends/FriendsView.css` + +--- + +## Task P3-1: Renderer — packets + registration + parser test + +**Files:** see File map (renderer). + +- [ ] **Step 1: Write the failing parser test** + +Create `packages/communication/src/messages/parser/friendlist/__tests__/ConsoleReadReceiptParser.test.ts` (mirror the existing `__tests__/FriendCategoryComposers.test.ts` / mentions parser test style with a `TestWrapper` over `BinaryReader`/`BinaryWriter`): +```typescript +import { describe, expect, it } from 'vitest'; +import { BinaryReader, BinaryWriter } from '@nitrots/utils'; +import { ConsoleReadReceiptParser } from '../ConsoleReadReceiptParser'; + +class TestWrapper +{ + constructor(private reader: BinaryReader) {} + readByte() { return this.reader.readByte(); } + readShort() { return this.reader.readShort(); } + readInt() { return this.reader.readInt(); } + readString() { const len = this.reader.readShort(); return this.reader.readBytes(len).toString(); } + header = 0; + get bytesAvailable() { return this.reader.remaining() > 0; } +} + +describe('ConsoleReadReceiptParser', () => +{ + it('parses the reader id', () => + { + const w = new BinaryWriter(); + w.writeInt(42); + const parser = new ConsoleReadReceiptParser(); + parser.flush(); + parser.parse(new TestWrapper(new BinaryReader(w.getBuffer())) as any); + expect(parser.readerId).toBe(42); + }); +}); +``` + +- [ ] **Step 2: Run it, confirm FAIL** + +Run: `cd Nitro_Render_V3 && yarn test --run packages/communication/src/messages/parser/friendlist/__tests__/ConsoleReadReceiptParser.test.ts` +Expected: FAIL (module not found). + +- [ ] **Step 3: Create the parser** + +`packages/communication/src/messages/parser/friendlist/ConsoleReadReceiptParser.ts` (mirror `NewConsoleMessageParser`): +```typescript +import { IMessageDataWrapper, IMessageParser } from '@nitrots/api'; + +export class ConsoleReadReceiptParser implements IMessageParser +{ + private _readerId: number; + + public flush(): boolean + { + this._readerId = 0; + return true; + } + + public parse(wrapper: IMessageDataWrapper): boolean + { + if(!wrapper) return false; + + this._readerId = wrapper.readInt(); + + return true; + } + + public get readerId(): number + { + return this._readerId; + } +} +``` + +- [ ] **Step 4: Create the incoming event** + +`packages/communication/src/messages/incoming/friendlist/ConsoleReadReceiptEvent.ts` (mirror `NewConsoleMessageEvent`): +```typescript +import { IMessageEvent } from '@nitrots/api'; +import { MessageEvent } from '@nitrots/events'; +import { ConsoleReadReceiptParser } from '../../parser'; + +export class ConsoleReadReceiptEvent extends MessageEvent implements IMessageEvent +{ + constructor(callBack: Function) + { + super(callBack, ConsoleReadReceiptParser); + } + + public getParser(): ConsoleReadReceiptParser + { + return this.parser as ConsoleReadReceiptParser; + } +} +``` + +- [ ] **Step 5: Create the outgoing composer** + +`packages/communication/src/messages/outgoing/friendlist/MarkConsoleReadComposer.ts` (mirror `SetRelationshipStatusComposer`): +```typescript +import { IMessageComposer } from '@nitrots/api'; + +export class MarkConsoleReadComposer implements IMessageComposer> +{ + private _data: ConstructorParameters; + + constructor(peerId: number) + { + this._data = [ peerId ]; + } + + public getMessageArray() + { + return this._data; + } + + public dispose(): void + { + return; + } +} +``` + +- [ ] **Step 6: Add header constants** + +In `OutgoingHeader.ts` (near the friend headers): `public static MARK_CONSOLE_READ = 4085;` +In `IncomingHeader.ts` (near the messenger headers): `public static CONSOLE_READ_RECEIPT = 4086;` + +- [ ] **Step 7: Barrel exports** + +- `messages/outgoing/friendlist/index.ts`: `export * from './MarkConsoleReadComposer';` +- `messages/incoming/friendlist/index.ts`: `export * from './ConsoleReadReceiptEvent';` +- `messages/parser/friendlist/index.ts`: `export * from './ConsoleReadReceiptParser';` + +- [ ] **Step 8: Register in NitroMessages** + +In `NitroMessages.ts`: add the two classes to the existing friendlist imports, then: +- in the events block (next to `this._events.set(IncomingHeader.MESSENGER_CHAT, NewConsoleMessageEvent);`): `this._events.set(IncomingHeader.CONSOLE_READ_RECEIPT, ConsoleReadReceiptEvent);` +- in the composers block (next to `this._composers.set(OutgoingHeader.MESSENGER_CHAT, SendMessageComposer);`): `this._composers.set(OutgoingHeader.MARK_CONSOLE_READ, MarkConsoleReadComposer);` + +- [ ] **Step 9: Compile + test** + +Run: `cd Nitro_Render_V3 && yarn compile:fast && yarn test --run` +Expected: compile clean; all tests pass (142 prior + 1 new = 143). + +- [ ] **Step 10: Commit** +```bash +cd Nitro_Render_V3 +git add packages/communication/src/messages/ packages/communication/src/NitroMessages.ts +git commit -m "feat(messenger): read-receipt packets (MarkConsoleRead + ConsoleReadReceipt)" +``` + +--- + +## Task P3-2: Emulator — handler + composer + registration + +**Files:** see File map (emulator). + +> No emulator unit tests; verify with `mvn package`. + +- [ ] **Step 1: Header constants** + +In `Incoming.java` (near the friend constants): `public static final int MarkConsoleReadEvent = 4085;` +In `Outgoing.java` (near the friend composers): `public final static int ConsoleReadReceiptComposer = 4086;` + +- [ ] **Step 2: Create the outgoing composer** + +`messages/outgoing/friends/ConsoleReadReceiptComposer.java`: +```java +package com.eu.habbo.messages.outgoing.friends; + +import com.eu.habbo.messages.ServerMessage; +import com.eu.habbo.messages.outgoing.MessageComposer; +import com.eu.habbo.messages.outgoing.Outgoing; + +public class ConsoleReadReceiptComposer extends MessageComposer { + private final int readerId; + + public ConsoleReadReceiptComposer(int readerId) { + this.readerId = readerId; + } + + @Override + protected ServerMessage composeInternal() { + this.response.init(Outgoing.ConsoleReadReceiptComposer); + this.response.appendInt(this.readerId); + return this.response; + } +} +``` + +- [ ] **Step 3: Create the incoming handler** + +`messages/incoming/friends/MarkConsoleReadEvent.java`. The reader (me) tells the server it read `peerId`'s messages; the server relays a receipt to `peerId` IF `peerId` is online AND a friend (anti-spoof). 1:1 only — `peerId <= 0` (e.g. StaffChat = -1) is ignored. +```java +package com.eu.habbo.messages.incoming.friends; + +import com.eu.habbo.Emulator; +import com.eu.habbo.habbohotel.users.Habbo; +import com.eu.habbo.messages.incoming.MessageHandler; +import com.eu.habbo.messages.outgoing.friends.ConsoleReadReceiptComposer; + +public class MarkConsoleReadEvent extends MessageHandler { + @Override + public void handle() throws Exception { + int peerId = this.packet.readInt(); + Habbo me = this.client.getHabbo(); + + if (me == null || peerId <= 0) return; + + if (me.getMessenger().getFriend(peerId) == null) return; + + Habbo peer = Emulator.getGameServer().getGameClientManager().getHabbo(peerId); + if (peer == null || peer.getClient() == null) return; + + peer.getClient().sendResponse(new ConsoleReadReceiptComposer(me.getHabboInfo().getId())); + } +} +``` +Before writing, confirm `me.getMessenger().getFriend(int)` exists (it's used in `FriendPrivateMessageEvent`) and `Emulator.getGameServer().getGameClientManager().getHabbo(int)` (used in `MessengerBuddy.onMessageReceived`). Adapt + report if a signature differs. + +- [ ] **Step 4: Register the handler** + +In `PacketManager.registerFriends()`: `this.registerHandler(Incoming.MarkConsoleReadEvent, MarkConsoleReadEvent.class);` +(`registerFriends` uses a wildcard `import com.eu.habbo.messages.incoming.friends.*;` — confirm with `grep -n "incoming.friends" PacketManager.java`; if explicit imports are used instead, add `import ...MarkConsoleReadEvent;`.) + +- [ ] **Step 5: Build** + +Run: `cd Arcturus-Morningstar-Extended/Emulator && mvn -q clean package -DskipTests` +Expected: BUILD SUCCESS. + +- [ ] **Step 6: Commit (only the 4 files)** +```bash +cd Arcturus-Morningstar-Extended +git add Emulator/src/main/java/com/eu/habbo/messages/incoming/friends/MarkConsoleReadEvent.java Emulator/src/main/java/com/eu/habbo/messages/outgoing/friends/ConsoleReadReceiptComposer.java Emulator/src/main/java/com/eu/habbo/messages/incoming/Incoming.java Emulator/src/main/java/com/eu/habbo/messages/outgoing/Outgoing.java Emulator/src/main/java/com/eu/habbo/messages/PacketManager.java +git commit -m "feat(messenger): relay read receipts between friends" +``` +`git show --stat HEAD` → exactly 5 files (no soundboard, no jars). + +--- + +## Task P3-3: Client — message status model (TDD) + +**Files:** +- Modify: `Nitro-V3/src/api/friends/MessengerThreadChat.ts` + Test `MessengerThreadChat.test.ts` (extend the existing test file from Phase 2) +- Modify: `Nitro-V3/src/api/friends/MessengerThread.ts` + Test `Nitro-V3/src/api/friends/MessengerThread.test.ts` + +- [ ] **Step 1: Write the failing tests** + +Append to the existing `src/api/friends/MessengerThreadChat.test.ts`: +```typescript +describe('MessengerThreadChat status', () => +{ + it('defaults to SENT', () => + { + const chat = new MessengerThreadChat(5, 'hi', 0, null, MessengerThreadChat.CHAT); + expect(chat.status).toBe(MessengerThreadChat.SENT); + }); + + it('can be set to READ', () => + { + const chat = new MessengerThreadChat(5, 'hi', 0, null, MessengerThreadChat.CHAT); + chat.setStatus(MessengerThreadChat.READ); + expect(chat.status).toBe(MessengerThreadChat.READ); + }); +}); +``` + +Create `src/api/friends/MessengerThread.test.ts`: +```typescript +import { describe, expect, it } from 'vitest'; +import { MessengerFriend } from './MessengerFriend'; +import { MessengerThread } from './MessengerThread'; +import { MessengerThreadChat } from './MessengerThreadChat'; + +const makeThread = (participantId: number): MessengerThread => +{ + const friend = new MessengerFriend(); + friend.id = participantId; + return new MessengerThread(friend); +}; + +describe('MessengerThread.setMessagesReadFromUser', () => +{ + it('marks only the given user\'s messages as READ', () => + { + const thread = makeThread(7); + const mine = thread.addMessage(100, 'a', 0, null, MessengerThreadChat.CHAT); // my message + const theirs = thread.addMessage(7, 'b', 0, null, MessengerThreadChat.CHAT); // their message + + thread.setMessagesReadFromUser(100); + + expect(mine.status).toBe(MessengerThreadChat.READ); + expect(theirs.status).toBe(MessengerThreadChat.SENT); + }); +}); +``` + +- [ ] **Step 2: Run, confirm FAIL** + +Run: `cd Nitro-V3 && yarn test --run src/api/friends/MessengerThreadChat.test.ts src/api/friends/MessengerThread.test.ts` +Expected: FAIL (SENT/READ/status/setStatus/setMessagesReadFromUser missing). + +- [ ] **Step 3: Add status to MessengerThreadChat** + +In `MessengerThreadChat.ts`, add the constants next to the existing `CHAT`/`ROOM_INVITE` statics: +```typescript + public static SENT: number = 0; + public static READ: number = 1; +``` +Add the field next to the other private fields: +```typescript + private _status: number = MessengerThreadChat.SENT; +``` +Add getter + setter (next to the `offlineDelivered` getter): +```typescript + public get status(): number + { + return this._status; + } + + public setStatus(status: number): void + { + this._status = status; + } +``` + +- [ ] **Step 4: Add the marking method to MessengerThread** + +In `MessengerThread.ts`, add (e.g. after `setRead()`): +```typescript + public setMessagesReadFromUser(userId: number): void + { + for(const group of this._groups) + { + if(group.userId !== userId) continue; + + for(const chat of group.chats) chat.setStatus(MessengerThreadChat.READ); + } + } +``` +(`MessengerThreadChat` is already imported in this file.) + +- [ ] **Step 5: Run, confirm PASS** (Chat: 6 cases now; Thread: 1 case). + +- [ ] **Step 6: typecheck + full suite** + +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run` +Expected: only the known pre-existing `FloorplanCanvasSVG.tsx(143,20): TS2503`; no new failures (3 known floorplan failures remain). + +- [ ] **Step 7: Commit** +```bash +cd Nitro-V3 +git add src/api/friends/MessengerThreadChat.ts src/api/friends/MessengerThreadChat.test.ts src/api/friends/MessengerThread.ts src/api/friends/MessengerThread.test.ts +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(messenger): SENT/READ status on thread chats + mark-read helper" +``` + +--- + +## Task P3-4: Client — wire receipts into useMessenger + +**Files:** +- Modify: `Nitro-V3/src/hooks/friends/useMessenger.ts` + +- [ ] **Step 1: Import the packets** + +In the top `@nitrots/nitro-renderer` import of `useMessenger.ts`, add `ConsoleReadReceiptEvent` and `MarkConsoleReadComposer` (alongside `NewConsoleMessageEvent`, `SendMessageComposer as SendMessageComposerPacket`). `GetSessionDataManager` is already imported. + +- [ ] **Step 2: Send MarkConsoleRead when a conversation is focused** + +The existing `useEffect([activeThreadId])` marks the active thread read locally. Extend it to also tell the peer. Replace that effect's body so that, after computing the active thread, it sends the composer for a real 1:1 participant: +```typescript + useEffect(() => + { + if (activeThreadId <= 0) return; + + let participantId = 0; + + setMessageThreads(prevValue => + { + const newValue = [...prevValue]; + const index = newValue.findIndex(newThread => (newThread.threadId === activeThreadId)); + + if (index >= 0) + { + newValue[index] = CloneObject(newValue[index]); + newValue[index].setRead(); + participantId = newValue[index].participant?.id ?? 0; + } + + return newValue; + }); + + if (participantId > 0) SendMessageComposer(new MarkConsoleReadComposer(participantId)); + }, [activeThreadId]); +``` + +- [ ] **Step 3: Also mark-read when a message arrives in the already-active thread** + +In the `NewConsoleMessageEvent` handler, after `sendMessage(...)`, notify the peer if this thread is the one currently open: +```typescript + useMessageEvent(NewConsoleMessageEvent, event => + { + const parser = event.getParser(); + const thread = getMessageThread(parser.senderId); + + if (!thread) return; + + sendMessage(thread, parser.senderId, parser.messageText, parser.secondsSinceSent, parser.extraData); + + if ((thread.threadId === activeThreadId) && (parser.senderId > 0)) SendMessageComposer(new MarkConsoleReadComposer(parser.senderId)); + }); +``` + +- [ ] **Step 4: Handle the incoming receipt — mark own messages READ** + +Add a new event subscription (near the other `useMessageEvent` calls). `parser.readerId` is the friend who read MY messages; find the thread with that participant and mark my own messages READ: +```typescript + useMessageEvent(ConsoleReadReceiptEvent, event => + { + const parser = event.getParser(); + const ownUserId = GetSessionDataManager().userId; + + setMessageThreads(prevValue => + { + const index = prevValue.findIndex(thread => (thread.participant && (thread.participant.id === parser.readerId))); + + if (index === -1) return prevValue; + + const newValue = [...prevValue]; + + newValue[index] = CloneObject(newValue[index]); + newValue[index].setMessagesReadFromUser(ownUserId); + + return newValue; + }); + }); +``` + +- [ ] **Step 5: typecheck + full suite** + +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run` +Expected: only the pre-existing typecheck error; no new test failures. + +- [ ] **Step 6: Commit** +```bash +cd Nitro-V3 +git add src/hooks/friends/useMessenger.ts +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(messenger): send mark-read on focus, mark own messages read on receipt" +``` + +--- + +## Task P3-5: Client — render ✓ / ✓✓ + CSS + +**Files:** +- Modify: `Nitro-V3/src/components/friends/views/messenger/messenger-thread/FriendsMessengerThreadGroup.tsx` +- Modify: `Nitro-V3/src/css/friends/FriendsView.css` + +- [ ] **Step 1: Render the status indicator on own private-chat bubbles** + +In `FriendsMessengerThreadGroup.tsx`, the final `return (...)` renders the message row; the own-message avatar is gated by `isOwnChat`. `MessengerThreadChat` and `MessengerGroupType` are already imported. After the `.messenger-message-time` `` (inside `.messenger-message-body`), add a status indicator shown only for own 1:1 CHAT groups. Compute the last chat once and render: +```tsx + { group.chats[0].date.toLocaleTimeString() } + { isOwnChat && (group.type === MessengerGroupType.PRIVATE_CHAT) && (group.chats[group.chats.length - 1].type === MessengerThreadChat.CHAT) && + + { (group.chats[group.chats.length - 1].status === MessengerThreadChat.READ) ? '✓✓' : '✓' } + } +``` +(Insert this block immediately after the existing `messenger-message-time` line, still inside the `.messenger-message-body` ``.) + +- [ ] **Step 2: Add CSS** + +Append to `src/css/friends/FriendsView.css`: +```css +.messenger-message-status { + margin-top: 1px; + font-size: 10px; + line-height: 10px; + text-align: right; + opacity: 0.6; +} +.messenger-message-status.read { + color: #4fc3f7; + opacity: 1; +} +``` + +- [ ] **Step 3: typecheck + full suite** + +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run` +Expected: only the pre-existing typecheck error; no new test failures. + +- [ ] **Step 4: Commit** +```bash +cd Nitro-V3 +git add src/components/friends/views/messenger/messenger-thread/FriendsMessengerThreadGroup.tsx src/css/friends/FriendsView.css +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(messenger): render sent/read checkmarks on own messages" +``` + +--- + +## Task P3-6: Integration verification + +**Files:** none (automated + manual; fix-ups only). + +- [ ] **Step 1: Automated checks** +``` +cd Nitro_Render_V3 && yarn compile:fast && yarn test --run +cd Nitro-V3 && yarn typecheck && yarn test --run +cd Arcturus-Morningstar-Extended/Emulator && mvn -q clean package -DskipTests +``` +Expected: renderer tests green (143); client typecheck shows only the pre-existing `FloorplanCanvasSVG.tsx(143,20): TS2503`, tests green except the 3 known floorplan failures (+ the new model cases pass); emulator BUILD SUCCESS. + +- [ ] **Step 2: Live two-session manual test** + +Run the new jar + `yarn start`. Accounts A and B (friends), both online: +1. **Sent (✓):** A sends B a message while B's messenger thread with A is NOT focused → on A's side the message shows a single `✓`. +2. **Read (✓✓):** B opens/focuses the conversation with A → A's message flips to `✓✓` (blue) live. +3. **New message after read:** A sends another message → shows `✓` again; when B (thread still focused) receives it, A flips to `✓✓` (the active-thread mark-read path). +4. **Offline interplay (Phase 2):** A messages B while B offline → A shows `✓`; B logs in and opens the thread → A (if still online) sees `✓✓`. +5. **No receipts for non-1:1:** opening the Staff Chat / a group chat thread does not produce errors and shows no checkmarks on those messages. +6. **Privacy/abuse:** a receipt only arrives for actual friends (the handler ignores non-friends and `peerId <= 0`). +7. **No regressions:** sending, receiving, offline markers (Phase 2), and groups (Phase 1) all still work. + +- [ ] **Step 3: Commit any fix-ups** (only if needed) +```bash +cd Nitro-V3 +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -am "fix(messenger): read-receipt integration fixes" +``` + +--- + +## Scope boundaries +- **No persistence / no login batch** (see Design note): receipts are live-relay only; ✓✓ applies within the session the sender is online for. +- **2-state only:** `✓` (sent) and `✓✓` (read). No separate "delivered" state. +- **1:1 only:** group chat, staff chat, and bots never produce receipts (`peerId <= 0` and non-friends are ignored server-side; the client only renders checks on `PRIVATE_CHAT` CHAT groups). +- **Receipt marks ALL current own messages in the thread read** (not a per-message timestamp diff) — correct for the 2-state model since a focus/read means everything visible is read; messages sent afterward start at `✓` again. +- No renderer/client message-history persistence is added. +- Do NOT push/merge automatically; the branch carries Phases 1–2 + the user's own parallel commits. diff --git a/docs/superpowers/plans/2026-06-02-messenger-phase4-typing-indicator.md b/docs/superpowers/plans/2026-06-02-messenger-phase4-typing-indicator.md new file mode 100644 index 0000000..e1e40e0 --- /dev/null +++ b/docs/superpowers/plans/2026-06-02-messenger-phase4-typing-indicator.md @@ -0,0 +1,533 @@ +# Messenger Phase 4 — Typing Indicator Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Show "X sta scrivendo…" in a 1:1 conversation while the friend is typing, WhatsApp-style. + +**Architecture:** Two ephemeral CUSTOM packets (never stored). Client→server `ConsoleTyping(peerId, isTyping)` is sent when the user starts/stops typing in a thread; the emulator relays it (friend + online only) to the peer as server→client `FriendTyping(senderId, isTyping)`. The recipient's client shows a typing indicator for that friend, auto-expiring after a few seconds. + +**Tech Stack:** Arcturus (Java 21/Maven), Nitro_Render_V3 (TypeScript, Vitest), Nitro-V3 (React 19, Vitest). No DB. + +--- + +## Branches & rules +All repos on `feat/messenger-groups-receipts`. Client commits use `git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com`. No Co-Authored-By / AI attribution. Emulator working tree has an UNRELATED modified `soundboard/SoundboardPlayEvent.java` + untracked jars — never stage those; `git add` only the listed files. + +## Header IDs (custom, verified free in all 4 files) +| Packet | Direction | Renderer header | Emulator header | Value | +|---|---|---|---|---| +| ConsoleTyping | client→server | `OutgoingHeader.CONSOLE_TYPING` | `Incoming.ConsoleTypingEvent` | **4087** | +| FriendTyping | server→client | `IncomingHeader.FRIEND_TYPING` | `Outgoing.FriendTypingComposer` | **4088** | + +Wire: ConsoleTyping = `int peerId`, `boolean isTyping`. FriendTyping = `int senderId`, `boolean isTyping`. (Booleans are supported in composers/parsers — e.g. `DeclineFriendMessageComposer` sends a boolean; `FriendParser` reads booleans.) + +## File map +**Renderer (`Nitro_Render_V3/packages/communication/src/`):** +- Create `messages/outgoing/friendlist/ConsoleTypingComposer.ts` +- Create `messages/incoming/friendlist/FriendIsTypingEvent.ts` +- Create `messages/parser/friendlist/FriendIsTypingParser.ts` +- Create `messages/parser/friendlist/__tests__/FriendIsTypingParser.test.ts` +- Modify `messages/outgoing/OutgoingHeader.ts`, `messages/incoming/IncomingHeader.ts`, `NitroMessages.ts`, the 3 friendlist `index.ts` + +**Emulator (`Arcturus-Morningstar-Extended/Emulator/src/main/java/com/eu/habbo/`):** +- Create `messages/incoming/friends/ConsoleTypingEvent.java` +- Create `messages/outgoing/friends/FriendTypingComposer.java` +- Modify `messages/incoming/Incoming.java`, `messages/outgoing/Outgoing.java`, `messages/PacketManager.java` + +**Client (`Nitro-V3/src/`):** +- Modify `hooks/friends/useMessenger.ts` (incoming typing state + outgoing action) +- Modify `components/friends/views/messenger/FriendsMessengerView.tsx` (send typing + render indicator) +- Modify `public/configuration/UITexts.example` (`messenger.typing` key) +- Modify `src/css/friends/FriendsView.css` (`.messenger-typing-indicator`) + +--- + +## Task P4-1: Renderer — typing packets + parser test + +**Files:** see File map (renderer). + +- [ ] **Step 1: Failing parser test** + +Create `packages/communication/src/messages/parser/friendlist/__tests__/FriendIsTypingParser.test.ts`: +```typescript +import { describe, expect, it } from 'vitest'; +import { BinaryReader, BinaryWriter } from '@nitrots/utils'; +import { FriendIsTypingParser } from '../FriendIsTypingParser'; + +class TestWrapper +{ + constructor(private reader: BinaryReader) {} + readByte() { return this.reader.readByte(); } + readBoolean() { return this.reader.readByte() === 1; } + readShort() { return this.reader.readShort(); } + readInt() { return this.reader.readInt(); } + readString() { const len = this.reader.readShort(); return this.reader.readBytes(len).toString(); } + header = 0; + get bytesAvailable() { return this.reader.remaining() > 0; } +} + +describe('FriendIsTypingParser', () => +{ + it('parses senderId + isTyping=true', () => + { + const w = new BinaryWriter(); + w.writeInt(42); w.writeByte(1); + const parser = new FriendIsTypingParser(); + parser.flush(); + parser.parse(new TestWrapper(new BinaryReader(w.getBuffer())) as any); + expect(parser.senderId).toBe(42); + expect(parser.isTyping).toBe(true); + }); + + it('parses isTyping=false', () => + { + const w = new BinaryWriter(); + w.writeInt(42); w.writeByte(0); + const parser = new FriendIsTypingParser(); + parser.flush(); + parser.parse(new TestWrapper(new BinaryReader(w.getBuffer())) as any); + expect(parser.isTyping).toBe(false); + }); +}); +``` +Run `cd Nitro_Render_V3 && yarn test --run packages/communication/src/messages/parser/friendlist/__tests__/FriendIsTypingParser.test.ts` → FAIL. + +(Confirm `BinaryWriter` has `writeByte`/`writeInt` — the mentions/category tests use `writeInt`/`writeString`; if `writeByte` is named differently, use the real method that writes a single byte, mirroring how the existing parser tests write a boolean/byte. If unsure, write the boolean as `w.writeInt(1)` and read with `readInt() === 1` in BOTH parser and test — but prefer a real 1-byte boolean to match the emulator's `appendBoolean`/`readBoolean`. Inspect an existing parser test that round-trips a boolean to copy the exact writer call.) + +- [ ] **Step 2: Create the parser** + +`packages/communication/src/messages/parser/friendlist/FriendIsTypingParser.ts`: +```typescript +import { IMessageDataWrapper, IMessageParser } from '@nitrots/api'; + +export class FriendIsTypingParser implements IMessageParser +{ + private _senderId: number; + private _isTyping: boolean; + + public flush(): boolean + { + this._senderId = 0; + this._isTyping = false; + return true; + } + + public parse(wrapper: IMessageDataWrapper): boolean + { + if(!wrapper) return false; + + this._senderId = wrapper.readInt(); + this._isTyping = wrapper.readBoolean(); + + return true; + } + + public get senderId(): number + { + return this._senderId; + } + + public get isTyping(): boolean + { + return this._isTyping; + } +} +``` +(Confirm `IMessageDataWrapper` has `readBoolean()` — `FriendParser` uses it. If not, use `wrapper.readInt() === 1`.) + +- [ ] **Step 3: Create the incoming event** + +`packages/communication/src/messages/incoming/friendlist/FriendIsTypingEvent.ts`: +```typescript +import { IMessageEvent } from '@nitrots/api'; +import { MessageEvent } from '@nitrots/events'; +import { FriendIsTypingParser } from '../../parser'; + +export class FriendIsTypingEvent extends MessageEvent implements IMessageEvent +{ + constructor(callBack: Function) + { + super(callBack, FriendIsTypingParser); + } + + public getParser(): FriendIsTypingParser + { + return this.parser as FriendIsTypingParser; + } +} +``` + +- [ ] **Step 4: Create the outgoing composer** + +`packages/communication/src/messages/outgoing/friendlist/ConsoleTypingComposer.ts`: +```typescript +import { IMessageComposer } from '@nitrots/api'; + +export class ConsoleTypingComposer implements IMessageComposer> +{ + private _data: ConstructorParameters; + + constructor(peerId: number, isTyping: boolean) + { + this._data = [ peerId, isTyping ]; + } + + public getMessageArray() + { + return this._data; + } + + public dispose(): void + { + return; + } +} +``` + +- [ ] **Step 5: Header constants** +- `OutgoingHeader.ts`: `public static CONSOLE_TYPING = 4087;` +- `IncomingHeader.ts`: `public static FRIEND_TYPING = 4088;` + +- [ ] **Step 6: Barrel exports** +- `messages/outgoing/friendlist/index.ts`: `export * from './ConsoleTypingComposer';` +- `messages/incoming/friendlist/index.ts`: `export * from './FriendIsTypingEvent';` +- `messages/parser/friendlist/index.ts`: `export * from './FriendIsTypingParser';` + +- [ ] **Step 7: Register in NitroMessages** +Add the two classes to the friendlist imports, then: +- events: `this._events.set(IncomingHeader.FRIEND_TYPING, FriendIsTypingEvent);` +- composers: `this._composers.set(OutgoingHeader.CONSOLE_TYPING, ConsoleTypingComposer);` + +- [ ] **Step 8: Compile + test** +Run: `cd Nitro_Render_V3 && yarn compile:fast && yarn test --run` +Expected: compile clean; all tests pass (143 prior + 2 new = 145). + +- [ ] **Step 9: Commit** +```bash +cd Nitro_Render_V3 +git add packages/communication/src/messages/ packages/communication/src/NitroMessages.ts +git commit -m "feat(messenger): typing packets (ConsoleTyping + FriendTyping)" +``` + +--- + +## Task P4-2: Emulator — typing relay + +**Files:** see File map (emulator). No emulator unit tests; verify with `mvn package`. + +- [ ] **Step 1: Header constants** +- `Incoming.java`: `public static final int ConsoleTypingEvent = 4087;` +- `Outgoing.java`: `public final static int FriendTypingComposer = 4088;` + +- [ ] **Step 2: Outgoing composer** + +`messages/outgoing/friends/FriendTypingComposer.java`: +```java +package com.eu.habbo.messages.outgoing.friends; + +import com.eu.habbo.messages.ServerMessage; +import com.eu.habbo.messages.outgoing.MessageComposer; +import com.eu.habbo.messages.outgoing.Outgoing; + +public class FriendTypingComposer extends MessageComposer { + private final int senderId; + private final boolean isTyping; + + public FriendTypingComposer(int senderId, boolean isTyping) { + this.senderId = senderId; + this.isTyping = isTyping; + } + + @Override + protected ServerMessage composeInternal() { + this.response.init(Outgoing.FriendTypingComposer); + this.response.appendInt(this.senderId); + this.response.appendBoolean(this.isTyping); + return this.response; + } +} +``` +(Confirm `ServerMessage.appendBoolean(boolean)` exists — `UpdateFriendComposer`/`MessengerBuddy.serialize` both use `appendBoolean`. It does.) + +- [ ] **Step 3: Incoming handler** + +`messages/incoming/friends/ConsoleTypingEvent.java`. Reads `peerId` + `isTyping`; relays to `peerId` if online AND a friend; ignores `peerId <= 0` (1:1 only). Ephemeral — no storage. +```java +package com.eu.habbo.messages.incoming.friends; + +import com.eu.habbo.Emulator; +import com.eu.habbo.habbohotel.users.Habbo; +import com.eu.habbo.messages.incoming.MessageHandler; +import com.eu.habbo.messages.outgoing.friends.FriendTypingComposer; + +public class ConsoleTypingEvent extends MessageHandler { + @Override + public void handle() throws Exception { + int peerId = this.packet.readInt(); + boolean isTyping = this.packet.readBoolean(); + Habbo me = this.client.getHabbo(); + + if (me == null || peerId <= 0) return; + + if (me.getMessenger().getFriend(peerId) == null) return; + + Habbo peer = Emulator.getGameServer().getGameClientManager().getHabbo(peerId); + if (peer == null || peer.getClient() == null) return; + + peer.getClient().sendResponse(new FriendTypingComposer(me.getHabboInfo().getId(), isTyping)); + } +} +``` +(Confirm `this.packet.readBoolean()` exists — `ClientMessage.readBoolean()` is used across handlers. It does.) + +- [ ] **Step 4: Register handler** +In `PacketManager.registerFriends()`: `this.registerHandler(Incoming.ConsoleTypingEvent, ConsoleTypingEvent.class);` +(The `incoming.friends.*` wildcard import covers it — confirm with `grep -n "incoming.friends" PacketManager.java`.) + +- [ ] **Step 5: Build** +Run: `cd Arcturus-Morningstar-Extended/Emulator && mvn -q clean package -DskipTests` +Expected: BUILD SUCCESS. + +- [ ] **Step 6: Commit (only the 5 files)** +```bash +cd Arcturus-Morningstar-Extended +git add Emulator/src/main/java/com/eu/habbo/messages/incoming/friends/ConsoleTypingEvent.java Emulator/src/main/java/com/eu/habbo/messages/outgoing/friends/FriendTypingComposer.java Emulator/src/main/java/com/eu/habbo/messages/incoming/Incoming.java Emulator/src/main/java/com/eu/habbo/messages/outgoing/Outgoing.java Emulator/src/main/java/com/eu/habbo/messages/PacketManager.java +git commit -m "feat(messenger): relay typing status between friends" +``` +`git show --stat HEAD` → exactly 5 files (no soundboard, no jars). + +--- + +## Task P4-3: Client — typing state + action in useMessenger + +**Files:** Modify `Nitro-V3/src/hooks/friends/useMessenger.ts`. + +> No clean unit test here (timer + event-bus via the renderer mock). Verified by typecheck + the live test in P4-5. Keep the implementation tight. + +- [ ] **Step 1: Imports** +Add `ConsoleTypingComposer` and `FriendIsTypingEvent` to the `@nitrots/nitro-renderer` import line. Ensure `useRef` is imported from 'react' (the file imports `useEffect, useMemo, useRef, useState` after Phase 3 — confirm `useRef` is present). + +- [ ] **Step 2: Typing state + timers ref** +Inside `useMessengerState`, near the other `useState` calls, add: +```typescript + const [typingUserIds, setTypingUserIds] = useState([]); + const typingTimersRef = useRef>>(new Map()); +``` + +- [ ] **Step 3: Outgoing action** +Add (near `sendMessage` / other actions): +```typescript + const sendTypingStatus = (peerId: number, isTyping: boolean) => + { + if (!peerId || (peerId <= 0)) return; + + SendMessageComposer(new ConsoleTypingComposer(peerId, isTyping)); + }; +``` + +- [ ] **Step 4: Incoming handler with auto-expire** +Add a new `useMessageEvent` (near the others). When a friend is typing, add their id and (re)arm a 6s expiry; when they stop, remove immediately. +```typescript + useMessageEvent(FriendIsTypingEvent, event => + { + const parser = event.getParser(); + const senderId = parser.senderId; + + if (senderId <= 0) return; + + const timers = typingTimersRef.current; + const existing = timers.get(senderId); + + if (existing) + { + clearTimeout(existing); + timers.delete(senderId); + } + + if (parser.isTyping) + { + setTypingUserIds(prev => (prev.indexOf(senderId) >= 0) ? prev : [...prev, senderId]); + + timers.set(senderId, setTimeout(() => + { + typingTimersRef.current.delete(senderId); + setTypingUserIds(prev => prev.filter(id => (id !== senderId))); + }, 6000)); + } + else + { + setTypingUserIds(prev => prev.filter(id => (id !== senderId))); + } + }); +``` + +- [ ] **Step 5: Expose** +Add `typingUserIds` and `sendTypingStatus` to the `useMessengerState` return object (the bottom `return { ... }`). + +- [ ] **Step 6: typecheck + tests + lint:hooks** +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run && yarn lint:hooks` +Expected: typecheck only the pre-existing floorplan error; no new test failures; `lint:hooks` 0 errors. + +- [ ] **Step 7: Commit** +```bash +cd Nitro-V3 +git add src/hooks/friends/useMessenger.ts +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(messenger): incoming typing state + outgoing typing action" +``` + +--- + +## Task P4-4: Client — send typing + render indicator + +**Files:** +- Modify `Nitro-V3/src/components/friends/views/messenger/FriendsMessengerView.tsx` +- Modify `Nitro-V3/public/configuration/UITexts.example` +- Modify `Nitro-V3/src/css/friends/FriendsView.css` + +- [ ] **Step 1: Pull the new hook members** +In `FriendsMessengerView.tsx`, the `useMessenger()` destructure currently grabs `visibleThreads, activeThread, getMessageThread, sendMessage, setActiveThreadId, closeThread`. Add `typingUserIds = [], sendTypingStatus = null`. + +- [ ] **Step 2: Outgoing typing notifier (refs + idle timer)** +Add near the other refs/state at the top of the component: +```tsx + const isTypingRef = useRef(false); + const typingTimeoutRef = useRef>(null); + + const stopTyping = () => + { + if(typingTimeoutRef.current) + { + clearTimeout(typingTimeoutRef.current); + typingTimeoutRef.current = null; + } + + if(isTypingRef.current && activeThread && activeThread.participant && (activeThread.participant.id > 0)) + { + sendTypingStatus(activeThread.participant.id, false); + } + + isTypingRef.current = false; + }; + + const handleInputChange = (value: string) => + { + setMessageText(value); + + const peerId = (activeThread && activeThread.participant) ? activeThread.participant.id : 0; + + if(peerId <= 0) return; + + if(!value.length) + { + stopTyping(); + return; + } + + if(!isTypingRef.current) + { + sendTypingStatus(peerId, true); + isTypingRef.current = true; + } + + if(typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current); + typingTimeoutRef.current = setTimeout(() => stopTyping(), 4000); + }; +``` +`useRef` is already imported in this file. + +- [ ] **Step 3: Wire the input + send** +- Change the input's `onChange` from `event => setMessageText(event.target.value)` to `event => handleInputChange(event.target.value)`. +- In `send()`, after each `setMessageText('')` (there are a few early returns — simplest: call `stopTyping()` once at the START of `send()` after the `if(!activeThread || !messageText.length) return;` guard, so any in-progress typing is cleared and a `false` is sent before the message). Add `stopTyping();` right after that guard line. + +- [ ] **Step 4: Stop typing when switching away from / closing a thread** +The component already has an effect on `[ isVisible, activeThread, ... ]`. To avoid a stale typing flag when the active thread changes, add a small effect: +```tsx + useEffect(() => + { + // when the active conversation changes (or closes), clear local typing state + return () => + { + if(typingTimeoutRef.current) + { + clearTimeout(typingTimeoutRef.current); + typingTimeoutRef.current = null; + } + isTypingRef.current = false; + }; + }, [ activeThread ]); +``` +(This clears the local flag/timer on thread switch; the peer's indicator auto-expires after 6s, so an explicit "false" on switch isn't required.) + +- [ ] **Step 5: Render the indicator** +Between the `chat-messages` div and the `messenger-input-row`, add: +```tsx + { activeThread.participant && (activeThread.participant.id > 0) && (typingUserIds.indexOf(activeThread.participant.id) >= 0) && +
+ { LocalizeText('messenger.typing', [ 'FRIEND_NAME' ], [ activeThread.participant.name ]) } +
} +``` + +- [ ] **Step 6: Localization key** +In `public/configuration/UITexts.example`, add (keep valid JSON): +```json +"messenger.typing": "%FRIEND_NAME% is typing...", +``` + +- [ ] **Step 7: CSS** +Append to `src/css/friends/FriendsView.css`: +```css +.messenger-typing-indicator { + padding: 2px 8px; + font-size: 11px; + font-style: italic; + opacity: 0.7; +} +``` + +- [ ] **Step 8: typecheck + tests** +Run: `cd Nitro-V3 && yarn typecheck && yarn test --run` +Expected: only the pre-existing floorplan typecheck error; no new test failures. + +- [ ] **Step 9: Commit** +```bash +cd Nitro-V3 +git add src/components/friends/views/messenger/FriendsMessengerView.tsx public/configuration/UITexts.example src/css/friends/FriendsView.css +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -m "feat(messenger): send typing status + show 'is typing' indicator" +``` + +--- + +## Task P4-5: Integration verification + +**Files:** none (automated + manual; fix-ups only). + +- [ ] **Step 1: Automated checks** +``` +cd Nitro_Render_V3 && yarn compile:fast && yarn test --run +cd Nitro-V3 && yarn typecheck && yarn test --run && yarn lint:hooks +cd Arcturus-Morningstar-Extended/Emulator && mvn -q clean package -DskipTests +``` +Expected: renderer 145 tests green; client typecheck only the pre-existing floorplan error, tests green except the 3 known floorplan failures, `lint:hooks` 0 errors; emulator BUILD SUCCESS. + +- [ ] **Step 2: Live two-session manual test** + +Run the new jar + `yarn start`. Accounts A and B (friends), both online, conversation open on both sides: +1. **Typing shows:** A starts typing in the thread with B → B sees "A is typing..." above the input. +2. **Stops on idle:** A stops typing → after ~4s (A's idle timer sends stop) B's indicator disappears; even if the stop packet is lost, B's indicator auto-expires after ~6s. +3. **Stops on send:** A types then sends → B's indicator disappears (stop sent at send time) and the message arrives. +4. **1:1 only:** typing in the Staff Chat / a group thread produces no errors and no indicator (server ignores `peerId <= 0` / non-friends). +5. **No regressions:** sending, receipts (Phase 3 ✓/✓✓), offline markers (Phase 2), and groups (Phase 1) all still work. + +- [ ] **Step 3: Commit any fix-ups** (only if needed) +```bash +cd Nitro-V3 +git -c user.name=simoleo89 -c user.email=simoleo89@users.noreply.github.com commit -am "fix(messenger): typing indicator integration fixes" +``` + +--- + +## Scope boundaries +- **Ephemeral only:** typing status is never stored; relayed only between online friends. +- **1:1 only:** group/staff/bots produce no typing (server ignores `peerId <= 0` and non-friends; client only renders for `participant.id > 0`). +- **Throttling:** the client sends `true` once per typing burst and `false` on idle(4s)/send/empty; the recipient auto-expires the indicator after 6s as a safety net for lost stop packets. +- This completes the messenger initiative (Phases 1–4). Do NOT push/merge automatically; the branch carries all four phases + the user's own parallel commits. diff --git a/docs/superpowers/plans/2026-06-06-furni-editor-furnidata-client.md b/docs/superpowers/plans/2026-06-06-furni-editor-furnidata-client.md new file mode 100644 index 0000000..44c57ec --- /dev/null +++ b/docs/superpowers/plans/2026-06-06-furni-editor-furnidata-client.md @@ -0,0 +1,240 @@ +# Furni editor — furnidata editing UI + typography refresh (Client/Renderer) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development. Steps use checkbox (`- [ ]`). + +**Goal:** Expose the server-side furnidata name/description editing (Plan A, already on Arcturus `main`) in the React furni editor: make Classname/Public Name read-only, add an editable **Furnidata** section (Display Name + Description) with diff-confirm + revert, search by furnidata name, and refresh the editor's typography/colors to the theme tokens. + +**Architecture:** Renderer (`Nitro_Render_V3`) gains 2 outgoing composers matching the server's incoming headers (update **10046**, revert **10048**); the success result reuses the existing `FurniEditorResult` (10044) and live propagation reuses the merged `FurnitureDataReload` (10047). Client (`Nitro-V3`) adds hook actions + UI. A small server tweak lets search match furnidata display names. + +**Tech Stack:** React 19 + Vite + TailwindCSS 4 (theme tokens in `tailwind.config.js`), TS, Vitest (client); TS/PixiJS (renderer); Java/Maven (server tweak). Server feature already built (Plan A). + +**Companion:** spec `Arcturus-Morningstar-Extended/docs/superpowers/specs/2026-06-06-furni-editor-furnidata-names-design.md`; server plan `…/plans/2026-06-06-furni-editor-furnidata-names-server.md`. Exploration of the client (exact file:line) is in this session's history — follow the cited patterns. + +**Server header contract (already on Arcturus main):** incoming `FurniEditorUpdateFurnidataEvent = 10046` reads `int itemId` + `String` (JSON `{name,description}`); incoming `FurniEditorRevertFurnidataEvent = 10048` reads `int itemId`; both respond with `FurniEditorResultComposer` (10044) and broadcast `FurnitureDataReloadComposer` (10047). + +--- + +## Task 1 (renderer): outgoing composers + headers + +**Files (in `E:\Users\simol\Desktop\DEV\Nitro_Render_V3\packages\communication\src\messages`):** +- Modify: `outgoing/OutgoingHeader.ts` (after `FURNI_EDITOR_DELETE = 10045`, ~line 505) +- Create: `outgoing/furnieditor/FurniEditorUpdateFurnidataComposer.ts` +- Create: `outgoing/furnieditor/FurniEditorRevertFurnidataComposer.ts` +- Modify: the furnieditor `index.ts` barrel (same folder as the existing furni-editor composers) + +- [ ] **Step 1: Add headers** in `OutgoingHeader.ts`: +```ts + public static readonly FURNI_EDITOR_UPDATE_FURNIDATA = 10046; + public static readonly FURNI_EDITOR_REVERT_FURNIDATA = 10048; +``` +(Match the real declaration style in that file — `public static readonly NAME: number = id;` or the enum/const pattern actually used. Verify 10046/10048 are unused in OutgoingHeader.) + +- [ ] **Step 2: Create `FurniEditorUpdateFurnidataComposer.ts`** (mirror the existing `FurniEditorUpdateComposer` in the same folder): +```ts +import { IMessageComposer } from '../../../../api'; +import { OutgoingHeader } from '../OutgoingHeader'; + +export class FurniEditorUpdateFurnidataComposer implements IMessageComposer> +{ + private _data: ConstructorParameters; + + constructor(itemId: number, jsonFields: string) + { + this._data = [ itemId, jsonFields ]; + } + + public getMessageArray() { return this._data; } + public dispose() { this._data = null; } + public getHeader() { return OutgoingHeader.FURNI_EDITOR_UPDATE_FURNIDATA; } +} +``` +**Before writing, open the real `FurniEditorUpdateComposer.ts`** and copy its EXACT structure/imports (the `IMessageComposer` import path + the `getMessageArray/getHeader/dispose` shape may differ from the above; match it verbatim, only changing the header constant and that the payload is `[itemId, jsonFields]`). + +- [ ] **Step 3: Create `FurniEditorRevertFurnidataComposer.ts`** — same pattern, constructor `(itemId: number)`, payload `[ itemId ]`, header `FURNI_EDITOR_REVERT_FURNIDATA`. + +- [ ] **Step 4: Export both** from the furnieditor composers `index.ts` barrel (add the two `export * from './FurniEditor...Composer';` lines next to the existing furni-editor composer exports). + +- [ ] **Step 5: Build** — `cd E:\Users\simol\Desktop\DEV\Nitro_Render_V3 && yarn compile:fast` (or the real compile script in package.json). Expected: clean, no TS errors. + +- [ ] **Step 6: Commit** (renderer repo): +``` +git -C "E:/Users/simol/Desktop/DEV/Nitro_Render_V3" add packages/communication/src/messages/outgoing/OutgoingHeader.ts packages/communication/src/messages/outgoing/furnieditor/ +git -C "E:/Users/simol/Desktop/DEV/Nitro_Render_V3" commit -m "feat(furnieditor): outgoing composers for furnidata update (10046) + revert (10048)" +``` +NO `Co-Authored-By` trailer. + +--- + +## Task 2 (client): hook actions + +**Files:** Modify `E:\Users\simol\Desktop\DEV\Nitro-V3\src\hooks\furni-editor\useFurniEditor.ts` + +- [ ] **Step 1: Parse furnidata name/desc into state.** Where the detail handler parses `furniDataJson` into `furniDataEntry` (lines ~140–152), also derive convenience strings. The `furniDataEntry` is `Record` with `name`/`description` keys. No new state needed — the EditView will read `furniDataEntry?.name`/`furniDataEntry?.description`. (No change required here if the EditView reads `furniDataEntry`; otherwise expose `furniDataName`/`furniDataDescription` strings. Choose the minimal path — prefer reading `furniDataEntry` directly in the view.) + +- [ ] **Step 2: Add actions.** Mirror `updateItem` (lines ~233–239). Add inside the hook body and to the return object (lines ~254–259): +```ts +const updateFurnidata = useCallback((id: number, name: string, description: string) => +{ + pendingActionRef.current = { type: 'update', id }; + setLoading(true); + SendMessageComposer(new FurniEditorUpdateFurnidataComposer(id, JSON.stringify({ name, description }))); +}, []); + +const revertFurnidata = useCallback((id: number) => +{ + pendingActionRef.current = { type: 'update', id }; + setLoading(true); + SendMessageComposer(new FurniEditorRevertFurnidataComposer(id)); +}, []); +``` +Use the REAL send-composer helper this hook already uses (the exploration shows `updateItem` sends `new FurniEditorUpdateComposer(...)` — copy its exact send mechanism, whether `SendMessageComposer(...)` or a local `send`). Import the two new composers from `@nitrots/nitro-renderer`. Reusing `pendingActionRef.type='update'` makes the existing `FurniEditorResultEvent` success handler (lines ~162–210) auto-reload the detail — which is what we want after a furnidata write. + +- [ ] **Step 3: Export** `updateFurnidata`, `revertFurnidata` in the hook's return object. + +- [ ] **Step 4: Typecheck** — `cd E:\Users\simol\Desktop\DEV\Nitro-V3 && yarn typecheck`. Expected: no new errors (pre-existing renderer-SDK TS2307 in a sandbox without the renderer are acceptable, but here the renderer IS present so it should be clean for these files). + +- [ ] **Step 5: Commit:** +``` +git -C "E:/Users/simol/Desktop/DEV/Nitro-V3" add src/hooks/furni-editor/useFurniEditor.ts +git -C "E:/Users/simol/Desktop/DEV/Nitro-V3" commit -m "feat(furni-editor): updateFurnidata/revertFurnidata hook actions" +``` +NO `Co-Authored-By`. + +--- + +## Task 3 (client): EditView — read-only classname/public_name + editable Furnidata section + props + +**Files:** Modify `src\components\furni-editor\views\FurniEditorEditView.tsx` and `src\components\furni-editor\FurniEditorView.tsx`. + +- [ ] **Step 1: Thread props.** In `FurniEditorEditViewProps` add `onUpdateFurnidata: (id: number, name: string, description: string) => void;` and `onRevertFurnidata: (id: number) => void;`. In `FurniEditorView.tsx` (where `` is rendered, ~lines 149–158), pass `onUpdateFurnidata={ updateFurnidata }` and `onRevertFurnidata={ revertFurnidata }` (destructure them from `useFurniEditor()`). + +- [ ] **Step 2: Make Classname + Public Name read-only.** In the Basic Info section (lines ~232–256): replace the **Item Name** `` with a read-only display, relabel to **"Classname"**, and render the value in monospace on a muted background (see Task 4 classes). Same for **Public Name** (label it "Public Name (DB fallback)"). Use a shared `readonlyClass` (Task 4). Keep `form.itemName`/`form.publicName` in state (so `updateItem` still sends unchanged values harmlessly) but do NOT let them be edited. Example: +```tsx +
+ +
{ form.itemName }
+
+
+ +
{ form.publicName }
+
+``` + +- [ ] **Step 3: New editable Furnidata section.** Replace the read-only `FurniData.json` section (lines ~323–334) with: +```tsx +
+ +
+ + setFurniName(e.target.value) } maxLength={ 256 } /> +
+
+ +