fix(desktop): collapse thread-unread badge on thread-open (#1118)

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
This commit is contained in:
Will Pfleger
2026-06-18 15:36:47 -04:00
committed by GitHub
parent 826945e1bb
commit 0176d5f31e
5 changed files with 180 additions and 117 deletions

View File

@@ -4,7 +4,6 @@ import test from "node:test";
import { computeThreadUnreadMarker } from "../../messages/lib/unreadMarker.ts";
import {
buildDirectRepliesByParentId,
directRepliesMaxCreatedAt,
subtreeMaxCreatedAt,
} from "./subtreeCreatedAt.ts";
@@ -89,76 +88,6 @@ test("expandDeepBranch_advancesFrontierToSubtreeMax_consumesOlderSibling", () =>
assert.equal(marker.unreadCount, 0);
});
// directRepliesMaxCreatedAt covers the head and its DIRECT replies only — it
// must NOT descend into deeper branches. Here w's direct replies are deep1(400)
// and sib(300); deep2(500) is a grandchild and must be excluded.
test("directRepliesMaxCreatedAt_excludesDeeperDescendants", () => {
const { directReplyIdsByParentId, createdAtByMessageId } = fixture();
const result = directRepliesMaxCreatedAt(
"w",
directReplyIdsByParentId,
createdAtByMessageId,
);
// max(w=100, deep1=400, sib=300) = 400 — deep2(500) is NOT counted.
assert.equal(result, 400);
});
test("directRepliesMaxCreatedAt_noReplies_returnsOwnCreatedAt", () => {
const { directReplyIdsByParentId, createdAtByMessageId } = fixture();
const result = directRepliesMaxCreatedAt(
"sib",
directReplyIdsByParentId,
createdAtByMessageId,
);
assert.equal(result, 300);
});
test("directRepliesMaxCreatedAt_absentMessage_returnsNull", () => {
const { directReplyIdsByParentId, createdAtByMessageId } = fixture();
const result = directRepliesMaxCreatedAt(
"ghost",
directReplyIdsByParentId,
createdAtByMessageId,
);
assert.equal(result, null);
});
// Invariant 2: opening a thread advances the frontier to the visible direct
// replies' max, consuming them (their channel badge clears), while a deeper
// collapsed branch stays unread until expanded. The channel badge counts the
// head's DIRECT replies, so we assert against those.
test("openThread_frontierAtDirectRepliesMax_consumesVisible_keepsDeeperUnread", () => {
const { directReplyIdsByParentId, createdAtByMessageId } = fixture();
const openFrontier = directRepliesMaxCreatedAt(
"w",
directReplyIdsByParentId,
createdAtByMessageId,
);
// The channel badge is computed over the head's direct replies.
const directReplies = [
{ id: "deep1", createdAt: 400 },
{ id: "sib", createdAt: 300 },
];
const channelBadge = computeThreadUnreadMarker(directReplies, openFrontier);
assert.equal(openFrontier, 400);
// Both visible direct replies are at/below 400 → channel badge clears.
assert.equal(channelBadge.unreadCount, 0);
// But the deeper collapsed branch deep2(500) is still unread until expanded.
const deepBranch = [{ id: "deep2", createdAt: 500 }];
const deepUnread = computeThreadUnreadMarker(deepBranch, openFrontier);
assert.equal(deepUnread.unreadCount, 1);
});
// Invariant 1: the session divider is computed from the open-time frontier
// SNAPSHOT, the badge/consume from the LIVE frontier. After expand advances the
// live frontier to the subtree-max (500), the two clocks deliberately diverge:

View File

