Skip to content
TypeScript

fix(web): composer regains focus when you tab back into T3 Code (#10463)

Theo Browneecf3716fd190
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index 1dd686cc803..537828e0e06 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -42,6 +42,7 @@ import {
getStartedThreadModelChangeBlockReason,
hasEnvironmentReconnectWarningGraceElapsed,
hasServerAcknowledgedLocalDispatch,
+ shouldRefocusComposerOnWindowFocus,
isBranchMismatchDismissedForSession,
reconcileMountedTerminalThreadIds,
reconcileRetainedMountedThreadIds,
@@ -1861,3 +1862,45 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
).toBe(true);
});
});
+
+describe("shouldRefocusComposerOnWindowFocus", () => {
+ function element(
+ tagName: string,
+ options?: { editable?: boolean; role?: string; within?: string },
+ ) {
+ return {
+ tagName,
+ isContentEditable: options?.editable ?? false,
+ getAttribute: (name: string) => (name === "role" ? (options?.role ?? null) : null),
+ closest: (selector: string) =>
+ options?.within !== undefined && selector.includes(options.within) ? ({} as Element) : null,
+ };
+ }
+
+ it("refocuses when nothing or the body holds focus", () => {
+ expect(shouldRefocusComposerOnWindowFocus(null)).toBe(true);
+ expect(shouldRefocusComposerOnWindowFocus(element("BODY"))).toBe(true);
+ });
+
+ it("refocuses away from a plain button, such as a pull request tab", () => {
+ expect(shouldRefocusComposerOnWindowFocus(element("BUTTON"))).toBe(true);
+ });
+
+ it("leaves other text fields alone", () => {
+ expect(shouldRefocusComposerOnWindowFocus(element("INPUT"))).toBe(false);
+ expect(shouldRefocusComposerOnWindowFocus(element("TEXTAREA"))).toBe(false);
+ expect(shouldRefocusComposerOnWindowFocus(element("DIV", { editable: true }))).toBe(false);
+ expect(shouldRefocusComposerOnWindowFocus(element("DIV", { role: "textbox" }))).toBe(false);
+ });
+
+ it("leaves a focused terminal alone in the drawer and the right panel", () => {
+ expect(
+ shouldRefocusComposerOnWindowFocus(element("BUTTON", { within: "data-terminal-owner" })),
+ ).toBe(false);
+ });
+
+ it("leaves focus inside a dialog or popup alone", () => {
+ expect(shouldRefocusComposerOnWindowFocus(element("BUTTON", { within: "dialog" }))).toBe(false);
+ expect(shouldRefocusComposerOnWindowFocus(element("BUTTON", { within: "-popup" }))).toBe(false);
+ });
+});
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 649ffef081d..03770bf20fc 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -1027,3 +1027,29 @@ export function hasServerAcknowledgedLocalDispatch(input: {
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
);
}
+
+// Returning to the window should land the caret in the composer, so the reader can type right
+// away. The exceptions are places where focus is deliberate: another text field, a terminal in
+// the drawer or the right panel, or an open dialog or popup. A focused button outside those is
+// not one of them, so it yields to the composer.
+export function shouldRefocusComposerOnWindowFocus(
+ activeElement:
+ | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
+ | null,
+): boolean {
+ if (activeElement === null || activeElement.tagName === "BODY") return true;
+ if (
+ activeElement.tagName === "INPUT" ||
+ activeElement.tagName === "TEXTAREA" ||
+ activeElement.tagName === "SELECT" ||
+ activeElement.isContentEditable === true ||
+ activeElement.getAttribute("role") === "textbox"
+ ) {
+ return false;
+ }
+ return (
+ activeElement.closest(
+ '[role="dialog"], [role="alertdialog"], [data-slot$="-popup"], [data-terminal-owner]',
+ ) === null
+ );
+}
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index ebec47a7a66..1415fffab19 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -404,6 +404,7 @@ import {
codexArtifactTemplatePromptToAppend,
toolGroupConsumesUpwardNavigation,
waitForStartedServerThread,
+ shouldRefocusComposerOnWindowFocus,
} from "./ChatView.logic";
import type { ThreadSyncPhase } from "../threadSync";
import { useLocalStorage } from "~/hooks/useLocalStorage";
@@ -1625,6 +1626,7 @@ export default function ChatView(props: ChatViewProps) {
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
const shouldUseRightPanelSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
+ const isMobileViewport = useMediaQuery("max-sm");
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
@@ -4988,6 +4990,33 @@ export default function ChatView(props: ChatViewProps) {
};
}, [activeThread?.id, focusComposer, terminalUiState.terminalOpen]);
+ // Tabbing back into the app lands focus wherever it last was, often the right panel or the
+ // body. Put it in the composer unless something that takes typing already holds it. The
+ // drawer terminal owns keyboard input while it is open, so it opts out here; a right panel
+ // terminal is a surface and is recognized by the predicate instead. Mobile is left alone so
+ // returning to the app does not raise the keyboard.
+ useEffect(() => {
+ if (!activeThread?.id || terminalUiState.terminalOpen || isMobileViewport) return;
+ let frame: number | null = null;
+ const onWindowFocus = () => {
+ if (frame !== null) window.cancelAnimationFrame(frame);
+ // The element that held focus receives it again after the window's own event, and the
+ // composer ignores that same frame so a restored focus does not lift a scroll-collapsed
+ // composer. Wait one more frame so this focus counts as a request to expand it.
+ frame = window.requestAnimationFrame(() => {
+ frame = window.requestAnimationFrame(() => {
+ frame = null;
+ if (shouldRefocusComposerOnWindowFocus(document.activeElement)) focusComposer();
+ });
+ });
+ };
+ window.addEventListener("focus", onWindowFocus);
+ return () => {
+ window.removeEventListener("focus", onWindowFocus);
+ if (frame !== null) window.cancelAnimationFrame(frame);
+ };
+ }, [activeThread?.id, focusComposer, isMobileViewport, terminalUiState.terminalOpen]);
+
useEffect(() => {
if (!activeThread?.id) return;
if (activeThread.messages.length === 0) {