refactor(history): read session history from its existing owner

RoomHistory owns the data window and changes; the Session no longer reads its own UI projection back as history authority. Follow-latest data, viewport following and read position retain their distinct lifetimes.

The integrated Session checks and TypeScript pass. Admission cancellation controls verify chat and deletion failures before dispatch and successful confirmation after dispatch; real Chrome component checks preserve drafts and scoped errors.
This commit is contained in:
AAA committed 2026-11-25 23:00:12 -05:00
1 parent 31679ee629
commit 1b10ae63b0
2 files changed
+50 -10

No files matched your search

+10 -10
View File
@@ -279,7 +279,7 @@ export class ChannelSession {
private watchBytes = new WatchBytes((peer, kind, data, allowed) => this.media.sendData(peer, kind, data, allowed));
readonly attachments = new ChannelAttachments(command => this.request(command), async (peer, kind, data, allowed, request) =>
this.media.sendData(peer, kind, kind === "control" ? await this.conversation.fileFrame(data as string) : data, allowed, request),
key => messageRemoved(this.view.historyChangesByRoom[key.roomId], key.messageSeq),
key => messageRemoved(this.histories.get(key.roomId)?.changes, key.messageSeq),
(peer, request) => this.media.cancelChunks(peer, request), () => this.conversation.fileAvailabilityLimit());
getSnapshot = (): ChannelView => this.view;
@@ -422,7 +422,7 @@ export class ChannelSession {
if ((document.hidden && !popoutFocused) || !isThrow(event.payload.reaction)) return;
const target = event.contentTarget;
const recipient = target ? "messageSeq" in target
? this.view.messagesByRoom[roomId]?.find(message => message.seq === target.messageSeq && message.id === target.messageId)?.userId
? this.histories.get(roomId)?.messages?.find(message => message.seq === target.messageSeq && message.id === target.messageId)?.userId
: this.view.state?.publications.find(source => source.id === target.publicationId)?.userId
: event.payload.targetPeerId ?? event.sender.peerId;
if (event.sender.peerId === self || recipient === self) this.feedbackAudio.play("throw");
@@ -780,7 +780,7 @@ export class ChannelSession {
if (this.socket === socket && !this.watching.has(next.id)) this.declineSuccessor(next.roomId, { kind: "screen", id: next.id });
});
}
const historyProfiles = Object.values(this.view.messagesByRoom).flatMap(historyProfileIds);
const historyProfiles = [...this.histories.values()].flatMap(history => historyProfileIds(history.messages ?? []));
void this.loadProfiles([...state.users.map(user => user.id), ...historyProfiles]).catch(() => {});
if (refreshHelper) void this.syncAppWatching(true);
this.hosting.update(state);
@@ -995,7 +995,7 @@ export class ChannelSession {
return;
}
this.applyHistory(reply.roomId, history, page);
} else if (record.type === "confirmed" && !messageRemoved(this.view.historyChangesByRoom[reply.roomId], record.message.seq)) {
} else if (record.type === "confirmed" && !messageRemoved(history?.changes, record.message.seq)) {
request.result?.(record);
this.applyMessage(reply.roomId, record.message, record.inserted);
}
@@ -1286,8 +1286,8 @@ export class ChannelSession {
this.retireReadings();
this.syncRoomReading(current);
if (this.roomId !== id || current.history || this.view.pending.has(`history:${id}`)) return;
const rows = this.view.messagesByRoom[id];
const latest = this.view.historyByRoom[id]?.atLatest !== false;
const history = this.histories.get(id), rows = history?.messages;
const latest = history?.paging?.atLatest !== false;
const refresh: HistoryRefresh | undefined = rows?.length ? { from: rows[0].seq,
through: latest ? Math.max(room.lastMessageSeq, rows.at(-1)!.seq) : rows.at(-1)!.seq, latest, window: [] } : undefined;
let before = !latest && refresh ? refresh.through + 1 : undefined;
@@ -1469,7 +1469,7 @@ export class ChannelSession {
const follow = () => {
if (this.readings.get(roomId) !== reading || !this.wantedReadings().has(roomId) || reading.followLatest !== followIntent) return;
delete reading.followLatest;
if (this.view.historyByRoom[roomId]?.atLatest === false)
if (this.histories.get(roomId)?.paging?.atLatest === false)
void this.requestHistory(roomId, undefined, false, { clearError: false }).catch(() => {});
};
if (reading.history && this.view.pending.has(`history:${roomId}`)) void reading.history.then(follow, follow);
@@ -1485,7 +1485,7 @@ export class ChannelSession {
}, false);
clearLocalRoomCache = (roomId: string): Promise<void> =>
this.action(`clear-local-cache:${roomId}`, () => this.attachments.clearLocalCache(roomId), false);
loadHistory = (roomId: string): Promise<void> => this.requestHistory(roomId, this.view.historyByRoom[roomId]?.before);
loadHistory = (roomId: string): Promise<void> => this.requestHistory(roomId, this.histories.get(roomId)?.paging?.before);
loadLatestHistory = (roomId: string): Promise<void> => this.requestHistory(roomId);
loadMessage = async (roomId: string, seq: number): Promise<void> => {
const reading = this.readings.get(roomId);
@@ -1494,11 +1494,11 @@ export class ChannelSession {
};
private async ensureMessage(roomId: string, seq: number, options: { signal?: AbortSignal; bindingId?: string } = {}): Promise<ChannelMessage> {
if (!this.view.messagesByRoom[roomId]?.some(message => message.seq === seq)) {
if (!this.histories.get(roomId)?.messages?.some(message => message.seq === seq)) {
await this.requestHistory(roomId, seq + 1, true, { ...options, clearError: !options.signal });
}
options.signal?.throwIfAborted();
const message = this.view.messagesByRoom[roomId]?.find(message => message.seq === seq);
const message = this.histories.get(roomId)?.messages?.find(message => message.seq === seq);
if (!message) throw new Error("message_unavailable");
return message;
}
+40
View File
@@ -189,6 +189,46 @@ const message = (seq: number) => ({ id: `message-${seq}`, seq, userId: "self", t
const reactionSnapshot = (seq: number, revision: number, counts: Record<string, number> = {}) =>
({ messageId: `message-${seq}`, messageSeq: seq, revision, counts });
test.each(["chat", "deletion"] as const)("leaving before browse admission rejects the waiting %s caller", async kind => {
const { session, socket, peer } = await setup(1000, false, "room=first", false);
try {
const first = socket.sent.findLast(command => command.type === "browse" && command.active)!;
const result = (kind === "chat" ? session.sendMessage("first", "Retain this draft")
: session.deleteMessage("first", 1, message(1).id)).catch(error => error);
expect(peer.sent).toEqual([]);
expect(session.getSnapshot().interactionsByRoom.has("first")).toBe(false);
session.browse("second");
socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId });
const history = await peer.next();
expect(history).toMatchObject({ type: "history", roomId: "second" });
peer.page(history, [], false, null);
expect(await result).toMatchObject({ name: "AbortError" });
expect(session.getSnapshot().pending.has(kind === "chat" ? "chat:first" : "delete-message:first:message-1")).toBe(false);
expect(session.getSnapshot().error).toBeNull();
socket.receive({ type: "ack", requestId: first.requestId });
await Promise.resolve();
expect(peer.sent.map(command => command.type)).toEqual(["history"]);
expect(peer.interactions.some(command => command.roomId === "first")).toBe(false);
} finally { session.close(); }
});
test.each(["chat", "deletion"] as const)("leaving after dispatch preserves the %s confirmation", async kind => {
const { session, socket, peer } = await setup();
try {
const result = kind === "chat" ? session.sendMessage("first", message(1).text)
: session.deleteMessage("first", 1, message(1).id);
const operation = await peer.next();
expect(operation.type).toBe(kind === "chat" ? "chat" : "delete_message");
session.browse("second");
socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId });
peer.page(await peer.next(), [], false, null);
peer.reply(operation, kind === "chat" ? { type: "confirmed", message: message(1), inserted: true }
: { type: "message_deleted", messageSeq: 1 });
await expect(result).resolves.toBeUndefined();
expect(session.getSnapshot().error).toBeNull();
} finally { session.close(); }
});
test.each(["latest", "message"] as const)("leaving a room retires a %s read still awaiting browse admission", async kind => {
const { session, socket, peer } = await setup(1000, false);
try {