Skip to content

Commit 1eb67bb

Browse files
matt2eclaudeJitter
authored
fix(desktop): fix the product races behind four E2E flakes (#8680)
## Summary Fixes the four desktop product races behind recurring E2E flakes in the 21–28 Oct 2026 CI audit. Each fix has a regression test: - In the channel browser, Enter acted on a stale deferred list. - A stale autocomplete swallowed the Enter that submits an empty edit. - Same-second messages swapped order on screen. - The unread pill read "Jump to latest" instead of "N new messages". Two E2E specs that failed for the same ordering reason also get test-side fixes. This is one of seven PRs split out of the `flakey-tests` branch (siblings below). ### Related issue None found for these. Draft #8559 does not fix the voice-note flake. Draft #8661 (Refs #6733) closes the `#channel` list synchronously when an edit is cleared. §11 below also covers that case, plus the `@mention` and `:emoji` lists, so the two PRs overlap in `useChannelLinks.ts` and `empty-edit-delete.spec.ts`. ### Flaky tests fixed | Test | Failing runs | Cause | Change | |---|---|---|---| | §5 `channel-browser.spec.ts:402` "Enter with no matches jumps to create" | 15 of 50 main runs, e.g. 40597484657, 40582387515, 40566841699, 40367495044 | **Product.** The list renders from `useDeferredValue(query)`. An Enter that landed before the deferred render read the old list, so it opened a stale match or skipped the create row. | While the deferred query lags, Enter filters the live query with the same `selectBrowserChannels` the list renders from. | | §11 `empty-edit-delete.spec.ts:88`, `:111`, `:132` | :88 in 3 jobs, :111 in 3, :132 in 2. :111 failed all 3 attempts on main 39822883395 and 39799090750 | **Product.** Clearing the draft went through the 120 ms query debounce. The `#channel` list stayed open, so Enter re-inserted the suggestion instead of submitting the empty edit. | `useChannelLinks`, `useEmojiAutocomplete` and `useMentions` (typed `@` only) close as soon as the trigger is gone. Typing a query still debounces. `ChannelAutocomplete` gains `data-testid="channel-autocomplete"`. | | §10 `video-attachment.spec.ts:1469` "right-click menus expose distinct selectors…" | 10 of 50 main runs, e.g. 40528171327 | **Product.** The live cache merge (`sortMessages`, ascending id within a second) and the channel-window projection (descending id) disagreed, so two same-second rows swapped on screen as each writer landed. | A new `shared/lib/eventOrder.ts` holds `compareRelayOrder` and its exact reverse, `compareChronologicalOrder`. `sortMessages` and the window and reconciliation sorts all use the window's order, so older-page paging is unchanged. `sortEvents` keeps ascending id. The spec gives its three messages distinct seconds. | | §16 `voice-note.spec.ts:906` "starting a duplicate voice-note player pauses the other instance" | 6 of 50 main runs. All 3 attempts on PRs 39622488737 and 40309414135 | Same-second messages plus index-based card lookup. | Distinct seconds, and each card is found through its own message row. | | §13 `stream.spec.ts:477` "keeps scroll position when new messages arrive above the fold" (integration) | 7 of 50 main runs. All 3 attempts on PR 39546556833 | **Product.** Frozen rows came back reordered (7 of 12 instrumented runs). The selector ended older history at the snapshot's first id, so moved rows were both prepended and kept in the frozen tail. The duplicates filled the row count, `pendingCount` fell to 0, and the pill read "Jump to latest". Deleting a frozen row also dropped the whole freeze. | `useBufferedTimelineMessages` keys rows by `renderKey`, which is stable across an optimistic send and its ack (`frozenRowKeys`). It drops only deleted frozen rows, and ends older history at the first frozen row of any key. `stream.spec` is unchanged. | New regression tests: - `channel-browser.spec`: two forced Enter variants. - `empty-edit-delete.spec`: a `#`/`@`/`:` autocomplete table. - `autocompleteTriggerClose.jsdom-test`. - `projectChannelWindow.test`: the cache merge and the window agree in both arrival orders. - `channel-dense-second-reach.spec`: a RAF sampler sees one order. - `useBufferedTimelineMessages.test`: deletion, reorder and ack rows. - `virtualization.spec`: deleting a row while reading keeps the next arrival counted. - A `useThreadReplies.test` row: the thread fetch and a live append agree on same-second order. Local before/after counts are from the original `flakey-tests` commits (238c08c7c, c66f411f3): | Test | Before | After | |---|---|---| | channel-browser | 0/20 | 20/20 | | autocomplete table | 0/30 | 30/30 | | jsdom | 0/2 | 2/2 | | dense-second sampler | 0/10 | 10/10 | | buffered-timeline unit | 4/7 | 7/7 | | virtualization deletion | 0/10 | 10/10 | | `stream:477` against an isolated relay | 25/30, all failures "Jump to latest" | 30/30, then 20/20 and 10/10 | ### Verification This branch was pushed without local re-verification, by the user's choice: local test runs were overloading the machine and failing for that reason. **Hosted CI is the check.** It was pushed with `git push --no-verify`, because the pre-push hook runs typecheck and the unit suites. #8613's flake-check lane will also repeat the changed specs and unit tests. - Every file except `empty-edit-delete.spec.ts` and `virtualization.spec.ts` is byte-identical to its final version on `flakey-tests` (67185df6a). Those two carry only this PR's hunks; see "Merge order". - Checked for this PR: `git diff --check`, biome on both partial specs (no changes, the same as on `main`), and a conflict-free merge with all six siblings onto `main`. ### Readiness These are **product fixes in the desktop app**. Under AGENTS.md "Before opening a PR", this needs an agent review, an agent run of the affected flows, and a **human in-app check** before `buzz-review-completed` is added. Suggested check, in `just dev` or a local build against any community: 1. **Channel browser:** open "Browse channels", type a name that matches nothing and press Enter straight away. The create-channel flow opens with that name. Then type an existing channel's exact name and press Enter straight away. That channel opens, not an earlier match. 2. **Empty-edit delete:** edit one of your own messages and type `#gen` so the channel list opens. Select all, delete, and press Enter at once. The empty edit is submitted (the delete-by-clearing flow) and no suggestion is re-inserted. Repeat with `@` (mention list) and `:sm` (emoji list). 3. **Same-second order:** send two short messages in quick succession, within one second. They appear in send order and never swap while they land. 4. **Unread pill:** in a busy channel, scroll up past the fold, and have a second client post one message. The pill reads "1 new message". While still scrolled up, delete one of your visible messages, then have the second client post again. The pill still counts the new message. ### Merge order No required order, but two files are shared: - `desktop/tests/e2e/empty-edit-delete.spec.ts` is also edited by **flakey-tests-desktop-e2e-actions**. This PR adds the autocomplete table after line 158. The sibling changes imports, helpers, `beforeEach` and line 143. - `desktop/tests/e2e/virtualization.spec.ts` is also edited by **flakey-tests-desktop-e2e-gates**. This PR adds one test after line 929. The sibling's hunks are all above line 551. The hunks don't touch, so each pair merges cleanly in either order, as checked with `git merge-tree`. Draft #8661 overlaps this PR in `useChannelLinks.ts` and `empty-edit-delete.spec.ts`; whichever lands second will need a rebase. ### Sibling PRs Split from `flakey-tests` (one PR per area): #8676 (PostgreSQL lease + lane), #8677 (relay E2E helper + Windows shell), #8678 (mobile), #8679 (Tauri apt cache + Windows Rust cap), #8681 (desktop E2E state gates), #8682 (desktop E2E composer + row actions). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Matt Toohey <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Jitter <2b2e6415e748c35180847a37aadae06a11e30dddc76b784e7fd9354c4eb42e7a@buzz.block.builderlab.xyz>
1 parent 158b3bf commit 1eb67bb

26 files changed

Lines changed: 947 additions & 200 deletions

‎desktop/src/features/channels/ui/ChannelBrowserDialog.tsx‎

Lines changed: 94 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,69 @@ const CHANNEL_SORT_OPTIONS: { label: string; value: ChannelSort }[] = [
6161
{ label: "Most members", value: "members" },
6262
];
6363

64+
/**
65+
* The browser's channel list for one lowercased query: filtered to the active
66+
* tab and ordered by the chosen sort, then by match score while searching.
67+
*/
68+
function selectBrowserChannels(
69+
channels: Channel[],
70+
{
71+
activeTab,
72+
channelTypeFilter,
73+
query,
74+
sort,
75+
}: {
76+
activeTab: BrowserTab;
77+
channelTypeFilter?: "stream" | "forum";
78+
query: string;
79+
sort: ChannelSort;
80+
},
81+
): Channel[] {
82+
// Fuzzy match score per channel id, so filtering and relevance-ordering
83+
// share one source of truth. Empty when no query.
84+
const matchScoreById = new Map<string, number>();
85+
if (query.length > 0) {
86+
for (const channel of channels) {
87+
const score = scoreChannelMatch(channel, query);
88+
if (score !== null) matchScoreById.set(channel.id, score);
89+
}
90+
}
91+
92+
const visibleChannels = channels.filter(
93+
(channel) =>
94+
channel.channelType !== "dm" &&
95+
(channel.archivedAt
96+
? channel.isMember
97+
: channel.visibility === "open" || channel.isMember) &&
98+
(channelTypeFilter ? channel.channelType === channelTypeFilter : true) &&
99+
(query.length === 0 || matchScoreById.has(channel.id)) &&
100+
(activeTab === "archived"
101+
? channel.archivedAt !== null
102+
: activeTab === "joined"
103+
? channel.archivedAt === null && channel.isMember
104+
: true),
105+
);
106+
107+
const sorted =
108+
sort === "members"
109+
? [...visibleChannels].sort(
110+
(a, b) =>
111+
b.memberCount - a.memberCount ||
112+
a.name.localeCompare(b.name, undefined, {
113+
sensitivity: "base",
114+
}),
115+
)
116+
: sortChannelsForSidebar(visibleChannels, sort);
117+
118+
if (query.length === 0) return sorted;
119+
120+
return sorted.sort(
121+
(a, b) =>
122+
(matchScoreById.get(a.id) ?? Number.POSITIVE_INFINITY) -
123+
(matchScoreById.get(b.id) ?? Number.POSITIVE_INFINITY),
124+
);
125+
}
126+
64127
function BrowseState({
65128
icon: Icon,
66129
title,
@@ -162,80 +225,18 @@ export function ChannelBrowserDialog({
162225
onCreated: () => onOpenChange(false),
163226
});
164227

165-
// Fuzzy match score per channel id for the current query, so both filtering
166-
// and relevance-ordering share one source of truth. Empty when no query.
167-
const matchScoreById = React.useMemo(() => {
168-
const scores = new Map<string, number>();
169-
if (deferredQuery.length === 0) return scores;
170-
for (const channel of channels) {
171-
const score = scoreChannelMatch(channel, deferredQuery);
172-
if (score !== null) scores.set(channel.id, score);
173-
}
174-
return scores;
175-
}, [channels, deferredQuery]);
176-
177-
const matchingChannels = React.useMemo(() => {
178-
const filtered = channels.filter(
179-
(channel) =>
180-
channel.channelType !== "dm" &&
181-
(channel.archivedAt
182-
? channel.isMember
183-
: channel.visibility === "open" || channel.isMember) &&
184-
(channelTypeFilter ? channel.channelType === channelTypeFilter : true),
185-
);
186-
187-
if (deferredQuery.length === 0) {
188-
return filtered;
189-
}
190-
191-
return filtered.filter((channel) => matchScoreById.has(channel.id));
192-
}, [channels, channelTypeFilter, deferredQuery, matchScoreById]);
193-
194-
const currentChannels = React.useMemo(
195-
() => matchingChannels.filter((channel) => channel.archivedAt === null),
196-
[matchingChannels],
197-
);
198-
199-
const joinedChannels = React.useMemo(
200-
() => currentChannels.filter((channel) => channel.isMember),
201-
[currentChannels],
202-
);
203-
204-
const archivedChannels = React.useMemo(
205-
() => matchingChannels.filter((channel) => channel.archivedAt !== null),
206-
[matchingChannels],
228+
// The list renders from the deferred query so typing stays responsive.
229+
const orderedVisibleChannels = React.useMemo(
230+
() =>
231+
selectBrowserChannels(channels, {
232+
activeTab,
233+
channelTypeFilter,
234+
query: deferredQuery,
235+
sort,
236+
}),
237+
[activeTab, channelTypeFilter, channels, deferredQuery, sort],
207238
);
208239

209-
const visibleChannels =
210-
activeTab === "archived"
211-
? archivedChannels
212-
: activeTab === "joined"
213-
? joinedChannels
214-
: matchingChannels;
215-
216-
const isSearching = deferredQuery.length > 0;
217-
218-
const orderedVisibleChannels = React.useMemo(() => {
219-
const sorted =
220-
sort === "members"
221-
? [...visibleChannels].sort(
222-
(a, b) =>
223-
b.memberCount - a.memberCount ||
224-
a.name.localeCompare(b.name, undefined, {
225-
sensitivity: "base",
226-
}),
227-
)
228-
: sortChannelsForSidebar(visibleChannels, sort);
229-
230-
if (!isSearching) return sorted;
231-
232-
return sorted.sort(
233-
(a, b) =>
234-
(matchScoreById.get(a.id) ?? Number.POSITIVE_INFINITY) -
235-
(matchScoreById.get(b.id) ?? Number.POSITIVE_INFINITY),
236-
);
237-
}, [isSearching, matchScoreById, sort, visibleChannels]);
238-
239240
const selectedSortLabel =
240241
CHANNEL_SORT_OPTIONS.find((option) => option.value === sort)?.label ??
241242
"Alphabetical";
@@ -386,12 +387,6 @@ export function ChannelBrowserDialog({
386387
});
387388
}
388389

389-
// Map the flat nav index back to a channel, accounting for the create row
390-
// occupying index 0 when present.
391-
const selectedItem =
392-
selectedIndex !== null && !isCreateRowSelected
393-
? orderedVisibleChannels[selectedIndex - channelNavOffset]
394-
: undefined;
395390
const emptyTitle =
396391
deferredQuery.length > 0
397392
? `No ${entityLabel}s match your search`
@@ -487,23 +482,38 @@ export function ChannelBrowserDialog({
487482
event.key === "Enter" &&
488483
!event.nativeEvent.isComposing
489484
) {
485+
// Enter acts on what was typed. A fast Enter can land
486+
// before the deferred list renders, so filter the live
487+
// query here rather than reading the stale list.
488+
const results =
489+
deferredQuery === normalizedQuery
490+
? orderedVisibleChannels
491+
: selectBrowserChannels(channels, {
492+
activeTab,
493+
channelTypeFilter,
494+
query: normalizedQuery,
495+
sort,
496+
});
490497
// If the create row is highlighted — or it's the only
491498
// actionable item (no channel matches) — Enter creates.
492499
if (
493500
showCreateRow &&
494-
(isCreateRowSelected ||
495-
orderedVisibleChannels.length === 0)
501+
(isCreateRowSelected || results.length === 0)
496502
) {
497503
event.preventDefault();
498504
enterCreateMode(trimmedQuery);
499505
return;
500506
}
501507

502-
if (orderedVisibleChannels.length > 0) {
508+
if (results.length > 0) {
503509
event.preventDefault();
504-
handleSelect(
505-
selectedItem ?? orderedVisibleChannels[0],
506-
);
510+
// Map the flat nav index back to a channel,
511+
// accounting for the create row at index 0.
512+
const selectedItem =
513+
selectedIndex !== null && !isCreateRowSelected
514+
? results[selectedIndex - channelNavOffset]
515+
: undefined;
516+
handleSelect(selectedItem ?? results[0]);
507517
}
508518
}
509519
}}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/**
2+
* Clearing a composer draft must close its `#channel` or `:emoji`
3+
* autocomplete at once. Closing used to wait out the 120 ms query debounce, so
4+
* an Enter pressed right after clearing picked the stale suggestion instead of
5+
* submitting (empty-edit-delete.spec.ts covers the `@mention` hook end to end).
6+
*/
7+
8+
import assert from "node:assert/strict";
9+
import { afterEach, test } from "node:test";
10+
11+
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
12+
import * as React from "react";
13+
14+
import { ChannelNavigationProvider } from "../../../shared/context/ChannelNavigationContext.tsx";
15+
import { useChannelLinks } from "./useChannelLinks.ts";
16+
import { useEmojiAutocomplete } from "./useEmojiAutocomplete.ts";
17+
18+
afterEach(cleanup);
19+
20+
const channels = [
21+
{
22+
id: "general-id",
23+
name: "general",
24+
channelType: "stream",
25+
archivedAt: null,
26+
},
27+
];
28+
const customEmoji = [
29+
{ shortcode: "partyparrot", url: "https://example.test/partyparrot.png" },
30+
];
31+
32+
const cases = [
33+
{
34+
trigger: "#channel",
35+
draft: "Ship notes for #general",
36+
renderAutocomplete: () =>
37+
renderHook(() => useChannelLinks(), {
38+
wrapper: ({ children }) =>
39+
React.createElement(
40+
ChannelNavigationProvider,
41+
{ channels },
42+
children,
43+
),
44+
}),
45+
isOpen: (hook) => hook.isChannelOpen,
46+
update: (hook, value, cursor) => hook.updateChannelQuery(value, cursor),
47+
keyDown: (hook, event) => hook.handleChannelKeyDown(event),
48+
},
49+
{
50+
trigger: ":emoji",
51+
draft: "Ship notes :party",
52+
renderAutocomplete: () =>
53+
renderHook(() => useEmojiAutocomplete(customEmoji)),
54+
isOpen: (hook) => hook.isEmojiAutocompleteOpen,
55+
update: (hook, value, cursor) => hook.updateEmojiQuery(value, cursor),
56+
keyDown: (hook, event) => hook.handleEmojiKeyDown(event),
57+
},
58+
];
59+
60+
for (const {
61+
trigger,
62+
draft,
63+
renderAutocomplete,
64+
isOpen,
65+
update,
66+
keyDown,
67+
} of cases) {
68+
test(`clearing a ${trigger} draft closes its autocomplete before Enter`, async () => {
69+
const { result } = renderAutocomplete();
70+
71+
act(() => update(result.current, draft, draft.length));
72+
// Typing a query still debounces.
73+
assert.equal(isOpen(result.current), false);
74+
await waitFor(() => assert.equal(isOpen(result.current), true));
75+
76+
act(() => update(result.current, "", 0));
77+
assert.equal(isOpen(result.current), false);
78+
let prevented = false;
79+
const enter = {
80+
key: "Enter",
81+
altKey: false,
82+
ctrlKey: false,
83+
metaKey: false,
84+
shiftKey: false,
85+
preventDefault: () => {
86+
prevented = true;
87+
},
88+
};
89+
assert.deepEqual(keyDown(result.current, enter), { handled: false });
90+
assert.equal(prevented, false);
91+
});
92+
93+
test(`dropping a ${trigger} trigger without clearing the draft still debounces`, async () => {
94+
const { result } = renderAutocomplete();
95+
96+
act(() => update(result.current, draft, draft.length));
97+
await waitFor(() => assert.equal(isOpen(result.current), true));
98+
99+
// Selecting a suggestion with Enter splits the paragraph in the editor
100+
// before the composer's keydown handler runs. That update carries no
101+
// trigger, but the handler must still see the open autocomplete.
102+
act(() => update(result.current, "Ship notes\n", 11));
103+
assert.equal(isOpen(result.current), true);
104+
await waitFor(() => assert.equal(isOpen(result.current), false));
105+
});
106+
}

0 commit comments

Comments
 (0)