Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/lapis-terminal-colors.md
Original file line number Diff line number Diff line change
@@ -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.
18 changes: 18 additions & 0 deletions docs/lapis-terminal-viewport.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 5 additions & 5 deletions lib/addons/fit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -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 });
});
});
16 changes: 14 additions & 2 deletions lib/addons/fit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

// ============================================================================
Expand Down Expand Up @@ -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;
}

Expand All @@ -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(() => {
Expand Down Expand Up @@ -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)
Expand All @@ -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
*
Expand Down
23 changes: 23 additions & 0 deletions lib/default-colors.test.ts
Original file line number Diff line number Diff line change
@@ -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();
}
});
32 changes: 32 additions & 0 deletions lib/fit-viewport.test.ts
Original file line number Diff line number Diff line change
@@ -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();
}
});
1 change: 1 addition & 0 deletions lib/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export interface ITerminalCore {
rows: number;
element?: HTMLElement;
textarea?: HTMLTextAreaElement;
resizeViewport?(width: number, height: number): void;
}

/**
Expand Down
39 changes: 31 additions & 8 deletions lib/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -280,15 +282,27 @@ 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;
}

// 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);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -788,6 +802,7 @@ export class CanvasRenderer {
*/
public setTheme(theme: ITheme): void {
this.theme = { ...DEFAULT_THEME, ...theme };
this.themeChanged = true;

// Rebuild palette
this.palette = [
Expand All @@ -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
*/
Expand Down Expand Up @@ -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;

Expand Down
26 changes: 11 additions & 15 deletions lib/terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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 });

Expand All @@ -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
*/
Expand Down Expand Up @@ -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
Expand Down
15 changes: 7 additions & 8 deletions patches/ghostty-wasm-api.patch
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down