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,253 @@
import { describe, expect, it } from "vitest";
import type { ChatChannelDetailVM, ChatFeatureMessageVM, ChatMessageVM, ChatPinnedMessagesVM, ChatThreadVM } from "@hivegrid/view-models";
import {
beginChatFeatureMutation,
chatFeatureErrorsByMessageId,
failedChatFeatureMutationForMessage,
overlayChatChannelFeatureMutations,
overlayChatPinnedFeatureMutations,
overlayChatThreadFeatureMutations,
reconcileChatChannelFeatureMutations,
reconcileChatPinnedFeatureMutations,
retryChatFeatureMutation,
settleChatFeatureMutation,
type ChatOptimisticFeatureMutationInput,
} from "./ChatFeatureOptimistic";
const reactionMutation: ChatOptimisticFeatureMutationInput = {
kind: "reaction",
requestId: "request_reaction",
messageId: "message_1",
emoji: "👍",
active: true,
actorLabel: "Raffael",
startedAtIso: "2026-07-16T09:00:00.000Z",
};
const pinMutation: ChatOptimisticFeatureMutationInput = {
kind: "pin",
requestId: "request_pin",
messageId: "message_1",
pinned: false,
actorLabel: "Raffael",
startedAtIso: "2026-07-16T09:00:00.000Z",
};
describe("chat feature optimistic overlays", () => {
it("sets a reaction immediately and never doubles the count when the authoritative echo arrives", () => {
const pending = beginChatFeatureMutation([], reactionMutation);
const optimistic = overlayChatChannelFeatureMutations(channelVM(message()), pending);
expect(readyChannelMessage(optimistic).reactions).toEqual([
{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] },
]);
const confirmed = settleChatFeatureMutation(pending, reactionMutation.requestId, { ok: true, errorKey: null });
const echoed = channelVM(
message({ reactions: [{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] }] })
);
expect(readyChannelMessage(overlayChatChannelFeatureMutations(echoed, confirmed)).reactions[0]?.count).toBe(1);
expect(reconcileChatChannelFeatureMutations(confirmed, echoed)).toEqual([]);
});
it("rolls a rejected reaction back, keeps an element-local error, and retries the same request id", () => {
const pending = beginChatFeatureMutation([], reactionMutation);
const failed = settleChatFeatureMutation(pending, reactionMutation.requestId, {
ok: false,
errorKey: "chat.errors.invalidInput",
});
expect(readyChannelMessage(overlayChatChannelFeatureMutations(channelVM(message()), failed)).reactions).toEqual([]);
expect(chatFeatureErrorsByMessageId(failed)).toEqual({ message_1: "chat.errors.invalidInput" });
expect(failedChatFeatureMutationForMessage(failed, "message_1")?.requestId).toBe("request_reaction");
expect(retryChatFeatureMutation(failed, "request_reaction")).toMatchObject([
{ requestId: "request_reaction", status: "pending", errorKey: null },
]);
});
it("removes a pin optimistically and restores it after an error", () => {
const canonical = channelVM(message({ pin: { pinnedAtIso: "2026-07-16T08:00:00.000Z", pinnedByLabel: "Ada", note: null } }));
const pending = beginChatFeatureMutation([], pinMutation);
expect(readyChannelMessage(overlayChatChannelFeatureMutations(canonical, pending)).pin).toBeNull();
const failed = settleChatFeatureMutation(pending, pinMutation.requestId, { ok: false, errorKey: "chat.errors.pinLimitReached" });
expect(readyChannelMessage(overlayChatChannelFeatureMutations(canonical, failed)).pin).not.toBeNull();
});
it("hides a pinned row until the loader echo confirms it without duplicating state", () => {
const canonical = pinnedVM([featureMessage({ pinned: true })]);
const pending = beginChatFeatureMutation([], pinMutation);
expect(readyPinnedRows(overlayChatPinnedFeatureMutations(canonical, pending))).toHaveLength(0);
const failed = settleChatFeatureMutation(pending, pinMutation.requestId, { ok: false, errorKey: "chat.errors.invalidInput" });
expect(readyPinnedRows(overlayChatPinnedFeatureMutations(canonical, failed))).toHaveLength(1);
const confirmed = settleChatFeatureMutation(pending, pinMutation.requestId, { ok: true, errorKey: null });
const authoritative = pinnedVM([]);
expect(reconcileChatPinnedFeatureMutations(confirmed, authoritative)).toEqual([]);
});
it("applies the same set-semantics reaction overlay in a thread", () => {
const pending = beginChatFeatureMutation([], reactionMutation);
const overlaid = overlayChatThreadFeatureMutations(threadVM(featureMessage()), pending);
expect(overlaid.status === "ready" ? overlaid.data.parent.reactions : []).toEqual([
{ emoji: "👍", count: 1, reactedByViewer: true },
]);
});
});
function message(overrides: Partial<ChatMessageVM> = {}): ChatMessageVM {
return {
id: "message_1",
clientMessageId: "client_1",
source: "persisted",
deliveryState: "sent",
deliveryStateKey: "chat.message.delivery.sent",
failureReasonKey: null,
retryable: false,
author: {
userId: "user_1",
displayName: "Raffael",
avatar: { imageUrl: null, fallbackLabel: "R" },
isCurrentUser: true,
},
bodyMarkdown: "Hello",
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: "2026-07-16T08:00:00.000Z",
updatedAtIso: "2026-07-16T08:00:00.000Z",
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: { readCount: 0, recipientCount: 0, readerUserIds: [], readerLabels: [], labelKey: "chat.message.read.none" },
pin: null,
actions: { canReact: true, canReply: true, canEdit: false, canDelete: false, canPin: true, canMarkAsTask: false },
tombstoneKey: null,
...overrides,
};
}
function channelVM(item: ChatMessageVM): ChatChannelDetailVM {
return {
status: "ready",
data: {
header: {
id: "chat_1",
kind: "group",
title: "Team",
subtitle: null,
avatar: { imageUrl: null, fallbackLabel: "T" },
project: null,
memberCount: 2,
isPrivate: false,
isArchived: false,
isAuditMode: false,
dmAuditBannerKey: null,
canManage: false,
settingsHref: null,
pinnedHref: "/demo/chat/chat_1/pinned",
searchHref: "/demo/chat/search",
},
messages: [item],
messageGroups: [{ dateIso: "2026-07-16", messages: [item] }],
presence: [],
typingLabels: [],
pinnedMessages: item.pin
? [{ messageId: item.id, authorLabel: "Raffael", snippet: "Hello", pinnedAtIso: item.pin.pinnedAtIso, pinnedByLabel: item.pin.pinnedByLabel, href: "#message-message_1" }]
: [],
history: { olderCursor: null, hasOlder: false },
composer: {
enabled: true,
disabledReasonKey: null,
canSend: true,
canAttachFiles: false,
canRecordVoice: false,
canMention: false,
canMarkAsTask: false,
draftStorageKey: "draft",
maxBodyLength: 10_000,
placeholderKey: "chat.composer.placeholder",
},
connection: { state: "online", stateLabelKey: "chat.connection.online", reconnectAttempt: 0, retryAtIso: null, canRetry: false },
emptyHeadlineKey: "chat.empty.headline",
emptyBodyKey: "chat.empty.body",
loadOlderLabelKey: "chat.message.loadOlder",
newMessagesLabelKey: "chat.message.newMessages",
},
};
}
function featureMessage(overrides: Partial<ChatFeatureMessageVM> = {}): ChatFeatureMessageVM {
return {
id: "message_1",
authorLabel: "Raffael",
authorAvatarUrl: null,
bodyMarkdown: "Hello",
createdAtIso: "2026-07-16T08:00:00.000Z",
deleted: false,
mentions: [],
attachments: [],
reactions: [],
pinned: false,
canReact: true,
canPin: true,
canEdit: true,
canDelete: true,
...overrides,
};
}
function threadVM(parent: ChatFeatureMessageVM): ChatThreadVM {
return {
status: "ready",
data: {
chatId: "chat_1",
threadId: parent.id,
channelTitle: "Team",
backHref: "/demo/chat/chat_1",
parent,
replies: [],
replyCount: 0,
canReply: true,
composerPlaceholderKey: "chat.thread.composerPlaceholder",
emptyRepliesHeadlineKey: "chat.thread.empty.headline",
emptyRepliesBodyKey: "chat.thread.empty.body",
},
};
}
function pinnedVM(messages: readonly ChatFeatureMessageVM[]): ChatPinnedMessagesVM {
return {
status: "ready",
data: {
chatId: "chat_1",
channelTitle: "Team",
backHref: "/demo/chat/chat_1",
rows: messages.map((item) => ({
message: item,
pinnedAtIso: "2026-07-16T08:00:00.000Z",
pinnedByLabel: "Raffael",
note: null,
messageHref: "/demo/chat/chat_1#message-message_1",
canUnpin: true,
})),
emptyHeadlineKey: "chat.pinned.empty.headline",
emptyBodyKey: "chat.pinned.empty.body",
},
};
}
function readyChannelMessage(vm: ChatChannelDetailVM): ChatMessageVM {
if (vm.status !== "ready") throw new Error("expected ready channel VM");
return vm.data.messages[0]!;
}
function readyPinnedRows(vm: ChatPinnedMessagesVM) {
if (vm.status !== "ready") throw new Error("expected ready pinned VM");
return vm.data.rows;
}
@@ -0,0 +1,270 @@
import type { ChatChannelDetailVM, ChatFeatureMessageVM, ChatMessageVM, ChatPinnedMessagesVM, ChatThreadVM } from "@hivegrid/view-models";
type FeatureMutationStatus = "pending" | "confirmed" | "failed";
const MAX_OPTIMISTIC_FEATURE_MUTATIONS = 100;
type FeatureMutationBase = {
readonly requestId: string;
readonly messageId: string;
readonly actorLabel: string;
readonly startedAtIso: string;
readonly status: FeatureMutationStatus;
readonly errorKey: string | null;
};
export type ChatOptimisticFeatureMutation =
| (FeatureMutationBase & {
readonly kind: "reaction";
readonly emoji: string;
readonly active: boolean;
})
| (FeatureMutationBase & {
readonly kind: "pin";
readonly pinned: boolean;
});
export type ChatOptimisticFeatureMutationInput =
| Omit<Extract<ChatOptimisticFeatureMutation, { kind: "reaction" }>, "status" | "errorKey">
| Omit<Extract<ChatOptimisticFeatureMutation, { kind: "pin" }>, "status" | "errorKey">;
export type ChatOptimisticFeatureState = readonly ChatOptimisticFeatureMutation[];
export function beginChatFeatureMutation(
state: ChatOptimisticFeatureState,
mutation: ChatOptimisticFeatureMutationInput
): ChatOptimisticFeatureState {
const next: ChatOptimisticFeatureMutation = { ...mutation, status: "pending", errorKey: null };
return [...state.filter((candidate) => candidate.requestId !== mutation.requestId && !sameFeature(candidate, next)), next].slice(
-MAX_OPTIMISTIC_FEATURE_MUTATIONS
);
}
export function settleChatFeatureMutation(
state: ChatOptimisticFeatureState,
requestId: string,
result: { readonly ok: boolean; readonly errorKey: string | null }
): ChatOptimisticFeatureState {
const status: FeatureMutationStatus = result.ok ? "confirmed" : "failed";
const errorKey = result.ok ? null : (result.errorKey ?? "chat.errors.invalidInput");
let changed = false;
const next = state.map<ChatOptimisticFeatureMutation>((mutation) => {
if (mutation.requestId !== requestId || (mutation.status === status && mutation.errorKey === errorKey)) return mutation;
changed = true;
return { ...mutation, status, errorKey };
});
return changed ? next : state;
}
export function retryChatFeatureMutation(
state: ChatOptimisticFeatureState,
requestId: string
): ChatOptimisticFeatureState {
return state.map<ChatOptimisticFeatureMutation>((mutation) =>
mutation.requestId === requestId ? { ...mutation, status: "pending", errorKey: null } : mutation
);
}
export function failedChatFeatureMutationForMessage(
state: ChatOptimisticFeatureState,
messageId: string
): ChatOptimisticFeatureMutation | null {
return [...state].reverse().find((mutation) => mutation.messageId === messageId && mutation.status === "failed") ?? null;
}
export function chatFeatureErrorsByMessageId(state: ChatOptimisticFeatureState): Readonly<Record<string, string>> {
const errors: Record<string, string> = {};
for (const mutation of state) {
if (mutation.status === "failed" && mutation.errorKey) errors[mutation.messageId] = mutation.errorKey;
}
return errors;
}
export function overlayChatChannelFeatureMutations(
vm: ChatChannelDetailVM,
state: ChatOptimisticFeatureState
): ChatChannelDetailVM {
if (vm.status !== "ready") return vm;
const overlayById = new Map(vm.data.messages.map((message) => [message.id, overlayChannelMessage(message, state)]));
return {
...vm,
data: {
...vm.data,
messages: vm.data.messages.map((message) => overlayById.get(message.id) ?? message),
messageGroups: vm.data.messageGroups.map((group) => ({
...group,
messages: group.messages.map((message) => overlayById.get(message.id) ?? message),
})),
pinnedMessages: vm.data.pinnedMessages.filter((row) => !isOptimisticallyUnpinned(state, row.messageId)),
},
};
}
export function overlayChatThreadFeatureMutations(vm: ChatThreadVM, state: ChatOptimisticFeatureState): ChatThreadVM {
if (vm.status !== "ready") return vm;
return {
...vm,
data: {
...vm.data,
parent: overlayFeatureMessage(vm.data.parent, state),
replies: vm.data.replies.map((message) => overlayFeatureMessage(message, state)),
},
};
}
export function overlayChatPinnedFeatureMutations(
vm: ChatPinnedMessagesVM,
state: ChatOptimisticFeatureState
): ChatPinnedMessagesVM {
if (vm.status !== "ready") return vm;
return {
...vm,
data: {
...vm.data,
rows: vm.data.rows.filter((row) => !isOptimisticallyUnpinned(state, row.message.id)),
},
};
}
export function reconcileChatChannelFeatureMutations(
state: ChatOptimisticFeatureState,
vm: ChatChannelDetailVM
): ChatOptimisticFeatureState {
if (vm.status !== "ready") return state;
const byId = new Map(vm.data.messages.map((message) => [message.id, message]));
return reconcileConfirmed(state, (mutation) => authoritativeChannelStateMatches(byId.get(mutation.messageId), mutation));
}
export function reconcileChatThreadFeatureMutations(
state: ChatOptimisticFeatureState,
vm: ChatThreadVM
): ChatOptimisticFeatureState {
if (vm.status !== "ready") return state;
const messages = [vm.data.parent, ...vm.data.replies];
const byId = new Map(messages.map((message) => [message.id, message]));
return reconcileConfirmed(state, (mutation) => authoritativeFeatureStateMatches(byId.get(mutation.messageId), mutation));
}
export function reconcileChatPinnedFeatureMutations(
state: ChatOptimisticFeatureState,
vm: ChatPinnedMessagesVM
): ChatOptimisticFeatureState {
if (vm.status !== "ready") return state;
const pinnedIds = new Set(vm.data.rows.map((row) => row.message.id));
return reconcileConfirmed(state, (mutation) => mutation.kind === "pin" && pinnedIds.has(mutation.messageId) === mutation.pinned);
}
function overlayChannelMessage(message: ChatMessageVM, state: ChatOptimisticFeatureState): ChatMessageVM {
let next = message;
for (const mutation of activeMutations(state, message.id)) {
if (mutation.kind === "reaction") {
next = { ...next, reactions: overlayReactions(next.reactions, mutation) };
} else {
next = {
...next,
pin: mutation.pinned
? { pinnedAtIso: mutation.startedAtIso, pinnedByLabel: mutation.actorLabel, note: null }
: null,
};
}
}
return next;
}
function overlayFeatureMessage(message: ChatFeatureMessageVM, state: ChatOptimisticFeatureState): ChatFeatureMessageVM {
let next = message;
for (const mutation of activeMutations(state, message.id)) {
if (mutation.kind === "reaction") {
next = {
...next,
reactions: overlayReactions(
next.reactions.map((reaction) => ({ ...reaction, reactorLabels: [] })),
mutation
).map(({ emoji, count, reactedByViewer }) => ({ emoji, count, reactedByViewer })),
};
} else {
next = { ...next, pinned: mutation.pinned };
}
}
return next;
}
type OverlayReaction = {
readonly emoji: string;
readonly count: number;
readonly reactedByViewer: boolean;
readonly reactorLabels: readonly string[];
};
function overlayReactions(
reactions: readonly OverlayReaction[],
mutation: Extract<ChatOptimisticFeatureMutation, { kind: "reaction" }>
): readonly OverlayReaction[] {
const current = reactions.find((reaction) => reaction.emoji === mutation.emoji);
if (current?.reactedByViewer === mutation.active || (!current && !mutation.active)) return reactions;
if (!current) {
return [
...reactions,
{
emoji: mutation.emoji,
count: 1,
reactedByViewer: true,
reactorLabels: [mutation.actorLabel],
},
];
}
const nextCount = current.count + (mutation.active ? 1 : -1);
if (nextCount <= 0) return reactions.filter((reaction) => reaction.emoji !== mutation.emoji);
const reactorLabels = mutation.active
? [...current.reactorLabels, mutation.actorLabel]
: removeFirst(current.reactorLabels, mutation.actorLabel);
return reactions.map((reaction) =>
reaction.emoji === mutation.emoji
? { ...reaction, count: nextCount, reactedByViewer: mutation.active, reactorLabels }
: reaction
);
}
function activeMutations(state: ChatOptimisticFeatureState, messageId: string): readonly ChatOptimisticFeatureMutation[] {
return state.filter((mutation) => mutation.messageId === messageId && mutation.status !== "failed");
}
function isOptimisticallyUnpinned(state: ChatOptimisticFeatureState, messageId: string): boolean {
return activeMutations(state, messageId).some((mutation) => mutation.kind === "pin" && !mutation.pinned);
}
function reconcileConfirmed(
state: ChatOptimisticFeatureState,
matches: (mutation: ChatOptimisticFeatureMutation) => boolean
): ChatOptimisticFeatureState {
const next = state.filter((mutation) => mutation.status !== "confirmed" || !matches(mutation));
return next.length === state.length ? state : next;
}
function authoritativeChannelStateMatches(
message: ChatMessageVM | undefined,
mutation: ChatOptimisticFeatureMutation
): boolean {
if (!message) return false;
if (mutation.kind === "pin") return (message.pin !== null) === mutation.pinned;
return (message.reactions.find((reaction) => reaction.emoji === mutation.emoji)?.reactedByViewer ?? false) === mutation.active;
}
function authoritativeFeatureStateMatches(
message: ChatFeatureMessageVM | undefined,
mutation: ChatOptimisticFeatureMutation
): boolean {
if (!message) return false;
if (mutation.kind === "pin") return message.pinned === mutation.pinned;
return (message.reactions.find((reaction) => reaction.emoji === mutation.emoji)?.reactedByViewer ?? false) === mutation.active;
}
function sameFeature(left: ChatOptimisticFeatureMutation, right: ChatOptimisticFeatureMutation): boolean {
if (left.messageId !== right.messageId || left.kind !== right.kind) return false;
return left.kind === "pin" || (right.kind === "reaction" && left.emoji === right.emoji);
}
function removeFirst(values: readonly string[], value: string): readonly string[] {
const index = values.indexOf(value);
if (index < 0) return values;
return [...values.slice(0, index), ...values.slice(index + 1)];
}
@@ -0,0 +1,99 @@
import { buildChatChannelDetailVM, type ChatResolvedAuthorVM } from "@hivegrid/view-models";
import { describe, expect, it } from "vitest";
import { overlayChatAttachmentSendAttempt, type ChatAttachmentSendAttempt } from "./chatAttachmentOptimistic";
const currentUser: ChatResolvedAuthorVM = {
userId: "user_1",
displayName: "Raffael",
avatar: { imageUrl: null, fallbackLabel: "RS" },
isCurrentUser: true,
};
function vm() {
return buildChatChannelDetailVM({
header: {
id: "chat_1",
kind: "group",
title: "Team",
subtitle: null,
avatar: { imageUrl: null, fallbackLabel: "T" },
project: null,
memberCount: 3,
isPrivate: true,
isArchived: false,
isAuditMode: false,
canManage: false,
settingsHref: null,
pinnedHref: null,
searchHref: "/demo/chat/search",
},
messages: [],
pinnedMessages: [],
typingLabels: [],
history: { hasOlder: false, olderCursor: null },
composer: {
disabledReasonKey: null,
canSend: true,
canAttachFiles: true,
canRecordVoice: true,
canMention: true,
canMarkAsTask: true,
draftStorageKey: "chat:draft:chat_1",
maxBodyLength: 4_000,
},
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
});
}
function attempt(deliveryState: "sending" | "failed", errorKey: string | null): ChatAttachmentSendAttempt {
return {
payloadKey: "payload",
requestId: "request_stable",
clientMessageId: "client_stable",
fileIds: ["file_1"],
body: "Montagefoto",
attachments: [
{
clientId: "upload_1",
fileId: "file_1",
fileName: "camera.jpg",
mimeType: "image/jpeg",
sizeBytes: 1024,
kind: "image",
status: "ready",
progress: 100,
errorKey: null,
durationSeconds: null,
},
],
createdAtIso: "2026-07-16T08:00:00.000Z",
deliveryState,
errorKey,
};
}
describe("attachment optimistic message overlay", () => {
it("shows a local sending echo with the stable client id and attachment metadata", () => {
const result = overlayChatAttachmentSendAttempt(vm(), attempt("sending", null), currentUser);
expect(result.status).toBe("ready");
if (result.status !== "ready") return;
expect(result.data.messages[0]).toMatchObject({
id: "local:client_stable",
clientMessageId: "client_stable",
source: "local_echo",
deliveryState: "sending",
attachments: [{ fileId: "file_1", fileName: "camera.jpg" }],
});
});
it("keeps a failed send element-local and retryable without changing its identity", () => {
const result = overlayChatAttachmentSendAttempt(vm(), attempt("failed", "chat.errors.invalidInput"), currentUser);
expect(result.status === "ready" ? result.data.messages[0] : null).toMatchObject({
clientMessageId: "client_stable",
deliveryState: "failed",
retryable: true,
failureReasonKey: "chat.errors.invalidInput",
});
});
});
@@ -0,0 +1,93 @@
import { chatMessageIdentityKey, groupChatMessagesByDay, type ChatChannelDetailVM, type ChatMessageVM, type ChatResolvedAuthorVM } from "@hivegrid/view-models";
import type { ChatPendingAttachment } from "./useChatAttachmentUploads";
export type ChatAttachmentSendAttempt = {
readonly payloadKey: string;
readonly requestId: string;
readonly clientMessageId: string;
readonly fileIds: readonly string[];
readonly body: string;
readonly attachments: readonly ChatPendingAttachment[];
readonly createdAtIso: string;
readonly deliveryState: "sending" | "failed";
readonly errorKey: string | null;
};
export function overlayChatAttachmentSendAttempt(
vm: ChatChannelDetailVM,
attempt: ChatAttachmentSendAttempt | null,
currentUser: ChatResolvedAuthorVM
): ChatChannelDetailVM {
if (vm.status !== "ready" || attempt === null) return vm;
const recipientCount = Math.max(0, vm.data.header.memberCount - 1);
const localMessage: ChatMessageVM = {
id: `local:${attempt.clientMessageId}`,
clientMessageId: attempt.clientMessageId,
source: "local_echo",
deliveryState: attempt.deliveryState,
deliveryStateKey: attempt.deliveryState === "sending" ? "chat.message.delivery.sending" : "chat.message.delivery.failed",
failureReasonKey: attempt.errorKey,
retryable: attempt.deliveryState === "failed",
author: currentUser,
bodyMarkdown: attempt.body || null,
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: attempt.createdAtIso,
updatedAtIso: attempt.createdAtIso,
editedAtIso: null,
deletedAtIso: null,
tombstoneKey: null,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: attempt.attachments.flatMap((attachment) =>
attachment.fileId
? [
{
id: `${attempt.clientMessageId}:${attachment.fileId}`,
fileId: attachment.fileId,
kind: attachment.kind,
fileName: attachment.fileName,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
downloadHref: "#pending-chat-attachment",
previewHref: null,
altText: attachment.kind === "image" ? attachment.fileName : null,
durationSeconds: attachment.durationSeconds,
scanStatus: "clean" as const,
},
]
: []
),
linkPreviews: [],
readAggregate: {
readCount: 0,
recipientCount,
readerUserIds: [],
readerLabels: [],
labelKey: "chat.message.read.aggregate",
},
pin: null,
actions: {
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
},
};
const byKey = new Map(vm.data.messages.map((message) => [chatMessageIdentityKey(message), message]));
byKey.set(chatMessageIdentityKey(localMessage), localMessage);
const messages = [...byKey.values()].sort((left, right) => left.createdAtIso.localeCompare(right.createdAtIso));
return {
...vm,
data: {
...vm.data,
messages,
messageGroups: groupChatMessagesByDay(messages),
},
};
}
@@ -0,0 +1,310 @@
import { CHAT_EVENT_NAMES, type ChatLocalEcho, type ChatMessageCreatedEvent, type ChatRealtimeMessage, type ChatThreadReplyEvent } from "@hivegrid/realtime";
import type { ChatResolvedAuthorVM } from "@hivegrid/view-models";
import { describe, expect, it } from "vitest";
import {
candidateFromChatEvent,
candidateFromLocalEcho,
chatChannelRealtimeReducer,
createChatRealtimeScopeKey,
createInitialChatChannelRealtimeState,
filterHydratedChatCandidates,
safeResolveChatAuthor,
type ChatCandidateMapping,
} from "./chatChannelRealtimeReducer";
const viewer: ChatResolvedAuthorVM = {
userId: "user_viewer",
displayName: "Raffael",
avatar: { imageUrl: null, fallbackLabel: "R" },
isCurrentUser: true,
};
const scopeKey = createChatRealtimeScopeKey("tenant_1", "chat_1");
function message(overrides: Partial<ChatRealtimeMessage> = {}): ChatRealtimeMessage {
return {
id: "message_1",
clientMessageId: "client_1",
authorUserId: "user_unknown",
body: "Hallo",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [{ type: "user", id: "user_viewer", label: null }],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T08:00:00.000Z",
updatedAt: "2026-07-15T08:00:00.000Z",
editedAt: null,
deletedAt: null,
...overrides,
};
}
function mapping(overrides: Partial<ChatCandidateMapping> = {}): ChatCandidateMapping {
return {
currentUser: viewer,
unknownAuthorLabel: "Unbekannt",
resolveAuthor: () => undefined,
...overrides,
};
}
describe("chatChannelRealtimeReducer", () => {
it("maps an event with an unknown or failing author projection without throwing", () => {
const event: ChatMessageCreatedEvent = {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:1",
requestId: "request_1",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:00:00.000Z",
data: { message: message() },
};
const candidate = candidateFromChatEvent(
event,
mapping({
resolveAuthor: () => {
throw new Error("stale author cache");
},
messageActions: () => {
throw new Error("stale permission projection");
},
})
);
expect(candidate?.author).toMatchObject({ userId: "user_unknown", displayName: "Unbekannt", isCurrentUser: false });
expect(candidate?.mentions).toEqual([{ kind: "user", id: "user_viewer", label: "user_viewer", href: null }]);
expect(candidate?.actions).toEqual({
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
});
});
it("reconciles local echo lifecycle by author-scoped client id", () => {
const echo: ChatLocalEcho = {
chatId: "chat_1",
requestId: "request_1",
clientMessageId: "client_local",
body: "Optimistisch",
mentions: [],
status: "sending",
failureI18nKey: null,
retryable: false,
attempts: 1,
createdAtMs: Date.parse("2026-07-15T08:00:00.000Z"),
canonicalMessage: null,
};
const sending = candidateFromLocalEcho(echo, mapping());
let state = chatChannelRealtimeReducer(createInitialChatChannelRealtimeState(scopeKey), {
type: "upsert_candidate",
scopeKey,
candidate: sending,
});
expect(state.candidates).toHaveLength(1);
expect(state.candidates[0]?.deliveryState).toBe("sending");
const failed = candidateFromLocalEcho({ ...echo, status: "failed", failureI18nKey: "chat.errors.realtimeUnavailable", retryable: true }, mapping());
state = chatChannelRealtimeReducer(state, { type: "upsert_candidate", scopeKey, candidate: failed });
expect(state.candidates).toHaveLength(1);
expect(state.candidates[0]).toMatchObject({ deliveryState: "failed", failureReasonKey: "chat.errors.realtimeUnavailable" });
const acknowledged = candidateFromLocalEcho(
{ ...echo, status: "sent", canonicalMessage: message({ authorUserId: viewer.userId, clientMessageId: echo.clientMessageId }) },
mapping()
);
state = chatChannelRealtimeReducer(state, { type: "upsert_candidate", scopeKey, candidate: acknowledged });
expect(state.candidates[0]).toMatchObject({ id: "message_1", source: "http_ack", deliveryState: "sent" });
state = chatChannelRealtimeReducer(state, {
type: "remove_candidate",
scopeKey,
authorUserId: viewer.userId,
clientMessageId: echo.clientMessageId,
});
expect(state.candidates).toEqual([]);
});
it("deduplicates typing labels and safely falls back for the current user", () => {
const author = safeResolveChatAuthor(viewer.userId, mapping({ unknownAuthorLabel: "Unbekannt" }));
expect(author).toBe(viewer);
const state = chatChannelRealtimeReducer(createInitialChatChannelRealtimeState(scopeKey), {
type: "typing",
scopeKey,
labels: ["Ada", "Ada", "Grace"],
});
expect(state.typingLabels).toEqual(["Ada", "Grace"]);
});
it("lets the richer loader projection replace a hydrated realtime candidate", () => {
const event: ChatMessageCreatedEvent = {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:1",
requestId: "request_1",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:00:00.000Z",
data: { message: message() },
};
const realtime = candidateFromChatEvent(event, mapping());
if (!realtime) throw new Error("fixture must map to a candidate");
if (!realtime.author) throw new Error("fixture must carry a markdown author");
const hydrated = {
...realtime,
source: "persisted" as const,
author: { ...realtime.author, displayName: "Grace Hopper" },
};
expect(filterHydratedChatCandidates([hydrated], [realtime])).toEqual([]);
expect(filterHydratedChatCandidates([], [realtime])).toEqual([realtime]);
});
it("drops stale-scope actions after a tenant or channel switch", () => {
const candidate = candidateFromLocalEcho(
{
chatId: "chat_1",
requestId: "request_old",
clientMessageId: "client_old",
body: "Alt",
mentions: [],
status: "sending",
failureI18nKey: null,
retryable: false,
attempts: 1,
createdAtMs: Date.parse("2026-07-15T08:00:00.000Z"),
canonicalMessage: null,
},
mapping()
);
const nextScopeKey = createChatRealtimeScopeKey("tenant_2", "chat_1");
let state = chatChannelRealtimeReducer(createInitialChatChannelRealtimeState(scopeKey), {
type: "upsert_candidate",
scopeKey,
candidate,
});
state = chatChannelRealtimeReducer(state, { type: "reset", scopeKey: nextScopeKey });
state = chatChannelRealtimeReducer(state, { type: "upsert_candidate", scopeKey, candidate });
state = chatChannelRealtimeReducer(state, {
type: "connection",
scopeKey,
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
});
expect(state).toEqual(createInitialChatChannelRealtimeState(nextScopeKey));
});
it("never projects thread replies into the top-level channel timeline", () => {
const event: ChatThreadReplyEvent = {
event: CHAT_EVENT_NAMES.threadReply,
cursor: "stream_1:2",
requestId: "request_reply",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:01:00.000Z",
data: {
thread: {
id: "thread_1",
parentMessageId: "message_parent",
replyCount: 1,
lastReplyAt: "2026-07-15T08:01:00.000Z",
participantUserIds: ["user_unknown"],
},
message: message({ id: "message_reply", parentMessageId: "message_parent" }),
},
};
expect(candidateFromChatEvent(event, mapping())).toBeNull();
});
it("projects actorless system events without fake author or user-message affordances", () => {
const event: ChatMessageCreatedEvent = {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:4",
requestId: "request_system",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:03:00.000Z",
data: {
message: {
id: "system_message_1",
clientMessageId: "system:member-write:user_1:false",
authorUserId: null,
body: "stored fallback copy",
bodyFormat: "system",
systemEvent: {
kind: "member_write_access_changed",
metadata: { memberName: "Nora Weber", canWrite: false },
},
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T08:03:00.000Z",
updatedAt: "2026-07-15T08:03:00.000Z",
editedAt: null,
deletedAt: null,
},
},
};
const candidate = candidateFromChatEvent(event, mapping());
expect(candidate).toMatchObject({
author: null,
bodyMarkdown: null,
bodyFormat: "system",
readAggregate: null,
systemEvent: {
kind: "member_write_access_changed",
labelKey: "chat.systemEvent.memberWriteAccessRevoked",
values: { member: "Nora Weber" },
},
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
});
});
it("strips mentions, previews and actions from deleted realtime candidates", () => {
const event: ChatMessageCreatedEvent = {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:3",
requestId: "request_deleted",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:02:00.000Z",
data: {
message: message({
deletedAt: "2026-07-15T08:02:00.000Z",
linkPreviews: [
{
url: "https://example.test",
title: "Vorschau",
description: null,
imageUrl: null,
siteName: "Example",
},
],
}),
},
};
const candidate = candidateFromChatEvent(
event,
mapping({
messageActions: () => ({
canReact: true,
canReply: true,
canEdit: true,
canDelete: true,
canPin: true,
canMarkAsTask: true,
}),
})
);
expect(candidate).toMatchObject({ bodyMarkdown: null, mentions: [], linkPreviews: [], actions: expect.objectContaining({ canReact: false }) });
});
});
@@ -0,0 +1,307 @@
import { CHAT_EVENT_NAMES, type ChatLocalEcho, type ChatRealtimeMessage, type ChatRemotePresence, type ChatServerEvent } from "@hivegrid/realtime";
import {
buildChatSystemEventVM,
chatMessageIdentityKey,
type ChatMessageActionsVM,
type ChatMessageCandidate,
type ChatResolvedAuthorVM,
type ChatResolvedMentionVM,
} from "@hivegrid/view-models";
const MAX_OVERLAY_MESSAGES = 500;
const MAX_READ_RECEIPT_OVERLAYS = 500;
const NO_MESSAGE_ACTIONS: ChatMessageActionsVM = Object.freeze({
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
});
export type ChatRealtimeConnection = {
readonly state: "connecting" | "online" | "reconnecting" | "offline" | "blocked";
readonly reconnectAttempt: number;
readonly retryAtIso: string | null;
};
export type ChatChannelRealtimeState = {
readonly scopeKey: string | null;
readonly connection: ChatRealtimeConnection;
readonly candidates: readonly ChatMessageCandidate[];
readonly readReceipts: readonly ChatReadReceiptOverlay[];
readonly typingLabels: readonly string[];
readonly presence: readonly ChatRemotePresence[];
};
export type ChatReadReceiptOverlay = {
readonly messageId: string;
readonly userId: string;
};
export type ChatChannelRealtimeAction =
| { readonly type: "reset"; readonly scopeKey: string }
| { readonly type: "connection"; readonly scopeKey: string; readonly connection: ChatRealtimeConnection }
| { readonly type: "upsert_candidate"; readonly scopeKey: string; readonly candidate: ChatMessageCandidate }
| { readonly type: "remove_candidate"; readonly scopeKey: string; readonly authorUserId: string; readonly clientMessageId: string }
| { readonly type: "read_receipt"; readonly scopeKey: string; readonly receipt: ChatReadReceiptOverlay }
| { readonly type: "typing"; readonly scopeKey: string; readonly labels: readonly string[] }
| { readonly type: "presence"; readonly scopeKey: string; readonly entries: readonly ChatRemotePresence[] };
export type ChatCandidateMapping = {
readonly currentUser: ChatResolvedAuthorVM;
readonly unknownAuthorLabel: string;
readonly resolveAuthor: (userId: string) => ChatResolvedAuthorVM | null | undefined;
readonly messageActions?: (message: ChatRealtimeMessage) => ChatMessageActionsVM;
};
export function createChatRealtimeScopeKey(tenantSlug: string, chatId: string): string {
return `${tenantSlug}\u0000${chatId}`;
}
export function createInitialChatChannelRealtimeState(scopeKey: string | null = null): ChatChannelRealtimeState {
return {
scopeKey,
connection: { state: "offline", reconnectAttempt: 0, retryAtIso: null },
candidates: [],
readReceipts: [],
typingLabels: [],
presence: [],
};
}
export function chatChannelRealtimeReducer(state: ChatChannelRealtimeState, action: ChatChannelRealtimeAction): ChatChannelRealtimeState {
if (action.type !== "reset" && state.scopeKey !== action.scopeKey) return state;
switch (action.type) {
case "reset":
return createInitialChatChannelRealtimeState(action.scopeKey);
case "connection":
return { ...state, connection: action.connection };
case "upsert_candidate":
return { ...state, candidates: upsertCandidate(state.candidates, action.candidate) };
case "remove_candidate":
return {
...state,
candidates: state.candidates.filter(
(candidate) => candidate.author?.userId !== action.authorUserId || candidate.clientMessageId !== action.clientMessageId
),
};
case "read_receipt":
return { ...state, readReceipts: upsertReadReceipt(state.readReceipts, action.receipt) };
case "typing":
return { ...state, typingLabels: [...new Set(action.labels)] };
case "presence":
return { ...state, presence: action.entries.map((entry) => ({ ...entry })) };
}
}
/** Maps only top-level message events. All other persistent mutations are
* hydrated by the loader revalidation triggered by the hook. */
export function candidateFromChatEvent(event: ChatServerEvent, mapping: ChatCandidateMapping): ChatMessageCandidate | null {
if (event.event !== CHAT_EVENT_NAMES.messageCreated || event.data.message.parentMessageId !== null) return null;
return candidateFromRealtimeMessage(event.data.message, "websocket", "sent", null, mapping);
}
export function candidateFromLocalEcho(echo: ChatLocalEcho, mapping: ChatCandidateMapping): ChatMessageCandidate {
if (echo.canonicalMessage) {
return candidateFromRealtimeMessage(echo.canonicalMessage, "http_ack", "sent", null, mapping);
}
const timestamp = new Date(echo.createdAtMs).toISOString();
return {
id: `local:${echo.clientMessageId}`,
clientMessageId: echo.clientMessageId,
source: "local_echo",
deliveryState: echo.status,
failureReasonKey: echo.failureI18nKey,
retryable: echo.retryable,
author: mapping.currentUser,
bodyMarkdown: echo.body,
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: timestamp,
updatedAtIso: timestamp,
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: echo.mentions.map(resolveMention),
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: emptyReadAggregate(),
pin: null,
actions: NO_MESSAGE_ACTIONS,
};
}
export function safeResolveChatAuthor(userId: string, mapping: ChatCandidateMapping): ChatResolvedAuthorVM {
if (userId === mapping.currentUser.userId) return mapping.currentUser;
try {
const resolved = mapping.resolveAuthor(userId);
if (resolved) return resolved;
} catch {
// A stale author projection must not break the realtime stream.
}
const label = mapping.unknownAuthorLabel.trim() || userId;
return {
userId,
displayName: label,
avatar: { imageUrl: null, fallbackLabel: label.slice(0, 1).toUpperCase() || "?" },
isCurrentUser: userId === mapping.currentUser.userId,
};
}
/** Once the loader has hydrated a message, its richer author, attachment,
* permission and read projections replace the transport-only candidate. */
export function filterHydratedChatCandidates(
loaderMessages: readonly ChatMessageCandidate[],
realtimeCandidates: readonly ChatMessageCandidate[]
): readonly ChatMessageCandidate[] {
const hydratedKeys = new Set(loaderMessages.map(chatMessageCandidateKey));
return realtimeCandidates.filter((candidate) => !hydratedKeys.has(chatMessageCandidateKey(candidate)));
}
function candidateFromRealtimeMessage(
message: ChatRealtimeMessage,
source: "websocket" | "http_ack",
deliveryState: "sent",
failureReasonKey: null,
mapping: ChatCandidateMapping
): ChatMessageCandidate {
if (message.bodyFormat === "system") {
return {
id: message.id,
clientMessageId: message.clientMessageId,
source,
deliveryState,
failureReasonKey,
author: null,
bodyMarkdown: null,
bodyFormat: "system",
systemEvent: buildChatSystemEventVM(message.systemEvent.kind, message.systemEvent.metadata),
createdAtIso: message.createdAt,
updatedAtIso: message.updatedAt,
editedAtIso: message.editedAt,
deletedAtIso: message.deletedAt,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: null,
pin: null,
actions: NO_MESSAGE_ACTIONS,
};
}
const isDeleted = message.deletedAt !== null;
let actions = NO_MESSAGE_ACTIONS;
if (!isDeleted) {
try {
actions = mapping.messageActions?.(message) ?? NO_MESSAGE_ACTIONS;
} catch {
// Permission projections can become stale; safe read-only actions win.
}
}
return {
id: message.id,
clientMessageId: message.clientMessageId,
source,
deliveryState,
failureReasonKey,
author: safeResolveChatAuthor(message.authorUserId, mapping),
bodyMarkdown: isDeleted ? null : message.body,
bodyFormat: message.bodyFormat,
systemEvent: null,
createdAtIso: message.createdAt,
updatedAtIso: message.updatedAt,
editedAtIso: message.editedAt,
deletedAtIso: message.deletedAt,
parentMessageId: message.parentMessageId,
mentions: isDeleted ? [] : message.mentions.map(resolveMention),
reactions: [],
thread: null,
// Realtime frames intentionally contain only attachment ids. The loader
// resolves scan state, names and download URLs after revalidation.
attachments: [],
linkPreviews: isDeleted ? [] : message.linkPreviews.map((preview) => ({ ...preview })),
readAggregate: emptyReadAggregate(),
pin: null,
actions,
};
}
function resolveMention(mention: { readonly type: ChatResolvedMentionVM["kind"]; readonly id: string; readonly label: string | null }): ChatResolvedMentionVM {
return {
kind: mention.type,
id: mention.id,
label: mention.label?.trim() || mention.id,
href: null,
};
}
function emptyReadAggregate() {
return {
readCount: 0,
recipientCount: 0,
readerUserIds: [],
readerLabels: [],
labelKey: "chat.message.read.none",
} as const;
}
export function overlayChatReadReceipts(
candidates: readonly ChatMessageCandidate[],
receipts: readonly ChatReadReceiptOverlay[],
mapping: ChatCandidateMapping
): readonly ChatMessageCandidate[] {
if (receipts.length === 0) return candidates;
const receiptsByMessage = new Map<string, Set<string>>();
for (const receipt of receipts) {
const readers = receiptsByMessage.get(receipt.messageId) ?? new Set<string>();
readers.add(receipt.userId);
receiptsByMessage.set(receipt.messageId, readers);
}
return candidates.map((candidate) => {
if (candidate.author === null || candidate.readAggregate === null) return candidate;
const readAggregate = candidate.readAggregate;
const liveReaders = receiptsByMessage.get(candidate.id);
if (!liveReaders) return candidate;
const labelsByUserId = new Map(readAggregate.readerUserIds.map((userId, index) => [userId, readAggregate.readerLabels[index]!]));
for (const userId of liveReaders) {
if (userId === candidate.author.userId || labelsByUserId.has(userId)) continue;
labelsByUserId.set(userId, safeResolveChatAuthor(userId, mapping).displayName);
}
const readers = [...labelsByUserId.entries()].slice(0, readAggregate.recipientCount);
return {
...candidate,
readAggregate: {
...readAggregate,
readCount: readers.length,
readerUserIds: readers.map(([userId]) => userId),
readerLabels: readers.map(([, label]) => label),
labelKey: readers.length > 0 ? "chat.message.read.aggregate" : readAggregate.labelKey,
},
};
});
}
function upsertReadReceipt(receipts: readonly ChatReadReceiptOverlay[], receipt: ChatReadReceiptOverlay): readonly ChatReadReceiptOverlay[] {
const withoutDuplicate = receipts.filter((candidate) => candidate.messageId !== receipt.messageId || candidate.userId !== receipt.userId);
return [...withoutDuplicate, receipt].slice(-MAX_READ_RECEIPT_OVERLAYS);
}
function upsertCandidate(candidates: readonly ChatMessageCandidate[], candidate: ChatMessageCandidate): readonly ChatMessageCandidate[] {
const candidateKey = chatMessageIdentityKey(candidate);
const index = candidates.findIndex((existing) => chatMessageIdentityKey(existing) === candidateKey);
if (index < 0) return [...candidates, candidate].slice(-MAX_OVERLAY_MESSAGES);
const next = [...candidates];
next[index] = candidate;
return next;
}
function chatMessageCandidateKey(candidate: ChatMessageCandidate): string {
return chatMessageIdentityKey(candidate);
}
@@ -0,0 +1,278 @@
import { describe, expect, it, vi } from "vitest";
import {
createChatReadReceiptBatcher,
createChatTypingController,
type ChatInteractionScheduler,
type ChatVisibilitySource,
} from "./chatInteractionControllers";
class FakeScheduler implements ChatInteractionScheduler {
private nextHandle = 1;
private now = 0;
private readonly timers = new Map<number, { at: number; callback: () => void }>();
setTimeout(callback: () => void, delayMs: number): number {
const handle = this.nextHandle++;
this.timers.set(handle, { at: this.now + delayMs, callback });
return handle;
}
clearTimeout(handle: unknown): void {
if (typeof handle === "number") this.timers.delete(handle);
}
advanceBy(delayMs: number): void {
const target = this.now + delayMs;
while (true) {
const next = [...this.timers.entries()]
.filter(([, timer]) => timer.at <= target)
.sort((left, right) => left[1].at - right[1].at || left[0] - right[0])[0];
if (!next) break;
this.timers.delete(next[0]);
this.now = next[1].at;
next[1].callback();
}
this.now = target;
}
}
class FakeVisibility implements ChatVisibilitySource {
visibilityState: DocumentVisibilityState = "visible";
private readonly listeners = new Set<() => void>();
addEventListener(_type: "visibilitychange", listener: () => void): void {
this.listeners.add(listener);
}
removeEventListener(_type: "visibilitychange", listener: () => void): void {
this.listeners.delete(listener);
}
set(next: DocumentVisibilityState): void {
this.visibilityState = next;
for (const listener of this.listeners) listener();
}
}
describe("chat interaction controllers", () => {
it("debounces typing start and emits stop after inactivity or disposal", () => {
const scheduler = new FakeScheduler();
const send = vi.fn(() => true);
const controller = createChatTypingController({ chatId: "chat_1", send, scheduler, startDelayMs: 250, idleStopMs: 1_500, refreshMs: 3_000 });
controller.update("H");
scheduler.advanceBy(249);
expect(send).not.toHaveBeenCalled();
scheduler.advanceBy(1);
expect(send).toHaveBeenLastCalledWith("chat_1", "started");
scheduler.advanceBy(1_000);
controller.update("Hallo");
scheduler.advanceBy(1_499);
expect(send).toHaveBeenCalledTimes(1);
scheduler.advanceBy(1);
expect(send).toHaveBeenLastCalledWith("chat_1", "stopped");
controller.update("Noch einmal");
scheduler.advanceBy(250);
controller.dispose();
expect(send).toHaveBeenLastCalledWith("chat_1", "stopped");
});
it("never sends a receipt for visibility shorter than one foreground second", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_short", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(999);
batcher.endVisible("chat_1", "message_short");
scheduler.advanceBy(5_000);
expect(send).not.toHaveBeenCalled();
batcher.dispose();
});
it("restarts the continuous visibility window after the document was hidden", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(500);
visibility.set("hidden");
scheduler.advanceBy(5_000);
expect(send).not.toHaveBeenCalled();
visibility.set("visible");
scheduler.advanceBy(999);
expect(send).not.toHaveBeenCalled();
scheduler.advanceBy(1);
batcher.endVisible("chat_1", "message_1");
scheduler.advanceBy(1_999);
expect(send).not.toHaveBeenCalled();
scheduler.advanceBy(1);
expect(send).toHaveBeenCalledWith("chat_1", "message_1");
batcher.dispose();
});
it("holds qualified receipts while hidden and resumes the two-second cadence", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_pending", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(1_000);
visibility.set("hidden");
scheduler.advanceBy(10_000);
expect(send).not.toHaveBeenCalled();
visibility.set("visible");
scheduler.advanceBy(1_999);
expect(send).not.toHaveBeenCalled();
scheduler.advanceBy(1);
expect(send).toHaveBeenCalledWith("chat_1", "message_pending");
batcher.dispose();
});
it("keeps every qualified receipt and flushes out-of-order callbacks monotonically", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_z", "2026-07-15T08:05:00.000Z");
batcher.beginVisible("chat_1", "message_old", "2026-07-15T08:04:59.000Z");
batcher.beginVisible("chat_1", "message_a", "2026-07-15T08:05:00.000Z");
scheduler.advanceBy(1_000);
batcher.endVisible("chat_1", "message_z");
batcher.endVisible("chat_1", "message_old");
batcher.endVisible("chat_1", "message_a");
scheduler.advanceBy(2_000);
expect(send.mock.calls).toEqual([
["chat_1", "message_old"],
["chat_1", "message_a"],
["chat_1", "message_z"],
]);
batcher.acknowledge("chat_1", "message_old");
batcher.acknowledge("chat_1", "message_a");
batcher.acknowledge("chat_1", "message_z");
batcher.beginVisible("chat_1", "message_old", "2026-07-15T08:04:59.000Z");
scheduler.advanceBy(5_000);
expect(send).toHaveBeenCalledTimes(3);
batcher.dispose();
});
it("retains a failed exact receipt and does not overtake it within the same channel", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi
.fn()
.mockReturnValueOnce({ requestId: "request_1", sent: false })
.mockReturnValueOnce({ requestId: "request_2", sent: true })
.mockReturnValueOnce({ requestId: "request_1", sent: true })
.mockReturnValueOnce({ requestId: "request_4", sent: true });
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
batcher.beginVisible("chat_1", "message_2", "2026-07-15T08:01:00.000Z");
batcher.beginVisible("chat_2", "message_3", "2026-07-15T08:02:00.000Z");
scheduler.advanceBy(3_000);
expect(send.mock.calls).toEqual([
["chat_1", "message_1"],
["chat_2", "message_3"],
]);
scheduler.advanceBy(2_000);
expect(send.mock.calls).toEqual([
["chat_1", "message_1"],
["chat_2", "message_3"],
["chat_1", "message_1", "request_1"],
["chat_1", "message_2"],
]);
batcher.acknowledge("chat_1", "message_1");
batcher.acknowledge("chat_1", "message_2");
batcher.acknowledge("chat_2", "message_3");
batcher.dispose();
});
it("sends at most fifty exact receipts per flush", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
const base = Date.parse("2026-07-15T08:00:00.000Z");
for (let index = 54; index >= 0; index -= 1) {
batcher.beginVisible("chat_1", `message_${String(index).padStart(2, "0")}`, new Date(base + index).toISOString());
}
scheduler.advanceBy(3_000);
expect(send).toHaveBeenCalledTimes(50);
expect(send.mock.calls[0]).toEqual(["chat_1", "message_00"]);
expect(send.mock.calls[49]).toEqual(["chat_1", "message_49"]);
for (let index = 0; index < 50; index += 1) {
batcher.acknowledge("chat_1", `message_${String(index).padStart(2, "0")}`);
}
scheduler.advanceBy(2_000);
expect(send).toHaveBeenCalledTimes(55);
expect(send.mock.calls[54]).toEqual(["chat_1", "message_54"]);
batcher.dispose();
});
it("retries an unacknowledged receipt with the same request id after reconnect and stops only on acknowledgement", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn((_chatId: string, _messageId: string, requestId?: string) => ({ requestId: requestId ?? "request_stable", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(3_000);
expect(send).toHaveBeenCalledOnce();
expect(send).toHaveBeenLastCalledWith("chat_1", "message_1");
expect(batcher.retryPending()).toBe(1);
expect(send).toHaveBeenLastCalledWith("chat_1", "message_1", "request_stable");
batcher.acknowledge("chat_1", "message_1");
expect(batcher.retryPending()).toBe(0);
scheduler.advanceBy(20_000);
expect(send).toHaveBeenCalledTimes(2);
batcher.dispose();
});
it("retries an unacknowledged receipt with the same request id after the acknowledgement timeout", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn((_chatId: string, _messageId: string, requestId?: string) => ({ requestId: requestId ?? "request_timeout", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler, acknowledgementTimeoutMs: 3_000 });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(3_000);
expect(send).toHaveBeenCalledOnce();
scheduler.advanceBy(4_999);
expect(send).toHaveBeenCalledOnce();
scheduler.advanceBy(1);
expect(send).toHaveBeenLastCalledWith("chat_1", "message_1", "request_timeout");
batcher.dispose();
});
it("flushes qualified receipts once when leaving the channel", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(1_000);
visibility.set("hidden");
batcher.dispose();
expect(send).toHaveBeenCalledOnce();
expect(send).toHaveBeenCalledWith("chat_1", "message_1");
});
});
@@ -0,0 +1,349 @@
import type { ChatReadResult } from "@hivegrid/realtime";
export type ChatInteractionScheduler = {
setTimeout(callback: () => void, delayMs: number): unknown;
clearTimeout(handle: unknown): void;
};
export type ChatVisibilitySource = {
readonly visibilityState: DocumentVisibilityState;
addEventListener(type: "visibilitychange", listener: () => void): void;
removeEventListener(type: "visibilitychange", listener: () => void): void;
};
export type ChatTypingController = {
update(body: string): void;
stop(): void;
dispose(): void;
};
export type ChatReadReceiptBatcher = {
beginVisible(chatId: string, messageId: string, createdAtIso: string): void;
endVisible(chatId: string, messageId: string): void;
acknowledge(chatId: string, messageId: string): void;
retryPending(): number;
flush(): number;
dispose(): void;
};
const globalScheduler: ChatInteractionScheduler = {
setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),
clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
};
export function createChatTypingController(input: {
readonly chatId: string;
readonly send: (chatId: string, status: "started" | "stopped") => boolean;
readonly scheduler?: ChatInteractionScheduler;
readonly startDelayMs?: number;
readonly idleStopMs?: number;
readonly refreshMs?: number;
}): ChatTypingController {
const scheduler = input.scheduler ?? globalScheduler;
const startDelayMs = positiveDelay(input.startDelayMs, 250);
const idleStopMs = positiveDelay(input.idleStopMs, 1_500);
const refreshMs = positiveDelay(input.refreshMs, 3_000);
let startTimer: unknown;
let stopTimer: unknown;
let refreshTimer: unknown;
let activeBody = false;
let started = false;
let disposed = false;
const clearTimer = (kind: "start" | "stop" | "refresh") => {
const handle = kind === "start" ? startTimer : kind === "stop" ? stopTimer : refreshTimer;
if (handle !== undefined) scheduler.clearTimeout(handle);
if (kind === "start") startTimer = undefined;
else if (kind === "stop") stopTimer = undefined;
else refreshTimer = undefined;
};
const scheduleRefresh = () => {
clearTimer("refresh");
if (!started || !activeBody || disposed) return;
refreshTimer = scheduler.setTimeout(() => {
refreshTimer = undefined;
if (!started || !activeBody || disposed) return;
input.send(input.chatId, "started");
scheduleRefresh();
}, refreshMs);
};
const signalStarted = () => {
startTimer = undefined;
if (!activeBody || started || disposed) return;
started = input.send(input.chatId, "started");
if (started) scheduleRefresh();
};
const stop = () => {
activeBody = false;
clearTimer("start");
clearTimer("stop");
clearTimer("refresh");
if (!started) return;
started = false;
input.send(input.chatId, "stopped");
};
return {
update(body) {
if (disposed) return;
activeBody = body.trim().length > 0;
if (!activeBody) {
stop();
return;
}
if (!started && startTimer === undefined) {
startTimer = scheduler.setTimeout(signalStarted, startDelayMs);
}
clearTimer("stop");
stopTimer = scheduler.setTimeout(stop, idleStopMs);
},
stop,
dispose() {
if (disposed) return;
stop();
disposed = true;
},
};
}
/** Qualifies exact message receipts after continuous foreground visibility and
* delivers them in monotonic channel order. */
export function createChatReadReceiptBatcher(input: {
readonly send: (chatId: string, messageId: string, requestId?: string) => ChatReadResult;
readonly visibility: ChatVisibilitySource;
readonly scheduler?: ChatInteractionScheduler;
readonly minimumVisibleMs?: number;
readonly flushIntervalMs?: number;
readonly acknowledgementTimeoutMs?: number;
readonly maxPerFlush?: number;
}): ChatReadReceiptBatcher {
const scheduler = input.scheduler ?? globalScheduler;
const minimumVisibleMs = positiveDelay(input.minimumVisibleMs, 1_000);
const flushIntervalMs = positiveDelay(input.flushIntervalMs, 2_000);
const acknowledgementTimeoutMs = positiveDelay(input.acknowledgementTimeoutMs, 10_000);
const maxPerFlush = positiveInteger(input.maxPerFlush, 50);
const visibilityEntries = new Map<string, ChatMessageVisibilityEntry>();
const pending = new Map<string, ChatPendingRead>();
const completed = new Set<string>();
let flushTimer: unknown;
let disposed = false;
const clearFlushTimer = () => {
if (flushTimer !== undefined) scheduler.clearTimeout(flushTimer);
flushTimer = undefined;
};
const clearAcknowledgementTimer = (receipt: ChatPendingRead) => {
if (receipt.acknowledgementTimer !== undefined) scheduler.clearTimeout(receipt.acknowledgementTimer);
receipt.acknowledgementTimer = undefined;
};
const scheduleAcknowledgementTimeout = (key: string, receipt: ChatPendingRead) => {
clearAcknowledgementTimer(receipt);
receipt.acknowledgementTimer = scheduler.setTimeout(() => {
receipt.acknowledgementTimer = undefined;
if (disposed || pending.get(key) !== receipt) return;
receipt.inFlight = false;
scheduleFlush();
}, acknowledgementTimeoutMs);
};
const flushPending = (allowHidden = false, scheduleNext = true): number => {
clearFlushTimer();
if (disposed || (!allowHidden && input.visibility.visibilityState !== "visible")) return 0;
const blockedChats = new Set<string>();
const ordered = [...pending.entries()].sort((left, right) => comparePendingRead(left[1], right[1]));
let sent = 0;
let attempted = 0;
for (const [key, receipt] of ordered) {
if (attempted >= maxPerFlush) break;
if (blockedChats.has(receipt.chatId)) continue;
if (receipt.inFlight) {
blockedChats.add(receipt.chatId);
continue;
}
attempted += 1;
const result = receipt.requestId
? input.send(receipt.chatId, receipt.messageId, receipt.requestId)
: input.send(receipt.chatId, receipt.messageId);
receipt.requestId = result.requestId;
if (!result.sent) {
blockedChats.add(receipt.chatId);
continue;
}
receipt.inFlight = true;
scheduleAcknowledgementTimeout(key, receipt);
sent += 1;
}
if (scheduleNext) scheduleFlush();
return sent;
};
const flush = (): number => flushPending();
const scheduleFlush = () => {
if (disposed || flushTimer !== undefined || input.visibility.visibilityState !== "visible" || !hasFlushCandidate(pending)) return;
flushTimer = scheduler.setTimeout(flush, flushIntervalMs);
};
const clearQualificationTimer = (entry: ChatMessageVisibilityEntry) => {
if (entry.qualificationTimer !== undefined) scheduler.clearTimeout(entry.qualificationTimer);
entry.qualificationTimer = undefined;
};
const scheduleQualification = (key: string, entry: ChatMessageVisibilityEntry) => {
if (disposed || !entry.intersecting || entry.qualificationTimer !== undefined || input.visibility.visibilityState !== "visible") return;
entry.qualificationTimer = scheduler.setTimeout(() => {
entry.qualificationTimer = undefined;
if (disposed || !entry.intersecting || input.visibility.visibilityState !== "visible") return;
visibilityEntries.delete(key);
if (!completed.has(key) && !pending.has(key)) {
pending.set(key, {
chatId: entry.chatId,
messageId: entry.messageId,
createdAtIso: entry.createdAtIso,
requestId: null,
inFlight: false,
acknowledgementTimer: undefined,
});
scheduleFlush();
}
}, minimumVisibleMs);
};
const onVisibilityChange = () => {
if (input.visibility.visibilityState === "visible") {
for (const [key, entry] of visibilityEntries) scheduleQualification(key, entry);
scheduleFlush();
return;
}
clearFlushTimer();
for (const entry of visibilityEntries.values()) clearQualificationTimer(entry);
};
input.visibility.addEventListener("visibilitychange", onVisibilityChange);
return {
beginVisible(chatId, messageId, createdAtIso) {
if (disposed) return;
const key = readKey(chatId, messageId);
if (completed.has(key) || pending.has(key)) return;
const existing = visibilityEntries.get(key);
if (existing) {
existing.intersecting = true;
existing.createdAtIso = createdAtIso;
scheduleQualification(key, existing);
return;
}
const entry: ChatMessageVisibilityEntry = {
chatId,
messageId,
createdAtIso,
intersecting: true,
qualificationTimer: undefined,
};
visibilityEntries.set(key, entry);
scheduleQualification(key, entry);
},
endVisible(chatId, messageId) {
if (disposed) return;
const key = readKey(chatId, messageId);
const entry = visibilityEntries.get(key);
if (!entry) return;
entry.intersecting = false;
clearQualificationTimer(entry);
visibilityEntries.delete(key);
},
acknowledge(chatId, messageId) {
if (disposed) return;
const key = readKey(chatId, messageId);
const entry = visibilityEntries.get(key);
if (entry) clearQualificationTimer(entry);
visibilityEntries.delete(key);
const receipt = pending.get(key);
if (receipt) clearAcknowledgementTimer(receipt);
pending.delete(key);
completed.add(key);
scheduleFlush();
},
retryPending() {
if (disposed) return 0;
for (const receipt of pending.values()) {
clearAcknowledgementTimer(receipt);
receipt.inFlight = false;
}
return flushPending();
},
flush,
dispose() {
if (disposed) return;
clearFlushTimer();
for (const entry of visibilityEntries.values()) clearQualificationTimer(entry);
// The channel teardown still has a live socket, so qualified receipts
// get one final best-effort batch even when the document is hidden.
for (const receipt of pending.values()) {
clearAcknowledgementTimer(receipt);
receipt.inFlight = false;
}
flushPending(true, false);
for (const receipt of pending.values()) clearAcknowledgementTimer(receipt);
disposed = true;
visibilityEntries.clear();
pending.clear();
completed.clear();
input.visibility.removeEventListener("visibilitychange", onVisibilityChange);
},
};
}
type ChatMessageVisibilityEntry = {
readonly chatId: string;
readonly messageId: string;
createdAtIso: string;
intersecting: boolean;
qualificationTimer: unknown;
};
type ChatPendingRead = {
readonly chatId: string;
readonly messageId: string;
readonly createdAtIso: string;
requestId: string | null;
inFlight: boolean;
acknowledgementTimer: unknown;
};
function comparePendingRead(left: ChatPendingRead, right: ChatPendingRead): number {
if (left.chatId < right.chatId) return -1;
if (left.chatId > right.chatId) return 1;
if (left.createdAtIso < right.createdAtIso) return -1;
if (left.createdAtIso > right.createdAtIso) return 1;
if (left.messageId < right.messageId) return -1;
if (left.messageId > right.messageId) return 1;
return 0;
}
function hasFlushCandidate(pending: ReadonlyMap<string, ChatPendingRead>): boolean {
const blockedChats = new Set<string>();
const ordered = [...pending.values()].sort(comparePendingRead);
for (const receipt of ordered) {
if (blockedChats.has(receipt.chatId)) continue;
if (!receipt.inFlight) return true;
blockedChats.add(receipt.chatId);
}
return false;
}
function readKey(chatId: string, messageId: string): string {
return `${chatId}\u0000${messageId}`;
}
function positiveDelay(value: number | undefined, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
}
function positiveInteger(value: number | undefined, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
}
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import type { ChatChannelDetailVM, ChatMessageVM } from "@hivegrid/view-models";
import {
beginChatMessageMutation,
overlayChatMessageMutations,
reconcileChatMessageMutations,
retryChatMessageMutation,
settleChatMessageMutation,
} from "./chatMessageMutationOptimistic";
const message = {
id: "message_1",
clientMessageId: "client_1",
source: "persisted",
deliveryState: "sent",
deliveryStateKey: "chat.message.sent",
failureReasonKey: null,
retryable: false,
author: { userId: "user_1", displayName: "Raffael", avatar: { imageUrl: null, fallbackLabel: "R" }, isCurrentUser: true },
bodyMarkdown: "Alt",
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: "2026-07-16T01:00:00.000Z",
updatedAtIso: "2026-07-16T01:00:00.000Z",
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: [],
reactions: [{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] }],
thread: null,
attachments: [{ id: "a", fileId: "f", kind: "file", fileName: "a.pdf", mimeType: "application/pdf", sizeBytes: 1, downloadHref: "/f", previewHref: null, altText: null, durationSeconds: null, scanStatus: "clean" }],
linkPreviews: [],
readAggregate: null,
pin: { pinnedAtIso: "2026-07-16T01:00:00.000Z", pinnedByLabel: "Raffael", note: null },
actions: { canReact: true, canReply: true, canEdit: true, canDelete: true, canPin: true, canMarkAsTask: true },
tombstoneKey: null,
} satisfies ChatMessageVM;
function vm(currentMessage: ChatMessageVM = message): ChatChannelDetailVM {
return {
status: "ready",
data: {
header: { id: "chat_1", kind: "group", title: "Büro", subtitle: null, avatar: { imageUrl: null, fallbackLabel: "B" }, project: null, memberCount: 1, isPrivate: true, isArchived: false, isAuditMode: false, dmAuditBannerKey: null, canManage: false, settingsHref: null, pinnedHref: null, searchHref: "/chat" },
messages: [currentMessage],
messageGroups: [{ dateIso: "2026-07-16", messages: [currentMessage] }],
presence: [],
typingLabels: [],
pinnedMessages: [{ messageId: "message_1", authorLabel: "Raffael", snippet: "Alt", pinnedAtIso: "2026-07-16T01:00:00.000Z", pinnedByLabel: "Raffael", href: "#message-1" }],
history: { olderCursor: null, hasOlder: false },
composer: { enabled: true, disabledReasonKey: null, canSend: true, canAttachFiles: false, canRecordVoice: false, canMention: true, canMarkAsTask: false, draftStorageKey: "draft", maxBodyLength: 8000, placeholderKey: "chat.composer.placeholder" },
connection: { state: "online", stateLabelKey: "chat.connection.online", reconnectAttempt: 0, retryAtIso: null, canRetry: false },
emptyHeadlineKey: "chat.empty.title",
emptyBodyKey: "chat.empty.body",
loadOlderLabelKey: "chat.loadOlder",
newMessagesLabelKey: "chat.newMessages",
},
};
}
describe("optimistic chat message mutations", () => {
it("preserves the state reference when reconciliation has nothing to remove", () => {
const current = [] as const;
expect(reconcileChatMessageMutations(current, vm())).toBe(current);
});
it("overlays an edit and rolls it back when the request fails", () => {
const pending = beginChatMessageMutation([], {
kind: "edit_message",
requestId: "request_1",
messageId: "message_1",
startedAtIso: "2026-07-16T02:00:00.000Z",
bodyMarkdown: "Neu",
mentions: [],
});
expect(overlayChatMessageMutations(vm(), pending).data.messages[0]?.bodyMarkdown).toBe("Neu");
const failed = settleChatMessageMutation(pending, { ok: false, requestId: "request_1", errorKey: "chat.errors.invalidInput" });
expect(overlayChatMessageMutations(vm(), failed).data.messages[0]?.bodyMarkdown).toBe("Alt");
expect(retryChatMessageMutation(failed, "request_1")[0]).toMatchObject({ requestId: "request_1", state: "pending" });
});
it("tombstones optimistically and removes attachments, reactions and pins", () => {
const pending = beginChatMessageMutation([], {
kind: "delete_message",
requestId: "request_delete",
messageId: "message_1",
startedAtIso: "2026-07-16T02:00:00.000Z",
});
const overlaid = overlayChatMessageMutations(vm(), pending);
expect(overlaid.data.messages[0]).toMatchObject({ bodyMarkdown: null, tombstoneKey: "chat.message.deleted", attachments: [], reactions: [], pin: null });
expect(overlaid.data.pinnedMessages).toEqual([]);
});
it("drops a confirmed overlay once the authoritative echo is hydrated", () => {
const confirmed = settleChatMessageMutation(
beginChatMessageMutation([], {
kind: "edit_message",
requestId: "request_1",
messageId: "message_1",
startedAtIso: "2026-07-16T02:00:00.000Z",
bodyMarkdown: "Neu",
mentions: [],
}),
{ ok: true, requestId: "request_1", errorKey: null }
);
expect(reconcileChatMessageMutations(confirmed, vm({ ...message, bodyMarkdown: "Neu", editedAtIso: "2026-07-16T02:00:00.000Z" }))).toEqual([]);
});
});
@@ -0,0 +1,194 @@
import type { ChatChannelDetailVM, ChatFeatureMessageVM, ChatMessageVM, ChatResolvedMentionVM, ChatThreadVM } from "@hivegrid/view-models";
export type ChatMessageMutationState = "pending" | "confirmed" | "failed";
type ChatMessageMutationBase = Readonly<{
requestId: string;
messageId: string;
startedAtIso: string;
state: ChatMessageMutationState;
errorKey: string | null;
}>;
export type ChatOptimisticMessageMutation =
| (ChatMessageMutationBase &
Readonly<{
kind: "edit_message";
bodyMarkdown: string;
mentions: readonly ChatResolvedMentionVM[];
}>)
| (ChatMessageMutationBase & Readonly<{ kind: "delete_message" }>);
export type ChatOptimisticMessageMutationInput =
| Omit<Extract<ChatOptimisticMessageMutation, { kind: "edit_message" }>, "state" | "errorKey">
| Omit<Extract<ChatOptimisticMessageMutation, { kind: "delete_message" }>, "state" | "errorKey">;
export type ChatMessageMutationResponse = Readonly<{
ok: boolean;
requestId: string;
errorKey: string | null;
}>;
export function beginChatMessageMutation(
current: readonly ChatOptimisticMessageMutation[],
input: ChatOptimisticMessageMutationInput
): readonly ChatOptimisticMessageMutation[] {
return [
...current.filter((mutation) => mutation.messageId !== input.messageId),
{ ...input, state: "pending", errorKey: null } as ChatOptimisticMessageMutation,
];
}
export function settleChatMessageMutation(
current: readonly ChatOptimisticMessageMutation[],
response: ChatMessageMutationResponse
): readonly ChatOptimisticMessageMutation[] {
return current.map((mutation) =>
mutation.requestId === response.requestId
? { ...mutation, state: response.ok ? "confirmed" : "failed", errorKey: response.ok ? null : response.errorKey ?? "chat.errors.integrityFailure" }
: mutation
);
}
/** Retains the stable request id for an explicit retry. */
export function retryChatMessageMutation(
current: readonly ChatOptimisticMessageMutation[],
requestId: string
): readonly ChatOptimisticMessageMutation[] {
return current.map((mutation) => (mutation.requestId === requestId ? { ...mutation, state: "pending", errorKey: null } : mutation));
}
export function reconcileChatMessageMutations(
current: readonly ChatOptimisticMessageMutation[],
authoritativeVm: ChatChannelDetailVM
): readonly ChatOptimisticMessageMutation[] {
if (authoritativeVm.status !== "ready") return current;
const messages = new Map(authoritativeVm.data.messages.map((message) => [message.id, message]));
const next = current.filter((mutation) => {
if (mutation.state === "failed" || mutation.state === "pending") return true;
const message = messages.get(mutation.messageId);
if (!message) return true;
if (mutation.kind === "delete_message") return message.deletedAtIso === null;
return message.bodyMarkdown !== mutation.bodyMarkdown || message.editedAtIso === null;
});
return next.length === current.length ? current : next;
}
export function failedChatMessageMutationForMessage(
current: readonly ChatOptimisticMessageMutation[],
messageId: string
): ChatOptimisticMessageMutation | null {
return current.find((mutation) => mutation.messageId === messageId && mutation.state === "failed") ?? null;
}
export function chatMessageMutationErrors(
current: readonly ChatOptimisticMessageMutation[]
): Readonly<Record<string, string>> {
return Object.fromEntries(
current.flatMap((mutation) => (mutation.state === "failed" && mutation.errorKey ? [[mutation.messageId, mutation.errorKey] as const] : []))
);
}
export function overlayChatMessageMutations(
vm: ChatChannelDetailVM,
mutations: readonly ChatOptimisticMessageMutation[]
): ChatChannelDetailVM {
if (vm.status !== "ready" || mutations.length === 0) return vm;
const active = new Map(mutations.filter((mutation) => mutation.state !== "failed").map((mutation) => [mutation.messageId, mutation]));
if (active.size === 0) return vm;
const messages = vm.data.messages.map((message) => overlayMessage(message, active.get(message.id)));
const messagesById = new Map(messages.map((message) => [message.id, message]));
return {
...vm,
data: {
...vm.data,
messages,
messageGroups: vm.data.messageGroups.map((group) => ({
...group,
messages: group.messages.map((message) => messagesById.get(message.id) ?? message),
})),
pinnedMessages: vm.data.pinnedMessages.filter((pin) => active.get(pin.messageId)?.kind !== "delete_message"),
},
};
}
export function reconcileChatThreadMessageMutations(
current: readonly ChatOptimisticMessageMutation[],
authoritativeVm: ChatThreadVM
): readonly ChatOptimisticMessageMutation[] {
if (authoritativeVm.status !== "ready") return current;
const messages = new Map([authoritativeVm.data.parent, ...authoritativeVm.data.replies].map((message) => [message.id, message]));
const next = current.filter((mutation) => {
if (mutation.state === "failed" || mutation.state === "pending") return true;
const message = messages.get(mutation.messageId);
if (!message) return true;
if (mutation.kind === "delete_message") return !message.deleted;
return message.bodyMarkdown !== mutation.bodyMarkdown;
});
return next.length === current.length ? current : next;
}
export function overlayChatThreadMessageMutations(
vm: ChatThreadVM,
mutations: readonly ChatOptimisticMessageMutation[]
): ChatThreadVM {
if (vm.status !== "ready" || mutations.length === 0) return vm;
const active = new Map(mutations.filter((mutation) => mutation.state !== "failed").map((mutation) => [mutation.messageId, mutation]));
if (active.size === 0) return vm;
return {
...vm,
data: {
...vm.data,
parent: overlayFeatureMessage(vm.data.parent, active.get(vm.data.parent.id)),
replies: vm.data.replies.map((message) => overlayFeatureMessage(message, active.get(message.id))),
},
};
}
function overlayMessage(message: ChatMessageVM, mutation: ChatOptimisticMessageMutation | undefined): ChatMessageVM {
if (!mutation) return message;
if (mutation.kind === "delete_message") {
return {
...message,
bodyMarkdown: null,
editedAtIso: null,
deletedAtIso: mutation.startedAtIso,
mentions: [],
reactions: [],
attachments: [],
linkPreviews: [],
pin: null,
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
tombstoneKey: "chat.message.deleted",
};
}
return {
...message,
bodyMarkdown: mutation.bodyMarkdown,
mentions: mutation.mentions,
editedAtIso: mutation.startedAtIso,
};
}
function overlayFeatureMessage(
message: ChatFeatureMessageVM,
mutation: ChatOptimisticMessageMutation | undefined
): ChatFeatureMessageVM {
if (!mutation) return message;
if (mutation.kind === "delete_message") {
return {
...message,
bodyMarkdown: null,
deleted: true,
mentions: [],
reactions: [],
attachments: [],
pinned: false,
canReact: false,
canPin: false,
canEdit: false,
canDelete: false,
};
}
return { ...message, bodyMarkdown: mutation.bodyMarkdown, mentions: mutation.mentions };
}
@@ -0,0 +1,174 @@
import { buildChatChannelDetailVM, type ChatMessageCandidate } from "@hivegrid/view-models";
import { describe, expect, it } from "vitest";
import { overlayChatChannelDetailRealtime } from "./chatRealtimeViewModel";
const message: ChatMessageCandidate = {
id: "message_1",
clientMessageId: "client_1",
source: "websocket",
deliveryState: "sent",
failureReasonKey: null,
author: {
userId: "user_1",
displayName: "Ada",
avatar: { imageUrl: null, fallbackLabel: "A" },
isCurrentUser: false,
},
bodyMarkdown: "Hallo",
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: "2026-07-15T08:00:00.000Z",
updatedAtIso: "2026-07-15T08:00:00.000Z",
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: { readCount: 0, recipientCount: 1, readerUserIds: [], readerLabels: [], labelKey: "chat.message.read.none" },
pin: null,
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
};
function readyVm() {
return buildChatChannelDetailVM({
header: {
id: "chat_1",
kind: "group",
title: "Team",
subtitle: null,
avatar: { imageUrl: null, fallbackLabel: "T" },
project: null,
memberCount: 2,
isPrivate: false,
isArchived: false,
isAuditMode: false,
canManage: false,
settingsHref: null,
pinnedHref: null,
searchHref: "/tenant/chat/chat_1/search",
},
messages: [],
pinnedMessages: [],
typingLabels: [],
history: { olderCursor: null, hasOlder: false },
composer: {
disabledReasonKey: null,
canSend: true,
canAttachFiles: false,
canRecordVoice: false,
canMention: false,
canMarkAsTask: false,
draftStorageKey: "chat:draft",
maxBodyLength: 8_000,
},
connection: { state: "connecting", reconnectAttempt: 0, retryAtIso: null },
});
}
describe("overlayChatChannelDetailRealtime", () => {
it("overlays transport state on a ready loader VM without replacing domain data", () => {
const renderedMessage = buildChatChannelDetailVM({ ...readyVmInput(), messages: [message] });
if (renderedMessage.status !== "ready") throw new Error("fixture must be ready");
const vm = readyVm();
const result = overlayChatChannelDetailRealtime(vm, {
messages: renderedMessage.data.messages,
messageGroups: renderedMessage.data.messageGroups,
presence: [{ userId: "user_2", status: "online" }],
typingLabels: ["Ada"],
connection: { state: "reconnecting", reconnectAttempt: 2, retryAtIso: "2026-07-15T08:01:00.000Z" },
});
expect(result.status).toBe("ready");
if (result.status !== "ready" || vm.status !== "ready") throw new Error("fixture must be ready");
expect(result.data.header).toBe(vm.data.header);
expect(result.data.messages).toEqual(renderedMessage.data.messages);
expect(result.data.presence).toEqual([{ userId: "user_2", status: "online" }]);
expect(result.data.typingLabels).toEqual(["Ada"]);
expect(result.data.connection).toEqual({
state: "reconnecting",
stateLabelKey: "chat.connection.reconnecting",
reconnectAttempt: 2,
retryAtIso: "2026-07-15T08:01:00.000Z",
canRetry: true,
});
});
it("leaves non-ready loader states untouched", () => {
const vm = { status: "loading" } as const;
expect(
overlayChatChannelDetailRealtime(vm, {
messages: [],
messageGroups: [],
presence: [],
typingLabels: [],
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
})
).toBe(vm);
});
it("makes a terminally blocked connection read-only without hiding the draft", () => {
const vm = readyVm();
const result = overlayChatChannelDetailRealtime(vm, {
messages: [],
messageGroups: [],
presence: [],
typingLabels: [],
connection: { state: "blocked", reconnectAttempt: 0, retryAtIso: null },
});
expect(result.status).toBe("ready");
if (result.status !== "ready") return;
expect(result.data.composer).toMatchObject({
enabled: false,
canSend: false,
disabledReasonKey: "chat.composer.connectionBlocked",
});
expect(result.data.connection.canRetry).toBe(false);
});
});
function readyVmInput(): Parameters<typeof buildChatChannelDetailVM>[0] {
const vm = readyVm();
if (vm.status !== "ready") throw new Error("fixture must be ready");
return {
header: {
id: vm.data.header.id,
kind: vm.data.header.kind,
title: vm.data.header.title,
subtitle: vm.data.header.subtitle,
avatar: vm.data.header.avatar,
project: vm.data.header.project,
memberCount: vm.data.header.memberCount,
isPrivate: vm.data.header.isPrivate,
isArchived: vm.data.header.isArchived,
isAuditMode: vm.data.header.isAuditMode,
canManage: vm.data.header.canManage,
settingsHref: vm.data.header.settingsHref,
pinnedHref: vm.data.header.pinnedHref,
searchHref: vm.data.header.searchHref,
},
messages: [],
pinnedMessages: [],
typingLabels: [],
history: vm.data.history,
composer: {
disabledReasonKey: vm.data.composer.disabledReasonKey,
canSend: vm.data.composer.canSend,
canAttachFiles: vm.data.composer.canAttachFiles,
canRecordVoice: vm.data.composer.canRecordVoice,
canMention: vm.data.composer.canMention,
canMarkAsTask: vm.data.composer.canMarkAsTask,
draftStorageKey: vm.data.composer.draftStorageKey,
maxBodyLength: vm.data.composer.maxBodyLength,
},
connection: {
state: vm.data.connection.state,
reconnectAttempt: vm.data.connection.reconnectAttempt,
retryAtIso: vm.data.connection.retryAtIso,
},
};
}
@@ -0,0 +1,56 @@
import {
chatConnectionStateLabelKey,
type ChatChannelDetailVM,
type ChatMessageDayGroupVM,
type ChatMessageVM,
type ChatPresenceVM,
} from "@hivegrid/view-models";
import type { ChatRealtimeConnection } from "./chatChannelRealtimeReducer";
export type ChatChannelRealtimeViewOverlay = {
readonly messages: readonly ChatMessageVM[];
readonly messageGroups: readonly ChatMessageDayGroupVM[];
readonly presence: readonly ChatPresenceVM[];
readonly typingLabels: readonly string[];
readonly connection: ChatRealtimeConnection;
};
/** Applies transport-only state to the loader-owned render contract. Repository
* records never cross this boundary. */
export function overlayChatChannelDetailRealtime(vm: ChatChannelDetailVM, overlay: ChatChannelRealtimeViewOverlay): ChatChannelDetailVM {
if (vm.status !== "ready") return vm;
const canRetry = overlay.connection.state === "offline" || overlay.connection.state === "reconnecting";
const composer =
overlay.connection.state === "blocked"
? {
...vm.data.composer,
enabled: false,
disabledReasonKey: "chat.composer.connectionBlocked",
canSend: false,
canAttachFiles: false,
canRecordVoice: false,
canMention: false,
canMarkAsTask: false,
}
: vm.data.composer;
return {
status: "ready",
data: {
...vm.data,
messages: overlay.messages,
messageGroups: overlay.messageGroups,
presence: overlay.presence.map(({ userId, status }) => ({ userId, status })),
typingLabels: overlay.typingLabels,
composer,
connection: {
...vm.data.connection,
state: overlay.connection.state,
stateLabelKey: chatConnectionStateLabelKey(overlay.connection.state),
reconnectAttempt: overlay.connection.reconnectAttempt,
retryAtIso: overlay.connection.retryAtIso,
canRetry,
},
},
};
}
@@ -0,0 +1,41 @@
import { describe, expect, it, vi } from "vitest";
import { buildChatWebSocketUrl, createChatTokenProvider } from "./chatTokenProvider";
describe("chatTokenProvider", () => {
it("builds the gateway URL from the configured API host with the fixed chat path", () => {
expect(buildChatWebSocketUrl({ protocol: "https", apiHost: "api.example.test" })).toBe("wss://api.example.test/ws/chat");
expect(buildChatWebSocketUrl({ protocol: "http", apiHost: "api.localhost:3000" })).toBe("ws://api.localhost:3000/ws/chat");
expect(() => buildChatWebSocketUrl({ protocol: "https", apiHost: "api.example.test/not-allowed" })).toThrow();
});
it("requests a same-origin no-store token with header-only CSRF", async () => {
const fetchImpl = vi.fn(async () => Response.json({ ok: true, data: { token: "header.payload.signature", expiresIn: 300, refreshAfter: 240 } }));
const provider = createChatTokenProvider({ tenantSlug: "hivegrid demo", csrfToken: "csrf-token", fetchImpl });
await expect(provider({ reconnectAttempt: 2 })).resolves.toBe("header.payload.signature");
expect(fetchImpl).toHaveBeenCalledWith("/hivegrid%20demo/chat/token", {
method: "POST",
headers: { accept: "application/json", "x-csrf-token": "csrf-token" },
credentials: "same-origin",
cache: "no-store",
redirect: "error",
});
});
it("rejects failed and malformed token responses without exposing their bodies", async () => {
const failed = createChatTokenProvider({
tenantSlug: "tenant",
csrfToken: "csrf",
fetchImpl: async () => new Response("secret upstream detail", { status: 503 }),
});
await expect(failed({ reconnectAttempt: 0 })).rejects.toThrow("Chat gateway token could not be loaded.");
const malformed = createChatTokenProvider({
tenantSlug: "tenant",
csrfToken: "csrf",
fetchImpl: async () => Response.json({ ok: true, data: { token: " padded " } }),
});
await expect(malformed({ reconnectAttempt: 0 })).rejects.toThrow("Chat gateway token response was invalid.");
});
});
@@ -0,0 +1,83 @@
import type { ChatTokenProvider } from "@hivegrid/realtime";
export type ChatGatewayRouting = {
readonly protocol: "http" | "https";
readonly apiHost: string;
};
export type ChatTokenFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
export type CreateChatTokenProviderInput = {
readonly tenantSlug: string;
readonly csrfToken: string;
readonly fetchImpl?: ChatTokenFetch;
};
type ChatTokenPayload = {
readonly ok: true;
readonly data: {
readonly token: string;
};
};
/** The gateway lives on the configured API host and exposes one fixed path. */
export function buildChatWebSocketUrl(routing: ChatGatewayRouting): string {
const url = new URL(`${routing.protocol}://${routing.apiHost}`);
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
throw new Error("Chat API routing must contain a host without credentials or a path.");
}
url.protocol = routing.protocol === "https" ? "wss:" : "ws:";
url.pathname = "/ws/chat";
return url.toString();
}
/** Loads a short-lived token over the same-origin session boundary. */
export function createChatTokenProvider(input: CreateChatTokenProviderInput): ChatTokenProvider {
const tenantSlug = requireNonEmpty(input.tenantSlug, "tenant slug");
const csrfToken = requireNonEmpty(input.csrfToken, "CSRF token");
const fetchImpl = input.fetchImpl ?? globalThis.fetch;
if (typeof fetchImpl !== "function") {
throw new Error("Fetch is not available; provide a fetch implementation.");
}
const tokenPath = `/${encodeURIComponent(tenantSlug)}/chat/token`;
return async () => {
const response = await fetchImpl(tokenPath, {
method: "POST",
headers: {
accept: "application/json",
"x-csrf-token": csrfToken,
},
credentials: "same-origin",
cache: "no-store",
redirect: "error",
});
if (!response.ok) throw new Error("Chat gateway token could not be loaded.");
let payload: unknown;
try {
payload = await response.json();
} catch {
throw new Error("Chat gateway token response was invalid.");
}
if (!isChatTokenPayload(payload)) {
throw new Error("Chat gateway token response was invalid.");
}
return payload.data.token;
};
}
function isChatTokenPayload(value: unknown): value is ChatTokenPayload {
if (!isRecord(value) || value.ok !== true || !isRecord(value.data)) return false;
const token = value.data.token;
return typeof token === "string" && token.length > 0 && token === token.trim();
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireNonEmpty(value: string, label: string): string {
if (value.length === 0 || value !== value.trim()) throw new Error(`Chat ${label} is invalid.`);
return value;
}
@@ -0,0 +1,6 @@
export * from "./chatChannelRealtimeReducer";
export * from "./chatInteractionControllers";
export * from "./chatRealtimeViewModel";
export * from "./chatTokenProvider";
export * from "./useChatChannelRealtime";
export * from "./useChatMessageViewport";
@@ -0,0 +1,228 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ upload: vi.fn(), waitForScan: vi.fn() }));
vi.mock("~/utils/files/uploadFileClient", () => ({
uploadFileInChunks: (...args: unknown[]) => mocks.upload(...args),
waitForChatAttachmentScan: (...args: unknown[]) => mocks.waitForScan(...args),
}));
import { useChatAttachmentUploads } from "./useChatAttachmentUploads";
describe("useChatAttachmentUploads", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
mocks.waitForScan.mockResolvedValue(undefined);
});
it("shows an optimistic upload, reports progress, and keeps only the returned File id", async () => {
let finishUpload: (() => void) | undefined;
const uploadBarrier = new Promise<void>((resolve) => {
finishUpload = resolve;
});
mocks.upload.mockImplementation(async (input: { onProgress?: (progress: number) => void; onProcessing?: () => void }) => {
input.onProgress?.(50);
input.onProcessing?.();
await uploadBarrier;
return { id: "file_1", displayName: "photo.jpg" };
});
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
act(() => result.current.addFiles([new File(["image"], "camera.jpg", { type: "image/jpeg" })]));
expect(result.current.attachments).toHaveLength(1);
expect(result.current.attachments[0]).toMatchObject({ kind: "image", status: "processing", fileId: null });
await act(async () => finishUpload?.());
await waitFor(() => expect(result.current.attachments[0]).toMatchObject({ status: "ready", progress: 100, fileId: "file_1" }));
expect(mocks.upload).toHaveBeenCalledWith(expect.objectContaining({ tenantSlug: "acme", file: expect.any(File), signal: expect.any(AbortSignal) }));
expect(mocks.waitForScan).toHaveBeenCalledWith(expect.objectContaining({ tenantSlug: "acme", fileId: "file_1" }));
act(() => result.current.clearReady(["file_1"]));
expect(result.current.attachments).toEqual([]);
});
it("keeps failed files retryable and removes them from the queue on demand", async () => {
mocks.upload
.mockRejectedValueOnce(Object.assign(new Error("failed"), { errorKey: "files.error.mimeBlocked" }))
.mockResolvedValueOnce({ id: "file_2", displayName: "notes.txt" });
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
act(() => result.current.addFiles([new File(["notes"], "notes.txt", { type: "text/plain" })]));
await waitFor(() => expect(result.current.attachments[0]).toMatchObject({ status: "error", errorKey: "files.error.mimeBlocked" }));
const clientId = result.current.attachments[0]!.clientId;
act(() => result.current.retry(clientId));
await waitFor(() => expect(result.current.attachments[0]).toMatchObject({ status: "ready", fileId: "file_2" }));
expect(mocks.upload).toHaveBeenCalledTimes(2);
act(() => result.current.remove(clientId));
expect(result.current.attachments).toEqual([]);
});
it("reports an oversized queue selection instead of silently truncating it", () => {
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
const files = Array.from({ length: 21 }, (_, index) => new File([String(index)], `file-${index}.txt`, { type: "text/plain" }));
act(() => result.current.addFiles(files));
expect(result.current.attachments).toEqual([]);
expect(result.current.errorKey).toBe("chat.attachments.tooMany");
expect(mocks.upload).not.toHaveBeenCalled();
});
it("reserves the 20 attachment slots atomically across same-tick selections", () => {
mocks.upload.mockImplementation(() => new Promise(() => undefined));
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
const first = Array.from({ length: 11 }, (_, index) => new File([String(index)], `first-${index}.txt`, { type: "text/plain" }));
const second = Array.from({ length: 10 }, (_, index) => new File([String(index)], `second-${index}.txt`, { type: "text/plain" }));
act(() => {
result.current.addFiles(first);
result.current.addFiles(second);
});
expect(result.current.attachments).toHaveLength(11);
expect(result.current.errorKey).toBe("chat.attachments.tooMany");
expect(mocks.upload).toHaveBeenCalledTimes(11);
});
it("surfaces unsupported voice recording instead of failing silently", async () => {
vi.stubGlobal("MediaRecorder", undefined);
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
await act(() => result.current.startRecording());
expect(result.current.errorKey).toBe("chat.attachments.recordingUnsupported");
vi.unstubAllGlobals();
});
it("shows recording duration and discards a cancelled voice note before upload", async () => {
vi.useFakeTimers();
const stopTrack = vi.fn();
class FakeMediaRecorder {
static isTypeSupported(): boolean {
return true;
}
state: RecordingState = "inactive";
mimeType = "audio/webm";
ondataavailable: ((event: BlobEvent) => void) | null = null;
onstop: (() => void) | null = null;
onerror: (() => void) | null = null;
start(): void {
this.state = "recording";
}
stop(): void {
this.state = "inactive";
this.ondataavailable?.({ data: new Blob(["voice"], { type: this.mimeType }) } as BlobEvent);
this.onstop?.();
}
}
vi.stubGlobal("MediaRecorder", FakeMediaRecorder);
Object.defineProperty(navigator, "mediaDevices", {
configurable: true,
value: { getUserMedia: vi.fn().mockResolvedValue({ getTracks: () => [{ stop: stopTrack }] }) },
});
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
await act(() => result.current.startRecording());
expect(result.current.isRecording).toBe(true);
act(() => vi.advanceTimersByTime(1_250));
expect(result.current.recordingDurationSeconds).toBe(1);
act(() => result.current.cancelRecording());
expect(result.current.isRecording).toBe(false);
expect(result.current.recordingDurationSeconds).toBe(0);
expect(result.current.attachments).toEqual([]);
expect(mocks.upload).not.toHaveBeenCalled();
expect(stopTrack).toHaveBeenCalledOnce();
vi.unstubAllGlobals();
vi.useRealTimers();
});
it("does not request the microphone twice while the first permission request is pending", async () => {
let resolveStream: ((stream: MediaStream) => void) | undefined;
const streamPromise = new Promise<MediaStream>((resolve) => {
resolveStream = resolve;
});
const getUserMedia = vi.fn(() => streamPromise);
class FakeMediaRecorder {
static isTypeSupported(): boolean {
return true;
}
state: RecordingState = "inactive";
mimeType = "audio/webm;codecs=opus";
ondataavailable: ((event: BlobEvent) => void) | null = null;
onstop: (() => void) | null = null;
onerror: (() => void) | null = null;
start(): void {
this.state = "recording";
}
stop(): void {
this.state = "inactive";
this.onstop?.();
}
}
vi.stubGlobal("MediaRecorder", FakeMediaRecorder);
Object.defineProperty(navigator, "mediaDevices", { configurable: true, value: { getUserMedia } });
const stopTrack = vi.fn();
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
let firstStart: Promise<void> | undefined;
await act(async () => {
firstStart = result.current.startRecording();
await result.current.startRecording();
});
expect(result.current.isStartingRecording).toBe(true);
expect(getUserMedia).toHaveBeenCalledOnce();
resolveStream?.({ getTracks: () => [{ stop: stopTrack }] } as unknown as MediaStream);
await act(async () => firstStart);
expect(result.current.isStartingRecording).toBe(false);
expect(result.current.isRecording).toBe(true);
act(() => result.current.cancelRecording());
vi.unstubAllGlobals();
});
it("canonicalizes codec MIME parameters and keeps the voice-note duration in the optimistic item", async () => {
vi.useFakeTimers();
mocks.upload.mockImplementation(async (input: { file: File }) => ({ id: "voice-1", displayName: input.file.name }));
class FakeMediaRecorder {
static isTypeSupported(): boolean {
return true;
}
state: RecordingState = "inactive";
mimeType = "audio/webm;codecs=opus";
ondataavailable: ((event: BlobEvent) => void) | null = null;
onstop: (() => void) | null = null;
onerror: (() => void) | null = null;
start(): void {
this.state = "recording";
}
stop(): void {
this.state = "inactive";
this.ondataavailable?.({ data: new Blob(["voice"], { type: this.mimeType }) } as BlobEvent);
this.onstop?.();
}
}
vi.stubGlobal("MediaRecorder", FakeMediaRecorder);
Object.defineProperty(navigator, "mediaDevices", {
configurable: true,
value: { getUserMedia: vi.fn().mockResolvedValue({ getTracks: () => [{ stop: vi.fn() }] }) },
});
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
await act(() => result.current.startRecording());
act(() => vi.advanceTimersByTime(2_100));
act(() => result.current.stopRecording());
vi.useRealTimers();
await waitFor(() => expect(result.current.attachments[0]?.status).toBe("ready"));
expect(result.current.attachments[0]).toMatchObject({ mimeType: "audio/webm", durationSeconds: 2, fileId: "voice-1" });
expect(mocks.upload.mock.calls.at(-1)?.[0].file.type).toBe("audio/webm");
vi.unstubAllGlobals();
});
});
@@ -0,0 +1,331 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { FILE_UPLOAD_MAX_FILE_SIZE_BYTES } from "@hivegrid/view-models";
import { uploadFileInChunks, waitForChatAttachmentScan } from "~/utils/files/uploadFileClient";
export type ChatPendingAttachment = {
readonly clientId: string;
readonly fileId: string | null;
readonly fileName: string;
readonly mimeType: string;
readonly sizeBytes: number;
readonly kind: "file" | "image" | "voice";
readonly status: "uploading" | "processing" | "ready" | "error";
readonly progress: number;
readonly errorKey: string | null;
readonly durationSeconds: number | null;
};
export const MAX_CHAT_ATTACHMENTS = 20;
export const MAX_VOICE_RECORDING_SECONDS = 10 * 60;
export function useChatAttachmentUploads(input: { readonly tenantSlug: string; readonly enabled: boolean }): {
readonly attachments: readonly ChatPendingAttachment[];
readonly isStartingRecording: boolean;
readonly isRecording: boolean;
readonly recordingDurationSeconds: number;
readonly errorKey: string | null;
readonly addFiles: (files: FileList | readonly File[], kindHint?: "voice") => void;
readonly retry: (clientId: string) => void;
readonly remove: (clientId: string) => void;
readonly clearReady: (fileIds: readonly string[]) => void;
readonly startRecording: () => Promise<void>;
readonly stopRecording: () => void;
readonly cancelRecording: () => void;
} {
const [attachments, setAttachments] = useState<readonly ChatPendingAttachment[]>([]);
const [isStartingRecording, setIsStartingRecording] = useState(false);
const [isRecording, setIsRecording] = useState(false);
const [recordingDurationSeconds, setRecordingDurationSeconds] = useState(0);
const [errorKey, setErrorKey] = useState<string | null>(null);
const filesRef = useRef(new Map<string, File>());
const attachmentCountRef = useRef(0);
const abortRef = useRef(new Map<string, AbortController>());
const recorderRef = useRef<MediaRecorder | null>(null);
const recordingStreamRef = useRef<MediaStream | null>(null);
const recordingChunksRef = useRef<Blob[]>([]);
const recordingStartedAtRef = useRef<number | null>(null);
const recordingTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const recordingCancelledRef = useRef(false);
const recordingStartingRef = useRef(false);
const recordingBytesRef = useRef(0);
const disposedRef = useRef(false);
const enabledRef = useRef(input.enabled);
enabledRef.current = input.enabled;
const clearRecordingTimer = useCallback(() => {
if (recordingTimerRef.current !== null) clearInterval(recordingTimerRef.current);
recordingTimerRef.current = null;
recordingStartedAtRef.current = null;
}, []);
const upload = useCallback(
async (clientId: string, file: File): Promise<void> => {
const controller = new AbortController();
abortRef.current.set(clientId, controller);
setAttachments((current) => current.map((item) => (item.clientId === clientId ? { ...item, status: "uploading", progress: 0, errorKey: null } : item)));
try {
const result = await uploadFileInChunks({
tenantSlug: input.tenantSlug,
file,
signal: controller.signal,
onProgress: (progress) => setAttachments((current) => current.map((item) => (item.clientId === clientId ? { ...item, progress } : item))),
onProcessing: () =>
setAttachments((current) => current.map((item) => (item.clientId === clientId ? { ...item, status: "processing", progress: 100 } : item))),
});
setAttachments((current) =>
current.map((item) =>
item.clientId === clientId ? { ...item, fileId: result.id, fileName: result.displayName, status: "processing", progress: 100 } : item
)
);
await waitForChatAttachmentScan({
tenantSlug: input.tenantSlug,
fileId: result.id,
signal: controller.signal,
});
setAttachments((current) =>
current.map((item) =>
item.clientId === clientId ? { ...item, fileId: result.id, fileName: result.displayName, status: "ready", progress: 100 } : item
)
);
} catch (error) {
if (controller.signal.aborted) return;
const errorKey = error instanceof Error && "errorKey" in error && typeof error.errorKey === "string" ? error.errorKey : "chat.attachments.uploadFailed";
setAttachments((current) => current.map((item) => (item.clientId === clientId ? { ...item, status: "error", errorKey } : item)));
} finally {
abortRef.current.delete(clientId);
}
},
[input.tenantSlug]
);
const addFiles = useCallback(
(files: FileList | readonly File[], kindHint?: "voice", durationSeconds: number | null = null) => {
if (!input.enabled) return;
const selected = Array.from(files);
if (selected.length === 0) return;
if (selected.length > Math.max(0, MAX_CHAT_ATTACHMENTS - attachmentCountRef.current)) {
setErrorKey("chat.attachments.tooMany");
return;
}
attachmentCountRef.current += selected.length;
setErrorKey(null);
const entries = selected.map((file) => {
const clientId = createClientId();
filesRef.current.set(clientId, file);
return {
clientId,
fileId: null,
fileName: file.name,
mimeType: file.type || "application/octet-stream",
sizeBytes: file.size,
kind:
kindHint === "voice" || file.type.startsWith("audio/")
? ("voice" as const)
: file.type.startsWith("image/")
? ("image" as const)
: ("file" as const),
status: "uploading" as const,
progress: 0,
errorKey: null,
durationSeconds: kindHint === "voice" ? durationSeconds : null,
};
});
setAttachments((current) => [...current, ...entries]);
for (const entry of entries) void upload(entry.clientId, filesRef.current.get(entry.clientId)!);
},
[input.enabled, upload]
);
const remove = useCallback((clientId: string) => {
abortRef.current.get(clientId)?.abort();
abortRef.current.delete(clientId);
filesRef.current.delete(clientId);
setAttachments((current) => {
const removed = current.some((item) => item.clientId === clientId);
if (removed) attachmentCountRef.current = Math.max(0, attachmentCountRef.current - 1);
return current.filter((item) => item.clientId !== clientId);
});
setErrorKey(null);
}, []);
const retry = useCallback(
(clientId: string) => {
const file = filesRef.current.get(clientId);
if (file) void upload(clientId, file);
},
[upload]
);
const clearReady = useCallback((fileIds: readonly string[]) => {
const sent = new Set(fileIds);
setAttachments((current) => {
const removedClientIds = current.filter((item) => item.fileId && sent.has(item.fileId)).map((item) => item.clientId);
for (const clientId of removedClientIds) filesRef.current.delete(clientId);
attachmentCountRef.current = Math.max(0, attachmentCountRef.current - removedClientIds.length);
return current.filter((item) => !item.fileId || !sent.has(item.fileId));
});
}, []);
const stopRecording = useCallback(() => {
recordingCancelledRef.current = false;
if (recorderRef.current?.state === "recording") recorderRef.current.stop();
}, []);
const cancelRecording = useCallback(() => {
recordingCancelledRef.current = true;
if (recorderRef.current?.state === "recording") recorderRef.current.stop();
}, []);
const startRecording = useCallback(async () => {
if (!input.enabled || isRecording || recordingStartingRef.current || recorderRef.current) {
return;
}
if (typeof MediaRecorder === "undefined" || !navigator.mediaDevices?.getUserMedia) {
setErrorKey("chat.attachments.recordingUnsupported");
return;
}
let stream: MediaStream | null = null;
recordingStartingRef.current = true;
setIsStartingRecording(true);
try {
setErrorKey(null);
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
if (disposedRef.current || !enabledRef.current) {
stream.getTracks().forEach((track) => track.stop());
return;
}
recordingStreamRef.current = stream;
recordingChunksRef.current = [];
recordingBytesRef.current = 0;
recordingCancelledRef.current = false;
setRecordingDurationSeconds(0);
const preferredMimeType = preferredRecordingMimeType();
const recorder = new MediaRecorder(stream, preferredMimeType ? { mimeType: preferredMimeType } : undefined);
recorderRef.current = recorder;
recorder.ondataavailable = (event) => {
if (event.data.size <= 0 || recordingCancelledRef.current) return;
if (recordingBytesRef.current + event.data.size > FILE_UPLOAD_MAX_FILE_SIZE_BYTES) {
recordingCancelledRef.current = true;
setErrorKey("chat.attachments.recordingTooLarge");
if (recorder.state === "recording") recorder.stop();
return;
}
recordingBytesRef.current += event.data.size;
recordingChunksRef.current.push(event.data);
};
recorder.onstop = () => {
const cancelled = recordingCancelledRef.current;
const durationSeconds = recordingStartedAtRef.current
? Math.min(MAX_VOICE_RECORDING_SECONDS, Math.max(1, Math.round((Date.now() - recordingStartedAtRef.current) / 1_000)))
: null;
const mimeType = canonicalRecordingMimeType(recorder.mimeType);
const blob = new Blob(recordingChunksRef.current, { type: mimeType });
const extension = recordingFileExtension(mimeType);
if (!cancelled && blob.size > 0 && isSupportedRecordingMimeType(mimeType)) {
addFiles([new File([blob], `voice-note-${Date.now()}.${extension}`, { type: mimeType })], "voice", durationSeconds);
} else if (!cancelled && blob.size > 0) {
setErrorKey("chat.attachments.recordingFailed");
}
recordingChunksRef.current = [];
recordingBytesRef.current = 0;
recordingCancelledRef.current = false;
clearRecordingTimer();
recordingStreamRef.current?.getTracks().forEach((track) => track.stop());
recordingStreamRef.current = null;
recorderRef.current = null;
setIsRecording(false);
setRecordingDurationSeconds(0);
};
recorder.onerror = () => {
recordingCancelledRef.current = true;
recordingChunksRef.current = [];
clearRecordingTimer();
recordingStreamRef.current?.getTracks().forEach((track) => track.stop());
recordingStreamRef.current = null;
recorderRef.current = null;
setIsRecording(false);
setRecordingDurationSeconds(0);
setErrorKey("chat.attachments.recordingFailed");
};
recorder.start(1_000);
recordingStartedAtRef.current = Date.now();
recordingTimerRef.current = setInterval(() => {
const startedAt = recordingStartedAtRef.current;
if (startedAt === null) return;
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1_000));
setRecordingDurationSeconds(Math.min(MAX_VOICE_RECORDING_SECONDS, elapsedSeconds));
if (elapsedSeconds >= MAX_VOICE_RECORDING_SECONDS && recorder.state === "recording") {
recordingCancelledRef.current = false;
recorder.stop();
}
}, 250);
setIsRecording(true);
} catch {
stream?.getTracks().forEach((track) => track.stop());
recordingStreamRef.current = null;
setIsRecording(false);
setErrorKey("chat.attachments.microphoneDenied");
} finally {
recordingStartingRef.current = false;
if (!disposedRef.current) setIsStartingRecording(false);
}
}, [addFiles, clearRecordingTimer, input.enabled, isRecording]);
useEffect(
() => () => {
disposedRef.current = true;
for (const controller of abortRef.current.values()) controller.abort();
recordingCancelledRef.current = true;
clearRecordingTimer();
if (recorderRef.current?.state === "recording") recorderRef.current.stop();
recordingStreamRef.current?.getTracks().forEach((track) => track.stop());
},
[clearRecordingTimer]
);
return {
attachments,
isStartingRecording,
isRecording,
recordingDurationSeconds,
errorKey,
addFiles,
retry,
remove,
clearReady,
startRecording,
stopRecording,
cancelRecording,
};
}
function createClientId(): string {
return typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
? crypto.randomUUID()
: `upload-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
const RECORDING_MIME_TYPES = new Set(["audio/webm", "audio/ogg", "audio/mp4", "audio/mpeg", "audio/wav"]);
function preferredRecordingMimeType(): string | undefined {
if (typeof MediaRecorder.isTypeSupported !== "function") return undefined;
return ["audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/mp4"].find((mimeType) => MediaRecorder.isTypeSupported(mimeType));
}
function canonicalRecordingMimeType(value: string): string {
const base = (value || "audio/webm").split(";", 1)[0]?.trim().toLowerCase() || "audio/webm";
return base === "audio/x-m4a" ? "audio/mp4" : base === "audio/x-wav" ? "audio/wav" : base;
}
function isSupportedRecordingMimeType(value: string): boolean {
return RECORDING_MIME_TYPES.has(value);
}
function recordingFileExtension(mimeType: string): string {
if (mimeType === "audio/ogg") return "ogg";
if (mimeType === "audio/mp4") return "m4a";
if (mimeType === "audio/mpeg") return "mp3";
if (mimeType === "audio/wav") return "wav";
return "webm";
}
@@ -0,0 +1,388 @@
// @vitest-environment jsdom
import {
CHAT_EVENT_NAMES,
type ChatLocalEcho,
type ChatMessageCreatedEvent,
type ChatReadReceiptEvent,
type ChatRealtimeClient,
type ChatRealtimeClientOptions,
} from "@hivegrid/realtime";
import type { ChatMessageCandidate, ChatResolvedAuthorVM } from "@hivegrid/view-models";
import { act, renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type { ChatVisibilitySource } from "./chatInteractionControllers";
import { useChatChannelRealtime, type UseChatChannelRealtimeInput } from "./useChatChannelRealtime";
const viewer: ChatResolvedAuthorVM = {
userId: "user_viewer",
displayName: "Raffael",
avatar: { imageUrl: null, fallbackLabel: "R" },
isCurrentUser: true,
};
const reader: ChatResolvedAuthorVM = {
userId: "user_reader",
displayName: "Mara",
avatar: { imageUrl: null, fallbackLabel: "M" },
isCurrentUser: false,
};
function hydratedMessage(): ChatMessageCandidate {
return {
id: "message_read",
clientMessageId: "client_read",
source: "persisted",
deliveryState: "sent",
failureReasonKey: null,
retryable: false,
author: { userId: "user_author", displayName: "Ada", avatar: { imageUrl: null, fallbackLabel: "A" }, isCurrentUser: false },
bodyMarkdown: "Ältere Nachricht",
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: "2026-07-15T07:00:00.000Z",
updatedAtIso: "2026-07-15T07:00:00.000Z",
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: { readCount: 0, recipientCount: 2, readerUserIds: [], readerLabels: [], labelKey: "chat.message.read.none" },
pin: null,
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
};
}
function createdEvent(clientMessageId = "client_remote"): ChatMessageCreatedEvent {
return {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:2",
requestId: "request_remote",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:00:00.000Z",
data: {
message: {
id: "message_remote",
clientMessageId,
authorUserId: "user_missing",
body: "Realtime",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T08:00:00.000Z",
updatedAt: "2026-07-15T08:00:00.000Z",
editedAt: null,
deletedAt: null,
},
},
};
}
function readReceiptEvent(userId = viewer.userId): ChatReadReceiptEvent {
return {
event: CHAT_EVENT_NAMES.readReceipt,
cursor: "stream_1:3",
requestId: "request_read",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:02:00.000Z",
data: { messageId: "message_read", userId, readAt: "2026-07-15T08:02:00.000Z" },
};
}
function localEcho(overrides: Partial<ChatLocalEcho> = {}): ChatLocalEcho {
return {
chatId: "chat_1",
requestId: "request_local",
clientMessageId: "client_local",
body: "Optimistisch",
mentions: [],
status: "sending",
failureI18nKey: null,
retryable: false,
attempts: 1,
createdAtMs: Date.parse("2026-07-15T08:01:00.000Z"),
canonicalMessage: null,
...overrides,
};
}
function createHarness() {
const calls: string[] = [];
let callbacks: ChatRealtimeClientOptions | null = null;
const callbackHistory: ChatRealtimeClientOptions[] = [];
const client: ChatRealtimeClient = {
status: "offline",
connect: vi.fn(() => calls.push("connect")),
retryNow: vi.fn(),
close: vi.fn(() => calls.push("close")),
subscribe: vi.fn((chatId, cursor) => calls.push(`subscribe:${chatId}:${cursor ?? ""}`)),
unsubscribe: vi.fn((chatId) => calls.push(`unsubscribe:${chatId}`)),
sendMessage: vi.fn((request) => localEcho({ chatId: request.chatId, body: request.body })),
restoreFailedMessage: vi.fn((request) =>
localEcho({
chatId: request.chatId,
body: request.body,
clientMessageId: request.clientMessageId,
requestId: request.requestId,
status: "failed",
failureI18nKey: request.failureI18nKey,
retryable: request.retryable,
createdAtMs: request.createdAtMs,
})
),
retryMessage: vi.fn(() => localEcho({ status: "sending" })),
discardMessage: vi.fn(() => true),
markRead: vi.fn(() => ({ requestId: "request_read", sent: true })),
setTyping: vi.fn(() => true),
setPresence: vi.fn(() => true),
ping: vi.fn(() => true),
getLocalEchoes: vi.fn(() => []),
getTyping: vi.fn(() => []),
getPresence: vi.fn(() => []),
getSubscriptions: vi.fn(() => []),
};
const clientFactory = vi.fn((options: ChatRealtimeClientOptions) => {
callbacks = options;
callbackHistory.push(options);
return client;
});
return {
calls,
client,
clientFactory,
getCallbacks: () => callbacks as ChatRealtimeClientOptions,
getCallbackHistory: () => callbackHistory,
};
}
function options(
harness: ReturnType<typeof createHarness>,
revalidate: ReturnType<typeof vi.fn>,
visibility: ChatVisibilitySource,
initialCursor = "stream_1:1",
tenantSlug = "hivegrid-demo",
chatId = "chat_1"
): UseChatChannelRealtimeInput {
return {
tenantSlug,
chatId,
initialCursor,
csrfToken: "csrf",
routing: { protocol: "https", apiHost: "api.example.test" },
initialMessages: [],
currentUser: viewer,
unknownAuthorLabel: "Unbekannt",
resolveAuthor: () => {
throw new Error("projection miss");
},
revalidate,
clientFactory: harness.clientFactory,
tokenProviderFactory: () => async () => "token",
visibility,
};
}
describe("useChatChannelRealtime", () => {
it("subscribes before connecting and reapplies a newer loader cursor without reconnecting", () => {
const harness = createHarness();
const visibility = fakeVisibility();
const revalidate = vi.fn();
const { rerender, unmount } = renderHook(({ cursor }) => useChatChannelRealtime(options(harness, revalidate, visibility, cursor)), {
initialProps: { cursor: "stream_1:1" },
});
expect(harness.calls.slice(0, 2)).toEqual(["subscribe:chat_1:stream_1:1", "connect"]);
rerender({ cursor: "stream_1:3" });
expect(harness.calls).toContain("subscribe:chat_1:stream_1:3");
expect(harness.client.connect).toHaveBeenCalledTimes(1);
unmount();
expect(harness.calls.slice(-2)).toEqual(["unsubscribe:chat_1", "close"]);
});
it("revalidates after reconnect and reset, and safely renders unknown event authors", async () => {
const harness = createHarness();
const visibility = fakeVisibility();
const revalidate = vi.fn();
const { result } = renderHook(() => useChatChannelRealtime(options(harness, revalidate, visibility)));
const callbacks = harness.getCallbacks();
act(() => {
callbacks.onStatus?.("reconnecting", { reconnectAttempt: 1, retryAtMs: 1_000 });
callbacks.onStatus?.("online", { reconnectAttempt: 0, retryAtMs: null });
callbacks.onResetRequired?.({ chatId: "chat_1", currentStreamId: "stream_2" });
expect(() => callbacks.onEvent?.(createdEvent(), { source: "live", reconciledClientMessageId: null })).not.toThrow();
});
await waitFor(() => expect(revalidate).toHaveBeenCalled());
expect(harness.client.setPresence).toHaveBeenCalledWith("online");
expect(result.current.connection.state).toBe("online");
expect(result.current.messages).toHaveLength(1);
expect(result.current.messages[0]?.author).toMatchObject({ userId: "user_missing", displayName: "Unbekannt" });
});
it("projects local echo, failure, acknowledgement and discard while delegating controls", () => {
const harness = createHarness();
const visibility = fakeVisibility();
const { result } = renderHook(() => useChatChannelRealtime(options(harness, vi.fn(), visibility)));
const callbacks = harness.getCallbacks();
act(() => callbacks.onLocalEcho?.(localEcho(), "created"));
expect(result.current.messages[0]).toMatchObject({ source: "local_echo", deliveryState: "sending" });
act(() => callbacks.onLocalEcho?.(localEcho({ status: "failed", retryable: true, failureI18nKey: "chat.errors.realtimeUnavailable" }), "updated"));
expect(result.current.messages[0]).toMatchObject({ deliveryState: "failed", failureReasonKey: "chat.errors.realtimeUnavailable" });
act(() =>
callbacks.onLocalEcho?.(
localEcho({
status: "sent",
canonicalMessage: { ...createdEvent("client_local").data.message, authorUserId: viewer.userId },
}),
"updated"
)
);
expect(result.current.messages[0]).toMatchObject({ source: "http_ack", deliveryState: "sent" });
expect(result.current.sendMessage("Neu")).not.toBeNull();
expect(harness.client.sendMessage).toHaveBeenCalledWith({ chatId: "chat_1", body: "Neu", mentions: [] });
expect(result.current.sendMessage("Retry", [], "persisted_client_1", "persisted_request_1")).not.toBeNull();
expect(harness.client.sendMessage).toHaveBeenCalledWith({
chatId: "chat_1",
body: "Retry",
mentions: [],
clientMessageId: "persisted_client_1",
requestId: "persisted_request_1",
});
expect(
result.current.restoreFailedMessage("Fehlgeschlagen", "persisted_client_2", "persisted_request_2", "chat.errors.realtimeUnavailable", true, 500)
).not.toBeNull();
expect(harness.client.restoreFailedMessage).toHaveBeenCalledWith({
chatId: "chat_1",
body: "Fehlgeschlagen",
mentions: [],
clientMessageId: "persisted_client_2",
requestId: "persisted_request_2",
failureI18nKey: "chat.errors.realtimeUnavailable",
retryable: true,
createdAtMs: 500,
});
expect(result.current.retryMessage("client_local")).not.toBeNull();
expect(result.current.discardMessage("client_local")).toBe(true);
result.current.retryConnection();
expect(harness.client.retryNow).toHaveBeenCalledOnce();
act(() => callbacks.onLocalEcho?.(localEcho(), "discarded"));
expect(result.current.messages).toEqual([]);
});
it("does not expose candidates from the previous tenant or channel scope", () => {
const harness = createHarness();
const visibility = fakeVisibility();
const revalidate = vi.fn();
const { result, rerender } = renderHook(
({ tenantSlug, chatId }) => useChatChannelRealtime(options(harness, revalidate, visibility, "stream_1:1", tenantSlug, chatId)),
{ initialProps: { tenantSlug: "tenant-one", chatId: "chat_1" } }
);
const oldCallbacks = harness.getCallbacks();
act(() => oldCallbacks.onEvent?.(createdEvent(), { source: "live", reconciledClientMessageId: null }));
expect(result.current.messages).toHaveLength(1);
rerender({ tenantSlug: "tenant-two", chatId: "chat_2" });
expect(result.current.messages).toEqual([]);
expect(result.current.typingLabels).toEqual([]);
expect(result.current.connection.state).toBe("offline");
act(() => oldCallbacks.onLocalEcho?.(localEcho(), "created"));
expect(result.current.messages).toEqual([]);
expect(harness.getCallbackHistory()).toHaveLength(2);
});
it("tracks begin/end visibility sessions before delegating exact read receipts", () => {
vi.useFakeTimers();
const harness = createHarness();
const visibility = fakeVisibility();
const { result, unmount } = renderHook(() => useChatChannelRealtime(options(harness, vi.fn(), visibility)));
act(() => {
result.current.beginMessageVisible("message_short", "2026-07-15T08:00:00.000Z");
vi.advanceTimersByTime(999);
result.current.endMessageVisible("message_short");
vi.advanceTimersByTime(5_000);
});
expect(harness.client.markRead).not.toHaveBeenCalled();
act(() => {
result.current.beginMessageVisible("message_read", "2026-07-15T08:01:00.000Z");
vi.advanceTimersByTime(3_000);
});
expect(harness.client.markRead).toHaveBeenCalledWith("chat_1", "message_read");
act(() => {
callbacksFor(harness).onStatus?.("reconnecting", { reconnectAttempt: 1, retryAtMs: 1_000 });
callbacksFor(harness).onStatus?.("online", { reconnectAttempt: 0, retryAtMs: null });
});
expect(harness.client.markRead).toHaveBeenLastCalledWith("chat_1", "message_read", "request_read");
act(() => {
callbacksFor(harness).onStatus?.("reconnecting", { reconnectAttempt: 1, retryAtMs: 1_000 });
callbacksFor(harness).onEvent?.(readReceiptEvent(), { source: "gap", reconciledClientMessageId: null });
callbacksFor(harness).onStatus?.("online", { reconnectAttempt: 0, retryAtMs: null });
});
expect(harness.client.markRead).toHaveBeenCalledTimes(2);
unmount();
vi.useRealTimers();
});
it("keeps live read aggregates on older hydrated messages across loader revalidation", () => {
const harness = createHarness();
const visibility = fakeVisibility();
const revalidate = vi.fn();
const { result, rerender } = renderHook(
({ revision }) => {
const base = options(harness, revalidate, visibility);
return useChatChannelRealtime({
...base,
initialMessages: [{ ...hydratedMessage(), updatedAtIso: `2026-07-15T07:00:0${revision}.000Z` }],
resolveAuthor: (userId) => (userId === reader.userId ? reader : null),
});
},
{ initialProps: { revision: 0 } }
);
act(() => callbacksFor(harness).onEvent?.(readReceiptEvent(reader.userId), { source: "live", reconciledClientMessageId: null }));
expect(result.current.messages[0]?.readAggregate).toMatchObject({
readCount: 1,
readerUserIds: [reader.userId],
readerLabels: [reader.displayName],
});
rerender({ revision: 1 });
expect(result.current.messages[0]?.readAggregate).toMatchObject({
readCount: 1,
readerUserIds: [reader.userId],
readerLabels: [reader.displayName],
});
});
});
function callbacksFor(harness: ReturnType<typeof createHarness>): ChatRealtimeClientOptions {
return harness.getCallbacks();
}
function fakeVisibility(): ChatVisibilitySource {
return {
visibilityState: "visible",
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
};
}
@@ -0,0 +1,363 @@
import {
CHAT_EVENT_NAMES,
createChatRealtimeClient,
isPersistentChatEvent,
type ChatLocalEcho,
type ChatMention,
type ChatRealtimeClient,
type ChatRealtimeClientOptions,
type ChatRealtimeMessage,
type ChatRemotePresence,
type ChatTokenProvider,
} from "@hivegrid/realtime";
import {
groupChatMessagesByDay,
reconcileChatMessages,
type ChatMessageActionsVM,
type ChatMessageCandidate,
type ChatResolvedAuthorVM,
} from "@hivegrid/view-models";
import { useCallback, useEffect, useMemo, useReducer, useRef } from "react";
import {
candidateFromChatEvent,
candidateFromLocalEcho,
chatChannelRealtimeReducer,
createChatRealtimeScopeKey,
createInitialChatChannelRealtimeState,
filterHydratedChatCandidates,
overlayChatReadReceipts,
safeResolveChatAuthor,
type ChatCandidateMapping,
} from "./chatChannelRealtimeReducer";
import {
createChatReadReceiptBatcher,
createChatTypingController,
type ChatInteractionScheduler,
type ChatReadReceiptBatcher,
type ChatTypingController,
type ChatVisibilitySource,
} from "./chatInteractionControllers";
import { buildChatWebSocketUrl, createChatTokenProvider, type ChatGatewayRouting, type ChatTokenFetch } from "./chatTokenProvider";
export type ChatRealtimeClientFactory = (options: ChatRealtimeClientOptions) => ChatRealtimeClient;
export type UseChatChannelRealtimeInput = {
readonly enabled?: boolean;
readonly tenantSlug: string;
readonly chatId: string;
readonly initialCursor: string;
readonly csrfToken: string | null;
readonly routing: ChatGatewayRouting;
readonly initialMessages: readonly ChatMessageCandidate[];
readonly currentUser: ChatResolvedAuthorVM;
readonly unknownAuthorLabel: string;
readonly resolveAuthor: (userId: string) => ChatResolvedAuthorVM | null | undefined;
readonly messageActions?: (message: ChatRealtimeMessage) => ChatMessageActionsVM;
readonly revalidate: () => void | Promise<void>;
readonly fetchImpl?: ChatTokenFetch;
readonly clientFactory?: ChatRealtimeClientFactory;
readonly tokenProviderFactory?: (input: {
readonly tenantSlug: string;
readonly csrfToken: string;
readonly fetchImpl?: ChatTokenFetch;
}) => ChatTokenProvider;
readonly visibility?: ChatVisibilitySource;
readonly interactionScheduler?: ChatInteractionScheduler;
};
export type UseChatChannelRealtimeResult = {
readonly connection: ReturnType<typeof createInitialChatChannelRealtimeState>["connection"];
readonly messages: ReturnType<typeof reconcileChatMessages>;
readonly messageGroups: ReturnType<typeof groupChatMessagesByDay>;
readonly typingLabels: readonly string[];
readonly presence: readonly ChatRemotePresence[];
readonly sendMessage: (body: string, mentions?: readonly ChatMention[], clientMessageId?: string, requestId?: string) => ChatLocalEcho | null;
readonly restoreFailedMessage: (
body: string,
clientMessageId: string,
requestId: string,
failureI18nKey: string,
retryable: boolean,
createdAtMs: number
) => ChatLocalEcho | null;
readonly retryMessage: (clientMessageId: string) => ChatLocalEcho | null;
readonly discardMessage: (clientMessageId: string) => boolean;
readonly updateTyping: (body: string) => void;
readonly stopTyping: () => void;
readonly beginMessageVisible: (messageId: string, createdAtIso: string) => void;
readonly endMessageVisible: (messageId: string) => void;
readonly retryConnection: () => void;
};
export function useChatChannelRealtime(input: UseChatChannelRealtimeInput): UseChatChannelRealtimeResult {
const initialScopeKey = createChatRealtimeScopeKey(input.tenantSlug, input.chatId);
const [state, dispatch] = useReducer(chatChannelRealtimeReducer, initialScopeKey, createInitialChatChannelRealtimeState);
const clientRef = useRef<ChatRealtimeClient | null>(null);
const typingRef = useRef<ChatTypingController | null>(null);
const readBatcherRef = useRef<ChatReadReceiptBatcher | null>(null);
const retryConnectionRef = useRef<(() => void) | null>(null);
const appliedCursorRef = useRef<string | null>(null);
const inputRef = useRef(input);
inputRef.current = input;
const chatId = input.chatId;
const tenantSlug = input.tenantSlug;
const csrfToken = input.csrfToken;
const enabled = input.enabled;
const apiHost = input.routing.apiHost;
const protocol = input.routing.protocol;
const scopeKey = createChatRealtimeScopeKey(tenantSlug, chatId);
const scopedState = useMemo(() => (state.scopeKey === scopeKey ? state : createInitialChatChannelRealtimeState(scopeKey)), [scopeKey, state]);
const messages = useMemo(() => {
const candidates = [...input.initialMessages, ...filterHydratedChatCandidates(input.initialMessages, scopedState.candidates)];
return reconcileChatMessages(
overlayChatReadReceipts(candidates, scopedState.readReceipts, {
currentUser: input.currentUser,
unknownAuthorLabel: input.unknownAuthorLabel,
resolveAuthor: input.resolveAuthor,
...(input.messageActions ? { messageActions: input.messageActions } : {}),
}),
{ allowPins: true }
);
}, [
input.currentUser,
input.initialMessages,
input.messageActions,
input.resolveAuthor,
input.unknownAuthorLabel,
scopedState.candidates,
scopedState.readReceipts,
]);
const messageGroups = useMemo(() => groupChatMessagesByDay(messages), [messages]);
useEffect(() => {
const setup = inputRef.current;
const active = enabled !== false && csrfToken !== null && csrfToken.trim().length > 0;
dispatch({ type: "reset", scopeKey });
appliedCursorRef.current = null;
if (!active) return;
let mounted = true;
let revalidationQueued = false;
let reconnectObserved = false;
const requestRevalidation = () => {
if (!mounted || revalidationQueued) return;
revalidationQueued = true;
queueMicrotask(() => {
revalidationQueued = false;
if (!mounted) return;
try {
void Promise.resolve(inputRef.current.revalidate()).catch(() => undefined);
} catch {
// Transport state must not be affected by a route revalidation error.
}
});
};
const mapping = (): ChatCandidateMapping => ({
currentUser: inputRef.current.currentUser,
unknownAuthorLabel: inputRef.current.unknownAuthorLabel,
resolveAuthor: inputRef.current.resolveAuthor,
...(inputRef.current.messageActions ? { messageActions: inputRef.current.messageActions } : {}),
});
const visibility = setup.visibility ?? getDocumentVisibility();
const clientFactory = setup.clientFactory ?? createChatRealtimeClient;
const tokenProviderFactory = setup.tokenProviderFactory ?? createChatTokenProvider;
let client: ChatRealtimeClient;
try {
client = clientFactory({
url: buildChatWebSocketUrl({ apiHost, protocol }),
tokenProvider: tokenProviderFactory({
tenantSlug,
csrfToken,
...(setup.fetchImpl ? { fetchImpl: setup.fetchImpl } : {}),
}),
onStatus(status, detail) {
if (!mounted) return;
dispatch({
type: "connection",
scopeKey,
connection: {
state: status,
reconnectAttempt: detail.reconnectAttempt,
retryAtIso: detail.retryAtMs === null ? null : new Date(detail.retryAtMs).toISOString(),
},
});
if (status === "reconnecting") reconnectObserved = true;
if (status === "online") {
clientRef.current?.setPresence(visibility.visibilityState === "visible" ? "online" : "away");
readBatcherRef.current?.retryPending();
if (reconnectObserved) requestRevalidation();
reconnectObserved = false;
}
},
onEvent(event) {
if (!mounted || event.chatId !== chatId) return;
if (event.event === CHAT_EVENT_NAMES.readReceipt) {
if (event.data.userId === inputRef.current.currentUser.userId) {
readBatcherRef.current?.acknowledge(event.chatId, event.data.messageId);
}
dispatch({ type: "read_receipt", scopeKey, receipt: { messageId: event.data.messageId, userId: event.data.userId } });
}
try {
const candidate = candidateFromChatEvent(event, mapping());
if (candidate) dispatch({ type: "upsert_candidate", scopeKey, candidate });
} catch {
// A stale or unknown projection must never tear down the stream.
}
if (isPersistentChatEvent(event)) requestRevalidation();
},
onLocalEcho(echo, reason) {
if (!mounted || echo.chatId !== chatId) return;
if (reason === "discarded" || reason === "evicted") {
dispatch({
type: "remove_candidate",
scopeKey,
authorUserId: inputRef.current.currentUser.userId,
clientMessageId: echo.clientMessageId,
});
return;
}
try {
dispatch({ type: "upsert_candidate", scopeKey, candidate: candidateFromLocalEcho(echo, mapping()) });
} catch {
// Invalid local timestamps or projections are ignored, not fatal.
}
},
onTyping(chatId, entries) {
if (!mounted || chatId !== setup.chatId) return;
const currentUserId = inputRef.current.currentUser.userId;
const labels = entries.filter((entry) => entry.userId !== currentUserId).map((entry) => safeResolveChatAuthor(entry.userId, mapping()).displayName);
dispatch({ type: "typing", scopeKey, labels });
},
onPresence(chatId, entries) {
if (mounted && chatId === setup.chatId) dispatch({ type: "presence", scopeKey, entries });
},
onResetRequired({ chatId }) {
if (mounted && chatId === setup.chatId) requestRevalidation();
},
});
} catch {
dispatch({ type: "connection", scopeKey, connection: { state: "blocked", reconnectAttempt: 0, retryAtIso: null } });
return;
}
clientRef.current = client;
typingRef.current = createChatTypingController({
chatId,
send: (chatId, status) => client.setTyping(chatId, status),
...(setup.interactionScheduler ? { scheduler: setup.interactionScheduler } : {}),
});
readBatcherRef.current = createChatReadReceiptBatcher({
send: (chatId, messageId, requestId) => (requestId ? client.markRead(chatId, messageId, requestId) : client.markRead(chatId, messageId)),
visibility,
...(setup.interactionScheduler ? { scheduler: setup.interactionScheduler } : {}),
});
retryConnectionRef.current = () => {
reconnectObserved = true;
client.retryNow();
};
// Subscribe before connect so the authenticate frame carries the resume cursor.
client.subscribe(chatId, setup.initialCursor);
appliedCursorRef.current = setup.initialCursor;
client.connect();
const onVisibilityChange = () => {
if (visibility.visibilityState === "visible") {
client.setPresence("online");
} else {
typingRef.current?.stop();
client.setPresence("away");
}
};
visibility.addEventListener("visibilitychange", onVisibilityChange);
return () => {
mounted = false;
visibility.removeEventListener("visibilitychange", onVisibilityChange);
typingRef.current?.dispose();
readBatcherRef.current?.dispose();
typingRef.current = null;
readBatcherRef.current = null;
retryConnectionRef.current = null;
client.unsubscribe(chatId);
client.close();
if (clientRef.current === client) clientRef.current = null;
};
}, [apiHost, chatId, csrfToken, enabled, protocol, scopeKey, tenantSlug]);
useEffect(() => {
const client = clientRef.current;
if (!client || appliedCursorRef.current === input.initialCursor) return;
client.subscribe(input.chatId, input.initialCursor);
appliedCursorRef.current = input.initialCursor;
}, [input.chatId, input.initialCursor]);
const sendMessage = useCallback((body: string, mentions: readonly ChatMention[] = [], clientMessageId?: string, requestId?: string) => {
const client = clientRef.current;
if (!client) return null;
typingRef.current?.stop();
return client.sendMessage({
chatId: inputRef.current.chatId,
body,
mentions,
...(clientMessageId ? { clientMessageId } : {}),
...(requestId ? { requestId } : {}),
});
}, []);
const restoreFailedMessage = useCallback(
(body: string, clientMessageId: string, requestId: string, failureI18nKey: string, retryable: boolean, createdAtMs: number) =>
clientRef.current?.restoreFailedMessage({
chatId: inputRef.current.chatId,
body,
mentions: [],
clientMessageId,
requestId,
failureI18nKey,
retryable,
createdAtMs,
}) ?? null,
[]
);
const retryMessage = useCallback((clientMessageId: string) => clientRef.current?.retryMessage(clientMessageId) ?? null, []);
const discardMessage = useCallback((clientMessageId: string) => clientRef.current?.discardMessage(clientMessageId) ?? false, []);
const updateTyping = useCallback((body: string) => typingRef.current?.update(body), []);
const stopTyping = useCallback(() => typingRef.current?.stop(), []);
const beginMessageVisible = useCallback((messageId: string, createdAtIso: string) => {
readBatcherRef.current?.beginVisible(inputRef.current.chatId, messageId, createdAtIso);
}, []);
const endMessageVisible = useCallback((messageId: string) => {
readBatcherRef.current?.endVisible(inputRef.current.chatId, messageId);
}, []);
const retryConnection = useCallback(() => retryConnectionRef.current?.(), []);
return {
connection: scopedState.connection,
messages,
messageGroups,
typingLabels: scopedState.typingLabels,
presence: scopedState.presence,
sendMessage,
restoreFailedMessage,
retryMessage,
discardMessage,
updateTyping,
stopTyping,
beginMessageVisible,
endMessageVisible,
retryConnection,
};
}
function getDocumentVisibility(): ChatVisibilitySource {
if (typeof document === "undefined") {
return {
visibilityState: "visible",
addEventListener: () => undefined,
removeEventListener: () => undefined,
};
}
return document;
}
@@ -0,0 +1,467 @@
// @vitest-environment jsdom
import { act, renderHook } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useChatDraft, type ChatDraftDelivery, type ChatDraftStorage } from "./useChatDraft";
const STORAGE_KEY = "chat:draft:v1:tenant:user:chat";
const PENDING_STORAGE_KEY = `${STORAGE_KEY}:pending`;
afterEach(() => {
vi.useRealTimers();
});
describe("useChatDraft", () => {
it("loads a channel-scoped draft and saves edits only after the debounce", () => {
vi.useFakeTimers();
const storage = createMemoryStorage();
storage.setItem(STORAGE_KEY, "Vorhanden");
const { result } = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries: [],
sendMessage: () => null,
updateTyping: vi.fn(),
storage,
})
);
expect(result.current).toMatchObject({ draft: "Vorhanden", loaded: true });
act(() => result.current.updateDraft("Neu"));
expect(storage.getItem(STORAGE_KEY)).toBe("Vorhanden");
act(() => vi.advanceTimersByTime(300));
expect(storage.getItem(STORAGE_KEY)).toBe("Neu");
});
it("keeps the draft when the realtime client cannot accept the send", () => {
const storage = createMemoryStorage();
const { result } = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries: [],
sendMessage: () => null,
updateTyping: vi.fn(),
storage,
})
);
act(() => result.current.updateDraft("Nicht verlieren"));
let accepted = true;
act(() => {
accepted = result.current.sendDraft("Nicht verlieren");
});
expect(accepted).toBe(false);
expect(result.current.draft).toBe("Nicht verlieren");
expect(storage.getItem(STORAGE_KEY)).toBe("Nicht verlieren");
});
it("rehydrates an unresolved send after navigation with the original correlation ids", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const first = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
act(() => first.result.current.updateDraft("Ack abwarten"));
act(() => {
expect(first.result.current.sendDraft("Ack abwarten")).toBe(true);
});
expect(first.result.current.draft).toBe("");
expect(storage.getItem(STORAGE_KEY)).toBeNull();
expect(storage.getItem(PENDING_STORAGE_KEY)).not.toBeNull();
first.unmount();
const second = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
expect(second.result.current.draft).toBe("");
expect(sendMessage).toHaveBeenCalledTimes(2);
expect(sendMessage).toHaveBeenLastCalledWith("Ack abwarten", "client_1", "request_1");
deliveries = [{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false }];
second.rerender();
expect(second.result.current.draft).toBe("");
expect(storage.getItem(STORAGE_KEY)).toBeNull();
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
it("rehydrates every older pending send without replacing a newer composer draft", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi
.fn()
.mockReturnValueOnce({ clientMessageId: "client_1", requestId: "request_1" })
.mockReturnValueOnce({ clientMessageId: "client_2", requestId: "request_2" })
.mockImplementation((_body: string, clientMessageId?: string, requestId?: string) =>
clientMessageId && requestId ? { clientMessageId, requestId } : null
);
const first = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
act(() => first.result.current.updateDraft("Nachricht A"));
act(() => {
expect(first.result.current.sendDraft("Nachricht A")).toBe(true);
first.result.current.updateDraft("Nachricht B");
expect(first.result.current.sendDraft("Nachricht B")).toBe(true);
first.result.current.updateDraft("Neuer Entwurf C");
});
first.unmount();
const second = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
expect(second.result.current.draft).toBe("Neuer Entwurf C");
expect(sendMessage).toHaveBeenNthCalledWith(3, "Nachricht A", "client_1", "request_1");
expect(sendMessage).toHaveBeenNthCalledWith(4, "Nachricht B", "client_2", "request_2");
deliveries = [
{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false },
{ clientMessageId: "client_2", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false },
];
second.rerender();
expect(second.result.current.draft).toBe("Neuer Entwurf C");
expect(storage.getItem(STORAGE_KEY)).toBe("Neuer Entwurf C");
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
it("dispatches an explicit retry for a failed echo that still belongs to the active client", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const retryMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const hook = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
retryMessage,
updateTyping: vi.fn(),
storage,
})
);
act(() => hook.result.current.updateDraft("Direkt erneut versuchen"));
act(() => {
expect(hook.result.current.sendDraft("Direkt erneut versuchen")).toBe(true);
});
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.realtimeUnavailable",
retryable: true,
},
];
hook.rerender();
expect(hook.result.current.draft).toBe("Direkt erneut versuchen");
act(() => {
expect(hook.result.current.sendDraft("Direkt erneut versuchen")).toBe(true);
});
expect(retryMessage).toHaveBeenCalledWith("client_1");
expect(sendMessage).toHaveBeenCalledTimes(1);
expect(hook.result.current.draft).toBe("");
});
it("restores an observed failure as a local echo without sending it again", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const first = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
act(() => first.result.current.updateDraft("Nicht automatisch senden"));
act(() => {
expect(first.result.current.sendDraft("Nicht automatisch senden")).toBe(true);
});
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.invalidInput",
retryable: false,
},
];
first.rerender();
first.unmount();
deliveries = [];
const restoreFailedMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const second = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
restoreFailedMessage,
updateTyping: vi.fn(),
storage,
})
);
expect(sendMessage).toHaveBeenCalledTimes(1);
expect(restoreFailedMessage).toHaveBeenCalledWith(
"Nicht automatisch senden",
"client_1",
"request_1",
"chat.errors.invalidInput",
false,
expect.any(Number)
);
expect(second.result.current.draft).toBe("");
});
it("persists a later terminal retry failure with its new reason", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const retryMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const first = renderHook(() => useChatDraft({ storageKey: STORAGE_KEY, deliveries, sendMessage, retryMessage, updateTyping: vi.fn(), storage }));
act(() => first.result.current.updateDraft("Noch einmal"));
act(() => {
expect(first.result.current.sendDraft("Noch einmal")).toBe(true);
});
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.realtimeUnavailable",
retryable: true,
},
];
first.rerender();
act(() => {
expect(first.result.current.sendDraft("Noch einmal")).toBe(true);
});
deliveries = [{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sending", failureReasonKey: null, retryable: false }];
first.rerender();
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.invalidInput",
retryable: false,
},
];
first.rerender();
first.unmount();
deliveries = [];
const restoreFailedMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
renderHook(() => useChatDraft({ storageKey: STORAGE_KEY, deliveries, sendMessage, restoreFailedMessage, updateTyping: vi.fn(), storage }));
expect(restoreFailedMessage).toHaveBeenCalledWith("Noch einmal", "client_1", "request_1", "chat.errors.invalidInput", false, expect.any(Number));
});
it("refuses a seventeenth unresolved send without dropping the sixteen pending messages", () => {
const storage = createMemoryStorage();
const now = Date.now();
storage.setItem(
PENDING_STORAGE_KEY,
JSON.stringify({
version: 2,
revision: 16,
pending: Array.from({ length: 16 }, (_, index) => ({
body: `Nachricht ${index + 1}`,
clientMessageId: `client_${index + 1}`,
requestId: `request_${index + 1}`,
createdAt: now - 16 + index,
failureObserved: false,
failureReasonKey: null,
retryable: false,
restored: false,
revision: index + 1,
})),
})
);
const sendMessage = vi.fn((_body: string, clientMessageId?: string, requestId?: string) =>
clientMessageId && requestId ? { clientMessageId, requestId } : { clientMessageId: "client_17", requestId: "request_17" }
);
const first = renderHook(() => useChatDraft({ storageKey: STORAGE_KEY, deliveries: [], sendMessage, updateTyping: vi.fn(), storage }));
act(() => first.result.current.updateDraft("Nachricht 17"));
act(() => {
expect(first.result.current.sendDraft("Nachricht 17")).toBe(false);
});
expect(first.result.current.draft).toBe("Nachricht 17");
expect(JSON.parse(storage.getItem(PENDING_STORAGE_KEY) ?? "{}").pending).toHaveLength(16);
expect(sendMessage).toHaveBeenCalledTimes(16);
first.unmount();
renderHook(() => useChatDraft({ storageKey: STORAGE_KEY, deliveries: [], sendMessage, updateTyping: vi.fn(), storage }));
expect(sendMessage).toHaveBeenCalledTimes(32);
expect(JSON.parse(storage.getItem(PENDING_STORAGE_KEY) ?? "{}").pending).toHaveLength(16);
});
it("restores a failed send across remounts and clears that restoration after acknowledgement", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const input = () => ({
storageKey: STORAGE_KEY,
deliveries,
sendMessage: () => ({ clientMessageId: "client_1", requestId: "request_1" }),
updateTyping: vi.fn(),
storage,
});
const first = renderHook(() => useChatDraft(input()));
act(() => first.result.current.updateDraft("Erneut versuchen"));
act(() => {
expect(first.result.current.sendDraft("Erneut versuchen")).toBe(true);
});
first.unmount();
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.realtimeUnavailable",
retryable: true,
},
];
const failed = renderHook(() => useChatDraft(input()));
expect(failed.result.current.draft).toBe("Erneut versuchen");
expect(storage.getItem(STORAGE_KEY)).toBe("Erneut versuchen");
failed.unmount();
const restored = renderHook(() => useChatDraft(input()));
expect(restored.result.current.draft).toBe("Erneut versuchen");
deliveries = [{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false }];
restored.rerender();
expect(restored.result.current.draft).toBe("");
expect(storage.getItem(STORAGE_KEY)).toBeNull();
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
it("does not restore or clear a newer persisted draft when an older send settles", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const input = () => ({
storageKey: STORAGE_KEY,
deliveries,
sendMessage: () => ({ clientMessageId: "client_1", requestId: "request_1" }),
updateTyping: vi.fn(),
storage,
});
const first = renderHook(() =>
useChatDraft({
...input(),
})
);
act(() => first.result.current.updateDraft("Erste Nachricht"));
act(() => {
first.result.current.sendDraft("Erste Nachricht");
first.result.current.updateDraft("Nächster Entwurf");
});
first.unmount();
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.realtimeUnavailable",
retryable: true,
},
];
const remounted = renderHook(() => useChatDraft(input()));
expect(remounted.result.current.draft).toBe("Nächster Entwurf");
deliveries = [{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false }];
remounted.rerender();
expect(remounted.result.current.draft).toBe("Nächster Entwurf");
expect(storage.getItem(STORAGE_KEY)).toBe("Nächster Entwurf");
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
it.each([
["invalid JSON", "{not-json"],
[
"an oversized pending body",
JSON.stringify({
version: 2,
revision: 0,
pending: [
{
body: "x".repeat(8_001),
clientMessageId: "client_1",
createdAt: Date.now(),
failureObserved: false,
restored: false,
revision: 0,
},
],
}),
],
])("ignores %s without hiding a legacy plain-text draft", (_label, corruptMetadata) => {
const storage = createMemoryStorage();
storage.setItem(STORAGE_KEY, "Legacy-Entwurf");
storage.setItem(PENDING_STORAGE_KEY, corruptMetadata);
const { result } = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries: [],
sendMessage: () => null,
updateTyping: vi.fn(),
storage,
})
);
expect(result.current.draft).toBe("Legacy-Entwurf");
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
});
function createMemoryStorage(): ChatDraftStorage {
const values = new Map<string, string>();
return {
getItem: (key) => values.get(key) ?? null,
setItem: (key, value) => {
values.set(key, value);
},
removeItem: (key) => {
values.delete(key);
},
};
}
@@ -0,0 +1,494 @@
import { useCallback, useEffect, useRef, useState } from "react";
export type ChatDraftDelivery = {
readonly clientMessageId: string;
readonly isCurrentUser: boolean;
readonly deliveryState: "sending" | "sent" | "failed";
readonly failureReasonKey: string | null;
readonly retryable: boolean;
};
export type ChatDraftStorage = Pick<Storage, "getItem" | "setItem" | "removeItem">;
export type UseChatDraftInput = {
readonly storageKey: string | null;
readonly deliveries: readonly ChatDraftDelivery[];
readonly sendMessage: (body: string, clientMessageId?: string, requestId?: string) => { readonly clientMessageId: string; readonly requestId: string } | null;
readonly restoreFailedMessage?: (
body: string,
clientMessageId: string,
requestId: string,
failureReasonKey: string,
retryable: boolean,
createdAt: number
) => { readonly clientMessageId: string; readonly requestId: string } | null;
readonly retryMessage?: (clientMessageId: string) => { readonly clientMessageId: string; readonly requestId: string } | null;
readonly updateTyping: (body: string) => void;
readonly storage?: ChatDraftStorage | null;
readonly debounceMs?: number;
};
export type UseChatDraftResult = {
readonly draft: string;
readonly loaded: boolean;
readonly updateDraft: (body: string) => void;
readonly sendDraft: (body: string) => boolean;
readonly discardPendingDraft: (clientMessageId: string) => void;
};
type PendingDraft = {
readonly body: string;
readonly requestId: string;
readonly revision: number;
readonly storageKey: string;
readonly createdAt: number;
failureObserved: boolean;
failureReasonKey: string | null;
retryable: boolean;
restored: boolean;
};
type PendingSave = {
readonly handle: ReturnType<typeof setTimeout>;
readonly storage: ChatDraftStorage | null;
readonly storageKey: string;
readonly body: string;
};
const DEFAULT_DEBOUNCE_MS = 300;
const PENDING_STORAGE_SUFFIX = ":pending";
const PENDING_STORAGE_VERSION = 2;
const MAX_DRAFT_LENGTH = 8_000;
const MAX_CLIENT_MESSAGE_ID_LENGTH = 256;
const MAX_REQUEST_ID_LENGTH = 128;
const MAX_FAILURE_REASON_KEY_LENGTH = 256;
const MAX_PENDING_DRAFTS = 16;
const MAX_PENDING_STORAGE_LENGTH = 150_000;
const MAX_PENDING_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
type PersistedPendingDraft = {
readonly body: string;
readonly clientMessageId: string;
readonly requestId: string;
readonly createdAt: number;
readonly failureObserved: boolean;
readonly failureReasonKey: string | null;
readonly retryable: boolean;
readonly restored: boolean;
readonly revision: number;
};
type PersistedDraftState = {
readonly version: typeof PENDING_STORAGE_VERSION;
readonly revision: number;
readonly pending: readonly PersistedPendingDraft[];
};
/** Keeps the visible composer responsive while persisting drafts and accepted
* sends separately until their local echoes settle. */
export function useChatDraft(input: UseChatDraftInput): UseChatDraftResult {
const [draft, setDraft] = useState("");
const [loaded, setLoaded] = useState(false);
const draftRef = useRef("");
const revisionRef = useRef(0);
const pendingRef = useRef(new Map<string, PendingDraft>());
const pendingSaveRef = useRef<PendingSave | null>(null);
const inputRef = useRef(input);
inputRef.current = input;
const setDraftValue = useCallback((value: string) => {
draftRef.current = value;
setDraft(value);
}, []);
const clearPendingSave = useCallback((persist: boolean) => {
const pending = pendingSaveRef.current;
if (!pending) return;
clearTimeout(pending.handle);
pendingSaveRef.current = null;
if (persist) writeDraft(pending.storage, pending.storageKey, pending.body);
}, []);
useEffect(() => {
clearPendingSave(true);
pendingRef.current.clear();
setLoaded(false);
const storageKey = input.storageKey;
if (!storageKey) {
revisionRef.current = 0;
setDraftValue("");
setLoaded(true);
return () => clearPendingSave(true);
}
const storage = resolveStorage(input.storage);
const persisted = readPendingState(storage, storageKey);
revisionRef.current = persisted.revision;
for (const pending of persisted.pending) {
pendingRef.current.set(pending.clientMessageId, { ...pending, storageKey });
}
const rehydratedClientMessageIds = rehydratePendingMessages(
persisted,
inputRef.current.deliveries,
inputRef.current.sendMessage,
inputRef.current.restoreFailedMessage
);
let storedDraft = readDraft(storage, storageKey);
const restored = findRecoverableDraft(persisted, inputRef.current.deliveries, rehydratedClientMessageIds);
if (!storedDraft && restored) {
const pending = pendingRef.current.get(restored.clientMessageId);
if (pending && !pending.restored) {
pending.failureObserved = true;
pending.restored = true;
persistPendingState(storage, storageKey, persisted.revision, pendingRef.current);
}
storedDraft = restored.body;
writeDraft(storage, storageKey, storedDraft);
} else if (storedDraft && isStaleSentDraft(storedDraft, persisted)) {
storedDraft = "";
writeDraft(storage, storageKey, "");
}
setDraftValue(storedDraft);
setLoaded(true);
return () => clearPendingSave(true);
}, [clearPendingSave, input.storage, input.storageKey, setDraftValue]);
useEffect(() => {
for (const [clientMessageId, pending] of pendingRef.current) {
const delivery = input.deliveries.find((candidate) => candidate.isCurrentUser && candidate.clientMessageId === clientMessageId);
if (!delivery) continue;
if (delivery.deliveryState === "sending") {
if (!pending.failureObserved) continue;
const clearRestoredDraft = pending.restored && revisionRef.current === pending.revision && draftRef.current === pending.body;
pending.failureObserved = false;
pending.failureReasonKey = null;
pending.retryable = false;
pending.restored = false;
if (clearRestoredDraft) {
setDraftValue("");
writeDraft(resolveStorage(inputRef.current.storage), pending.storageKey, "");
}
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
continue;
}
if (delivery.deliveryState === "failed") {
if (pending.failureObserved) continue;
pending.failureObserved = true;
pending.failureReasonKey = delivery.failureReasonKey;
pending.retryable = delivery.retryable;
if (delivery.retryable && revisionRef.current === pending.revision && draftRef.current.length === 0) {
pending.restored = true;
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
setDraftValue(pending.body);
writeDraft(resolveStorage(inputRef.current.storage), pending.storageKey, pending.body);
} else {
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
}
continue;
}
if (delivery.deliveryState !== "sent") continue;
if (pending.restored && revisionRef.current === pending.revision && draftRef.current === pending.body) {
setDraftValue("");
writeDraft(resolveStorage(inputRef.current.storage), pending.storageKey, "");
}
pendingRef.current.delete(clientMessageId);
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
}
}, [input.deliveries, setDraftValue]);
const updateDraft = useCallback(
(body: string) => {
revisionRef.current += 1;
setDraftValue(body);
inputRef.current.updateTyping(body);
clearPendingSave(false);
const storageKey = inputRef.current.storageKey;
if (!storageKey) return;
const delay = normalizeDebounce(inputRef.current.debounceMs);
const storage = resolveStorage(inputRef.current.storage);
persistPendingState(storage, storageKey, revisionRef.current, pendingRef.current);
const handle = setTimeout(() => {
const pending = pendingSaveRef.current;
if (!pending || pending.handle !== handle) return;
pendingSaveRef.current = null;
writeDraft(pending.storage, pending.storageKey, pending.body);
}, delay);
pendingSaveRef.current = { handle, storage, storageKey, body };
},
[clearPendingSave, setDraftValue]
);
const sendDraft = useCallback(
(body: string): boolean => {
const storageKey = inputRef.current.storageKey;
if (!storageKey) return false;
clearPendingSave(false);
writeDraft(resolveStorage(inputRef.current.storage), storageKey, body);
const restored = findPendingRetry(pendingRef.current, revisionRef.current, body);
if (!restored && pendingRef.current.size >= MAX_PENDING_DRAFTS) return false;
const failedInCurrentClient =
restored !== null &&
inputRef.current.deliveries.some(
(delivery) => delivery.isCurrentUser && delivery.clientMessageId === restored.clientMessageId && delivery.deliveryState === "failed"
);
const echo = failedInCurrentClient
? (inputRef.current.retryMessage?.(restored.clientMessageId) ?? null)
: inputRef.current.sendMessage(body, restored?.clientMessageId, restored?.requestId);
if (!echo) return false;
const storage = resolveStorage(inputRef.current.storage);
if (isValidClientMessageId(echo.clientMessageId) && isValidDraft(body)) {
pendingRef.current.set(echo.clientMessageId, {
body,
requestId: echo.requestId,
revision: revisionRef.current,
storageKey,
createdAt: Date.now(),
failureObserved: false,
failureReasonKey: null,
retryable: false,
restored: false,
});
persistPendingState(storage, storageKey, revisionRef.current, pendingRef.current);
}
setDraftValue("");
writeDraft(storage, storageKey, "");
return true;
},
[clearPendingSave, setDraftValue]
);
const discardPendingDraft = useCallback((clientMessageId: string) => {
const pending = pendingRef.current.get(clientMessageId);
if (!pending) return;
pendingRef.current.delete(clientMessageId);
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
}, []);
return { draft, loaded, updateDraft, sendDraft, discardPendingDraft };
}
function resolveStorage(storage: ChatDraftStorage | null | undefined): ChatDraftStorage | null {
if (storage !== undefined) return storage;
return typeof window === "undefined" ? null : window.localStorage;
}
function readDraft(storage: ChatDraftStorage | null, storageKey: string): string {
try {
const draft = storage?.getItem(storageKey) ?? "";
if (isValidDraft(draft)) return draft;
storage?.removeItem(storageKey);
return "";
} catch {
return "";
}
}
function writeDraft(storage: ChatDraftStorage | null, storageKey: string, draft: string): void {
try {
if (draft && isValidDraft(draft)) storage?.setItem(storageKey, draft);
else storage?.removeItem(storageKey);
} catch {
// Local persistence must never block delivery or composer input.
}
}
function normalizeDebounce(value: number | undefined): number {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : DEFAULT_DEBOUNCE_MS;
}
function pendingStorageKey(storageKey: string): string {
return `${storageKey}${PENDING_STORAGE_SUFFIX}`;
}
function readPendingState(storage: ChatDraftStorage | null, storageKey: string): PersistedDraftState {
const empty = emptyPendingState();
try {
const key = pendingStorageKey(storageKey);
const raw = storage?.getItem(key);
if (!raw) return empty;
if (raw.length > MAX_PENDING_STORAGE_LENGTH) {
storage?.removeItem(key);
return empty;
}
const parsed: unknown = JSON.parse(raw);
if (!isRecord(parsed) || parsed.version !== PENDING_STORAGE_VERSION || !isRevision(parsed.revision) || !Array.isArray(parsed.pending)) {
storage?.removeItem(key);
return empty;
}
const now = Date.now();
const pending: PersistedPendingDraft[] = [];
const seen = new Set<string>();
for (const candidate of parsed.pending) {
const normalized = normalizePersistedPending(candidate, parsed.revision, now);
if (!normalized || seen.has(normalized.clientMessageId)) continue;
seen.add(normalized.clientMessageId);
pending.push(normalized);
}
pending.sort((left, right) => left.createdAt - right.createdAt);
const bounded = pending.slice(-MAX_PENDING_DRAFTS);
const state: PersistedDraftState = { version: PENDING_STORAGE_VERSION, revision: parsed.revision, pending: bounded };
if (bounded.length === 0 || bounded.length !== parsed.pending.length) {
persistPendingState(storage, storageKey, state.revision, toPendingMap(state, storageKey));
}
return state;
} catch {
try {
storage?.removeItem(pendingStorageKey(storageKey));
} catch {
// Corrupt or inaccessible local persistence must not block the composer.
}
return empty;
}
}
function persistPendingState(storage: ChatDraftStorage | null, storageKey: string, revision: number, pendingDrafts: ReadonlyMap<string, PendingDraft>): void {
try {
const key = pendingStorageKey(storageKey);
const pending = [...pendingDrafts.entries()]
.filter(([, candidate]) => candidate.storageKey === storageKey)
.sort(([, left], [, right]) => left.createdAt - right.createdAt)
.slice(-MAX_PENDING_DRAFTS)
.map(([clientMessageId, candidate]) => ({
body: candidate.body,
clientMessageId,
requestId: candidate.requestId,
createdAt: candidate.createdAt,
failureObserved: candidate.failureObserved,
failureReasonKey: candidate.failureReasonKey,
retryable: candidate.retryable,
restored: candidate.restored,
revision: candidate.revision,
}));
if (pending.length === 0) {
storage?.removeItem(key);
return;
}
const serialized = JSON.stringify({ version: PENDING_STORAGE_VERSION, revision, pending } satisfies PersistedDraftState);
if (serialized.length <= MAX_PENDING_STORAGE_LENGTH) storage?.setItem(key, serialized);
else storage?.removeItem(key);
} catch {
// Local persistence must never block delivery or composer input.
}
}
function normalizePersistedPending(candidate: unknown, currentRevision: number, now: number): PersistedPendingDraft | null {
if (!isRecord(candidate)) return null;
if (!isValidClientMessageId(candidate.clientMessageId) || !isValidDraft(candidate.body)) return null;
if (!isValidRequestId(candidate.requestId)) return null;
if (!isRevision(candidate.revision) || candidate.revision > currentRevision) return null;
if (!isTimestamp(candidate.createdAt, now)) return null;
if (typeof candidate.failureObserved !== "boolean" || typeof candidate.restored !== "boolean") return null;
if (candidate.failureReasonKey !== null && !isValidFailureReasonKey(candidate.failureReasonKey)) return null;
if (typeof candidate.retryable !== "boolean") return null;
if (!candidate.failureObserved && (candidate.failureReasonKey !== null || candidate.retryable)) return null;
if (candidate.restored && !candidate.failureObserved) return null;
return {
body: candidate.body,
clientMessageId: candidate.clientMessageId,
requestId: candidate.requestId,
createdAt: candidate.createdAt,
failureObserved: candidate.failureObserved,
failureReasonKey: candidate.failureReasonKey,
retryable: candidate.retryable,
restored: candidate.restored,
revision: candidate.revision,
};
}
function emptyPendingState(): PersistedDraftState {
return { version: PENDING_STORAGE_VERSION, revision: 0, pending: [] };
}
function rehydratePendingMessages(
state: PersistedDraftState,
deliveries: readonly ChatDraftDelivery[],
sendMessage: UseChatDraftInput["sendMessage"],
restoreFailedMessage: UseChatDraftInput["restoreFailedMessage"]
): ReadonlySet<string> {
const rehydrated = new Set<string>();
for (const pending of state.pending) {
const alreadyVisible = deliveries.some((delivery) => delivery.isCurrentUser && delivery.clientMessageId === pending.clientMessageId);
if (alreadyVisible) continue;
const echo = pending.failureObserved
? (restoreFailedMessage?.(
pending.body,
pending.clientMessageId,
pending.requestId,
pending.failureReasonKey ?? "chat.message.sendFailed",
pending.retryable,
pending.createdAt
) ?? null)
: sendMessage(pending.body, pending.clientMessageId, pending.requestId);
if (echo?.clientMessageId === pending.clientMessageId && echo.requestId === pending.requestId) {
rehydrated.add(pending.clientMessageId);
}
}
return rehydrated;
}
function findRecoverableDraft(
state: PersistedDraftState,
deliveries: readonly ChatDraftDelivery[],
rehydratedClientMessageIds: ReadonlySet<string>
): PersistedPendingDraft | null {
return (
[...state.pending]
.reverse()
.find(
(pending) =>
!rehydratedClientMessageIds.has(pending.clientMessageId) &&
pending.revision === state.revision &&
(pending.restored || !deliveries.some((delivery) => delivery.isCurrentUser && delivery.clientMessageId === pending.clientMessageId))
) ?? null
);
}
function findPendingRetry(
pendingDrafts: ReadonlyMap<string, PendingDraft>,
revision: number,
body: string
): { readonly clientMessageId: string; readonly requestId: string } | null {
const match = [...pendingDrafts.entries()].reverse().find(([, pending]) => pending.restored && pending.revision === revision && pending.body === body);
return match ? { clientMessageId: match[0], requestId: match[1].requestId } : null;
}
function isStaleSentDraft(draft: string, state: PersistedDraftState): boolean {
return state.pending.some((pending) => !pending.restored && pending.revision === state.revision && pending.body === draft);
}
function toPendingMap(state: PersistedDraftState, storageKey: string): Map<string, PendingDraft> {
return new Map(state.pending.map((pending) => [pending.clientMessageId, { ...pending, storageKey }]));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isRevision(value: unknown): value is number {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
}
function isTimestamp(value: unknown, now: number): value is number {
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value <= now && value >= now - MAX_PENDING_AGE_MS;
}
function isValidClientMessageId(value: unknown): value is string {
return typeof value === "string" && value.length > 0 && value.length <= MAX_CLIENT_MESSAGE_ID_LENGTH;
}
function isValidRequestId(value: unknown): value is string {
return typeof value === "string" && value.length > 0 && value.length <= MAX_REQUEST_ID_LENGTH && /^[A-Za-z0-9][A-Za-z0-9._:~-]*$/.test(value);
}
function isValidFailureReasonKey(value: unknown): value is string {
return typeof value === "string" && value.length > 0 && value.length <= MAX_FAILURE_REASON_KEY_LENGTH;
}
function isValidDraft(value: unknown): value is string {
return typeof value === "string" && value.length <= MAX_DRAFT_LENGTH;
}
@@ -0,0 +1,267 @@
// @vitest-environment jsdom
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type ChatViewportMessage, useChatMessageViewport } from "./useChatMessageViewport";
type ScrollMetrics = {
scrollTop: number;
scrollHeight: number;
clientHeight: number;
};
type ViewportHarness = {
readonly logRoot: HTMLDivElement;
readonly main: HTMLElement;
readonly metrics: ScrollMetrics;
readonly scrollTo: ReturnType<typeof vi.fn>;
readonly dispatchScroll: () => void;
};
const remoteMessage = (key: string): ChatViewportMessage => ({ key, isCurrentUser: false });
const ownMessage = (key: string): ChatViewportMessage => ({ key, isCurrentUser: true });
beforeEach(() => {
sessionStorage.clear();
vi.stubGlobal(
"matchMedia",
vi.fn(() => ({
matches: false,
media: "(prefers-reduced-motion: reduce)",
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
);
});
afterEach(() => {
document.body.replaceChildren();
vi.unstubAllGlobals();
});
describe("useChatMessageViewport", () => {
it("places the initial message log at the document end without animation", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
const { result } = renderHook(() => useChatMessageViewport({ messages: [remoteMessage("message_1")] }));
act(() => result.current.logRootRef(harness.logRoot));
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 700, behavior: "auto" });
expect(harness.metrics.scrollTop).toBe(700);
expect(result.current.latestRemoteAnnouncementKey).toBeNull();
expect(result.current.newMessageCount).toBe(0);
});
it("restores and persists a tenant-user-channel scroll position", () => {
const storageKey = "hivegrid:chat:scroll:v1:demo:user-1:chat-1";
sessionStorage.setItem(storageKey, JSON.stringify({ scrollTop: 240, nearBottom: false }));
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
const { result, unmount } = renderHook(() => useChatMessageViewport({ messages: [remoteMessage("message_1")], storageKey }));
act(() => result.current.logRootRef(harness.logRoot));
expect(harness.scrollTo).not.toHaveBeenCalled();
expect(harness.metrics.scrollTop).toBe(240);
act(() => {
harness.metrics.scrollTop = 320;
harness.dispatchScroll();
});
unmount();
expect(JSON.parse(sessionStorage.getItem(storageKey) ?? "null")).toEqual({ scrollTop: 320, nearBottom: false });
});
it("announces the first remote message that arrives after an initially empty channel", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 300, clientHeight: 300 });
let messages: readonly ChatViewportMessage[] = [];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
harness.metrics.scrollHeight = 400;
messages = [remoteMessage("message_remote")];
rerender();
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 100, behavior: "smooth" });
expect(result.current.latestRemoteAnnouncementKey).toBe("message_remote");
harness.metrics.scrollHeight = 500;
messages = [...messages, ownMessage("message_own")];
rerender();
expect(result.current.latestRemoteAnnouncementKey).toBeNull();
});
it("preserves the visual anchor when older messages are prepended", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
let messages = [remoteMessage("message_2"), remoteMessage("message_3")];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 200;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_400;
messages = [remoteMessage("message_1"), ...messages];
rerender();
expect(harness.metrics.scrollTop).toBe(600);
expect(harness.scrollTo).not.toHaveBeenCalled();
});
it("auto-scrolls a remote append only when the viewport was near the end", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
let messages = [remoteMessage("message_1")];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 695;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_100;
messages = [...messages, remoteMessage("message_2")];
rerender();
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 800, behavior: "smooth" });
expect(result.current.latestRemoteAnnouncementKey).toBe("message_2");
expect(result.current.newMessageCount).toBe(0);
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 100;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_200;
messages = [...messages, remoteMessage("message_3")];
rerender();
expect(harness.scrollTo).not.toHaveBeenCalled();
expect(result.current.latestRemoteAnnouncementKey).toBeNull();
expect(result.current.newMessageCount).toBe(1);
});
it("always follows an appended local echo and clears a pending remote count", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
let messages = [remoteMessage("message_1")];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 100;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_100;
messages = [...messages, remoteMessage("message_2")];
rerender();
expect(result.current.newMessageCount).toBe(1);
harness.metrics.scrollHeight = 1_200;
messages = [...messages, ownMessage("local_echo_1")];
rerender();
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 900, behavior: "smooth" });
expect(result.current.latestRemoteAnnouncementKey).toBeNull();
expect(result.current.newMessageCount).toBe(0);
});
it("jumps to pending messages and also clears their count after a manual scroll to the end", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
let messages = [remoteMessage("message_1")];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 100;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_100;
messages = [...messages, remoteMessage("message_2")];
rerender();
expect(result.current.newMessageCount).toBe(1);
act(() => result.current.jumpToLatest());
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 800, behavior: "smooth" });
expect(result.current.newMessageCount).toBe(0);
act(() => {
harness.metrics.scrollTop = 100;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_200;
messages = [...messages, remoteMessage("message_3")];
rerender();
expect(result.current.newMessageCount).toBe(1);
act(() => {
harness.metrics.scrollTop = 900;
harness.dispatchScroll();
});
expect(result.current.newMessageCount).toBe(0);
});
it("uses immediate scrolling when reduced motion is requested", () => {
vi.stubGlobal(
"matchMedia",
vi.fn(() => ({
matches: true,
media: "(prefers-reduced-motion: reduce)",
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
);
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
const { result } = renderHook(() => useChatMessageViewport({ messages: [remoteMessage("message_1")] }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => result.current.jumpToLatest());
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 700, behavior: "auto" });
});
});
function createViewportHarness(initialMetrics: ScrollMetrics): ViewportHarness {
const main = document.createElement("main");
const logRoot = document.createElement("div");
const metrics = { ...initialMetrics };
const scrollTo = vi.fn((options: ScrollToOptions) => {
if (typeof options.top === "number") metrics.scrollTop = options.top;
});
Object.defineProperties(main, {
scrollTop: {
configurable: true,
get: () => metrics.scrollTop,
set: (value: number) => {
metrics.scrollTop = value;
},
},
scrollHeight: { configurable: true, get: () => metrics.scrollHeight },
clientHeight: { configurable: true, get: () => metrics.clientHeight },
scrollTo: { configurable: true, value: scrollTo },
});
main.append(logRoot);
document.body.append(main);
return {
logRoot,
main,
metrics,
scrollTo,
dispatchScroll: () => main.dispatchEvent(new Event("scroll")),
};
}
@@ -0,0 +1,218 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
export type ChatViewportMessage = {
readonly key: string;
readonly isCurrentUser: boolean;
};
export type UseChatMessageViewportInput = {
readonly messages: readonly ChatViewportMessage[];
readonly nearBottomThresholdPx?: number;
readonly storageKey?: string;
};
export type UseChatMessageViewportResult = {
readonly logRootRef: (node: HTMLElement | null) => void;
readonly latestRemoteAnnouncementKey: string | null;
readonly newMessageCount: number;
readonly jumpToLatest: () => void;
};
type ViewportSnapshot = {
readonly container: HTMLElement;
readonly keys: readonly string[];
readonly scrollHeight: number;
readonly scrollTop: number;
readonly nearBottom: boolean;
};
const DEFAULT_NEAR_BOTTOM_THRESHOLD_PX = 96;
export function useChatMessageViewport(input: UseChatMessageViewportInput): UseChatMessageViewportResult {
const [logRoot, setLogRoot] = useState<HTMLElement | null>(null);
const [latestRemoteAnnouncementKey, setLatestRemoteAnnouncementKey] = useState<string | null>(null);
const [newMessageCount, setNewMessageCount] = useState(0);
const snapshotRef = useRef<ViewportSnapshot | null>(null);
const messagesRef = useRef(input.messages);
messagesRef.current = input.messages;
const thresholdPx = normalizeThreshold(input.nearBottomThresholdPx);
const messageSignature = useMemo(
() => input.messages.map((message) => `${message.key.length}:${message.key}:${message.isCurrentUser ? "1" : "0"}`).join("|"),
[input.messages]
);
const scrollContainer = useMemo(() => resolveScrollContainer(logRoot), [logRoot]);
useLayoutEffect(() => {
if (!scrollContainer) return;
const messages = messagesRef.current;
const nextKeys = messages.map((message) => message.key);
const previousSnapshot = snapshotRef.current;
const previous = previousSnapshot?.container === scrollContainer ? previousSnapshot : null;
let commandedBottom = false;
if (!previous) {
const stored = readStoredViewport(input.storageKey);
if (stored && !stored.nearBottom) {
scrollContainer.scrollTop = Math.min(stored.scrollTop, Math.max(0, scrollContainer.scrollHeight - scrollContainer.clientHeight));
} else {
scrollToBottom(scrollContainer, "auto");
commandedBottom = true;
}
setLatestRemoteAnnouncementKey(null);
setNewMessageCount(0);
} else {
const sequenceIndex = findSequenceIndex(nextKeys, previous.keys);
if (sequenceIndex >= 0) {
const prependedCount = sequenceIndex;
const appendedMessages = messages.slice(sequenceIndex + previous.keys.length);
if (prependedCount > 0) {
const heightDelta = scrollContainer.scrollHeight - previous.scrollHeight;
scrollContainer.scrollTop = previous.scrollTop + heightDelta;
}
if (appendedMessages.length > 0) {
const ownMessageAppended = appendedMessages.some((message) => message.isCurrentUser);
const latestRemoteMessage = appendedMessages
.slice()
.reverse()
.find((message) => !message.isCurrentUser);
if (ownMessageAppended || previous.nearBottom) {
scrollToBottom(scrollContainer, preferredMotionBehavior());
commandedBottom = true;
setLatestRemoteAnnouncementKey(latestRemoteMessage?.key ?? null);
setNewMessageCount(0);
} else {
setLatestRemoteAnnouncementKey(null);
setNewMessageCount((current) => current + appendedMessages.length);
}
}
}
}
snapshotRef.current = {
container: scrollContainer,
keys: nextKeys,
scrollHeight: scrollContainer.scrollHeight,
scrollTop: scrollContainer.scrollTop,
nearBottom: commandedBottom || isNearBottom(scrollContainer, thresholdPx),
};
}, [input.storageKey, messageSignature, scrollContainer, thresholdPx]);
useEffect(() => {
if (!scrollContainer) return;
const onScroll = () => {
const nearBottom = isNearBottom(scrollContainer, thresholdPx);
const current = snapshotRef.current;
if (current) {
snapshotRef.current = {
...current,
container: scrollContainer,
scrollHeight: scrollContainer.scrollHeight,
scrollTop: scrollContainer.scrollTop,
nearBottom,
};
}
if (nearBottom) setNewMessageCount(0);
persistViewport(input.storageKey, scrollContainer.scrollTop, nearBottom);
};
scrollContainer.addEventListener("scroll", onScroll, { passive: true });
return () => {
scrollContainer.removeEventListener("scroll", onScroll);
persistViewport(input.storageKey, scrollContainer.scrollTop, isNearBottom(scrollContainer, thresholdPx));
};
}, [input.storageKey, scrollContainer, thresholdPx]);
const jumpToLatest = useCallback(() => {
const container = resolveScrollContainer(logRoot);
if (!container) return;
scrollToBottom(container, preferredMotionBehavior());
const current = snapshotRef.current;
if (current) {
snapshotRef.current = {
...current,
container,
scrollHeight: container.scrollHeight,
scrollTop: container.scrollTop,
nearBottom: true,
};
}
setNewMessageCount(0);
persistViewport(input.storageKey, container.scrollTop, true);
}, [input.storageKey, logRoot]);
return {
logRootRef: setLogRoot,
latestRemoteAnnouncementKey,
newMessageCount,
jumpToLatest,
};
}
function resolveScrollContainer(logRoot: HTMLElement | null): HTMLElement | null {
if (!logRoot) return null;
const nearestMain = logRoot.closest("main");
if (nearestMain instanceof HTMLElement) return nearestMain;
if (typeof document === "undefined") return null;
return document.scrollingElement instanceof HTMLElement ? document.scrollingElement : null;
}
function scrollToBottom(container: HTMLElement, behavior: ScrollBehavior): void {
const top = Math.max(0, container.scrollHeight - container.clientHeight);
if (typeof container.scrollTo === "function") {
container.scrollTo({ top, behavior });
return;
}
container.scrollTop = top;
}
function isNearBottom(container: HTMLElement, thresholdPx: number): boolean {
return container.scrollHeight - container.clientHeight - container.scrollTop <= thresholdPx;
}
function findSequenceIndex(nextKeys: readonly string[], previousKeys: readonly string[]): number {
if (previousKeys.length === 0) return 0;
const lastStart = nextKeys.length - previousKeys.length;
for (let start = 0; start <= lastStart; start += 1) {
let matches = true;
for (let offset = 0; offset < previousKeys.length; offset += 1) {
if (nextKeys[start + offset] !== previousKeys[offset]) {
matches = false;
break;
}
}
if (matches) return start;
}
return -1;
}
function preferredMotionBehavior(): ScrollBehavior {
if (typeof matchMedia !== "function") return "smooth";
return matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth";
}
function normalizeThreshold(value: number | undefined): number {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : DEFAULT_NEAR_BOTTOM_THRESHOLD_PX;
}
type StoredViewport = Readonly<{ scrollTop: number; nearBottom: boolean }>;
function readStoredViewport(storageKey: string | undefined): StoredViewport | null {
if (!storageKey || typeof sessionStorage === "undefined") return null;
try {
const parsed = JSON.parse(sessionStorage.getItem(storageKey) ?? "null") as Partial<StoredViewport> | null;
if (!parsed || typeof parsed.scrollTop !== "number" || !Number.isFinite(parsed.scrollTop) || typeof parsed.nearBottom !== "boolean") {
return null;
}
return { scrollTop: Math.max(0, parsed.scrollTop), nearBottom: parsed.nearBottom };
} catch {
return null;
}
}
function persistViewport(storageKey: string | undefined, scrollTop: number, nearBottom: boolean): void {
if (!storageKey || typeof sessionStorage === "undefined") return;
try {
sessionStorage.setItem(storageKey, JSON.stringify({ scrollTop: Math.max(0, scrollTop), nearBottom } satisfies StoredViewport));
} catch {
// Private mode or a full storage quota must never break chat scrolling.
}
}
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { buildChatMessageDiscoveryVM } from "@hivegrid/view-models";
import { mergeChatMessageDiscoveryPages } from "./ChatMessageDiscoveryRouteView";
const hrefs = { chat: "/demo/chat", search: "/demo/chat/search", mentions: "/demo/chat/mentions" } as const;
function row(id: string) {
return {
id,
chatId: "chat_1",
channelKind: "group" as const,
channelTitle: "Montage",
authorLabel: "Ada Lovelace",
authorAvatar: { imageUrl: null, fallbackLabel: "AL" },
body: `Message ${id}`,
createdAtIso: "2026-07-16T11:00:00.000Z",
detailHref: `/demo/chat/chat_1?message=${id}`,
isThreadReply: false,
};
}
describe("chat message discovery pagination", () => {
it("appends cursor pages once and keeps the incoming next cursor", () => {
const first = buildChatMessageDiscoveryVM({ mode: "search", query: "heat", rows: [row("m2")], nextCursor: "cursor_2", hrefs });
const second = buildChatMessageDiscoveryVM({
mode: "search",
query: "heat",
rows: [row("m2"), row("m1")],
nextCursor: null,
hrefs,
});
const merged = mergeChatMessageDiscoveryPages(first, second);
expect(merged.status === "ready" && merged.data.rows.map(({ id }) => id)).toEqual(["m2", "m1"]);
expect(merged.status === "ready" && merged.data.nextCursor).toBeNull();
});
it("does not mix pages from different queries", () => {
const first = buildChatMessageDiscoveryVM({ mode: "search", query: "heat", rows: [row("m2")], hrefs });
const other = buildChatMessageDiscoveryVM({ mode: "search", query: "solar", rows: [row("m1")], hrefs });
expect(mergeChatMessageDiscoveryPages(first, other)).toEqual(other);
});
});
@@ -0,0 +1,108 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useFetcher, useNavigate, useRevalidator } from "react-router";
import type { ChatMessageDiscoveryData, ChatMessageDiscoveryVM } from "@hivegrid/view-models";
import { ChatMessageDiscoveryPage } from "~/components/screens/chat/ChatMessageDiscoveryPage";
import type { ChatMessageDiscoveryLoaderData } from "./chatMessageDiscoveryRouteTypes";
const QUERY_DEBOUNCE_MS = 250;
export function ChatMessageDiscoveryRouteView({ data }: { readonly data: ChatMessageDiscoveryLoaderData }) {
const navigate = useNavigate();
const revalidator = useRevalidator();
const pageFetcher = useFetcher<ChatMessageDiscoveryLoaderData>();
const requestedCursor = useRef<string | null>(null);
const queryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const [display, setDisplay] = useState<{ readonly source: ChatMessageDiscoveryVM; readonly vm: ChatMessageDiscoveryVM }>({
source: data.vm,
vm: data.vm,
});
useEffect(() => {
requestedCursor.current = null;
setDisplay({ source: data.vm, vm: data.vm });
}, [data.vm]);
useEffect(() => {
if (pageFetcher.state !== "idle" || !requestedCursor.current || !pageFetcher.data) return;
const requested = requestedCursor.current;
requestedCursor.current = null;
if (pageFetcher.data.pageCursor !== requested || !sameDiscovery(data.vm, pageFetcher.data.vm)) return;
setDisplay((current) => ({ source: data.vm, vm: mergePages(current.source === data.vm ? current.vm : data.vm, pageFetcher.data!.vm) }));
}, [data.vm, pageFetcher.data, pageFetcher.state]);
useEffect(
() => () => {
if (queryTimer.current) clearTimeout(queryTimer.current);
},
[]
);
const vm = display.source === data.vm ? display.vm : data.vm;
const navigateToQuery = useCallback(
(query: string) => {
const params = new URLSearchParams();
const normalized = query.trim().slice(0, 200);
if (normalized) params.set("q", normalized);
void navigate(`${discoveryBasePath(data.vm)}${params.size ? `?${params.toString()}` : ""}`, { replace: true });
},
[data.vm, navigate]
);
return (
<ChatMessageDiscoveryPage
vm={vm}
actions={{
onBack: (href) => void navigate(href),
onSwitchMode: (href) => void navigate(href),
onOpenResult: (row) => void navigate(row.detailHref),
onQueryChange: (query) => {
setDisplay((current) => ({ source: current.source, vm: withQuery(current.source, query) }));
if (queryTimer.current) clearTimeout(queryTimer.current);
queryTimer.current = setTimeout(() => {
queryTimer.current = null;
navigateToQuery(query);
}, QUERY_DEBOUNCE_MS);
},
onLoadMore: (cursor) => {
if (pageFetcher.state !== "idle" || requestedCursor.current) return;
requestedCursor.current = cursor;
const ready = readyData(vm);
const params = new URLSearchParams({ cursor });
if (ready?.mode === "search" && ready.query) params.set("q", ready.query);
void pageFetcher.load(`${discoveryBasePath(vm)}?${params.toString()}`);
},
onRetry: () => revalidator.revalidate(),
}}
/>
);
}
export function mergeChatMessageDiscoveryPages(current: ChatMessageDiscoveryVM, incoming: ChatMessageDiscoveryVM): ChatMessageDiscoveryVM {
if (!sameDiscovery(current, incoming) || current.status !== "ready" || incoming.status !== "ready") return incoming;
const rows = new Map(current.data.rows.map((row) => [row.id, row]));
for (const row of incoming.data.rows) rows.set(row.id, row);
return { ...incoming, data: { ...incoming.data, rows: [...rows.values()] } };
}
function mergePages(current: ChatMessageDiscoveryVM, incoming: ChatMessageDiscoveryVM): ChatMessageDiscoveryVM {
return mergeChatMessageDiscoveryPages(current, incoming);
}
function sameDiscovery(left: ChatMessageDiscoveryVM, right: ChatMessageDiscoveryVM): boolean {
return left.status === "ready" && right.status === "ready" && left.data.mode === right.data.mode && left.data.query === right.data.query;
}
function withQuery(vm: ChatMessageDiscoveryVM, query: string): ChatMessageDiscoveryVM {
if (vm.status !== "ready" || vm.data.mode !== "search") return vm;
if (query === vm.data.query) return vm;
return { ...vm, data: { ...vm.data, query, rows: [], nextCursor: null } };
}
function discoveryBasePath(vm: ChatMessageDiscoveryVM): string {
const data = readyData(vm);
return data?.mode === "mentions" ? (data.hrefs.mentions) : (data?.hrefs.search ?? "");
}
function readyData(vm: ChatMessageDiscoveryVM): ChatMessageDiscoveryData | null {
return vm.status === "ready" ? vm.data : null;
}
@@ -0,0 +1,140 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { CatalogError } from "@hivegrid/foundation";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
const mocks = vi.hoisted(() => ({
requireAuth: vi.fn(),
getTenantIdFromUrl: vi.fn(),
getUserInfo: vi.fn(),
tenantHasModule: vi.fn(),
getPermissionsByUser: vi.fn(),
membership: { id: "tenant-user-1" } as { id: string } | null,
tx: {
tenantUser: {
findFirst: vi.fn(),
},
},
}));
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: (...args: unknown[]) => mocks.requireAuth(...args) }));
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args) }));
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: (...args: unknown[]) => mocks.tenantHasModule(...args) }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({ getPermissionsByUser: (...args: unknown[]) => mocks.getPermissionsByUser(...args) }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
}));
import {
chatHasPermission,
loadChatContext,
requireChatChannelAdminAccess,
requireChatChannelReadAccess,
requireChatChannelWriteAccess,
requireChatPermission,
type ChatChannelAccessSnapshot,
type ChatRouteContext,
} from "./chatAccess.server";
const activeMember: ChatChannelAccessSnapshot = {
isActiveMember: true,
isChannelAdmin: false,
isArchived: false,
};
function context(permissions: readonly string[]): ChatRouteContext {
return {
tenantId: "tenant-1",
userId: "user-1",
tenantUserId: "tenant-user-1",
permissions,
hasModule: true,
};
}
describe("chat access", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.requireAuth.mockResolvedValue(undefined);
mocks.getTenantIdFromUrl.mockResolvedValue("tenant-1");
mocks.getUserInfo.mockResolvedValue({ userId: "user-1" });
mocks.tenantHasModule.mockResolvedValue(true);
mocks.getPermissionsByUser.mockResolvedValue([CHAT_PERMISSIONS.readOwnChannels]);
mocks.tx.tenantUser.findFirst.mockImplementation(async () => mocks.membership);
mocks.membership = { id: "tenant-user-1" };
});
it("loads an authenticated, tenant-scoped module context", async () => {
const request = new Request("http://app.localhost/acme/chat");
await expect(loadChatContext({ request, params: { tenant: "acme" } })).resolves.toEqual({
tenantId: "tenant-1",
userId: "user-1",
tenantUserId: "tenant-user-1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
hasModule: true,
});
expect(mocks.tenantHasModule).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "user-1", moduleKey: "chat" });
expect(mocks.tx.tenantUser.findFirst).toHaveBeenCalledWith({
where: {
tenantId: "tenant-1",
userId: "user-1",
status: TenantUserStatus.ACTIVE,
user: { active: true },
tenant: { active: true },
},
select: { id: true },
});
});
it("fails closed when the chat module is disabled", async () => {
mocks.tenantHasModule.mockResolvedValue(false);
const request = new Request("http://app.localhost/acme/chat");
await expect(loadChatContext({ request, params: { tenant: "acme" } })).rejects.toBeInstanceOf(CatalogError);
});
it("rejects a session without an active tenant membership", async () => {
mocks.membership = null;
await expect(loadChatContext({ request: new Request("http://app.localhost/acme/chat"), params: { tenant: "acme" } })).rejects.toBeInstanceOf(CatalogError);
});
it("requires exact permissions without making chat.admin an audit capability", () => {
const admin = context([CHAT_PERMISSIONS.admin]);
expect(chatHasPermission(admin, CHAT_PERMISSIONS.admin)).toBe(true);
expect(chatHasPermission(admin, CHAT_PERMISSIONS.readAllChannels)).toBe(false);
expect(() => requireChatPermission(admin, CHAT_PERMISSIONS.readAllChannels)).toThrow(CatalogError);
});
it("allows active members to read and keeps audit reads behind the dedicated audit-session service", () => {
expect(requireChatChannelReadAccess(context([CHAT_PERMISSIONS.readOwnChannels]), activeMember)).toBe("member");
const outsider = { ...activeMember, isActiveMember: false };
expect(() => requireChatChannelReadAccess(context([CHAT_PERMISSIONS.readAllChannels]), outsider)).toThrow(CatalogError);
expect(() => requireChatChannelReadAccess(context([CHAT_PERMISSIONS.admin]), outsider)).toThrow(CatalogError);
});
it("never lets audit mode or archived membership write", () => {
const auditOnly = context([CHAT_PERMISSIONS.readAllChannels]);
expect(() => requireChatChannelWriteAccess(auditOnly, { ...activeMember, isActiveMember: false })).toThrow(CatalogError);
expect(() => requireChatChannelWriteAccess(context([CHAT_PERMISSIONS.write]), { ...activeMember, isArchived: true })).toThrow(CatalogError);
expect(requireChatChannelWriteAccess(context([CHAT_PERMISSIONS.write]), activeMember)).toMatchObject({ userId: "user-1" });
});
it("allows channel admins only as members while global chat admins override membership", () => {
expect(requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.readOwnChannels]), { ...activeMember, isChannelAdmin: true })).toMatchObject({
userId: "user-1",
});
expect(requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.admin]), activeMember)).toMatchObject({
userId: "user-1",
});
expect(
requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.admin]), {
...activeMember,
isActiveMember: false,
})
).toMatchObject({ userId: "user-1" });
expect(() => requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.readOwnChannels]), activeMember)).toThrow(CatalogError);
});
});
@@ -0,0 +1,108 @@
import { CHAT_PERMISSIONS, type ChatPermission } from "@hivegrid/chat";
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getUserInfo } from "~/utils/session.server";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { CHAT_MODULE_KEY } from "./chatRoutePaths";
export type ChatRouteContext = {
tenantId: string;
userId: string;
tenantUserId: string;
permissions: readonly string[];
hasModule: true;
};
export type ChatChannelAccessSnapshot = {
isActiveMember: boolean;
isChannelAdmin: boolean;
isArchived: boolean;
};
export type ChatChannelReadMode = "member";
export async function loadChatContext({ request, params }: { request: Request; params: Record<string, string | undefined> }): Promise<ChatRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions, membership] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: CHAT_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
withTenantRLS(tenantId, (tx) =>
tx.tenantUser.findFirst({
where: {
tenantId,
userId: userInfo.userId,
status: TenantUserStatus.ACTIVE,
user: { active: true },
tenant: { active: true },
},
select: { id: true },
})
),
]);
if (!membership || !hasModule) {
throw new CatalogError(foundationErrors.notFound, !hasModule ? { module: CHAT_MODULE_KEY } : undefined);
}
return {
tenantId,
userId: userInfo.userId,
tenantUserId: membership.id,
permissions,
hasModule: true,
};
}
export function chatHasPermission(ctx: ChatRouteContext, permission: ChatPermission): boolean {
return ctx.permissions.includes(permission);
}
export function requireChatPermission(ctx: ChatRouteContext, permission: ChatPermission): ChatRouteContext {
if (!chatHasPermission(ctx, permission)) {
throw new CatalogError(foundationErrors.notFound, { permission });
}
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
return ctx;
}
export function requireChatChannelReadAccess(ctx: ChatRouteContext, channel: ChatChannelAccessSnapshot): ChatChannelReadMode {
if (channel.isActiveMember && chatHasPermission(ctx, CHAT_PERMISSIONS.readOwnChannels)) {
return "member";
}
throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
}
export function requireChatChannelWriteAccess(ctx: ChatRouteContext, channel: ChatChannelAccessSnapshot): ChatRouteContext {
if (channel.isActiveMember && !channel.isArchived && chatHasPermission(ctx, CHAT_PERMISSIONS.write)) {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, CHAT_PERMISSIONS.write);
return ctx;
}
throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
}
export function requireChatChannelAdminAccess(ctx: ChatRouteContext, channel: ChatChannelAccessSnapshot): ChatRouteContext {
if (chatHasPermission(ctx, CHAT_PERMISSIONS.admin)) {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, CHAT_PERMISSIONS.admin);
return ctx;
}
if (channel.isActiveMember && channel.isChannelAdmin && chatHasPermission(ctx, CHAT_PERMISSIONS.readOwnChannels)) {
return ctx;
}
throw new CatalogError(foundationErrors.notFound, { chat: "not-administerable" });
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import {
chatChannelListFilterHref,
chatChannelListPageHref,
normalizeChatChannelQuery,
parseChatChannelListCursor,
parseChatChannelListFilter,
} from "./chatListFilter";
describe("chat list filter", () => {
it("parses supported filters and rejects unknown views", () => {
expect(parseChatChannelListFilter(new URL("https://app.test/demo/chat?q=%20Montage%20&view=unread&archived=1"))).toEqual({
query: "Montage",
view: "unread",
showArchived: true,
});
expect(parseChatChannelListFilter(new URL("https://app.test/demo/chat?view=admin"))).toEqual({
query: "",
view: "all",
showArchived: false,
});
});
it("serializes only non-default filter state", () => {
expect(chatChannelListFilterHref("demo", { query: "", view: "all", showArchived: false })).toBe("/demo/chat");
expect(chatChannelListFilterHref("demo", { query: "Ada", view: "direct", showArchived: true })).toBe("/demo/chat?q=Ada&view=direct&archived=1");
});
it("round-trips a page cursor while filter navigation resets it", () => {
const filter = { query: "Ada", view: "direct" as const, showArchived: true };
const href = chatChannelListPageHref("demo", filter, "cursor.page_2");
const url = new URL(href, "https://app.test");
expect(parseChatChannelListCursor(url)).toBe("cursor.page_2");
expect(chatChannelListFilterHref("demo", filter)).toBe("/demo/chat?q=Ada&view=direct&archived=1");
expect(chatChannelListFilterHref("demo", parseChatChannelListFilter(url))).not.toContain("cursor");
});
it("treats an empty page cursor as absent", () => {
expect(parseChatChannelListCursor(new URL("https://app.test/demo/chat?cursor=%20%20"))).toBeUndefined();
});
it("uses the same bounded query normalization for local and URL state", () => {
expect(normalizeChatChannelQuery(" Montage ")).toBe("Montage");
expect(normalizeChatChannelQuery("x".repeat(250))).toHaveLength(200);
});
});
@@ -0,0 +1,40 @@
import { chatChannelListViewSchema, type ChatChannelListFilterState } from "@hivegrid/view-models";
const MAX_CHANNEL_QUERY_LENGTH = 200;
const MAX_CHANNEL_CURSOR_LENGTH = 2_048;
export function parseChatChannelListFilter(url: URL): ChatChannelListFilterState {
const parsedView = chatChannelListViewSchema.safeParse(url.searchParams.get("view") ?? "all");
const showArchivedValue = url.searchParams.get("archived");
return {
query: normalizeChatChannelQuery(url.searchParams.get("q") ?? ""),
view: parsedView.success ? parsedView.data : "all",
showArchived: showArchivedValue === "1" || showArchivedValue === "true",
};
}
export function normalizeChatChannelQuery(query: string): string {
return query.trim().slice(0, MAX_CHANNEL_QUERY_LENGTH);
}
export function chatChannelListFilterHref(tenantSlug: string, filter: ChatChannelListFilterState): string {
return chatChannelListPageHref(tenantSlug, filter);
}
export function parseChatChannelListCursor(url: URL): string | undefined {
const cursor = url.searchParams.get("cursor")?.trim();
if (!cursor) return undefined;
return cursor.slice(0, MAX_CHANNEL_CURSOR_LENGTH);
}
export function chatChannelListPageHref(tenantSlug: string, filter: ChatChannelListFilterState, cursor?: string): string {
const params = new URLSearchParams();
const query = normalizeChatChannelQuery(filter.query);
if (query) params.set("q", query);
if (filter.view !== "all") params.set("view", filter.view);
if (filter.showArchived) params.set("archived", "1");
const normalizedCursor = cursor?.trim().slice(0, MAX_CHANNEL_CURSOR_LENGTH);
if (normalizedCursor) params.set("cursor", normalizedCursor);
const search = params.toString();
return `/${encodeURIComponent(tenantSlug)}/chat${search ? `?${search}` : ""}`;
}
@@ -0,0 +1,86 @@
import { buildChatChannelListVM, type ChatChannelListFilterState, type ChatChannelListRowInput } from "@hivegrid/view-models";
import { describe, expect, it } from "vitest";
import { mergeChatChannelListPages, sameChatChannelListFilter } from "./chatListPagination";
const DEFAULT_FILTER: ChatChannelListFilterState = { query: "", view: "all", showArchived: false };
function row(id: string, unreadCount: number): ChatChannelListRowInput {
return {
id,
kind: "group",
title: id,
subtitle: null,
detailHref: `/demo/chat/${id}`,
avatar: { imageUrl: null, fallbackLabel: id.slice(0, 1) },
project: null,
lastMessage: null,
typingLabels: [],
unreadCount,
hasMention: unreadCount > 1,
isPinned: false,
isPrivate: false,
notificationPreference: "all_messages",
archivedAtIso: null,
memberCount: 2,
canManage: false,
};
}
function page(rows: readonly ChatChannelListRowInput[], nextCursor: string | null, filter = DEFAULT_FILTER) {
return buildChatChannelListVM({
rows,
discoverRows: [],
filter,
permissions: {
canWrite: false,
canCreateGroup: false,
canCreateDm: false,
canDiscover: false,
canViewMentions: false,
canSearch: true,
canViewArchived: true,
canAdmin: false,
},
hrefs: {
newChannel: "/demo/chat/new",
newDm: "/demo/chat/new?kind=dm",
search: "/demo/chat/search",
mentions: "/demo/chat/mentions",
archived: "/demo/chat?archived=1",
},
totals: {
unread: rows.reduce((total, entry) => total + entry.unreadCount, 0),
mentions: rows.filter((entry) => entry.hasMention).length,
},
nextCursor,
});
}
describe("chat list pagination", () => {
it("appends in server order, refreshes duplicate boundary rows, and adopts the incoming cursor", () => {
const merged = mergeChatChannelListPages(page([row("chat_1", 1), row("chat_2", 0)], "cursor_2"), page([row("chat_2", 3), row("chat_3", 2)], null));
expect(merged.status).toBe("ready");
if (merged.status !== "ready") return;
expect(merged.data.rows.map((entry) => [entry.id, entry.unreadCount])).toEqual([
["chat_1", 1],
["chat_2", 3],
["chat_3", 2],
]);
expect(merged.data.totals).toEqual({ unread: 6, mentions: 2 });
expect(merged.data.nextCursor).toBeNull();
});
it("resets to the incoming page when the normalized server filter changes", () => {
const unreadFilter = { ...DEFAULT_FILTER, view: "unread" as const };
const reset = mergeChatChannelListPages(page([row("chat_old", 1)], "old_cursor"), page([row("chat_new", 2)], "new_cursor", unreadFilter));
expect(sameChatChannelListFilter(DEFAULT_FILTER, unreadFilter)).toBe(false);
expect(reset.status).toBe("ready");
if (reset.status !== "ready") return;
expect(reset.data.rows.map((entry) => entry.id)).toEqual(["chat_new"]);
expect(reset.data.filter).toEqual(unreadFilter);
expect(reset.data.nextCursor).toBe("new_cursor");
});
});
@@ -0,0 +1,29 @@
import type { ChatChannelListFilterState, ChatChannelListRowVM, ChatChannelListVM } from "@hivegrid/view-models";
export function sameChatChannelListFilter(left: ChatChannelListFilterState, right: ChatChannelListFilterState): boolean {
return left.query === right.query && left.view === right.view && left.showArchived === right.showArchived;
}
/** Appends one server-filtered keyset page without changing the server order.
* Repeated boundary rows are refreshed in place and never rendered twice. */
export function mergeChatChannelListPages(current: ChatChannelListVM, incoming: ChatChannelListVM): ChatChannelListVM {
if (incoming.status !== "ready") return current;
if (current.status !== "ready" || !sameChatChannelListFilter(current.data.filter, incoming.data.filter)) return incoming;
const rowsById = new Map<string, ChatChannelListRowVM>(current.data.rows.map((row) => [row.id, row]));
for (const row of incoming.data.rows) rowsById.set(row.id, row);
const rows = [...rowsById.values()];
return {
...current,
data: {
...current.data,
rows,
totals: {
unread: rows.reduce((total, row) => total + row.unreadCount, 0),
mentions: rows.filter((row) => row.hasMention).length,
},
nextCursor: incoming.data.nextCursor,
},
};
}
@@ -0,0 +1,67 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { buildChatMessageDiscoveryVM } from "@hivegrid/view-models";
const mocks = vi.hoisted(() => ({
getTranslations: vi.fn(),
loadContext: vi.fn(),
loadDiscovery: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
vi.mock("./chatAccess.server", () => ({ loadChatContext: (...args: unknown[]) => mocks.loadContext(...args) }));
vi.mock("~/modules/chat/services/ChatMessageDiscoveryService.server", () => ({
loadChatMessageDiscovery: (...args: unknown[]) => mocks.loadDiscovery(...args),
}));
import { loadChatMessageDiscoveryRoute } from "./chatMessageDiscoveryLoader.server";
const context = {
tenantId: "tenant_1",
userId: "viewer_1",
tenantUserId: "tenant_user_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
hasModule: true,
} as const;
const hrefs = { chat: "/demo/chat", search: "/demo/chat/search", mentions: "/demo/chat/mentions" } as const;
describe("chat message discovery route loader", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getTranslations.mockResolvedValue({ t: (key: string) => `t:${key}` });
mocks.loadContext.mockResolvedValue(context);
mocks.loadDiscovery.mockResolvedValue(buildChatMessageDiscoveryVM({ mode: "search", query: "heat", rows: [], hrefs }));
});
it("normalizes search query and forwards the opaque cursor", async () => {
const request = new Request("http://app.localhost:3000/demo/chat/search?q=%20heat%20&cursor=cursor_1");
const result = await loadChatMessageDiscoveryRoute({ request, params: { tenant: "demo" }, context: {} } as never, "search");
expect(mocks.loadDiscovery).toHaveBeenCalledWith({
context,
tenantSlug: "demo",
mode: "search",
query: "heat",
beforeCursor: "cursor_1",
limit: 30,
labels: {
directMessage: "t:chat.channel.fallback.directMessage",
unnamedGroup: "t:chat.channel.fallback.group",
unnamedProject: "t:chat.channel.fallback.project",
unknownUser: "t:chat.participant.unknown",
},
});
expect(result.pageCursor).toBe("cursor_1");
expect(result.title).toContain("t:chat.messageDiscovery.search.title");
});
it("keeps mentions query-free even when the URL contains q", async () => {
mocks.loadDiscovery.mockResolvedValue(buildChatMessageDiscoveryVM({ mode: "mentions", rows: [], hrefs }));
const request = new Request("http://app.localhost:3000/demo/chat/mentions?q=ignored");
await loadChatMessageDiscoveryRoute({ request, params: { tenant: "demo" }, context: {} } as never, "mentions");
expect(mocks.loadDiscovery).toHaveBeenCalledWith(expect.not.objectContaining({ query: expect.anything() }));
});
});
@@ -0,0 +1,50 @@
import type { LoaderFunctionArgs } from "react-router";
import type { ChatMessageDiscoveryMode } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { loadChatMessageDiscovery } from "~/modules/chat/services/ChatMessageDiscoveryService.server";
import { loadChatContext } from "./chatAccess.server";
import type { ChatMessageDiscoveryLoaderData } from "./chatMessageDiscoveryRouteTypes";
const PAGE_LIMIT = 30;
export async function loadChatMessageDiscoveryRoute(
args: LoaderFunctionArgs,
mode: ChatMessageDiscoveryMode
): Promise<ChatMessageDiscoveryLoaderData> {
const [{ t }, context] = await Promise.all([getTranslations(args.request), loadChatContext(args)]);
const url = new URL(args.request.url);
const tenantSlug = args.params.tenant ?? "";
const pageCursor = normalizeCursor(url.searchParams.get("cursor"));
const query = mode === "search" ? normalizeQuery(url.searchParams.get("q")) : undefined;
const vm = await loadChatMessageDiscovery({
context,
tenantSlug,
mode,
...(query !== undefined ? { query } : {}),
...(pageCursor ? { beforeCursor: pageCursor } : {}),
limit: PAGE_LIMIT,
labels: {
directMessage: t("chat.channel.fallback.directMessage"),
unnamedGroup: t("chat.channel.fallback.group"),
unnamedProject: t("chat.channel.fallback.project"),
unknownUser: t("chat.participant.unknown"),
},
});
return {
title: `${t(mode === "search" ? "chat.messageDiscovery.search.title" : "chat.messageDiscovery.mentions.title")} | ${process.env.APP_NAME}`,
tenantSlug,
pageCursor,
vm,
};
}
function normalizeQuery(value: string | null): string {
return (value ?? "").trim().slice(0, 200);
}
function normalizeCursor(value: string | null): string | null {
const normalized = value?.trim() ?? "";
return normalized ? normalized.slice(0, 2_048) : null;
}
@@ -0,0 +1,8 @@
import type { ChatMessageDiscoveryVM } from "@hivegrid/view-models";
export type ChatMessageDiscoveryLoaderData = Readonly<{
title: string;
tenantSlug: string;
pageCursor: string | null;
vm: ChatMessageDiscoveryVM;
}>;
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import {
CHAT_MODULE_KEY,
chatArchivedPath,
chatAuditAttachmentPath,
chatAuditPath,
chatChannelInfoPath,
chatChannelPath,
chatChannelSettingsPath,
chatFilesPath,
chatIndexPath,
chatMentionsPath,
chatNewPath,
chatNotFoundResponse,
chatPinnedPath,
chatSearchPath,
chatThreadPath,
} from "./chatRoutePaths";
describe("chat route paths", () => {
it("uses the canonical chat module key and tenant-scoped collection paths", () => {
expect(CHAT_MODULE_KEY).toBe("chat");
expect(chatIndexPath("acme")).toBe("/acme/chat");
expect(chatNewPath("acme")).toBe("/acme/chat/new");
expect(chatMentionsPath("acme")).toBe("/acme/chat/mentions");
expect(chatSearchPath("acme")).toBe("/acme/chat/search");
expect(chatArchivedPath("acme")).toBe("/acme/chat/archived");
});
it("builds channel, thread, pin, and file paths without changing identifiers", () => {
expect(chatChannelPath("acme", "chat_1")).toBe("/acme/chat/chat_1");
expect(chatChannelSettingsPath("acme", "chat_1")).toBe("/acme/chat/chat_1/settings");
expect(chatChannelInfoPath("acme", "chat_1")).toBe("/acme/chat/chat_1/info");
expect(chatThreadPath("acme", "chat_1", "thread_1")).toBe("/acme/chat/chat_1/thread/thread_1");
expect(chatPinnedPath("acme", "chat_1")).toBe("/acme/chat/chat_1/pinned");
expect(chatFilesPath("acme", "chat_1")).toBe("/acme/chat/chat_1/files");
});
it("uses the compliance hub for audit screens while keeping the published attachment endpoint stable", () => {
expect(chatAuditPath("acme")).toBe("/acme/settings/compliance/chat");
expect(chatAuditAttachmentPath("acme", "chat/1", "file/1", "preview")).toBe(
"/acme/settings/chat/audit/chat%2F1/attachments/file%2F1/preview"
);
});
it("provides the standard opaque not-found response", async () => {
const response = chatNotFoundResponse();
expect(response.status).toBe(404);
expect(await response.text()).toBe("Not Found");
});
});
@@ -0,0 +1,62 @@
export const CHAT_MODULE_KEY = "chat";
export function chatIndexPath(tenantSlug: string): string {
return `/${tenantSlug}/chat`;
}
export function chatNewPath(tenantSlug: string): string {
return `/${tenantSlug}/chat/new`;
}
export function chatMentionsPath(tenantSlug: string): string {
return `/${tenantSlug}/chat/mentions`;
}
export function chatSearchPath(tenantSlug: string): string {
return `/${tenantSlug}/chat/search`;
}
export function chatArchivedPath(tenantSlug: string): string {
return `/${tenantSlug}/chat/archived`;
}
export function chatChannelPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}`;
}
export function chatChannelSettingsPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}/settings`;
}
export function chatChannelInfoPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}/info`;
}
export function chatThreadPath(tenantSlug: string, chatId: string, threadId: string): string {
return `/${tenantSlug}/chat/${chatId}/thread/${threadId}`;
}
export function chatPinnedPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}/pinned`;
}
export function chatFilesPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}/files`;
}
export function chatAuditPath(tenantSlug: string): string {
return `/${tenantSlug}/settings/compliance/chat`;
}
export function chatAuditAttachmentPath(
tenantSlug: string,
chatId: string,
fileId: string,
variant: "original" | "preview"
): string {
return `/${tenantSlug}/settings/chat/audit/${encodeURIComponent(chatId)}/attachments/${encodeURIComponent(fileId)}/${variant}`;
}
export function chatNotFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
@@ -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;
}
}