Skip to content

Commit 6bdc05f

Browse files
matt2eclaude
andcommitted
fix(channels): focus a moved thread tab in the same task as its placement
Fixes the Linux WebKit flake in navigation-thread-history.spec.mjs "dragging thread tabs reorders and crosses panes without losing the reply", seen on PR #930 (run 38344091833) and PR #920 (run 38331018192) with the identical `toHaveCount(0)` failure on the side pane's last tab. Cause: `moveBy` and the drag `move` in useConversationTabs placed the tab with `tabState.moveTab` and then focused it where it landed from a `requestAnimationFrame`. On a loaded runner that frame arrives late. The trace shows the first `Alt+Shift+ArrowLeft` commit at 177949 ms with the moved tab in main at tabindex -1, the test focusing the remaining side tab at 177960, and the stale frame then pulling focus back to the main tab (it flips to tabindex 0 in the post-press snapshot) before the second press at 177976. That press therefore reached a main-pane tab at index 0, where `moveBy` returns without moving, and the side tab stayed. The same race hits a user who moves a tab and touches anything else within a frame; it is a product defect, so the spec is unchanged. Fix: `placeTab` commits the move with `flushSync` and focuses the tab's re-inserted element immediately, in the same keydown/pointerup task. Both callers use it; nothing is deferred, so a later frame cannot take focus away from wherever the user moved it. Browser cases added/removed: none. One colocated Vitest regression: a keyboard move leaves focus on the placed tab synchronously and a later frame does not take it back; it fails on the previous code at the first assertion (focus still on body) and passes with the fix. Fail-then-pass: a scratch spec held every rAF callback and released it between the test's `focus()` and `keyboard.press`, mirroring the CI ordering. Before: 4/4 failed (2 WebKit, 2 Chromium) with the identical `Expected: 0 / Received: 1`. After: 6/6 passed. An 80 ms delay probe was racy (1 of 8 failed) and was replaced by the gate. Validation (macOS, Playwright 1.63 engines): navigation-thread-history spec 5x WebKit 50/50, 3x Chromium 30/30; vitest src/bundled/channels + src/features/panels 564/564; tsc and biome clean. Deferred: hosted CI on Linux WebKit; a green run does not prove the flake is gone. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent 03b73ec commit 6bdc05f

2 files changed

Lines changed: 73 additions & 17 deletions

File tree

‎src/bundled/channels/useConversationTabs.test.tsx‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,65 @@ it("retained offline tabs can close and open threads without activating connecte
7777
expect(restored.result.current.tabs).toHaveLength(2);
7878
});
7979

