perf(chat): reuse encoded sizes and profile IDs across history updates

This commit is contained in:
AAA committed 2026-11-19 13:40:25 -05:00
1 parent 63246592be
commit f34ae4a4d6
4 files changed
+97 -41

No files matched your search

+1 -1
View File
@@ -155,7 +155,7 @@ in [introduction design](./public-introduction.md) and the [website runbook](../
| Room UI, share/watch workflow and page lifecycle | [ChannelPreviewPage](../../src/client/pages/ChannelPreviewPage.tsx), [Browser session](../../src/client/channel/session.ts) |
| Browser peer/media, playback proof and quality | [Channel media](../../src/client/channel/media.ts), [transport](../../src/client/channel/transport.ts), [decoded-frame proof](../../src/client/media/decoded-frame-proof.ts), [shared capture profiles](../../src/client/media/quality.ts) |
| Domain admission, room authority and route plans | [Core](../../prototype/channel-core/src), [Domain I/O](../../prototype/channel-server/src/domain.rs) |
| Confirmed conversation, history and storage | [Core host](../../prototype/channel-core/src/host.rs), [Browser room adapter](../../prototype/channel-browser/src/room-host.ts), [Native hosted room](../../prototype/channel-native/src/hosted_room.rs) |
| Confirmed conversation, history and storage | [Core host](../../prototype/channel-core/src/host.rs), [Browser room adapter](../../prototype/channel-browser/src/room-host.ts), [Native hosted room](../../prototype/channel-native/src/hosted_room.rs), [Browser history window](../../src/client/channel/message-history.ts) |
| Files and selected copies | [Core delivery](../../prototype/channel-core/src/file_delivery.rs), [Browser attachments](../../src/client/channel/attachments.ts), [Native file owner](../../prototype/channel-native/src/file.rs) |
| App discovery, approval and hosting | [Browser App link](../../src/client/channel/app-link.ts), [App composition](../../prototype/channel-server/src/app.rs), [site namespaces](../../prototype/channel-server/src/app_sites.rs), [local domain](../../prototype/channel-server/src/app_domain.rs) |
| Native RTC/media and gateway mapping | [Native peer](../../prototype/channel-native/src/peer.rs), [mapping](../../prototype/channel-native/src/peer/mapping.rs), [media](../../prototype/channel-native/src/media.rs), [dependency provenance](../../prototype/channel-native/README.md#rtc-dependency) |
+61
View File
@@ -0,0 +1,61 @@
import type { ChannelMessage } from "./protocol";
import { messageRemoved, type RoomHistoryChanges } from "./types";
export function mergeMessages(messages: ChannelMessage[]): ChannelMessage[] {
const merged = new Map<string, ChannelMessage>();
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);
}
export function mergeMessage(previous: ChannelMessage | undefined, message: ChannelMessage): ChannelMessage {
return previous?.reactions && (!message.reactions || previous.reactions.revision > message.reactions.revision)
? { ...message, reactions: previous.reactions } : message;
}
export function redactReply(message: ChannelMessage, changes: RoomHistoryChanges | undefined): ChannelMessage {
if (!message.reply || !messageRemoved(changes, message.reply.seq)) return message;
const { reply: _reply, ...remaining } = message;
return remaining;
}
const textEncoder = new TextEncoder();
const maxHistoryBytes = 4 * 1024 * 1024;
const messageBytes = new WeakMap<ChannelMessage, number>();
function encodedSize(message: ChannelMessage): number {
let size = messageBytes.get(message);
if (size === undefined) {
size = textEncoder.encode(JSON.stringify(message)).length;
messageBytes.set(message, size);
}
return size;
}
/** Keep a contiguous end of history within the message and byte limits. */
export function readingWindow(messages: ChannelMessage[], count: number, latest: boolean): ChannelMessage[] {
let bytes = 0, kept = 0;
for (let index = latest ? messages.length - 1 : 0; index >= 0 && index < messages.length && kept < count; index += latest ? -1 : 1) {
const size = encodedSize(messages[index]);
if (kept > 0 && bytes + size > maxHistoryBytes) break;
bytes += size; kept++;
}
return latest ? messages.slice(messages.length - kept) : messages.slice(0, kept);
}
// Pages are replaced when history changes. Keep only IDs, so a profile refresh
// or a reconnect still reads the current display names and avatars.
const pageProfiles = new WeakMap<readonly ChannelMessage[], readonly string[]>();
export function historyProfileIds(messages: readonly ChannelMessage[]): readonly string[] {
const cached = pageProfiles.get(messages);
if (cached) return cached;
const ids = new Set<string>();
for (const message of messages) {
if (!message.archivedAuthorName) ids.add(message.userId);
if (message.reply && !message.reply.archivedAuthorName) ids.add(message.reply.userId);
for (const mention of message.mentions ?? []) ids.add(mention.userId);
}
const result = [...ids];
pageProfiles.set(messages, result);
return result;
}
+6 -40
View File
@@ -13,9 +13,10 @@ import { ChannelInput } from "./input";
import { ChannelConversation } from "./conversation";
import { selectedRoom } from "./navigation";
import { RoomReadMarkers } from "./read-markers";
import { historyProfileIds, mergeMessage, mergeMessages, readingWindow, redactReply } from "./message-history";
import { CHANNEL_PROTOCOL, CHANNEL_EVENT_BYTES, PROFILE_PAGE_SIZE, ChannelEventDecoder, channelTopologySchema, roomSummarySchema, userSchema, type ChannelUser, type ProfilePage, type ChannelCommand, type ChannelEvent, type ChannelMessage, type ChannelReply, type ChannelSnapshot, type ChannelTopology, type ConversationReply, type DomainSettings, type MessageReactionSnapshot, type RoomInvitationState, type RoomSettings, type RoomSummary, type ScreenSource } from "./protocol";
import { ChannelAttachments, type DraftFile, type PreparedFile } from "./attachments";
import { messageRemoved, type ChannelActions, type ChannelView, type ChatOptions, type RoomHistoryChanges, type ScreenPresentation, type SourceMicrophoneConfiguration, type SourceMicrophoneSettings } from "./types";
import { messageRemoved, type ChannelActions, type ChannelView, type ChatOptions, type ScreenPresentation, type SourceMicrophoneConfiguration, type SourceMicrophoneSettings } from "./types";
import { loadRoomHosting, roomDatabaseName } from "./hosting";
import { validBackupSequence, type HostedRoom, type BrowserRoomSnapshot, type BrowserRoomStage, type BackupHistoryRow } from "../../../prototype/channel-browser/src/hosting-contract";
import type { BackupHistoryImport } from "../../../prototype/channel-browser/pkg/piik_channel_browser";
@@ -159,35 +160,6 @@ function withoutRoomPictures(state: ChannelSnapshot): ChannelSnapshot {
return { ...state, channel: { ...state.channel, rooms } };
}
function mergeMessages(messages: ChannelMessage[]): ChannelMessage[] {
const merged = new Map<string, ChannelMessage>();
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;
}
function redactReply(message: ChannelMessage, changes: RoomHistoryChanges | undefined): ChannelMessage {
if (!message.reply || !messageRemoved(changes, message.reply.seq)) return message;
const { reply: _reply, ...remaining } = message;
return remaining;
}
/** A reading window retains a contiguous end of history, bounded by text and image bytes. */
function readingWindow(messages: ChannelMessage[], count: number, latest: boolean): ChannelMessage[] {
const encoder = new TextEncoder(), maximum = 4 * 1024 * 1024;
let bytes = 0, kept = 0;
for (let index = latest ? messages.length - 1 : 0; index >= 0 && index < messages.length && kept < count; index += latest ? -1 : 1) {
const size = encoder.encode(JSON.stringify(messages[index])).length;
if (kept > 0 && bytes + size > maximum) break;
bytes += size; kept++;
}
return latest ? messages.slice(messages.length - kept) : messages.slice(0, kept);
}
/** The live browser endpoint owns captures and reconnects; browsing owns neither. */
export class ChannelSession {
private view: ChannelView = {
@@ -343,13 +315,6 @@ export class ChannelSession {
}
return ids.flatMap(id => this.profileFresh(id) ? [this.view.profiles.get(id)!] : []);
};
private historyProfileIds(messages = Object.values(this.view.messagesByRoom).flat()): string[] {
return messages.flatMap(message => [
...(!message.archivedAuthorName ? [message.userId] : []),
...(message.reply && !message.reply.archivedAuthorName ? [message.reply.userId] : []),
...(message.mentions ?? []).map(mention => mention.userId),
]);
}
screenPresentation = (flowId: string, stream: MediaStream, state: ScreenPresentation): void => this.media.screenPresentation(flowId, stream, state);
setQuality = (profile: QualityProfile): void => {
if (!supportsCaptureProfile(profile)) throw new Error("capture_quality_unsupported");
@@ -729,7 +694,8 @@ export class ChannelSession {
&& canRead(publication.roomId) && !freshBindings.has(publication.roomId)))),
historyByRoom: Object.fromEntries(Object.entries(this.view.historyByRoom).filter(([id]) => canRead(id) && !freshBindings.has(id))),
});
void this.loadProfiles([...state.users.map(user => user.id), ...this.historyProfileIds()]).catch(() => {});
const historyProfiles = Object.values(this.view.messagesByRoom).flatMap(historyProfileIds);
void this.loadProfiles([...state.users.map(user => user.id), ...historyProfiles]).catch(() => {});
if (refreshHelper) void this.syncAppWatching(true);
for (const [id, hosted] of this.hostedRooms) if (!state.channel.rooms.some(room => room.id === id)) {
this.hostedRooms.delete(id);
@@ -994,7 +960,7 @@ export class ChannelSession {
|| oldestSeq !== null && messages.length > 0 && messages[0].seq > oldestSeq);
this.patch({ messagesByRoom: { ...this.view.messagesByRoom, [roomId]: messages },
historyByRoom: { ...this.view.historyByRoom, [roomId]: { hasMore, before: messages[0]?.seq, atLatest } } });
void this.loadProfiles(this.historyProfileIds(messages)).catch(() => {});
void this.loadProfiles(historyProfileIds(messages)).catch(() => {});
}
private applyMessage(roomId: string, message: ChannelMessage): void {
@@ -1003,7 +969,7 @@ export class ChannelSession {
const changes = this.view.historyChangesByRoom[roomId];
if (messageRemoved(changes, message.seq)) return;
message = redactReply(message, changes);
void this.loadProfiles(this.historyProfileIds([message])).catch(() => {});
void this.loadProfiles(historyProfileIds([message])).catch(() => {});
const sender = state.users.find(user => user.id === message.userId) ?? this.view.profiles.get(message.userId) ?? { id: message.userId, name: message.archivedAuthorName ?? "User" };
const points = Array.from(message.text.replace(/\s+/gu, " ").normalize("NFC").trim());
const text = points.length > MAX_CHAT_CODE_POINTS ? `${points.slice(0, MAX_CHAT_CODE_POINTS - 1).join("")}…` : points.join("");
+29
View File
@@ -0,0 +1,29 @@
import { expect, test } from "vitest";
import { historyProfileIds, readingWindow } from "../src/client/channel/message-history";
import type { ChannelMessage } from "../src/client/channel/protocol";
function message(seq: number, text = ""): ChannelMessage {
return { id: String(seq), seq, time: seq, userId: "reader", attachments: [], text };
}
test("history tracks live profiles for each retained page and excludes archived identities", () => {
const quote = { seq: 1, userId: "author", text: "earlier", notify: true };
const row = { ...message(2), reply: quote, mentions: [{ userId: "reader", start: 0, end: 1 }] };
const page = [row, message(3)];
const ids = historyProfileIds(page);
expect(ids).toEqual(["reader", "author"]);
expect(historyProfileIds(page)).toBe(ids);
expect(historyProfileIds([{ ...row, archivedAuthorName: "Archive", reply: { ...quote, archivedAuthorName: "Archive" } }]))
.toEqual(["reader"]);
});
test("history byte limits use the replacement row when its text changes", () => {
const first = message(1), last = message(2);
const size = (row: ChannelMessage) => new TextEncoder().encode(JSON.stringify(row)).length;
const budget = 4 * 1024 * 1024;
const full = { ...last, text: "a".repeat(budget - size(first) - size(last)) };
expect(readingWindow([first, full], 2, true)).toHaveLength(2);
const changed = { ...full, text: full.text + "a" };
expect(readingWindow([first, changed], 2, true)).toEqual([changed]);
expect(readingWindow([first, changed], 2, false)).toEqual([first]);
});