@@ -27,32 +27,6 @@ export function subtreeMaxCreatedAt(
return maxCreatedAt;
}
/**
* Newest `createdAt` across a thread head and its DIRECT replies only — the
* content visible the instant the panel opens, before any branch is expanded.
* Opening a thread advances the read frontier to this, mirroring channel-open
* parity: you see (and thus consume) the top-level replies on open, while
* deeper collapsed branches stay unread until drilled into. Returns null when
* the head is absent so the caller can skip the read-state write.
*/
export function directRepliesMaxCreatedAt(
messageId: string,
directReplyIdsByParentId: ReadonlyMap<string, string[]>,
createdAtByMessageId: ReadonlyMap<string, number>,
): number | null {
const ownCreatedAt = createdAtByMessageId.get(messageId);
if (ownCreatedAt === undefined) return null;
let maxCreatedAt = ownCreatedAt;
for (const replyId of directReplyIdsByParentId.get(messageId) ?? []) {
const createdAt = createdAtByMessageId.get(replyId);
if (createdAt !== undefined && createdAt > maxCreatedAt) {
maxCreatedAt = createdAt;
}
}
return maxCreatedAt;
}
/** Minimal timeline shape the adjacency/createdAt builders read. */
interface ReplyGraphMessage {
id: string;

View File

@@ -0,0 +1,164 @@
import assert from "node:assert/strict";
import test from "node:test";
import { computeThreadBadgeCounts } from "./threadBadgeCounts.ts";
import { nextThreadBadgeFrontier } from "./threadBadgeFrontier.ts";
import {
buildCreatedAtByMessageId,
buildDirectRepliesByParentId,
buildDirectReplyIdsByParentId,
subtreeMaxCreatedAt,
} from "./subtreeCreatedAt.ts";
// End-to-end model of the mark-read-on-thread-open pipeline in
// useChannelUnreadState. The open effect computes a read ceiling for the thread
// head, markThreadRead advances the thread-OWN marker toward it (monotonic, per
// advanceContext), the badge frontier snapshot then advances toward that live
// marker (seedThreadBadgeFrontiers -> nextThreadBadgeFrontier), and the
// summary badge counts the whole subtree against that snapshot
// (computeThreadBadgeCounts). The fix changed the open ceiling from the
// direct-replies max (head + direct children) to the full-subtree max
// (subtreeMaxCreatedAt); these tests pin that the badge collapses to 0 on open
// whether or not the OWN marker actually advances.
const msg = (id, parentId, createdAt, pubkey = "author") => ({
id,
parentId,
createdAt,
pubkey,
});
// The ceiling the open effect now writes: full-subtree max over the head.
const openCeiling = (rootId, messages) =>
subtreeMaxCreatedAt(
rootId,
buildDirectReplyIdsByParentId(messages),
buildCreatedAtByMessageId(messages),
);
// Drive one thread-open through the pipeline. `priorOwnMarker` is the thread's
// OWN read marker before this open (null = never read). Returns the resulting
// badge count for the root after open.
const badgeAfterOpen = (rootId, messages, priorOwnMarker, currentPubkey) => {
const ceiling = openCeiling(rootId, messages);
// markThreadRead -> advanceContext: monotonic max of prior own marker and the
// new ceiling. A null ceiling means no replies; the effect early-returns.
const liveMarker =
ceiling === null
? priorOwnMarker
: priorOwnMarker === null
? ceiling
: Math.max(priorOwnMarker, ceiling);
// seedThreadBadgeFrontiers advances the snapshot toward the live marker.
const frontier = nextThreadBadgeFrontier(undefined, liveMarker);
return computeThreadBadgeCounts(
messages,
buildDirectRepliesByParentId(messages),
new Map([[rootId, frontier]]),
() => true,
currentPubkey,
).get(rootId);
};
test("openThreadWithUnreadNestedReply_advancesFrontierToSubtreeMax", () => {
// root -> a(100) -> b(200): the unread lives in nested reply b.
// The OLD direct-replies ceiling stopped at a(100) (b is a grandchild, not a
// direct reply of root); only subtree-max reaches the nested b(200).
const messages = [
msg("root", null, 50),
msg("a", "root", 100),
msg("b", "a", 200),
];
const ids = buildDirectReplyIdsByParentId(messages);
const createdAt = buildCreatedAtByMessageId(messages);
assert.equal(subtreeMaxCreatedAt("root", ids, createdAt), 200);
});
test("openThreadWithUnreadNestedReply_collapsesBadgeToZero", () => {
// The reported bug: before the fix the frontier sat at the direct-replies
// ceiling (100) and the nested reply b(200) kept the badge lit. The fix
// advances to subtree-max (200), so the badge recomputes to 0 on open.
const messages = [
msg("root", null, 50),
msg("a", "root", 100),
msg("b", "a", 200),
];
assert.equal(badgeAfterOpen("root", messages, null), undefined);
});
test("openThreadWithUnreadNestedReply_oldDirectCeilingLeftBadgeLit", () => {
// Regression guard: the OLD behavior advanced the frontier only to the
// direct-replies ceiling — max over root(50) and its DIRECT reply a(100),
// i.e. 100. The nested grandchild b(200) was excluded, so the badge stayed
// lit (count=1). This pins the exact gap the fix closes: had the fix been
// reverted to that ceiling, the badge would NOT clear. The subtree-max
// ceiling (200) is asserted to clear the badge in the test above.
const messages = [
msg("root", null, 50),
msg("a", "root", 100),
msg("b", "a", 200),
];
const oldDirectCeiling = 100;
const frontier = nextThreadBadgeFrontier(undefined, oldDirectCeiling);
const count = computeThreadBadgeCounts(
messages,
buildDirectRepliesByParentId(messages),
new Map([["root", frontier]]),
() => true,
).get("root");
assert.equal(count, 1);
});
test("ownMarkerAlreadyAtSubtreeMax_stillCollapsesBadgeToZero", () => {
// Prior-session expand synced the OWN marker to subtree-max BEFORE this
// session's first open. markThreadRead's advance is then a no-op
// (advanceContext early-returns, no notify), but the badge still reads 0
// because the frontier snapshot is seeded from the live marker on render,
// independent of whether the advance notified. Pins the no-op-return path.
const messages = [
msg("root", null, 50),
msg("a", "root", 100),
msg("b", "a", 200),
];
assert.equal(badgeAfterOpen("root", messages, 200), undefined);
});
test("openThreadWhereOnlyUnreadIsOwnReply_neverShowsBadge", () => {
// Will "commented back": a nested reply authored by the current user. Self
// authored replies are excluded from the count, so no badge ever shows and
// the fix is inert — the badge is already absent before and after open.
const messages = [
msg("root", null, 50),
msg("a", "root", 100, "other"),
msg("b", "a", 200, "ME"),
];
// Frontier below every reply (never read) — only "other"'s reply a counts.
const beforeOpen = computeThreadBadgeCounts(
messages,
buildDirectRepliesByParentId(messages),
new Map([["root", null]]),
() => true,
"me",
).get("root");
assert.equal(beforeOpen, 1);
// After open the frontier reaches subtree-max (200), clearing a as well.
assert.equal(badgeAfterOpen("root", messages, null, "me"), undefined);
});
test("openThreadWhereEveryUnreadIsOwnReply_inertNoBadgeEver", () => {
// Every reply is the user's own → no badge before OR after open.
const messages = [
msg("root", null, 50),
msg("a", "root", 100, "ME"),
msg("b", "a", 200, "ME"),
];
const before = computeThreadBadgeCounts(
messages,
buildDirectRepliesByParentId(messages),
new Map([["root", null]]),
() => true,
"me",
).get("root");
assert.equal(before, undefined);
assert.equal(badgeAfterOpen("root", messages, null, "me"), undefined);
});

View File

@@ -5,7 +5,6 @@ import {
buildDirectRepliesByParentId,
buildDirectReplyIdsByParentId,
collectReplyDescendantIds,
directRepliesMaxCreatedAt,
subtreeMaxCreatedAt,
} from "@/features/channels/lib/subtreeCreatedAt";
import { computeThreadReplyUnreadCounts } from "@/features/channels/lib/threadReplyUnreadCounts";
@@ -222,27 +221,27 @@ export function useChannelUnreadState({
};
}, [openThreadHeadId]);
// Mark thread read when the panel opens, advancing the frontier to the max
// createdAt over the head and its DIRECT replies — the content visible
// without expanding anything. This mirrors channel-open parity: opening
// consumes what you can see, clearing the channel-level badge for unread that
// lived in the visible direct replies, while deeper collapsed branches stay
// unread until drilled into (expand advances the frontier further from here).
// createdAt over the head and its ENTIRE subtree — every reply, including
// ones nested in collapsed branches. Opening a notified thread means engaging
// with it, so the badge must collapse the instant the panel opens (not wait
// for a channel change or for each branch to be expanded). The badge counts
// the whole subtree (computeThreadBadgeCounts), so marking only the visible
// direct replies would leave it lit whenever the unread lives in a nested
// reply — the reported bug. Consuming collapsed branches here is not lossy:
// a NEWER reply re-raises the badge, because the unread comparison is strictly
// `createdAt > frontier` (computeThreadUnreadMarker) and the badge snapshot
// advances toward the live marker (nextThreadBadgeFrontier).
// Only persist read state for threads the user has notification interest in
// (participated, authored, or followed) to avoid bloating the context blob.
React.useEffect(() => {
if (!openThreadHeadId) return;
if (!isNotifiedForCurrentThread) return;
const openReadCeiling = directRepliesMaxCreatedAt(
openThreadHeadId,
directReplyIdsByParentId,
createdAtByMessageId,
);
const openReadCeiling = getSubtreeMaxCreatedAt(openThreadHeadId);
if (openReadCeiling === null) return;
markThreadRead(openThreadHeadId, openReadCeiling);
}, [
openThreadHeadId,
directReplyIdsByParentId,
createdAtByMessageId,
getSubtreeMaxCreatedAt,
markThreadRead,
isNotifiedForCurrentThread,
]);

View File

@@ -911,16 +911,13 @@ test.describe("thread unread indicator screenshots", () => {
await expect(badge).toBeVisible();
await expect(badge).toContainText("2");
// Clearing a NESTED unread mirrors the channel-open read model: opening the
// thread consumes only the visible direct replies (A), so the badge drops
// to "1" — the mention reply B stays unread inside A's collapsed branch.
// Opening a notified thread advances the frontier to the full subtree max,
// so it consumes the direct reply A AND the nested mention B at once — the
// badge clears to 0 in place without drilling into A's collapsed branch.
await aliceSummary.click();
await expect(page.getByTestId("message-thread-panel")).toBeVisible();
await expect(badge).toContainText("1");
await expect(badge).toHaveCount(0);
// Drilling into A's branch advances the frontier over B, the deepest reply,
// and the badge clears in place. Stays in general — no channel switch.
await expandReply(page, replyA?.id ?? "");
await page.getByTestId("message-thread-close").click();
await expect(page.getByTestId("message-thread-panel")).not.toBeVisible();