From 22e5bbac6fd4efa63ab020af5ef903ce73f4e5ca Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:32:30 -0400 Subject: [PATCH] feat(channel): project confirmed message reaction snapshots --- src/client/channel/conversation.ts | 6 +- src/client/channel/protocol.ts | 7 ++- src/client/channel/session.ts | 72 ++++++++++++++++++----- src/client/channel/types.ts | 1 + src/client/channel/use-channel.ts | 1 + tests/channel-conversation.test.ts | 25 ++++++-- tests/channel-session.test.ts | 94 +++++++++++++++++++++++++++--- 7 files changed, 180 insertions(+), 26 deletions(-) diff --git a/src/client/channel/conversation.ts b/src/client/channel/conversation.ts index 1f2ddca3e..18446fce4 100644 --- a/src/client/channel/conversation.ts +++ b/src/client/channel/conversation.ts @@ -39,7 +39,7 @@ export class ChannelConversation { return new TextDecoder().decode(runtime.encode_control(JSON.stringify({ kind: "file", body: JSON.parse(control) }))); } - async send(command: Extract, requestId: string): Promise { + async send(command: Extract, requestId: string): Promise { const { runtime, signer } = await this.ready(); const { state, sessionId, connected } = this.options.context(); if (!connected || !sessionId) throw new Error("disconnected"); @@ -106,6 +106,10 @@ export class ChannelConversation { } } else if (reply.record.type === "interaction") { for (const recipient of await host.currentReaders()) if (recipient !== reply.recipient) broadcasts.push({ ...reply, recipient }); + } else if (reply.record.type === "reaction_confirmed" && reply.record.changed) { + for (const recipient of await host.currentReaders()) if (recipient !== reply.recipient) { + broadcasts.push({ ...reply, recipient, record: { type: "message_reactions", snapshot: reply.record.snapshot } }); + } } } await Promise.allSettled([ diff --git a/src/client/channel/protocol.ts b/src/client/channel/protocol.ts index 2f736bbde..76b934125 100644 --- a/src/client/channel/protocol.ts +++ b/src/client/channel/protocol.ts @@ -67,7 +67,9 @@ export const eventSchema = z.discriminatedUnion("type", [ export type ChannelSnapshot = z.infer; export type ChannelPublication = z.infer; -export type ChannelMessage = z.infer; +export interface MessageReactions { revision: number; choices: Record } +export interface MessageReactionSnapshot extends MessageReactions { messageId: string; messageSeq: number } +export type ChannelMessage = z.infer & { reactions?: MessageReactions }; export type ChannelAttachment = z.infer; export type ChannelFileKey = z.infer; export type ChannelFilePlan = z.infer; @@ -81,6 +83,8 @@ export type ChannelReply = Extract | Extr export interface SignedConversationPacket { sender: string; payload: string; signature: number[]; remainingHops: number } export interface ConversationAddress { roomId: string; bindingId: string; sender: string; recipient: string; requestId: string } export type ConversationReply = ConversationAddress & { record: + | { type: "reaction_confirmed"; snapshot: MessageReactionSnapshot; changed: boolean } + | { type: "message_reactions"; snapshot: MessageReactionSnapshot } | { type: "interaction_ready"; serverTime: number; reactionIds: string[] } | { type: "interaction"; id: string; occurredAt: number; senderUserId: string; reaction: string; targetUserId?: string } | { type: "confirmed"; message: ChannelMessage; inserted: boolean } @@ -103,6 +107,7 @@ export type ChannelCommand = | { type: "browse"; roomId: string; active: boolean } | { type: "interaction_ready"; roomId: string } | { type: "interaction"; roomId: string; reaction: string; targetUserId?: string } + | { type: "set_reaction"; roomId: string; messageSeq: number; reaction: string; active: boolean } | { type: "history"; roomId: string; before?: number } | { type: "chat"; roomId: string; text: string; nonce: string; attachments: ChannelAttachment[] } | ({ type: "file_offer"; available: boolean } & ChannelFileKey) diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts index ae6523b56..373f9bb39 100644 --- a/src/client/channel/session.ts +++ b/src/client/channel/session.ts @@ -1,7 +1,7 @@ import { ChannelMedia } from "./media"; import { ChannelInput } from "./input"; import { ChannelConversation } from "./conversation"; -import { eventSchema, type ChannelCommand, type ChannelEvent, type ChannelMessage, type ChannelReply, type ChannelSnapshot, type ConversationReply, type DomainSettings, type RoomSettings } from "./protocol"; +import { eventSchema, type ChannelCommand, type ChannelEvent, type ChannelMessage, type ChannelReply, type ChannelSnapshot, type ConversationReply, type DomainSettings, type MessageReactionSnapshot, type RoomSettings } from "./protocol"; import { ChannelAttachments, type DraftFile } from "./attachments"; import type { ChannelView, ScreenPresentation } from "./types"; import { loadRoomHosting, roomDatabaseName, type HostedRoom } from "./hosting"; @@ -31,8 +31,14 @@ function stored(key: string, value?: string): string | null { } function mergeMessages(messages: ChannelMessage[]): ChannelMessage[] { - return [...new Map(messages.map(message => [message.id, message])).values()] - .sort((a, b) => a.seq - b.seq); + const merged = new Map(); + for (const message of messages) merged.set(message.id, mergeMessage(merged.get(message.id), message)); + return [...merged.values()].sort((a, b) => a.seq - b.seq); +} + +function mergeMessage(previous: ChannelMessage | undefined, message: ChannelMessage): ChannelMessage { + return previous?.reactions && (!message.reactions || previous.reactions.revision > message.reactions.revision) + ? { ...message, reactions: previous.reactions } : message; } /** The live browser endpoint owns captures and reconnects; browsing owns neither. */ @@ -58,8 +64,9 @@ export class ChannelSession { private invitedRoom = new URLSearchParams(location.hash.slice(1)).get("room") ?? undefined; private roomId: string | null = this.invitedRoom ?? null; private requests = new Map; + roomId?: string; bindingId?: string; + history?: { before?: number; entries: Map }; + pendingSend?: Extract; resolve(): void; reject(error: Error): void; result?: (event: ChannelReply) => void; timer: ReturnType; }>(); private hostedRooms = new Map(); @@ -333,7 +340,7 @@ export class ChannelSession { private async request(command: ChannelCommand, result?: (event: ChannelReply) => void, roomId = this.commandRoom(command)): Promise { const reading = this.reading; - const conversation = command.type === "chat" || command.type === "history"; + const conversation = command.type === "chat" || command.type === "history" || command.type === "set_reaction"; if (conversation && reading && reading.roomId === roomId) await reading.ready; if (this.view.connection !== "connected") return Promise.reject(new Error("disconnected")); const room = this.view.state?.channel.rooms.find(room => room.id === roomId); @@ -343,7 +350,8 @@ export class ChannelSession { return new Promise((resolve, reject) => { const timer = setTimeout(() => { this.requests.delete(requestId); reject(new Error("request_timeout")); }, 10000); this.requests.set(requestId, { resolve, reject, timer, result, roomId, - ...(conversation ? { bindingId: delivery!.bindingId, pendingSend: command, ...(command.type === "history" ? { history: [] } : {}) } : {}) }); + ...(conversation ? { bindingId: delivery!.bindingId, pendingSend: command, + ...(command.type === "history" ? { history: { before: command.before, entries: new Map() } } : {}) } : {}) }); if (conversation) this.sendConversations(); else this.write({ ...command, requestId }); }); @@ -367,6 +375,10 @@ export class ChannelSession { private receiveConversation(reply: ConversationReply): void { const record = reply.record; + if (record.type === "message_reactions" || record.type === "reaction_confirmed") { + this.applyReactionSnapshot(reply.roomId, reply.bindingId, record.snapshot); + if (record.type === "message_reactions") return; + } const interaction = this.view.interactionsByRoom.get(reply.roomId); if (interaction && this.reading?.interactionBinding === reply.bindingId) { if (record.type === "interaction_ready") { @@ -395,19 +407,23 @@ export class ChannelSession { const request = this.requests.get(reply.requestId); if (!request || request.roomId !== reply.roomId || request.bindingId !== reply.bindingId) return; if (record.type === "history_message") { - if (!request.history || request.history.length >= 100 || request.history.some(message => message.seq === record.message.seq)) { + const entries = request.history?.entries, entry = entries?.get(record.message.seq); + if (!entries || entry?.message || (!entry && entries.size >= 100) + || (entry?.snapshot && entry.snapshot.messageId !== record.message.id)) { this.receive({ type: "error", requestId: reply.requestId, code: "incomplete_history" }); return; } - request.history.push(record.message); + entries.set(record.message.seq, { ...entry, message: record.message }); return; } if (record.type === "history_end" && request.history) { - if (record.count !== request.history.length) { + const entries = [...request.history.entries.values()].filter(entry => entry.message); + if (record.count !== entries.length || entries.some(entry => !entry.snapshot)) { this.receive({ type: "error", requestId: reply.requestId, code: "incomplete_history" }); return; } - this.applyHistory(reply.roomId, request.history, record); + const page = entries.map(({ message, snapshot }) => ({ ...message!, reactions: { revision: snapshot!.revision, choices: snapshot!.choices } })); + this.applyHistory(reply.roomId, page.sort((a, b) => a.seq - b.seq), record); } else if (record.type === "confirmed") { request.result?.(record); this.applyMessage(reply.roomId, record.message); @@ -416,6 +432,27 @@ export class ChannelSession { : { type: "ack", requestId: reply.requestId }); } + private applyReactionSnapshot(roomId: string, bindingId: string, snapshot: MessageReactionSnapshot): void { + const state = this.view.state; + if (!state?.channel.rooms.some(room => room.id === roomId && room.authorized && room.delivery?.bindingId === bindingId)) return; + for (const [requestId, request] of this.requests) { + if (request.roomId !== roomId || request.bindingId !== bindingId || !request.history + || (request.history.before !== undefined && snapshot.messageSeq >= request.history.before)) continue; + const entries = request.history.entries, entry = entries.get(snapshot.messageSeq); + if ((!entry && entries.size >= 100) || (entry?.message && entry.message.id !== snapshot.messageId)) { + this.receive({ type: "error", requestId, code: "incomplete_history" }); + continue; + } + if (!entry?.snapshot || entry.snapshot.revision < snapshot.revision) entries.set(snapshot.messageSeq, { ...entry, snapshot }); + } + const messages = this.view.messagesByRoom[roomId]; + if (!messages?.some(message => message.id === snapshot.messageId && message.seq === snapshot.messageSeq + && (!message.reactions || message.reactions.revision < snapshot.revision))) return; + this.patch({ messagesByRoom: { ...this.view.messagesByRoom, [roomId]: messages.map(message => + message.id === snapshot.messageId && message.seq === snapshot.messageSeq + ? { ...message, reactions: { revision: snapshot.revision, choices: snapshot.choices } } : message) } }); + } + private applyHistory(roomId: string, page: ChannelMessage[], result: Extract): void { const state = this.view.state; if (!state?.channel.rooms.some(room => room.id === roomId && room.authorized)) return; @@ -423,7 +460,8 @@ export class ChannelSession { const last = page.at(-1)?.seq ?? 0; const latest = result.before === null; const existing = latest ? current.filter(message => message.seq > last) : current; - const merged = mergeMessages([...existing, ...page] + const projected = page.map(message => mergeMessage(current.find(previous => previous.id === message.id), message)); + const merged = mergeMessages([...existing, ...projected] .filter(message => result.oldestSeq === null || message.seq >= result.oldestSeq)); const messages = latest ? merged.slice(-state.channel.historyWindow) : merged.slice(0, state.channel.historyWindow); const atLatest = latest || ((this.view.historyByRoom[roomId]?.atLatest ?? true) && merged.length <= state.channel.historyWindow); @@ -437,8 +475,14 @@ export class ChannelSession { // A bounded historical window stays put until its reader requests latest. if (this.view.historyByRoom[roomId]?.atLatest === false) return; const messages = this.view.messagesByRoom[roomId] ?? []; + let projected: ChannelMessage = { ...message, reactions: { revision: 0, choices: {} } }; + for (const request of this.requests.values()) { + const snapshot = request.roomId === roomId ? request.history?.entries.get(message.seq)?.snapshot : undefined; + if (snapshot?.messageId === message.id) projected = mergeMessage(projected, + { ...message, reactions: { revision: snapshot.revision, choices: snapshot.choices } }); + } this.patch({ messagesByRoom: { ...this.view.messagesByRoom, - [roomId]: mergeMessages([...messages, message]).slice(-state.channel.historyWindow) } }); + [roomId]: mergeMessages([...messages, projected]).slice(-state.channel.historyWindow) } }); } private commandRoom(command: ChannelCommand): string | undefined { @@ -662,6 +706,8 @@ export class ChannelSession { this.outgoingMessages.delete(roomId); if (this.view.historyByRoom[roomId]?.atLatest === false) void this.loadLatestHistory(roomId).catch(() => {}); }); + setMessageReaction = (roomId: string, messageSeq: number, reaction: string, active: boolean): Promise => + this.action(`reaction:${roomId}:${messageSeq}`, () => this.request({ type: "set_reaction", roomId, messageSeq, reaction, active })); loadHistory = (roomId: string): Promise => this.action(`history:${roomId}`, () => this.request({ type: "history", roomId, before: this.view.historyByRoom[roomId]?.before })); loadLatestHistory = (roomId: string): Promise => this.action(`history:${roomId}`, () => this.request({ type: "history", roomId })); renameSelf = (name: string): Promise => this.action("rename", async () => { diff --git a/src/client/channel/types.ts b/src/client/channel/types.ts index 66e8afcb7..ed162d268 100644 --- a/src/client/channel/types.ts +++ b/src/client/channel/types.ts @@ -41,6 +41,7 @@ export interface ChannelActions { activateApp(): Promise; browse(roomId: string): void; sendMessage(roomId: string, text: string, attachments?: DraftFile[], signal?: AbortSignal): Promise; + setMessageReaction(roomId: string, messageSeq: number, reaction: string, active: boolean): Promise; loadHistory(roomId: string): Promise; loadLatestHistory(roomId: string): Promise; attachments: ChannelAttachments; diff --git a/src/client/channel/use-channel.ts b/src/client/channel/use-channel.ts index 234188989..2409733f5 100644 --- a/src/client/channel/use-channel.ts +++ b/src/client/channel/use-channel.ts @@ -28,6 +28,7 @@ export function useChannel(onInvitation?: (roomId: string) => void): ChannelCont return { ...view, activateApp: session.activateApp, browse: session.browse, sendMessage: session.sendMessage, renameSelf: session.renameSelf, updateDomain: session.updateDomain, + setMessageReaction: session.setMessageReaction, createRoom: session.createRoom, updateRoom: session.updateRoom, enterRoom: session.enterRoom, createRoomInvite: session.createRoomInvite, revokeRoomAccess: session.revokeRoomAccess, attachments: session.attachments, loadHistory: session.loadHistory, loadLatestHistory: session.loadLatestHistory, diff --git a/tests/channel-conversation.test.ts b/tests/channel-conversation.test.ts index fd55b9bf6..05c5a2e5b 100644 --- a/tests/channel-conversation.test.ts +++ b/tests/channel-conversation.test.ts @@ -5,14 +5,17 @@ import type { ChannelSnapshot, ConversationReply, SignedConversationPacket } fro afterEach(() => vi.restoreAllMocks()); -test("the Browser room host signs interaction fanout for its readers and keeps readiness source-only", async () => { +test("the Browser room host fans out transient interactions and changed message reactions, keeping readiness and unchanged results source-only", async () => { const state = { channel: { rooms: [{ id: "room", delivery: { bindingId: "binding", hostSessionId: "host" } }] } } as ChannelSnapshot; const sent: SignedConversationPacket[] = []; + let changed = true; const host = { currentReaders: vi.fn(() => ["source", "second", "third"]), dispatchPeer: vi.fn(async (packet: SignedConversationPacket) => { - const request = JSON.parse(packet.payload); - const record: ConversationReply["record"] = request.command.type === "interaction_ready" + const { command, ...request } = JSON.parse(packet.payload); + const record: ConversationReply["record"] = command.type === "set_reaction" + ? { type: "reaction_confirmed", changed, snapshot: { messageId: "message", messageSeq: 1, revision: 1, choices: { user: ["heart"] } } } + : command.type === "interaction_ready" ? { type: "interaction_ready", serverTime: 1000, reactionIds: ["wave"] } : { type: "interaction", id: "event", occurredAt: 1000, senderUserId: "user", reaction: "wave", targetUserId: "friend" }; return [{ ...request, sender: "host", recipient: "source", record }]; @@ -30,7 +33,7 @@ test("the Browser room host signs interaction fanout for its readers and keeps r const conversation = new ChannelConversation({ context: () => ({ sessionId: "host", state, connected: true }), host: () => host, send: async (_peer, frame, allowed) => { expect(allowed()).toBe(true); sent.push(JSON.parse(frame).body); }, file: vi.fn(), reply: vi.fn() }); await conversation.initialize(); - const receive = async (type: "interaction_ready" | "interaction") => conversation.receive("source", JSON.stringify({ kind: "conversation", body: { + const receive = async (type: "interaction_ready" | "interaction" | "set_reaction") => conversation.receive("source", JSON.stringify({ kind: "conversation", body: { sender: "source", signature: [1], remainingHops: 20, payload: JSON.stringify({ roomId: "room", bindingId: "binding", sender: "source", recipient: "host", requestId: "original-id", command: { type }, }), @@ -48,5 +51,19 @@ test("the Browser room host signs interaction fanout for its readers and keeps r } }); expect(sent.every(packet => packet.sender === "host")).toBe(true); expect(sign).toHaveBeenCalledTimes(4); + sent.length = 0; + changed = false; + await receive("set_reaction"); + expect(sent.map(packet => JSON.parse(packet.payload).record.type)).toEqual(["reaction_confirmed"]); + expect(host.currentReaders).toHaveBeenCalledTimes(1); + sent.length = 0; + changed = true; + await receive("set_reaction"); + const reactions = sent.map(packet => JSON.parse(packet.payload) as ConversationReply); + expect(reactions.find(reply => reply.recipient === "source")?.record.type).toBe("reaction_confirmed"); + expect(reactions.filter(reply => reply.record.type === "message_reactions").map(reply => reply.recipient).sort()).toEqual(["second", "third"]); + for (const reply of reactions) expect(reply).toMatchObject({ requestId: "original-id", record: { + snapshot: { messageId: "message", messageSeq: 1, revision: 1, choices: { user: ["heart"] } }, + } }); } finally { conversation.close(); } }); diff --git a/tests/channel-session.test.ts b/tests/channel-session.test.ts index 8e876248f..51500babd 100644 --- a/tests/channel-session.test.ts +++ b/tests/channel-session.test.ts @@ -8,7 +8,7 @@ import * as launchSession from "../src/client/lib/session"; import { ChannelMedia } from "../src/client/channel/media"; import { ChannelTransport } from "../src/client/channel/transport"; import { ChannelAttachments } from "../src/client/channel/attachments"; -import { identityIconSchema, snapshotSchema, signalSchema, type ChannelCommand, type ChannelMessage, type ChannelSignal, type ConversationReply } from "../src/client/channel/protocol"; +import { identityIconSchema, messageSchema, snapshotSchema, signalSchema, type ChannelCommand, type ChannelMessage, type ChannelSignal, type ConversationReply } from "../src/client/channel/protocol"; import type { ChannelScreenInput } from "../src/client/channel/types"; import { ChannelInput } from "../src/client/channel/input"; import { RemoteInputSession } from "../src/client/remote-control/input-session"; @@ -43,7 +43,7 @@ async function setup(window = 1000, read = true, hash = "", readyInteractions = vi.stubGlobal("localStorage", { getItem: () => null, setItem: () => {} }); vi.stubGlobal("WebSocket", ChannelSocket); const session = new ChannelSession(); - type PeerRequest = Extract & { requestId: string }; + type PeerRequest = Extract & { requestId: string }; type InteractionRequest = Extract & { requestId: string }; const sent: PeerRequest[] = [], pending: PeerRequest[] = []; const interactions: InteractionRequest[] = []; @@ -63,14 +63,23 @@ async function setup(window = 1000, read = true, hash = "", readyInteractions = sent, interactions, async next() { await vi.waitFor(() => expect(pending.length).toBeGreaterThan(0)); return pending.shift()!; }, reply(request: PeerRequest | InteractionRequest, record: ConversationReply["record"]) { - deliver({ roomId: request.roomId, bindingId: "binding", sender: "host", recipient: "endpoint", requestId: request.requestId, record }); + const reply = { roomId: request.roomId, bindingId: "binding", sender: "host", recipient: "endpoint", requestId: request.requestId }; + deliver({ ...reply, record: "message" in record ? { ...record, message: messageSchema.parse(record.message) } : record }); + if (record.type === "confirmed") deliver({ ...reply, record: { type: "message_reactions", snapshot: { + messageId: record.message.id, messageSeq: record.message.seq, ...(record.message.reactions ?? { revision: 0, choices: {} }), + } } }); }, page(request: PeerRequest, messages: ChannelMessage[], hasMore = false, oldestSeq: number | null = 1) { - for (const message of messages) peer.reply(request, { type: "history_message", message }); + for (const message of messages) { + peer.reply(request, { type: "history_message", message }); + peer.reply(request, { type: "message_reactions", snapshot: { + messageId: message.id, messageSeq: message.seq, ...(message.reactions ?? { revision: 0, choices: {} }), + } }); + } peer.reply(request, { type: "history_end", count: messages.length, hasMore, oldestSeq, before: "before" in request ? request.before ?? null : null }); }, live(message: ChannelMessage, roomId = "first") { - deliver({ roomId, bindingId: "binding", sender: "host", recipient: "endpoint", requestId: "live", record: { type: "live_message", message } }); + deliver({ roomId, bindingId: "binding", sender: "host", recipient: "endpoint", requestId: "live", record: { type: "live_message", message: messageSchema.parse(message) } }); }, async history(messages: ChannelMessage[], hasMore = false, older = false) { const loading = older ? session.loadHistory("first") : session.loadLatestHistory("first"); @@ -100,7 +109,72 @@ async function setup(window = 1000, read = true, hash = "", readyInteractions = return { session, socket, peer }; } -const message = (seq: number) => ({ id: `message-${seq}`, seq, userId: "self", text: `Hello ${seq}`, time: seq, attachments: [] }); +const message = (seq: number) => ({ id: `message-${seq}`, seq, userId: "self", text: `Hello ${seq}`, time: seq, attachments: [], + reactions: { revision: 0, choices: {} } }); +const reactionSnapshot = (seq: number, revision: number, choices: Record = {}) => + ({ messageId: `message-${seq}`, messageSeq: seq, revision, choices }); + +test("message reaction confirmation applies canonical snapshots and survives later body confirmation", async () => { + const { session, peer } = await setup(); + try { + await peer.history([message(1)]); + const setting = session.setMessageReaction("first", 1, "heart", true), request = await peer.next(); + expect(request).toMatchObject({ type: "set_reaction", roomId: "first", messageSeq: 1, reaction: "heart", active: true }); + expect(request).not.toHaveProperty("userId"); + expect(session.getSnapshot().pending.has("reaction:first:1")).toBe(true); + expect(session.getSnapshot().messagesByRoom.first[0].reactions).toEqual({ revision: 0, choices: {} }); + const snapshot = reactionSnapshot(1, 2, { self: ["heart"], friend: ["clap"] }); + peer.reply(request, { type: "reaction_confirmed", changed: false, snapshot }); + await setting; + expect(session.getSnapshot().messagesByRoom.first[0].reactions).toEqual({ revision: 2, choices: snapshot.choices }); + expect(session.getSnapshot().pending.has("reaction:first:1")).toBe(false); + const sending = session.sendMessage("first", message(1).text), chat = await peer.next(); + peer.reply(chat, { type: "confirmed", message: message(1), inserted: false }); + await sending; + expect(session.getSnapshot().messagesByRoom.first[0].reactions?.revision).toBe(2); + // The chat request is settled before its separately carried snapshot arrives. + peer.reply(chat, { type: "message_reactions", snapshot: reactionSnapshot(1, 3, { friend: ["clap"] }) }); + expect(session.getSnapshot().messagesByRoom.first).toEqual([{ ...message(1), reactions: { revision: 3, choices: { friend: ["clap"] } } }]); + const removing = session.setMessageReaction("first", 1, "heart", false), removal = await peer.next(); + peer.reply(removal, { type: "reaction_confirmed", changed: false, snapshot: reactionSnapshot(1, 3, { friend: ["clap"] }) }); + await removing; + expect(session.getSnapshot().messagesByRoom.first[0].reactions?.revision).toBe(3); + } finally { session.close(); } +}); + +test("history assembles early live reaction snapshots and preserves the newer projection in a historical window", async () => { + const { session, peer } = await setup(2); + try { + await peer.history([message(3), message(4)], true); + const older = session.loadHistory("first"), request = await peer.next(); + peer.reply({ ...request, requestId: "live-reaction" }, { type: "message_reactions", snapshot: reactionSnapshot(1, 3, { self: ["heart"] }) }); + expect(session.getSnapshot().messagesByRoom.first).toEqual([message(3), message(4)]); + peer.reply(request, { type: "history_message", message: message(1) }); + peer.reply(request, { type: "message_reactions", snapshot: reactionSnapshot(1, 1, { self: ["wave"] }) }); + peer.reply(request, { type: "history_message", message: message(2) }); + peer.reply(request, { type: "message_reactions", snapshot: reactionSnapshot(2, 0) }); + peer.reply(request, { type: "history_end", count: 2, hasMore: false, oldestSeq: 1, before: 3 }); + await older; + expect(session.getSnapshot().messagesByRoom.first).toEqual([{ ...message(1), reactions: { revision: 3, choices: { self: ["heart"] } } }, message(2)]); + expect(session.getSnapshot().historyByRoom.first.atLatest).toBe(false); + peer.reply(request, { type: "message_reactions", snapshot: reactionSnapshot(2, 4, { friend: ["clap"] }) }); + peer.reply(request, { type: "message_reactions", snapshot: reactionSnapshot(5, 2, { self: ["wave"] }) }); + peer.live(message(5)); + expect(session.getSnapshot().messagesByRoom.first.map(message => message.seq)).toEqual([1, 2]); + expect(session.getSnapshot().messagesByRoom.first[1].reactions).toEqual({ revision: 4, choices: { friend: ["clap"] } }); + const latest = session.loadLatestHistory("first"); + peer.page(await peer.next(), [message(1), message(2)], false, 1); + await latest; + expect(session.getSnapshot().messagesByRoom.first.map(message => message.reactions?.revision)).toEqual([3, 4]); + const refreshing = session.loadLatestHistory("first"), refresh = await peer.next(); + peer.reply({ ...refresh, requestId: "new-live-reaction" }, { type: "message_reactions", snapshot: reactionSnapshot(3, 5, { self: ["wave"] }) }); + peer.live(message(3)); + peer.page(refresh, [message(1), message(2)], false, 1); + await refreshing; + expect(session.getSnapshot().messagesByRoom.first.map(message => message.seq)).toEqual([2, 3]); + expect(session.getSnapshot().messagesByRoom.first.map(message => message.reactions?.revision)).toEqual([4, 5]); + } finally { session.close(); } +}); test("room interactions reuse their original acknowledgement and user identity without chat or media permission", async () => { vi.useFakeTimers(); @@ -819,6 +893,7 @@ test("room replies settle only the request belonging to that room", async () => test.each([ ["missing record", [2]], ["duplicate sequence", [2, 2]], + ["missing snapshot", [2, 3]], ] as const)("an incomplete peer history page (%s) preserves messages and permits a complete retry", async (_fault, sequences) => { const { session, peer } = await setup(); try { @@ -827,7 +902,10 @@ test.each([ const incomplete = session.loadLatestHistory("first"); const rejected = expect(incomplete).rejects.toThrow("incomplete_history"); const request = await peer.next(); - for (const seq of sequences) peer.reply(request, { type: "history_message", message: message(seq) }); + for (const seq of sequences) { + peer.reply(request, { type: "history_message", message: message(seq) }); + if (_fault !== "missing snapshot") peer.reply(request, { type: "message_reactions", snapshot: reactionSnapshot(seq, 0) }); + } peer.reply(request, { type: "history_end", count: 2, hasMore: false, oldestSeq: 2, before: null }); await rejected; expect(session.getSnapshot().messagesByRoom.first).toBe(existing); @@ -837,6 +915,8 @@ test.each([ const retry = await peer.next(); peer.reply(retry, { type: "history_message", message: message(2) }); peer.reply(retry, { type: "history_message", message: message(3) }); + peer.reply(retry, { type: "message_reactions", snapshot: reactionSnapshot(2, 0) }); + peer.reply(retry, { type: "message_reactions", snapshot: reactionSnapshot(3, 0) }); expect(session.getSnapshot().messagesByRoom.first).toBe(existing); peer.reply(retry, { type: "history_end", count: 2, hasMore: false, oldestSeq: 2, before: null }); await complete;