Skip to content

Commit fb1d8c9

Browse files
fix(ui): preserve composer focus after menu close
1 parent b528f6c commit fb1d8c9

3 files changed

Lines changed: 196 additions & 8 deletions

File tree

‎ui/src/pages/chat/chat-page.test.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import { insertPane, type ChatSplitLayout } from "./split-layout.ts";
5151

5252
type RenderedPane = HTMLElement & {
5353
paneId: string;
54+
focusComposer: boolean;
5455
chatMessagesBySession: ChatMessageCache;
5556
sessionKey: string;
5657
active: boolean;
@@ -258,6 +259,62 @@ describe("chat page split layout host", () => {
258259
expect(typeof itemAt(panes, 0, "rendered pane").onOpenSplitView).toBe("function");
259260
});
260261

262+
it("hands route-owned focus to the final page across pane replacement", async () => {
263+
const sourcePage = new ChatPage();
264+
setNavigationContext(sourcePage);
265+
sourcePage.data = {
266+
sessionKey: "main",
267+
draft: "What can you do?",
268+
focusComposer: true,
269+
};
270+
const page = new ChatPage();
271+
setNavigationContext(page);
272+
page.data = { sessionKey: "main" };
273+
274+
vi.useFakeTimers();
275+
try {
276+
document.body.append(sourcePage);
277+
await sourcePage.updateComplete;
278+
await Promise.resolve();
279+
280+
document.body.append(page);
281+
await page.updateComplete;
282+
const pane = itemAt(page.querySelectorAll<RenderedPane>("openclaw-chat-pane"), 0, "pane");
283+
expect(pane.focusComposer).toBe(true);
284+
285+
const combobox = document.createElement("div");
286+
combobox.className = "agent-chat__composer-combobox";
287+
const textarea = document.createElement("textarea");
288+
combobox.append(textarea);
289+
pane.append(combobox);
290+
vi.advanceTimersByTime(250);
291+
expect(document.activeElement).toBe(textarea);
292+
293+
const replacementPane = document.createElement("openclaw-chat-pane") as RenderedPane;
294+
replacementPane.active = true;
295+
replacementPane.sessionKey = "main";
296+
const replacementCombobox = document.createElement("div");
297+
replacementCombobox.className = "agent-chat__composer-combobox";
298+
const replacementTextarea = document.createElement("textarea");
299+
replacementCombobox.append(replacementTextarea);
300+
replacementPane.append(replacementCombobox);
301+
pane.replaceWith(replacementPane);
302+
303+
vi.advanceTimersByTime(250);
304+
expect(document.activeElement).toBe(replacementTextarea);
305+
306+
const userTarget = document.createElement("button");
307+
document.body.append(userTarget);
308+
userTarget.focus();
309+
vi.advanceTimersByTime(250);
310+
expect(document.activeElement).toBe(userTarget);
311+
} finally {
312+
sourcePage.remove();
313+
page.remove();
314+
vi.useRealTimers();
315+
}
316+
});
317+
261318
it("passes the chat-owned gateway capability only to the rightmost pane", async () => {
262319
const gatewaySnapshot: NativeGatewaysSnapshot = {
263320
gateways: [],

‎ui/src/pages/chat/chat-page.ts‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { stillOwnsCanonicalLocation } from "./chat-canonical-location.ts";
2323
import { ChatViewerPresenceController } from "./chat-viewer-presence.ts";
2424
import "../../styles/chat.css";
2525
import "./chat-pane.ts";
26+
import { RouteDraftComposerFocus, type ChatPaneElement } from "./route-draft-focus-handoff.ts";
2627
import { routeDraft } from "./route-draft.ts";
2728
import { locationWithoutDraft, type SessionChatRouteData } from "./route-loader.ts";
2829
import type { ChatMessageCache } from "./session-message-cache.ts";
@@ -51,8 +52,6 @@ import {
5152
} from "./split-layout.ts";
5253

5354
type DropIndicator = { paneId: string; zone: SplitDropZone; rect: SplitDropRect };
54-
type ChatPaneElement = HTMLElement & { paneId?: string; sessionKey?: string };
55-
5655
export class ChatPage extends OpenClawLightDomElement {
5756
@consume({ context: applicationContext, subscribe: true })
5857
private context!: ApplicationContext;
@@ -78,6 +77,7 @@ export class ChatPage extends OpenClawLightDomElement {
7877
private dragFrame = 0;
7978
private pendingDragOver: { pane: ChatPaneElement; x: number; y: number } | null = null;
8079
private consumedDraftData: SessionChatRouteData | null = null;
80+
private readonly draftFocus = new RouteDraftComposerFocus(this);
8181
private readonly chatMessagesBySession: ChatMessageCache = new Map();
8282
private classicColumnId = "c1";
8383
private classicPaneId = "p1";
@@ -129,10 +129,8 @@ export class ChatPage extends OpenClawLightDomElement {
129129
}
130130
const data = this.data;
131131
const activePane = this.layout ? findPane(this.layout, this.layout.activePaneId)?.pane : null;
132-
const routeDraftWasRendered =
133-
Boolean(data?.draft) &&
134-
this.consumedDraftData !== data &&
135-
(!this.layout || activePane?.sessionKey === data.sessionKey);
132+
const activeSessionKey = this.layout ? (activePane?.sessionKey ?? null) : undefined;
133+
const draftRendered = this.draftFocus.rendered(data, activeSessionKey, this.consumedDraftData);
136134
if (changedProperties.has("data")) {
137135
if (
138136
data?.canonicalLocation &&
@@ -161,10 +159,11 @@ export class ChatPage extends OpenClawLightDomElement {
161159
this.syncRouteAgent();
162160
this.syncRouteToActivePane();
163161
}
164-
if (data && routeDraftWasRendered) {
162+
if (data && draftRendered) {
165163
// Process the route draft once so later focus changes cannot hand it to another pane.
166164
queueMicrotask(() => {
167165
if (this.isConnected && this.data === data && this.consumedDraftData !== data) {
166+
this.draftFocus.beforeDraftCleanup(data);
168167
this.consumedDraftData = data;
169168
// Remove the one-shot draft from history once the matching pane owns it.
170169
this.updateRoute(data.sessionKey, true, data.face ?? "chat");
@@ -554,7 +553,7 @@ export class ChatPage extends OpenClawLightDomElement {
554553
const draft = active
555554
? routeDraft(this.data, this.consumedDraftData, pane.sessionKey)
556555
: undefined;
557-
const focus = Boolean(draft && this.data?.focusComposer);
556+
const focus = this.draftFocus.shouldFocusPane(active, draft, pane.sessionKey, this.data);
558557
// Resolve aliases like the pane does so renamed sessions keep their display title.
559558
const resolvedKey =
560559
resolveSessionKey(pane.sessionKey, this.context?.gateway?.snapshot?.hello) || pane.sessionKey;
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import { areUiSessionKeysEquivalent } from "../../lib/sessions/session-key.ts";
2+
import type { SessionChatRouteData } from "./route-loader.ts";
3+
4+
const HANDOFF_TTL_MS = 30_000;
5+
const MAINTENANCE_MS = 15_000;
6+
const RETRY_MS = 250;
7+
const COMPOSER_SELECTOR = ".agent-chat__composer-combobox textarea";
8+
9+
type PendingHandoff = {
10+
expiresAt: number;
11+
sessionKey: string;
12+
sourceData: SessionChatRouteData;
13+
};
14+
15+
export type ChatPaneElement = HTMLElement & {
16+
active?: boolean;
17+
paneId?: string;
18+
sessionKey?: string;
19+
};
20+
21+
let pendingHandoff: PendingHandoff | undefined;
22+
23+
function pendingMatches(sessionKey: string, data: SessionChatRouteData): boolean {
24+
if (!pendingHandoff) {
25+
return false;
26+
}
27+
if (pendingHandoff.expiresAt <= Date.now()) {
28+
pendingHandoff = undefined;
29+
return false;
30+
}
31+
return (
32+
pendingHandoff.sourceData !== data &&
33+
areUiSessionKeysEquivalent(pendingHandoff.sessionKey, sessionKey)
34+
);
35+
}
36+
37+
export class RouteDraftComposerFocus {
38+
private timer: number | undefined;
39+
private readonly host: HTMLElement;
40+
41+
constructor(host: HTMLElement) {
42+
this.host = host;
43+
}
44+
45+
rendered(
46+
data: SessionChatRouteData | undefined,
47+
activeSessionKey: string | null | undefined,
48+
consumedData: SessionChatRouteData | null,
49+
): boolean {
50+
const matchesActivePane = Boolean(
51+
data &&
52+
(activeSessionKey === undefined ||
53+
(activeSessionKey !== null &&
54+
areUiSessionKeysEquivalent(activeSessionKey, data.sessionKey))),
55+
);
56+
if (data && !data.draft && matchesActivePane && pendingMatches(data.sessionKey, data)) {
57+
pendingHandoff = undefined;
58+
this.maintain(data.sessionKey);
59+
}
60+
return Boolean(data?.draft && consumedData !== data && matchesActivePane);
61+
}
62+
63+
shouldFocusPane(
64+
active: boolean,
65+
hasDraft: unknown,
66+
sessionKey: string,
67+
data?: SessionChatRouteData,
68+
): boolean {
69+
return Boolean(
70+
active &&
71+
data &&
72+
((hasDraft && data.focusComposer) || (!hasDraft && pendingMatches(sessionKey, data))),
73+
);
74+
}
75+
76+
beforeDraftCleanup(data: SessionChatRouteData): void {
77+
if (!data.focusComposer) {
78+
return;
79+
}
80+
// Draft cleanup remounts the route page; carry the one-shot focus fact
81+
// to that final owner so focus does not die with this page instance.
82+
pendingHandoff = {
83+
expiresAt: Date.now() + HANDOFF_TTL_MS,
84+
sessionKey: data.sessionKey,
85+
sourceData: data,
86+
};
87+
}
88+
89+
private maintain(sessionKey: string): void {
90+
if (this.timer !== undefined) {
91+
window.clearTimeout(this.timer);
92+
this.timer = undefined;
93+
}
94+
const deadline = Date.now() + MAINTENANCE_MS;
95+
let ownedComposer: HTMLTextAreaElement | undefined;
96+
97+
const focusCurrentComposer = () => {
98+
if (!this.host.isConnected) {
99+
this.timer = undefined;
100+
return;
101+
}
102+
const pane = [...this.host.querySelectorAll<ChatPaneElement>("openclaw-chat-pane")].find(
103+
(candidate) =>
104+
candidate.active &&
105+
candidate.sessionKey !== undefined &&
106+
areUiSessionKeysEquivalent(candidate.sessionKey, sessionKey),
107+
);
108+
const composer = pane?.querySelector<HTMLTextAreaElement>(COMPOSER_SELECTOR);
109+
const activeElement = document.activeElement;
110+
const focusStillOwned =
111+
activeElement === ownedComposer ||
112+
activeElement === document.body ||
113+
(activeElement instanceof HTMLElement && !activeElement.isConnected);
114+
115+
if (composer && (!ownedComposer || focusStillOwned)) {
116+
composer.focus({ preventScroll: true });
117+
ownedComposer = composer;
118+
} else if (ownedComposer && !focusStillOwned) {
119+
this.timer = undefined;
120+
return;
121+
}
122+
123+
if (Date.now() < deadline) {
124+
this.timer = window.setTimeout(focusCurrentComposer, RETRY_MS);
125+
} else {
126+
this.timer = undefined;
127+
}
128+
};
129+
130+
focusCurrentComposer();
131+
}
132+
}

0 commit comments

Comments
 (0)