feat(cli): add OSC notification support for iTerm2, Kitty, and Ghostty (#3562)
* feat(cli): add OSC notification support for iTerm2, Kitty, and Ghostty Replace the basic terminal bell with protocol-specific OSC notifications that display rich system notifications with title and message content. - Add terminal detection (TERM → TERM_PROGRAM → KITTY_WINDOW_ID fallback) - Add OSC 9 (iTerm2), OSC 99 (Kitty 3-step), OSC 777 (Ghostty/cmux) - Add tmux/screen DCS passthrough with ESC byte doubling - Add notification routing service with auto terminal detection - Add dynamic tool name in approval notifications - Refactor useTerminalProgress to use shared osc.ts module - 42 unit tests covering all detection paths and protocols Closes #2528 * fix(cli): address PR review feedback for OSC notification system - Reorder terminal detection: TERM_PROGRAM first, TERM fallback, KITTY_WINDOW_ID last - Add TTY guard in sendNotification to skip OSC when stdout is piped - Add sanitizeOscPayload to prevent control character injection in OSC payloads - Replace hand-rolled PendingToolCall with imported TrackedToolCall type - Extract awaiting tool name via useMemo to avoid useEffect re-fires - Unify brand name to "Qwen Code" in all notification messages - Remove unused TerminalWriteContext/Provider/Hook exports - Fix docstring: OSC_PREFIX 9;4 → OSC 9;4 * fix(cli): base64-encode Kitty OSC 99 payloads and fix screen ST conflict - Add encodeKittyPayload() to base64-encode UTF-8 text for Kitty OSC 99 - oscKittyNotify() now uses e=1 flag with base64-encoded title/body - osc() falls back to BEL terminator for Kitty inside GNU screen to avoid ST conflicting with the DCS passthrough wrapper's own ST
This commit is contained in:
parent
f420742831
commit
00ba2ef600
144
packages/cli/src/services/notificationService.test.ts
Normal file
144
packages/cli/src/services/notificationService.test.ts
Normal file
@ -0,0 +1,144 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { sendNotification } from './notificationService.js';
|
||||
import type { TerminalNotification } from '../ui/hooks/useTerminalNotification.js';
|
||||
|
||||
vi.mock('../utils/osc.js', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('../utils/osc.js')>();
|
||||
return {
|
||||
...original,
|
||||
detectTerminal: vi.fn(() => 'unknown'),
|
||||
generateKittyId: vi.fn(() => 42),
|
||||
};
|
||||
});
|
||||
|
||||
const { detectTerminal: mockedDetectTerminal } = await import(
|
||||
'../utils/osc.js'
|
||||
);
|
||||
|
||||
function createMockTerminal(): TerminalNotification {
|
||||
return {
|
||||
notifyITerm2: vi.fn(),
|
||||
notifyKitty: vi.fn(),
|
||||
notifyGhostty: vi.fn(),
|
||||
notifyBell: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('sendNotification', () => {
|
||||
let terminal: TerminalNotification;
|
||||
|
||||
const origIsTTY = process.stdout.isTTY;
|
||||
|
||||
beforeEach(() => {
|
||||
terminal = createMockTerminal();
|
||||
vi.mocked(mockedDetectTerminal).mockReturnValue('unknown');
|
||||
Object.defineProperty(process.stdout, 'isTTY', {
|
||||
value: true,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process.stdout, 'isTTY', {
|
||||
value: origIsTTY,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns disabled when not enabled', () => {
|
||||
const result = sendNotification({ message: 'test' }, terminal, false);
|
||||
expect(result).toBe('disabled');
|
||||
expect(terminal.notifyBell).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends iTerm2 notification for iTerm.app', () => {
|
||||
vi.mocked(mockedDetectTerminal).mockReturnValue('iTerm.app');
|
||||
const result = sendNotification(
|
||||
{ message: 'test', title: 'Title' },
|
||||
terminal,
|
||||
true,
|
||||
);
|
||||
expect(result).toBe('iterm2');
|
||||
expect(terminal.notifyITerm2).toHaveBeenCalledWith({
|
||||
message: 'test',
|
||||
title: 'Title',
|
||||
});
|
||||
});
|
||||
|
||||
it('sends kitty notification for kitty', () => {
|
||||
vi.mocked(mockedDetectTerminal).mockReturnValue('kitty');
|
||||
const result = sendNotification(
|
||||
{ message: 'test', title: 'Title' },
|
||||
terminal,
|
||||
true,
|
||||
);
|
||||
expect(result).toBe('kitty');
|
||||
expect(terminal.notifyKitty).toHaveBeenCalledWith({
|
||||
message: 'test',
|
||||
title: 'Title',
|
||||
id: 42,
|
||||
});
|
||||
});
|
||||
|
||||
it('sends ghostty notification for ghostty', () => {
|
||||
vi.mocked(mockedDetectTerminal).mockReturnValue('ghostty');
|
||||
const result = sendNotification(
|
||||
{ message: 'test', title: 'Title' },
|
||||
terminal,
|
||||
true,
|
||||
);
|
||||
expect(result).toBe('ghostty');
|
||||
expect(terminal.notifyGhostty).toHaveBeenCalledWith({
|
||||
message: 'test',
|
||||
title: 'Title',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to bell for Apple_Terminal', () => {
|
||||
vi.mocked(mockedDetectTerminal).mockReturnValue('Apple_Terminal');
|
||||
const result = sendNotification({ message: 'test' }, terminal, true);
|
||||
expect(result).toBe('terminal_bell');
|
||||
expect(terminal.notifyBell).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('falls back to bell for unknown terminal', () => {
|
||||
vi.mocked(mockedDetectTerminal).mockReturnValue('unknown');
|
||||
const result = sendNotification({ message: 'test' }, terminal, true);
|
||||
expect(result).toBe('terminal_bell');
|
||||
expect(terminal.notifyBell).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses default title when not provided', () => {
|
||||
vi.mocked(mockedDetectTerminal).mockReturnValue('iTerm.app');
|
||||
sendNotification({ message: 'test' }, terminal, true);
|
||||
expect(terminal.notifyITerm2).toHaveBeenCalledWith({
|
||||
message: 'test',
|
||||
title: 'Qwen Code',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns error when notification method throws', () => {
|
||||
vi.mocked(mockedDetectTerminal).mockReturnValue('iTerm.app');
|
||||
vi.mocked(terminal.notifyITerm2).mockImplementation(() => {
|
||||
throw new Error('write failed');
|
||||
});
|
||||
const result = sendNotification({ message: 'test' }, terminal, true);
|
||||
expect(result).toBe('error');
|
||||
});
|
||||
|
||||
it('returns disabled when stdout is not a TTY', () => {
|
||||
Object.defineProperty(process.stdout, 'isTTY', {
|
||||
value: false,
|
||||
configurable: true,
|
||||
});
|
||||
const result = sendNotification({ message: 'test' }, terminal, true);
|
||||
expect(result).toBe('disabled');
|
||||
expect(terminal.notifyBell).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
81
packages/cli/src/services/notificationService.ts
Normal file
81
packages/cli/src/services/notificationService.ts
Normal file
@ -0,0 +1,81 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* Notification routing service.
|
||||
*
|
||||
* When `terminalBell` setting is enabled, auto-detects the terminal and
|
||||
* sends notifications through the best available channel:
|
||||
*
|
||||
* iTerm.app → OSC 9 (native notification)
|
||||
* kitty → OSC 99 (desktop notification protocol)
|
||||
* ghostty → OSC 777 (notify)
|
||||
* others → terminal bell fallback
|
||||
*
|
||||
* When disabled, no notification is sent.
|
||||
*/
|
||||
|
||||
import { createDebugLogger } from '@qwen-code/qwen-code-core';
|
||||
import type { TerminalNotification } from '../ui/hooks/useTerminalNotification.js';
|
||||
import { detectTerminal, generateKittyId } from '../utils/osc.js';
|
||||
|
||||
const debugLogger = createDebugLogger('NOTIFICATION_SERVICE');
|
||||
|
||||
export interface NotificationOptions {
|
||||
message: string;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_TITLE = 'Qwen Code';
|
||||
|
||||
/**
|
||||
* Send a notification through the auto-detected channel.
|
||||
*
|
||||
* @param opts - Notification content
|
||||
* @param terminal - Terminal notification primitives
|
||||
* @param enabled - Whether notifications are enabled (from `terminalBell` setting)
|
||||
* @returns The channel method that was actually used, or 'disabled'.
|
||||
*/
|
||||
export function sendNotification(
|
||||
opts: NotificationOptions,
|
||||
terminal: TerminalNotification,
|
||||
enabled: boolean,
|
||||
): string {
|
||||
if (!enabled) {
|
||||
return 'disabled';
|
||||
}
|
||||
|
||||
// Don't write raw escape sequences when stdout is not a TTY
|
||||
// (CI, piped output, redirected to log files, etc.)
|
||||
if (!process.stdout?.isTTY) {
|
||||
return 'disabled';
|
||||
}
|
||||
|
||||
const title = opts.title ?? DEFAULT_TITLE;
|
||||
|
||||
try {
|
||||
const terminalType = detectTerminal();
|
||||
|
||||
switch (terminalType) {
|
||||
case 'iTerm.app':
|
||||
terminal.notifyITerm2({ ...opts, title });
|
||||
return 'iterm2';
|
||||
case 'kitty':
|
||||
terminal.notifyKitty({ ...opts, title, id: generateKittyId() });
|
||||
return 'kitty';
|
||||
case 'ghostty':
|
||||
terminal.notifyGhostty({ ...opts, title });
|
||||
return 'ghostty';
|
||||
case 'Apple_Terminal':
|
||||
default:
|
||||
terminal.notifyBell();
|
||||
return 'terminal_bell';
|
||||
}
|
||||
} catch (error) {
|
||||
debugLogger.warn('Failed to send notification:', error);
|
||||
return 'error';
|
||||
}
|
||||
}
|
||||
@ -138,6 +138,7 @@ import { useMcpDialog } from './hooks/useMcpDialog.js';
|
||||
import { useHooksDialog } from './hooks/useHooksDialog.js';
|
||||
import { useMemoryDialog } from './hooks/useMemoryDialog.js';
|
||||
import { useAttentionNotifications } from './hooks/useAttentionNotifications.js';
|
||||
import { buildTerminalNotification } from './hooks/useTerminalNotification.js';
|
||||
import { useContextualTips } from './hooks/useContextualTips.js';
|
||||
import { getTipHistory } from '../services/tips/index.js';
|
||||
import { useRemoteInput } from '../remoteInput/RemoteInputContext.js';
|
||||
@ -315,6 +316,20 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
const { stdin, setRawMode } = useStdin();
|
||||
const { stdout } = useStdout();
|
||||
|
||||
// Raw write function for terminal escape sequences.
|
||||
// Uses process.stdout directly instead of Ink's useStdout() because
|
||||
// standard Ink v6.2.3 proxies stdout writes through its rendering
|
||||
// pipeline, which can corrupt binary escape sequences (OSC, DCS).
|
||||
const writeRaw = useCallback((data: string) => {
|
||||
process.stdout.write(data);
|
||||
}, []);
|
||||
|
||||
// Terminal notification helpers (constructed directly, not via context)
|
||||
const terminal = useMemo(
|
||||
() => buildTerminalNotification(writeRaw),
|
||||
[writeRaw],
|
||||
);
|
||||
|
||||
// Additional hooks moved from App.tsx
|
||||
const { stats: sessionStats, startNewSession } = useSessionStats();
|
||||
const logger = useLogger(config.storage, sessionStats.sessionId);
|
||||
@ -1879,6 +1894,8 @@ export const AppContainer = (props: AppContainerProps) => {
|
||||
elapsedTime,
|
||||
settings,
|
||||
config,
|
||||
terminal,
|
||||
pendingToolCalls,
|
||||
});
|
||||
|
||||
// Dialog close functionality
|
||||
|
||||
@ -7,15 +7,28 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { StreamingState } from '../types.js';
|
||||
import {
|
||||
AttentionNotificationReason,
|
||||
notifyTerminalAttention,
|
||||
} from '../../utils/attentionNotification.js';
|
||||
import {
|
||||
LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS,
|
||||
useAttentionNotifications,
|
||||
} from './useAttentionNotifications.js';
|
||||
import type { LoadedSettings } from '../../config/settings.js';
|
||||
import type { TerminalNotification } from './useTerminalNotification.js';
|
||||
import type { TrackedToolCall } from './useReactToolScheduler.js';
|
||||
|
||||
vi.mock('../../services/notificationService.js', () => ({
|
||||
sendNotification: vi.fn(),
|
||||
}));
|
||||
|
||||
const { sendNotification: mockedSendNotification } = await import(
|
||||
'../../services/notificationService.js'
|
||||
);
|
||||
|
||||
const mockTerminal: TerminalNotification = {
|
||||
notifyITerm2: vi.fn(),
|
||||
notifyKitty: vi.fn(),
|
||||
notifyGhostty: vi.fn(),
|
||||
notifyBell: vi.fn(),
|
||||
};
|
||||
|
||||
const mockSettings: LoadedSettings = {
|
||||
merged: {
|
||||
@ -33,19 +46,9 @@ const mockSettingsDisabled: LoadedSettings = {
|
||||
},
|
||||
} as LoadedSettings;
|
||||
|
||||
vi.mock('../../utils/attentionNotification.js', () => ({
|
||||
notifyTerminalAttention: vi.fn(),
|
||||
AttentionNotificationReason: {
|
||||
ToolApproval: 'tool_approval',
|
||||
LongTaskComplete: 'long_task_complete',
|
||||
},
|
||||
}));
|
||||
|
||||
const mockedNotify = vi.mocked(notifyTerminalAttention);
|
||||
|
||||
describe('useAttentionNotifications', () => {
|
||||
beforeEach(() => {
|
||||
mockedNotify.mockReset();
|
||||
vi.mocked(mockedSendNotification).mockReset();
|
||||
});
|
||||
|
||||
const render = (
|
||||
@ -58,6 +61,7 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.Idle,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
...props,
|
||||
},
|
||||
},
|
||||
@ -72,12 +76,15 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.WaitingForConfirmation,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockedNotify).toHaveBeenCalledWith(
|
||||
AttentionNotificationReason.ToolApproval,
|
||||
{ enabled: true },
|
||||
expect(mockedSendNotification).toHaveBeenCalledTimes(1);
|
||||
expect(mockedSendNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: 'Qwen Code' }),
|
||||
mockTerminal,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
@ -93,10 +100,11 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.WaitingForConfirmation,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockedNotify).toHaveBeenCalledTimes(1);
|
||||
expect(mockedSendNotification).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('sends a notification when a long task finishes while unfocused', () => {
|
||||
@ -108,6 +116,7 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.Responding,
|
||||
elapsedTime: LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS + 5,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
@ -117,13 +126,11 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.Idle,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockedNotify).toHaveBeenCalledWith(
|
||||
AttentionNotificationReason.LongTaskComplete,
|
||||
{ enabled: true },
|
||||
);
|
||||
expect(mockedSendNotification).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not notify about long tasks when the CLI is focused', () => {
|
||||
@ -135,6 +142,7 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.Responding,
|
||||
elapsedTime: LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS + 2,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
@ -144,13 +152,11 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.Idle,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockedNotify).not.toHaveBeenCalledWith(
|
||||
AttentionNotificationReason.LongTaskComplete,
|
||||
expect.anything(),
|
||||
);
|
||||
expect(mockedSendNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not treat short responses as long tasks', () => {
|
||||
@ -162,6 +168,7 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.Responding,
|
||||
elapsedTime: 5,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
@ -171,13 +178,95 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.Idle,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockedNotify).not.toHaveBeenCalled();
|
||||
expect(mockedSendNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not notify when terminalBell setting is disabled', () => {
|
||||
it('includes tool name in approval notification message', () => {
|
||||
const { rerender } = render();
|
||||
|
||||
rerender({
|
||||
hookProps: {
|
||||
isFocused: false,
|
||||
streamingState: StreamingState.WaitingForConfirmation,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
pendingToolCalls: [
|
||||
{ status: 'awaiting_approval', request: { name: 'Bash' } },
|
||||
] as unknown as TrackedToolCall[],
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockedSendNotification).toHaveBeenCalledTimes(1);
|
||||
expect(mockedSendNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Qwen Code needs your permission to use Bash',
|
||||
}),
|
||||
mockTerminal,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('uses fallback message when no pending tool call is found', () => {
|
||||
const { rerender } = render();
|
||||
|
||||
rerender({
|
||||
hookProps: {
|
||||
isFocused: false,
|
||||
streamingState: StreamingState.WaitingForConfirmation,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
pendingToolCalls: [] as TrackedToolCall[],
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockedSendNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Qwen Code is waiting for your input',
|
||||
}),
|
||||
mockTerminal,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('sends "waiting for input" message for long task completion', () => {
|
||||
const { rerender } = render();
|
||||
|
||||
rerender({
|
||||
hookProps: {
|
||||
isFocused: false,
|
||||
streamingState: StreamingState.Responding,
|
||||
elapsedTime: LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS + 5,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
rerender({
|
||||
hookProps: {
|
||||
isFocused: false,
|
||||
streamingState: StreamingState.Idle,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettings,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockedSendNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Qwen Code is waiting for your input',
|
||||
}),
|
||||
mockTerminal,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('does not notify when terminalBell is disabled', () => {
|
||||
const { rerender } = render({
|
||||
settings: mockSettingsDisabled,
|
||||
});
|
||||
@ -188,12 +277,10 @@ describe('useAttentionNotifications', () => {
|
||||
streamingState: StreamingState.WaitingForConfirmation,
|
||||
elapsedTime: 0,
|
||||
settings: mockSettingsDisabled,
|
||||
terminal: mockTerminal,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockedNotify).toHaveBeenCalledWith(
|
||||
AttentionNotificationReason.ToolApproval,
|
||||
{ enabled: false },
|
||||
);
|
||||
expect(mockedSendNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@ -4,27 +4,30 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { StreamingState } from '../types.js';
|
||||
import {
|
||||
notifyTerminalAttention,
|
||||
AttentionNotificationReason,
|
||||
} from '../../utils/attentionNotification.js';
|
||||
import type { LoadedSettings } from '../../config/settings.js';
|
||||
import type { Config } from '@qwen-code/qwen-code-core';
|
||||
import {
|
||||
fireNotificationHook,
|
||||
NotificationType,
|
||||
} from '@qwen-code/qwen-code-core';
|
||||
import type { TerminalNotification } from './useTerminalNotification.js';
|
||||
import type { TrackedToolCall } from './useReactToolScheduler.js';
|
||||
import { sendNotification } from '../../services/notificationService.js';
|
||||
|
||||
export const LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS = 20;
|
||||
|
||||
const NOTIFICATION_TITLE = 'Qwen Code';
|
||||
|
||||
interface UseAttentionNotificationsOptions {
|
||||
isFocused: boolean;
|
||||
streamingState: StreamingState;
|
||||
elapsedTime: number;
|
||||
settings: LoadedSettings;
|
||||
config?: Config;
|
||||
terminal: TerminalNotification;
|
||||
pendingToolCalls?: TrackedToolCall[];
|
||||
}
|
||||
|
||||
export const useAttentionNotifications = ({
|
||||
@ -33,33 +36,58 @@ export const useAttentionNotifications = ({
|
||||
elapsedTime,
|
||||
settings,
|
||||
config,
|
||||
terminal,
|
||||
pendingToolCalls,
|
||||
}: UseAttentionNotificationsOptions) => {
|
||||
const terminalBellEnabled = settings?.merged?.general?.terminalBell ?? true;
|
||||
const terminalBellEnabled: boolean =
|
||||
(settings?.merged?.general?.terminalBell as boolean) ?? true;
|
||||
|
||||
const awaitingNotificationSentRef = useRef(false);
|
||||
const respondingElapsedRef = useRef(0);
|
||||
const idleNotificationSentRef = useRef(false);
|
||||
|
||||
// Extract the awaiting tool name as a primitive so the effect doesn't
|
||||
// re-fire on every render due to pendingToolCalls array identity changes.
|
||||
const awaitingToolName = useMemo(() => {
|
||||
const awaitingTool = pendingToolCalls?.find(
|
||||
(tc) => tc.status === 'awaiting_approval',
|
||||
);
|
||||
return awaitingTool?.request.name;
|
||||
}, [pendingToolCalls]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
streamingState === StreamingState.WaitingForConfirmation &&
|
||||
!isFocused &&
|
||||
!awaitingNotificationSentRef.current
|
||||
!awaitingNotificationSentRef.current &&
|
||||
terminalBellEnabled
|
||||
) {
|
||||
notifyTerminalAttention(AttentionNotificationReason.ToolApproval, {
|
||||
enabled: terminalBellEnabled,
|
||||
});
|
||||
const message = awaitingToolName
|
||||
? `Qwen Code needs your permission to use ${awaitingToolName}`
|
||||
: 'Qwen Code is waiting for your input';
|
||||
|
||||
sendNotification(
|
||||
{ message, title: NOTIFICATION_TITLE },
|
||||
terminal,
|
||||
terminalBellEnabled,
|
||||
);
|
||||
awaitingNotificationSentRef.current = true;
|
||||
}
|
||||
|
||||
if (streamingState !== StreamingState.WaitingForConfirmation || isFocused) {
|
||||
awaitingNotificationSentRef.current = false;
|
||||
}
|
||||
}, [isFocused, streamingState, terminalBellEnabled]);
|
||||
}, [
|
||||
isFocused,
|
||||
streamingState,
|
||||
terminalBellEnabled,
|
||||
terminal,
|
||||
awaitingToolName,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (streamingState === StreamingState.Responding) {
|
||||
respondingElapsedRef.current = elapsedTime;
|
||||
// Reset idle notification flag when responding
|
||||
idleNotificationSentRef.current = false;
|
||||
return;
|
||||
}
|
||||
@ -68,12 +96,16 @@ export const useAttentionNotifications = ({
|
||||
const wasLongTask =
|
||||
respondingElapsedRef.current >=
|
||||
LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS;
|
||||
if (wasLongTask && !isFocused) {
|
||||
notifyTerminalAttention(AttentionNotificationReason.LongTaskComplete, {
|
||||
enabled: terminalBellEnabled,
|
||||
});
|
||||
if (wasLongTask && !isFocused && terminalBellEnabled) {
|
||||
sendNotification(
|
||||
{
|
||||
message: 'Qwen Code is waiting for your input',
|
||||
title: NOTIFICATION_TITLE,
|
||||
},
|
||||
terminal,
|
||||
terminalBellEnabled,
|
||||
);
|
||||
}
|
||||
// Reset tracking for next task
|
||||
respondingElapsedRef.current = 0;
|
||||
|
||||
// Fire idle_prompt notification hook when entering idle state
|
||||
@ -88,7 +120,6 @@ export const useAttentionNotifications = ({
|
||||
'Waiting for input',
|
||||
).catch(() => {
|
||||
// Silently ignore errors - fireNotificationHook has internal error handling
|
||||
// and notification hooks should not block the idle flow
|
||||
});
|
||||
}
|
||||
idleNotificationSentRef.current = true;
|
||||
@ -96,7 +127,13 @@ export const useAttentionNotifications = ({
|
||||
return;
|
||||
}
|
||||
|
||||
// Reset idle notification flag when in WaitingForConfirmation state
|
||||
idleNotificationSentRef.current = false;
|
||||
}, [streamingState, elapsedTime, isFocused, terminalBellEnabled, config]);
|
||||
}, [
|
||||
streamingState,
|
||||
elapsedTime,
|
||||
isFocused,
|
||||
terminalBellEnabled,
|
||||
config,
|
||||
terminal,
|
||||
]);
|
||||
};
|
||||
|
||||
60
packages/cli/src/ui/hooks/useTerminalNotification.test.ts
Normal file
60
packages/cli/src/ui/hooks/useTerminalNotification.test.ts
Normal file
@ -0,0 +1,60 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { buildTerminalNotification } from './useTerminalNotification.js';
|
||||
|
||||
describe('buildTerminalNotification', () => {
|
||||
const originalEnv = { ...process.env };
|
||||
const writeRaw = vi.fn();
|
||||
|
||||
afterEach(() => {
|
||||
writeRaw.mockReset();
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it('notifyITerm2 writes OSC 9 sequence', () => {
|
||||
process.env['TERM_PROGRAM'] = 'iTerm.app';
|
||||
delete process.env['TERM'];
|
||||
const terminal = buildTerminalNotification(writeRaw);
|
||||
terminal.notifyITerm2({ message: 'Hello', title: 'Test' });
|
||||
expect(writeRaw).toHaveBeenCalledTimes(1);
|
||||
const written = writeRaw.mock.calls[0]![0] as string;
|
||||
expect(written).toContain('Test:\nHello');
|
||||
expect(written).toContain('\x1b]9;');
|
||||
});
|
||||
|
||||
it('notifyKitty writes three OSC 99 sequences', () => {
|
||||
process.env['TERM'] = 'xterm-kitty';
|
||||
delete process.env['TERM_PROGRAM'];
|
||||
const terminal = buildTerminalNotification(writeRaw);
|
||||
terminal.notifyKitty({ message: 'Body', title: 'Title', id: 7 });
|
||||
expect(writeRaw).toHaveBeenCalledTimes(3);
|
||||
const calls = writeRaw.mock.calls.map((c) => c[0] as string);
|
||||
expect(calls[0]).toContain('i=7:d=0:p=title');
|
||||
expect(calls[1]).toContain('i=7:p=body');
|
||||
expect(calls[2]).toContain('i=7:d=1:a=focus');
|
||||
});
|
||||
|
||||
it('notifyGhostty writes OSC 777 sequence', () => {
|
||||
process.env['TERM_PROGRAM'] = 'ghostty';
|
||||
delete process.env['TERM'];
|
||||
const terminal = buildTerminalNotification(writeRaw);
|
||||
terminal.notifyGhostty({ message: 'Body', title: 'Title' });
|
||||
expect(writeRaw).toHaveBeenCalledTimes(1);
|
||||
const written = writeRaw.mock.calls[0]![0] as string;
|
||||
expect(written).toContain('777;notify;Title;Body');
|
||||
});
|
||||
|
||||
it('notifyBell writes raw BEL without wrapping', () => {
|
||||
process.env['TMUX'] = '/tmp/tmux';
|
||||
const terminal = buildTerminalNotification(writeRaw);
|
||||
terminal.notifyBell();
|
||||
expect(writeRaw).toHaveBeenCalledWith('\x07');
|
||||
// BEL should NOT be wrapped in DCS passthrough
|
||||
expect(writeRaw.mock.calls[0]![0]).not.toContain('\x1bPtmux');
|
||||
});
|
||||
});
|
||||
63
packages/cli/src/ui/hooks/useTerminalNotification.ts
Normal file
63
packages/cli/src/ui/hooks/useTerminalNotification.ts
Normal file
@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* React hook and context for writing raw escape sequences to the terminal,
|
||||
* bypassing Ink's stdout interception.
|
||||
*
|
||||
* Provides per-protocol notification helpers (iTerm2 / Kitty / Ghostty / Bell)
|
||||
* and terminal progress reporting.
|
||||
*/
|
||||
|
||||
import {
|
||||
BEL,
|
||||
wrapForMultiplexer,
|
||||
oscITerm2Notify,
|
||||
oscKittyNotify,
|
||||
oscGhosttyNotify,
|
||||
} from '../../utils/osc.js';
|
||||
|
||||
// ── Types ──────────────────────────────────────────────────────────
|
||||
|
||||
type WriteRaw = (data: string) => void;
|
||||
|
||||
export interface TerminalNotification {
|
||||
notifyITerm2: (opts: { message: string; title?: string }) => void;
|
||||
notifyKitty: (opts: { message: string; title: string; id: number }) => void;
|
||||
notifyGhostty: (opts: { message: string; title: string }) => void;
|
||||
notifyBell: () => void;
|
||||
}
|
||||
|
||||
// ── Factory (no React context needed) ──────────────────────────────
|
||||
|
||||
/**
|
||||
* Build a TerminalNotification object from a raw write function.
|
||||
* Useful when the caller already has stdout.write and does not need
|
||||
* (or cannot use) TerminalWriteContext (e.g. in AppContainer's body
|
||||
* before the provider is mounted in the JSX tree).
|
||||
*/
|
||||
export function buildTerminalNotification(
|
||||
writeRaw: WriteRaw,
|
||||
): TerminalNotification {
|
||||
return {
|
||||
notifyITerm2({ message, title }) {
|
||||
writeRaw(wrapForMultiplexer(oscITerm2Notify(title ?? '', message)));
|
||||
},
|
||||
notifyKitty({ message, title, id }) {
|
||||
for (const seq of oscKittyNotify(title, message, id)) {
|
||||
writeRaw(wrapForMultiplexer(seq));
|
||||
}
|
||||
},
|
||||
notifyGhostty({ message, title }) {
|
||||
writeRaw(wrapForMultiplexer(oscGhosttyNotify(title, message)));
|
||||
},
|
||||
notifyBell() {
|
||||
// Raw BEL — inside tmux this triggers tmux's bell-action (window flag).
|
||||
// Wrapping would make it opaque DCS payload and lose that fallback.
|
||||
writeRaw(BEL);
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -7,6 +7,12 @@
|
||||
import { useEffect, useCallback } from 'react';
|
||||
import { useStdout } from 'ink';
|
||||
import { StreamingState } from '../types.js';
|
||||
import {
|
||||
OSC_PREFIX,
|
||||
BEL,
|
||||
wrapForMultiplexer,
|
||||
detectTerminal,
|
||||
} from '../../utils/osc.js';
|
||||
|
||||
/**
|
||||
* OSC 9;4 progress sequences for terminal tab/title bar progress.
|
||||
@ -15,32 +21,14 @@ import { StreamingState } from '../types.js';
|
||||
* @see https://iterm2.com/documentation-escape-codes.html
|
||||
* @see https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences
|
||||
*/
|
||||
const OSC = '\x1b]';
|
||||
const BEL = '\x07';
|
||||
|
||||
/**
|
||||
* Wrap an OSC sequence for tmux/screen passthrough.
|
||||
* tmux requires DCS escape: \ePtmux;\e<seq>\e\\
|
||||
* screen requires DCS escape: \eP<seq>\e\\
|
||||
*/
|
||||
function wrapForMultiplexer(seq: string): string {
|
||||
if (process.env['TMUX']) {
|
||||
return `\x1bPtmux;\x1b${seq}\x1b\\`;
|
||||
}
|
||||
if (process.env['STY']) {
|
||||
return `\x1bP${seq}\x1b\\`;
|
||||
}
|
||||
return seq;
|
||||
}
|
||||
|
||||
const PROGRESS_CLEAR = wrapForMultiplexer(`${OSC}9;4;0;${BEL}`);
|
||||
const PROGRESS_INDETERMINATE = wrapForMultiplexer(`${OSC}9;4;3;;${BEL}`);
|
||||
const PROGRESS_CLEAR = wrapForMultiplexer(`${OSC_PREFIX}9;4;0;${BEL}`);
|
||||
const PROGRESS_INDETERMINATE = wrapForMultiplexer(`${OSC_PREFIX}9;4;3;;${BEL}`);
|
||||
|
||||
function isProgressBarSupported(): boolean {
|
||||
// Don't emit escape sequences when stdout is not a TTY (CI, piped output,
|
||||
// redirected to log files, etc.)
|
||||
if (!process.stdout?.isTTY) return false;
|
||||
const term = process.env['TERM_PROGRAM'];
|
||||
const term = detectTerminal();
|
||||
if (term === 'iTerm.app') return true;
|
||||
if (term === 'ghostty') return true;
|
||||
if (process.env['ConEmuPID']) return true;
|
||||
|
||||
@ -1,72 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Qwen
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import {
|
||||
notifyTerminalAttention,
|
||||
AttentionNotificationReason,
|
||||
} from './attentionNotification.js';
|
||||
|
||||
describe('notifyTerminalAttention', () => {
|
||||
let stream: { write: ReturnType<typeof vi.fn>; isTTY: boolean };
|
||||
|
||||
beforeEach(() => {
|
||||
stream = { write: vi.fn().mockReturnValue(true), isTTY: true };
|
||||
});
|
||||
|
||||
it('emits terminal bell character', () => {
|
||||
const result = notifyTerminalAttention(
|
||||
AttentionNotificationReason.ToolApproval,
|
||||
{
|
||||
stream,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(stream.write).toHaveBeenCalledWith('\u0007');
|
||||
});
|
||||
|
||||
it('returns false when not running inside a tty', () => {
|
||||
stream.isTTY = false;
|
||||
|
||||
const result = notifyTerminalAttention(
|
||||
AttentionNotificationReason.ToolApproval,
|
||||
{ stream },
|
||||
);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(stream.write).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns false when stream write fails', () => {
|
||||
stream.write = vi.fn().mockImplementation(() => {
|
||||
throw new Error('Write failed');
|
||||
});
|
||||
|
||||
const result = notifyTerminalAttention(
|
||||
AttentionNotificationReason.ToolApproval,
|
||||
{ stream },
|
||||
);
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('works with different notification reasons', () => {
|
||||
const reasons = [
|
||||
AttentionNotificationReason.ToolApproval,
|
||||
AttentionNotificationReason.LongTaskComplete,
|
||||
];
|
||||
|
||||
reasons.forEach((reason) => {
|
||||
stream.write.mockClear();
|
||||
|
||||
const result = notifyTerminalAttention(reason, { stream });
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(stream.write).toHaveBeenCalledWith('\u0007');
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1,51 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Qwen
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import process from 'node:process';
|
||||
import { createDebugLogger } from '@qwen-code/qwen-code-core';
|
||||
|
||||
export enum AttentionNotificationReason {
|
||||
ToolApproval = 'tool_approval',
|
||||
LongTaskComplete = 'long_task_complete',
|
||||
}
|
||||
|
||||
export interface TerminalNotificationOptions {
|
||||
stream?: Pick<NodeJS.WriteStream, 'write' | 'isTTY'>;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
const TERMINAL_BELL = '\u0007';
|
||||
const debugLogger = createDebugLogger('ATTENTION_NOTIFICATION');
|
||||
|
||||
/**
|
||||
* Grabs the user's attention by emitting the terminal bell character.
|
||||
* This causes the terminal to flash or play a sound, alerting the user
|
||||
* to check the CLI for important events.
|
||||
*
|
||||
* @returns true when the bell was successfully written to the terminal.
|
||||
*/
|
||||
export function notifyTerminalAttention(
|
||||
_reason: AttentionNotificationReason,
|
||||
options: TerminalNotificationOptions = {},
|
||||
): boolean {
|
||||
// Check if terminal bell is enabled (default true for backwards compatibility)
|
||||
if (options.enabled === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const stream = options.stream ?? process.stdout;
|
||||
if (!stream?.write || stream.isTTY === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
stream.write(TERMINAL_BELL);
|
||||
return true;
|
||||
} catch (error) {
|
||||
debugLogger.warn('Failed to send terminal bell:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
280
packages/cli/src/utils/osc.test.ts
Normal file
280
packages/cli/src/utils/osc.test.ts
Normal file
@ -0,0 +1,280 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import {
|
||||
detectTerminal,
|
||||
osc,
|
||||
wrapForMultiplexer,
|
||||
oscITerm2Notify,
|
||||
oscKittyNotify,
|
||||
oscGhosttyNotify,
|
||||
sanitizeOscPayload,
|
||||
encodeKittyPayload,
|
||||
OSC,
|
||||
BEL,
|
||||
ST,
|
||||
} from './osc.js';
|
||||
|
||||
describe('detectTerminal', () => {
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env['TERM_PROGRAM'];
|
||||
delete process.env['TERM'];
|
||||
delete process.env['KITTY_WINDOW_ID'];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it('detects iTerm.app via TERM_PROGRAM', () => {
|
||||
process.env['TERM_PROGRAM'] = 'iTerm.app';
|
||||
expect(detectTerminal()).toBe('iTerm.app');
|
||||
});
|
||||
|
||||
it('detects kitty via TERM_PROGRAM', () => {
|
||||
process.env['TERM_PROGRAM'] = 'kitty';
|
||||
expect(detectTerminal()).toBe('kitty');
|
||||
});
|
||||
|
||||
it('detects ghostty via TERM_PROGRAM', () => {
|
||||
process.env['TERM_PROGRAM'] = 'ghostty';
|
||||
expect(detectTerminal()).toBe('ghostty');
|
||||
});
|
||||
|
||||
it('detects Apple_Terminal via TERM_PROGRAM', () => {
|
||||
process.env['TERM_PROGRAM'] = 'Apple_Terminal';
|
||||
expect(detectTerminal()).toBe('Apple_Terminal');
|
||||
});
|
||||
|
||||
it('detects kitty via TERM=xterm-kitty when TERM_PROGRAM is absent', () => {
|
||||
process.env['TERM'] = 'xterm-kitty';
|
||||
expect(detectTerminal()).toBe('kitty');
|
||||
});
|
||||
|
||||
it('detects ghostty via TERM=xterm-ghostty when TERM_PROGRAM is absent', () => {
|
||||
process.env['TERM'] = 'xterm-ghostty';
|
||||
expect(detectTerminal()).toBe('ghostty');
|
||||
});
|
||||
|
||||
it('detects kitty via KITTY_WINDOW_ID as fallback', () => {
|
||||
process.env['KITTY_WINDOW_ID'] = '1';
|
||||
expect(detectTerminal()).toBe('kitty');
|
||||
});
|
||||
|
||||
it('returns unknown when no terminal is detected', () => {
|
||||
expect(detectTerminal()).toBe('unknown');
|
||||
});
|
||||
|
||||
it('TERM_PROGRAM takes priority over TERM', () => {
|
||||
process.env['TERM'] = 'xterm-ghostty';
|
||||
process.env['TERM_PROGRAM'] = 'iTerm.app';
|
||||
expect(detectTerminal()).toBe('iTerm.app');
|
||||
});
|
||||
|
||||
it('falls back to TERM when TERM_PROGRAM is not a known terminal', () => {
|
||||
process.env['TERM'] = 'xterm-ghostty';
|
||||
process.env['TERM_PROGRAM'] = 'some-unknown-terminal';
|
||||
expect(detectTerminal()).toBe('ghostty');
|
||||
});
|
||||
|
||||
it('KITTY_WINDOW_ID is last resort fallback', () => {
|
||||
process.env['TERM'] = 'xterm-256color';
|
||||
process.env['KITTY_WINDOW_ID'] = '1';
|
||||
expect(detectTerminal()).toBe('kitty');
|
||||
});
|
||||
});
|
||||
|
||||
describe('osc', () => {
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it('builds OSC sequence with BEL terminator for non-kitty', () => {
|
||||
process.env['TERM_PROGRAM'] = 'iTerm.app';
|
||||
delete process.env['TERM'];
|
||||
const result = osc(9, 'hello');
|
||||
expect(result).toBe(`\x1b]9;hello${BEL}`);
|
||||
});
|
||||
|
||||
it('builds OSC sequence with ST terminator for kitty', () => {
|
||||
process.env['TERM'] = 'xterm-kitty';
|
||||
delete process.env['TERM_PROGRAM'];
|
||||
delete process.env['STY'];
|
||||
const result = osc(99, 'test');
|
||||
expect(result).toBe(`\x1b]99;test${ST}`);
|
||||
});
|
||||
|
||||
it('falls back to BEL for kitty inside screen to avoid ST conflict with DCS wrapper', () => {
|
||||
process.env['TERM'] = 'xterm-kitty';
|
||||
delete process.env['TERM_PROGRAM'];
|
||||
process.env['STY'] = '12345.pts-0.host';
|
||||
const result = osc(99, 'test');
|
||||
expect(result).toBe(`\x1b]99;test${BEL}`);
|
||||
});
|
||||
|
||||
it('joins multiple parts with semicolons', () => {
|
||||
process.env['TERM_PROGRAM'] = 'ghostty';
|
||||
delete process.env['TERM'];
|
||||
const result = osc(777, 'notify', 'Title', 'Body');
|
||||
expect(result).toBe(`\x1b]777;notify;Title;Body${BEL}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('wrapForMultiplexer', () => {
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it('returns sequence unchanged outside multiplexer', () => {
|
||||
delete process.env['TMUX'];
|
||||
delete process.env['STY'];
|
||||
const seq = `\x1b]9;hello${BEL}`;
|
||||
expect(wrapForMultiplexer(seq)).toBe(seq);
|
||||
});
|
||||
|
||||
it('wraps in DCS passthrough for tmux with ESC doubling', () => {
|
||||
process.env['TMUX'] = '/tmp/tmux-1000/default,12345,0';
|
||||
delete process.env['STY'];
|
||||
const seq = `\x1b]9;hello${BEL}`;
|
||||
// ESC bytes in payload should be doubled
|
||||
expect(wrapForMultiplexer(seq)).toBe(
|
||||
`\x1bPtmux;\x1b\x1b]9;hello${BEL}\x1b\\`,
|
||||
);
|
||||
});
|
||||
|
||||
it('wraps in DCS passthrough for screen', () => {
|
||||
delete process.env['TMUX'];
|
||||
process.env['STY'] = '12345.pts-0.host';
|
||||
const seq = `\x1b]9;hello${BEL}`;
|
||||
expect(wrapForMultiplexer(seq)).toBe(`\x1bP${seq}\x1b\\`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('oscITerm2Notify', () => {
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it('formats notification with title and message', () => {
|
||||
process.env['TERM_PROGRAM'] = 'iTerm.app';
|
||||
delete process.env['TERM'];
|
||||
const result = oscITerm2Notify('Qwen Code', 'Hello');
|
||||
expect(result).toContain('Qwen Code:\nHello');
|
||||
});
|
||||
|
||||
it('formats notification without title', () => {
|
||||
process.env['TERM_PROGRAM'] = 'iTerm.app';
|
||||
delete process.env['TERM'];
|
||||
const result = oscITerm2Notify('', 'Hello');
|
||||
expect(result).toContain('Hello');
|
||||
expect(result).not.toContain(':');
|
||||
});
|
||||
});
|
||||
|
||||
describe('encodeKittyPayload', () => {
|
||||
it('base64-encodes ASCII text', () => {
|
||||
expect(encodeKittyPayload('Title')).toBe(
|
||||
Buffer.from('Title', 'utf8').toString('base64'),
|
||||
);
|
||||
});
|
||||
|
||||
it('base64-encodes UTF-8 text', () => {
|
||||
expect(encodeKittyPayload('你好')).toBe(
|
||||
Buffer.from('你好', 'utf8').toString('base64'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('oscKittyNotify', () => {
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it('returns three-step protocol sequences with base64-encoded payloads', () => {
|
||||
process.env['TERM'] = 'xterm-kitty';
|
||||
delete process.env['TERM_PROGRAM'];
|
||||
delete process.env['STY'];
|
||||
const seqs = oscKittyNotify('Title', 'Body', 42);
|
||||
expect(seqs).toHaveLength(3);
|
||||
const b64Title = Buffer.from('Title', 'utf8').toString('base64');
|
||||
const b64Body = Buffer.from('Body', 'utf8').toString('base64');
|
||||
// Step 1: title with e=1 (base64)
|
||||
expect(seqs[0]).toContain('i=42:d=0:p=title:e=1');
|
||||
expect(seqs[0]).toContain(b64Title);
|
||||
expect(seqs[0]).not.toContain('Title');
|
||||
// Step 2: body with e=1 (base64)
|
||||
expect(seqs[1]).toContain('i=42:p=body:e=1');
|
||||
expect(seqs[1]).toContain(b64Body);
|
||||
expect(seqs[1]).not.toContain('Body');
|
||||
// Step 3: activate (no payload to encode)
|
||||
expect(seqs[2]).toContain('i=42:d=1:a=focus');
|
||||
});
|
||||
});
|
||||
|
||||
describe('oscGhosttyNotify', () => {
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it('formats OSC 777 notification', () => {
|
||||
process.env['TERM_PROGRAM'] = 'ghostty';
|
||||
delete process.env['TERM'];
|
||||
const result = oscGhosttyNotify('Title', 'Body');
|
||||
expect(result).toBe(`\x1b]${OSC.GHOSTTY};notify;Title;Body${BEL}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeOscPayload', () => {
|
||||
it('strips ESC character', () => {
|
||||
expect(sanitizeOscPayload('hello\x1bworld')).toBe('helloworld');
|
||||
});
|
||||
|
||||
it('strips BEL character', () => {
|
||||
expect(sanitizeOscPayload('hello\x07world')).toBe('helloworld');
|
||||
});
|
||||
|
||||
it('strips all C0 control characters', () => {
|
||||
expect(sanitizeOscPayload('a\x00b\x01c\x1fd')).toBe('abcd');
|
||||
});
|
||||
|
||||
it('preserves normal text', () => {
|
||||
expect(sanitizeOscPayload('Hello World! 你好')).toBe('Hello World! 你好');
|
||||
});
|
||||
|
||||
it('strips C1 control characters', () => {
|
||||
expect(sanitizeOscPayload('hello\x9cworld')).toBe('helloworld');
|
||||
});
|
||||
});
|
||||
|
||||
describe('osc sanitizes payloads', () => {
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it('strips control characters from string parts', () => {
|
||||
process.env['TERM_PROGRAM'] = 'ghostty';
|
||||
delete process.env['TERM'];
|
||||
const result = osc(OSC.GHOSTTY, 'notify', 'Title\x1b]hack', 'Body\x07end');
|
||||
expect(result).not.toContain('\x1b]hack');
|
||||
expect(result).toContain('Title]hack');
|
||||
expect(result).toContain('Bodyend');
|
||||
});
|
||||
});
|
||||
196
packages/cli/src/utils/osc.ts
Normal file
196
packages/cli/src/utils/osc.ts
Normal file
@ -0,0 +1,196 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* OSC (Operating System Command) escape sequence utilities for terminal
|
||||
* notifications, tab status indicators, and multiplexer passthrough.
|
||||
*/
|
||||
|
||||
// ── Escape sequence primitives ──────────────────────────────────────
|
||||
|
||||
export const ESC = '\x1b';
|
||||
export const BEL = '\x07';
|
||||
/** String Terminator — used by Kitty instead of BEL */
|
||||
export const ST = ESC + '\\';
|
||||
export const OSC_PREFIX = ESC + ']';
|
||||
const SEP = ';';
|
||||
|
||||
// ── OSC type codes ──────────────────────────────────────────────────
|
||||
|
||||
export const OSC = {
|
||||
/** iTerm2 notification / progress */
|
||||
ITERM2: 9,
|
||||
/** Kitty desktop notification protocol */
|
||||
KITTY: 99,
|
||||
/** Ghostty / cmux notification */
|
||||
GHOSTTY: 777,
|
||||
} as const;
|
||||
|
||||
// ── Terminal type detection ─────────────────────────────────────────
|
||||
|
||||
export type TerminalType =
|
||||
| 'iTerm.app'
|
||||
| 'kitty'
|
||||
| 'ghostty'
|
||||
| 'Apple_Terminal'
|
||||
| 'unknown';
|
||||
|
||||
/**
|
||||
* Detect the current terminal emulator from environment variables.
|
||||
*
|
||||
* Strategy: check TERM_PROGRAM first (identifies the actual emulator),
|
||||
* then fall back to TERM (describes capabilities, but Ghostty/Kitty set
|
||||
* distinctive TERM values when TERM_PROGRAM is absent — e.g. over SSH
|
||||
* or inside multiplexers), and finally check terminal-specific env vars.
|
||||
*/
|
||||
export function detectTerminal(): TerminalType {
|
||||
// 1. TERM_PROGRAM — most reliable for identifying the emulator
|
||||
const termProgram = process.env['TERM_PROGRAM'];
|
||||
switch (termProgram) {
|
||||
case 'iTerm.app':
|
||||
return 'iTerm.app';
|
||||
case 'kitty':
|
||||
return 'kitty';
|
||||
case 'ghostty':
|
||||
return 'ghostty';
|
||||
case 'Apple_Terminal':
|
||||
return 'Apple_Terminal';
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// 2. TERM — Ghostty and Kitty set distinctive TERM values even when
|
||||
// TERM_PROGRAM is absent (SSH sessions, multiplexers)
|
||||
if (process.env['TERM'] === 'xterm-ghostty') {
|
||||
return 'ghostty';
|
||||
}
|
||||
if (process.env['TERM']?.includes('kitty')) {
|
||||
return 'kitty';
|
||||
}
|
||||
|
||||
// 3. Terminal-specific env vars as last resort
|
||||
if (process.env['KITTY_WINDOW_ID']) return 'kitty';
|
||||
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
// ── Sanitization ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Strip control characters that could break out of an OSC payload.
|
||||
* Removes ESC (\x1b), BEL (\x07), ST (ESC + \), and other C0/C1
|
||||
* control bytes that terminals interpret as sequence boundaries.
|
||||
* Preserves HT (\t), LF (\n), and CR (\r) which are safe in payloads.
|
||||
*/
|
||||
export function sanitizeOscPayload(text: string): string {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return text.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x80-\x9f]/g, '');
|
||||
}
|
||||
|
||||
// ── Core OSC builders ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Build an OSC escape sequence from parts.
|
||||
*
|
||||
* Terminator selection:
|
||||
* - Kitty prefers ST (`ESC \`), but ST inside a GNU screen DCS wrapper
|
||||
* would prematurely terminate the outer DCS. So when `STY` is set
|
||||
* (screen session), we fall back to BEL even for Kitty.
|
||||
* - All other terminals always use BEL.
|
||||
*
|
||||
* All string parts are sanitized to prevent control character injection.
|
||||
*/
|
||||
export function osc(...parts: Array<string | number>): string {
|
||||
const isKitty = detectTerminal() === 'kitty';
|
||||
const inScreen = !!process.env['STY'];
|
||||
// Use ST for Kitty except inside screen where ST conflicts with DCS wrapper
|
||||
const terminator = isKitty && !inScreen ? ST : BEL;
|
||||
const sanitized = parts.map((p) =>
|
||||
typeof p === 'string' ? sanitizeOscPayload(p) : p,
|
||||
);
|
||||
return `${OSC_PREFIX}${sanitized.join(SEP)}${terminator}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap an OSC sequence for tmux / screen passthrough.
|
||||
*
|
||||
* - tmux: DCS `\ePtmux;\e<seq>\e\\` with ESC doubling inside
|
||||
* - screen: DCS `\eP<seq>\e\\`
|
||||
*
|
||||
* BEL should NOT be wrapped — raw BEL triggers tmux's bell-action,
|
||||
* whereas a wrapped BEL becomes an opaque DCS payload and is ignored.
|
||||
*/
|
||||
export function wrapForMultiplexer(sequence: string): string {
|
||||
if (process.env['TMUX']) {
|
||||
// tmux requires all ESC bytes inside the payload to be doubled
|
||||
const escaped = sequence.replaceAll('\x1b', '\x1b\x1b');
|
||||
return `\x1bPtmux;${escaped}\x1b\\`;
|
||||
}
|
||||
if (process.env['STY']) {
|
||||
return `\x1bP${sequence}\x1b\\`;
|
||||
}
|
||||
return sequence;
|
||||
}
|
||||
|
||||
// ── Encoding helpers ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Base64-encode a UTF-8 string for Kitty OSC 99 payloads.
|
||||
* Kitty requires `e=1` (base64) encoding to safely transport arbitrary
|
||||
* UTF-8 text without delimiter/control-character conflicts.
|
||||
*/
|
||||
export function encodeKittyPayload(text: string): string {
|
||||
return Buffer.from(text, 'utf8').toString('base64');
|
||||
}
|
||||
|
||||
// ── Notification helpers ────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* iTerm2 notification via OSC 9.
|
||||
* Format: `\e]9;\n\n<title>:\n<message>\a`
|
||||
*/
|
||||
export function oscITerm2Notify(title: string, message: string): string {
|
||||
const displayString = title ? `${title}:\n${message}` : message;
|
||||
// The \n\n prefix signals iTerm2 to show a system notification
|
||||
// rather than just a tab badge/growl.
|
||||
return osc(OSC.ITERM2, `\n\n${displayString}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kitty desktop notification via OSC 99 (three-step protocol).
|
||||
* Returns an array of sequences that must be written in order.
|
||||
*
|
||||
* Payloads are base64-encoded (`e=1`) as required by the Kitty
|
||||
* notification protocol to safely transport UTF-8 text.
|
||||
*
|
||||
* @see https://sw.kovidgoyal.net/kitty/desktop-notifications/
|
||||
*/
|
||||
export function oscKittyNotify(
|
||||
title: string,
|
||||
message: string,
|
||||
id: number,
|
||||
): string[] {
|
||||
return [
|
||||
osc(OSC.KITTY, `i=${id}:d=0:p=title:e=1`, encodeKittyPayload(title)),
|
||||
osc(OSC.KITTY, `i=${id}:p=body:e=1`, encodeKittyPayload(message)),
|
||||
osc(OSC.KITTY, `i=${id}:d=1:a=focus`, ''),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ghostty / cmux notification via OSC 777.
|
||||
* Format: `\e]777;notify;<title>;<message>\a`
|
||||
*/
|
||||
export function oscGhosttyNotify(title: string, message: string): string {
|
||||
return osc(OSC.GHOSTTY, 'notify', title, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random Kitty notification ID.
|
||||
*/
|
||||
export function generateKittyId(): number {
|
||||
return Math.floor(Math.random() * 2 ** 31);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user