The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): gate the chat WebGL renderer and fall back to DOM
Austin Pickett0620913eacf2
diff --git a/web/src/lib/chat-channel-id.test.ts b/web/src/lib/chat-channel-id.test.tsnew file mode 100644index 00000000000..460e48267fc--- /dev/null+++ b/web/src/lib/chat-channel-id.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from "vitest";++import { generateChannelId } from "./chat-channel-id";++describe("generateChannelId", () => {+ it("prefixes chat when scoped and chat-fresh when not", () => {+ expect(generateChannelId("scope")).toMatch(/^chat-/);+ expect(generateChannelId()).toMatch(/^chat-fresh-/);+ });++ it("never returns the same id twice", () => {+ expect(generateChannelId("s")).not.toBe(generateChannelId("s"));+ });+});diff --git a/web/src/lib/chat-channel-id.ts b/web/src/lib/chat-channel-id.tsnew file mode 100644index 00000000000..0a767dcd70d--- /dev/null+++ b/web/src/lib/chat-channel-id.ts@@ -0,0 +1,13 @@+// Channel id ties a chat tab's PTY child (publisher) to its sidebar+// (subscriber). Generated once per mount so a tab refresh starts a fresh+// channel — the previous PTY child terminates with the old WS, and its+// channel auto-evicts when no subscribers remain.+export function generateChannelId(scope?: string): string {+ const prefix = scope ? "chat" : "chat-fresh";+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {+ return `${prefix}-${crypto.randomUUID()}`;+ }+ return `${prefix}-${Math.random().toString(36).slice(2)}-${Date.now().toString(+ 36,+ )}`;+}diff --git a/web/src/lib/chat-copy-last.ts b/web/src/lib/chat-copy-last.tsnew file mode 100644index 00000000000..3d963c0361d--- /dev/null+++ b/web/src/lib/chat-copy-last.ts@@ -0,0 +1,30 @@+import type { RefObject } from "react";+import type { Terminal } from "@xterm/xterm";++/**+ * Sends `/copy` over the open PTY WebSocket, waits long enough for Ink's+ * tokenizer to emit a keypress event per character (not coalesce them into+ * a paste), then sends Return as its own event. The 100ms timing is+ * empirical — safely past Node's default stdin coalescing window and well+ * inside UI responsiveness. Flips `copyState` to "copied" for 1.5s and+ * refocuses the terminal.+ */+export function sendCopyLastCommand(opts: {+ wsRef: RefObject<WebSocket | null>;+ termRef: RefObject<Terminal | null>;+ copyResetRef: RefObject<ReturnType<typeof setTimeout> | null>;+ onCopied: () => void;+ onCopyReset: () => void;+}): void {+ const ws = opts.wsRef.current;+ if (!ws || ws.readyState !== WebSocket.OPEN) return;+ ws.send("/copy");+ setTimeout(() => {+ const s = opts.wsRef.current;+ if (s && s.readyState === WebSocket.OPEN) s.send("\r");+ }, 100);+ opts.onCopied();+ if (opts.copyResetRef.current) clearTimeout(opts.copyResetRef.current);+ opts.copyResetRef.current = setTimeout(() => opts.onCopyReset(), 1500);+ opts.termRef.current?.focus();+}diff --git a/web/src/lib/chat-image-drop.ts b/web/src/lib/chat-image-drop.tsnew file mode 100644index 00000000000..7c904c784c8--- /dev/null+++ b/web/src/lib/chat-image-drop.ts@@ -0,0 +1,41 @@+import { imageFilesFromTransfer, transferMayContainImage } from "./chatImagePaste";++/**+ * Browser clipboard/drag-and-drop image wiring for the chat host element.+ *+ * paste / dragover / drop listeners (capture phase) that pull image files out+ * of the transfer data and hand them to the caller's upload+attach pipeline.+ * `attachChatImageDropListeners` returns a detach function for effect cleanup.+ */+export function attachChatImageDropListeners(+ host: HTMLElement,+ uploadAndAttachImages: (files: File[]) => void,+): () => void {+ const handleBrowserPaste = (ev: ClipboardEvent) => {+ const files = imageFilesFromTransfer(ev.clipboardData);+ if (!files.length) return;+ ev.preventDefault();+ ev.stopPropagation();+ uploadAndAttachImages(files);+ };+ const handleBrowserDragOver = (ev: DragEvent) => {+ if (!transferMayContainImage(ev.dataTransfer)) return;+ ev.preventDefault();+ if (ev.dataTransfer) ev.dataTransfer.dropEffect = "copy";+ };+ const handleBrowserDrop = (ev: DragEvent) => {+ const files = imageFilesFromTransfer(ev.dataTransfer);+ if (!files.length) return;+ ev.preventDefault();+ ev.stopPropagation();+ uploadAndAttachImages(files);+ };+ host.addEventListener("paste", handleBrowserPaste, { capture: true });+ host.addEventListener("dragover", handleBrowserDragOver, { capture: true });+ host.addEventListener("drop", handleBrowserDrop, { capture: true });+ return () => {+ host.removeEventListener("paste", handleBrowserPaste, true);+ host.removeEventListener("dragover", handleBrowserDragOver, true);+ host.removeEventListener("drop", handleBrowserDrop, true);+ };+}diff --git a/web/src/lib/xterm-webgl-gating.test.ts b/web/src/lib/xterm-webgl-gating.test.tsnew file mode 100644index 00000000000..5e81c3e9d74--- /dev/null+++ b/web/src/lib/xterm-webgl-gating.test.ts@@ -0,0 +1,163 @@+// @vitest-environment jsdom+import { describe, expect, it, vi } from "vitest";++import {+ isSafari,+ probeWebglSupport,+ shouldUseWebglRenderer,+ textNeedsDomShaping,+} from "./xterm-webgl-gating";++const SUPPORTED = { contextAvailable: true, softwareRenderer: false };++describe("isSafari", () => {+ it("accepts desktop and iOS Safari", () => {+ expect(+ isSafari(+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15",+ ),+ ).toBe(true);+ expect(+ isSafari(+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1",+ ),+ ).toBe(true);+ });++ it("rejects Chromium derivatives and iOS wrappers that carry Safari/", () => {+ const uas = [+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",+ "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36",+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/124.0.0.0 Mobile/15E148 Safari/604.1",+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/124.0 Mobile/15E148 Safari/605.1.15",+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0",+ ];+ for (const ua of uas) expect(isSafari(ua)).toBe(false);+ });++ it("rejects non-Safari UAs", () => {+ expect(isSafari("Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0")).toBe(false);+ expect(isSafari("")).toBe(false);+ });+});++describe("shouldUseWebglRenderer", () => {+ const chromeUa =+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";+ const safariUa =+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15";++ it("uses WebGL for wide Chrome hosts with hardware GL (#18773 fixed for others)", () => {+ expect(+ shouldUseWebglRenderer({ layoutWidthPx: 1024, userAgent: chromeUa, support: SUPPORTED }),+ ).toBe(true);+ expect(+ shouldUseWebglRenderer({ layoutWidthPx: 767, userAgent: chromeUa, support: SUPPORTED }),+ ).toBe(false);+ });++ it("never uses WebGL on Safari regardless of width (#18773)", () => {+ expect(+ shouldUseWebglRenderer({ layoutWidthPx: 1280, userAgent: safariUa, support: SUPPORTED }),+ ).toBe(false);+ });++ it("never uses WebGL without a GL context (#45520)", () => {+ expect(+ shouldUseWebglRenderer({+ layoutWidthPx: 1280,+ userAgent: chromeUa,+ support: { contextAvailable: false, softwareRenderer: false },+ }),+ ).toBe(false);+ });++ it("never uses WebGL on software rasterizers like llvmpipe (#45520)", () => {+ expect(+ shouldUseWebglRenderer({+ layoutWidthPx: 1280,+ userAgent: chromeUa,+ support: { contextAvailable: true, softwareRenderer: true },+ }),+ ).toBe(false);+ });+});++describe("probeWebglSupport", () => {+ it("reports unavailable when context creation fails", () => {+ const doc = {+ createElement: () => ({+ getContext: () => null,+ }),+ } as unknown as Document;+ expect(probeWebglSupport(doc)).toEqual({+ contextAvailable: false,+ softwareRenderer: false,+ });+ });++ it("flags llvmpipe as a software renderer and releases the probe context", () => {+ const loseContext = vi.fn();+ const getParameter = vi.fn(() => "llvmpipe (LLVM 21.1.8, 256 bits)");+ const getExtension = vi.fn((name: string) => {+ if (name === "WEBGL_debug_renderer_info") {+ return { UNMASKED_RENDERER_WEBGL: 0x9246 };+ }+ if (name === "WEBGL_lose_context") {+ return { loseContext };+ }+ return null;+ });+ const doc = {+ createElement: () => ({+ getContext: () => ({ getExtension, getParameter }),+ }),+ } as unknown as Document;++ const support = probeWebglSupport(doc);+ expect(support).toEqual({ contextAvailable: true, softwareRenderer: true });+ expect(loseContext).toHaveBeenCalledTimes(1);+ });++ it("treats a hardware renderer as usable and releases the probe context", () => {+ const loseContext = vi.fn();+ const getParameter = vi.fn(() => "Apple M2");+ const getExtension = vi.fn((name: string) => {+ if (name === "WEBGL_debug_renderer_info") {+ return { UNMASKED_RENDERER_WEBGL: 0x9246 };+ }+ if (name === "WEBGL_lose_context") {+ return { loseContext };+ }+ return null;+ });+ const doc = {+ createElement: () => ({+ getContext: () => ({ getExtension, getParameter }),+ }),+ } as unknown as Document;++ expect(probeWebglSupport(doc)).toEqual({+ contextAvailable: true,+ softwareRenderer: false,+ });+ expect(loseContext).toHaveBeenCalledTimes(1);+ });+});++describe("textNeedsDomShaping", () => {+ it("flags Bengali conjunct text but not plain ASCII or box-drawing", () => {+ expect(textNeedsDomShaping("প্রযুক্তি ক্লিপবোর্ড যুক্তাক্ষর")).toBe(true);+ expect(textNeedsDomShaping("Devanagari: क्रिया")).toBe(true);+ expect(textNeedsDomShaping("Khmer: សួស្តី")).toBe(true);++ expect(textNeedsDomShaping("plain ascii output")).toBe(false);+ expect(textNeedsDomShaping("box drawing: ╔═╗║╚╝")).toBe(false);+ expect(textNeedsDomShaping("emoji 👍 and surrogate pairs")).toBe(false);+ expect(textNeedsDomShaping("")).toBe(false);+ });++ it("handles code points above the BMP", () => {+ expect(textNeedsDomShaping("😀 ক")).toBe(true);+ });+});diff --git a/web/src/lib/xterm-webgl-gating.ts b/web/src/lib/xterm-webgl-gating.tsnew file mode 100644index 00000000000..2575654fa71--- /dev/null+++ b/web/src/lib/xterm-webgl-gating.ts@@ -0,0 +1,127 @@+/**+ * Gate the dashboard chat's xterm WebGL renderer.+ *+ * The WebGL renderer is the fast path, but a whole class of hosts and content+ * renders wrong or dies on it:+ *+ * - Safari's WebGL texture atlas mangles Unicode box-drawing glyphs+ * (╔╗║╚╝, the HERMES banner) — the DOM renderer draws them fine (#18773).+ * - Software rasterizers (llvmpipe, SwiftShader, softpipe) succeed at+ * `getContext("webgl")` but regl then throws+ * "(regl) webgl not supported" from inside the addon (#45520).+ * - Atlas drawing is per code point, so complex scripts that need shaping+ * (Bengali conjuncts যুক্তাক্ষর and friends) come out visually broken;+ * the DOM renderer runs text through the browser's shaper (#58685).+ *+ * Decision helpers here are pure; `probeWebglSupport` is the only part that+ * touches the DOM.+ */++export interface WebglSupport {+ /** A WebGL(2) context could be created at all. */+ contextAvailable: boolean;+ /** The unmasked renderer string looks like a software rasterizer. */+ softwareRenderer: boolean;+}++// Renderer strings reported by the rasterizers that advertise WebGL but+// can't back regl / the addon usefully.+const SOFTWARE_RENDERER_RE = /llvmpipe|swiftshader|softpipe|software/i;++/**+ * Probe once whether WebGL is usable on this host, then release the probe+ * context: browsers cap live contexts (~16) and chat reconnects already fight+ * that cap (see xterm-webgl-release.ts).+ */+export function probeWebglSupport(doc: Document): WebglSupport {+ let gl: WebGLRenderingContext | WebGL2RenderingContext | null = null;+ try {+ const canvas = doc.createElement("canvas");+ gl = (canvas.getContext("webgl2") ?? canvas.getContext("webgl")) || null;+ } catch {+ // WebGL disabled or blocked — fall through to "unavailable".+ }+ if (!gl) return { contextAvailable: false, softwareRenderer: false };++ let softwareRenderer = false;+ try {+ const debug = gl.getExtension("WEBGL_debug_renderer_info");+ if (debug) {+ const renderer = String(gl.getParameter(debug.UNMASKED_RENDERER_WEBGL));+ softwareRenderer = SOFTWARE_RENDERER_RE.test(renderer);+ }+ } catch {+ // Renderer info stripped (privacy modes) — context creation succeeded,+ // so give the hardware path the benefit of the doubt.+ }+ try {+ gl.getExtension("WEBGL_lose_context")?.loseContext();+ } catch {+ // Already lost — nothing to release.+ }+ return { contextAvailable: true, softwareRenderer };+}++/**+ * Detect Safari (the WebKit browser shipped with macOS/iOS). Chromium+ * derivatives and iOS wrapper apps keep the legacy `Safari/` token in their+ * UA for compat, so exclude every fingerprint we know wraps another engine.+ */+export function isSafari(userAgent: string): boolean {+ if (!userAgent.includes("Safari/")) return false;+ return !/Chrom(e|ium)\/|CriOS\/|FxiOS\/|EdgiOS\/|EdgA\/|SamsungBrowser\/|Android/i.test(+ userAgent,+ );+}++/**+ * Wide layouts get WebGL for crisp box-drawing — but only where it works:+ * never on Safari (#18773), never without a real hardware GL context+ * (#45520). Everything else stays on the default DOM renderer.+ */+export function shouldUseWebglRenderer(input: {+ layoutWidthPx: number;+ userAgent: string;+ support: WebglSupport;+}): boolean {+ return (+ input.layoutWidthPx >= 768 &&+ !isSafari(input.userAgent) &&+ input.support.contextAvailable &&+ !input.support.softwareRenderer+ );+}++// Unicode blocks for scripts that need contextual shaping (conjuncts,+// ligatures, reordering) — impossible for a per-glyph atlas. Southeast Asian+// and Indic families; Bengali (U+0980–U+09FF) is the reported case (#58685).+const COMPLEX_SCRIPT_RANGES: ReadonlyArray<readonly [number, number]> = [+ [0x0900, 0x097f], // Devanagari+ [0x0980, 0x09ff], // Bengali+ [0x0a00, 0x0a7f], // Gurmukhi+ [0x0a80, 0x0aff], // Gujarati+ [0x0b00, 0x0b7f], // Oriya+ [0x0b80, 0x0bff], // Tamil+ [0x0c00, 0x0c7f], // Telugu+ [0x0c80, 0x0cff], // Kannada+ [0x0d00, 0x0d7f], // Malayalam+ [0x0d80, 0x0dff], // Sinhala+ [0x1000, 0x109f], // Myanmar+ [0x1780, 0x17ff], // Khmer+];++/**+ * True when the payload contains a script the WebGL/canvas atlas cannot+ * shape. Used to drop the WebGL addon mid-stream so xterm re-renders+ * through the DOM renderer (#58685).+ */+export function textNeedsDomShaping(text: string): boolean {+ for (let i = 0; i < text.length; i += 1) {+ const codePoint = text.codePointAt(i) ?? 0;+ if (codePoint > 0xffff) i += 1; // surrogate pair — skip the low half+ for (const [low, high] of COMPLEX_SCRIPT_RANGES) {+ if (codePoint >= low && codePoint <= high) return true;+ }+ }+ return false;+}diff --git a/web/src/pages/ChatPage.test.tsx b/web/src/pages/ChatPage.test.tsxindex 7429b87dce5..3f82b398766 100644--- a/web/src/pages/ChatPage.test.tsx+++ b/web/src/pages/ChatPage.test.tsx@@ -14,10 +14,19 @@ class FakeFitAddon {fit() {}}+const webglInstances: FakeWebglAddon[] = [];+class FakeWebglAddon {+ disposed = false;onContextLoss() {return { dispose() {} };}+ dispose() {+ this.disposed = true;+ }+ constructor() {+ webglInstances.push(this);+ }}class FakeTerminal {@@ -205,6 +214,7 @@ async function render(ui: ReactNode) {beforeEach(() => {FakeWebSocket.instances = [];+ webglInstances.length = 0;maybeReloadForLoopbackWsAuthFailure.mockClear();apiMocks.buildWsUrl.mockReset();apiMocks.buildWsUrl.mockResolvedValue("ws://localhost/api/pty?channel=chat-1");@@ -727,3 +737,136 @@ describe("ChatPage PTY ticket connect deadline", () => {expect(apiMocks.buildWsUrl).toHaveBeenCalledTimes(1);});});++// xterm WebGL renderer gating (#18773 / #45520 / #58685): the addon must only+// load when the host can actually use it (wide layout, non-Safari, hardware GL)+// and must be dropped when shaped-script text arrives.+describe("ChatPage WebGL renderer gating", () => {+ const CHROME_UA =+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";+ const SAFARI_UA =+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15";++ /** Stub the probe's canvas context per test. */+ function stubCanvasContext(+ getContext: () => WebGLRenderingContext | null,+ ): void {+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(+ getContext as never,+ );+ }++ function hardwareGl(): WebGLRenderingContext | null {+ return {+ getExtension: (name: string) => {+ if (name === "WEBGL_debug_renderer_info") {+ return { UNMASKED_RENDERER_WEBGL: 0x9246 };+ }+ if (name === "WEBGL_lose_context") {+ return { loseContext: () => undefined };+ }+ return null;+ },+ getParameter: () => "Apple M2",+ } as unknown as WebGLRenderingContext;+ }++ async function renderChat() {+ const { default: ChatPage } = await import("./ChatPage");+ await render(+ <MemoryRouter initialEntries={["/chat"]}>+ <ChatPage isActive />+ </MemoryRouter>,+ );+ await act(async () => {+ await Promise.resolve();+ });+ }++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("loads the WebGL addon on a wide hardware-GL Chrome host", async () => {+ Object.defineProperty(window.navigator, "userAgent", {+ configurable: true,+ value: CHROME_UA,+ writable: true,+ });+ stubCanvasContext(hardwareGl);++ await renderChat();+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));++ expect(webglInstances).toHaveLength(1);+ expect(webglInstances[0].disposed).toBe(false);+ });++ it("skips the WebGL addon on Safari (#18773)", async () => {+ Object.defineProperty(window.navigator, "userAgent", {+ configurable: true,+ value: SAFARI_UA,+ writable: true,+ });+ stubCanvasContext(hardwareGl);++ await renderChat();+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));++ expect(webglInstances).toHaveLength(0);+ });++ it("skips the WebGL addon when no WebGL context exists (#45520)", async () => {+ Object.defineProperty(window.navigator, "userAgent", {+ configurable: true,+ value: CHROME_UA,+ writable: true,+ });+ stubCanvasContext(() => null);++ await renderChat();+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));++ expect(webglInstances).toHaveLength(0);+ });++ it("skips the WebGL addon on a software renderer like llvmpipe (#45520)", async () => {+ Object.defineProperty(window.navigator, "userAgent", {+ configurable: true,+ value: CHROME_UA,+ writable: true,+ });+ stubCanvasContext(() =>+ ({+ ...hardwareGl(),+ getParameter: () => "llvmpipe (LLVM 21.1.8, 256 bits)",+ }) as unknown as WebGLRenderingContext,+ );++ await renderChat();+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));++ expect(webglInstances).toHaveLength(0);+ });++ it("disposes the WebGL addon when Bengali text arrives (#58685)", async () => {+ Object.defineProperty(window.navigator, "userAgent", {+ configurable: true,+ value: CHROME_UA,+ writable: true,+ });+ stubCanvasContext(hardwareGl);++ await renderChat();+ const socket = FakeWebSocket.instances[0];+ await act(async () => socket.onopen?.());+ expect(webglInstances).toHaveLength(1);+ expect(webglInstances[0].disposed).toBe(false);++ await act(async () => {+ socket.onmessage?.({ data: "যুক্তাক্ষর প্রযুক্তি" });+ });++ expect(webglInstances[0].disposed).toBe(true);+ });+});diff --git a/web/src/pages/ChatPage.tsx b/web/src/pages/ChatPage.tsxindex dc0453ee115..f5a931ffe5d 100644--- a/web/src/pages/ChatPage.tsx+++ b/web/src/pages/ChatPage.tsx@@ -76,11 +76,8 @@ import {parseResumeControlMessage,shouldFollowPtyOutput,} from "@/lib/pty-scroll";-import {- imageFilesFromTransfer,- transferMayContainImage,- uploadChatImage,-} from "@/lib/chatImagePaste";+import { uploadChatImage } from "@/lib/chatImagePaste";+import { attachChatImageDropListeners } from "@/lib/chat-image-drop";import { maybeReloadForLoopbackWsAuthFailure } from "@/lib/dashboard-auth-reload";import {PTY_GAVE_UP_BANNER,@@ -98,6 +95,13 @@ import {refitWhenTerminalFontLoads,TERMINAL_FONT_FAMILY,} from "@/lib/terminal-font-refit";+import { generateChannelId } from "@/lib/chat-channel-id";+import { sendCopyLastCommand } from "@/lib/chat-copy-last";+import {+ probeWebglSupport,+ shouldUseWebglRenderer,+ textNeedsDomShaping,+} from "@/lib/xterm-webgl-gating";import { loseWebglContexts } from "@/lib/xterm-webgl-release";import {buildTerminalTheme,@@ -116,20 +120,6 @@ import { errorMessage } from "@/lib/api-error";// second tab — including a Chrome "Duplicate tab" — gets its own PTY instead of// taking over this one. See #115304.-// Channel id ties this chat tab's PTY child (publisher) to its sidebar-// (subscriber). Generated once per mount so a tab refresh starts a fresh-// channel — the previous PTY child terminates with the old WS, and its-// channel auto-evicts when no subscribers remain.-function generateChannelId(scope?: string): string {- const prefix = scope ? "chat" : "chat-fresh";- if (typeof crypto !== "undefined" && "randomUUID" in crypto) {- return `${prefix}-${crypto.randomUUID()}`;- }- return `${prefix}-${Math.random().toString(36).slice(2)}-${Date.now().toString(- 36,- )}`;-}-export default function ChatPage({ isActive = true }: { isActive?: boolean }) {const hostRef = useRef<HTMLDivElement | null>(null);const termWrapRef = useRef<HTMLDivElement | null>(null);@@ -494,22 +484,13 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {}, [isActive, narrow, mobilePanelOpen, modelToolsLabel, setEnd]);const handleCopyLast = () => {- const ws = wsRef.current;- if (!ws || ws.readyState !== WebSocket.OPEN) return;- // Send the slash as a burst, wait long enough for Ink's tokenizer to- // emit a keypress event for each character (not coalesce them into a- // paste), then send Return as its own event. The timing here is- // empirical — 100ms is safely past Node's default stdin coalescing- // window and well inside UI responsiveness.- ws.send("/copy");- setTimeout(() => {- const s = wsRef.current;- if (s && s.readyState === WebSocket.OPEN) s.send("\r");- }, 100);- setCopyState("copied");- if (copyResetRef.current) clearTimeout(copyResetRef.current);- copyResetRef.current = setTimeout(() => setCopyState("idle"), 1500);- termRef.current?.focus();+ sendCopyLastCommand({+ wsRef,+ termRef,+ copyResetRef,+ onCopied: () => setCopyState("copied"),+ onCopyReset: () => setCopyState("idle"),+ });};useEffect(() => {@@ -665,28 +646,10 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {await driveImageAttach(paths);})().catch(reportImageUploadError);};- const handleBrowserPaste = (ev: ClipboardEvent) => {- const files = imageFilesFromTransfer(ev.clipboardData);- if (!files.length) return;- ev.preventDefault();- ev.stopPropagation();- uploadAndAttachImages(files);- };- const handleBrowserDragOver = (ev: DragEvent) => {- if (!transferMayContainImage(ev.dataTransfer)) return;- ev.preventDefault();- if (ev.dataTransfer) ev.dataTransfer.dropEffect = "copy";- };- const handleBrowserDrop = (ev: DragEvent) => {- const files = imageFilesFromTransfer(ev.dataTransfer);- if (!files.length) return;- ev.preventDefault();- ev.stopPropagation();- uploadAndAttachImages(files);- };- host.addEventListener("paste", handleBrowserPaste, { capture: true });- host.addEventListener("dragover", handleBrowserDragOver, { capture: true });- host.addEventListener("drop", handleBrowserDrop, { capture: true });+ const handleBrowserDropCleanup = attachChatImageDropListeners(+ host,+ uploadAndAttachImages,+ );term.attachCustomKeyEventHandler((ev) => {if (ev.type !== "keydown") return true;@@ -896,13 +859,28 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {// in DevTools device mode that often produces *visually* much larger cells// than `fontSize` suggests — users see "huge" text even at 7–9px settings.// The canvas/DOM renderer tracks `fontSize` faithfully; use it for narrow- // hosts. Wide layouts still get WebGL for crisp box-drawing.- const useWebgl = terminalTierWidthPx(host) >= 768;+ // hosts. Wide layouts still get WebGL for crisp box-drawing — but only+ // where WebGL actually works. Safari's atlas garbles box-drawing glyphs+ // (#18773), hosts whose only GL is a software rasterizer (llvmpipe,+ // SwiftShader) crash the addon with "(regl) webgl not supported"+ // (#45520), and without any GL context there is nothing to load at all.+ // Everything else falls back to the default DOM renderer.+ const userAgent = typeof navigator !== "undefined" ? navigator.userAgent : "";+ const useWebgl = shouldUseWebglRenderer({+ layoutWidthPx: terminalTierWidthPx(host),+ userAgent,+ support: probeWebglSupport(document),+ });+ // Set once the addon is live; the PTY write path below drops it again if+ // shaping-requiring text (Bengali conjuncts, Devanagari, Khmer…) arrives,+ // so xterm re-renders through the DOM renderer (#58685).+ let webglAddon: { dispose(): void } | null = null;if (useWebgl) {try {const webgl = new WebglAddon();webgl.onContextLoss(() => webgl.dispose());term.loadAddon(webgl);+ webglAddon = webgl;} catch (err) {console.warn("[hermes-chat] WebGL renderer unavailable; falling back to default",@@ -1387,6 +1365,18 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {)? () => termRef.current?.scrollToBottom(): undefined;+ // Complex scripts (Bengali conjuncts etc.) cannot be drawn from a+ // per-glyph atlas — the first such payload swaps to the DOM renderer,+ // whose text shaping renders them properly (#58685). Disposing the+ // addon makes xterm fall back and redraw on its own.+ if (webglAddon && textNeedsDomShaping(text)) {+ try {+ webglAddon.dispose();+ } catch {+ /* already gone */+ }+ webglAddon = null;+ }term.write(rendered, followScroll);noteResumePtyChunk(rendered);};@@ -1566,9 +1556,7 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {onScrollDisposable?.dispose();mobileInputCleanup?.();compositionForwarder.dispose();- host.removeEventListener("paste", handleBrowserPaste, true);- host.removeEventListener("dragover", handleBrowserDragOver, true);- host.removeEventListener("drop", handleBrowserDrop, true);+ handleBrowserDropCleanup();if (metricsDebounce) clearTimeout(metricsDebounce);window.removeEventListener("resize", scheduleSyncTerminalMetrics);window.clearTimeout(keyboardRevealTimer);