Skip to content

Commit 5e5daa3

Browse files
author
Carl
committed
fix(unread): preserve reads across partial thread and roster updates
Signed-off-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
1 parent a2c3dce commit 5e5daa3

4 files changed

Lines changed: 129 additions & 38 deletions

File tree

‎src/features/messages/ThreadPanel.test.tsx‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -812,3 +812,53 @@ it("without close, the embedded thread keeps its reader but has no close header
812812
});
813813
expect(close).toHaveBeenCalledOnce();
814814
});
815+
816+
it("observes a visible reply before its root resolves, then enables thread catch-up", async () => {
817+
vi.useFakeTimers();
818+
const h = messagesHarness();
819+
const reply = {
820+
...row,
821+
id: "c".repeat(64),
822+
content: "available reply",
823+
createdAt: 2,
824+
};
825+
h.snapshot.root = undefined;
826+
h.snapshot.replies = [reply];
827+
h.resize(600);
828+
const observe = vi.fn(async () => {});
829+
const catchUp = vi.fn(async (_id: string, rootId?: string) => {
830+
if (!rootId)
831+
throw new Error("A thread reply cannot advance the channel frontier");
832+
});
833+
h.props.session = {
834+
...h.session,
835+
unread: {
836+
...h.session.unread,
837+
sync: () =>
838+
({ capability: "frontier-sync" }) as ReturnType<
839+
RelaySession["unread"]["sync"]
840+
>,
841+
reading: () => ({ view() {}, observe, catchUp, dispose() {} }),
842+
},
843+
};
844+
vi.spyOn(document, "hasFocus").mockReturnValue(true);
845+
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
846+
vi.spyOn(HTMLElement.prototype, "getClientRects").mockReturnValue([
847+
new DOMRect(0, 0, 500, 500),
848+
] as unknown as DOMRectList);
849+
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(
850+
new DOMRect(0, 0, 500, 500),
851+
);
852+
h.render();
853+
screen.getByRole("button", { name: "Close thread" }).focus();
854+
await act(() => vi.advanceTimersByTimeAsync(299));
855+
expect(observe).not.toHaveBeenCalled();
856+
await act(() => vi.advanceTimersByTimeAsync(1));
857+
expect(observe).toHaveBeenCalledExactlyOnceWith([reply.id]);
858+
expect(catchUp).not.toHaveBeenCalled();
859+
860+
h.snapshot.root = row;
861+
h.render();
862+
await act(() => vi.advanceTimersByTimeAsync(300));
863+
expect(catchUp).toHaveBeenCalledExactlyOnceWith(reply.id, row.id);
864+
});

