Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(web): add mobile reaction details dialog (#637)
Generb77956024779
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex db6501cb2..44c812d6d 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -57,6 +57,7 @@ export const SPEC_SECONDS = {"41-account-unread-projection.spec.ts": 55,"41-community-initial-load-module-skeletons.spec.ts": 30,"42-versioned-avatar-identity.spec.ts": 50,+ "44-mobile-reaction-details.spec.ts": 70,}function walk(directory) {diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex 28037d731..dfecb1ec5 100644--- a/scripts/ci/e2e-shards.test.ts+++ b/scripts/ci/e2e-shards.test.ts@@ -70,7 +70,7 @@ describe("planE2eShards", () => {expect(first).toHaveLength(E2E_SHARD_COUNT)expect([...assigned].sort()).toEqual(specs)expect(new Set(assigned).size).toBe(specs.length)- expect(totals.sort((left, right) => left - right)).toEqual([415, 416, 416, 418, 420])+ expect(totals.sort((left, right) => left - right)).toEqual([429, 430, 430, 432, 434])expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)})diff --git a/src/shared/src/db/queries/community/reaction.ts b/src/shared/src/db/queries/community/reaction.tsindex 11fb5463c..6c6fe17f3 100644--- a/src/shared/src/db/queries/community/reaction.ts+++ b/src/shared/src/db/queries/community/reaction.ts@@ -1,8 +1,146 @@-import { eq, and, inArray } from "drizzle-orm";-import { communityReaction } from "../../community-schema";+import { asc, eq, and, inArray, isNotNull, isNull, or } from "drizzle-orm";+import { alias } from "drizzle-orm/sqlite-core";+import {+ communityChannelMember,+ communityReaction,+ communityServerMember,+} from "../../community-schema";+import { user } from "../../schema";import type { Database } from "../../index";import { chunk, maxInParams } from "../_chunk";+export type ReactionDetailsScope =+ | { kind: "server"; serverId: string; channelId: string }+ | { kind: "dm"; channelId: string };++export type ReactionDetailsActor = {+ userId: string;+ profile: null | {+ id: string;+ name: string;+ discriminator: string;+ image: string | null;+ avatarVersion: number;+ };+};++function mapReactionActors(rows: Array<{+ userId: string;+ id: string | null;+ name: string | null;+ discriminator: string | null;+ image: string | null;+ avatarVersion: number | null;+}>): ReactionDetailsActor[] {+ return rows.map((row) => ({+ userId: row.userId,+ profile: row.id && row.name !== null && row.discriminator !== null+ && row.avatarVersion !== null+ ? {+ id: row.id,+ name: row.name,+ discriminator: row.discriminator,+ image: row.image,+ avatarVersion: row.avatarVersion,+ }+ : null,+ }));+}++export async function getReactionDetailsActors(+ db: Database,+ messageId: string,+ scope: ReactionDetailsScope+): Promise<ReactionDetailsActor[]> {+ const actor = alias(user, scope.kind === "server" ? "server_reaction_actor" : "dm_reaction_actor");+ const owner = alias(user, scope.kind === "server" ? "server_reaction_owner" : "dm_reaction_owner");++ if (scope.kind === "server") {+ const eligible = db+ .select({+ id: actor.id,+ name: actor.name,+ discriminator: actor.discriminator,+ image: actor.image,+ avatarVersion: actor.avatarVersion,+ })+ .from(actor)+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.userId, actor.id),+ eq(communityServerMember.serverId, scope.serverId)+ )+ )+ .leftJoin(+ owner,+ and(eq(owner.id, actor.ownerUserId), isNull(owner.deletedAt))+ )+ .where(and(+ isNull(actor.deletedAt),+ or(eq(actor.isBot, false), isNotNull(owner.id))+ ))+ .as("eligible_server_reaction_actor");++ const rows = await db+ .selectDistinct({+ userId: communityReaction.userId,+ id: eligible.id,+ name: eligible.name,+ discriminator: eligible.discriminator,+ image: eligible.image,+ avatarVersion: eligible.avatarVersion,+ })+ .from(communityReaction)+ .leftJoin(eligible, eq(eligible.id, communityReaction.userId))+ .where(eq(communityReaction.messageId, messageId))+ .orderBy(asc(communityReaction.userId));+ return mapReactionActors(rows);+ }++ const eligible = db+ .select({+ id: actor.id,+ name: actor.name,+ discriminator: actor.discriminator,+ image: actor.image,+ avatarVersion: actor.avatarVersion,+ })+ .from(actor)+ .innerJoin(+ communityChannelMember,+ and(+ eq(communityChannelMember.userId, actor.id),+ eq(communityChannelMember.channelId, scope.channelId),+ eq(communityChannelMember.relation, "access")+ )+ )+ .leftJoin(+ owner,+ and(eq(owner.id, actor.ownerUserId), isNull(owner.deletedAt))+ )+ .where(and(+ isNull(actor.deletedAt),+ or(eq(actor.isBot, false), isNotNull(owner.id))+ ))+ .as("eligible_dm_reaction_actor");++ const rows = await db+ .selectDistinct({+ userId: communityReaction.userId,+ id: eligible.id,+ name: eligible.name,+ discriminator: eligible.discriminator,+ image: eligible.image,+ avatarVersion: eligible.avatarVersion,+ })+ .from(communityReaction)+ .leftJoin(eligible, eq(eligible.id, communityReaction.userId))+ .where(eq(communityReaction.messageId, messageId))+ .orderBy(asc(communityReaction.userId));+ return mapReactionActors(rows);+}+export async function addReaction(db: Database,data: { messageId: string; userId: string; emoji: string }diff --git a/src/shared/test/queries/community-reaction-details.test.ts b/src/shared/test/queries/community-reaction-details.test.tsnew file mode 100644index 000000000..33b5a0220--- /dev/null+++ b/src/shared/test/queries/community-reaction-details.test.ts@@ -0,0 +1,159 @@+import Sqlite from "better-sqlite3"+import { drizzle } from "drizzle-orm/better-sqlite3"+import { afterEach, beforeEach, describe, expect, it } from "vitest"+import type { Database } from "../../src/db"+import { getReactionDetailsActors } from "../../src/db/queries/community/reaction"++describe("getReactionDetailsActors against real SQLite", () => {+ let sqlite: Sqlite.Database+ let db: Database++ beforeEach(() => {+ sqlite = new Sqlite(":memory:")+ sqlite.exec(`+ CREATE TABLE user (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ email TEXT NOT NULL UNIQUE,+ image TEXT,+ avatarVersion INTEGER NOT NULL DEFAULT 0,+ isBot INTEGER NOT NULL DEFAULT 0,+ ownerUserId TEXT,+ deletedAt TEXT,+ discriminator TEXT NOT NULL DEFAULT '0000'+ );+ CREATE TABLE community_server_member (+ id TEXT PRIMARY KEY,+ server_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ role TEXT DEFAULT 'member',+ rail_order INTEGER DEFAULT 0,+ joined_at TEXT NOT NULL+ );+ CREATE TABLE community_channel_member (+ id TEXT PRIMARY KEY,+ channel_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ relation TEXT NOT NULL,+ source TEXT NOT NULL DEFAULT 'added',+ added_by TEXT,+ added_at TEXT NOT NULL+ );+ CREATE TABLE community_reaction (+ id TEXT PRIMARY KEY,+ message_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ emoji TEXT NOT NULL,+ created_at TEXT NOT NULL+ );+ `)+ db = drizzle(sqlite) as unknown as Database+ })++ afterEach(() => sqlite.close())++ function user(+ id: string,+ options: { deleted?: boolean; bot?: boolean; owner?: string } = {},+ ) {+ sqlite.prepare(`+ INSERT INTO user+ (id, name, email, image, avatarVersion, isBot, ownerUserId, deletedAt, discriminator)+ VALUES (?, ?, ?, ?, 3, ?, ?, ?, ?)+ `).run(+ id,+ `Name ${id}`,+ `${id}@example.com`,+ `/avatar/${id}`,+ options.bot ? 1 : 0,+ options.owner ?? null,+ options.deleted ? "2026-01-01T00:00:00.000Z" : null,+ id.slice(-4).padStart(4, "0"),+ )+ }++ function member(serverId: string, userId: string) {+ sqlite.prepare(`+ INSERT INTO community_server_member (id, server_id, user_id, joined_at)+ VALUES (?, ?, ?, '2026-01-01T00:00:00.000Z')+ `).run(`member-${serverId}-${userId}`, serverId, userId)+ }++ function participant(channelId: string, userId: string, relation = "access") {+ sqlite.prepare(`+ INSERT INTO community_channel_member+ (id, channel_id, user_id, relation, added_at)+ VALUES (?, ?, ?, ?, '2026-01-01T00:00:00.000Z')+ `).run(`participant-${channelId}-${userId}-${relation}`, channelId, userId, relation)+ }++ function reaction(messageId: string, userId: string, emoji: string) {+ sqlite.prepare(`+ INSERT INTO community_reaction (id, message_id, user_id, emoji, created_at)+ VALUES (?, ?, ?, ?, '2026-01-01T00:00:00.000Z')+ `).run(`reaction-${messageId}-${userId}-${emoji}`, messageId, userId, emoji)+ }++ it("scopes server identities before the join and returns unique sorted nullable actors", async () => {+ user("active")+ user("departed")+ user("deleted", { deleted: true })+ user("owner-live")+ user("owner-gone", { deleted: true })+ user("bot-live", { bot: true, owner: "owner-live" })+ user("bot-orphan", { bot: true, owner: "owner-gone" })+ user("outsider")+ for (const id of ["active", "deleted", "bot-live", "bot-orphan"]) member("server-1", id)+ member("server-2", "outsider")+ for (const id of ["active", "departed", "deleted", "bot-live", "bot-orphan", "outsider"]) {+ reaction("message-1", id, "π")+ }+ reaction("message-1", "active", "π₯")+ reaction("message-2", "outsider", "π")++ const actors = await getReactionDetailsActors(db, "message-1", {+ kind: "server",+ serverId: "server-1",+ channelId: "channel-1",+ })+ expect(actors.map((actor) => actor.userId)).toEqual([+ "active",+ "bot-live",+ "bot-orphan",+ "deleted",+ "departed",+ "outsider",+ ])+ expect(actors.filter((actor) => actor.profile).map((actor) => actor.userId))+ .toEqual(["active", "bot-live"])+ expect(actors.find((actor) => actor.userId === "departed")?.profile).toBeNull()+ expect(actors.find((actor) => actor.userId === "deleted")?.profile).toBeNull()+ expect(actors.find((actor) => actor.userId === "bot-orphan")?.profile).toBeNull()+ expect(actors.find((actor) => actor.userId === "outsider")?.profile).toBeNull()+ })++ it("exposes only exact-DM access participants", async () => {+ for (const id of ["access", "notify", "other-dm", "deleted-dm"]) {+ user(id, { deleted: id === "deleted-dm" })+ reaction("message-dm", id, "π")+ }+ participant("dm-1", "access")+ participant("dm-1", "notify", "notify")+ participant("dm-2", "other-dm")+ participant("dm-1", "deleted-dm")++ const actors = await getReactionDetailsActors(db, "message-dm", {+ kind: "dm",+ channelId: "dm-1",+ })+ expect(actors.map((actor) => actor.userId)).toEqual([+ "access",+ "deleted-dm",+ "notify",+ "other-dm",+ ])+ expect(actors.find((actor) => actor.userId === "access")?.profile).not.toBeNull()+ expect(actors.filter((actor) => actor.userId !== "access").every((actor) => actor.profile === null))+ .toBe(true)+ })+})diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.tsindex 54ed77be2..f1f19cab0 100644--- a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts@@ -98,7 +98,7 @@ describe("reactions [emoji] surface guard", () => {beforeEach(() => {vi.clearAllMocks();mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1" });- mockGetChannelForMember.mockResolvedValue({ ok: true, value: { id: "c1" } });+ mockGetChannelForMember.mockResolvedValue({ ok: true, value: { id: "c1", serverId: "s1" } });mockGetDM.mockResolvedValue({ ok: true });mockAddReaction.mockResolvedValue({ messageId: "m1", userId: "u1", emoji: "π" });mockRemoveReaction.mockResolvedValue(undefined);diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.tsindex 50249631c..62964e88f 100644--- a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts@@ -8,49 +8,14 @@ import {MAX_EMOJI_BYTES,WS_EVENTS,} from "@alook/shared"-import type { Database } from "@alook/shared"import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"-import {- requireChannelMember,- requireDMAccess,-} from "@/lib/community/permissions"-import { requireReactableSurface } from "@/lib/community/channel-write-guard"import { resolveMessageRefForBot } from "@/lib/community/resolve-message-ref"+import { authorizeReaction } from "@/lib/community/reaction-access"// A bot addresses by ref-in-body (`{ channel, seq }`, the folded `reactAdd`// verb); the path `[id]` is then the `resolve` placeholder (a ref carries `/`// and can't sit in a path segment). A human/web caller puts the real messageId// in the path.-type AccessOk = { ok: true; channelId: string; isDm: boolean }-type AccessErr = { ok: false; status: 400 | 401 | 403 | 404; error: string }--/**- * Resolve the message and verify the caller can react.- * Reactions follow the same access rules as reading the message itself β- * for a DM channel, that also requires the other user not to have blocked the- * caller.- */-async function authorizeReaction(- db: Database,- messageId: string,- userId: string,-): Promise<AccessOk | AccessErr> {- const message = await queries.communityMessage.getMessage(db, messageId)- if (!message) return { ok: false, status: 404, error: "message not found" }-- const channelType = await queries.communityChannel.getChannelType(db, message.channelId)- const reactable = requireReactableSurface(channelType)- if (!reactable.ok) return { ok: false, status: reactable.status, error: reactable.error }- if (channelType === "dm") {- const check = await requireDMAccess(db, message.channelId, userId)- if (!check.ok) return check- return { ok: true, channelId: message.channelId, isDm: true }- }- const check = await requireChannelMember(db, message.channelId, userId)- if (!check.ok) return check- return { ok: true, channelId: message.channelId, isDm: false }-}-/*** Message-keyed reaction door (route/disc trunk β message-keyed faces dual-actor).* withCommunityActor: both human (session) and bot (crk_, the folded `reactAdd`diff --git a/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts b/src/web/src/app/api/community/messages/[id]/reactions/route.test.tsnew file mode 100644index 000000000..0b3eda889--- /dev/null+++ b/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts@@ -0,0 +1,122 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const mocks = vi.hoisted(() => ({+ authorize: vi.fn(),+ actors: vi.fn(),+}))++vi.mock("@/lib/db", () => ({ getDb: () => ({}) }))+vi.mock("@/lib/community/reaction-access", () => ({+ authorizeReaction: (...args: unknown[]) => mocks.authorize(...args),+}))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityReaction: {+ ...actual.queries.communityReaction,+ getReactionDetailsActors: (...args: unknown[]) => mocks.actors(...args),+ },+ },+ }+})+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: Function) => async (req: NextRequest, ctx: { params: { id: string } }) => {+ const bot = req.headers.get("authorization")?.startsWith("Bearer crk_")+ return handler(req, {+ env: { DB: {} },+ params: ctx.params,+ actor: bot+ ? { kind: "bot", userId: "bot_1", ownerUserId: "u1", machineId: "machine_1" }+ : { kind: "human", userId: "viewer_1", email: "[email protected]" },+ })+ },+}))++import { GET } from "./route"++const context = { params: { id: "message_1" } } as never+const request = (bot = false) => new NextRequest(+ "http://localhost/api/community/messages/message_1/reactions",+ bot ? { headers: { authorization: "Bearer crk_test" } } : undefined,+)++describe("GET reaction details", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.authorize.mockResolvedValue({+ ok: true,+ channelId: "channel_1",+ isDm: false,+ scope: { kind: "server", serverId: "server_1", channelId: "channel_1" },+ })+ mocks.actors.mockResolvedValue([])+ })++ it("authorizes before one message-scoped actor query and preserves nullable identities", async () => {+ mocks.actors.mockResolvedValue([+ {+ userId: "user_1",+ profile: {+ id: "user_1",+ name: "Alice",+ discriminator: "0042",+ image: "/api/community/users/user_1/avatar",+ avatarVersion: 7,+ },+ },+ { userId: "departed_1", profile: null },+ ])++ const response = await GET(request(), context)+ expect(response.status).toBe(200)+ expect(mocks.authorize).toHaveBeenCalledWith({}, "message_1", "viewer_1")+ expect(mocks.actors).toHaveBeenCalledOnce()+ expect(mocks.actors).toHaveBeenCalledWith(+ {},+ "message_1",+ { kind: "server", serverId: "server_1", channelId: "channel_1" },+ )+ await expect(response.json()).resolves.toMatchObject({+ messageId: "message_1",+ actors: [+ { userId: "user_1", profile: { avatar: "/api/community/users/user_1/avatar?v=7" } },+ { userId: "departed_1", profile: null },+ ],+ })+ })++ it("does not run actor SQL when authorization fails", async () => {+ mocks.authorize.mockResolvedValue({ ok: false, error: "message not found", status: 404 })+ const response = await GET(request(), context)+ expect(response.status).toBe(404)+ expect(mocks.actors).not.toHaveBeenCalled()+ })++ it("rejects bot credentials before authorization or actor SQL", async () => {+ const response = await GET(request(true), context)+ expect(response.status).toBe(401)+ expect(mocks.authorize).not.toHaveBeenCalled()+ expect(mocks.actors).not.toHaveBeenCalled()+ })++ it("derives a stable avatar fallback inside the authorized profile", async () => {+ mocks.actors.mockResolvedValue([{+ userId: "user_1",+ profile: {+ id: "user_1",+ name: "Alice",+ discriminator: "0042",+ image: null,+ avatarVersion: 0,+ },+ }])+ const response = await GET(request(), context)+ await expect(response.json()).resolves.toMatchObject({+ actors: [{ userId: "user_1", profile: { avatar: "A" } }],+ })+ })+})diff --git a/src/web/src/app/api/community/messages/[id]/reactions/route.ts b/src/web/src/app/api/community/messages/[id]/reactions/route.tsnew file mode 100644index 000000000..fa6e6346f--- /dev/null+++ b/src/web/src/app/api/community/messages/[id]/reactions/route.ts@@ -0,0 +1,43 @@+import { withCommunityActor } from "@/lib/middleware/community-actor"+import { writeError, writeJSON } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries } from "@alook/shared"+import { authorizeReaction } from "@/lib/community/reaction-access"+import { canonicalUserImage } from "@/lib/community/storage"+import { avatarInitial } from "@/lib/community/avatar"++export const GET = withCommunityActor(async (_req, ctx) => {+ if (ctx.actor.kind !== "human") return writeError("human session required", 401)+ const messageId = ctx.params?.id+ if (!messageId) return writeError("missing message id", 400)++ const db = getDb(ctx.env.DB)+ const access = await authorizeReaction(db, messageId, ctx.actor.userId)+ if (!access.ok) return writeError(access.error, access.status)++ const actors = await queries.communityReaction.getReactionDetailsActors(+ db,+ messageId,+ access.scope,+ )+ return writeJSON({+ messageId,+ scope: access.scope,+ actors: actors.map((actor) => ({+ userId: actor.userId,+ profile: actor.profile+ ? {+ id: actor.profile.id,+ name: actor.profile.name,+ discriminator: actor.profile.discriminator,+ avatar: canonicalUserImage(+ actor.profile.id,+ actor.profile.image,+ actor.profile.avatarVersion,+ ) ?? avatarInitial(actor.profile.name),+ avatarVersion: actor.profile.avatarVersion,+ }+ : null,+ })),+ })+})diff --git a/src/web/src/components/community/channels/thread-channel-surface.test.ts b/src/web/src/components/community/channels/thread-channel-surface.test.tsindex 16f053425..beb7a4ae4 100644--- a/src/web/src/components/community/channels/thread-channel-surface.test.ts+++ b/src/web/src/components/community/channels/thread-channel-surface.test.ts@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({apiFetch: vi.fn(),toastApiError: vi.fn(),editMessage: vi.fn(),+ toggleReaction: vi.fn(),acceptMessage: vi.fn(() => true),handleTyping: vi.fn(),setReplyTo: vi.fn(),@@ -39,6 +40,7 @@ vi.mock("@/hooks/community/use-channel-message-feed", () => ({}))vi.mock("@/hooks/community/mutations", () => ({useEditMessage: () => ({ mutateAsync: mocks.editMessage }),+ useToggleReactionApi: () => mocks.toggleReaction,}))vi.mock("@/components/community/channels/channel-header", () => ({ChannelHeader: vi.fn(() => null),@@ -268,9 +270,19 @@ describe("ThreadChannelSurface ownership", () => {parentMessageId: "opener_1",viewerUserId: "viewer_1",onOpenProfile: props.onOpenProfile,+ onToggleReaction: expect.any(Function),+ resolveUserName: props.resolveUserName,resolveAuthorMentionText: expect.any(Function),onInsertMentionText: expect.any(Function),}))+ act(() => opener.props.onToggleReaction?.("π₯"))+ expect(mocks.toggleReaction).toHaveBeenCalledWith({+ serverId: "server_1",+ channelId: "parent_1",+ messageId: "opener_1",+ emoji: "π₯",+ userId: "viewer_1",+ })act(() => opener.props.onJump?.())expect(mocks.router.push).toHaveBeenCalledWith("/c/channels/server_1/parent_1?msg=opener_1")act(() => opener.props.onPreviewImage?.("https://example.test/image.png"))diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex 3841e89c6..bce48a970 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation"import { toastApiError, apiFetch } from "@/lib/api/client"import { useBreakpoint } from "@/hooks/use-mobile"import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"-import { useEditMessage } from "@/hooks/community/mutations"+import { useEditMessage, useToggleReactionApi } from "@/hooks/community/mutations"import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channels/channel-header"import { ChannelShell } from "@/components/community/channels/channel-shell"import { CommunityPanel } from "@/components/community/shell/community-panel"@@ -97,6 +97,17 @@ export function ThreadChannelSurface({viewerDiscriminator: viewer.discriminator,})const { mutateAsync: editMessageAsync } = useEditMessage()+ const toggleReactionApi = useToggleReactionApi()+ const toggleOpenerReaction = useCallback((emoji: string) => {+ if (!parentChannelId || !parentMessageId) return+ toggleReactionApi({+ serverId,+ channelId: parentChannelId,+ messageId: parentMessageId,+ emoji,+ userId: viewer.id,+ })+ }, [parentChannelId, parentMessageId, serverId, toggleReactionApi, viewer.id])useClaimThreadOpenerReadHandoff(threadOpenerHandoff)const feed = useChannelMessageFeed({channelId,@@ -164,6 +175,8 @@ export function ThreadChannelSurface({parentMessageId={parentMessageId}viewerUserId={viewer.id}onOpenProfile={onOpenProfile}+ onToggleReaction={parentChannelId ? toggleOpenerReaction : undefined}+ resolveUserName={resolveUserName}resolveAuthorMentionText={mentionInsertion.resolveAuthorMentionText}onInsertMentionText={mentionInsertion.insertMentionText}onPreviewImage={(image) => uiHandlers.previewImage?.(image)}diff --git a/src/web/src/components/community/messages/message-reactions.test.ts b/src/web/src/components/community/messages/message-reactions.test.tsnew file mode 100644index 000000000..d88ec6bfe--- /dev/null+++ b/src/web/src/components/community/messages/message-reactions.test.ts@@ -0,0 +1,175 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"++vi.mock("@/hooks/community/use-reaction-details", () => ({+ useReactionDetails: () => ({+ data: {+ messageId: "message_1",+ scope: { kind: "server", serverId: "server_1", channelId: "channel_1" },+ actors: [+ { userId: "user_1", profile: { id: "user_1", name: "Alice", discriminator: "0001", avatar: "A", avatarVersion: 0 } },+ { userId: "user_2", profile: { id: "user_2", name: "Bob", discriminator: "0002", avatar: "B", avatarVersion: 0 } },+ ],+ },+ isLoading: false,+ }),+}))+vi.mock("@/stores/community/ws", () => ({+ useCommunityProfile: () => undefined,+}))+vi.mock("@/components/ui/dialog", () => ({+ Dialog: ({ open, children, ...props }: { open: boolean; children: React.ReactNode }) =>+ React.createElement("mock-dialog", { "data-open": open, ...props }, open ? children : null),+ DialogContent: ({ children, ...props }: React.ComponentProps<"div">) =>+ React.createElement("mock-dialog-content", props, children),+ DialogHeader: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),+ DialogTitle: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),+ DialogDescription: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),+}))+vi.mock("@/components/ui/tabs", () => ({+ Tabs: ({ children, value }: { children: React.ReactNode; value: string }) =>+ React.createElement("mock-tabs", { value }, children),+ TabsList: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),+ TabsTrigger: ({ children, ...props }: React.ComponentProps<"button">) =>+ React.createElement("button", props, children),+}))+vi.mock("@/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: React.ReactNode }) => React.createElement(React.Fragment, null, children),+ TooltipTrigger: ({ render }: { render: React.ReactNode }) => render,+ TooltipContent: ({ children }: { children: React.ReactNode }) => React.createElement("span", null, children),+}))++import { MessageReactions, reconcileReactionSelection } from "./message-reactions"+import { tid } from "@/lib/community/testids"++const buttonNode = { focus: vi.fn(), isConnected: true }+const reactionGroupNode = { focus: vi.fn() }+const reactions = [+ { emoji: "π", count: 1, me: false, userIds: ["user_1"] },+ { emoji: "π₯", count: 1, me: true, userIds: ["user_2"] },+]++function renderReactions(onToggleReaction = vi.fn()) {+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(MessageReactions, {+ messageId: "message_1",+ reactions,+ hoverCapable: false,+ tooltipActive: false,+ onToggleReaction,+ }),+ {+ createNodeMock: (node) => node.type === "button"+ ? buttonNode+ : node.props?.["data-testid"] === tid.reactionGroup("message_1")+ ? reactionGroupNode+ : {},+ },+ )+ })+ return { renderer: renderer!, onToggleReaction }+}++describe("MessageReactions", () => {+ afterEach(() => {+ vi.useRealTimers()+ vi.clearAllMocks()+ buttonNode.isConnected = true+ })++ it("keeps a normal chip click as the exact toggle action", () => {+ const { renderer, onToggleReaction } = renderReactions()+ const chip = renderer.root.findByProps({ "data-testid": tid.reactionChip("message_1", "π") })+ act(() => chip.props.onClick({ preventDefault: vi.fn(), stopPropagation: vi.fn() }))+ expect(onToggleReaction).toHaveBeenCalledWith("π")+ })++ it("opens details after a stationary hold without firing the trailing click", () => {+ vi.useFakeTimers()+ const { renderer, onToggleReaction } = renderReactions()+ const chip = renderer.root.findByProps({ "data-testid": tid.reactionChip("message_1", "π₯") })+ act(() => chip.props.onPointerDown({ pointerType: "touch", clientX: 10, clientY: 10, stopPropagation: vi.fn() }))+ act(() => vi.advanceTimersByTime(449))+ expect(renderer.root.findByType("mock-dialog").props["data-open"]).toBe(false)+ act(() => vi.advanceTimersByTime(1))+ expect(renderer.root.findByType("mock-dialog").props["data-open"]).toBe(true)+ const event = { preventDefault: vi.fn(), stopPropagation: vi.fn() }+ act(() => chip.props.onClick(event))+ expect(onToggleReaction).not.toHaveBeenCalled()+ expect(event.preventDefault).toHaveBeenCalledOnce()+ })++ it("cancels both the hold and trailing toggle when the finger scrolls", () => {+ vi.useFakeTimers()+ const { renderer, onToggleReaction } = renderReactions()+ const chip = renderer.root.findByProps({ "data-testid": tid.reactionChip("message_1", "π") })+ act(() => chip.props.onPointerDown({ pointerType: "touch", clientX: 10, clientY: 10, stopPropagation: vi.fn() }))+ act(() => chip.props.onPointerMove({ pointerType: "touch", clientX: 10, clientY: 25, stopPropagation: vi.fn() }))+ act(() => vi.advanceTimersByTime(500))+ expect(renderer.root.findByType("mock-dialog").props["data-open"]).toBe(false)+ act(() => chip.props.onClick({ preventDefault: vi.fn(), stopPropagation: vi.fn() }))+ expect(onToggleReaction).not.toHaveBeenCalled()+ })++ it("requests a 44px mobile close target for the details dialog", () => {+ vi.useFakeTimers()+ const { renderer } = renderReactions()+ const chip = renderer.root.findByProps({ "data-testid": tid.reactionChip("message_1", "π") })+ act(() => chip.props.onPointerDown({ pointerType: "touch", clientX: 10, clientY: 10, stopPropagation: vi.fn() }))+ act(() => vi.advanceTimersByTime(450))+ expect(renderer.root.findByType("mock-dialog-content").props.className)+ .toContain("**:data-[slot=dialog-close]:size-11")+ })++ it("restores focus after the dialog close focus handoff", () => {+ vi.useFakeTimers()+ const { renderer } = renderReactions()+ const chip = renderer.root.findByProps({ "data-testid": tid.reactionChip("message_1", "π") })+ act(() => chip.props.onPointerDown({ pointerType: "touch", clientX: 10, clientY: 10, stopPropagation: vi.fn() }))+ act(() => vi.advanceTimersByTime(450))+ const dialog = renderer.root.findByType("mock-dialog")+ act(() => dialog.props.onOpenChange(false))+ expect(buttonNode.focus).not.toHaveBeenCalled()+ act(() => vi.advanceTimersByTime(0))+ expect(buttonNode.focus).toHaveBeenCalledOnce()+ })++ it("restores focus to the reaction group when the initiating chip disappeared", () => {+ vi.useFakeTimers()+ const { renderer, onToggleReaction } = renderReactions()+ const chip = renderer.root.findByProps({ "data-testid": tid.reactionChip("message_1", "π") })+ act(() => chip.props.onPointerDown({ pointerType: "touch", clientX: 10, clientY: 10, stopPropagation: vi.fn() }))+ act(() => vi.advanceTimersByTime(450))+ act(() => renderer.update(React.createElement(MessageReactions, {+ messageId: "message_1",+ reactions: [],+ hoverCapable: false,+ tooltipActive: false,+ onToggleReaction,+ })))+ buttonNode.isConnected = false+ const dialog = renderer.root.findByType("mock-dialog")+ act(() => dialog.props.onOpenChange(false))+ act(() => vi.advanceTimersByTime(0))+ expect(buttonNode.focus).not.toHaveBeenCalled()+ expect(reactionGroupNode.focus).toHaveBeenCalledOnce()+ })+})++describe("reconcileReactionSelection", () => {+ it("keeps the selected emoji while it remains live", () => {+ expect(reconcileReactionSelection(["π", "π₯"], ["π", "π₯", "π"], "π₯")).toBe("π₯")+ })++ it("selects the stable neighboring tab when the selected emoji disappears", () => {+ expect(reconcileReactionSelection(["π", "π₯", "π"], ["π", "π"], "π₯")).toBe("π")+ expect(reconcileReactionSelection(["π", "π₯"], ["π"], "π₯")).toBe("π")+ })++ it("closes selection when the final reaction disappears", () => {+ expect(reconcileReactionSelection(["π"], [], "π")).toBeNull()+ })+})diff --git a/src/web/src/components/community/messages/message-reactions.tsx b/src/web/src/components/community/messages/message-reactions.tsxnew file mode 100644index 000000000..d7db5cfba--- /dev/null+++ b/src/web/src/components/community/messages/message-reactions.tsx@@ -0,0 +1,351 @@+"use client"++import { useEffect, useMemo, useRef, useState } from "react"+import type React from "react"+import { Avatar } from "../avatar"+import { NumberTicker } from "@/components/ui/number-ticker"+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog"+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"+import { avatarInitial } from "@/lib/community/avatar"+import { displayName } from "@/lib/community/display-name"+import type { Reaction } from "@/lib/community/models/message"+import { tid } from "@/lib/community/testids"+import {+ type ReactionDetailsProfile,+ useReactionDetails,+} from "@/hooks/community/use-reaction-details"+import { useCommunityProfile } from "@/stores/community/ws"++const HOLD_MS = 450+const MOVE_TOLERANCE_PX = 10++export function reconcileReactionSelection(+ previousEmojis: readonly string[],+ nextEmojis: readonly string[],+ selectedEmoji: string | null,+): string | null {+ if (nextEmojis.length === 0) return null+ if (selectedEmoji && nextEmojis.includes(selectedEmoji)) return selectedEmoji+ const previousIndex = selectedEmoji ? previousEmojis.indexOf(selectedEmoji) : 0+ const neighborIndex = previousIndex < 0 ? 0 : Math.min(previousIndex, nextEmojis.length - 1)+ return nextEmojis[neighborIndex] ?? null+}++function ReactionMemberRow({+ userId,+ authorizedProfile,+}: {+ userId: string+ authorizedProfile: ReactionDetailsProfile | null | undefined+}) {+ const liveProfile = useCommunityProfile(authorizedProfile ? userId : null)+ const name = authorizedProfile ? (liveProfile?.name ?? authorizedProfile.name) : "Unknown member"+ const avatar = authorizedProfile+ ? (liveProfile?.avatar ?? authorizedProfile.avatar ?? avatarInitial(name))+ : avatarInitial(name)+ return (+ <li data-testid={tid.reactionMember(userId)} className="flex min-h-11 items-center gap-3 rounded-lg px-2 py-2">+ <Avatar label={name} seed={authorizedProfile ? userId : undefined} src={authorizedProfile ? avatar : undefined} size={32} ringColor="var(--popover)" />+ <div className="min-w-0">+ <div className="truncate text-sm font-medium">{name}</div>+ {authorizedProfile && (+ <div className="truncate text-xs text-muted-foreground">+ @{liveProfile?.name ?? authorizedProfile.name}#{liveProfile?.discriminator ?? authorizedProfile.discriminator}+ </div>+ )}+ </div>+ </li>+ )+}++function ReactionChip({+ messageId,+ reaction,+ hoverCapable,+ tooltipActive,+ tooltipNames,+ onToggle,+ onOpen,+}: {+ messageId: string+ reaction: Reaction+ hoverCapable: boolean+ tooltipActive: boolean+ tooltipNames?: string+ onToggle?: (emoji: string) => void+ onOpen: (emoji: string, button: HTMLButtonElement) => void+}) {+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const startRef = useRef<{ x: number; y: number } | null>(null)+ const buttonRef = useRef<HTMLButtonElement | null>(null)+ const suppressClickRef = useRef(false)+ const coarsePointer = (pointerType: string) =>+ !hoverCapable && (pointerType === "touch" || pointerType === "pen")++ const clearHold = () => {+ if (timerRef.current) clearTimeout(timerRef.current)+ timerRef.current = null+ }+ useEffect(() => clearHold, [])++ const chip = (+ <button+ ref={buttonRef}+ type="button"+ data-testid={tid.reactionChip(messageId, reaction.emoji)}+ aria-label={`${reaction.emoji}, ${reaction.count} ${reaction.count === 1 ? "reaction" : "reactions"}, ${reaction.me ? "you reacted" : "you have not reacted"}. Press to toggle${hoverCapable ? "" : "; long press for details"}`}+ aria-pressed={reaction.me}+ aria-haspopup={hoverCapable ? undefined : "dialog"}+ className={[+ "flex h-6 touch-pan-y select-none items-center gap-1 rounded-md px-2 text-sm focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none [-webkit-touch-callout:none]",+ reaction.me ? "border border-primary/50 bg-accent" : "bg-secondary",+ ].join(" ")}+ onPointerDown={(event) => {+ if (!coarsePointer(event.pointerType)) return+ event.stopPropagation()+ clearHold()+ suppressClickRef.current = false+ startRef.current = { x: event.clientX, y: event.clientY }+ timerRef.current = setTimeout(() => {+ timerRef.current = null+ suppressClickRef.current = true+ const button = buttonRef.current+ if (button) onOpen(reaction.emoji, button)+ }, HOLD_MS)+ }}+ onPointerMove={(event) => {+ const start = startRef.current+ if (!start || !coarsePointer(event.pointerType)) return+ event.stopPropagation()+ if (Math.hypot(event.clientX - start.x, event.clientY - start.y) > MOVE_TOLERANCE_PX) {+ clearHold()+ startRef.current = null+ suppressClickRef.current = true+ }+ }}+ onPointerUp={() => {+ clearHold()+ startRef.current = null+ }}+ onPointerLeave={(event) => {+ if (!coarsePointer(event.pointerType) || !startRef.current) return+ clearHold()+ startRef.current = null+ suppressClickRef.current = true+ }}+ onPointerCancel={() => {+ clearHold()+ startRef.current = null+ suppressClickRef.current = true+ }}+ onContextMenu={(event) => {+ if (!hoverCapable) {+ event.preventDefault()+ event.stopPropagation()+ }+ }}+ onKeyDown={(event) => {+ if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {+ event.preventDefault()+ onOpen(reaction.emoji, event.currentTarget)+ }+ }}+ onClick={(event) => {+ if (suppressClickRef.current) {+ suppressClickRef.current = false+ event.preventDefault()+ event.stopPropagation()+ return+ }+ onToggle?.(reaction.emoji)+ }}+ >+ <span aria-hidden="true">{reaction.emoji}</span>+ <NumberTicker value={reaction.count} className="text-xs text-muted-foreground" />+ </button>+ )++ if (!hoverCapable || !tooltipActive || !tooltipNames) return chip+ return (+ <Tooltip>+ <TooltipTrigger render={chip} />+ <TooltipContent>Reacted by {tooltipNames}</TooltipContent>+ </Tooltip>+ )+}++function ReactionDetailsDialog({+ messageId,+ reactions,+ selectedEmoji,+ onSelectedEmojiChange,+}: {+ messageId: string+ reactions: readonly Reaction[]+ selectedEmoji: string | null+ onSelectedEmojiChange: (emoji: string) => void+}) {+ const userIds = useMemo(+ () => reactions.flatMap((reaction) => reaction.userIds ?? []),+ [reactions],+ )+ const details = useReactionDetails({ messageId, open: true, userIds })+ const selectedReaction = reactions.find((reaction) => reaction.emoji === selectedEmoji)+ const actors = new Map(details.data?.actors.map((actor) => [actor.userId, actor]))++ return (+ <DialogContent+ data-testid={tid.reactionDialog(messageId)}+ className="max-h-[calc(100dvh-2rem-env(safe-area-inset-top)-env(safe-area-inset-bottom))] gap-3 overflow-hidden sm:max-w-sm **:data-[slot=dialog-close]:size-11 sm:**:data-[slot=dialog-close]:size-7"+ >+ <DialogHeader>+ <DialogTitle>Reactions</DialogTitle>+ <DialogDescription>People who reacted to this message</DialogDescription>+ </DialogHeader>++ {reactions.length > 0 && selectedEmoji && (+ <Tabs value={selectedEmoji} onValueChange={onSelectedEmojiChange}>+ <TabsList variant="default" className="h-11! min-h-11 thin-scrollbar">+ {reactions.map((reaction) => (+ <TabsTrigger+ key={reaction.emoji}+ value={reaction.emoji}+ id={tid.reactionTab(reaction.emoji)}+ data-testid={tid.reactionTab(reaction.emoji)}+ aria-label={`${reaction.emoji}, ${reaction.count}`}+ aria-controls={`${tid.reactionDialog(messageId)}-panel`}+ className="h-11! min-h-11 min-w-11"+ >+ <span aria-hidden="true">{reaction.emoji}</span>+ <span>{reaction.count}</span>+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ )}++ <div+ id={`${tid.reactionDialog(messageId)}-panel`}+ role="tabpanel"+ aria-labelledby={selectedEmoji ? tid.reactionTab(selectedEmoji) : undefined}+ className="min-h-28 overflow-y-auto thin-scrollbar"+ aria-live="polite"+ >+ {details.isLoading ? (+ <div className="space-y-2 py-2" aria-label="Loading reactions">+ {[0, 1, 2].map((index) => <div key={index} className="h-11 animate-pulse rounded-lg bg-muted" />)}+ </div>+ ) : selectedReaction?.userIds.length ? (+ <ul>+ {selectedReaction.userIds.map((userId) => (+ <ReactionMemberRow+ key={userId}+ userId={userId}+ authorizedProfile={actors.get(userId)?.profile}+ />+ ))}+ </ul>+ ) : (+ <p data-testid={tid.reactionEmpty(messageId)} className="py-8 text-center text-sm text-muted-foreground">+ No reactions yet+ </p>+ )}+ </div>+ </DialogContent>+ )+}++export function MessageReactions({+ messageId,+ reactions,+ hoverCapable,+ tooltipActive,+ onToggleReaction,+ resolveUserName,+ trailingControl,+}: {+ messageId: string+ reactions: readonly Reaction[]+ hoverCapable: boolean+ tooltipActive: boolean+ onToggleReaction?: (emoji: string) => void+ resolveUserName?: (userId: string) => string+ trailingControl?: React.ReactNode+}) {+ const emojis = useMemo(() => reactions.map((reaction) => reaction.emoji), [reactions])+ const previousEmojisRef = useRef(emojis)+ const initiatingChipRef = useRef<HTMLButtonElement | null>(null)+ const reactionGroupRef = useRef<HTMLDivElement | null>(null)+ const [open, setOpen] = useState(false)+ const [selectedEmoji, setSelectedEmoji] = useState<string | null>(null)+ const restoreInitiatingFocus = () => {+ const initiatingChip = initiatingChipRef.current+ if (initiatingChip?.isConnected !== false) initiatingChip?.focus()+ else reactionGroupRef.current?.focus()+ }++ useEffect(() => {+ const previous = previousEmojisRef.current+ setSelectedEmoji((selected) => reconcileReactionSelection(previous, emojis, selected))+ previousEmojisRef.current = emojis+ }, [emojis])++ return (+ <>+ <div+ ref={reactionGroupRef}+ data-testid={tid.reactionGroup(messageId)}+ className="flex flex-wrap gap-1 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ tabIndex={-1}+ aria-label="Message reactions"+ >+ {reactions.map((reaction) => {+ const tooltipNames = reaction.userIds?.length+ ? reaction.userIds.map((id) => resolveUserName?.(id) ?? displayName(null)).join(", ")+ : undefined+ return (+ <ReactionChip+ key={reaction.emoji}+ messageId={messageId}+ reaction={reaction}+ hoverCapable={hoverCapable}+ tooltipActive={tooltipActive}+ tooltipNames={tooltipNames}+ onToggle={onToggleReaction}+ onOpen={(emoji, button) => {+ initiatingChipRef.current = button+ setSelectedEmoji(emoji)+ setOpen(true)+ }}+ />+ )+ })}+ {trailingControl}+ </div>++ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ setOpen(nextOpen)+ if (!nextOpen) setTimeout(restoreInitiatingFocus, 0)+ }}+ >+ {open && (+ <ReactionDetailsDialog+ messageId={messageId}+ reactions={reactions}+ selectedEmoji={selectedEmoji}+ onSelectedEmojiChange={setSelectedEmoji}+ />+ )}+ </Dialog>+ </>+ )+}diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsxindex 7a5ebf602..313a0f3cd 100644--- a/src/web/src/components/community/messages/message.tsx+++ b/src/web/src/components/community/messages/message.tsx@@ -14,12 +14,10 @@ import { MessageBody } from "./message-body"import { BotApprovalCard } from "../social/bot-approval-card"import { EmojiPickerPopover } from "./emoji-picker"import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"-import { NumberTicker } from "@/components/ui/number-ticker"import { MessageContextItems, MessageDropdownItems, hasMessageMenu } from "./message-menu"import { formatMessageTime } from "@/lib/community/format-time"import { tid } from "@/lib/community/testids"import { avatarInitial } from "@/lib/community/avatar"-import { displayName } from "@/lib/community/display-name"import { stripInlineMarkup } from "@alook/shared"import type { FileAttachment, ImagePreview, RenderMsg } from "@/lib/community/models/message"import type { OpenProfile } from "@/components/community/social/profile-types"@@ -35,6 +33,7 @@ import {} from "./mobile-message-gesture"import { useMobileAvatarMention } from "./use-mobile-avatar-mention"import { useCommunityProfile } from "@/stores/community/ws"+import { MessageReactions } from "./message-reactions"// Whether the "Share as Image" action is offered for a message. Share is// computed inside `Message` from the message alone (no handler is threaded in),@@ -613,35 +612,16 @@ function MessageImpl({)}{m.reactions && (- <div className="mt-2 flex flex-wrap gap-1">- {m.reactions.map((r, i) => {- const names = r.userIds?.length- ? r.userIds.map((id) => resolveUserName?.(id) ?? displayName(null)).join(", ")- : undefined- const chip = (- <button- onClick={() => onToggleReaction?.(r.emoji)}- className={[- "flex h-6 items-center gap-1 rounded-md px-2 text-sm",- r.me ? "border border-primary/50 bg-accent" : "bg-secondary",- ].join(" ")}- >- <span>{r.emoji}</span>- <NumberTicker value={r.count} className="text-xs text-muted-foreground" />- </button>- )- // Until the row is activated, render the bare chip (still fully- // clickable) without its Base UI Tooltip root β the name tooltip- // only matters on hover, and hover activates the row.- if (!names || !activated) return <div key={i}>{chip}</div>- return (- <Tooltip key={i}>- <TooltipTrigger render={chip} />- <TooltipContent>Reacted by {names}</TooltipContent>- </Tooltip>- )- })}- {reactionAddControl}+ <div className="mt-2">+ <MessageReactions+ messageId={m.id}+ reactions={m.reactions}+ hoverCapable={hoverCapable}+ tooltipActive={activated}+ onToggleReaction={onToggleReaction}+ resolveUserName={resolveUserName}+ trailingControl={reactionAddControl}+ /></div>)}diff --git a/src/web/src/components/community/messages/thread-opener.test.ts b/src/web/src/components/community/messages/thread-opener.test.tsindex d2e257535..614830539 100644--- a/src/web/src/components/community/messages/thread-opener.test.ts+++ b/src/web/src/components/community/messages/thread-opener.test.ts@@ -11,6 +11,14 @@ vi.mock("@/stores/community/ws", () => ({? { id: userId, name: "Alice", avatar: "A" }: undefined,}))+vi.mock("@/hooks/use-hover-capable", () => ({ useHoverCapable: () => true }))+vi.mock("./message-reactions", () => ({+ MessageReactions: ({ onToggleReaction }: { onToggleReaction?: (emoji: string) => void }) =>+ React.createElement("button", {+ "data-testid": "mock-opener-reaction",+ onClick: () => onToggleReaction?.("π₯"),+ }, "π₯"),+}))import { ThreadOpener } from "./thread-opener"@@ -63,6 +71,36 @@ describe("ThreadOpener image attachment layout", () => {expect(textContent(body)).toContain("visible")})+ it("threads reaction toggles through the live opener surface", () => {+ const onToggleReaction = vi.fn()+ useMessageMock.mockReturnValue({+ isLoading: false,+ isError: false,+ message: {+ id: "opener_1",+ type: "chat",+ authorId: "user_1",+ authorName: "Alice",+ content: "React here",+ createdAt: "2026-08-08T00:00:00.000Z",+ reactions: [{ emoji: "π₯", count: 1, me: false, userIds: ["user_1"] }],+ },+ })+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(ThreadOpener, {+ parentMessageId: "opener_1",+ viewerUserId: "viewer_1",+ onToggleReaction,+ }),+ { createNodeMock: () => genericMock },+ )+ })+ act(() => renderer!.root.findByProps({ "data-testid": "mock-opener-reaction" }).props.onClick())+ expect(onToggleReaction).toHaveBeenCalledWith("π₯")+ })+it("keeps a known portrait image intrinsic and constrains it by message width + max height", () => {useMessageMock.mockReturnValue({isLoading: false,diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsxindex fcdc71baa..7d15b1ba8 100644--- a/src/web/src/components/community/messages/thread-opener.tsx+++ b/src/web/src/components/community/messages/thread-opener.tsx@@ -6,7 +6,6 @@ import { MessageBody } from "./message-body"import { attachmentAspectRatio } from "./attachment-layout"import { formatMessageTime } from "@/lib/community/format-time"import { Skeleton } from "@/components/ui/skeleton"-import { NumberTicker } from "@/components/ui/number-ticker"import { avatarInitial } from "@/lib/community/avatar"import { useMessage } from "@/hooks/community/use-message"import { tid } from "@/lib/community/testids"@@ -16,6 +15,8 @@ import { AttachmentCard } from "./attachment-card"import { displayReplyContent } from "@/lib/community/reply-content"import { useMobileAvatarMention } from "./use-mobile-avatar-mention"import { useCommunityProfile } from "@/stores/community/ws"+import { useHoverCapable } from "@/hooks/use-hover-capable"+import { MessageReactions } from "./message-reactions"// Thread opener β the parent message the thread was created from, pinned at// the top of the thread's message list. Deliberately styled like a REGULAR@@ -39,6 +40,8 @@ export function ThreadOpener({onPreviewAttachment,onDownloadFile,onJump,+ onToggleReaction,+ resolveUserName,resolveAuthorMentionText,onInsertMentionText,}: {@@ -48,12 +51,15 @@ export function ThreadOpener({onPreviewImage?: (image: ImagePreview) => voidonPreviewAttachment?: (attachment: FileAttachment) => voidonDownloadFile?: (url: string, name: string) => void+ onToggleReaction?: (emoji: string) => void+ resolveUserName?: (userId: string) => stringresolveAuthorMentionText?: (authorId: string) => string | nullonInsertMentionText?: (text: string) => void// Jump to the parent message in its channel. When provided, a hover-revealed// "Jump" button appears in the opener's top-right.onJump?: () => void}) {+ const hoverCapable = useHoverCapable()const { message: msg, isLoading, isError } = useMessage(parentMessageId)const authorProfile = useCommunityProfile(msg?.authorId)const mentionText = msg ? resolveAuthorMentionText?.(msg.authorId) ?? null : null@@ -179,20 +185,16 @@ export function ThreadOpener({</div>)}- {msg.reactions && msg.reactions.length > 0 && (- <div className="mt-2 flex flex-wrap gap-1">- {msg.reactions.map((r, i) => (- <span- key={i}- className={[- "flex h-6 items-center gap-1 rounded-full px-2 text-sm",- r.me ? "border border-primary/50 bg-accent" : "bg-secondary",- ].join(" ")}- >- <span>{r.emoji}</span>- <NumberTicker value={r.count} className="text-xs text-muted-foreground" />- </span>- ))}+ {msg.reactions && (+ <div className="mt-2">+ <MessageReactions+ messageId={msg.id}+ reactions={msg.reactions}+ hoverCapable={hoverCapable}+ tooltipActive+ onToggleReaction={onToggleReaction}+ resolveUserName={resolveUserName}+ /></div>)}</div>diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.tsindex a0ede9c19..5219f40ca 100644--- a/src/web/src/hooks/community/community-ws/membership-events.test.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts@@ -34,6 +34,16 @@ describe("useCommunityWs β member events", () => {id: "srv_1",categories: [],})+ capturedQueryClient.setQueryData(communityKeys.reactionDetails("message_1"), {+ messageId: "message_1",+ scope: { kind: "server", serverId: "srv_1", channelId: "channel_1" },+ actors: [],+ })+ capturedQueryClient.setQueryData(communityKeys.reactionDetails("message_2"), {+ messageId: "message_2",+ scope: { kind: "server", serverId: "srv_2", channelId: "channel_2" },+ actors: [],+ })capturedOnMessage!({type: "community:member.leave",@@ -47,6 +57,71 @@ describe("useCommunityWs β member events", () => {currentChannelMeta: null,})expect(capturedQueryClient.getQueryState(communityKeys.server("srv_1"))).toBeUndefined()+ expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("message_1"))).toBeUndefined()+ expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("message_2"))).toBeDefined()+ })++ it("evicts an unresolved reaction-details request when the viewer leaves", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const key = communityKeys.reactionDetails("pending_message")+ void capturedQueryClient.fetchQuery({+ queryKey: key,+ queryFn: () => new Promise(() => undefined),+ }).catch(() => undefined)+ expect(capturedQueryClient.getQueryState(key)).toBeDefined()++ capturedOnMessage!({+ type: "community:member.leave",+ serverId: "srv_1",+ userId: "u_me",+ } satisfies CommunityMemberLeave)++ expect(capturedQueryClient.getQueryState(key)).toBeUndefined()+ })++ it("invalidates matching reactor identities when another member leaves", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const matching = communityKeys.reactionDetails("message_1")+ const other = communityKeys.reactionDetails("message_2")+ capturedQueryClient.setQueryData(matching, {+ messageId: "message_1",+ scope: { kind: "server", serverId: "srv_1", channelId: "channel_1" },+ actors: [],+ })+ capturedQueryClient.setQueryData(other, {+ messageId: "message_2",+ scope: { kind: "server", serverId: "srv_2", channelId: "channel_2" },+ actors: [],+ })+ capturedOnMessage!({+ type: "community:member.leave",+ serverId: "srv_1",+ userId: "u_other",+ } satisfies CommunityMemberLeave)+ expect(capturedQueryClient.getQueryState(matching)?.isInvalidated).toBe(true)+ expect(capturedQueryClient.getQueryState(other)?.isInvalidated).toBe(false)+ })++ it("invalidates an unresolved active reaction-details request on member leave", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const key = communityKeys.reactionDetails("pending_message")+ const queryFn = vi.fn(() => new Promise<never>(() => undefined))+ const observer = new QueryObserver(capturedQueryClient, {+ queryKey: key,+ queryFn,+ })+ const unsubscribe = observer.subscribe(() => undefined)+ expect(queryFn).toHaveBeenCalledOnce()++ capturedOnMessage!({+ type: "community:member.leave",+ serverId: "srv_1",+ userId: "u_other",+ } satisfies CommunityMemberLeave)++ await vi.waitFor(() => expect(queryFn).toHaveBeenCalledTimes(2))+ expect(capturedQueryClient.getQueryState(key)?.data).toBeUndefined()+ unsubscribe()})it("patches the members cache with a join event", async () => {diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.tsindex 4a67f414d..da45e1cbe 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -30,6 +30,10 @@ import {invalidateServerDetail,invalidateServersList,} from "./invalidation-projections"+import {+ refreshServerReactionDetails,+ removeServerReactionDetails,+} from "./reaction-details-invalidation"type ChannelMemberEvent = Extract<CommunityWsEvent,@@ -113,6 +117,7 @@ export function handleMemberJoin(// affected server's authoritative presence seed so a newly rendered member// does not inherit the offline fallback until the next presence frame.invalidatePresence(projection, event.serverId)+ refreshServerReactionDetails(queryClient, event.serverId)if (event.member.userId === viewerUserIdRef.current) {invalidateChannelRefDirectory(projection)invalidateServersList(projection)@@ -141,6 +146,7 @@ export function handleMemberLeave(// so the layout's eject effect can detect the drop and route// the user away from the now-forbidden URL.if (event.userId === viewerUserIdRef.current) {+ removeServerReactionDetails(queryClient, event.serverId)invalidateChannelRefDirectory(projection)useMessageStreamStore.getState().removeServer(event.serverId)queryClient.removeQueries({ queryKey: communityKeys.server(event.serverId) })@@ -154,6 +160,8 @@ export function handleMemberLeave(// kicked viewer away). `exact` so a kick doesn't cascade-refetch// every server's nested detail subtree.invalidateServersList(projection)+ } else {+ refreshServerReactionDetails(queryClient, event.serverId)}finishMemberEvent(event, context)}diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.tsindex 9d2dd51b4..6f0fe5762 100644--- a/src/web/src/hooks/community/community-ws/message-events.test.ts+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts@@ -742,6 +742,57 @@ describe("useCommunityWs β reactions", () => {])})+ it("leaves a focused overlay unchanged when the reaction message is absent", async () => {+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_empty" })+ await mountHook({ viewerUserId: "u_me" })++ capturedOnMessage!({+ type: "community:reaction.add",+ channelId: "ch_empty",+ messageId: "m_missing",+ userId: "u_other",+ emoji: "π",+ })++ expect(getMessageOverlay({ kind: "channel", id: "ch_empty", serverId: "s1" }).liveById.size)+ .toBe(0)+ })++ it("patches every mounted message-context copy for the reaction channel", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const unresolvedContext = { notFound: true }+ capturedQueryClient.setQueryData(communityKeys.messageContext("channel", "ch_1", 7), {+ anchorId: "m_1",+ messages: [{ id: "m_1", type: "chat", content: "x", reactions: [] }],+ })+ capturedQueryClient.setQueryData(communityKeys.messageContext("channel", "ch_1", 99), {+ anchorId: "m_other",+ messages: [{ id: "m_other", type: "chat", content: "other", reactions: [] }],+ })+ capturedQueryClient.setQueryData(+ communityKeys.messageContext("dm", "ch_1", 8),+ unresolvedContext,+ )+ capturedOnMessage!({+ type: "community:reaction.add",+ channelId: "ch_1",+ messageId: "m_1",+ userId: "u_other",+ emoji: "π₯",+ })+ expect(capturedQueryClient.getQueryData<{+ messages: { id: string; reactions: { emoji: string; userIds: string[] }[] }[]+ }>(communityKeys.messageContext("channel", "ch_1", 7))?.messages[0].reactions).toEqual([+ { emoji: "π₯", count: 1, me: false, userIds: ["u_other"] },+ ])+ expect(capturedQueryClient.getQueryData<{+ messages: { reactions: unknown[] }[]+ }>(communityKeys.messageContext("channel", "ch_1", 99))?.messages[0].reactions).toEqual([])+ expect(capturedQueryClient.getQueryData(communityKeys.messageContext("dm", "ch_1", 8)))+ .toBe(unresolvedContext)+ })+it("refreshes a focused DM row that exists only in the overlay", async () => {const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })diff --git a/src/web/src/hooks/community/community-ws/message-projections.ts b/src/web/src/hooks/community/community-ws/message-projections.tsindex dba13c425..84a27cbfe 100644--- a/src/web/src/hooks/community/community-ws/message-projections.ts+++ b/src/web/src/hooks/community/community-ws/message-projections.ts@@ -20,6 +20,7 @@ import {import type { MessageEventContext } from "./handler-context"type ReactionEvent = CommunityReactionAdd | CommunityReactionRemove+type MessageContextCache = { messages?: Msg[] }type MessageProjectionContext = Pick<MessageEventContext,"projection" | "queryClient" | "sub" | "viewerUserIdRef"@@ -65,6 +66,19 @@ export function projectReactionCopies(communityKeys.message(event.messageId),(message) => message ? applyReactionToMessage(message, event, viewerId) : message,)+ for (const type of ["channel", "dm"] as const) {+ queryClient.setQueriesData<MessageContextCache>(+ { queryKey: communityKeys.messageContexts(type, event.channelId) },+ (cache) => cache?.messages+ ? {+ ...cache,+ messages: cache.messages.map((message) => message.id === event.messageId+ ? applyReactionToMessage(message, event, viewerId)+ : message),+ }+ : cache,+ )+ }if (event.channelId === sub.channelId) {const serverId = useCommunityStore.getState().currentServerIdif (serverId) {diff --git a/src/web/src/hooks/community/community-ws/reaction-details-invalidation.ts b/src/web/src/hooks/community/community-ws/reaction-details-invalidation.tsnew file mode 100644index 000000000..b2fb888a2--- /dev/null+++ b/src/web/src/hooks/community/community-ws/reaction-details-invalidation.ts@@ -0,0 +1,41 @@+import type { QueryClient, QueryKey } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"+import type { ReactionDetailsEnvelope } from "@/hooks/community/use-reaction-details"++function reactionDetails(+ queryClient: QueryClient,+): Array<[QueryKey, ReactionDetailsEnvelope | undefined]> {+ return queryClient+ .getQueriesData<ReactionDetailsEnvelope>({ queryKey: communityKeys.reactionDetailsAll() })+}++export function refreshServerReactionDetails(+ queryClient: QueryClient,+ serverId: string,+) {+ for (const [key, data] of reactionDetails(queryClient)) {+ if (!data) {+ void queryClient.resetQueries({ queryKey: key, exact: true })+ continue+ }+ if (data.scope.kind !== "server" || data.scope.serverId !== serverId) continue+ void queryClient.invalidateQueries({ queryKey: key, exact: true, refetchType: "active" })+ }+}++export function removeServerReactionDetails(+ queryClient: QueryClient,+ serverId: string,+) {+ for (const [key, data] of reactionDetails(queryClient)) {+ if (data && (data.scope.kind !== "server" || data.scope.serverId !== serverId)) continue+ queryClient.removeQueries({ queryKey: key, exact: true })+ }+}++export function removeDmReactionDetails(queryClient: QueryClient) {+ for (const [key, data] of reactionDetails(queryClient)) {+ if (data && data.scope.kind !== "dm") continue+ queryClient.removeQueries({ queryKey: key, exact: true })+ }+}diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.tsindex 89989e422..1c845a57a 100644--- a/src/web/src/hooks/community/community-ws/social-events.test.ts+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import type {+ CommunityFriendBlock,CommunityFriendRequest,CommunityMentionCreate,} from "@alook/shared"@@ -176,6 +177,43 @@ describe("useCommunityWs β friend + mention β invalidate", () => {))).toBe(true)})+ it("friend.block evicts cached DM reactor identities", async () => {+ await mountHook()+ capturedQueryClient.setQueryData(communityKeys.reactionDetails("dm_message"), {+ messageId: "dm_message",+ scope: { kind: "dm", channelId: "dm_1" },+ actors: [],+ })+ capturedQueryClient.setQueryData(communityKeys.reactionDetails("server_message"), {+ messageId: "server_message",+ scope: { kind: "server", serverId: "server_1", channelId: "channel_1" },+ actors: [],+ })+ capturedOnMessage!({+ type: "community:friend.block",+ userId: "blocked_1",+ } satisfies CommunityFriendBlock)+ expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("dm_message"))).toBeUndefined()+ expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("server_message"))).toBeDefined()+ })++ it("friend.block evicts an unresolved reaction-details request", async () => {+ await mountHook()+ const key = communityKeys.reactionDetails("pending_message")+ void capturedQueryClient.fetchQuery({+ queryKey: key,+ queryFn: () => new Promise(() => undefined),+ }).catch(() => undefined)+ expect(capturedQueryClient.getQueryState(key)).toBeDefined()++ capturedOnMessage!({+ type: "community:friend.block",+ userId: "blocked_1",+ } satisfies CommunityFriendBlock)++ expect(capturedQueryClient.getQueryState(key)).toBeUndefined()+ })+it("routes mention.create through the debounced Inbox owner", async () => {vi.useFakeTimers()try {diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.tsindex a773e01c0..6c9d60973 100644--- a/src/web/src/hooks/community/community-ws/social-events.ts+++ b/src/web/src/hooks/community/community-ws/social-events.ts@@ -19,6 +19,7 @@ import {reconcileAccountReadState,} from "./read-state-reconciliation"import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"+import { removeDmReactionDetails } from "./reaction-details-invalidation"export function handleReadStateAdvanced(event: CommunityReadStateAdvanced,@@ -94,10 +95,11 @@ type FriendEvent =| CommunityFriendBlockexport function handleFriendEvent(- _event: FriendEvent,- { projection }: SocialEventContext,+ event: FriendEvent,+ { projection, queryClient }: SocialEventContext,) {invalidateFriends(projection)+ if (event.type === "community:friend.block") removeDmReactionDetails(queryClient)}export function handleMentionCreate(diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex 95f97cd21..7b1b5b48e 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -605,6 +605,40 @@ describe("useSendMessage β no blocked branch on channel path", () => {// timer on subsequent clicks. Step 3's hook dropped the coalescing; this// restores it via useCommunityStore.reactionTimers.describe("useToggleReactionApi β 300ms debounce coalescing", () => {+ it("optimistically patches and rolls back a thread opener's single-message cache", async () => {+ vi.useFakeTimers()+ try {+ capturedQc.setQueryData(communityKeys.message("m_opener"), {+ id: "m_opener",+ type: "chat",+ reactions: [{ emoji: "π₯", count: 1, me: false, userIds: ["u_other"] }],+ })+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))+ const mod = await loadMod()+ mod.useToggleReactionApi()({+ serverId: "s1",+ channelId: "ch_parent",+ messageId: "m_opener",+ emoji: "π₯",+ userId: "u_me",+ })+ expect(capturedQc.getQueryData<{ reactions: Msg["reactions"] }>(+ communityKeys.message("m_opener"),+ )?.reactions).toEqual([+ { emoji: "π₯", count: 2, me: true, userIds: ["u_other", "u_me"] },+ ])+ await vi.advanceTimersByTimeAsync(300)+ await Promise.resolve()+ expect(capturedQc.getQueryData<{ reactions: Msg["reactions"] }>(+ communityKeys.message("m_opener"),+ )?.reactions).toEqual([+ { emoji: "π₯", count: 1, me: false, userIds: ["u_other"] },+ ])+ } finally {+ vi.useRealTimers()+ }+ })+it("updates and rolls back a fallback-only channel row without creating a second row", async () => {vi.useFakeTimers()try {diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex dcdfb7c9f..4cf4c546a 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -420,13 +420,13 @@ function togglePageCacheReaction(return { ...cache, pages }}-function toggleMessageReaction(- message: Msg,+function toggledReactions(+ reactionsSource: Msg["reactions"],emoji: string,userId: string,add: boolean,-): Msg {- const reactions = (message.reactions ?? []).map((reaction) => ({+): NonNullable<Msg["reactions"]> {+ const reactions = (reactionsSource ?? []).map((reaction) => ({...reaction,userIds: [...(reaction.userIds ?? [])],}))@@ -445,7 +445,27 @@ function toggleMessageReaction(existing.me = falseif (existing.count <= 0) reactions.splice(reactions.indexOf(existing), 1)}- return { ...message, reactions }+ return reactions+}++function toggleMessageReaction(+ message: Msg,+ emoji: string,+ userId: string,+ add: boolean,+): Msg {+ return { ...message, reactions: toggledReactions(message.reactions, emoji, userId, add) }+}++function toggleSingleMessageReaction<T extends { reactions?: Msg["reactions"] }>(+ message: T | undefined,+ emoji: string,+ userId: string,+ add: boolean,+): T | undefined {+ return message+ ? { ...message, reactions: toggledReactions(message.reactions, emoji, userId, add) }+ : message}function messageScope(args: ToggleReactionArgs): MessageScope | undefined {@@ -533,19 +553,26 @@ export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {? communityKeys.dmMessages(args.dmId): communityKeys.channelMessages("__none__")const cache = queryClient.getQueryData<PageCache>(key)+ const messageKey = communityKeys.message(args.messageId)+ const singleMessage = queryClient.getQueryData<{ reactions?: Msg["reactions"] }>(messageKey)const scope = messageScope(args)const source = scope? currentMaterializedMessage(cache, scope, args.messageId): undefinedconst wasMe = source? source.reactions?.find((reaction) => reaction.emoji === args.emoji)?.me ?? false- : currentMeStatus(cache, args.messageId, args.emoji)+ : singleMessage+ ? singleMessage.reactions?.find((reaction) => reaction.emoji === args.emoji)?.me ?? false+ : currentMeStatus(cache, args.messageId, args.emoji)const nextMe = !wasMe// Optimistic write is always synchronous β the debounce only defers the// API call, not the visible UI.queryClient.setQueryData<PageCache>(key, (c) =>togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, nextMe),)+ queryClient.setQueryData(messageKey, (message: typeof singleMessage) =>+ toggleSingleMessageReaction(message, args.emoji, args.userId, nextMe),+ )refreshExistingReactionFallback(queryClient.getQueryData<PageCache>(key), args, nextMe)const timerKey = `${args.messageId}:${args.emoji}`@@ -574,6 +601,9 @@ export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {queryClient.setQueryData<PageCache>(key, (c) =>togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, originalMe),)+ queryClient.setQueryData(messageKey, (message: typeof singleMessage) =>+ toggleSingleMessageReaction(message, args.emoji, args.userId, originalMe),+ )refreshExistingReactionFallback(queryClient.getQueryData<PageCache>(key), args, originalMe)})}, REACTION_DEBOUNCE_MS)diff --git a/src/web/src/hooks/community/use-reaction-details.test.ts b/src/web/src/hooks/community/use-reaction-details.test.tsnew file mode 100644index 000000000..65757f97b--- /dev/null+++ b/src/web/src/hooks/community/use-reaction-details.test.ts@@ -0,0 +1,188 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"++const apiFetchProfiles = vi.fn()+const communityUserProfilePatch = vi.fn((userId: string, profile: unknown) => ({ userId, profile }))+vi.mock("@/lib/community/profile-seed", () => ({+ apiFetchProfiles: (...args: unknown[]) => apiFetchProfiles(...args),+ communityUserProfilePatch: (userId: string, profile: unknown) =>+ communityUserProfilePatch(userId, profile),+}))++import { useReactionDetails, type ReactionDetailsEnvelope } from "./use-reaction-details"+import { communityKeys } from "@/lib/query-keys"++function deferred<T>() {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((done) => { resolve = done })+ return { promise, resolve }+}++function envelope(actorIds: string[]): ReactionDetailsEnvelope {+ return {+ messageId: "message_1",+ scope: { kind: "server", serverId: "server_1", channelId: "channel_1" },+ actors: actorIds.map((userId) => ({+ userId,+ profile: {+ id: userId,+ name: userId,+ discriminator: "0001",+ avatar: userId.slice(0, 1).toUpperCase(),+ avatarVersion: 0,+ },+ })),+ }+}++describe("useReactionDetails", () => {+ afterEach(() => {+ vi.useRealTimers()+ vi.clearAllMocks()+ vi.unstubAllGlobals()+ })++ it("loads only while open and bounds burst, in-flight, missing, and reappearing actor refreshes", async () => {+ vi.useFakeTimers()+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true)+ const first = deferred<ReactionDetailsEnvelope>()+ const second = deferred<ReactionDetailsEnvelope>()+ const third = deferred<ReactionDetailsEnvelope>()+ const fourth = deferred<ReactionDetailsEnvelope>()+ apiFetchProfiles+ .mockReturnValueOnce(first.promise)+ .mockReturnValueOnce(second.promise)+ .mockReturnValueOnce(third.promise)+ .mockReturnValueOnce(fourth.promise)++ let props = { open: false, userIds: ["user_1"] as string[] }+ let latest: ReturnType<typeof useReactionDetails> | undefined+ function Probe() {+ latest = useReactionDetails({ messageId: "message_1", ...props })+ return null+ }+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ let renderer: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)),+ )+ })+ expect(apiFetchProfiles).not.toHaveBeenCalled()++ props = { open: true, userIds: ["user_1"] }+ await act(async () => renderer!.update(+ React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)),+ ))+ expect(apiFetchProfiles).toHaveBeenCalledTimes(1)+ await act(async () => {+ first.resolve(envelope(["user_1"]))+ await first.promise+ await vi.advanceTimersByTimeAsync(0)+ })+ expect(latest?.data?.actors).toHaveLength(1)++ props = { open: true, userIds: ["user_1", "user_2", "user_3"] }+ await act(async () => renderer!.update(+ React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)),+ ))+ await act(async () => vi.advanceTimersByTime(99))+ expect(apiFetchProfiles).toHaveBeenCalledTimes(1)+ await act(async () => vi.advanceTimersByTime(1))+ expect(apiFetchProfiles).toHaveBeenCalledTimes(2)++ props = { open: true, userIds: ["user_1", "user_2", "user_3", "user_4"] }+ await act(async () => renderer!.update(+ React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)),+ ))+ expect(apiFetchProfiles).toHaveBeenCalledTimes(2)+ await act(async () => {+ second.resolve(envelope(["user_1", "user_2", "user_3"]))+ await second.promise+ await vi.advanceTimersByTimeAsync(0)+ })+ await act(async () => vi.advanceTimersByTime(100))+ expect(apiFetchProfiles).toHaveBeenCalledTimes(3)+ await act(async () => {+ third.resolve(envelope(["user_1", "user_2", "user_3"]))+ await third.promise+ await vi.advanceTimersByTimeAsync(0)+ })+ await act(async () => vi.advanceTimersByTime(500))+ expect(apiFetchProfiles).toHaveBeenCalledTimes(3)++ props = { open: true, userIds: ["user_1", "user_2", "user_3"] }+ await act(async () => renderer!.update(+ React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)),+ ))+ props = { open: true, userIds: ["user_1", "user_2", "user_3", "user_4"] }+ await act(async () => renderer!.update(+ React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)),+ ))+ await act(async () => vi.advanceTimersByTime(100))+ expect(apiFetchProfiles).toHaveBeenCalledTimes(4)+ await act(async () => {+ fourth.resolve(envelope(["user_1", "user_2", "user_3", "user_4"]))+ await fourth.promise+ await vi.advanceTimersByTimeAsync(0)+ })+ act(() => renderer!.unmount())+ })++ it("seeds only authorized non-null profiles from the initial envelope", async () => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true)+ const data = envelope(["user_1"])+ data.actors.push({ userId: "departed", profile: null })+ apiFetchProfiles.mockImplementationOnce(async (_url, selectProfiles) => {+ expect(selectProfiles(data)).toEqual([{+ userId: "user_1",+ profile: data.actors[0].profile,+ }])+ return data+ })++ function Probe() {+ useReactionDetails({ messageId: "message_1", open: true, userIds: ["user_1"] })+ return null+ }+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ let renderer: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)),+ )+ })+ expect(communityUserProfilePatch).toHaveBeenCalledOnce()+ expect(communityUserProfilePatch).toHaveBeenCalledWith("user_1", data.actors[0].profile)+ act(() => renderer!.unmount())+ })++ it("cancels a scheduled unknown-actor refresh when the dialog closes", async () => {+ vi.useFakeTimers()+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true)+ let props = { open: true, userIds: ["user_1", "user_2"] as string[] }+ function Probe() {+ useReactionDetails({ messageId: "message_1", ...props })+ return null+ }+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ queryClient.setQueryData(communityKeys.reactionDetails("message_1"), envelope(["user_1"]))+ let renderer: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)),+ )+ })+ expect(apiFetchProfiles).not.toHaveBeenCalled()++ props = { open: false, userIds: ["user_1", "user_2"] }+ await act(async () => renderer!.update(+ React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)),+ ))+ await act(async () => vi.advanceTimersByTimeAsync(100))+ expect(apiFetchProfiles).not.toHaveBeenCalled()+ act(() => renderer!.unmount())+ })+})diff --git a/src/web/src/hooks/community/use-reaction-details.ts b/src/web/src/hooks/community/use-reaction-details.tsnew file mode 100644index 000000000..17186b79e--- /dev/null+++ b/src/web/src/hooks/community/use-reaction-details.ts@@ -0,0 +1,79 @@+"use client"++import { useEffect, useMemo, useRef } from "react"+import { useQuery } from "@tanstack/react-query"+import { apiFetchProfiles, communityUserProfilePatch } from "@/lib/community/profile-seed"+import { communityKeys } from "@/lib/query-keys"++export type ReactionDetailsProfile = {+ id: string+ name: string+ discriminator: string+ avatar: string+ avatarVersion: number+}++export type ReactionDetailsEnvelope = {+ messageId: string+ scope:+ | { kind: "server"; serverId: string; channelId: string }+ | { kind: "dm"; channelId: string }+ actors: Array<{+ userId: string+ profile: ReactionDetailsProfile | null+ }>+}++const loadReactionDetails = (messageId: string) =>+ apiFetchProfiles<ReactionDetailsEnvelope>(+ `/api/community/messages/${messageId}/reactions`,+ (data) => data.actors.flatMap((actor) => actor.profile+ ? [communityUserProfilePatch(actor.userId, actor.profile)]+ : []),+ )++export function useReactionDetails({+ messageId,+ open,+ userIds,+}: {+ messageId: string+ open: boolean+ userIds: readonly string[]+}) {+ const uniqueUserIds = useMemo(() => [...new Set(userIds)], [userIds])+ const attemptedRef = useRef(new Set<string>())+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const query = useQuery({+ queryKey: communityKeys.reactionDetails(messageId),+ queryFn: () => loadReactionDetails(messageId),+ enabled: open,+ staleTime: 5 * 60_000,+ })+ const { data, isFetching, refetch } = query++ useEffect(() => {+ const current = new Set(uniqueUserIds)+ for (const attempted of attemptedRef.current) {+ if (!current.has(attempted)) attemptedRef.current.delete(attempted)+ }+ if (!open || !data || isFetching) return+ const known = new Set(data.actors.map((actor) => actor.userId))+ const unknown = uniqueUserIds.filter((id) =>+ !known.has(id) && !attemptedRef.current.has(id))+ if (unknown.length === 0) return+ unknown.forEach((id) => attemptedRef.current.add(id))++ const refresh = async () => {+ timerRef.current = null+ await refetch()+ }+ timerRef.current = setTimeout(refresh, 100)+ return () => {+ if (timerRef.current) clearTimeout(timerRef.current)+ timerRef.current = null+ }+ }, [data, isFetching, open, refetch, uniqueUserIds])++ return query+}diff --git a/src/web/src/lib/community/reaction-access.ts b/src/web/src/lib/community/reaction-access.tsnew file mode 100644index 000000000..0de3218c2--- /dev/null+++ b/src/web/src/lib/community/reaction-access.ts@@ -0,0 +1,55 @@+import { queries } from "@alook/shared"+import type { Database } from "@alook/shared"+import {+ requireChannelMember,+ requireDMAccess,+} from "@/lib/community/permissions"+import { requireReactableSurface } from "@/lib/community/channel-write-guard"++type ReactionAccessScope =+ | { kind: "server"; serverId: string; channelId: string }+ | { kind: "dm"; channelId: string }++export type ReactionAccessResult =+ | {+ ok: true+ channelId: string+ isDm: boolean+ scope: ReactionAccessScope+ }+ | { ok: false; status: 400 | 401 | 403 | 404; error: string }++export async function authorizeReaction(+ db: Database,+ messageId: string,+ userId: string,+): Promise<ReactionAccessResult> {+ const message = await queries.communityMessage.getMessage(db, messageId)+ if (!message) return { ok: false, status: 404, error: "message not found" }++ const channelType = await queries.communityChannel.getChannelType(db, message.channelId)+ const reactable = requireReactableSurface(channelType)+ if (!reactable.ok) return reactable++ if (channelType === "dm") {+ const check = await requireDMAccess(db, message.channelId, userId)+ if (!check.ok) return check+ return {+ ok: true,+ channelId: message.channelId,+ isDm: true,+ scope: { kind: "dm", channelId: message.channelId },+ }+ }++ const check = await requireChannelMember(db, message.channelId, userId)+ if (!check.ok) return check+ const serverId = check.value.serverId+ if (!serverId) return { ok: false, status: 404, error: "channel not found" }+ return {+ ok: true,+ channelId: message.channelId,+ isDm: false,+ scope: { kind: "server", serverId, channelId: message.channelId },+ }+}diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.tsindex 9f971c8b1..54573d2b1 100644--- a/src/web/src/lib/community/testids.test.ts+++ b/src/web/src/lib/community/testids.test.ts@@ -42,6 +42,13 @@ describe("community QA selectors", () => {expect(tid.memberRow("member_1")).toBe("community-member-row-member_1")expect(tid.composerFileInput).toBe("community-composer-file-input")expect(tid.messageScroller).toBe("community-message-scroller")+ expect(tid.reactionGroup("message_1")).toBe("community-reaction-group-message_1")+ expect(tid.reactionChip("message_1", "π₯"))+ .toBe("community-reaction-chip-message_1-%F0%9F%94%A5")+ expect(tid.reactionDialog("message_1")).toBe("community-reaction-dialog-message_1")+ expect(tid.reactionTab("π")).toBe("community-reaction-tab-%F0%9F%91%8D")+ expect(tid.reactionMember("user_1")).toBe("community-reaction-member-user_1")+ expect(tid.reactionEmpty("message_1")).toBe("community-reaction-empty-message_1")})it("keys a pending channel sidebar by its target server", () => {diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 860bd99d6..5ca7058a9 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -126,6 +126,13 @@ export const tid = {channelRefPopup: "community-channel-ref-popup",channelRefStatus: "community-channel-ref-status",reactionAdd: (msgId: string) => `community-reaction-add-${msgId}`,+ reactionGroup: (msgId: string) => `community-reaction-group-${msgId}`,+ reactionChip: (msgId: string, emoji: string) =>+ `community-reaction-chip-${msgId}-${encodeURIComponent(emoji)}`,+ reactionDialog: (msgId: string) => `community-reaction-dialog-${msgId}`,+ reactionTab: (emoji: string) => `community-reaction-tab-${encodeURIComponent(emoji)}`,+ reactionMember: (userId: string) => `community-reaction-member-${userId}`,+ reactionEmpty: (msgId: string) => `community-reaction-empty-${msgId}`,messageShare: (msgId: string) => `community-message-share-${msgId}`,messageShareCopy: `community-message-share-copy`,threadIndicator: (msgId: string) => `community-thread-indicator-${msgId}`,diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.tsindex 76bae7281..48b7d3072 100644--- a/src/web/src/lib/query-keys.test.ts+++ b/src/web/src/lib/query-keys.test.ts@@ -147,6 +147,16 @@ describe("communityKeys", () => {"d1",7,])+ expect(communityKeys.messageContexts("dm", "d1")).toEqual([+ "community",+ "message-context",+ "dm",+ "d1",+ ])+ expect(communityKeys.reactionDetails("m1")).toEqual([+ ...communityKeys.reactionDetailsAll(),+ "m1",+ ])})it("keeps report polling specific to one report and outside the bots-list cache", () => {diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex 21736b498..48b7bfd5a 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -105,8 +105,14 @@ export const communityKeys = {// Single hydrated message (opener block, deep-link previews).message: (messageId: string) =>[...communityKeys.all, "message", messageId] as const,+ messageContexts: (type: "channel" | "dm", channelId: string) =>+ [...communityKeys.all, "message-context", type, channelId] as const,messageContext: (type: "channel" | "dm", channelId: string, targetSeq: number | null) =>- [...communityKeys.all, "message-context", type, channelId, targetSeq] as const,+ [...communityKeys.messageContexts(type, channelId), targetSeq] as const,+ reactionDetailsAll: () =>+ [...communityKeys.all, "reaction-details"] as const,+ reactionDetails: (messageId: string) =>+ [...communityKeys.reactionDetailsAll(), messageId] as const,// ββ Inbox βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββinbox: () => [...communityKeys.all, "inbox"] as const,diff --git a/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts b/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.tsnew file mode 100644index 000000000..1a15a1d10--- /dev/null+++ b/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts@@ -0,0 +1,218 @@+import type { Locator, Page } from "@playwright/test"+import { expect, test, userId } from "./_fixtures/community-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import {+ seedChannel,+ seedJoinServer,+ seedMessage,+ seedReaction,+ seedServer,+ seedThread,+} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"++const HOVER_QUERY = "(hover: hover) and (pointer: fine)"++async function installInputCapability(page: Page, hoverCapable: boolean) {+ await page.addInitScript(({ query, matches }) => {+ const nativeMatchMedia = window.matchMedia.bind(window)+ window.matchMedia = (candidate: string) => candidate === query+ ? {+ matches,+ media: candidate,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ } as MediaQueryList+ : nativeMatchMedia(candidate)+ }, { query: HOVER_QUERY, matches: hoverCapable })+}++async function holdReaction(page: Page, chip: Locator, pointerId = 41) {+ const box = await chip.boundingBox()+ if (!box) throw new Error("reaction chip has no box")+ const point = { x: box.x + box.width / 2, y: box.y + box.height / 2 }+ const pointer = { pointerType: "touch", pointerId, isPrimary: true, button: 0 }+ await chip.dispatchEvent("pointerdown", { ...pointer, clientX: point.x, clientY: point.y })+ await page.waitForTimeout(500)+ await chip.dispatchEvent("pointerup", { ...pointer, clientX: point.x, clientY: point.y })+ await chip.dispatchEvent("click", point)+}++async function expectDialogInsideViewport(page: Page, messageId: string) {+ const dialog = page.getByTestId(tid.reactionDialog(messageId))+ await expect(dialog).toBeVisible()+ const geometry = await dialog.evaluate((element) => {+ const rect = element.getBoundingClientRect()+ return {+ top: rect.top,+ right: rect.right,+ bottom: rect.bottom,+ left: rect.left,+ width: window.innerWidth,+ height: window.innerHeight,+ }+ })+ expect(geometry.left).toBeGreaterThanOrEqual(0)+ expect(geometry.top).toBeGreaterThanOrEqual(0)+ expect(geometry.right).toBeLessThanOrEqual(geometry.width)+ expect(geometry.bottom).toBeLessThanOrEqual(geometry.height)+}++test.describe.serial("mobile reaction details", () => {+ let serverId: string+ let channelId: string+ let messageId: string+ let emptyMessageId: string+ let threadId: string+ let threadOpenerId: string++ test.beforeAll(async () => {+ const stamp = Date.now()+ serverId = await seedServer("alice", `Reaction details ${stamp}`)+ channelId = await seedChannel("alice", serverId, `reactions-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ await seedJoinServer("alice", "carol", serverId)+ messageId = await seedMessage("alice", channelId, `Hold a reaction ${stamp}`)+ await seedReaction("alice", messageId, "π")+ await seedReaction("bob", messageId, "π")+ await seedReaction("bob", messageId, "π₯")+ await seedReaction("carol", messageId, "π")+ emptyMessageId = await seedMessage("alice", channelId, `Empty reactions ${stamp}`)+ await seedReaction("alice", emptyMessageId, "β ")+ threadOpenerId = await seedMessage("alice", channelId, `Thread opener reactions ${stamp}`)+ await seedReaction("bob", threadOpenerId, "π")+ threadId = await seedThread("alice", threadOpenerId, `Reaction thread ${stamp}`)+ })++ test("hold opens one authorized batch dialog while tap keeps the canonical toggle", async ({ asUser }, testInfo) => {+ const alice = await asUser("alice")+ await alice.page.setViewportSize({ width: 390, height: 844 })+ await alice.page.emulateMedia({ colorScheme: "light" })+ await installInputCapability(alice.page, false)+ const detailsPath = `/api/community/messages/${messageId}/reactions`+ const mutationPath = `/api/community/messages/${messageId}/reactions/${encodeURIComponent("π")}`+ const detailsRequests: string[] = []+ const mutationRequests: string[] = []+ alice.page.on("request", (request) => {+ const pathname = new URL(request.url()).pathname+ if (request.method() === "GET" && pathname === detailsPath) detailsRequests.push(pathname)+ if (request.method() !== "GET" && pathname === mutationPath) mutationRequests.push(request.method())+ })+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)+ const fire = alice.page.getByTestId(tid.reactionChip(messageId, "π₯"))+ await expect(fire).toBeVisible()+ await holdReaction(alice.page, fire)+ await expectDialogInsideViewport(alice.page, messageId)+ await expect(alice.page.getByTestId(tid.reactionTab("π₯"))).toHaveAttribute("data-active", "")+ await expect(alice.page.getByTestId(tid.reactionMember(userId("bob")))).toBeVisible()+ await testInfo.attach("390-mobile-reaction-details.png", {+ body: await alice.page.screenshot(),+ contentType: "image/png",+ })+ await alice.page.emulateMedia({ colorScheme: "dark" })+ await expect(alice.page.locator("html")).toHaveClass(/dark/)+ await testInfo.attach("390-mobile-reaction-details-dark.png", {+ body: await alice.page.screenshot(),+ contentType: "image/png",+ })+ await alice.page.emulateMedia({ colorScheme: "light" })+ expect(detailsRequests).toHaveLength(1)+ expect(mutationRequests).toHaveLength(0)+ await alice.page.getByRole("button", { name: "Close" }).click()+ await expect(fire).toBeFocused()++ const thumb = alice.page.getByTestId(tid.reactionChip(messageId, "π"))+ const toggleResponse = alice.page.waitForResponse((response) => (+ new URL(response.url()).pathname === mutationPath+ && response.request().method() === "DELETE"+ ))+ await thumb.click()+ expect((await toggleResponse).status()).toBe(204)+ expect(mutationRequests).toEqual(["DELETE"])++ await holdReaction(alice.page, fire, 42)+ await expectDialogInsideViewport(alice.page, messageId)+ expect(detailsRequests).toHaveLength(1)+ })++ test("coarse input follows the 320, 639, and 640 cross-capability geometry", async ({ asUser }) => {+ for (const width of [320, 639, 640]) {+ const session = await asUser("alice")+ await session.page.setViewportSize({ width, height: width === 320 ? 568 : 844 })+ await installInputCapability(session.page, false)+ await gotoAfterUserWsAuth(session.page, `/c/channels/${serverId}/${channelId}`)+ const chip = session.page.getByTestId(tid.reactionChip(messageId, "π"))+ await holdReaction(session.page, chip, 50 + width)+ await expectDialogInsideViewport(session.page, messageId)+ const tabs = session.page.getByTestId(tid.reactionDialog(messageId)).getByRole("tab")+ await expect.poll(async () => Math.min(...await tabs.evaluateAll(+ (items) => items.map((item) => item.getBoundingClientRect().height),+ ))).toBeGreaterThanOrEqual(44)+ await session.context.close()+ }+ })++ test("hover-capable desktop keeps compact click and tooltip behavior", async ({ asUser }, testInfo) => {+ const alice = await asUser("alice")+ await alice.page.setViewportSize({ width: 1280, height: 900 })+ await installInputCapability(alice.page, true)+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)+ const chip = alice.page.getByTestId(tid.reactionChip(messageId, "π"))+ await alice.page.getByTestId(tid.message(messageId))+ .locator("[data-community-message-body]")+ .hover()+ await expect(chip).toHaveAttribute("data-slot", "tooltip-trigger")+ await chip.hover()+ await expect(alice.page.getByText(/Reacted by/)).toBeVisible()+ await testInfo.attach("1280-desktop-reaction-tooltip.png", {+ body: await alice.page.screenshot(),+ contentType: "image/png",+ })+ const height = await chip.evaluate((element) => element.getBoundingClientRect().height)+ expect(height).toBeLessThan(44)+ })++ test("the shared thread opener opens the same mobile dialog", async ({ asUser }, testInfo) => {+ const alice = await asUser("alice")+ await alice.page.setViewportSize({ width: 390, height: 844 })+ await alice.page.emulateMedia({ colorScheme: "light" })+ await installInputCapability(alice.page, false)+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${threadId}`)+ const chip = alice.page.getByTestId(tid.reactionChip(threadOpenerId, "π"))+ await expect(chip).toBeVisible()+ await holdReaction(alice.page, chip)+ await expectDialogInsideViewport(alice.page, threadOpenerId)+ await testInfo.attach("390-thread-opener-reaction-details.png", {+ body: await alice.page.screenshot(),+ contentType: "image/png",+ })+ })++ test("removing the last reaction keeps the dialog open on its empty state", async ({ asUser }, testInfo) => {+ const alice = await asUser("alice")+ await alice.page.setViewportSize({ width: 390, height: 844 })+ await alice.page.emulateMedia({ colorScheme: "light" })+ await installInputCapability(alice.page, false)+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)+ const chip = alice.page.getByTestId(tid.reactionChip(emptyMessageId, "β "))+ await holdReaction(alice.page, chip)+ await expectDialogInsideViewport(alice.page, emptyMessageId)+ const status = await alice.page.evaluate(async ({ id, emoji }) => {+ const response = await fetch(`/api/community/messages/${id}/reactions/${encodeURIComponent(emoji)}`, {+ method: "DELETE",+ })+ return response.status+ }, { id: emptyMessageId, emoji: "β " })+ expect(status).toBe(204)+ await expect(alice.page.getByTestId(tid.reactionEmpty(emptyMessageId))).toBeVisible()+ await expect(alice.page.getByTestId(tid.reactionDialog(emptyMessageId))).toBeVisible()+ await testInfo.attach("390-mobile-reaction-details-empty.png", {+ body: await alice.page.screenshot(),+ contentType: "image/png",+ })+ })+})diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.tsindex a7eb58821..02aff5667 100644--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts@@ -159,6 +159,14 @@ export async function seedMessage(author: UserKey, channelId: string, content: sreturn data.message.id}+export async function seedReaction(author: UserKey, messageId: string, emoji: string): Promise<void> {+ const response = await retrySeedRequest(() => fetch(+ `${WEB_URL}/api/community/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`,+ { method: "PUT", headers: { Cookie: sessionCookie(author), Origin: WEB_URL } },+ ))+ if (!response.ok) throw new Error(`seedReaction failed (${response.status})`)+}+export async function seedMark(author: UserKey, channelId: string, messageId: string): Promise<void> {const response = await retrySeedRequest(() => fetch(`${WEB_URL}/api/community/messages/${messageId}/marks`,