Skip to content

Commit c257ff1

Browse files
matt2eclaude
andcommitted
fix(desktop): disarm an own send's pin and hold when the send fails
Problem: Second review of the branch (warning, regression vs main) on a2a9767de ("fix(desktop): end an own send's freeze hold when its row lands"), useAnchoredScroll.ts and ChannelPane.tsx. The hold can still go stale when a send never adds a row to this timeline. `ChannelPane.handleSendMessage` armed the pin and the hold before it awaited `onSendMessage`, for every main-composer send. That includes a DM send that `useMentionSendFlow`'s `onPrepareSendChannel` moves to another DM (the message mentions an agent who isn't in this one). Its optimistic row goes to that channel's window, and `goChannel` runs only after the send succeeds. If the publish is rejected or times out, the user stays on the original DM with both flags armed. A same-channel send whose `onMutate` can't resolve the channel also adds no row. Then the reader scrolls up, the hold skips the freeze, the next arrival from the other person becomes the tail, and the stale pin moves the reader to the bottom with no pill. The reviewer's jsdom repro: at HEAD, no pill and scrollTop 660 -> 956. At the merge base, "1 new message" and 660 stays. A failed send to the same channel was fine: its optimistic row lands in `onMutate`, an append that clears the hold, and is then reverted. Fix: - `ChannelPane.handleSendMessage` arms only when the send targets this channel (`!channelId || channelId === activeChannelId`). A send prepared into another channel lands its row there, and the pane navigates to it once the send succeeds. - `MessageTimelineHandle.cancelScrollToBottomOnNextUpdate` disarms a send. `useAnchoredScroll` clears the pin and the pending-send flag. The hold skipped every freeze while the send was pending, including one queued before the send that the arm cancelled. So if the send was still pending and Virtua's last report has the reader off the floor, the cancel queues that freeze, as the report would have without the hold. Later arrivals then wait behind the pill. If the send's row already landed, the hold had ended and the cancel only clears the pin. - `ChannelPane` arms through `armOwnSend`, which returns the disarm. The main composer calls it when `onSendMessage` rejects, and the Welcome "create in chat" flow when its `mutateAsync` rejects. Its `beforeSend` option now returns the disarm. A generation counter keeps a late failure from disarming a pin that a later send armed. Validation: - `MessageTimeline.ownSend.jsdom-test.mjs` adds the reviewer's no-row case in three orders: fail before the reader scrolls up, after, and with the freeze queued before the send. Each expects "1 new message" and the reader's offset unchanged after a new tail arrives. With the cancel a no-op (HEAD's behavior), all three fail: no pill, and the reader moves from 660 to 956. With the cancel clearing the flags but not queueing the freeze, the two orders where the reader left the floor during the send fail with "Jump to latest". A fourth case, a same-channel send whose row lands and is then reverted, still shows "1 new message" and keeps the offset. It passes on HEAD as well, because it pins behavior that must not change. 7/7 pass. - `useAnchoredScroll.lifecycle.test.mjs` adds a hook case: arm, cancel, the reader leaves the floor, a new tail arrives without a jump, and a later send still pins. It fails if the cancel is a no-op, or if it clears only the pending flag. useAnchoredScroll unit tests: 45/45. - Full desktop `pnpm test`: 6934 unit and 183 jsdom tests pass. - `tsc --noEmit`, `biome check --error-on-warnings` on the changed files and `git diff --check` are clean. - No test renders `ChannelPane`, so its arm condition, the rejection handlers and the generation counter are covered only by tsc and review. No browser E2E was run. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: mtoohey <[email protected]> (cherry picked from commit 159a87b411947e390e39c5bf94376bea9400a4fd)
1 parent c176734 commit c257ff1

9 files changed