‎src/features/messages/ThreadPanel.tsx‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -783,12 +783,16 @@ function ThreadMessages({
783783
scroller={scroller}
784784
settled={positioned}
785785
rootId={snapshot.root?.id}
786+
// A visible exact reply can outlive its unavailable root. Until resolved,
787+
// observe rows individually; an absent root must not mean channel catch-up.
786788
latestMessageId={
787-
snapshot.replies.reduce<ChannelMessage | undefined>(
788-
(latest, row) =>
789-
!latest || row.createdAt > latest.createdAt ? row : latest,
790-
undefined,
791-
)?.id
789+
snapshot.root
790+
? snapshot.replies.reduce<ChannelMessage | undefined>(
791+
(latest, row) =>
792+
!latest || row.createdAt > latest.createdAt ? row : latest,
793+
undefined,
794+
)?.id
795+
: undefined
792796
}
793797
/>
794798
<section

‎src/features/relay/unread.test.ts‎

Lines changed: 56 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ function setup(
4343
let journal: ReadJournal | undefined = preloaded?.(newReadJournal());
4444
let hold: Promise<void> | undefined;
4545
let commitHold: Promise<void> | undefined;
46+
let committedSignal: (() => void) | undefined;
4647
let started: (() => void) | undefined;
4748
let failNextSave = false;
4849
let failure: Error | undefined;
@@ -68,6 +69,8 @@ function setup(
6869
if (commitHold) {
6970
const wait = commitHold;
7071
commitHold = undefined;
72+
committedSignal?.();
73+
committedSignal = undefined;
7174
await wait;
7275
}
7376
return journal;
@@ -155,10 +158,15 @@ function setup(
155158
* like a storage transaction still committing when relay events arrive. */
156159
holdCommit() {
157160
let release = () => {};
161+
let signal = () => {};
162+
const committed = new Promise<void>((resolve) => {
163+
signal = resolve;
164+
});
165+
committedSignal = signal;
158166
commitHold = new Promise<void>((resolve) => {
159167
release = resolve;
160168
});
161-
return release;
169+
return { committed, release };
162170
},
163171
};
164172
}
@@ -1541,36 +1549,53 @@ it("mark all serialises channel reads over listed channels, skips read ones and
15411549
).toBe(0);
15421550
});
15431551

1544-
it("mark all skips a channel whose grant is revoked mid-sweep instead of failing", async () => {
1545-
const h = setup();
1546-
h.grant("room");
1547-
h.grant("other");
1548-
h.emit([
1549-
message(h.alice, "room", "one", 11),
1550-
message(h.alice, "other", "two", 12),
1551-
]);
1552-
clock(0);
1553-
const cut = { room: 11, other: 12 };
1554-
const [first, second] = h.session.channels
1555-
.list()
1556-
.channels.map((channel) => channel.id)
1557-
.filter((id) => id in cut) as (keyof typeof cut)[];
1558-
assert(first && second);
1559-
// Let the initial journal save settle so the hold lands on the sweep's write.
1560-
await flush();
1561-
// The first channel's write is still committing when the second grant goes.
1562-
const release = h.holdCommit();
1563-
const sweep = h.session.unread.markAllChannelsRead();
1564-
await flush();
1565-
expect(h.journal()?.state.frontiers).toEqual({ [first]: cut[first] });
1566-
h.emit([roster(h.relay, second, [], 20)]);
1567-
release();
1568-
const results = await sweep;
1569-
expect(results).toHaveLength(1);
1570-
expect(results[0]?.durability).toBe("saved");
1571-
// The revoked channel earned neither a frontier nor a failure.
1572-
expect(h.journal()?.state.frontiers).toEqual({ [first]: cut[first] });
1573-
});
1552+
it.each(["revoke", "grant"] as const)(
1553+
"mark all keeps untouched channels and click-time cuts across a mid-sweep %s",
1554+
async (action) => {
1555+
const h = setup();
1556+
const cut = { room: 11, other: 12, third: 13 };
1557+
for (const [id, timestamp] of Object.entries(cut)) {
1558+
h.grant(id);
1559+
h.emit([message(h.alice, id, id, timestamp)]);
1560+
}
1561+
clock(20);
1562+
const [first, second, third] = h.session.channels
1563+
.list()
1564+
.channels.map((channel) => channel.id);
1565+
assert(first && second && third);
1566+
await flush();
1567+
const held = h.holdCommit();
1568+
const sweep = h.session.unread.markAllChannelsRead();
1569+
// Attach before releasing the save so a regression is an assertion failure,
1570+
// not an unhandled rejection while the ordering gate is held.
1571+
const result = expect(sweep).resolves.toHaveLength(
1572+
action === "revoke" ? 2 : 3,
1573+
);
1574+
try {
1575+
await held.committed;
1576+
expect(h.journal()?.state.frontiers).toEqual({ [first]: 20 });
1577+
if (action === "revoke") h.emit([roster(h.relay, second, [], 30)]);
1578+
else {
1579+
h.grant("new", 30);
1580+
h.emit([message(h.alice, "new", "not selected", 31)]);
1581+
}
1582+
clock(40);
1583+
h.emit([message(h.alice, third, "after the click", 35)]);
1584+
} finally {
1585+
held.release();
1586+
}
1587+
await result;
1588+
expect(h.journal()?.state.frontiers).toEqual({
1589+
[first]: 20,
1590+
...(action === "grant" ? { [second]: 20 } : {}),
1591+
[third]: 20,
1592+
});
1593+
expect(
1594+
h.session.unread.snapshot({ kind: "channel", channelId: third })
1595+
.observedCount,
1596+
).toBe(1);
1597+
},
1598+
);
15741599

15751600
it.each([true, false])(
15761601
"empty channel read saves a click cutoff only with frontier support (%s)",

‎src/features/relay/unread.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,9 @@ export function createUnread({
192192
const messageForceKey = (channelId: string) => `message-force:${channelId}`;
193193
const visits = new Map<string, number>();
194194
const mutations = new Map<string, Promise<unknown>>();
195+
// Explicit channel reads survive unrelated roster changes, but never their
196+
// own revoke/regrant or a session/cache reset. Tokens cannot be revived.
197+
const channelReadGenerations = new Map<string, object>();
195198
function serialize<T>(
196199
channelId: string,
197200
operation: () => Promise<T>,
@@ -681,6 +684,8 @@ export function createUnread({
681684
function purge() {
682685
// A revoke/regrant must not revive a transaction accepted under the old access epoch.
683686
epoch++;
687+
for (const channelId of channelReadGenerations.keys())
688+
if (!allowed(channelId)) channelReadGenerations.delete(channelId);
684689
const denied = new Set(
685690
[...known, ...forcedMessages.keys()].filter(
686691
(channel) => !allowed(channel),
@@ -930,8 +935,12 @@ export function createUnread({
930935
// when that thread's replies are outside our bounded evidence window.
931936
if (!threadReference(event)) keys.add(`thread:${event.id}`);
932937
}
933-
const generation = epoch;
934-
const valid = () => !closed && generation === epoch && allowed(channelId);
938+
const generation = channelReadGenerations.get(channelId) ?? {};
939+
channelReadGenerations.set(channelId, generation);
940+
const valid = () =>
941+
!closed &&
942+
channelReadGenerations.get(channelId) === generation &&
943+
allowed(channelId);
935944
return async () => {
936945
const result =
937946
rows.length || reads.snapshot().capability === "frontier-sync"
@@ -1300,12 +1309,14 @@ export function createUnread({
13001309
},
13011310
stale() {
13021311
epoch++;
1312+
channelReadGenerations.clear();
13031313
freshness = "stale";
13041314
reads.stale();
13051315
publish();
13061316
},
13071317
clear() {
13081318
epoch++;
1319+
channelReadGenerations.clear();
13091320
repairAgain = false;
13101321
indexed = false;
13111322
events.clear();
@@ -1320,6 +1331,7 @@ export function createUnread({
13201331
dispose() {
13211332
closed = true;
13221333
epoch++;
1334+
channelReadGenerations.clear();
13231335
lifetime.abort();
13241336
for (const stop of [...handles]) stop();
13251337
stopRead();

0 commit comments

Comments
 (0)