The best way to control Claude Code, Codex and more from any computer or phone
fix(web): terminal reports focus changes to programs that request them (#37066)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 15, 2026 at 07:56 UTC
3fe1dd922dec43cea8fbeddcf95fc9586499b190
4 files changed
+171
-23
apps/web/src/terminal/ghostty/core.ts
+25
-19
@@ -497,20 +497,12 @@ export class GhosttyTerminalCore {
497
498
isMouseAnyEventTracking(): boolean {
499
this.ensureActive();
500
- this.runtime.bytes(this.scratch, 1)[0] = 0;
501
- return (
502
- this.runtime.call("ghostty_terminal_mode_get", this.terminal, 1003, this.scratch) ===
503
- GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
504
- );
500
+ return this.modeEnabled(1003);
501
}
502
503
isSynchronizedOutput(): boolean {
504
this.ensureActive();
509
- this.runtime.bytes(this.scratch, 1)[0] = 0;
510
- return (
511
- this.runtime.call("ghostty_terminal_mode_get", this.terminal, 2026, this.scratch) ===
512
- GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
513
- );
505
+ return this.modeEnabled(2026);
506
}
507
508
endSynchronizedOutput(): void {
@@ -532,11 +524,7 @@ export class GhosttyTerminalCore {
524
525
isApplicationCursorKeys(): boolean {
526
this.ensureActive();
535
- this.runtime.bytes(this.scratch, 1)[0] = 0;
536
- return (
537
- this.runtime.call("ghostty_terminal_mode_get", this.terminal, 1, this.scratch) ===
538
- GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
539
- );
527
+ return this.modeEnabled(1);
528
}
529
530
encodeKey(event: KeyboardEvent, action: "press" | "release" = "press"): string {
@@ -596,10 +584,7 @@ export class GhosttyTerminalCore {
584
if (input.length === 0) return "";
585
const inputPointer = this.runtime.alloc(input.length);
586
this.runtime.bytes(inputPointer, input.length).set(input);
599
- this.runtime.bytes(this.scratch, 1)[0] = 0;
600
- const bracketed =
601
- this.runtime.call("ghostty_terminal_mode_get", this.terminal, 2004, this.scratch) ===
602
- GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0;
587
+ const bracketed = this.modeEnabled(2004);
588
const written = this.runtime.call("ghostty_wasm_alloc_usize");
589
let encoded = "";
590
const sizeResult = this.runtime.call(
@@ -633,6 +618,18 @@ export class GhosttyTerminalCore {
618
return encoded;
619
}
620
621
+ /** Empty unless the program enabled DEC 1004 focus reporting. */
622
+ encodeFocus(focused: boolean): string {
623
+ this.ensureActive();
624
+ if (!this.modeEnabled(1004)) return "";
625
+ const written = this.runtime.call("ghostty_wasm_alloc_usize");
626
+ const encoded = this.encodeOutput(written, (output, outputSize) =>
627
+ this.runtime.call("ghostty_focus_encode", focused ? 0 : 1, output, outputSize, written),
628
+ );
629
+ this.runtime.call("ghostty_wasm_free_usize", written);
630
+ return encoded;
631
+ }
632
+
633
encodeMouse(input: GhosttyMouseInput): string {
634
this.ensureActive();
635
this.runtime.call(
@@ -992,6 +989,15 @@ export class GhosttyTerminalCore {
989
}
990
}
991
992
+ /** Reads a DEC private mode; an unknown mode reads as off. */
993
+ private modeEnabled(mode: number): boolean {
994
+ this.runtime.bytes(this.scratch, 1)[0] = 0;
995
+ return (
996
+ this.runtime.call("ghostty_terminal_mode_get", this.terminal, mode, this.scratch) ===
997
+ GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
998
+ );
999
+ }
1000
+
1001
private encodeOutput(
1002
written: number,
1003
encode: (output: number, outputSize: number) => number,
apps/web/src/terminal/ghostty/surface.test.ts
+40
-2
@@ -89,6 +89,7 @@ describe("GhosttyTerminalSurface visibility", () => {
89
width = 300;
90
height = 150;
91
value = "";
92
+ children: TerminalTestElement[] = [];
93
private readonly captures = new Set<number>();
94
95
setAttribute() {}
@@ -96,6 +97,7 @@ describe("GhosttyTerminalSurface visibility", () => {
97
for (const child of children) child.parentElement = this;
98
}
99
replaceChildren(...children: TerminalTestElement[]) {
100
+ this.children = children;
101
this.append(...children);
102
}
103
remove() {
@@ -105,6 +107,7 @@ describe("GhosttyTerminalSurface visibility", () => {
107
return context;
108
}
109
focus() {
110
+ fakeDocument.activeElement = this;
111
this.dispatchEvent(new Event("focus"));
112
}
113
setPointerCapture(pointerId: number) {
@@ -142,10 +145,12 @@ describe("GhosttyTerminalSurface visibility", () => {
145
actualBoundingBoxDescent: 3,
146
}),
147
};
145
- vi.stubGlobal("document", {
148
+ const fakeDocument = {
149
+ activeElement: null as TerminalTestElement | null,
150
createElement: (tag: string) => (tag === "canvas" ? canvas : new TerminalTestElement()),
151
fonts: Object.assign(new EventTarget(), { load: async () => [], add() {} }),
148
- });
152
+ };
153
+ vi.stubGlobal("document", fakeDocument);
154
vi.stubGlobal(
155
"window",
156
Object.assign(new EventTarget(), {
@@ -400,6 +405,39 @@ describe("GhosttyTerminalSurface visibility", () => {
405
]);
406
});
407
408
+ it("reports focus transitions only while DEC 1004 is enabled", async () => {
409
+ vi.stubGlobal("navigator", { platform: "Linux x86_64" });
410
+ const harness = createHarness();
411
+ const surface = await harness.create();
412
+ const blur = () => surface.input.dispatchEvent(new Event("blur"));
413
+ const reports = () => harness.onData.mock.calls.map(([data]) => data);
414
+
415
+ surface.write("\x1b[?1004h");
416
+ surface.focus();
417
+ surface.focus();
418
+ blur();
419
+ blur();
420
+ expect(reports()).toEqual(["\x1b[I", "\x1b[O"]);
421
+
422
+ harness.onData.mockClear();
423
+ surface.write("\x1b[?1004l");
424
+ surface.focus();
425
+ blur();
426
+ expect(reports()).toEqual([]);
427
+ });
428
+
429
+ it("reports the blur of an input focused while the surface was still loading", async () => {
430
+ vi.stubGlobal("navigator", { platform: "Linux x86_64" });
431
+ const harness = createHarness();
432
+ const pending = harness.create();
433
+ harness.mount.children[1]?.focus();
434
+ const surface = await pending;
435
+
436
+ surface.write("\x1b[?1004h");
437
+ surface.input.dispatchEvent(new Event("blur"));
438
+ expect(harness.onData.mock.calls.map(([data]) => data)).toEqual(["\x1b[O"]);
439
+ });
440
+
441
it("honors host interception, IME candidates, and AltGr before local shortcuts", async () => {
442
vi.stubGlobal("navigator", { platform: "Linux x86_64" });
443
const harness = createHarness();
apps/web/src/terminal/ghostty/surface.ts
+12
-2
@@ -672,6 +672,8 @@ export class GhosttyTerminalSurface {
672
this.requestedFontFamily = options.font?.family;
673
this.fontSize = terminalFontSize(options.font?.size);
674
this.installEvents();
675
+ // The input is mounted before the core loads, so focus can land before the listeners.
676
+ this.focused = document.activeElement === input;
677
this.watchDevicePixelRatio();
678
this.reducedMotionMedia?.addEventListener("change", this.onReducedMotionChange);
679
document.fonts.addEventListener("loadingdone", this.onFontsLoaded);
@@ -1235,19 +1237,27 @@ export class GhosttyTerminalSurface {
1237
};
1238
1239
private readonly onFocus = () => {
1238
- this.focused = true;
1240
+ this.setFocused(true);
1241
this.cursorOn = true;
1242
this.requestRender();
1243
};
1244
1245
private readonly onBlur = () => {
1244
- this.focused = false;
1246
+ this.setFocused(false);
1247
this.pasteShortcutGesture = null;
1248
this.refreshHoveredLink();
1249
this.cursorOn = true;
1250
this.requestRender();
1251
};
1252
1253
+ // DOM focus events can repeat without a change; report only real transitions.
1254
+ private setFocused(focused: boolean): void {
1255
+ if (this.focused === focused) return;
1256
+ this.focused = focused;
1257
+ const data = this.core.encodeFocus(focused);
1258
+ if (data.length > 0) this.options.onData(data);
1259
+ }
1260
+
1261
private readonly onDevicePixelRatioChange = () => {
1262
this.watchDevicePixelRatio();
1263
this.fit();
scripts/scenarios/terminal-reports-focus-while-enabled.e2e.ts
new
+94
@@ -0,0 +1,94 @@
1
+/// <reference lib="dom" />
2
+// The DOM lib types the function this scenario runs in the page.
3
+import { expect } from "e2e";
4
+import * as Effect from "effect/Effect";
5
+import * as FileSystem from "effect/FileSystem";
6
+
7
+import { runPromise, test, WEB } from "./t3.ts";
8
+
9
+// One raw-mode process logs every byte the terminal sends to `received` and steps on exact
10
+// input: DECRQM replies mark when 1004 is on or off, and `x` ends it.
11
+const PROBE = String.raw`import { appendFileSync, writeFileSync } from "node:fs";
12
+
13
+const log = new URL("received", import.meta.url);
14
+const ENABLED = "\x1b[?1004;1$y";
15
+const REPORTS = "\x1b[O\x1b[I";
16
+const DISABLED = "\x1b[?1004;2$y";
17
+let received = "";
18
+
19
+writeFileSync(log, "");
20
+process.stdin.setRawMode(true);
21
+process.stdin.on("data", (chunk) => {
22
+ appendFileSync(log, chunk);
23
+ received += chunk.toString("latin1");
24
+ if (received === ENABLED + REPORTS) process.stdout.write("\x1b[?1004l\x1b[?1004$p");
25
+ if (received === ENABLED + REPORTS + DISABLED + "x") {
26
+ process.stdin.setRawMode(false);
27
+ process.exit(0);
28
+ }
29
+});
30
+process.stdout.write("\x1b[?1004h\x1b[?1004$p");
31
+`;
32
+
33
+const ENABLED = "\x1b[?1004;1$y";
34
+const REPORTS = "\x1b[O\x1b[I";
35
+const DISABLED = "\x1b[?1004;2$y";
36
+
37
+test(
38
+ "The web terminal reports focus changes only while a program enables DEC 1004",
39
+ WEB,
40
+ async ({ t3, app, browser, screen }) => {
41
+ const project = await t3.project("demo", { "focus-probe.mjs": PROBE });
42
+ const thread = await t3.thread({ project, title: "Focus", messages: ["hello"] });
43
+ const read = (file: string) =>
44
+ runPromise(
45
+ Effect.gen(function* () {
46
+ const fs = yield* FileSystem.FileSystem;
47
+ return yield* fs.readFileString(`${project}/${file}`);
48
+ }).pipe(Effect.orElseSucceed(() => "")),
49
+ );
50
+ await t3.open(thread);
51
+ await browser.evaluate(() => {
52
+ localStorage.setItem("t3code:theme", "dark");
53
+ return null;
54
+ });
55
+ await t3.open(thread);
56
+
57
+ await screen.getByRole("button", "Toggle terminal drawer").tap();
58
+ const terminal = screen.getByLabel("Terminal input");
59
+ const composer = screen.getByRole("textbox", "Message Focus");
60
+
61
+ // Input sent before the shell runs is dropped, so retype until it lands.
62
+ await expect
63
+ .poll(
64
+ async () => {
65
+ await terminal.focus();
66
+ await browser.keyboard.type(`echo ready > '${project}/shell-ready'`);
67
+ await browser.keyboard.press("Enter");
68
+ return read("shell-ready");
69
+ },
70
+ { timeout: 30_000 },
71
+ )
72
+ .toBe("ready\n");
73
+
74
+ await terminal.focus();
75
+ await browser.keyboard.type(`'${process.execPath}' '${project}/focus-probe.mjs'`);
76
+ await browser.keyboard.press("Enter");
77
+ await expect.poll(() => read("received"), { timeout: 15_000 }).toBe(ENABLED);
78
+
79
+ await composer.tap();
80
+ await terminal.focus();
81
+ await app.screenshot("enabled");
82
+ await expect
83
+ .poll(() => read("received"), { timeout: 10_000 })
84
+ .toBe(ENABLED + REPORTS + DISABLED);
85
+
86
+ await composer.tap();
87
+ await terminal.focus();
88
+ await browser.keyboard.type("x");
89
+ await app.screenshot("disabled");
90
+ await expect
91
+ .poll(() => read("received"), { timeout: 10_000 })
92
+ .toBe(ENABLED + REPORTS + DISABLED + "x");
93
+ },
94
+);