Lines changed: 199 additions & 21 deletions

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

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,17 @@ export const ChannelPane = React.memo(function ChannelPane({
280280
}
281281
return pubkeys;
282282
}, [activityAgents, agentPubkeys, agentSessionAgents]);
283+
// Arms the timeline's own-send pin and returns its disarm for a failed send.
284+
// The generation keeps a late failure from disarming a later send's pin.
285+
const ownSendGenerationRef = React.useRef(0);
286+
const armOwnSend = React.useCallback(() => {
287+
const generation = ++ownSendGenerationRef.current;
288+
messageTimelineRef.current?.scrollToBottomOnNextUpdate();
289+
return () => {
290+
if (ownSendGenerationRef.current !== generation) return;
291+
messageTimelineRef.current?.cancelScrollToBottomOnNextUpdate();
292+
};
293+
}, []);
283294
const handleSendMessage = React.useCallback(
284295
async (
285296
content: string,
@@ -296,15 +307,24 @@ export const ChannelPane = React.memo(function ChannelPane({
296307
isActiveWelcomeChannel &&
297308
(containsWelcomePersonaMention(content) ||
298309
mentionsKnownAgent(mentionPubkeys, knownAgentPubkeys));
299-
messageTimelineRef.current?.scrollToBottomOnNextUpdate();
300-
await onSendMessage(
301-
content,
302-
mentionPubkeys,
303-
mediaTags,
304-
channelId,
305-
threadContext,
306-
forceRest,
307-
);
310+
// A send prepared into another channel (a DM message that mentions an
311+
// agent outside the DM) lands its row there, so this timeline never sees
312+
// it. The pane navigates there once the send succeeds.
313+
const disarmOwnSend =
314+
!channelId || channelId === activeChannelId ? armOwnSend() : null;
315+
try {
316+
await onSendMessage(
317+
content,
318+
mentionPubkeys,
319+
mediaTags,
320+
channelId,
321+
threadContext,
322+
forceRest,
323+
);
324+
} catch (error) {
325+
disarmOwnSend?.();
326+
throw error;
327+
}
308328
if (
309329
channelId &&
310330
channelId !== activeChannelId &&
@@ -319,6 +339,7 @@ export const ChannelPane = React.memo(function ChannelPane({
319339
},
320340
[
321341
activeChannelId,
342+
armOwnSend,
322343
completeWelcomeComposerBanner,
323344
goChannel,
324345
isActiveWelcomeChannel,
@@ -357,11 +378,8 @@ export const ChannelPane = React.memo(function ChannelPane({
357378
[activeChannel, currentPubkey, profiles],
358379
);
359380
const handleWelcomeAddAgent = React.useCallback(() => {
360-
onAddAgent?.({
361-
beforeSend: () =>
362-
messageTimelineRef.current?.scrollToBottomOnNextUpdate(),
363-
});
364-
}, [onAddAgent]);
381+
onAddAgent?.({ beforeSend: armOwnSend });
382+
}, [armOwnSend, onAddAgent]);
365383
const standardChannelIntro = useChannelIntro({
366384
activeChannel,
367385
onAddAgent,

‎desktop/src/features/channels/ui/ChannelPane.types.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ export type ChannelPaneProps = {
9696
onChannelManagementDeleted?: () => void;
9797
onCloseIdleAuxiliaryPanel?: () => void;
9898
onCloseProfilePanel: () => void;
99-
onAddAgent?: (options?: { beforeSend?: () => void }) => void;
99+
onAddAgent?: (options?: { beforeSend?: () => () => void }) => void;
100100
onAddFiles?: () => void;
101101
onBrowseChannels?: () => void;
102102
onCreateChannel?: () => void;

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,7 @@ export function ChannelScreen({
559559
? handleSendVideoReviewComment
560560
: undefined;
561561
const handleOpenAddBot = React.useCallback(
562-
(options?: { beforeSend?: () => void }) =>
562+
(options?: { beforeSend?: () => () => void }) =>
563563
welcomeAgentCreate.openAddAgent(() => setIsAddBotOpen(true), options),
564564
[welcomeAgentCreate],
565565
);

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ export function useChannelIntro({
3838
onWelcomeAddAgent,
3939
}: {
4040
activeChannel: Channel | null;
41-
onAddAgent?: (options?: { beforeSend?: () => void }) => void;
41+
onAddAgent?: (options?: { beforeSend?: () => () => void }) => void;
4242
onAddFiles?: () => void;
4343
onBrowseChannels?: () => void;
4444
onCreateChannel?: () => void;

‎desktop/src/features/channels/useWelcomeAgentCreate.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,15 @@ export function useWelcomeAgentCreate({
2626
);
2727
const [isOpen, setIsOpen] = React.useState(false);
2828
const [error, setError] = React.useState<string | null>(null);
29-
const beforeSendRef = React.useRef<(() => void) | null>(null);
29+
// Runs right before the chat-first send and returns how to undo it if the
30+
// send fails.
31+
const beforeSendRef = React.useRef<(() => () => void) | null>(null);
3032

3133
const openAddAgent = React.useCallback(
32-
(openRegularPicker: () => void, options?: { beforeSend?: () => void }) => {
34+
(
35+
openRegularPicker: () => void,
36+
options?: { beforeSend?: () => () => void },
37+
) => {
3338
setError(null);
3439
if (isWelcomeExperienceChannel(activeChannel)) {
3540
beforeSendRef.current = options?.beforeSend ?? null;
@@ -59,15 +64,17 @@ export function useWelcomeAgentCreate({
5964
return;
6065
}
6166
setError(null);
67+
let undoBeforeSend: (() => void) | undefined;
6268
try {
63-
beforeSendRef.current?.();
69+
undoBeforeSend = beforeSendRef.current?.();
6470
await sendMessageMutation.mutateAsync({
6571
channelId: activeChannel.id,
6672
content: `@${welcomeGuideAgent.name}, help me create a new agent.`,
6773
mentionPubkeys: [welcomeGuideAgent.pubkey],
6874
});
6975
setIsOpen(false);
7076
} catch (cause) {
77+
undoBeforeSend?.();
7178
setError(
7279
cause instanceof Error
7380
? cause.message

‎desktop/src/features/messages/ui/MessageTimeline.ownSend.jsdom-test.mjs‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,3 +263,66 @@ test("a reader who scrolls up after a send that lands above the tail keeps their
263263
);
264264
assert.equal(scroller.scrollTop, readingOffset);
265265
});
266+
267+
// A failed send can leave no row here, as when its optimistic row never
268+
// resolved a channel. Its cancel drops the pin and the hold, and freezes the
269+
// tail the hold left open if the reader is off the floor, so the next arrival
270+
// waits behind the pill instead of firing the pin under the reader.
271+
for (const order of [
272+
["send", "fail", "gap"],
273+
["send", "gap", "fail"],
274+
["gap", "send", "fail"],
275+
]) {
276+
test(`a send that fails without a row leaves the reader in place (${order.join(", ")})`, async () => {
277+
const { render, scroller, timeline } = await mountAtFloor();
278+
279+
for (const step of order) {
280+
if (step === "send") {
281+
act(() => timeline.current.scrollToBottomOnNextUpdate());
282+
} else if (step === "fail") {
283+
act(() => timeline.current.cancelScrollToBottomOnNextUpdate());
284+
} else {
285+
readerScrollsTo(scroller, scroller.scrollTop - 200);
286+
}
287+
}
288+
const readingOffset = scroller.scrollTop;
289+
flushFrames();
290+
await render([...history, message(22, "from the other person")]);
291+
flushFrames();
292+
293+
assert.equal(
294+
container.querySelector('[data-testid="message-scroll-to-latest"]')
295+
?.textContent,
296+
"1 new message",
297+
);
298+
assert.equal(scroller.scrollTop, readingOffset);
299+
});
300+
}
301+
302+
// A send to this channel lands its optimistic row at once, which is an append
303+
// that fires the pin and ends the hold. When the publish then fails, the row
304+
// is reverted and the cancel finds nothing pending.
305+
test("a reader who scrolls up before a same-channel send fails keeps their place", async () => {
306+
const { render, scroller, timeline } = await mountAtFloor();
307+
308+
act(() => timeline.current.scrollToBottomOnNextUpdate());
309+
await render([...history, sent]);
310+
flushFrames();
311+
assert.equal(scroller.scrollTop, scroller.scrollHeight - VIEWPORT);
312+
313+
readerScrollsTo(scroller, scroller.scrollTop - 200);
314+
const readingOffset = scroller.scrollTop;
315+
flushFrames();
316+
act(() => timeline.current.cancelScrollToBottomOnNextUpdate());
317+
await render(history);
318+
flushFrames();
319+
await render([...history, message(22, "from the other person")]);
320+
flushFrames();
321+
322+
assert.equal(
323+
container.querySelector('[data-testid="message-scroll-to-latest"]')
324+
?.textContent,
325+
"1 new message",
326+
);
327+
assert.equal(scroller.scrollTop, readingOffset);
328+
});

‎desktop/src/features/messages/ui/MessageTimeline.tsx‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ import { useSettleGatedPrependMessages } from "./useSettleGatedPrependMessages";
3535

3636
export type MessageTimelineHandle = {
3737
scrollToBottomOnNextUpdate: () => void;
38+
/** Undo `scrollToBottomOnNextUpdate` for a send that failed. */
39+
cancelScrollToBottomOnNextUpdate: () => void;
3840
settleAtBottom: () => boolean;
3941
};
4042

@@ -359,6 +361,7 @@ const MessageTimelineBase = React.forwardRef<
359361
scrollToBottom,
360362
scrollToBottomOnNextUpdate,
361363
isOwnSendPending,
364+
cancelScrollToBottomOnNextUpdate,
362365
scrollToMessage,
363366
onVirtualizerAtBottomStateChange,
364367
} = useAnchoredScroll({
@@ -379,6 +382,7 @@ const MessageTimelineBase = React.forwardRef<
379382
});
380383

381384
const hasConfirmedVirtualizerBottomRef = React.useRef(false);
385+
const virtualizerAtBottomRef = React.useRef(true);
382386
const bottomConfirmationChannelRef = React.useRef(channelId);
383387
if (bottomConfirmationChannelRef.current !== channelId) {
384388
bottomConfirmationChannelRef.current = channelId;
@@ -412,6 +416,7 @@ const MessageTimelineBase = React.forwardRef<
412416
// scroll-to-end is still converging. Do not turn that mount transient
413417
// into a semantic dataset freeze: wait until this channel has reached a
414418
// confirmed bottom once, then track genuine bottom -> history movement.
419+
virtualizerAtBottomRef.current = atBottom;
415420
if (atBottom) {
416421
hasConfirmedVirtualizerBottomRef.current = true;
417422
onVirtualizerAtBottomStateChange(true);
@@ -496,18 +501,38 @@ const MessageTimelineBase = React.forwardRef<
496501
setIsSemanticallyAtBottom(true);
497502
scrollToBottomOnNextUpdate();
498503
}, [scrollToBottomOnNextUpdate]);
504+
const cancelOwnMessage = React.useCallback(() => {
505+
// While the send was pending, its hold skipped any freeze, including one
506+
// queued before the send. If the reader is off the floor now, freeze as
507+
// that report would have, so later arrivals wait behind the pill.
508+
const skippedFreeze =
509+
isOwnSendPending() &&
510+
hasConfirmedVirtualizerBottomRef.current &&
511+
!virtualizerAtBottomRef.current;
512+
cancelScrollToBottomOnNextUpdate();
513+
if (skippedFreeze) {
514+
suppressNextSemanticBottomRef.current = true;
515+
queueSemanticBottom(false);
516+
}
517+
}, [cancelScrollToBottomOnNextUpdate, isOwnSendPending, queueSemanticBottom]);
499518

500519
React.useImperativeHandle(
501520
ref,
502521
() => ({
503522
scrollToBottomOnNextUpdate: prepareForOwnMessage,
523+
cancelScrollToBottomOnNextUpdate: cancelOwnMessage,
504524
settleAtBottom: () => {
505525
if (!timelineVirtualizerApi) return false;
506526
scrollToBottom("auto");
507527
return true;
508528
},
509529
}),
510-
[prepareForOwnMessage, scrollToBottom, timelineVirtualizerApi],
530+
[
531+
cancelOwnMessage,
532+
prepareForOwnMessage,
533+
scrollToBottom,
534+
timelineVirtualizerApi,
535+
],
511536
);
512537

513538
const jumpToMessage = React.useCallback(

‎desktop/src/features/messages/ui/useAnchoredScroll.lifecycle.test.mjs‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1085,3 +1085,58 @@ test("reader input at the floor resumes following live messages", async () => {
10851085
assert.deepEqual(held.settles, ["settle"]);
10861086
await act(async () => held.root.unmount());
10871087
});
1088+
1089+
// A failed send may add no row, so its cancel must drop the one-shot and the
1090+
// pending send. The next tail is then someone else's arrival and must not pull
1091+
// a reader who left the floor, while a later send still pins.
1092+
test("a cancelled own send leaves the next tail with the reader", async () => {
1093+
globalThis.ResizeObserver = class {
1094+
disconnect() {}
1095+
observe() {}
1096+
};
1097+
const scroller = document.createElement("div");
1098+
scroller.querySelector = () => null;
1099+
const settles = [];
1100+
const fake = {
1101+
content: { current: null },
1102+
messages: [{ createdAt: 500, id: "latest" }],
1103+
scrollToBottom: () => settles.push("jump"),
1104+
scrollToMessage: () => true,
1105+
scroller: { current: scroller },
1106+
settleAtBottom: () => settles.push("settle"),
1107+
};
1108+
let state = null;
1109+
const root = createRoot(document.createElement("div"));
1110+
const render = () =>
1111+
act(async () =>
1112+
root.render(
1113+
React.createElement(TargetHoldHarness, {
1114+
fake,
1115+
onState: (next) => {
1116+
state = next;
1117+
},
1118+
}),
1119+
),
1120+
);
1121+
await render();
1122+
await act(async () => state.onVirtualizerAtBottomStateChange(true));
1123+
settles.length = 0; // the mount's own bottom pin
1124+
1125+
state.scrollToBottomOnNextUpdate();
1126+
assert.equal(state.isOwnSendPending(), true);
1127+
state.cancelScrollToBottomOnNextUpdate();
1128+
assert.equal(state.isOwnSendPending(), false);
1129+
1130+
await act(async () => state.onVirtualizerAtBottomStateChange(false));
1131+
fake.messages = [...fake.messages, { createdAt: 600, id: "live" }];
1132+
await render();
1133+
assert.deepEqual(settles, [], "the arrival does not move the reader");
1134+
assert.equal(state.isAtBottom, false);
1135+
1136+
state.scrollToBottomOnNextUpdate();
1137+
fake.messages = [...fake.messages, { createdAt: 700, id: "sent" }];
1138+
await render();
1139+
assert.deepEqual(settles, ["jump"], "a later send still pins");
1140+
assert.equal(state.isOwnSendPending(), false);
1141+
await act(async () => root.unmount());
1142+
});

‎desktop/src/features/messages/ui/useAnchoredScroll.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,9 @@ type UseAnchoredScrollResult = {
9191
/** True from that arming until the first append lands, whether or not the
9292
* append moves the tail and fires the one-shot. */
9393
isOwnSendPending: () => boolean;
94+
/** Disarm that one-shot and the pending send without moving the view, for
95+
* a send that failed. */
96+
cancelScrollToBottomOnNextUpdate: () => void;
9497
/** Imperative: scroll a specific message into view; optionally pulse it.
9598
* Returns true if the row was found and scrolled, false otherwise. */
9699
scrollToMessage: (
@@ -459,6 +462,12 @@ export function useAnchoredScroll({
459462
() => ownSendPendingRef.current,
460463
[],
461464
);
465+
// A send that fails may never add a row here, so nothing else would clear
466+
// these.
467+
const cancelScrollToBottomOnNextUpdate = React.useCallback(() => {
468+
forceBottomOnNextAppendRef.current = false;
469+
ownSendPendingRef.current = false;
470+
}, []);
462471

463472
const settleAtBottomAfterLayout = React.useCallback(() => {
464473
const container = scrollContainerRef.current;
@@ -1078,6 +1087,7 @@ export function useAnchoredScroll({
10781087
settleAtBottomAfterLayout,
10791088
scrollToBottomOnNextUpdate,
10801089
isOwnSendPending,
1090+
cancelScrollToBottomOnNextUpdate,
10811091
scrollToMessage: scrollToMessageImperative,
10821092
onVirtualizerAtBottomStateChange,
10831093
};

0 commit comments

Comments
 (0)