diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2680ce9..36ee3a2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,7 +7,7 @@ on: description: Existing release tag to publish or retry required: true type: choice - options: [ext-v0.4.2, terminal-v0.4.3, terminal-v0.4.2, ext-v0.4.1, terminal-v0.4.1, dsh-v0.4.0, terminal-v0.4.0, ext-v0.4.0, dsh-v0.3.0, terminal-v0.3.0, ext-v0.3.0, dsh-v0.2.0, terminal-v0.2.0, terminal-v0.2.1, ext-v0.2.0, ext-v0.2.1] + options: [terminal-v0.4.4, ext-v0.4.2, terminal-v0.4.3, terminal-v0.4.2, ext-v0.4.1, terminal-v0.4.1, dsh-v0.4.0, terminal-v0.4.0, ext-v0.4.0, dsh-v0.3.0, terminal-v0.3.0, ext-v0.3.0, dsh-v0.2.0, terminal-v0.2.0, terminal-v0.2.1, ext-v0.2.0, ext-v0.2.1] push: tags: ["ext-v*", "dsh-v*", "terminal-v*"] diff --git a/CHANGELOG.md b/CHANGELOG.md index c714cf5..0639f21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## Terminal host 0.4.4 — 2026-11-05 + +- Keep a WebGL terminal renderer across Focus and Chill modes to improve typing and scrolling under dense output. Preserve translucent ANSI/truecolor backgrounds, opaque text, selection and cursor, with a DOM fallback when GPU rendering is unavailable. +- Bound large output writes, coalesce cumulative acknowledgements and drain the host output queue in linear time. Avoid redundant PTY pause/resume calls, viewport updates and presentation changes. +- Preserve ordinary text selection, copy, TUI mouse input and keyboard mode switching. Keep 3,000 lines of scrollback. +- This patch ships with terminal host 0.4.4. Extension 0.4.2, DSH 0.4.0 and connector protocol 1 remain unchanged. Finish live shells, then run `aow update` from a separate macOS Terminal. + ## Extension 0.4.2 — 2026-10-29 - Drag the floating AgentOnWeb icon with a mouse, trackpad or touch to uncover page controls. Remember its position across pages and reloads, and adapt it when the window changes size. diff --git a/README.md b/README.md index e882820..2307c87 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ For Pi 1.1+, run `pi` in the same terminal. Setup adds `extensions/agentonweb.ts Use **+** in the terminal tab bar to open another project, click a tab to switch, double-click its name to rename it, or click **×** to close it. Hiding the workspace or refreshing the page keeps your sessions running. -Terminal host 0.4.3 checks for stable npm updates daily and shows reminders in its private management page. Use `aow check-update` to check now or `aow check-update --disable` to turn automatic checks off. After closing live terminals, run `aow update` in a separate macOS Terminal; `aow service restart` reloads already-installed code. CLI 0.4.3 also supports `aow update --force` to reinstall and restart a verified older service, ending its live tasks. If an older CLI cannot prepare an update, finish terminal work, run `aow service uninstall`, then rerun the installer once. +Terminal host 0.4.4 checks for stable npm updates daily and shows reminders in its private management page. Use `aow check-update` to check now or `aow check-update --disable` to turn automatic checks off. After closing live terminals, run `aow update` in a separate macOS Terminal; `aow service restart` reloads already-installed code. CLI 0.4.3 also supports `aow update --force` to reinstall and restart a verified older service, ending its live tasks. If an older CLI cannot prepare an update, finish terminal work, run `aow service uninstall`, then rerun the installer once. [Setup and troubleshooting](docs/one-command-setup.md) · [Terminal guide](packages/terminal-host/README.md) diff --git a/README.zh-CN.md b/README.zh-CN.md index 4d4efa3..ad333ec 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -72,7 +72,7 @@ codex 点击终端标签栏的 **+** 打开另一个项目,点击标签切换,双击名称重命名,点击 **×** 关闭。隐藏工作区或刷新网页不会中断正在运行的会话。 -终端主机 0.4.3 每天检查 npm 正式版,并在本地管理页显示更新提醒。运行 `aow check-update` 可立即检查,`aow check-update --disable` 可关闭自动检查。退出或关闭所有终端后,在 Mac 的独立“终端”窗口运行 `aow update` 升级;`aow service restart` 用于加载已安装的新代码。CLI 0.4.3 还支持通过 `aow update --force` 重新安装并重启已核实归属的旧服务,这会结束其活动任务。如果旧 CLI 提示无法准备更新,请先完成终端任务,运行 `aow service uninstall`,再重新运行安装命令一次。 +终端主机 0.4.4 每天检查 npm 正式版,并在本地管理页显示更新提醒。运行 `aow check-update` 可立即检查,`aow check-update --disable` 可关闭自动检查。退出或关闭所有终端后,在 Mac 的独立“终端”窗口运行 `aow update` 升级;`aow service restart` 用于加载已安装的新代码。CLI 0.4.3 还支持通过 `aow update --force` 重新安装并重启已核实归属的旧服务,这会结束其活动任务。如果旧 CLI 提示无法准备更新,请先完成终端任务,运行 `aow service uninstall`,再重新运行安装命令一次。 [安装与常见问题](docs/one-command-setup.md) · [终端指南](packages/terminal-host/README.md) diff --git a/apps/terminal-surface/package.json b/apps/terminal-surface/package.json index 712bc4e..b287652 100644 --- a/apps/terminal-surface/package.json +++ b/apps/terminal-surface/package.json @@ -7,8 +7,9 @@ "build": "node ../../scripts/build-terminal-surface.mjs" }, "dependencies": { - "@xterm/xterm": "^5.5.0", - "@xterm/addon-fit": "^0.10.0" + "@xterm/addon-fit": "^0.10.0", + "@xterm/addon-webgl": "0.18.0", + "@xterm/xterm": "5.5.0" }, "devDependencies": { "@agentonweb/connector-contract": "workspace:*" diff --git a/apps/terminal-surface/src/cell-backgrounds.test.ts b/apps/terminal-surface/src/cell-backgrounds.test.ts new file mode 100644 index 0000000..dce2285 --- /dev/null +++ b/apps/terminal-surface/src/cell-backgrounds.test.ts @@ -0,0 +1,26 @@ +import { JSDOM } from "jsdom"; +import type { Terminal } from "@xterm/xterm"; +import { afterEach, expect, it, vi } from "vitest"; +import { installCellBackgroundOpacity } from "./cell-backgrounds.js"; + +let dom: JSDOM; +afterEach(() => { dom?.window.close(); }); +it("does no cell traversal for opaque output or unchanged presentation", () => { + dom = new JSDOM('
Text
'); + const container = dom.window.document.querySelector("main")!; + let render!: (range: { start: number; end: number }) => void; + const setOpacity = installCellBackgroundOpacity({ onRender(fn: typeof render) { render = fn; } } as Terminal, container); + const query = vi.spyOn(container, "querySelector"); + for (let i = 0; i < 100; i++) render({ start: 0, end: 0 }); + setOpacity(1); + expect(query).not.toHaveBeenCalled(); + setOpacity(0.4); + query.mockClear(); + setOpacity(0.4); + expect(query).not.toHaveBeenCalled(); + setOpacity(1); + expect(container.querySelector("span")!.style.backgroundColor).toBe("rgb(32, 71, 51)"); + query.mockClear(); + render({ start: 0, end: 0 }); + expect(query).not.toHaveBeenCalled(); +}); diff --git a/apps/terminal-surface/src/cell-backgrounds.ts b/apps/terminal-surface/src/cell-backgrounds.ts index 16564da..2e15873 100644 --- a/apps/terminal-surface/src/cell-backgrounds.ts +++ b/apps/terminal-surface/src/cell-backgrounds.ts @@ -1,49 +1,81 @@ import type { Terminal } from "@xterm/xterm"; -// xterm's DOM renderer paints ANSI cell backgrounds independently of the theme -// background. Adjust only their rendered colors, leaving PTY attributes intact. +function translucent(color: string, opacity: number): string | undefined { + const hex = /^#([\da-f]{6})$/iu.exec(color); + if (hex) { + const value = Number.parseInt(hex[1]!, 16); + return `rgba(${value >> 16}, ${(value >> 8) & 255}, ${value & 255}, ${opacity})`; + } + const rgb = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/u.exec(color); + if (rgb) return `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${Number(rgb[4] ?? 1) * opacity})`; + return undefined; +} + +// Palette backgrounds are shared CSS rules, so changing their opacity must not +// read computed styles and rewrite thousands of cells on every frame. Only +// truecolor backgrounds need per-cell work. PTY attributes stay untouched. export function installCellBackgroundOpacity(terminal: Terminal, container: HTMLElement) { let opacity = 1; - const originals = new WeakMap(); + const originals = new WeakMap(); + const style = container.ownerDocument.createElement("style"); + container.append(style); + let themeStyle: HTMLStyleElement | undefined; + let observer: MutationObserver | undefined; + function updatePalette() { + const rules: string[] = []; + if (opacity !== 1) { + for (const rule of themeStyle?.sheet?.cssRules ?? []) { + const css = rule as CSSStyleRule; + if (!/\.xterm-bg-\d+$/u.test(css.selectorText ?? "")) continue; + const color = translucent(css.style.getPropertyValue("background-color"), opacity); + if (color) rules.push(`${css.selectorText}:not(.xterm-cursor):not(.xterm-decoration-top){background-color:${color}}`); + } + } + const text = rules.join("\n"); + if (style.textContent !== text) style.textContent = text; + } + function ensurePalette() { + if (themeStyle?.isConnected) return; + observer?.disconnect(); + themeStyle = [...container.querySelectorAll(".xterm-screen style")] + .find(candidate => candidate.textContent?.includes(".xterm-bg-")); + if (themeStyle) { + observer = new container.ownerDocument.defaultView!.MutationObserver(updatePalette); + observer.observe(themeStyle, { childList: true, characterData: true, subtree: true }); + } + updatePalette(); + } function render(start = 0, end = Infinity) { const rows = container.querySelector(".xterm-rows")?.children; if (!rows) return; - const palette = new Map(); + // Reuse conversions within each frame without retaining arbitrary RGB colors. + const colors = new Map(); for (let row = start; row <= end && row < rows.length; row++) { - for (const cell of rows[row]!.querySelectorAll("span")) { - // Preserve xterm's cursor and selection contrast. - if (cell.matches(".xterm-cursor, .xterm-decoration-top")) continue; - let original = originals.get(cell); + for (const cell of rows[row]!.querySelectorAll('span[style*="background-color"]:not(.xterm-cursor):not(.xterm-decoration-top)')) { + const saved = originals.get(cell); if (opacity === 1) { - if (original) { - cell.style.backgroundColor = original.inline; - originals.delete(cell); - } + if (saved !== undefined) { cell.style.backgroundColor = saved; originals.delete(cell); } continue; } - if (!original) { - const inline = cell.style.backgroundColor; - let color = inline; - if (!color) { - const colorClass = [...cell.classList].find(name => name.startsWith("xterm-bg-")); - if (!colorClass) continue; - color = palette.get(colorClass) ?? container.ownerDocument.defaultView!.getComputedStyle(cell).backgroundColor; - palette.set(colorClass, color); - } - const match = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/u.exec(color); - if (!match || Number(match[4] ?? 1) === 0) continue; - original = { inline, channels: match.slice(1) }; - originals.set(cell, original); - } - const [red, green, blue, alpha] = original.channels; - const color = `rgba(${red}, ${green}, ${blue}, ${Number(alpha ?? 1) * opacity})`; + const original = saved ?? cell.style.backgroundColor; + if (!colors.has(original)) colors.set(original, translucent(original, opacity)); + const color = colors.get(original); + if (!color) continue; + originals.set(cell, original); if (cell.style.backgroundColor !== color) cell.style.backgroundColor = color; } } } - terminal.onRender(({ start, end }) => render(start, end)); + terminal.onRender(({ start, end }) => { + if (opacity === 1) return; + ensurePalette(); + render(start, end); + }); return (nextOpacity: number) => { + if (nextOpacity === opacity) return; opacity = nextOpacity; + ensurePalette(); + updatePalette(); render(); }; } diff --git a/apps/terminal-surface/src/main.test.ts b/apps/terminal-surface/src/main.test.ts index 520a860..714520f 100644 --- a/apps/terminal-surface/src/main.test.ts +++ b/apps/terminal-surface/src/main.test.ts @@ -3,13 +3,14 @@ import { JSDOM } from "jsdom"; import { afterEach, expect, it, vi } from "vitest"; const terminalMock = vi.hoisted(() => ({ focus: vi.fn(), + theme: vi.fn(), writes: [] as (() => void)[], input: undefined as ((data: string) => void) | undefined, binary: undefined as ((data: string) => void) | undefined, })); vi.mock("@xterm/xterm", () => ({ Terminal: class { - options: any = {}; + options: any = Object.defineProperty({}, "theme", { set: terminalMock.theme }); modes = { mouseTrackingMode: "none" }; parser = { registerCsiHandler() {}, registerOscHandler() {} }; loadAddon() {} @@ -36,6 +37,7 @@ vi.mock("@xterm/addon-fit", () => ({ } }, })); +vi.mock("@xterm/addon-webgl", () => ({ WebglAddon: class {} })); let dom: JSDOM; afterEach(() => { dom.window.close(); @@ -44,20 +46,22 @@ afterEach(() => { vi.resetModules(); terminalMock.writes.length = 0; terminalMock.focus.mockClear(); + terminalMock.theme.mockClear(); terminalMock.input = terminalMock.binary = undefined; }); -async function terminalFixture() { - dom = new JSDOM(await readFile(new URL("./index.html", import.meta.url), "utf8"), { url: "http://localhost:1234/" }); +async function terminalFixture(hash = "") { + dom = new JSDOM(await readFile(new URL("./index.html", import.meta.url), "utf8"), { url: "http://localhost:1234/" + hash }); for (const key of ["window", "document", "location", "sessionStorage"]) vi.stubGlobal(key, (dom.window as any)[key]); vi.stubGlobal("parent", dom.window); vi.stubGlobal("ResizeObserver", class { observe() {} }); - vi.useFakeTimers({ toFake: ["setTimeout", "setInterval"] }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval"] }); const sockets: any[] = []; vi.stubGlobal("WebSocket", class { static OPEN = 1; readyState = 1; constructor() { sockets.push(this); } - send() {} + sent: any[] = []; + send(data: string) { this.sent.push(JSON.parse(data)); } close() { this.readyState = 3; } }); let failure = 0; @@ -74,6 +78,48 @@ async function terminalFixture() { return { sockets, list, fetch, fail: (status: number) => { failure = status; } }; } +it("coalesces parsed output ACKs while keyboard input is sent immediately", async () => { + const { sockets } = await terminalFixture(); + const socket = sockets[0]; + const emit = (message: object) => socket.onmessage({ data: JSON.stringify(message) }); + emit({ type: "snapshot", epoch: "one", cols: 80, rows: 24, data: "" }); + terminalMock.writes.shift()!(); + emit({ type: "control", epoch: "one", lease: 1, active: true }); + socket.sent.length = 0; + for (let sequence = 1; sequence <= 100; sequence++) { + emit({ type: "output", epoch: "one", sequence, data: "x" }); + terminalMock.writes.shift()!(); + } + terminalMock.input!("typed now"); + expect(socket.sent).toEqual([{ type: "input", epoch: "one", lease: 1, data: "typed now" }]); + await vi.advanceTimersByTimeAsync(0); + expect(socket.sent.at(-1)).toEqual({ type: "ack", sequence: 100 }); + expect(socket.sent).toHaveLength(2); + emit({ type: "output", epoch: "one", sequence: 101, data: "late" }); + terminalMock.writes.shift()!(); + socket.onclose({ code: 1006 }); + await vi.advanceTimersByTimeAsync(0); + expect(socket.sent).toHaveLength(2); +}); + +it("does not repaint on focus messages, duplicate modes or inactive opacity changes", async () => { + await terminalFixture("#agentonweb=fixture"); + const emit = (extra: object) => dom.window.dispatchEvent(new dom.window.MessageEvent("message", { + source: dom.window as unknown as Window, origin: "chrome-extension://fixture", + data: { source: "agentonweb-extension", nonce: "fixture", ...extra }, + })); + emit({ type: "surface.focus" }); + emit({ type: "mode.set", mode: "focus" }); + emit({ type: "opacity.set", opacity: 0.4 }); + expect(terminalMock.theme).not.toHaveBeenCalled(); + emit({ type: "mode.set", mode: "chill" }); + emit({ type: "mode.set", mode: "chill" }); + emit({ type: "opacity.set", opacity: 0.4 }); + expect(terminalMock.theme).toHaveBeenCalledTimes(1); + emit({ type: "mode.set", mode: "focus" }); + expect(terminalMock.theme).toHaveBeenCalledTimes(2); +}); + it("continues automatic retries after a temporary HTTP failure and stops on revoked access", async () => { const fixture = await terminalFixture(); fixture.fail(503); diff --git a/apps/terminal-surface/src/main.ts b/apps/terminal-surface/src/main.ts index 7f301d0..92d38ee 100644 --- a/apps/terminal-surface/src/main.ts +++ b/apps/terminal-surface/src/main.ts @@ -2,8 +2,10 @@ import { surfaceShortcut } from "@agentonweb/connector-contract"; import { OptionTapTracker } from "@agentonweb/connector-contract"; import { Terminal } from "@xterm/xterm"; import { splitInput } from "./input.js"; +import { writeOutput } from "./output.js"; import { installCellBackgroundOpacity } from "./cell-backgrounds.js"; import { installMouseSelection } from "./mouse-selection.js"; +import { installRenderer } from "./renderer.js"; import { FitAddon } from "@xterm/addon-fit"; import "@xterm/xterm/css/xterm.css"; import "./style.css"; @@ -34,6 +36,8 @@ function showStatus(message: string) { terminal.open(container); installMouseSelection(terminal, container); const setCellBackgroundOpacity = installCellBackgroundOpacity(terminal, container); +const setBackgroundOpacity = installRenderer(terminal, setCellBackgroundOpacity); +setBackgroundOpacity(1); const sessionPicker = document.querySelector("#sessions")!; const newButton = document.querySelector("#new")!; type ConnectionState = "background" | "connecting" | "connected" | "disconnected" | "exited"; @@ -286,7 +290,8 @@ function send(message: object) { function resize() { if (!active || !ready || !resizeOwner || !document.hasFocus() || document.hidden || container.clientWidth < 30 || container.clientHeight < 30) return; const size = fit.proposeDimensions(); - if (size && size.cols >= 2 && size.rows >= 2) send({ type: "resize", ...size, epoch, lease }); + if (size && size.cols >= 2 && size.rows >= 2 && (size.cols !== terminal.cols || size.rows !== terminal.rows)) + send({ type: "resize", ...size, epoch, lease }); } function input(data: string, binary = false) { if (!active || !ready) return; @@ -369,6 +374,21 @@ async function connect(automaticRetry = false) { const info = await response.json(); if (current !== generation) return; const ws = new WebSocket(`ws://${location.host}/terminal`, info.token); + let ackTimer: ReturnType | undefined; + let ackSequence = 0; + const acknowledge = (sequence: number) => { + if (current !== generation || ws.readyState !== WebSocket.OPEN) return; + ackSequence = sequence; + if (ackTimer !== undefined) return; + // ACKs are cumulative. One per parser turn avoids thousands of frames + // competing with keyboard input during a burst; never wait for rAF in + // background tabs where it can be suspended. + ackTimer = setTimeout(() => { + ackTimer = undefined; + if (current === generation && ws.readyState === WebSocket.OPEN) + ws.send(JSON.stringify({ type: "ack", sequence: ackSequence })); + }, 0); + }; socket = ws; ws.onmessage = (event) => { if (current !== generation) return; @@ -385,7 +405,7 @@ async function connect(automaticRetry = false) { setConnectionState(m.exitCode !== undefined ? "exited" : "connected"); terminal.reset(); terminal.resize(m.cols, m.rows); - terminal.write(m.data, () => { + writeOutput(terminal, m.data, () => { if (current !== generation) return; ready = true; if (focusOnConnect) { @@ -398,10 +418,7 @@ async function connect(automaticRetry = false) { if (m.exitCode !== undefined) showStatus(`Process exited (${m.exitCode}). Open a new terminal with +.`); } else if (m.type === "output" && m.epoch === epoch) { - terminal.write(m.data, () => { - if (current === generation && ws.readyState === WebSocket.OPEN) - ws.send(JSON.stringify({ type: "ack", sequence: m.sequence })); - }); + writeOutput(terminal, m.data, () => acknowledge(m.sequence)); if (nonce && Date.now() - outputNoticeAt > 1000) { outputNoticeAt = Date.now(); parent.postMessage({ source: "agentonweb-surface", type: "surface.output", nonce }, "*"); @@ -430,6 +447,7 @@ async function connect(automaticRetry = false) { } }; ws.onclose = (event) => { + clearTimeout(ackTimer); if (current !== generation) return; setConnectionState("disconnected"); ready = active = resizeOwner = false; @@ -615,7 +633,11 @@ let authorizedParent = parent === window; let modeShortcuts: readonly string[] = []; let mode = "focus", opacity = 0.82; +let presentedOpacity = 1; function presentation() { + const backgroundOpacity = mode === "chill" ? opacity : 1; + if (backgroundOpacity === presentedOpacity) return; + presentedOpacity = backgroundOpacity; terminal.options.theme = { background: mode === "chill" @@ -625,7 +647,7 @@ function presentation() { : "#15171cff", foreground: "#f1f3f5", }; - setCellBackgroundOpacity(mode === "chill" ? opacity : 1); + setBackgroundOpacity(backgroundOpacity); } window.addEventListener("message", (event) => { if (event.source !== parent || !/^(chrome-extension|moz-extension|safari-web-extension):\/\//u.test(event.origin)) @@ -645,10 +667,14 @@ window.addEventListener("message", (event) => { focusOnConnect = true; void connect(); } - if (m.type === "mode.set" && ["focus", "chill", "watch"].includes(m.mode)) mode = m.mode; - if (m.type === "opacity.set" && typeof m.opacity === "number" && m.opacity >= 0 && m.opacity <= 1) + if (m.type === "mode.set" && ["focus", "chill", "watch"].includes(m.mode)) { + mode = m.mode; + presentation(); + } + if (m.type === "opacity.set" && typeof m.opacity === "number" && m.opacity >= 0 && m.opacity <= 1) { opacity = m.opacity; - presentation(); + presentation(); + } }); const optionTap = new OptionTapTracker(); window.addEventListener("keydown", (event) => { diff --git a/apps/terminal-surface/src/output.test.ts b/apps/terminal-surface/src/output.test.ts new file mode 100644 index 0000000..cceee02 --- /dev/null +++ b/apps/terminal-surface/src/output.test.ts @@ -0,0 +1,20 @@ +import { expect, it } from "vitest"; +import { writeOutput } from "./output.js"; + +it("bounds parser work for a large ANSI/Unicode snapshot and completes after its last chunk", () => { + const writes: { data: string; done: (() => void) | undefined }[] = []; + const terminal = { write(data: string | Uint8Array, done?: () => void) { writes.push({ data: String(data), done }); } }; + const data = "\x1b[42m" + "界👋".repeat(30000) + "\x1b[0m"; + let completed = false; + writeOutput(terminal, data, () => { completed = true; }); + expect(writes.map(write => write.data).join("")).toBe(data); + expect(writes.every(write => write.data.length <= 8192 && !/[\ud800-\udbff]$/u.test(write.data) && !/^[\udc00-\udfff]/u.test(write.data))).toBe(true); + for (const write of writes.slice(0, -1)) write.done?.(); + expect(completed).toBe(false); + writes.at(-1)!.done!(); + expect(completed).toBe(true); + writes.length = 0; + writeOutput(terminal, "", () => {}); + expect(writes).toHaveLength(1); + expect(writes[0]!.done).toBeTypeOf("function"); +}); diff --git a/apps/terminal-surface/src/output.ts b/apps/terminal-surface/src/output.ts new file mode 100644 index 0000000..ce44df7 --- /dev/null +++ b/apps/terminal-surface/src/output.ts @@ -0,0 +1,13 @@ +import type { Terminal } from "@xterm/xterm"; +import { splitInput } from "./input.js"; + +// xterm yields between writes, but cannot yield in the middle of a large +// individual string. Bound snapshot/flood chunks so input gets a turn too. +export function writeOutput(terminal: Pick, data: string, done: () => void) { + if (data.length <= 8192) { terminal.write(data, done); return; } + let remaining = data.length; + for (const chunk of splitInput(data)) { + remaining -= chunk.length; + terminal.write(chunk, remaining === 0 ? done : undefined); + } +} diff --git a/apps/terminal-surface/src/renderer.test.ts b/apps/terminal-surface/src/renderer.test.ts new file mode 100644 index 0000000..a454dd1 --- /dev/null +++ b/apps/terminal-surface/src/renderer.test.ts @@ -0,0 +1,42 @@ +import { afterEach, expect, it, vi } from "vitest"; +import type { Terminal } from "@xterm/xterm"; +import { installRenderer } from "./renderer.js"; + +const addons = vi.hoisted(() => [] as { dispose: ReturnType; loss?: () => void }[]); +const bridge = vi.hoisted(() => ({ setOpacity: vi.fn() })); +vi.mock("./webgl-backgrounds.js", () => ({ installWebglBackgroundOpacity: () => bridge.setOpacity })); +vi.mock("@xterm/addon-webgl", () => ({ WebglAddon: class { + dispose = vi.fn(); + loss?: () => void; + constructor() { addons.push(this); } + onContextLoss(callback: () => void) { this.loss = callback; } +} })); +afterEach(() => { addons.length = 0; bridge.setOpacity.mockClear(); vi.unstubAllGlobals(); }); + +it("keeps the GPU renderer across modes and preserves opacity after context loss", () => { + vi.stubGlobal("WebGL2RenderingContext", class {}); + const loadAddon = vi.fn(); + const fallback = vi.fn(); + const setOpacity = installRenderer({ loadAddon } as unknown as Terminal, fallback); + setOpacity(1); setOpacity(1); + expect(loadAddon).toHaveBeenCalledTimes(1); + setOpacity(0.4); setOpacity(0.2); + expect(addons[0]!.dispose).not.toHaveBeenCalled(); + expect(bridge.setOpacity).toHaveBeenLastCalledWith(0.2); + addons[0]!.loss!(); + expect(addons[0]!.dispose).toHaveBeenCalledTimes(1); + expect(fallback).toHaveBeenLastCalledWith(0.2); + setOpacity(1); + expect(fallback).toHaveBeenLastCalledWith(1); + expect(loadAddon).toHaveBeenCalledTimes(1); +}); + +it("falls back without repeated initialization when WebGL is unavailable", () => { + vi.stubGlobal("WebGL2RenderingContext", class {}); + const loadAddon = vi.fn(() => { throw new Error("Context unavailable"); }); + const fallback = vi.fn(); + const setOpacity = installRenderer({ loadAddon } as unknown as Terminal, fallback); + expect(() => { setOpacity(1); setOpacity(0.4); setOpacity(1); }).not.toThrow(); + expect(loadAddon).toHaveBeenCalledTimes(1); + expect(addons[0]!.dispose).toHaveBeenCalledTimes(1); +}); diff --git a/apps/terminal-surface/src/renderer.ts b/apps/terminal-surface/src/renderer.ts new file mode 100644 index 0000000..60a0e1f --- /dev/null +++ b/apps/terminal-surface/src/renderer.ts @@ -0,0 +1,36 @@ +import { WebglAddon } from "@xterm/addon-webgl"; +import type { Terminal } from "@xterm/xterm"; +import { installWebglBackgroundOpacity } from "./webgl-backgrounds.js"; + +/** Keep one GPU renderer across modes; use DOM only if GPU support fails. */ +export function installRenderer(terminal: Terminal, setDomOpacity: (opacity: number) => void) { + let addon: WebglAddon | undefined; + let setGpuOpacity: ((opacity: number) => void) | undefined; + let opacity = 1; + let unavailable = typeof WebGL2RenderingContext === "undefined"; + return (nextOpacity: number) => { + opacity = nextOpacity; + if (unavailable) { setDomOpacity(opacity); return; } + if (addon) { setGpuOpacity!(opacity); return; } + let candidate: WebglAddon | undefined; + try { + candidate = new WebglAddon(); + candidate.onContextLoss(() => { + unavailable = true; + addon?.dispose(); + addon = undefined; + setGpuOpacity = undefined; + setDomOpacity(opacity); + }); + terminal.loadAddon(candidate); + setGpuOpacity = installWebglBackgroundOpacity(candidate, terminal); + setGpuOpacity(opacity); + addon = candidate; + } catch { + // Disabled GPUs and exhausted contexts must leave a usable DOM terminal. + candidate?.dispose(); + unavailable = true; + setDomOpacity(opacity); + } + }; +} diff --git a/apps/terminal-surface/src/webgl-backgrounds.test.ts b/apps/terminal-surface/src/webgl-backgrounds.test.ts new file mode 100644 index 0000000..bb96b96 --- /dev/null +++ b/apps/terminal-surface/src/webgl-backgrounds.test.ts @@ -0,0 +1,64 @@ +import { expect, it, vi } from "vitest"; +import type { Terminal } from "@xterm/xterm"; +import type { WebglAddon } from "@xterm/addon-webgl"; +import { installWebglBackgroundOpacity } from "./webgl-backgrounds.js"; + +function fixture() { + const terminal = { cols: 8, rows: 2, buffer: { active: { viewportY: 1000 } }, refresh: vi.fn() }; + const source = new Float32Array([0, 0, 1, 1, 0.1, 0.2, 0.3, 0.4, 0, 0, 1, 0.5, 0.2, 0.3, 0.4, 1]); + const makeRectangles = () => ({ _vertices: { attributes: source, count: 2 }, _renderVertices: vi.fn(), renderBackgrounds: vi.fn() }); + const rectangles = makeRectangles(); + const selection = { hasSelection: false, isCellSelected: (_terminal: unknown, x: number, y: number) => y === 1000 && x >= 2 && x < 4 }; + const model: { selection: typeof selection; cursor?: { x: number; y: number; width: number; style: string } } = { selection }; + const gl = { clearColor: vi.fn(), clear: vi.fn(), blendFuncSeparate: vi.fn(), blendFunc: vi.fn(), + COLOR_BUFFER_BIT: 0x4000, SRC_ALPHA: 0x302, ONE_MINUS_SRC_ALPHA: 0x303, ONE: 1 }; + const renderer = { _gl: gl, _rectangleRenderer: { value: rectangles }, _model: model, renderRows: () => { renderer._rectangleRenderer.value.renderBackgrounds(); } }; + const addon = { _renderer: renderer }; + const setOpacity = installWebglBackgroundOpacity(addon as unknown as WebglAddon, terminal as unknown as Terminal); + return { terminal, source, rectangles, selection, model, renderer, setOpacity, makeRectangles }; +} + +it("changes only background alpha and reuses its bounded viewport buffer", () => { + const f = fixture(); + f.setOpacity(0.4); + f.renderer.renderRows(); + const vertices = f.rectangles._renderVertices.mock.calls[0]![0]; + expect(vertices.count).toBe(2); + expect(vertices.attributes[7]).toBe(0); // Do not double-paint the CSS background. + expect(vertices.attributes[15]).toBeCloseTo(0.4); + expect(f.source[15]).toBe(1); // Never mutate xterm's canonical draw data. + expect(f.renderer._gl.blendFuncSeparate).toHaveBeenCalledWith(0x302, 0x303, 1, 0x303); + f.renderer.renderRows(); + expect(f.rectangles._renderVertices.mock.calls[1]![0].attributes).toBe(vertices.attributes); + f.setOpacity(1); + expect(f.terminal.refresh).toHaveBeenCalledTimes(2); + f.renderer.renderRows(); + expect(f.rectangles._renderVertices).toHaveBeenCalledTimes(2); +}); + +it("splits merged colors around selection and wide cursors without fading either", () => { + const f = fixture(); + f.selection.hasSelection = true; + f.model.cursor = { x: 5, y: 0, width: 2, style: "block" }; + f.setOpacity(0.2); + f.renderer.renderRows(); + const { attributes, count } = f.rectangles._renderVertices.mock.calls[0]![0]; + const spans = Array.from({ length: count - 1 }, (_, index) => { + const i = (index + 1) * 8; + return [Math.round(attributes[i] * 8), Math.round(attributes[i + 2] * 8), Number(attributes[i + 7].toFixed(2))]; + }); + expect(spans).toEqual([[0, 2, 0.2], [2, 2, 1], [4, 1, 0.2], [5, 2, 1], [7, 1, 0.2]]); +}); + +it("reattaches after context restoration replaces the rectangle renderer", () => { + const f = fixture(); + f.setOpacity(0.3); + const restored = f.makeRectangles(); + f.renderer._rectangleRenderer.value = restored; + f.renderer.renderRows(); + expect(restored._renderVertices.mock.calls[0]![0].attributes[15]).toBeCloseTo(0.3); +}); + +it("rejects incompatible addon internals so the caller can use the DOM fallback", () => { + expect(() => installWebglBackgroundOpacity({} as WebglAddon, {} as Terminal)).toThrow("Unsupported"); +}); diff --git a/apps/terminal-surface/src/webgl-backgrounds.ts b/apps/terminal-surface/src/webgl-backgrounds.ts new file mode 100644 index 0000000..ecc889a --- /dev/null +++ b/apps/terminal-surface/src/webgl-backgrounds.ts @@ -0,0 +1,119 @@ +import type { Terminal } from "@xterm/xterm"; +import type { WebglAddon } from "@xterm/addon-webgl"; + +interface Vertices { attributes: Float32Array; count: number } +interface RenderModel { + selection: { hasSelection: boolean; isCellSelected(terminal: Terminal, x: number, y: number): boolean }; + cursor?: { x: number; y: number; width: number; style: string }; +} +interface Rectangles { + _vertices: Vertices; + _renderVertices(vertices: Vertices): void; + renderBackgrounds(): void; +} +interface Renderer { + _gl: WebGL2RenderingContext; + _model: RenderModel; + _rectangleRenderer: { value?: Rectangles }; + renderRows(start: number, end: number): void; +} + +/** + * Compatibility boundary for the pinned xterm 5.5.0 / WebGL addon 0.18.0. + * The public addon only supports transparency for the default background; its + * ANSI/truecolor rectangles always have alpha=1. Adapt that draw batch, not the + * terminal buffer or glyph atlas. No DOM cells are created or inspected. + * + * Vertex layout: normalized x/y/width/height, then RGBA (8 floats). The first + * rectangle is the viewport background; in Chill the viewport's CSS already + * paints it, so the GPU layer must not paint it a second time. + * Check this boundary and the real-browser pixel test before upgrading xterm. + */ +export function installWebglBackgroundOpacity(addon: WebglAddon, terminal: Terminal) { + const renderer = (addon as unknown as { _renderer?: Renderer })._renderer; + const supported = (rectangles: Rectangles | undefined): rectangles is Rectangles => Boolean( + rectangles && rectangles._vertices?.attributes instanceof Float32Array + && typeof rectangles._renderVertices === "function" && typeof rectangles.renderBackgrounds === "function", + ); + if (!renderer || typeof renderer.renderRows !== "function" + || typeof renderer._gl?.blendFuncSeparate !== "function" + || typeof renderer._model?.selection?.isCellSelected !== "function" + || !supported(renderer._rectangleRenderer?.value)) throw new Error("Unsupported WebGL background renderer"); + + let opacity = 1; + let rectangles: Rectangles | undefined; + let scratch: Vertices = { attributes: new Float32Array(0), count: 0 }; + function attach() { + const next = renderer!._rectangleRenderer.value; + if (next === rectangles) return; + if (!supported(next)) throw new Error("Unsupported restored WebGL background renderer"); + rectangles = next; + const draw = next.renderBackgrounds; + next.renderBackgrounds = () => { + if (opacity === 1) { draw.call(next); return; } + const source = next._vertices; + // At most one rectangle per visible cell, plus the viewport. Reuse this + // storage across scroll/selection frames; history length is irrelevant. + const capacity = (terminal.cols * terminal.rows + 1) * 8; + if (scratch.attributes.length < capacity) scratch = { attributes: new Float32Array(capacity), count: 0 }; + const target = scratch.attributes; + const data = source.attributes; + target.set(data.subarray(0, 8)); + target[7] = 0; // Default background comes from the viewport's CSS. + scratch.count = source.count ? 1 : 0; + const model = renderer!._model; + const viewportY = terminal.buffer.active.viewportY; + const cursor = model.cursor?.style === "block" ? model.cursor : undefined; + const selected = model.selection.hasSelection; + function emit(offset: number, start: number, end: number, alpha: number) { + const output = scratch.count++ * 8; + target[output] = start / terminal.cols; + target[output + 1] = data[offset + 1]!; + target[output + 2] = (end - start) / terminal.cols; + for (let channel = 3; channel < 7; channel++) target[output + channel] = data[offset + channel]!; + target[output + 7] = alpha; + } + for (let i = 8; i < source.count * 8; i += 8) { + const row = Math.round(data[i + 1]! * terminal.rows); + const start = Math.round(data[i]! * terminal.cols); + const end = Math.round((data[i]! + data[i + 2]!) * terminal.cols); + const alpha = data[i + 7]!; + if (!selected && cursor?.y !== row) { emit(i, start, end, alpha * opacity); continue; } + // Split at selection/cursor boundaries even if their color happens to + // equal the surrounding ANSI background and xterm merged the rectangles. + let segment = start; + let previous = -1; + for (let x = start; x < end; x++) { + const opaque = (selected && model.selection.isCellSelected(terminal, x, row + viewportY)) + || (cursor?.y === row && x >= cursor.x && x < cursor.x + cursor.width); + const nextAlpha = opaque ? alpha : alpha * opacity; + if (previous !== -1 && nextAlpha !== previous) { emit(i, segment, x, previous); segment = x; } + previous = nextAlpha; + } + if (end > start) emit(i, segment, end, previous); + } + next._renderVertices(scratch); + }; + } + attach(); + // WebGL can restore a context without recreating the addon. Reattach to its + // new rectangle renderer before the first restored frame is drawn. + const renderRows = renderer.renderRows; + renderer.renderRows = (start, end) => { + attach(); + if (opacity === 1) { renderRows.call(renderer, start, end); return; } + const gl = renderer._gl; + // With transparent rectangles, source alpha must not be multiplied by + // itself. Clear instead of blending another background over the last frame. + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + try { renderRows.call(renderer, start, end); } + finally { gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } + }; + return (nextOpacity: number) => { + if (opacity === nextOpacity) return; + opacity = nextOpacity; + terminal.refresh(0, terminal.rows - 1); + }; +} diff --git a/docs/architecture.md b/docs/architecture.md index 026ce00..071655d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -25,6 +25,21 @@ The local terminal launches a new interactive login shell in the user's home dir The terminal runtime ID is `terminal`. `@agentonweb/terminal-host` launches the user’s shell; installed CLI tools run inside that shell. +Focus and Chill share one WebGL renderer, including while scrolling history or +changing opacity. Chill changes only the visible background draw batch; glyphs, +the cursor and selection remain opaque. A reusable viewport-sized buffer keeps +this work independent of history length. `webgl-backgrounds.ts` isolates the +version-specific bridge for pinned xterm 5.5.0 / WebGL addon 0.18.0; upgrading +either requires its unit and real-browser pixel tests. Context restoration +reattaches the bridge to the restored draw objects. Initialization failure or +unrecoverable context loss falls back to DOM rendering with the same opacity. +The DOM fallback uses shared palette CSS and per-cell truecolor updates. +Unchanged presentation messages do not rebuild the theme. Large snapshots and +output strings are parsed in bounded chunks, with cumulative acknowledgements +coalesced after parsing. The host drains acknowledged queue entries in sequence +order, and only changes PTY flow control or size when the corresponding state +changes. Scrollback remains 3,000 lines. + ## Process and connection lifetime A host owns up to eight shells. Viewers attach to a shell's canonical headless terminal snapshot and then receive ordered output. Detaching a viewer, closing the overlay, refreshing a page or switching runtimes does not stop the shell. Every connected viewer can type into the same shell. Only the focused viewer controls resizing; focus changes rotate the resize lease. Input is not replayed after an uncertain disconnect. Binary terminal events preserve their bytes separately from Unicode text. diff --git a/docs/development.md b/docs/development.md index 9e1f762..d9d4288 100644 --- a/docs/development.md +++ b/docs/development.md @@ -34,6 +34,21 @@ pnpm release:audit For an offline presentation sample, run `pnpm build:preview` and `pnpm preview`. The sample does not execute commands. See the [architecture](architecture.md) and [release guide](releasing.md) for implementation and packaging details. +For terminal performance regressions, build the terminal surface and run +`scripts/check-terminal-performance-browser.mjs --deps --chromium `. +It exercises the actual browser UI with 3,000 history lines, continuous ANSI +redraws and concurrent typing under 4× CPU throttling, checking ordered input and +100 ms p95 keyboard/frame budgets at 120×40. Optional `--profile ` captures +a CPU profile; `--columns`, `--rows`, `--history` and `--assets` support stress and +before/after comparisons. Add `--scroll --columns 140 --rows 48` to test actual +wheel and native scrollbar dragging through dense, varying colored history; +`--live` adds ongoing output and `--dom` measures the fallback baseline. The +scroll frame budget is 50 ms. The transport is a local fixture; the installed +host and existing browser profile are untouched. The copy browser check accepts +`--chill` and `--dom`. `check-terminal-presentation-browser.mjs` checks actual +pixels for background transparency, opaque text/cursor/selection, mode changes, +GPU context restoration and DOM fallback. + [Report an issue](https://github.com/HeftyKoo/AgentOnWeb/issues) · [Privacy policy](https://heftykoo.github.io/AgentOnWeb/privacy.html) diff --git a/docs/releasing.md b/docs/releasing.md index b611bb7..65c6204 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,6 +1,12 @@ # Release AgentOnWeb -## Extension launcher patch release +## Terminal performance patch release + +Terminal host **0.4.4** improves terminal typing and scrolling during dense output. Focus and Chill retain one WebGL renderer with translucent cell backgrounds and a DOM fallback. Output chunks, cumulative acknowledgements and host queue draining keep input responsive without reducing the 3,000-line history. See the [performance verification record](verification/terminal-performance-2026-11-05.md) for workload limits and browser acceptance. + +Publish only `terminal-v0.4.4`: the audited npm package, version-pinned installer and GitHub release. Extension **0.4.2**, Safari source **0.4.2** / build **11**, DSH **0.4.0** and connector protocol **1** retain their versions; no browser-store submission is needed. After finishing live shells, run `aow update` from a separate macOS Terminal. + +## Previous extension launcher patch release Extension **0.4.2** adds mouse and touch dragging for the floating launcher, remembers its position across pages and reloads, and keeps the controls within the viewport. This release targets the Chrome Web Store and Firefox Add-ons. Safari source metadata is prepared at **0.4.2** / build **11**, without submitting a Safari update. Terminal host **0.4.3**, DSH **0.4.0** and connector protocol **1** are unchanged. @@ -10,7 +16,7 @@ Extension **0.4.2** adds mouse and touch dragging for the floating launcher, rem | DSH plugin TGZ | `pluginVersion` | Remains 0.4.0; no publication | | Terminal host TGZ + installer | `terminalHostVersion` | Remains 0.4.3; no publication | -## Terminal host update patch release +## Previous terminal host update patch release Terminal host **0.4.3** repairs forced updates when an older host is still running, reinstalls the current stable version on explicit force, and retries transient manual npm checks with longer deadlines. It retains the direct terminal selection improvements from 0.4.2. Extension **0.4.1**, Safari marketing version **0.4.1** / build **10**, DSH **0.4.0** and connector protocol **1** remain unchanged; this release publishes only the terminal host. @@ -56,19 +62,19 @@ The `dsh-latest` CI job installs `@deepseek-ai/dsh@latest`, builds the actual pl After the relevant release is public, users can run: ```sh -npm install -g @agentonweb/terminal-host@0.4.3 +npm install -g @agentonweb/terminal-host@0.4.4 # Repair setup or run it explicitly when lifecycle scripts were blocked: aow setup ``` -The release installer at `https://github.com/HeftyKoo/AgentOnWeb/releases/download/terminal-v0.4.3/install.sh` pins the package to 0.4.3 and explicitly calls setup. The user-facing command downloads `https://raw.githubusercontent.com/HeftyKoo/AgentOnWeb/main/scripts/install.sh`. Both that script and its pinned npm package must be live before announcing the installation flow. The installer uses the user-owned `~/.local` npm prefix, configures zsh/bash/fish startup paths, and links `aow` beside Node when that directory is writable and already on PATH. Existing AgentOnWeb npm links are updated; unrelated commands are preserved. The versioned release URL is a publication target, not proof that the asset exists. Download and inspect it before running it; do not advertise it until the release and clean-install test succeed. +The release installer at `https://github.com/HeftyKoo/AgentOnWeb/releases/download/terminal-v0.4.4/install.sh` pins the package to 0.4.4 and explicitly calls setup. The user-facing command downloads `https://raw.githubusercontent.com/HeftyKoo/AgentOnWeb/main/scripts/install.sh`. Both that script and its pinned npm package must be live before announcing the installation flow. The installer uses the user-owned `~/.local` npm prefix, configures zsh/bash/fish startup paths, and links `aow` beside Node when that directory is writable and already on PATH. Existing AgentOnWeb npm links are updated; unrelated commands are preserved. The versioned release URL is a publication target, not proof that the asset exists. Download and inspect it before running it; do not advertise it until the release and clean-install test succeed. ## Local installation and upgrades Before publishing, use the audited archive with the source-built extension: ```sh -AOW_SKIP_SETUP=1 npm install -g ./release/agentonweb-terminal-host-0.4.3.tgz +AOW_SKIP_SETUP=1 npm install -g ./release/agentonweb-terminal-host-0.4.4.tgz aow setup --extension-id YOUR_UNPACKED_CHROME_EXTENSION_ID ``` diff --git a/docs/verification/terminal-performance-2026-11-05.md b/docs/verification/terminal-performance-2026-11-05.md new file mode 100644 index 0000000..2e0e8d4 --- /dev/null +++ b/docs/verification/terminal-performance-2026-11-05.md @@ -0,0 +1,112 @@ +# Terminal performance — 2026-11-05 + +Initial scope: local source/build validation. No installed host restart, extension reload +in the user's browser, commit, package publication or release was performed. +Existing user terminal sessions were preserved. + +## Reproduction and findings + +The real terminal-surface bundle was served by a local HTTP fixture. Only the +host transport was replaced. CPU throttling was fixed at 4×. The final Chill +checks use 3,000 varying, densely colored history lines at 140×48, actual mouse +wheel events and dragging the native scrollbar. Playwright's default hidden +scrollbars are disabled in the fixture; tests assert that the viewport actually +moves through history. Interaction timings include dispatch plus two animation +frames, while typing timings measure key dispatch completion, not a complete +browser-to-PTY echo round trip. Timings vary by machine and browser load. + +| Chill metric (p95) | DOM path before | Final WebGL path | +| --- | ---: | ---: | +| Wheel response | 197 ms | 61 ms | +| Wheel frame interval | 117 ms | 17 ms | +| Scrollbar drag response | 271 ms | 43 ms | +| Scrollbar drag frame interval | 133 ms | 33 ms | + +The final GPU run recorded zero main-thread long tasks for both interactions +(the DOM run recorded 24/33). With continuous output while reading history, +wheel/drag response p95 remained 62/47 ms, both frame p95 values were 17 ms, +and neither interaction was pulled back to the bottom. The benchmark enforces +100 ms interaction and 50 ms scroll-frame budgets. The DOM baseline is the same +bundle with WebGL disabled, exercising the previous Chill render path. + +The initial full-screen redraw workload reproduced 134 ms Focus / 179 ms Chill +keyboard p95. Removing history still reproduced 112 ms / 146 ms, isolating dense +visible redraws as a sufficient trigger. At the same 140×48 size, the final +continuous full-screen output test measured 4 ms Focus / 3 ms Chill keyboard +p95 and 17 ms frame p95 in both modes, with all 24 typed characters delivered in +order and zero long tasks. Scrollback remains 3,000 lines; it was not reduced to +obtain these improvements. GPU-disabled environments still use the slower DOM +fallback, so these figures are not a guarantee for every device or workload. + +CPU profiling identified the per-render cell-opacity scan and DOM row rebuilding +as hot paths. Both modes now retain one GPU canvas. A small compatibility bridge +for the pinned xterm 5.5.0 / WebGL addon 0.18.0 adjusts only background vertices, +splitting merged rectangles at selection and wide-cursor boundaries. The GPU +layer is cleared and uses separate RGB/alpha blending to avoid double-painting +the CSS background or multiplying alpha by itself. Screenshot pixel comparisons +with DOM at 0.4, 0.2 and opaque settings agree within 3/255 per channel. Text, +selection and cursor stay opaque. Restoration reattaches the bridge to the new +draw objects; unrecoverable context loss restores a usable translucent DOM view. +Duplicate presentation updates do not rebuild themes or the GPU context. + +The host regression fixture also reproduced 8,002,000 queue-entry visits while +acknowledging 4,000 outstanding output frames. Ordered draining now requires at +most 8,000 visits. The browser coalesces cumulative ACKs per parser turn and writes +large snapshots/output in chunks of at most 8,192 UTF-16 units without splitting +surrogate pairs. Typing is sent immediately. Redundant PTY pause/resume calls and +unchanged viewport broadcasts are suppressed. + +## Commands and acceptance + +```sh +pnpm --config.verify-deps-before-run=false check +node scripts/check-terminal-performance-browser.mjs --deps "$PLAYWRIGHT_PREFIX" --chromium "$CHROMIUM_BIN" +node scripts/check-terminal-performance-browser.mjs --deps "$PLAYWRIGHT_PREFIX" --chromium "$CHROMIUM_BIN" --scroll --columns 140 --rows 48 +node scripts/check-terminal-performance-browser.mjs --deps "$PLAYWRIGHT_PREFIX" --chromium "$CHROMIUM_BIN" --scroll --live --columns 140 --rows 48 +node scripts/check-terminal-presentation-browser.mjs --deps "$PLAYWRIGHT_PREFIX" --chromium "$CHROMIUM_BIN" +node scripts/check-terminal-copy-browser.mjs --deps "$PLAYWRIGHT_PREFIX" --chromium "$CHROMIUM_BIN" +node scripts/check-terminal-copy-browser.mjs --deps "$PLAYWRIGHT_PREFIX" --chromium "$CHROMIUM_BIN" --dom +node scripts/check-terminal-copy-browser.mjs --deps "$PLAYWRIGHT_PREFIX" --chromium "$CHROMIUM_BIN" --chill +node scripts/check-terminal-copy-browser.mjs --deps "$PLAYWRIGHT_PREFIX" --chromium "$CHROMIUM_BIN" --chill --dom +node scripts/check-terminal-mode-focus-browser.mjs --deps "$PLAYWRIGHT_PREFIX" --chromium "$CHROMIUM_BIN" +``` + +- Full check: 441 tests passed, 2 intentionally skipped; privacy/architecture, + TypeScript, Chrome/Firefox/Safari builds and Safari native validation passed. + Dependency auto-install was disabled for this run after tightening the xterm + version range; installed dependency resolutions were unchanged. +- Real Chrome copy checks passed in both WebGL and forced DOM paths: mouse + reporting off/1000/1002/1003, direct drag, reverse Chinese selection, right-click + copy, double-click word selection and native TUI click/wheel forwarding. +- Chrome for Testing 156.0.8078.4 with an isolated unpacked extension and actual + PTY passed keyboard-only Focus/Chill/Watch transitions, five repeated mode + cycles, 15 background presentation updates without lost focus, and shell input. +- Unit coverage checks renderer failure/context loss, no-op presentation, cell + opacity and selection, Unicode snapshot chunks, cumulative ACK ordering and + cancellation, shared input, slow viewers, PTY watermarks and viewport deduping. +- `git diff --check` passed. No debug logging was retained. + +The browser fixture accepts `--assets` for a baseline bundle, `--profile` for a +CPU profile, `--scroll`/`--live`/`--dom` for interaction comparisons, and +`--columns`, `--rows`, `--history` for further stress cases. Timing +budgets are a manual performance check; deterministic queue/work-count +regressions run in the ordinary test suite. + +## Terminal host 0.4.4 release preparation + +The release preparation reran `pnpm install --frozen-lockfile` and +`pnpm release:audit` with terminal host 0.4.4, extension 0.4.2 and DSH 0.4.0. +All 441 tests passed, with two optional integration tests skipped. Privacy, +architecture, TypeScript, Chrome/Firefox/Safari builds, Safari native validation, +reproducible archives and isolated production installation passed. The packed +host passed Claude/Pi install/uninstall, authenticated assets and real shell I/O. + +Chrome for Testing 156.0.8078.4 release-build checks passed at 140×48 under 4× +CPU throttling: Focus/Chill typing p95 was 4/3 ms, and continuous-output Chill +wheel/scrollbar-drag p95 was 61/49 ms. Frame p95 was 17 ms with zero long tasks. +The GPU/DOM pixel comparison, context restoration/loss, Chill GPU and DOM copy +checks, and isolated extension/PTY keyboard mode checks all passed again. +The user's installed host and live terminal sessions were preserved. + +These are pre-publication checks. Public npm installation and release checksums +must be verified after the tag workflow publishes the package. diff --git a/packages/terminal-core/src/index.ts b/packages/terminal-core/src/index.ts index fc4209a..d9e2e5e 100644 --- a/packages/terminal-core/src/index.ts +++ b/packages/terminal-core/src/index.ts @@ -17,6 +17,7 @@ export class TerminalSession { #lease = 0; #sequence = 0; #pendingBytes = 0; + #paused = false; #exited: number | undefined; constructor(executable: string, args: string[], cwd: string, env: Record) { @@ -26,10 +27,13 @@ export class TerminalSession { this.terminal.onData(data => { if (this.#exited === undefined) this.pty.write(data); }); this.pty.onData(data => { this.#pendingBytes += data.length; - if (this.#pendingBytes > 256_000) this.pty.pause(); + if (!this.#paused && this.#pendingBytes > 256_000) { this.#paused = true; this.pty.pause(); } this.terminal.write(data, () => { this.#pendingBytes -= data.length; - if (this.#pendingBytes < 64_000 && this.#exited === undefined) this.pty.resume(); + if (this.#paused && this.#pendingBytes < 64_000 && this.#exited === undefined) { + this.#paused = false; + this.pty.resume(); + } const sequence = ++this.#sequence; for (const [id, client] of this.#clients) { if (!client.ready) continue; @@ -67,7 +71,13 @@ export class TerminalSession { if (!client || !message || typeof message !== "object") return; const m = message as Record; if (m.type === "ack" && Number.isSafeInteger(m.sequence)) { - for (const [seq, bytes] of client.outstanding) if (seq <= (m.sequence as number)) { client.bytes -= bytes; client.outstanding.delete(seq); } + // Map insertion order is output sequence order. Never rescan the entire + // unacknowledged tail for every ACK (quadratic during output bursts). + for (const [seq, bytes] of client.outstanding) { + if (seq > (m.sequence as number)) break; + client.bytes -= bytes; + client.outstanding.delete(seq); + } return; } if (!client.ready || m.epoch !== this.epoch || this.#exited !== undefined) return; @@ -87,6 +97,7 @@ export class TerminalSession { && /^[\x00-\xff]*$/u.test(m.data)) this.pty.write(Buffer.from(m.data, "latin1")); if (m.type === "resize" && id === this.#resizeOwner && m.lease === this.#lease && Number.isInteger(m.cols) && Number.isInteger(m.rows) && (m.cols as number) >= 2 && (m.cols as number) <= 500 && (m.rows as number) >= 2 && (m.rows as number) <= 300) { + if (m.cols === this.terminal.cols && m.rows === this.terminal.rows) return; this.terminal.resize(m.cols as number, m.rows as number); this.pty.resize(m.cols as number, m.rows as number); this.#broadcast({ type: "resize", cols: m.cols, rows: m.rows }); diff --git a/packages/terminal-core/src/performance.test.ts b/packages/terminal-core/src/performance.test.ts new file mode 100644 index 0000000..7c72e2c --- /dev/null +++ b/packages/terminal-core/src/performance.test.ts @@ -0,0 +1,66 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { TerminalSession } from "./index.js"; + +const pty = vi.hoisted(() => ({ + data: undefined as ((data: string) => void) | undefined, + exit: undefined as ((event: { exitCode: number }) => void) | undefined, + write: vi.fn(), resize: vi.fn(), pause: vi.fn(), resume: vi.fn(), kill: vi.fn(), +})); +vi.mock("node-pty", () => ({ spawn: () => ({ ...pty, + onData(callback: typeof pty.data) { pty.data = callback; }, + onExit(callback: typeof pty.exit) { pty.exit = callback; }, +}) })); +let session: TerminalSession; +afterEach(() => { session?.dispose(); vi.restoreAllMocks(); vi.clearAllMocks(); }); +const parsed = () => new Promise(done => session.terminal.write("", done)); +async function fixture() { + session = new TerminalSession("fixture", [], "/", {}); + const messages: any[] = []; + const close = vi.fn(); + const id = session.attach({ send: message => messages.push(message), close }); + await parsed(); + return { id, messages, close }; +} + +it("keeps cumulative ACK work linear while a viewer drains a large output backlog", async () => { + const { id, messages } = await fixture(); + for (let i = 0; i < 4000; i++) pty.data!("x"); + await parsed(); + // Count queue entries visited, not machine-dependent timing. This exercises + // the real parser/broadcast/receive chain with many outstanding output frames. + const frames = messages.filter(message => message.type === "output"); + let visited = 0; + const original = Map.prototype[Symbol.iterator]; + const iterator = vi.spyOn(Map.prototype, Symbol.iterator).mockImplementation(function* (this: Map) { + for (const entry of original.call(this)) { visited++; yield entry; } + return undefined; + }); + for (const frame of frames) session.receive(id, { type: "ack", sequence: frame.sequence }); + iterator.mockRestore(); + expect(visited).toBeLessThanOrEqual(frames.length * 2); + session.receive(id, { type: "input", epoch: session.epoch, data: "responsive" }); + expect(pty.write).toHaveBeenLastCalledWith("responsive"); +}); + +it("only pauses and resumes the PTY when crossing parser watermarks", async () => { + await fixture(); + pty.data!("small output"); + await parsed(); + expect(pty.resume).not.toHaveBeenCalled(); + for (let i = 0; i < 40; i++) pty.data!("x".repeat(8192)); + await parsed(); + expect(pty.pause).toHaveBeenCalledTimes(1); + expect(pty.resume).toHaveBeenCalledTimes(1); +}); + +it("ignores unchanged viewport sizes without resizing the PTY or notifying viewers", async () => { + const { id, messages } = await fixture(); + session.receive(id, { type: "focus", epoch: session.epoch }); + const control = messages.at(-1); + const size = { type: "resize", epoch: session.epoch, lease: control.lease, cols: 100, rows: 30 }; + for (let i = 0; i < 20; i++) session.receive(id, size); + expect(pty.resize).not.toHaveBeenCalled(); + expect(messages.filter(message => message.type === "resize")).toHaveLength(0); + session.receive(id, { ...size, cols: 80 }); + expect(pty.resize).toHaveBeenCalledTimes(1); +}); diff --git a/packages/terminal-host/package.json b/packages/terminal-host/package.json index 48e339a..114091e 100644 --- a/packages/terminal-host/package.json +++ b/packages/terminal-host/package.json @@ -1,6 +1,6 @@ { "name": "@agentonweb/terminal-host", - "version": "0.4.3", + "version": "0.4.4", "type": "module", "license": "MIT", "description": "Your local interactive shell in AgentOnWeb", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 18064b2..a4ea7bb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -48,8 +48,11 @@ importers: '@xterm/addon-fit': specifier: ^0.10.0 version: 0.10.0(@xterm/xterm@5.5.0) + '@xterm/addon-webgl': + specifier: 0.18.0 + version: 0.18.0(@xterm/xterm@5.5.0) '@xterm/xterm': - specifier: ^5.5.0 + specifier: 5.5.0 version: 5.5.0 devDependencies: '@agentonweb/connector-contract': @@ -768,6 +771,11 @@ packages: peerDependencies: '@xterm/xterm': ^5.0.0 + '@xterm/addon-webgl@0.18.0': + resolution: {integrity: sha512-xCnfMBTI+/HKPdRnSOHaJDRqEpq2Ugy8LEj9GiY4J3zJObo3joylIFaMvzBwbYRg8zLtkO0KQaStCeSfoaI2/w==} + peerDependencies: + '@xterm/xterm': ^5.0.0 + '@xterm/headless@5.5.0': resolution: {integrity: sha512-5xXB7kdQlFBP82ViMJTwwEc3gKCLGKR/eoxQm4zge7GPBl86tCdI0IdPJjoKd8mUSFXz5V7i/25sfsEkP4j46g==} @@ -1958,6 +1966,10 @@ snapshots: dependencies: '@xterm/xterm': 5.5.0 + '@xterm/addon-webgl@0.18.0(@xterm/xterm@5.5.0)': + dependencies: + '@xterm/xterm': 5.5.0 + '@xterm/headless@5.5.0': {} '@xterm/xterm@5.5.0': {} diff --git a/release-contract.json b/release-contract.json index 23f78d9..6ccdc0a 100644 --- a/release-contract.json +++ b/release-contract.json @@ -1,7 +1,7 @@ { "extensionVersion": "0.4.2", "pluginVersion": "0.4.0", - "terminalHostVersion": "0.4.3", + "terminalHostVersion": "0.4.4", "dsh": "0.1.7-rc.2", "connectorProtocol": 1, "artifacts": { @@ -9,6 +9,6 @@ "firefoxExtension": "agentonweb-extension-firefox-0.4.2.zip", "extensionSource": "agentonweb-extension-source-0.4.2.zip", "dshPlugin": "agentonweb-dsh-surface-0.4.0.tgz", - "terminalHost": "agentonweb-terminal-host-0.4.3.tgz" + "terminalHost": "agentonweb-terminal-host-0.4.4.tgz" } } diff --git a/scripts/check-terminal-copy-browser.mjs b/scripts/check-terminal-copy-browser.mjs index 419bfb4..d824497 100644 --- a/scripts/check-terminal-copy-browser.mjs +++ b/scripts/check-terminal-copy-browser.mjs @@ -7,7 +7,7 @@ import { resolve } from "node:path"; import { pathToFileURL } from "node:url"; import { parseArgs } from "node:util"; -const { values } = parseArgs({ options: { deps: { type: "string" }, chromium: { type: "string" } } }); +const { values } = parseArgs({ options: { deps: { type: "string" }, chromium: { type: "string" }, dom: { type: "boolean", default: false }, chill: { type: "boolean", default: false } } }); assert.ok(values.deps && values.chromium, "Required: --deps --chromium "); const { chromium } = await import(pathToFileURL(resolve(values.deps, "node_modules/playwright-core/index.mjs"))); const root = new URL("../apps/terminal-surface/dist/", import.meta.url); @@ -40,7 +40,8 @@ try { browser = await chromium.launch({ executablePath: values.chromium, headless: false }); const context = await browser.newContext({ permissions: ["clipboard-read"], viewport: { width: 1000, height: 600 } }); page = await context.newPage(); - await page.addInitScript(() => { + await page.addInitScript(dom => { + if (dom) Object.defineProperty(window, "WebGL2RenderingContext", { value: undefined }); window.copyInputs = []; window.WebSocket = class { static OPEN = 1; @@ -59,14 +60,20 @@ try { } close() { this.readyState = 3; } }; + }, values.dom); + await page.goto(`http://127.0.0.1:${server.address().port}/#agentonweb=fixture`); + await page.locator('.terminal-tab[data-state="connected"]').waitFor(); + if (values.chill) await page.evaluate(() => { + for (const message of [{ type: "mode.set", mode: "chill" }, { type: "opacity.set", opacity: 0.4 }]) { + window.dispatchEvent(new MessageEvent("message", { source: window, origin: "chrome-extension://fixture", + data: { source: "agentonweb-extension", nonce: "fixture", ...message } })); + } }); - await page.goto(`http://127.0.0.1:${server.address().port}/`); - await page.getByText("COPY_ME_123", { exact: true }).waitFor(); + await page.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))); originalClipboard = await page.evaluate(() => navigator.clipboard.readText()); const screen = await page.locator(".xterm-screen").boundingBox(); - const row = await page.locator(".xterm-rows > div").first().boundingBox(); const cellWidth = screen.width / 100; - const point = (column, line = 0) => ({ x: screen.x + cellWidth * column, y: row.y + row.height * (line + 0.5) }); + const point = (column, line = 0) => ({ x: screen.x + cellWidth * column, y: screen.y + screen.height / 30 * (line + 0.5) }); const inputs = () => page.evaluate(() => window.copyInputs); const clearInputs = () => page.evaluate(() => { window.copyInputs = []; }); const output = data => page.evaluate(data => window.copySocket.emit({ type: "output", epoch: "one", sequence: 1, data }), data); diff --git a/scripts/check-terminal-mode-focus-browser.mjs b/scripts/check-terminal-mode-focus-browser.mjs index 5364cd6..0ba4118 100644 --- a/scripts/check-terminal-mode-focus-browser.mjs +++ b/scripts/check-terminal-mode-focus-browser.mjs @@ -82,6 +82,14 @@ try { }, true); const NativeWebSocket = window.WebSocket; window.WebSocket = class extends NativeWebSocket { + constructor(...args) { + super(...args); + window.modeKeyOutput = ""; + this.addEventListener("message", event => { + const message = JSON.parse(event.data); + if (message.type === "output" || message.type === "snapshot") window.modeKeyOutput += message.data; + }); + } send(data) { const message = JSON.parse(data); if (["input", "input-binary"].includes(message.type)) (window.modeKeyInputs ??= []).push(message.data); @@ -201,7 +209,7 @@ try { const text = 'printf "%s\\n" AOW_"MODE_KEYS_OK"'; await a.page.keyboard.type(text); await a.page.keyboard.press("Enter"); - await until(async () => (await frameA.locator(".xterm-rows").innerText()).includes("AOW_MODE_KEYS_OK"), "real shell input after mode switches"); + await until(() => frameA.evaluate(() => window.modeKeyOutput.includes("AOW_MODE_KEYS_OK")), "real shell input after mode switches"); passed("15 background presentation updates retain focus, followed by successful real PTY input"); await a.page.screenshot({ path: resolve(output, "focus-terminal-input.png") }); const delivery = await worker.evaluate(() => ({ browserCommands: globalThis.modeCommands, iframeOrPageFallback: globalThis.modeRequests })); diff --git a/scripts/check-terminal-performance-browser.mjs b/scripts/check-terminal-performance-browser.mjs new file mode 100644 index 0000000..3c9bac5 --- /dev/null +++ b/scripts/check-terminal-performance-browser.mjs @@ -0,0 +1,167 @@ +// Real terminal surface with a deterministic, local transport fixture. +// No installed host, browser profile or running shell is touched. +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile, writeFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { parseArgs } from "node:util"; + +const { values } = parseArgs({ options: { + deps: { type: "string" }, chromium: { type: "string" }, profile: { type: "string" }, + assets: { type: "string" }, history: { type: "string", default: "3000" }, + columns: { type: "string", default: "120" }, rows: { type: "string", default: "40" }, + scroll: { type: "boolean", default: false }, + dom: { type: "boolean", default: false }, + screenshot: { type: "string" }, + live: { type: "boolean", default: false }, +} }); +assert.ok(values.deps && values.chromium, "Required: --deps --chromium "); +const { chromium } = await import(pathToFileURL(resolve(values.deps, "node_modules/playwright-core/index.mjs"))); +const root = values.assets ? pathToFileURL(resolve(values.assets) + "/") : new URL("../apps/terminal-surface/dist/", import.meta.url); +const server = createServer(async (request, response) => { + const path = new URL(request.url, "http://localhost").pathname; + if (path === "/api/terminals" || path === "/ticket") { + response.setHeader("content-type", "application/json"); + response.end(JSON.stringify(path === "/api/terminals" ? [{ id: "perf", name: "Performance fixture" }] : { token: "fixture" })); + return; + } + const file = { "/": "index.html", "/main.js": "main.js", "/main.css": "main.css" }[path]; + if (!file) { response.statusCode = 404; response.end(); return; } + response.setHeader("content-type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "text/html"); + response.end(await readFile(new URL(file, root))); +}); +await new Promise(done => server.listen(0, "127.0.0.1", done)); +let browser; +try { + browser = await chromium.launch({ executablePath: values.chromium, headless: true, ignoreDefaultArgs: ["--hide-scrollbars"] }); + const page = await browser.newPage({ viewport: { width: 1280, height: 900 } }); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + await page.addInitScript(({ history, columns, rows, scroll, dom, live }) => { + if (dom) Object.defineProperty(window, "WebGL2RenderingContext", { value: undefined }); + const fixture = window.perfFixture = { sequence: 0, ack: 0, inputs: [], frames: [], longTasks: [], running: false }; + new PerformanceObserver(list => { + if (fixture.running) fixture.longTasks.push(...list.getEntries().map(entry => entry.duration)); + }).observe({ type: "longtask", buffered: false }); + window.WebSocket = class { + static OPEN = 1; + readyState = 1; + constructor() { + fixture.socket = this; + setTimeout(() => { + const historyLines = Array.from({ length: 10 }, (_, row) => Array.from({ length: columns }, (_, i) => `\x1b[${41 + i % 6}m${(i + row) % 10}`).join("") + "\x1b[0m\r\n"); + fixture.historyLines = historyLines; + const data = scroll ? Array.from({ length: history }, (_, row) => historyLines[row % 10]).join("") : "history line\r\n".repeat(history); + this.emit({ type: "snapshot", epoch: "perf", cols: columns, rows, data }); + this.emit({ type: "control", epoch: "perf", active: true, lease: 1, resizeOwner: false }); + fixture.output(""); + }, 0); + } + emit(message) { this.onmessage?.({ data: JSON.stringify(message) }); } + send(data) { + const message = JSON.parse(data); + if (message.type === "ack") fixture.ack = message.sequence; + if (message.type === "input") fixture.inputs.push(message.data); + } + close() { this.readyState = 3; } + }; + fixture.output = data => fixture.socket.emit({ type: "output", epoch: "perf", sequence: ++fixture.sequence, data }); + fixture.presentation = mode => window.dispatchEvent(new MessageEvent("message", { + source: window, origin: "chrome-extension://fixture", + data: { source: "agentonweb-extension", nonce: "fixture", type: "mode.set", mode }, + })); + fixture.start = () => { + fixture.frames = []; fixture.inputs = []; fixture.longTasks = []; fixture.running = true; + let previous = performance.now(); + const frame = now => { + if (!fixture.running) return; + fixture.frames.push(now - previous); previous = now; fixture.frameId = requestAnimationFrame(frame); + }; + fixture.frameId = requestAnimationFrame(frame); + if (scroll) { + let line = 0; + if (live) fixture.timer = setInterval(() => fixture.output(fixture.historyLines[line++ % 10]), 32); + return; + } + let count = 0; + const screens = Array.from({ length: 10 }, (_, frame) => { + const line = Array.from({ length: columns }, (_, i) => `\x1b[${41 + i % 6}m${(i + frame) % 10}`).join("") + "\x1b[0m"; + return "\x1b[H" + Array.from({ length: rows - 1 }, () => line).join("\r\n"); + }); + fixture.timer = setInterval(() => { + fixture.output(screens[count++ % screens.length] + `\r\nframe ${count}`); + }, 32); + }; + }, { history: Number(values.history), columns: Number(values.columns), rows: Number(values.rows), scroll: values.scroll, dom: values.dom, live: values.live }); + await page.goto(`http://127.0.0.1:${server.address().port}/#agentonweb=fixture`); + await page.waitForFunction(() => window.perfFixture.ack === 1); + await page.locator(".xterm-helper-textarea").focus(); + if (values.scroll) await page.addStyleTag({ content: ".xterm-viewport::-webkit-scrollbar{width:14px}.xterm-viewport::-webkit-scrollbar-thumb{background:#888;min-height:20px}.xterm-viewport::-webkit-scrollbar-track{background:#222}" }); + const client = await page.context().newCDPSession(page); + // Keep the latency budget useful on fast development machines too. + await client.send("Emulation.setCPUThrottlingRate", { rate: 4 }); + if (values.profile) { await client.send("Profiler.enable"); await client.send("Profiler.start"); } + const results = []; + const scenarios = values.scroll ? [{ mode: "chill", action: "wheel" }, { mode: "chill", action: "drag" }] + : [{ mode: "focus", action: "typing" }, { mode: "chill", action: "typing" }]; + for (const { mode, action } of scenarios) { + await page.evaluate(mode => window.perfFixture.presentation(mode), mode); + const viewport = page.locator(".xterm-viewport"); + if (values.scroll) { + await viewport.evaluate(element => { element.scrollTop = element.scrollHeight; }); + await page.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))); + } + const scrollBefore = await viewport.evaluate(element => element.scrollTop); + const bounds = await viewport.boundingBox(); + if (values.scroll) { + await page.mouse.move(bounds.x + (action === "drag" ? bounds.width - 7 : bounds.width / 2), bounds.y + (action === "drag" ? bounds.height - 10 : bounds.height / 2)); + if (action === "drag" && values.screenshot) await page.screenshot({ path: values.screenshot }); + if (action === "drag") await page.mouse.down(); + } + await page.evaluate(() => window.perfFixture.start()); + const keyLatency = []; + for (let i = 0; i < 24; i++) { + await new Promise(done => setTimeout(done, 40)); + const start = performance.now(); + if (values.scroll) { + if (action === "wheel") await page.mouse.wheel(0, -600); + else await page.mouse.move(bounds.x + bounds.width - 7, bounds.y + bounds.height - 10 - (i + 1) / 24 * (bounds.height - 40)); + await page.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))); + } else await page.keyboard.type("x"); + keyLatency.push(performance.now() - start); + } + if (action === "drag") await page.mouse.up(); + await page.evaluate(() => clearInterval(window.perfFixture.timer)); + await page.waitForFunction(() => window.perfFixture.ack === window.perfFixture.sequence); + const result = await page.evaluate(() => { + const f = window.perfFixture; + f.running = false; + cancelAnimationFrame(f.frameId); + return { inputs: f.inputs.join(""), frames: f.frames, longTasks: f.longTasks, + renderer: document.querySelector(".xterm-rows") ? "dom" : "webgl" }; + }); + const percentile = (values, fraction) => [...values].sort((a, b) => a - b)[Math.floor((values.length - 1) * fraction)] ?? 0; + results.push({ mode, action, renderer: result.renderer, actionP95: Math.round(percentile(keyLatency, 0.95)), actionMax: Math.round(Math.max(...keyLatency)), + frameP95: Math.round(percentile(result.frames, 0.95)), longTasks: result.longTasks.length }); + if (values.scroll) { + const actual = await viewport.evaluate(element => ({ top: element.scrollTop, height: element.clientHeight, scrollHeight: element.scrollHeight, width: element.clientWidth, outerWidth: element.offsetWidth })); + assert.ok(actual.top < scrollBefore - 1000, `${action} must actually scroll through history: ${JSON.stringify({ scrollBefore, actual, bounds })}`); + } + else assert.equal(result.inputs, "x".repeat(24), "typing must stay ordered and lossless during output"); + } + if (values.profile) { + const { profile } = await client.send("Profiler.stop"); + await writeFile(values.profile, JSON.stringify(profile)); + } + console.log(JSON.stringify(results, null, 2)); + assert.deepEqual(errors, []); + for (const result of results) { + assert.ok(result.actionP95 < 100, `${result.mode} ${result.action}: p95 response ${result.actionP95} ms exceeds 100 ms`); + const frameBudget = values.scroll ? 50 : 100; + assert.ok(result.frameP95 < frameBudget, `${result.mode}: p95 frame interval ${result.frameP95} ms exceeds ${frameBudget} ms`); + } +} finally { + await browser?.close(); + await new Promise(done => server.close(done)); +} diff --git a/scripts/check-terminal-presentation-browser.mjs b/scripts/check-terminal-presentation-browser.mjs new file mode 100644 index 0000000..2475373 --- /dev/null +++ b/scripts/check-terminal-presentation-browser.mjs @@ -0,0 +1,157 @@ +// Pixel-level transparency/selection checks against the real terminal bundle. +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { parseArgs } from "node:util"; + +const { values } = parseArgs({ options: { deps: { type: "string" }, chromium: { type: "string" } } }); +assert.ok(values.deps && values.chromium, "Required: --deps --chromium "); +const { chromium } = await import(pathToFileURL(resolve(values.deps, "node_modules/playwright-core/index.mjs"))); +const root = new URL("../apps/terminal-surface/dist/", import.meta.url); +const server = createServer(async (request, response) => { + const path = new URL(request.url, "http://localhost").pathname; + if (path === "/api/terminals" || path === "/ticket") { + response.setHeader("content-type", "application/json"); + response.end(JSON.stringify(path === "/api/terminals" ? [{ id: "one", name: "Pixel fixture" }] : { token: "fixture" })); + return; + } + const file = { "/": "index.html", "/main.js": "main.js", "/main.css": "main.css" }[path]; + if (!file) { response.statusCode = 404; response.end(); return; } + response.setHeader("content-type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "text/html"); + response.end(await readFile(new URL(file, root))); +}); +await new Promise(done => server.listen(0, "127.0.0.1", done)); +let browser; +try { + browser = await chromium.launch({ executablePath: values.chromium, headless: true }); + const results = {}; + for (const renderer of ["dom", "webgl"]) { + const page = await browser.newPage({ viewport: { width: 800, height: 500 }, deviceScaleFactor: 1 }); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + await page.addInitScript(renderer => { + if (renderer === "dom") Object.defineProperty(window, "WebGL2RenderingContext", { value: undefined }); + const fixture = window.pixelFixture = { inputs: [], ack: 0 }; + window.WebSocket = class { + static OPEN = 1; + readyState = 1; + constructor() { + fixture.socket = this; + setTimeout(() => { + const data = "\x1b[38;2;241;243;245m" + + "\x1b[48;2;32;71;51m ███ Truecolor\x1b[0m\r\n" + + "\x1b[42m ███ ANSI\x1b[0m\r\n" + + "\x1b[48;5;22m ███ Palette\x1b[0m\r\n" + + "\x1b[7m ███ Inverse\x1b[0m\r\n" + + "Plain text\r\n\r\n\r\n"; + this.emit({ type: "snapshot", epoch: "one", cols: 60, rows: 20, data }); + this.emit({ type: "control", epoch: "one", active: true, lease: 1, resizeOwner: false }); + this.emit({ type: "output", epoch: "one", sequence: 1, data: "" }); + }, 0); + } + emit(message) { this.onmessage?.({ data: JSON.stringify(message) }); } + send(data) { + const message = JSON.parse(data); + if (message.type === "ack") fixture.ack = message.sequence; + if (message.type === "input") fixture.inputs.push(message.data); + } + close() {} + }; + fixture.emit = message => window.dispatchEvent(new MessageEvent("message", { + source: window, origin: "chrome-extension://fixture", + data: { source: "agentonweb-extension", nonce: "fixture", ...message }, + })); + }, renderer); + await page.goto(`http://127.0.0.1:${server.address().port}/#agentonweb=fixture`); + await page.waitForFunction(() => window.pixelFixture.ack === 1); + await page.locator(".xterm-helper-textarea").focus(); + const settle = () => page.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))); + const presentation = async (mode, opacity) => { + await page.evaluate(({ mode, opacity }) => { + window.pixelFixture.emit({ type: "mode.set", mode }); + window.pixelFixture.emit({ type: "opacity.set", opacity }); + }, { mode, opacity }); + await settle(); + }; + const bounds = await page.locator(".xterm-screen").boundingBox(); + const point = (column, row) => ({ x: bounds.x + column * bounds.width / 60, y: bounds.y + row * bounds.height / 20 }); + const points = [point(1.5, 0.5), point(1.5, 1.5), point(1.5, 2.5), point(1.5, 3.5), + point(5.5, 0.5), point(0.5, 7.5), point(1.5, 6.5)]; + const pixels = async () => { + const png = await page.screenshot({ omitBackground: true }); + return page.evaluate(async ({ png, points }) => { + const bytes = Uint8Array.from(atob(png), c => c.charCodeAt(0)); + const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" })); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext("2d"); + context.drawImage(bitmap, 0, 0); + const result = points.map(({ x, y }) => [...context.getImageData(Math.floor(x), Math.floor(y), 1, 1).data]); + bitmap.close(); + return result; + }, { png: png.toString("base64"), points }); + }; + await presentation("chill", 0.4); + assert.equal(await page.locator(".xterm-rows").count(), renderer === "dom" ? 1 : 0); + const translucent = await pixels(); + await page.mouse.move(point(1.05, 0.5).x, point(1.05, 0.5).y); + await page.mouse.down(); + await page.mouse.move(point(3.95, 0.5).x, point(3.95, 0.5).y, { steps: 8 }); + await page.mouse.up(); + await settle(); + const selected = await pixels(); + assert.equal(selected[0][3], 255, `${renderer}: selected background remains opaque`); + await page.mouse.click(point(30, 6.5).x, point(30, 6.5).y); + await presentation("chill", 0.2); + const lower = await pixels(); + await presentation("focus", 0.2); + const opaque = await pixels(); + results[renderer] = { translucent, lower, opaque }; + for (let i = 0; i < 4; i++) { + assert.ok(translucent[i][3] < 255 && lower[i][3] < translucent[i][3], `${renderer}: cell background follows opacity`); + assert.equal(opaque[i][3], 255, `${renderer}: Focus background is opaque`); + } + assert.deepEqual(translucent[4], opaque[4], `${renderer}: text must not fade`); + assert.equal(translucent[5][3], 255, `${renderer}: block cursor must not fade`); + if (renderer === "webgl") { + await page.evaluate(() => { window.pixelFixture.canvas = [...document.querySelectorAll(".xterm-screen canvas")].find(canvas => canvas.getContext("webgl2")); }); + for (let i = 0; i < 3; i++) { await presentation("chill", 0.4); await presentation("focus", 0.4); } + assert.equal(await page.evaluate(() => window.pixelFixture.canvas?.isConnected), true, "mode changes retain the same GPU canvas"); + await presentation("chill", 0.4); + await page.evaluate(async () => { + const canvas = window.pixelFixture.canvas; + const extension = canvas.getContext("webgl2").getExtension("WEBGL_lose_context"); + const restored = new Promise(done => canvas.addEventListener("webglcontextrestored", done, { once: true })); + canvas.addEventListener("webglcontextlost", () => setTimeout(() => extension.restoreContext(), 50), { once: true }); + extension.loseContext(); + await restored; + }); + await settle(); + const restored = await pixels(); + for (let channel = 0; channel < 4; channel++) assert.ok(Math.abs(restored[0][channel] - translucent[0][channel]) <= 3, "restored GPU context keeps cell opacity"); + await page.evaluate(() => window.pixelFixture.canvas.getContext("webgl2").getExtension("WEBGL_lose_context").loseContext()); + await page.locator(".xterm-rows").waitFor(); + await settle(); + const fallback = await pixels(); + for (let channel = 0; channel < 4; channel++) assert.ok(Math.abs(fallback[0][channel] - results.dom.translucent[0][channel]) <= 2, "GPU loss preserves translucent DOM presentation"); + await page.keyboard.type("still usable"); + assert.equal(await page.evaluate(() => window.pixelFixture.inputs.join("")), "still usable"); + } + assert.deepEqual(errors, []); + await page.close(); + } + console.log(JSON.stringify(results)); + for (const state of ["translucent", "lower", "opaque"]) { + for (const sample of [0, 1, 2, 3, 6]) { + for (let channel = 0; channel < 4; channel++) { + assert.ok(Math.abs(results.dom[state][sample][channel] - results.webgl[state][sample][channel]) <= 3, + `${state} sample ${sample}: GPU and DOM background pixels agree`); + } + } + } + console.log("PASS: GPU/DOM transparency, truecolor/ANSI/inverse backgrounds, opaque text/cursor/selection, stable mode switching, context restoration and context-loss fallback"); +} finally { + await browser?.close(); + await new Promise(done => server.close(done)); +} diff --git a/scripts/install.sh b/scripts/install.sh index 595fa0a..d1f6139 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -23,7 +23,7 @@ install_agentonweb() { aow_node_bin="$(dirname "$(command -v node)")" export PATH="$aow_prefix/bin:$PATH" echo 'Installing AgentOnWeb terminal…' - AOW_SKIP_SETUP=1 npm install --global --prefix "$aow_prefix" --foreground-scripts --prefer-online --no-audit --no-fund '@agentonweb/terminal-host@0.4.3'