446 lines
20 KiB
TypeScript
446 lines
20 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
getMemberChannelDetail: vi.fn(),
|
|
runChatRepositoryTransaction: vi.fn(),
|
|
publishWakeup: vi.fn(),
|
|
publishLinkPreviewRequest: vi.fn(),
|
|
publishAudit: vi.fn(),
|
|
logActivity: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("./repository.server.js", () => ({
|
|
getMemberChannelDetail: mocks.getMemberChannelDetail,
|
|
runChatRepositoryTransaction: mocks.runChatRepositoryTransaction,
|
|
}));
|
|
vi.mock("./realtime-wakeup.server.js", () => ({ publishChatPersistentRealtimeWakeup: mocks.publishWakeup }));
|
|
vi.mock("./link-preview.server.js", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("./link-preview.server.js")>();
|
|
return { ...actual, publishChatLinkPreviewRequest: (...args: unknown[]) => mocks.publishLinkPreviewRequest(...args) };
|
|
});
|
|
vi.mock("@hivegrid/db/audit-events.server", () => ({ publishAuditEventViaOutbox: mocks.publishAudit }));
|
|
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
|
|
|
|
import { CHAT_PERMISSIONS } from "./permissions.js";
|
|
import { sendChatThreadReply, setChatMessagePin, setChatReaction } from "./message-features.server.js";
|
|
|
|
const context = {
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
permissions: [CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.write],
|
|
} as const;
|
|
|
|
function eventRow(input: {
|
|
type: "message_pin_changed" | "reaction_added" | "reaction_removed" | "thread_reply";
|
|
requestId: string;
|
|
data: unknown;
|
|
entityId?: string;
|
|
}) {
|
|
return {
|
|
sequence: 12n,
|
|
occurredAt: new Date("2026-07-16T09:00:00.000Z"),
|
|
tenantId: context.tenantId,
|
|
chatId: "chat_1",
|
|
type: input.type,
|
|
actorUserId: context.userId,
|
|
entityId: input.entityId ?? "message_1",
|
|
requestId: input.requestId,
|
|
data: input.data,
|
|
};
|
|
}
|
|
|
|
function messageRow(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
id: "message_1",
|
|
createdAt: new Date("2026-07-16T08:00:00.000Z"),
|
|
updatedAt: new Date("2026-07-16T08:00:00.000Z"),
|
|
tenantId: context.tenantId,
|
|
chatId: "chat_1",
|
|
authorUserId: context.userId,
|
|
clientMessageId: "client_parent",
|
|
body: "Parent",
|
|
bodyFormat: "markdown",
|
|
parentMessageId: null,
|
|
mentions: [],
|
|
linkPreviews: [],
|
|
editedAt: null,
|
|
deletedAt: null,
|
|
systemEventKind: null,
|
|
systemEventMetadata: null,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function txFixture() {
|
|
return {
|
|
$executeRaw: vi.fn().mockResolvedValue(1),
|
|
$queryRaw: vi.fn().mockResolvedValue([{ id: "membership_1", roleInChat: "member" }]),
|
|
teamChat: {
|
|
findFirst: vi.fn().mockResolvedValue({
|
|
id: "chat_1",
|
|
kind: "group",
|
|
name: "Team",
|
|
isPrivate: false,
|
|
eventStreamId: "stream_1",
|
|
projektId: null,
|
|
}),
|
|
update: vi.fn().mockResolvedValue({ id: "chat_1" }),
|
|
},
|
|
tenant: { findUnique: vi.fn().mockResolvedValue({ slug: "demo" }) },
|
|
teamChatMember: { findMany: vi.fn().mockResolvedValue([]) },
|
|
tenantUser: { findMany: vi.fn().mockResolvedValue([]) },
|
|
userRole: { findMany: vi.fn().mockResolvedValue([]) },
|
|
groupUser: { findMany: vi.fn().mockResolvedValue([]) },
|
|
notificationDelivery: { upsert: vi.fn(), create: vi.fn() },
|
|
teamChatMessage: {
|
|
findFirst: vi.fn().mockResolvedValue({ id: "message_1", authorUserId: context.userId }),
|
|
create: vi.fn(),
|
|
findMany: vi.fn().mockResolvedValue([]),
|
|
},
|
|
teamChatEvent: { findFirst: vi.fn().mockResolvedValue(null), create: vi.fn() },
|
|
teamChatPinnedMessage: { findFirst: vi.fn().mockResolvedValue(null), create: vi.fn(), delete: vi.fn(), findMany: vi.fn() },
|
|
teamChatReaction: { findFirst: vi.fn().mockResolvedValue(null), create: vi.fn(), delete: vi.fn(), findMany: vi.fn(), count: vi.fn().mockResolvedValue(0) },
|
|
teamChatThread: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn(), findMany: vi.fn() },
|
|
};
|
|
}
|
|
|
|
describe("chat message feature mutations", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mocks.publishWakeup.mockResolvedValue(undefined);
|
|
mocks.publishLinkPreviewRequest.mockResolvedValue(undefined);
|
|
mocks.publishAudit.mockResolvedValue(undefined);
|
|
mocks.logActivity.mockResolvedValue(undefined);
|
|
});
|
|
|
|
it("rechecks chat.write through the shared atomic repository gate", async () => {
|
|
const tx = txFixture();
|
|
tx.teamChatEvent.create.mockResolvedValue(
|
|
eventRow({
|
|
type: "reaction_added",
|
|
requestId: "request_reaction",
|
|
data: {
|
|
reaction: { id: "reaction_1", messageId: "message_1", userId: context.userId, emoji: "👍", reactedAt: "2026-07-16T09:00:00.000Z" },
|
|
},
|
|
})
|
|
);
|
|
tx.teamChatReaction.create.mockResolvedValue({ id: "reaction_1", reactedAt: new Date("2026-07-16T09:00:00.000Z") });
|
|
mocks.runChatRepositoryTransaction.mockImplementation(async (_input, permission, operation) => {
|
|
expect(permission).toBe(CHAT_PERMISSIONS.write);
|
|
return operation(tx, [CHAT_PERMISSIONS.write]);
|
|
});
|
|
|
|
const result = await setChatReaction({ ...context, requestId: "request_reaction", chatId: "chat_1", messageId: "message_1", emoji: "👍", active: true });
|
|
|
|
expect(result).toMatchObject({ changed: true, replayed: false, active: true });
|
|
expect(mocks.publishWakeup).toHaveBeenCalledWith(tx, { event: result.event });
|
|
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
|
tx,
|
|
expect.objectContaining({
|
|
action: "chat.message.reaction_added",
|
|
targetId: "message_1",
|
|
requestId: "request_reaction",
|
|
metadata: { chatId: "chat_1", emoji: "👍" },
|
|
})
|
|
);
|
|
});
|
|
|
|
it("rejects text disguised as an emoji before opening the repository transaction", async () => {
|
|
await expect(
|
|
setChatReaction({ ...context, requestId: "request_reaction", chatId: "chat_1", messageId: "message_1", emoji: "👍oops", active: true })
|
|
).rejects.toMatchObject({ code: "chat.invalid_input" });
|
|
expect(mocks.runChatRepositoryTransaction).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("strictly rejects pins in direct messages before touching a message", async () => {
|
|
const tx = txFixture();
|
|
tx.teamChat.findFirst.mockResolvedValue({ kind: "dm", eventStreamId: "stream_1" });
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
await expect(setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true })).rejects.toMatchObject({
|
|
code: "chat.pins_not_allowed_in_direct_messages",
|
|
});
|
|
expect(tx.teamChatMessage.findFirst).not.toHaveBeenCalled();
|
|
expect(tx.teamChatPinnedMessage.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a ninth distinct reaction for one user and message", async () => {
|
|
const tx = txFixture();
|
|
tx.teamChatReaction.count.mockResolvedValue(8);
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
await expect(
|
|
setChatReaction({ ...context, requestId: "request_reaction", chatId: "chat_1", messageId: "message_1", emoji: "👍", active: true })
|
|
).rejects.toMatchObject({ code: "chat.reaction_limit_reached" });
|
|
expect(tx.teamChatReaction.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("hides pinning from members who neither authored the message nor administer the channel", async () => {
|
|
const tx = txFixture();
|
|
tx.teamChatMessage.findFirst.mockResolvedValue({ id: "message_1", authorUserId: "user_2" });
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
await expect(setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true })).rejects.toMatchObject({
|
|
code: "foundation.not_found",
|
|
});
|
|
expect(tx.teamChatPinnedMessage.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("enforces the 50-pin channel limit while holding row locks", async () => {
|
|
const tx = txFixture();
|
|
tx.$queryRaw.mockResolvedValueOnce([{ id: "membership_1" }]).mockResolvedValueOnce(Array.from({ length: 50 }, (_, index) => ({ id: `pin_${index}` })));
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
await expect(setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true })).rejects.toMatchObject({
|
|
code: "chat.pin_limit_reached",
|
|
});
|
|
expect(tx.teamChatPinnedMessage.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("replays an identical pin request without a second write or audit", async () => {
|
|
const tx = txFixture();
|
|
tx.teamChatEvent.findFirst.mockResolvedValue(
|
|
eventRow({
|
|
type: "message_pin_changed",
|
|
requestId: "request_pin",
|
|
data: { messageId: "message_1", pinned: true, changedByUserId: context.userId },
|
|
})
|
|
);
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
const result = await setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true });
|
|
|
|
expect(result).toMatchObject({ pinned: true, replayed: true, changed: false });
|
|
expect(tx.teamChatPinnedMessage.create).not.toHaveBeenCalled();
|
|
expect(mocks.publishAudit).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects request-id payload drift", async () => {
|
|
const tx = txFixture();
|
|
tx.teamChatEvent.findFirst.mockResolvedValue(
|
|
eventRow({
|
|
type: "message_pin_changed",
|
|
requestId: "request_pin",
|
|
data: { messageId: "message_other", pinned: true, changedByUserId: context.userId },
|
|
})
|
|
);
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
await expect(setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true })).rejects.toMatchObject({
|
|
code: "foundation.idempotency_conflict",
|
|
});
|
|
});
|
|
|
|
it("creates exactly one level of replies and publishes the durable thread event atomically", async () => {
|
|
const tx = txFixture();
|
|
tx.teamChatMessage.findFirst.mockResolvedValueOnce(messageRow()).mockResolvedValueOnce(null);
|
|
tx.teamChatMessage.create.mockResolvedValue(messageRow({ id: "reply_1", clientMessageId: "client_reply", body: "Reply", parentMessageId: "message_1" }));
|
|
tx.teamChatThread.findFirst.mockResolvedValue(null);
|
|
tx.teamChatThread.create.mockResolvedValue({
|
|
id: "message_1",
|
|
parentMessageId: "message_1",
|
|
replyCount: 1,
|
|
lastReplyAt: new Date("2026-07-16T08:00:00.000Z"),
|
|
participantUserIds: [context.userId],
|
|
});
|
|
tx.teamChatEvent.create.mockImplementation(({ data }) =>
|
|
eventRow({ type: "thread_reply", requestId: "request_reply", data: data.data, entityId: "reply_1" })
|
|
);
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
const result = await sendChatThreadReply({
|
|
...context,
|
|
requestId: "request_reply",
|
|
chatId: "chat_1",
|
|
threadId: "message_1",
|
|
clientMessageId: "client_reply",
|
|
body: "Reply",
|
|
});
|
|
|
|
expect(tx.teamChatMessage.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ parentMessageId: "message_1" }) }));
|
|
expect(result).toMatchObject({ threadId: "message_1", replayed: false });
|
|
expect(mocks.publishWakeup).toHaveBeenCalledWith(tx, { event: result.event });
|
|
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
|
tx,
|
|
expect.objectContaining({ action: "chat.thread.reply_created", targetId: "reply_1", requestId: "request_reply" })
|
|
);
|
|
});
|
|
|
|
it("keeps a deleted thread starter readable as a tombstone and accepts new replies", async () => {
|
|
const tx = txFixture();
|
|
const deletedAt = new Date("2026-07-16T08:30:00.000Z");
|
|
tx.teamChatMessage.findFirst
|
|
.mockResolvedValueOnce(messageRow({ body: "", deletedAt, authorUserId: "user_parent" }))
|
|
.mockResolvedValueOnce(null);
|
|
tx.teamChatMessage.create.mockResolvedValue(
|
|
messageRow({ id: "reply_after_delete", clientMessageId: "client_after_delete", body: "Weiter im Thread", parentMessageId: "message_1" })
|
|
);
|
|
tx.teamChatThread.findFirst.mockResolvedValue({ id: "message_1", participantUserIds: ["user_parent"] });
|
|
tx.teamChatThread.update.mockResolvedValue({
|
|
id: "message_1",
|
|
parentMessageId: "message_1",
|
|
replyCount: 2,
|
|
lastReplyAt: new Date("2026-07-16T09:00:00.000Z"),
|
|
participantUserIds: [context.userId, "user_parent"],
|
|
});
|
|
tx.teamChatEvent.create.mockImplementation(({ data }) =>
|
|
eventRow({ type: "thread_reply", requestId: "request_after_delete", data: data.data, entityId: "reply_after_delete" })
|
|
);
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
const result = await sendChatThreadReply({
|
|
...context,
|
|
requestId: "request_after_delete",
|
|
chatId: "chat_1",
|
|
threadId: "message_1",
|
|
clientMessageId: "client_after_delete",
|
|
body: "Weiter im Thread",
|
|
});
|
|
|
|
const parentLookup = tx.teamChatMessage.findFirst.mock.calls[0]?.[0];
|
|
expect(parentLookup).toEqual(
|
|
expect.objectContaining({
|
|
where: expect.objectContaining({ chatId: "chat_1", parentMessageId: null, OR: [{ id: "message_1" }, { thread: { id: "message_1" } }] }),
|
|
})
|
|
);
|
|
expect(parentLookup.where).not.toHaveProperty("deletedAt");
|
|
expect(tx.teamChatMessage.create).toHaveBeenCalledWith(
|
|
expect.objectContaining({ data: expect.objectContaining({ parentMessageId: "message_1", body: "Weiter im Thread" }) })
|
|
);
|
|
expect(result).toMatchObject({ threadId: "message_1", replayed: false, message: { id: "reply_after_delete" } });
|
|
});
|
|
|
|
it("persists mentioned followers and lets direct mentions, but not ordinary replies, bypass mute", async () => {
|
|
const tx = txFixture();
|
|
tx.teamChat.findFirst.mockResolvedValue({
|
|
id: "chat_1",
|
|
kind: "project",
|
|
name: "P-100",
|
|
isPrivate: true,
|
|
eventStreamId: "stream_1",
|
|
projektId: "project_1",
|
|
});
|
|
tx.teamChatMessage.findFirst.mockResolvedValueOnce(messageRow({ authorUserId: "user_parent" })).mockResolvedValueOnce(null);
|
|
tx.teamChatMessage.create.mockResolvedValue(
|
|
messageRow({ id: "reply_1", clientMessageId: "client_reply", body: "Hallo <@user:user_mentioned>", parentMessageId: "message_1" })
|
|
);
|
|
tx.teamChatThread.findFirst.mockResolvedValue({ id: "message_1", participantUserIds: ["user_previous", "user_hidden"] });
|
|
tx.teamChatThread.update.mockResolvedValue({
|
|
id: "message_1",
|
|
parentMessageId: "message_1",
|
|
replyCount: 2,
|
|
lastReplyAt: new Date("2026-07-16T08:00:00.000Z"),
|
|
participantUserIds: [context.userId, "user_hidden", "user_mentioned", "user_parent", "user_previous"],
|
|
});
|
|
tx.teamChatMember.findMany
|
|
.mockResolvedValueOnce([{ userId: "user_mentioned" }])
|
|
.mockResolvedValueOnce([
|
|
{ userId: "user_parent", notificationPref: "all_messages" },
|
|
{ userId: "user_previous", notificationPref: "muted" },
|
|
{ userId: "user_mentioned", notificationPref: "muted" },
|
|
]);
|
|
tx.tenantUser.findMany.mockResolvedValue([
|
|
{ userId: "user_mentioned", user: { firstName: "Mia", lastName: "Mention", email: "mia@example.test" } },
|
|
]);
|
|
tx.teamChatEvent.create.mockImplementation(({ data }) =>
|
|
eventRow({ type: "thread_reply", requestId: "request_reply", data: data.data, entityId: "reply_1" })
|
|
);
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
await sendChatThreadReply({
|
|
...context,
|
|
requestId: "request_reply",
|
|
chatId: "chat_1",
|
|
threadId: "message_1",
|
|
clientMessageId: "client_reply",
|
|
body: "Hallo <@user:user_mentioned>",
|
|
});
|
|
|
|
expect(tx.teamChatThread.update).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
data: expect.objectContaining({ participantUserIds: [context.userId, "user_hidden", "user_mentioned", "user_parent", "user_previous"] }),
|
|
})
|
|
);
|
|
expect(tx.teamChatMember.findMany).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
where: expect.objectContaining({ tenantId: context.tenantId, chatId: "chat_1", leftAt: null }),
|
|
})
|
|
);
|
|
expect(tx.notificationDelivery.upsert).toHaveBeenCalledTimes(2);
|
|
expect(tx.notificationDelivery.upsert).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
create: expect.objectContaining({
|
|
userId: "user_parent",
|
|
channel: "IN_APP",
|
|
messageKey: "chat.notifications.threadReply",
|
|
payloadMetadata: {
|
|
deeplink: "/demo/chat/chat_1/thread/message_1?message=reply_1#message-reply_1",
|
|
chatId: "chat_1",
|
|
threadId: "message_1",
|
|
messageId: "reply_1",
|
|
},
|
|
}),
|
|
})
|
|
);
|
|
expect(tx.notificationDelivery.upsert).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
create: expect.objectContaining({
|
|
userId: "user_mentioned",
|
|
messageKey: "chat.notifications.mentioned",
|
|
}),
|
|
})
|
|
);
|
|
expect(tx.notificationDelivery.upsert).not.toHaveBeenCalledWith(expect.objectContaining({ create: expect.objectContaining({ userId: context.userId }) }));
|
|
expect(tx.notificationDelivery.upsert).not.toHaveBeenCalledWith(expect.objectContaining({ create: expect.objectContaining({ userId: "user_hidden" }) }));
|
|
expect(tx.notificationDelivery.upsert).not.toHaveBeenCalledWith(expect.objectContaining({ create: expect.objectContaining({ userId: "user_previous" }) }));
|
|
expect(mocks.logActivity).toHaveBeenCalledWith(expect.objectContaining({ activityType: "chat_message", subjectType: "project", subjectId: "project_1" }), {
|
|
client: tx,
|
|
});
|
|
});
|
|
|
|
it("lets direct-message thread replies bypass a muted channel preference", async () => {
|
|
const tx = txFixture();
|
|
tx.teamChat.findFirst.mockResolvedValue({
|
|
id: "chat_1",
|
|
kind: "dm",
|
|
name: null,
|
|
isPrivate: true,
|
|
eventStreamId: "stream_1",
|
|
projektId: null,
|
|
});
|
|
tx.teamChatMessage.findFirst.mockResolvedValueOnce(messageRow({ authorUserId: "user_parent" })).mockResolvedValueOnce(null);
|
|
tx.teamChatMessage.create.mockResolvedValue(
|
|
messageRow({ id: "reply_dm", clientMessageId: "client_reply_dm", body: "Reply", parentMessageId: "message_1" })
|
|
);
|
|
tx.teamChatThread.findFirst.mockResolvedValue({ id: "message_1", participantUserIds: ["user_parent"] });
|
|
tx.teamChatThread.update.mockResolvedValue({
|
|
id: "message_1",
|
|
parentMessageId: "message_1",
|
|
replyCount: 2,
|
|
lastReplyAt: new Date("2026-07-16T08:00:00.000Z"),
|
|
participantUserIds: [context.userId, "user_parent"],
|
|
});
|
|
tx.teamChatMember.findMany.mockResolvedValue([{ userId: "user_parent", notificationPref: "muted" }]);
|
|
tx.teamChatEvent.create.mockImplementation(({ data }) =>
|
|
eventRow({ type: "thread_reply", requestId: "request_dm_reply", data: data.data, entityId: "reply_dm" })
|
|
);
|
|
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
|
|
|
|
await sendChatThreadReply({
|
|
...context,
|
|
requestId: "request_dm_reply",
|
|
chatId: "chat_1",
|
|
threadId: "message_1",
|
|
clientMessageId: "client_reply_dm",
|
|
body: "Reply",
|
|
});
|
|
|
|
expect(tx.notificationDelivery.upsert).toHaveBeenCalledOnce();
|
|
expect(tx.notificationDelivery.upsert).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
create: expect.objectContaining({ userId: "user_parent", messageKey: "chat.notifications.directMessage" }),
|
|
})
|
|
);
|
|
});
|
|
});
|