diff --git a/packages/app/e2e/browser/terminal-protocol-query.spec.ts b/packages/app/e2e/browser/terminal-protocol-query.spec.ts index 4b2fc06d41..917ab9629f 100644 --- a/packages/app/e2e/browser/terminal-protocol-query.spec.ts +++ b/packages/app/e2e/browser/terminal-protocol-query.spec.ts @@ -4,7 +4,9 @@ import path from "node:path"; import type { Page } from "@playwright/test"; import { test, expect } from "../support/fixtures"; import { holdFileUploadResponse } from "../support/helpers/file-upload-gate"; +import { clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher"; import { installLocalDesktopHost } from "../support/helpers/local-desktop-host"; +import { clickSettingsBackToWorkspace, openSettingsSection } from "../support/helpers/settings"; import { TerminalE2EHarness } from "../support/helpers/terminal-dsl"; import { getTerminalBufferText, waitForTerminalContent } from "../support/helpers/terminal-perf"; @@ -23,13 +25,134 @@ if (process.stdin.isTTY) { process.stdin.resume(); process.stdin.on("data", (chunk) => { captured = Buffer.concat([captured, chunk]); - if (captured.includes(Buffer.from("rgb:"))) { - finish(); - } }); setTimeout(finish, 700); `; +const TERMINAL_PALETTE_PROBE_SCRIPT = ` +process.stdin.setRawMode(true); +process.stdin.resume(); +const mode = process.argv[2]; +let buf = ""; +const timer = setTimeout(() => { + process.stdout.write("PROBE_TIMEOUT:" + mode + ":" + buf.replace(/\\x1b/g, "ESC") + "\\n"); + process.exit(2); +}, 5000); + +if (mode === "osc") { + const code = process.argv[3]; + process.stdin.on("data", (chunk) => { + buf += chunk.toString("binary"); + const match = buf.match(new RegExp("\\\\x1b\\\\]" + code + ";rgb:[0-9a-f/]+\\\\x1b\\\\\\\\")); + if (!match) return; + clearTimeout(timer); + process.stdout.write("OSC_COLOR_OK:" + code + ":" + match[0].replace(/\\x1b/g, "ESC") + "\\n"); + process.exit(0); + }); + process.stdout.write("\\x1b]" + code + ";?\\x07"); +} else if (mode === "dsr996") { + process.stdin.on("data", (chunk) => { + buf += chunk.toString("binary"); + const match = buf.match(/\\x1b\\[\\?997;([12])n/); + if (!match) return; + clearTimeout(timer); + process.stdout.write("DSR996_OK:" + match[1] + "\\n"); + process.exit(0); + }); + process.stdout.write("\\x1b[?996n"); +} else if (mode === "watch2031") { + clearTimeout(timer); + process.stdin.on("data", (chunk) => { + buf += chunk.toString("binary"); + if (buf.includes("Q")) { + process.stdout.write("\\x1b[?2031lWATCH2031_DONE\\n"); + process.exit(0); + } + let match; + while ((match = buf.match(/\\x1b\\[\\?997;([12])n/))) { + process.stdout.write("WATCH2031_EVENT:" + match[1] + "\\n"); + buf = buf.slice(match.index + match[0].length); + } + }); + process.stdout.write("\\x1b[?2031hWATCH2031_READY\\n"); +} +`; + +const TERMINAL_PALETTE_SCENARIOS = { + light: { + label: "Light", + colorFgBg: "0;15", + schemeCode: "2", + colors: { + 10: "rgb:1a1a/1a1a/1e1e", + 11: "rgb:ffff/ffff/ffff", + 12: "rgb:1a1a/1a1a/1e1e", + }, + }, + dark: { + label: "Dark", + colorFgBg: "15;0", + schemeCode: "1", + colors: { + 10: "rgb:fafa/fafa/fafa", + 11: "rgb:1818/1b1b/1a1a", + 12: "rgb:fafa/fafa/fafa", + }, + }, +} as const; + +type TerminalPaletteScenario = + (typeof TERMINAL_PALETTE_SCENARIOS)[keyof typeof TERMINAL_PALETTE_SCENARIOS]; + +async function selectAppThemeInApp( + page: Page, + label: TerminalPaletteScenario["label"], +): Promise { + await page.getByRole("button", { name: "Settings", exact: true }).click(); + await expect(page.getByTestId("settings-sidebar")).toBeVisible(); + await openSettingsSection(page, "appearance"); + + const themeRadio = page.getByRole("radio", { name: label, exact: true }); + await themeRadio.click(); + await expect(themeRadio).toBeChecked(); + await clickSettingsBackToWorkspace(page); +} + +function collectBrowserOsc11Replies(page: Page): string[] { + const replies: string[] = []; + page.on("websocket", (ws) => { + ws.on("framesent", ({ payload }) => { + const text = typeof payload === "string" ? payload : payload.toString("latin1"); + if (text.includes("]11;rgb:")) { + replies.push(text); + } + }); + }); + return replies; +} + +async function waitForCreatedTerminal( + harness: TerminalE2EHarness, + knownTerminalIds: Set, +): Promise { + let createdTerminalId: string | undefined; + await expect + .poll( + async () => { + const result = await harness.client.listTerminals(harness.tempRepo.path, undefined, { + workspaceId: harness.workspaceId, + }); + createdTerminalId = result.terminals.find( + (terminal) => !knownTerminalIds.has(terminal.id), + )?.id; + return createdTerminalId; + }, + { timeout: 10_000 }, + ) + .toBeTruthy(); + return createdTerminalId!; +} + // A TUI stand-in: turns on bracketed paste, reads every quoted path in each // bracketed paste, and echoes typed lines, so the PTY output proves what reached // the terminal and where the file was read from. @@ -158,6 +281,10 @@ test.describe("Terminal protocol queries", () => { test.beforeAll(async () => { harness = await TerminalE2EHarness.create({ tempPrefix: "terminal-protocol-query-" }); await writeFile(path.join(harness.tempRepo.path, "osc11-capture.cjs"), OSC11_CAPTURE_SCRIPT); + await writeFile( + path.join(harness.tempRepo.path, "palette-probe.cjs"), + TERMINAL_PALETTE_PROBE_SCRIPT, + ); await writeFile(path.join(harness.tempRepo.path, "file-receiver.cjs"), FILE_RECEIVER_SCRIPT); }); @@ -166,6 +293,8 @@ test.describe("Terminal protocol queries", () => { }); test("does not send browser OSC 11 color-query replies back to the PTY", async ({ page }) => { + const browserOscReplies = collectBrowserOsc11Replies(page); + const terminalInstance = await harness.createTerminal({ name: "osc11-query" }); try { await harness.openTerminal(page, { terminalId: terminalInstance.id }); @@ -178,14 +307,110 @@ test.describe("Terminal protocol queries", () => { await page.waitForTimeout(500); const text = await getTerminalBufferText(page); + const captureLine = + text.split("\n").find((line) => line.includes("PASEO_OSC11_CAPTURE:")) ?? ""; + const capturedMatches = captureLine.match(/\]11;rgb:[0-9a-f/]+/g) ?? []; - expect(text).toContain("rgb:0b0b/0b0b/0b0b"); - expect(text).not.toContain("rgb:ffff/ffff/ffff"); + expect(capturedMatches).toHaveLength(1); + expect(browserOscReplies).toEqual([]); + const afterCapture = text.slice(text.indexOf("PASEO_OSC11_CAPTURE:") + captureLine.length); + expect(afterCapture).not.toContain("rgb:"); } finally { await harness.killTerminal(terminalInstance.id); } }); + test("reports Light and Dark palettes through OSC 10/11/12, COLORFGBG, DSR 996/997, and live DEC 2031 toggles", async ({ + page, + }) => { + const createAppTerminal = async (): Promise => { + const existing = await harness.client.listTerminals(harness.tempRepo.path, undefined, { + workspaceId: harness.workspaceId, + }); + const knownIds = new Set(existing.terminals.map((entry) => entry.id)); + await clickNewTerminal(page); + const terminalId = await waitForCreatedTerminal(harness, knownIds); + const surface = terminalSurface(page); + await expect(surface).toBeVisible({ timeout: 20_000 }); + await surface.click(); + const readyTag = `READY_${Date.now()}`; + await surface.pressSequentially(`echo ${readyTag}\n`, { delay: 0 }); + await expectTerminalOutput(terminalId, readyTag); + return terminalId; + }; + + const runPaletteChecks = async ( + terminalId: string, + scenario: TerminalPaletteScenario, + options: { checkColorFgBg: boolean }, + ): Promise => { + const surface = terminalSurface(page); + await surface.click(); + if (options.checkColorFgBg) { + await surface.pressSequentially('echo "CFGBG=$COLORFGBG"\n', { delay: 0 }); + await expectTerminalOutput(terminalId, `CFGBG=${scenario.colorFgBg}`); + } + for (const code of [10, 11, 12] as const) { + await surface.pressSequentially(`${process.execPath} palette-probe.cjs osc ${code}\n`, { + delay: 0, + }); + await expectTerminalOutput( + terminalId, + `OSC_COLOR_OK:${code}:ESC]${code};${scenario.colors[code]}ESC\\`, + ); + } + await surface.pressSequentially(`${process.execPath} palette-probe.cjs dsr996\n`, { + delay: 0, + }); + await expectTerminalOutput(terminalId, `DSR996_OK:${scenario.schemeCode}`); + }; + + // 1. Open workspace once, switch to Light in-app, and create a fresh Light terminal. + await gotoWorkspace(page, harness.workspaceId); + await selectAppThemeInApp(page, "Light"); + const lightTerminalId = await createAppTerminal(); + let darkTerminalId: string | null = null; + try { + await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.light, { + checkColorFgBg: true, + }); + + // 2. Start DEC 2031 watcher in that running Light terminal, then toggle Light -> Dark -> Light. + await terminalSurface(page).pressSequentially( + `${process.execPath} palette-probe.cjs watch2031\n`, + { delay: 0 }, + ); + await expectTerminalOutput(lightTerminalId, "WATCH2031_READY"); + + await selectAppThemeInApp(page, "Dark"); + await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:1"); + + await selectAppThemeInApp(page, "Light"); + await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:2"); + + // Stop watcher, toggle to Dark, and verify live OSC 10/11/12 + DSR 996 update on the same PTY. + await terminalSurface(page).click(); + await terminalSurface(page).pressSequentially("Q", { delay: 0 }); + await expectTerminalOutput(lightTerminalId, "WATCH2031_DONE"); + + await selectAppThemeInApp(page, "Dark"); + await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, { + checkColorFgBg: false, + }); + + // 3. Fresh Dark terminal reports Dark OSC 10/11/12, COLORFGBG=15;0, and DSR 996 -> dark (1). + darkTerminalId = await createAppTerminal(); + await runPaletteChecks(darkTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, { + checkColorFgBg: true, + }); + } finally { + await harness.killTerminal(lightTerminalId); + if (darkTerminalId) { + await harness.killTerminal(darkTerminalId); + } + } + }); + async function openFileReceiver(page: Page, name: string) { const terminal = await harness.createTerminal({ name, diff --git a/packages/app/e2e/support/helpers/seed-client.ts b/packages/app/e2e/support/helpers/seed-client.ts index 5473dd1cee..9ec064687f 100644 --- a/packages/app/e2e/support/helpers/seed-client.ts +++ b/packages/app/e2e/support/helpers/seed-client.ts @@ -1,5 +1,6 @@ import path from "node:path"; import { readFileSync } from "node:fs"; +import type { TerminalDefaultColors } from "@getpaseo/protocol/messages"; import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity"; import { connectDaemonClient } from "./daemon-client-loader"; import { withProjectOwnership } from "./project-ownership"; @@ -94,7 +95,13 @@ export interface SeedDaemonClient { cwd: string, name?: string, requestId?: string, - options?: { agentId?: string; command?: string; args?: string[]; workspaceId?: string }, + options?: { + agentId?: string; + command?: string; + args?: string[]; + workspaceId?: string; + defaultColors?: TerminalDefaultColors; + }, ): Promise<{ terminal: { id: string; name: string; cwd: string; activity?: TerminalActivity | null } | null; error: string | null; diff --git a/packages/app/e2e/support/helpers/terminal-dsl.ts b/packages/app/e2e/support/helpers/terminal-dsl.ts index bf16276464..f980f1f4b2 100644 --- a/packages/app/e2e/support/helpers/terminal-dsl.ts +++ b/packages/app/e2e/support/helpers/terminal-dsl.ts @@ -1,4 +1,5 @@ import type { Page } from "@playwright/test"; +import type { TerminalDefaultColors } from "@getpaseo/protocol/messages"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; import { createTempGitRepo } from "./workspace"; import { navigateToTerminal, setupDeterministicPrompt } from "./terminal-perf"; @@ -19,6 +20,7 @@ interface CreateTerminalInput { name: string; command?: string; args?: string[]; + defaultColors?: TerminalDefaultColors; } function sleep(ms: number): Promise { @@ -69,14 +71,11 @@ export class TerminalE2EHarness { } async createTerminal(input: CreateTerminalInput): Promise { - const options = - input.command || input.args - ? { - command: input.command, - args: input.args, - workspaceId: this.workspaceId, - } - : { workspaceId: this.workspaceId }; + const options = { + ...(input.command || input.args ? { command: input.command, args: input.args } : {}), + workspaceId: this.workspaceId, + ...(input.defaultColors ? { defaultColors: input.defaultColors } : {}), + }; const result = await this.client.createTerminal( this.tempRepo.path, input.name, diff --git a/packages/app/src/components/terminal-pane-focus-claim.test.ts b/packages/app/src/components/terminal-pane-focus-claim.test.ts index 528cdffc9b..d030e823df 100644 --- a/packages/app/src/components/terminal-pane-focus-claim.test.ts +++ b/packages/app/src/components/terminal-pane-focus-claim.test.ts @@ -1,8 +1,10 @@ import { describe, expect, it } from "vitest"; import { EMPTY_FOCUS_CLAIM_STATE, + EMPTY_PALETTE_SYNC_STATE, canRequestFocusClaim, reconcileFocusClaim, + resolveTerminalPaletteSync, resolveTerminalResizeClaim, settleFocusClaim, type FocusClaimState, @@ -250,3 +252,120 @@ describe("terminal pane focus claim", () => { expect(changed.shouldRequest).toBe(true); }); }); + +describe("terminal pane palette sync", () => { + const readyFocused = { + isWorkspaceFocused: true, + isPaneFocused: true, + isAppActivelyVisible: true, + isClientReady: true, + isConnected: true, + }; + + it("claims on focus, skips duplicate sends, and re-claims on theme change or explicit focus", () => { + const first = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, { + terminalKey: "ws:term-1", + paletteKey: "light", + supportsTerminalPaletteOwnership: true, + readiness: readyFocused, + }); + expect(first).toMatchObject({ shouldSend: true, intent: "claim" }); + + const duplicate = resolveTerminalPaletteSync(first.state, { + terminalKey: "ws:term-1", + paletteKey: "light", + supportsTerminalPaletteOwnership: true, + readiness: readyFocused, + }); + expect(duplicate.shouldSend).toBe(false); + + const themeFlipped = resolveTerminalPaletteSync(duplicate.state, { + terminalKey: "ws:term-1", + paletteKey: "dark", + supportsTerminalPaletteOwnership: true, + readiness: readyFocused, + }); + expect(themeFlipped).toMatchObject({ shouldSend: true, intent: "claim" }); + + const explicitReclaim = resolveTerminalPaletteSync(themeFlipped.state, { + terminalKey: "ws:term-1", + paletteKey: "dark", + forceClaim: true, + supportsTerminalPaletteOwnership: true, + readiness: readyFocused, + }); + expect(explicitReclaim).toMatchObject({ shouldSend: true, intent: "claim" }); + }); + + it("sends owner-only updates when theme changes while away and re-claims on return", () => { + const claimed = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, { + terminalKey: "ws:term-1", + paletteKey: "light", + supportsTerminalPaletteOwnership: true, + readiness: readyFocused, + }); + const inSettings = resolveTerminalPaletteSync(claimed.state, { + terminalKey: "ws:term-1", + paletteKey: "light", + supportsTerminalPaletteOwnership: true, + readiness: { ...readyFocused, isWorkspaceFocused: false }, + }); + expect(inSettings.shouldSend).toBe(false); + + const toggledInSettings = resolveTerminalPaletteSync(inSettings.state, { + terminalKey: "ws:term-1", + paletteKey: "dark", + supportsTerminalPaletteOwnership: true, + readiness: { ...readyFocused, isWorkspaceFocused: false }, + }); + expect(toggledInSettings).toMatchObject({ shouldSend: true, intent: "update" }); + + const returned = resolveTerminalPaletteSync(toggledInSettings.state, { + terminalKey: "ws:term-1", + paletteKey: "dark", + supportsTerminalPaletteOwnership: true, + readiness: readyFocused, + }); + expect(returned).toMatchObject({ shouldSend: true, intent: "claim" }); + }); + + it("never sends updates from an unfocused pane that has not claimed or against unsupported daemons", () => { + const neverFocused = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, { + terminalKey: "ws:term-1", + paletteKey: "dark", + supportsTerminalPaletteOwnership: true, + readiness: { ...readyFocused, isPaneFocused: false }, + }); + expect(neverFocused.shouldSend).toBe(false); + + const unsupported = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, { + terminalKey: "ws:term-1", + paletteKey: "light", + supportsTerminalPaletteOwnership: false, + readiness: readyFocused, + }); + expect(unsupported.shouldSend).toBe(false); + }); + + it("resets on disconnect so reconnect re-claims ownership on the fresh connection", () => { + const claimed = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, { + terminalKey: "ws:term-1", + paletteKey: "light", + supportsTerminalPaletteOwnership: true, + readiness: readyFocused, + }); + const disconnected = resolveTerminalPaletteSync(claimed.state, { + terminalKey: "ws:term-1", + paletteKey: "light", + supportsTerminalPaletteOwnership: true, + readiness: { ...readyFocused, isConnected: false }, + }); + const reconnected = resolveTerminalPaletteSync(disconnected.state, { + terminalKey: "ws:term-1", + paletteKey: "light", + supportsTerminalPaletteOwnership: true, + readiness: readyFocused, + }); + expect(reconnected).toMatchObject({ shouldSend: true, intent: "claim" }); + }); +}); diff --git a/packages/app/src/components/terminal-pane-focus-claim.ts b/packages/app/src/components/terminal-pane-focus-claim.ts index c22f96bdb4..2be5522938 100644 --- a/packages/app/src/components/terminal-pane-focus-claim.ts +++ b/packages/app/src/components/terminal-pane-focus-claim.ts @@ -127,3 +127,102 @@ export function settleFocusClaim( requestedKey: null, }; } + +export interface TerminalPaletteSyncState { + terminalKey: string | null; + claimed: boolean; + sentPaletteKey: string | null; +} + +export const EMPTY_PALETTE_SYNC_STATE: TerminalPaletteSyncState = { + terminalKey: null, + claimed: false, + sentPaletteKey: null, +}; + +export interface TerminalPaletteSyncReadiness { + isWorkspaceFocused: boolean; + isPaneFocused: boolean; + isAppActivelyVisible: boolean; + isClientReady: boolean; + isConnected: boolean; +} + +export function resolveTerminalPaletteSync( + state: TerminalPaletteSyncState, + input: { + terminalKey: string | null; + paletteKey: string; + forceClaim?: boolean; + supportsTerminalPaletteOwnership: boolean; + readiness: TerminalPaletteSyncReadiness; + }, +): { + state: TerminalPaletteSyncState; + shouldSend: boolean; + intent: "claim" | "update"; +} { + if ( + !input.supportsTerminalPaletteOwnership || + !input.terminalKey || + !input.readiness.isClientReady || + !input.readiness.isConnected + ) { + return { + state: EMPTY_PALETTE_SYNC_STATE, + shouldSend: false, + intent: "update", + }; + } + + const base = state.terminalKey === input.terminalKey ? state : EMPTY_PALETTE_SYNC_STATE; + const canClaim = + input.readiness.isWorkspaceFocused && + input.readiness.isPaneFocused && + input.readiness.isAppActivelyVisible; + + if (canClaim) { + if (input.forceClaim || !base.claimed || base.sentPaletteKey !== input.paletteKey) { + return { + state: { + terminalKey: input.terminalKey, + claimed: true, + sentPaletteKey: input.paletteKey, + }, + shouldSend: true, + intent: "claim", + }; + } + return { + state: base, + shouldSend: false, + intent: "claim", + }; + } + + if ( + input.readiness.isAppActivelyVisible && + base.sentPaletteKey !== null && + base.sentPaletteKey !== input.paletteKey + ) { + return { + state: { + terminalKey: input.terminalKey, + claimed: false, + sentPaletteKey: input.paletteKey, + }, + shouldSend: true, + intent: "update", + }; + } + + return { + state: { + terminalKey: input.terminalKey, + claimed: false, + sentPaletteKey: base.sentPaletteKey, + }, + shouldSend: false, + intent: "update", + }; +} diff --git a/packages/app/src/components/terminal-pane.tsx b/packages/app/src/components/terminal-pane.tsx index 9b244be72f..600b1e827c 100644 --- a/packages/app/src/components/terminal-pane.tsx +++ b/packages/app/src/components/terminal-pane.tsx @@ -62,11 +62,17 @@ import { prepareDroppedPathsForTerminal } from "@/terminal/drop/terminal-path"; import { toErrorMessage } from "@/utils/error-messages"; import { EMPTY_FOCUS_CLAIM_STATE, + EMPTY_PALETTE_SYNC_STATE, canRequestFocusClaim, reconcileFocusClaim, + resolveTerminalPaletteSync, resolveTerminalResizeClaim, settleFocusClaim, } from "./terminal-pane-focus-claim"; +import { + terminalDefaultColorsFromTheme, + terminalDefaultColorsKey, +} from "@/utils/terminal-default-colors"; import { TerminalStreamController, type TerminalStreamControllerStatus, @@ -276,6 +282,24 @@ export function TerminalPane({ const { theme } = useUnistyles(); const { settings } = useAppSettings(); const xtermTheme = useMemo(() => toXtermTheme(theme.colors.terminal), [theme]); + const { + foreground: terminalForeground, + background: terminalBackground, + cursor: terminalCursor, + } = theme.colors.terminal; + const terminalDefaultColors = useMemo( + () => + terminalDefaultColorsFromTheme({ + foreground: terminalForeground, + background: terminalBackground, + cursor: terminalCursor, + }), + [terminalBackground, terminalCursor, terminalForeground], + ); + const terminalPaletteKey = useMemo( + () => terminalDefaultColorsKey(terminalDefaultColors), + [terminalDefaultColors], + ); const terminalFontFamily = useMemo(() => { const trimmed = settings.monoFontFamily.trim(); return trimmed.length > 0 ? trimmed : undefined; @@ -310,6 +334,10 @@ export function TerminalPane({ const supportsTerminalSizeOwnership = useSessionStore( (state) => state.sessions[serverId]?.serverInfo?.features?.["terminal-size-ownership"] === true, ); + const supportsTerminalPaletteOwnership = useSessionStore( + (state) => + state.sessions[serverId]?.serverInfo?.features?.["terminal-palette-ownership"] === true, + ); const characterWidths: TerminalCharacterWidths = useSessionStore((state) => state.sessions[serverId]?.serverInfo?.features?.["terminal-grapheme-widths"] === true ? "graphemes" @@ -387,6 +415,7 @@ export function TerminalPane({ const keyboardRefitTimeoutsRef = useRef>>([]); const lastAutoFocusKeyRef = useRef(null); const paneFocusResizeClaimRef = useRef(EMPTY_FOCUS_CLAIM_STATE); + const panePaletteSyncRef = useRef(EMPTY_PALETTE_SYNC_STATE); useEffect(() => { terminalIdRef.current = terminalId; @@ -497,11 +526,51 @@ export function TerminalPane({ terminalStreamKey, ]); + const syncTerminalPalette = useStableEvent((options?: { forceClaim?: boolean }) => { + const step = resolveTerminalPaletteSync(panePaletteSyncRef.current, { + terminalKey: terminalId ? `${scopeKey}:${terminalId}` : null, + paletteKey: terminalPaletteKey, + forceClaim: options?.forceClaim, + supportsTerminalPaletteOwnership, + readiness: { + isWorkspaceFocused: isTerminalPresented, + isPaneFocused, + isAppActivelyVisible, + isClientReady: client !== null, + isConnected, + }, + }); + panePaletteSyncRef.current = step.state; + if (step.shouldSend && client && terminalId) { + client.sendTerminalInput(terminalId, { + type: "palette", + defaultColors: terminalDefaultColors, + intent: step.intent, + }); + } + }); + + useEffect(() => { + syncTerminalPalette(); + }, [ + client, + isAppActivelyVisible, + isConnected, + isPaneFocused, + isTerminalPresented, + scopeKey, + supportsTerminalPaletteOwnership, + syncTerminalPalette, + terminalId, + terminalPaletteKey, + ]); + const handleTerminalFocus = useCallback(() => { if (isWorkspaceFocused && isPaneFocused) { setFocusedTerminalId(serverId, terminalId); } lastSentTerminalSizeRef.current = null; + syncTerminalPalette({ forceClaim: true }); requestTerminalReflow(); emulatorRef.current?.claimSize(); }, [ @@ -510,6 +579,7 @@ export function TerminalPane({ requestTerminalReflow, serverId, setFocusedTerminalId, + syncTerminalPalette, terminalId, ]); diff --git a/packages/app/src/plugins/themes/index.ts b/packages/app/src/plugins/themes/index.ts index 735ddda41b..30bf74d624 100644 --- a/packages/app/src/plugins/themes/index.ts +++ b/packages/app/src/plugins/themes/index.ts @@ -2,6 +2,7 @@ import type { PluginMessage } from "@getpaseo/plugin/client"; import { isPluginMessage } from "@getpaseo/plugin/client/host"; import { useMemo } from "react"; import { z } from "zod"; +import { HexColorSchema } from "@getpaseo/protocol/messages"; import type { PluginThemeContribution } from "../types"; import { useHostFeatureMap } from "@/runtime/host-features"; import { @@ -26,29 +27,25 @@ import { import { useInstalledPlugins } from "../registry"; import type { InstalledPlugin } from "../types"; -const hexColorSchema = z - .string() - .regex(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/, "Must be a hex color"); - const contributionSchema: z.ZodType = z.strictObject({ id: z.string(), name: z.union([z.string().trim().min(1).max(60), z.custom(isPluginMessage)]), appearance: z.enum(["light", "dark"]), colors: z.strictObject({ - background: hexColorSchema, - foreground: hexColorSchema, - raised: hexColorSchema, - control: hexColorSchema, - border: hexColorSchema, - accent: hexColorSchema.optional(), - mutedForeground: hexColorSchema, - ring: hexColorSchema, - sidebar: hexColorSchema.optional(), - sidebarHover: hexColorSchema.optional(), - sidebarSelected: hexColorSchema.optional(), - surface3: hexColorSchema.optional(), - surface4: hexColorSchema.optional(), - foregroundExtraMuted: hexColorSchema.optional(), + background: HexColorSchema, + foreground: HexColorSchema, + raised: HexColorSchema, + control: HexColorSchema, + border: HexColorSchema, + accent: HexColorSchema.optional(), + mutedForeground: HexColorSchema, + ring: HexColorSchema, + sidebar: HexColorSchema.optional(), + sidebarHover: HexColorSchema.optional(), + sidebarSelected: HexColorSchema.optional(), + surface3: HexColorSchema.optional(), + surface4: HexColorSchema.optional(), + foregroundExtraMuted: HexColorSchema.optional(), }), }); diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index d3b83a65aa..c58637bcdd 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -36,6 +36,7 @@ import { resolveTerminalProfiles } from "@getpaseo/protocol/terminal-profiles"; import type { TerminalProfile } from "@getpaseo/protocol/messages"; import { resolveLaunchTarget, type LaunchTarget } from "@/new-workspace-launch/target"; import { useTerminalComposerState } from "@/new-workspace-launch/composer-state"; +import { getActiveTerminalDefaultColors } from "@/utils/terminal-default-colors"; import { runCreateTerminalWorkspace } from "./new-workspace-terminal"; import { useHostRuntimeClient, @@ -1492,7 +1493,12 @@ export function NewWorkspaceScreen({ input.workspaceDirectory, input.name, undefined, - { command: input.command, args: input.args, workspaceId: input.workspaceId }, + { + command: input.command, + args: input.args, + workspaceId: input.workspaceId, + defaultColors: getActiveTerminalDefaultColors(), + }, ); const terminal = createdTerminal.terminal; if (!terminal) { diff --git a/packages/app/src/screens/workspace/terminals/use-workspace-terminals.ts b/packages/app/src/screens/workspace/terminals/use-workspace-terminals.ts index e35e9d44a4..6975413d23 100644 --- a/packages/app/src/screens/workspace/terminals/use-workspace-terminals.ts +++ b/packages/app/src/screens/workspace/terminals/use-workspace-terminals.ts @@ -7,6 +7,7 @@ import type { WorkspaceDescriptor } from "@/stores/session-store"; import { useTranslation } from "react-i18next"; import { useReplicaQuery } from "@/data/query"; import { workspaceTerminalsPushRoute } from "@/data/push-router"; +import { getActiveTerminalDefaultColors } from "@/utils/terminal-default-colors"; import { buildTerminalsQueryKey, canCreateWorkspaceTerminal, @@ -134,14 +135,17 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) { throw new Error(t("workspace.terminal.hostDisconnected")); } const profile = _input.profile ? resolveTerminalProfileLaunch(_input.profile, "") : undefined; + const defaultColors = getActiveTerminalDefaultColors(); const payload = profile ? await client.createTerminal(workspaceDirectory, profile.name, undefined, { command: profile.command, args: profile.args, workspaceId: normalizedWorkspaceId || undefined, + defaultColors, }) : await client.createTerminal(workspaceDirectory, undefined, undefined, { workspaceId: normalizedWorkspaceId || undefined, + defaultColors, }); // The daemon reports a failed spawn (e.g. a profile command that isn't // installed) via payload.error with a null terminal. Surface it instead diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts index a875ae5a3a..6bd4a846aa 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts @@ -741,8 +741,10 @@ describe("terminal emulator runtime in a real browser", () => { { name: "DSR-5", bytes: "\x1b[5n" }, { name: "DSR-6", bytes: "\x1b[6n" }, { name: "DSR-?6", bytes: "\x1b[?6n" }, + { name: "DSR-?996-color-scheme", bytes: "\x1b[?996n" }, { name: "DECRQM", bytes: "\x1b[1$p" }, { name: "DECRQM-?", bytes: "\x1b[?1$p" }, + { name: "DECRQM-?2031", bytes: "\x1b[?2031$p" }, { name: "DECRQSS", bytes: "\x1bP$qm\x1b\\" }, { name: "OSC-10-foreground-color", bytes: "\x1b]10;?\x07" }, { name: "OSC-11-background-color", bytes: "\x1b]11;?\x07" }, diff --git a/packages/app/src/utils/terminal-default-colors.ts b/packages/app/src/utils/terminal-default-colors.ts new file mode 100644 index 0000000000..2759262d70 --- /dev/null +++ b/packages/app/src/utils/terminal-default-colors.ts @@ -0,0 +1,31 @@ +import type { TerminalDefaultColors } from "@getpaseo/protocol/messages"; +import { UnistylesRuntime } from "react-native-unistyles"; +import type { Theme } from "@/styles/theme"; + +type TerminalThemeColors = Pick< + Theme["colors"]["terminal"], + "foreground" | "background" | "cursor" +>; + +export function terminalDefaultColorsFromTheme( + terminal: TerminalThemeColors, +): TerminalDefaultColors { + return { + foreground: terminal.foreground, + background: terminal.background, + cursor: terminal.cursor, + }; +} + +/** + * Read the active terminal palette at the creation action boundary so a newly + * created PTY gets matching OSC 10/11/12, DSR 996/997, and COLORFGBG values + * from its first byte on desktop, web, and mobile. + */ +export function getActiveTerminalDefaultColors(): TerminalDefaultColors { + return terminalDefaultColorsFromTheme(UnistylesRuntime.getTheme().colors.terminal); +} + +export function terminalDefaultColorsKey(colors: TerminalDefaultColors): string { + return `${colors.foreground}|${colors.background}|${colors.cursor ?? ""}`; +} diff --git a/packages/client/src/daemon-client-core.ts b/packages/client/src/daemon-client-core.ts index 852a369fd2..b7261de83f 100644 --- a/packages/client/src/daemon-client-core.ts +++ b/packages/client/src/daemon-client-core.ts @@ -45,6 +45,7 @@ import type { DaemonUpdateResponseSchema, AgentActiveTurnBehavior, ServerInfoStatusPayload, + TerminalDefaultColors, } from "@getpaseo/protocol/messages"; import type { DaemonProtocolCodec, OutboundValidationResult } from "./daemon-protocol-codec.js"; import { leanProtocolCodec } from "./daemon-protocol-codec-lean.js"; @@ -7260,6 +7261,7 @@ export class DaemonClientCore { args?: string[]; workspaceId?: string; size?: { rows: number; cols: number }; + defaultColors?: TerminalDefaultColors; }, ): Promise { const resolvedRequestId = this.createRequestId(requestId); @@ -7272,6 +7274,7 @@ export class DaemonClientCore { args: options?.args, ...(options?.workspaceId !== undefined ? { workspaceId: options.workspaceId } : {}), ...(options?.size !== undefined ? { size: options.size } : {}), + ...(options?.defaultColors !== undefined ? { defaultColors: options.defaultColors } : {}), requestId: resolvedRequestId, }); return this.sendCorrelatedRequest({ diff --git a/packages/protocol/src/messages.create-terminal-size.test.ts b/packages/protocol/src/messages.create-terminal-size.test.ts index 10a61dae49..6d92b67fb4 100644 --- a/packages/protocol/src/messages.create-terminal-size.test.ts +++ b/packages/protocol/src/messages.create-terminal-size.test.ts @@ -20,6 +20,25 @@ describe("CreateTerminalRequest size", () => { expect(parsed.size).toEqual({ rows: 55, cols: 136 }); }); + it("parses an optional terminal creation palette", () => { + const defaultColors = { + foreground: "#18181b", + background: "#ffffff", + cursor: "#18181b", + }; + const parsed = CreateTerminalRequestSchema.parse({ ...base, defaultColors }); + expect(parsed.defaultColors).toEqual(defaultColors); + }); + + it("rejects non-hex terminal colors", () => { + expect(() => + CreateTerminalRequestSchema.parse({ + ...base, + defaultColors: { foreground: "rgb(24 24 27)", background: "#ffffff" }, + }), + ).toThrow(); + }); + it("rejects a non-positive or non-integer size", () => { expect(() => CreateTerminalRequestSchema.parse({ ...base, size: { rows: 0, cols: 80 } }), diff --git a/packages/protocol/src/messages.terminal-resize.test.ts b/packages/protocol/src/messages.terminal-resize.test.ts index a7d4f0d991..3f4e967b84 100644 --- a/packages/protocol/src/messages.terminal-resize.test.ts +++ b/packages/protocol/src/messages.terminal-resize.test.ts @@ -32,4 +32,38 @@ describe("terminal resize messages", () => { }, }); }); + + it.each(["claim", "update"] as const)("accepts palette messages with %s intent", (intent) => { + const defaultColors = { + foreground: "#1a1a1e", + background: "#ffffff", + cursor: "#1a1a1e", + }; + const result = TerminalInputSchema.safeParse({ + type: "terminal_input", + terminalId: "terminal-1", + message: { type: "palette", defaultColors, intent }, + }); + + expect(result).toMatchObject({ + success: true, + data: { + message: { type: "palette", defaultColors, intent }, + }, + }); + }); + + it("rejects palette messages with invalid hex colors", () => { + const result = TerminalInputSchema.safeParse({ + type: "terminal_input", + terminalId: "terminal-1", + message: { + type: "palette", + defaultColors: { foreground: "white", background: "#ffffff" }, + intent: "claim", + }, + }); + + expect(result.success).toBe(false); + }); }); diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 73c811f8f0..205da412e2 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -188,6 +188,10 @@ export const DAEMON_PERMISSIONS = [ export const DaemonPermissionSchema = z.enum(DAEMON_PERMISSIONS); export type DaemonPermission = z.infer; +export const HexColorSchema = z + .string() + .regex(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/, "Must be a hex color"); + const MutableDaemonProviderModelSchema = z .object({ id: z.string().min(1), @@ -3381,6 +3385,14 @@ export const UnsubscribeTerminalsRequestSchema = z.object({ workspaceId: z.string().optional(), }); +export const TerminalDefaultColorsSchema = z.object({ + foreground: HexColorSchema, + background: HexColorSchema, + cursor: HexColorSchema.optional(), +}); + +export type TerminalDefaultColors = z.infer; + export const CreateTerminalRequestSchema = z.object({ type: z.literal("create_terminal_request"), cwd: z.string(), @@ -3389,6 +3401,10 @@ export const CreateTerminalRequestSchema = z.object({ agentId: z.string().optional(), command: z.string().optional(), args: z.array(z.string()).optional(), + // Initial active palette sent by the client when this terminal is created so + // OSC 10/11/12 queries, DSR 996/997, and COLORFGBG match the active theme from + // the first byte. Omitted by CLI/MCP/older clients, which retain dark defaults. + defaultColors: TerminalDefaultColorsSchema.optional(), // Initial PTY size. Added in v0.1.107; the app no longer sends it (the estimate cache that fed // it was removed — the pane-focus resize claim sizes the PTY instead). Kept and honored // permanently: released v0.1.107 clients still send it, and programmatic callers may pass an @@ -3474,6 +3490,11 @@ const TerminalClientMessageSchema = z.discriminatedUnion("type", [ button: z.number(), action: z.enum(["down", "up", "move"]), }), + z.object({ + type: z.literal("palette"), + defaultColors: TerminalDefaultColorsSchema, + intent: z.enum(["claim", "update"]).optional(), + }), ]); export const TerminalInputSchema = z.object({ @@ -4162,6 +4183,8 @@ export const ServerInfoStatusPayloadSchema = z "terminal-input-mode-replay": z.boolean().optional(), // COMPAT(terminalSizeOwnership): added in v0.2.6, remove gate after 2027-02-02. "terminal-size-ownership": z.boolean().optional(), + // COMPAT(terminalPaletteOwnership): added in v0.18.0, remove gate after 2027-06-01. + "terminal-palette-ownership": z.boolean().optional(), // COMPAT(terminalGraphemeWidths): added in v0.15.0, remove gate after 2027-05-01. "terminal-grapheme-widths": z.boolean().optional(), // COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X. diff --git a/packages/server/src/server/websocket-server.relay-reconnect.test.ts b/packages/server/src/server/websocket-server.relay-reconnect.test.ts index 9db4d138f6..ac36723960 100644 --- a/packages/server/src/server/websocket-server.relay-reconnect.test.ts +++ b/packages/server/src/server/websocket-server.relay-reconnect.test.ts @@ -1160,6 +1160,7 @@ describe("relay external socket reconnect behavior", () => { expect(serverInfo.features?.workspaceMarkUnread).toBe(true); expect(serverInfo.features?.["terminal-input-mode-replay"]).toBe(true); expect(serverInfo.features?.["terminal-size-ownership"]).toBe(true); + expect(serverInfo.features?.["terminal-palette-ownership"]).toBe(true); expect(serverInfo.features?.["terminal-grapheme-widths"]).toBe(true); expect(serverInfo.features?.agentTurnIdentity).toBeUndefined(); expect(serverInfo.permissions).toEqual(DAEMON_PERMISSIONS); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 6671b6ceea..e399ec183f 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2228,6 +2228,8 @@ export class VoiceAssistantWebSocketServer { "terminal-input-mode-replay": true, // COMPAT(terminalSizeOwnership): added in v0.2.6, remove gate after 2027-02-02. "terminal-size-ownership": true, + // COMPAT(terminalPaletteOwnership): added in v0.18.0, remove gate after 2027-06-01. + "terminal-palette-ownership": true, // COMPAT(terminalGraphemeWidths): added in v0.15.0, remove gate after 2027-05-01. "terminal-grapheme-widths": true, workspaceTerminals: true, diff --git a/packages/server/src/terminal/terminal-manager.ts b/packages/server/src/terminal/terminal-manager.ts index 6d16622460..661e5a3e9f 100644 --- a/packages/server/src/terminal/terminal-manager.ts +++ b/packages/server/src/terminal/terminal-manager.ts @@ -14,6 +14,7 @@ import { type CaptureTerminalLinesResult } from "./terminal-capture.js"; import { randomBytes, randomUUID } from "node:crypto"; import { resolve, sep } from "node:path"; import { assertAbsolutePath, isSameOrDescendantPath } from "../server/path-utils.js"; +import type { TerminalDefaultColors } from "@getpaseo/protocol/messages"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; import { deriveTerminalActivityStatusBucket } from "@getpaseo/protocol/terminal-activity"; @@ -80,6 +81,7 @@ export interface TerminalManager { name?: string; title?: string; env?: Record; + defaultColors?: TerminalDefaultColors; command?: string; args?: string[]; rows?: number; @@ -350,6 +352,7 @@ export function createTerminalManager( name?: string; title?: string; env?: Record; + defaultColors?: TerminalDefaultColors; command?: string; args?: string[]; rows?: number; @@ -385,6 +388,7 @@ export function createTerminalManager( id: terminalId, cwd: options.cwd, workspaceId: options.workspaceId, + defaultColors: options.defaultColors, name: options.name ?? defaultName, ...(options.title ? { title: options.title } : {}), ...(options.command ? { command: options.command } : {}), diff --git a/packages/server/src/terminal/terminal-palette-ownership.test.ts b/packages/server/src/terminal/terminal-palette-ownership.test.ts new file mode 100644 index 0000000000..51636532f4 --- /dev/null +++ b/packages/server/src/terminal/terminal-palette-ownership.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, test } from "vitest"; +import type { TerminalDefaultColors } from "@getpaseo/protocol/messages"; +import type { ClientMessage, TerminalSession } from "./terminal.js"; +import { + applyTerminalPalette, + claimInitialTerminalPaletteOwner, +} from "./terminal-palette-ownership.js"; + +const LIGHT: TerminalDefaultColors = { + foreground: "#1a1a1e", + background: "#ffffff", + cursor: "#1a1a1e", +}; + +const DARK: TerminalDefaultColors = { + foreground: "#fafafa", + background: "#181b1a", + cursor: "#fafafa", +}; + +const ALT_DARK: TerminalDefaultColors = { + foreground: "#fafafa", + background: "#161820", + cursor: "#fafafa", +}; + +function createTerminal(initialColors?: TerminalDefaultColors): { + terminal: TerminalSession; + appliedPalettes: TerminalDefaultColors[]; +} { + const appliedPalettes: TerminalDefaultColors[] = []; + let defaultColors: TerminalDefaultColors | undefined = initialColors; + const terminal = { + getDefaultColors: () => defaultColors, + send: (message: ClientMessage) => { + if (message.type !== "palette") { + return; + } + defaultColors = message.defaultColors; + appliedPalettes.push(message.defaultColors); + }, + } as TerminalSession; + return { terminal, appliedPalettes }; +} + +describe("terminal palette ownership", () => { + test("only the latest claimant can update a terminal palette", () => { + const { terminal, appliedPalettes } = createTerminal(); + const ownerA = {}; + const ownerB = {}; + + expect(applyTerminalPalette(terminal, ownerA, { defaultColors: LIGHT, intent: "claim" })).toBe( + true, + ); + expect(applyTerminalPalette(terminal, ownerA, { defaultColors: DARK, intent: "update" })).toBe( + true, + ); + expect(applyTerminalPalette(terminal, ownerB, { defaultColors: LIGHT, intent: "update" })).toBe( + false, + ); + expect(applyTerminalPalette(terminal, ownerB, { defaultColors: LIGHT, intent: "claim" })).toBe( + true, + ); + expect( + applyTerminalPalette(terminal, ownerA, { defaultColors: ALT_DARK, intent: "update" }), + ).toBe(false); + expect(applyTerminalPalette(terminal, ownerB, { defaultColors: DARK, intent: "update" })).toBe( + true, + ); + + expect(appliedPalettes).toEqual([LIGHT, DARK, LIGHT, DARK]); + }); + + test("transfers ownership even when a new claimant reports the active palette", () => { + const { terminal, appliedPalettes } = createTerminal(LIGHT); + const ownerA = {}; + const ownerB = {}; + + claimInitialTerminalPaletteOwner(terminal, ownerA); + expect(applyTerminalPalette(terminal, ownerB, { defaultColors: LIGHT, intent: "claim" })).toBe( + true, + ); + expect(applyTerminalPalette(terminal, ownerA, { defaultColors: DARK, intent: "update" })).toBe( + false, + ); + expect(applyTerminalPalette(terminal, ownerB, { defaultColors: DARK, intent: "update" })).toBe( + true, + ); + + expect(appliedPalettes).toEqual([DARK]); + }); + + test("grants initial owner update rights without waiting for a separate claim", () => { + const { terminal, appliedPalettes } = createTerminal(LIGHT); + const creator = {}; + + claimInitialTerminalPaletteOwner(terminal, creator); + expect(applyTerminalPalette(terminal, creator, { defaultColors: DARK, intent: "update" })).toBe( + true, + ); + expect(appliedPalettes).toEqual([DARK]); + }); +}); diff --git a/packages/server/src/terminal/terminal-palette-ownership.ts b/packages/server/src/terminal/terminal-palette-ownership.ts new file mode 100644 index 0000000000..9ca8c90627 --- /dev/null +++ b/packages/server/src/terminal/terminal-palette-ownership.ts @@ -0,0 +1,37 @@ +import type { TerminalDefaultColors } from "@getpaseo/protocol/messages"; +import type { TerminalSession } from "./terminal.js"; +import { resolveTerminalPalette, terminalPalettesEqual } from "./terminal-palette.js"; + +export interface TerminalPaletteRequest { + defaultColors: TerminalDefaultColors; + intent?: "claim" | "update"; +} + +const terminalPaletteOwners = new WeakMap>(); + +export function claimInitialTerminalPaletteOwner(terminal: TerminalSession, owner: object): void { + terminalPaletteOwners.set(terminal, new WeakRef(owner)); +} + +export function applyTerminalPalette( + terminal: TerminalSession, + owner: object, + request: TerminalPaletteRequest, +): boolean { + const intent = request.intent ?? "claim"; + if (intent === "update" && terminalPaletteOwners.get(terminal)?.deref() !== owner) { + return false; + } + + if (intent === "claim") { + terminalPaletteOwners.set(terminal, new WeakRef(owner)); + } + + const nextPalette = resolveTerminalPalette(request.defaultColors); + const currentColors = terminal.getDefaultColors?.(); + const currentPalette = resolveTerminalPalette(currentColors); + if (!terminalPalettesEqual(currentPalette, nextPalette)) { + terminal.send({ type: "palette", defaultColors: request.defaultColors }); + } + return true; +} diff --git a/packages/server/src/terminal/terminal-palette.test.ts b/packages/server/src/terminal/terminal-palette.test.ts new file mode 100644 index 0000000000..15199f3858 --- /dev/null +++ b/packages/server/src/terminal/terminal-palette.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from "vitest"; +import { + formatColorSchemeReport, + resolveTerminalPalette, + terminalPalettesEqual, +} from "./terminal-palette.js"; + +describe("terminal palette", () => { + it("falls back to dark defaults when defaultColors is omitted", () => { + const palette = resolveTerminalPalette(); + expect(palette.oscResponses.get(10)).toBe("rgb:e6e6/e6e6/e6e6"); + expect(palette.oscResponses.get(11)).toBe("rgb:0b0b/0b0b/0b0b"); + expect(palette.oscResponses.get(12)).toBe("rgb:e6e6/e6e6/e6e6"); + expect(palette.colorScheme).toBe("dark"); + expect(palette.colorFgBg).toBe("15;0"); + }); + + it("resolves light theme colors, 16-bit X11 rgb replies, and light COLORFGBG", () => { + const palette = resolveTerminalPalette({ + foreground: "#1a1a1e", + background: "#ffffff", + cursor: "#1a1a1e", + }); + expect(palette.oscResponses.get(10)).toBe("rgb:1a1a/1a1a/1e1e"); + expect(palette.oscResponses.get(11)).toBe("rgb:ffff/ffff/ffff"); + expect(palette.oscResponses.get(12)).toBe("rgb:1a1a/1a1a/1e1e"); + expect(palette.colorScheme).toBe("light"); + expect(palette.colorFgBg).toBe("0;15"); + }); + + it("defaults cursor to foreground when cursor is omitted", () => { + const palette = resolveTerminalPalette({ + foreground: "#112233", + background: "#fafafa", + }); + expect(palette.oscResponses.get(12)).toBe("rgb:1111/2222/3333"); + expect(palette.colorScheme).toBe("light"); + expect(palette.colorFgBg).toBe("0;15"); + }); + + it("composites translucent hex colors over the displayed background", () => { + const palette = resolveTerminalPalette({ + foreground: "#33669980", + background: "#112233cc", + cursor: "#abcdef40", + }); + expect(palette.oscResponses.get(10)).toBe("rgb:2222/4242/6262"); + expect(palette.oscResponses.get(11)).toBe("rgb:1010/1d1d/2b2b"); + expect(palette.oscResponses.get(12)).toBe("rgb:3737/4949/5c5c"); + expect(palette.colorScheme).toBe("dark"); + expect(palette.colorFgBg).toBe("15;0"); + }); + + it("expands 3-digit and 4-digit hex shorthands", () => { + const palette = resolveTerminalPalette({ + foreground: "#123", + background: "#fff", + cursor: "#f008", + }); + expect(palette.oscResponses.get(10)).toBe("rgb:1111/2222/3333"); + expect(palette.oscResponses.get(11)).toBe("rgb:ffff/ffff/ffff"); + expect(palette.oscResponses.get(12)).toBe("rgb:ffff/7777/7777"); + expect(palette.colorScheme).toBe("light"); + }); + + it("formats DSR 997 color-scheme reports for dark and light modes", () => { + expect(formatColorSchemeReport("dark")).toBe("\x1b[?997;1n"); + expect(formatColorSchemeReport("light")).toBe("\x1b[?997;2n"); + }); + + it("compares resolved palettes by displayed foreground, background, and cursor", () => { + const lightA = resolveTerminalPalette({ foreground: "#1a1a1e", background: "#fff" }); + const lightB = resolveTerminalPalette({ + foreground: "#1A1A1E", + background: "#ffffff", + cursor: "#1a1a1e", + }); + const dark = resolveTerminalPalette({ foreground: "#fafafa", background: "#181b1a" }); + + expect(terminalPalettesEqual(lightA, lightB)).toBe(true); + expect(terminalPalettesEqual(lightA, dark)).toBe(false); + }); +}); diff --git a/packages/server/src/terminal/terminal-palette.ts b/packages/server/src/terminal/terminal-palette.ts new file mode 100644 index 0000000000..5a460a9143 --- /dev/null +++ b/packages/server/src/terminal/terminal-palette.ts @@ -0,0 +1,146 @@ +import type { TerminalDefaultColors } from "@getpaseo/protocol/messages"; + +export interface RgbColor { + readonly red: number; + readonly green: number; + readonly blue: number; +} + +export type TerminalColorScheme = "dark" | "light"; +export type TerminalOscColorCode = 10 | 11 | 12; + +export interface ResolvedTerminalPalette { + readonly foreground: RgbColor; + readonly background: RgbColor; + readonly cursor: RgbColor; + readonly oscResponses: ReadonlyMap; + readonly colorScheme: TerminalColorScheme; + readonly colorFgBg: "15;0" | "0;15"; +} + +const DEFAULT_TERMINAL_BACKGROUND: RgbColor = { red: 0x0b, green: 0x0b, blue: 0x0b }; +const DEFAULT_TERMINAL_FOREGROUND: RgbColor = { red: 0xe6, green: 0xe6, blue: 0xe6 }; + +function parseHexColor(value: string | undefined): { color: RgbColor; alpha: number } | undefined { + const hex = value?.trim().replace(/^#/, "").toLowerCase(); + if (!hex || ![3, 4, 6, 8].includes(hex.length) || !/^[0-9a-f]+$/.test(hex)) { + return undefined; + } + + const rgb = + hex.length <= 4 + ? hex.slice(0, 3).replaceAll(/./g, (channel) => channel + channel) + : hex.slice(0, 6); + let alpha = 0xff; + if (hex.length === 4) { + alpha = Number.parseInt(hex[3]!.repeat(2), 16); + } else if (hex.length === 8) { + alpha = Number.parseInt(hex.slice(6), 16); + } + + return { + color: { + red: Number.parseInt(rgb.slice(0, 2), 16), + green: Number.parseInt(rgb.slice(2, 4), 16), + blue: Number.parseInt(rgb.slice(4, 6), 16), + }, + alpha, + }; +} + +function compositeColor( + foreground: { color: RgbColor; alpha: number }, + background: RgbColor, +): RgbColor { + if (foreground.alpha === 0xff) { + return foreground.color; + } + + const opacity = foreground.alpha / 0xff; + return { + red: Math.round(background.red + (foreground.color.red - background.red) * opacity), + green: Math.round(background.green + (foreground.color.green - background.green) * opacity), + blue: Math.round(background.blue + (foreground.color.blue - background.blue) * opacity), + }; +} + +function resolveColor( + value: string | undefined, + fallback: RgbColor, + background: RgbColor, +): RgbColor { + const parsed = parseHexColor(value); + return parsed ? compositeColor(parsed, background) : fallback; +} + +function toOscColor(color: RgbColor): string { + const channel = (value: number): string => value.toString(16).padStart(2, "0").repeat(2); + return `rgb:${channel(color.red)}/${channel(color.green)}/${channel(color.blue)}`; +} + +function deriveColorScheme(background: RgbColor): TerminalColorScheme { + // Rec. 709 perceived luminance normalized to [0, 1]. + const luma = + (0.2126 * background.red + 0.7152 * background.green + 0.0722 * background.blue) / 255; + return luma >= 0.5 ? "light" : "dark"; +} + +function rgbEquals(left: RgbColor, right: RgbColor): boolean { + return left.red === right.red && left.green === right.green && left.blue === right.blue; +} + +export function resolveTerminalPalette( + defaultColors?: TerminalDefaultColors, +): ResolvedTerminalPalette { + // OSC RGB responses cannot carry alpha. xterm blends the foreground and cursor over the + // terminal background; use the existing dark fallback as the backdrop for a translucent + // background because the protocol does not carry another compositing surface. + const background = resolveColor( + defaultColors?.background, + DEFAULT_TERMINAL_BACKGROUND, + DEFAULT_TERMINAL_BACKGROUND, + ); + const foreground = resolveColor( + defaultColors?.foreground, + DEFAULT_TERMINAL_FOREGROUND, + background, + ); + const cursor = resolveColor( + defaultColors?.cursor ?? defaultColors?.foreground, + foreground, + background, + ); + const colorScheme = deriveColorScheme(background); + + return { + foreground, + background, + cursor, + oscResponses: new Map([ + [10, toOscColor(foreground)], + [11, toOscColor(background)], + [12, toOscColor(cursor)], + ]), + colorScheme, + colorFgBg: colorScheme === "light" ? "0;15" : "15;0", + }; +} + +export function terminalPalettesEqual( + left: ResolvedTerminalPalette, + right: ResolvedTerminalPalette, +): boolean { + return ( + rgbEquals(left.foreground, right.foreground) && + rgbEquals(left.background, right.background) && + rgbEquals(left.cursor, right.cursor) + ); +} + +export function formatColorSchemeReport(colorScheme: TerminalColorScheme): string { + return colorScheme === "light" ? "\x1b[?997;2n" : "\x1b[?997;1n"; +} + +export function formatColorSchemeModeReport(enabled: boolean): string { + return `\x1b[?2031;${enabled ? 1 : 2}$y`; +} diff --git a/packages/server/src/terminal/terminal-session-controller.resize.test.ts b/packages/server/src/terminal/terminal-session-controller.resize.test.ts index c84b03cab7..e82c78e306 100644 --- a/packages/server/src/terminal/terminal-session-controller.resize.test.ts +++ b/packages/server/src/terminal/terminal-session-controller.resize.test.ts @@ -9,6 +9,7 @@ import { SessionDelivery } from "../server/session/owned-subscriptions/index.js" import type { SessionInboundMessage, SessionOutboundMessage, + TerminalDefaultColors, TerminalState, } from "@getpaseo/protocol/messages"; import type pino from "pino"; @@ -21,9 +22,12 @@ function createFixture(): { terminal: TerminalSession; terminalManager: TerminalManager; appliedSizes: string[]; + appliedPalettes: TerminalDefaultColors[]; } { const appliedSizes: string[] = []; + const appliedPalettes: TerminalDefaultColors[] = []; let size = { rows: 24, cols: 80 }; + let defaultColors: TerminalDefaultColors | undefined; const state = (): TerminalState => ({ rows: size.rows, cols: size.cols, @@ -37,12 +41,20 @@ function createFixture(): { cwd: "/tmp", workspaceId: "workspace-1", getSize: () => size, - send: (message: { type: string; rows?: number; cols?: number }) => { - if (message.type !== "resize" || message.rows === undefined || message.cols === undefined) { - return; + getDefaultColors: () => defaultColors, + send: (message: { + type: string; + rows?: number; + cols?: number; + defaultColors?: TerminalDefaultColors; + }) => { + if (message.type === "resize" && message.rows !== undefined && message.cols !== undefined) { + size = { rows: message.rows, cols: message.cols }; + appliedSizes.push(`${message.cols}x${message.rows}`); + } else if (message.type === "palette" && message.defaultColors) { + defaultColors = message.defaultColors; + appliedPalettes.push(message.defaultColors); } - size = { rows: message.rows, cols: message.cols }; - appliedSizes.push(`${message.cols}x${message.rows}`); }, subscribe: () => () => {}, onExit: () => () => {}, @@ -51,7 +63,7 @@ function createFixture(): { getTerminal: () => terminal, getTerminalState: async () => ({ state: state(), revision: 0 }), } as unknown as TerminalManager; - return { terminal, terminalManager, appliedSizes }; + return { terminal, terminalManager, appliedSizes, appliedPalettes }; } function createController( @@ -138,4 +150,52 @@ describe("terminal session controller size ownership", () => { await ownership.close(); expect(appliedSizes).toEqual(["100x30", "101x31", "103x33", "105x35"]); }); + + test("routes palette claims and owner-only updates through one connection-owned arbiter", async () => { + const { terminalManager, appliedPalettes } = createFixture(); + const controllerA = createController(terminalManager); + const controllerB = createController(terminalManager); + const sourceA = {}; + const sourceB = {}; + const ownership = new SessionDelivery(() => {}); + const light = { foreground: "#1a1a1e", background: "#ffffff", cursor: "#1a1a1e" }; + const dark = { foreground: "#fafafa", background: "#181b1a", cursor: "#fafafa" }; + const dispatch = ( + controller: TerminalSessionController, + source: object, + message: SessionInboundMessage, + ) => + ownership.request(source, message, async () => { + await controller.dispatch(message, ownership); + }); + + await dispatch(controllerA, sourceA, { + type: "terminal_input", + terminalId: "terminal-1", + message: { type: "palette", defaultColors: light, intent: "claim" }, + }); + await dispatch(controllerB, sourceB, { + type: "terminal_input", + terminalId: "terminal-1", + message: { type: "palette", defaultColors: dark, intent: "update" }, + }); + await dispatch(controllerA, sourceA, { + type: "terminal_input", + terminalId: "terminal-1", + message: { type: "palette", defaultColors: dark, intent: "update" }, + }); + await dispatch(controllerB, sourceB, { + type: "terminal_input", + terminalId: "terminal-1", + message: { type: "palette", defaultColors: light, intent: "claim" }, + }); + await dispatch(controllerA, sourceA, { + type: "terminal_input", + terminalId: "terminal-1", + message: { type: "palette", defaultColors: dark, intent: "update" }, + }); + + await ownership.close(); + expect(appliedPalettes).toEqual([light, dark, light]); + }); }); diff --git a/packages/server/src/terminal/terminal-session-controller.ts b/packages/server/src/terminal/terminal-session-controller.ts index 0dd46ac6be..1f6fd94ac6 100644 --- a/packages/server/src/terminal/terminal-session-controller.ts +++ b/packages/server/src/terminal/terminal-session-controller.ts @@ -37,6 +37,10 @@ import type { TerminalReplayMetadata } from "./terminal-replay.js"; import type { TerminalSession } from "./terminal.js"; import type { TerminalManager, TerminalsChangedEvent } from "./terminal-manager.js"; import { applyTerminalSize } from "./terminal-size-ownership.js"; +import { + applyTerminalPalette, + claimInitialTerminalPaletteOwner, +} from "./terminal-palette-ownership.js"; import { TerminalWorkerIncompatibleError } from "./terminal-worker-pool.js"; import { terminalSubscriptionKey } from "@getpaseo/protocol/terminal-subscription-key"; @@ -219,7 +223,7 @@ export class TerminalSessionController { case "list_terminals_request": return this.handleListTerminalsRequest(msg); case "create_terminal_request": - return this.handleCreateTerminalRequest(msg); + return this.handleCreateTerminalRequest(msg, ownership); case "subscribe_terminal_request": return this.handleSubscribeTerminalRequest(msg, ownership); case "unsubscribe_terminal_request": @@ -571,7 +575,10 @@ export class TerminalSessionController { ); } - private async handleCreateTerminalRequest(msg: CreateTerminalRequest): Promise { + private async handleCreateTerminalRequest( + msg: CreateTerminalRequest, + ownership: SessionDelivery, + ): Promise { if (!this.terminalManager) { this.emit({ type: "create_terminal_response", @@ -621,9 +628,13 @@ export class TerminalSessionController { name: msg.name, command: msg.command, args: msg.args, + defaultColors: msg.defaultColors, rows: msg.size?.rows, cols: msg.size?.cols, }); + if (msg.defaultColors && ownership.currentSource) { + claimInitialTerminalPaletteOwner(session, ownership.currentSource); + } this.emit({ type: "create_terminal_response", payload: { @@ -808,6 +819,10 @@ export class TerminalSessionController { applyTerminalSize(session, source, msg.message); return; } + if (msg.message.type === "palette") { + applyTerminalPalette(session, source, msg.message); + return; + } session.send(msg.message); } diff --git a/packages/server/src/terminal/terminal-worker-client.ts b/packages/server/src/terminal/terminal-worker-client.ts index ac48293879..de677ee69c 100644 --- a/packages/server/src/terminal/terminal-worker-client.ts +++ b/packages/server/src/terminal/terminal-worker-client.ts @@ -16,6 +16,7 @@ const DEFAULT_CONNECT_TIMEOUT_MS = 5_000; export interface TerminalWorkerConnection { readonly connected: boolean; readonly workerPid: number; + readonly protocolVersion?: number; send(message: TerminalWorkerRequest, callback: (error: Error | null) => void): boolean; /** Closes the socket. The worker keeps running and keeps its terminals. */ disconnect(): void; @@ -32,13 +33,15 @@ export class TerminalWorkerConnectError extends Error { class SocketTerminalWorkerConnection extends EventEmitter implements TerminalWorkerConnection { readonly workerPid: number; + readonly protocolVersion: number; private readonly framed: FramedSocket; private closed = false; - constructor(framed: FramedSocket, workerPid: number) { + constructor(framed: FramedSocket, workerPid: number, protocolVersion: number) { super(); this.framed = framed; this.workerPid = workerPid; + this.protocolVersion = protocolVersion; framed.socket.once("close", () => { this.closed = true; this.emit("close"); @@ -110,7 +113,7 @@ export function connectTerminalWorker(input: { } settled = true; clearTimeout(timer); - connection = new SocketTerminalWorkerConnection(framed, message.pid); + connection = new SocketTerminalWorkerConnection(framed, message.pid, message.protocolVersion); resolve(connection); }); // `on`, not `once`: an error after authentication must not go unhandled. `close` diff --git a/packages/server/src/terminal/terminal-worker-process.ts b/packages/server/src/terminal/terminal-worker-process.ts index 7e548552b0..1888f97780 100644 --- a/packages/server/src/terminal/terminal-worker-process.ts +++ b/packages/server/src/terminal/terminal-worker-process.ts @@ -263,11 +263,13 @@ function runWorker(argv: string[]): void { } function terminalMetadata(session: LocalTerminalSession) { + const defaultColors = session.getDefaultColors?.(); return { ...session.getSize(), createdAt: session.createdAt, hasOutput: session.hasOutput(), title: session.getTitle(), + ...(defaultColors ? { defaultColors } : {}), }; } diff --git a/packages/server/src/terminal/terminal-worker-protocol.test.ts b/packages/server/src/terminal/terminal-worker-protocol.test.ts index 9193a5dabd..d9d8971385 100644 --- a/packages/server/src/terminal/terminal-worker-protocol.test.ts +++ b/packages/server/src/terminal/terminal-worker-protocol.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { classifyTerminalWorkerProtocol, + isUnsupportedForWorkerProtocol, TERMINAL_WORKER_PROTOCOL_VERSION, } from "./terminal-worker-protocol.js"; @@ -12,22 +13,42 @@ describe("classifyTerminalWorkerProtocol", () => { expect(classifyTerminalWorkerProtocol(4, 5)).toBe("obsolete"); }); it.each([ - [6, "current"], - [5, "previous"], + [7, "current"], + [6, "previous"], + [5, "obsolete"], [4, "obsolete"], [-1, "obsolete"], - [7, "newer"], + [8, "newer"], // A version this daemon cannot read comes from a Paseo it does not know. - ["6", "newer"], + ["7", "newer"], [4.5, "newer"], [Number.NaN, "newer"], [undefined, "newer"], - ])("a worker reporting %s to a daemon at 6 is %s", (reported, fit) => { - expect(classifyTerminalWorkerProtocol(reported, 6)).toBe(fit); + ])("a worker reporting %s to a daemon at 7 is %s", (reported, fit) => { + expect(classifyTerminalWorkerProtocol(reported, 7)).toBe(fit); }); }); -it("drains v5 terminals while v6 supplies creation timestamps", () => { - expect(TERMINAL_WORKER_PROTOCOL_VERSION).toBe(6); - expect(classifyTerminalWorkerProtocol(5)).toBe("previous"); +it("drains v6 terminals while v7 adds terminal palette support", () => { + expect(TERMINAL_WORKER_PROTOCOL_VERSION).toBe(7); + expect(classifyTerminalWorkerProtocol(6)).toBe("previous"); + expect(classifyTerminalWorkerProtocol(5)).toBe("obsolete"); +}); + +it("drops v7 palette updates for draining v6 workers while keeping other sends", () => { + const palette = { + type: "palette" as const, + defaultColors: { foreground: "#1a1a1e", background: "#ffffff" }, + }; + expect(isUnsupportedForWorkerProtocol({ type: "send", message: palette }, 6)).toBe(true); + expect(isUnsupportedForWorkerProtocol({ type: "send", message: palette }, 7)).toBe(false); + expect( + isUnsupportedForWorkerProtocol({ type: "send", message: { type: "input", data: "hi" } }, 6), + ).toBe(false); + expect( + isUnsupportedForWorkerProtocol( + { type: "send", message: { type: "resize", rows: 24, cols: 80 } }, + 6, + ), + ).toBe(false); }); diff --git a/packages/server/src/terminal/terminal-worker-protocol.ts b/packages/server/src/terminal/terminal-worker-protocol.ts index 62e731a4dc..66cb23b0af 100644 --- a/packages/server/src/terminal/terminal-worker-protocol.ts +++ b/packages/server/src/terminal/terminal-worker-protocol.ts @@ -1,12 +1,14 @@ import type { TerminalExitInfo, ServerMessage, ClientMessage } from "./terminal.js"; import type { TerminalReplayEvent, TerminalReplayOptions } from "./terminal-replay.js"; +import type { TerminalDefaultColors } from "@getpaseo/protocol/messages"; export interface WorkerTerminalState { - /** COMPAT(terminal-created-at): v6; v5 draining workers omit this, remove after 2027-06. */ createdAt?: string; rows: number; cols: number; hasOutput: boolean; title?: string; + /** COMPAT(terminal-worker-v6-drain): v7; v6 draining workers omit this, remove when bumping to v8. */ + defaultColors?: TerminalDefaultColors; } import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; import type { CaptureTerminalLinesResult } from "./terminal-capture.js"; @@ -27,6 +29,7 @@ export interface WorkerCreateTerminalOptions { name?: string; title?: string; env?: Record; + defaultColors?: TerminalDefaultColors; command?: string; args?: string[]; rows?: number; @@ -45,7 +48,24 @@ export interface WorkerCreateTerminalOptions { // `shutdown`. A daemon drives a worker of its own version, drains one a version older (no new // terminals; it exits after its last terminal), shuts down anything older, and leaves a newer // worker running untouched. See docs/terminal-worker.md. -export const TERMINAL_WORKER_PROTOCOL_VERSION = 6; +export const TERMINAL_WORKER_PROTOCOL_VERSION = 7; + +/** + * COMPAT(terminal-worker-v6-drain): added in v0.18.0 for worker protocol v7; + * remove when bumping to v8 once v6 workers are obsolete. + * + * Returns true when a request carries a v7-only command that a draining v6 + * worker does not support and must not receive over its socket. + */ +export function isUnsupportedForWorkerProtocol( + request: { type: TerminalWorkerRequest["type"]; message?: ClientMessage }, + workerProtocolVersion: number, +): boolean { + if (workerProtocolVersion >= TERMINAL_WORKER_PROTOCOL_VERSION) { + return false; + } + return request.type === "send" && request.message?.type === "palette"; +} // Test-only: the protocol version a worker reports, so tests can stand up older and newer // workers from one build. diff --git a/packages/server/src/terminal/terminal.posix.test.ts b/packages/server/src/terminal/terminal.posix.test.ts index 474507f771..35492c15da 100644 --- a/packages/server/src/terminal/terminal.posix.test.ts +++ b/packages/server/src/terminal/terminal.posix.test.ts @@ -222,6 +222,111 @@ function writeOsc11Helper(prefix: string): string { return path; } +const OSC_COLOR_HELPER_SCRIPT = `process.stdin.setRawMode(true); +process.stdin.resume(); +const code = process.argv[2]; +let buf = ""; +const timer = setTimeout(() => { + process.stdout.write("OSC_COLOR_TIMEOUT\\n"); + process.exit(2); +}, 2500); +process.stdin.on("data", (chunk) => { + buf += chunk.toString("binary"); + const match = buf.match(new RegExp("\\\\x1b\\\\]" + code + ";rgb:[0-9a-f/]+\\\\x1b\\\\\\\\")); + if (!match) { + return; + } + clearTimeout(timer); + process.stdout.write("OSC_COLOR_OK:" + code + ":" + match[0].replace(/\\x1b/g, "ESC") + "\\n"); + process.exit(0); +}); +process.stdout.write("\\x1b]" + code + ";?\\x07"); +`; + +const COLOR_SCHEME_HELPER_SCRIPT = `process.stdin.setRawMode(true); +process.stdin.resume(); +const mode = process.argv[2]; +let buf = ""; +const timer = setTimeout(() => { + process.stdout.write("SCHEME_TIMEOUT:" + buf.replace(/\\x1b/g, "ESC") + "\\n"); + process.exit(2); +}, 4000); +if (mode === "query") { + process.stdin.on("data", (chunk) => { + buf += chunk.toString("binary"); + const match = buf.match(/\\x1b\\[\\?997;([12])n/); + if (!match) return; + clearTimeout(timer); + process.stdout.write("SCHEME_QUERY_OK:" + match[1] + "\\n"); + process.exit(0); + }); + process.stdout.write("\\x1b[?996n"); +} else if (mode === "decrqm") { + let stage = 0; + let before = ""; + process.stdin.on("data", (chunk) => { + buf += chunk.toString("binary"); + if (stage === 0) { + const m = buf.match(/\\x1b\\[\\?2031;(\\d)\\$y/); + if (!m) return; + before = m[1]; + buf = ""; + stage = 1; + process.stdout.write("\\x1b[?2031h\\x1b[?2031$p"); + } else if (stage === 1) { + const m = buf.match(/\\x1b\\[\\?2031;(\\d)\\$y/); + if (!m) return; + clearTimeout(timer); + process.stdout.write("DECRQM_OK:" + before + ":" + m[1] + "\\n"); + process.exit(0); + } + }); + process.stdout.write("\\x1b[?2031$p"); +} else if (mode === "watch") { + const reports = []; + process.stdin.on("data", (chunk) => { + buf += chunk.toString("binary"); + if (buf.includes("D")) { + buf = buf.replaceAll("D", ""); + process.stdout.write("\\x1b[?2031l"); + process.stdout.write("SCHEME_DISABLED\\n"); + } + if (buf.includes("Q")) { + clearTimeout(timer); + process.stdout.write("SCHEME_DONE:" + reports.join(",") + "\\n"); + process.exit(0); + } + let match; + while ((match = buf.match(/\\x1b\\[\\?997;([12])n/))) { + reports.push(match[1]); + process.stdout.write("SCHEME_EVENT:" + match[1] + "\\n"); + buf = buf.slice(match.index + match[0].length); + } + }); + process.stdout.write("\\x1b[?2031hSCHEME_WATCH_READY\\n"); +} +`; + +function waitForOutputLine(session: TerminalSession, line: string): Promise { + return waitForState(session, (state) => getLines(state).includes(line)); +} + +function writeOscColorHelper(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)); + temporaryDirs.push(dir); + const path = join(dir, "helper.cjs"); + writeFileSync(path, OSC_COLOR_HELPER_SCRIPT); + return path; +} + +function writeColorSchemeHelper(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)); + temporaryDirs.push(dir); + const path = join(dir, "helper.cjs"); + writeFileSync(path, COLOR_SCHEME_HELPER_SCRIPT); + return path; +} + function isDaOkLine(line: string): boolean { return line.startsWith("DA_OK:"); } @@ -1072,6 +1177,136 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => { const ack = getLines(await readTerminalState(session)).find(isOsc11OkLine) ?? ""; expect(ack).toBe("OSC11_OK:ESC]11;rgb:0b0b/0b0b/0b0bESC\\"); }); + + it("reports the terminal creation palette for OSC 10/11/12 queries and sets COLORFGBG", async () => { + const colors = { + foreground: "#112233", + background: "#abcdef", + cursor: "#445566", + }; + const helperPath = writeOscColorHelper("terminal-osc-all-helper-"); + const session = trackSession( + await createTerminal({ + workspaceId: "ws-test", + cwd: "/tmp", + shell: "/bin/sh", + env: { PS1: "$ " }, + defaultColors: colors, + }), + ); + await waitForLines(session, ["$"]); + + session.send({ type: "input", data: 'echo "CFGBG=$COLORFGBG"\r' }); + await waitForOutputLine(session, "CFGBG=0;15"); + + for (const [code, expected] of [ + [10, "rgb:1111/2222/3333"], + [11, "rgb:abab/cdcd/efef"], + [12, "rgb:4444/5555/6666"], + ] as const) { + session.send({ type: "input", data: `${process.execPath} ${helperPath} ${code}\r` }); + await waitForState(session, (state) => + getLines(state).some((line) => line.startsWith(`OSC_COLOR_OK:${code}:`)), + ); + const ack = + getLines(await readTerminalState(session)).find((line) => + line.startsWith(`OSC_COLOR_OK:${code}:`), + ) ?? ""; + expect(ack).toBe(`OSC_COLOR_OK:${code}:ESC]${code};${expected}ESC\\`); + } + }); + + it("composites translucent terminal colors before reporting OSC queries", async () => { + const colors = { + foreground: "#33669980", + background: "#112233cc", + cursor: "#abcdef40", + }; + const helperPath = writeOscColorHelper("terminal-osc-alpha-helper-"); + const session = trackSession( + await createTerminal({ + workspaceId: "ws-test", + cwd: "/tmp", + shell: "/bin/sh", + env: { PS1: "$ " }, + defaultColors: colors, + }), + ); + await waitForLines(session, ["$"]); + + for (const [code, response] of [ + [10, "rgb:2222/4242/6262"], + [11, "rgb:1010/1d1d/2b2b"], + [12, "rgb:3737/4949/5c5c"], + ] as const) { + session.send({ type: "input", data: `${process.execPath} ${helperPath} ${code}\r` }); + await waitForState(session, (state) => + getLines(state).some((line) => line.startsWith(`OSC_COLOR_OK:${code}:`)), + ); + const ack = + getLines(await readTerminalState(session)).find((line) => + line.startsWith(`OSC_COLOR_OK:${code}:`), + ) ?? ""; + expect(ack).toBe(`OSC_COLOR_OK:${code}:ESC]${code};${response}ESC\\`); + } + }); + + it("updates OSC 10/11/12, answers DSR 996/997 + DECRQM 2031, and emits DEC 2031 polarity changes live", async () => { + const oscHelper = writeOscColorHelper("terminal-osc-live-helper-"); + const schemeHelper = writeColorSchemeHelper("terminal-scheme-live-helper-"); + const light = { foreground: "#1a1a1e", background: "#ffffff", cursor: "#1a1a1e" }; + const dark = { foreground: "#fafafa", background: "#181b1a", cursor: "#fafafa" }; + + const session = trackSession( + await createTerminal({ + workspaceId: "ws-test", + cwd: "/tmp", + shell: "/bin/sh", + env: { PS1: "$ " }, + defaultColors: light, + }), + ); + await waitForLines(session, ["$"]); + + // DSR 996 query reports light (2) initially + session.send({ type: "input", data: `${process.execPath} ${schemeHelper} query\r` }); + await waitForOutputLine(session, "SCHEME_QUERY_OK:2"); + + // DECRQM 2031 reports reset (2) before enabling and set (1) after enabling + session.send({ type: "input", data: `${process.execPath} ${schemeHelper} decrqm\r` }); + await waitForOutputLine(session, "DECRQM_OK:2:1"); + + // Start mode 2031 watcher + session.send({ type: "input", data: `${process.execPath} ${schemeHelper} watch\r` }); + await waitForOutputLine(session, "SCHEME_WATCH_READY"); + + // Same polarity update (another light palette) does NOT emit a 997 report + session.send({ + type: "palette", + defaultColors: { foreground: "#111111", background: "#fafafa", cursor: "#111111" }, + }); + // Flip light -> dark emits CSI ? 997 ; 1 n + session.send({ type: "palette", defaultColors: dark }); + await waitForOutputLine(session, "SCHEME_EVENT:1"); + + // Flip dark -> light emits CSI ? 997 ; 2 n + session.send({ type: "palette", defaultColors: light }); + await waitForOutputLine(session, "SCHEME_EVENT:2"); + + // Disable mode 2031, flip to dark again, confirm no third event is emitted + session.send({ type: "input", data: "D" }); + await waitForOutputLine(session, "SCHEME_DISABLED"); + session.send({ type: "palette", defaultColors: dark }); + session.send({ type: "input", data: "Q" }); + await waitForOutputLine(session, "SCHEME_DONE:1,2"); + + // Subsequent OSC 11 and DSR 996 queries immediately reflect the updated dark palette + session.send({ type: "input", data: `${process.execPath} ${oscHelper} 11\r` }); + await waitForOutputLine(session, "OSC_COLOR_OK:11:ESC]11;rgb:1818/1b1b/1a1aESC\\"); + + session.send({ type: "input", data: `${process.execPath} ${schemeHelper} query\r` }); + await waitForOutputLine(session, "SCHEME_QUERY_OK:1"); + }); }); describe("stream snapshots", () => { diff --git a/packages/server/src/terminal/terminal.test.ts b/packages/server/src/terminal/terminal.test.ts index fc3a9797e5..4db62f2ba4 100644 --- a/packages/server/src/terminal/terminal.test.ts +++ b/packages/server/src/terminal/terminal.test.ts @@ -1217,6 +1217,47 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => { }, ); + it("derives COLORFGBG from defaultColors unless already set in env", () => { + const defaultEnv = buildTerminalEnvironment({ + shell: "/bin/sh", + env: {}, + baseEnv: { PATH: "/usr/bin:/bin", COLORFGBG: "9;9" }, + paseoCliBinDir: null, + paseoHookCliPath: null, + }); + expect(defaultEnv.COLORFGBG).toBe("15;0"); + + const lightEnv = buildTerminalEnvironment({ + shell: "/bin/sh", + env: {}, + baseEnv: { PATH: "/usr/bin:/bin", COLORFGBG: "15;0" }, + defaultColors: { foreground: "#1a1a1e", background: "#ffffff" }, + paseoCliBinDir: null, + paseoHookCliPath: null, + }); + expect(lightEnv.COLORFGBG).toBe("0;15"); + + const darkEnv = buildTerminalEnvironment({ + shell: "/bin/sh", + env: {}, + baseEnv: { PATH: "/usr/bin:/bin", COLORFGBG: "0;15" }, + defaultColors: { foreground: "#fafafa", background: "#181b1a" }, + paseoCliBinDir: null, + paseoHookCliPath: null, + }); + expect(darkEnv.COLORFGBG).toBe("15;0"); + + const explicitEnv = buildTerminalEnvironment({ + shell: "/bin/sh", + env: { COLORFGBG: "7;0" }, + baseEnv: { PATH: "/usr/bin:/bin" }, + defaultColors: { foreground: "#1a1a1e", background: "#ffffff" }, + paseoCliBinDir: null, + paseoHookCliPath: null, + }); + expect(explicitEnv.COLORFGBG).toBe("7;0"); + }); + it.skipIf(!hasZsh)("emits zsh shell integration command completion", async () => { const homeDir = mkdtempSync(join(tmpdir(), "terminal-zsh-command-finished-home-")); temporaryDirs.push(homeDir); diff --git a/packages/server/src/terminal/terminal.ts b/packages/server/src/terminal/terminal.ts index 02f168b5ee..040924c39f 100644 --- a/packages/server/src/terminal/terminal.ts +++ b/packages/server/src/terminal/terminal.ts @@ -39,21 +39,24 @@ import { type CaptureTerminalLinesResult, } from "./terminal-capture.js"; import type { TerminalReplayOptions, TerminalReplayMetadata } from "./terminal-replay.js"; +import type { TerminalDefaultColors } from "@getpaseo/protocol/messages"; import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode"; import { TerminalActivityTracker } from "./activity/terminal-activity-tracker.js"; import { resolveDefaultTerminalShell } from "./default-terminal-shell.js"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; +import { + formatColorSchemeModeReport, + formatColorSchemeReport, + resolveTerminalPalette, + type ResolvedTerminalPalette, +} from "./terminal-palette.js"; const require = createRequire(import.meta.url); let nodePtySpawnHelperChecked = false; const TERMINAL_TITLE_DEBOUNCE_MS = 150; const TERMINAL_EXIT_OUTPUT_LINE_LIMIT = 12; const TERMINAL_EXIT_OUTPUT_CHAR_LIMIT = 16000; -const TERMINAL_OSC_COLOR_QUERY_RESPONSES = new Map([ - [10, "rgb:e6e6/e6e6/e6e6"], - [11, "rgb:0b0b/0b0b/0b0b"], - [12, "rgb:e6e6/e6e6/e6e6"], -]); +const DEC_COLOR_SCHEME_REPORTING_MODE = 2031; export interface TerminalExitInfo { exitCode: number | null; @@ -82,7 +85,8 @@ export interface TerminalCommandFinishedInfo { export type ClientMessage = | { type: "input"; data: string } | { type: "resize"; rows: number; cols: number } - | { type: "mouse"; row: number; col: number; button: number; action: "down" | "up" | "move" }; + | { type: "mouse"; row: number; col: number; button: number; action: "down" | "up" | "move" } + | { type: "palette"; defaultColors: TerminalDefaultColors }; export type ServerMessage = | { type: "output"; data: string; revision?: number } @@ -108,6 +112,7 @@ export interface TerminalSession { onTitleChange(listener: (title?: string) => void): () => void; onActivityChange(listener: (transition: TerminalActivityTransition) => void): () => void; getSize(): { rows: number; cols: number }; + getDefaultColors?(): TerminalDefaultColors | undefined; hasOutput(): boolean; getReplayPreamble(): string; getTitle(): string | undefined; @@ -151,6 +156,7 @@ export interface CreateTerminalOptions { id?: string; cwd: string; workspaceId: string; + defaultColors?: TerminalDefaultColors; shell?: string; env?: Record; activityEnv?: Record; @@ -193,6 +199,7 @@ function isTerminalActivityInterruptInput(data: string): boolean { interface BuildTerminalEnvironmentInput { shell: string; env: Record; + defaultColors?: TerminalDefaultColors; baseEnv?: Record; zshShellIntegrationDir?: string; paseoCliBinDir?: string | null; @@ -379,13 +386,20 @@ function prepareZshShellIntegrationRuntimeDir(sourceDir = resolveZshShellIntegra export function buildTerminalEnvironment( input: BuildTerminalEnvironmentInput, ): Record { + const hasExplicitColorFgBg = Object.keys(input.env).some( + (key) => key.toLowerCase() === "colorfgbg" && input.env[key] !== undefined, + ); + const terminalOverrides: Record = { + TERM: "xterm-256color", + TERM_PROGRAM: "kitty", + ...(hasExplicitColorFgBg + ? {} + : { COLORFGBG: resolveTerminalPalette(input.defaultColors).colorFgBg }), + }; const baseEnv: Record = createExternalProcessEnv( input.baseEnv ?? process.env, input.env, - { - TERM: "xterm-256color", - TERM_PROGRAM: "kitty", - }, + terminalOverrides, ); const envWithAgentHooks = prependPaseoCliToPath( baseEnv, @@ -683,6 +697,7 @@ export async function createTerminal( const { cwd, workspaceId, + defaultColors, shell, env = {}, activityEnv = {}, @@ -698,6 +713,9 @@ export async function createTerminal( const resolvedShell = shell ?? resolveDefaultTerminalShell({ env: baseEnv }); const id = options.id ?? randomUUID(); + let activeDefaultColors: TerminalDefaultColors | undefined = defaultColors; + let activePalette: ResolvedTerminalPalette = resolveTerminalPalette(defaultColors); + let colorSchemeReportingEnabled = false; const listeners = new Set<(msg: ServerMessage) => void>(); const exitListeners = new Set<(info: TerminalExitInfo) => void>(); const commandFinishedListeners = new Set<(info: TerminalCommandFinishedInfo) => void>(); @@ -743,6 +761,7 @@ export async function createTerminal( ...activityEnv, PASEO_WORKSPACE_ID: workspaceId, }, + ...(defaultColors ? { defaultColors } : {}), ...resolveTerminalEnvironmentSource({ baseEnv, paseoCliPath }), }); @@ -833,19 +852,53 @@ export async function createTerminal( } return false; }); + terminal.parser.registerCsiHandler({ prefix: "?", final: "h" }, (params) => { + if (params.includes(DEC_COLOR_SCHEME_REPORTING_MODE)) { + colorSchemeReportingEnabled = true; + } + return false; + }); + terminal.parser.registerCsiHandler({ prefix: "?", final: "l" }, (params) => { + if (params.includes(DEC_COLOR_SCHEME_REPORTING_MODE)) { + colorSchemeReportingEnabled = false; + } + return false; + }); + terminal.parser.registerEscHandler({ final: "c" }, () => { + colorSchemeReportingEnabled = false; + return false; + }); + terminal.parser.registerCsiHandler({ prefix: "?", intermediates: "$", final: "p" }, (params) => { + if (params.length === 1 && params[0] === DEC_COLOR_SCHEME_REPORTING_MODE) { + ptyProcess.write(formatColorSchemeModeReport(colorSchemeReportingEnabled)); + return true; + } + return false; + }); terminal.parser.registerCsiHandler({ prefix: "?", final: "n" }, (params) => { - if (params.length !== 1 || params[0] !== 6) { + if (params.length !== 1) { return false; } - const buffer = terminal.buffer.active; - ptyProcess.write(`\x1b[?${buffer.cursorY + 1};${buffer.cursorX + 1}R`); - return true; + if (params[0] === 6) { + const buffer = terminal.buffer.active; + ptyProcess.write(`\x1b[?${buffer.cursorY + 1};${buffer.cursorX + 1}R`); + return true; + } + if (params[0] === 996) { + ptyProcess.write(formatColorSchemeReport(activePalette.colorScheme)); + return true; + } + return false; }); - for (const [code, response] of TERMINAL_OSC_COLOR_QUERY_RESPONSES) { + for (const code of [10, 11, 12] as const) { terminal.parser.registerOscHandler(code, (data) => { if (data.trim() !== "?") { return false; } + const response = activePalette.oscResponses.get(code); + if (!response) { + return false; + } ptyProcess.write(`\x1b]${code};${response}\x1b\\`); return true; }); @@ -1108,6 +1161,20 @@ export async function createTerminal( // Mouse events can be sent as escape sequences if terminal supports it // For now, we'll just ignore them - can be implemented later break; + case "palette": { + const previousScheme = activePalette.colorScheme; + activeDefaultColors = msg.defaultColors; + activePalette = resolveTerminalPalette(msg.defaultColors); + if ( + colorSchemeReportingEnabled && + activePalette.colorScheme !== previousScheme && + !disposed + ) { + flushPendingInput(); + ptyProcess.write(formatColorSchemeReport(activePalette.colorScheme)); + } + break; + } } } @@ -1328,6 +1395,7 @@ export async function createTerminal( onTitleChange, onActivityChange, getSize, + getDefaultColors: () => activeDefaultColors, serializeReplay, captureLines: (captureOptions) => captureTerminalLines(terminal.buffer.active, captureOptions), hasOutput: () => { diff --git a/packages/server/src/terminal/worker-terminal-manager.test.ts b/packages/server/src/terminal/worker-terminal-manager.test.ts index 678c4d68cd..d109992b3f 100644 --- a/packages/server/src/terminal/worker-terminal-manager.test.ts +++ b/packages/server/src/terminal/worker-terminal-manager.test.ts @@ -1691,8 +1691,8 @@ async function leaveWorkerWithTerminal( }; } -it.each([1, 4])( - "hard cuts unreleased worker protocol %s, closing its terminals", +it.each([1, 4, 5])( + "hard cuts obsolete worker protocol %s, closing its terminals", async (version) => { const paseoHome = createTemporaryHome(); const old = await leaveWorkerWithTerminal(paseoHome, version); @@ -1718,19 +1718,58 @@ it.each([1, 4])( expect(manager.getTerminal(old.terminalId)).toBeUndefined(); const workers = await workerRecords(paseoHome); expect(workers).toHaveLength(1); - expect(workers[0]!.protocolVersion).toBe(6); + expect(workers[0]!.protocolVersion).toBe(TERMINAL_WORKER_PROTOCOL_VERSION); }, ); +it("drains a v6 worker safely while v7 carries creation and live terminal palettes", async () => { + const paseoHome = createTemporaryHome(); + const draining = await leaveWorkerWithTerminal(paseoHome, 6); + const light = { foreground: "#1a1a1e", background: "#ffffff", cursor: "#1a1a1e" }; + const dark = { foreground: "#fafafa", background: "#181b1a", cursor: "#fafafa" }; + + manager = await startRealWorkerManager({ paseoHome }); + + const drainingSession = manager.getTerminal(draining.terminalId); + expect(drainingSession).toBeDefined(); + expect(drainingSession?.getDefaultColors?.()).toBeUndefined(); + // v6 draining adapter drops v7 palette sends without erroring or killing the draining worker. + drainingSession?.send({ type: "palette", defaultColors: light }); + expect(drainingSession?.getDefaultColors?.()).toBeUndefined(); + expect(isProcessAlive(draining.programPid)).toBe(true); + + // New terminals land on the v7 worker with creation-time and live palette state. + const created = await manager.createTerminal({ + workspaceId: "ws-protocol", + cwd: draining.cwd, + defaultColors: light, + ...nodeTerminalCommand("setInterval(() => {}, 1000);"), + }); + expect(created.getDefaultColors?.()).toEqual(light); + + created.send({ type: "palette", defaultColors: dark }); + expect(created.getDefaultColors?.()).toEqual(dark); + + // Detach and re-adopt to confirm the v7 worker retains the live palette across daemon restarts. + await manager.detach({ afterPendingRequests: true }); + manager = await startRealWorkerManager({ paseoHome }); + expect(manager.getTerminal(created.id)?.getDefaultColors?.()).toEqual(dark); + expect(manager.getTerminal(draining.terminalId)).toBeDefined(); + + const workers = await workerRecords(paseoHome); + expect(workers.map((record) => record.protocolVersion).sort()).toEqual([6, 7]); +}, 30000); + it("leaves a worker from a newer Paseo running, reports it incompatible, and closes it on a kill stop", async () => { const paseoHome = createTemporaryHome(); - const newer = await leaveWorkerWithTerminal(paseoHome, 7); + const newerProtocol = TERMINAL_WORKER_PROTOCOL_VERSION + 1; + const newer = await leaveWorkerWithTerminal(paseoHome, newerProtocol); manager = await startRealWorkerManager({ paseoHome }); const unavailable = manager.getUnavailableError?.(); expect(unavailable).toBeInstanceOf(TerminalWorkerIncompatibleError); - expect(unavailable?.message).toContain("worker protocol 7"); + expect(unavailable?.message).toContain(`worker protocol ${newerProtocol}`); await expect(manager.getTerminals(newer.cwd)).rejects.toBeInstanceOf( TerminalWorkerIncompatibleError, ); diff --git a/packages/server/src/terminal/worker-terminal-manager.ts b/packages/server/src/terminal/worker-terminal-manager.ts index 7747fdb891..18977ad649 100644 --- a/packages/server/src/terminal/worker-terminal-manager.ts +++ b/packages/server/src/terminal/worker-terminal-manager.ts @@ -48,6 +48,8 @@ import type { } from "./terminal-manager.js"; import { classifyTerminalWorkerProtocol, + isUnsupportedForWorkerProtocol, + TERMINAL_WORKER_PROTOCOL_VERSION, type TerminalWorkerProtocolFit, } from "./terminal-worker-protocol.js"; import type { @@ -281,12 +283,21 @@ export function createWorkerTerminalManager( return record.info.workspaceId; }, send(message: ClientMessage): void { + const workerProtocolVersion = worker.protocolVersion ?? TERMINAL_WORKER_PROTOCOL_VERSION; + if (isUnsupportedForWorkerProtocol({ type: "send", message }, workerProtocolVersion)) { + return; + } if (message.type === "resize") { record.state = { ...record.state, rows: message.rows, cols: message.cols, }; + } else if (message.type === "palette") { + record.state = { + ...record.state, + defaultColors: message.defaultColors, + }; } sendBestEffortRequest({ type: "send", terminalId: record.info.id, message }); }, @@ -355,6 +366,9 @@ export function createWorkerTerminalManager( cols: record.state.cols, }; }, + getDefaultColors() { + return record.state.defaultColors; + }, hasOutput(): boolean { return record.state.hasOutput; },