From 653eed950af61e46d6caf41db4d1d8de6db78f0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Wed, 26 Aug 2026 09:04:23 +0000 Subject: [PATCH] fix: keep terminal colors readable across themes (#3018) --- .../components/settings/pty-terminal-view.tsx | 7 +- .../components/task/passthrough-terminal.tsx | 10 ++ apps/web/components/task/shell-terminal.tsx | 38 ++++-- .../components/task/terminal-buffer-reader.ts | 6 + .../task/use-passthrough-terminal.ts | 16 ++- .../task/use-terminal-theme.test.ts | 103 +++++++++++++++ .../web/components/task/use-terminal-theme.ts | 45 +++++++ apps/web/components/theme/app-theme.test.tsx | 21 ++++ apps/web/components/theme/app-theme.tsx | 3 +- .../terminal/mobile-terminal-theme.spec.ts | 40 ++++++ .../tests/terminal/terminal-test-helpers.ts | 94 +++++++++++++- .../e2e/tests/terminal/terminal-theme.spec.ts | 118 ++++++++++++++++++ apps/web/lib/theme/terminal-theme.test.ts | 101 +++++++++++++++ apps/web/lib/theme/terminal-theme.ts | 39 +++++- docs/plans/terminal-theme-rendering/plan.md | 103 +++++++++++++++ .../task-01-add-terminal-theme-regressions.md | 97 ++++++++++++++ ...k-02-implement-adaptive-terminal-themes.md | 117 +++++++++++++++++ docs/specs/ui/README.md | 2 + .../ui/requirements/terminal-rendering.md | 43 +++++++ .../ui/system-design/terminal-rendering.md | 85 +++++++++++++ 20 files changed, 1069 insertions(+), 19 deletions(-) create mode 100644 apps/web/components/task/use-terminal-theme.test.ts create mode 100644 apps/web/components/task/use-terminal-theme.ts create mode 100644 apps/web/e2e/tests/terminal/mobile-terminal-theme.spec.ts create mode 100644 apps/web/e2e/tests/terminal/terminal-theme.spec.ts create mode 100644 apps/web/lib/theme/terminal-theme.test.ts create mode 100644 docs/plans/terminal-theme-rendering/plan.md create mode 100644 docs/plans/terminal-theme-rendering/task-01-add-terminal-theme-regressions.md create mode 100644 docs/plans/terminal-theme-rendering/task-02-implement-adaptive-terminal-themes.md create mode 100644 docs/specs/ui/requirements/terminal-rendering.md create mode 100644 docs/specs/ui/system-design/terminal-rendering.md diff --git a/apps/web/components/settings/pty-terminal-view.tsx b/apps/web/components/settings/pty-terminal-view.tsx index 0cd11aba7b..7065473018 100644 --- a/apps/web/components/settings/pty-terminal-view.tsx +++ b/apps/web/components/settings/pty-terminal-view.tsx @@ -18,6 +18,10 @@ import { openExternalLink } from "@/lib/desktop/external-links"; import { clearBufferReader, exposeBufferReader } from "@/components/task/terminal-buffer-reader"; import { pendingPtyStarts, type PendingPtyStart } from "./pty-terminal-lifecycle"; import { FONT } from "@/lib/theme/colors"; +import { + getFixedDarkTerminalTheme, + TERMINAL_MINIMUM_CONTRAST_RATIO, +} from "@/lib/theme/terminal-theme"; export type PtySessionStatus = "connecting" | "running" | "exited" | "error"; @@ -56,7 +60,8 @@ function createTerminal(container: HTMLDivElement): { term: Terminal; fit: FitAd cursorBlink: true, fontFamily: FONT.mono, fontSize: FONT.size, - theme: { background: "#0b0b0c" }, + minimumContrastRatio: TERMINAL_MINIMUM_CONTRAST_RATIO, + theme: getFixedDarkTerminalTheme(), }); const fit = new FitAddon(); term.loadAddon(fit); diff --git a/apps/web/components/task/passthrough-terminal.tsx b/apps/web/components/task/passthrough-terminal.tsx index e21900150a..62f3178aa6 100644 --- a/apps/web/components/task/passthrough-terminal.tsx +++ b/apps/web/components/task/passthrough-terminal.tsx @@ -9,6 +9,7 @@ import "@xterm/xterm/css/xterm.css"; import { PanelLoadingState } from "@/components/panel-loading-state"; import { useAppStore } from "@/components/state-provider"; import { useSession } from "@/hooks/domains/session/use-session"; +import { useTheme } from "@/components/theme/app-theme"; import type { TaskSessionState } from "@/app/office/tasks/[id]/types"; import { getBackendConfig } from "@/lib/config"; import { useTerminalLinkHandler } from "@/hooks/use-terminal-link-handler"; @@ -28,6 +29,7 @@ import { useTerminalSearch } from "./use-terminal-search"; import { TerminalSearchBar } from "./terminal-search-bar"; import { usePanelSearch } from "@/hooks/use-panel-search"; import { useTerminalBusyTracking } from "./use-terminal-busy-tracking"; +import { useTerminalTheme } from "./use-terminal-theme"; import { useTranslation } from "react-i18next"; type BaseProps = { @@ -221,6 +223,7 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) { onWsReady, enableTouchScroll, } = props; + const { resolvedTheme } = useTheme(); const terminalId = mode === "shell" ? props.terminalId : undefined; const environmentId = mode === "shell" ? props.environmentId : undefined; const refs = useTerminalRefs(); @@ -296,11 +299,18 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) { fontFamily: buildTerminalFontFamily(terminalFontFamily), fontSize: terminalFontSize ?? undefined, disableWebgl, + resolvedTheme, onToggleBottomTerminal: toggleBottomTerminal, sendInput, keyboardShortcutsRef, onFindInPanelRef, }); + useTerminalTheme({ + terminalRef: xtermRef, + containerRef: terminalRef, + isTerminalReady, + resolvedTheme, + }); useTerminalBusyTracking(terminalId, xtermRef, mode === "shell", isTerminalReady); useTouchScroll({ diff --git a/apps/web/components/task/shell-terminal.tsx b/apps/web/components/task/shell-terminal.tsx index 9fa6cdcb33..69104dcb6c 100644 --- a/apps/web/components/task/shell-terminal.tsx +++ b/apps/web/components/task/shell-terminal.tsx @@ -9,10 +9,13 @@ import { useAppStore, useAppStoreApi } from "@/components/state-provider"; import { getWebSocketClient } from "@/lib/ws/connection"; import { useSession } from "@/hooks/domains/session/use-session"; import { useSessionAgentctl } from "@/hooks/domains/session/use-session-agentctl"; -import { getTerminalTheme } from "@/lib/theme/terminal-theme"; +import { useTheme } from "@/components/theme/app-theme"; +import type { ResolvedTheme } from "@/components/theme/app-theme"; +import { getTerminalTheme, TERMINAL_MINIMUM_CONTRAST_RATIO } from "@/lib/theme/terminal-theme"; import { useTerminalLinkHandler } from "@/hooks/use-terminal-link-handler"; import { buildTerminalFontFamily } from "@/lib/terminal/terminal-font"; -import { exposeBufferReader } from "./terminal-buffer-reader"; +import { clearBufferReader, exposeBufferReader } from "./terminal-buffer-reader"; +import { useTerminalTheme } from "./use-terminal-theme"; import { SHORTCUTS } from "@/lib/keyboard/constants"; import { matchesShortcut } from "@/lib/keyboard/utils"; import { useTerminalSearch } from "./use-terminal-search"; @@ -48,6 +51,7 @@ type ShellTerminalInitOptions = { fontFamily?: string; fontSize?: number; onReady?: () => void; + resolvedTheme: ResolvedTheme; }; function useTerminalInit({ @@ -59,11 +63,17 @@ function useTerminalInit({ fontFamily, fontSize, onReady, + resolvedTheme, }: ShellTerminalInitOptions) { const { terminalRef, xtermRef, fitAddonRef, lastOutputLengthRef, outputRef } = refs; + const resolvedThemeRef = useRef(resolvedTheme); + resolvedThemeRef.current = resolvedTheme; + // Theme changes update the existing xterm through useTerminalTheme; this + // initialization effect intentionally does not rerun for them. useEffect(() => { - if (!terminalRef.current || xtermRef.current) return; + const container = terminalRef.current; + if (!container || xtermRef.current) return; const terminal = new Terminal({ cursorBlink: !isReadOnlyMode, disableStdin: isReadOnlyMode, @@ -72,15 +82,16 @@ function useTerminalInit({ // i18n-exempt: CSS font stack. fontFamily: fontFamily || 'Menlo, Monaco, "Courier New", monospace', macOptionIsMeta: true, - theme: getTerminalTheme(terminalRef.current), + minimumContrastRatio: TERMINAL_MINIMUM_CONTRAST_RATIO, + theme: getTerminalTheme(container, resolvedThemeRef.current), }); const fitAddon = new FitAddon(); terminal.loadAddon(fitAddon); const webLinksAddon = new WebLinksAddon(linkHandler); terminal.loadAddon(webLinksAddon); - terminal.open(terminalRef.current); - suppressIOSKeyboardAssists(terminalRef.current); - exposeBufferReader(terminalRef.current, terminal); + terminal.open(container); + suppressIOSKeyboardAssists(container); + exposeBufferReader(container, terminal); fitAddon.fit(); xtermRef.current = terminal; fitAddonRef.current = fitAddon; @@ -97,7 +108,7 @@ function useTerminalInit({ const resizeObserver = new ResizeObserver(() => { fitAddon.fit(); }); - resizeObserver.observe(terminalRef.current); + resizeObserver.observe(container); const intersectionObserver = new IntersectionObserver( (entries) => { entries.forEach((entry) => { @@ -110,13 +121,14 @@ function useTerminalInit({ }, { threshold: 0.1 }, ); - intersectionObserver.observe(terminalRef.current); + intersectionObserver.observe(container); if (!isReadOnlyMode) lastOutputLengthRef.current = 0; return () => { clearTimeout(initialFitTimeout); resizeObserver.disconnect(); intersectionObserver.disconnect(); + clearBufferReader(container); terminal.dispose(); xtermRef.current = null; fitAddonRef.current = null; @@ -402,6 +414,7 @@ export function ShellTerminal({ isStopping = false, }: ShellTerminalProps) { const { t } = useTranslation(); + const { resolvedTheme } = useTheme(); const terminalRef = useRef(null); const xtermRef = useRef(null); const fitAddonRef = useRef(null); @@ -451,6 +464,13 @@ export function ShellTerminal({ fontFamily: buildTerminalFontFamily(terminalFontFamily), fontSize: terminalFontSize ?? undefined, onReady: onTerminalReady, + resolvedTheme, + }); + useTerminalTheme({ + terminalRef: xtermRef, + containerRef: terminalRef, + isTerminalReady, + resolvedTheme, }); const search = useTerminalSearch({ xtermRef, isTerminalReady }); diff --git a/apps/web/components/task/terminal-buffer-reader.ts b/apps/web/components/task/terminal-buffer-reader.ts index 71a360537b..90267b60de 100644 --- a/apps/web/components/task/terminal-buffer-reader.ts +++ b/apps/web/components/task/terminal-buffer-reader.ts @@ -5,6 +5,7 @@ type TerminalContainerWithBuffer = HTMLDivElement & { __xtermReadViewportY?: () => number; __xtermGetFontFamily?: () => string; __xtermGetFontSize?: () => number; + __xtermReadTheme?: () => Record; }; /** Expose buffer reader on the container for e2e tests (xterm renders to canvas). */ @@ -21,6 +22,10 @@ export function exposeBufferReader(container: HTMLDivElement, terminal: Terminal c.__xtermReadViewportY = () => terminal.buffer.active.viewportY; c.__xtermGetFontFamily = () => terminal.options.fontFamily ?? ""; c.__xtermGetFontSize = () => terminal.options.fontSize ?? 13; + c.__xtermReadTheme = () => ({ + ...(terminal.options.theme ?? {}), + minimumContrastRatio: terminal.options.minimumContrastRatio, + }); } export function clearBufferReader(container: HTMLDivElement) { @@ -29,4 +34,5 @@ export function clearBufferReader(container: HTMLDivElement) { c.__xtermReadViewportY = undefined; c.__xtermGetFontFamily = undefined; c.__xtermGetFontSize = undefined; + c.__xtermReadTheme = undefined; } diff --git a/apps/web/components/task/use-passthrough-terminal.ts b/apps/web/components/task/use-passthrough-terminal.ts index 6843034770..3d8e29177f 100644 --- a/apps/web/components/task/use-passthrough-terminal.ts +++ b/apps/web/components/task/use-passthrough-terminal.ts @@ -5,7 +5,8 @@ import { AttachAddon } from "@xterm/addon-attach"; import { Unicode11Addon } from "@xterm/addon-unicode11"; import { WebLinksAddon } from "@xterm/addon-web-links"; import { WebglAddon } from "@xterm/addon-webgl"; -import { getTerminalTheme } from "@/lib/theme/terminal-theme"; +import { getTerminalTheme, TERMINAL_MINIMUM_CONTRAST_RATIO } from "@/lib/theme/terminal-theme"; +import type { ResolvedTheme } from "@/components/theme/app-theme"; import { startReconnectLoop, teardownWebSocket } from "./ws-reconnect"; import { matchesShortcut } from "@/lib/keyboard/utils"; import { SHORTCUTS } from "@/lib/keyboard/constants"; @@ -32,6 +33,7 @@ export type TerminalInitOptions = { webglAddonRef: React.MutableRefObject; fitAndResize: (force?: boolean) => void; onReady: () => void; + resolvedTheme: ResolvedTheme; }; type TerminalKeyHandlerOptions = { @@ -135,11 +137,11 @@ function initTerminalInstance( fontFamily?: string; fontSize?: number; disableWebgl?: boolean; + resolvedTheme: ResolvedTheme; } & TerminalKeyHandlerOptions, ) { if (refs.isInitializedRef.current || refs.xtermRef.current) return undefined; refs.isInitializedRef.current = true; - log("Creating terminal"); const terminal = new Terminal({ allowProposedApi: true, cursorBlink: true, @@ -151,7 +153,8 @@ function initTerminalInstance( // i18n-exempt: CSS font-family stack, not copy. fontFamily: options.fontFamily || 'Menlo, Monaco, "Courier New", monospace', macOptionIsMeta: true, - theme: getTerminalTheme(termContainer), + minimumContrastRatio: TERMINAL_MINIMUM_CONTRAST_RATIO, + theme: getTerminalTheme(termContainer, options.resolvedTheme), }); const fitAddon = new FitAddon(); terminal.loadAddon(fitAddon); @@ -224,11 +227,14 @@ export function useTerminalInit({ fontFamily, fontSize, disableWebgl, + resolvedTheme, onToggleBottomTerminal, sendInput, keyboardShortcutsRef, onFindInPanelRef, }: TerminalInitHookOptions) { + const resolvedThemeRef = useRef(resolvedTheme); + resolvedThemeRef.current = resolvedTheme; const refs = { xtermRef, fitAddonRef, @@ -238,10 +244,8 @@ export function useTerminalInit({ webglAddonRef, }; useEffect(() => { - log("Terminal init effect"); const container = terminalRef.current; if (!container) { - log("No container ref"); return; } if (isInitializedRef.current) { @@ -259,6 +263,7 @@ export function useTerminalInit({ fontFamily, fontSize, disableWebgl, + resolvedTheme: resolvedThemeRef.current, onToggleBottomTerminal, sendInput, keyboardShortcutsRef, @@ -305,6 +310,7 @@ export function useTerminalInit({ xterm.current.dispose(); xterm.current = null; } + clearBufferReader(container); fitAddon.current = null; isInitializedRef.current = false; lastDimensionsRef.current = { cols: 0, rows: 0 }; diff --git a/apps/web/components/task/use-terminal-theme.test.ts b/apps/web/components/task/use-terminal-theme.test.ts new file mode 100644 index 0000000000..cdded7a183 --- /dev/null +++ b/apps/web/components/task/use-terminal-theme.test.ts @@ -0,0 +1,103 @@ +import { act, renderHook } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { Terminal } from "@xterm/xterm"; +import { useTerminalTheme } from "./use-terminal-theme"; + +const getTerminalTheme = vi.hoisted(() => vi.fn(() => ({ background: "#updated" }))); + +vi.mock("@/lib/theme/terminal-theme", () => ({ + getTerminalTheme, +})); + +type QueuedFrame = { + callback: FrameRequestCallback; + id: number; +}; + +function createRefs() { + const container = document.createElement("div"); + const terminal = { + element: document.createElement("div"), + options: { theme: { background: "#initial" } }, + } as unknown as Terminal; + const terminalRef = { current: terminal }; + const containerRef = { current: container }; + return { container, containerRef, terminal, terminalRef }; +} + +describe("useTerminalTheme", () => { + let nextFrameId = 1; + let queuedFrames: QueuedFrame[] = []; + let cancelAnimationFrameMock: ReturnType; + + afterEach(() => { + vi.unstubAllGlobals(); + queuedFrames = []; + nextFrameId = 1; + getTerminalTheme.mockClear(); + }); + + function stubAnimationFrames() { + cancelAnimationFrameMock = vi.fn((frameId: number) => { + queuedFrames = queuedFrames.filter(({ id }) => id !== frameId); + }); + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { + const id = nextFrameId++; + queuedFrames.push({ callback, id }); + return id; + }); + vi.stubGlobal("cancelAnimationFrame", cancelAnimationFrameMock); + } + + function runNextFrame() { + const frame = queuedFrames.shift(); + expect(frame).toBeDefined(); + act(() => frame?.callback(0)); + } + + it("updates the existing terminal after the second animation frame", () => { + stubAnimationFrames(); + const { containerRef, terminal, terminalRef } = createRefs(); + + renderHook(() => + useTerminalTheme({ + terminalRef, + containerRef, + isTerminalReady: true, + resolvedTheme: "dark", + }), + ); + + expect(terminal.options.theme).toMatchObject({ background: "#initial" }); + runNextFrame(); + expect(terminal.options.theme).toMatchObject({ background: "#initial" }); + + runNextFrame(); + + expect(getTerminalTheme).toHaveBeenCalledWith(containerRef.current, "dark"); + expect(terminal.options.theme).toMatchObject({ background: "#updated" }); + }); + + it("cancels the pending second frame during cleanup", () => { + stubAnimationFrames(); + const { containerRef, terminal, terminalRef } = createRefs(); + const { unmount } = renderHook(() => + useTerminalTheme({ + terminalRef, + containerRef, + isTerminalReady: true, + resolvedTheme: "light", + }), + ); + + runNextFrame(); + const pendingSecondFrame = queuedFrames[0]?.id; + expect(pendingSecondFrame).toBeDefined(); + + unmount(); + + expect(cancelAnimationFrameMock).toHaveBeenCalledWith(pendingSecondFrame); + expect(queuedFrames).toHaveLength(0); + expect(terminal.options.theme).toMatchObject({ background: "#initial" }); + }); +}); diff --git a/apps/web/components/task/use-terminal-theme.ts b/apps/web/components/task/use-terminal-theme.ts new file mode 100644 index 0000000000..ae5ead89ba --- /dev/null +++ b/apps/web/components/task/use-terminal-theme.ts @@ -0,0 +1,45 @@ +import { useEffect, type RefObject } from "react"; +import type { Terminal } from "@xterm/xterm"; +import type { ResolvedTheme } from "@/components/theme/app-theme"; +import { getTerminalTheme } from "@/lib/theme/terminal-theme"; + +type UseTerminalThemeOptions = { + terminalRef: RefObject; + containerRef: RefObject; + isTerminalReady: boolean; + resolvedTheme: ResolvedTheme; +}; + +/** Keep an open xterm instance in sync without replacing its buffer or socket. */ +export function useTerminalTheme({ + terminalRef, + containerRef, + isTerminalReady, + resolvedTheme, +}: UseTerminalThemeOptions): void { + useEffect(() => { + if (!isTerminalReady) return; + + const terminal = terminalRef.current; + const container = containerRef.current; + if (!terminal || !container || !terminal.element) return; + + let cancelled = false; + let secondFrame: number | null = null; + const firstFrame = requestAnimationFrame(() => { + secondFrame = requestAnimationFrame(() => { + if (cancelled) return; + const currentTerminal = terminalRef.current; + const currentContainer = containerRef.current; + if (!currentTerminal || !currentContainer || !currentTerminal.element) return; + currentTerminal.options.theme = getTerminalTheme(currentContainer, resolvedTheme); + }); + }); + + return () => { + cancelled = true; + cancelAnimationFrame(firstFrame); + if (secondFrame !== null) cancelAnimationFrame(secondFrame); + }; + }, [containerRef, isTerminalReady, resolvedTheme, terminalRef]); +} diff --git a/apps/web/components/theme/app-theme.test.tsx b/apps/web/components/theme/app-theme.test.tsx index 080306a4d4..4cd868e550 100644 --- a/apps/web/components/theme/app-theme.test.tsx +++ b/apps/web/components/theme/app-theme.test.tsx @@ -1,4 +1,5 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { useEffect } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { AppThemeProvider, useTheme } from "./app-theme"; @@ -33,10 +34,30 @@ describe("AppThemeProvider settings preview", () => { afterEach(() => { cleanup(); + document.documentElement.className = ""; window.localStorage.clear(); vi.unstubAllGlobals(); }); + it("applies the initial resolved theme before descendant passive effects", () => { + const observedRootThemes: string[] = []; + + function InitialThemeProbe() { + useEffect(() => { + observedRootThemes.push(document.documentElement.className); + }, []); + return null; + } + + render( + + + , + ); + + expect(observedRootThemes).toEqual(["dark"]); + }); + it("previews without writing storage and restores the saved theme", () => { render( diff --git a/apps/web/components/theme/app-theme.tsx b/apps/web/components/theme/app-theme.tsx index 4d0180fc5f..2602730a84 100644 --- a/apps/web/components/theme/app-theme.tsx +++ b/apps/web/components/theme/app-theme.tsx @@ -5,6 +5,7 @@ import { useCallback, useContext, useEffect, + useLayoutEffect, useMemo, useState, type ReactNode, @@ -93,7 +94,7 @@ export function AppThemeProvider({ return () => media.removeEventListener("change", listener); }, []); - useEffect(() => { + useLayoutEffect(() => { const update = () => applyTheme(attribute, resolvedTheme); if (disableTransitionOnChange) { withDisabledTransitions(update); diff --git a/apps/web/e2e/tests/terminal/mobile-terminal-theme.spec.ts b/apps/web/e2e/tests/terminal/mobile-terminal-theme.spec.ts new file mode 100644 index 0000000000..1d89a54ee7 --- /dev/null +++ b/apps/web/e2e/tests/terminal/mobile-terminal-theme.spec.ts @@ -0,0 +1,40 @@ +// Routing: /t/{taskId}. The mobile- prefix selects the Pixel 5 project. +import { expect, test } from "../../fixtures/test-base"; +import { openTaskSession } from "../../helpers/session"; +import { expectTerminalTheme, readTerminalHostTheme } from "./terminal-test-helpers"; +import { switchToTerminalPanel, waitForShellReady } from "./mobile-terminal-helpers"; + +test.describe("mobile adaptive terminal theme", () => { + test("keeps the light-theme terminal readable on a phone", async ({ + testPage, + apiClient, + seedData, + prCapture, + }) => { + const task = await apiClient.createTaskWithAgent( + seedData.workspaceId, + "Mobile terminal theme", + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repository_ids: [seedData.repositoryId], + }, + ); + await openTaskSession(testPage, task.id); + await switchToTerminalPanel(testPage); + await waitForShellReady(testPage); + + await expect(testPage.locator("html")).toHaveClass(/(^|\s)light(\s|$)/); + const host = testPage + .getByTestId("terminal-panel") + .locator('[data-testid="terminal-xterm-host"]:visible'); + const theme = await readTerminalHostTheme(host); + + expectTerminalTheme(theme, "light", "the mobile xterm"); + await prCapture.screenshot("mobile-terminal-theme-light", { + caption: "Pixel 5 task terminal with the readable light-theme palette", + }); + }); +}); diff --git a/apps/web/e2e/tests/terminal/terminal-test-helpers.ts b/apps/web/e2e/tests/terminal/terminal-test-helpers.ts index 9de6b80f4e..a22e6eb10f 100644 --- a/apps/web/e2e/tests/terminal/terminal-test-helpers.ts +++ b/apps/web/e2e/tests/terminal/terminal-test-helpers.ts @@ -1,4 +1,80 @@ -import type { Locator } from "@playwright/test"; +import { expect, type Locator } from "@playwright/test"; + +export type TerminalThemeSnapshot = { + background?: string; + foreground?: string; + cursor?: string; + cursorAccent?: string; + selectionBackground?: string; + minimumContrastRatio?: number; + [key: string]: string | number | string[] | undefined; +}; + +export type TerminalThemeMode = "light" | "dark"; + +const terminalThemeContracts: Record = { + light: { + background: "oklch(100% 0 0)", + foreground: "oklch(14.5% 0 0)", + cursor: "oklch(14.5% 0 0)", + cursorAccent: "oklch(100% 0 0)", + selectionBackground: "oklch(97% 0 0)", + minimumContrastRatio: 4.5, + black: "#000000", + red: "#cd3131", + green: "#008000", + yellow: "#795e00", + blue: "#0451a5", + magenta: "#bc05bc", + cyan: "#005a5a", + white: "#555555", + brightBlack: "#666666", + brightRed: "#c41a16", + brightGreen: "#006400", + brightYellow: "#9c6500", + brightBlue: "#1769aa", + brightMagenta: "#9c00a8", + brightCyan: "#007a7a", + brightWhite: "#000000", + }, + dark: { + background: "#181818", + foreground: "#d4d4d4", + cursor: "#d4d4d4", + cursorAccent: "#181818", + selectionBackground: "#2a2a2a", + minimumContrastRatio: 4.5, + black: "#1e1e1e", + red: "#f44747", + green: "#6a9955", + yellow: "#dcdcaa", + blue: "#569cd6", + magenta: "#c586c0", + cyan: "#4ec9b0", + white: "#d4d4d4", + brightBlack: "#808080", + brightRed: "#f44747", + brightGreen: "#6a9955", + brightYellow: "#dcdcaa", + brightBlue: "#569cd6", + brightMagenta: "#c586c0", + brightCyan: "#4ec9b0", + brightWhite: "#ffffff", + }, +}; + +export function terminalThemeContract(mode: TerminalThemeMode): TerminalThemeSnapshot { + return terminalThemeContracts[mode]; +} + +export function expectTerminalTheme( + theme: TerminalThemeSnapshot | null, + mode: TerminalThemeMode, + message: string, +) { + expect(theme, `${message} should expose its complete theme snapshot`).not.toBeNull(); + expect(theme).toMatchObject(terminalThemeContract(mode)); +} export async function readTerminalHostBuffer(host: Locator): Promise { return host.evaluate((element) => { @@ -6,3 +82,19 @@ export async function readTerminalHostBuffer(host: Locator): Promise { return (element as XtermHost).__xtermReadBuffer?.() ?? ""; }); } + +export async function readTerminalViewportY(host: Locator): Promise { + return host.evaluate((element) => { + type XtermHost = HTMLElement & { __xtermReadViewportY?: () => number }; + return (element as XtermHost).__xtermReadViewportY?.() ?? -1; + }); +} + +export async function readTerminalHostTheme(host: Locator): Promise { + return host.evaluate((element) => { + type XtermHost = HTMLElement & { + __xtermReadTheme?: () => TerminalThemeSnapshot; + }; + return (element as XtermHost).__xtermReadTheme?.() ?? null; + }); +} diff --git a/apps/web/e2e/tests/terminal/terminal-theme.spec.ts b/apps/web/e2e/tests/terminal/terminal-theme.spec.ts new file mode 100644 index 0000000000..880ad45bc2 --- /dev/null +++ b/apps/web/e2e/tests/terminal/terminal-theme.spec.ts @@ -0,0 +1,118 @@ +import { expect, test } from "../../fixtures/test-base"; +import { seedIdleSession } from "../../helpers/session"; +import { + expectTerminalTheme, + readTerminalHostBuffer, + readTerminalHostTheme, + readTerminalViewportY, + terminalThemeContract, +} from "./terminal-test-helpers"; + +async function activeTerminalHost(testPage: Parameters[0]) { + return testPage + .getByTestId("terminal-panel") + .locator('[data-testid="terminal-xterm-host"]:visible'); +} + +test.describe("adaptive terminal themes", () => { + test("constructs an initial terminal with the saved dark theme", async ({ + testPage, + apiClient, + seedData, + }) => { + await testPage.addInitScript(() => localStorage.setItem("theme", "dark")); + await seedIdleSession(testPage, apiClient, seedData, "Initial dark terminal theme"); + + const host = await activeTerminalHost(testPage); + await expect(testPage.locator("html")).toHaveClass(/(^|\s)dark(\s|$)/); + const theme = await readTerminalHostTheme(host); + + expectTerminalTheme(theme, "dark", "the initial xterm"); + }); + + test("updates an open terminal when the application theme changes", async ({ + testPage, + apiClient, + seedData, + prCapture, + }) => { + const session = await seedIdleSession( + testPage, + apiClient, + seedData, + "Terminal theme synchronization", + ); + const host = await activeTerminalHost(testPage); + const beforeMarker = "TERMINAL_THEME_BEFORE"; + await session.typeInTerminal(`printf ${beforeMarker}`); + await session.expectTerminalHasText(beforeMarker); + + const xterm = host.locator(".xterm"); + const helperTextarea = xterm.locator(".xterm-helper-textarea"); + await xterm.click(); + await expect(helperTextarea).toBeFocused(); + + await session.typeInTerminal("seq 1 500"); + await expect.poll(() => readTerminalHostBuffer(host)).toContain("500"); + const bottomViewportY = await readTerminalViewportY(host); + expect(bottomViewportY).toBeGreaterThan(0); + const runningMarker = "TERMINAL_THEME_RUNNING"; + await testPage.keyboard.type(`sleep 10; printf ${runningMarker}`); + await testPage.keyboard.press("Enter"); + + await xterm.click(); + await xterm.hover(); + await testPage.mouse.wheel(0, -1200); + await expect + .poll(() => readTerminalViewportY(host), { + message: "Mouse wheel should scroll the terminal into its scrollback", + }) + .toBeLessThan(bottomViewportY); + + const viewportBeforeTheme = await readTerminalViewportY(host); + + const initialTheme = await readTerminalHostTheme(host); + expectTerminalTheme(initialTheme, "light", "the active xterm before switching"); + const initialBuffer = await readTerminalHostBuffer(host); + + const themeToggle = testPage.getByRole("button", { + name: "Switch to Dark Mode", + exact: true, + }); + await expect(themeToggle).toBeVisible(); + await themeToggle.evaluate((element) => (element as HTMLButtonElement).click()); + await expect(testPage.locator("html")).toHaveClass(/(^|\s)dark(\s|$)/); + + await expect + .poll(() => readTerminalHostTheme(host), { + timeout: 5_000, + message: "the open terminal should receive the resolved dark theme", + }) + .toMatchObject(terminalThemeContract("dark")); + expectTerminalTheme( + await readTerminalHostTheme(host), + "dark", + "the active xterm after switching", + ); + await expect + .poll(() => readTerminalHostBuffer(host), { + timeout: 5_000, + message: "the theme update should preserve the terminal buffer", + }) + .toContain(beforeMarker); + await expect(helperTextarea).toBeFocused(); + const viewportAfterTheme = await readTerminalViewportY(host); + expect(Math.abs(viewportAfterTheme - viewportBeforeTheme)).toBeLessThanOrEqual(1); + + const afterMarker = "TERMINAL_THEME_AFTER"; + await expect + .poll(() => readTerminalHostBuffer(host), { timeout: 15_000 }) + .toContain(runningMarker); + await session.typeInTerminal(`printf ${afterMarker}`); + await session.expectTerminalHasText(afterMarker); + expect(await readTerminalHostBuffer(host)).toContain(initialBuffer); + await prCapture.screenshot("terminal-theme-dark", { + caption: "Open task terminal after switching from the light theme to the dark theme", + }); + }); +}); diff --git a/apps/web/lib/theme/terminal-theme.test.ts b/apps/web/lib/theme/terminal-theme.test.ts new file mode 100644 index 0000000000..c2dbc722ec --- /dev/null +++ b/apps/web/lib/theme/terminal-theme.test.ts @@ -0,0 +1,101 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { + getFixedDarkTerminalTheme, + getTerminalTheme, + TERMINAL_MINIMUM_CONTRAST_RATIO, +} from "./terminal-theme"; + +const ANSI_COLOR_KEYS = [ + "black", + "red", + "green", + "yellow", + "blue", + "magenta", + "cyan", + "white", + "brightBlack", + "brightRed", + "brightGreen", + "brightYellow", + "brightBlue", + "brightMagenta", + "brightCyan", + "brightWhite", +] as const; + +function createThemeContainer(): HTMLDivElement { + const container = document.createElement("div"); + container.style.setProperty("--background", "#ffffff"); + container.style.setProperty("--foreground", "#111111"); + container.style.setProperty("--muted", "#e5e7eb"); + document.body.append(container); + return container; +} + +function channel(value: number): number { + const normalized = value / 255; + return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4; +} + +function luminance(color: string): number { + const hex = color.replace("#", ""); + const red = Number.parseInt(hex.slice(0, 2), 16); + const green = Number.parseInt(hex.slice(2, 4), 16); + const blue = Number.parseInt(hex.slice(4, 6), 16); + return 0.2126 * channel(red) + 0.7152 * channel(green) + 0.0722 * channel(blue); +} + +function contrastRatio(first: string, second: string): number { + const firstLuminance = luminance(first); + const secondLuminance = luminance(second); + const lighter = Math.max(firstLuminance, secondLuminance); + const darker = Math.min(firstLuminance, secondLuminance); + return (lighter + 0.05) / (darker + 0.05); +} + +afterEach(() => { + document.body.replaceChildren(); +}); + +describe("getTerminalTheme", () => { + it("uses a readable ANSI palette in light mode", () => { + const theme = getTerminalTheme(createThemeContainer(), "light"); + const background = theme.background ?? ""; + const unreadableColors = ANSI_COLOR_KEYS.filter((key) => { + const color = theme[key]; + return typeof color === "string" && contrastRatio(color, background) < 4.5; + }); + + expect(unreadableColors).toEqual([]); + }); + + it("selects the resolved theme palette", () => { + const container = createThemeContainer(); + const lightTheme = getTerminalTheme(container, "light"); + const darkTheme = getTerminalTheme(container, "dark"); + + expect(lightTheme.red).toBe("#cd3131"); + expect(darkTheme.red).toBe("#f44747"); + }); + + it("keeps light bright ANSI variants visually distinct", () => { + const theme = getTerminalTheme(createThemeContainer(), "light"); + + expect(theme.brightBlue).not.toBe(theme.blue); + expect(theme.brightCyan).not.toBe(theme.cyan); + expect(theme.brightYellow).not.toBe(theme.yellow); + }); + + it("keeps fixed-dark terminals independent of the application theme", () => { + expect(getFixedDarkTerminalTheme()).toMatchObject({ + background: "#0b0b0c", + foreground: "#d4d4d4", + red: "#f44747", + }); + }); + + it("uses the WCAG AA xterm contrast contract", () => { + expect(TERMINAL_MINIMUM_CONTRAST_RATIO).toBe(4.5); + }); +}); diff --git a/apps/web/lib/theme/terminal-theme.ts b/apps/web/lib/theme/terminal-theme.ts index 931abf21c4..61ebbb6af6 100644 --- a/apps/web/lib/theme/terminal-theme.ts +++ b/apps/web/lib/theme/terminal-theme.ts @@ -1,10 +1,13 @@ import type { ITheme } from "@xterm/xterm"; +import type { ResolvedTheme } from "@/components/theme/app-theme"; + +export const TERMINAL_MINIMUM_CONTRAST_RATIO = 4.5; /** * ANSI terminal colors — standard palette, not derived from the app theme. * These are used for syntax highlighting, command output, etc. */ -const ansiColors = { +const darkAnsiColors = { black: "#1e1e1e", red: "#f44747", green: "#6a9955", @@ -23,6 +26,25 @@ const ansiColors = { brightWhite: "#ffffff", } as const; +const lightAnsiColors = { + black: "#000000", + red: "#cd3131", + green: "#008000", + yellow: "#795e00", + blue: "#0451a5", + magenta: "#bc05bc", + cyan: "#005a5a", + white: "#555555", + brightBlack: "#666666", + brightRed: "#c41a16", + brightGreen: "#006400", + brightYellow: "#9c6500", + brightBlue: "#1769aa", + brightMagenta: "#9c00a8", + brightCyan: "#007a7a", + brightWhite: "#000000", +} as const; + /** * Build the xterm.js theme by resolving CSS custom properties from the DOM. * @@ -32,9 +54,10 @@ const ansiColors = { * All theme-dependent colors come from CSS variables defined in globals.css, * so changing the app theme in one place updates terminals too. */ -export function getTerminalTheme(container: HTMLElement): ITheme { +export function getTerminalTheme(container: HTMLElement, resolvedTheme: ResolvedTheme): ITheme { const s = getComputedStyle(container); const v = (name: string) => s.getPropertyValue(name).trim(); + const ansiColors = resolvedTheme === "light" ? lightAnsiColors : darkAnsiColors; return { background: v("--background"), @@ -45,3 +68,15 @@ export function getTerminalTheme(container: HTMLElement): ITheme { ...ansiColors, }; } + +/** Build the dark palette used by terminals that are independent of the app theme. */ +export function getFixedDarkTerminalTheme(): ITheme { + return { + background: "#0b0b0c", + foreground: "#d4d4d4", + cursor: "#d4d4d4", + cursorAccent: "#0b0b0c", + selectionBackground: "#2a2a2a", + ...darkAnsiColors, + }; +} diff --git a/docs/plans/terminal-theme-rendering/plan.md b/docs/plans/terminal-theme-rendering/plan.md new file mode 100644 index 0000000000..267e23c092 --- /dev/null +++ b/docs/plans/terminal-theme-rendering/plan.md @@ -0,0 +1,103 @@ +--- +created: 2026-08-25 +status: complete +requirements: + - REQ-UI-TERMINAL-RENDERING-001 +system_design: + - ../../specs/ui/system-design/terminal-rendering.md +legacy_specs: [] +--- + +# Implementation Plan: Terminal Theme Rendering + +## Overview + +The current renderer combines a light background with a dark-only ANSI palette. It also captures theme values only when xterm starts. This plan adds red regression evidence first, then implements one shared adaptive theme contract for all xterm constructors. + +## Scope + +### In scope + +- Add separate light and dark ANSI palettes. +- Enforce a 4.5:1 minimum contrast ratio through xterm. +- Update open adaptive terminals when the resolved theme changes. +- Keep fixed-dark terminals on the shared dark palette. +- Cover desktop and phone task terminals with Playwright, and document the + shared rendering path used by tablet task terminals. + +### Out of scope + +- Change terminal transport, PTY lifecycle, output buffering, or shell configuration. +- Add user-defined palettes or new appearance settings. +- Change terminal layout, mobile composition, keyboard controls, or scrolling. +- Change the visual design of Quick Terminal or agent-login dialogs. + +## Technical approach + +### Shared palette + +Update `apps/web/lib/theme/terminal-theme.ts` to select an ANSI palette from an explicit `ResolvedTheme`. Export one minimum contrast value for every xterm constructor. + +Use the shared fixed-dark result in `PtyTerminalView`. Remove its isolated background-only xterm theme. + +### Reactive application + +Add `apps/web/components/task/use-terminal-theme.ts`. The hook receives the xterm reference, host reference, readiness state, and resolved theme. + +The hook updates `terminal.options.theme` after the root theme class commits. It cancels pending work during cleanup and never reconstructs the terminal. + +`AppThemeProvider` applies the initial root theme class in a layout effect, so +descendant terminal construction effects read CSS variables for the resolved +theme on the first render. + +Pass `resolvedTheme` through `ShellTerminal` and `PassthroughTerminal`. Keep their current connection, resize, input, search, and mobile behavior. + +### Browser evidence + +Extend the existing xterm test bridge with a read-only theme snapshot. Clear the snapshot function with the other bridge functions during cleanup. + +Add desktop and mobile terminal theme specs. The desktop flow changes theme while the terminal stays mounted. The mobile flow uses the existing Pixel 5 terminal surface in light mode. + +## Tests + +| Acceptance criterion | Evidence | +| --- | --- | +| `AC-UI-TERMINAL-RENDERING-001.1` | `terminal-theme.test.ts` selects the initial light and dark palettes. | +| `AC-UI-TERMINAL-RENDERING-001.2` | `terminal-theme.test.ts` checks the shared contrast setting. Desktop and mobile specs inspect the live xterm value. | +| `AC-UI-TERMINAL-RENDERING-001.3` | `terminal-theme.spec.ts` changes the application theme and observes the live xterm theme. | +| `AC-UI-TERMINAL-RENDERING-001.4` | `terminal-theme.spec.ts` keeps buffer content, focus, scroll position, and a running command while accepting new shell output after the theme change. | +| `AC-UI-TERMINAL-RENDERING-001.5` | Desktop and `mobile-terminal-theme.spec.ts` check the same light-theme contract. | +| `AC-UI-TERMINAL-RENDERING-001.6` | `terminal-theme.test.ts` checks the shared fixed-dark theme. | + +The first work order must fail against the current implementation. The expected unit failure is `uses a readable ANSI palette in light mode`. The expected desktop failure is `updates an open terminal when the application theme changes`. + +## E2E tests + +- `apps/web/e2e/tests/terminal/terminal-theme.spec.ts` uses the `chromium` project for `AC-UI-TERMINAL-RENDERING-001.1` through `.4`. +- `apps/web/e2e/tests/terminal/mobile-terminal-theme.spec.ts` uses the `mobile-chrome` Pixel 5 project for `AC-UI-TERMINAL-RENDERING-001.2` and `.5`. +- Tablet task terminals use the same `PassthroughTerminal` and + `useTerminalTheme` path as the desktop and phone surfaces. The shared-path + evidence covers tablet rendering without adding a separate viewport test. + +## Work orders + +- [x] [Task 01: Add terminal theme regressions](task-01-add-terminal-theme-regressions.md) +- [x] [Task 02: Implement adaptive terminal themes](task-02-implement-adaptive-terminal-themes.md) + +## Verification results + +Passed on 2026-08-25: + +- `cd apps/web && pnpm test -- lib/theme/terminal-theme.test.ts` +- `cd apps/web && pnpm test -- components/task/use-terminal-theme.test.ts components/theme/app-theme.test.tsx` +- `cd apps/web && pnpm run typecheck` +- Targeted ESLint for all changed terminal, theme, bridge, and E2E files with zero warnings. +- `cd apps/web && pnpm e2e:run tests/terminal/terminal-theme.spec.ts` +- `cd apps/web && pnpm e2e:run --project mobile-chrome tests/terminal/mobile-terminal-theme.spec.ts` + +## Risks + +- A theme effect can read old CSS variables before the root theme class changes. The browser test must change theme through Kandev UI. +- Reconstructing xterm can clear the buffer or reconnect the shell. The implementation must mutate `terminal.options.theme` only. +- WebGL and canvas renderers use the same xterm theme contract. The mobile path keeps WebGL disabled for its existing scaling rule. +- The test bridge must remain read-only and must remove every added function during cleanup. diff --git a/docs/plans/terminal-theme-rendering/task-01-add-terminal-theme-regressions.md b/docs/plans/terminal-theme-rendering/task-01-add-terminal-theme-regressions.md new file mode 100644 index 0000000000..55dbcb7328 --- /dev/null +++ b/docs/plans/terminal-theme-rendering/task-01-add-terminal-theme-regressions.md @@ -0,0 +1,97 @@ +--- +id: "01-add-terminal-theme-regressions" +title: "Add terminal theme regressions" +status: done +wave: 1 +depends_on: [] +plan: "plan.md" +requirements: + - REQ-UI-TERMINAL-RENDERING-001 +acceptance_criteria: + - AC-UI-TERMINAL-RENDERING-001.1 + - AC-UI-TERMINAL-RENDERING-001.2 + - AC-UI-TERMINAL-RENDERING-001.3 + - AC-UI-TERMINAL-RENDERING-001.4 + - AC-UI-TERMINAL-RENDERING-001.5 + - AC-UI-TERMINAL-RENDERING-001.6 +system_design: + - ../../specs/ui/system-design/terminal-rendering.md +--- + +# Task 01: Add Terminal Theme Regressions + +## Summary + +Add unit and browser regressions before the correction. Record the expected failures for the light ANSI palette and stale live theme. + +## In scope + +- Add unit coverage for light, dark, and fixed-dark terminal themes. +- Extend the read-only xterm browser bridge with theme and minimum-contrast snapshots. +- Add a desktop test that changes theme while one terminal stays open. +- Add a Pixel 5 test for the existing mobile terminal in light mode. +- Document the shared `PassthroughTerminal` rendering path used by tablet + terminals instead of duplicating the browser regression for a third viewport. +- Add `@covers` comments where the acceptance mapping is not clear from the test name. + +## Out of scope + +- Change palette values or terminal constructors. +- Add live theme synchronization. +- Change terminal transport, layout, or mobile interaction. + +## Acceptance + +- The unit test fails because the current light theme uses the dark ANSI palette. +- The desktop test fails because the open xterm instance keeps stale theme values. +- The mobile test fails because the live light terminal does not meet the shared contrast contract. + +## Verification + +These commands must fail for the documented reasons before Task 02 starts. + +```bash +cd apps/web && pnpm test -- lib/theme/terminal-theme.test.ts +``` + +```bash +cd apps/web && pnpm e2e:run tests/terminal/terminal-theme.spec.ts +``` + +```bash +cd apps/web && pnpm e2e:run --project mobile-chrome tests/terminal/mobile-terminal-theme.spec.ts +``` + +## Files likely touched + +- `apps/web/lib/theme/terminal-theme.test.ts` +- `apps/web/components/task/terminal-buffer-reader.ts` +- `apps/web/e2e/tests/terminal/terminal-test-helpers.ts` +- `apps/web/e2e/tests/terminal/terminal-theme.spec.ts` +- `apps/web/e2e/tests/terminal/mobile-terminal-theme.spec.ts` + +## Dependencies + +None. + +## Risks + +- The test must read the active terminal panel because Dockview can mount hidden siblings. +- The test bridge can create false evidence if cleanup leaves a stale snapshot function. + +## Parallelism + +`sequential` + +## Inputs + +- `REQ-UI-TERMINAL-RENDERING-001` +- `docs/specs/ui/system-design/terminal-rendering.md` +- Existing terminal keyboard, settings, and mobile helper patterns. + +## Results + +The unit, desktop, and Pixel 5 regressions were added and run before the +implementation. Each failed for the expected missing palette or live-theme +snapshot behavior, with no fixture or compilation failure. The read-only +xterm bridge now removes the theme snapshot during cleanup. diff --git a/docs/plans/terminal-theme-rendering/task-02-implement-adaptive-terminal-themes.md b/docs/plans/terminal-theme-rendering/task-02-implement-adaptive-terminal-themes.md new file mode 100644 index 0000000000..d69943de1a --- /dev/null +++ b/docs/plans/terminal-theme-rendering/task-02-implement-adaptive-terminal-themes.md @@ -0,0 +1,117 @@ +--- +id: "02-implement-adaptive-terminal-themes" +title: "Implement adaptive terminal themes" +status: done +wave: 2 +depends_on: + - "01-add-terminal-theme-regressions" +plan: "plan.md" +requirements: + - REQ-UI-TERMINAL-RENDERING-001 +acceptance_criteria: + - AC-UI-TERMINAL-RENDERING-001.1 + - AC-UI-TERMINAL-RENDERING-001.2 + - AC-UI-TERMINAL-RENDERING-001.3 + - AC-UI-TERMINAL-RENDERING-001.4 + - AC-UI-TERMINAL-RENDERING-001.5 + - AC-UI-TERMINAL-RENDERING-001.6 +system_design: + - ../../specs/ui/system-design/terminal-rendering.md +--- + +# Task 02: Implement Adaptive Terminal Themes + +## Summary + +Implement the shared light, dark, and fixed-dark theme contract. Update open adaptive terminals without replacing their xterm instance or connection. + +## In scope + +- Add separate light and dark ANSI palettes. +- Add the shared xterm minimum contrast value. +- Apply the resolved theme during every xterm construction path. +- Synchronize open task and agent terminals after a resolved theme change. +- Use the shared fixed-dark theme in `PtyTerminalView`. +- Turn every Task 01 regression green. + +## Out of scope + +- Change PTY or WebSocket ownership. +- Clear or recreate a terminal during a theme change. +- Add a theme preference or configurable palette. +- Change desktop, tablet, or phone terminal composition. + +## Acceptance + +- Every xterm constructor uses the shared palette and minimum contrast contract. +- An open adaptive terminal updates all theme colors without losing buffer content, focus, scroll position, a running command, or new shell output. +- Desktop, mobile, and fixed-dark terminal checks pass without changing their lifecycle behavior. + +## Verification + +```bash +cd apps/web && pnpm test -- lib/theme/terminal-theme.test.ts +``` + +```bash +cd apps/web && pnpm test -- components/task/use-terminal-theme.test.ts components/theme/app-theme.test.tsx +``` + +```bash +cd apps/web && pnpm run typecheck +``` + +```bash +cd apps/web && pnpm exec eslint lib/theme/terminal-theme.ts lib/theme/terminal-theme.test.ts components/task/use-terminal-theme.ts components/task/use-passthrough-terminal.ts components/task/passthrough-terminal.tsx components/task/shell-terminal.tsx components/task/terminal-buffer-reader.ts components/settings/pty-terminal-view.tsx e2e/tests/terminal/terminal-test-helpers.ts e2e/tests/terminal/terminal-theme.spec.ts e2e/tests/terminal/mobile-terminal-theme.spec.ts +``` + +```bash +cd apps/web && pnpm e2e:run tests/terminal/terminal-theme.spec.ts +``` + +```bash +cd apps/web && pnpm e2e:run --project mobile-chrome tests/terminal/mobile-terminal-theme.spec.ts +``` + +## Files likely touched + +- `apps/web/lib/theme/terminal-theme.ts` +- `apps/web/components/task/use-terminal-theme.ts` +- `apps/web/components/task/use-terminal-theme.test.ts` +- `apps/web/components/theme/app-theme.test.tsx` +- `apps/web/components/task/use-passthrough-terminal.ts` +- `apps/web/components/task/passthrough-terminal.tsx` +- `apps/web/components/task/shell-terminal.tsx` +- `apps/web/components/settings/pty-terminal-view.tsx` +- Files from Task 01 when selectors or helper types need final adjustment. + +## Dependencies + +- Task 01 must record the expected red tests. + +## Risks + +- Reading computed CSS colors too early can apply the previous theme. +- Recreating xterm can interrupt active commands and erase the scrollback buffer. +- A palette correction can reduce the distinction between ANSI hues after contrast adjustment. + +## Parallelism + +`sequential` + +## Inputs + +- Task 01 failure evidence. +- `REQ-UI-TERMINAL-RENDERING-001` +- `docs/specs/ui/system-design/terminal-rendering.md` +- All three current xterm constructor paths. + +## Results + +Implemented the shared light and dark palettes, xterm minimum contrast +setting, adaptive live-theme synchronization, and fixed-dark PTY theme. The +root theme now applies before descendant terminal construction effects, and +the light bright variants remain visually distinct. The existing terminal +instance, buffer, WebSocket, focus, scroll position, running command, and +mobile composition remain unchanged. Unit, typecheck, targeted lint, desktop +production E2E, and Pixel 5 production E2E verification all pass. diff --git a/docs/specs/ui/README.md b/docs/specs/ui/README.md index 69ba6c96f1..6817a66a6f 100644 --- a/docs/specs/ui/README.md +++ b/docs/specs/ui/README.md @@ -127,6 +127,7 @@ contract that other capabilities can reuse. - [Task Surface Foreground Refresh and Mobile Create Action](requirements/task-surface-refresh.md) - [Task Workspace Content Search](requirements/task-workspace-content-search.md) - [Terminal close feedback](requirements/terminal-close-feedback.md) +- [Terminal Rendering](requirements/terminal-rendering.md) - [Transcript Auto-scroll Stability](requirements/transcript-auto-scroll.md) - [Transcript Navigation Settings](requirements/transcript-navigation-settings.md) - [Voice Mode In Task Behavior](requirements/voice-mode-task-behavior.md) @@ -154,6 +155,7 @@ contract that other capabilities can reuse. - [Quick Chat and Terminal Tabs](system-design/quick-terminal.md) - [Resizable Markdown Table Columns](system-design/resizable-markdown-tables.md) - [Task Layout Profiles](system-design/task-layout-profiles.md) +- [Terminal Rendering](system-design/terminal-rendering.md) - [Task Transcript History Visibility](system-design/task-prompt-transcript-visibility.md) ## Migration record diff --git a/docs/specs/ui/requirements/terminal-rendering.md b/docs/specs/ui/requirements/terminal-rendering.md new file mode 100644 index 0000000000..009845f75d --- /dev/null +++ b/docs/specs/ui/requirements/terminal-rendering.md @@ -0,0 +1,43 @@ +--- +status: draft +system: ui +created: 2026-08-25 +owners: + - kandev +--- + +# Terminal Rendering Requirements + +## Overview + +Kandev terminal surfaces must keep text readable when the application uses a light or dark theme. The UI system owns this presentation contract because the same terminal renderer serves several task and utility flows. + +## Terminology + +- **Resolved theme:** The active `light` or `dark` theme after Kandev resolves the saved setting and system preference. +- **Adaptive terminal:** An xterm surface that uses the current application background and foreground colors. +- **Fixed-dark terminal:** An xterm surface that keeps its own dark background in both application themes. + +## Requirements + +### REQ-UI-TERMINAL-RENDERING-001: Readable terminal themes + +**Intent:** Terminal prompts, commands, and output remain readable in each supported application theme. A theme change does not interrupt the terminal session. + +**User story:** As a user, I want terminal text to remain readable in light and dark modes, so that I can use my selected theme. + +#### Acceptance criteria + +- **AC-UI-TERMINAL-RENDERING-001.1:** When an adaptive terminal opens, it shall apply the palette for the resolved theme before it shows terminal output. +- **AC-UI-TERMINAL-RENDERING-001.2:** Standard and bright ANSI text shall have a contrast ratio of at least 4.5:1 against the terminal background. +- **AC-UI-TERMINAL-RENDERING-001.3:** When the resolved theme changes, an open adaptive terminal shall update its background, foreground, cursor, selection, and ANSI colors. +- **AC-UI-TERMINAL-RENDERING-001.4:** A theme update shall preserve the terminal instance, buffer, connection, focus, running command, and scroll position. +- **AC-UI-TERMINAL-RENDERING-001.5:** Desktop, tablet, and phone task terminals shall provide the same readable output for the same resolved theme. +- **AC-UI-TERMINAL-RENDERING-001.6:** A fixed-dark terminal shall use a matching dark palette and remain readable in either application theme. + +## Out of scope + +- User-defined terminal palettes. +- Changes to PTY connections, terminal persistence, shell prompts, or ANSI stream interpretation. +- Changes to terminal fonts, layout, navigation, touch controls, scrolling, or keyboard behavior. +- A redesign of fixed-dark Quick Terminal or agent-login surfaces. diff --git a/docs/specs/ui/system-design/terminal-rendering.md b/docs/specs/ui/system-design/terminal-rendering.md new file mode 100644 index 0000000000..3503d25c24 --- /dev/null +++ b/docs/specs/ui/system-design/terminal-rendering.md @@ -0,0 +1,85 @@ +--- +status: draft +system: ui +requirements: + - REQ-UI-TERMINAL-RENDERING-001 +--- + +# Terminal Rendering System Design + +## Purpose and boundaries + +This design defines one theme contract for every xterm constructor in the web application. The contract changes terminal presentation only. Backend shell sessions, WebSocket transport, PTY state, and stored user settings keep their current owners. + +## Requirement mapping + +| Requirement | Design section | +| --- | --- | +| `REQ-UI-TERMINAL-RENDERING-001` | [Shared theme contract](#shared-theme-contract), [Live theme flow](#live-theme-flow), [Responsive behavior](#responsive-behavior) | + +## Confirmed fault + +`getTerminalTheme` reads the current application background and foreground. It then adds one ANSI palette that was made for a dark background. Light mode therefore combines a white background with low-contrast white, yellow, cyan, blue, and magenta ANSI colors. + +The consumers read the theme only when they construct xterm. An open terminal therefore keeps stale colors after the resolved theme changes. + +## Components and responsibilities + +- `apps/web/lib/theme/terminal-theme.ts` owns the light and dark ANSI palettes. It also owns the minimum contrast setting and the xterm theme builder. +- `apps/web/components/task/use-terminal-theme.ts` synchronizes an existing xterm instance with the resolved application theme. +- `apps/web/components/task/shell-terminal.tsx` supplies the resolved theme to development-server and shell-output terminals. +- `apps/web/components/task/use-passthrough-terminal.ts` supplies the initial theme to task and agent terminals. +- `apps/web/components/task/passthrough-terminal.tsx` keeps task, agent, desktop, tablet, and phone instances synchronized. +- `apps/web/components/settings/pty-terminal-view.tsx` uses the shared fixed-dark theme for Quick Terminal and agent-login PTYs. +- `apps/web/components/task/terminal-buffer-reader.ts` exposes bounded xterm theme data for browser tests. It removes that data during terminal cleanup. + +## Shared theme contract + +The theme builder receives an explicit `ResolvedTheme`. It selects a matching ANSI palette and combines it with the terminal surface colors. + +Every xterm constructor sets `minimumContrastRatio` to `4.5`. Xterm can then adjust ANSI cells that do not meet the contrast requirement. The configured palette still keeps distinct ANSI hues before this final renderer adjustment. + +Adaptive terminals use the application background, foreground, cursor, and selection colors. Fixed-dark terminals use the dark base and ANSI palette in both application themes. + +## Live theme flow + +1. `useTheme` supplies the current `resolvedTheme` to each adaptive terminal. +2. `AppThemeProvider` applies the initial root theme class in a layout effect, + before descendant terminal construction effects run. +3. The constructor applies the matching theme before `terminal.open` shows output. +4. A synchronization hook observes later `resolvedTheme` changes. +5. The hook waits for the root theme class and CSS variables to update. +6. The hook assigns the new value to `terminal.options.theme`. +7. Xterm redraws the existing buffer without a new terminal or connection. + +The synchronization hook cancels pending work during unmount. It does nothing when the terminal is not ready or is already disposed. + +## Responsive behavior + +This repair does not change terminal composition. Desktop Dockview, tablet panels, and `MobileTerminalPane` continue to share `PassthroughTerminal` and its state. + +The nearest mobile implementation is `apps/web/components/task/mobile/mobile-terminal-pane.tsx`. The Pixel 5 test opens that existing surface and checks the same light-theme contract. The repair adds no drawer, touch target, safe-area rule, or scroll owner. + +## Failure and recovery + +The initial root-theme layout effect and constructor path prevent a light-theme +flash during terminal creation. The synchronization path handles later theme +changes. + +If a theme update races terminal disposal, the cancellation guard prevents writes to the disposed instance. A theme update never reconnects the socket, clears the buffer, or changes terminal dimensions. + +## Test contract + +Unit tests cover palette selection, distinct light bright variants, the minimum +contrast value, initial root-theme ordering, and deferred hook cleanup. Browser +tests cover the theme that reaches a live xterm instance. + +The desktop browser test changes the theme while one terminal remains open. It +checks that the buffer, focus, scroll position, and running command survive, +and that later shell output uses the same connection. + +The mobile browser test opens the existing phone terminal in light mode. It checks the same palette and contrast contract without changing the phone composition. + +## Related decisions + +No architecture decision record applies. This repair keeps the existing UI theme and xterm ownership boundaries.