Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,293 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
listChannels: vi.fn(),
getDetail: vi.fn(),
getAdministration: vi.fn(),
recordSession: vi.fn(),
archiveChannel: vi.fn(),
setMemberRole: vi.fn(),
removeMember: vi.fn(),
getAttachment: vi.fn(),
}));
vi.mock("@hivegrid/chat/audit.server", () => ({
listChatAuditChannels: mocks.listChannels,
getChatAuditChannelDetail: mocks.getDetail,
getChatAuditAdministration: mocks.getAdministration,
recordChatAuditSessionStarted: mocks.recordSession,
forceArchiveChatAuditChannel: mocks.archiveChannel,
forceSetChatAuditMemberRole: mocks.setMemberRole,
forceRemoveChatAuditMember: mocks.removeMember,
getChatAuditAttachmentDownload: mocks.getAttachment,
}));
import {
archiveChatAuditChannel,
loadChatAuditChannel,
loadChatAuditAttachment,
loadChatAuditOverview,
removeChatAuditMember,
setChatAuditMemberRole,
startChatAuditSession,
} from "./ChatAuditService.server";
const context = {
tenantId: "tenant-1",
userId: "admin-1",
tenantUserId: "tenant-user-1",
permissions: ["chat.read_all_channels"],
hasModule: true as const,
};
const session = {
id: "session-1",
tenantId: "tenant-1",
userId: "admin-1",
reason: "Kundenreklamation prüfen",
issuedAt: Date.parse("2026-07-16T10:00:00.000Z"),
expiresAt: Date.parse("2026-07-16T10:15:00.000Z"),
};
const labels = {
directMessage: "Direktnachricht",
unnamedGroup: "Gruppe",
unnamedProject: "Projekt",
unknownUser: "Unbekannt",
unknownMention: "Unbekannte Erwähnung",
};
describe("AK-P15b chat audit service", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.listChannels.mockResolvedValue([]);
mocks.getAdministration.mockResolvedValue({
channel: { id: "dm-1", kind: "dm", archivedAtIso: null },
canAdminister: true,
members: [
{ userId: "user-a", displayName: "Anna Adler", avatarUrl: null, roleInChat: "admin" },
{ userId: "user-b", displayName: "Ben Bauer", avatarUrl: null, roleInChat: "member" },
],
});
});
it("does not load tenant channels before a justified session exists", async () => {
const vm = await loadChatAuditOverview({ context, tenantSlug: "demo", session: null, labels });
expect(mocks.listChannels).not.toHaveBeenCalled();
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.requiresReason).toBe(true);
});
it("audits the overview read with the active reason session", async () => {
const vm = await loadChatAuditOverview({
context,
tenantSlug: "demo",
session,
requestId: "overview-read-1",
labels,
});
expect(mocks.listChannels).toHaveBeenCalledWith(
expect.objectContaining({
requestId: "overview-read-1",
auditSession: expect.objectContaining({
sessionId: "session-1",
reason: "Kundenreklamation prüfen",
}),
})
);
expect(vm.status).toBe("ready");
});
it("records the session reason with the canonical read-all permission boundary", async () => {
await startChatAuditSession({ context, session, requestId: "request-1" });
expect(mocks.recordSession).toHaveBeenCalledWith({
tenantId: "tenant-1",
userId: "admin-1",
permissions: ["chat.read_all_channels"],
requestId: "request-1",
auditSession: {
sessionId: "session-1",
reason: "Kundenreklamation prüfen",
expiresAtIso: "2026-07-16T10:15:00.000Z",
},
});
});
it("renders direct messages with the mandatory audit banner and no write affordance", async () => {
mocks.getDetail.mockResolvedValue(detailFixture());
const result = await loadChatAuditChannel({
context,
tenantSlug: "demo",
chatId: "dm-1",
session,
requestId: "open-1",
labels,
});
expect(mocks.getDetail).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant-1", chatId: "dm-1" }));
if (result.vm.status !== "ready") throw new Error("expected ready");
expect(result.vm.data.header).toMatchObject({
isAuditMode: true,
dmAuditBannerKey: "chat.audit.dmBanner",
title: "Anna Adler · Ben Bauer",
canManage: false,
settingsHref: null,
});
expect(result.vm.data.composer).toMatchObject({ enabled: false, canSend: false, disabledReasonKey: "chat.composer.auditReadOnly" });
expect(result.vm.data.messages[0]?.actions).toEqual({
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
});
expect(result.vm.data.messages[0]?.attachments[0]).toMatchObject({
downloadHref: "/demo/settings/chat/audit/dm-1/attachments/file-1/original",
previewHref: "/demo/settings/chat/audit/dm-1/attachments/file-1/preview",
});
if (result.administrationVm.status !== "ready") throw new Error("expected ready");
expect(result.administrationVm.data).toMatchObject({ canAdminister: true, canArchive: true });
});
it("keeps attachment delivery inside the active audit session", async () => {
mocks.getAttachment.mockResolvedValue({ fileId: "file-1", storageKey: "tenant/file-1" });
await loadChatAuditAttachment({
context,
chatId: "dm-1",
fileId: "file-1",
variant: "original",
session,
requestId: "download-1",
});
expect(mocks.getAttachment).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant-1",
userId: "admin-1",
chatId: "dm-1",
fileId: "file-1",
variant: "original",
requestId: "download-1",
auditSession: expect.objectContaining({ sessionId: "session-1", reason: session.reason }),
})
);
});
it("routes cleanup and force-member mutations through both admin permissions and the active reason", async () => {
const adminContext = { ...context, permissions: ["chat.read_own_channels", "chat.read_all_channels", "chat.admin"] };
await archiveChatAuditChannel({ context: adminContext, chatId: "dm-1", session, requestId: "archive-1" });
await setChatAuditMemberRole({
context: adminContext,
chatId: "dm-1",
memberUserId: "user-b",
roleInChat: "admin",
session,
requestId: "role-1",
});
await removeChatAuditMember({
context: adminContext,
chatId: "dm-1",
memberUserId: "user-b",
session,
requestId: "remove-1",
});
const reasonContext = {
tenantId: "tenant-1",
permissions: adminContext.permissions,
};
expect(mocks.archiveChannel).toHaveBeenCalledWith(
expect.objectContaining({
...reasonContext,
requestId: "archive-1",
auditSession: expect.objectContaining({ sessionId: "session-1", reason: "Kundenreklamation prüfen" }),
})
);
expect(mocks.setMemberRole).toHaveBeenCalledWith(
expect.objectContaining({
...reasonContext,
memberUserId: "user-b",
roleInChat: "admin",
requestId: "role-1",
auditSession: expect.objectContaining({ sessionId: "session-1", reason: "Kundenreklamation prüfen" }),
})
);
expect(mocks.removeMember).toHaveBeenCalledWith(
expect.objectContaining({
...reasonContext,
memberUserId: "user-b",
requestId: "remove-1",
auditSession: expect.objectContaining({ sessionId: "session-1", reason: "Kundenreklamation prüfen" }),
})
);
});
});
function detailFixture() {
return {
channel: {
id: "dm-1",
kind: "dm",
name: null,
description: null,
projektId: null,
isPrivate: true,
archivedAtIso: null,
lastMessageAtIso: "2026-07-16T09:00:00.000Z",
eventStreamId: "stream-1",
eventCursor: "stream-1:1",
member: {
roleInChat: "member",
notificationPreference: "muted",
lastReadMessageId: null,
lastReadAtIso: null,
isPinned: false,
canWrite: false,
},
memberCount: 2,
participants: [
{ userId: "user-a", displayName: "Anna Adler", avatarUrl: null },
{ userId: "user-b", displayName: "Ben Bauer", avatarUrl: null },
],
unreadCount: 0,
hasUnreadMention: false,
lastMessage: null,
},
messages: [
{
id: "message-1",
clientMessageId: "client-1",
authorUserId: "user-a",
body: "Vertrauliche Nachricht",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [],
attachmentIds: ["file-1"],
linkPreviews: [],
createdAt: "2026-07-16T09:00:00.000Z",
updatedAt: "2026-07-16T09:00:00.000Z",
editedAt: null,
deletedAt: null,
},
],
readReceipts: [],
messageFeatures: [],
attachments: [
{
messageId: "message-1",
fileId: "file-1",
displayName: "foto.png",
mimeType: "image/png",
sizeBytes: 42,
linkRole: "image",
previewStatus: "ready",
scanStatus: "clean",
},
],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream-1:1",
};
}
@@ -0,0 +1,290 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import {
forceArchiveChatAuditChannel,
forceRemoveChatAuditMember,
forceSetChatAuditMemberRole,
getChatAuditAdministration,
getChatAuditAttachmentDownload,
getChatAuditChannelDetail,
listChatAuditChannels,
recordChatAuditSessionStarted,
type ChatAuditAttachmentDownload,
type ChatAuditAttachmentVariant,
} from "@hivegrid/chat/audit.server";
import {
buildChatAuditAdministrationVM,
buildChatAuditOverviewVM,
buildChatChannelDetailVM,
type ChatAuditAdministrationVM,
type ChatAuditOverviewVM,
type ChatChannelDetailVM,
type ChatResolvedAuthorVM,
} from "@hivegrid/view-models";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
import { chatAuditAttachmentPath, chatAuditPath } from "../routes/chatRoutePaths";
import { buildChatResolvedAuthors, buildMemberChatChannelDetailVM } from "./chatViewModel.server";
import type { ChatAuditSession } from "./chatAuditSession.server";
export type ChatAuditLabels = Readonly<{
directMessage: string;
unnamedGroup: string;
unnamedProject: string;
unknownUser: string;
unknownMention: string;
}>;
export async function loadChatAuditOverview(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly session: ChatAuditSession | null;
readonly requestId?: string;
readonly labels: Pick<ChatAuditLabels, "directMessage" | "unnamedGroup" | "unnamedProject">;
}): Promise<ChatAuditOverviewVM> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readAllChannels);
const channels = input.session
? await listChatAuditChannels({
...repositoryContext(context),
requestId: input.requestId ?? crypto.randomUUID(),
auditSession: auditSessionContext(input.session),
})
: [];
return buildChatAuditOverviewVM({
canAdminister: context.permissions.includes(CHAT_PERMISSIONS.admin),
session: input.session
? {
id: input.session.id,
reason: input.session.reason,
expiresAtIso: new Date(input.session.expiresAt).toISOString(),
}
: null,
channels: channels.map((channel) => ({
id: channel.id,
kind: channel.kind,
title: resolveAuditTitle(channel, input.labels),
description: channel.description,
participantLabels: channel.participants.map((participant) => participant.displayName),
memberCount: channel.memberCount,
isPrivate: channel.isPrivate,
archivedAtIso: channel.archivedAtIso,
lastMessageAtIso: channel.lastMessageAtIso,
detailHref: `${chatAuditPath(input.tenantSlug)}/${encodeURIComponent(channel.id)}`,
})),
});
}
export async function startChatAuditSession(input: {
readonly context: ChatRouteContext;
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<void> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readAllChannels);
await recordChatAuditSessionStarted({
...repositoryContext(context),
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
export async function loadChatAuditChannel(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly session: ChatAuditSession;
readonly requestId: string;
readonly beforeMessageCursor?: string;
readonly labels: ChatAuditLabels;
}): Promise<{
readonly vm: ChatChannelDetailVM;
readonly administrationVm: ChatAuditAdministrationVM;
readonly authors: readonly ChatResolvedAuthorVM[];
}> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readAllChannels);
const [detail, administration] = await Promise.all([
getChatAuditChannelDetail({
...repositoryContext(context),
chatId: input.chatId,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
...(input.beforeMessageCursor ? { beforeMessageCursor: input.beforeMessageCursor } : {}),
}),
getChatAuditAdministration({ ...repositoryContext(context), chatId: input.chatId }),
]);
const baseVm = buildMemberChatChannelDetailVM({
detail,
tenantSlug: input.tenantSlug,
currentUserId: context.userId,
permissions: [],
nowIso: new Date().toISOString(),
labels: input.labels,
});
const title = resolveAuditTitle(detail.channel, input.labels);
const administrationVm = buildChatAuditAdministrationVM({
channel: {
id: administration.channel.id,
kind: administration.channel.kind,
title,
archivedAtIso: administration.channel.archivedAtIso,
},
canAdminister: administration.canAdminister,
members: administration.members,
});
if (baseVm.status !== "ready") return { vm: baseVm, administrationVm, authors: [] };
const auditedMessages = baseVm.data.messages.map((message) => ({
...message,
attachments: message.attachments.map((attachment) => ({
...attachment,
downloadHref: chatAuditAttachmentPath(input.tenantSlug, input.chatId, attachment.fileId, "original"),
previewHref: attachment.previewHref ? chatAuditAttachmentPath(input.tenantSlug, input.chatId, attachment.fileId, "preview") : null,
})),
}));
const vm = buildChatChannelDetailVM({
header: {
...baseVm.data.header,
title,
avatar: { imageUrl: null, fallbackLabel: initials(title) },
isAuditMode: true,
canManage: false,
settingsHref: null,
searchHref: chatAuditPath(input.tenantSlug),
},
messages: auditedMessages,
pinnedMessages: baseVm.data.pinnedMessages,
typingLabels: [],
history: baseVm.data.history,
composer: {
...baseVm.data.composer,
canSend: false,
canAttachFiles: false,
canRecordVoice: false,
canMention: false,
canMarkAsTask: false,
disabledReasonKey: "chat.composer.auditReadOnly",
},
connection: { ...baseVm.data.connection, state: "blocked", reconnectAttempt: 0, retryAtIso: null },
});
return {
vm,
administrationVm,
authors: buildChatResolvedAuthors(detail.channel.participants, context.userId),
};
}
export async function loadChatAuditAttachment(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly fileId: string;
readonly variant: ChatAuditAttachmentVariant;
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<ChatAuditAttachmentDownload> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readAllChannels);
return getChatAuditAttachmentDownload({
...repositoryContext(context),
chatId: input.chatId,
fileId: input.fileId,
variant: input.variant,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
export async function archiveChatAuditChannel(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<void> {
const context = requireChatAuditAdministrator(input.context);
await forceArchiveChatAuditChannel({
...repositoryContext(context),
chatId: input.chatId,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
export async function setChatAuditMemberRole(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly memberUserId: string;
readonly roleInChat: "admin" | "member";
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<void> {
const context = requireChatAuditAdministrator(input.context);
await forceSetChatAuditMemberRole({
...repositoryContext(context),
chatId: input.chatId,
memberUserId: input.memberUserId,
roleInChat: input.roleInChat,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
export async function removeChatAuditMember(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly memberUserId: string;
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<void> {
const context = requireChatAuditAdministrator(input.context);
await forceRemoveChatAuditMember({
...repositoryContext(context),
chatId: input.chatId,
memberUserId: input.memberUserId,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
function requireChatAuditAdministrator(context: ChatRouteContext): ChatRouteContext {
return requireChatPermission(requireChatPermission(context, CHAT_PERMISSIONS.readAllChannels), CHAT_PERMISSIONS.admin);
}
function repositoryContext(context: ChatRouteContext) {
return { tenantId: context.tenantId, userId: context.userId, permissions: context.permissions };
}
function auditSessionContext(session: ChatAuditSession) {
return {
sessionId: session.id,
reason: session.reason,
expiresAtIso: new Date(session.expiresAt).toISOString(),
};
}
function resolveAuditTitle(
channel: {
readonly kind: "project" | "group" | "dm";
readonly name: string | null;
readonly participants: readonly { readonly displayName: string }[];
},
labels: Pick<ChatAuditLabels, "directMessage" | "unnamedGroup" | "unnamedProject">
): string {
const name = channel.name?.trim();
if (name) return name;
if (channel.kind === "dm") {
return (
channel.participants
.map((participant) => participant.displayName.trim())
.filter(Boolean)
.join(" · ") || labels.directMessage
);
}
return channel.kind === "project" ? labels.unnamedProject : labels.unnamedGroup;
}
function initials(label: string): string {
return (
label
.trim()
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0]?.toLocaleUpperCase() ?? "")
.join("") || "?"
);
}
@@ -0,0 +1,156 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
tenantUserFindMany: vi.fn(),
groupFindMany: vi.fn(),
createGroupChat: vi.fn(),
getOrCreateDirectMessage: vi.fn(),
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: vi.fn(async (_tenantId: string, operation: (tx: unknown) => Promise<unknown>) =>
operation({ tenantUser: { findMany: mocks.tenantUserFindMany }, group: { findMany: mocks.groupFindMany } })
),
}));
vi.mock("@hivegrid/chat/lifecycle.server", () => ({
createGroupChat: mocks.createGroupChat,
getOrCreateDirectMessage: mocks.getOrCreateDirectMessage,
}));
import { createChatChannel, loadChatChannelCreatePage } from "./ChatChannelCreateService.server";
const context = {
tenantId: "tenant_1",
userId: "user_current",
tenantUserId: "tenant_user_current",
permissions: ["chat.create_channel", "chat.create_dm"],
hasModule: true as const,
};
describe("AK-P15b chat channel create service", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tenantUserFindMany.mockResolvedValue([
{
userId: "user_current",
user: { email: "raffael@example.test", firstName: "Raffael", lastName: "Sheikh", avatar: null },
},
{
userId: "user_mara",
user: { email: "mara@example.test", firstName: "Mara", lastName: "Klein", avatar: " https://example.test/mara.png " },
},
]);
mocks.groupFindMany.mockResolvedValue([
{
id: "group_south",
name: "Team Süd",
description: "Montage",
users: [{ userId: "user_mara" }],
},
]);
mocks.createGroupChat.mockResolvedValue({ chatId: "chat_group" });
mocks.getOrCreateDirectMessage.mockResolvedValue({ chatId: "chat_dm", dmPairKey: "pair", created: true });
});
it("loads only active tenant users inside tenant RLS and excludes the viewer from options", async () => {
const vm = await loadChatChannelCreatePage({ context, requestedMode: "group" });
expect(mocks.tenantUserFindMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
status: 2,
user: { active: true, pendingDeletion: false, pseudonymized: false },
},
select: {
userId: true,
user: { select: { email: true, firstName: true, lastName: true, avatar: true } },
},
orderBy: [{ user: { firstName: "asc" } }, { user: { lastName: "asc" } }, { user: { email: "asc" } }],
});
expect(mocks.groupFindMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
select: {
id: true,
name: true,
description: true,
users: {
where: {
user: {
active: true,
pendingDeletion: false,
pseudonymized: false,
tenants: { some: { tenantId: "tenant_1", status: 2 } },
},
},
select: { userId: true },
},
},
orderBy: [{ name: "asc" }, { id: "asc" }],
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") throw new Error("fixture must be ready");
expect(vm.data.userOptions).toEqual([
{
userId: "user_mara",
displayName: "Mara Klein",
email: "mara@example.test",
avatar: { imageUrl: "https://example.test/mara.png", fallbackLabel: "MK" },
isCurrentUser: false,
},
]);
expect(vm.data.groupOptions).toEqual([
{ groupId: "group_south", name: "Team Süd", description: "Montage", memberCount: 1 },
]);
});
it("passes group privacy and initial members into the atomic lifecycle", async () => {
await expect(
createChatChannel({
context,
requestId: "request_group",
submission: {
mode: "group",
name: "Montage Nord",
description: "Abstimmung",
privacy: "private",
initialUserIds: ["user_mara"],
initialGroupIds: ["group_south"],
syncGroupMembership: true,
},
})
).resolves.toEqual({ chatId: "chat_group" });
expect(mocks.createGroupChat).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_current",
permissions: context.permissions,
requestId: "request_group",
name: "Montage Nord",
description: "Abstimmung",
isPrivate: true,
notificationDefault: "all_messages",
initialMemberUserIds: ["user_mara"],
initialGroupIds: ["group_south"],
syncGroupMembership: true,
});
});
it("uses the canonical get-or-create lifecycle for direct messages", async () => {
await expect(
createChatChannel({
context,
requestId: "request_dm",
submission: { mode: "dm", peerUserId: "user_mara" },
})
).resolves.toEqual({ chatId: "chat_dm", dmPairKey: "pair", created: true });
expect(mocks.getOrCreateDirectMessage).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_current",
permissions: context.permissions,
requestId: "request_dm",
peerUserId: "user_mara",
});
});
});
@@ -0,0 +1,158 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { createGroupChat, getOrCreateDirectMessage } from "@hivegrid/chat/lifecycle.server";
import { withTenantScope } from "@hivegrid/foundation";
import {
buildChatChannelCreateVM,
type ChatChannelCreateMode,
type ChatChannelCreateSubmission,
type ChatChannelCreateVM,
type ChatPermissionGroupOptionInput,
type ChatTenantUserOptionInput,
} from "@hivegrid/view-models";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { chatHasPermission, requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
export async function loadChatChannelCreatePage(input: {
readonly context: ChatRouteContext;
readonly requestedMode?: ChatChannelCreateMode;
}): Promise<ChatChannelCreateVM> {
const permissions = {
canCreateGroup: chatHasPermission(input.context, CHAT_PERMISSIONS.createChannel),
canCreateDm: chatHasPermission(input.context, CHAT_PERMISSIONS.createDm),
};
const options =
permissions.canCreateGroup || permissions.canCreateDm
? await loadChatChannelCreateOptions(input.context, permissions.canCreateGroup)
: { tenantUsers: [], tenantGroups: [] };
return buildChatChannelCreateVM({
currentUserId: input.context.userId,
tenantUsers: options.tenantUsers,
tenantGroups: options.tenantGroups,
permissions,
requestedMode: input.requestedMode,
});
}
export async function createChatChannel(input: {
readonly context: ChatRouteContext;
readonly requestId: string;
readonly submission: ChatChannelCreateSubmission;
}): Promise<{ readonly chatId: string }> {
if (input.submission.mode === "group") {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.createChannel);
return createGroupChat({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
requestId: input.requestId,
name: input.submission.name,
description: input.submission.description,
isPrivate: input.submission.privacy === "private",
notificationDefault: "all_messages",
initialMemberUserIds: input.submission.initialUserIds,
initialGroupIds: input.submission.initialGroupIds,
syncGroupMembership: input.submission.syncGroupMembership,
});
}
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.createDm);
return getOrCreateDirectMessage({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
requestId: input.requestId,
peerUserId: input.submission.peerUserId,
});
}
async function loadChatChannelCreateOptions(
context: ChatRouteContext,
includeGroups: boolean
): Promise<Readonly<{ tenantUsers: readonly ChatTenantUserOptionInput[]; tenantGroups: readonly ChatPermissionGroupOptionInput[] }>> {
const { memberships, groups } = await withTenantRLS(context.tenantId, async (tx) => {
const membershipsPromise = tx.tenantUser.findMany({
where: {
tenantId: context.tenantId,
status: TenantUserStatus.ACTIVE,
user: {
active: true,
pendingDeletion: false,
pseudonymized: false,
},
},
select: {
userId: true,
user: {
select: {
email: true,
firstName: true,
lastName: true,
avatar: true,
},
},
},
orderBy: [{ user: { firstName: "asc" } }, { user: { lastName: "asc" } }, { user: { email: "asc" } }],
});
const groupsPromise = includeGroups
? tx.group.findMany({
where: withTenantScope(context.tenantId, {}),
select: {
id: true,
name: true,
description: true,
users: {
where: {
user: {
active: true,
pendingDeletion: false,
pseudonymized: false,
tenants: { some: withTenantScope(context.tenantId, { status: TenantUserStatus.ACTIVE }) },
},
},
select: { userId: true },
},
},
orderBy: [{ name: "asc" }, { id: "asc" }],
})
: Promise.resolve([]);
const [memberships, groups] = await Promise.all([membershipsPromise, groupsPromise]);
return { memberships, groups };
});
const tenantUsers = memberships.map(({ userId, user }) => {
const displayName =
[user.firstName, user.lastName]
.map((part) => part?.trim())
.filter((part): part is string => Boolean(part))
.join(" ") || user.email;
const fallbackLabel =
[user.firstName?.trim().slice(0, 1), user.lastName?.trim().slice(0, 1)]
.filter((part): part is string => Boolean(part))
.join("")
.toLocaleUpperCase() ||
user.email.slice(0, 1).toLocaleUpperCase() ||
"?";
return {
userId,
displayName,
email: user.email,
avatar: {
imageUrl: user.avatar?.trim() || null,
fallbackLabel,
},
};
});
const tenantGroups = groups.map((group) => ({
groupId: group.id,
name: group.name,
description: group.description,
memberCount: group.users.length,
}));
return { tenantUsers, tenantGroups };
}
@@ -0,0 +1,173 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadSettings: vi.fn(),
setMember: vi.fn(),
removeMember: vi.fn(),
setPrivacy: vi.fn(),
leave: vi.fn(),
archive: vi.fn(),
projectFindFirst: vi.fn(),
}));
vi.mock("@hivegrid/chat/channel-settings.server", () => ({ loadChatChannelSettings: mocks.loadSettings }));
vi.mock("@hivegrid/chat/lifecycle.server", () => ({
setChatChannelMember: mocks.setMember,
removeChatChannelMember: mocks.removeMember,
setGroupChatPrivacy: mocks.setPrivacy,
leaveGroupChat: mocks.leave,
archiveChatChannel: mocks.archive,
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: vi.fn((_tenantId: string, operation: (tx: unknown) => Promise<unknown>) =>
operation({ projekt: { findFirst: mocks.projectFindFirst } })
),
}));
import {
addChatChannelMember,
archiveChatChannel,
changeChatChannelMemberRole,
changeChatChannelPrivacy,
leaveChatChannel,
loadChatChannelSettingsPage,
removeChatChannelMember,
} from "./ChatChannelSettingsService.server";
const context = {
tenantId: "tenant_1",
userId: "user_current",
tenantUserId: "tenant_user_current",
permissions: ["chat.read_own_channels"],
hasModule: true as const,
};
const labels = {
directMessage: "Direktnachricht",
unnamedGroup: "Gruppe",
unnamedProject: "Projekt",
unknownProjectStage: "Unbekannte Phase",
};
function profile(userId: string, displayName: string) {
return { userId, displayName, email: `${userId}@example.test`, avatarUrl: null };
}
function settingsRecord(kind: "group" | "dm" | "project" = "group") {
return {
channel: {
id: "chat_1",
kind,
name: kind === "group" ? "Montage" : null,
description: null,
privacy: kind === "group" ? ("private" as const) : null,
archivedAtIso: null,
projectId: kind === "project" ? "project_1" : null,
},
members: [
{
...profile("user_current", "Raffael Sheikh"),
roleInChat: "admin" as const,
joinedAtIso: "2026-07-15T10:00:00.000Z",
joinedViaUserId: null,
writeRevokedAtIso: null,
provenance: {
isManualMember: kind !== "dm",
manualRoleInChat: kind !== "dm" ? ("admin" as const) : null,
isProjectManaged: kind === "project",
projectRoleInChat: kind === "project" ? ("admin" as const) : null,
isGroupManaged: false,
},
},
{
...profile("user_peer", "Mara Klein"),
roleInChat: "member" as const,
joinedAtIso: "2026-07-15T10:00:00.000Z",
joinedViaUserId: null,
writeRevokedAtIso: null,
provenance: {
isManualMember: kind === "group",
manualRoleInChat: kind === "group" ? ("member" as const) : null,
isProjectManaged: kind === "project",
projectRoleInChat: kind === "project" ? ("member" as const) : null,
isGroupManaged: false,
},
},
],
candidateUsers: kind === "group" ? [profile("user_candidate", "Ada Lovelace")] : [],
capabilities: {
canManageMembers: kind === "group",
canManageAdmins: kind === "group",
canChangePrivacy: kind === "group",
canManageManualGuests: kind === "project",
canArchive: kind !== "dm",
canLeave: false,
isReadOnly: kind !== "group",
},
};
}
describe("AK-P15b chat channel settings service", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadSettings.mockResolvedValue(settingsRecord());
});
it("maps the RLS-scoped group record to the pure settings VM", async () => {
const vm = await loadChatChannelSettingsPage({ context, tenantSlug: "demo", chatId: "chat_1", labels });
expect(mocks.loadSettings).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_current",
permissions: context.permissions,
chatId: "chat_1",
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") throw new Error("fixture must be ready");
expect(vm.data.channel).toMatchObject({ title: "Montage", privacy: "private", isArchived: false });
expect(vm.data.members.map(({ displayName }) => displayName)).toEqual(["Raffael Sheikh", "Mara Klein"]);
expect(vm.data.candidateUsers.map(({ displayName }) => displayName)).toEqual(["Ada Lovelace"]);
});
it("resolves project metadata inside tenant RLS and keeps project membership read-only", async () => {
mocks.loadSettings.mockResolvedValue(settingsRecord("project"));
mocks.projectFindFirst.mockResolvedValue({
id: "project_1",
projektNummer: "P-42",
projektname: "Wärmepumpe Klein",
stage: { name: "Montage" },
});
const vm = await loadChatChannelSettingsPage({ context, tenantSlug: "demo", chatId: "chat_1", labels });
expect(mocks.projectFindFirst).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: "tenant_1", id: "project_1" } }));
expect(vm.status).toBe("ready");
if (vm.status !== "ready") throw new Error("fixture must be ready");
expect(vm.data.channel.project).toEqual({
id: "project_1",
number: "P-42",
label: "Wärmepumpe Klein",
stageLabel: "Montage",
href: "/demo/projects/project_1",
});
expect(vm.data.infoKey).toBe("chat.channelSettings.project.managedExternally");
expect(vm.data.permissions).toMatchObject({ canManageManualGuests: true, canArchive: true });
});
it("delegates group settings mutations with tenant context and stable request ids", async () => {
const base = { context, chatId: "chat_1", requestId: "request_1" };
await addChatChannelMember({ ...base, memberUserId: "user_new" });
await changeChatChannelMemberRole({ ...base, memberUserId: "user_new", roleInChat: "admin" });
await removeChatChannelMember({ ...base, memberUserId: "user_new" });
await changeChatChannelPrivacy({ ...base, privacy: "public" });
await leaveChatChannel(base);
await archiveChatChannel(base);
const repositoryContext = { tenantId: "tenant_1", userId: "user_current", permissions: context.permissions };
expect(mocks.setMember).toHaveBeenNthCalledWith(1, { ...repositoryContext, chatId: "chat_1", requestId: "request_1", memberUserId: "user_new", roleInChat: "member" });
expect(mocks.setMember).toHaveBeenNthCalledWith(2, { ...repositoryContext, chatId: "chat_1", requestId: "request_1", memberUserId: "user_new", roleInChat: "admin" });
expect(mocks.removeMember).toHaveBeenCalledWith({ ...repositoryContext, chatId: "chat_1", requestId: "request_1", memberUserId: "user_new" });
expect(mocks.setPrivacy).toHaveBeenCalledWith({ ...repositoryContext, chatId: "chat_1", requestId: "request_1", isPrivate: false });
expect(mocks.leave).toHaveBeenCalledWith({ ...repositoryContext, chatId: "chat_1", requestId: "request_1" });
expect(mocks.archive).toHaveBeenCalledWith({ ...repositoryContext, chatId: "chat_1", requestId: "request_1" });
});
});
@@ -0,0 +1,186 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { loadChatChannelSettings, type ChatChannelSettingsRecord } from "@hivegrid/chat/channel-settings.server";
import {
archiveChatChannel as archiveManagedChatChannel,
leaveGroupChat,
removeChatChannelMember as removeManagedChatChannelMember,
setChatChannelMember,
setGroupChatPrivacy,
} from "@hivegrid/chat/lifecycle.server";
import { buildChatChannelSettingsVM, type ChatChannelSettingsVM } from "@hivegrid/view-models";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { projectDetailPath } from "~/utils/integrations/projects/projectRoutePaths";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
export type ChatChannelSettingsLabels = Readonly<{
directMessage: string;
unnamedGroup: string;
unnamedProject: string;
unknownProjectStage: string;
}>;
export async function loadChatChannelSettingsPage(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly labels: ChatChannelSettingsLabels;
}): Promise<ChatChannelSettingsVM> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
const record = await loadChatChannelSettings({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
});
const project = record.channel.projectId
? await loadProjectSummary(context.tenantId, input.tenantSlug, record.channel.projectId, input.labels)
: null;
return buildChatChannelSettingsVM({
currentUserId: context.userId,
channel: {
id: record.channel.id,
kind: record.channel.kind,
title: channelTitle(record, context.userId, project?.label ?? null, input.labels),
description: record.channel.description,
isPrivate: record.channel.privacy !== "public",
isArchived: record.channel.archivedAtIso !== null,
project,
},
members: record.members.map((member) => ({
user: profileInput(member),
role: member.roleInChat,
isProjectManaged: member.provenance.isProjectManaged,
isManualGuest: member.provenance.isManualMember,
manualRole: member.provenance.manualRoleInChat,
})),
tenantUsers: record.candidateUsers.map(profileInput),
permissions: {
canManageMembers: record.capabilities.canManageMembers,
canManageAdmins: record.capabilities.canManageAdmins,
canChangePrivacy: record.capabilities.canChangePrivacy,
canLeave: record.capabilities.canLeave,
canManageManualGuests: record.capabilities.canManageManualGuests,
canArchive: record.capabilities.canArchive,
},
});
}
export async function addChatChannelMember(input: MutationInput & { readonly memberUserId: string }): Promise<void> {
await setChatChannelMember({ ...repositoryContext(input.context), chatId: input.chatId, requestId: input.requestId, memberUserId: input.memberUserId, roleInChat: "member" });
}
export async function changeChatChannelMemberRole(
input: MutationInput & { readonly memberUserId: string; readonly roleInChat: "admin" | "member" }
): Promise<void> {
await setChatChannelMember({
...repositoryContext(input.context),
chatId: input.chatId,
requestId: input.requestId,
memberUserId: input.memberUserId,
roleInChat: input.roleInChat,
});
}
export async function removeChatChannelMember(input: MutationInput & { readonly memberUserId: string }): Promise<void> {
await removeManagedChatChannelMember({
...repositoryContext(input.context),
chatId: input.chatId,
requestId: input.requestId,
memberUserId: input.memberUserId,
});
}
export async function changeChatChannelPrivacy(input: MutationInput & { readonly privacy: "public" | "private" }): Promise<void> {
await setGroupChatPrivacy({
...repositoryContext(input.context),
chatId: input.chatId,
requestId: input.requestId,
isPrivate: input.privacy === "private",
});
}
export async function leaveChatChannel(input: MutationInput): Promise<void> {
await leaveGroupChat({ ...repositoryContext(input.context), chatId: input.chatId, requestId: input.requestId });
}
export async function archiveChatChannel(input: MutationInput): Promise<void> {
await archiveManagedChatChannel({ ...repositoryContext(input.context), chatId: input.chatId, requestId: input.requestId });
}
type MutationInput = Readonly<{
context: ChatRouteContext;
chatId: string;
requestId: string;
}>;
function repositoryContext(context: ChatRouteContext) {
return { tenantId: context.tenantId, userId: context.userId, permissions: context.permissions };
}
function profileInput(profile: {
readonly userId: string;
readonly displayName: string;
readonly email: string;
readonly avatarUrl: string | null;
}) {
return {
userId: profile.userId,
displayName: profile.displayName,
email: profile.email,
avatar: {
imageUrl: profile.avatarUrl,
fallbackLabel: fallbackLabel(profile.displayName, profile.email),
},
};
}
function fallbackLabel(displayName: string, email: string): string {
const initials = displayName
.split(/\s+/u)
.filter(Boolean)
.slice(0, 2)
.map((part) => part.slice(0, 1))
.join("")
.toLocaleUpperCase();
return initials || email.slice(0, 1).toLocaleUpperCase() || "?";
}
function channelTitle(
record: ChatChannelSettingsRecord,
currentUserId: string,
projectLabel: string | null,
labels: ChatChannelSettingsLabels
): string {
if (record.channel.kind === "group") return record.channel.name ?? labels.unnamedGroup;
if (record.channel.kind === "project") return projectLabel ?? record.channel.name ?? labels.unnamedProject;
return record.members.find((member) => member.userId !== currentUserId)?.displayName ?? labels.directMessage;
}
async function loadProjectSummary(
tenantId: string,
tenantSlug: string,
projectId: string,
labels: ChatChannelSettingsLabels
) {
const project = await withTenantRLS(tenantId, (tx) =>
tx.projekt.findFirst({
where: { tenantId, id: projectId },
select: {
id: true,
projektNummer: true,
projektname: true,
stage: { select: { name: true } },
},
})
);
return {
id: projectId,
number: project?.projektNummer ?? projectId,
label: project?.projektname?.trim() || labels.unnamedProject,
stageLabel: project?.stage.name?.trim() || labels.unknownProjectStage,
href: projectDetailPath(tenantSlug, projectId),
};
}
@@ -0,0 +1,29 @@
import { describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ list: vi.fn() }));
vi.mock("@hivegrid/chat/mentions.server", () => ({ listChatMentionSuggestions: mocks.list }));
import { loadChatMentionSuggestions } from "./ChatMentionsService.server";
describe("loadChatMentionSuggestions", () => {
it("passes the route identity to the fresh repository and returns the pure grouped VM", async () => {
mocks.list.mockResolvedValue([
{ type: "user", id: "user_1", label: "Raffael", detail: "raffael@example.test" },
{ type: "project", id: "project_1", label: "P-100", detail: "P-100" },
]);
const context = {
tenantId: "tenant_1",
tenantUserId: "tenant_user_1",
userId: "user_1",
permissions: ["chat.read_own_channels"],
hasModule: true as const,
};
const vm = await loadChatMentionSuggestions({ context, tenantSlug: "acme", chatId: "chat_1", query: "ra", type: null });
expect(mocks.list).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", chatId: "chat_1", query: "ra", limit: 10 })
);
expect(vm.groups.map((group) => group.kind)).toEqual(["user", "project"]);
});
});
@@ -0,0 +1,31 @@
import { listChatMentionSuggestions, type ChatMentionSuggestion } from "@hivegrid/chat/mentions.server";
import { buildChatMentionAutocompleteVM, type ChatMentionAutocompleteVM } from "@hivegrid/view-models";
import type { ChatRouteContext } from "../routes/chatAccess.server";
export async function loadChatMentionSuggestions(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly query: string;
readonly type: ChatMentionSuggestion["type"] | null;
}): Promise<ChatMentionAutocompleteVM> {
const suggestions = await listChatMentionSuggestions({
tenantId: input.context.tenantId,
userId: input.context.userId,
permissions: input.context.permissions,
chatId: input.chatId,
query: input.query,
type: input.type,
limit: 10,
});
return buildChatMentionAutocompleteVM({
tenantSlug: input.tenantSlug,
suggestions: suggestions.map((suggestion) => ({
kind: suggestion.type,
id: suggestion.id,
label: suggestion.label,
detail: suggestion.detail,
})),
});
}
@@ -0,0 +1,109 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
const mocks = vi.hoisted(() => ({ list: vi.fn() }));
vi.mock("@hivegrid/chat/message-discovery.server", () => ({
listChatMessageDiscovery: (...args: unknown[]) => mocks.list(...args),
}));
import { loadChatMessageDiscovery } from "./ChatMessageDiscoveryService.server";
const context = {
tenantId: "tenant_1",
userId: "viewer_1",
tenantUserId: "tenant_user_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
hasModule: true,
} as const;
const labels = {
directMessage: "Direct message",
unnamedGroup: "Unnamed group",
unnamedProject: "Project chat",
unknownUser: "Unknown user",
} as const;
describe("ChatMessageDiscoveryService", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.list.mockResolvedValue({ messages: [], nextCursor: null });
});
it("maps repository records to pure VM rows and resolves a DM counterpart", async () => {
mocks.list.mockResolvedValue({
nextCursor: "cursor_1",
messages: [
{
id: "message_1",
chatId: "chat_dm",
channelKind: "dm",
channelName: null,
projectId: null,
authorUserId: "peer_1",
body: "Heat pump update",
parentMessageId: null,
createdAtIso: "2026-07-16T11:00:00.000Z",
participants: [
{ userId: "viewer_1", displayName: "Raffael Sheikh", avatarUrl: null },
{ userId: "peer_1", displayName: "Ada Lovelace", avatarUrl: "/avatars/ada" },
],
},
],
});
const vm = await loadChatMessageDiscovery({ context, tenantSlug: "demo", mode: "search", query: "heat", labels });
expect(mocks.list).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "viewer_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
mode: "search",
query: "heat",
});
expect(vm).toMatchObject({
status: "ready",
data: {
nextCursor: "cursor_1",
rows: [
{
channelTitle: "Ada Lovelace",
authorLabel: "Ada Lovelace",
authorAvatar: { imageUrl: "/avatars/ada", fallbackLabel: "AL" },
detailHref: "/demo/chat/chat_dm?message=message_1#message-message_1",
},
],
},
});
});
it("uses localized fallbacks without exposing unresolved identities", async () => {
mocks.list.mockResolvedValue({
nextCursor: null,
messages: [
{
id: "message_2",
chatId: "chat_project",
channelKind: "project",
channelName: null,
projectId: "project_1",
authorUserId: "former_user",
body: "Archived author stays readable",
parentMessageId: "parent_1",
createdAtIso: "2026-07-16T10:00:00.000Z",
participants: [],
},
],
});
const vm = await loadChatMessageDiscovery({ context, tenantSlug: "demo", mode: "mentions", labels });
expect(vm.status === "ready" && vm.data.rows[0]).toMatchObject({
channelTitle: "Project chat",
authorLabel: "Unknown user",
authorAvatar: { fallbackLabel: "UU" },
isThreadReply: true,
detailHref: "/demo/chat/chat_project/thread/parent_1?message=message_2#message-message_2",
});
});
});
@@ -0,0 +1,86 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { buildChatMessageDeepLink } from "@hivegrid/chat/deep-links";
import { listChatMessageDiscovery, type ChatMessageDiscoveryRecord } from "@hivegrid/chat/message-discovery.server";
import { buildChatMessageDiscoveryVM, type ChatMessageDiscoveryMode, type ChatMessageDiscoveryVM } from "@hivegrid/view-models";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
import { chatIndexPath, chatMentionsPath, chatSearchPath } from "../routes/chatRoutePaths";
export type ChatMessageDiscoveryLabels = Readonly<{
directMessage: string;
unnamedGroup: string;
unnamedProject: string;
unknownUser: string;
}>;
export async function loadChatMessageDiscovery(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly mode: ChatMessageDiscoveryMode;
readonly query?: string;
readonly beforeCursor?: string;
readonly limit?: number;
readonly labels: ChatMessageDiscoveryLabels;
}): Promise<ChatMessageDiscoveryVM> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
const result = await listChatMessageDiscovery({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
mode: input.mode,
...(input.query !== undefined ? { query: input.query } : {}),
...(input.beforeCursor ? { beforeCursor: input.beforeCursor } : {}),
...(input.limit !== undefined ? { limit: input.limit } : {}),
});
return buildChatMessageDiscoveryVM({
mode: input.mode,
query: input.query,
nextCursor: result.nextCursor,
hrefs: {
chat: chatIndexPath(input.tenantSlug),
search: chatSearchPath(input.tenantSlug),
mentions: chatMentionsPath(input.tenantSlug),
},
rows: result.messages.map((message) => toRow(message, context.userId, input.tenantSlug, input.labels)),
});
}
function toRow(message: ChatMessageDiscoveryRecord, currentUserId: string, tenantSlug: string, labels: ChatMessageDiscoveryLabels) {
const author = message.participants.find((participant) => participant.userId === message.authorUserId);
const authorLabel = author?.displayName ?? labels.unknownUser;
const channelTitle = resolveChannelTitle(message, currentUserId, labels);
return {
id: message.id,
chatId: message.chatId,
channelKind: message.channelKind,
channelTitle,
authorLabel,
authorAvatar: {
imageUrl: author?.avatarUrl ?? null,
fallbackLabel: initials(authorLabel),
},
body: message.body,
createdAtIso: message.createdAtIso,
detailHref: buildChatMessageDeepLink({
tenantSlug,
chatId: message.chatId,
messageId: message.id,
parentMessageId: message.parentMessageId,
}),
isThreadReply: message.parentMessageId !== null,
} as const;
}
function resolveChannelTitle(message: ChatMessageDiscoveryRecord, currentUserId: string, labels: ChatMessageDiscoveryLabels): string {
if (message.channelKind === "dm") {
return message.participants.find((participant) => participant.userId !== currentUserId)?.displayName ?? labels.directMessage;
}
return message.channelName ?? (message.channelKind === "project" ? labels.unnamedProject : labels.unnamedGroup);
}
function initials(label: string): string {
const normalized = label.trim();
const parts = normalized.split(/\s+/).filter(Boolean);
return (parts.length > 1 ? `${parts[0]?.[0] ?? ""}${parts.at(-1)?.[0] ?? ""}` : normalized.slice(0, 2)).toUpperCase() || "?";
}
@@ -0,0 +1,217 @@
import { CHAT_PERMISSIONS, type ChatAttachmentRecord, type ChatMemberChannelRecord, type ChatMessageFeatureRecord } from "@hivegrid/chat";
import { buildChatMessageDeepLink } from "@hivegrid/chat/deep-links";
import type { ChatRealtimeMessage } from "@hivegrid/realtime";
import { getChatThreadDetail, listChatPinnedMessages, sendChatThreadReply, setChatMessagePin, setChatReaction } from "@hivegrid/chat/message-features.server";
import { buildChatPinnedMessagesVM, buildChatThreadVM, type ChatFeatureMessageVM, type ChatPinnedMessagesVM, type ChatThreadVM } from "@hivegrid/view-models";
import type { ChatRouteContext } from "../routes/chatAccess.server";
import { chatChannelPath } from "../routes/chatRoutePaths";
import { toChatAttachmentVM, toChatResolvedMentionVM } from "./chatViewModel.server";
export type ChatMessageFeatureLabels = {
readonly directMessage: string;
readonly unnamedGroup: string;
readonly unnamedProject: string;
readonly unknownUser: string;
readonly unknownMention: string;
};
export async function loadChatThreadPage(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly threadId: string;
readonly labels: ChatMessageFeatureLabels;
}): Promise<{ readonly vm: ChatThreadVM; readonly eventCursor: string }> {
const detail = await getChatThreadDetail({ ...input.context, chatId: input.chatId, threadId: input.threadId });
const features = new Map(detail.messageFeatures.map((feature) => [feature.messageId, feature]));
const attachments = groupAttachments(detail.attachments);
const profiles = new Map(detail.channel.participants.map((profile) => [profile.userId, profile]));
const canWrite = input.context.permissions.includes(CHAT_PERMISSIONS.write) && detail.channel.member.canWrite && detail.channel.archivedAtIso === null;
const canAdministerMessages = input.context.permissions.includes(CHAT_PERMISSIONS.admin);
const canDeleteAsChannelAdmin = detail.channel.member.roleInChat === "admin" || canAdministerMessages;
const nowIso = new Date().toISOString();
const vm = buildChatThreadVM({
chatId: detail.channel.id,
threadId: detail.parentMessage.id,
channelTitle: resolveChannelTitle(detail.channel, input.context.userId, input.labels),
backHref: chatChannelPath(input.tenantSlug, detail.channel.id),
parent: mapFeatureMessage(
detail.parentMessage,
features.get(detail.parentMessage.id) ?? null,
profiles,
input.context.userId,
canWrite,
detail.channel.kind,
input.tenantSlug,
attachments.get(detail.parentMessage.id) ?? [],
canAdministerMessages,
canDeleteAsChannelAdmin,
nowIso,
input.labels
),
replies: detail.replies.map((message) =>
mapFeatureMessage(
message,
features.get(message.id) ?? null,
profiles,
input.context.userId,
canWrite,
detail.channel.kind,
input.tenantSlug,
attachments.get(message.id) ?? [],
canAdministerMessages,
canDeleteAsChannelAdmin,
nowIso,
input.labels
)
),
replyCount: detail.replies.length,
canReply: canWrite,
});
return { vm, eventCursor: detail.channel.eventCursor };
}
export async function loadChatPinnedPage(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly labels: ChatMessageFeatureLabels;
}): Promise<{ readonly vm: ChatPinnedMessagesVM; readonly eventCursor: string }> {
const result = await listChatPinnedMessages({ ...input.context, chatId: input.chatId });
const profiles = new Map(result.channel.participants.map((profile) => [profile.userId, profile]));
const canWrite = input.context.permissions.includes(CHAT_PERMISSIONS.write) && result.channel.member.canWrite && result.channel.archivedAtIso === null;
const vm = buildChatPinnedMessagesVM({
chatId: result.channel.id,
channelTitle: resolveChannelTitle(result.channel, input.context.userId, input.labels),
backHref: chatChannelPath(input.tenantSlug, result.channel.id),
rows: result.pinnedMessages.map((row) => ({
message: mapFeatureMessage(
row.message,
{
messageId: row.message.id,
reactions: [],
thread: null,
pin: row.pin,
},
profiles,
input.context.userId,
false,
result.channel.kind,
input.tenantSlug,
[],
false,
false,
new Date().toISOString(),
input.labels
),
pinnedAtIso: row.pin.pinnedAtIso,
pinnedByLabel: row.pinnedBy?.displayName ?? input.labels.unknownUser,
note: row.pin.note,
messageHref: buildChatMessageDeepLink({ tenantSlug: input.tenantSlug, chatId: result.channel.id, messageId: row.message.id }),
canUnpin: canWrite,
})),
});
return { vm, eventCursor: result.channel.eventCursor };
}
export async function createChatThreadReply(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly threadId: string;
readonly body: string;
readonly requestId: string;
readonly clientMessageId: string;
}) {
return sendChatThreadReply({ ...input.context, ...input });
}
export async function changeChatReaction(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly emoji: string;
readonly active: boolean;
readonly requestId: string;
}) {
return setChatReaction({ ...input.context, ...input });
}
export async function changeChatMessagePin(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly pinned: boolean;
readonly requestId: string;
}) {
return setChatMessagePin({ ...input.context, ...input });
}
function mapFeatureMessage(
message: ChatRealtimeMessage,
feature: ChatMessageFeatureRecord | null,
profiles: ReadonlyMap<string, ChatMemberChannelRecord["participants"][number]>,
currentUserId: string,
canWrite: boolean,
channelKind: ChatMemberChannelRecord["kind"],
tenantSlug: string,
attachments: readonly ChatAttachmentRecord[],
canAdministerMessages: boolean,
canDeleteAsChannelAdmin: boolean,
nowIso: string,
labels: ChatMessageFeatureLabels
): ChatFeatureMessageVM {
const deleted = message.deletedAt !== null;
const author = message.authorUserId ? profiles.get(message.authorUserId) : null;
const ownMessage = message.authorUserId === currentUserId;
const ageMs = Date.parse(nowIso) - Date.parse(message.createdAt);
const withinOwnMutationWindow = Number.isFinite(ageMs) && ageMs >= 0 && ageMs <= 24 * 60 * 60 * 1_000;
const reactionGroups = new Map<string, string[]>();
for (const reaction of feature?.reactions ?? []) {
const userIds = reactionGroups.get(reaction.emoji) ?? [];
userIds.push(reaction.userId);
reactionGroups.set(reaction.emoji, userIds);
}
return {
id: message.id,
authorLabel: author?.displayName ?? "?",
authorAvatarUrl: author?.avatarUrl ?? null,
bodyMarkdown: deleted ? null : message.body,
createdAtIso: message.createdAt,
deleted,
mentions: deleted
? []
: message.mentions.map((mention) =>
toChatResolvedMentionVM(mention, profiles, tenantSlug, {
...labels,
})
),
attachments: deleted ? [] : attachments.map((attachment) => toChatAttachmentVM(attachment, tenantSlug)),
reactions: [...reactionGroups].map(([emoji, userIds]) => ({
emoji,
count: userIds.length,
reactedByViewer: userIds.includes(currentUserId),
})),
pinned: feature?.pin !== null && feature?.pin !== undefined,
canReact: canWrite && !deleted,
canPin: canWrite && !deleted && channelKind !== "dm",
canEdit: canWrite && !deleted && (canAdministerMessages || (ownMessage && withinOwnMutationWindow)),
canDelete: canWrite && !deleted && (canDeleteAsChannelAdmin || (ownMessage && withinOwnMutationWindow)),
};
}
function groupAttachments(attachments: readonly ChatAttachmentRecord[]): ReadonlyMap<string, readonly ChatAttachmentRecord[]> {
const grouped = new Map<string, ChatAttachmentRecord[]>();
for (const attachment of attachments) {
grouped.set(attachment.messageId, [...(grouped.get(attachment.messageId) ?? []), attachment]);
}
return grouped;
}
function resolveChannelTitle(channel: ChatMemberChannelRecord, currentUserId: string, labels: ChatMessageFeatureLabels): string {
if (channel.kind === "dm") {
return channel.participants.find((participant) => participant.userId !== currentUserId)?.displayName ?? labels.directMessage;
}
return channel.name?.trim() || (channel.kind === "project" ? labels.unnamedProject : labels.unnamedGroup);
}
@@ -0,0 +1,50 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
updateMessage: vi.fn(),
deleteMessage: vi.fn(),
}));
vi.mock("@hivegrid/chat/message-mutations.server", () => ({
updateChatMessage: mocks.updateMessage,
deleteChatMessage: mocks.deleteMessage,
}));
import { editMemberChatMessage, removeMemberChatMessage } from "./ChatMessageMutationsService.server";
const context = {
tenantId: "tenant_1",
userId: "user_1",
permissions: ["chat.read_own_channels", "chat.write"],
} as const;
describe("ChatMessageMutationsService", () => {
beforeEach(() => vi.clearAllMocks());
it("passes the fresh route context to an edit mutation", async () => {
mocks.updateMessage.mockResolvedValue({ replayed: false });
await editMemberChatMessage({ context, chatId: "chat_1", messageId: "message_1", requestId: "request_1", body: "Neu" });
expect(mocks.updateMessage).toHaveBeenCalledWith({
...context,
chatId: "chat_1",
messageId: "message_1",
requestId: "request_1",
body: "Neu",
});
});
it("passes the stable request id to a delete mutation", async () => {
mocks.deleteMessage.mockResolvedValue({ replayed: false });
await removeMemberChatMessage({ context, chatId: "chat_1", messageId: "message_1", requestId: "request_2" });
expect(mocks.deleteMessage).toHaveBeenCalledWith({
...context,
chatId: "chat_1",
messageId: "message_1",
requestId: "request_2",
});
});
});
@@ -0,0 +1,40 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { deleteChatMessage, updateChatMessage } from "@hivegrid/chat/message-mutations.server";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
export async function editMemberChatMessage(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly requestId: string;
readonly body: string;
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.write);
return updateChatMessage({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
messageId: input.messageId,
requestId: input.requestId,
body: input.body,
});
}
export async function removeMemberChatMessage(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly requestId: string;
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.write);
return deleteChatMessage({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
messageId: input.messageId,
requestId: input.requestId,
});
}
@@ -0,0 +1,153 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
withWritableSource: vi.fn(),
createTask: vi.fn(),
linkEntities: vi.fn(),
auditTask: vi.fn(),
logActivity: vi.fn(),
writeSystemMessage: vi.fn(),
publishWakeup: vi.fn(),
hasTasksModule: vi.fn(),
}));
vi.mock("@hivegrid/chat/repository.server", () => ({
withWritableChatMessageTaskSource: (...args: unknown[]) => mocks.withWritableSource(...args),
}));
vi.mock("@hivegrid/chat/system-message.server", () => ({
writeChatSystemMessageWithTx: (...args: unknown[]) => mocks.writeSystemMessage(...args),
}));
vi.mock("@hivegrid/chat/realtime-wakeup.server", () => ({
publishChatPersistentRealtimeWakeup: (...args: unknown[]) => mocks.publishWakeup(...args),
}));
vi.mock("@hivegrid/chat/module-access.server", () => ({
tenantHasTasksModuleWithPermissionsTx: (...args: unknown[]) => mocks.hasTasksModule(...args),
}));
vi.mock("~/utils/integrations/taskService.server", () => ({
createIdempotentTaskFromSourceWithTx: (...args: unknown[]) => mocks.createTask(...args),
}));
vi.mock("~/utils/integrations/entityLinkService.server", () => ({
linkEntitiesWithTx: (...args: unknown[]) => mocks.linkEntities(...args),
}));
vi.mock("~/utils/integrations/taskAudit.server", () => ({
auditTaskEvent: (...args: unknown[]) => mocks.auditTask(...args),
logTaskActivity: (...args: unknown[]) => mocks.logActivity(...args),
}));
import { markChatMessageAsTask } from "./ChatMessageTaskService.server";
const tx = { transaction: "shared" };
const source = { chatId: "chat_1", messageId: "message_1", body: "Heizung prüfen\nDetails", projectId: "project_1" };
const currentPermissions = ["chat.read_own_channels", "chat.write", "tasks.read_own", "tasks.write"];
const chatContext = {
tenantId: "tenant_1",
userId: "user_1",
tenantUserId: "tenant_user_1",
permissions: currentPermissions,
hasModule: true as const,
};
const taskContext = { tenantId: "tenant_1", userId: "user_1", permissions: ["tasks.write"], hasModule: true };
const input = {
chatContext,
taskContext,
chatId: "chat_1",
messageId: "message_1",
requestId: "request_1",
tenantSlug: "demo",
fallbackTitle: "Aufgabe aus Chat",
};
describe("markChatMessageAsTask", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.withWritableSource.mockImplementation(async (_input: unknown, operation: (...args: unknown[]) => unknown) =>
operation(tx, source, currentPermissions)
);
mocks.createTask.mockResolvedValue({
replayed: false,
task: { id: "task_1", linkedEntityType: "project", linkedEntityId: "project_1" },
});
mocks.linkEntities.mockResolvedValue(undefined);
mocks.auditTask.mockResolvedValue(undefined);
mocks.logActivity.mockResolvedValue(undefined);
mocks.writeSystemMessage.mockResolvedValue({ replayed: false, event: { event: "chat.message.created" } });
mocks.publishWakeup.mockResolvedValue(undefined);
mocks.hasTasksModule.mockResolvedValue(true);
});
it("writes task, backlink, strict effects and system link in one chat-authorized transaction", async () => {
await expect(markChatMessageAsTask(input)).resolves.toEqual({ taskId: "task_1", replayed: false });
expect(mocks.withWritableSource).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", chatId: "chat_1", messageId: "message_1" }),
expect.any(Function)
);
expect(mocks.createTask).toHaveBeenCalledWith(
tx,
expect.objectContaining({
tenantId: "tenant_1",
title: "Heizung prüfen",
description: "Heizung prüfen\nDetails",
linkedEntityType: "project",
linkedEntityId: "project_1",
source: "chat",
sourceRef: "chat-message:message_1",
ctx: expect.objectContaining({ permissions: currentPermissions }),
})
);
expect(mocks.linkEntities).toHaveBeenCalledWith(tx, {
tenantId: "tenant_1",
userId: "user_1",
sourceType: "chat_message",
sourceId: "message_1",
targetType: "task",
targetId: "task_1",
linkRole: "created-from",
});
expect(mocks.auditTask).toHaveBeenCalledWith(expect.objectContaining({ action: "task.created", taskId: "task_1" }), { client: tx, strict: true });
expect(mocks.logActivity).toHaveBeenCalledWith(expect.objectContaining({ taskId: "task_1", activityType: "task_created", summaryText: "Heizung prüfen" }), {
client: tx,
strict: true,
});
expect(mocks.writeSystemMessage).toHaveBeenCalledWith(
tx,
expect.objectContaining({
systemEventKey: "task-created:message_1",
kind: "task_created",
metadata: expect.objectContaining({ taskId: "task_1", taskHref: "/demo/tasks/task_1" }),
})
);
expect(mocks.publishWakeup).toHaveBeenCalledOnce();
});
it("repairs the backlink and system reply on replay without duplicating audit or activity", async () => {
mocks.createTask.mockResolvedValue({ replayed: true, task: { id: "task_1", linkedEntityType: null, linkedEntityId: null } });
mocks.writeSystemMessage.mockResolvedValue({ replayed: true, event: { event: "chat.message.created" } });
await expect(markChatMessageAsTask(input)).resolves.toEqual({ taskId: "task_1", replayed: true });
expect(mocks.linkEntities).toHaveBeenCalledOnce();
expect(mocks.auditTask).not.toHaveBeenCalled();
expect(mocks.logActivity).not.toHaveBeenCalled();
expect(mocks.writeSystemMessage).toHaveBeenCalledOnce();
expect(mocks.publishWakeup).not.toHaveBeenCalled();
});
it("fails closed when tasks.write was revoked after the route context was loaded", async () => {
mocks.withWritableSource.mockImplementation(async (_input: unknown, operation: (...args: unknown[]) => unknown) =>
operation(tx, source, ["chat.read_own_channels", "chat.write"])
);
await expect(markChatMessageAsTask(input)).rejects.toMatchObject({ status: 404 });
expect(mocks.createTask).not.toHaveBeenCalled();
});
it("fails closed when the Tasks module was disabled after the route context was loaded", async () => {
mocks.hasTasksModule.mockResolvedValue(false);
await expect(markChatMessageAsTask(input)).rejects.toMatchObject({ status: 404 });
expect(mocks.hasTasksModule).toHaveBeenCalledWith(tx, "tenant_1", currentPermissions);
expect(mocks.createTask).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,110 @@
import type { OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { AuditEventWriterClient } from "@hivegrid/db/audit-events.server";
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { publishChatPersistentRealtimeWakeup } from "@hivegrid/chat/realtime-wakeup.server";
import { withWritableChatMessageTaskSource } from "@hivegrid/chat/repository.server";
import { tenantHasTasksModuleWithPermissionsTx } from "@hivegrid/chat/module-access.server";
import { writeChatSystemMessageWithTx } from "@hivegrid/chat/system-message.server";
import type { ChatRouteContext } from "../routes/chatAccess.server";
import { linkEntitiesWithTx } from "~/utils/integrations/entityLinkService.server";
import type { TasksRouteContext } from "~/utils/integrations/taskAccess.server";
import { auditTaskEvent, logTaskActivity } from "~/utils/integrations/taskAudit.server";
import { tasksDetailPath } from "~/utils/integrations/taskRoutePaths";
import { createIdempotentTaskFromSourceWithTx } from "~/utils/integrations/taskService.server";
export async function markChatMessageAsTask(input: {
readonly chatContext: ChatRouteContext;
readonly taskContext: TasksRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly requestId: string;
readonly tenantSlug: string;
readonly fallbackTitle: string;
}): Promise<{ readonly taskId: string; readonly replayed: boolean }> {
if (input.chatContext.tenantId !== input.taskContext.tenantId || input.chatContext.userId !== input.taskContext.userId) {
throw new Error("Chat and task contexts must belong to the same tenant user");
}
const tenantSlug = input.tenantSlug.trim();
if (!tenantSlug) throw new CatalogError(foundationErrors.notFound);
return withWritableChatMessageTaskSource(
{
tenantId: input.chatContext.tenantId,
userId: input.chatContext.userId,
permissions: input.chatContext.permissions,
chatId: input.chatId,
messageId: input.messageId,
},
async (tx, source, currentPermissions) => {
if (!currentPermissions.includes("tasks.write")) {
throw new CatalogError(foundationErrors.notFound, { permission: "tasks.write" });
}
if (!(await tenantHasTasksModuleWithPermissionsTx(tx, input.chatContext.tenantId, currentPermissions))) {
throw new CatalogError(foundationErrors.notFound, { module: "tasks" });
}
requirePermission({ tenantId: input.taskContext.tenantId, userId: input.taskContext.userId, permissions: currentPermissions }, "tasks.write");
const currentTaskContext = { ...input.taskContext, permissions: currentPermissions };
const firstLine = source.body
.split(/\r?\n/u)
.map((line) => line.trim())
.find(Boolean);
const title = (firstLine || input.fallbackTitle).slice(0, 255);
const result = await createIdempotentTaskFromSourceWithTx(tx, {
tenantId: currentTaskContext.tenantId,
ctx: currentTaskContext,
title,
description: source.body.trim() || null,
linkedEntityType: source.projectId ? "project" : null,
linkedEntityId: source.projectId,
source: "chat",
sourceRef: `chat-message:${source.messageId}`,
});
await linkEntitiesWithTx(tx, {
tenantId: currentTaskContext.tenantId,
userId: currentTaskContext.userId,
sourceType: "chat_message",
sourceId: source.messageId,
targetType: "task",
targetId: result.task.id,
linkRole: "created-from",
});
if (!result.replayed) {
await auditTaskEvent(
{
ctx: currentTaskContext,
action: "task.created",
taskId: result.task.id,
metadata: { source: "chat", chatId: source.chatId, messageId: source.messageId },
},
{ client: tx as unknown as AuditEventWriterClient, strict: true }
);
await logTaskActivity(
{
ctx: currentTaskContext,
taskId: result.task.id,
activityType: "task_created",
summaryText: title,
linkedEntityType: result.task.linkedEntityType,
linkedEntityId: result.task.linkedEntityId,
},
{ client: tx, strict: true }
);
}
const taskHref = tasksDetailPath(tenantSlug, result.task.id);
const systemMessage = await writeChatSystemMessageWithTx(tx, {
tenantId: currentTaskContext.tenantId,
chatId: source.chatId,
systemEventKey: `task-created:${source.messageId}`,
requestId: `${input.requestId}:task-created`,
kind: "task_created",
metadata: { sourceMessageId: source.messageId, taskId: result.task.id, taskTitle: title, taskHref },
body: `${input.fallbackTitle}: ${title}`,
actorUserId: currentTaskContext.userId,
});
if (!systemMessage.replayed) {
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event: systemMessage.event });
}
return { taskId: result.task.id, replayed: result.replayed };
}
);
}
@@ -0,0 +1,249 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS, type ChatMemberChannelDetail, type ChatMemberChannelRecord, type ListMemberChannelsResult } from "@hivegrid/chat";
const mocks = vi.hoisted(() => ({
listMemberChannels: vi.fn(),
getMemberChannelDetail: vi.fn(),
listDiscoverablePublicGroupChats: vi.fn(),
joinPublicGroupChat: vi.fn(),
setChatMemberPreferences: vi.fn(),
tenantHasModule: vi.fn(),
}));
vi.mock("@hivegrid/chat/repository.server", () => ({
listMemberChannels: mocks.listMemberChannels,
getMemberChannelDetail: mocks.getMemberChannelDetail,
}));
vi.mock("@hivegrid/chat/discovery.server", () => ({
listDiscoverablePublicGroupChats: mocks.listDiscoverablePublicGroupChats,
}));
vi.mock("@hivegrid/chat/lifecycle.server", () => ({
joinPublicGroupChat: mocks.joinPublicGroupChat,
}));
vi.mock("@hivegrid/chat/member-preferences.server", () => ({
setChatMemberPreferences: mocks.setChatMemberPreferences,
}));
vi.mock("~/utils/connector/tenantConnector.server", () => ({
tenantHasModule: mocks.tenantHasModule,
}));
vi.mock("../routes/chatAccess.server", () => ({
requireChatPermission: (context: unknown) => context,
}));
import { joinPublicChatChannel, loadMemberChatChannel, loadMemberChatChannels, updateOwnChatChannelPreferences } from "./ChatService.server";
import type { ChatRouteContext } from "../routes/chatAccess.server";
const context: ChatRouteContext = {
tenantId: "tenant_1",
userId: "user_1",
tenantUserId: "tenant_user_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.write],
hasModule: true,
};
const labels = {
directMessage: "Direktnachricht",
unnamedGroup: "Unbenannte Gruppe",
unnamedProject: "Projektchat",
unknownUser: "Unbekannte Person",
unknownMention: "Unbekannte Erwähnung",
};
const emptyChannelResult: ListMemberChannelsResult = { channels: [], nextCursor: null };
const listedChannel: ChatMemberChannelRecord = {
id: "chat_1",
kind: "group",
name: "Montage",
description: null,
projektId: null,
isPrivate: false,
archivedAtIso: null,
lastMessageAtIso: null,
eventStreamId: "stream_1",
eventCursor: "stream_1:12",
member: {
roleInChat: "member",
notificationPreference: "all_messages",
lastReadMessageId: null,
lastReadAtIso: null,
isPinned: false,
canWrite: true,
},
memberCount: 1,
participants: [{ userId: "user_1", displayName: "Raffael Sheikh", avatarUrl: null }],
unreadCount: 0,
hasUnreadMention: false,
lastMessage: null,
};
describe("ChatService", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.listMemberChannels.mockResolvedValue(emptyChannelResult);
mocks.listDiscoverablePublicGroupChats.mockResolvedValue({ channels: [] });
mocks.joinPublicGroupChat.mockResolvedValue({ chatId: "chat_public", memberUserId: "user_1", roleInChat: "member", changed: true });
mocks.setChatMemberPreferences.mockResolvedValue({ chatId: "chat_1", isPinned: true, notificationPreference: "muted", changed: true });
mocks.tenantHasModule.mockResolvedValue(true);
});
it("passes the authenticated tenant/user context into the RLS repository list", async () => {
mocks.listMemberChannels.mockResolvedValue({ channels: [listedChannel], nextCursor: "next_cursor" });
const vm = await loadMemberChatChannels({
context,
tenantSlug: "demo",
filter: { query: "Montage", view: "groups", showArchived: true },
afterCursor: "current_cursor",
limit: 25,
labels,
});
expect(mocks.listMemberChannels).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
query: "Montage",
view: "groups",
includeArchived: true,
afterCursor: "current_cursor",
limit: 25,
});
expect(vm.status).toBe("ready");
expect(vm.data?.rows.map((row) => row.id)).toEqual(["chat_1"]);
expect(vm.data?.nextCursor).toBe("next_cursor");
expect(mocks.listDiscoverablePublicGroupChats).not.toHaveBeenCalled();
});
it("loads discoverable public groups only on the first page and maps no pre-join detail link", async () => {
mocks.listDiscoverablePublicGroupChats.mockResolvedValue({
channels: [{ id: "chat_public", name: "Montage Nord", description: "Austausch", memberCount: 4 }],
});
const vm = await loadMemberChatChannels({
context,
tenantSlug: "demo",
filter: { query: "Montage", view: "all", showArchived: false },
labels,
});
expect(mocks.listDiscoverablePublicGroupChats).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
query: "Montage",
});
expect(vm.status).toBe("ready");
expect(vm.data?.permissions.canDiscover).toBe(true);
expect(vm.data?.discoverRows).toEqual([
expect.objectContaining({
id: "chat_public",
title: "Montage Nord",
memberCount: 4,
canJoin: true,
joinHref: "/demo/chat",
detailHref: null,
}),
]);
});
it("joins through the lifecycle boundary with the authenticated tenant context", async () => {
await joinPublicChatChannel({ context, chatId: "chat_public", requestId: "request_join_1" });
expect(mocks.joinPublicGroupChat).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
chatId: "chat_public",
requestId: "request_join_1",
});
});
it("updates only the authenticated member's channel preferences through the RLS boundary", async () => {
await updateOwnChatChannelPreferences({
context,
chatId: "chat_1",
requestId: "request_preferences_1",
isPinned: true,
notificationPreference: "muted",
});
expect(mocks.setChatMemberPreferences).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
chatId: "chat_1",
requestId: "request_preferences_1",
isPinned: true,
notificationPreference: "muted",
});
});
it("passes the opaque history cursor and returns the repository event cursor", async () => {
const detail: ChatMemberChannelDetail = {
channel: {
id: "chat_1",
kind: "group",
name: "Montage",
description: null,
projektId: null,
isPrivate: false,
archivedAtIso: null,
lastMessageAtIso: null,
eventStreamId: "stream_1",
eventCursor: "stream_1:12",
member: {
roleInChat: "member",
notificationPreference: "all_messages",
lastReadMessageId: null,
lastReadAtIso: null,
isPinned: false,
},
memberCount: 1,
participants: [{ userId: "user_1", displayName: "Raffael Sheikh", avatarUrl: null }],
unreadCount: 0,
hasUnreadMention: false,
lastMessage: null,
},
messages: [],
readReceipts: [],
attachments: [],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:12",
};
mocks.getMemberChannelDetail.mockResolvedValue(detail);
const result = await loadMemberChatChannel({
context,
tenantSlug: "demo",
chatId: "chat_1",
beforeMessageCursor: "opaque_cursor",
labels,
});
expect(mocks.getMemberChannelDetail).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
chatId: "chat_1",
beforeMessageCursor: "opaque_cursor",
});
expect(mocks.tenantHasModule).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", moduleKey: "files" });
expect(mocks.tenantHasModule).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", moduleKey: "tasks" });
expect(result.eventCursor).toBe("stream_1:12");
expect(result.authors).toEqual([
{
userId: "user_1",
displayName: "Raffael Sheikh",
avatar: { imageUrl: null, fallbackLabel: "RS" },
isCurrentUser: true,
},
]);
expect(result.vm.status).toBe("ready");
});
});
@@ -0,0 +1,148 @@
import { CHAT_PERMISSIONS, type ChatNotificationPreference } from "@hivegrid/chat";
import { listDiscoverablePublicGroupChats } from "@hivegrid/chat/discovery.server";
import { joinPublicGroupChat } from "@hivegrid/chat/lifecycle.server";
import { setChatMemberPreferences } from "@hivegrid/chat/member-preferences.server";
import { getMemberChannelDetail, listMemberChannels, sendTopLevelChatMessage } from "@hivegrid/chat/repository.server";
import type { ChatChannelDetailVM, ChatChannelListFilterState, ChatChannelListVM, ChatResolvedAuthorVM } from "@hivegrid/view-models";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
import { buildMemberChatChannelDetailVM, buildMemberChatChannelListVM, buildChatResolvedAuthors, type ChatViewModelLabels } from "./chatViewModel.server";
export async function loadMemberChatChannels(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly filter: ChatChannelListFilterState;
readonly afterCursor?: string;
readonly limit?: number;
readonly labels: ChatViewModelLabels;
}): Promise<ChatChannelListVM> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
const [result, discover] = await Promise.all([
listMemberChannels({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
query: input.filter.query,
view: input.filter.view,
includeArchived: input.filter.showArchived,
afterCursor: input.afterCursor,
limit: input.limit,
}),
input.afterCursor
? Promise.resolve(undefined)
: listDiscoverablePublicGroupChats({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
query: input.filter.query,
}),
]);
return buildMemberChatChannelListVM({
channels: result.channels,
tenantSlug: input.tenantSlug,
currentUserId: context.userId,
permissions: context.permissions,
filter: input.filter,
nextCursor: result.nextCursor,
discoverChannels: discover?.channels,
labels: input.labels,
});
}
export async function joinPublicChatChannel(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly requestId: string;
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
return joinPublicGroupChat({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
requestId: input.requestId,
});
}
export async function updateOwnChatChannelPreferences(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly requestId: string;
readonly isPinned?: boolean;
readonly notificationPreference?: ChatNotificationPreference;
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
return setChatMemberPreferences({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
requestId: input.requestId,
...(input.isPinned === undefined ? {} : { isPinned: input.isPinned }),
...(input.notificationPreference === undefined ? {} : { notificationPreference: input.notificationPreference }),
});
}
export async function loadMemberChatChannel(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly beforeMessageCursor?: string;
readonly focusMessageId?: string;
readonly labels: ChatViewModelLabels;
}): Promise<{
readonly vm: ChatChannelDetailVM;
readonly eventCursor: string;
readonly authors: readonly ChatResolvedAuthorVM[];
}> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
const [detail, filesEnabled, tasksEnabled] = await Promise.all([
getMemberChannelDetail({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
...(input.beforeMessageCursor ? { beforeMessageCursor: input.beforeMessageCursor } : {}),
...(input.focusMessageId ? { focusMessageId: input.focusMessageId } : {}),
}),
tenantHasModule({ tenantId: context.tenantId, userId: context.userId, moduleKey: "files" }),
tenantHasModule({ tenantId: context.tenantId, userId: context.userId, moduleKey: "tasks" }),
]);
return {
vm: buildMemberChatChannelDetailVM({
detail,
tenantSlug: input.tenantSlug,
currentUserId: context.userId,
permissions: context.permissions,
nowIso: new Date().toISOString(),
featureAvailability: { files: filesEnabled, tasks: tasksEnabled },
labels: input.labels,
}),
eventCursor: detail.eventCursor,
authors: buildChatResolvedAuthors(detail.channel.participants, context.userId),
};
}
export async function sendMemberChatMessage(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly clientMessageId: string;
readonly requestId: string;
readonly body: string;
readonly attachmentFileIds: readonly string[];
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.write);
return sendTopLevelChatMessage({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
clientMessageId: input.clientMessageId,
requestId: input.requestId,
body: input.body,
attachmentFileIds: input.attachmentFileIds,
});
}
@@ -0,0 +1,74 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@hivegrid/config", async (importOriginal) => {
const actual = await importOriginal<typeof import("@hivegrid/config")>();
return {
...actual,
loadRequiredWebConfig: () => ({
nodeEnv: "test",
routing: {
appHost: "app.localhost",
adminHost: "admin.localhost",
marketingHost: "localhost",
protocol: "http",
},
sessionSecret: "chat-audit-test-session-secret-with-enough-entropy",
}),
};
});
import {
__resetChatAuditSessionCookieForTests,
beginChatAuditSession,
CHAT_AUDIT_SESSION_TTL_MS,
normalizeChatAuditReason,
readChatAuditSession,
} from "./chatAuditSession.server";
describe("AK-P15b short-lived chat audit sessions", () => {
beforeEach(() => __resetChatAuditSessionCookieForTests());
it("binds the signed reason session to its tenant and user", async () => {
const now = new Date("2026-07-16T10:00:00.000Z");
const issued = await beginChatAuditSession({
tenantId: "tenant-a",
userId: "admin-a",
reason: " Kundenreklamation nachvollziehen ",
now,
sessionId: "audit-session-1",
});
const request = requestWithCookie(issued.cookie);
await expect(readChatAuditSession({ request, tenantId: "tenant-a", userId: "admin-a", now })).resolves.toMatchObject({
id: "audit-session-1",
reason: "Kundenreklamation nachvollziehen",
expiresAt: now.getTime() + CHAT_AUDIT_SESSION_TTL_MS,
});
await expect(readChatAuditSession({ request, tenantId: "tenant-b", userId: "admin-a", now })).resolves.toBeNull();
await expect(readChatAuditSession({ request, tenantId: "tenant-a", userId: "admin-b", now })).resolves.toBeNull();
});
it("expires server-side even when a client retains the cookie", async () => {
const now = new Date("2026-07-16T10:00:00.000Z");
const issued = await beginChatAuditSession({ tenantId: "tenant-a", userId: "admin-a", reason: "Audit", now });
await expect(
readChatAuditSession({
request: requestWithCookie(issued.cookie),
tenantId: "tenant-a",
userId: "admin-a",
now: new Date(now.getTime() + CHAT_AUDIT_SESSION_TTL_MS),
})
).resolves.toBeNull();
});
it("rejects a missing justification", () => {
expect(normalizeChatAuditReason(" \n ")).toBeNull();
expect(normalizeChatAuditReason("Legitimer Supportfall")).toBe("Legitimer Supportfall");
});
});
function requestWithCookie(setCookie: string): Request {
return new Request("http://app.localhost/demo/settings/chat/audit", {
headers: { cookie: setCookie.split(";", 1)[0]! },
});
}
@@ -0,0 +1,153 @@
import { randomUUID } from "node:crypto";
import { createCookie } from "react-router";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
export const CHAT_AUDIT_SESSION_TTL_MS = 15 * 60 * 1_000;
export const CHAT_AUDIT_REASON_MAX_LENGTH = 500;
const CLOCK_SKEW_MS = 30 * 1_000;
const SECURE_COOKIE_NAME = "__Host-hivegrid_chat_audit";
const LOCAL_COOKIE_NAME = "hivegrid_chat_audit";
const PAYLOAD_VERSION = 1;
export type ChatAuditSession = Readonly<{
id: string;
tenantId: string;
userId: string;
reason: string;
issuedAt: number;
expiresAt: number;
}>;
type StoredChatAuditSession = ChatAuditSession & { readonly version: typeof PAYLOAD_VERSION };
let cachedCookie: ReturnType<typeof createCookie> | null = null;
function getChatAuditCookie(): ReturnType<typeof createCookie> {
if (cachedCookie) return cachedCookie;
const config = loadRequiredWebConfig();
const policy = resolveHostOnlyCookiePolicy({
nodeEnv: config.nodeEnv,
routing: config.routing,
secureName: SECURE_COOKIE_NAME,
localName: LOCAL_COOKIE_NAME,
maxAge: Math.ceil(CHAT_AUDIT_SESSION_TTL_MS / 1_000),
});
cachedCookie = createCookie(policy.name, {
httpOnly: true,
sameSite: "strict",
path: policy.path,
secure: policy.secure,
maxAge: policy.maxAge,
secrets: config.sessionSecret ? [config.sessionSecret] : [],
});
return cachedCookie;
}
export async function beginChatAuditSession(input: {
readonly tenantId: string;
readonly userId: string;
readonly reason: string;
readonly now?: Date;
readonly sessionId?: string;
}): Promise<{ readonly session: ChatAuditSession; readonly cookie: string }> {
const now = input.now ?? new Date();
const reason = normalizeReason(input.reason);
const session: ChatAuditSession = {
id: normalizeIdentifier(input.sessionId ?? randomUUID(), "session id"),
tenantId: normalizeIdentifier(input.tenantId, "tenant id"),
userId: normalizeIdentifier(input.userId, "user id"),
reason,
issuedAt: now.getTime(),
expiresAt: now.getTime() + CHAT_AUDIT_SESSION_TTL_MS,
};
const stored: StoredChatAuditSession = { version: PAYLOAD_VERSION, ...session };
return { session, cookie: await getChatAuditCookie().serialize(stored) };
}
export async function readChatAuditSession(input: {
readonly request: Request;
readonly tenantId: string;
readonly userId: string;
readonly now?: Date;
}): Promise<ChatAuditSession | null> {
let parsed: unknown;
try {
parsed = await getChatAuditCookie().parse(input.request.headers.get("cookie"));
} catch {
return null;
}
const session = parseStoredSession(parsed);
if (!session) return null;
const now = (input.now ?? new Date()).getTime();
if (
session.tenantId !== input.tenantId ||
session.userId !== input.userId ||
now < session.issuedAt - CLOCK_SKEW_MS ||
now >= session.expiresAt ||
session.expiresAt - session.issuedAt !== CHAT_AUDIT_SESSION_TTL_MS
) {
return null;
}
return session;
}
export function clearChatAuditSession(): Promise<string> {
return getChatAuditCookie().serialize("", { maxAge: 0, expires: new Date(0) });
}
export function normalizeChatAuditReason(value: unknown): string | null {
if (typeof value !== "string") return null;
try {
return normalizeReason(value);
} catch {
return null;
}
}
export function __resetChatAuditSessionCookieForTests(): void {
cachedCookie = null;
}
function parseStoredSession(value: unknown): ChatAuditSession | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const row = value as Record<string, unknown>;
if (
row.version !== PAYLOAD_VERSION ||
typeof row.id !== "string" ||
typeof row.tenantId !== "string" ||
typeof row.userId !== "string" ||
typeof row.reason !== "string" ||
typeof row.issuedAt !== "number" ||
typeof row.expiresAt !== "number" ||
!Number.isFinite(row.issuedAt) ||
!Number.isFinite(row.expiresAt)
) {
return null;
}
try {
return {
id: normalizeIdentifier(row.id, "session id"),
tenantId: normalizeIdentifier(row.tenantId, "tenant id"),
userId: normalizeIdentifier(row.userId, "user id"),
reason: normalizeReason(row.reason),
issuedAt: row.issuedAt,
expiresAt: row.expiresAt,
};
} catch {
return null;
}
}
function normalizeReason(value: string): string {
const reason = value.trim().replace(/\s+/g, " ");
if (!reason || reason.length > CHAT_AUDIT_REASON_MAX_LENGTH || reason.includes("\0")) {
throw new Error("A chat audit reason is required");
}
return reason;
}
function normalizeIdentifier(value: string, label: string): string {
const normalized = value.trim();
if (!normalized || normalized.length > 500 || normalized.includes("\0")) throw new Error(`${label} is invalid`);
return normalized;
}
@@ -0,0 +1,100 @@
// @vitest-environment node
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
CHAT_GATEWAY_TOKEN_SESSION_LIMIT,
CHAT_GATEWAY_TOKEN_USER_LIMIT,
__resetChatGatewayTokenRateLimitStoreForTests,
__setChatGatewayTokenRateLimitStoreForTests,
checkChatGatewayTokenRateLimit,
} from "./chatGatewayRateLimit.server";
const stores: Array<ReturnType<typeof createSharedStore>> = [];
function useMemoryStore() {
const store = createSharedStore({ namespace: "chat-token-rate-test", adapter: new MemoryAdapter() });
stores.push(store);
__setChatGatewayTokenRateLimitStoreForTests(store);
return store;
}
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-07-15T12:00:00.000Z"));
useMemoryStore();
});
afterEach(async () => {
__resetChatGatewayTokenRateLimitStoreForTests();
vi.useRealTimers();
await Promise.allSettled(stores.splice(0).map((store) => store.close()));
});
describe("chat gateway token rate limit", () => {
it("atomically caps token minting per session and resets with the fixed window", async () => {
const input = { tenantId: "tenant_1", userId: "user_1", sessionId: "session_1" };
const reservations = await Promise.all(Array.from({ length: CHAT_GATEWAY_TOKEN_SESSION_LIMIT + 1 }, () => checkChatGatewayTokenRateLimit(input)));
expect(reservations.filter((result) => result.allowed)).toHaveLength(CHAT_GATEWAY_TOKEN_SESSION_LIMIT);
expect(reservations.filter((result) => !result.allowed)).toEqual([{ allowed: false, retryAfterSeconds: 60 }]);
vi.advanceTimersByTime(60_000);
await expect(checkChatGatewayTokenRateLimit(input)).resolves.toMatchObject({ allowed: true });
});
it("applies an authoritative tenant-user cap across independent sessions", async () => {
for (let index = 0; index < CHAT_GATEWAY_TOKEN_USER_LIMIT; index += 1) {
await expect(
checkChatGatewayTokenRateLimit({
tenantId: "tenant_1",
userId: "user_1",
sessionId: `session_${Math.floor(index / CHAT_GATEWAY_TOKEN_SESSION_LIMIT)}`,
})
).resolves.toMatchObject({ allowed: true });
}
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_fresh" })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 60,
});
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_2", userId: "user_1", sessionId: "session_fresh" })).resolves.toMatchObject({
allowed: true,
});
});
it("does not consume a session budget when the user-wide reservation is denied", async () => {
for (let index = 0; index < CHAT_GATEWAY_TOKEN_USER_LIMIT; index += 1) {
await checkChatGatewayTokenRateLimit({
tenantId: "tenant_1",
userId: "user_1",
sessionId: `session_${Math.floor(index / CHAT_GATEWAY_TOKEN_SESSION_LIMIT)}`,
});
}
vi.advanceTimersByTime(30_000);
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_fresh" })).resolves.toMatchObject({
allowed: false,
});
vi.advanceTimersByTime(30_001);
const nextWindow = await Promise.all(
Array.from({ length: CHAT_GATEWAY_TOKEN_SESSION_LIMIT }, () =>
checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_fresh" })
)
);
expect(nextWindow.every((result) => result.allowed)).toBe(true);
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_fresh" })).resolves.toMatchObject({
allowed: false,
});
});
it("fails closed when the shared rate-limit store is unavailable", async () => {
const store = stores.at(-1);
if (!store) throw new Error("Expected a test store");
await store.close();
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_1" })).rejects.toThrow(/closed/i);
});
});
@@ -0,0 +1,165 @@
import { MemoryAdapter, type SharedStore } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
export const CHAT_GATEWAY_TOKEN_SESSION_LIMIT = 20;
export const CHAT_GATEWAY_TOKEN_USER_LIMIT = 60;
export const CHAT_GATEWAY_TOKEN_WINDOW_SECONDS = 60;
const CHAT_GATEWAY_TOKEN_WINDOW_MS = CHAT_GATEWAY_TOKEN_WINDOW_SECONDS * 1_000;
const CHAT_GATEWAY_TOKEN_RATE_LIMIT_SCRIPT = `
local time = redis.call("TIME")
local now = (tonumber(time[1]) * 1000) + math.floor(tonumber(time[2]) / 1000)
local window_ms = tonumber(ARGV[1])
local session_limit = tonumber(ARGV[2])
local user_limit = tonumber(ARGV[3])
if not window_ms or window_ms <= 0 or not session_limit or session_limit <= 0 or
not user_limit or user_limit < session_limit then
return redis.error_reply("invalid chat token rate limit arguments")
end
local function read_bucket(key)
local raw = redis.call("GET", key)
if not raw then
return { count = 0, resetAt = now + window_ms }
end
local ok, bucket = pcall(cjson.decode, raw)
if not ok or type(bucket) ~= "table" or type(bucket.count) ~= "number" or
bucket.count < 0 or bucket.count % 1 ~= 0 or type(bucket.resetAt) ~= "number" then
return nil
end
if bucket.resetAt <= now then
return { count = 0, resetAt = now + window_ms }
end
return bucket
end
local session_bucket = read_bucket(KEYS[1])
local user_bucket = read_bucket(KEYS[2])
if not session_bucket or not user_bucket then
return redis.error_reply("invalid chat token rate limit bucket")
end
local session_blocked = session_bucket.count >= session_limit
local user_blocked = user_bucket.count >= user_limit
if session_blocked or user_blocked then
local retry_after_ms = 1
if session_blocked then retry_after_ms = math.max(retry_after_ms, session_bucket.resetAt - now) end
if user_blocked then retry_after_ms = math.max(retry_after_ms, user_bucket.resetAt - now) end
return { 0, 0, retry_after_ms }
end
session_bucket.count = session_bucket.count + 1
user_bucket.count = user_bucket.count + 1
redis.call("SET", KEYS[1], cjson.encode(session_bucket), "PX", math.max(1, session_bucket.resetAt - now))
redis.call("SET", KEYS[2], cjson.encode(user_bucket), "PX", math.max(1, user_bucket.resetAt - now))
local remaining = math.min(session_limit - session_bucket.count, user_limit - user_bucket.count)
return { 1, remaining, 0 }
`;
export type ChatGatewayTokenRateLimitInput = {
tenantId: string;
userId: string;
sessionId: string;
};
export type ChatGatewayTokenRateLimitResult = { allowed: true; remaining: number } | { allowed: false; retryAfterSeconds: number };
let storeFactory: () => SharedStore = () => getSharedStore();
export async function checkChatGatewayTokenRateLimit(input: ChatGatewayTokenRateLimitInput): Promise<ChatGatewayTokenRateLimitResult> {
const scope = `${encodeKeyPart(input.tenantId)}:${encodeKeyPart(input.userId)}`;
const result = await storeFactory().eval(
CHAT_GATEWAY_TOKEN_RATE_LIMIT_SCRIPT,
[`token-session:${scope}:${encodeKeyPart(input.sessionId)}`, `token-user:${scope}`],
[String(CHAT_GATEWAY_TOKEN_WINDOW_MS), String(CHAT_GATEWAY_TOKEN_SESSION_LIMIT), String(CHAT_GATEWAY_TOKEN_USER_LIMIT), String(Date.now())]
);
const decision = parseDecision(result);
if (decision.allowed) return { allowed: true, remaining: decision.remaining };
return { allowed: false, retryAfterSeconds: Math.max(1, Math.ceil(decision.retryAfterMs / 1_000)) };
}
function parseDecision(result: unknown): { allowed: true; remaining: number } | { allowed: false; retryAfterMs: number } {
if (!Array.isArray(result) || result.length !== 3) throw new Error("chat token rate limit returned an invalid result");
const allowed = Number(result[0]);
const remaining = Number(result[1]);
const retryAfterMs = Number(result[2]);
if ((allowed !== 0 && allowed !== 1) || !Number.isSafeInteger(remaining) || remaining < 0 || !Number.isFinite(retryAfterMs) || retryAfterMs < 0) {
throw new Error("chat token rate limit returned an invalid result");
}
return allowed === 1 ? { allowed: true, remaining } : { allowed: false, retryAfterMs };
}
function encodeKeyPart(value: string): string {
return Buffer.from(value, "utf8").toString("base64url");
}
type TokenRateBucket = { count: number; resetAt: number };
async function runTokenRateLimitInMemory(adapter: MemoryAdapter, keys: string[], args: string[]): Promise<[number, number, number]> {
if (keys.length !== 2 || args.length !== 4) throw new Error("invalid chat token rate limit arguments");
const windowMs = requirePositiveInteger(args[0], "window");
const sessionLimit = requirePositiveInteger(args[1], "session limit");
const userLimit = requirePositiveInteger(args[2], "user limit");
const now = Number(args[3]);
if (userLimit < sessionLimit || !Number.isFinite(now)) throw new Error("invalid chat token rate limit arguments");
const sessionBucket = readBucket(await adapter.get(keys[0] ?? ""), now, windowMs);
const userBucket = readBucket(await adapter.get(keys[1] ?? ""), now, windowMs);
const sessionBlocked = sessionBucket.count >= sessionLimit;
const userBlocked = userBucket.count >= userLimit;
if (sessionBlocked || userBlocked) {
return [0, 0, Math.max(1, sessionBlocked ? sessionBucket.resetAt - now : 0, userBlocked ? userBucket.resetAt - now : 0)];
}
sessionBucket.count += 1;
userBucket.count += 1;
await Promise.all([persistBucket(adapter, keys[0], sessionBucket, now), persistBucket(adapter, keys[1], userBucket, now)]);
return [1, Math.min(sessionLimit - sessionBucket.count, userLimit - userBucket.count), 0];
}
function readBucket(raw: string | null, now: number, windowMs: number): TokenRateBucket {
if (raw === null) return { count: 0, resetAt: now + windowMs };
let parsed: unknown;
try {
parsed = JSON.parse(raw) as unknown;
} catch {
throw new Error("invalid chat token rate limit bucket");
}
if (
typeof parsed !== "object" ||
parsed === null ||
Array.isArray(parsed) ||
!Number.isSafeInteger((parsed as Partial<TokenRateBucket>).count) ||
((parsed as Partial<TokenRateBucket>).count ?? -1) < 0 ||
!Number.isFinite((parsed as Partial<TokenRateBucket>).resetAt)
) {
throw new Error("invalid chat token rate limit bucket");
}
const bucket = parsed as TokenRateBucket;
return bucket.resetAt <= now ? { count: 0, resetAt: now + windowMs } : bucket;
}
async function persistBucket(adapter: MemoryAdapter, key: string | undefined, bucket: TokenRateBucket, now: number): Promise<void> {
if (!key) throw new Error("invalid chat token rate limit key");
const stored = await adapter.set(key, JSON.stringify(bucket), { ttlSeconds: Math.max(1, Math.ceil((bucket.resetAt - now) / 1_000)) });
if (!stored) throw new Error("chat token rate limit bucket could not be stored");
}
function requirePositiveInteger(value: string | undefined, label: string): number {
const parsed = Number(value);
if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new Error(`invalid chat token rate limit ${label}`);
return parsed;
}
MemoryAdapter.registerScript(CHAT_GATEWAY_TOKEN_RATE_LIMIT_SCRIPT, runTokenRateLimitInMemory);
export function __setChatGatewayTokenRateLimitStoreForTests(store: SharedStore): void {
storeFactory = () => store;
}
export function __resetChatGatewayTokenRateLimitStoreForTests(): void {
storeFactory = () => getSharedStore();
}
@@ -0,0 +1,491 @@
import { describe, expect, it } from "vitest";
import type { ChatMemberChannelDetail, ChatMemberChannelRecord } from "@hivegrid/chat";
import type { ChatRealtimeSystemMessage } from "@hivegrid/realtime";
import { buildMemberChatChannelDetailVM, buildMemberChatChannelListVM, type ChatViewModelLabels } from "./chatViewModel.server";
const labels: ChatViewModelLabels = {
directMessage: "Direktnachricht",
unnamedGroup: "Unbenannte Gruppe",
unnamedProject: "Projektchat",
unknownUser: "Unbekannte Person",
unknownMention: "Unbekannte Erwähnung",
};
const channel = (overrides: Partial<ChatMemberChannelRecord> = {}): ChatMemberChannelRecord => ({
id: "chat_1",
kind: "dm",
name: null,
description: null,
projektId: null,
isPrivate: true,
archivedAtIso: null,
lastMessageAtIso: "2026-07-15T10:00:00.000Z",
eventStreamId: "stream_1",
eventCursor: "stream_1:8",
member: {
roleInChat: "member",
notificationPreference: "all_messages",
lastReadMessageId: null,
lastReadAtIso: null,
isPinned: false,
canWrite: true,
},
memberCount: 2,
participants: [
{ userId: "user_me", displayName: "Raffael Sheikh", avatarUrl: "/avatars/user_me?v=1" },
{ userId: "user_other", displayName: "Ada Lovelace", avatarUrl: null },
],
unreadCount: 1,
hasUnreadMention: true,
lastMessage: {
id: "message_1",
clientMessageId: "client_1",
authorUserId: "user_other",
body: "Hallo Raffael",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [{ type: "user", id: "user_me", label: null }],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T10:00:00.000Z",
updatedAt: "2026-07-15T10:00:00.000Z",
editedAt: null,
deletedAt: null,
},
...overrides,
});
const systemMessage = (overrides: Partial<ChatRealtimeSystemMessage> = {}): ChatRealtimeSystemMessage => ({
id: "system_message_1",
clientMessageId: "system:project-created:project_1",
authorUserId: null,
body: "stored fallback copy",
bodyFormat: "system",
systemEvent: { kind: "project_created", metadata: { projectName: "Wärmepumpe Müller" } },
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T10:00:00.000Z",
updatedAt: "2026-07-15T10:00:00.000Z",
editedAt: null,
deletedAt: null,
...overrides,
});
describe("chatViewModel.server", () => {
it("maps the repository page without applying query, view, or archive filters a second time", () => {
const vm = buildMemberChatChannelListVM({
channels: [channel(), channel({ id: "chat_archived", archivedAtIso: "2026-07-14T10:00:00.000Z", unreadCount: 3 })],
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write", "chat.create_dm"],
filter: { query: "ada", view: "mentions", showArchived: false },
nextCursor: "next_cursor",
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.rows).toHaveLength(2);
expect(vm.data.rows[0]).toMatchObject({
id: "chat_1",
title: "Ada Lovelace",
detailHref: "/demo/chat/chat_1",
unreadCount: 1,
hasMention: true,
avatar: { fallbackLabel: "AL" },
});
expect(vm.data.totals).toEqual({ unread: 4, mentions: 2 });
expect(vm.data.nextCursor).toBe("next_cursor");
expect(vm.data.permissions).toMatchObject({ canWrite: true, canCreateDm: true, canCreateGroup: false, canSearch: true });
expect(vm.data.hrefs).toMatchObject({
newChannel: "/demo/chat/new?kind=group",
newDm: "/demo/chat/new?kind=dm",
});
});
it("renders a bounded plain-text channel snippet from long markdown", () => {
const markdown = `**Wichtig** [Plan](https://example.com) ${"x".repeat(300)}`;
const vm = buildMemberChatChannelListVM({
channels: [channel({ lastMessage: { ...channel().lastMessage!, body: markdown } })],
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels"],
filter: { query: "", view: "all", showArchived: false },
nextCursor: null,
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.rows[0]?.lastMessage?.snippet).toMatch(/^Wichtig Plan x+…$/);
expect(vm.data.rows[0]?.lastMessage?.snippet).toHaveLength(160);
});
it("maps discoverable public groups to join-only rows without exposing a detail route", () => {
const vm = buildMemberChatChannelListVM({
channels: [],
discoverChannels: [{ id: "chat_public", name: "Montage Nord", description: "Offener Austausch", memberCount: 7 }],
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels"],
filter: { query: "", view: "all", showArchived: false },
nextCursor: null,
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.permissions.canDiscover).toBe(true);
expect(vm.data.discoverRows).toEqual([
{
id: "chat_public",
title: "Montage Nord",
description: "Offener Austausch",
avatar: { imageUrl: null, fallbackLabel: "MN" },
memberCount: 7,
isJoined: false,
canJoin: true,
joinHref: "/demo/chat",
detailHref: null,
},
]);
});
it("maps the latest system event to an i18n preview without a fake author", () => {
const vm = buildMemberChatChannelListVM({
channels: [channel({ lastMessage: systemMessage() })],
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels"],
filter: { query: "", view: "all", showArchived: false },
nextCursor: null,
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.rows[0]?.lastMessage).toMatchObject({
authorLabel: null,
snippet: "",
systemEvent: {
kind: "project_created",
labelKey: "chat.systemEvent.projectCreated",
values: { project: "Wärmepumpe Müller" },
},
});
});
it("maps persisted messages, resolved mentions, reads and the enabled thread/reaction actions", () => {
const detail: ChatMemberChannelDetail = {
channel: channel(),
messages: [channel().lastMessage!],
readReceipts: [{ messageId: "message_1", userId: "user_me", readAtIso: "2026-07-15T10:01:00.000Z" }],
attachments: [
{
messageId: "message_1",
fileId: "file_1",
displayName: "camera.jpg",
mimeType: "image/jpeg",
sizeBytes: 1024,
linkRole: "image",
previewStatus: "ready",
scanStatus: "clean",
},
],
hasOlderMessages: true,
olderMessageCursor: "opaque_cursor",
eventCursor: "stream_1:8",
};
const vm = buildMemberChatChannelDetailVM({
detail,
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write", "files.write", "tasks.write"],
featureAvailability: { files: true, tasks: true },
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.header).toMatchObject({ title: "Ada Lovelace", kind: "dm", pinnedHref: null });
expect(vm.data.history).toEqual({ hasOlder: true, olderCursor: "opaque_cursor" });
expect(vm.data.messages[0]).toMatchObject({
source: "persisted",
deliveryState: "sent",
author: { displayName: "Ada Lovelace", isCurrentUser: false },
mentions: [{ kind: "user", id: "user_me", label: "Raffael Sheikh", href: null }],
readAggregate: { readCount: 1, recipientCount: 1, readerUserIds: ["user_me"], readerLabels: ["Raffael Sheikh"] },
attachments: [{ fileId: "file_1", kind: "image", previewHref: "/demo/media/file_1/preview", scanStatus: "clean" }],
actions: { canReact: true, canReply: true, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: true },
});
expect(vm.data.composer).toMatchObject({
enabled: true,
canSend: true,
canMention: true,
canAttachFiles: true,
canRecordVoice: true,
canMarkAsTask: true,
});
});
it("projects reactions, one-level thread aggregates, and pins for non-DM channels", () => {
const group = channel({
kind: "group",
name: "Montage Nord",
isPrivate: false,
member: { ...channel().member, roleInChat: "admin" },
});
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: group,
messages: [group.lastMessage!],
readReceipts: [],
attachments: [],
messageFeatures: [
{
messageId: "message_1",
reactions: [
{ id: "reaction_1", messageId: "message_1", userId: "user_me", emoji: "👍", reactedAtIso: "2026-07-15T10:02:00.000Z" },
{ id: "reaction_2", messageId: "message_1", userId: "user_other", emoji: "👍", reactedAtIso: "2026-07-15T10:03:00.000Z" },
],
thread: {
id: "message_1",
parentMessageId: "message_1",
replyCount: 2,
lastReplyAtIso: "2026-07-15T10:04:00.000Z",
participantUserIds: ["user_me", "user_other"],
},
pin: { messageId: "message_1", pinnedByUserId: "user_me", pinnedAtIso: "2026-07-15T10:05:00.000Z", note: null },
},
],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:8",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.header.pinnedHref).toBe("/demo/chat/chat_1/pinned");
expect(vm.data.messages[0]).toMatchObject({
reactions: [{ emoji: "👍", count: 2, reactedByViewer: true, reactorLabels: ["Raffael Sheikh", "Ada Lovelace"] }],
thread: { replyCount: 2, href: "/demo/chat/chat_1/thread/message_1", isFollowing: true },
pin: { pinnedByLabel: "Raffael Sheikh" },
actions: { canReact: true, canReply: true, canPin: true },
});
expect(vm.data.pinnedMessages).toHaveLength(1);
});
it("keeps archived channels read-only", () => {
const archived = channel({ archivedAtIso: "2026-07-15T09:00:00.000Z" });
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: archived,
messages: [],
readReceipts: [],
attachments: [],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:0",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.composer).toMatchObject({ enabled: false, canSend: false, disabledReasonKey: "chat.composer.archived" });
});
it("derives edit and delete actions from the deterministic 24-hour window and fresh admin capabilities", () => {
const ownMessage = { ...channel().lastMessage!, authorUserId: "user_me" };
const detail = (memberRole: "admin" | "member", message = ownMessage): ChatMemberChannelDetail => ({
channel: channel({ kind: "group", name: "Team", member: { ...channel().member, roleInChat: memberRole }, lastMessage: message }),
messages: [message],
readReceipts: [],
attachments: [],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:8",
});
const freshOwn = buildMemberChatChannelDetailVM({
detail: detail("member"),
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
nowIso: "2026-07-16T09:00:00.000Z",
labels,
});
const expiredOwn = buildMemberChatChannelDetailVM({
detail: detail("member"),
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
nowIso: "2026-07-17T11:00:00.000Z",
labels,
});
const channelAdmin = buildMemberChatChannelDetailVM({
detail: detail("admin", channel().lastMessage!),
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
nowIso: "2026-07-17T11:00:00.000Z",
labels,
});
const globalAdmin = buildMemberChatChannelDetailVM({
detail: detail("member", channel().lastMessage!),
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write", "chat.admin"],
nowIso: "2026-07-17T11:00:00.000Z",
labels,
});
expect(freshOwn.status === "ready" && freshOwn.data.messages[0]?.actions).toMatchObject({ canEdit: true, canDelete: true });
expect(expiredOwn.status === "ready" && expiredOwn.data.messages[0]?.actions).toMatchObject({ canEdit: false, canDelete: false });
expect(channelAdmin.status === "ready" && channelAdmin.data.messages[0]?.actions).toMatchObject({ canEdit: false, canDelete: true });
expect(globalAdmin.status === "ready" && globalAdmin.data.messages[0]?.actions).toMatchObject({ canEdit: true, canDelete: true });
});
it("maps actorless system messages fail-soft without author, receipts, or message actions", () => {
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: channel({ lastMessage: systemMessage() }),
messages: [
systemMessage(),
systemMessage({
id: "system_message_2",
clientMessageId: "system:future",
systemEvent: { kind: "channel_renamed", metadata: { internalId: "secret" } },
}),
],
readReceipts: [{ messageId: "system_message_1", userId: "user_me", readAtIso: "2026-07-15T10:01:00.000Z" }],
attachments: [],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:8",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.messages[0]).toMatchObject({
author: null,
bodyMarkdown: null,
bodyFormat: "system",
readAggregate: null,
systemEvent: {
kind: "project_created",
labelKey: "chat.systemEvent.projectCreated",
values: { project: "Wärmepumpe Müller" },
},
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
});
expect(vm.data.messages[1]?.systemEvent).toEqual({
kind: "channel_renamed",
labelKey: "chat.systemEvent.generic",
values: {},
});
});
it("keeps deleted message projections free of stale mention and preview metadata", () => {
const deletedMessage = {
...channel().lastMessage!,
body: "deleted secret",
deletedAt: "2026-07-15T10:02:00.000Z",
mentions: [{ type: "user" as const, id: "user_me", label: null }],
linkPreviews: [
{
url: "https://example.com/secret",
title: "Secret",
description: null,
imageUrl: null,
siteName: "Example",
},
],
};
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: channel(),
messages: [deletedMessage],
readReceipts: [],
attachments: [
{
messageId: deletedMessage.id,
fileId: "file_secret",
displayName: "secret.pdf",
mimeType: "application/pdf",
sizeBytes: 10,
linkRole: "file",
previewStatus: "not_supported",
scanStatus: "clean",
},
],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:1",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.messages[0]).toMatchObject({
bodyMarkdown: null,
mentions: [],
linkPreviews: [],
attachments: [],
deletedAtIso: "2026-07-15T10:02:00.000Z",
});
});
it("maps skipped attachment scans fail-closed instead of exposing a download", () => {
const persisted = channel().lastMessage!;
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: channel(),
messages: [persisted],
readReceipts: [],
attachments: [
{
messageId: persisted.id,
fileId: "file_skipped",
displayName: "unchecked.pdf",
mimeType: "application/pdf",
sizeBytes: 20,
linkRole: "file",
previewStatus: "not_supported",
scanStatus: "skipped",
},
],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:1",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels"],
labels,
});
expect(vm.status === "ready" ? vm.data.messages[0]?.attachments[0]?.scanStatus : null).toBe("blocked");
});
});
@@ -0,0 +1,502 @@
import {
CHAT_PERMISSIONS,
type ChatAttachmentRecord,
type ChatMemberChannelDetail,
type ChatMemberChannelRecord,
type ChatParticipantProfileRecord,
} from "@hivegrid/chat";
import { buildChatMessageDeepLink } from "@hivegrid/chat/deep-links";
import type { DiscoverablePublicGroupChat } from "@hivegrid/chat/discovery.server";
import { CHAT_MESSAGE_MAX_BODY_LENGTH, type ChatMention, type ChatRealtimeMessage } from "@hivegrid/realtime";
import {
buildChatChannelDetailVM,
buildChatChannelListVM,
buildChatSystemEventVM,
type ChatAvatarVM,
type ChatAttachmentVM,
type ChatChannelDetailVM,
type ChatChannelListFilterState,
type ChatChannelListRowInput,
type ChatChannelListVM,
type ChatMessageCandidate,
type ChatReadAggregateVM,
type ChatResolvedAuthorVM,
type ChatResolvedMentionVM,
} from "@hivegrid/view-models";
import { mediaVariantPath } from "~/utils/integrations/fileRoutePaths";
import {
chatArchivedPath,
chatChannelPath,
chatChannelSettingsPath,
chatPinnedPath,
chatIndexPath,
chatMentionsPath,
chatNewPath,
chatSearchPath,
chatThreadPath,
} from "../routes/chatRoutePaths";
const CHAT_LIST_SNIPPET_MAX_LENGTH = 160;
export type ChatViewModelLabels = {
readonly directMessage: string;
readonly unnamedGroup: string;
readonly unnamedProject: string;
readonly unknownUser: string;
readonly unknownMention: string;
};
type ChatListViewModelInput = {
readonly channels: readonly ChatMemberChannelRecord[];
readonly tenantSlug: string;
readonly currentUserId: string;
readonly permissions: readonly string[];
readonly filter: ChatChannelListFilterState;
readonly nextCursor: string | null;
readonly discoverChannels?: readonly DiscoverablePublicGroupChat[];
readonly labels: ChatViewModelLabels;
};
type ChatDetailViewModelInput = {
readonly detail: ChatMemberChannelDetail;
readonly tenantSlug: string;
readonly currentUserId: string;
readonly permissions: readonly string[];
readonly featureAvailability?: { readonly files: boolean; readonly tasks: boolean };
/** Injected by the server assembler so the pure builder enforces the 24-hour window deterministically. */
readonly nowIso?: string;
readonly labels: ChatViewModelLabels;
};
/** Maps the already RLS-scoped repository projection to the serializable list
* contract. Filtering remains deterministic and does not trigger client-side
* data access or a second permission path. */
export function buildMemberChatChannelListVM(input: ChatListViewModelInput): ChatChannelListVM {
const rows = input.channels.map((channel) => toChannelListRow(channel, input));
return buildChatChannelListVM({
rows,
discoverRows: (input.discoverChannels ?? []).map((channel) => ({
id: channel.id,
title: channel.name,
description: channel.description,
avatar: fallbackAvatar(channel.name),
memberCount: channel.memberCount,
isJoined: false,
canJoin: true,
joinHref: chatIndexPath(input.tenantSlug),
detailHref: null,
})),
filter: input.filter,
permissions: {
canWrite: hasPermission(input.permissions, CHAT_PERMISSIONS.write),
canCreateGroup: hasPermission(input.permissions, CHAT_PERMISSIONS.createChannel),
canCreateDm: hasPermission(input.permissions, CHAT_PERMISSIONS.createDm),
canDiscover: input.discoverChannels !== undefined && hasPermission(input.permissions, CHAT_PERMISSIONS.readOwnChannels),
canViewMentions: hasPermission(input.permissions, CHAT_PERMISSIONS.readOwnChannels),
canSearch: hasPermission(input.permissions, CHAT_PERMISSIONS.readOwnChannels),
canViewArchived: hasPermission(input.permissions, CHAT_PERMISSIONS.readOwnChannels),
canAdmin: hasPermission(input.permissions, CHAT_PERMISSIONS.admin),
},
hrefs: {
newChannel: `${chatNewPath(input.tenantSlug)}?kind=group`,
newDm: `${chatNewPath(input.tenantSlug)}?kind=dm`,
search: chatSearchPath(input.tenantSlug),
mentions: chatMentionsPath(input.tenantSlug),
archived: chatArchivedPath(input.tenantSlug),
},
totals: {
unread: input.channels.reduce((total, channel) => total + channel.unreadCount, 0),
mentions: input.channels.filter((channel) => channel.hasUnreadMention).length,
},
nextCursor: input.nextCursor,
});
}
/** Builds the first member-channel live-loop without exposing unfinished
* thread/reaction/file/pin actions. Repository data is already authorized and
* contains every profile/read projection needed by this mapper. */
export function buildMemberChatChannelDetailVM(input: ChatDetailViewModelInput): ChatChannelDetailVM {
const { channel } = input.detail;
const profiles = new Map(channel.participants.map((participant) => [participant.userId, participant]));
const title = resolveChannelTitle(channel, input.currentUserId, input.labels);
const counterpart = resolveDmCounterpart(channel, input.currentUserId);
const canWrite = hasPermission(input.permissions, CHAT_PERMISSIONS.write) && channel.archivedAtIso === null && channel.member.canWrite;
const canManageGroup = channel.kind === "group" && (channel.member.roleInChat === "admin" || hasPermission(input.permissions, CHAT_PERMISSIONS.admin));
const featuresByMessageId = new Map((input.detail.messageFeatures ?? []).map((feature) => [feature.messageId, feature]));
const attachmentsByMessageId = new Map<string, ChatMemberChannelDetail["attachments"]>();
for (const attachment of input.detail.attachments ?? []) {
attachmentsByMessageId.set(attachment.messageId, [...(attachmentsByMessageId.get(attachment.messageId) ?? []), attachment]);
}
const canAttachFiles = canWrite && input.featureAvailability?.files === true && hasPermission(input.permissions, "files.write");
const canMarkAsTask = canWrite && input.featureAvailability?.tasks === true && hasPermission(input.permissions, "tasks.write");
const canPinAnyMessage = channel.member.roleInChat === "admin" || hasPermission(input.permissions, CHAT_PERMISSIONS.admin);
const canAdministerMessages = hasPermission(input.permissions, CHAT_PERMISSIONS.admin);
const canDeleteAsChannelAdmin = channel.member.roleInChat === "admin" || canAdministerMessages;
return buildChatChannelDetailVM({
header: {
id: channel.id,
kind: channel.kind,
title,
subtitle: channel.description,
avatar: counterpart ? participantAvatar(counterpart) : fallbackAvatar(title),
project: null,
memberCount: channel.memberCount,
isPrivate: channel.isPrivate,
isArchived: channel.archivedAtIso !== null,
isAuditMode: false,
canManage: canManageGroup,
settingsHref: chatChannelSettingsPath(input.tenantSlug, channel.id),
pinnedHref: channel.kind === "dm" ? null : chatPinnedPath(input.tenantSlug, channel.id),
searchHref: chatIndexPath(input.tenantSlug),
},
messages: input.detail.messages.map((message) =>
toMessageCandidate({
message,
profiles,
readReceipts: input.detail.readReceipts,
memberCount: channel.memberCount,
currentUserId: input.currentUserId,
tenantSlug: input.tenantSlug,
labels: input.labels,
feature: featuresByMessageId.get(message.id) ?? null,
canWrite,
channelKind: channel.kind,
chatId: channel.id,
attachments: attachmentsByMessageId.get(message.id) ?? [],
canMarkAsTask,
canPinAnyMessage,
canAdministerMessages,
canDeleteAsChannelAdmin,
nowIso: input.nowIso ?? "9999-12-31T23:59:59.999Z",
})
),
pinnedMessages: input.detail.messages.flatMap((message) => {
const feature = featuresByMessageId.get(message.id);
if (!feature?.pin || message.bodyFormat !== "markdown") return [];
return [
{
messageId: message.id,
authorLabel: profiles.get(message.authorUserId)?.displayName ?? input.labels.unknownUser,
snippet: chatListSnippet(message.body),
pinnedAtIso: feature.pin.pinnedAtIso,
pinnedByLabel: profiles.get(feature.pin.pinnedByUserId)?.displayName ?? input.labels.unknownUser,
href: buildChatMessageDeepLink({ tenantSlug: input.tenantSlug, chatId: channel.id, messageId: message.id }),
},
];
}),
typingLabels: [],
history: {
olderCursor: input.detail.olderMessageCursor,
hasOlder: input.detail.hasOlderMessages,
},
composer: {
canSend: canWrite,
canAttachFiles,
canRecordVoice: canAttachFiles,
canMention: canWrite,
canMarkAsTask,
disabledReasonKey: canWrite ? null : channel.archivedAtIso ? "chat.composer.archived" : "chat.composer.permissionDenied",
draftStorageKey: `chat:draft:v1:${input.tenantSlug}:${input.currentUserId}:${channel.id}`,
maxBodyLength: CHAT_MESSAGE_MAX_BODY_LENGTH,
},
connection: {
state: "connecting",
reconnectAttempt: 0,
retryAtIso: null,
},
});
}
export function buildChatResolvedAuthors(participants: readonly ChatParticipantProfileRecord[], currentUserId: string): readonly ChatResolvedAuthorVM[] {
return participants.map((participant) => ({
userId: participant.userId,
displayName: participant.displayName,
avatar: participantAvatar(participant),
isCurrentUser: participant.userId === currentUserId,
}));
}
function toChannelListRow(channel: ChatMemberChannelRecord, input: ChatListViewModelInput): ChatChannelListRowInput {
const title = resolveChannelTitle(channel, input.currentUserId, input.labels);
const counterpart = resolveDmCounterpart(channel, input.currentUserId);
const lastMessageAuthor = channel.lastMessage?.bodyFormat === "markdown" ? findParticipant(channel.participants, channel.lastMessage.authorUserId) : null;
return {
id: channel.id,
kind: channel.kind,
title,
subtitle: channel.description,
detailHref: chatChannelPath(input.tenantSlug, channel.id),
avatar: counterpart ? participantAvatar(counterpart) : fallbackAvatar(title),
project: null,
lastMessage: channel.lastMessage
? {
authorLabel: channel.lastMessage.bodyFormat === "system" ? null : (lastMessageAuthor?.displayName ?? input.labels.unknownUser),
snippet: channel.lastMessage.bodyFormat === "system" || channel.lastMessage.deletedAt ? "" : chatListSnippet(channel.lastMessage.body),
systemEvent:
channel.lastMessage.bodyFormat === "system"
? buildChatSystemEventVM(channel.lastMessage.systemEvent.kind, channel.lastMessage.systemEvent.metadata)
: null,
createdAtIso: channel.lastMessage.createdAt,
}
: null,
typingLabels: [],
unreadCount: channel.unreadCount,
hasMention: channel.hasUnreadMention,
isPinned: channel.member.isPinned,
isPrivate: channel.isPrivate,
notificationPreference: channel.member.notificationPreference,
archivedAtIso: channel.archivedAtIso,
memberCount: channel.memberCount,
canManage: false,
};
}
function chatListSnippet(markdown: string): string {
const plainText = markdown
.replace(/<[^>]*>/g, " ")
.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.replace(/[`*_~>#]/g, " ")
.replace(/^\s*[-+]\s+/gm, "")
.replace(/\s+/g, " ")
.trim();
if (plainText.length <= CHAT_LIST_SNIPPET_MAX_LENGTH) return plainText;
return `${plainText.slice(0, CHAT_LIST_SNIPPET_MAX_LENGTH - 1).trimEnd()}…`;
}
function toMessageCandidate(input: {
readonly message: ChatRealtimeMessage;
readonly profiles: ReadonlyMap<string, ChatParticipantProfileRecord>;
readonly readReceipts: ChatMemberChannelDetail["readReceipts"];
readonly memberCount: number;
readonly currentUserId: string;
readonly tenantSlug: string;
readonly labels: ChatViewModelLabels;
readonly feature: NonNullable<ChatMemberChannelDetail["messageFeatures"]>[number] | null;
readonly canWrite: boolean;
readonly channelKind: ChatMemberChannelRecord["kind"];
readonly chatId: string;
readonly attachments: ChatMemberChannelDetail["attachments"];
readonly canMarkAsTask: boolean;
readonly canPinAnyMessage: boolean;
readonly canAdministerMessages: boolean;
readonly canDeleteAsChannelAdmin: boolean;
readonly nowIso: string;
}): ChatMessageCandidate {
if (input.message.bodyFormat === "system") {
return {
id: input.message.id,
clientMessageId: input.message.clientMessageId,
source: "persisted",
deliveryState: "sent",
failureReasonKey: null,
author: null,
bodyMarkdown: null,
bodyFormat: "system",
systemEvent: buildChatSystemEventVM(input.message.systemEvent.kind, input.message.systemEvent.metadata),
createdAtIso: input.message.createdAt,
updatedAtIso: input.message.updatedAt,
editedAtIso: input.message.editedAt,
deletedAtIso: input.message.deletedAt,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: null,
pin: null,
actions: NO_MESSAGE_ACTIONS,
};
}
const profile = input.profiles.get(input.message.authorUserId);
const readerProfiles = input.readReceipts
.filter((receipt) => receipt.messageId === input.message.id && receipt.userId !== input.message.authorUserId)
.map((receipt) => input.profiles.get(receipt.userId))
.filter((reader): reader is ChatParticipantProfileRecord => reader !== undefined);
const reactionGroups = new Map<string, string[]>();
for (const reaction of input.feature?.reactions ?? []) {
const reactors = reactionGroups.get(reaction.emoji) ?? [];
reactors.push(reaction.userId);
reactionGroups.set(reaction.emoji, reactors);
}
const reactions = [...reactionGroups.entries()].map(([emoji, userIds]) => ({
emoji,
count: userIds.length,
reactedByViewer: userIds.includes(input.currentUserId),
reactorLabels: userIds.map((userId) => input.profiles.get(userId)?.displayName ?? input.labels.unknownUser),
}));
const thread = input.feature?.thread
? {
id: input.feature.thread.id,
replyCount: input.feature.thread.replyCount,
participantLabels: input.feature.thread.participantUserIds.map((userId) => input.profiles.get(userId)?.displayName ?? input.labels.unknownUser),
lastReplyAtIso: input.feature.thread.lastReplyAtIso,
isFollowing: input.feature.thread.participantUserIds.includes(input.currentUserId),
href: chatThreadPath(input.tenantSlug, input.chatId, input.feature.thread.id),
}
: null;
const pin = input.feature?.pin
? {
pinnedAtIso: input.feature.pin.pinnedAtIso,
pinnedByLabel: input.profiles.get(input.feature.pin.pinnedByUserId)?.displayName ?? input.labels.unknownUser,
note: input.feature.pin.note,
}
: null;
const deleted = input.message.deletedAt !== null;
const ownMessage = input.message.authorUserId === input.currentUserId;
const ageMs = Date.parse(input.nowIso) - Date.parse(input.message.createdAt);
const withinOwnMutationWindow = Number.isFinite(ageMs) && ageMs >= 0 && ageMs <= 24 * 60 * 60 * 1_000;
return {
id: input.message.id,
clientMessageId: input.message.clientMessageId,
source: "persisted",
deliveryState: "sent",
failureReasonKey: null,
author: {
userId: input.message.authorUserId,
displayName: profile?.displayName ?? input.labels.unknownUser,
avatar: profile ? participantAvatar(profile) : fallbackAvatar(input.labels.unknownUser),
isCurrentUser: input.message.authorUserId === input.currentUserId,
},
bodyMarkdown: deleted ? null : input.message.body,
bodyFormat: input.message.bodyFormat,
systemEvent: null,
createdAtIso: input.message.createdAt,
updatedAtIso: input.message.updatedAt,
editedAtIso: input.message.editedAt,
deletedAtIso: input.message.deletedAt,
parentMessageId: input.message.parentMessageId,
mentions: deleted ? [] : input.message.mentions.map((mention) => toChatResolvedMentionVM(mention, input.profiles, input.tenantSlug, input.labels)),
reactions,
thread,
attachments: deleted ? [] : input.attachments.map((attachment) => toChatAttachmentVM(attachment, input.tenantSlug)),
linkPreviews: deleted ? [] : input.message.linkPreviews,
readAggregate: toReadAggregate(readerProfiles, input.memberCount),
pin,
actions: {
canReact: input.canWrite && !deleted,
canReply: input.canWrite && !deleted,
canEdit: input.canWrite && !deleted && (input.canAdministerMessages || (ownMessage && withinOwnMutationWindow)),
canDelete: input.canWrite && !deleted && (input.canDeleteAsChannelAdmin || (ownMessage && withinOwnMutationWindow)),
canPin: input.canWrite && !deleted && input.channelKind !== "dm" && (ownMessage || input.canPinAnyMessage),
canMarkAsTask: input.canMarkAsTask && !deleted,
},
};
}
export function toChatAttachmentVM(attachment: ChatAttachmentRecord, tenantSlug: string): ChatAttachmentVM {
return {
id: `${attachment.messageId}:${attachment.fileId}`,
fileId: attachment.fileId,
kind:
attachment.linkRole === "voice" || attachment.mimeType.startsWith("audio/")
? "voice"
: attachment.linkRole === "image" || attachment.mimeType.startsWith("image/")
? "image"
: "file",
fileName: attachment.displayName,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
downloadHref: mediaVariantPath(tenantSlug, attachment.fileId, "original"),
previewHref:
attachment.mimeType.startsWith("image/") && attachment.previewStatus === "ready" ? mediaVariantPath(tenantSlug, attachment.fileId, "preview") : null,
altText: attachment.mimeType.startsWith("image/") ? attachment.displayName : null,
durationSeconds: null,
scanStatus: attachment.scanStatus === "clean" ? "clean" : attachment.scanStatus === "pending" ? "pending" : "blocked",
};
}
const NO_MESSAGE_ACTIONS = Object.freeze({
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
});
export function toChatResolvedMentionVM(
mention: ChatMention,
profiles: ReadonlyMap<string, ChatParticipantProfileRecord>,
tenantSlug: string,
labels: ChatViewModelLabels
): ChatResolvedMentionVM {
const userLabel = mention.type === "user" ? profiles.get(mention.id)?.displayName : null;
const href =
mention.type === "project"
? `/${tenantSlug}/projects/${encodeURIComponent(mention.id)}`
: mention.type === "contact"
? `/${tenantSlug}/contacts/${encodeURIComponent(mention.id)}`
: mention.type === "company"
? `/${tenantSlug}/contacts/companies/${encodeURIComponent(mention.id)}`
: null;
return {
kind: mention.type,
id: mention.id,
label: userLabel ?? mention.label ?? labels.unknownMention,
href,
};
}
function toReadAggregate(readers: readonly ChatParticipantProfileRecord[], memberCount: number): ChatReadAggregateVM {
const uniqueReaders = [...new Map(readers.map((reader) => [reader.userId, reader])).values()];
return {
readCount: uniqueReaders.length,
recipientCount: Math.max(0, memberCount - 1),
readerUserIds: uniqueReaders.map((reader) => reader.userId),
readerLabels: uniqueReaders.map((reader) => reader.displayName),
labelKey: "chat.message.read.aggregate",
};
}
function resolveChannelTitle(channel: ChatMemberChannelRecord, currentUserId: string, labels: ChatViewModelLabels): string {
if (channel.kind === "dm") {
return resolveDmCounterpart(channel, currentUserId)?.displayName ?? labels.directMessage;
}
const name = channel.name?.trim();
if (name) return name;
return channel.kind === "project" ? labels.unnamedProject : labels.unnamedGroup;
}
function resolveDmCounterpart(channel: ChatMemberChannelRecord, currentUserId: string): ChatParticipantProfileRecord | null {
if (channel.kind !== "dm") return null;
return channel.participants.find((participant) => participant.userId !== currentUserId) ?? null;
}
function findParticipant(participants: readonly ChatParticipantProfileRecord[], userId: string): ChatParticipantProfileRecord | null {
return participants.find((participant) => participant.userId === userId) ?? null;
}
function participantAvatar(participant: ChatParticipantProfileRecord): ChatAvatarVM {
return {
imageUrl: participant.avatarUrl,
fallbackLabel: initials(participant.displayName),
};
}
function fallbackAvatar(label: string): ChatAvatarVM {
return { imageUrl: null, fallbackLabel: initials(label) };
}
function initials(label: string): string {
const result = label
.trim()
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0]?.toLocaleUpperCase() ?? "")
.join("");
return result || "?";
}
function hasPermission(permissions: readonly string[], permission: string): boolean {
return permissions.includes(permission);
}
@@ -0,0 +1,63 @@
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadChatContext: vi.fn(),
findMemberProjectChatLink: vi.fn(),
}));
vi.mock("../routes/chatAccess.server", () => ({
loadChatContext: mocks.loadChatContext,
}));
vi.mock("@hivegrid/chat/project-link.server", () => ({
findMemberProjectChatLink: mocks.findMemberProjectChatLink,
}));
import { loadOptionalProjectChatLink } from "./projectChatLink.server";
const request = new Request("https://app.example.test/demo/projects/project_1");
const params = { tenant: "demo", id: "project_1" };
const context = {
tenantId: "tenant_1",
userId: "user_1",
tenantUserId: "tenant_user_1",
permissions: ["chat.read_own_channels"],
hasModule: true as const,
};
describe("optional project chat link", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadChatContext.mockResolvedValue(context);
mocks.findMemberProjectChatLink.mockResolvedValue({ chatId: "chat_1", archivedAtIso: null, canWrite: true });
});
it("gates the repository lookup through the tenant chat context", async () => {
await expect(loadOptionalProjectChatLink({ request, params, projectId: "project_1" })).resolves.toEqual({
chatId: "chat_1",
archivedAtIso: null,
canWrite: true,
});
expect(mocks.loadChatContext).toHaveBeenCalledWith({ request, params });
expect(mocks.findMemberProjectChatLink).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: ["chat.read_own_channels"],
projectId: "project_1",
});
});
it("hides the affordance when the module, permission or membership is unavailable", async () => {
mocks.loadChatContext.mockRejectedValue(new CatalogError(foundationErrors.notFound));
await expect(loadOptionalProjectChatLink({ request, params, projectId: "project_1" })).resolves.toBeNull();
expect(mocks.findMemberProjectChatLink).not.toHaveBeenCalled();
});
it("does not swallow operational failures", async () => {
mocks.findMemberProjectChatLink.mockRejectedValue(new Error("database unavailable"));
await expect(loadOptionalProjectChatLink({ request, params, projectId: "project_1" })).rejects.toThrow("database unavailable");
});
});
@@ -0,0 +1,25 @@
import { findMemberProjectChatLink, type MemberProjectChatLink } from "@hivegrid/chat/project-link.server";
import { CatalogError } from "@hivegrid/foundation";
import { loadChatContext } from "../routes/chatAccess.server";
export async function loadOptionalProjectChatLink(input: {
readonly request: Request;
readonly params: Record<string, string | undefined>;
readonly projectId: string;
}): Promise<MemberProjectChatLink | null> {
try {
const context = await loadChatContext({ request: input.request, params: input.params });
return await findMemberProjectChatLink({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
projectId: input.projectId,
});
} catch (error) {
// Chat is optional on the project surface. Missing module, permission or
// membership all resolve to the same absent affordance.
if (error instanceof CatalogError && error.status === 404) return null;
throw error;
}
}