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.
}
}