The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 18:30 UTC
fix(web): restore composer focus when returning to a thread (#29179)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Lakshmi Tanmay committed
Nov 13, 2026 at 04:21 UTC
05089062d4df32cc9a4f5969911122e9808ac0c5
7 files changed
+262
-41
apps/web/src/components/ChatView.tsx
+5
-11
@@ -217,7 +217,7 @@ import { usePanelAnimationSettings, usePanelPresence } from "../panelAnimations"
217
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
218
import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
219
import { isPreviewFocused } from "../lib/previewFocus";
220
-import { focusTerminalOnThreadEnter, getTerminalFocusOwner } from "../lib/terminalFocus";
220
+import { getTerminalFocusOwner } from "../lib/terminalFocus";
221
import {
222
deriveLogicalProjectKeyFromSettings,
223
selectProjectGroupingSettings,
@@ -2142,8 +2142,10 @@ export default function ChatView(props: ChatViewProps) {
2142
});
2143
2144
useFocusComposerOnThreadOpen(
2145
- activeThread?.id,
2146
- !embedded && !terminalUiState.terminalOpen,
2145
+ activeThreadRef,
2146
+ workspaceLayoutElement,
2147
+ !embedded,
2148
+ terminalUiState.terminalOpen,
2149
focusComposerStable,
2150
);
2151
@@ -2680,14 +2682,6 @@ export default function ChatView(props: ChatViewProps) {
2682
setTerminalUiLaunchContext(null);
2683
}
2684
2683
- // Entering a thread with its drawer open focuses the drawer terminal; opening
2684
- // it from a handler requests focus there. A closed drawer leaves focus to the
2685
- // composer effect above.
2686
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- focuses the open drawer terminal when entering a thread
2687
- useEffect(() => {
2688
- if (activeThreadRef && !embedded) return focusTerminalOnThreadEnter(activeThreadRef);
2689
- }, [activeThreadRef, embedded]);
2690
-
2685
const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({
2686
terminalFocus: getTerminalFocusOwner() !== null,
2687
terminalOpen: Boolean(terminalUiState.terminalOpen),
apps/web/src/components/ThreadTerminalDrawer.tsx
+1
@@ -1111,6 +1111,7 @@ function TerminalSessionViewport({
1111
const unregister = registerTerminalFocusTarget({
1112
threadRef,
1113
terminalId,
1114
+ element: mount,
1115
focus,
1116
});
1117
return () => {
apps/web/src/components/chat/useFocusComposerOnThreadOpen.browser.test.tsx
+13
-4
@@ -1,4 +1,6 @@
1
-import { useRef } from "react";
1
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3
+import { useRef, useState } from "react";
4
import { expect, it, vi } from "vite-plus/test";
5
6
import { act, fakeTimers, render } from "../../../test/render";
@@ -6,14 +8,21 @@ import { useFocusComposerOnThreadOpen } from "./useFocusComposerOnThreadOpen";
8
9
function ThreadProbe(props: { threadId: string }) {
10
const composerRef = useRef<HTMLTextAreaElement>(null);
9
- useFocusComposerOnThreadOpen(props.threadId, true, () => composerRef.current?.focus());
11
+ const [root, setRoot] = useState<HTMLDivElement | null>(null);
12
+ useFocusComposerOnThreadOpen(
13
+ scopeThreadRef(EnvironmentId.make("rename"), ThreadId.make(props.threadId)),
14
+ root,
15
+ true,
16
+ false,
17
+ () => composerRef.current?.focus(),
18
+ );
19
return (
11
- <>
20
+ <div ref={setRoot}>
21
<div data-sidebar-row="thread:beta">
22
<input aria-label="Thread title" />
23
</div>
24
<textarea aria-label="Message" ref={composerRef} />
16
- </>
25
+ </div>
26
);
27
}
28
apps/web/src/components/chat/useFocusComposerOnThreadOpen.ts
+29
-10
@@ -1,21 +1,40 @@
1
+import type { ScopedThreadRef } from "@t3tools/contracts";
2
import { useEffect } from "react";
3
3
-/** Lands the caret in the composer a frame after a thread opens. */
4
+import { restoreFocusOnThreadEnter } from "../../lib/terminalFocus";
5
+
6
+/** Restores thread focus, landing the caret a frame after composer entry. */
7
export function useFocusComposerOnThreadOpen(
5
- threadId: string | undefined,
8
+ threadRef: ScopedThreadRef | null,
9
+ root: HTMLElement | null,
10
enabled: boolean,
11
+ terminalOpen: boolean,
12
focusComposer: () => void,
13
) {
9
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- schedules a frame to focus the composer DOM element when a thread opens with the terminal closed
14
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores DOM focus on thread entry and after the drawer opens or closes
15
useEffect(() => {
11
- if (!threadId || !enabled) return;
12
- const frame = window.requestAnimationFrame(() => {
13
- // Double-clicking a sidebar row opens its thread and its rename field in one gesture.
14
- if (document.activeElement?.matches("[data-sidebar-row] input")) return;
15
- focusComposer();
16
+ if (!threadRef || !enabled || !root) return;
17
+ let frame: number | undefined;
18
+ const leave = restoreFocusOnThreadEnter(threadRef, {
19
+ root,
20
+ focusComposer: () => {
21
+ frame = window.requestAnimationFrame(() => {
22
+ // Double-clicking a sidebar row opens its thread and its rename field in one gesture.
23
+ if (document.activeElement?.matches("[data-sidebar-row] input")) return;
24
+ focusComposer();
25
+ });
26
+ },
27
});
28
return () => {
18
- window.cancelAnimationFrame(frame);
29
+ leave();
30
+ if (frame !== undefined) window.cancelAnimationFrame(frame);
31
};
20
- }, [threadId, enabled, focusComposer]);
32
+ }, [
33
+ threadRef,
34
+ root,
35
+ enabled,
36
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Drawer visibility changes also restore focus after explicit open/close actions.
37
+ terminalOpen,
38
+ focusComposer,
39
+ ]);
40
}
apps/web/src/lib/terminalFocus.browser.test.ts
+145
@@ -2,11 +2,16 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3
import { describe, expect, it } from "vite-plus/test";
4
5
+import { useRightPanelStore } from "../rightPanelStore";
6
+import { useTerminalUiStateStore } from "../terminalUiStateStore";
7
+
8
import {
9
consumePendingTerminalFocus,
10
focusTerminal,
11
+ focusTerminalOnNavigation,
12
focusTerminalViewport,
13
registerTerminalFocusTarget,
14
+ restoreFocusOnThreadEnter,
15
} from "./terminalFocus";
16
17
// The drawer's collapsed shape: a 0fr grid row that clips the viewport, which
@@ -57,3 +62,143 @@ describe("focusTerminalViewport", () => {
62
expect(document.activeElement).toBe(viewport.input);
63
});
64
});
65
+
66
+function enterOtherThread(threadId: string) {
67
+ restoreFocusOnThreadEnter(scopeThreadRef(EnvironmentId.make("env"), ThreadId.make(threadId)), {
68
+ root: document.createElement("div"),
69
+ focusComposer: () => {},
70
+ })();
71
+}
72
+
73
+function mountThread(threadId: string, environmentId = "env") {
74
+ const ref = scopeThreadRef(EnvironmentId.make(environmentId), ThreadId.make(threadId));
75
+ const root = document.createElement("div");
76
+ const composer = document.createElement("textarea");
77
+ composer.ariaLabel = "Composer";
78
+ composer.dataset.workspaceArea = "composer";
79
+ root.append(composer);
80
+ document.body.append(root);
81
+ const drawerState = { visible: true };
82
+ const mountTerminal = (id: string) => {
83
+ const input = document.createElement("textarea");
84
+ input.ariaLabel = id;
85
+ root.append(input);
86
+ const unregister = registerTerminalFocusTarget({
87
+ threadRef: ref,
88
+ terminalId: id,
89
+ element: input,
90
+ focus: () => {
91
+ if (id === "drawer" && !drawerState.visible) return false;
92
+ input.focus();
93
+ return document.activeElement === input;
94
+ },
95
+ });
96
+ return {
97
+ input,
98
+ [Symbol.dispose]() {
99
+ unregister();
100
+ input.remove();
101
+ },
102
+ };
103
+ };
104
+ useTerminalUiStateStore.getState().ensureTerminal(ref, "drawer", { open: true, active: true });
105
+ useRightPanelStore.getState().openTerminal(ref, "panel");
106
+ return {
107
+ ref,
108
+ root,
109
+ composer,
110
+ drawerState,
111
+ mountTerminal,
112
+ enter: () => restoreFocusOnThreadEnter(ref, { root, focusComposer: () => composer.focus() }),
113
+ [Symbol.dispose]: () => root.remove(),
114
+ };
115
+}
116
+
117
+describe("thread focus restoration", () => {
118
+ it.each(["composer", "drawer", "panel", "remounted composer"] as const)(
119
+ "restores %s focus when returning to a thread with both terminals open",
120
+ (control) => {
121
+ using thread = mountThread(`return-${control}`);
122
+ using drawer = thread.mountTerminal("drawer");
123
+ using panel = thread.mountTerminal("panel");
124
+ const leave = thread.enter();
125
+ if (control === "panel") document.body.append(panel.input);
126
+ const remount = control === "remounted composer";
127
+ const initial =
128
+ control === "composer" || remount
129
+ ? thread.composer
130
+ : control === "drawer"
131
+ ? drawer.input
132
+ : panel.input;
133
+ initial.focus();
134
+ expect(document.activeElement).toBe(initial);
135
+ if (remount) focusTerminal(thread.ref, "not-ready");
136
+ leave();
137
+ thread.root.hidden = true;
138
+ if (!remount) enterOtherThread("other-thread");
139
+ drawer[Symbol.dispose]();
140
+ panel[Symbol.dispose]();
141
+ if (remount) thread.root.remove();
142
+ using remountedThread = remount ? mountThread(`return-${control}`) : undefined;
143
+ const returnedThread = remountedThread ?? thread;
144
+ returnedThread.root.hidden = false;
145
+ using remountedDrawer = returnedThread.mountTerminal("drawer");
146
+ using remountedPanel = returnedThread.mountTerminal("panel");
147
+ if (control === "panel") document.body.append(remountedPanel.input);
148
+ using _leave = { [Symbol.dispose]: returnedThread.enter() };
149
+ const expected =
150
+ control === "composer" || remount
151
+ ? returnedThread.composer
152
+ : control === "drawer"
153
+ ? remountedDrawer.input
154
+ : remountedPanel.input;
155
+
156
+ expect(document.activeElement).toBe(expected);
157
+ },
158
+ );
159
+
160
+ it("keeps an explicit terminal navigation request ahead of remembered composer focus", () => {
161
+ using thread = mountThread("explicit-reveal");
162
+ using _drawer = thread.mountTerminal("drawer");
163
+ using panel = thread.mountTerminal("panel");
164
+ const leave = thread.enter();
165
+ thread.composer.focus();
166
+ leave();
167
+ enterOtherThread("before-reveal");
168
+
169
+ focusTerminalOnNavigation(thread.ref, "panel");
170
+ using _leave = { [Symbol.dispose]: thread.enter() };
171
+
172
+ expect(document.activeElement).toBe(panel.input);
173
+ });
174
+
175
+ it("keeps an explicit drawer-open request while its viewport becomes visible", () => {
176
+ using thread = mountThread("drawer-open");
177
+ using drawer = thread.mountTerminal("drawer");
178
+ const leave = thread.enter();
179
+ thread.composer.focus();
180
+ thread.drawerState.visible = false;
181
+ useTerminalUiStateStore.getState().setTerminalOpen(thread.ref, false);
182
+ focusTerminal(thread.ref, "drawer");
183
+ useTerminalUiStateStore.getState().setTerminalOpen(thread.ref, true);
184
+ leave();
185
+ using _leave = { [Symbol.dispose]: thread.enter() };
186
+ thread.drawerState.visible = true;
187
+ consumePendingTerminalFocus(thread.ref, "drawer");
188
+
189
+ expect(document.activeElement).toBe(drawer.input);
190
+ });
191
+
192
+ it("falls back to the composer when the remembered drawer terminal was closed", () => {
193
+ using thread = mountThread("closed-remembered");
194
+ using drawer = thread.mountTerminal("drawer");
195
+ const leave = thread.enter();
196
+ expect(document.activeElement).toBe(drawer.input);
197
+ leave();
198
+ useTerminalUiStateStore.getState().setTerminalOpen(thread.ref, false);
199
+ thread.drawerState.visible = false;
200
+ using _leave = { [Symbol.dispose]: thread.enter() };
201
+
202
+ expect(document.activeElement).toBe(thread.composer);
203
+ });
204
+});
apps/web/src/lib/terminalFocus.test.ts
+16
-7
@@ -11,13 +11,22 @@ import {
11
focusPanelTerminalAfterClose,
12
focusTerminal,
13
focusTerminalOnNavigation,
14
- focusTerminalOnThreadEnter,
14
registerTerminalFocusTarget,
15
+ restoreFocusOnThreadEnter,
16
} from "./terminalFocus";
17
18
const threadRef = (threadId: string) =>
19
scopeThreadRef(EnvironmentId.make("env"), ThreadId.make(threadId));
20
21
+// Node has no DOM; entry only listens on the root's document for focus changes.
22
+const enterThread = (ref: ReturnType<typeof threadRef>) =>
23
+ restoreFocusOnThreadEnter(ref, {
24
+ root: {
25
+ ownerDocument: Object.assign(new EventTarget(), { activeElement: null }),
26
+ } as unknown as HTMLElement,
27
+ focusComposer: () => {},
28
+ });
29
+
30
describe("focusTerminal", () => {
31
it("focuses a mounted target right away", () => {
32
const ref = threadRef("mounted");
@@ -173,7 +182,7 @@ describe("focusTerminal", () => {
182
const focus = vi.fn(() => true);
183
const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });
184
176
- const leave = focusTerminalOnThreadEnter(ref);
185
+ const leave = enterThread(ref);
186
187
expect(focus).toHaveBeenCalledTimes(1);
188
leave();
@@ -199,7 +208,7 @@ describe("focusTerminal", () => {
208
terminalId: "panel",
209
focus: panel,
210
});
202
- const leave = focusTerminalOnThreadEnter(ref);
211
+ const leave = enterThread(ref);
212
213
expect(drawer).not.toHaveBeenCalled();
214
expect(panel).toHaveBeenCalledTimes(1);
@@ -218,12 +227,12 @@ describe("focusTerminal", () => {
227
focus: drawer,
228
});
229
221
- const leaveFirst = focusTerminalOnThreadEnter(ref);
230
+ const leaveFirst = enterThread(ref);
231
focusTerminal(ref, "drawer");
232
focusTerminalOnNavigation(ref, "drawer");
233
leaveFirst();
234
drawer.mockClear();
226
- const leaveSecond = focusTerminalOnThreadEnter(ref);
235
+ const leaveSecond = enterThread(ref);
236
237
expect(drawer).toHaveBeenCalledTimes(1);
238
leaveSecond();
@@ -234,7 +243,7 @@ describe("focusTerminal", () => {
243
const ref = threadRef("revisited");
244
useTerminalUiStateStore.getState().ensureTerminal(ref, "drawer", { open: true, active: true });
245
focusTerminalOnNavigation(ref, "panel");
237
- focusTerminalOnThreadEnter(threadRef("elsewhere"))();
246
+ enterThread(threadRef("elsewhere"))();
247
248
const drawer = vi.fn(() => true);
249
const unregisterDrawer = registerTerminalFocusTarget({
@@ -242,7 +251,7 @@ describe("focusTerminal", () => {
251
terminalId: "drawer",
252
focus: drawer,
253
});
245
- const leave = focusTerminalOnThreadEnter(ref);
254
+ const leave = enterThread(ref);
255
256
expect(drawer).toHaveBeenCalledTimes(1);
257
leave();
apps/web/src/lib/terminalFocus.ts
+53
-9
@@ -31,11 +31,13 @@ export function subscribeToTerminalFocusChanges(listener: () => void): () => voi
31
interface TerminalFocusTarget {
32
readonly threadRef: ScopedThreadRef;
33
readonly terminalId: string;
34
+ readonly element?: HTMLElement;
35
/** Returns false when the target cannot take focus yet (hidden, or no operate grant). */
36
readonly focus: () => boolean;
37
}
38
39
const focusTargets = new Set<TerminalFocusTarget>();
40
+const lastThreadFocus = new Map<string, "composer" | { terminalId: string }>();
41
// One request at a time: the newest terminal the user asked for wins, so an
42
// older request never fires later and steals focus.
43
let pendingFocus: { readonly threadKey: string; readonly terminalId: string } | null = null;
@@ -44,6 +46,8 @@ let pendingFocus: { readonly threadKey: string; readonly terminalId: string } |
46
// thread's viewports mount and consume the handler's request in the commit's
47
// layout phase, before ChatView's thread-enter effect runs.
48
let enteredThreadKey: string | null = null;
49
+// Drawer visibility reruns reuse the root; a remounted chat must not inherit parked requests.
50
+const lastEnteredThreadByRoot = new WeakMap<HTMLElement, string>();
51
let navigationRequestThreadKey: string | null = null;
52
53
function isPending(threadKey: string, terminalId: string): boolean {
@@ -122,24 +126,64 @@ export function focusTerminalOnNavigation(threadRef: ScopedThreadRef, terminalId
126
focusTerminal(threadRef, terminalId);
127
}
128
125
-/**
126
- * Entering a thread with its drawer open focuses the drawer terminal, unless a
127
- * navigating handler already asked for a terminal there. Returns the leave
128
- * cleanup for ChatView's effect.
129
- */
130
-export function focusTerminalOnThreadEnter(threadRef: ScopedThreadRef): () => void {
129
+/** Restores composer or terminal focus; explicit terminal navigation takes precedence. */
130
+export function restoreFocusOnThreadEnter(
131
+ threadRef: ScopedThreadRef,
132
+ content: { readonly root: HTMLElement; readonly focusComposer: () => void },
133
+): () => void {
134
const threadKey = scopedThreadKey(threadRef);
132
- const requestedByHandler = navigationRequestThreadKey === threadKey;
135
+ const requestedByHandler =
136
+ navigationRequestThreadKey === threadKey ||
137
+ (lastEnteredThreadByRoot.get(content.root) === threadKey &&
138
+ pendingFocus?.threadKey === threadKey);
139
+ if (!requestedByHandler) pendingFocus = null;
140
+ lastEnteredThreadByRoot.set(content.root, threadKey);
141
navigationRequestThreadKey = null;
142
enteredThreadKey = threadKey;
143
+ const previous = lastThreadFocus.get(threadKey);
144
+ const remember = () => {
145
+ const element = content.root.ownerDocument.activeElement;
146
+ if (!element) return;
147
+ const terminal = Array.from(focusTargets).find((target) => target.element?.contains(element));
148
+ if (terminal) {
149
+ if (scopedThreadKey(terminal.threadRef) === threadKey)
150
+ lastThreadFocus.set(threadKey, { terminalId: terminal.terminalId });
151
+ } else if (
152
+ content.root.contains(element) &&
153
+ element.closest('[data-workspace-area="composer"]')
154
+ ) {
155
+ lastThreadFocus.set(threadKey, "composer");
156
+ }
157
+ };
158
+ content.root.ownerDocument.addEventListener("focusin", remember);
159
if (!requestedByHandler) {
136
- const { terminalOpen, activeTerminalId } = selectThreadTerminalUiState(
160
+ const drawer = selectThreadTerminalUiState(
161
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
162
threadRef,
163
);
140
- if (terminalOpen && activeTerminalId) focusTerminal(threadRef, activeTerminalId);
164
+ const panel = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadRef);
165
+ const panelTerminal = panel.isOpen
166
+ ? panel.surfaces.find((surface) => surface.id === panel.activeSurfaceId)
167
+ : null;
168
+ if (previous === "composer") {
169
+ content.focusComposer();
170
+ } else if (
171
+ previous &&
172
+ ((drawer.terminalOpen &&
173
+ drawer.terminalGroups
174
+ .find((group) => group.id === drawer.activeTerminalGroupId)
175
+ ?.terminalIds.includes(previous.terminalId)) ||
176
+ (panelTerminal?.kind === "terminal" &&
177
+ panelTerminal.terminalIds.includes(previous.terminalId)))
178
+ ) {
179
+ focusTerminal(threadRef, previous.terminalId);
180
+ } else if (drawer.terminalOpen && drawer.activeTerminalId) {
181
+ focusTerminal(threadRef, drawer.activeTerminalId);
182
+ } else content.focusComposer();
183
}
184
+ if (requestedByHandler) remember();
185
return () => {
186
+ content.root.ownerDocument.removeEventListener("focusin", remember);
187
// A handler navigating elsewhere marks its target before this cleanup runs.
188
if (enteredThreadKey === threadKey) enteredThreadKey = null;
189
};