80+
it("a keyboard move focuses the placed tab at once and never takes focus back later", async () => {
81+
const session = {
82+
viewer: "viewer",
83+
channels: { list: () => ({ channels: [] }), window: () => ({ rows: [] }) },
84+
} as unknown as RelaySession;
85+
const emptyPanels: RegisteredPanel[] = [];
86+
const panels = {
87+
snapshot: () => emptyPanels,
88+
subscribe: () => () => {},
89+
} as unknown as Panels;
90+
const relay = {
91+
snapshot: () => ({ status: "ready", session }),
92+
} as unknown as RelayData;
93+
const current = { id: "alpha", name: "Alpha" };
94+
const h = renderHook(() => {
95+
const state = useChannelTabState(session, "alpha");
96+
const workspace = useConversationTabs({
97+
state,
98+
relay,
99+
session,
100+
panels,
101+
current,
102+
channels: [current],
103+
scope: "scope:viewer",
104+
conversationIcon: () => null,
105+
leadingIds: [],
106+
continuingVisit: true,
107+
isLive: () => true,
108+
openLink: () => false,
109+
});
110+
return { state, workspace };
111+
});
112+
act(() => h.result.current.state.openThreadTab("alpha", "first", "first"));
113+
act(() => h.result.current.state.openThreadTab("alpha", "second", "second"));
114+
const strip = document.createElement("div");
115+
for (const item of h.result.current.workspace.items) {
116+
const tab = document.createElement("button");
117+
tab.setAttribute("role", "tab");
118+
tab.dataset.tabValue = item.id;
119+
strip.append(tab);
120+
}
121+
const elsewhere = document.createElement("button");
122+
document.body.append(strip, elsewhere);
123+
const moving = h.result.current.workspace.items[1];
124+
if (!moving || !("move" in moving)) throw new Error("expected a thread tab");
125+
act(() => moving.move?.(-1));
126+
expect(h.result.current.state.tabs.map((tab) => tab.id)).toEqual([
127+
"thread:alpha:second",
128+
"thread:alpha:first",
129+
]);
130+
expect(document.activeElement).toBe(strip.lastElementChild);
131+
// The user moves on before the next frame; that frame must not undo it.
132+
elsewhere.focus();
133+
await new Promise((frame) => requestAnimationFrame(frame));
134+
expect(document.activeElement).toBe(elsewhere);
135+
strip.remove();
136+
elsewhere.remove();
137+
});
138+
80139
it("the current verified read-only preview owns its thread host, but unrelated previews do not", () => {
81140
const current = { id: "preview", name: "Public", readOnly: true as const };
82141
const other = { id: "other", name: "Other public", readOnly: true as const };

‎src/bundled/channels/useConversationTabs.tsx‎

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import {
2424
import { parseBuzzLink } from "../../features/navigation/buzz-links";
2525
import { ConversationTab } from "./ConversationTab";
2626
import { TabSlot, useTabNodes } from "./TabHosts";
27-
import { createPortal } from "react-dom";
27+
import { createPortal, flushSync } from "react-dom";
2828
import type { PageNavigation } from "../../features/navigation/service";
2929
import { useChannelPanels } from "./useChannelPanels";
3030
import {
@@ -309,6 +309,17 @@ export function useConversationTabs({
309309
notify();
310310
};
311311
const [announcement, setAnnouncement] = useState("");
312+
// Place the tab and focus it where it landed in the same task. Reinserting
313+
// the tab's element blurs it, and a frame-deferred refocus would take focus
314+
// back from wherever the user has since moved it.
315+
const placeTab = (id: string, pane: TabPane, index: number) => {
316+
flushSync(() => tabState.moveTab(id, pane, index));
317+
document
318+
.querySelector<HTMLElement>(
319+
`[role="tab"][data-tab-value="${CSS.escape(id)}"]`,
320+
)
321+
?.focus({ preventScroll: true });
322+
};
312323
// One keyboard gesture both reorders and crosses panes at an edge.
313324
const moveBy = (tab: Tab, delta: -1 | 1) => {
314325
if (!currentVisit() || tab.kind !== "thread") return;
@@ -326,19 +337,12 @@ export function useConversationTabs({
326337
target = pane === "main" ? "side" : "main";
327338
position = target === "side" ? 0 : mainTabs.length;
328339
} else if (position < 0 || position >= order.length) return;
329-
tabState.moveTab(tab.id, target, position);
340+
placeTab(tab.id, target, position);
330341
setAnnouncement(
331342
crossing
332343
? `Moved to the ${target === "main" ? "main" : "side"} pane.`
333344
: `Moved to position ${position + 1} of ${order.length}.`,
334345
);
335-
requestAnimationFrame(() =>
336-
document
337-
.querySelector<HTMLElement>(
338-
`[role="tab"][data-tab-value="${CSS.escape(tab.id)}"]`,
339-
)
340-
?.focus({ preventScroll: true }),
341-
);
342346
};
343347
const drag = useTabDrag({
344348
visit,
@@ -366,15 +370,8 @@ export function useConversationTabs({
366370
const order = tabState.tabs.filter((tab) => tabPane(tab) === pane);
367371
if (moving && tabPane(moving) === pane && order.indexOf(moving) === index)
368372
return;
369-
tabState.moveTab(id, pane, index);
373+
placeTab(id, pane, index);
370374
setAnnouncement(`Moved to position ${index + 1} in the ${pane} pane.`);
371-
requestAnimationFrame(() =>
372-
document
373-
.querySelector<HTMLElement>(
374-
`[role="tab"][data-tab-value="${CSS.escape(id)}"]`,
375-
)
376-
?.focus({ preventScroll: true }),
377-
);
378375
},
379376
});
380377
const openConversationThread = (

0 commit comments

Comments
 (0)