Skip to content

Commit 2ac0aa1

Browse files
Collapse contiguous join messages (#7262)
1 parent 75f101d commit 2ac0aa1

8 files changed

Lines changed: 1469 additions & 207 deletions

File tree

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
import assert from "node:assert/strict";
2+
import { test } from "node:test";
3+
4+
import { buildGroupedMembershipPayload } from "./membershipGroupPayload.ts";
5+
import { buildTimelineItems } from "./timelineItems.ts";
6+
import { KIND_SYSTEM_MESSAGE } from "../../../shared/constants/kinds.ts";
7+
8+
const DAY_START = Math.floor(Date.UTC(2026, 5, 14, 12, 0, 0) / 1000);
9+
10+
function systemEntry(id, createdAt, body) {
11+
return {
12+
message: {
13+
author: "System",
14+
body: JSON.stringify(body),
15+
createdAt,
16+
depth: 0,
17+
id,
18+
kind: KIND_SYSTEM_MESSAGE,
19+
pubkey: "aa".repeat(32),
20+
reactions: [],
21+
time: "12:00 PM",
22+
},
23+
summary: null,
24+
};
25+
}
26+
27+
// One symbol per membership mechanism the relay can emit, so the matrix covers
28+
// self-arrival, addition (same and different actor), and departure — for two
29+
// distinct targets, which is what makes same-target vs cross-target grouping
30+
// observable.
31+
const SYMBOLS = {
32+
"self-join(a)": { type: "member_joined", actor: "aaa", target: "aaa" },
33+
"self-join(b)": { type: "member_joined", actor: "bbb", target: "bbb" },
34+
"add(a by x)": { type: "member_joined", actor: "xxx", target: "aaa" },
35+
"add(b by x)": { type: "member_joined", actor: "xxx", target: "bbb" },
36+
"add(b by y)": { type: "member_joined", actor: "yyy", target: "bbb" },
37+
"leave(a)": { type: "member_left", actor: "aaa" },
38+
"leave(b)": { type: "member_left", actor: "bbb" },
39+
};
40+
41+
const SYMBOL_NAMES = Object.keys(SYMBOLS);
42+
43+
function sequencesOfLength(length) {
44+
if (length === 0) return [[]];
45+
return sequencesOfLength(length - 1).flatMap((prefix) =>
46+
SYMBOL_NAMES.map((name) => [...prefix, name]),
47+
);
48+
}
49+
50+
function entriesFor(sequence) {
51+
return sequence.map((name, index) =>
52+
systemEntry(`e${index}`, DAY_START + index * 30, SYMBOLS[name]),
53+
);
54+
}
55+
56+
/**
57+
* The seam this guards: `buildTimelineItems` owns *which* contiguous membership
58+
* events collapse into one `system-group`, and `buildGroupedMembershipPayload`
59+
* owns *how* that group is described. They are two statements of one rule.
60+
*
61+
* When the builder emits a group the payload builder returns null for,
62+
* `SystemMessageRow` falls back to the group's oldest message and every other
63+
* event in the group vanishes from the timeline — a member who left still
64+
* renders as present. That failure is silent, so it needs a standing guard
65+
* rather than one case-by-case regression per shape.
66+
*/
67+
test("every membership group buildTimelineItems emits is describable", () => {
68+
const undescribable = [];
69+
let groupsChecked = 0;
70+
71+
for (const length of [2, 3, 4]) {
72+
for (const sequence of sequencesOfLength(length)) {
73+
const { items } = buildTimelineItems(entriesFor(sequence), null);
74+
for (const item of items) {
75+
if (item.kind !== "system-group") continue;
76+
groupsChecked += 1;
77+
const payload = buildGroupedMembershipPayload(
78+
item.entries.map((entry) => entry.message),
79+
);
80+
if (!payload) {
81+
undescribable.push(
82+
`${sequence.join(" → ")} [group: ${item.entries
83+
.map((entry) => entry.message.id)
84+
.join(",")}]`,
85+
);
86+
}
87+
}
88+
}
89+
}
90+
91+
assert.ok(groupsChecked > 0, "matrix produced no groups to check");
92+
assert.deepEqual(
93+
undescribable.slice(0, 10),
94+
[],
95+
`${undescribable.length} grouped shape(s) render as the oldest event only`,
96+
);
97+
});
98+
99+
test("a lifecycle group needs every arrival to be a self-join by the departing member", () => {
100+
const elrond = "11".repeat(32);
101+
const viewer = "10".repeat(32);
102+
const message = (id, body) => ({
103+
author: "System",
104+
body: JSON.stringify(body),
105+
createdAt: 1,
106+
depth: 0,
107+
id,
108+
kind: KIND_SYSTEM_MESSAGE,
109+
reactions: [],
110+
time: "12:00 PM",
111+
});
112+
const selfJoin = (id) =>
113+
message(id, { type: "member_joined", actor: elrond, target: elrond });
114+
const leave = (id) => message(id, { type: "member_left", actor: elrond });
115+
116+
// Accepted: one or more equivalent self-arrivals, then that member departing.
117+
for (const arrivals of [1, 2, 3]) {
118+
const messages = [
119+
...Array.from({ length: arrivals }, (_, index) => selfJoin(`j${index}`)),
120+
leave("l"),
121+
];
122+
assert.equal(
123+
buildGroupedMembershipPayload(messages)?.type,
124+
"member_joined_then_left",
125+
`${arrivals} self-arrival(s) + departure should be one lifecycle summary`,
126+
);
127+
}
128+
129+
// Rejected: anything else. Each of these would misattribute a self-join the
130+
// member never made, or fold in an unrelated member's activity.
131+
const rejected = {
132+
"addition, not a self-join": [
133+
message("a", { type: "member_joined", actor: viewer, target: elrond }),
134+
leave("l"),
135+
],
136+
"one arrival is an addition": [
137+
selfJoin("j0"),
138+
message("a", { type: "member_joined", actor: viewer, target: elrond }),
139+
leave("l"),
140+
],
141+
"a different member departs": [
142+
selfJoin("j0"),
143+
message("l", { type: "member_left", actor: viewer }),
144+
],
145+
"departure is not last": [leave("l"), selfJoin("j0")],
146+
"no departure at all": [selfJoin("j0"), selfJoin("j1")],
147+
};
148+
for (const [name, messages] of Object.entries(rejected)) {
149+
assert.notEqual(
150+
buildGroupedMembershipPayload(messages)?.type,
151+
"member_joined_then_left",
152+
`${name} must not render as a lifecycle summary`,
153+
);
154+
}
155+
});
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
/**
2+
* Grouped-membership payload construction for system rows.
3+
*
4+
* `buildTimelineItems` decides *which* contiguous membership events collapse
5+
* into one `system-group`; this module decides *how* that group is described.
6+
* The two rules are one invariant, so they live where both the renderer and a
7+
* lib-level test can import them — a group the builder emits but this module
8+
* cannot describe silently degrades to "render only the oldest event", which
9+
* drops the rest of the group from the timeline.
10+
*
11+
* Kept pure (no React, no DOM) so `membershipGroupPayload.test.mjs` and
12+
* `timelineItems.test.mjs` can cross-check the two rules directly.
13+
*/
14+
15+
import type { TimelineMessage } from "@/features/messages/types";
16+
import { normalizePubkey } from "@/shared/lib/pubkey";
17+
18+
/** Parsed body of a kind:40099 system message, plus the synthetic group kinds. */
19+
export type SystemMessagePayload = {
20+
type: string;
21+
actor?: string;
22+
arrivals?: Array<{ actor: string; target: string }>;
23+
target?: string;
24+
targets?: string[];
25+
topic?: string;
26+
purpose?: string;
27+
// Moderation tombstone fields (kind:40099 "message_deleted"). All optional and
28+
// moderator-authored — present when a moderator removed the message, absent for
29+
// a plain member self-delete. Reporter identity/evidence never appears here.
30+
public_reason?: string;
31+
reason_code?: string;
32+
action_id?: string;
33+
};
34+
35+
/** Parses one system message body; returns null when the body is not JSON. */
36+
export function parseSystemMessagePayload(
37+
message: TimelineMessage,
38+
): SystemMessagePayload | null {
39+
try {
40+
return JSON.parse(message.body) as SystemMessagePayload;
41+
} catch {
42+
return null;
43+
}
44+
}
45+
46+
/**
47+
* Derives the synthetic payload describing a grouped membership row, or null
48+
* when the group is not a shape this module can describe.
49+
*
50+
* Must stay total over everything `buildTimelineItems` groups —
51+
* `membershipGroupPayload.test.mjs` asserts that with a matrix invariant.
52+
*/
53+
export function buildGroupedMembershipPayload(
54+
messages: readonly TimelineMessage[],
55+
): SystemMessagePayload | null {
56+
if (messages.length < 2) return null;
57+
58+
const payloads = messages.map(parseSystemMessagePayload);
59+
const joinedThenLeft = buildJoinedThenLeftPayload(payloads);
60+
if (joinedThenLeft) return joinedThenLeft;
61+
62+
const arrivals = payloads.map((payload) => {
63+
const payloadActor = payload?.actor ? normalizePubkey(payload.actor) : null;
64+
const payloadTarget = payload?.target
65+
? normalizePubkey(payload.target)
66+
: null;
67+
if (payload?.type !== "member_joined" || !payloadActor || !payloadTarget) {
68+
return null;
69+
}
70+
return { actor: payloadActor, target: payloadTarget };
71+
});
72+
if (arrivals.some((arrival) => !arrival)) return null;
73+
74+
const membershipArrivals = arrivals as Array<{
75+
actor: string;
76+
target: string;
77+
}>;
78+
const targets = [...new Set(membershipArrivals.map(({ target }) => target))];
79+
return {
80+
arrivals: membershipArrivals,
81+
type: "members_arrived",
82+
target: targets[0],
83+
targets,
84+
};
85+
}
86+
87+
/**
88+
* One lifecycle summary for N>=1 equivalent self-arrivals of a member followed
89+
* by that same member departing.
90+
*
91+
* Mirrors `membershipChangesCanGroup`: a departure only groups with self-arrivals
92+
* of the departing member, and the builder absorbs *every* contiguous one, not
93+
* just the nearest. Duplicate `member_joined` events are a real relay artifact —
94+
* `handle_put_user` re-emits one on each PUT_USER — so pinning this to a 2-event
95+
* pair dropped the departure from the timeline entirely.
96+
*/
97+
function buildJoinedThenLeftPayload(
98+
payloads: readonly (SystemMessagePayload | null)[],
99+
): SystemMessagePayload | null {
100+
if (payloads.length < 2) return null;
101+
102+
const departure = payloads[payloads.length - 1];
103+
const departureActor = departure?.actor
104+
? normalizePubkey(departure.actor)
105+
: null;
106+
if (departure?.type !== "member_left" || !departureActor) return null;
107+
108+
const arrivals = payloads.slice(0, -1);
109+
const arrivalTarget = arrivals[0]?.target;
110+
if (!arrivalTarget) return null;
111+
112+
const everyArrivalIsSelfJoinByDeparture = arrivals.every((arrival) => {
113+
const actor = arrival?.actor ? normalizePubkey(arrival.actor) : null;
114+
const target = arrival?.target ? normalizePubkey(arrival.target) : null;
115+
return (
116+
arrival?.type === "member_joined" &&
117+
actor !== null &&
118+
target !== null &&
119+
actor === target &&
120+
target === departureActor
121+
);
122+
});
123+
if (!everyArrivalIsSelfJoinByDeparture) return null;
124+
125+
return { type: "member_joined_then_left", target: arrivalTarget };
126+
}

‎desktop/src/features/messages/lib/systemEventCopy.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ export function addedByActionPrefix(isCurrentUser: boolean): string {
2323
return isCurrentUser ? "were added by" : "added by";
2424
}
2525

26+
/**
27+
* Generic add caption when the timeline should state that someone was added
28+
* without attributing the action to a single actor.
29+
*/
30+
export function addedActionPrefix(isCurrentUser: boolean): string {
31+
return isCurrentUser ? "were added" : "was added";
32+
}
33+
2634
/**
2735
* Caption for a channel topic or purpose change.
2836
*

0 commit comments

Comments
 (0)