Skip to content

Commit e5a6de3

Browse files
committed
Preserve keyboard focus through sidebar activity transitions
Signed-off-by: OpenAI Codex <[email protected]>
1 parent 4681e76 commit e5a6de3

8 files changed

Lines changed: 224 additions & 59 deletions

File tree

‎src/bundled/channels/ChannelActivityPopover.tsx‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ function ActivityRow({
122122
icon={<EnvelopeOpenIcon />}
123123
aria-label={`Mark thread from ${name} as read`}
124124
title="Mark as read"
125-
disabled={pending}
125+
loading={pending}
126126
onClick={() => void markRead()}
127127
/>
128128
</span>
@@ -202,13 +202,17 @@ export function ChannelActivityPopover({
202202
),
203203
) as ({ startedAt: number; messageId?: string } | null)[];
204204
const keyLabels = publicKeyLabels(activeAgents);
205-
if (!items.length && !activeAgents.length) return trigger;
205+
const hasActivity = items.length > 0 || activeAgents.length > 0;
206+
useEffect(() => {
207+
if (!hasActivity) setOpen(false);
208+
}, [hasActivity]);
206209
const stale = items.length > 0 && snapshot.freshness === "stale";
207210
return (
208211
<PopoverRoot
209212
modal={false}
210213
open={open}
211214
onOpenChange={(next, details) => {
215+
if (next && !hasActivity) return;
212216
if (details.reason === "trigger-press") {
213217
const mousePress =
214218
triggerPointerType.current === "mouse" &&
@@ -233,7 +237,7 @@ export function ChannelActivityPopover({
233237
>
234238
<PopoverTrigger
235239
render={trigger}
236-
openOnHover
240+
openOnHover={hasActivity}
237241
delay={250}
238242
closeDelay={150}
239243
onPointerDown={(event) => {

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,3 +463,23 @@ it.each(["ContextMenu", "F10"])(
463463
expect(onSelect).toHaveBeenCalledWith("child");
464464
},
465465
);
466+
467+
it.each(["Collapse sessions in Alpha", "Plan, session in Alpha"])(
468+
"retains focused %s across idle and working transitions",
469+
(name) => {
470+
const props = {
471+
...itemProps(owner().session, false),
472+
sessions: [
473+
{ id: "child", name: "Plan", channelType: "session" as const },
474+
],
475+
};
476+
const view = render(<ChannelSidebarItem {...props} />);
477+
const control = screen.getByRole("button", { name });
478+
control.focus();
479+
for (const working of [true, false]) {
480+
view.rerender(<ChannelSidebarItem {...props} working={working} />);
481+
expect(screen.getByRole("button", { name })).toBe(control);
482+
expect(control).toHaveFocus();
483+
}
484+
},
485+
);

‎src/bundled/channels/ChannelSidebarItem.tsx‎

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,19 @@ type ItemProps = {
6767
menuFinalFocus?: (channelId: string) => HTMLElement | false;
6868
};
6969

70-
function WorkingChannelSidebarItem(props: ItemProps) {
71-
const { channel, session } = props;
72-
// Only active rows subscribe; idle rows are numerous in large sidebars.
73-
const agentKeys = useSyncExternalStore(session.agentActivity.subscribe, () =>
74-
workingAgents(session.agentActivity.snapshot(), channel.id).join(","),
70+
// Keep the row mounted as activity starts and stops; only its subscriptions change.
71+
export const ChannelSidebarItem = memo(function ChannelSidebarItem(
72+
props: ItemProps,
73+
) {
74+
const { channel, session, working } = props;
75+
const agentKeys = useSyncExternalStore(
76+
working ? session.agentActivity.subscribe : noSubscribe,
77+
() =>
78+
working
79+
? workingAgents(session.agentActivity.snapshot(), channel.id).join(",")
80+
: "",
7581
);
76-
const agents = agentKeys ? agentKeys.split(",") : [];
82+
const agents = agentKeys ? agentKeys.split(",") : noAgents;
7783
const agentProfiles = useSyncExternalStore(
7884
agents.length ? session.profiles.subscribe : noSubscribe,
7985
agents.length ? session.profiles.snapshot : () => noProfiles,
@@ -85,22 +91,6 @@ function WorkingChannelSidebarItem(props: ItemProps) {
8591
agentProfiles={agentProfiles}
8692
/>
8793
);
88-
}
89-
90-
// Own the connected row inside the memo boundary. Selecting another channel
91-
// must not rebuild every unchanged row's controls and subscriptions.
92-
export const ChannelSidebarItem = memo(function ChannelSidebarItem(
93-
props: ItemProps,
94-
) {
95-
return props.working ? (
96-
<WorkingChannelSidebarItem {...props} />
97-
) : (
98-
<ChannelSidebarItemCore
99-
{...props}
100-
agents={noAgents}
101-
agentProfiles={noProfiles}
102-
/>
103-
);
10494
});
10595

10696
function ChannelSidebarItemCore({

‎src/bundled/channels/ChannelsPage.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -577,7 +577,9 @@ function ChannelWorkspace({
577577
if (
578578
activity &&
579579
activity.channelId === requestedChannel &&
580-
activity.rootId === requestedThread
580+
activity.messageId === requestedMessage &&
581+
activity.entryId === navigation?.entryId &&
582+
!activity.signal.aborted
581583
) {
582584
threadTrigger.current = activity.trigger;
583585
handoff.activityThread.current = undefined;
@@ -602,7 +604,6 @@ function ChannelWorkspace({
602604
requestedMessage,
603605
navigation,
604606
requestedChannel,
605-
requestedThread,
606607
open,
607608
handoff?.activityThread,
608609
handoff?.activityAgent,

‎src/features/channel-navigation/ChannelNavigationState.test.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,9 @@ it("resets transient handoffs and rejects retired callbacks on session replaceme
107107
const retired = view.result.current;
108108
retired.activityThread.current = {
109109
channelId: "channel",
110-
rootId: "root",
110+
messageId: "root",
111+
entryId: "visit",
112+
signal: new AbortController().signal,
111113
trigger: null,
112114
};
113115
retired.activityAgent.current = {

‎src/features/channel-navigation/ChannelNavigationState.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ type State = {
3131
};
3232
type ActivityThread = {
3333
channelId: string;
34-
rootId: string;
34+
messageId: string;
35+
entryId: string;
36+
signal: AbortSignal;
3537
trigger: HTMLElement | null;
3638
};
3739
type ActivityAgent = {

‎src/features/channel-navigation/ChannelSidebar.tsx‎

Lines changed: 42 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -498,58 +498,70 @@ function ReadySidebar({
498498
scope,
499499
],
500500
);
501-
const openActivityThread = useCallback(
502-
(channelId: string, rootId: string) => {
501+
const openActivityMessage = useCallback(
502+
(
503+
channelId: string,
504+
messageId: string | undefined,
505+
threadRootId?: string,
506+
) => {
503507
if (!viewer || relay.snapshot().session !== queries) return;
504-
if (handoff)
505-
handoff.activityThread.current = {
506-
channelId,
507-
rootId,
508-
trigger:
509-
sidebar.list.current?.querySelector<HTMLElement>(
510-
`[data-channel-id="${CSS.escape(channelId)}"]`,
511-
) ?? null,
512-
};
513-
void navigator.open({
508+
const trigger =
509+
sidebar.list.current?.querySelector<HTMLElement>(
510+
`[data-channel-id="${CSS.escape(channelId)}"]`,
511+
) ?? null;
512+
const result = navigator.open({
514513
version: 1,
515514
kind: "conversation",
516515
channelId,
517-
messageId: rootId,
518-
threadRootId: rootId,
516+
...(messageId ? { messageId } : {}),
517+
...(threadRootId ? { threadRootId } : {}),
519518
scope: {
520519
viewer,
521520
communityOrigin: scope.slice(0, -(viewer.length + 1)),
522521
},
523522
});
523+
const { attempt } = navigator.snapshot();
524+
const target = attempt.entry.target;
525+
if (
526+
handoff &&
527+
messageId &&
528+
target.kind === "conversation" &&
529+
target.channelId === channelId &&
530+
target.messageId === messageId
531+
) {
532+
const intent = {
533+
channelId,
534+
messageId,
535+
trigger,
536+
entryId: attempt.entry.id,
537+
signal: attempt.signal,
538+
};
539+
handoff.activityThread.current = intent;
540+
void result.then(() => {
541+
if (handoff.activityThread.current === intent)
542+
handoff.activityThread.current = undefined;
543+
});
544+
}
524545
},
525546
[viewer, relay, queries, handoff, sidebar.list, navigator, scope],
526547
);
548+
const openActivityThread = useCallback(
549+
(channelId: string, rootId: string) =>
550+
openActivityMessage(channelId, rootId, rootId),
551+
[openActivityMessage],
552+
);
527553
const openWorkingAgent = useCallback(
528554
(channelId: string, _agent: string, messageId: string | undefined) => {
529-
if (!viewer || relay.snapshot().session !== queries) return;
530555
const root =
531556
messageId &&
532557
channels.find((channel) => channel.id === channelId)?.channelType !==
533558
"session" &&
534559
queries.channels
535560
.window(channelId)
536561
.rows.some((row) => row.id === messageId && !row.threadRootId);
537-
if (root) {
538-
openActivityThread(channelId, messageId);
539-
return;
540-
}
541-
void navigator.open({
542-
version: 1,
543-
kind: "conversation",
544-
channelId,
545-
...(messageId ? { messageId } : {}),
546-
scope: {
547-
viewer,
548-
communityOrigin: scope.slice(0, -(viewer.length + 1)),
549-
},
550-
});
562+
openActivityMessage(channelId, messageId, root ? messageId : undefined);
551563
},
552-
[viewer, relay, queries, channels, openActivityThread, navigator, scope],
564+
[queries, channels, openActivityMessage],
553565
);
554566
const openAgentActivity = useCallback(
555567
(channelId: string, agent: string) => {
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import { test, expect } from "./fixture.mjs";
2+
import { open } from "./timeline.mjs";
3+
import { generateSecretKey } from "nostr-tools";
4+
5+
test.use({
6+
productionBroker: true,
7+
readState: true,
8+
threadUnread: true,
9+
exactMessages: true,
10+
pluginFixtures: true,
11+
historyCounts: { alpha: 80, beta: 1 },
12+
});
13+
14+
const activity = (kind, messageId) => ({
15+
kind,
16+
seq: 1,
17+
timestamp: new Date().toISOString(),
18+
channelId: "alpha",
19+
sessionId: "S",
20+
turnId: "focus-test",
21+
...(messageId ? { payload: { triggeringEventIds: [messageId] } } : {}),
22+
});
23+
24+
test("mark-read retains focus through a gated storage failure, working transitions, and last-item retry", async ({
25+
page,
26+
app,
27+
}) => {
28+
await open(page, app);
29+
const row = page.locator('button[data-channel-id="alpha"]');
30+
const popup = page.getByRole("dialog", { name: "Activity in Alpha" });
31+
await expect(row.getByRole("img", { name: /unread threads?/ })).toBeVisible();
32+
await row.focus();
33+
const originalRow = await row.elementHandle();
34+
await row.press("Enter");
35+
await expect(popup).toBeVisible();
36+
const markRead = popup.getByRole("button", {
37+
name: /Mark thread from .+ as read/,
38+
});
39+
await expect(markRead).toHaveCount(1);
40+
await markRead.focus();
41+
const originalAction = await markRead.elementHandle();
42+
// Keep the real IndexedDB transaction alive until the test aborts it.
43+
await page.evaluate(() => {
44+
const transaction = IDBDatabase.prototype.transaction;
45+
IDBDatabase.prototype.transaction = function (...args) {
46+
const tx = transaction.apply(this, args);
47+
if (this.name === "buzz-read-state-v1" && args[1] === "readwrite") {
48+
IDBDatabase.prototype.transaction = transaction;
49+
let held = true;
50+
const keepAlive = () => {
51+
if (held)
52+
tx.objectStore("partitions").get("focus-test-gate").onsuccess =
53+
keepAlive;
54+
};
55+
keepAlive();
56+
window.abortFocusWrite = () => {
57+
held = false;
58+
tx.abort();
59+
};
60+
}
61+
return tx;
62+
};
63+
});
64+
await markRead.press("Enter");
65+
await expect
66+
.poll(() => page.evaluate(() => !!window.abortFocusWrite))
67+
.toBe(true);
68+
await expect(markRead).toHaveAttribute("aria-disabled", "true");
69+
await expect(markRead).toBeFocused();
70+
await page.evaluate(() => window.abortFocusWrite());
71+
await expect(popup.getByRole("alert")).toContainText("Try again");
72+
await expect(markRead).toBeFocused();
73+
74+
await expect.poll(() => app.relay.hasRoute("primary", "observer")).toBe(true);
75+
const key = generateSecretKey();
76+
app.observer(activity("turn_started"), key);
77+
await expect(
78+
row.getByRole("img", { name: /working in Alpha/ }),
79+
).toBeVisible();
80+
await expect(popup.getByRole("alert")).toBeVisible();
81+
await expect(markRead).toBeFocused();
82+
app.observer(activity("turn_completed"), key);
83+
await expect(row.getByRole("img", { name: /working in Alpha/ })).toHaveCount(
84+
0,
85+
);
86+
await expect(popup.getByRole("alert")).toBeVisible();
87+
await expect(markRead).toBeFocused();
88+
expect(await originalAction.evaluate((node) => node.isConnected)).toBe(true);
89+
await markRead.press("Enter");
90+
await expect(popup).toHaveCount(0);
91+
await expect(row).toBeFocused();
92+
expect(await originalRow.evaluate((node) => node.isConnected)).toBe(true);
93+
});
94+
95+
for (const destination of ["reply", "off-window root"]) {
96+
test(`working ${destination} returns focus to the originating sidebar row`, async ({
97+
page,
98+
app,
99+
}) => {
100+
await open(page, app);
101+
await expect
102+
.poll(() => app.relay.hasRoute("primary", "observer"))
103+
.toBe(true);
104+
const target = destination === "reply" ? app.exact.target : app.exact.root;
105+
await expect(
106+
page.locator(`[data-channel-timeline] [data-message-id="${target.id}"]`),
107+
).toHaveCount(0);
108+
const key = generateSecretKey();
109+
app.observer(activity("turn_started", target.id), key);
110+
const row = page.locator('button[data-channel-id="alpha"]');
111+
await expect(
112+
row.getByRole("img", { name: /working in Alpha/ }),
113+
).toBeVisible();
114+
await row.focus();
115+
await row.press("Enter");
116+
const popup = page.getByRole("dialog", { name: "Activity in Alpha" });
117+
const action = popup.getByRole("button", { name: /Open thread for/ });
118+
await action.focus();
119+
await action.press("Enter");
120+
const panel = page.getByRole("complementary", {
121+
name: "Thread",
122+
exact: true,
123+
});
124+
await expect(panel).toBeVisible();
125+
const close = panel.getByRole("button", {
126+
name: "Close thread",
127+
exact: true,
128+
});
129+
await close.focus();
130+
await close.press(destination === "reply" ? "Escape" : "Enter");
131+
await expect(panel).toHaveCount(0);
132+
await expect(row).toBeFocused();
133+
});
134+
}

0 commit comments

Comments
 (0)