From 3c691a0575d36243932a7381fb28837598bc6e1c Mon Sep 17 00:00:00 2001 From: Steve Juma Date: Thu, 19 Nov 2026 21:28:26 +0000 Subject: [PATCH 1/2] Support default colour updates in the WASM terminal stream --- docs/lapis-terminal-colors.md | 30 ++++++++++++++++++++++++++++++ lib/default-colors.test.ts | 23 +++++++++++++++++++++++ patches/ghostty-wasm-api.patch | 15 +++++++-------- 3 files changed, 60 insertions(+), 8 deletions(-) create mode 100644 docs/lapis-terminal-colors.md create mode 100644 lib/default-colors.test.ts diff --git a/docs/lapis-terminal-colors.md b/docs/lapis-terminal-colors.md new file mode 100644 index 00000000..cd0d4552 --- /dev/null +++ b/docs/lapis-terminal-colors.md @@ -0,0 +1,30 @@ +# WASM default-colour regression qualification + +The Lapis Server review found that OSC 10/11 could not update default colours: +the WASM response stream had no allocator, and its colour action handler ignored +requests. The WASM bridge now uses an allocator and delegates colour operations +to Ghostty's existing readonly handler, marking palette state dirty. This keeps +existing default cells in sync while preserving explicit background colours. + +The source change is in `patches/ghostty-wasm-api.patch`; generated WASM and npm +archives are local build outputs, not committed substitutes for source. + +Validation on 2026-11-19: + +- `bun test lib/default-colors.test.ts`: initially 1 failed / 0 passed; rebuilt + source passes 1 / 0 with four assertions, including explicit-colour retention. +- `bun run fmt`, `bun run lint`, `bun run typecheck`: pass. +- `bun test`: 360 passed / 0 failed, 4569 assertions. +- `bun run build`: passes with Zig 0.15.2 compiling the pinned Ghostty source to + WASM inside a disposable Linux container, then the normal Vite library build. + Zig runs through an external command-scoped tooling adapter because the macOS + SDK 27.2 attempt failed while linking the native build runner. Earlier Linux + setup attempts lacked a mounted compiler and `xz`; both setup issues were + corrected before the successful build. One compiler attempt lacked the colour + action's terminator field; passing the complete action fixed that error. +- The packed public output feeds Lapis Terminal plugin browser acceptance: + five checks pass, including live theme pixel matching and repeated narrow + renderer replacement. Server keeps independent Storybook reload acceptance. + +No upstream PR, registry publication or tag was created. This source/archive +cohort is a local validation prerequisite until upstream delivery is agreed. diff --git a/lib/default-colors.test.ts b/lib/default-colors.test.ts new file mode 100644 index 00000000..b535b42c --- /dev/null +++ b/lib/default-colors.test.ts @@ -0,0 +1,23 @@ +import { expect, test } from 'bun:test'; +import { Ghostty } from './ghostty'; + +test('OSC default colors update existing default cells and preserve explicit colors', async () => { + const ghostty = await Ghostty.load(); + const terminal = ghostty.createTerminal(20, 4, { + fgColor: 0x222222, + bgColor: 0xffffff, + }); + try { + terminal.write('plain \x1b[48;2;255;0;0mred\x1b[0m'); + terminal.update(); + terminal.write('\x1b]10;#d4d4d4\x1b\\\x1b]11;#1e1e1e\x1b\\'); + terminal.update(); + expect(terminal.getColors().background).toEqual({ r: 30, g: 30, b: 30 }); + expect(terminal.getColors().foreground).toEqual({ r: 212, g: 212, b: 212 }); + const line = terminal.getLine(0)!; + expect([line[0].bg_r, line[0].bg_g, line[0].bg_b]).toEqual([30, 30, 30]); + expect([line[6].bg_r, line[6].bg_g, line[6].bg_b]).toEqual([255, 0, 0]); + } finally { + terminal.free(); + } +}); diff --git a/patches/ghostty-wasm-api.patch b/patches/ghostty-wasm-api.patch index 231b32a4..67451a11 100644 --- a/patches/ghostty-wasm-api.patch +++ b/patches/ghostty-wasm-api.patch @@ -440,7 +440,7 @@ new file mode 100644 index 000000000..73ae2e6fa --- /dev/null +++ b/src/terminal/c/terminal.zig -@@ -0,0 +1,1123 @@ +@@ -0,0 +1,1122 @@ +//! C API wrapper for Terminal +//! +//! This provides a minimal, high-performance interface to Ghostty's Terminal @@ -619,7 +619,7 @@ index 000000000..73ae2e6fa + .end_of_input => self.terminal.markSemanticPrompt(.command), + .end_of_command => self.terminal.screens.active.cursor.page_row.semantic_prompt = .input, + .mouse_shape => self.terminal.mouse_shape = value, -+ .color_operation => try self.colorOperation(value.op, &value.requests), ++ .color_operation => try self.colorOperation(value), + .kitty_color_report => try self.kittyColorOperation(value), + + // Actions that require no response and have no terminal effect @@ -739,11 +739,10 @@ index 000000000..73ae2e6fa + } + } + -+ fn colorOperation(self: *ResponseHandler, op: anytype, requests: anytype) !void { -+ _ = self; -+ _ = op; -+ _ = requests; -+ // Color operations are not supported in WASM context ++ fn colorOperation(self: *ResponseHandler, value: anytype) !void { ++ var handler = @import("../stream_readonly.zig").Handler.init(self.terminal); ++ try handler.vt(.color_operation, value); ++ self.terminal.flags.dirty.palette = true; + } + + fn kittyColorOperation(self: *ResponseHandler, value: anytype) !void { @@ -884,7 +883,7 @@ index 000000000..73ae2e6fa + wrapper.handler = ResponseHandler.init(alloc, &wrapper.terminal, &wrapper.response_buffer); + + // Initialize stream with the handler -+ wrapper.stream = ResponseStream.init(wrapper.handler); ++ wrapper.stream = ResponseStream.initAlloc(alloc, wrapper.handler); + + wrapper.* = .{ + .alloc = alloc, From 184ae98285e474ad8080d8e95c0fee7278428fba Mon Sep 17 00:00:00 2001 From: Steve Juma Date: Thu, 19 Nov 2026 21:56:05 +0000 Subject: [PATCH 2/2] Fill terminal viewport without reserving a scrollbar gutter --- docs/lapis-terminal-viewport.md | 18 +++++++++++++++ lib/addons/fit.test.ts | 10 ++++----- lib/addons/fit.ts | 16 ++++++++++++-- lib/fit-viewport.test.ts | 32 +++++++++++++++++++++++++++ lib/interfaces.ts | 1 + lib/renderer.ts | 39 ++++++++++++++++++++++++++------- lib/terminal.ts | 26 ++++++++++------------ 7 files changed, 112 insertions(+), 30 deletions(-) create mode 100644 docs/lapis-terminal-viewport.md create mode 100644 lib/fit-viewport.test.ts diff --git a/docs/lapis-terminal-viewport.md b/docs/lapis-terminal-viewport.md new file mode 100644 index 00000000..8cb86c91 --- /dev/null +++ b/docs/lapis-terminal-viewport.md @@ -0,0 +1,18 @@ +# Lapis terminal viewport qualification + +FitAddon no longer reserves a 15px gutter for a scrollbar drawn over the canvas. +CanvasRenderer fills the measured content viewport, including partial character +cells, without changing cell metrics. The scrollbar and its hit target meet the +right edge. Canvas dimensions remain owned by the renderer at device pixel ratio. +Theme changes repaint the viewport remainder as well as complete rows. + +Regression: `bun test lib/fit-viewport.test.ts` initially failed once; now passes +with six assertions, including a viewport resize that does not change columns. +Two existing FitAddon expectations encoded the removed gutter and were updated +to the overlay contract. `bun test lib/fit-viewport.test.ts lib/addons/fit.test.ts`: +13 passed, zero failures. Full suite: 361 passed, zero failures. Formatting, +lint, TypeScript and the normal library/WASM build passed. WASM used the same +external Docker Zig adapter described in lapis-terminal-colors.md. + +These are unpublished local prerequisites. Browser pixel, scrollbar and Server +acceptance are recorded separately in the consuming source repositories. diff --git a/lib/addons/fit.test.ts b/lib/addons/fit.test.ts index 2da7bd00..89692f08 100644 --- a/lib/addons/fit.test.ts +++ b/lib/addons/fit.test.ts @@ -206,13 +206,13 @@ describe('Dimension Calculation', () => { addon.activate(mockTerminal as any); addon.fit(); - // Expected: (900 - 15 scrollbar) / 9 = 98 cols, 480 / 16 = 30 rows - expect(resizedCols).toBe(98); + // The scrollbar overlays the canvas: 900 / 9 = 100 cols, 480 / 16 = 30 rows + expect(resizedCols).toBe(100); expect(resizedRows).toBe(30); }); test('proposeDimensions returns correct values', () => { - // FitAddon subtracts 15px for scrollbar width + // Overlay scrollbars do not reserve terminal columns. const mockElement = document.createElement('div'); Object.defineProperty(mockElement, 'clientWidth', { value: 720, configurable: true }); Object.defineProperty(mockElement, 'clientHeight', { value: 384, configurable: true }); @@ -230,7 +230,7 @@ describe('Dimension Calculation', () => { addon.activate(mockTerminal as any); const dims = addon.proposeDimensions(); - // Expected: (720 - 15 scrollbar) / 8 = 88 cols, 384 / 16 = 24 rows - expect(dims).toEqual({ cols: 88, rows: 24 }); + // Expected: 720 / 8 = 90 cols, 384 / 16 = 24 rows + expect(dims).toEqual({ cols: 90, rows: 24 }); }); }); diff --git a/lib/addons/fit.ts b/lib/addons/fit.ts index ea532656..575643bd 100644 --- a/lib/addons/fit.ts +++ b/lib/addons/fit.ts @@ -21,7 +21,6 @@ import type { ITerminalAddon, ITerminalCore } from '../interfaces'; const MINIMUM_COLS = 2; const MINIMUM_ROWS = 1; -const DEFAULT_SCROLLBAR_WIDTH = 15; // Reserve space for future scrollback scrollbar const RESIZE_DEBOUNCE_MS = 100; // Debounce time for ResizeObserver // ============================================================================ @@ -103,6 +102,7 @@ export class FitAddon implements ITerminalAddon { (dims.cols === this._lastCols && dims.rows === this._lastRows) || (dims.cols === currentCols && dims.rows === currentRows) ) { + this.fitViewport(); return; } @@ -118,6 +118,7 @@ export class FitAddon implements ITerminalAddon { if (terminal.resize && typeof terminal.resize === 'function') { terminal.resize(dims.cols, dims.rows); } + this.fitViewport(); } finally { // Clear flag after a short delay to allow DOM to settle setTimeout(() => { @@ -185,7 +186,7 @@ export class FitAddon implements ITerminalAddon { } // Calculate available space (subtract padding since clientWidth includes padding) - const availableWidth = containerWidth - paddingLeft - paddingRight - DEFAULT_SCROLLBAR_WIDTH; + const availableWidth = containerWidth - paddingLeft - paddingRight; const availableHeight = containerHeight - paddingTop - paddingBottom; // Calculate dimensions (enforce minimums) @@ -195,6 +196,17 @@ export class FitAddon implements ITerminalAddon { return { cols, rows }; } + private fitViewport(): void { + const terminal = this._terminal; + const element = terminal?.element; + if (!element || !terminal.resizeViewport) return; + const style = window.getComputedStyle(element); + const padding = (name: string) => Number.parseFloat(style.getPropertyValue(name)) || 0; + const width = element.clientWidth - padding('padding-left') - padding('padding-right'); + const height = element.clientHeight - padding('padding-top') - padding('padding-bottom'); + if (width > 0 && height > 0) terminal.resizeViewport(width, height); + } + /** * Observe the terminal's container for resize events * diff --git a/lib/fit-viewport.test.ts b/lib/fit-viewport.test.ts new file mode 100644 index 00000000..037446dd --- /dev/null +++ b/lib/fit-viewport.test.ts @@ -0,0 +1,32 @@ +import { expect, test } from 'bun:test'; +import { FitAddon } from './addons/fit'; +import { createIsolatedTerminal } from './test-helpers'; + +test('fit fills the container without a reserved scrollbar gutter or stretched cells', async () => { + const terminal = await createIsolatedTerminal(); + const element = document.createElement('div'); + let width = 901; + Object.defineProperty(element, 'clientWidth', { get: () => width }); + Object.defineProperty(element, 'clientHeight', { value: 207 }); + document.body.append(element); + const fit = new FitAddon(); + terminal.loadAddon(fit); + try { + terminal.open(element); + const metrics = terminal.renderer!.getMetrics(); + fit.fit(); + expect(terminal.cols).toBe(Math.floor(width / metrics.width)); + const canvas = element.querySelector('canvas')!; + expect(canvas.style.width).toBe('901px'); + expect(canvas.style.height).toBe('207px'); + expect(terminal.renderer!.getMetrics()).toEqual(metrics); + await new Promise((resolve) => setTimeout(resolve, 55)); + width = 902; + fit.fit(); + expect(canvas.style.width).toBe('902px'); + expect(canvas.width).toBe(Math.round(width * window.devicePixelRatio)); + } finally { + terminal.dispose(); + element.remove(); + } +}); diff --git a/lib/interfaces.ts b/lib/interfaces.ts index 4c6fbe43..a37f0bd3 100644 --- a/lib/interfaces.ts +++ b/lib/interfaces.ts @@ -70,6 +70,7 @@ export interface ITerminalCore { rows: number; element?: HTMLElement; textarea?: HTMLTextAreaElement; + resizeViewport?(width: number, height: number): void; } /** diff --git a/lib/renderer.ts b/lib/renderer.ts index 3b51bfdd..59154aca 100644 --- a/lib/renderer.ts +++ b/lib/renderer.ts @@ -102,6 +102,8 @@ export class CanvasRenderer { private devicePixelRatio: number; private metrics: FontMetrics; private palette: string[]; + private viewportSize?: { width: number; height: number }; + private themeChanged = false; // Cursor blinking state private cursorVisible: boolean = true; @@ -234,16 +236,16 @@ export class CanvasRenderer { * Resize canvas to fit terminal dimensions */ public resize(cols: number, rows: number): void { - const cssWidth = cols * this.metrics.width; - const cssHeight = rows * this.metrics.height; + const cssWidth = this.viewportSize?.width ?? cols * this.metrics.width; + const cssHeight = this.viewportSize?.height ?? rows * this.metrics.height; // Set CSS size (what user sees) this.canvas.style.width = `${cssWidth}px`; this.canvas.style.height = `${cssHeight}px`; // Set actual canvas size (scaled for DPI) - this.canvas.width = cssWidth * this.devicePixelRatio; - this.canvas.height = cssHeight * this.devicePixelRatio; + this.canvas.width = Math.round(cssWidth * this.devicePixelRatio); + this.canvas.height = Math.round(cssHeight * this.devicePixelRatio); // Scale context to match DPI (setting canvas.width/height resets the context) this.ctx.scale(this.devicePixelRatio, this.devicePixelRatio); @@ -280,6 +282,12 @@ export class CanvasRenderer { const dims = buffer.getDimensions(); const scrollbackLength = scrollbackProvider ? scrollbackProvider.getScrollbackLength() : 0; + if (this.themeChanged) { + this.clear(); + forceAll = true; + this.themeChanged = false; + } + // Check if buffer needs full redraw (e.g., screen change between normal/alternate) if (buffer.needsFullRedraw?.()) { forceAll = true; @@ -287,8 +295,14 @@ export class CanvasRenderer { // Resize canvas if dimensions changed const needsResize = - this.canvas.width !== dims.cols * this.metrics.width * this.devicePixelRatio || - this.canvas.height !== dims.rows * this.metrics.height * this.devicePixelRatio; + this.canvas.width !== + Math.round( + (this.viewportSize?.width ?? dims.cols * this.metrics.width) * this.devicePixelRatio + ) || + this.canvas.height !== + Math.round( + (this.viewportSize?.height ?? dims.rows * this.metrics.height) * this.devicePixelRatio + ); if (needsResize) { this.resize(dims.cols, dims.rows); @@ -515,7 +529,7 @@ export class CanvasRenderer { */ private renderLine(line: GhosttyCell[], y: number, cols: number): void { const lineY = y * this.metrics.height; - const lineWidth = cols * this.metrics.width; + const lineWidth = this.viewportSize?.width ?? cols * this.metrics.width; // Clear line background then fill with theme color. // We clear just the cell area - glyph overflow is handled by also @@ -788,6 +802,7 @@ export class CanvasRenderer { */ public setTheme(theme: ITheme): void { this.theme = { ...DEFAULT_THEME, ...theme }; + this.themeChanged = true; // Rebuild palette this.palette = [ @@ -810,6 +825,14 @@ export class CanvasRenderer { ]; } + public setViewportSize(width: number, height: number): boolean { + if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) + return false; + if (this.viewportSize?.width === width && this.viewportSize?.height === height) return false; + this.viewportSize = { width, height }; + return true; + } + /** * Update font size */ @@ -867,7 +890,7 @@ export class CanvasRenderer { // Scrollbar dimensions const scrollbarWidth = 8; - const scrollbarX = canvasWidth - scrollbarWidth - 4; + const scrollbarX = canvasWidth - scrollbarWidth; const scrollbarPadding = 4; const scrollbarTrackHeight = canvasHeight - scrollbarPadding * 2; diff --git a/lib/terminal.ts b/lib/terminal.ts index 92d5f3d0..dff3c26a 100644 --- a/lib/terminal.ts +++ b/lib/terminal.ts @@ -244,13 +244,6 @@ export class Terminal implements ITerminalCore { // Resize canvas to match new font metrics this.renderer.resize(this.cols, this.rows); - // Update canvas element dimensions to match renderer - const metrics = this.renderer.getMetrics(); - this.canvas.width = metrics.width * this.cols; - this.canvas.height = metrics.height * this.rows; - this.canvas.style.width = `${metrics.width * this.cols}px`; - this.canvas.style.height = `${metrics.height * this.rows}px`; - // Force full re-render with new font this.renderer.render(this.wasmTerm, true, this.viewportY, this); } @@ -694,13 +687,6 @@ export class Terminal implements ITerminalCore { // Resize renderer this.renderer!.resize(cols, rows); - // Update canvas dimensions - const metrics = this.renderer!.getMetrics(); - this.canvas!.width = metrics.width * cols; - this.canvas!.height = metrics.height * rows; - this.canvas!.style.width = `${metrics.width * cols}px`; - this.canvas!.style.height = `${metrics.height * rows}px`; - // Fire resize event this.resizeEmitter.fire({ cols, rows }); @@ -715,6 +701,16 @@ export class Terminal implements ITerminalCore { this.startRenderLoop(); } + /** + * Fill the available CSS viewport without stretching terminal cells. + */ + resizeViewport(width: number, height: number): void { + this.assertOpen(); + if (!this.renderer!.setViewportSize(width, height)) return; + this.renderer!.resize(this.cols, this.rows); + this.renderer!.render(this.wasmTerm!, true, this.viewportY, this); + } + /** * Clear terminal screen */ @@ -1631,7 +1627,7 @@ export class Terminal implements ITerminalCore { const canvasWidth = rect.width; const canvasHeight = rect.height; const scrollbarWidth = 8; - const scrollbarX = canvasWidth - scrollbarWidth - 4; + const scrollbarX = canvasWidth - scrollbarWidth; const scrollbarPadding = 4; // Check if click is in scrollbar area