Compare commits

...

4 Commits

11 changed files with 454 additions and 346 deletions
+25
View File
@@ -106,6 +106,30 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
enterAlternateScreen: vi.fn(),
disableLineWrapping: vi.fn(),
getVersion: vi.fn(() => Promise.resolve('1.0.0')),
detectTerminalEnvironment: vi.fn().mockReturnValue({
isTmux: false,
isJetBrains: false,
isWindowsTerminal: false,
isVSCode: false,
isITerm2: false,
isGhostty: false,
isAppleTerminal: false,
isWindows10: false,
supports256Colors: true,
supportsTrueColor: true,
supportsKeyboardProtocol: true,
}),
getTerminalCapabilities: vi.fn().mockReturnValue({
capabilities: {
supportsAltBuffer: true,
supportsMouse: true,
supportsReliableBackbufferClear: true,
supportsKeyboardProtocol: true,
},
warnings: [],
reasons: {},
}),
supportsKeyboardProtocolHeuristic: vi.fn().mockReturnValue(true),
startupProfiler: {
start: vi.fn(() => ({
end: vi.fn(),
@@ -184,6 +208,7 @@ vi.mock('./ui/utils/terminalCapabilityManager.js', () => ({
terminalCapabilityManager: {
detectCapabilities: vi.fn(),
getTerminalBackgroundColor: vi.fn(),
isKeyboardProtocolSupported: vi.fn().mockReturnValue(false),
},
}));
+3
View File
@@ -15,6 +15,7 @@ import { createHash } from 'node:crypto';
import v8 from 'node:v8';
import os from 'node:os';
import dns from 'node:dns';
import { terminalCapabilityManager } from './ui/utils/terminalCapabilityManager.js';
import { start_sandbox } from './utils/sandbox.js';
import type { DnsResolutionOrder, LoadedSettings } from './config/settings.js';
import {
@@ -690,6 +691,8 @@ export async function main() {
})),
...(await getUserStartupWarnings(settings.merged, undefined, {
isAlternateBuffer: useAlternateBuffer,
supportsKeyboardProtocol:
terminalCapabilityManager.isKeyboardProtocolSupported(),
})),
];
@@ -49,6 +49,7 @@ describe('TerminalCapabilityManager', () => {
beforeEach(() => {
vi.resetAllMocks();
vi.useFakeTimers();
// Reset singleton
TerminalCapabilityManager.resetInstanceForTesting();
@@ -58,11 +59,9 @@ describe('TerminalCapabilityManager', () => {
stdin.isTTY = true;
stdin.isRaw = false;
stdin.setRawMode = vi.fn();
stdin.removeListener = vi.fn();
stdout = { isTTY: true, fd: 1 };
// Use defineProperty to mock process.stdin/stdout
// Use defineProperty to mock process properties
Object.defineProperty(process, 'stdin', {
value: stdin,
configurable: true,
@@ -71,8 +70,6 @@ describe('TerminalCapabilityManager', () => {
value: stdout,
configurable: true,
});
vi.useFakeTimers();
});
afterEach(() => {
@@ -92,25 +89,24 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate Kitty response: \x1b[?1u
// Simulate kitty protocol response
stdin.emit('data', Buffer.from('\x1b[?1u'));
// Complete detection with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
// Simulate sentinel response
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
expect(manager.isKittyProtocolEnabled()).toBe(true);
expect(enableKittyKeyboardProtocol).toHaveBeenCalled();
});
it('should detect Background Color', async () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate OSC 11 response
// \x1b]11;rgb:0000/ff00/0000\x1b\
// RGB: 0, 255, 0 -> #00ff00
// Simulate background color response
stdin.emit('data', Buffer.from('\x1b]11;rgb:0000/ffff/0000\x1b\\'));
// Complete detection with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
// Simulate sentinel response
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
expect(manager.getTerminalBackgroundColor()).toBe('#00ff00');
@@ -120,10 +116,10 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate Terminal Name response
// Simulate terminal name response
stdin.emit('data', Buffer.from('\x1bP>|WezTerm 20240203\x1b\\'));
// Complete detection with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
// Simulate sentinel response
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
expect(manager.getTerminalName()).toBe('WezTerm 20240203');
@@ -133,14 +129,15 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
stdin.emit('data', Buffer.from('\x1b[?1u'));
stdin.emit('data', Buffer.from('\x1b]11;rgb:0000/0000/0000\x1b\\'));
// Sentinel
stdin.emit('data', Buffer.from('\x1b[?62c'));
// Send everything at once
stdin.emit(
'data',
Buffer.from(
'\x1b[?1u\x1b]11;rgb:0000/0000/0000\x1b\\\x1bP>|xterm\x1b\\\x1b[?1c',
),
);
// Should resolve without waiting for timeout
await promise;
expect(manager.isKittyProtocolEnabled()).toBe(true);
expect(manager.getTerminalBackgroundColor()).toBe('#000000');
});
@@ -149,22 +146,19 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate only Kitty response
stdin.emit('data', Buffer.from('\x1b[?1u'));
// Advance to timeout
// Don't send any data, just trigger timeout
vi.advanceTimersByTime(1000);
await promise;
expect(manager.isKittyProtocolEnabled()).toBe(true);
expect(manager.getTerminalBackgroundColor()).toBeUndefined();
});
it('should not detect Kitty if only DA1 (c) is received', async () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate DA1 response only: \x1b[?62;c
stdin.emit('data', Buffer.from('\x1b[?62c'));
// Send only sentinel
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
expect(manager.isKittyProtocolEnabled()).toBe(false);
@@ -174,14 +168,13 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Split response: \x1b[? 1u
stdin.emit('data', Buffer.from('\x1b[?'));
stdin.emit('data', Buffer.from('1u'));
// Complete with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
// Split background color response
stdin.emit('data', Buffer.from('\x1b]11;'));
stdin.emit('data', Buffer.from('rgb:ffff/0000/0000\x1b\\'));
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
expect(manager.isKittyProtocolEnabled()).toBe(true);
expect(manager.getTerminalBackgroundColor()).toBe('#ff0000');
});
describe('modifyOtherKeys detection', () => {
@@ -189,10 +182,9 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate modifyOtherKeys level 2 response: \x1b[>4;2m
// level 2
stdin.emit('data', Buffer.from('\x1b[>4;2m'));
// Complete detection with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
@@ -203,10 +195,9 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate modifyOtherKeys level 0 response: \x1b[>4;0m
// level 0 (disabled)
stdin.emit('data', Buffer.from('\x1b[>4;0m'));
// Complete detection with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
@@ -217,14 +208,11 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate both Kitty and modifyOtherKeys responses
stdin.emit('data', Buffer.from('\x1b[?1u'));
stdin.emit('data', Buffer.from('\x1b[>4;2m'));
// Complete detection with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
expect(manager.isKittyProtocolEnabled()).toBe(true);
expect(enableKittyKeyboardProtocol).toHaveBeenCalled();
expect(enableModifyOtherKeys).not.toHaveBeenCalled();
@@ -234,10 +222,8 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate only modifyOtherKeys response (no Kitty)
stdin.emit('data', Buffer.from('\x1b[>4;2m'));
// Complete detection with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
@@ -249,11 +235,9 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Split response: \x1b[>4;2m
stdin.emit('data', Buffer.from('\x1b[>4;'));
stdin.emit('data', Buffer.from('2m'));
// Complete detection with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
@@ -264,17 +248,15 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
stdin.emit('data', Buffer.from('\x1b]11;rgb:1a1a/1a1a/1a1a\x1b\\')); // background color
stdin.emit('data', Buffer.from('\x1bP>|tmux\x1b\\')); // Terminal name
stdin.emit('data', Buffer.from('\x1b[>4;2m')); // modifyOtherKeys
// Complete detection with DA1
stdin.emit('data', Buffer.from('\x1b[?62c'));
stdin.emit('data', Buffer.from('\x1b]11;rgb:1a1a/1a1a/1a1a\x1b\\'));
stdin.emit('data', Buffer.from('\x1bP>|tmux\x1b\\'));
stdin.emit('data', Buffer.from('\x1b[>4;2m'));
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
expect(manager.getTerminalBackgroundColor()).toBe('#1a1a1a');
expect(manager.getTerminalName()).toBe('tmux');
expect(enableModifyOtherKeys).toHaveBeenCalled();
});
@@ -282,8 +264,7 @@ describe('TerminalCapabilityManager', () => {
const manager = TerminalCapabilityManager.getInstance();
const promise = manager.detectCapabilities();
// Simulate only DA1 response (no specific MOK or Kitty response)
stdin.emit('data', Buffer.from('\x1b[?62c'));
stdin.emit('data', Buffer.from('\x1b[?1c'));
await promise;
@@ -298,18 +279,16 @@ describe('TerminalCapabilityManager', () => {
expect(fs.writeSync).toHaveBeenCalledWith(
expect.anything(),
// eslint-disable-next-line no-control-regex
expect.stringMatching(/^\x1b\[8m.*\x1b\[2K\r\x1b\[0m$/s),
expect.stringMatching(/^\x1b\[8m.*?\x1b\[2K\r\x1b\[0m$/),
);
});
});
describe('supportsOsc9Notifications', () => {
const manager = TerminalCapabilityManager.getInstance();
it.each([
const testCases = [
{
name: 'WezTerm (terminal name)',
terminalName: 'WezTerm',
terminalName: 'WezTerm 20240203',
env: {},
expected: true,
},
@@ -327,7 +306,7 @@ describe('TerminalCapabilityManager', () => {
},
{
name: 'kitty (terminal name)',
terminalName: 'kitty',
terminalName: 'xterm-kitty',
env: {},
expected: true,
},
@@ -361,18 +340,14 @@ describe('TerminalCapabilityManager', () => {
env: { TERM: 'xterm-256color' },
expected: false,
},
{
name: 'Windows Terminal (WT_SESSION)',
terminalName: 'iTerm.app',
env: { WT_SESSION: 'some-guid' },
expected: false,
},
])(
'should return $expected for $name',
({ terminalName, env, expected }) => {
];
testCases.forEach(({ name, terminalName, env, expected }) => {
it(`should return ${expected} for '${name}'`, () => {
const manager = TerminalCapabilityManager.getInstance();
vi.spyOn(manager, 'getTerminalName').mockReturnValue(terminalName);
expect(manager.supportsOsc9Notifications(env)).toBe(expected);
},
);
});
});
});
});
@@ -35,6 +35,9 @@ export function cleanupTerminalOnExit() {
disableBracketedPasteMode();
}
/**
* Manages terminal capability detection.
*/
export class TerminalCapabilityManager {
private static instance: TerminalCapabilityManager | undefined;
@@ -47,16 +50,6 @@ export class TerminalCapabilityManager {
private static readonly CLEAR_LINE_AND_RETURN = '\x1b[2K\r';
private static readonly RESET_ATTRIBUTES = '\x1b[0m';
/**
* Triggers a terminal background color query.
* @param stdout The stdout stream to write to.
*/
static queryBackgroundColor(stdout: {
write: (data: string) => void | boolean;
}): void {
stdout.write(TerminalCapabilityManager.OSC_11_QUERY);
}
// Kitty keyboard flags: CSI ? flags u
// eslint-disable-next-line no-control-regex
private static readonly KITTY_REGEX = /\x1b\[\?(\d+)u/;
@@ -80,6 +73,7 @@ export class TerminalCapabilityManager {
private kittyEnabled = false;
private modifyOtherKeysSupported = false;
private terminalName: string | undefined;
private sentinelReceived = false;
private constructor() {}
@@ -212,6 +206,7 @@ export class TerminalCapabilityManager {
);
if (match) {
deviceAttributesReceived = true;
this.sentinelReceived = true;
cleanup();
}
}
@@ -270,11 +265,18 @@ export class TerminalCapabilityManager {
return this.kittyEnabled;
}
supportsOsc9Notifications(env: NodeJS.ProcessEnv = process.env): boolean {
if (env['WT_SESSION']) {
return false;
}
/**
* Returns true if keyboard protocol support was explicitly detected.
* Returns false if detection finished and no support was found.
* Returns undefined if detection timed out or failed to receive the sentinel.
*/
isKeyboardProtocolSupported(): boolean | undefined {
if (this.kittySupported || this.modifyOtherKeysSupported) return true;
if (this.sentinelReceived) return false;
return undefined;
}
supportsOsc9Notifications(env: NodeJS.ProcessEnv = process.env): boolean {
return (
this.hasOsc9TerminalSignature(this.getTerminalName()) ||
this.hasOsc9TerminalSignature(env['TERM_PROGRAM']) ||
@@ -174,5 +174,20 @@ describe('getUserStartupWarnings', () => {
);
expect(warnings).not.toContainEqual(compWarning);
});
it('should pass options to getCompatibilityWarnings', async () => {
const projectDir = path.join(testRootDir, 'project');
await fs.mkdir(projectDir);
await getUserStartupWarnings({}, projectDir, {
isAlternateBuffer: true,
supportsKeyboardProtocol: true,
});
expect(getCompatibilityWarnings).toHaveBeenCalledWith({
isAlternateBuffer: true,
supportsKeyboardProtocol: true,
});
});
});
});
@@ -88,7 +88,10 @@ const WARNING_CHECKS: readonly WarningCheck[] = [
export async function getUserStartupWarnings(
settings: Settings,
workspaceRoot: string = process.cwd(),
options?: { isAlternateBuffer?: boolean },
options?: {
isAlternateBuffer?: boolean;
supportsKeyboardProtocol?: boolean;
},
): Promise<StartupWarning[]> {
const results = await Promise.all(
WARNING_CHECKS.map(async (check) => {
@@ -109,6 +112,7 @@ export async function getUserStartupWarnings(
warnings.push(
...getCompatibilityWarnings({
isAlternateBuffer: options?.isAlternateBuffer,
supportsKeyboardProtocol: options?.supportsKeyboardProtocol,
}),
);
}
+1
View File
@@ -191,6 +191,7 @@ export { logBillingEvent } from './telemetry/loggers.js';
export * from './telemetry/constants.js';
export { sessionId, createSessionId } from './utils/session.js';
export * from './utils/compatibility.js';
export * from './utils/terminalEnvironment.js';
export * from './utils/browser.js';
export { Storage } from './config/storage.js';
+86 -236
View File
@@ -4,16 +4,18 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, vi, afterEach } from 'vitest';
import os from 'node:os';
import {
isWindows10,
isJetBrainsTerminal,
supports256Colors,
supportsTrueColor,
getCompatibilityWarnings,
WarningPriority,
isTmux,
supportsKeyboardProtocolHeuristic,
} from './compatibility.js';
import { isWindows10 } from './terminalEnvironment.js';
vi.mock('node:os', () => ({
default: {
@@ -24,286 +26,134 @@ vi.mock('node:os', () => ({
describe('compatibility', () => {
const originalGetColorDepth = process.stdout.getColorDepth;
const originalIsTTY = process.stdout.isTTY;
afterEach(() => {
process.stdout.getColorDepth = originalGetColorDepth;
process.stdout.isTTY = originalIsTTY;
vi.restoreAllMocks();
vi.unstubAllEnvs();
});
describe('isWindows10', () => {
it.each<{
platform: NodeJS.Platform;
release: string;
expected: boolean;
desc: string;
}>([
{
platform: 'win32',
release: '10.0.19041',
expected: true,
desc: 'Windows 10 (build < 22000)',
},
{
platform: 'win32',
release: '10.0.22000',
expected: false,
desc: 'Windows 11 (build >= 22000)',
},
{
platform: 'darwin',
release: '20.6.0',
expected: false,
desc: 'non-Windows platforms',
},
])(
'should return $expected for $desc',
({ platform, release, expected }) => {
vi.mocked(os.platform).mockReturnValue(platform);
vi.mocked(os.release).mockReturnValue(release);
expect(isWindows10()).toBe(expected);
},
);
it('should return true for Windows 10', () => {
vi.mocked(os.platform).mockReturnValue('win32');
vi.mocked(os.release).mockReturnValue('10.0.19041');
expect(isWindows10()).toBe(true);
});
it('should return false for Windows 11', () => {
vi.mocked(os.platform).mockReturnValue('win32');
vi.mocked(os.release).mockReturnValue('10.0.22000');
expect(isWindows10()).toBe(false);
});
it('should return false for non-Windows', () => {
vi.mocked(os.platform).mockReturnValue('darwin');
expect(isWindows10()).toBe(false);
});
});
describe('isJetBrainsTerminal', () => {
it.each<{ env: string; expected: boolean; desc: string }>([
{
env: 'JetBrains-JediTerm',
expected: true,
desc: 'TERMINAL_EMULATOR is JetBrains-JediTerm',
},
{ env: 'something-else', expected: false, desc: 'other terminals' },
{ env: '', expected: false, desc: 'TERMINAL_EMULATOR is not set' },
])('should return $expected when $desc', ({ env, expected }) => {
vi.stubEnv('TERMINAL_EMULATOR', env);
expect(isJetBrainsTerminal()).toBe(expected);
it('should detect JetBrains terminal via env var', () => {
vi.stubEnv('TERMINAL_EMULATOR', 'JetBrains-JediTerm');
expect(isJetBrainsTerminal()).toBe(true);
});
});
describe('isTmux', () => {
it('should detect tmux via TMUX env var', () => {
vi.stubEnv('TMUX', '/tmp/tmux-1000/default,123,0');
expect(isTmux()).toBe(true);
});
});
describe('supports256Colors', () => {
it.each<{
depth: number;
term?: string;
expected: boolean;
desc: string;
}>([
{
depth: 8,
term: undefined,
expected: true,
desc: 'getColorDepth returns >= 8',
},
{
depth: 4,
term: 'xterm-256color',
expected: true,
desc: 'TERM contains 256color',
},
{
depth: 4,
term: 'xterm',
expected: false,
desc: '256 colors are not supported',
},
])('should return $expected when $desc', ({ depth, term, expected }) => {
process.stdout.getColorDepth = vi.fn().mockReturnValue(depth);
if (term !== undefined) {
vi.stubEnv('TERM', term);
}
expect(supports256Colors()).toBe(expected);
it('should return true if getColorDepth returns 8', () => {
process.stdout.getColorDepth = vi.fn().mockReturnValue(8);
expect(supports256Colors()).toBe(true);
});
it('should return true if TERM includes 256color', () => {
process.stdout.getColorDepth = vi.fn().mockReturnValue(4);
vi.stubEnv('TERM', 'xterm-256color');
expect(supports256Colors()).toBe(true);
});
});
describe('supportsTrueColor', () => {
it.each<{
colorterm: string;
depth: number;
expected: boolean;
desc: string;
}>([
{
colorterm: 'truecolor',
depth: 8,
expected: true,
desc: 'COLORTERM is truecolor',
},
{
colorterm: '24bit',
depth: 8,
expected: true,
desc: 'COLORTERM is 24bit',
},
{
colorterm: '',
depth: 24,
expected: true,
desc: 'getColorDepth returns >= 24',
},
{
colorterm: '',
depth: 8,
expected: false,
desc: 'true color is not supported',
},
])(
'should return $expected when $desc',
({ colorterm, depth, expected }) => {
vi.stubEnv('COLORTERM', colorterm);
process.stdout.getColorDepth = vi.fn().mockReturnValue(depth);
expect(supportsTrueColor()).toBe(expected);
},
);
it('should return true if COLORTERM is truecolor', () => {
vi.stubEnv('COLORTERM', 'truecolor');
expect(supportsTrueColor()).toBe(true);
});
it('should return true if getColorDepth returns 24', () => {
process.stdout.getColorDepth = vi.fn().mockReturnValue(24);
expect(supportsTrueColor()).toBe(true);
});
});
describe('supportsKeyboardProtocolHeuristic', () => {
it('should return true for Ghostty', () => {
vi.stubEnv('TERM_PROGRAM', 'ghostty');
expect(supportsKeyboardProtocolHeuristic()).toBe(true);
});
it('should return false for Apple Terminal', () => {
vi.stubEnv('TERM_PROGRAM', 'Apple_Terminal');
expect(supportsKeyboardProtocolHeuristic()).toBe(false);
});
});
describe('getCompatibilityWarnings', () => {
beforeEach(() => {
// Default to supporting true color to keep existing tests simple
vi.stubEnv('COLORTERM', 'truecolor');
process.stdout.getColorDepth = vi.fn().mockReturnValue(24);
});
it('should return Windows 10 warning when detected', () => {
vi.mocked(os.platform).mockReturnValue('win32');
vi.mocked(os.release).mockReturnValue('10.0.19041');
vi.stubEnv('TERMINAL_EMULATOR', '');
const warnings = getCompatibilityWarnings();
expect(warnings).toContainEqual(
expect.objectContaining({
id: 'windows-10',
message: expect.stringContaining('Windows 10 detected'),
}),
);
});
it.each<{
platform: NodeJS.Platform;
release: string;
externalTerminal: string;
desc: string;
}>([
{
platform: 'darwin',
release: '20.6.0',
externalTerminal: 'iTerm2 or Ghostty',
desc: 'macOS',
},
{
platform: 'win32',
release: '10.0.22000',
externalTerminal: 'Windows Terminal',
desc: 'Windows',
}, // Valid Windows 11 release to not trigger the Windows 10 warning
{
platform: 'linux',
release: '5.10.0',
externalTerminal: 'Ghostty',
desc: 'Linux',
},
])(
'should return JetBrains warning when detected and in alternate buffer ($desc)',
({ platform, release, externalTerminal }) => {
vi.mocked(os.platform).mockReturnValue(platform);
vi.mocked(os.release).mockReturnValue(release);
vi.stubEnv('TERMINAL_EMULATOR', 'JetBrains-JediTerm');
const warnings = getCompatibilityWarnings({ isAlternateBuffer: true });
expect(warnings).toContainEqual(
expect.objectContaining({
id: 'jetbrains-terminal',
message: expect.stringContaining(
`Warning: JetBrains mouse scrolling is unreliable. Disabling alternate buffer mode in settings or using an external terminal (e.g., ${externalTerminal}) is recommended.`,
),
priority: WarningPriority.High,
}),
);
},
);
it('should not return JetBrains warning when detected but NOT in alternate buffer', () => {
vi.mocked(os.platform).mockReturnValue('darwin');
vi.stubEnv('TERMINAL_EMULATOR', 'JetBrains-JediTerm');
const warnings = getCompatibilityWarnings({ isAlternateBuffer: false });
expect(
warnings.find((w) => w.id === 'jetbrains-terminal'),
).toBeUndefined();
});
it('should return 256-color warning when 256 colors are not supported', () => {
vi.mocked(os.platform).mockReturnValue('linux');
vi.stubEnv('TERMINAL_EMULATOR', '');
vi.stubEnv('COLORTERM', '');
vi.stubEnv('TERM', 'xterm');
process.stdout.getColorDepth = vi.fn().mockReturnValue(4);
const warnings = getCompatibilityWarnings();
expect(warnings).toContainEqual(
expect.objectContaining({
id: '256-color',
message: expect.stringContaining('256-color support not detected'),
priority: WarningPriority.High,
}),
);
// Should NOT show true-color warning if 256-color warning is shown
expect(warnings.find((w) => w.id === 'true-color')).toBeUndefined();
});
it('should return true color warning when 256 colors are supported but true color is not, and not Apple Terminal', () => {
vi.mocked(os.platform).mockReturnValue('linux');
vi.stubEnv('TERMINAL_EMULATOR', '');
vi.stubEnv('COLORTERM', '');
vi.stubEnv('TERM_PROGRAM', 'xterm');
process.stdout.getColorDepth = vi.fn().mockReturnValue(8);
it('should return JetBrains warning when detected and in alt buffer', () => {
vi.mocked(os.platform).mockReturnValue('darwin');
vi.stubEnv('TERMINAL_EMULATOR', 'JetBrains-JediTerm');
const warnings = getCompatibilityWarnings({ isAlternateBuffer: true });
expect(warnings).toContainEqual(
expect.objectContaining({
id: 'jetbrains-terminal',
priority: WarningPriority.High,
}),
);
});
it('should return tmux warning', () => {
vi.stubEnv('TMUX', '/tmp/tmux-1000/default,123,0');
const warnings = getCompatibilityWarnings();
expect(warnings).toContainEqual(
expect.objectContaining({
id: 'true-color',
message: expect.stringContaining(
'True color (24-bit) support not detected',
),
id: 'tmux-mouse-support',
priority: WarningPriority.Low,
}),
);
});
it('should NOT return true color warning for Apple Terminal', () => {
vi.mocked(os.platform).mockReturnValue('darwin');
vi.stubEnv('TERMINAL_EMULATOR', '');
vi.stubEnv('COLORTERM', '');
it('should return keyboard protocol warning', () => {
vi.stubEnv('TERM_PROGRAM', 'Apple_Terminal');
process.stdout.getColorDepth = vi.fn().mockReturnValue(8);
const warnings = getCompatibilityWarnings();
expect(warnings.find((w) => w.id === 'true-color')).toBeUndefined();
});
it('should return all warnings when all are detected', () => {
vi.mocked(os.platform).mockReturnValue('win32');
vi.mocked(os.release).mockReturnValue('10.0.19041');
vi.stubEnv('TERMINAL_EMULATOR', 'JetBrains-JediTerm');
vi.stubEnv('COLORTERM', '');
vi.stubEnv('TERM_PROGRAM', 'xterm');
process.stdout.getColorDepth = vi.fn().mockReturnValue(8);
const warnings = getCompatibilityWarnings({ isAlternateBuffer: true });
expect(warnings).toHaveLength(3);
expect(warnings[0].message).toContain('Windows 10 detected');
expect(warnings[1].message).toContain('JetBrains');
expect(warnings[2].message).toContain(
'True color (24-bit) support not detected',
const warnings = getCompatibilityWarnings({
supportsKeyboardProtocol: false,
});
expect(warnings).toContainEqual(
expect.objectContaining({
id: 'keyboard-protocol',
priority: WarningPriority.Low,
}),
);
});
it('should return no warnings in a standard environment with true color', () => {
vi.mocked(os.platform).mockReturnValue('darwin');
vi.stubEnv('TERMINAL_EMULATOR', '');
vi.stubEnv('COLORTERM', 'truecolor');
const warnings = getCompatibilityWarnings();
expect(warnings).toHaveLength(0);
});
});
});
+95 -19
View File
@@ -5,36 +5,64 @@
*/
import os from 'node:os';
import {
TerminalType,
detectTerminalType,
isWindows10 as detectIsWindows10,
} from './terminalEnvironment.js';
/**
* Detects if the current OS is Windows 10.
* Windows 11 also reports as version 10.0, but with build numbers >= 22000.
*/
export function isWindows10(): boolean {
if (os.platform() !== 'win32') {
return false;
}
const release = os.release();
const parts = release.split('.');
if (parts.length >= 3 && parts[0] === '10' && parts[1] === '0') {
const build = parseInt(parts[2], 10);
return build < 22000;
}
return false;
}
// Removed duplicate export to avoid ambiguity in index.ts
/**
* Detects if the current terminal is a JetBrains-based IDE terminal.
*/
export function isJetBrainsTerminal(): boolean {
return process.env['TERMINAL_EMULATOR'] === 'JetBrains-JediTerm';
return detectTerminalType() === TerminalType.JetBrains;
}
/**
* Detects if the current terminal is the default Apple Terminal.app.
*/
export function isAppleTerminal(): boolean {
return process.env['TERM_PROGRAM'] === 'Apple_Terminal';
return detectTerminalType() === TerminalType.AppleTerminal;
}
/**
* Detects if the current terminal is VS Code.
*/
export function isVSCode(): boolean {
return detectTerminalType() === TerminalType.VSCode;
}
/**
* Detects if the current terminal is iTerm2.
*/
export function isITerm2(): boolean {
return detectTerminalType() === TerminalType.ITerm2;
}
/**
* Detects if the current terminal is Ghostty.
*/
export function isGhostty(): boolean {
return detectTerminalType() === TerminalType.Ghostty;
}
/**
* Detects if running inside tmux.
*/
export function isTmux(): boolean {
return detectTerminalType() === TerminalType.Tmux;
}
/**
* Detects if the current terminal is Windows Terminal.
*/
export function isWindowsTerminal(): boolean {
return detectTerminalType() === TerminalType.WindowsTerminal;
}
/**
@@ -75,6 +103,19 @@ export function supportsTrueColor(): boolean {
return false;
}
/**
* Heuristic for keyboard protocol support based on terminal identity.
*/
export function supportsKeyboardProtocolHeuristic(): boolean {
const type = detectTerminalType();
return (
type === TerminalType.Ghostty ||
type === TerminalType.ITerm2 ||
type === TerminalType.VSCode ||
type === TerminalType.WindowsTerminal
);
}
export enum WarningPriority {
Low = 'low',
High = 'high',
@@ -91,10 +132,12 @@ export interface StartupWarning {
*/
export function getCompatibilityWarnings(options?: {
isAlternateBuffer?: boolean;
supportsKeyboardProtocol?: boolean;
}): StartupWarning[] {
const warnings: StartupWarning[] = [];
const type = detectTerminalType();
if (isWindows10()) {
if (detectIsWindows10()) {
warnings.push({
id: 'windows-10',
message:
@@ -103,7 +146,7 @@ export function getCompatibilityWarnings(options?: {
});
}
if (isJetBrainsTerminal() && options?.isAlternateBuffer) {
if (type === TerminalType.JetBrains && options?.isAlternateBuffer) {
const platformTerminals: Partial<Record<NodeJS.Platform, string>> = {
win32: 'Windows Terminal',
darwin: 'iTerm2 or Ghostty',
@@ -114,11 +157,20 @@ export function getCompatibilityWarnings(options?: {
warnings.push({
id: 'jetbrains-terminal',
message: `Warning: JetBrains mouse scrolling is unreliable. Disabling alternate buffer mode in settings or using an external terminal${suggestedTerminals} is recommended.`,
message: `Warning: JetBrains mouse scrolling is unreliable with alternate buffer enabled. Using an external terminal${suggestedTerminals} or disabling alternate buffer in settings is recommended.`,
priority: WarningPriority.High,
});
}
if (type === TerminalType.Tmux) {
warnings.push({
id: 'tmux-mouse-support',
message:
'Warning: Running inside tmux. For the best experience (including mouse scrolling), ensure "set -g mouse on" is enabled in your tmux configuration.',
priority: WarningPriority.Low,
});
}
if (!supports256Colors()) {
warnings.push({
id: '256-color',
@@ -126,7 +178,13 @@ export function getCompatibilityWarnings(options?: {
'Warning: 256-color support not detected. Using a terminal with at least 256-color support is recommended for a better visual experience.',
priority: WarningPriority.High,
});
} else if (!supportsTrueColor() && !isAppleTerminal()) {
} else if (
!supportsTrueColor() &&
type !== TerminalType.ITerm2 &&
type !== TerminalType.VSCode &&
type !== TerminalType.Ghostty &&
type !== TerminalType.AppleTerminal
) {
warnings.push({
id: 'true-color',
message:
@@ -135,5 +193,23 @@ export function getCompatibilityWarnings(options?: {
});
}
const hasKeyboardProtocol =
options?.supportsKeyboardProtocol ?? supportsKeyboardProtocolHeuristic();
if (!hasKeyboardProtocol) {
const suggestion =
os.platform() === 'darwin'
? 'iTerm2 or Ghostty'
: os.platform() === 'win32'
? 'Windows Terminal'
: 'Ghostty';
warnings.push({
id: 'keyboard-protocol',
message: `Warning: Advanced keyboard features (like Shift+Enter for newlines) are not supported in this terminal. Consider using ${suggestion} for a better experience.`,
priority: WarningPriority.Low,
});
}
return warnings;
}
@@ -0,0 +1,73 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import { TerminalType, detectTerminalType } from './terminalEnvironment.js';
describe('terminalEnvironment', () => {
describe('detectTerminalType', () => {
it('should detect JetBrains', () => {
expect(
detectTerminalType({ TERMINAL_EMULATOR: 'JetBrains-JediTerm' }),
).toBe(TerminalType.JetBrains);
expect(detectTerminalType({ IDEA_INITIAL_DIRECTORY: '/some/path' })).toBe(
TerminalType.JetBrains,
);
});
it('should detect tmux', () => {
expect(detectTerminalType({ TMUX: '/tmp/tmux-1000/default,123,0' })).toBe(
TerminalType.Tmux,
);
expect(detectTerminalType({ TERM: 'screen-256color' })).not.toBe(
TerminalType.Tmux,
);
expect(detectTerminalType({ TERM: 'tmux-256color' })).toBe(
TerminalType.Tmux,
);
});
it('should detect VSCode', () => {
expect(detectTerminalType({ TERM_PROGRAM: 'vscode' })).toBe(
TerminalType.VSCode,
);
expect(detectTerminalType({ VSCODE_GIT_IPC_HANDLE: 'something' })).toBe(
TerminalType.VSCode,
);
});
it('should detect iTerm2', () => {
expect(detectTerminalType({ TERM_PROGRAM: 'iTerm.app' })).toBe(
TerminalType.ITerm2,
);
});
it('should detect Ghostty', () => {
expect(detectTerminalType({ TERM_PROGRAM: 'ghostty' })).toBe(
TerminalType.Ghostty,
);
expect(detectTerminalType({ GHOSTTY_BIN_DIR: '/usr/bin' })).toBe(
TerminalType.Ghostty,
);
});
it('should detect Windows Terminal', () => {
expect(detectTerminalType({ WT_SESSION: 'guid' })).toBe(
TerminalType.WindowsTerminal,
);
});
it('should fallback to xterm', () => {
expect(detectTerminalType({ TERM: 'xterm-256color' })).toBe(
TerminalType.XTerm,
);
});
it('should return Unknown for unknown environments', () => {
expect(detectTerminalType({})).toBe(TerminalType.Unknown);
});
});
});
@@ -0,0 +1,84 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import os from 'node:os';
/**
* Known terminal types that Gemini CLI recognizes for specialized behavior.
*/
export enum TerminalType {
Unknown = 'unknown',
JetBrains = 'jetbrains',
Tmux = 'tmux',
VSCode = 'vscode',
ITerm2 = 'iterm2',
Ghostty = 'ghostty',
AppleTerminal = 'apple_terminal',
WindowsTerminal = 'windows_terminal',
XTerm = 'xterm',
}
/**
* Detects the current terminal type based on environment variables.
*/
export function detectTerminalType(
env: NodeJS.ProcessEnv = process.env,
): TerminalType {
if (
env['TERMINAL_EMULATOR'] === 'JetBrains-JediTerm' ||
env['TERM_PROGRAM'] === 'JetBrains-JediTerm' ||
!!env['IDEA_INITIAL_DIRECTORY'] ||
!!env['JETBRAINS_IDE']
) {
return TerminalType.JetBrains;
}
if (!!env['TMUX'] || (env['TERM'] || '').includes('tmux')) {
return TerminalType.Tmux;
}
if (env['TERM_PROGRAM'] === 'vscode' || !!env['VSCODE_GIT_IPC_HANDLE']) {
return TerminalType.VSCode;
}
if (env['TERM_PROGRAM'] === 'iTerm.app') {
return TerminalType.ITerm2;
}
if (env['TERM_PROGRAM'] === 'ghostty' || !!env['GHOSTTY_BIN_DIR']) {
return TerminalType.Ghostty;
}
if (env['TERM_PROGRAM'] === 'Apple_Terminal') {
return TerminalType.AppleTerminal;
}
if (env['WT_SESSION']) {
return TerminalType.WindowsTerminal;
}
if ((env['TERM'] || '').includes('xterm')) {
return TerminalType.XTerm;
}
return TerminalType.Unknown;
}
/**
* Detects if the current OS is Windows 10.
*/
export function isWindows10(): boolean {
if (os.platform() !== 'win32') {
return false;
}
const release = os.release();
const parts = release.split('.');
if (parts.length >= 3 && parts[0] === '10' && parts[1] === '0') {
const build = parseInt(parts[2], 10);
return build < 22000;
}
return false;
}