@devries-cameron20 / t3code Mirror · read-only / commits / 26338ea544
Fork 0

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 23, 00:30 UTC

fix(web): paint synchronized terminal updates atomically (#9867)

Co-authored-by: Wout Stiens <71498452+StiensWout@users.noreply.github.com>

Julius Marminge committed Oct 19, 2026 at 18:35 UTC 26338ea544ba5aff59ffd596c793597682333c58
3 files changed +259 -10
apps/web/src/terminal/ghostty/core.ts
+36 -3
@@ -341,14 +341,30 @@ export class GhosttyTerminalCore {
341 this.resize(cols, rows, cellWidth, cellHeight);
342 }
343
344 - write(data: string | Uint8Array): void {
344 + write(data: string | Uint8Array, onSynchronizedOutputEnd?: () => void): void {
345 this.ensureActive();
346 const bytes = typeof data === "string" ? encoder.encode(data) : data;
347 if (bytes.length === 0) return;
348 const pointer = this.runtime.alloc(bytes.length);
349 this.runtime.bytes(pointer, bytes.length).set(bytes);
350 - this.runtime.call("ghostty_terminal_vt_write", this.terminal, pointer, bytes.length);
351 - this.runtime.free(pointer, bytes.length);
350 + // An existing render deadline belongs to one group. Observe Ghostty before
351 + // the next escape can reopen it; Ghostty still parses OSC/DCS and split VT
352 + // sequences itself. Once that group ends, the remaining bytes can be batched.
353 + let synchronized = onSynchronizedOutputEnd !== undefined && this.isSynchronizedOutput();
354 + try {
355 + for (let start = 0; start < bytes.length;) {
356 + const nextEscape = synchronized ? bytes.indexOf(0x1b, start + 1) : -1;
357 + const end = nextEscape === -1 ? bytes.length : nextEscape;
358 + this.runtime.call("ghostty_terminal_vt_write", this.terminal, pointer + start, end - start);
359 + start = end;
360 + if (synchronized && !this.isSynchronizedOutput()) {
361 + synchronized = false;
362 + onSynchronizedOutputEnd?.();
363 + }
364 + }
365 + } finally {
366 + this.runtime.free(pointer, bytes.length);
367 + }
368 }
369
370 resetAndWrite(data: string): void {
@@ -490,6 +506,23 @@ export class GhosttyTerminalCore {
506 );
507 }
508
509 + isSynchronizedOutput(): boolean {
510 + this.ensureActive();
511 + this.runtime.bytes(this.scratch, 1)[0] = 0;
512 + return (
513 + this.runtime.call("ghostty_terminal_mode_get", this.terminal, 2026, this.scratch) ===
514 + GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0
515 + );
516 + }
517 +
518 + endSynchronizedOutput(): void {
519 + this.ensureActive();
520 + this.assertSuccess(
521 + "ghostty_terminal_mode_set",
522 + this.runtime.call("ghostty_terminal_mode_set", this.terminal, 2026, 0),
523 + );
524 + }
525 +
526 isAlternateScreen(): boolean {
527 this.ensureActive();
528 this.runtime.bytes(this.scratch, 4).fill(0);
apps/web/src/terminal/ghostty/surface.test.ts
+156
@@ -186,6 +186,7 @@ describe("GhosttyTerminalSurface visibility", () => {
186 const onData = vi.fn<(data: string) => void>();
187
188 return {
189 + canvas,
190 mount,
191 frames,
192 paint,
@@ -271,6 +272,161 @@ describe("GhosttyTerminalSurface visibility", () => {
272 vi.restoreAllMocks();
273 });
274
275 + it("holds the complete frame across split synchronized markers and a DPR change", async () => {
276 + const harness = createHarness();
277 + const surface = await harness.create();
278 + surface.write("\x1b[?1049h\x1b[HOLD first\x1b[2;1HOLD second");
279 + harness.flushFrame();
280 + expect(harness.renderedSnapshot.rowData.slice(0, 2).map((row) => row.text)).toEqual([
281 + "OLD first",
282 + "OLD second",
283 + ]);
284 + const { width, height } = harness.canvas;
285 + harness.snapshot.mockClear();
286 + harness.paint.mockClear();
287 +
288 + surface.write("\x1b[?20");
289 + surface.write("26h\x1b[HNEW first\x1b[5n");
290 + expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");
291 + harness.flushFrame();
292 + window.devicePixelRatio = 2;
293 + harness.resize();
294 + vi.advanceTimersByTime(200);
295 + surface.write("\x1b[2;1HNEW second\x1b[?2026");
296 + harness.flushFrame();
297 + expect(harness.snapshot).not.toHaveBeenCalled();
298 + expect(harness.paint).not.toHaveBeenCalled();
299 + expect([harness.canvas.width, harness.canvas.height]).toEqual([width, height]);
300 +
301 + surface.write("l");
302 + harness.flushFrame();
303 + expect(harness.snapshot).toHaveBeenCalledTimes(1);
304 + expect(harness.renderedSnapshot.rowData.slice(0, 2).map((row) => row.text)).toEqual([
305 + "NEW first",
306 + "NEW second",
307 + ]);
308 + expect([harness.canvas.width, harness.canvas.height]).toEqual([width * 2, height * 2]);
309 + expect(
310 + harness.paint.mock.calls
311 + .filter(([operation]) => operation === "fillText")
312 + .map(([, args]) => args[0]),
313 + ).toEqual(expect.arrayContaining(["NEW first", "NEW second"]));
314 + vi.advanceTimersByTime(1_000);
315 + harness.flushFrame();
316 + expect(harness.snapshot).toHaveBeenCalledTimes(1);
317 + });
318 +
319 + it("recovers an unterminated synchronized update at 500ms despite later output", async () => {
320 + const harness = createHarness();
321 + const surface = await harness.create();
322 + surface.write("before");
323 + harness.flushFrame();
324 + harness.snapshot.mockClear();
325 + harness.paint.mockClear();
326 + surface.write("\x1b[?2026h\rpartial");
327 + vi.advanceTimersByTime(499);
328 + surface.write(" frame");
329 + harness.flushFrame();
330 + expect(harness.snapshot).not.toHaveBeenCalled();
331 + expect(harness.paint).not.toHaveBeenCalled();
332 + vi.advanceTimersByTime(1);
333 + harness.flushFrame();
334 + expect(harness.snapshot).toHaveBeenCalledTimes(1);
335 + expect(harness.renderedSnapshot.rowData[0]?.text).toBe("partial frame");
336 + vi.advanceTimersByTime(1_000);
337 + harness.flushFrame();
338 + expect(harness.snapshot).toHaveBeenCalledTimes(1);
339 + surface.write("!");
340 + harness.flushFrame();
341 + expect(harness.renderedSnapshot.rowData[0]?.text).toBe("partial frame!");
342 + });
343 +
344 + it("gives a synchronized group its own deadline when one write closes A and opens B", async () => {
345 + const harness = createHarness();
346 + const surface = await harness.create();
347 + surface.write("old");
348 + harness.flushFrame();
349 + harness.snapshot.mockClear();
350 + harness.paint.mockClear();
351 + surface.write("\x1b[?2026h\rAAA");
352 + vi.advanceTimersByTime(450);
353 + surface.write("\x1b[?2026l\x1b[?2026h\rBBB");
354 + vi.advanceTimersByTime(50);
355 + harness.flushFrame();
356 + expect(harness.snapshot).not.toHaveBeenCalled();
357 + expect(harness.paint).not.toHaveBeenCalled();
358 + vi.advanceTimersByTime(449);
359 + harness.flushFrame();
360 + expect(harness.snapshot).not.toHaveBeenCalled();
361 + vi.advanceTimersByTime(1);
362 + harness.flushFrame();
363 + expect(harness.snapshot).toHaveBeenCalledTimes(1);
364 + expect(harness.renderedSnapshot.rowData[0]?.text).toBe("BBB");
365 + });
366 +
367 + it.each(["hide", "zero-size", "dispose"] as const)(
368 + "cancels synchronized recovery on %s",
369 + async (action) => {
370 + const harness = createHarness();
371 + const surface = await harness.create();
372 + surface.write("old");
373 + harness.flushFrame();
374 + surface.write("\x1b[?2026h\rnew");
375 + harness.snapshot.mockClear();
376 + harness.paint.mockClear();
377 + if (action === "hide") surface.setVisible(false);
378 + else if (action === "zero-size") {
379 + harness.mount.clientWidth = 0;
380 + harness.resize();
381 + } else surface.dispose();
382 + vi.advanceTimersByTime(1_000);
383 + harness.flushFrame();
384 + expect(harness.snapshot).not.toHaveBeenCalled();
385 + expect(harness.paint).not.toHaveBeenCalled();
386 + if (action === "dispose") return;
387 + if (action === "hide") surface.setVisible(true);
388 + else {
389 + harness.mount.clientWidth = 168;
390 + harness.resize();
391 + }
392 + expect(harness.snapshot).not.toHaveBeenCalled();
393 + surface.write("\x1b[?2026l");
394 + harness.flushFrame();
395 + expect(harness.renderedSnapshot.rowData[0]?.text).toBe("new");
396 + },
397 + );
398 +
399 + it("replaces an open synchronized update on reset without a stale recovery paint", async () => {
400 + const harness = createHarness();
401 + const surface = await harness.create();
402 + surface.write("\x1b[?2026hpartial");
403 + harness.snapshot.mockClear();
404 + surface.resetAndWrite("replacement");
405 + harness.flushFrame();
406 + expect(harness.snapshot).toHaveBeenCalledTimes(1);
407 + expect(harness.renderedSnapshot.rowData[0]?.text).toBe("replacement");
408 + vi.advanceTimersByTime(1_000);
409 + harness.flushFrame();
410 + expect(harness.snapshot).toHaveBeenCalledTimes(1);
411 + });
412 +
413 + it("paints a grid resize immediately when Ghostty ends synchronized output", async () => {
414 + const harness = createHarness();
415 + const surface = await harness.create();
416 + surface.write("old");
417 + harness.flushFrame();
418 + surface.write("\x1b[?2026h\rnew");
419 + harness.snapshot.mockClear();
420 + harness.mount.clientWidth = 176;
421 + harness.resize();
422 + expect(harness.snapshot).toHaveBeenCalledTimes(1);
423 + expect(harness.canvas.width).toBe(176);
424 + expect(harness.renderedSnapshot.rowData[0]?.text).toBe("new");
425 + vi.advanceTimersByTime(1_000);
426 + harness.flushFrame();
427 + expect(harness.snapshot).toHaveBeenCalledTimes(1);
428 + });
429 +
430 it.each([
431 { platform: "Linux x86_64", primary: { ctrlKey: true } },
432 { platform: "MacIntel", primary: { metaKey: true } },
apps/web/src/terminal/ghostty/surface.ts
+67 -7
@@ -33,6 +33,8 @@ export const DEFAULT_TERMINAL_FONT_FAMILY =
33 const CONTENT_PADDING = 4;
34 const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
35 const CURSOR_BLINK_INTERVAL_MS = 500;
36 +/** End an unterminated synchronized update instead of freezing the last frame. */
37 +const SYNCHRONIZED_OUTPUT_RENDER_TIMEOUT_MS = 500;
38 const TERMINAL_FONT_LOAD_TEXT = "iMW0@# .";
39 const TERMINAL_FONT_LOAD_VARIANTS = [
40 "normal 400",
@@ -535,6 +537,7 @@ export class GhosttyTerminalSurface {
537 private readonly scrollbarThumb: HTMLDivElement;
538 private snapshot: GhosttySnapshot | null = null;
539 private frame = 0;
540 + private synchronizedRenderTimer: number | null = null;
541 private cursorTimer: number | null = null;
542 private compositionInputToSuppress: string | null = null;
543 private compositionSuppressionTimer: number | null = null;
@@ -577,6 +580,12 @@ export class GhosttyTerminalSurface {
580 private focused = false;
581 private resizeNotified = false;
582 private canvasConfigured = false;
583 + private canvasDevicePixelRatio = 0;
584 + private pendingCanvasConfiguration: {
585 + readonly width: number;
586 + readonly height: number;
587 + readonly ratio: number;
588 + } | null = null;
589 private theme: GhosttyTheme;
590 private readonly suppressedKeyCodes = new Set<string>();
591 private pasteShortcutToken = 0;
@@ -723,7 +732,12 @@ export class GhosttyTerminalSurface {
732
733 write(data: string): void {
734 if (this.disposed) return;
726 - this.core.write(data);
735 + this.core.write(
736 + data,
737 + this.synchronizedRenderTimer === null
738 + ? undefined
739 + : () => this.cancelSynchronizedRenderTimer(),
740 + );
741 this.synchronizeMouseTrackingState();
742 this.cursorOn = true;
743 this.scrollbarDirty = true;
@@ -732,6 +746,7 @@ export class GhosttyTerminalSurface {
746
747 resetAndWrite(data: string): void {
748 if (this.disposed) return;
749 + this.cancelSynchronizedRenderTimer();
750 this.lastMouseMotionData = "";
751 this.core.resetAndWrite(data);
752 this.synchronizeMouseTrackingState();
@@ -837,15 +852,18 @@ export class GhosttyTerminalSurface {
852 if (
853 this.canvas.width !== pixelWidth ||
854 this.canvas.height !== pixelHeight ||
840 - !this.canvasConfigured
855 + !this.canvasConfigured ||
856 + this.canvasDevicePixelRatio !== ratio
857 ) {
842 - this.canvas.width = pixelWidth;
843 - this.canvas.height = pixelHeight;
844 - this.context.setTransform(ratio, 0, 0, ratio, 0, 0);
845 - this.canvasConfigured = true;
858 + // A backing-size change clears the canvas. Apply it with the gated paint
859 + // so a DPR change cannot erase a frame while synchronized output is open.
860 + this.pendingCanvasConfiguration = { width: pixelWidth, height: pixelHeight, ratio };
861 this.forceFullRender = true;
862 this.scrollbarDirty = true;
863 shouldRender = true;
864 + } else {
865 + // A resize can return to the painted size before its queued frame runs.
866 + this.pendingCanvasConfiguration = null;
867 }
868 const grid = terminalGridSize(width, height, this.metrics, CONTENT_PADDING);
869 this.mountHeight = height;
@@ -1865,7 +1883,8 @@ export class GhosttyTerminalSurface {
1883 }
1884
1885 private requestRender(): void {
1868 - if (this.disposed || !this.visible || !this.hasSize || this.frame !== 0) return;
1886 + if (this.disposed || !this.visible || !this.hasSize) return;
1887 + if (this.deferSynchronizedRender() || this.frame !== 0) return;
1888 this.frame = window.requestAnimationFrame(() => {
1889 this.frame = 0;
1890 this.renderFrame();
@@ -1873,6 +1892,29 @@ export class GhosttyTerminalSurface {
1892 }
1893
1894 private cancelRender(): void {
1895 + this.cancelSynchronizedRenderTimer();
1896 + if (this.frame !== 0) {
1897 + window.cancelAnimationFrame(this.frame);
1898 + this.frame = 0;
1899 + }
1900 + if (this.cursorTimer !== null) {
1901 + window.clearTimeout(this.cursorTimer);
1902 + this.cursorTimer = null;
1903 + }
1904 + }
1905 +
1906 + private cancelSynchronizedRenderTimer(): void {
1907 + if (this.synchronizedRenderTimer === null) return;
1908 + window.clearTimeout(this.synchronizedRenderTimer);
1909 + this.synchronizedRenderTimer = null;
1910 + }
1911 +
1912 + private deferSynchronizedRender(): boolean {
1913 + if (!this.core.isSynchronizedOutput()) {
1914 + this.cancelSynchronizedRenderTimer();
1915 + return false;
1916 + }
1917 + // A frame queued before the opening marker would now consume partial rows.
1918 if (this.frame !== 0) {
1919 window.cancelAnimationFrame(this.frame);
1920 this.frame = 0;
@@ -1881,6 +1923,14 @@ export class GhosttyTerminalSurface {
1923 window.clearTimeout(this.cursorTimer);
1924 this.cursorTimer = null;
1925 }
1926 + if (this.synchronizedRenderTimer === null) {
1927 + this.synchronizedRenderTimer = window.setTimeout(() => {
1928 + this.synchronizedRenderTimer = null;
1929 + this.core.endSynchronizedOutput();
1930 + this.renderFrame();
1931 + }, SYNCHRONIZED_OUTPUT_RENDER_TIMEOUT_MS);
1932 + }
1933 + return true;
1934 }
1935
1936 private renderFrame(): void {
@@ -1895,6 +1945,16 @@ export class GhosttyTerminalSurface {
1945 this.cancelRender();
1946 return;
1947 }
1948 + if (this.deferSynchronizedRender()) return;
1949 + const canvasConfiguration = this.pendingCanvasConfiguration;
1950 + if (canvasConfiguration !== null) {
1951 + this.pendingCanvasConfiguration = null;
1952 + this.canvas.width = canvasConfiguration.width;
1953 + this.canvas.height = canvasConfiguration.height;
1954 + this.context.setTransform(canvasConfiguration.ratio, 0, 0, canvasConfiguration.ratio, 0, 0);
1955 + this.canvasConfigured = true;
1956 + this.canvasDevicePixelRatio = canvasConfiguration.ratio;
1957 + }
1958 this.snapshot = this.core.snapshot();
1959 if (!this.blinkEnabled()) this.cursorOn = true;
1960 // The origin only moves together with a forced full repaint: partial